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.
#define FML_USED_ON_EMBEDDER
#include "flutter/fml/message_loop.h"
#include <iostream>
#include <thread>
#include "flutter/fml/build_config.h"
#include "flutter/fml/concurrent_message_loop.h"
#include "flutter/fml/synchronization/count_down_latch.h"
#include "flutter/fml/synchronization/waitable_event.h"
#include "flutter/fml/task_runner.h"
#include "flutter/fml/time/chrono_timestamp_provider.h"
#include "gtest/gtest.h"
TEST(MessageLoop, GetCurrent) {
std::thread thread([]() {
fml::MessageLoop::EnsureInitializedForCurrentThread();
ASSERT_TRUE(fml::MessageLoop::GetCurrent().GetTaskRunner());
});
thread.join();
}
TEST(MessageLoop, DifferentThreadsHaveDifferentLoops) {
fml::MessageLoop* loop1 = nullptr;
fml::AutoResetWaitableEvent latch1;
fml::AutoResetWaitableEvent term1;
std::thread thread1([&loop1, &latch1, &term1]() {
fml::MessageLoop::EnsureInitializedForCurrentThread();
loop1 = &fml::MessageLoop::GetCurrent();
latch1.Signal();
term1.Wait();
});
fml::MessageLoop* loop2 = nullptr;
fml::AutoResetWaitableEvent latch2;
fml::AutoResetWaitableEvent term2;
std::thread thread2([&loop2, &latch2, &term2]() {
fml::MessageLoop::EnsureInitializedForCurrentThread();
loop2 = &fml::MessageLoop::GetCurrent();
latch2.Signal();
term2.Wait();
});
latch1.Wait();
latch2.Wait();
ASSERT_FALSE(loop1 == loop2);
term1.Signal();
term2.Signal();
thread1.join();
thread2.join();
}
TEST(MessageLoop, CanRunAndTerminate) {
bool started = false;
bool terminated = false;
std::thread thread([&started, &terminated]() {
fml::MessageLoop::EnsureInitializedForCurrentThread();
auto& loop = fml::MessageLoop::GetCurrent();
ASSERT_TRUE(loop.GetTaskRunner());
loop.GetTaskRunner()->PostTask([&terminated]() {
fml::MessageLoop::GetCurrent().Terminate();
terminated = true;
});
loop.Run();
started = true;
});
thread.join();
ASSERT_TRUE(started);
ASSERT_TRUE(terminated);
}
TEST(MessageLoop, NonDelayedTasksAreRunInOrder) {
const size_t count = 100;
bool started = false;
bool terminated = false;
std::thread thread([&started, &terminated, count]() {
fml::MessageLoop::EnsureInitializedForCurrentThread();
auto& loop = fml::MessageLoop::GetCurrent();
size_t current = 0;
for (size_t i = 0; i < count; i++) {
loop.GetTaskRunner()->PostTask([&terminated, i, ¤t]() {
ASSERT_EQ(current, i);
current++;
if (count == i + 1) {
fml::MessageLoop::GetCurrent().Terminate();
terminated = true;
}
});
}
loop.Run();
ASSERT_EQ(current, count);
started = true;
});
thread.join();
ASSERT_TRUE(started);
ASSERT_TRUE(terminated);
}
TEST(MessageLoop, DelayedTasksAtSameTimeAreRunInOrder) {
const size_t count = 100;
bool started = false;
bool terminated = false;
std::thread thread([&started, &terminated, count]() {
fml::MessageLoop::EnsureInitializedForCurrentThread();
auto& loop = fml::MessageLoop::GetCurrent();
size_t current = 0;
const auto now_plus_some =
fml::ChronoTicksSinceEpoch() + fml::TimeDelta::FromMilliseconds(2);
for (size_t i = 0; i < count; i++) {
loop.GetTaskRunner()->PostTaskForTime(
[&terminated, i, ¤t]() {
ASSERT_EQ(current, i);
current++;
if (count == i + 1) {
fml::MessageLoop::GetCurrent().Terminate();
terminated = true;
}
},
now_plus_some);
}
loop.Run();
ASSERT_EQ(current, count);
started = true;
});
thread.join();
ASSERT_TRUE(started);
ASSERT_TRUE(terminated);
}
TEST(MessageLoop, CheckRunsTaskOnCurrentThread) {
fml::RefPtr<fml::TaskRunner> runner;
fml::AutoResetWaitableEvent latch;
std::thread thread([&runner, &latch]() {
fml::MessageLoop::EnsureInitializedForCurrentThread();
auto& loop = fml::MessageLoop::GetCurrent();
runner = loop.GetTaskRunner();
latch.Signal();
ASSERT_TRUE(loop.GetTaskRunner()->RunsTasksOnCurrentThread());
});
latch.Wait();
ASSERT_TRUE(runner);
ASSERT_FALSE(runner->RunsTasksOnCurrentThread());
thread.join();
}
TEST(MessageLoop, TaskObserverFire) {
bool started = false;
bool terminated = false;
std::thread thread([&started, &terminated]() {
fml::MessageLoop::EnsureInitializedForCurrentThread();
const size_t count = 25;
auto& loop = fml::MessageLoop::GetCurrent();
size_t task_count = 0;
size_t obs_count = 0;
auto obs = [&obs_count]() { obs_count++; };
for (size_t i = 0; i < count; i++) {
loop.GetTaskRunner()->PostTask([&terminated, i, &task_count]() {
ASSERT_EQ(task_count, i);
task_count++;
if (count == i + 1) {
fml::MessageLoop::GetCurrent().Terminate();
terminated = true;
}
});
}
loop.AddTaskObserver(0, obs);
loop.Run();
ASSERT_EQ(task_count, count);
ASSERT_EQ(obs_count, count);
started = true;
});
thread.join();
ASSERT_TRUE(started);
ASSERT_TRUE(terminated);
}
TEST(MessageLoop, ConcurrentMessageLoopHasNonZeroWorkers) {
auto loop = fml::ConcurrentMessageLoop::Create(
0u /* explicitly specify zero workers */);
ASSERT_GT(loop->GetWorkerCount(), 0u);
}
TEST(MessageLoop, CanCreateAndShutdownConcurrentMessageLoopsOverAndOver) {
for (size_t i = 0; i < 10; ++i) {
auto loop = fml::ConcurrentMessageLoop::Create(i + 1);
ASSERT_EQ(loop->GetWorkerCount(), i + 1);
}
}
TEST(MessageLoop, CanCreateConcurrentMessageLoop) {
auto loop = fml::ConcurrentMessageLoop::Create();
auto task_runner = loop->GetTaskRunner();
const size_t kCount = 10;
fml::CountDownLatch latch(kCount);
std::mutex thread_ids_mutex;
std::set<std::thread::id> thread_ids;
for (size_t i = 0; i < kCount; ++i) {
task_runner->PostTask([&]() {
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Ran on thread: " << std::this_thread::get_id() << std::endl;
{
std::scoped_lock lock(thread_ids_mutex);
thread_ids.insert(std::this_thread::get_id());
}
latch.CountDown();
});
}
latch.Wait();
ASSERT_GE(thread_ids.size(), 1u);
}
| engine/fml/message_loop_unittests.cc/0 | {
"file_path": "engine/fml/message_loop_unittests.cc",
"repo_id": "engine",
"token_count": 2560
} | 169 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FML_PLATFORM_ANDROID_SCOPED_JAVA_REF_H_
#define FLUTTER_FML_PLATFORM_ANDROID_SCOPED_JAVA_REF_H_
#include <jni.h>
#include <cstddef>
#include "flutter/fml/macros.h"
namespace fml {
namespace jni {
// Creates a new local reference frame, in which at least a given number of
// local references can be created. Note that local references already created
// in previous local frames are still valid in the current local frame.
class ScopedJavaLocalFrame {
public:
explicit ScopedJavaLocalFrame(JNIEnv* env);
ScopedJavaLocalFrame(JNIEnv* env, int capacity);
~ScopedJavaLocalFrame();
private:
// This class is only good for use on the thread it was created on so
// it's safe to cache the non-threadsafe JNIEnv* inside this object.
JNIEnv* env_;
FML_DISALLOW_COPY_AND_ASSIGN(ScopedJavaLocalFrame);
};
// Forward declare the generic java reference template class.
template <typename T>
class JavaRef;
// Template specialization of JavaRef, which acts as the base class for all
// other JavaRef<> template types. This allows you to e.g. pass
// ScopedJavaLocalRef<jstring> into a function taking const JavaRef<jobject>&
template <>
class JavaRef<jobject> {
public:
jobject obj() const { return obj_; }
bool is_null() const { return obj_ == NULL; }
protected:
// Initializes a NULL reference.
JavaRef();
// Takes ownership of the |obj| reference passed; requires it to be a local
// reference type.
JavaRef(JNIEnv* env, jobject obj);
~JavaRef();
// The following are implementation detail convenience methods, for
// use by the sub-classes.
JNIEnv* SetNewLocalRef(JNIEnv* env, jobject obj);
void SetNewGlobalRef(JNIEnv* env, jobject obj);
void ResetLocalRef(JNIEnv* env);
void ResetGlobalRef();
jobject ReleaseInternal();
private:
jobject obj_;
FML_DISALLOW_COPY_AND_ASSIGN(JavaRef);
};
// Generic base class for ScopedJavaLocalRef and ScopedJavaGlobalRef. Useful
// for allowing functions to accept a reference without having to mandate
// whether it is a local or global type.
template <typename T>
class JavaRef : public JavaRef<jobject> {
public:
T obj() const { return static_cast<T>(JavaRef<jobject>::obj()); }
protected:
JavaRef() {}
~JavaRef() {}
JavaRef(JNIEnv* env, T obj) : JavaRef<jobject>(env, obj) {}
private:
FML_DISALLOW_COPY_AND_ASSIGN(JavaRef);
};
// Holds a local reference to a Java object. The local reference is scoped
// to the lifetime of this object.
// Instances of this class may hold onto any JNIEnv passed into it until
// destroyed. Therefore, since a JNIEnv is only suitable for use on a single
// thread, objects of this class must be created, used, and destroyed, on a
// single thread.
// Therefore, this class should only be used as a stack-based object and from a
// single thread. If you wish to have the reference outlive the current
// callstack (e.g. as a class member) or you wish to pass it across threads,
// use a ScopedJavaGlobalRef instead.
template <typename T>
class ScopedJavaLocalRef : public JavaRef<T> {
public:
ScopedJavaLocalRef() : env_(NULL) {}
// Non-explicit copy constructor, to allow ScopedJavaLocalRef to be returned
// by value as this is the normal usage pattern.
ScopedJavaLocalRef(const ScopedJavaLocalRef<T>& other) : env_(other.env_) {
this->SetNewLocalRef(env_, other.obj());
}
template <typename U>
explicit ScopedJavaLocalRef(const U& other) : env_(NULL) {
this->Reset(other);
}
// Assumes that |obj| is a local reference to a Java object and takes
// ownership of this local reference.
ScopedJavaLocalRef(JNIEnv* env, T obj) : JavaRef<T>(env, obj), env_(env) {}
~ScopedJavaLocalRef() { this->Reset(); }
// Overloaded assignment operator defined for consistency with the implicit
// copy constructor.
void operator=(const ScopedJavaLocalRef<T>& other) { this->Reset(other); }
void Reset() { this->ResetLocalRef(env_); }
template <typename U>
void Reset(const ScopedJavaLocalRef<U>& other) {
// We can copy over env_ here as |other| instance must be from the same
// thread as |this| local ref. (See class comment for multi-threading
// limitations, and alternatives).
this->Reset(other.env_, other.obj());
}
template <typename U>
void Reset(const U& other) {
// If |env_| was not yet set (is still NULL) it will be attached to the
// current thread in SetNewLocalRef().
this->Reset(env_, other.obj());
}
template <typename U>
void Reset(JNIEnv* env, U obj) {
env_ = this->SetNewLocalRef(env, obj);
}
// Releases the local reference to the caller. The caller *must* delete the
// local reference when it is done with it.
T Release() { return static_cast<T>(this->ReleaseInternal()); }
private:
// This class is only good for use on the thread it was created on so
// it's safe to cache the non-threadsafe JNIEnv* inside this object.
JNIEnv* env_;
};
// Holds a global reference to a Java object. The global reference is scoped
// to the lifetime of this object. This class does not hold onto any JNIEnv*
// passed to it, hence it is safe to use across threads (within the constraints
// imposed by the underlying Java object that it references).
template <typename T>
class ScopedJavaGlobalRef : public JavaRef<T> {
public:
ScopedJavaGlobalRef() {}
// NOLINTNEXTLINE(google-explicit-constructor)
explicit ScopedJavaGlobalRef(const ScopedJavaGlobalRef<T>& other) {
this->Reset(other);
}
ScopedJavaGlobalRef(JNIEnv* env, T obj) { this->Reset(env, obj); }
template <typename U>
explicit ScopedJavaGlobalRef(const U& other) {
this->Reset(other);
}
~ScopedJavaGlobalRef() { this->Reset(); }
void Reset() { this->ResetGlobalRef(); }
template <typename U>
void Reset(const U& other) {
this->Reset(NULL, other.obj());
}
template <typename U>
void Reset(JNIEnv* env, U obj) {
this->SetNewGlobalRef(env, obj);
}
// Releases the global reference to the caller. The caller *must* delete the
// global reference when it is done with it.
T Release() { return static_cast<T>(this->ReleaseInternal()); }
};
} // namespace jni
} // namespace fml
#endif // FLUTTER_FML_PLATFORM_ANDROID_SCOPED_JAVA_REF_H_
| engine/fml/platform/android/scoped_java_ref.h/0 | {
"file_path": "engine/fml/platform/android/scoped_java_ref.h",
"repo_id": "engine",
"token_count": 2037
} | 170 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <vector>
#import <CoreFoundation/CoreFoundation.h>
#include "flutter/fml/platform/darwin/scoped_nsobject.h"
#include "fml/logging.h"
#include "gtest/gtest.h"
#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "This file requires ARC support."
#endif
namespace {
template <typename NST>
CFIndex GetRetainCount(const fml::scoped_nsobject<NST>& nst) {
@autoreleasepool {
return CFGetRetainCount((__bridge CFTypeRef)nst.get()) - 1;
}
}
#if __has_feature(objc_arc_weak)
TEST(ScopedNSObjectTestARC, DefaultPolicyIsRetain) {
__weak id o;
@autoreleasepool {
fml::scoped_nsprotocol<id> p([[NSObject alloc] init]);
o = p.get();
EXPECT_EQ(o, p.get());
}
EXPECT_EQ(o, nil);
}
#endif
TEST(ScopedNSObjectTestARC, ScopedNSObject) {
fml::scoped_nsobject<NSObject> p1([[NSObject alloc] init]);
@autoreleasepool {
EXPECT_TRUE(p1.get());
EXPECT_TRUE(p1.get());
}
EXPECT_EQ(1, GetRetainCount(p1));
EXPECT_EQ(1, GetRetainCount(p1));
fml::scoped_nsobject<NSObject> p2(p1);
@autoreleasepool {
EXPECT_EQ(p1.get(), p2.get());
}
EXPECT_EQ(2, GetRetainCount(p1));
p2.reset();
EXPECT_EQ(nil, p2.get());
EXPECT_EQ(1, GetRetainCount(p1));
{
fml::scoped_nsobject<NSObject> p3 = p1;
@autoreleasepool {
EXPECT_EQ(p1.get(), p3.get());
}
EXPECT_EQ(2, GetRetainCount(p1));
p3 = p1;
@autoreleasepool {
EXPECT_EQ(p1.get(), p3.get());
}
EXPECT_EQ(2, GetRetainCount(p1));
}
EXPECT_EQ(1, GetRetainCount(p1));
fml::scoped_nsobject<NSObject> p4;
@autoreleasepool {
p4 = fml::scoped_nsobject<NSObject>(p1.get());
}
EXPECT_EQ(2, GetRetainCount(p1));
@autoreleasepool {
EXPECT_TRUE(p1 == p1.get());
EXPECT_TRUE(p1 == p1);
EXPECT_FALSE(p1 != p1);
EXPECT_FALSE(p1 != p1.get());
}
fml::scoped_nsobject<NSObject> p5([[NSObject alloc] init]);
@autoreleasepool {
EXPECT_TRUE(p1 != p5);
EXPECT_TRUE(p1 != p5.get());
EXPECT_FALSE(p1 == p5);
EXPECT_FALSE(p1 == p5.get());
}
fml::scoped_nsobject<NSObject> p6 = p1;
EXPECT_EQ(3, GetRetainCount(p6));
@autoreleasepool {
p6.autorelease();
EXPECT_EQ(nil, p6.get());
}
EXPECT_EQ(2, GetRetainCount(p1));
}
TEST(ScopedNSObjectTestARC, ScopedNSObjectInContainer) {
fml::scoped_nsobject<id> p([[NSObject alloc] init]);
@autoreleasepool {
EXPECT_TRUE(p.get());
}
EXPECT_EQ(1, GetRetainCount(p));
@autoreleasepool {
std::vector<fml::scoped_nsobject<id>> objects;
objects.push_back(p);
EXPECT_EQ(2, GetRetainCount(p));
@autoreleasepool {
EXPECT_EQ(p.get(), objects[0].get());
}
objects.push_back(fml::scoped_nsobject<id>([[NSObject alloc] init]));
@autoreleasepool {
EXPECT_TRUE(objects[1].get());
}
EXPECT_EQ(1, GetRetainCount(objects[1]));
}
EXPECT_EQ(1, GetRetainCount(p));
}
TEST(ScopedNSObjectTestARC, ScopedNSObjectFreeFunctions) {
fml::scoped_nsobject<id> p1([[NSObject alloc] init]);
id o1 = p1.get();
EXPECT_TRUE(o1 == p1);
EXPECT_FALSE(o1 != p1);
fml::scoped_nsobject<id> p2([[NSObject alloc] init]);
EXPECT_TRUE(o1 != p2);
EXPECT_FALSE(o1 == p2);
id o2 = p2.get();
swap(p1, p2);
EXPECT_EQ(o2, p1.get());
EXPECT_EQ(o1, p2.get());
}
} // namespace
| engine/fml/platform/darwin/scoped_nsobject_arc_unittests.mm/0 | {
"file_path": "engine/fml/platform/darwin/scoped_nsobject_arc_unittests.mm",
"repo_id": "engine",
"token_count": 1629
} | 171 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/fml/platform/fuchsia/message_loop_fuchsia.h"
#include <lib/async-loop/default.h>
#include <lib/async/cpp/task.h>
#include <lib/async/default.h>
#include <lib/zx/time.h>
#include <zircon/status.h>
#include "flutter/fml/platform/fuchsia/task_observers.h"
namespace fml {
namespace {
// See comment on `ExecuteAfterTaskObservers` for explanation.
static void LoopEpilogue(async_loop_t*, void*) {
ExecuteAfterTaskObservers();
}
constexpr async_loop_config_t kLoopConfig = {
.make_default_for_current_thread = false,
.epilogue = &LoopEpilogue,
};
} // namespace
MessageLoopFuchsia::MessageLoopFuchsia() : loop_(&kLoopConfig) {
async_set_default_dispatcher(loop_.dispatcher());
zx_status_t timer_status =
zx::timer::create(ZX_TIMER_SLACK_LATE, ZX_CLOCK_MONOTONIC, &timer_);
FML_CHECK(timer_status == ZX_OK)
<< "MessageLoopFuchsia failed to create timer; status="
<< zx_status_get_string(timer_status);
}
MessageLoopFuchsia::~MessageLoopFuchsia() {
// It is only safe to unset the current thread's default dispatcher if it is
// already pointing to this loop.
if (async_get_default_dispatcher() == loop_.dispatcher()) {
async_set_default_dispatcher(nullptr);
}
}
void MessageLoopFuchsia::Run() {
timer_wait_ = std::make_unique<async::Wait>(
timer_.get(), ZX_TIMER_SIGNALED, 0,
[this](async_dispatcher_t* dispatcher, async::Wait* wait,
zx_status_t status, const zx_packet_signal_t* signal) {
if (status == ZX_ERR_CANCELED) {
return;
}
FML_CHECK(signal->observed & ZX_TIMER_SIGNALED);
// Cancel the timer now, because `RunExpiredTasksNow` might not re-arm
// the timer. That would leave the timer in a signalled state and it
// would trigger the async::Wait again immediately, creating a busy
// loop.
//
// NOTE: It is not neccesary to synchronize this with the timer_.set()
// call below, even though WakeUp() can be called from any thread and
// thus timer_.set() can run in parallel with this timer_.cancel().
//
// Zircon will synchronize the 2 syscalls internally, and the Wait loop
// here is resilient to cancel() and set() being called in any order.
timer_.cancel();
// Run the tasks, which may or may not re-arm the timer for the future.
RunExpiredTasksNow();
// Kick off the next iteration of the timer wait loop.
zx_status_t wait_status = wait->Begin(loop_.dispatcher());
FML_CHECK(wait_status == ZX_OK)
<< "MessageLoopFuchsia::WakeUp failed to wait for timer; status="
<< zx_status_get_string(wait_status);
});
// Kick off the first iteration of the timer wait loop.
zx_status_t wait_status = timer_wait_->Begin(loop_.dispatcher());
FML_CHECK(wait_status == ZX_OK)
<< "MessageLoopFuchsia::WakeUp failed to wait for timer; status="
<< zx_status_get_string(wait_status);
// Kick off the underlying async loop that services the timer wait in addition
// to other tasks and waits queued on its `async_dispatcher_t`.
loop_.Run();
// Ensure any pending waits on the timer are properly canceled.
if (timer_wait_->is_pending()) {
timer_wait_->Cancel();
timer_.cancel();
}
}
void MessageLoopFuchsia::Terminate() {
loop_.Quit();
}
void MessageLoopFuchsia::WakeUp(fml::TimePoint time_point) {
constexpr zx::duration kZeroSlack(0);
zx::time due_time(time_point.ToEpochDelta().ToNanoseconds());
zx_status_t timer_status = timer_.set(due_time, kZeroSlack);
FML_CHECK(timer_status == ZX_OK)
<< "MessageLoopFuchsia::WakeUp failed to set timer; status="
<< zx_status_get_string(timer_status);
}
} // namespace fml
| engine/fml/platform/fuchsia/message_loop_fuchsia.cc/0 | {
"file_path": "engine/fml/platform/fuchsia/message_loop_fuchsia.cc",
"repo_id": "engine",
"token_count": 1498
} | 172 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FML_PLATFORM_WIN_WSTRING_CONVERSION_H_
#define FLUTTER_FML_PLATFORM_WIN_WSTRING_CONVERSION_H_
#include <string>
namespace fml {
// Returns a UTF-8 encoded equivalent of a UTF-16 encoded input wide string.
std::string WideStringToUtf8(const std::wstring_view str);
// Returns a UTF-16 encoded wide string equivalent of a UTF-8 encoded input
// string.
std::wstring Utf8ToWideString(const std::string_view str);
// Returns a UTF-16 encoded equivalent of a UTF-16 encoded wide string.
std::u16string WideStringToUtf16(const std::wstring_view str);
// Returns a UTF-16 encoded wide string equivalent of a UTF-16 string.
std::wstring Utf16ToWideString(const std::u16string_view str);
} // namespace fml
#endif // FLUTTER_FML_PLATFORM_WIN_WSTRING_CONVERSION_H_
| engine/fml/platform/win/wstring_conversion.h/0 | {
"file_path": "engine/fml/platform/win/wstring_conversion.h",
"repo_id": "engine",
"token_count": 306
} | 173 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/fml/synchronization/count_down_latch.h"
#include "flutter/fml/logging.h"
namespace fml {
CountDownLatch::CountDownLatch(size_t count) : count_(count) {
if (count_ == 0) {
waitable_event_.Signal();
}
}
CountDownLatch::~CountDownLatch() = default;
void CountDownLatch::Wait() {
waitable_event_.Wait();
}
void CountDownLatch::CountDown() {
if (--count_ == 0) {
waitable_event_.Signal();
}
}
} // namespace fml
| engine/fml/synchronization/count_down_latch.cc/0 | {
"file_path": "engine/fml/synchronization/count_down_latch.cc",
"repo_id": "engine",
"token_count": 222
} | 174 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#define FML_USED_ON_EMBEDDER
#include "flutter/fml/task_runner.h"
#include "flutter/fml/memory/task_runner_checker.h"
#include <utility>
#include "flutter/fml/logging.h"
#include "flutter/fml/message_loop.h"
#include "flutter/fml/message_loop_impl.h"
#include "flutter/fml/message_loop_task_queues.h"
namespace fml {
TaskRunner::TaskRunner(fml::RefPtr<MessageLoopImpl> loop)
: loop_(std::move(loop)) {}
TaskRunner::~TaskRunner() = default;
void TaskRunner::PostTask(const fml::closure& task) {
loop_->PostTask(task, fml::TimePoint::Now());
}
void TaskRunner::PostTaskForTime(const fml::closure& task,
fml::TimePoint target_time) {
loop_->PostTask(task, target_time);
}
void TaskRunner::PostDelayedTask(const fml::closure& task,
fml::TimeDelta delay) {
loop_->PostTask(task, fml::TimePoint::Now() + delay);
}
TaskQueueId TaskRunner::GetTaskQueueId() {
FML_DCHECK(loop_);
return loop_->GetTaskQueueId();
}
bool TaskRunner::RunsTasksOnCurrentThread() {
if (!fml::MessageLoop::IsInitializedForCurrentThread()) {
return false;
}
const auto current_queue_id = MessageLoop::GetCurrentTaskQueueId();
const auto loop_queue_id = loop_->GetTaskQueueId();
return TaskRunnerChecker::RunsOnTheSameThread(current_queue_id,
loop_queue_id);
}
void TaskRunner::RunNowOrPostTask(const fml::RefPtr<fml::TaskRunner>& runner,
const fml::closure& task) {
FML_DCHECK(runner);
if (runner->RunsTasksOnCurrentThread()) {
task();
} else {
runner->PostTask(task);
}
}
} // namespace fml
| engine/fml/task_runner.cc/0 | {
"file_path": "engine/fml/task_runner.cc",
"repo_id": "engine",
"token_count": 739
} | 175 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <thread>
#include "flutter/fml/time/chrono_timestamp_provider.h"
#include "flutter/fml/time/time_delta.h"
#include "gtest/gtest.h"
namespace fml {
namespace {
TEST(Time, Now) {
auto start = ChronoTicksSinceEpoch();
for (int i = 0; i < 3; ++i) {
auto now = ChronoTicksSinceEpoch();
EXPECT_GE(now, start);
std::this_thread::yield();
}
}
TEST(Time, IntConversions) {
// Integer conversions should all truncate, not round.
TimeDelta delta = TimeDelta::FromNanoseconds(102304506708ll);
EXPECT_EQ(102304506708ll, delta.ToNanoseconds());
EXPECT_EQ(102304506ll, delta.ToMicroseconds());
EXPECT_EQ(102304ll, delta.ToMilliseconds());
EXPECT_EQ(102ll, delta.ToSeconds());
}
TEST(Time, FloatConversions) {
// Float conversions should remain close to the original value.
TimeDelta delta = TimeDelta::FromNanoseconds(102304506708ll);
EXPECT_FLOAT_EQ(102304506708.0, delta.ToNanosecondsF());
EXPECT_FLOAT_EQ(102304506.708, delta.ToMicrosecondsF());
EXPECT_FLOAT_EQ(102304.506708, delta.ToMillisecondsF());
EXPECT_FLOAT_EQ(102.304506708, delta.ToSecondsF());
}
TEST(Time, TimespecConversions) {
struct timespec ts;
ts.tv_sec = 5;
ts.tv_nsec = 7;
TimeDelta from_timespec = TimeDelta::FromTimespec(ts);
EXPECT_EQ(5, from_timespec.ToSeconds());
EXPECT_EQ(5 * 1000000000ll + 7, from_timespec.ToNanoseconds());
struct timespec to_timespec = from_timespec.ToTimespec();
EXPECT_EQ(ts.tv_sec, to_timespec.tv_sec);
EXPECT_EQ(ts.tv_nsec, to_timespec.tv_nsec);
}
} // namespace
} // namespace fml
| engine/fml/time/time_unittest.cc/0 | {
"file_path": "engine/fml/time/time_unittest.cc",
"repo_id": "engine",
"token_count": 674
} | 176 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/impeller/aiks/aiks_unittests.h"
#include "impeller/aiks/canvas.h"
#include "impeller/entity/contents/conical_gradient_contents.h"
#include "impeller/entity/contents/linear_gradient_contents.h"
#include "impeller/entity/contents/radial_gradient_contents.h"
#include "impeller/entity/contents/sweep_gradient_contents.h"
#include "impeller/geometry/geometry_asserts.h"
#include "impeller/geometry/path_builder.h"
#include "impeller/playground/widgets.h"
#include "third_party/imgui/imgui.h"
////////////////////////////////////////////////////////////////////////////////
// This is for tests of Canvas that are interested the results of rendering
// gradients.
////////////////////////////////////////////////////////////////////////////////
namespace impeller {
namespace testing {
namespace {
void CanRenderLinearGradient(AiksTest* aiks_test, Entity::TileMode tile_mode) {
Canvas canvas;
canvas.Scale(aiks_test->GetContentScale());
Paint paint;
canvas.Translate({100.0f, 0, 0});
std::vector<Color> colors = {Color{0.9568, 0.2627, 0.2118, 1.0},
Color{0.1294, 0.5882, 0.9529, 0.0}};
std::vector<Scalar> stops = {0.0, 1.0};
paint.color_source = ColorSource::MakeLinearGradient(
{0, 0}, {200, 200}, std::move(colors), std::move(stops), tile_mode, {});
paint.color = Color(1.0, 1.0, 1.0, 1.0);
canvas.DrawRect(Rect::MakeXYWH(0, 0, 600, 600), paint);
ASSERT_TRUE(aiks_test->OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
} // namespace
TEST_P(AiksTest, CanRenderLinearGradientClamp) {
CanRenderLinearGradient(this, Entity::TileMode::kClamp);
}
TEST_P(AiksTest, CanRenderLinearGradientRepeat) {
CanRenderLinearGradient(this, Entity::TileMode::kRepeat);
}
TEST_P(AiksTest, CanRenderLinearGradientMirror) {
CanRenderLinearGradient(this, Entity::TileMode::kMirror);
}
TEST_P(AiksTest, CanRenderLinearGradientDecal) {
CanRenderLinearGradient(this, Entity::TileMode::kDecal);
}
TEST_P(AiksTest, CanRenderLinearGradientDecalWithColorFilter) {
Canvas canvas;
canvas.Scale(GetContentScale());
Paint paint;
canvas.Translate({100.0f, 0, 0});
std::vector<Color> colors = {Color{0.9568, 0.2627, 0.2118, 1.0},
Color{0.1294, 0.5882, 0.9529, 0.0}};
std::vector<Scalar> stops = {0.0, 1.0};
paint.color_source = ColorSource::MakeLinearGradient(
{0, 0}, {200, 200}, std::move(colors), std::move(stops),
Entity::TileMode::kDecal, {});
// Overlay the gradient with 25% green. This should appear as the entire
// rectangle being drawn with 25% green, including the border area outside the
// decal gradient.
paint.color_filter = ColorFilter::MakeBlend(BlendMode::kSourceOver,
Color::Green().WithAlpha(0.25));
paint.color = Color(1.0, 1.0, 1.0, 1.0);
canvas.DrawRect(Rect::MakeXYWH(0, 0, 600, 600), paint);
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
static void CanRenderLinearGradientWithDithering(AiksTest* aiks_test,
bool use_dithering) {
Canvas canvas;
Paint paint;
canvas.Translate({100.0, 100.0, 0});
// 0xffcccccc --> 0xff333333, taken from
// https://github.com/flutter/flutter/issues/118073#issue-1521699748
std::vector<Color> colors = {Color{0.8, 0.8, 0.8, 1.0},
Color{0.2, 0.2, 0.2, 1.0}};
std::vector<Scalar> stops = {0.0, 1.0};
paint.color_source = ColorSource::MakeLinearGradient(
{0, 0}, {800, 500}, std::move(colors), std::move(stops),
Entity::TileMode::kClamp, {});
paint.dither = use_dithering;
canvas.DrawRect(Rect::MakeXYWH(0, 0, 800, 500), paint);
ASSERT_TRUE(aiks_test->OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_P(AiksTest, CanRenderLinearGradientWithDitheringDisabled) {
CanRenderLinearGradientWithDithering(this, false);
}
TEST_P(AiksTest, CanRenderLinearGradientWithDitheringEnabled) {
CanRenderLinearGradientWithDithering(this, true);
} // namespace
static void CanRenderRadialGradientWithDithering(AiksTest* aiks_test,
bool use_dithering) {
Canvas canvas;
Paint paint;
canvas.Translate({100.0, 100.0, 0});
// #FFF -> #000
std::vector<Color> colors = {Color{1.0, 1.0, 1.0, 1.0},
Color{0.0, 0.0, 0.0, 1.0}};
std::vector<Scalar> stops = {0.0, 1.0};
paint.color_source = ColorSource::MakeRadialGradient(
{600, 600}, 600, std::move(colors), std::move(stops),
Entity::TileMode::kClamp, {});
paint.dither = use_dithering;
canvas.DrawRect(Rect::MakeXYWH(0, 0, 1200, 1200), paint);
ASSERT_TRUE(aiks_test->OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_P(AiksTest, CanRenderRadialGradientWithDitheringDisabled) {
CanRenderRadialGradientWithDithering(this, false);
}
TEST_P(AiksTest, CanRenderRadialGradientWithDitheringEnabled) {
CanRenderRadialGradientWithDithering(this, true);
}
static void CanRenderSweepGradientWithDithering(AiksTest* aiks_test,
bool use_dithering) {
Canvas canvas;
canvas.Scale(aiks_test->GetContentScale());
Paint paint;
canvas.Translate({100.0, 100.0, 0});
// #FFF -> #000
std::vector<Color> colors = {Color{1.0, 1.0, 1.0, 1.0},
Color{0.0, 0.0, 0.0, 1.0}};
std::vector<Scalar> stops = {0.0, 1.0};
paint.color_source = ColorSource::MakeSweepGradient(
{100, 100}, Degrees(45), Degrees(135), std::move(colors),
std::move(stops), Entity::TileMode::kMirror, {});
paint.dither = use_dithering;
canvas.DrawRect(Rect::MakeXYWH(0, 0, 600, 600), paint);
ASSERT_TRUE(aiks_test->OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_P(AiksTest, CanRenderSweepGradientWithDitheringDisabled) {
CanRenderSweepGradientWithDithering(this, false);
}
TEST_P(AiksTest, CanRenderSweepGradientWithDitheringEnabled) {
CanRenderSweepGradientWithDithering(this, true);
}
static void CanRenderConicalGradientWithDithering(AiksTest* aiks_test,
bool use_dithering) {
Canvas canvas;
canvas.Scale(aiks_test->GetContentScale());
Paint paint;
canvas.Translate({100.0, 100.0, 0});
// #FFF -> #000
std::vector<Color> colors = {Color{1.0, 1.0, 1.0, 1.0},
Color{0.0, 0.0, 0.0, 1.0}};
std::vector<Scalar> stops = {0.0, 1.0};
paint.color_source = ColorSource::MakeConicalGradient(
{100, 100}, 100, std::move(colors), std::move(stops), {0, 1}, 0,
Entity::TileMode::kMirror, {});
paint.dither = use_dithering;
canvas.DrawRect(Rect::MakeXYWH(0, 0, 600, 600), paint);
ASSERT_TRUE(aiks_test->OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_P(AiksTest, CanRenderConicalGradientWithDitheringDisabled) {
CanRenderConicalGradientWithDithering(this, false);
}
TEST_P(AiksTest, CanRenderConicalGradientWithDitheringEnabled) {
CanRenderConicalGradientWithDithering(this, true);
}
namespace {
void CanRenderLinearGradientWithOverlappingStops(AiksTest* aiks_test,
Entity::TileMode tile_mode) {
Canvas canvas;
Paint paint;
canvas.Translate({100.0, 100.0, 0});
std::vector<Color> colors = {
Color{0.9568, 0.2627, 0.2118, 1.0}, Color{0.9568, 0.2627, 0.2118, 1.0},
Color{0.1294, 0.5882, 0.9529, 1.0}, Color{0.1294, 0.5882, 0.9529, 1.0}};
std::vector<Scalar> stops = {0.0, 0.5, 0.5, 1.0};
paint.color_source = ColorSource::MakeLinearGradient(
{0, 0}, {500, 500}, std::move(colors), std::move(stops), tile_mode, {});
paint.color = Color(1.0, 1.0, 1.0, 1.0);
canvas.DrawRect(Rect::MakeXYWH(0, 0, 500, 500), paint);
ASSERT_TRUE(aiks_test->OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
} // namespace
// Only clamp is necessary. All tile modes are the same output.
TEST_P(AiksTest, CanRenderLinearGradientWithOverlappingStopsClamp) {
CanRenderLinearGradientWithOverlappingStops(this, Entity::TileMode::kClamp);
}
namespace {
void CanRenderLinearGradientManyColors(AiksTest* aiks_test,
Entity::TileMode tile_mode) {
Canvas canvas;
canvas.Scale(aiks_test->GetContentScale());
Paint paint;
canvas.Translate({100, 100, 0});
std::vector<Color> colors = {
Color{0x1f / 255.0, 0.0, 0x5c / 255.0, 1.0},
Color{0x5b / 255.0, 0.0, 0x60 / 255.0, 1.0},
Color{0x87 / 255.0, 0x01 / 255.0, 0x60 / 255.0, 1.0},
Color{0xac / 255.0, 0x25 / 255.0, 0x53 / 255.0, 1.0},
Color{0xe1 / 255.0, 0x6b / 255.0, 0x5c / 255.0, 1.0},
Color{0xf3 / 255.0, 0x90 / 255.0, 0x60 / 255.0, 1.0},
Color{0xff / 255.0, 0xb5 / 255.0, 0x6b / 250.0, 1.0}};
std::vector<Scalar> stops = {
0.0,
(1.0 / 6.0) * 1,
(1.0 / 6.0) * 2,
(1.0 / 6.0) * 3,
(1.0 / 6.0) * 4,
(1.0 / 6.0) * 5,
1.0,
};
paint.color_source = ColorSource::MakeLinearGradient(
{0, 0}, {200, 200}, std::move(colors), std::move(stops), tile_mode, {});
paint.color = Color(1.0, 1.0, 1.0, 1.0);
canvas.DrawRect(Rect::MakeXYWH(0, 0, 600, 600), paint);
canvas.Restore();
ASSERT_TRUE(aiks_test->OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
} // namespace
TEST_P(AiksTest, CanRenderLinearGradientManyColorsClamp) {
CanRenderLinearGradientManyColors(this, Entity::TileMode::kClamp);
}
TEST_P(AiksTest, CanRenderLinearGradientManyColorsRepeat) {
CanRenderLinearGradientManyColors(this, Entity::TileMode::kRepeat);
}
TEST_P(AiksTest, CanRenderLinearGradientManyColorsMirror) {
CanRenderLinearGradientManyColors(this, Entity::TileMode::kMirror);
}
TEST_P(AiksTest, CanRenderLinearGradientManyColorsDecal) {
CanRenderLinearGradientManyColors(this, Entity::TileMode::kDecal);
}
namespace {
void CanRenderLinearGradientWayManyColors(AiksTest* aiks_test,
Entity::TileMode tile_mode) {
Canvas canvas;
Paint paint;
canvas.Translate({100.0, 100.0, 0});
auto color = Color{0x1f / 255.0, 0.0, 0x5c / 255.0, 1.0};
std::vector<Color> colors;
std::vector<Scalar> stops;
auto current_stop = 0.0;
for (int i = 0; i < 2000; i++) {
colors.push_back(color);
stops.push_back(current_stop);
current_stop += 1 / 2000.0;
}
stops[2000 - 1] = 1.0;
paint.color_source = ColorSource::MakeLinearGradient(
{0, 0}, {200, 200}, std::move(colors), std::move(stops), tile_mode, {});
canvas.DrawRect(Rect::MakeXYWH(0, 0, 600, 600), paint);
ASSERT_TRUE(aiks_test->OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
} // namespace
// Only test clamp on purpose since they all look the same.
TEST_P(AiksTest, CanRenderLinearGradientWayManyColorsClamp) {
CanRenderLinearGradientWayManyColors(this, Entity::TileMode::kClamp);
}
TEST_P(AiksTest, CanRenderLinearGradientManyColorsUnevenStops) {
auto callback = [&](AiksContext& renderer) -> std::optional<Picture> {
const char* tile_mode_names[] = {"Clamp", "Repeat", "Mirror", "Decal"};
const Entity::TileMode tile_modes[] = {
Entity::TileMode::kClamp, Entity::TileMode::kRepeat,
Entity::TileMode::kMirror, Entity::TileMode::kDecal};
static int selected_tile_mode = 0;
static Matrix matrix = {
1, 0, 0, 0, //
0, 1, 0, 0, //
0, 0, 1, 0, //
0, 0, 0, 1 //
};
if (AiksTest::ImGuiBegin("Controls", nullptr,
ImGuiWindowFlags_AlwaysAutoResize)) {
ImGui::Combo("Tile mode", &selected_tile_mode, tile_mode_names,
sizeof(tile_mode_names) / sizeof(char*));
std::string label = "##1";
for (int i = 0; i < 4; i++) {
ImGui::InputScalarN(label.c_str(), ImGuiDataType_Float,
&(matrix.vec[i]), 4, NULL, NULL, "%.2f", 0);
label[2]++;
}
ImGui::End();
}
Canvas canvas;
Paint paint;
canvas.Translate({100.0, 100.0, 0});
auto tile_mode = tile_modes[selected_tile_mode];
std::vector<Color> colors = {
Color{0x1f / 255.0, 0.0, 0x5c / 255.0, 1.0},
Color{0x5b / 255.0, 0.0, 0x60 / 255.0, 1.0},
Color{0x87 / 255.0, 0x01 / 255.0, 0x60 / 255.0, 1.0},
Color{0xac / 255.0, 0x25 / 255.0, 0x53 / 255.0, 1.0},
Color{0xe1 / 255.0, 0x6b / 255.0, 0x5c / 255.0, 1.0},
Color{0xf3 / 255.0, 0x90 / 255.0, 0x60 / 255.0, 1.0},
Color{0xff / 255.0, 0xb5 / 255.0, 0x6b / 250.0, 1.0}};
std::vector<Scalar> stops = {
0.0, 2.0 / 62.0, 4.0 / 62.0, 8.0 / 62.0, 16.0 / 62.0, 32.0 / 62.0, 1.0,
};
paint.color_source = ColorSource::MakeLinearGradient(
{0, 0}, {200, 200}, std::move(colors), std::move(stops), tile_mode, {});
canvas.DrawRect(Rect::MakeXYWH(0, 0, 600, 600), paint);
return canvas.EndRecordingAsPicture();
};
ASSERT_TRUE(OpenPlaygroundHere(callback));
}
TEST_P(AiksTest, CanRenderLinearGradientMaskBlur) {
Canvas canvas;
Paint paint = {
.color = Color::White(),
.color_source = ColorSource::MakeLinearGradient(
{200, 200}, {400, 400},
{Color::Red(), Color::White(), Color::Red(), Color::White(),
Color::Red(), Color::White(), Color::Red(), Color::White(),
Color::Red(), Color::White(), Color::Red()},
{0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0},
Entity::TileMode::kClamp, {}),
.mask_blur_descriptor =
Paint::MaskBlurDescriptor{
.style = FilterContents::BlurStyle::kNormal,
.sigma = Sigma(20),
},
};
canvas.DrawCircle({300, 300}, 200, paint);
canvas.DrawRect(Rect::MakeLTRB(100, 300, 500, 600), paint);
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_P(AiksTest, CanRenderRadialGradient) {
auto callback = [&](AiksContext& renderer) -> std::optional<Picture> {
const char* tile_mode_names[] = {"Clamp", "Repeat", "Mirror", "Decal"};
const Entity::TileMode tile_modes[] = {
Entity::TileMode::kClamp, Entity::TileMode::kRepeat,
Entity::TileMode::kMirror, Entity::TileMode::kDecal};
static int selected_tile_mode = 0;
static Matrix matrix = {
1, 0, 0, 0, //
0, 1, 0, 0, //
0, 0, 1, 0, //
0, 0, 0, 1 //
};
if (AiksTest::ImGuiBegin("Controls", nullptr,
ImGuiWindowFlags_AlwaysAutoResize)) {
ImGui::Combo("Tile mode", &selected_tile_mode, tile_mode_names,
sizeof(tile_mode_names) / sizeof(char*));
std::string label = "##1";
for (int i = 0; i < 4; i++) {
ImGui::InputScalarN(label.c_str(), ImGuiDataType_Float,
&(matrix.vec[i]), 4, NULL, NULL, "%.2f", 0);
label[2]++;
}
ImGui::End();
}
Canvas canvas;
Paint paint;
canvas.Translate({100.0, 100.0, 0});
auto tile_mode = tile_modes[selected_tile_mode];
std::vector<Color> colors = {Color{0.9568, 0.2627, 0.2118, 1.0},
Color{0.1294, 0.5882, 0.9529, 1.0}};
std::vector<Scalar> stops = {0.0, 1.0};
paint.color_source = ColorSource::MakeRadialGradient(
{100, 100}, 100, std::move(colors), std::move(stops), tile_mode, {});
canvas.DrawRect(Rect::MakeXYWH(0, 0, 600, 600), paint);
return canvas.EndRecordingAsPicture();
};
ASSERT_TRUE(OpenPlaygroundHere(callback));
}
TEST_P(AiksTest, CanRenderRadialGradientManyColors) {
auto callback = [&](AiksContext& renderer) -> std::optional<Picture> {
const char* tile_mode_names[] = {"Clamp", "Repeat", "Mirror", "Decal"};
const Entity::TileMode tile_modes[] = {
Entity::TileMode::kClamp, Entity::TileMode::kRepeat,
Entity::TileMode::kMirror, Entity::TileMode::kDecal};
static int selected_tile_mode = 0;
static Matrix matrix = {
1, 0, 0, 0, //
0, 1, 0, 0, //
0, 0, 1, 0, //
0, 0, 0, 1 //
};
if (AiksTest::ImGuiBegin("Controls", nullptr,
ImGuiWindowFlags_AlwaysAutoResize)) {
ImGui::Combo("Tile mode", &selected_tile_mode, tile_mode_names,
sizeof(tile_mode_names) / sizeof(char*));
std::string label = "##1";
for (int i = 0; i < 4; i++) {
ImGui::InputScalarN(label.c_str(), ImGuiDataType_Float,
&(matrix.vec[i]), 4, NULL, NULL, "%.2f", 0);
label[2]++;
}
ImGui::End();
}
Canvas canvas;
Paint paint;
canvas.Translate({100.0, 100.0, 0});
auto tile_mode = tile_modes[selected_tile_mode];
std::vector<Color> colors = {
Color{0x1f / 255.0, 0.0, 0x5c / 255.0, 1.0},
Color{0x5b / 255.0, 0.0, 0x60 / 255.0, 1.0},
Color{0x87 / 255.0, 0x01 / 255.0, 0x60 / 255.0, 1.0},
Color{0xac / 255.0, 0x25 / 255.0, 0x53 / 255.0, 1.0},
Color{0xe1 / 255.0, 0x6b / 255.0, 0x5c / 255.0, 1.0},
Color{0xf3 / 255.0, 0x90 / 255.0, 0x60 / 255.0, 1.0},
Color{0xff / 255.0, 0xb5 / 255.0, 0x6b / 250.0, 1.0}};
std::vector<Scalar> stops = {
0.0,
(1.0 / 6.0) * 1,
(1.0 / 6.0) * 2,
(1.0 / 6.0) * 3,
(1.0 / 6.0) * 4,
(1.0 / 6.0) * 5,
1.0,
};
paint.color_source = ColorSource::MakeRadialGradient(
{100, 100}, 100, std::move(colors), std::move(stops), tile_mode, {});
canvas.DrawRect(Rect::MakeXYWH(0, 0, 600, 600), paint);
return canvas.EndRecordingAsPicture();
};
ASSERT_TRUE(OpenPlaygroundHere(callback));
}
namespace {
void CanRenderSweepGradient(AiksTest* aiks_test, Entity::TileMode tile_mode) {
Canvas canvas;
canvas.Scale(aiks_test->GetContentScale());
Paint paint;
canvas.Translate({100, 100, 0});
std::vector<Color> colors = {Color{0.9568, 0.2627, 0.2118, 1.0},
Color{0.1294, 0.5882, 0.9529, 1.0}};
std::vector<Scalar> stops = {0.0, 1.0};
paint.color_source = ColorSource::MakeSweepGradient(
{100, 100}, Degrees(45), Degrees(135), std::move(colors),
std::move(stops), tile_mode, {});
canvas.DrawRect(Rect::MakeXYWH(0, 0, 600, 600), paint);
ASSERT_TRUE(aiks_test->OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
} // namespace
TEST_P(AiksTest, CanRenderSweepGradientClamp) {
CanRenderSweepGradient(this, Entity::TileMode::kClamp);
}
TEST_P(AiksTest, CanRenderSweepGradientRepeat) {
CanRenderSweepGradient(this, Entity::TileMode::kRepeat);
}
TEST_P(AiksTest, CanRenderSweepGradientMirror) {
CanRenderSweepGradient(this, Entity::TileMode::kMirror);
}
TEST_P(AiksTest, CanRenderSweepGradientDecal) {
CanRenderSweepGradient(this, Entity::TileMode::kDecal);
}
namespace {
void CanRenderSweepGradientManyColors(AiksTest* aiks_test,
Entity::TileMode tile_mode) {
Canvas canvas;
Paint paint;
canvas.Translate({100.0, 100.0, 0});
std::vector<Color> colors = {
Color{0x1f / 255.0, 0.0, 0x5c / 255.0, 1.0},
Color{0x5b / 255.0, 0.0, 0x60 / 255.0, 1.0},
Color{0x87 / 255.0, 0x01 / 255.0, 0x60 / 255.0, 1.0},
Color{0xac / 255.0, 0x25 / 255.0, 0x53 / 255.0, 1.0},
Color{0xe1 / 255.0, 0x6b / 255.0, 0x5c / 255.0, 1.0},
Color{0xf3 / 255.0, 0x90 / 255.0, 0x60 / 255.0, 1.0},
Color{0xff / 255.0, 0xb5 / 255.0, 0x6b / 250.0, 1.0}};
std::vector<Scalar> stops = {
0.0,
(1.0 / 6.0) * 1,
(1.0 / 6.0) * 2,
(1.0 / 6.0) * 3,
(1.0 / 6.0) * 4,
(1.0 / 6.0) * 5,
1.0,
};
paint.color_source = ColorSource::MakeSweepGradient(
{100, 100}, Degrees(45), Degrees(135), std::move(colors),
std::move(stops), tile_mode, {});
canvas.DrawRect(Rect::MakeXYWH(0, 0, 600, 600), paint);
ASSERT_TRUE(aiks_test->OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
} // namespace
TEST_P(AiksTest, CanRenderSweepGradientManyColorsClamp) {
CanRenderSweepGradientManyColors(this, Entity::TileMode::kClamp);
}
TEST_P(AiksTest, CanRenderSweepGradientManyColorsRepeat) {
CanRenderSweepGradientManyColors(this, Entity::TileMode::kRepeat);
}
TEST_P(AiksTest, CanRenderSweepGradientManyColorsMirror) {
CanRenderSweepGradientManyColors(this, Entity::TileMode::kMirror);
}
TEST_P(AiksTest, CanRenderSweepGradientManyColorsDecal) {
CanRenderSweepGradientManyColors(this, Entity::TileMode::kDecal);
}
TEST_P(AiksTest, CanRenderConicalGradient) {
Scalar size = 256;
Canvas canvas;
Paint paint;
paint.color = Color::White();
canvas.DrawRect(Rect::MakeXYWH(0, 0, size * 3, size * 3), paint);
std::vector<Color> colors = {Color::MakeRGBA8(0xF4, 0x43, 0x36, 0xFF),
Color::MakeRGBA8(0xFF, 0xEB, 0x3B, 0xFF),
Color::MakeRGBA8(0x4c, 0xAF, 0x50, 0xFF),
Color::MakeRGBA8(0x21, 0x96, 0xF3, 0xFF)};
std::vector<Scalar> stops = {0.0, 1.f / 3.f, 2.f / 3.f, 1.0};
std::array<std::tuple<Point, float, Point, float>, 8> array{
std::make_tuple(Point{size / 2.f, size / 2.f}, 0.f,
Point{size / 2.f, size / 2.f}, size / 2.f),
std::make_tuple(Point{size / 2.f, size / 2.f}, size / 4.f,
Point{size / 2.f, size / 2.f}, size / 2.f),
std::make_tuple(Point{size / 4.f, size / 4.f}, 0.f,
Point{size / 2.f, size / 2.f}, size / 2.f),
std::make_tuple(Point{size / 4.f, size / 4.f}, size / 2.f,
Point{size / 2.f, size / 2.f}, 0),
std::make_tuple(Point{size / 4.f, size / 4.f}, size / 4.f,
Point{size / 2.f, size / 2.f}, size / 2.f),
std::make_tuple(Point{size / 4.f, size / 4.f}, size / 16.f,
Point{size / 2.f, size / 2.f}, size / 8.f),
std::make_tuple(Point{size / 4.f, size / 4.f}, size / 8.f,
Point{size / 2.f, size / 2.f}, size / 16.f),
std::make_tuple(Point{size / 8.f, size / 8.f}, size / 8.f,
Point{size / 2.f, size / 2.f}, size / 8.f),
};
for (int i = 0; i < 8; i++) {
canvas.Save();
canvas.Translate({(i % 3) * size, i / 3 * size, 0});
paint.color_source = ColorSource::MakeConicalGradient(
std::get<0>(array[i]), std::get<1>(array[i]), colors, stops,
std::get<2>(array[i]), std::get<3>(array[i]), Entity::TileMode::kClamp,
{});
canvas.DrawRect(Rect::MakeXYWH(0, 0, size, size), paint);
canvas.Restore();
}
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_P(AiksTest, CanRenderGradientDecalWithBackground) {
std::vector<Color> colors = {Color::MakeRGBA8(0xF4, 0x43, 0x36, 0xFF),
Color::MakeRGBA8(0xFF, 0xEB, 0x3B, 0xFF),
Color::MakeRGBA8(0x4c, 0xAF, 0x50, 0xFF),
Color::MakeRGBA8(0x21, 0x96, 0xF3, 0xFF)};
std::vector<Scalar> stops = {0.0, 1.f / 3.f, 2.f / 3.f, 1.0};
std::array<ColorSource, 3> color_sources = {
ColorSource::MakeLinearGradient({0, 0}, {100, 100}, colors, stops,
Entity::TileMode::kDecal, {}),
ColorSource::MakeRadialGradient({100, 100}, 100, colors, stops,
Entity::TileMode::kDecal, {}),
ColorSource::MakeSweepGradient({100, 100}, Degrees(45), Degrees(135),
colors, stops, Entity::TileMode::kDecal,
{}),
};
Canvas canvas;
Paint paint;
paint.color = Color::White();
canvas.DrawRect(Rect::MakeLTRB(0, 0, 605, 205), paint);
for (int i = 0; i < 3; i++) {
canvas.Save();
canvas.Translate({i * 200.0f, 0, 0});
paint.color_source = color_sources[i];
canvas.DrawRect(Rect::MakeLTRB(0, 0, 200, 200), paint);
canvas.Restore();
}
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
#define APPLY_COLOR_FILTER_GRADIENT_TEST(name) \
TEST_P(AiksTest, name##GradientApplyColorFilter) { \
auto contents = name##GradientContents(); \
contents.SetColors({Color::CornflowerBlue().WithAlpha(0.75)}); \
auto result = contents.ApplyColorFilter([](const Color& color) { \
return color.Blend(Color::LimeGreen().WithAlpha(0.75), \
BlendMode::kScreen); \
}); \
ASSERT_TRUE(result); \
\
std::vector<Color> expected = {Color(0.433247, 0.879523, 0.825324, 0.75)}; \
ASSERT_COLORS_NEAR(contents.GetColors(), expected); \
}
APPLY_COLOR_FILTER_GRADIENT_TEST(Linear);
APPLY_COLOR_FILTER_GRADIENT_TEST(Radial);
APPLY_COLOR_FILTER_GRADIENT_TEST(Conical);
APPLY_COLOR_FILTER_GRADIENT_TEST(Sweep);
TEST_P(AiksTest, GradientStrokesRenderCorrectly) {
// Compare with https://fiddle.skia.org/c/027392122bec8ac2b5d5de00a4b9bbe2
auto callback = [&](AiksContext& renderer) -> std::optional<Picture> {
static float scale = 3;
static bool add_circle_clip = true;
const char* tile_mode_names[] = {"Clamp", "Repeat", "Mirror", "Decal"};
const Entity::TileMode tile_modes[] = {
Entity::TileMode::kClamp, Entity::TileMode::kRepeat,
Entity::TileMode::kMirror, Entity::TileMode::kDecal};
static int selected_tile_mode = 0;
static float alpha = 1;
if (AiksTest::ImGuiBegin("Controls", nullptr,
ImGuiWindowFlags_AlwaysAutoResize)) {
ImGui::SliderFloat("Scale", &scale, 0, 6);
ImGui::Checkbox("Circle clip", &add_circle_clip);
ImGui::SliderFloat("Alpha", &alpha, 0, 1);
ImGui::Combo("Tile mode", &selected_tile_mode, tile_mode_names,
sizeof(tile_mode_names) / sizeof(char*));
ImGui::End();
}
Canvas canvas;
canvas.Scale(GetContentScale());
Paint paint;
paint.color = Color::White();
canvas.DrawPaint(paint);
paint.style = Paint::Style::kStroke;
paint.color = Color(1.0, 1.0, 1.0, alpha);
paint.stroke_width = 10;
auto tile_mode = tile_modes[selected_tile_mode];
std::vector<Color> colors = {Color{0.9568, 0.2627, 0.2118, 1.0},
Color{0.1294, 0.5882, 0.9529, 1.0}};
std::vector<Scalar> stops = {0.0, 1.0};
paint.color_source = ColorSource::MakeLinearGradient(
{0, 0}, {50, 50}, std::move(colors), std::move(stops), tile_mode, {});
Path path = PathBuilder{}
.MoveTo({20, 20})
.QuadraticCurveTo({60, 20}, {60, 60})
.Close()
.MoveTo({60, 20})
.QuadraticCurveTo({60, 60}, {20, 60})
.TakePath();
canvas.Scale(Vector2(scale, scale));
if (add_circle_clip) {
static PlaygroundPoint circle_clip_point_a(Point(60, 300), 20,
Color::Red());
static PlaygroundPoint circle_clip_point_b(Point(600, 300), 20,
Color::Red());
auto [handle_a, handle_b] =
DrawPlaygroundLine(circle_clip_point_a, circle_clip_point_b);
auto screen_to_canvas = canvas.GetCurrentTransform().Invert();
Point point_a = screen_to_canvas * handle_a * GetContentScale();
Point point_b = screen_to_canvas * handle_b * GetContentScale();
Point middle = (point_a + point_b) / 2;
auto radius = point_a.GetDistance(middle);
canvas.ClipPath(PathBuilder{}.AddCircle(middle, radius).TakePath());
}
for (auto join : {Join::kBevel, Join::kRound, Join::kMiter}) {
paint.stroke_join = join;
for (auto cap : {Cap::kButt, Cap::kSquare, Cap::kRound}) {
paint.stroke_cap = cap;
canvas.DrawPath(path, paint);
canvas.Translate({80, 0});
}
canvas.Translate({-240, 60});
}
return canvas.EndRecordingAsPicture();
};
ASSERT_TRUE(OpenPlaygroundHere(callback));
}
} // namespace testing
} // namespace impeller
| engine/impeller/aiks/aiks_gradient_unittests.cc/0 | {
"file_path": "engine/impeller/aiks/aiks_gradient_unittests.cc",
"repo_id": "engine",
"token_count": 13434
} | 177 |
// Copyright 2013 The Flutter Authors. All rights 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_COLOR_FILTER_H_
#define FLUTTER_IMPELLER_AIKS_COLOR_FILTER_H_
#include "impeller/entity/contents/filters/color_filter_contents.h"
#include "impeller/geometry/color.h"
namespace impeller {
struct Paint;
/*******************************************************************************
******* ColorFilter
******************************************************************************/
class ColorFilter {
public:
/// A procedure that filters a given unpremultiplied color to produce a new
/// unpremultiplied color.
using ColorFilterProc = std::function<Color(Color)>;
ColorFilter();
virtual ~ColorFilter();
static std::shared_ptr<ColorFilter> MakeBlend(BlendMode blend_mode,
Color color);
static std::shared_ptr<ColorFilter> MakeMatrix(ColorMatrix color_matrix);
static std::shared_ptr<ColorFilter> MakeSrgbToLinear();
static std::shared_ptr<ColorFilter> MakeLinearToSrgb();
static std::shared_ptr<ColorFilter> MakeComposed(
const std::shared_ptr<ColorFilter>& outer,
const std::shared_ptr<ColorFilter>& inner);
/// @brief Wraps the given filter input with a GPU-based filter that will
/// perform the color operation. The given input will first be
/// rendered to a texture and then filtered.
///
/// Note that this operation has no consideration for the original
/// geometry mask of the filter input. And the entire input texture is
/// treated as color information.
virtual std::shared_ptr<ColorFilterContents> WrapWithGPUColorFilter(
std::shared_ptr<FilterInput> input,
ColorFilterContents::AbsorbOpacity absorb_opacity) const = 0;
/// @brief Returns a function that can be used to filter unpremultiplied
/// Impeller Colors on the CPU.
virtual ColorFilterProc GetCPUColorFilterProc() const = 0;
virtual std::shared_ptr<ColorFilter> Clone() const = 0;
};
/*******************************************************************************
******* BlendColorFilter
******************************************************************************/
class BlendColorFilter final : public ColorFilter {
public:
BlendColorFilter(BlendMode blend_mode, Color color);
~BlendColorFilter() override;
// |ColorFilter|
std::shared_ptr<ColorFilterContents> WrapWithGPUColorFilter(
std::shared_ptr<FilterInput> input,
ColorFilterContents::AbsorbOpacity absorb_opacity) const override;
// |ColorFilter|
ColorFilterProc GetCPUColorFilterProc() const override;
// |ColorFilter|
std::shared_ptr<ColorFilter> Clone() const override;
private:
BlendMode blend_mode_;
Color color_;
};
/*******************************************************************************
******* MatrixColorFilter
******************************************************************************/
class MatrixColorFilter final : public ColorFilter {
public:
explicit MatrixColorFilter(ColorMatrix color_matrix);
~MatrixColorFilter() override;
// |ColorFilter|
std::shared_ptr<ColorFilterContents> WrapWithGPUColorFilter(
std::shared_ptr<FilterInput> input,
ColorFilterContents::AbsorbOpacity absorb_opacity) const override;
// |ColorFilter|
ColorFilterProc GetCPUColorFilterProc() const override;
// |ColorFilter|
std::shared_ptr<ColorFilter> Clone() const override;
private:
ColorMatrix color_matrix_;
};
/*******************************************************************************
******* SrgbToLinearColorFilter
******************************************************************************/
class SrgbToLinearColorFilter final : public ColorFilter {
public:
explicit SrgbToLinearColorFilter();
~SrgbToLinearColorFilter() override;
// |ColorFilter|
std::shared_ptr<ColorFilterContents> WrapWithGPUColorFilter(
std::shared_ptr<FilterInput> input,
ColorFilterContents::AbsorbOpacity absorb_opacity) const override;
// |ColorFilter|
ColorFilterProc GetCPUColorFilterProc() const override;
// |ColorFilter|
std::shared_ptr<ColorFilter> Clone() const override;
};
/*******************************************************************************
******* LinearToSrgbColorFilter
******************************************************************************/
class LinearToSrgbColorFilter final : public ColorFilter {
public:
explicit LinearToSrgbColorFilter();
~LinearToSrgbColorFilter() override;
// |ColorFilter|
std::shared_ptr<ColorFilterContents> WrapWithGPUColorFilter(
std::shared_ptr<FilterInput> input,
ColorFilterContents::AbsorbOpacity absorb_opacity) const override;
// |ColorFilter|
ColorFilterProc GetCPUColorFilterProc() const override;
// |ColorFilter|
std::shared_ptr<ColorFilter> Clone() const override;
};
/// @brief Applies color filters as f(g(x)), where x is the input color.
class ComposedColorFilter final : public ColorFilter {
public:
ComposedColorFilter(const std::shared_ptr<ColorFilter>& outer,
const std::shared_ptr<ColorFilter>& inner);
~ComposedColorFilter() override;
// |ColorFilter|
std::shared_ptr<ColorFilterContents> WrapWithGPUColorFilter(
std::shared_ptr<FilterInput> input,
ColorFilterContents::AbsorbOpacity absorb_opacity) const override;
// |ColorFilter|
ColorFilterProc GetCPUColorFilterProc() const override;
// |ColorFilter|
std::shared_ptr<ColorFilter> Clone() const override;
private:
std::shared_ptr<ColorFilter> outer_;
std::shared_ptr<ColorFilter> inner_;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_AIKS_COLOR_FILTER_H_
| engine/impeller/aiks/color_filter.h/0 | {
"file_path": "engine/impeller/aiks/color_filter.h",
"repo_id": "engine",
"token_count": 1691
} | 178 |
// Copyright 2013 The Flutter Authors. 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 "impeller/renderer/command_buffer.h"
#include "impeller/renderer/command_queue.h"
#include "impeller/aiks/testing/context_spy.h"
namespace impeller {
namespace testing {
fml::Status NoopCommandQueue::Submit(
const std::vector<std::shared_ptr<CommandBuffer>>& buffers,
const CompletionCallback& completion_callback) {
if (completion_callback) {
completion_callback(CommandBuffer::Status::kCompleted);
}
return fml::Status();
}
std::shared_ptr<ContextSpy> ContextSpy::Make() {
return std::shared_ptr<ContextSpy>(new ContextSpy());
}
std::shared_ptr<ContextMock> ContextSpy::MakeContext(
const std::shared_ptr<Context>& real_context) {
std::shared_ptr<ContextMock> mock_context =
std::make_shared<::testing::NiceMock<ContextMock>>();
std::shared_ptr<ContextSpy> shared_this = shared_from_this();
ON_CALL(*mock_context, IsValid).WillByDefault([real_context]() {
return real_context->IsValid();
});
ON_CALL(*mock_context, GetBackendType)
.WillByDefault([real_context]() -> Context::BackendType {
return real_context->GetBackendType();
});
ON_CALL(*mock_context, GetCapabilities)
.WillByDefault(
[real_context]() -> const std::shared_ptr<const Capabilities>& {
return real_context->GetCapabilities();
});
ON_CALL(*mock_context, UpdateOffscreenLayerPixelFormat)
.WillByDefault([real_context](PixelFormat format) {
return real_context->UpdateOffscreenLayerPixelFormat(format);
});
ON_CALL(*mock_context, GetResourceAllocator).WillByDefault([real_context]() {
return real_context->GetResourceAllocator();
});
ON_CALL(*mock_context, GetShaderLibrary).WillByDefault([real_context]() {
return real_context->GetShaderLibrary();
});
ON_CALL(*mock_context, GetSamplerLibrary).WillByDefault([real_context]() {
return real_context->GetSamplerLibrary();
});
ON_CALL(*mock_context, GetPipelineLibrary).WillByDefault([real_context]() {
return real_context->GetPipelineLibrary();
});
ON_CALL(*mock_context, GetCommandQueue).WillByDefault([shared_this]() {
return shared_this->command_queue_;
});
ON_CALL(*mock_context, CreateCommandBuffer)
.WillByDefault([real_context, shared_this]() {
auto real_buffer = real_context->CreateCommandBuffer();
auto spy = std::make_shared<::testing::NiceMock<CommandBufferMock>>(
real_context);
ON_CALL(*spy, IsValid).WillByDefault([real_buffer]() {
return real_buffer->IsValid();
});
ON_CALL(*spy, SetLabel)
.WillByDefault([real_buffer](const std::string& label) {
return real_buffer->SetLabel(label);
});
ON_CALL(*spy, OnCreateRenderPass)
.WillByDefault([real_buffer, shared_this,
real_context](const RenderTarget& render_target) {
std::shared_ptr<RenderPass> result =
CommandBufferMock::ForwardOnCreateRenderPass(
real_buffer.get(), render_target);
std::shared_ptr<RecordingRenderPass> recorder =
std::make_shared<RecordingRenderPass>(result, real_context,
render_target);
shared_this->render_passes_.push_back(recorder);
return recorder;
});
ON_CALL(*spy, OnCreateBlitPass).WillByDefault([real_buffer]() {
return CommandBufferMock::ForwardOnCreateBlitPass(real_buffer.get());
});
ON_CALL(*spy, OnSubmitCommands)
.WillByDefault(
[real_buffer](CommandBuffer::CompletionCallback callback) {
return CommandBufferMock::ForwardOnSubmitCommands(
real_buffer.get(), std::move(callback));
});
ON_CALL(*spy, OnWaitUntilScheduled).WillByDefault([real_buffer]() {
return CommandBufferMock::ForwardOnWaitUntilScheduled(
real_buffer.get());
});
ON_CALL(*spy, OnCreateComputePass).WillByDefault([real_buffer]() {
return CommandBufferMock::ForwardOnCreateComputePass(
real_buffer.get());
});
return spy;
});
return mock_context;
}
} // namespace testing
} // namespace impeller
| engine/impeller/aiks/testing/context_spy.cc/0 | {
"file_path": "engine/impeller/aiks/testing/context_spy.cc",
"repo_id": "engine",
"token_count": 1856
} | 179 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_BASE_PROMISE_H_
#define FLUTTER_IMPELLER_BASE_PROMISE_H_
#include <future>
namespace impeller {
template <class T>
std::future<T> RealizedFuture(T t) {
std::promise<T> promise;
auto future = promise.get_future();
promise.set_value(std::move(t));
return future;
}
// Wraps a std::promise and completes the promise with a value during
// destruction if the promise does not already have a value.
//
// By default the std::promise destructor will complete an empty promise with an
// exception. This will fail because Flutter is built without exception support.
template <typename T>
class NoExceptionPromise {
public:
NoExceptionPromise() = default;
~NoExceptionPromise() {
if (!value_set_) {
promise_.set_value({});
}
}
std::future<T> get_future() { return promise_.get_future(); }
void set_value(const T& value) {
promise_.set_value(value);
value_set_ = true;
}
private:
std::promise<T> promise_;
bool value_set_ = false;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_BASE_PROMISE_H_
| engine/impeller/base/promise.h/0 | {
"file_path": "engine/impeller/base/promise.h",
"repo_id": "engine",
"token_count": 421
} | 180 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_COMPILER_COMPILER_H_
#define FLUTTER_IMPELLER_COMPILER_COMPILER_H_
#include <initializer_list>
#include <sstream>
#include <string>
#include "flutter/fml/macros.h"
#include "flutter/fml/mapping.h"
#include "impeller/compiler/include_dir.h"
#include "impeller/compiler/reflector.h"
#include "impeller/compiler/source_options.h"
#include "impeller/compiler/spirv_compiler.h"
#include "impeller/compiler/types.h"
#include "spirv_msl.hpp"
#include "spirv_parser.hpp"
namespace impeller {
namespace compiler {
class Compiler {
public:
Compiler(const std::shared_ptr<const fml::Mapping>& source_mapping,
const SourceOptions& options,
Reflector::Options reflector_options);
~Compiler();
bool IsValid() const;
std::shared_ptr<fml::Mapping> GetSPIRVAssembly() const;
std::shared_ptr<fml::Mapping> GetSLShaderSource() const;
std::string GetErrorMessages() const;
const std::vector<std::string>& GetIncludedFileNames() const;
std::unique_ptr<fml::Mapping> CreateDepfileContents(
std::initializer_list<std::string> targets) const;
const Reflector* GetReflector() const;
private:
SourceOptions options_;
std::shared_ptr<fml::Mapping> spirv_assembly_;
std::shared_ptr<fml::Mapping> sl_mapping_;
std::stringstream error_stream_;
std::unique_ptr<Reflector> reflector_;
std::vector<std::string> included_file_names_;
bool is_valid_ = false;
std::string GetSourcePrefix() const;
std::string GetDependencyNames(const std::string& separator) const;
Compiler(const Compiler&) = delete;
Compiler& operator=(const Compiler&) = delete;
};
} // namespace compiler
} // namespace impeller
#endif // FLUTTER_IMPELLER_COMPILER_COMPILER_H_
| engine/impeller/compiler/compiler.h/0 | {
"file_path": "engine/impeller/compiler/compiler.h",
"repo_id": "engine",
"token_count": 682
} | 181 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_COMPILER_RUNTIME_STAGE_DATA_H_
#define FLUTTER_IMPELLER_COMPILER_RUNTIME_STAGE_DATA_H_
#include <memory>
#include <vector>
#include "flutter/fml/macros.h"
#include "flutter/fml/mapping.h"
#include "impeller/compiler/types.h"
#include "impeller/core/runtime_types.h"
#include "runtime_stage_types_flatbuffers.h"
#include "spirv_parser.hpp"
namespace impeller {
namespace compiler {
class RuntimeStageData {
public:
struct Shader {
Shader() = default;
std::string entrypoint;
spv::ExecutionModel stage;
std::vector<UniformDescription> uniforms;
std::vector<InputDescription> inputs;
std::shared_ptr<fml::Mapping> shader;
RuntimeStageBackend backend;
Shader(const Shader&) = delete;
Shader& operator=(const Shader&) = delete;
};
RuntimeStageData();
~RuntimeStageData();
void AddShader(const std::shared_ptr<Shader>& data);
std::unique_ptr<fb::RuntimeStageT> CreateStageFlatbuffer(
impeller::RuntimeStageBackend backend) const;
std::unique_ptr<fb::RuntimeStagesT> CreateMultiStageFlatbuffer() const;
std::shared_ptr<fml::Mapping> CreateJsonMapping() const;
std::shared_ptr<fml::Mapping> CreateMapping() const;
private:
std::map<RuntimeStageBackend, std::shared_ptr<Shader>> data_;
RuntimeStageData(const RuntimeStageData&) = delete;
RuntimeStageData& operator=(const RuntimeStageData&) = delete;
};
} // namespace compiler
} // namespace impeller
#endif // FLUTTER_IMPELLER_COMPILER_RUNTIME_STAGE_DATA_H_
| engine/impeller/compiler/runtime_stage_data.h/0 | {
"file_path": "engine/impeller/compiler/runtime_stage_data.h",
"repo_id": "engine",
"token_count": 589
} | 182 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <impeller/tile_mode.glsl>
/// A triangle wave. 0->0, 1->1, 2->0, and so on... works with negative numbers.
float TriangleWave(float x) {
return abs(mod(x + 1, 2) - 1);
}
/// OES_EGL_image_external states that only CLAMP_TO_EDGE is valid, so we
/// emulate all other tile modes here by remapping the texture coordinates.
vec4 IPSampleWithTileModeOES(sampler2D tex,
vec2 coords,
float x_tile_mode,
float y_tile_mode) {
if (x_tile_mode == kTileModeDecal && (coords.x < 0 || coords.x >= 1) ||
y_tile_mode == kTileModeDecal && (coords.y < 0 || coords.y >= 1)) {
return vec4(0);
}
if (x_tile_mode == kTileModeRepeat) {
coords.x = mod(coords.x, 1);
} else if (x_tile_mode == kTileModeMirror) {
coords.x = TriangleWave(coords.x);
}
if (y_tile_mode == kTileModeRepeat) {
coords.y = mod(coords.y, 1);
} else if (y_tile_mode == kTileModeMirror) {
coords.y = TriangleWave(coords.y);
}
return texture(tex, coords);
}
| engine/impeller/compiler/shader_lib/impeller/external_texture_oes.glsl/0 | {
"file_path": "engine/impeller/compiler/shader_lib/impeller/external_texture_oes.glsl",
"repo_id": "engine",
"token_count": 515
} | 183 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_COMPILER_SWITCHES_H_
#define FLUTTER_IMPELLER_COMPILER_SWITCHES_H_
#include <cstdint>
#include <iostream>
#include <memory>
#include "flutter/fml/command_line.h"
#include "flutter/fml/unique_fd.h"
#include "impeller/compiler/include_dir.h"
#include "impeller/compiler/source_options.h"
#include "impeller/compiler/types.h"
namespace impeller {
namespace compiler {
class Switches {
public:
std::shared_ptr<fml::UniqueFD> working_directory = nullptr;
std::vector<IncludeDir> include_directories = {};
std::string source_file_name = "";
SourceType input_type = SourceType::kUnknown;
/// The raw shader file output by the compiler. For --iplr and
/// --shader-bundle modes, this is used as the filename for the output
/// flatbuffer output.
std::string sl_file_name = "";
bool iplr = false;
std::string shader_bundle = "";
std::string spirv_file_name = "";
std::string reflection_json_name = "";
std::string reflection_header_name = "";
std::string reflection_cc_name = "";
std::string depfile_path = "";
std::vector<std::string> defines = {};
bool json_format = false;
SourceLanguage source_language = SourceLanguage::kUnknown;
uint32_t gles_language_version = 0;
std::string metal_version = "";
std::string entry_point = "";
bool use_half_textures = false;
bool require_framebuffer_fetch = false;
Switches();
~Switches();
explicit Switches(const fml::CommandLine& command_line);
bool AreValid(std::ostream& explain) const;
/// A vector containing at least one valid platform.
std::vector<TargetPlatform> PlatformsToCompile() const;
TargetPlatform SelectDefaultTargetPlatform() const;
// Creates source options from these switches for the specified
// TargetPlatform. Uses SelectDefaultTargetPlatform if not specified.
SourceOptions CreateSourceOptions(
std::optional<TargetPlatform> target_platform = std::nullopt) const;
static void PrintHelp(std::ostream& stream);
private:
// Use |SelectDefaultTargetPlatform|.
TargetPlatform target_platform_ = TargetPlatform::kUnknown;
// Use |PlatformsToCompile|.
std::vector<TargetPlatform> runtime_stages_;
};
} // namespace compiler
} // namespace impeller
#endif // FLUTTER_IMPELLER_COMPILER_SWITCHES_H_
| engine/impeller/compiler/switches.h/0 | {
"file_path": "engine/impeller/compiler/switches.h",
"repo_id": "engine",
"token_count": 775
} | 184 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/core/device_buffer.h"
namespace impeller {
DeviceBuffer::DeviceBuffer(DeviceBufferDescriptor desc) : desc_(desc) {}
DeviceBuffer::~DeviceBuffer() = default;
void DeviceBuffer::Flush(std::optional<Range> range) const {}
void DeviceBuffer::Invalidate(std::optional<Range> range) const {}
// static
BufferView DeviceBuffer::AsBufferView(std::shared_ptr<DeviceBuffer> buffer) {
BufferView view;
view.buffer = std::move(buffer);
view.range = {0u, view.buffer->desc_.size};
return view;
}
std::shared_ptr<Texture> DeviceBuffer::AsTexture(
Allocator& allocator,
const TextureDescriptor& descriptor,
uint16_t row_bytes) const {
auto texture = allocator.CreateTexture(descriptor);
if (!texture) {
return nullptr;
}
if (!texture->SetContents(std::make_shared<fml::NonOwnedMapping>(
OnGetContents(), desc_.size))) {
return nullptr;
}
return texture;
}
const DeviceBufferDescriptor& DeviceBuffer::GetDeviceBufferDescriptor() const {
return desc_;
}
[[nodiscard]] bool DeviceBuffer::CopyHostBuffer(const uint8_t* source,
Range source_range,
size_t offset) {
if (source_range.length == 0u) {
// Nothing to copy. Bail.
return true;
}
if (source == nullptr) {
// Attempted to copy data from a null buffer.
return false;
}
if (desc_.storage_mode != StorageMode::kHostVisible) {
// One of the storage modes where a transfer queue must be used.
return false;
}
if (offset + source_range.length > desc_.size) {
// Out of bounds of this buffer.
return false;
}
return OnCopyHostBuffer(source, source_range, offset);
}
} // namespace impeller
| engine/impeller/core/device_buffer.cc/0 | {
"file_path": "engine/impeller/core/device_buffer.cc",
"repo_id": "engine",
"token_count": 694
} | 185 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/core/sampler.h"
namespace impeller {
Sampler::Sampler(SamplerDescriptor desc) : desc_(std::move(desc)) {}
Sampler::~Sampler() = default;
const SamplerDescriptor& Sampler::GetDescriptor() const {
return desc_;
}
} // namespace impeller
| engine/impeller/core/sampler.cc/0 | {
"file_path": "engine/impeller/core/sampler.cc",
"repo_id": "engine",
"token_count": 136
} | 186 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_DISPLAY_LIST_DL_IMAGE_IMPELLER_H_
#define FLUTTER_IMPELLER_DISPLAY_LIST_DL_IMAGE_IMPELLER_H_
#include "flutter/display_list/image/dl_image.h"
#include "impeller/core/texture.h"
namespace impeller {
class AiksContext;
class DlImageImpeller final : public flutter::DlImage {
public:
static sk_sp<DlImageImpeller> Make(
std::shared_ptr<Texture> texture,
OwningContext owning_context = OwningContext::kIO);
static sk_sp<DlImageImpeller> MakeFromYUVTextures(
AiksContext* aiks_context,
std::shared_ptr<Texture> y_texture,
std::shared_ptr<Texture> uv_texture,
YUVColorSpace yuv_color_space);
// |DlImage|
~DlImageImpeller() override;
// |DlImage|
sk_sp<SkImage> skia_image() const override;
// |DlImage|
std::shared_ptr<impeller::Texture> impeller_texture() const override;
// |DlImage|
bool isOpaque() const override;
// |DlImage|
bool isTextureBacked() const override;
// |DlImage|
bool isUIThreadSafe() const override;
// |DlImage|
SkISize dimensions() const override;
// |DlImage|
size_t GetApproximateByteSize() const override;
// |DlImage|
OwningContext owning_context() const override { return owning_context_; }
private:
std::shared_ptr<Texture> texture_;
OwningContext owning_context_;
explicit DlImageImpeller(std::shared_ptr<Texture> texture,
OwningContext owning_context = OwningContext::kIO);
DlImageImpeller(const DlImageImpeller&) = delete;
DlImageImpeller& operator=(const DlImageImpeller&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_DISPLAY_LIST_DL_IMAGE_IMPELLER_H_
| engine/impeller/display_list/dl_image_impeller.h/0 | {
"file_path": "engine/impeller/display_list/dl_image_impeller.h",
"repo_id": "engine",
"token_count": 687
} | 187 |
# Learning to Read GPU Frame Captures
This is a gentle introduction to learning how one may go about reading a GPU
frame capture. This would be using a tool like the [Xcode GPU Frame
Debugger](https://developer.apple.com/documentation/metal/frame_capture_debugging_tools?language=objc),
[RenderDoc](https://renderdoc.org/), or [Android GPU
Inspector](https://gpuinspector.dev/). If you are already comfortable using one
or all of these tools, this introduction is likely too rudimentary for you. If
so, please skip this.
If you are working on Impeller (or any low-level graphics API for that matter),
it is unlikely you are going to get any work done without a frame debugger.
Fortunately, it is also extremely easy and fun. But it does require learning a
new skill-set.
I liken getting proficient at graphics debugging to learning how to drive. It is
absolutely a skill-set that must be learned. And, you get better at it the more
you practice.
The car you choose to learn to drive on really doesn’t matter. It may be gas or
electric, stick-shift or automatic. Admittedly, some cars are easier to learn to
drive on than others. But again, the car isn’t the point. The same holds for
graphics debuggers and the client rendering APIs. If you can read a GPU Frame
capture of a Vulkan frame on Windows using RenderDoc, you should be quickly able
to read a trace for a Metal Frame on iOS using Xcode. In fact, in a
cross-platform framework like Impeller, it is unlikely you are going to be able
to get away with using just one debugger. Like cars, all of them have their own
quirks and use-cases with no one-size-fits all solution.
# Start in an Empty Parking Lot
You wouldn’t start learning to drive on a busy freeway or city street. So, if
you immediately open a frame trace of a very complicated application, you are
likely to get overwhelmed.
Start with a frame that renders absolutely nothing. You are only figuring out
what the pedals in the car are and what the gauges mean. We are going to be
using Xcode in this tutorial in case you are following along. But again, the car
doesn’t matter.
Make sure you have already set up an Xcode session by following the instructions
in the wiki. Setup a test that opens a blank playground. With the playground
running, click on the stylized `M` to capture a Metal frame.

Give Xcode a few seconds to capture the frame and show the frame overview.

Let’s figure out what the gauges of this car mean.
* In box `4`, the overview shows that there are no draw calls and one command
buffer with one render command encoder. This is for the playground to render
the blank screen with the clear-color.
* The playground renders a dark slate gray clear color as it was adequately
contrasty with the primary colors and also black and white.
* Box `2` shows the Metal calls made grouped by the API call. If you click on
the Group by API Call dropdown, you can group the calls made according to the
pipeline state. But we have no draw calls remember, so this will be empty.
But, realize that in a more complicated application where you are looking for
a single class of draw calls, viewing by the pipeline state is going to be
more useful.
* When grouping by the API call, absolutely all calls made to the Metal API will
be shown in the sidebar. Most of them are not particularly interesting. These
include calls to allocate memory, create command buffers, set labels, etc.. To
whittle down this list to a (potentially) more interesting subset, click the
little flag at the bottom (see box `8`). But, if you ever find a call you were
looking for is not present in the sidebar, you may have filtered it away.
* Box `5` shows frame performance. But there is nothing to show as we are not
rendering anything. We’ll come back to this later.
* Box `6` shows the graphics memory overview. We’ll revisit this in detail later
too. But, it is a good idea to see what memory rendering a blank slate needs.
Realize that all graphics memory is not equal and learning when to use one vs
the other can lead to some interesting performance improvements.
* Box `7` is Xcodes attempt at showing you how you can improve performance.
These are just insights though and not warnings or errors. But, in every
frame, try to understand and reason about each insight to see if action is
necessary. In most cases, you can address these insights fairly easily. In the
example above, there are three insights. Lets reason about them:
* There are two insights for the late creation of two textures. From the
names of the textures, you can tell that one is the texture used for the
stencil buffer and another the color texture used for the 4xMSAA resolve
step. Impeller uses memory-less textures for those on iOS and the
playground is running on Mac. So it hasn’t bothered to create and reuse
textures in the playground runner. But, it should. And Xcode’s point that
texture allocations should not occur in a frame workload is well made.
Advice that is universally prudent when working on Impeller.
* The last insight is that the main render pass is empty. Well, no shit,
Sherlock. We won’t have this concern in a real application. The playground
will always render frames over and over specifically so that a frame
debugger can capture a frame. Even if nothing is in that frame. This won’t
be a problem in Flutter where no frame will be rendered if nothing
changes.
* Notice that we could immediately tell what the two textures that were
created late were for. This is because all GPU objects in Impeller have
the ability to be labelled. In fact most APIs in Impeller make it very
hard to create unlabelled objects. If you notice an object that is not
labelled, file a bug to label it. Better yet, find and label it yourself.
Building for easier instrumentation must be done diligently and
proactively. And it is your responsibility!
* Box `1` is the nav stack that you will use often and is unreasonably effective
in Xcode relative to other debuggers. It’s a good idea to remember its key
binding (mine is ctrl+cmd+arrow). If you click on something and find yourself
lost, go back to a known point (usually the summary).
* Box `3` highlights an `Export` button. This allows you to export a GPU trace.
But, realize that whoever views a GPU Trace needs to have identical hardware.
The traces are also rather large. So, in a single debugging session, you
should store these traces locally so you can check how your iterations are
affecting the frame. But you may not find sending these to others super
useful.
Before we trace anything more complicated, let’s take a look at the memory usage
in the playground.
# Memory Overview
Click on the `Show Memory` button in Box `6` from the previous section. We are
still not rendering anything in the playground.
An overview of all graphics memory usage is shown.

Along with all the objects that occupy memory, their locations in different
memory categorizations are also shown. Notice how the totals all add up to the
same number. This is useful in cases where you forgot to assign the optimum
memory storage mode for textures or buffers (private, managed, or memory-less).
You can double click an object to inspect it and highlighting a texture should
give you a preview of its contents.

Do not underestimate the usefulness of filtering the results either by category
name or resource name. You can filter by category by selecting the small
circular callstack button next to the category. When you apply filters, the
memory totals will update to reflect just filtered items. Here, there is 3 MB of
device memory for managed textures.

You can also apply freeform text filters to the resources using the text field
highlighted by the second box. This is used by multiple Impeller subsystems. For
example, offscreen textures that are used within a frame between multiple
render-passes are named such that they can be easily filtered. So, if you wanted
to estimate the memory overhead of such render-passes (say you are working on
optimizations to elide these), you can easily tell using a simple text filter.
This also highlights the importance of always naming all GPU resources. Again,
if you find an unnamed resource in this view, file a but to have it be tagged or
[tag it yourself](#finding-where-api-calls-were-made-in-the-codebase).
The “Time Since Last Used” is useful in catching potential memory leaks as
allocations not referenced for multiple frames must typically be collected to
save memory. Flutter applications typically have tons of these as its image
caches reference images that aren’t used for a while. If these are tagged
correctly (which they should be), they can be filtered away. That way, you can
focus on leaks in specific subsystems without having “cached” items confuse the
memory view.
# Driving on the Street
So we’re comfortable with the car in the parking lot and we know what all the
gauges and pedals do. Let’s drive this car onto a quiet street.
Let’s render a scene that actually renders something. But, let’s just render a
solid red triangle in the playground.

We notice two changes in the overview.
* When grouping the calls by the pipeline state, we see one pipeline listed with
one draw call. Since all GPU objects in Impeller are labelled, we see one
pipeline aptly called the `SolidFillPipeline` with one draw call.
* The `Performance` section in box `5` from the last section is no longer empty.
Let’s dive into each of the new sections.
## Inspecting the Pipeline State Object
All draw calls use a pipeline state object that specifies the programmable and
fixed function elements of the draw call as well as the data referenced by that
draw call.
The programmable elements of the pipeline state object are defined by shaders
that are written on the host and compiled into the engine in an intermediate
representation. Vertex shaders are run per vertex in the draw call and fragment
shaders run once per texture element in the coverage area of the draw call.
There are numerous fixed function elements in a pipeline state object. But the
major ones Impeller typically must configure are blend modes (i.e, how the new
texture element must combine with items already in the framebuffer), sample
counts for resolve (used in MSAA), pixel formats of its various attachments,
etc..
Pipeline state objects are immutable. So, if either the programmable or fixed
function element of the object needs to be modified, a new variant must be
created.
So, if you see multiple instances of a named pipeline in the grouping of calls
by pipeline state, realize that it is a different variant of a prototype
pipeline state. If these are not named appropriately and you can’t tell the
difference, file a bug to disambiguate them or [tag them
yourself](#finding-where-api-calls-were-made-in-the-codebase)!
Let’s click on the `SolidFill Pipeline` in the example to analyze that pipeline.
All draw calls listed below that pipeline use the same programmable and fixed
function pipeline configuration.

You will get intimately familiar with this view when you set up a new pipeline
state object in Impeller or try to reason about the correctness of one of the
pipeline state object variants.
In this example, we can tell that all draw calls with this pipeline state have
blending enabled with the given blend mode and work on images with `BGRA8Unorm`
pixel format. The draw call can also expect a stencil buffer.
Clicking on either the vertex or fragment shader should show the equivalent
Metal source code for the GLSL shader written in Impeller. This Metal source
code (and the shader debugger) is only available in debug and profile modes.
When GLSL shaders are written in Impeller, they are converted into intermediate
representation for packaging with the engine. However, since debugging shaders
is such a useful exercise, the shader compiler will also compile the GLSL
shaders into Metal source code and then package it with the debug or profile
engine alongside the intermediate representation that is actually used. That
way, the Xcode frame debugger can find that code when you ask to debug the
programmable elements of the pipeline.
We'll go into using the shader debugger later. But, now you know how to inspect
a pipeline.
## Inspecting a Single Draw Call
Each draw call must reference a pipeline state (that we already know how to
inspect) and provide references to the data used by that draw call (like vertex
and uniform buffers, attachments) along with metadata about it (like primitive
topology).
To inspect how each draw call is configured, select the call in the sidebar.

To get an overview of the draw call, the Bound Resources section is the most
useful view. Let’s ensure we understand each item.
The `Pipeline States` section we have already [covered in
detail](#inspecting-the-pipeline-state-object).
In the `Vertex` section, the `Geometry` lists how each vertex is transformed by
the vertex shader.

Here, you see how each vertex (three here since we are rendering a triangle) is
transformed by the shader such that it ends up in the correct spot in normalized
device coordinates. In this particular case, the solid color seems to be
presented to the vertex shader in a uniform with the shader passing it along to
the fragment stage as an output. An improvement could be to present the uniform
directly to the fragment stage. Impeller may have done this because only a
single uniform buffer for all stages was easier to set up.
You can double click on any buffer in the `Bound Resources` section to dump
information about that buffer presented in a view appropriate for that stage.
When I double click the buffer containing the uniform data, the following view
is shown.

Pay specific attention to the `Row` index. Impeller architecture doesn’t create
small individual buffers for uniform data. All uniform data for a single render
pass is packed into a single jumbo uniform buffer with each draw call
referencing its uniform data at an offset into this larger buffer. This allows
Impeller to avoid small allocations and use a simpler and faster bump allocator.
Here, it looks like the uniform data is towards the end of that jumbo buffer as
noted by the negative indices present in the view. The data at negative indices
is interpreted as garbage when viewed through the lens of the uniform data
layout the draw call expects.
The other useful item in the `Bound Resources` section is the state of the
attachments when the draw call was made. This comes in particularly handy for
debugging writes to a buffer that you will never actually see. For instance, the
stencil buffers.
To demonstrate debugging stencil buffers, I captured a trace of a Fuchsia
colored rectangle clipped to a circular shape. You’d never see the stencil
buffer so it would be hard to understand how the draw call is affecting it
without viewing the attachment in the frame debugger. Clicking on the gear to
the right of the buffer label also shows a histogram of the image as well as
options to change the color mapping, or, to view values within a certain range.
In this simple example, the values in the stencil buffer only range from 0 to 2.
So viewing the entire range of values in the stencil buffer would have made the
changes in the buffer indiscernible to you. Xcode helpfully selected the “Min to
Max” view for us. You can do the same for any attachment.

## Debugging a Shader
The shaders authored in Impeller use [GLSL
4.60](https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.4.60.pdf).
Xcode does not support debugging these shaders natively. To work around this,
the Impeller shader compiler will convert those shaders to Metal source code and
embed them inside debug and profile mode engine binaries alongside the shaders
intermediate representation that is actually used to generate the pipeline state
objects. The Metal source code is converted such that it looks as similar to
GLSL as possible.
You can debug both vertex and fragment shaders. Remember that vertex shaders run
once per vertex (three times in the case of our example that renders a simple
triangle) and fragment shaders run once per texture element in the coverage area
of the draw call (potentially thousands of times depending on the side of the
triangle rendered). So, when you want to debug a shader, you must first find one
specific invocation of either the vertex or fragment shader to debug.
### iOS & macOS: Tell Xcode the Location of your Shaders
When using the Metal backend, instead of packaging shader sources as strings,
Impeller compiles and packages them into a single shader library. This library
is stripped of debugging information to minimize the size overhead. This
debugging information is not tossed away however. In the `out/<variant>/shaders`
directory, you will find a series of files with the `.metallibsym` extension.
When you try to debug a shader for the first time as described in the sections
below, Xcode you prompt you with a dialog that says it can't find the sources
for shader along with a button to show it where to find the relevant
`.metallibsym` files. Click that button and a dialog will pop up showing the
Metal libraries whose `.metallibsym` files could not be resolved.

In the "External Source Search Paths" section, click the tiny `+` button at the
bottom. In the file chooser dialog box that appears next, select all the
`metallibsym` files in the `out/<variant>/shaders` directory.
You will only have to do this once per engine variant. The search paths will
remain the same as you rebuild the engine and the `.metallibsym` files contain
the UUID of the shader library. So Xcode won't attempt to resolve shaders
sources in an outdated `.metallibsym` file.
You may however also run into Xcode complaining about "Invalid UUID" errors.
This is instead of the "No Source" errors as shown in the dialog above.

The team has been unable to to find documentation for this type of error. But
through trial-and-error, we have determined that the way to fix this is to set
the deployment target of the application to the current OS version during the
instrumentation run (either on macOS or iOS). To information about this line of
troubleshooting can be found [here](https://github.com/flutter/engine/pull/39532).
### Debugging a Fragment Shader
Since fragment shaders are run once per texture element in the coverage area of
the draw call, it is easiest to find invocations of the fragment shader by
opening one of the attachments used by the draw call.
Find and open either the color or stencil attachments in the `Bound Resources`
section as described in the section on [inspecting a single draw
call](#inspecting-a-single-draw-call).

At the bottom right corner of the attachment preview, you will see a disabled
`Debug` button with a crosshair to its right. The button is disabled because no
texture element is selected for debugging. Click on the crosshair and drag the
magnifier on a texture element converted by a draw call. The draw call will be
highlighted with a green outline.
Once a valid texture element is highlighted, the `Debug` button should be
enabled. Click it to debug that one invocation of the fragment shader used by
that draw call.

In the sidebar on the left, each step of execution of the fragment shader is
listed. You can click on each to move back and forth through the invocation. The
values of local variables will be updated as you do.
Some of the usual things to look out for when debugging fragment shaders:
* Pay attention to the input to the fragment stage from the vertex stage. This
is present in the argument marked with `[[stage_in]]`.
* The output of the stage (which defines the color of the texture element for
that invocation) is the return value of the invocation.
* If you aren’t sure of a particular operation within the shader, try adding
intermediate variables to the shader. The Impeller shader compiler will
faithfully add those intermediate for ease of debugging. Optimizations that
hinder debuggability are reserved for optimized release modes and occur on the
intermediate representation.
### Debugging a Vertex Shader
Since vertex shaders are run once per vertex in the draw call, it is easiest to
find an invocation of the vertex shader in the geometry viewer.
In the `Bound Resources` of a specific draw call, open the `Geometry` section as
described in the section on [inspecting a single draw
call](#inspecting-a-single-draw-call).

In this view, the `Debug` button on the bottom right will be disabled unless a
specific vertex in the geometry has been selected. Once you select the vertex
whose vertex shader invocation you want to debug, the button should be enabled.
Click it.

In the sidebar on the left, each step of execution of the vertex shader is
listed. You can click on each to move back and forth through the invocation. The
values of local variables will be updated as you do.
Some of the usual things to look out for when debugging vertex shaders:
* Pay attention to the input to the vertex stage invocation. This is present in
the argument marked with `[[stage_in]]`. This is the data you packed into the
vertex buffer for the draw call using an `impeller::VertexBufferBuilder`.
* The output of the stage (which defines vertex position in normalized device
coordinates) is the return value of the invocation.
* If you aren’t sure of a particular operation within the shader, try adding
intermediate variables to the shader. The Impeller shader compiler will
faithfully add those intermediate for ease of debugging. Optimizations that
hinder debuggability are reserved for optimized release modes and occur on the
intermediate representation.
### Live Shader Editing & Debugging
Often, it is useful to make minor edits to the shader to either visually see the
difference in the attachments or to see how local variables are affected.
When debugging an instrumentation of either the vertex or fragment shader, you
have the ability to edit the Metal source code. When you do, the `Reload Shader`
button at the bottom of the shader viewer that is typically disabled becomes
enabled.

Click on that button to see what that invocation would look like had it used the
updated shader. In the example above, I added an additional offset of 150 units
to the vertex position supplied to the vertex shader by the vertex buffer. When
I clicked on the `Reload Shaders` button, the location of the triangles in both
the color and stencil attachments was updated.
Unless you are only interested in inspecting local variables, it is often useful
to have the attachments viewer open side-by-side as you make live updates to the
shader.
No changes are being made to your GLSL shaders in Impeller. This is purely a
debugging aid and you must re-create those changes in GLSL to commit to those
updates.
# Finding Where API Calls Were Made in the Codebase
From either the frame insights or by selecting an API call on the object, open
the call-stack to navigate to the code that made that call. Then add your label.

When inspecting an API call, reveal the call-stack. This resource has already
been labelled and you’ll find the call in `AllocatorMTL::CreateTexture`.

This trace-first approach of navigating an unfamiliar codebase is unreasonably
effective.
# Next Steps & Further Reading
* Try repeating similar steps using a different profiler like RenderDoc or
Android GPU Inspector.
* [Watch] WWDC 2018: [Metal Shader Debugging &
Profiling](https://developer.apple.com/videos/play/wwdc2018/608/).
* [Watch] WWDC 2020: [Gain insights into your Metal app with
Xcode 12](https://developer.apple.com/videos/play/wwdc2020/10605).
* [Watch] WWDC 2020: [Optimize Metal apps and games with GPU
counters](https://developer.apple.com/videos/play/wwdc2020/10603).
| engine/impeller/docs/read_frame_captures.md/0 | {
"file_path": "engine/impeller/docs/read_frame_captures.md",
"repo_id": "engine",
"token_count": 6319
} | 188 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_CLIP_CONTENTS_H_
#define FLUTTER_IMPELLER_ENTITY_CONTENTS_CLIP_CONTENTS_H_
#include <functional>
#include <memory>
#include <vector>
#include "flutter/fml/macros.h"
#include "impeller/entity/contents/contents.h"
#include "impeller/entity/entity.h"
#include "impeller/entity/geometry/geometry.h"
namespace impeller {
class ClipContents final : public Contents {
public:
ClipContents();
~ClipContents();
void SetGeometry(const std::shared_ptr<Geometry>& geometry);
void SetClipOperation(Entity::ClipOperation clip_op);
// |Contents|
std::optional<Rect> GetCoverage(const Entity& entity) const override;
// |Contents|
ClipCoverage GetClipCoverage(
const Entity& entity,
const std::optional<Rect>& current_clip_coverage) const override;
// |Contents|
bool ShouldRender(const Entity& entity,
const std::optional<Rect> clip_coverage) const override;
// |Contents|
bool Render(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const override;
// |Contents|
bool CanInheritOpacity(const Entity& entity) const override;
// |Contents|
void SetInheritedOpacity(Scalar opacity) override;
private:
bool RenderDepthClip(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass,
Entity::ClipOperation clip_op,
const Geometry& geometry) const;
bool RenderStencilClip(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass,
Entity::ClipOperation clip_op,
const Geometry& geometry) const;
std::shared_ptr<Geometry> geometry_;
Entity::ClipOperation clip_op_ = Entity::ClipOperation::kIntersect;
ClipContents(const ClipContents&) = delete;
ClipContents& operator=(const ClipContents&) = delete;
};
class ClipRestoreContents final : public Contents {
public:
ClipRestoreContents();
~ClipRestoreContents();
/// @brief The area on the pass texture where this clip restore will be
/// applied. If unset, the entire pass texture will be restored.
///
/// @note This rectangle is not transformed by the entity's transform.
void SetRestoreCoverage(std::optional<Rect> coverage);
// |Contents|
std::optional<Rect> GetCoverage(const Entity& entity) const override;
// |Contents|
ClipCoverage GetClipCoverage(
const Entity& entity,
const std::optional<Rect>& current_clip_coverage) const override;
// |Contents|
bool ShouldRender(const Entity& entity,
const std::optional<Rect> clip_coverage) const override;
// |Contents|
bool Render(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const override;
// |Contents|
bool CanInheritOpacity(const Entity& entity) const override;
// |Contents|
void SetInheritedOpacity(Scalar opacity) override;
private:
std::optional<Rect> restore_coverage_;
ClipRestoreContents(const ClipRestoreContents&) = delete;
ClipRestoreContents& operator=(const ClipRestoreContents&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_CLIP_CONTENTS_H_
| engine/impeller/entity/contents/clip_contents.h/0 | {
"file_path": "engine/impeller/entity/contents/clip_contents.h",
"repo_id": "engine",
"token_count": 1273
} | 189 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/entity/contents/filters/color_matrix_filter_contents.h"
#include <optional>
#include "impeller/entity/contents/anonymous_contents.h"
#include "impeller/entity/contents/content_context.h"
#include "impeller/entity/contents/contents.h"
#include "impeller/entity/contents/filters/color_filter_contents.h"
#include "impeller/geometry/point.h"
#include "impeller/geometry/vector.h"
#include "impeller/renderer/render_pass.h"
#include "impeller/renderer/vertex_buffer_builder.h"
namespace impeller {
ColorMatrixFilterContents::ColorMatrixFilterContents() = default;
ColorMatrixFilterContents::~ColorMatrixFilterContents() = default;
void ColorMatrixFilterContents::SetMatrix(const ColorMatrix& matrix) {
matrix_ = matrix;
}
std::optional<Entity> ColorMatrixFilterContents::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 {
using VS = ColorMatrixColorFilterPipeline::VertexShader;
using FS = ColorMatrixColorFilterPipeline::FragmentShader;
//----------------------------------------------------------------------------
/// Handle inputs.
///
if (inputs.empty()) {
return std::nullopt;
}
auto input_snapshot = inputs[0]->GetSnapshot("ColorMatrix", renderer, entity);
if (!input_snapshot.has_value()) {
return std::nullopt;
}
//----------------------------------------------------------------------------
/// Create AnonymousContents for rendering.
///
RenderProc render_proc = [input_snapshot, color_matrix = matrix_,
absorb_opacity = GetAbsorbOpacity()](
const ContentContext& renderer,
const Entity& entity, RenderPass& pass) -> bool {
pass.SetCommandLabel("Color Matrix Filter");
pass.SetStencilReference(entity.GetClipDepth());
auto options = OptionsFromPassAndEntity(pass, entity);
options.primitive_type = PrimitiveType::kTriangleStrip;
pass.SetPipeline(renderer.GetColorMatrixColorFilterPipeline(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;
const float* matrix = color_matrix.array;
frag_info.color_v = Vector4(matrix[4], matrix[9], matrix[14], matrix[19]);
// clang-format off
frag_info.color_m = Matrix(
matrix[0], matrix[5], matrix[10], matrix[15],
matrix[1], matrix[6], matrix[11], matrix[16],
matrix[2], matrix[7], matrix[12], matrix[17],
matrix[3], matrix[8], matrix[13], matrix[18]
);
// clang-format on
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/color_matrix_filter_contents.cc/0 | {
"file_path": "engine/impeller/entity/contents/filters/color_matrix_filter_contents.cc",
"repo_id": "engine",
"token_count": 1628
} | 190 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/entity/contents/filters/inputs/texture_filter_input.h"
#include <utility>
#include "impeller/core/formats.h"
namespace impeller {
TextureFilterInput::TextureFilterInput(std::shared_ptr<Texture> texture,
Matrix local_transform)
: texture_(std::move(texture)), local_transform_(local_transform) {}
TextureFilterInput::~TextureFilterInput() = default;
FilterInput::Variant TextureFilterInput::GetInput() const {
return texture_;
}
std::optional<Snapshot> TextureFilterInput::GetSnapshot(
const std::string& label,
const ContentContext& renderer,
const Entity& entity,
std::optional<Rect> coverage_limit,
int32_t mip_count) const {
auto snapshot =
Snapshot{.texture = texture_, .transform = GetTransform(entity)};
if (texture_->GetMipCount() > 1) {
snapshot.sampler_descriptor.label = "TextureFilterInput Trilinear Sampler";
snapshot.sampler_descriptor.mip_filter = MipFilter::kLinear;
}
return snapshot;
}
std::optional<Rect> TextureFilterInput::GetCoverage(
const Entity& entity) const {
return Rect::MakeSize(texture_->GetSize())
.TransformBounds(GetTransform(entity));
}
Matrix TextureFilterInput::GetLocalTransform(const Entity& entity) const {
return local_transform_;
}
} // namespace impeller
| engine/impeller/entity/contents/filters/inputs/texture_filter_input.cc/0 | {
"file_path": "engine/impeller/entity/contents/filters/inputs/texture_filter_input.cc",
"repo_id": "engine",
"token_count": 503
} | 191 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include "impeller/entity/contents/gradient_generator.h"
#include "flutter/fml/logging.h"
#include "impeller/core/texture.h"
#include "impeller/entity/contents/content_context.h"
#include "impeller/renderer/context.h"
#include "impeller/renderer/render_pass.h"
namespace impeller {
std::shared_ptr<Texture> CreateGradientTexture(
const GradientData& gradient_data,
const std::shared_ptr<impeller::Context>& context) {
if (gradient_data.texture_size == 0) {
FML_DLOG(ERROR) << "Invalid gradient data.";
return nullptr;
}
impeller::TextureDescriptor texture_descriptor;
texture_descriptor.storage_mode = impeller::StorageMode::kHostVisible;
texture_descriptor.format = PixelFormat::kR8G8B8A8UNormInt;
texture_descriptor.size = {gradient_data.texture_size, 1};
auto texture =
context->GetResourceAllocator()->CreateTexture(texture_descriptor);
if (!texture) {
FML_DLOG(ERROR) << "Could not create Impeller texture.";
return nullptr;
}
auto mapping = std::make_shared<fml::DataMapping>(gradient_data.color_bytes);
if (!texture->SetContents(mapping)) {
FML_DLOG(ERROR) << "Could not copy contents into Impeller texture.";
return nullptr;
}
texture->SetLabel(impeller::SPrintF("Gradient(%p)", texture.get()).c_str());
return texture;
}
std::vector<StopData> CreateGradientColors(const std::vector<Color>& colors,
const std::vector<Scalar>& stops) {
FML_DCHECK(stops.size() == colors.size());
std::vector<StopData> result(stops.size());
for (auto i = 0u; i < stops.size(); i++) {
result[i] = {.color = colors[i], .stop = stops[i]};
}
return result;
}
} // namespace impeller
| engine/impeller/entity/contents/gradient_generator.cc/0 | {
"file_path": "engine/impeller/entity/contents/gradient_generator.cc",
"repo_id": "engine",
"token_count": 690
} | 192 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_SWEEP_GRADIENT_CONTENTS_H_
#define FLUTTER_IMPELLER_ENTITY_CONTENTS_SWEEP_GRADIENT_CONTENTS_H_
#include <functional>
#include <memory>
#include <vector>
#include "flutter/fml/macros.h"
#include "impeller/entity/contents/color_source_contents.h"
#include "impeller/entity/entity.h"
#include "impeller/geometry/color.h"
#include "impeller/geometry/gradient.h"
#include "impeller/geometry/path.h"
#include "impeller/geometry/point.h"
#include "impeller/geometry/scalar.h"
namespace impeller {
class SweepGradientContents final : public ColorSourceContents {
public:
SweepGradientContents();
~SweepGradientContents() override;
// |Contents|
bool IsOpaque() const override;
// |Contents|
bool Render(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const override;
// |Contents|
[[nodiscard]] bool ApplyColorFilter(
const ColorFilterProc& color_filter_proc) override;
void SetCenterAndAngles(Point center, Degrees start_angle, Degrees end_angle);
void SetColors(std::vector<Color> colors);
void SetStops(std::vector<Scalar> stops);
void SetTileMode(Entity::TileMode tile_mode);
const std::vector<Color>& GetColors() const;
const std::vector<Scalar>& GetStops() const;
private:
bool RenderTexture(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const;
bool RenderSSBO(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const;
Point center_;
Scalar bias_;
Scalar scale_;
std::vector<Color> colors_;
std::vector<Scalar> stops_;
Entity::TileMode tile_mode_;
Color decal_border_color_ = Color::BlackTransparent();
SweepGradientContents(const SweepGradientContents&) = delete;
SweepGradientContents& operator=(const SweepGradientContents&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_SWEEP_GRADIENT_CONTENTS_H_
| engine/impeller/entity/contents/sweep_gradient_contents.h/0 | {
"file_path": "engine/impeller/entity/contents/sweep_gradient_contents.h",
"repo_id": "engine",
"token_count": 796
} | 193 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_ENTITY_ENTITY_H_
#define FLUTTER_IMPELLER_ENTITY_ENTITY_H_
#include <cstdint>
#include "impeller/core/capture.h"
#include "impeller/entity/contents/contents.h"
#include "impeller/geometry/color.h"
#include "impeller/geometry/matrix.h"
#include "impeller/geometry/rect.h"
namespace impeller {
class Renderer;
class RenderPass;
class Entity {
public:
static constexpr BlendMode kLastPipelineBlendMode = BlendMode::kModulate;
static constexpr BlendMode kLastAdvancedBlendMode = BlendMode::kLuminosity;
enum class RenderingMode {
/// In direct mode, the Entity's transform is used as the current
/// local-to-screen transform matrix.
kDirect,
/// In subpass mode, the Entity passed through the filter is in screen space
/// rather than local space, and so some filters (namely,
/// MatrixFilterContents) need to interpret the given EffectTransform as the
/// current transform matrix.
kSubpass,
};
/// An enum to define how to repeat, fold, or omit colors outside of the
/// typically defined range of the source of the colors (such as the
/// bounds of an image or the defining geometry of a gradient).
enum class TileMode {
/// Replicate the edge color if the shader draws outside of its original
/// bounds.
kClamp,
/// Repeat the shader's image horizontally and vertically (or both along and
/// perpendicular to a gradient's geometry).
kRepeat,
/// Repeat the shader's image horizontally and vertically, seamlessly
/// alternating mirrored images.
kMirror,
/// Render the shader's image pixels only within its original bounds. If the
/// shader draws outside of its original bounds, transparent black is drawn
/// instead.
kDecal,
};
enum class ClipOperation {
kDifference,
kIntersect,
};
/// @brief Create an entity that can be used to render a given snapshot.
static Entity FromSnapshot(const Snapshot& snapshot,
BlendMode blend_mode = BlendMode::kSourceOver,
uint32_t clip_depth = 0);
Entity();
~Entity();
Entity(Entity&&);
/// @brief Get the global transform matrix for this Entity.
const Matrix& GetTransform() const;
/// @brief Set the global transform matrix for this Entity.
void SetTransform(const Matrix& transform);
std::optional<Rect> GetCoverage() const;
Contents::ClipCoverage GetClipCoverage(
const std::optional<Rect>& current_clip_coverage) const;
bool ShouldRender(const std::optional<Rect>& clip_coverage) const;
void SetContents(std::shared_ptr<Contents> contents);
const std::shared_ptr<Contents>& GetContents() const;
void SetClipDepth(uint32_t clip_depth);
void IncrementStencilDepth(uint32_t increment);
uint32_t GetClipDepth() const;
void SetNewClipDepth(uint32_t clip_depth);
uint32_t GetNewClipDepth() const;
float GetShaderClipDepth() const;
void SetBlendMode(BlendMode blend_mode);
BlendMode GetBlendMode() const;
bool Render(const ContentContext& renderer, RenderPass& parent_pass) const;
static bool IsBlendModeDestructive(BlendMode blend_mode);
bool CanInheritOpacity() const;
bool SetInheritedOpacity(Scalar alpha);
std::optional<Color> AsBackgroundColor(ISize target_size) const;
Scalar DeriveTextScale() const;
Capture& GetCapture() const;
void SetCapture(Capture capture) const;
Entity Clone() const;
private:
Entity(const Entity&);
Matrix transform_;
std::shared_ptr<Contents> contents_;
BlendMode blend_mode_ = BlendMode::kSourceOver;
uint32_t clip_depth_ = 0u;
uint32_t new_clip_depth_ = 1u;
mutable Capture capture_;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_ENTITY_ENTITY_H_
| engine/impeller/entity/entity.h/0 | {
"file_path": "engine/impeller/entity/entity.h",
"repo_id": "engine",
"token_count": 1250
} | 194 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/entity/geometry/vertices_geometry.h"
#include <cstdint>
#include <utility>
#include "impeller/core/buffer_view.h"
namespace impeller {
// Fan mode isn't natively supported. Unroll into triangle mode by
// manipulating the index array.
//
// In Triangle fan, the first vertex is shared across all triangles, and then
// each sliding window of two vertices plus that first vertex defines a
// triangle.
static std::vector<uint16_t> fromFanIndices(
const std::vector<Point>& vertices,
const std::vector<uint16_t>& indices) {
std::vector<uint16_t> unrolled_indices;
// Un-fan index buffer if provided.
if (indices.size() > 0u) {
if (indices.size() < 3u) {
return {};
}
auto center_point = indices[0];
for (auto i = 1u; i < indices.size() - 1; i++) {
unrolled_indices.push_back(center_point);
unrolled_indices.push_back(indices[i]);
unrolled_indices.push_back(indices[i + 1]);
}
} else {
if (vertices.size() < 3u) {
return {};
}
// If indices were not provided, create an index buffer that unfans
// triangles instead of re-writing points, colors, et cetera.
for (auto i = 1u; i < vertices.size() - 1; i++) {
unrolled_indices.push_back(0);
unrolled_indices.push_back(i);
unrolled_indices.push_back(i + 1);
}
}
return unrolled_indices;
}
/////// Vertices Geometry ///////
VerticesGeometry::VerticesGeometry(std::vector<Point> vertices,
std::vector<uint16_t> indices,
std::vector<Point> texture_coordinates,
std::vector<Color> colors,
Rect bounds,
VertexMode vertex_mode)
: vertices_(std::move(vertices)),
colors_(std::move(colors)),
texture_coordinates_(std::move(texture_coordinates)),
indices_(std::move(indices)),
bounds_(bounds),
vertex_mode_(vertex_mode) {
NormalizeIndices();
}
PrimitiveType VerticesGeometry::GetPrimitiveType() const {
switch (vertex_mode_) {
case VerticesGeometry::VertexMode::kTriangleFan:
// Unrolled into triangle mode.
return PrimitiveType::kTriangle;
case VerticesGeometry::VertexMode::kTriangleStrip:
return PrimitiveType::kTriangleStrip;
case VerticesGeometry::VertexMode::kTriangles:
return PrimitiveType::kTriangle;
}
}
void VerticesGeometry::NormalizeIndices() {
// Convert triangle fan if present.
if (vertex_mode_ == VerticesGeometry::VertexMode::kTriangleFan) {
indices_ = fromFanIndices(vertices_, indices_);
return;
}
}
bool VerticesGeometry::HasVertexColors() const {
return colors_.size() > 0;
}
bool VerticesGeometry::HasTextureCoordinates() const {
return texture_coordinates_.size() > 0;
}
std::optional<Rect> VerticesGeometry::GetTextureCoordinateCoverge() const {
if (!HasTextureCoordinates()) {
return std::nullopt;
}
auto vertex_count = vertices_.size();
if (vertex_count == 0) {
return std::nullopt;
}
return Rect::MakePointBounds(texture_coordinates_.begin(),
texture_coordinates_.end());
}
GeometryResult VerticesGeometry::GetPositionBuffer(
const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
auto index_count = indices_.size();
auto vertex_count = vertices_.size();
size_t total_vtx_bytes = vertex_count * sizeof(float) * 2;
size_t total_idx_bytes = index_count * sizeof(uint16_t);
auto vertex_buffer = renderer.GetTransientsBuffer().Emplace(
reinterpret_cast<const uint8_t*>(vertices_.data()), total_vtx_bytes,
alignof(float));
BufferView index_buffer = {};
if (index_count) {
index_buffer = renderer.GetTransientsBuffer().Emplace(
indices_.data(), total_idx_bytes, alignof(uint16_t));
}
return GeometryResult{
.type = GetPrimitiveType(),
.vertex_buffer =
{
.vertex_buffer = vertex_buffer,
.index_buffer = index_buffer,
.vertex_count = index_count > 0 ? index_count : vertex_count,
.index_type =
index_count > 0 ? IndexType::k16bit : IndexType::kNone,
},
.transform = pass.GetOrthographicTransform() * entity.GetTransform(),
};
}
GeometryResult VerticesGeometry::GetPositionColorBuffer(
const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) {
using VS = GeometryColorPipeline::VertexShader;
auto index_count = indices_.size();
auto vertex_count = vertices_.size();
size_t total_vtx_bytes = vertex_count * sizeof(VS::PerVertexData);
size_t total_idx_bytes = index_count * sizeof(uint16_t);
auto vertex_buffer = renderer.GetTransientsBuffer().Emplace(
total_vtx_bytes, alignof(VS::PerVertexData), [&](uint8_t* data) {
VS::PerVertexData* vtx_contents =
reinterpret_cast<VS::PerVertexData*>(data);
for (auto i = 0u; i < vertices_.size(); i++) {
VS::PerVertexData vertex_data = {
.position = vertices_[i],
.color = colors_[i],
};
std::memcpy(vtx_contents++, &vertex_data, sizeof(VS::PerVertexData));
}
});
BufferView index_buffer = {};
if (index_count > 0) {
index_buffer = renderer.GetTransientsBuffer().Emplace(
indices_.data(), total_idx_bytes, alignof(uint16_t));
}
return GeometryResult{
.type = GetPrimitiveType(),
.vertex_buffer =
{
.vertex_buffer = vertex_buffer,
.index_buffer = index_buffer,
.vertex_count = index_count > 0 ? index_count : vertex_count,
.index_type =
index_count > 0 ? IndexType::k16bit : IndexType::kNone,
},
.transform = pass.GetOrthographicTransform() * entity.GetTransform(),
};
}
GeometryResult VerticesGeometry::GetPositionUVBuffer(
Rect texture_coverage,
Matrix effect_transform,
const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
using VS = TexturePipeline::VertexShader;
auto index_count = indices_.size();
auto vertex_count = vertices_.size();
auto uv_transform =
texture_coverage.GetNormalizingTransform() * effect_transform;
auto has_texture_coordinates = HasTextureCoordinates();
size_t total_vtx_bytes = vertices_.size() * sizeof(VS::PerVertexData);
size_t total_idx_bytes = index_count * sizeof(uint16_t);
auto vertex_buffer = renderer.GetTransientsBuffer().Emplace(
total_vtx_bytes, alignof(VS::PerVertexData), [&](uint8_t* data) {
VS::PerVertexData* vtx_contents =
reinterpret_cast<VS::PerVertexData*>(data);
for (auto i = 0u; i < vertices_.size(); i++) {
auto vertex = vertices_[i];
auto texture_coord =
has_texture_coordinates ? texture_coordinates_[i] : vertices_[i];
auto uv = uv_transform * texture_coord;
// From experimentation we need to clamp these values to < 1.0 or else
// there can be flickering.
VS::PerVertexData vertex_data = {
.position = vertex,
.texture_coords =
Point(std::clamp(uv.x, 0.0f, 1.0f - kEhCloseEnough),
std::clamp(uv.y, 0.0f, 1.0f - kEhCloseEnough)),
};
std::memcpy(vtx_contents++, &vertex_data, sizeof(VS::PerVertexData));
}
});
BufferView index_buffer = {};
if (index_count > 0) {
index_buffer = renderer.GetTransientsBuffer().Emplace(
indices_.data(), total_idx_bytes, alignof(uint16_t));
}
return GeometryResult{
.type = GetPrimitiveType(),
.vertex_buffer =
{
.vertex_buffer = vertex_buffer,
.index_buffer = index_buffer,
.vertex_count = index_count > 0 ? index_count : vertex_count,
.index_type =
index_count > 0 ? IndexType::k16bit : IndexType::kNone,
},
.transform = pass.GetOrthographicTransform() * entity.GetTransform(),
};
}
GeometryVertexType VerticesGeometry::GetVertexType() const {
if (HasVertexColors()) {
return GeometryVertexType::kColor;
}
if (HasTextureCoordinates()) {
return GeometryVertexType::kUV;
}
return GeometryVertexType::kPosition;
}
std::optional<Rect> VerticesGeometry::GetCoverage(
const Matrix& transform) const {
return bounds_.TransformBounds(transform);
}
} // namespace impeller
| engine/impeller/entity/geometry/vertices_geometry.cc/0 | {
"file_path": "engine/impeller/entity/geometry/vertices_geometry.cc",
"repo_id": "engine",
"token_count": 3584
} | 195 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
precision mediump float;
#include <impeller/gaussian.glsl>
#include <impeller/texture.glsl>
#include <impeller/types.glsl>
// Constant time mask blur for image borders.
//
// This mask blur extends the geometry of the source image (with clamp border
// sampling) and applies a Gaussian blur to the alpha mask at the edges.
//
// The blur itself works by mapping the Gaussian distribution's indefinite
// integral (using an erf approximation) to the 4 edges of the UV rectangle and
// multiplying them.
uniform f16sampler2D texture_sampler;
uniform FragInfo {
float16_t src_factor;
float16_t inner_blur_factor;
float16_t outer_blur_factor;
float16_t alpha;
f16vec2 sigma_uv;
}
frag_info;
in highp vec2 v_texture_coords;
out f16vec4 frag_color;
float16_t BoxBlurMask(f16vec2 uv) {
// LTRB
return IPGaussianIntegral(uv.x, frag_info.sigma_uv.x) * //
IPGaussianIntegral(uv.y, frag_info.sigma_uv.y) * //
IPGaussianIntegral(1.0hf - uv.x, frag_info.sigma_uv.x) * //
IPGaussianIntegral(1.0hf - uv.y, frag_info.sigma_uv.y);
}
void main() {
f16vec4 image_color = texture(texture_sampler, v_texture_coords);
float16_t blur_factor = BoxBlurMask(f16vec2(v_texture_coords));
float16_t within_bounds =
float16_t(v_texture_coords.x >= 0.0 && v_texture_coords.y >= 0.0 &&
v_texture_coords.x < 1.0 && v_texture_coords.y < 1.0);
float16_t inner_factor =
(frag_info.inner_blur_factor * blur_factor + frag_info.src_factor) *
within_bounds;
float16_t outer_factor =
frag_info.outer_blur_factor * blur_factor * (1.0hf - within_bounds);
float16_t mask_factor = inner_factor + outer_factor;
frag_color = image_color * mask_factor;
}
| engine/impeller/entity/shaders/border_mask_blur.frag/0 | {
"file_path": "engine/impeller/entity/shaders/border_mask_blur.frag",
"repo_id": "engine",
"token_count": 744
} | 196 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
precision highp float;
#include <impeller/gaussian.glsl>
#include <impeller/types.glsl>
uniform FragInfo {
f16vec4 color;
vec2 rect_size;
float blur_sigma;
vec2 corner_radii;
}
frag_info;
in vec2 v_position;
out f16vec4 frag_color;
const int kSampleCount = 4;
/// Closed form unidirectional rounded rect blur mask solution using the
/// analytical Gaussian integral (with approximated erf).
float RRectBlurX(vec2 sample_position, vec2 half_size) {
// The vertical edge of the rrect consists of a flat portion and a curved
// portion, the two of which vary in size depending on the size of the
// corner radii, both adding up to half_size.y.
// half_size.y - corner_radii.y is the size of the vertical flat
// portion of the rrect.
// subtracting the absolute value of the Y sample_position will be
// negative (and then clamped to 0) for positions that are located
// vertically in the flat part of the rrect, and will be the relative
// distance from the center of curvature otherwise.
float space_y =
min(0.0, half_size.y - frag_info.corner_radii.y - abs(sample_position.y));
// space is now in the range [0.0, corner_radii.y]. If the y sample was
// in the flat portion of the rrect, it will be 0.0
// We will now calculate rrect_distance as the distance from the centerline
// of the rrect towards the near side of the rrect.
// half_size.x - frag_info.corner_radii.x is the size of the horizontal
// flat portion of the rrect.
// We add to that the X size (space_x) of the curved corner measured at
// the indicated Y coordinate we calculated as space_y, such that:
// (space_y / corner_radii.y)^2 + (space_x / corner_radii.x)^2 == 1.0
// Since we want the space_x, we rearrange the equation as:
// space_x = corner_radii.x * sqrt(1.0 - (space_y / corner_radii.y)^2)
// We need to prevent negative values inside the sqrt which can occur
// when the Y sample was beyond the vertical size of the rrect and thus
// space_y was larger than corner_radii.y.
// The calling function RRectBlur will never provide a Y sample outside
// of that range, though, so the max(0.0) is mostly a precaution.
float unit_space_y = space_y / frag_info.corner_radii.y;
float unit_space_x = sqrt(max(0.0, 1.0 - unit_space_y * unit_space_y));
float rrect_distance =
half_size.x - frag_info.corner_radii.x * (1.0 - unit_space_x);
// Now we integrate the Gaussian over the range of the relative positions
// of the left and right sides of the rrect relative to the sampling
// X coordinate.
vec2 integral = IPVec2FastGaussianIntegral(
float(sample_position.x) + vec2(-rrect_distance, rrect_distance),
float(frag_info.blur_sigma));
// integral.y contains the evaluation of the indefinite gaussian integral
// function at (X + rrect_distance) and integral.x contains the evaluation
// of it at (X - rrect_distance). Subtracting the two produces the
// integral result over the range from one to the other.
return integral.y - integral.x;
}
float RRectBlur(vec2 sample_position, vec2 half_size) {
// Limit the sampling range to 3 standard deviations in the Y direction from
// the kernel center to incorporate 99.7% of the color contribution.
float half_sampling_range = frag_info.blur_sigma * 3.0;
// We want to cover the range [Y - half_range, Y + half_range], but we
// don't want to sample beyond the edge of the rrect (where the RRectBlurX
// function produces bad information and where the real answer at those
// locations will be 0.0 anyway).
float begin_y = max(-half_sampling_range, sample_position.y - half_size.y);
float end_y = min(half_sampling_range, sample_position.y + half_size.y);
float interval = (end_y - begin_y) / kSampleCount;
// Sample the X blur kSampleCount times, weighted by the Gaussian function.
float result = 0.0;
for (int sample_i = 0; sample_i < kSampleCount; sample_i++) {
float y = begin_y + interval * (float(sample_i) + 0.5);
result +=
RRectBlurX(vec2(sample_position.x, sample_position.y - y), half_size) *
IPGaussian(float(y), float(frag_info.blur_sigma)) * interval;
}
return result;
}
void main() {
frag_color = frag_info.color;
vec2 half_size = frag_info.rect_size * 0.5;
vec2 sample_position = v_position - half_size;
frag_color *= float16_t(RRectBlur(sample_position, half_size));
}
| engine/impeller/entity/shaders/rrect_blur.frag/0 | {
"file_path": "engine/impeller/entity/shaders/rrect_blur.frag",
"repo_id": "engine",
"token_count": 1487
} | 197 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
precision mediump float;
#include <impeller/color.glsl>
#include <impeller/texture.glsl>
#include <impeller/types.glsl>
uniform f16sampler2D y_texture;
uniform f16sampler2D uv_texture;
// These values must correspond to the order of the items in the
// 'YUVColorSpace' enum class.
const float16_t kBT601LimitedRange = 0.0hf;
const float16_t kBT601FullRange = 1.0hf;
uniform FragInfo {
mat4 matrix;
float16_t yuv_color_space;
}
frag_info;
in highp vec2 v_texture_coords;
out f16vec4 frag_color;
void main() {
f16vec3 yuv;
f16vec3 yuv_offset = f16vec3(0.0hf, 0.5hf, 0.5hf);
if (frag_info.yuv_color_space == kBT601LimitedRange) {
yuv_offset.x = 16.0hf / 255.0hf;
}
yuv.x = texture(y_texture, v_texture_coords).r;
yuv.yz = texture(uv_texture, v_texture_coords).rg;
frag_color = f16mat4(frag_info.matrix) * f16vec4(yuv - yuv_offset, 1.0hf);
}
| engine/impeller/entity/shaders/yuv_to_rgb_filter.frag/0 | {
"file_path": "engine/impeller/entity/shaders/yuv_to_rgb_filter.frag",
"repo_id": "engine",
"token_count": 421
} | 198 |
// Copyright 2013 The Flutter 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 'dart:ui' as ui;
import '../../lib/gpu/lib/gpu.dart' as gpu;
void main() {}
@pragma('vm:entry-point')
void sayHi() {
print('Hi');
}
@pragma('vm:entry-point')
void instantiateDefaultContext() {
// ignore: unused_local_variable
final gpu.GpuContext context = gpu.gpuContext;
}
@pragma('vm:entry-point')
void canCreateShaderLibrary() {
final gpu.ShaderLibrary? library = gpu.ShaderLibrary.fromAsset('playground');
assert(library != null);
final gpu.Shader? shader = library!['UnlitVertex'];
assert(shader != null);
}
@pragma('vm:entry-point')
void canReflectUniformStructs() {
final gpu.RenderPipeline pipeline = createUnlitRenderPipeline();
final gpu.UniformSlot vertInfo =
pipeline.vertexShader.getUniformSlot('VertInfo');
assert(vertInfo.uniformName == 'VertInfo');
final int? totalSize = vertInfo.sizeInBytes;
assert(totalSize != null);
assert(totalSize! == 128);
final int? mvpOffset = vertInfo.getMemberOffsetInBytes('mvp');
assert(mvpOffset != null);
assert(mvpOffset! == 0);
final int? colorOffset = vertInfo.getMemberOffsetInBytes('color');
assert(colorOffset != null);
assert(colorOffset! == 64);
}
gpu.RenderPipeline createUnlitRenderPipeline() {
final gpu.ShaderLibrary? library = gpu.ShaderLibrary.fromAsset('playground');
assert(library != null);
final gpu.Shader? vertex = library!['UnlitVertex'];
assert(vertex != null);
final gpu.Shader? fragment = library['UnlitFragment'];
assert(fragment != null);
return gpu.gpuContext.createRenderPipeline(vertex!, fragment!);
}
gpu.RenderPass createRenderPass() {
final gpu.Texture? renderTexture =
gpu.gpuContext.createTexture(gpu.StorageMode.devicePrivate, 100, 100);
assert(renderTexture != null);
final gpu.CommandBuffer commandBuffer = gpu.gpuContext.createCommandBuffer();
final gpu.RenderTarget renderTarget = gpu.RenderTarget.singleColor(
gpu.ColorAttachment(texture: renderTexture!),
);
return commandBuffer.createRenderPass(renderTarget);
}
@pragma('vm:entry-point')
void uniformBindFailsForInvalidHostBufferOffset() {
final gpu.RenderPass encoder = createRenderPass();
final gpu.RenderPipeline pipeline = createUnlitRenderPipeline();
encoder.bindPipeline(pipeline);
final gpu.HostBuffer transients = gpu.gpuContext.createHostBuffer();
final gpu.BufferView vertInfoData = transients.emplace(float32(<double>[
1, 0, 0, 0, // mvp
0, 1, 0, 0, // mvp
0, 0, 1, 0, // mvp
0, 0, 0, 1, // mvp
0, 1, 0, 1, // color
]));
final gpu.BufferView viewWithBadOffset = gpu.BufferView(vertInfoData.buffer,
offsetInBytes: 1, lengthInBytes: vertInfoData.lengthInBytes);
final gpu.UniformSlot vertInfo =
pipeline.vertexShader.getUniformSlot('VertInfo');
String? exception;
try {
encoder.bindUniform(vertInfo, viewWithBadOffset);
} catch (e) {
exception = e.toString();
}
assert(exception!.contains('Failed to bind uniform'));
}
ByteData float32(List<double> values) {
return Float32List.fromList(values).buffer.asByteData();
}
@pragma('vm:entry-point')
void canCreateRenderPassAndSubmit() {
final gpu.Texture? renderTexture =
gpu.gpuContext.createTexture(gpu.StorageMode.devicePrivate, 100, 100);
assert(renderTexture != null);
final gpu.CommandBuffer commandBuffer = gpu.gpuContext.createCommandBuffer();
final gpu.RenderTarget renderTarget = gpu.RenderTarget.singleColor(
gpu.ColorAttachment(texture: renderTexture!),
);
final gpu.RenderPass encoder = commandBuffer.createRenderPass(renderTarget);
final gpu.RenderPipeline pipeline = createUnlitRenderPipeline();
encoder.bindPipeline(pipeline);
// Configure blending with defaults (just to test the bindings).
encoder.setColorBlendEnable(true);
encoder.setColorBlendEquation(gpu.ColorBlendEquation());
final gpu.HostBuffer transients = gpu.gpuContext.createHostBuffer();
final gpu.BufferView vertices = transients.emplace(float32(<double>[
-0.5, -0.5, //
0.5, 0.5, //
0.5, -0.5, //
]));
final gpu.BufferView vertInfoData = transients.emplace(float32(<double>[
1, 0, 0, 0, // mvp
0, 1, 0, 0, // mvp
0, 0, 1, 0, // mvp
0, 0, 0, 1, // mvp
0, 1, 0, 1, // color
]));
encoder.bindVertexBuffer(vertices, 3);
final gpu.UniformSlot vertInfo =
pipeline.vertexShader.getUniformSlot('VertInfo');
encoder.bindUniform(vertInfo, vertInfoData);
encoder.draw();
commandBuffer.submit();
}
| engine/impeller/fixtures/dart_tests.dart/0 | {
"file_path": "engine/impeller/fixtures/dart_tests.dart",
"repo_id": "engine",
"token_count": 1615
} | 199 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifdef IMPELLER_TARGET_OPENGLES
void main() {
// Instancing is not supported on legacy targets and test will be disabled.
}
#else // IMPELLER_TARGET_OPENGLES
uniform FrameInfo {
mat4 mvp;
}
frame_info;
readonly buffer InstanceInfo {
vec4 colors[];
}
instance_info;
in vec2 vtx;
out vec4 v_color;
void main() {
gl_Position =
frame_info.mvp * vec4(vtx.x + 105.0 * gl_InstanceIndex,
vtx.y + 105.0 * gl_InstanceIndex, 0.0, 1.0);
v_color = instance_info.colors[gl_InstanceIndex];
}
#endif // IMPELLER_TARGET_OPENGLES
| engine/impeller/fixtures/instanced_draw.vert/0 | {
"file_path": "engine/impeller/fixtures/instanced_draw.vert",
"repo_id": "engine",
"token_count": 289
} | 200 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_GEOMETRY_GRADIENT_H_
#define FLUTTER_IMPELLER_GEOMETRY_GRADIENT_H_
#include <cstdint>
#include <memory>
#include <vector>
#include "impeller/geometry/color.h"
#include "impeller/geometry/path.h"
#include "impeller/geometry/point.h"
namespace impeller {
// If texture_size is 0 then the gradient is invalid.
struct GradientData {
std::vector<uint8_t> color_bytes;
uint32_t texture_size;
};
/**
* @brief Populate a vector with the interpolated color bytes for the linear
* gradient described by colors and stops.
*
* @param colors
* @param stops
* @return GradientData
*/
GradientData CreateGradientBuffer(const std::vector<Color>& colors,
const std::vector<Scalar>& stops);
} // namespace impeller
#endif // FLUTTER_IMPELLER_GEOMETRY_GRADIENT_H_
| engine/impeller/geometry/gradient.h/0 | {
"file_path": "engine/impeller/geometry/gradient.h",
"repo_id": "engine",
"token_count": 362
} | 201 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "quaternion.h"
#include <sstream>
namespace impeller {
Quaternion Quaternion::Slerp(const Quaternion& to, double time) const {
double cosine = Dot(to);
if (fabs(cosine) < 1.0 - 1e-3 /* epsilon */) {
/*
* Spherical Interpolation.
*/
auto sine = sqrt(1.0 - cosine * cosine);
auto angle = atan2(sine, cosine);
auto sineInverse = 1.0 / sine;
auto c0 = sin((1.0 - time) * angle) * sineInverse;
auto c1 = sin(time * angle) * sineInverse;
return *this * c0 + to * c1;
} else {
/*
* Linear Interpolation.
*/
return (*this * (1.0 - time) + to * time).Normalize();
}
}
} // namespace impeller
| engine/impeller/geometry/quaternion.cc/0 | {
"file_path": "engine/impeller/geometry/quaternion.cc",
"repo_id": "engine",
"token_count": 331
} | 202 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_GEOMETRY_TRIG_H_
#define FLUTTER_IMPELLER_GEOMETRY_TRIG_H_
#include <functional>
#include <vector>
#include "flutter/impeller/geometry/point.h"
namespace impeller {
/// @brief A structure to store the sine and cosine of an angle.
struct Trig {
/// Construct a Trig object from a given angle in radians.
explicit Trig(Radians r)
: cos(std::cos(r.radians)), sin(std::sin(r.radians)) {}
/// Construct a Trig object from the given cosine and sine values.
Trig(double cos, double sin) : cos(cos), sin(sin) {}
double cos;
double sin;
/// @brief Returns the corresponding point on a circle of a given |radius|.
Vector2 operator*(double radius) const {
return Vector2(static_cast<Scalar>(cos * radius),
static_cast<Scalar>(sin * radius));
}
/// @brief Returns the corresponding point on an ellipse with the given size.
Vector2 operator*(const Size& ellipse_radii) const {
return Vector2(static_cast<Scalar>(cos * ellipse_radii.width),
static_cast<Scalar>(sin * ellipse_radii.height));
}
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_GEOMETRY_TRIG_H_
| engine/impeller/geometry/trig.h/0 | {
"file_path": "engine/impeller/geometry/trig.h",
"repo_id": "engine",
"token_count": 488
} | 203 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/golden_tests/metal_screenshot.h"
namespace impeller {
namespace testing {
MetalScreenshot::MetalScreenshot(CGImageRef cgImage) : cg_image_(cgImage) {
CGDataProviderRef data_provider = CGImageGetDataProvider(cgImage);
pixel_data_ = CGDataProviderCopyData(data_provider);
}
MetalScreenshot::~MetalScreenshot() {
CFRelease(pixel_data_);
CGImageRelease(cg_image_);
}
const uint8_t* MetalScreenshot::GetBytes() const {
return CFDataGetBytePtr(pixel_data_);
}
size_t MetalScreenshot::GetHeight() const {
return CGImageGetHeight(cg_image_);
}
size_t MetalScreenshot::GetWidth() const {
return CGImageGetWidth(cg_image_);
}
size_t MetalScreenshot::GetBytesPerRow() const {
return CGImageGetBytesPerRow(cg_image_);
}
bool MetalScreenshot::WriteToPNG(const std::string& path) const {
bool result = false;
NSURL* output_url =
[NSURL fileURLWithPath:[NSString stringWithUTF8String:path.c_str()]];
CGImageDestinationRef destination = CGImageDestinationCreateWithURL(
(__bridge CFURLRef)output_url, kUTTypePNG, 1, nullptr);
if (destination != nullptr) {
CGImageDestinationAddImage(destination, cg_image_,
(__bridge CFDictionaryRef) @{});
if (CGImageDestinationFinalize(destination)) {
result = true;
}
CFRelease(destination);
}
return result;
}
} // namespace testing
} // namespace impeller
| engine/impeller/golden_tests/metal_screenshot.mm/0 | {
"file_path": "engine/impeller/golden_tests/metal_screenshot.mm",
"repo_id": "engine",
"token_count": 548
} | 204 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_PLAYGROUND_BACKEND_VULKAN_PLAYGROUND_IMPL_VK_H_
#define FLUTTER_IMPELLER_PLAYGROUND_BACKEND_VULKAN_PLAYGROUND_IMPL_VK_H_
#include "impeller/playground/playground_impl.h"
#include "impeller/renderer/backend/vulkan/vk.h"
namespace impeller {
class PlaygroundImplVK final : public PlaygroundImpl {
public:
static bool IsVulkanDriverPresent();
explicit PlaygroundImplVK(PlaygroundSwitches switches);
~PlaygroundImplVK();
fml::Status SetCapabilities(
const std::shared_ptr<Capabilities>& capabilities) override;
private:
std::shared_ptr<Context> context_;
// Windows management.
static void DestroyWindowHandle(WindowHandle handle);
using UniqueHandle = std::unique_ptr<void, decltype(&DestroyWindowHandle)>;
UniqueHandle handle_;
ISize size_ = {1, 1};
// A global Vulkan instance which ensures that the Vulkan library will remain
// loaded throughout the lifetime of the process.
static vk::UniqueInstance global_instance_;
// |PlaygroundImpl|
std::shared_ptr<Context> GetContext() const override;
// |PlaygroundImpl|
WindowHandle GetWindowHandle() const override;
// |PlaygroundImpl|
std::unique_ptr<Surface> AcquireSurfaceFrame(
std::shared_ptr<Context> context) override;
PlaygroundImplVK(const PlaygroundImplVK&) = delete;
PlaygroundImplVK& operator=(const PlaygroundImplVK&) = delete;
static void InitGlobalVulkanInstance();
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_PLAYGROUND_BACKEND_VULKAN_PLAYGROUND_IMPL_VK_H_
| engine/impeller/playground/backend/vulkan/playground_impl_vk.h/0 | {
"file_path": "engine/impeller/playground/backend/vulkan/playground_impl_vk.h",
"repo_id": "engine",
"token_count": 531
} | 205 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
in vec2 frag_texture_coordinates;
in vec4 frag_vertex_color;
out vec4 frag_color;
uniform sampler2D tex;
void main() {
frag_color = frag_vertex_color * texture(tex, frag_texture_coordinates.st);
}
| engine/impeller/playground/imgui/imgui_raster.frag/0 | {
"file_path": "engine/impeller/playground/imgui/imgui_raster.frag",
"repo_id": "engine",
"token_count": 117
} | 206 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_ALLOCATOR_GLES_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_ALLOCATOR_GLES_H_
#include "flutter/fml/macros.h"
#include "impeller/core/allocator.h"
#include "impeller/renderer/backend/gles/reactor_gles.h"
namespace impeller {
class AllocatorGLES final : public Allocator {
public:
// |Allocator|
~AllocatorGLES() override;
private:
friend class ContextGLES;
ReactorGLES::Ref reactor_;
bool is_valid_ = false;
explicit AllocatorGLES(ReactorGLES::Ref reactor);
// |Allocator|
bool IsValid() const;
// |Allocator|
std::shared_ptr<DeviceBuffer> OnCreateBuffer(
const DeviceBufferDescriptor& desc) override;
// |Allocator|
std::shared_ptr<Texture> OnCreateTexture(
const TextureDescriptor& desc) override;
// |Allocator|
ISize GetMaxTextureSizeSupported() const override;
AllocatorGLES(const AllocatorGLES&) = delete;
AllocatorGLES& operator=(const AllocatorGLES&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_ALLOCATOR_GLES_H_
| engine/impeller/renderer/backend/gles/allocator_gles.h/0 | {
"file_path": "engine/impeller/renderer/backend/gles/allocator_gles.h",
"repo_id": "engine",
"token_count": 456
} | 207 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_DEVICE_BUFFER_GLES_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_DEVICE_BUFFER_GLES_H_
#include <cstdint>
#include <memory>
#include "impeller/base/allocation.h"
#include "impeller/base/backend_cast.h"
#include "impeller/core/device_buffer.h"
#include "impeller/renderer/backend/gles/reactor_gles.h"
namespace impeller {
class DeviceBufferGLES final
: public DeviceBuffer,
public BackendCast<DeviceBufferGLES, DeviceBuffer> {
public:
DeviceBufferGLES(DeviceBufferDescriptor desc,
ReactorGLES::Ref reactor,
std::shared_ptr<Allocation> backing_store);
// |DeviceBuffer|
~DeviceBufferGLES() override;
const uint8_t* GetBufferData() const;
void UpdateBufferData(
const std::function<void(uint8_t*, size_t length)>& update_buffer_data);
enum class BindingType {
kArrayBuffer,
kElementArrayBuffer,
};
[[nodiscard]] bool BindAndUploadDataIfNecessary(BindingType type) const;
void Flush(std::optional<Range> range = std::nullopt) const override;
private:
ReactorGLES::Ref reactor_;
HandleGLES handle_;
mutable std::shared_ptr<Allocation> backing_store_;
mutable uint32_t generation_ = 0;
mutable uint32_t upload_generation_ = 0;
// |DeviceBuffer|
uint8_t* OnGetContents() const override;
// |DeviceBuffer|
bool OnCopyHostBuffer(const uint8_t* source,
Range source_range,
size_t offset) override;
// |DeviceBuffer|
bool SetLabel(const std::string& label) override;
// |DeviceBuffer|
bool SetLabel(const std::string& label, Range range) override;
DeviceBufferGLES(const DeviceBufferGLES&) = delete;
DeviceBufferGLES& operator=(const DeviceBufferGLES&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_DEVICE_BUFFER_GLES_H_
| engine/impeller/renderer/backend/gles/device_buffer_gles.h/0 | {
"file_path": "engine/impeller/renderer/backend/gles/device_buffer_gles.h",
"repo_id": "engine",
"token_count": 767
} | 208 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/gles/render_pass_gles.h"
#include <cstdint>
#include "GLES3/gl3.h"
#include "flutter/fml/trace_event.h"
#include "fml/closure.h"
#include "fml/logging.h"
#include "impeller/base/validation.h"
#include "impeller/renderer/backend/gles/context_gles.h"
#include "impeller/renderer/backend/gles/device_buffer_gles.h"
#include "impeller/renderer/backend/gles/formats_gles.h"
#include "impeller/renderer/backend/gles/gpu_tracer_gles.h"
#include "impeller/renderer/backend/gles/pipeline_gles.h"
#include "impeller/renderer/backend/gles/texture_gles.h"
namespace impeller {
RenderPassGLES::RenderPassGLES(std::shared_ptr<const Context> context,
const RenderTarget& target,
ReactorGLES::Ref reactor)
: RenderPass(std::move(context), target),
reactor_(std::move(reactor)),
is_valid_(reactor_ && reactor_->IsValid()) {}
// |RenderPass|
RenderPassGLES::~RenderPassGLES() = default;
// |RenderPass|
bool RenderPassGLES::IsValid() const {
return is_valid_;
}
// |RenderPass|
void RenderPassGLES::OnSetLabel(std::string label) {
label_ = std::move(label);
}
void ConfigureBlending(const ProcTableGLES& gl,
const ColorAttachmentDescriptor* color) {
if (color->blending_enabled) {
gl.Enable(GL_BLEND);
gl.BlendFuncSeparate(
ToBlendFactor(color->src_color_blend_factor), // src color
ToBlendFactor(color->dst_color_blend_factor), // dst color
ToBlendFactor(color->src_alpha_blend_factor), // src alpha
ToBlendFactor(color->dst_alpha_blend_factor) // dst alpha
);
gl.BlendEquationSeparate(
ToBlendOperation(color->color_blend_op), // mode color
ToBlendOperation(color->alpha_blend_op) // mode alpha
);
} else {
gl.Disable(GL_BLEND);
}
{
const auto is_set = [](ColorWriteMask mask,
ColorWriteMask check) -> GLboolean {
return (mask & check) ? GL_TRUE : GL_FALSE;
};
gl.ColorMask(
is_set(color->write_mask, ColorWriteMaskBits::kRed), // red
is_set(color->write_mask, ColorWriteMaskBits::kGreen), // green
is_set(color->write_mask, ColorWriteMaskBits::kBlue), // blue
is_set(color->write_mask, ColorWriteMaskBits::kAlpha) // alpha
);
}
}
void ConfigureStencil(GLenum face,
const ProcTableGLES& gl,
const StencilAttachmentDescriptor& stencil,
uint32_t stencil_reference) {
gl.StencilOpSeparate(
face, // face
ToStencilOp(stencil.stencil_failure), // stencil fail
ToStencilOp(stencil.depth_failure), // depth fail
ToStencilOp(stencil.depth_stencil_pass) // depth stencil pass
);
gl.StencilFuncSeparate(face, // face
ToCompareFunction(stencil.stencil_compare), // func
stencil_reference, // ref
stencil.read_mask // mask
);
gl.StencilMaskSeparate(face, stencil.write_mask);
}
void ConfigureStencil(const ProcTableGLES& gl,
const PipelineDescriptor& pipeline,
uint32_t stencil_reference) {
if (!pipeline.HasStencilAttachmentDescriptors()) {
gl.Disable(GL_STENCIL_TEST);
return;
}
gl.Enable(GL_STENCIL_TEST);
const auto& front = pipeline.GetFrontStencilAttachmentDescriptor();
const auto& back = pipeline.GetBackStencilAttachmentDescriptor();
if (front.has_value() && back.has_value() && front == back) {
ConfigureStencil(GL_FRONT_AND_BACK, gl, *front, stencil_reference);
return;
}
if (front.has_value()) {
ConfigureStencil(GL_FRONT, gl, *front, stencil_reference);
}
if (back.has_value()) {
ConfigureStencil(GL_BACK, gl, *back, stencil_reference);
}
}
//------------------------------------------------------------------------------
/// @brief Encapsulates data that will be needed in the reactor for the
/// encoding of commands for this render pass.
///
struct RenderPassData {
Viewport viewport;
Color clear_color;
uint32_t clear_stencil = 0u;
Scalar clear_depth = 1.0;
std::shared_ptr<Texture> color_attachment;
std::shared_ptr<Texture> depth_attachment;
std::shared_ptr<Texture> stencil_attachment;
bool clear_color_attachment = true;
bool clear_depth_attachment = true;
bool clear_stencil_attachment = true;
bool discard_color_attachment = true;
bool discard_depth_attachment = true;
bool discard_stencil_attachment = true;
std::string label;
};
[[nodiscard]] bool EncodeCommandsInReactor(
const RenderPassData& pass_data,
const std::shared_ptr<Allocator>& transients_allocator,
const ReactorGLES& reactor,
const std::vector<Command>& commands,
const std::shared_ptr<GPUTracerGLES>& tracer) {
TRACE_EVENT0("impeller", "RenderPassGLES::EncodeCommandsInReactor");
const auto& gl = reactor.GetProcTable();
#ifdef IMPELLER_DEBUG
tracer->MarkFrameStart(gl);
#endif // IMPELLER_DEBUG
fml::ScopedCleanupClosure pop_pass_debug_marker(
[&gl]() { gl.PopDebugGroup(); });
if (!pass_data.label.empty()) {
gl.PushDebugGroup(pass_data.label);
} else {
pop_pass_debug_marker.Release();
}
GLuint fbo = GL_NONE;
fml::ScopedCleanupClosure delete_fbo([&gl, &fbo]() {
if (fbo != GL_NONE) {
gl.BindFramebuffer(GL_FRAMEBUFFER, GL_NONE);
gl.DeleteFramebuffers(1u, &fbo);
}
});
const auto is_default_fbo =
TextureGLES::Cast(*pass_data.color_attachment).IsWrapped();
if (!is_default_fbo) {
// Create and bind an offscreen FBO.
gl.GenFramebuffers(1u, &fbo);
gl.BindFramebuffer(GL_FRAMEBUFFER, fbo);
if (auto color = TextureGLES::Cast(pass_data.color_attachment.get())) {
if (!color->SetAsFramebufferAttachment(
GL_FRAMEBUFFER, TextureGLES::AttachmentType::kColor0)) {
return false;
}
}
if (auto depth = TextureGLES::Cast(pass_data.depth_attachment.get())) {
if (!depth->SetAsFramebufferAttachment(
GL_FRAMEBUFFER, TextureGLES::AttachmentType::kDepth)) {
return false;
}
}
if (auto stencil = TextureGLES::Cast(pass_data.stencil_attachment.get())) {
if (!stencil->SetAsFramebufferAttachment(
GL_FRAMEBUFFER, TextureGLES::AttachmentType::kStencil)) {
return false;
}
}
auto status = gl.CheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
VALIDATION_LOG << "Could not create a complete frambuffer: "
<< DebugToFramebufferError(status);
return false;
}
}
gl.ClearColor(pass_data.clear_color.red, // red
pass_data.clear_color.green, // green
pass_data.clear_color.blue, // blue
pass_data.clear_color.alpha // alpha
);
if (pass_data.depth_attachment) {
if (gl.DepthRangef.IsAvailable()) {
gl.ClearDepthf(pass_data.clear_depth);
} else {
gl.ClearDepth(pass_data.clear_depth);
}
}
if (pass_data.stencil_attachment) {
gl.ClearStencil(pass_data.clear_stencil);
}
GLenum clear_bits = 0u;
if (pass_data.clear_color_attachment) {
clear_bits |= GL_COLOR_BUFFER_BIT;
}
if (pass_data.clear_depth_attachment) {
clear_bits |= GL_DEPTH_BUFFER_BIT;
}
if (pass_data.clear_stencil_attachment) {
clear_bits |= GL_STENCIL_BUFFER_BIT;
}
gl.Disable(GL_SCISSOR_TEST);
gl.Disable(GL_DEPTH_TEST);
gl.Disable(GL_STENCIL_TEST);
gl.Disable(GL_CULL_FACE);
gl.Disable(GL_BLEND);
gl.ColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
gl.DepthMask(GL_TRUE);
gl.StencilMaskSeparate(GL_FRONT, 0xFFFFFFFF);
gl.StencilMaskSeparate(GL_BACK, 0xFFFFFFFF);
gl.Clear(clear_bits);
for (const auto& command : commands) {
if (command.instance_count != 1u) {
VALIDATION_LOG << "GLES backend does not support instanced rendering.";
return false;
}
if (!command.pipeline) {
VALIDATION_LOG << "Command has no pipeline specified.";
return false;
}
#ifdef IMPELLER_DEBUG
fml::ScopedCleanupClosure pop_cmd_debug_marker(
[&gl]() { gl.PopDebugGroup(); });
if (!command.label.empty()) {
gl.PushDebugGroup(command.label);
} else {
pop_cmd_debug_marker.Release();
}
#endif // IMPELLER_DEBUG
const auto& pipeline = PipelineGLES::Cast(*command.pipeline);
const auto* color_attachment =
pipeline.GetDescriptor().GetLegacyCompatibleColorAttachment();
if (!color_attachment) {
VALIDATION_LOG
<< "Color attachment is too complicated for a legacy renderer.";
return false;
}
//--------------------------------------------------------------------------
/// Configure blending.
///
ConfigureBlending(gl, color_attachment);
//--------------------------------------------------------------------------
/// Setup stencil.
///
ConfigureStencil(gl, pipeline.GetDescriptor(), command.stencil_reference);
//--------------------------------------------------------------------------
/// Configure depth.
///
if (auto depth =
pipeline.GetDescriptor().GetDepthStencilAttachmentDescriptor();
depth.has_value()) {
gl.Enable(GL_DEPTH_TEST);
gl.DepthFunc(ToCompareFunction(depth->depth_compare));
gl.DepthMask(depth->depth_write_enabled ? GL_TRUE : GL_FALSE);
} else {
gl.Disable(GL_DEPTH_TEST);
}
// Both the viewport and scissor are specified in framebuffer coordinates.
// Impeller's framebuffer coordinate system is top left origin, but OpenGL's
// is bottom left origin, so we convert the coordinates here.
auto target_size = pass_data.color_attachment->GetSize();
//--------------------------------------------------------------------------
/// Setup the viewport.
///
const auto& viewport = command.viewport.value_or(pass_data.viewport);
gl.Viewport(viewport.rect.GetX(), // x
target_size.height - viewport.rect.GetY() -
viewport.rect.GetHeight(), // y
viewport.rect.GetWidth(), // width
viewport.rect.GetHeight() // height
);
if (pass_data.depth_attachment) {
if (gl.DepthRangef.IsAvailable()) {
gl.DepthRangef(viewport.depth_range.z_near, viewport.depth_range.z_far);
} else {
gl.DepthRange(viewport.depth_range.z_near, viewport.depth_range.z_far);
}
}
//--------------------------------------------------------------------------
/// Setup the scissor rect.
///
if (command.scissor.has_value()) {
const auto& scissor = command.scissor.value();
gl.Enable(GL_SCISSOR_TEST);
gl.Scissor(
scissor.GetX(), // x
target_size.height - scissor.GetY() - scissor.GetHeight(), // y
scissor.GetWidth(), // width
scissor.GetHeight() // height
);
} else {
gl.Disable(GL_SCISSOR_TEST);
}
//--------------------------------------------------------------------------
/// Setup culling.
///
switch (pipeline.GetDescriptor().GetCullMode()) {
case CullMode::kNone:
gl.Disable(GL_CULL_FACE);
break;
case CullMode::kFrontFace:
gl.Enable(GL_CULL_FACE);
gl.CullFace(GL_FRONT);
break;
case CullMode::kBackFace:
gl.Enable(GL_CULL_FACE);
gl.CullFace(GL_BACK);
break;
}
//--------------------------------------------------------------------------
/// Setup winding order.
///
switch (pipeline.GetDescriptor().GetWindingOrder()) {
case WindingOrder::kClockwise:
gl.FrontFace(GL_CW);
break;
case WindingOrder::kCounterClockwise:
gl.FrontFace(GL_CCW);
break;
}
if (command.vertex_buffer.index_type == IndexType::kUnknown) {
return false;
}
auto vertex_desc_gles = pipeline.GetBufferBindings();
//--------------------------------------------------------------------------
/// Bind vertex and index buffers.
///
auto& vertex_buffer_view = command.vertex_buffer.vertex_buffer;
if (!vertex_buffer_view) {
return false;
}
auto vertex_buffer = vertex_buffer_view.buffer;
if (!vertex_buffer) {
return false;
}
const auto& vertex_buffer_gles = DeviceBufferGLES::Cast(*vertex_buffer);
if (!vertex_buffer_gles.BindAndUploadDataIfNecessary(
DeviceBufferGLES::BindingType::kArrayBuffer)) {
return false;
}
//--------------------------------------------------------------------------
/// Bind the pipeline program.
///
if (!pipeline.BindProgram()) {
return false;
}
//--------------------------------------------------------------------------
/// Bind vertex attribs.
///
if (!vertex_desc_gles->BindVertexAttributes(
gl, vertex_buffer_view.range.offset)) {
return false;
}
//--------------------------------------------------------------------------
/// Bind uniform data.
///
if (!vertex_desc_gles->BindUniformData(gl, //
*transients_allocator, //
command.vertex_bindings, //
command.fragment_bindings //
)) {
return false;
}
//--------------------------------------------------------------------------
/// Determine the primitive type.
///
// GLES doesn't support setting the fill mode, so override the primitive
// with GL_LINE_STRIP to somewhat emulate PolygonMode::kLine. This isn't
// correct; full triangle outlines won't be drawn and disconnected
// geometry may appear connected. However this can still be useful for
// wireframe debug views.
auto mode = pipeline.GetDescriptor().GetPolygonMode() == PolygonMode::kLine
? GL_LINE_STRIP
: ToMode(pipeline.GetDescriptor().GetPrimitiveType());
//--------------------------------------------------------------------------
/// Finally! Invoke the draw call.
///
if (command.vertex_buffer.index_type == IndexType::kNone) {
gl.DrawArrays(mode, command.base_vertex,
command.vertex_buffer.vertex_count);
} else {
// Bind the index buffer if necessary.
auto index_buffer_view = command.vertex_buffer.index_buffer;
auto index_buffer = index_buffer_view.buffer;
const auto& index_buffer_gles = DeviceBufferGLES::Cast(*index_buffer);
if (!index_buffer_gles.BindAndUploadDataIfNecessary(
DeviceBufferGLES::BindingType::kElementArrayBuffer)) {
return false;
}
gl.DrawElements(mode, // mode
command.vertex_buffer.vertex_count, // count
ToIndexType(command.vertex_buffer.index_type), // type
reinterpret_cast<const GLvoid*>(static_cast<GLsizei>(
index_buffer_view.range.offset)) // indices
);
}
//--------------------------------------------------------------------------
/// Unbind vertex attribs.
///
if (!vertex_desc_gles->UnbindVertexAttributes(gl)) {
return false;
}
//--------------------------------------------------------------------------
/// Unbind the program pipeline.
///
if (!pipeline.UnbindProgram()) {
return false;
}
}
if (gl.DiscardFramebufferEXT.IsAvailable()) {
std::vector<GLenum> attachments;
// TODO(jonahwilliams): discarding stencil or depth on the default fbo
// causes Angle to discard the entire render target. Until we know the
// reason, default to storing.
bool angle_safe = gl.GetCapabilities()->IsANGLE() ? !is_default_fbo : true;
if (pass_data.discard_color_attachment) {
attachments.push_back(is_default_fbo ? GL_COLOR_EXT
: GL_COLOR_ATTACHMENT0);
}
if (pass_data.discard_depth_attachment && angle_safe) {
attachments.push_back(is_default_fbo ? GL_DEPTH_EXT
: GL_DEPTH_ATTACHMENT);
}
if (pass_data.discard_stencil_attachment && angle_safe) {
attachments.push_back(is_default_fbo ? GL_STENCIL_EXT
: GL_STENCIL_ATTACHMENT);
}
gl.DiscardFramebufferEXT(GL_FRAMEBUFFER, // target
attachments.size(), // attachments to discard
attachments.data() // size
);
}
#ifdef IMPELLER_DEBUG
if (is_default_fbo) {
tracer->MarkFrameEnd(gl);
}
#endif // IMPELLER_DEBUG
return true;
}
// |RenderPass|
bool RenderPassGLES::OnEncodeCommands(const Context& context) const {
if (!IsValid()) {
return false;
}
const auto& render_target = GetRenderTarget();
if (!render_target.HasColorAttachment(0u)) {
return false;
}
const auto& color0 = render_target.GetColorAttachments().at(0u);
const auto& depth0 = render_target.GetDepthAttachment();
const auto& stencil0 = render_target.GetStencilAttachment();
auto pass_data = std::make_shared<RenderPassData>();
pass_data->label = label_;
pass_data->viewport.rect = Rect::MakeSize(GetRenderTargetSize());
//----------------------------------------------------------------------------
/// Setup color data.
///
pass_data->color_attachment = color0.texture;
pass_data->clear_color = color0.clear_color;
pass_data->clear_color_attachment = CanClearAttachment(color0.load_action);
pass_data->discard_color_attachment =
CanDiscardAttachmentWhenDone(color0.store_action);
// When we are using EXT_multisampled_render_to_texture, it is implicitly
// resolved when we bind the texture to the framebuffer. We don't need to
// discard the attachment when we are done.
if (color0.resolve_texture) {
FML_DCHECK(context.GetCapabilities()->SupportsImplicitResolvingMSAA());
pass_data->discard_color_attachment = false;
}
//----------------------------------------------------------------------------
/// Setup depth data.
///
if (depth0.has_value()) {
pass_data->depth_attachment = depth0->texture;
pass_data->clear_depth = depth0->clear_depth;
pass_data->clear_depth_attachment = CanClearAttachment(depth0->load_action);
pass_data->discard_depth_attachment =
CanDiscardAttachmentWhenDone(depth0->store_action);
}
//----------------------------------------------------------------------------
/// Setup stencil data.
///
if (stencil0.has_value()) {
pass_data->stencil_attachment = stencil0->texture;
pass_data->clear_stencil = stencil0->clear_stencil;
pass_data->clear_stencil_attachment =
CanClearAttachment(stencil0->load_action);
pass_data->discard_stencil_attachment =
CanDiscardAttachmentWhenDone(stencil0->store_action);
}
std::shared_ptr<const RenderPassGLES> shared_this = shared_from_this();
auto tracer = ContextGLES::Cast(context).GetGPUTracer();
return reactor_->AddOperation([pass_data,
allocator = context.GetResourceAllocator(),
render_pass = std::move(shared_this),
tracer](const auto& reactor) {
auto result = EncodeCommandsInReactor(*pass_data, allocator, reactor,
render_pass->commands_, tracer);
FML_CHECK(result) << "Must be able to encode GL commands without error.";
});
}
} // namespace impeller
| engine/impeller/renderer/backend/gles/render_pass_gles.cc/0 | {
"file_path": "engine/impeller/renderer/backend/gles/render_pass_gles.cc",
"repo_id": "engine",
"token_count": 8305
} | 209 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include "GLES3/gl3.h"
#include "fml/logging.h"
#include "impeller/renderer/backend/gles/proc_table_gles.h"
#include "impeller/renderer/backend/gles/test/mock_gles.h"
namespace impeller {
namespace testing {
// OpenGLES is not thread safe.
//
// This mutex is used to ensure that only one test is using the mock at a time.
static std::mutex g_test_lock;
static std::weak_ptr<MockGLES> g_mock_gles;
static ProcTableGLES::Resolver g_resolver;
static std::vector<const unsigned char*> g_extensions;
static const unsigned char* g_version;
// Has friend visibility into MockGLES to record calls.
void RecordGLCall(const char* name) {
if (auto mock_gles = g_mock_gles.lock()) {
mock_gles->RecordCall(name);
}
}
template <typename T, typename U>
struct CheckSameSignature : std::false_type {};
template <typename Ret, typename... Args>
struct CheckSameSignature<Ret(Args...), Ret(Args...)> : std::true_type {};
// This is a stub function that does nothing/records nothing.
void doNothing() {}
auto const kMockVendor = (unsigned char*)"MockGLES";
const auto kMockShadingLanguageVersion = (unsigned char*)"GLSL ES 1.0";
auto const kExtensions = std::vector<const unsigned char*>{
(unsigned char*)"GL_KHR_debug" //
};
const unsigned char* mockGetString(GLenum name) {
switch (name) {
case GL_VENDOR:
return kMockVendor;
case GL_VERSION:
return g_version;
case GL_SHADING_LANGUAGE_VERSION:
return kMockShadingLanguageVersion;
default:
return (unsigned char*)"";
}
}
static_assert(CheckSameSignature<decltype(mockGetString), //
decltype(glGetString)>::value);
const unsigned char* mockGetStringi(GLenum name, GLuint index) {
switch (name) {
case GL_EXTENSIONS:
return g_extensions[index];
default:
return (unsigned char*)"";
}
}
static_assert(CheckSameSignature<decltype(mockGetStringi), //
decltype(glGetStringi)>::value);
void mockGetIntegerv(GLenum name, int* value) {
switch (name) {
case GL_NUM_EXTENSIONS: {
*value = g_extensions.size();
} break;
case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS:
*value = 8;
break;
default:
*value = 0;
break;
}
}
static_assert(CheckSameSignature<decltype(mockGetIntegerv), //
decltype(glGetIntegerv)>::value);
GLenum mockGetError() {
return GL_NO_ERROR;
}
static_assert(CheckSameSignature<decltype(mockGetError), //
decltype(glGetError)>::value);
void mockPopDebugGroupKHR() {
RecordGLCall("PopDebugGroupKHR");
}
static_assert(CheckSameSignature<decltype(mockPopDebugGroupKHR), //
decltype(glPopDebugGroupKHR)>::value);
void mockPushDebugGroupKHR(GLenum source,
GLuint id,
GLsizei length,
const GLchar* message) {
RecordGLCall("PushDebugGroupKHR");
}
static_assert(CheckSameSignature<decltype(mockPushDebugGroupKHR), //
decltype(glPushDebugGroupKHR)>::value);
void mockGenQueriesEXT(GLsizei n, GLuint* ids) {
RecordGLCall("glGenQueriesEXT");
for (auto i = 0; i < n; i++) {
ids[i] = i + 1;
}
}
static_assert(CheckSameSignature<decltype(mockGenQueriesEXT), //
decltype(glGenQueriesEXT)>::value);
void mockBeginQueryEXT(GLenum target, GLuint id) {
RecordGLCall("glBeginQueryEXT");
}
static_assert(CheckSameSignature<decltype(mockBeginQueryEXT), //
decltype(glBeginQueryEXT)>::value);
void mockEndQueryEXT(GLuint id) {
RecordGLCall("glEndQueryEXT");
}
static_assert(CheckSameSignature<decltype(mockEndQueryEXT), //
decltype(glEndQueryEXT)>::value);
void mockGetQueryObjectuivEXT(GLuint id, GLenum target, GLuint* result) {
RecordGLCall("glGetQueryObjectuivEXT");
*result = GL_TRUE;
}
static_assert(CheckSameSignature<decltype(mockGetQueryObjectuivEXT), //
decltype(glGetQueryObjectuivEXT)>::value);
void mockGetQueryObjectui64vEXT(GLuint id, GLenum target, GLuint64* result) {
RecordGLCall("glGetQueryObjectui64vEXT");
*result = 1000u;
}
static_assert(CheckSameSignature<decltype(mockGetQueryObjectui64vEXT), //
decltype(glGetQueryObjectui64vEXT)>::value);
void mockDeleteQueriesEXT(GLsizei size, const GLuint* queries) {
RecordGLCall("glDeleteQueriesEXT");
}
static_assert(CheckSameSignature<decltype(mockDeleteQueriesEXT), //
decltype(glDeleteQueriesEXT)>::value);
std::shared_ptr<MockGLES> MockGLES::Init(
const std::optional<std::vector<const unsigned char*>>& extensions,
const char* version_string,
ProcTableGLES::Resolver resolver) {
// If we cannot obtain a lock, MockGLES is already being used elsewhere.
FML_CHECK(g_test_lock.try_lock())
<< "MockGLES is already being used by another test.";
g_version = (unsigned char*)version_string;
g_extensions = extensions.value_or(kExtensions);
auto mock_gles = std::shared_ptr<MockGLES>(new MockGLES(std::move(resolver)));
g_mock_gles = mock_gles;
return mock_gles;
}
const ProcTableGLES::Resolver kMockResolverGLES = [](const char* name) {
if (strcmp(name, "glPopDebugGroupKHR") == 0) {
return reinterpret_cast<void*>(&mockPopDebugGroupKHR);
} else if (strcmp(name, "glPushDebugGroupKHR") == 0) {
return reinterpret_cast<void*>(&mockPushDebugGroupKHR);
} else if (strcmp(name, "glGetString") == 0) {
return reinterpret_cast<void*>(&mockGetString);
} else if (strcmp(name, "glGetStringi") == 0) {
return reinterpret_cast<void*>(&mockGetStringi);
} else if (strcmp(name, "glGetIntegerv") == 0) {
return reinterpret_cast<void*>(&mockGetIntegerv);
} else if (strcmp(name, "glGetError") == 0) {
return reinterpret_cast<void*>(&mockGetError);
} else if (strcmp(name, "glGenQueriesEXT") == 0) {
return reinterpret_cast<void*>(&mockGenQueriesEXT);
} else if (strcmp(name, "glBeginQueryEXT") == 0) {
return reinterpret_cast<void*>(&mockBeginQueryEXT);
} else if (strcmp(name, "glEndQueryEXT") == 0) {
return reinterpret_cast<void*>(&mockEndQueryEXT);
} else if (strcmp(name, "glDeleteQueriesEXT") == 0) {
return reinterpret_cast<void*>(&mockDeleteQueriesEXT);
} else if (strcmp(name, "glGetQueryObjectui64vEXT") == 0) {
return reinterpret_cast<void*>(mockGetQueryObjectui64vEXT);
} else if (strcmp(name, "glGetQueryObjectuivEXT") == 0) {
return reinterpret_cast<void*>(mockGetQueryObjectuivEXT);
} else {
return reinterpret_cast<void*>(&doNothing);
}
};
MockGLES::MockGLES(ProcTableGLES::Resolver resolver)
: proc_table_(std::move(resolver)) {}
MockGLES::~MockGLES() {
g_test_lock.unlock();
}
} // namespace testing
} // namespace impeller
| engine/impeller/renderer/backend/gles/test/mock_gles.cc/0 | {
"file_path": "engine/impeller/renderer/backend/gles/test/mock_gles.cc",
"repo_id": "engine",
"token_count": 2936
} | 210 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_COMPUTE_PASS_BINDINGS_CACHE_MTL_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_COMPUTE_PASS_BINDINGS_CACHE_MTL_H_
#include <Metal/Metal.h>
#include "flutter/fml/macros.h"
#include "impeller/renderer/compute_pass.h"
#include "impeller/renderer/pipeline_descriptor.h"
namespace impeller {
//-----------------------------------------------------------------------------
/// @brief Ensures that bindings on the pass are not redundantly set or
/// updated. Avoids making the driver do additional checks and makes
/// the frame insights during profiling and instrumentation not
/// complain about the same.
///
/// There should be no change to rendering if this caching was
/// absent.
///
struct ComputePassBindingsCacheMTL {
explicit ComputePassBindingsCacheMTL() {}
ComputePassBindingsCacheMTL(const ComputePassBindingsCacheMTL&) = delete;
ComputePassBindingsCacheMTL(ComputePassBindingsCacheMTL&&) = delete;
void SetComputePipelineState(id<MTLComputePipelineState> pipeline);
id<MTLComputePipelineState> GetPipeline() const;
void SetEncoder(id<MTLComputeCommandEncoder> encoder);
void SetBuffer(uint64_t index, uint64_t offset, id<MTLBuffer> buffer);
void SetTexture(uint64_t index, id<MTLTexture> texture);
void SetSampler(uint64_t index, id<MTLSamplerState> sampler);
private:
struct BufferOffsetPair {
id<MTLBuffer> buffer = nullptr;
size_t offset = 0u;
};
using BufferMap = std::map<uint64_t, BufferOffsetPair>;
using TextureMap = std::map<uint64_t, id<MTLTexture>>;
using SamplerMap = std::map<uint64_t, id<MTLSamplerState>>;
id<MTLComputeCommandEncoder> encoder_;
id<MTLComputePipelineState> pipeline_ = nullptr;
BufferMap buffers_;
TextureMap textures_;
SamplerMap samplers_;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_COMPUTE_PASS_BINDINGS_CACHE_MTL_H_
| engine/impeller/renderer/backend/metal/compute_pass_bindings_cache_mtl.h/0 | {
"file_path": "engine/impeller/renderer/backend/metal/compute_pass_bindings_cache_mtl.h",
"repo_id": "engine",
"token_count": 771
} | 211 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_PASS_BINDINGS_CACHE_MTL_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_PASS_BINDINGS_CACHE_MTL_H_
#include <Metal/Metal.h>
#include "impeller/renderer/render_pass.h"
#include "impeller/renderer/render_target.h"
namespace impeller {
//-----------------------------------------------------------------------------
/// @brief Ensures that bindings on the pass are not redundantly set or
/// updated. Avoids making the driver do additional checks and makes
/// the frame insights during profiling and instrumentation not
/// complain about the same.
///
/// There should be no change to rendering if this caching was
/// absent.
///
struct PassBindingsCacheMTL {
explicit PassBindingsCacheMTL() {}
~PassBindingsCacheMTL() = default;
PassBindingsCacheMTL(const PassBindingsCacheMTL&) = delete;
PassBindingsCacheMTL(PassBindingsCacheMTL&&) = delete;
void SetEncoder(id<MTLRenderCommandEncoder> encoder);
void SetRenderPipelineState(id<MTLRenderPipelineState> pipeline);
void SetDepthStencilState(id<MTLDepthStencilState> depth_stencil);
bool SetBuffer(ShaderStage stage,
uint64_t index,
uint64_t offset,
id<MTLBuffer> buffer);
bool SetTexture(ShaderStage stage, uint64_t index, id<MTLTexture> texture);
bool SetSampler(ShaderStage stage,
uint64_t index,
id<MTLSamplerState> sampler);
void SetViewport(const Viewport& viewport);
void SetScissor(const IRect& scissor);
private:
struct BufferOffsetPair {
id<MTLBuffer> buffer = nullptr;
size_t offset = 0u;
};
using BufferMap = std::map<uint64_t, BufferOffsetPair>;
using TextureMap = std::map<uint64_t, id<MTLTexture>>;
using SamplerMap = std::map<uint64_t, id<MTLSamplerState>>;
id<MTLRenderCommandEncoder> encoder_;
id<MTLRenderPipelineState> pipeline_ = nullptr;
id<MTLDepthStencilState> depth_stencil_ = nullptr;
std::map<ShaderStage, BufferMap> buffers_;
std::map<ShaderStage, TextureMap> textures_;
std::map<ShaderStage, SamplerMap> samplers_;
std::optional<Viewport> viewport_;
std::optional<IRect> scissor_;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_PASS_BINDINGS_CACHE_MTL_H_
| engine/impeller/renderer/backend/metal/pass_bindings_cache_mtl.h/0 | {
"file_path": "engine/impeller/renderer/backend/metal/pass_bindings_cache_mtl.h",
"repo_id": "engine",
"token_count": 950
} | 212 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SURFACE_MTL_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SURFACE_MTL_H_
#include <QuartzCore/CAMetalLayer.h>
#include <memory>
#include "flutter/fml/macros.h"
#include "impeller/geometry/rect.h"
#include "impeller/renderer/context.h"
#include "impeller/renderer/surface.h"
namespace impeller {
class SurfaceMTL final : public Surface {
public:
#pragma GCC diagnostic push
// Disable the diagnostic for iOS Simulators. Metal without emulation isn't
// available prior to iOS 13 and that's what the simulator headers say when
// support for CAMetalLayer begins. CAMetalLayer is available on iOS 8.0 and
// above which is well below Flutters support level.
#pragma GCC diagnostic ignored "-Wunguarded-availability-new"
//----------------------------------------------------------------------------
/// @brief Wraps the current drawable of the given Metal layer to create
/// a surface Impeller can render to. The surface must be created
/// as late as possible and discarded immediately after rendering
/// to it.
///
/// @param[in] context The context
/// @param[in] layer The layer whose current drawable to wrap to create a
/// surface.
///
/// @return A pointer to the wrapped surface or null.
///
static id<CAMetalDrawable> GetMetalDrawableAndValidate(
const std::shared_ptr<Context>& context,
CAMetalLayer* layer);
static std::unique_ptr<SurfaceMTL> MakeFromMetalLayerDrawable(
const std::shared_ptr<Context>& context,
id<CAMetalDrawable> drawable,
std::optional<IRect> clip_rect = std::nullopt);
static std::unique_ptr<SurfaceMTL> MakeFromTexture(
const std::shared_ptr<Context>& context,
id<MTLTexture> texture,
std::optional<IRect> clip_rect,
id<CAMetalDrawable> drawable = nil);
#pragma GCC diagnostic pop
// |Surface|
~SurfaceMTL() override;
id<MTLDrawable> drawable() const { return drawable_; }
// Returns a Rect defining the area of the surface in device pixels
IRect coverage() const;
// |Surface|
bool Present() const override;
private:
std::weak_ptr<Context> context_;
std::shared_ptr<Texture> resolve_texture_;
id<CAMetalDrawable> drawable_ = nil;
std::shared_ptr<Texture> source_texture_;
std::shared_ptr<Texture> destination_texture_;
bool requires_blit_ = false;
std::optional<IRect> clip_rect_;
static bool ShouldPerformPartialRepaint(std::optional<IRect> damage_rect);
SurfaceMTL(const std::weak_ptr<Context>& context,
const RenderTarget& target,
std::shared_ptr<Texture> resolve_texture,
id<CAMetalDrawable> drawable,
std::shared_ptr<Texture> source_texture,
std::shared_ptr<Texture> destination_texture,
bool requires_blit,
std::optional<IRect> clip_rect);
SurfaceMTL(const SurfaceMTL&) = delete;
SurfaceMTL& operator=(const SurfaceMTL&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SURFACE_MTL_H_
| engine/impeller/renderer/backend/metal/surface_mtl.h/0 | {
"file_path": "engine/impeller/renderer/backend/metal/surface_mtl.h",
"repo_id": "engine",
"token_count": 1180
} | 213 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_BARRIER_VK_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_BARRIER_VK_H_
#include "flutter/fml/macros.h"
#include "impeller/renderer/backend/vulkan/vk.h"
namespace impeller {
//------------------------------------------------------------------------------
/// @brief Defines an operations and memory access barrier on a resource.
///
/// For further reading, see
/// https://www.khronos.org/events/vulkan-how-to-use-synchronisation-validation-across-multiple-queues-and-command-buffers
/// and the Vulkan spec. The docs for the various member of this
/// class are based on verbiage in the spec.
///
/// A useful mnemonic for building a mental model of how to add
/// these barriers is to build a sentence like so; "All commands
/// before this barrier may continue till they encounter a <src
/// access> in the <src pipeline stage>. And, all commands after
/// this barrier may proceed till <dst access> in the <dst pipeline
/// stage>."
///
struct BarrierVK {
vk::CommandBuffer cmd_buffer = {};
vk::ImageLayout new_layout = vk::ImageLayout::eUndefined;
// The first synchronization scope defines what operations the barrier waits
// for to be done. In the Vulkan spec, this is usually referred to as the src
// scope.
vk::PipelineStageFlags src_stage = vk::PipelineStageFlagBits::eNone;
// The first access scope defines what memory operations are guaranteed to
// happen before the barrier. In the Vulkan spec, this is usually referred to
// as the src scope.
vk::AccessFlags src_access = vk::AccessFlagBits::eNone;
// The second synchronization scope defines what operations wait for the
// barrier to be done. In the Vulkan spec, this is usually referred to as the
// dst scope.
vk::PipelineStageFlags dst_stage = vk::PipelineStageFlagBits::eNone;
// The second access scope defines what memory operations are prevented from
// running till after the barrier. In the Vulkan spec, this is usually
// referred to as the dst scope.
vk::AccessFlags dst_access = vk::AccessFlagBits::eNone;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_BARRIER_VK_H_
| engine/impeller/renderer/backend/vulkan/barrier_vk.h/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/barrier_vk.h",
"repo_id": "engine",
"token_count": 816
} | 214 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "fml/status.h"
#include "impeller/renderer/backend/vulkan/command_queue_vk.h"
#include "impeller/base/validation.h"
#include "impeller/renderer/backend/vulkan/command_buffer_vk.h"
#include "impeller/renderer/backend/vulkan/command_encoder_vk.h"
#include "impeller/renderer/backend/vulkan/context_vk.h"
#include "impeller/renderer/backend/vulkan/fence_waiter_vk.h"
#include "impeller/renderer/backend/vulkan/tracked_objects_vk.h"
#include "impeller/renderer/command_buffer.h"
namespace impeller {
CommandQueueVK::CommandQueueVK(const std::weak_ptr<ContextVK>& context)
: context_(context) {}
CommandQueueVK::~CommandQueueVK() = default;
fml::Status CommandQueueVK::Submit(
const std::vector<std::shared_ptr<CommandBuffer>>& buffers,
const CompletionCallback& completion_callback) {
if (buffers.empty()) {
return fml::Status(fml::StatusCode::kInvalidArgument,
"No command buffers provided.");
}
// Success or failure, you only get to submit once.
fml::ScopedCleanupClosure reset([&]() {
if (completion_callback) {
completion_callback(CommandBuffer::Status::kError);
}
});
std::vector<vk::CommandBuffer> vk_buffers;
std::vector<std::shared_ptr<TrackedObjectsVK>> tracked_objects;
vk_buffers.reserve(buffers.size());
tracked_objects.reserve(buffers.size());
for (const std::shared_ptr<CommandBuffer>& buffer : buffers) {
auto encoder = CommandBufferVK::Cast(*buffer).GetEncoder();
if (!encoder->EndCommandBuffer()) {
return fml::Status(fml::StatusCode::kCancelled,
"Failed to end command buffer.");
}
tracked_objects.push_back(encoder->tracked_objects_);
vk_buffers.push_back(encoder->GetCommandBuffer());
encoder->Reset();
}
auto context = context_.lock();
if (!context) {
VALIDATION_LOG << "Device lost.";
return fml::Status(fml::StatusCode::kCancelled, "Device lost.");
}
auto [fence_result, fence] = context->GetDevice().createFenceUnique({});
if (fence_result != vk::Result::eSuccess) {
VALIDATION_LOG << "Failed to create fence: " << vk::to_string(fence_result);
return fml::Status(fml::StatusCode::kCancelled, "Failed to create fence.");
}
vk::SubmitInfo submit_info;
submit_info.setCommandBuffers(vk_buffers);
auto status = context->GetGraphicsQueue()->Submit(submit_info, *fence);
if (status != vk::Result::eSuccess) {
VALIDATION_LOG << "Failed to submit queue: " << vk::to_string(status);
return fml::Status(fml::StatusCode::kCancelled, "Failed to submit queue: ");
}
// Submit will proceed, call callback with true when it is done and do not
// call when `reset` is collected.
auto added_fence = context->GetFenceWaiter()->AddFence(
std::move(fence), [completion_callback, tracked_objects = std::move(
tracked_objects)]() mutable {
// Ensure tracked objects are destructed before calling any final
// callbacks.
tracked_objects.clear();
if (completion_callback) {
completion_callback(CommandBuffer::Status::kCompleted);
}
});
if (!added_fence) {
return fml::Status(fml::StatusCode::kCancelled, "Failed to add fence.");
}
reset.Release();
return fml::Status();
}
} // namespace impeller
| engine/impeller/renderer/backend/vulkan/command_queue_vk.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/command_queue_vk.cc",
"repo_id": "engine",
"token_count": 1301
} | 215 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DEVICE_HOLDER_VK_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DEVICE_HOLDER_VK_H_
#include "impeller/renderer/backend/vulkan/vk.h" // IWYU pragma: keep.
namespace impeller {
//------------------------------------------------------------------------------
/// @brief Holds a strong reference to the underlying logical Vulkan
/// device. This comes in handy when the context is being torn down
/// and the various components on different threads may need to
/// orchestrate safe shutdown.
///
class DeviceHolderVK {
public:
virtual ~DeviceHolderVK() = default;
virtual const vk::Device& GetDevice() const = 0;
virtual const vk::PhysicalDevice& GetPhysicalDevice() const = 0;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DEVICE_HOLDER_VK_H_
| engine/impeller/renderer/backend/vulkan/device_holder_vk.h/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/device_holder_vk.h",
"repo_id": "engine",
"token_count": 359
} | 216 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/pipeline_vk.h"
#include "flutter/fml/make_copyable.h"
#include "flutter/fml/trace_event.h"
#include "impeller/base/timing.h"
#include "impeller/renderer/backend/vulkan/capabilities_vk.h"
#include "impeller/renderer/backend/vulkan/context_vk.h"
#include "impeller/renderer/backend/vulkan/formats_vk.h"
#include "impeller/renderer/backend/vulkan/render_pass_builder_vk.h"
#include "impeller/renderer/backend/vulkan/sampler_vk.h"
#include "impeller/renderer/backend/vulkan/shader_function_vk.h"
#include "impeller/renderer/backend/vulkan/vertex_descriptor_vk.h"
namespace impeller {
static vk::PipelineCreationFeedbackEXT EmptyFeedback() {
vk::PipelineCreationFeedbackEXT feedback;
// If the VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT is not set in flags, an
// implementation must not set any other bits in flags, and the values of all
// other VkPipelineCreationFeedback data members are undefined.
feedback.flags = vk::PipelineCreationFeedbackFlagBits::eValid;
return feedback;
}
constexpr vk::FrontFace ToVKFrontFace(WindingOrder order) {
switch (order) {
case WindingOrder::kClockwise:
return vk::FrontFace::eClockwise;
case WindingOrder::kCounterClockwise:
return vk::FrontFace::eCounterClockwise;
}
FML_UNREACHABLE();
}
static void ReportPipelineCreationFeedbackToLog(
std::stringstream& stream,
const vk::PipelineCreationFeedbackEXT& feedback) {
const auto pipeline_cache_hit =
feedback.flags &
vk::PipelineCreationFeedbackFlagBits::eApplicationPipelineCacheHit;
const auto base_pipeline_accl =
feedback.flags &
vk::PipelineCreationFeedbackFlagBits::eBasePipelineAcceleration;
auto duration = std::chrono::duration_cast<MillisecondsF>(
std::chrono::nanoseconds{feedback.duration});
stream << "Time: " << duration.count() << "ms"
<< " Cache Hit: " << static_cast<bool>(pipeline_cache_hit)
<< " Base Accel: " << static_cast<bool>(base_pipeline_accl)
<< " Thread: " << std::this_thread::get_id();
}
static void ReportPipelineCreationFeedbackToLog(
const PipelineDescriptor& desc,
const vk::PipelineCreationFeedbackCreateInfoEXT& feedback) {
std::stringstream stream;
stream << std::fixed << std::showpoint << std::setprecision(2);
stream << std::endl << ">>>>>>" << std::endl;
stream << "Pipeline '" << desc.GetLabel() << "' ";
ReportPipelineCreationFeedbackToLog(stream,
*feedback.pPipelineCreationFeedback);
if (feedback.pipelineStageCreationFeedbackCount != 0) {
stream << std::endl;
}
for (size_t i = 0, count = feedback.pipelineStageCreationFeedbackCount;
i < count; i++) {
stream << "\tStage " << i + 1 << ": ";
ReportPipelineCreationFeedbackToLog(
stream, feedback.pPipelineStageCreationFeedbacks[i]);
if (i != count - 1) {
stream << std::endl;
}
}
stream << std::endl << "<<<<<<" << std::endl;
FML_LOG(ERROR) << stream.str();
}
static void ReportPipelineCreationFeedbackToTrace(
const PipelineDescriptor& desc,
const vk::PipelineCreationFeedbackCreateInfoEXT& feedback) {
static int64_t gPipelineCacheHits = 0;
static int64_t gPipelineCacheMisses = 0;
static int64_t gPipelines = 0;
if (feedback.pPipelineCreationFeedback->flags &
vk::PipelineCreationFeedbackFlagBits::eApplicationPipelineCacheHit) {
gPipelineCacheHits++;
} else {
gPipelineCacheMisses++;
}
gPipelines++;
static constexpr int64_t kImpellerPipelineTraceID = 1988;
FML_TRACE_COUNTER("impeller", //
"PipelineCache", // series name
kImpellerPipelineTraceID, // series ID
"PipelineCacheHits", gPipelineCacheHits, //
"PipelineCacheMisses", gPipelineCacheMisses, //
"TotalPipelines", gPipelines //
);
}
static void ReportPipelineCreationFeedback(
const PipelineDescriptor& desc,
const vk::PipelineCreationFeedbackCreateInfoEXT& feedback) {
constexpr bool kReportPipelineCreationFeedbackToLogs = false;
constexpr bool kReportPipelineCreationFeedbackToTraces = true;
if (kReportPipelineCreationFeedbackToLogs) {
ReportPipelineCreationFeedbackToLog(desc, feedback);
}
if (kReportPipelineCreationFeedbackToTraces) {
ReportPipelineCreationFeedbackToTrace(desc, feedback);
}
}
//----------------------------------------------------------------------------
/// Render Pass
/// We are NOT going to use the same render pass with the framebuffer (later)
/// and the graphics pipeline (here). Instead, we are going to ensure that the
/// sub-passes are compatible. To see the compatibility rules, see the Vulkan
/// spec:
/// https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/chap8.html#renderpass-compatibility
///
static vk::UniqueRenderPass CreateCompatRenderPassForPipeline(
const vk::Device& device,
const PipelineDescriptor& desc) {
RenderPassBuilderVK builder;
for (const auto& [bind_point, color] : desc.GetColorAttachmentDescriptors()) {
builder.SetColorAttachment(bind_point, //
color.format, //
desc.GetSampleCount(), //
LoadAction::kDontCare, //
StoreAction::kDontCare //
);
}
if (auto depth = desc.GetDepthStencilAttachmentDescriptor();
depth.has_value()) {
builder.SetDepthStencilAttachment(desc.GetDepthPixelFormat(), //
desc.GetSampleCount(), //
LoadAction::kDontCare, //
StoreAction::kDontCare //
);
} else if (desc.HasStencilAttachmentDescriptors()) {
builder.SetStencilAttachment(desc.GetStencilPixelFormat(), //
desc.GetSampleCount(), //
LoadAction::kDontCare, //
StoreAction::kDontCare //
);
}
auto pass = builder.Build(device);
if (!pass) {
VALIDATION_LOG << "Failed to create render pass for pipeline: "
<< desc.GetLabel();
return {};
}
ContextVK::SetDebugName(device, pass.get(),
"Compat Render Pass: " + desc.GetLabel());
return pass;
}
std::unique_ptr<PipelineVK> PipelineVK::Create(
const PipelineDescriptor& desc,
const std::shared_ptr<DeviceHolderVK>& device_holder,
const std::weak_ptr<PipelineLibrary>& weak_library,
std::shared_ptr<SamplerVK> immutable_sampler) {
TRACE_EVENT0("flutter", "PipelineVK::Create");
auto library = weak_library.lock();
if (!device_holder || !library) {
return nullptr;
}
const auto& pso_cache = PipelineLibraryVK::Cast(*library).GetPSOCache();
vk::StructureChain<vk::GraphicsPipelineCreateInfo,
vk::PipelineCreationFeedbackCreateInfoEXT>
chain;
const auto* caps = pso_cache->GetCapabilities();
const auto supports_pipeline_creation_feedback = caps->HasExtension(
OptionalDeviceExtensionVK::kEXTPipelineCreationFeedback);
if (!supports_pipeline_creation_feedback) {
chain.unlink<vk::PipelineCreationFeedbackCreateInfoEXT>();
}
auto& pipeline_info = chain.get<vk::GraphicsPipelineCreateInfo>();
//----------------------------------------------------------------------------
/// Dynamic States
///
vk::PipelineDynamicStateCreateInfo dynamic_create_state_info;
std::vector<vk::DynamicState> dynamic_states = {
vk::DynamicState::eViewport,
vk::DynamicState::eScissor,
vk::DynamicState::eStencilReference,
};
dynamic_create_state_info.setDynamicStates(dynamic_states);
pipeline_info.setPDynamicState(&dynamic_create_state_info);
//----------------------------------------------------------------------------
/// Viewport State
///
vk::PipelineViewportStateCreateInfo viewport_state;
viewport_state.setViewportCount(1u);
viewport_state.setScissorCount(1u);
// The actual viewport and scissor rects are not set here since they are
// dynamic as mentioned above in the dynamic state info.
pipeline_info.setPViewportState(&viewport_state);
//----------------------------------------------------------------------------
/// Shader Stages
///
const auto& constants = desc.GetSpecializationConstants();
std::vector<std::vector<vk::SpecializationMapEntry>> map_entries(
desc.GetStageEntrypoints().size());
std::vector<vk::SpecializationInfo> specialization_infos(
desc.GetStageEntrypoints().size());
std::vector<vk::PipelineShaderStageCreateInfo> shader_stages;
size_t entrypoint_count = 0;
for (const auto& entrypoint : desc.GetStageEntrypoints()) {
auto stage = ToVKShaderStageFlagBits(entrypoint.first);
if (!stage.has_value()) {
VALIDATION_LOG << "Unsupported shader type in pipeline: "
<< desc.GetLabel();
return nullptr;
}
std::vector<vk::SpecializationMapEntry>& entries =
map_entries[entrypoint_count];
for (auto i = 0u; i < constants.size(); i++) {
vk::SpecializationMapEntry entry;
entry.offset = (i * sizeof(Scalar));
entry.size = sizeof(Scalar);
entry.constantID = i;
entries.emplace_back(entry);
}
vk::SpecializationInfo& specialization_info =
specialization_infos[entrypoint_count];
specialization_info.setMapEntries(map_entries[entrypoint_count]);
specialization_info.setPData(constants.data());
specialization_info.setDataSize(sizeof(Scalar) * constants.size());
vk::PipelineShaderStageCreateInfo info;
info.setStage(stage.value());
info.setPName("main");
info.setModule(
ShaderFunctionVK::Cast(entrypoint.second.get())->GetModule());
info.setPSpecializationInfo(&specialization_info);
shader_stages.push_back(info);
entrypoint_count++;
}
pipeline_info.setStages(shader_stages);
//----------------------------------------------------------------------------
/// Rasterization State
///
vk::PipelineRasterizationStateCreateInfo rasterization_state;
rasterization_state.setFrontFace(ToVKFrontFace(desc.GetWindingOrder()));
rasterization_state.setCullMode(ToVKCullModeFlags(desc.GetCullMode()));
rasterization_state.setPolygonMode(ToVKPolygonMode(desc.GetPolygonMode()));
rasterization_state.setLineWidth(1.0f);
rasterization_state.setDepthClampEnable(false);
rasterization_state.setRasterizerDiscardEnable(false);
pipeline_info.setPRasterizationState(&rasterization_state);
//----------------------------------------------------------------------------
/// Multi-sample State
///
vk::PipelineMultisampleStateCreateInfo multisample_state;
multisample_state.setRasterizationSamples(
ToVKSampleCountFlagBits(desc.GetSampleCount()));
pipeline_info.setPMultisampleState(&multisample_state);
//----------------------------------------------------------------------------
/// Primitive Input Assembly State
vk::PipelineInputAssemblyStateCreateInfo input_assembly;
const auto topology = ToVKPrimitiveTopology(desc.GetPrimitiveType());
input_assembly.setTopology(topology);
pipeline_info.setPInputAssemblyState(&input_assembly);
//----------------------------------------------------------------------------
/// Color Blend State
std::vector<vk::PipelineColorBlendAttachmentState> attachment_blend_state;
for (const auto& color_desc : desc.GetColorAttachmentDescriptors()) {
// TODO(csg): The blend states are per color attachment. But it isn't clear
// how the color attachment indices are specified in the pipeline create
// info. But, this should always work for one color attachment.
attachment_blend_state.push_back(
ToVKPipelineColorBlendAttachmentState(color_desc.second));
}
vk::PipelineColorBlendStateCreateInfo blend_state;
blend_state.setAttachments(attachment_blend_state);
pipeline_info.setPColorBlendState(&blend_state);
auto render_pass =
CreateCompatRenderPassForPipeline(device_holder->GetDevice(), //
desc //
);
if (!render_pass) {
VALIDATION_LOG << "Could not create render pass for pipeline.";
return nullptr;
}
// Convention wisdom says that the base acceleration pipelines are never used
// by drivers for cache hits. Instead, the PSO cache is the preferred
// mechanism.
pipeline_info.setBasePipelineHandle(VK_NULL_HANDLE);
pipeline_info.setSubpass(0u);
pipeline_info.setRenderPass(render_pass.get());
//----------------------------------------------------------------------------
/// Vertex Input Setup
///
std::vector<vk::VertexInputAttributeDescription> attr_descs;
std::vector<vk::VertexInputBindingDescription> buffer_descs;
const auto& stage_inputs = desc.GetVertexDescriptor()->GetStageInputs();
const auto& stage_buffer_layouts =
desc.GetVertexDescriptor()->GetStageLayouts();
for (const ShaderStageIOSlot& stage_in : stage_inputs) {
vk::VertexInputAttributeDescription attr_desc;
attr_desc.setBinding(stage_in.binding);
attr_desc.setLocation(stage_in.location);
attr_desc.setFormat(ToVertexDescriptorFormat(stage_in));
attr_desc.setOffset(stage_in.offset);
attr_descs.push_back(attr_desc);
}
for (const ShaderStageBufferLayout& layout : stage_buffer_layouts) {
vk::VertexInputBindingDescription binding_description;
binding_description.setBinding(layout.binding);
binding_description.setInputRate(vk::VertexInputRate::eVertex);
binding_description.setStride(layout.stride);
buffer_descs.push_back(binding_description);
}
vk::PipelineVertexInputStateCreateInfo vertex_input_state;
vertex_input_state.setVertexAttributeDescriptions(attr_descs);
vertex_input_state.setVertexBindingDescriptions(buffer_descs);
pipeline_info.setPVertexInputState(&vertex_input_state);
//----------------------------------------------------------------------------
/// Pipeline Layout a.k.a the descriptor sets and uniforms.
///
std::vector<vk::DescriptorSetLayoutBinding> set_bindings;
vk::Sampler vk_immutable_sampler =
immutable_sampler ? immutable_sampler->GetSampler()
: static_cast<vk::Sampler>(VK_NULL_HANDLE);
for (auto layout : desc.GetVertexDescriptor()->GetDescriptorSetLayouts()) {
vk::DescriptorSetLayoutBinding set_binding;
set_binding.binding = layout.binding;
set_binding.descriptorCount = 1u;
set_binding.descriptorType = ToVKDescriptorType(layout.descriptor_type);
set_binding.stageFlags = ToVkShaderStage(layout.shader_stage);
// TODO(143719): This specifies the immutable sampler for all sampled
// images. This is incorrect. In cases where the shader samples from the
// multiple images, there is currently no way to tell which sampler needs to
// be immutable and which one needs a binding set in the render pass. Expect
// errors if the shader has more than on sampled image. The sampling from
// the one that is expected to be non-immutable will be incorrect.
if (vk_immutable_sampler &&
layout.descriptor_type == DescriptorType::kSampledImage) {
set_binding.setImmutableSamplers(vk_immutable_sampler);
}
set_bindings.push_back(set_binding);
}
vk::DescriptorSetLayoutCreateInfo desc_set_layout_info;
desc_set_layout_info.setBindings(set_bindings);
auto [descs_result, descs_layout] =
device_holder->GetDevice().createDescriptorSetLayoutUnique(
desc_set_layout_info);
if (descs_result != vk::Result::eSuccess) {
VALIDATION_LOG << "unable to create uniform descriptors";
return nullptr;
}
ContextVK::SetDebugName(device_holder->GetDevice(), descs_layout.get(),
"Descriptor Set Layout " + desc.GetLabel());
//----------------------------------------------------------------------------
/// Create the pipeline layout.
///
vk::PipelineLayoutCreateInfo pipeline_layout_info;
pipeline_layout_info.setSetLayouts(descs_layout.get());
auto pipeline_layout = device_holder->GetDevice().createPipelineLayoutUnique(
pipeline_layout_info);
if (pipeline_layout.result != vk::Result::eSuccess) {
VALIDATION_LOG << "Could not create pipeline layout for pipeline "
<< desc.GetLabel() << ": "
<< vk::to_string(pipeline_layout.result);
return nullptr;
}
pipeline_info.setLayout(pipeline_layout.value.get());
//----------------------------------------------------------------------------
/// Create the depth stencil state.
///
auto depth_stencil_state = ToVKPipelineDepthStencilStateCreateInfo(
desc.GetDepthStencilAttachmentDescriptor(),
desc.GetFrontStencilAttachmentDescriptor(),
desc.GetBackStencilAttachmentDescriptor());
pipeline_info.setPDepthStencilState(&depth_stencil_state);
//----------------------------------------------------------------------------
/// Setup the optional pipeline creation feedback struct so we can understand
/// how Vulkan created the PSO.
///
auto& feedback = chain.get<vk::PipelineCreationFeedbackCreateInfoEXT>();
auto pipeline_feedback = EmptyFeedback();
std::vector<vk::PipelineCreationFeedbackEXT> stage_feedbacks(
pipeline_info.stageCount, EmptyFeedback());
feedback.setPPipelineCreationFeedback(&pipeline_feedback);
feedback.setPipelineStageCreationFeedbacks(stage_feedbacks);
//----------------------------------------------------------------------------
/// Finally, all done with the setup info. Create the pipeline itself.
///
auto pipeline = pso_cache->CreatePipeline(pipeline_info);
if (!pipeline) {
VALIDATION_LOG << "Could not create graphics pipeline: " << desc.GetLabel();
return nullptr;
}
if (supports_pipeline_creation_feedback) {
ReportPipelineCreationFeedback(desc, feedback);
}
ContextVK::SetDebugName(device_holder->GetDevice(), *pipeline_layout.value,
"Pipeline Layout " + desc.GetLabel());
ContextVK::SetDebugName(device_holder->GetDevice(), *pipeline,
"Pipeline " + desc.GetLabel());
auto pipeline_vk = std::unique_ptr<PipelineVK>(new PipelineVK(
device_holder, //
library, //
desc, //
std::move(pipeline), //
std::move(render_pass), //
std::move(pipeline_layout.value), //
std::move(descs_layout), //
std::move(immutable_sampler) //
));
if (!pipeline_vk->IsValid()) {
VALIDATION_LOG << "Could not create a valid pipeline.";
return nullptr;
}
return pipeline_vk;
}
PipelineVK::PipelineVK(std::weak_ptr<DeviceHolderVK> device_holder,
std::weak_ptr<PipelineLibrary> library,
const PipelineDescriptor& desc,
vk::UniquePipeline pipeline,
vk::UniqueRenderPass render_pass,
vk::UniquePipelineLayout layout,
vk::UniqueDescriptorSetLayout descriptor_set_layout,
std::shared_ptr<SamplerVK> immutable_sampler)
: Pipeline(std::move(library), desc),
device_holder_(std::move(device_holder)),
pipeline_(std::move(pipeline)),
render_pass_(std::move(render_pass)),
layout_(std::move(layout)),
descriptor_set_layout_(std::move(descriptor_set_layout)),
immutable_sampler_(std::move(immutable_sampler)) {
is_valid_ = pipeline_ && render_pass_ && layout_ && descriptor_set_layout_;
}
PipelineVK::~PipelineVK() {
if (auto device = device_holder_.lock(); !device) {
descriptor_set_layout_.release();
layout_.release();
render_pass_.release();
pipeline_.release();
}
}
bool PipelineVK::IsValid() const {
return is_valid_;
}
vk::Pipeline PipelineVK::GetPipeline() const {
return *pipeline_;
}
const vk::PipelineLayout& PipelineVK::GetPipelineLayout() const {
return *layout_;
}
const vk::DescriptorSetLayout& PipelineVK::GetDescriptorSetLayout() const {
return *descriptor_set_layout_;
}
std::shared_ptr<PipelineVK> PipelineVK::CreateVariantForImmutableSamplers(
const std::shared_ptr<SamplerVK>& immutable_sampler) const {
if (!immutable_sampler) {
return nullptr;
}
auto cache_key = ImmutableSamplerKeyVK{*immutable_sampler};
Lock lock(immutable_sampler_variants_mutex_);
auto found = immutable_sampler_variants_.find(cache_key);
if (found != immutable_sampler_variants_.end()) {
return found->second;
}
auto device_holder = device_holder_.lock();
if (!device_holder) {
return nullptr;
}
return (immutable_sampler_variants_[cache_key] =
Create(desc_, device_holder, library_, immutable_sampler));
}
} // namespace impeller
| engine/impeller/renderer/backend/vulkan/pipeline_vk.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/pipeline_vk.cc",
"repo_id": "engine",
"token_count": 7899
} | 217 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/shader_function_vk.h"
namespace impeller {
ShaderFunctionVK::ShaderFunctionVK(
const std::weak_ptr<DeviceHolderVK>& device_holder,
UniqueID parent_library_id,
std::string name,
ShaderStage stage,
vk::UniqueShaderModule module)
: ShaderFunction(parent_library_id, std::move(name), stage),
module_(std::move(module)),
device_holder_(device_holder) {}
ShaderFunctionVK::~ShaderFunctionVK() {
std::shared_ptr<DeviceHolderVK> device_holder = device_holder_.lock();
if (device_holder) {
module_.reset();
} else {
module_.release();
}
}
const vk::ShaderModule& ShaderFunctionVK::GetModule() const {
return module_.get();
}
} // namespace impeller
| engine/impeller/renderer/backend/vulkan/shader_function_vk.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/shader_function_vk.cc",
"repo_id": "engine",
"token_count": 313
} | 218 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_vk.h"
#include "flutter/fml/trace_event.h"
#include "impeller/base/validation.h"
#include "impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_impl_vk.h"
namespace impeller {
std::shared_ptr<KHRSwapchainVK> KHRSwapchainVK::Create(
const std::shared_ptr<Context>& context,
vk::UniqueSurfaceKHR surface,
const ISize& size,
bool enable_msaa) {
auto impl = KHRSwapchainImplVK::Create(context, std::move(surface), size,
enable_msaa);
if (!impl || !impl->IsValid()) {
VALIDATION_LOG << "Failed to create SwapchainVK implementation.";
return nullptr;
}
return std::shared_ptr<KHRSwapchainVK>(
new KHRSwapchainVK(std::move(impl), size, enable_msaa));
}
KHRSwapchainVK::KHRSwapchainVK(std::shared_ptr<KHRSwapchainImplVK> impl,
const ISize& size,
bool enable_msaa)
: impl_(std::move(impl)), size_(size), enable_msaa_(enable_msaa) {}
KHRSwapchainVK::~KHRSwapchainVK() = default;
bool KHRSwapchainVK::IsValid() const {
return impl_ ? impl_->IsValid() : false;
}
void KHRSwapchainVK::UpdateSurfaceSize(const ISize& size) {
// Update the size of the swapchain. On the next acquired drawable,
// the sizes may no longer match, forcing the swapchain to be recreated.
size_ = size;
}
std::unique_ptr<Surface> KHRSwapchainVK::AcquireNextDrawable() {
if (!IsValid()) {
return nullptr;
}
TRACE_EVENT0("impeller", __FUNCTION__);
auto result = impl_->AcquireNextDrawable();
if (!result.out_of_date && size_ == impl_->GetSize()) {
return std::move(result.surface);
}
TRACE_EVENT0("impeller", "RecreateSwapchain");
// This swapchain implementation indicates that it is out of date. Tear it
// down and make a new one.
auto context = impl_->GetContext();
auto [surface, old_swapchain] = impl_->DestroySwapchain();
auto new_impl = KHRSwapchainImplVK::Create(context, //
std::move(surface), //
size_, //
enable_msaa_, //
*old_swapchain //
);
if (!new_impl || !new_impl->IsValid()) {
VALIDATION_LOG << "Could not update swapchain.";
// The old swapchain is dead because we took its surface. This is
// unrecoverable.
impl_.reset();
return nullptr;
}
impl_ = std::move(new_impl);
//----------------------------------------------------------------------------
/// We managed to recreate the swapchain in the new configuration. Try again.
///
return AcquireNextDrawable();
}
vk::Format KHRSwapchainVK::GetSurfaceFormat() const {
return IsValid() ? impl_->GetSurfaceFormat() : vk::Format::eUndefined;
}
} // namespace impeller
| engine/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_vk.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_vk.cc",
"repo_id": "engine",
"token_count": 1302
} | 219 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/command_buffer.h"
#include "impeller/renderer/compute_pass.h"
#include "impeller/renderer/render_pass.h"
#include "impeller/renderer/render_target.h"
namespace impeller {
CommandBuffer::CommandBuffer(std::weak_ptr<const Context> context)
: context_(std::move(context)) {}
CommandBuffer::~CommandBuffer() = default;
bool CommandBuffer::SubmitCommands(const CompletionCallback& callback) {
if (!IsValid()) {
// Already committed or was never valid. Either way, this is caller error.
if (callback) {
callback(Status::kError);
}
return false;
}
return OnSubmitCommands(callback);
}
bool CommandBuffer::SubmitCommands() {
return SubmitCommands(nullptr);
}
void CommandBuffer::WaitUntilScheduled() {
return OnWaitUntilScheduled();
}
std::shared_ptr<RenderPass> CommandBuffer::CreateRenderPass(
const RenderTarget& render_target) {
auto pass = OnCreateRenderPass(render_target);
if (pass && pass->IsValid()) {
pass->SetLabel("RenderPass");
return pass;
}
return nullptr;
}
std::shared_ptr<BlitPass> CommandBuffer::CreateBlitPass() {
auto pass = OnCreateBlitPass();
if (pass && pass->IsValid()) {
pass->SetLabel("BlitPass");
return pass;
}
return nullptr;
}
std::shared_ptr<ComputePass> CommandBuffer::CreateComputePass() {
if (!IsValid()) {
return nullptr;
}
auto pass = OnCreateComputePass();
if (pass && pass->IsValid()) {
pass->SetLabel("ComputePass");
return pass;
}
return nullptr;
}
} // namespace impeller
| engine/impeller/renderer/command_buffer.cc/0 | {
"file_path": "engine/impeller/renderer/command_buffer.cc",
"repo_id": "engine",
"token_count": 571
} | 220 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/render_target.h"
#include <sstream>
#include "impeller/base/strings.h"
#include "impeller/base/validation.h"
#include "impeller/core/allocator.h"
#include "impeller/core/formats.h"
#include "impeller/core/texture.h"
#include "impeller/core/texture_descriptor.h"
#include "impeller/renderer/context.h"
namespace impeller {
RenderTarget::RenderTarget() = default;
RenderTarget::~RenderTarget() = default;
bool RenderTarget::IsValid() const {
// Validate that there is a color attachment at zero index.
if (!HasColorAttachment(0u)) {
VALIDATION_LOG
<< "Render target does not have color attachment at index 0.";
return false;
}
// Validate that all attachments are of the same size.
{
std::optional<ISize> size;
bool sizes_are_same = true;
auto iterator = [&](const Attachment& attachment) -> bool {
if (!size.has_value()) {
size = attachment.texture->GetSize();
}
if (size != attachment.texture->GetSize()) {
sizes_are_same = false;
return false;
}
return true;
};
IterateAllAttachments(iterator);
if (!sizes_are_same) {
VALIDATION_LOG
<< "Sizes of all render target attachments are not the same.";
return false;
}
}
// Validate that all attachments are of the same type and sample counts.
{
std::optional<TextureType> texture_type;
std::optional<SampleCount> sample_count;
bool passes_type_validation = true;
auto iterator = [&](const Attachment& attachment) -> bool {
if (!texture_type.has_value() || !sample_count.has_value()) {
texture_type = attachment.texture->GetTextureDescriptor().type;
sample_count = attachment.texture->GetTextureDescriptor().sample_count;
}
if (texture_type != attachment.texture->GetTextureDescriptor().type) {
passes_type_validation = false;
VALIDATION_LOG << "Render target has incompatible texture types: "
<< TextureTypeToString(texture_type.value()) << " != "
<< TextureTypeToString(
attachment.texture->GetTextureDescriptor().type)
<< " on target " << ToString();
return false;
}
if (sample_count !=
attachment.texture->GetTextureDescriptor().sample_count) {
passes_type_validation = false;
VALIDATION_LOG << "Render target (" << ToString()
<< ") has incompatible sample counts.";
return false;
}
return true;
};
IterateAllAttachments(iterator);
if (!passes_type_validation) {
return false;
}
}
return true;
}
void RenderTarget::IterateAllAttachments(
const std::function<bool(const Attachment& attachment)>& iterator) const {
for (const auto& color : colors_) {
if (!iterator(color.second)) {
return;
}
}
if (depth_.has_value()) {
if (!iterator(depth_.value())) {
return;
}
}
if (stencil_.has_value()) {
if (!iterator(stencil_.value())) {
return;
}
}
}
SampleCount RenderTarget::GetSampleCount() const {
if (auto found = colors_.find(0u); found != colors_.end()) {
return found->second.texture->GetTextureDescriptor().sample_count;
}
return SampleCount::kCount1;
}
bool RenderTarget::HasColorAttachment(size_t index) const {
if (auto found = colors_.find(index); found != colors_.end()) {
return true;
}
return false;
}
std::optional<ISize> RenderTarget::GetColorAttachmentSize(size_t index) const {
auto found = colors_.find(index);
if (found == colors_.end()) {
return std::nullopt;
}
return found->second.texture->GetSize();
}
ISize RenderTarget::GetRenderTargetSize() const {
auto size = GetColorAttachmentSize(0u);
return size.has_value() ? size.value() : ISize{};
}
std::shared_ptr<Texture> RenderTarget::GetRenderTargetTexture() const {
auto found = colors_.find(0u);
if (found == colors_.end()) {
return nullptr;
}
return found->second.resolve_texture ? found->second.resolve_texture
: found->second.texture;
}
PixelFormat RenderTarget::GetRenderTargetPixelFormat() const {
if (auto texture = GetRenderTargetTexture(); texture != nullptr) {
return texture->GetTextureDescriptor().format;
}
return PixelFormat::kUnknown;
}
size_t RenderTarget::GetMaxColorAttacmentBindIndex() const {
size_t max = 0;
for (const auto& color : colors_) {
max = std::max(color.first, max);
}
return max;
}
RenderTarget& RenderTarget::SetColorAttachment(
const ColorAttachment& attachment,
size_t index) {
if (attachment.IsValid()) {
colors_[index] = attachment;
}
return *this;
}
RenderTarget& RenderTarget::SetDepthAttachment(
std::optional<DepthAttachment> attachment) {
if (!attachment.has_value()) {
depth_ = std::nullopt;
} else if (attachment->IsValid()) {
depth_ = std::move(attachment);
}
return *this;
}
RenderTarget& RenderTarget::SetStencilAttachment(
std::optional<StencilAttachment> attachment) {
if (!attachment.has_value()) {
stencil_ = std::nullopt;
} else if (attachment->IsValid()) {
stencil_ = std::move(attachment);
}
return *this;
}
const std::map<size_t, ColorAttachment>& RenderTarget::GetColorAttachments()
const {
return colors_;
}
const std::optional<DepthAttachment>& RenderTarget::GetDepthAttachment() const {
return depth_;
}
const std::optional<StencilAttachment>& RenderTarget::GetStencilAttachment()
const {
return stencil_;
}
size_t RenderTarget::GetTotalAttachmentCount() const {
size_t count = 0u;
for (const auto& [_, color] : colors_) {
if (color.texture) {
count++;
}
if (color.resolve_texture) {
count++;
}
}
if (depth_.has_value()) {
count++;
}
if (stencil_.has_value()) {
count++;
}
return count;
}
std::string RenderTarget::ToString() const {
std::stringstream stream;
for (const auto& [index, color] : colors_) {
stream << SPrintF("Color[%zu]=(%s)", index,
ColorAttachmentToString(color).c_str());
}
if (depth_) {
stream << ",";
stream << SPrintF("Depth=(%s)",
DepthAttachmentToString(depth_.value()).c_str());
}
if (stencil_) {
stream << ",";
stream << SPrintF("Stencil=(%s)",
StencilAttachmentToString(stencil_.value()).c_str());
}
return stream.str();
}
RenderTargetAllocator::RenderTargetAllocator(
std::shared_ptr<Allocator> allocator)
: allocator_(std::move(allocator)) {}
void RenderTargetAllocator::Start() {}
void RenderTargetAllocator::End() {}
RenderTarget RenderTargetAllocator::CreateOffscreen(
const Context& context,
ISize size,
int mip_count,
const std::string& label,
RenderTarget::AttachmentConfig color_attachment_config,
std::optional<RenderTarget::AttachmentConfig> stencil_attachment_config,
const std::shared_ptr<Texture>& existing_color_texture,
const std::shared_ptr<Texture>& existing_depth_stencil_texture) {
if (size.IsEmpty()) {
return {};
}
RenderTarget target;
std::shared_ptr<Texture> color0_tex;
if (existing_color_texture) {
color0_tex = existing_color_texture;
} else {
PixelFormat pixel_format =
context.GetCapabilities()->GetDefaultColorFormat();
TextureDescriptor color0_tex_desc;
color0_tex_desc.storage_mode = color_attachment_config.storage_mode;
color0_tex_desc.format = pixel_format;
color0_tex_desc.size = size;
color0_tex_desc.mip_count = mip_count;
color0_tex_desc.usage =
TextureUsage::kRenderTarget | TextureUsage::kShaderRead;
color0_tex = allocator_->CreateTexture(color0_tex_desc);
if (!color0_tex) {
return {};
}
}
color0_tex->SetLabel(SPrintF("%s Color Texture", label.c_str()));
ColorAttachment color0;
color0.clear_color = color_attachment_config.clear_color;
color0.load_action = color_attachment_config.load_action;
color0.store_action = color_attachment_config.store_action;
color0.texture = color0_tex;
target.SetColorAttachment(color0, 0u);
if (stencil_attachment_config.has_value()) {
target.SetupDepthStencilAttachments(
context, *allocator_, size, false, label,
stencil_attachment_config.value(), existing_depth_stencil_texture);
} else {
target.SetStencilAttachment(std::nullopt);
target.SetDepthAttachment(std::nullopt);
}
return target;
}
RenderTarget RenderTargetAllocator::CreateOffscreenMSAA(
const Context& context,
ISize size,
int mip_count,
const std::string& label,
RenderTarget::AttachmentConfigMSAA color_attachment_config,
std::optional<RenderTarget::AttachmentConfig> stencil_attachment_config,
const std::shared_ptr<Texture>& existing_color_msaa_texture,
const std::shared_ptr<Texture>& existing_color_resolve_texture,
const std::shared_ptr<Texture>& existing_depth_stencil_texture) {
if (size.IsEmpty()) {
return {};
}
RenderTarget target;
PixelFormat pixel_format = context.GetCapabilities()->GetDefaultColorFormat();
// Create MSAA color texture.
std::shared_ptr<Texture> color0_msaa_tex;
if (existing_color_msaa_texture) {
color0_msaa_tex = existing_color_msaa_texture;
} else {
TextureDescriptor color0_tex_desc;
color0_tex_desc.storage_mode = color_attachment_config.storage_mode;
color0_tex_desc.type = TextureType::kTexture2DMultisample;
color0_tex_desc.sample_count = SampleCount::kCount4;
color0_tex_desc.format = pixel_format;
color0_tex_desc.size = size;
color0_tex_desc.usage = TextureUsage::kRenderTarget;
if (context.GetCapabilities()->SupportsImplicitResolvingMSAA()) {
// See below ("SupportsImplicitResolvingMSAA") for more details.
color0_tex_desc.storage_mode = StorageMode::kDevicePrivate;
}
color0_msaa_tex = allocator_->CreateTexture(color0_tex_desc);
if (!color0_msaa_tex) {
VALIDATION_LOG << "Could not create multisample color texture.";
return {};
}
}
color0_msaa_tex->SetLabel(
SPrintF("%s Color Texture (Multisample)", label.c_str()));
// Create color resolve texture.
std::shared_ptr<Texture> color0_resolve_tex;
if (existing_color_resolve_texture) {
color0_resolve_tex = existing_color_resolve_texture;
} else {
TextureDescriptor color0_resolve_tex_desc;
color0_resolve_tex_desc.storage_mode =
color_attachment_config.resolve_storage_mode;
color0_resolve_tex_desc.format = pixel_format;
color0_resolve_tex_desc.size = size;
color0_resolve_tex_desc.compression_type = CompressionType::kLossy;
color0_resolve_tex_desc.usage =
TextureUsage::kRenderTarget | TextureUsage::kShaderRead;
color0_resolve_tex_desc.mip_count = mip_count;
color0_resolve_tex = allocator_->CreateTexture(color0_resolve_tex_desc);
if (!color0_resolve_tex) {
VALIDATION_LOG << "Could not create color texture.";
return {};
}
}
color0_resolve_tex->SetLabel(SPrintF("%s Color Texture", label.c_str()));
// Color attachment.
ColorAttachment color0;
color0.clear_color = color_attachment_config.clear_color;
color0.load_action = color_attachment_config.load_action;
color0.store_action = color_attachment_config.store_action;
color0.texture = color0_msaa_tex;
color0.resolve_texture = color0_resolve_tex;
if (context.GetCapabilities()->SupportsImplicitResolvingMSAA()) {
// If implicit MSAA is supported, then the resolve texture is not needed
// because the multisample texture is automatically resolved. We instead
// provide a view of the multisample texture as the resolve texture (because
// the HAL does expect a resolve texture).
//
// In practice, this is used for GLES 2.0 EXT_multisampled_render_to_texture
// https://registry.khronos.org/OpenGL/extensions/EXT/EXT_multisampled_render_to_texture.txt
color0.resolve_texture = color0_msaa_tex;
}
target.SetColorAttachment(color0, 0u);
// Create MSAA stencil texture.
if (stencil_attachment_config.has_value()) {
target.SetupDepthStencilAttachments(context, *allocator_, size, true, label,
stencil_attachment_config.value(),
existing_depth_stencil_texture);
} else {
target.SetDepthAttachment(std::nullopt);
target.SetStencilAttachment(std::nullopt);
}
return target;
}
void RenderTarget::SetupDepthStencilAttachments(
const Context& context,
Allocator& allocator,
ISize size,
bool msaa,
const std::string& label,
RenderTarget::AttachmentConfig stencil_attachment_config,
const std::shared_ptr<Texture>& existing_depth_stencil_texture) {
std::shared_ptr<Texture> depth_stencil_texture;
if (existing_depth_stencil_texture) {
depth_stencil_texture = existing_depth_stencil_texture;
} else {
TextureDescriptor depth_stencil_texture_desc;
depth_stencil_texture_desc.storage_mode =
stencil_attachment_config.storage_mode;
if (msaa) {
depth_stencil_texture_desc.type = TextureType::kTexture2DMultisample;
depth_stencil_texture_desc.sample_count = SampleCount::kCount4;
}
depth_stencil_texture_desc.format =
context.GetCapabilities()->GetDefaultDepthStencilFormat();
depth_stencil_texture_desc.size = size;
depth_stencil_texture_desc.usage = TextureUsage::kRenderTarget;
depth_stencil_texture = allocator.CreateTexture(depth_stencil_texture_desc);
if (!depth_stencil_texture) {
return; // Error messages are handled by `Allocator::CreateTexture`.
}
}
DepthAttachment depth0;
depth0.load_action = stencil_attachment_config.load_action;
depth0.store_action = stencil_attachment_config.store_action;
depth0.clear_depth = 0u;
depth0.texture = depth_stencil_texture;
StencilAttachment stencil0;
stencil0.load_action = stencil_attachment_config.load_action;
stencil0.store_action = stencil_attachment_config.store_action;
stencil0.clear_stencil = 0u;
stencil0.texture = std::move(depth_stencil_texture);
stencil0.texture->SetLabel(
SPrintF("%s Depth+Stencil Texture", label.c_str()));
SetDepthAttachment(std::move(depth0));
SetStencilAttachment(std::move(stencil0));
}
} // namespace impeller
| engine/impeller/renderer/render_target.cc/0 | {
"file_path": "engine/impeller/renderer/render_target.cc",
"repo_id": "engine",
"token_count": 5431
} | 221 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#extension GL_KHR_shader_subgroup_arithmetic : enable
layout(local_size_x = 256, local_size_y = 1) in;
layout(std430) buffer;
layout(binding = 0) buffer Polyline {
uint count;
vec2 data[];
}
polyline;
layout(binding = 1) buffer VertexBuffer {
vec2 position[];
}
vertex_buffer;
layout(binding = 2) buffer VertexBufferCount {
uint count;
}
vertex_buffer_count;
uniform Config {
float width;
uint cap;
uint join;
float miter_limit;
}
config;
vec2 compute_offset(uint index) {
vec2 direction = normalize(polyline.data[index + 1] - polyline.data[index]);
return vec2(-direction.y, direction.x) * config.width * .5;
}
void main() {
uint ident = gl_GlobalInvocationID.x;
if (ident >= polyline.count || ident == 0) {
// This is ok because there is no barrier() below.
return;
}
atomicAdd(vertex_buffer_count.count, 4);
uint index = ident - 1;
vec2 offset = compute_offset(index);
vertex_buffer.position[index * 4 + 0] = polyline.data[ident - 1] + offset;
vertex_buffer.position[index * 4 + 1] = polyline.data[ident - 1] - offset;
vertex_buffer.position[index * 4 + 2] = polyline.data[ident] + offset;
vertex_buffer.position[index * 4 + 3] = polyline.data[ident] - offset;
// TODO(dnfield): Implement other cap/join mechanisms.
if (ident == polyline.count - 1) {
vertex_buffer.position[index * 4 + 4] = polyline.data[ident] + offset;
vertex_buffer.position[index * 4 + 5] = polyline.data[ident] - offset;
atomicAdd(vertex_buffer_count.count, 2);
}
}
| engine/impeller/renderer/stroke.comp/0 | {
"file_path": "engine/impeller/renderer/stroke.comp",
"repo_id": "engine",
"token_count": 582
} | 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_IMPELLER_RUNTIME_STAGE_RUNTIME_STAGE_PLAYGROUND_H_
#define FLUTTER_IMPELLER_RUNTIME_STAGE_RUNTIME_STAGE_PLAYGROUND_H_
#include "flutter/fml/macros.h"
#include "impeller/playground/playground_test.h"
#include "impeller/runtime_stage/runtime_stage.h"
namespace impeller {
class RuntimeStagePlayground : public PlaygroundTest {
public:
RuntimeStagePlayground();
~RuntimeStagePlayground();
bool RegisterStage(const RuntimeStage& stage);
private:
RuntimeStagePlayground(const RuntimeStagePlayground&) = delete;
RuntimeStagePlayground& operator=(const RuntimeStagePlayground&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RUNTIME_STAGE_RUNTIME_STAGE_PLAYGROUND_H_
| engine/impeller/runtime_stage/runtime_stage_playground.h/0 | {
"file_path": "engine/impeller/runtime_stage/runtime_stage_playground.h",
"repo_id": "engine",
"token_count": 290
} | 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.
#include "impeller/scene/geometry.h"
#include <memory>
#include <ostream>
#include "impeller/core/device_buffer_descriptor.h"
#include "impeller/core/formats.h"
#include "impeller/core/sampler_descriptor.h"
#include "impeller/core/vertex_buffer.h"
#include "impeller/geometry/point.h"
#include "impeller/geometry/vector.h"
#include "impeller/renderer/render_pass.h"
#include "impeller/renderer/vertex_buffer_builder.h"
#include "impeller/scene/importer/scene_flatbuffers.h"
#include "impeller/scene/shaders/skinned.vert.h"
#include "impeller/scene/shaders/unskinned.vert.h"
namespace impeller {
namespace scene {
//------------------------------------------------------------------------------
/// Geometry
///
Geometry::~Geometry() = default;
std::shared_ptr<CuboidGeometry> Geometry::MakeCuboid(Vector3 size) {
auto result = std::make_shared<CuboidGeometry>();
result->SetSize(size);
return result;
}
std::shared_ptr<Geometry> Geometry::MakeVertexBuffer(VertexBuffer vertex_buffer,
bool is_skinned) {
if (is_skinned) {
auto result = std::make_shared<SkinnedVertexBufferGeometry>();
result->SetVertexBuffer(std::move(vertex_buffer));
return result;
} else {
auto result = std::make_shared<UnskinnedVertexBufferGeometry>();
result->SetVertexBuffer(std::move(vertex_buffer));
return result;
}
}
std::shared_ptr<Geometry> Geometry::MakeFromFlatbuffer(
const fb::MeshPrimitive& mesh,
Allocator& allocator) {
IndexType index_type;
switch (mesh.indices()->type()) {
case fb::IndexType::k16Bit:
index_type = IndexType::k16bit;
break;
case fb::IndexType::k32Bit:
index_type = IndexType::k32bit;
break;
}
const uint8_t* vertices_start;
size_t vertices_bytes;
bool is_skinned;
switch (mesh.vertices_type()) {
case fb::VertexBuffer::UnskinnedVertexBuffer: {
const auto* vertices =
mesh.vertices_as_UnskinnedVertexBuffer()->vertices();
vertices_start = reinterpret_cast<const uint8_t*>(vertices->Get(0));
vertices_bytes = vertices->size() * sizeof(fb::Vertex);
is_skinned = false;
break;
}
case fb::VertexBuffer::SkinnedVertexBuffer: {
const auto* vertices = mesh.vertices_as_SkinnedVertexBuffer()->vertices();
vertices_start = reinterpret_cast<const uint8_t*>(vertices->Get(0));
vertices_bytes = vertices->size() * sizeof(fb::SkinnedVertex);
is_skinned = true;
break;
}
case fb::VertexBuffer::NONE:
VALIDATION_LOG << "Invalid vertex buffer type.";
return nullptr;
}
const uint8_t* indices_start =
reinterpret_cast<const uint8_t*>(mesh.indices()->data()->Data());
const size_t indices_bytes = mesh.indices()->data()->size();
if (vertices_bytes == 0 || indices_bytes == 0) {
return nullptr;
}
DeviceBufferDescriptor buffer_desc;
buffer_desc.size = vertices_bytes + indices_bytes;
buffer_desc.storage_mode = StorageMode::kHostVisible;
auto buffer = allocator.CreateBuffer(buffer_desc);
buffer->SetLabel("Mesh vertices+indices");
if (!buffer->CopyHostBuffer(vertices_start, Range(0, vertices_bytes))) {
return nullptr;
}
if (!buffer->CopyHostBuffer(indices_start, Range(0, indices_bytes),
vertices_bytes)) {
return nullptr;
}
VertexBuffer vertex_buffer = {
.vertex_buffer = {.buffer = buffer, .range = Range(0, vertices_bytes)},
.index_buffer = {.buffer = buffer,
.range = Range(vertices_bytes, indices_bytes)},
.vertex_count = mesh.indices()->count(),
.index_type = index_type,
};
return MakeVertexBuffer(std::move(vertex_buffer), is_skinned);
}
void Geometry::SetJointsTexture(const std::shared_ptr<Texture>& texture) {}
//------------------------------------------------------------------------------
/// CuboidGeometry
///
CuboidGeometry::CuboidGeometry() = default;
CuboidGeometry::~CuboidGeometry() = default;
void CuboidGeometry::SetSize(Vector3 size) {
size_ = size;
}
// |Geometry|
GeometryType CuboidGeometry::GetGeometryType() const {
return GeometryType::kUnskinned;
}
// |Geometry|
VertexBuffer CuboidGeometry::GetVertexBuffer(Allocator& allocator) const {
VertexBufferBuilder<UnskinnedVertexShader::PerVertexData, uint16_t> builder;
// Layout: position, normal, tangent, uv
builder.AddVertices({
// Front.
{Vector3(0, 0, 0), Vector3(0, 0, -1), Vector3(1, 0, 0), Point(0, 0),
Color::White()},
{Vector3(1, 0, 0), Vector3(0, 0, -1), Vector3(1, 0, 0), Point(1, 0),
Color::White()},
{Vector3(1, 1, 0), Vector3(0, 0, -1), Vector3(1, 0, 0), Point(1, 1),
Color::White()},
{Vector3(1, 1, 0), Vector3(0, 0, -1), Vector3(1, 0, 0), Point(1, 1),
Color::White()},
{Vector3(0, 1, 0), Vector3(0, 0, -1), Vector3(1, 0, 0), Point(0, 1),
Color::White()},
{Vector3(0, 0, 0), Vector3(0, 0, -1), Vector3(1, 0, 0), Point(0, 0),
Color::White()},
});
return builder.CreateVertexBuffer(allocator);
}
// |Geometry|
void CuboidGeometry::BindToCommand(const SceneContext& scene_context,
HostBuffer& buffer,
const Matrix& transform,
RenderPass& pass) const {
pass.SetVertexBuffer(
GetVertexBuffer(*scene_context.GetContext()->GetResourceAllocator()));
UnskinnedVertexShader::FrameInfo info;
info.mvp = transform;
UnskinnedVertexShader::BindFrameInfo(pass, buffer.EmplaceUniform(info));
}
//------------------------------------------------------------------------------
/// UnskinnedVertexBufferGeometry
///
UnskinnedVertexBufferGeometry::UnskinnedVertexBufferGeometry() = default;
UnskinnedVertexBufferGeometry::~UnskinnedVertexBufferGeometry() = default;
void UnskinnedVertexBufferGeometry::SetVertexBuffer(
VertexBuffer vertex_buffer) {
vertex_buffer_ = std::move(vertex_buffer);
}
// |Geometry|
GeometryType UnskinnedVertexBufferGeometry::GetGeometryType() const {
return GeometryType::kUnskinned;
}
// |Geometry|
VertexBuffer UnskinnedVertexBufferGeometry::GetVertexBuffer(
Allocator& allocator) const {
return vertex_buffer_;
}
// |Geometry|
void UnskinnedVertexBufferGeometry::BindToCommand(
const SceneContext& scene_context,
HostBuffer& buffer,
const Matrix& transform,
RenderPass& pass) const {
pass.SetVertexBuffer(
GetVertexBuffer(*scene_context.GetContext()->GetResourceAllocator()));
UnskinnedVertexShader::FrameInfo info;
info.mvp = transform;
UnskinnedVertexShader::BindFrameInfo(pass, buffer.EmplaceUniform(info));
}
//------------------------------------------------------------------------------
/// SkinnedVertexBufferGeometry
///
SkinnedVertexBufferGeometry::SkinnedVertexBufferGeometry() = default;
SkinnedVertexBufferGeometry::~SkinnedVertexBufferGeometry() = default;
void SkinnedVertexBufferGeometry::SetVertexBuffer(VertexBuffer vertex_buffer) {
vertex_buffer_ = std::move(vertex_buffer);
}
// |Geometry|
GeometryType SkinnedVertexBufferGeometry::GetGeometryType() const {
return GeometryType::kSkinned;
}
// |Geometry|
VertexBuffer SkinnedVertexBufferGeometry::GetVertexBuffer(
Allocator& allocator) const {
return vertex_buffer_;
}
// |Geometry|
void SkinnedVertexBufferGeometry::BindToCommand(
const SceneContext& scene_context,
HostBuffer& buffer,
const Matrix& transform,
RenderPass& pass) const {
pass.SetVertexBuffer(
GetVertexBuffer(*scene_context.GetContext()->GetResourceAllocator()));
SamplerDescriptor sampler_desc;
sampler_desc.min_filter = MinMagFilter::kNearest;
sampler_desc.mag_filter = MinMagFilter::kNearest;
sampler_desc.mip_filter = MipFilter::kNearest;
sampler_desc.width_address_mode = SamplerAddressMode::kRepeat;
sampler_desc.label = "NN Repeat";
SkinnedVertexShader::BindJointsTexture(
pass,
joints_texture_ ? joints_texture_ : scene_context.GetPlaceholderTexture(),
scene_context.GetContext()->GetSamplerLibrary()->GetSampler(
sampler_desc));
SkinnedVertexShader::FrameInfo info;
info.mvp = transform;
info.enable_skinning = joints_texture_ ? 1 : 0;
info.joint_texture_size =
joints_texture_ ? joints_texture_->GetSize().width : 1;
SkinnedVertexShader::BindFrameInfo(pass, buffer.EmplaceUniform(info));
}
// |Geometry|
void SkinnedVertexBufferGeometry::SetJointsTexture(
const std::shared_ptr<Texture>& texture) {
joints_texture_ = texture;
}
} // namespace scene
} // namespace impeller
| engine/impeller/scene/geometry.cc/0 | {
"file_path": "engine/impeller/scene/geometry.cc",
"repo_id": "engine",
"token_count": 3262
} | 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.
#ifndef FLUTTER_IMPELLER_SCENE_MATERIAL_H_
#define FLUTTER_IMPELLER_SCENE_MATERIAL_H_
#include <memory>
#include "impeller/core/formats.h"
#include "impeller/core/texture.h"
#include "impeller/geometry/scalar.h"
#include "impeller/renderer/render_pass.h"
#include "impeller/scene/importer/scene_flatbuffers.h"
#include "impeller/scene/pipeline_key.h"
namespace impeller {
namespace scene {
class SceneContext;
struct SceneContextOptions;
class Geometry;
class UnlitMaterial;
class PhysicallyBasedMaterial;
class Material {
public:
struct BlendConfig {
BlendOperation color_op = BlendOperation::kAdd;
BlendFactor source_color_factor = BlendFactor::kOne;
BlendFactor destination_color_factor = BlendFactor::kOneMinusSourceAlpha;
BlendOperation alpha_op = BlendOperation::kAdd;
BlendFactor source_alpha_factor = BlendFactor::kOne;
BlendFactor destination_alpha_factor = BlendFactor::kOneMinusSourceAlpha;
};
struct StencilConfig {
StencilOperation operation = StencilOperation::kKeep;
CompareFunction compare = CompareFunction::kAlways;
};
static std::unique_ptr<Material> MakeFromFlatbuffer(
const fb::Material& material,
const std::vector<std::shared_ptr<Texture>>& textures);
static std::unique_ptr<UnlitMaterial> MakeUnlit();
static std::unique_ptr<PhysicallyBasedMaterial> MakePhysicallyBased();
virtual ~Material();
void SetVertexColorWeight(Scalar weight);
void SetBlendConfig(BlendConfig blend_config);
void SetStencilConfig(StencilConfig stencil_config);
void SetTranslucent(bool is_translucent);
SceneContextOptions GetContextOptions(const RenderPass& pass) const;
virtual MaterialType GetMaterialType() const = 0;
virtual void BindToCommand(const SceneContext& scene_context,
HostBuffer& buffer,
RenderPass& pass) const = 0;
protected:
Scalar vertex_color_weight_ = 1;
BlendConfig blend_config_;
StencilConfig stencil_config_;
bool is_translucent_ = false;
};
class UnlitMaterial final : public Material {
public:
static std::unique_ptr<UnlitMaterial> MakeFromFlatbuffer(
const fb::Material& material,
const std::vector<std::shared_ptr<Texture>>& textures);
~UnlitMaterial();
void SetColor(Color color);
void SetColorTexture(std::shared_ptr<Texture> color_texture);
// |Material|
MaterialType GetMaterialType() const override;
// |Material|
void BindToCommand(const SceneContext& scene_context,
HostBuffer& buffer,
RenderPass& pass) const override;
private:
Color color_ = Color::White();
std::shared_ptr<Texture> color_texture_;
};
class PhysicallyBasedMaterial final : public Material {
public:
static std::unique_ptr<PhysicallyBasedMaterial> MakeFromFlatbuffer(
const fb::Material& material,
const std::vector<std::shared_ptr<Texture>>& textures);
~PhysicallyBasedMaterial();
void SetAlbedo(Color albedo);
void SetRoughness(Scalar roughness);
void SetMetallic(Scalar metallic);
void SetAlbedoTexture(std::shared_ptr<Texture> albedo_texture);
void SetMetallicRoughnessTexture(
std::shared_ptr<Texture> metallic_roughness_texture);
void SetNormalTexture(std::shared_ptr<Texture> normal_texture);
void SetOcclusionTexture(std::shared_ptr<Texture> occlusion_texture);
void SetEnvironmentMap(std::shared_ptr<Texture> environment_map);
// |Material|
MaterialType GetMaterialType() const override;
// |Material|
void BindToCommand(const SceneContext& scene_context,
HostBuffer& buffer,
RenderPass& pass) const override;
private:
Color albedo_ = Color::White();
Scalar metallic_ = 0.5;
Scalar roughness_ = 0.5;
std::shared_ptr<Texture> albedo_texture_;
std::shared_ptr<Texture> metallic_roughness_texture_;
std::shared_ptr<Texture> normal_texture_;
std::shared_ptr<Texture> occlusion_texture_;
std::shared_ptr<Texture> environment_map_;
};
} // namespace scene
} // namespace impeller
#endif // FLUTTER_IMPELLER_SCENE_MATERIAL_H_
| engine/impeller/scene/material.h/0 | {
"file_path": "engine/impeller/scene/material.h",
"repo_id": "engine",
"token_count": 1448
} | 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.
uniform FrameInfo {
mat4 mvp;
}
frame_info;
// This attribute layout is expected to be identical to that within
// `impeller/scene/importer/scene.fbs`.
in vec3 position;
in vec3 normal;
in vec4 tangent;
in vec2 texture_coords;
in vec4 color;
out vec3 v_position;
out mat3 v_tangent_space;
out vec2 v_texture_coords;
out vec4 v_color;
void main() {
gl_Position = frame_info.mvp * vec4(position, 1.0);
v_position = gl_Position.xyz;
vec3 lh_tangent = tangent.xyz * tangent.w;
v_tangent_space = mat3(frame_info.mvp) *
mat3(lh_tangent, cross(normal, lh_tangent), normal);
v_texture_coords = texture_coords;
v_color = color;
}
| engine/impeller/scene/shaders/unskinned.vert/0 | {
"file_path": "engine/impeller/scene/shaders/unskinned.vert",
"repo_id": "engine",
"token_count": 318
} | 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_IMPELLER_SHADER_ARCHIVE_SHADER_ARCHIVE_WRITER_H_
#define FLUTTER_IMPELLER_SHADER_ARCHIVE_SHADER_ARCHIVE_WRITER_H_
#include <memory>
#include <string>
#include <vector>
#include "flutter/fml/macros.h"
#include "flutter/fml/mapping.h"
#include "impeller/shader_archive/shader_archive_types.h"
namespace impeller {
class ShaderArchiveWriter {
public:
ShaderArchiveWriter();
~ShaderArchiveWriter();
[[nodiscard]] bool AddShaderAtPath(const std::string& path);
[[nodiscard]] bool AddShader(ArchiveShaderType type,
std::string name,
std::shared_ptr<fml::Mapping> mapping);
std::shared_ptr<fml::Mapping> CreateMapping() const;
private:
struct ShaderDescription {
ArchiveShaderType type;
std::string name;
std::shared_ptr<fml::Mapping> mapping;
};
std::vector<ShaderDescription> shader_descriptions_;
ShaderArchiveWriter(const ShaderArchiveWriter&) = delete;
ShaderArchiveWriter& operator=(const ShaderArchiveWriter&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_SHADER_ARCHIVE_SHADER_ARCHIVE_WRITER_H_
| engine/impeller/shader_archive/shader_archive_writer.h/0 | {
"file_path": "engine/impeller/shader_archive/shader_archive_writer.h",
"repo_id": "engine",
"token_count": 506
} | 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_IMPELLER_TOOLKIT_ANDROID_HARDWARE_BUFFER_H_
#define FLUTTER_IMPELLER_TOOLKIT_ANDROID_HARDWARE_BUFFER_H_
#include <optional>
#include "flutter/fml/unique_object.h"
#include "impeller/geometry/size.h"
#include "impeller/toolkit/android/proc_table.h"
namespace impeller::android {
enum class HardwareBufferFormat {
//----------------------------------------------------------------------------
/// This format is guaranteed to be supported on all versions of Android. This
/// format can also be converted to an Impeller and Vulkan format.
///
/// @see Vulkan Format: VK_FORMAT_R8G8B8A8_UNORM
/// @see OpenGL ES Format: GL_RGBA8
///
/// Why have many format when one format do trick?
///
kR8G8B8A8UNormInt,
};
using HardwareBufferUsage = uint8_t;
enum class HardwareBufferUsageFlags : HardwareBufferUsage {
kFrameBufferAttachment = 1u << 0u,
kCompositorOverlay = 1u << 1u,
kSampledImage = 1u << 2u,
};
//------------------------------------------------------------------------------
/// @brief A descriptor use to specify hardware buffer allocations.
///
struct HardwareBufferDescriptor {
HardwareBufferFormat format = HardwareBufferFormat::kR8G8B8A8UNormInt;
ISize size;
HardwareBufferUsage usage = 0u;
//----------------------------------------------------------------------------
/// @brief Create a descriptor of the given size that is suitable for use
/// as a swapchain image.
///
/// @warning Descriptors of zero size are not allocatable. The next best
/// valid size is picked. So make sure to check the actual size of
/// the descriptor after this call is made to determine the size
/// of the allocated hardware buffer.
///
/// @param[in] size The size. See the restrictions about valid sizes above.
///
/// @return The hardware buffer descriptor.
///
static HardwareBufferDescriptor MakeForSwapchainImage(const ISize& size);
//----------------------------------------------------------------------------
/// @brief If hardware buffers can be created using this descriptor.
/// Allocatable descriptors may still cause failing allocations in
/// case of resource exhaustion.
///
/// @return `true` if allocatable (unless resource exhaustion).
///
bool IsAllocatable() const;
constexpr bool operator==(const HardwareBufferDescriptor& o) const {
return format == o.format && size == o.size && usage == o.usage;
}
constexpr bool operator!=(const HardwareBufferDescriptor& o) const {
return !(*this == o);
}
};
//------------------------------------------------------------------------------
/// @brief A wrapper for AHardwareBuffer
/// https://developer.android.com/ndk/reference/group/a-hardware-buffer
///
/// This wrapper creates and owns a handle to a managed hardware
/// buffer. That is, there is no ability to take a reference to an
/// externally created hardware buffer.
///
/// This wrapper is only available on Android API 29 and above.
///
class HardwareBuffer {
public:
static bool IsAvailableOnPlatform();
explicit HardwareBuffer(HardwareBufferDescriptor descriptor);
~HardwareBuffer();
HardwareBuffer(const HardwareBuffer&) = delete;
HardwareBuffer& operator=(const HardwareBuffer&) = delete;
bool IsValid() const;
AHardwareBuffer* GetHandle() const;
const HardwareBufferDescriptor& GetDescriptor() const;
const AHardwareBuffer_Desc& GetAndroidDescriptor() const;
static std::optional<AHardwareBuffer_Desc> Describe(AHardwareBuffer* buffer);
//----------------------------------------------------------------------------
/// @brief Get the system wide unique ID of the hardware buffer if
/// possible. This is only available on Android API 31 and above.
/// Within the process, the handle are unique.
///
/// @return The system unique id if one can be obtained.
///
std::optional<uint64_t> GetSystemUniqueID() const;
//----------------------------------------------------------------------------
/// @brief Get the system wide unique ID of the hardware buffer if
/// possible. This is only available on Android API 31 and above.
/// Within the process, the handle are unique.
///
/// @return The system unique id if one can be obtained.
///
static std::optional<uint64_t> GetSystemUniqueID(AHardwareBuffer* buffer);
private:
struct UniqueAHardwareBufferTraits {
static AHardwareBuffer* InvalidValue() { return nullptr; }
static bool IsValid(AHardwareBuffer* value) {
return value != InvalidValue();
}
static void Free(AHardwareBuffer* value) {
GetProcTable().AHardwareBuffer_release(value);
}
};
const HardwareBufferDescriptor descriptor_;
const AHardwareBuffer_Desc android_descriptor_;
fml::UniqueObject<AHardwareBuffer*, UniqueAHardwareBufferTraits> buffer_;
bool is_valid_ = false;
};
} // namespace impeller::android
#endif // FLUTTER_IMPELLER_TOOLKIT_ANDROID_HARDWARE_BUFFER_H_
| engine/impeller/toolkit/android/hardware_buffer.h/0 | {
"file_path": "engine/impeller/toolkit/android/hardware_buffer.h",
"repo_id": "engine",
"token_count": 1614
} | 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_IMPELLER_TOOLKIT_EGL_DISPLAY_H_
#define FLUTTER_IMPELLER_TOOLKIT_EGL_DISPLAY_H_
#include <memory>
#include <optional>
#include "flutter/fml/macros.h"
#include "impeller/toolkit/egl/config.h"
#include "impeller/toolkit/egl/egl.h"
namespace impeller {
namespace egl {
class Context;
class Surface;
class Display {
public:
Display();
virtual ~Display();
virtual bool IsValid() const;
virtual std::unique_ptr<Config> ChooseConfig(ConfigDescriptor config) const;
virtual std::unique_ptr<Context> CreateContext(const Config& config,
const Context* share_context);
virtual std::unique_ptr<Surface> CreateWindowSurface(
const Config& config,
EGLNativeWindowType window);
virtual std::unique_ptr<Surface>
CreatePixelBufferSurface(const Config& config, size_t width, size_t height);
private:
EGLDisplay display_ = EGL_NO_DISPLAY;
Display(const Display&) = delete;
Display& operator=(const Display&) = delete;
};
} // namespace egl
} // namespace impeller
#endif // FLUTTER_IMPELLER_TOOLKIT_EGL_DISPLAY_H_
| engine/impeller/toolkit/egl/display.h/0 | {
"file_path": "engine/impeller/toolkit/egl/display.h",
"repo_id": "engine",
"token_count": 469
} | 229 |
{
"flutter/impeller/entity/advanced_blend.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/advanced_blend.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 2,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_fma"
],
"longest_path_cycles": [
0.578125,
0.578125,
0.21875,
0.125,
0.0,
0.5,
0.5
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_fma"
],
"shortest_path_cycles": [
0.53125,
0.53125,
0.203125,
0.0625,
0.0,
0.25,
0.25
],
"total_bound_pipelines": [
"arith_total",
"arith_fma"
],
"total_cycles": [
0.578125,
0.578125,
0.296875,
0.125,
0.0,
0.5,
0.5
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 12,
"work_registers_used": 25
}
}
}
},
"flutter/impeller/entity/advanced_blend.vert.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/advanced_blend.vert.vkspv",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.125,
0.125,
0.0,
0.0,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.125,
0.125,
0.0,
0.0,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.125,
0.125,
0.0,
0.0,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 30,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.03125,
0.03125,
0.03125,
0.0,
4.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.03125,
0.03125,
0.03125,
0.0,
4.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.03125,
0.03125,
0.03125,
0.0,
4.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 22,
"work_registers_used": 10
}
}
}
},
"flutter/impeller/entity/blend.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/blend.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 100,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"varying",
"texture"
],
"longest_path_cycles": [
0.03125,
0.03125,
0.0,
0.0,
0.0,
0.25,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying",
"texture"
],
"shortest_path_cycles": [
0.03125,
0.03125,
0.0,
0.0,
0.0,
0.25,
0.25
],
"total_bound_pipelines": [
"varying",
"texture"
],
"total_cycles": [
0.03125,
0.03125,
0.0,
0.0,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 4,
"work_registers_used": 4
}
}
}
},
"flutter/impeller/entity/blend.vert.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/blend.vert.vkspv",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.125,
0.125,
0.0,
0.0,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.125,
0.125,
0.0,
0.0,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.125,
0.125,
0.0,
0.0,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 30,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 22,
"work_registers_used": 8
}
}
}
},
"flutter/impeller/entity/border_mask_blur.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/border_mask_blur.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 44,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_fma"
],
"longest_path_cycles": [
0.875,
0.875,
0.203125,
0.25,
0.0,
0.25,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_fma"
],
"shortest_path_cycles": [
0.875,
0.875,
0.203125,
0.25,
0.0,
0.25,
0.25
],
"total_bound_pipelines": [
"arith_total",
"arith_fma"
],
"total_cycles": [
0.875,
0.875,
0.203125,
0.25,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 12,
"work_registers_used": 18
}
}
}
},
"flutter/impeller/entity/border_mask_blur.vert.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/border_mask_blur.vert.vkspv",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 24,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 20,
"work_registers_used": 8
}
}
}
},
"flutter/impeller/entity/checkerboard.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/checkerboard.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 80,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.125,
0.125,
0.125,
0.0625,
1.0,
0.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.125,
0.125,
0.125,
0.0625,
1.0,
0.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.125,
0.125,
0.125,
0.0625,
1.0,
0.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 6,
"work_registers_used": 7
}
}
}
},
"flutter/impeller/entity/checkerboard.vert.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/checkerboard.vert.vkspv",
"has_uniform_computation": false,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": null,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.0,
0.0,
0.0,
0.0,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.0,
0.0,
0.0,
0.0,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.0,
0.0,
0.0,
0.0,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 8,
"work_registers_used": 32
}
}
}
},
"flutter/impeller/entity/clip.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/clip.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": false,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": null,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"longest_path_cycles": [
0.015625,
0.0,
0.015625,
0.0,
0.0,
0.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"shortest_path_cycles": [
0.015625,
0.0,
0.015625,
0.0,
0.0,
0.0,
0.0
],
"total_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"total_cycles": [
0.015625,
0.0,
0.015625,
0.0,
0.0,
0.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 0,
"work_registers_used": 0
}
}
}
},
"flutter/impeller/entity/clip.vert.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/clip.vert.vkspv",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 24,
"work_registers_used": 32
}
}
}
},
"flutter/impeller/entity/color_matrix_color_filter.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/color_matrix_color_filter.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 100,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_fma",
"varying",
"texture"
],
"longest_path_cycles": [
0.25,
0.25,
0.0625,
0.0625,
0.0,
0.25,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_fma",
"varying",
"texture"
],
"shortest_path_cycles": [
0.25,
0.25,
0.0625,
0.0625,
0.0,
0.25,
0.25
],
"total_bound_pipelines": [
"arith_total",
"arith_fma",
"varying",
"texture"
],
"total_cycles": [
0.25,
0.25,
0.0625,
0.0625,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 14,
"work_registers_used": 10
}
}
}
},
"flutter/impeller/entity/color_matrix_color_filter.vert.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/color_matrix_color_filter.vert.vkspv",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 24,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 20,
"work_registers_used": 8
}
}
}
},
"flutter/impeller/entity/conical_gradient_fill.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/conical_gradient_fill.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 74,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"longest_path_cycles": [
0.800000011920929,
0.328125,
0.800000011920929,
0.0625,
0.0,
0.25,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.15625,
0.0,
0.15625,
0.0,
0.0,
0.25,
0.0
],
"total_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"total_cycles": [
1.1375000476837158,
0.699999988079071,
1.1375000476837158,
0.3125,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 40,
"work_registers_used": 9
}
}
}
},
"flutter/impeller/entity/conical_gradient_ssbo_fill.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/conical_gradient_ssbo_fill.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 68,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
null
],
"longest_path_cycles": [
null,
null,
null,
null,
null,
null,
null
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_sfu"
],
"shortest_path_cycles": [
0.5,
0.109375,
0.328125,
0.5,
0.0,
0.25,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
1.4500000476837158,
0.862500011920929,
1.4500000476837158,
0.875,
4.0,
0.25,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 46,
"work_registers_used": 20
}
}
}
},
"flutter/impeller/entity/gaussian_blur.vert.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gaussian_blur.vert.vkspv",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.125,
0.125,
0.0,
0.0,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.125,
0.125,
0.0,
0.0,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.125,
0.125,
0.0,
0.0,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 30,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 22,
"work_registers_used": 8
}
}
}
},
"flutter/impeller/entity/gaussian_blur_noalpha_decal.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gaussian_blur_noalpha_decal.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 42,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
null
],
"longest_path_cycles": [
null,
null,
null,
null,
null,
null,
null
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"shortest_path_cycles": [
0.109375,
0.03125,
0.109375,
0.0625,
0.0,
0.0,
0.0
],
"total_bound_pipelines": [
"arith_total",
"arith_cvt",
"arith_sfu"
],
"total_cycles": [
0.3125,
0.203125,
0.3125,
0.3125,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 10,
"work_registers_used": 16
}
}
}
},
"flutter/impeller/entity/gaussian_blur_noalpha_nodecal.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gaussian_blur_noalpha_nodecal.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 35,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
null
],
"longest_path_cycles": [
null,
null,
null,
null,
null,
null,
null
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"shortest_path_cycles": [
0.109375,
0.03125,
0.109375,
0.0625,
0.0,
0.0,
0.0
],
"total_bound_pipelines": [
"varying",
"texture"
],
"total_cycles": [
0.203125,
0.203125,
0.203125,
0.125,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 10,
"work_registers_used": 13
}
}
}
},
"flutter/impeller/entity/gles/advanced_blend.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/advanced_blend.frag.gles",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 2,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_fma"
],
"longest_path_cycles": [
0.578125,
0.578125,
0.265625,
0.125,
0.0,
0.5,
0.5
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_fma"
],
"shortest_path_cycles": [
0.53125,
0.53125,
0.21875,
0.0625,
0.0,
0.25,
0.25
],
"total_bound_pipelines": [
"arith_total",
"arith_fma"
],
"total_cycles": [
0.578125,
0.578125,
0.34375,
0.125,
0.0,
0.5,
0.5
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 14,
"work_registers_used": 23
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/advanced_blend.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic"
],
"longest_path_cycles": [
4.289999961853027,
2.0,
2.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic"
],
"shortest_path_cycles": [
3.299999952316284,
1.0,
1.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
4.666666507720947,
2.0,
2.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 2,
"work_registers_used": 4
}
}
}
},
"flutter/impeller/entity/gles/advanced_blend.vert.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/advanced_blend.vert.gles",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.140625,
0.140625,
0.0,
0.0,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.140625,
0.140625,
0.0,
0.0,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.140625,
0.140625,
0.0,
0.0,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 22,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.03125,
0.03125,
0.03125,
0.0,
4.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.03125,
0.03125,
0.03125,
0.0,
4.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.03125,
0.03125,
0.03125,
0.0,
4.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 10,
"work_registers_used": 10
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/advanced_blend.vert.gles",
"has_uniform_computation": false,
"type": "Vertex",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
3.299999952316284,
7.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
3.299999952316284,
7.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
3.3333332538604736,
7.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 6,
"work_registers_used": 3
}
}
}
},
"flutter/impeller/entity/gles/blend.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/blend.frag.gles",
"has_side_effects": false,
"has_uniform_computation": false,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 100,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"varying",
"texture"
],
"longest_path_cycles": [
0.03125,
0.03125,
0.03125,
0.0,
0.0,
0.25,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying",
"texture"
],
"shortest_path_cycles": [
0.03125,
0.03125,
0.0,
0.0,
0.0,
0.25,
0.25
],
"total_bound_pipelines": [
"varying",
"texture"
],
"total_cycles": [
0.03125,
0.03125,
0.03125,
0.0,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 4,
"work_registers_used": 19
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/blend.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic",
"load_store",
"texture"
],
"longest_path_cycles": [
1.0,
1.0,
1.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_cycles": [
1.0,
1.0,
1.0
],
"total_bound_pipelines": [
"load_store",
"texture"
],
"total_cycles": [
0.6666666865348816,
1.0,
1.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 1,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/blend.vert.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/blend.vert.gles",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.140625,
0.140625,
0.0,
0.0,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.140625,
0.140625,
0.0,
0.0,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.140625,
0.140625,
0.0,
0.0,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 22,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 10,
"work_registers_used": 8
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/blend.vert.gles",
"has_uniform_computation": false,
"type": "Vertex",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
2.9700000286102295,
5.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
2.9700000286102295,
5.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
3.0,
5.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 6,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/border_mask_blur.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/border_mask_blur.frag.gles",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 81,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_fma"
],
"longest_path_cycles": [
0.9375,
0.9375,
0.296875,
0.25,
0.0,
0.25,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_fma"
],
"shortest_path_cycles": [
0.9375,
0.9375,
0.265625,
0.25,
0.0,
0.25,
0.25
],
"total_bound_pipelines": [
"arith_total",
"arith_fma"
],
"total_cycles": [
0.9375,
0.9375,
0.296875,
0.25,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 10,
"work_registers_used": 29
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/border_mask_blur.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic"
],
"longest_path_cycles": [
8.579999923706055,
1.0,
1.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic"
],
"shortest_path_cycles": [
8.579999923706055,
1.0,
1.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
9.0,
1.0,
1.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 1,
"work_registers_used": 3
}
}
}
},
"flutter/impeller/entity/gles/border_mask_blur.vert.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/border_mask_blur.vert.gles",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 20,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 10,
"work_registers_used": 8
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/border_mask_blur.vert.gles",
"has_uniform_computation": false,
"type": "Vertex",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
2.9700000286102295,
5.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
2.9700000286102295,
5.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
3.0,
5.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 6,
"work_registers_used": 3
}
}
}
},
"flutter/impeller/entity/gles/checkerboard.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/checkerboard.frag.gles",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 27,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.234375,
0.234375,
0.171875,
0.0625,
1.0,
0.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.234375,
0.234375,
0.140625,
0.0625,
1.0,
0.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.234375,
0.234375,
0.171875,
0.0625,
1.0,
0.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 12,
"work_registers_used": 21
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/checkerboard.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic"
],
"longest_path_cycles": [
1.9800000190734863,
1.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic"
],
"shortest_path_cycles": [
1.9800000190734863,
1.0,
0.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
2.3333332538604736,
1.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 2,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/checkerboard.vert.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/checkerboard.vert.gles",
"has_uniform_computation": false,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": null,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.015625,
0.0,
0.015625,
0.0,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.015625,
0.0,
0.015625,
0.0,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.015625,
0.0,
0.015625,
0.0,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 8,
"work_registers_used": 32
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/checkerboard.vert.gles",
"has_uniform_computation": false,
"type": "Vertex",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
1.3200000524520874,
3.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
1.3200000524520874,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
1.3333333730697632,
3.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 2,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/clip.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/clip.frag.gles",
"has_side_effects": false,
"has_uniform_computation": false,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": null,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"longest_path_cycles": [
0.015625,
0.0,
0.015625,
0.0,
0.0,
0.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"shortest_path_cycles": [
0.015625,
0.0,
0.015625,
0.0,
0.0,
0.0,
0.0
],
"total_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"total_cycles": [
0.015625,
0.0,
0.015625,
0.0,
0.0,
0.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 0,
"work_registers_used": 1
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/clip.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic"
],
"longest_path_cycles": [
1.0,
0.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic"
],
"shortest_path_cycles": [
1.0,
0.0,
0.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
0.6666666865348816,
0.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 0,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/clip.vert.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/clip.vert.gles",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 18,
"work_registers_used": 32
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/clip.vert.gles",
"has_uniform_computation": false,
"type": "Vertex",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
2.640000104904175,
3.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
2.640000104904175,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
2.6666667461395264,
3.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 6,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/color_matrix_color_filter.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/color_matrix_color_filter.frag.gles",
"has_side_effects": false,
"has_uniform_computation": false,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 100,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_fma",
"varying",
"texture"
],
"longest_path_cycles": [
0.25,
0.25,
0.09375,
0.0625,
0.0,
0.25,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_fma",
"varying",
"texture"
],
"shortest_path_cycles": [
0.25,
0.25,
0.0625,
0.0625,
0.0,
0.25,
0.25
],
"total_bound_pipelines": [
"arith_total",
"arith_fma",
"varying",
"texture"
],
"total_cycles": [
0.25,
0.25,
0.09375,
0.0625,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 14,
"work_registers_used": 21
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/color_matrix_color_filter.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic"
],
"longest_path_cycles": [
2.640000104904175,
1.0,
1.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic"
],
"shortest_path_cycles": [
2.640000104904175,
1.0,
1.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
3.0,
1.0,
1.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 3,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/color_matrix_color_filter.vert.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/color_matrix_color_filter.vert.gles",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 20,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 10,
"work_registers_used": 8
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/color_matrix_color_filter.vert.gles",
"has_uniform_computation": false,
"type": "Vertex",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
2.9700000286102295,
4.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
2.9700000286102295,
4.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
3.0,
4.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 6,
"work_registers_used": 3
}
}
}
},
"flutter/impeller/entity/gles/conical_gradient_fill.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/conical_gradient_fill.frag.gles",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 52,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"longest_path_cycles": [
0.887499988079071,
0.4375,
0.887499988079071,
0.1875,
0.0,
0.25,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.171875,
0.0,
0.171875,
0.0,
0.0,
0.25,
0.0
],
"total_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"total_cycles": [
1.28125,
0.824999988079071,
1.28125,
0.4375,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 40,
"work_registers_used": 21
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/conical_gradient_fill.frag.gles",
"has_uniform_computation": true,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic"
],
"longest_path_cycles": [
12.869999885559082,
1.0,
1.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic"
],
"shortest_path_cycles": [
1.3200000524520874,
1.0,
0.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
19.66666603088379,
1.0,
1.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 6,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/gaussian_blur.vert.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/gaussian_blur.vert.gles",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.140625,
0.140625,
0.0,
0.0,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.140625,
0.140625,
0.0,
0.0,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.140625,
0.140625,
0.0,
0.0,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 22,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 10,
"work_registers_used": 8
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/gaussian_blur.vert.gles",
"has_uniform_computation": false,
"type": "Vertex",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
2.9700000286102295,
5.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
2.9700000286102295,
5.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
3.0,
5.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 6,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/gaussian_blur_noalpha_decal.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/gaussian_blur_noalpha_decal.frag.gles",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 70,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
null
],
"longest_path_cycles": [
null,
null,
null,
null,
null,
null,
null
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_cvt",
"arith_sfu"
],
"shortest_path_cycles": [
0.0625,
0.03125,
0.0625,
0.0625,
0.0,
0.0,
0.0
],
"total_bound_pipelines": [
"arith_total",
"arith_sfu"
],
"total_cycles": [
0.3125,
0.234375,
0.296875,
0.3125,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 8,
"work_registers_used": 19
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/gaussian_blur_noalpha_decal.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
null
],
"longest_path_cycles": [
null,
null,
null
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic"
],
"shortest_path_cycles": [
1.3200000524520874,
1.0,
0.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
4.666666507720947,
1.0,
1.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 1,
"work_registers_used": 3
}
}
}
},
"flutter/impeller/entity/gles/gaussian_blur_noalpha_nodecal.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/gaussian_blur_noalpha_nodecal.frag.gles",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 66,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
null
],
"longest_path_cycles": [
null,
null,
null,
null,
null,
null,
null
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_cvt",
"arith_sfu"
],
"shortest_path_cycles": [
0.0625,
0.03125,
0.0625,
0.0625,
0.0,
0.0,
0.0
],
"total_bound_pipelines": [
"varying",
"texture"
],
"total_cycles": [
0.234375,
0.234375,
0.1875,
0.125,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 8,
"work_registers_used": 19
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/gaussian_blur_noalpha_nodecal.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
null
],
"longest_path_cycles": [
null,
null,
null
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic"
],
"shortest_path_cycles": [
1.3200000524520874,
1.0,
0.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
3.3333332538604736,
1.0,
1.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 1,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/glyph_atlas.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/glyph_atlas.frag.gles",
"has_side_effects": false,
"has_uniform_computation": false,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 100,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"varying"
],
"longest_path_cycles": [
0.03125,
0.03125,
0.03125,
0.0,
0.0,
0.5,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.03125,
0.03125,
0.0,
0.0,
0.0,
0.5,
0.25
],
"total_bound_pipelines": [
"varying"
],
"total_cycles": [
0.03125,
0.03125,
0.03125,
0.0,
0.0,
0.5,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 4,
"work_registers_used": 19
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/glyph_atlas.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic",
"load_store",
"texture"
],
"longest_path_cycles": [
1.0,
1.0,
1.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_cycles": [
1.0,
1.0,
1.0
],
"total_bound_pipelines": [
"load_store",
"texture"
],
"total_cycles": [
0.6666666865348816,
1.0,
1.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 0,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/glyph_atlas.vert.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/glyph_atlas.vert.gles",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.5,
0.5,
0.140625,
0.0625,
4.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.46875,
0.46875,
0.03125,
0.0625,
4.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.71875,
0.71875,
0.15625,
0.0625,
4.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 44,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.15625,
0.15625,
0.0625,
0.0,
5.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.15625,
0.15625,
0.0625,
0.0,
5.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.15625,
0.15625,
0.0625,
0.0,
5.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 18,
"work_registers_used": 16
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/glyph_atlas.vert.gles",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
7.260000228881836,
8.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
6.269999980926514,
8.0,
0.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
9.333333015441895,
8.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 13,
"work_registers_used": 4
}
}
}
},
"flutter/impeller/entity/gles/glyph_atlas_color.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/glyph_atlas_color.frag.gles",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 100,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"varying"
],
"longest_path_cycles": [
0.0625,
0.0625,
0.0625,
0.0,
0.0,
0.5,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.0625,
0.0625,
0.03125,
0.0,
0.0,
0.5,
0.25
],
"total_bound_pipelines": [
"varying"
],
"total_cycles": [
0.0625,
0.0625,
0.0625,
0.0,
0.0,
0.5,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 4,
"work_registers_used": 19
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/glyph_atlas_color.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic",
"load_store",
"texture"
],
"longest_path_cycles": [
1.0,
1.0,
1.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_cycles": [
1.0,
1.0,
1.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
1.3333333730697632,
1.0,
1.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 1,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/gradient_fill.vert.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/gradient_fill.vert.gles",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 28,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.125,
0.125,
0.0,
0.0625,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.125,
0.125,
0.0,
0.0625,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.125,
0.125,
0.0,
0.0625,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 18,
"work_registers_used": 11
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/gradient_fill.vert.gles",
"has_uniform_computation": false,
"type": "Vertex",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
3.630000114440918,
4.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
3.630000114440918,
4.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
3.6666667461395264,
4.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 9,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/kernel_decal.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/kernel_decal.frag.gles",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 66,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
null
],
"longest_path_cycles": [
null,
null,
null,
null,
null,
null,
null
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"shortest_path_cycles": [
0.078125,
0.0,
0.078125,
0.0,
0.0,
0.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.359375,
0.0625,
0.359375,
0.1875,
2.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 4,
"work_registers_used": 19
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/kernel_decal.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
null
],
"longest_path_cycles": [
null,
null,
null
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic",
"load_store"
],
"shortest_path_cycles": [
1.0,
1.0,
0.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
3.6666667461395264,
3.0,
1.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 1,
"work_registers_used": 3
}
}
}
},
"flutter/impeller/entity/gles/kernel_nodecal.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/kernel_nodecal.frag.gles",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 50,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
null
],
"longest_path_cycles": [
null,
null,
null,
null,
null,
null,
null
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"shortest_path_cycles": [
0.078125,
0.0,
0.078125,
0.0,
0.0,
0.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.25,
0.0625,
0.25,
0.0,
2.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 4,
"work_registers_used": 19
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/kernel_nodecal.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
null
],
"longest_path_cycles": [
null,
null,
null
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic",
"load_store"
],
"shortest_path_cycles": [
1.0,
1.0,
0.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
2.3333332538604736,
2.0,
1.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 1,
"work_registers_used": 3
}
}
}
},
"flutter/impeller/entity/gles/linear_gradient_fill.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/linear_gradient_fill.frag.gles",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 52,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"longest_path_cycles": [
0.390625,
0.296875,
0.390625,
0.125,
0.0,
0.25,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.203125,
0.1875,
0.203125,
0.125,
0.0,
0.25,
0.0
],
"total_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"total_cycles": [
0.515625,
0.328125,
0.515625,
0.125,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 16,
"work_registers_used": 20
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/linear_gradient_fill.frag.gles",
"has_uniform_computation": true,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic"
],
"longest_path_cycles": [
6.929999828338623,
1.0,
1.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic"
],
"shortest_path_cycles": [
2.309999942779541,
1.0,
0.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
7.666666507720947,
1.0,
1.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 4,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/linear_to_srgb_filter.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/linear_to_srgb_filter.frag.gles",
"has_side_effects": false,
"has_uniform_computation": false,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 40,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_cvt",
"arith_sfu"
],
"longest_path_cycles": [
0.4375,
0.328125,
0.4375,
0.4375,
0.0,
0.25,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_sfu"
],
"shortest_path_cycles": [
0.4375,
0.328125,
0.40625,
0.4375,
0.0,
0.25,
0.25
],
"total_bound_pipelines": [
"arith_total",
"arith_cvt",
"arith_sfu"
],
"total_cycles": [
0.4375,
0.328125,
0.4375,
0.4375,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 10,
"work_registers_used": 30
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/linear_to_srgb_filter.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic"
],
"longest_path_cycles": [
4.949999809265137,
1.0,
1.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic"
],
"shortest_path_cycles": [
4.949999809265137,
1.0,
1.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
5.333333492279053,
1.0,
1.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 1,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/linear_to_srgb_filter.vert.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/linear_to_srgb_filter.vert.gles",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 20,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 10,
"work_registers_used": 8
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/linear_to_srgb_filter.vert.gles",
"has_uniform_computation": false,
"type": "Vertex",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
2.9700000286102295,
4.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
2.9700000286102295,
4.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
3.0,
4.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 6,
"work_registers_used": 3
}
}
}
},
"flutter/impeller/entity/gles/morphology_filter.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/morphology_filter.frag.gles",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 80,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
null
],
"longest_path_cycles": [
null,
null,
null,
null,
null,
null,
null
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"shortest_path_cycles": [
0.0625,
0.0,
0.0625,
0.0,
0.0,
0.0,
0.0
],
"total_bound_pipelines": [
"varying",
"texture"
],
"total_cycles": [
0.234375,
0.078125,
0.234375,
0.0,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 8,
"work_registers_used": 21
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/morphology_filter.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
null
],
"longest_path_cycles": [
null,
null,
null
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic",
"load_store"
],
"shortest_path_cycles": [
1.0,
1.0,
0.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
2.6666667461395264,
1.0,
1.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 1,
"work_registers_used": 4
}
}
}
},
"flutter/impeller/entity/gles/morphology_filter.vert.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/morphology_filter.vert.gles",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.140625,
0.140625,
0.0,
0.0,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.140625,
0.140625,
0.0,
0.0,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.140625,
0.140625,
0.0,
0.0,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 22,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 10,
"work_registers_used": 8
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/morphology_filter.vert.gles",
"has_uniform_computation": false,
"type": "Vertex",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
2.9700000286102295,
5.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
2.9700000286102295,
5.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
3.0,
5.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 6,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/porter_duff_blend.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/porter_duff_blend.frag.gles",
"has_side_effects": false,
"has_uniform_computation": false,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 71,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"varying"
],
"longest_path_cycles": [
0.21875,
0.21875,
0.03125,
0.0,
0.0,
0.5,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.21875,
0.21875,
0.0,
0.0,
0.0,
0.5,
0.25
],
"total_bound_pipelines": [
"varying"
],
"total_cycles": [
0.21875,
0.21875,
0.03125,
0.0,
0.0,
0.5,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 8,
"work_registers_used": 19
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/porter_duff_blend.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic"
],
"longest_path_cycles": [
1.649999976158142,
1.0,
1.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic"
],
"shortest_path_cycles": [
1.649999976158142,
1.0,
1.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
2.0,
1.0,
1.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 1,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/porter_duff_blend.vert.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/porter_duff_blend.vert.gles",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 20,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
5.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
5.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
5.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 10,
"work_registers_used": 12
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/porter_duff_blend.vert.gles",
"has_uniform_computation": false,
"type": "Vertex",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
2.9700000286102295,
7.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
2.9700000286102295,
7.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
3.0,
7.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 6,
"work_registers_used": 3
}
}
}
},
"flutter/impeller/entity/gles/position_color.vert.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/position_color.vert.gles",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 18,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": null,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.0,
0.0,
0.0,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.0,
0.0,
0.0,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.0,
0.0,
0.0,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 10,
"work_registers_used": 9
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/position_color.vert.gles",
"has_uniform_computation": false,
"type": "Vertex",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
2.640000104904175,
5.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
2.640000104904175,
5.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
2.6666667461395264,
5.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 6,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/radial_gradient_fill.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/radial_gradient_fill.frag.gles",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 44,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"longest_path_cycles": [
0.421875,
0.3125,
0.421875,
0.1875,
0.0,
0.25,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.234375,
0.203125,
0.234375,
0.1875,
0.0,
0.25,
0.0
],
"total_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"total_cycles": [
0.546875,
0.34375,
0.546875,
0.1875,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 14,
"work_registers_used": 20
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/radial_gradient_fill.frag.gles",
"has_uniform_computation": true,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic"
],
"longest_path_cycles": [
6.929999828338623,
1.0,
1.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic"
],
"shortest_path_cycles": [
2.309999942779541,
1.0,
0.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
7.666666507720947,
1.0,
1.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 3,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/rrect_blur.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/rrect_blur.frag.gles",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_fma"
],
"longest_path_cycles": [
1.65625,
1.65625,
0.453125,
1.5,
0.0,
0.25,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_fma"
],
"shortest_path_cycles": [
1.65625,
1.65625,
0.421875,
1.5,
0.0,
0.25,
0.0
],
"total_bound_pipelines": [
"arith_total",
"arith_fma"
],
"total_cycles": [
1.65625,
1.65625,
0.453125,
1.5,
0.0,
0.25,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 22,
"work_registers_used": 32
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/rrect_blur.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic"
],
"longest_path_cycles": [
25.739999771118164,
1.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic"
],
"shortest_path_cycles": [
25.739999771118164,
1.0,
0.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
8.333333015441895,
1.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 3,
"work_registers_used": 4
}
}
}
},
"flutter/impeller/entity/gles/rrect_blur.vert.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/rrect_blur.vert.gles",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 18,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": null,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.0,
0.0,
0.0,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.0,
0.0,
0.0,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.0,
0.0,
0.0,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 10,
"work_registers_used": 7
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/rrect_blur.vert.gles",
"has_uniform_computation": false,
"type": "Vertex",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
2.9700000286102295,
4.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
2.9700000286102295,
4.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
3.0,
4.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 6,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/runtime_effect.vert.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/runtime_effect.vert.gles",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 18,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": null,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.0,
0.0,
0.0,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.0,
0.0,
0.0,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.0,
0.0,
0.0,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 10,
"work_registers_used": 7
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/runtime_effect.vert.gles",
"has_uniform_computation": false,
"type": "Vertex",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
2.9700000286102295,
4.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
2.9700000286102295,
4.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
3.0,
4.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 6,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/solid_fill.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/solid_fill.frag.gles",
"has_side_effects": false,
"has_uniform_computation": false,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": null,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"varying"
],
"longest_path_cycles": [
0.03125,
0.0,
0.03125,
0.0,
0.0,
0.25,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.25,
0.0
],
"total_bound_pipelines": [
"varying"
],
"total_cycles": [
0.03125,
0.0,
0.03125,
0.0,
0.0,
0.25,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 0,
"work_registers_used": 19
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/solid_fill.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic",
"load_store"
],
"longest_path_cycles": [
1.0,
1.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic",
"load_store"
],
"shortest_path_cycles": [
1.0,
1.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.6666666865348816,
1.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 0,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/solid_fill.vert.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/solid_fill.vert.gles",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 22,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": null,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.0625,
0.0,
0.0625,
0.0,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.0625,
0.0,
0.0625,
0.0,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.0625,
0.0,
0.0625,
0.0,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 14,
"work_registers_used": 7
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/solid_fill.vert.gles",
"has_uniform_computation": false,
"type": "Vertex",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
2.9700000286102295,
4.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
2.9700000286102295,
4.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
3.0,
4.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 7,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/srgb_to_linear_filter.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/srgb_to_linear_filter.frag.gles",
"has_side_effects": false,
"has_uniform_computation": false,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 40,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"longest_path_cycles": [
0.484375,
0.328125,
0.484375,
0.4375,
0.0,
0.25,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"shortest_path_cycles": [
0.453125,
0.328125,
0.453125,
0.4375,
0.0,
0.25,
0.25
],
"total_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"total_cycles": [
0.484375,
0.328125,
0.484375,
0.4375,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 10,
"work_registers_used": 28
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/srgb_to_linear_filter.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic"
],
"longest_path_cycles": [
4.949999809265137,
1.0,
1.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic"
],
"shortest_path_cycles": [
4.949999809265137,
1.0,
1.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
5.333333492279053,
1.0,
1.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 1,
"work_registers_used": 3
}
}
}
},
"flutter/impeller/entity/gles/srgb_to_linear_filter.vert.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/srgb_to_linear_filter.vert.gles",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 20,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 10,
"work_registers_used": 8
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/srgb_to_linear_filter.vert.gles",
"has_uniform_computation": false,
"type": "Vertex",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
2.9700000286102295,
4.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
2.9700000286102295,
4.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
3.0,
4.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 6,
"work_registers_used": 3
}
}
}
},
"flutter/impeller/entity/gles/sweep_gradient_fill.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/sweep_gradient_fill.frag.gles",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 34,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_fma",
"arith_cvt"
],
"longest_path_cycles": [
0.46875,
0.46875,
0.46875,
0.375,
0.0,
0.25,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_sfu"
],
"shortest_path_cycles": [
0.375,
0.359375,
0.25,
0.375,
0.0,
0.25,
0.0
],
"total_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"total_cycles": [
0.5625,
0.5,
0.5625,
0.375,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 20,
"work_registers_used": 24
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/sweep_gradient_fill.frag.gles",
"has_uniform_computation": true,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic"
],
"longest_path_cycles": [
7.920000076293945,
1.0,
1.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic"
],
"shortest_path_cycles": [
2.9700000286102295,
1.0,
0.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
8.666666984558105,
1.0,
1.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 4,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/texture_fill.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/texture_fill.frag.gles",
"has_side_effects": false,
"has_uniform_computation": false,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 100,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"varying"
],
"longest_path_cycles": [
0.046875,
0.03125,
0.046875,
0.0,
0.0,
0.375,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.03125,
0.03125,
0.015625,
0.0,
0.0,
0.375,
0.25
],
"total_bound_pipelines": [
"varying"
],
"total_cycles": [
0.046875,
0.03125,
0.046875,
0.0,
0.0,
0.375,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 2,
"work_registers_used": 19
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/texture_fill.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic",
"load_store",
"texture"
],
"longest_path_cycles": [
1.0,
1.0,
1.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_cycles": [
1.0,
1.0,
1.0
],
"total_bound_pipelines": [
"load_store",
"texture"
],
"total_cycles": [
0.6666666865348816,
1.0,
1.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 0,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/texture_fill.vert.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/texture_fill.vert.gles",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 20,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.03125,
0.015625,
0.03125,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.03125,
0.015625,
0.03125,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.03125,
0.015625,
0.03125,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 12,
"work_registers_used": 8
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/texture_fill.vert.gles",
"has_uniform_computation": false,
"type": "Vertex",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
2.9700000286102295,
6.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
2.9700000286102295,
6.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
3.0,
6.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 6,
"work_registers_used": 3
}
}
}
},
"flutter/impeller/entity/gles/texture_fill_external.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/texture_fill_external.frag.gles",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"varying"
],
"longest_path_cycles": [
0.203125,
0.203125,
0.03125,
0.0,
0.0,
0.375,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.203125,
0.203125,
0.0,
0.0,
0.0,
0.375,
0.25
],
"total_bound_pipelines": [
"varying"
],
"total_cycles": [
0.203125,
0.203125,
0.03125,
0.0,
0.0,
0.375,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 14,
"work_registers_used": 19
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/texture_fill_external.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic"
],
"longest_path_cycles": [
1.649999976158142,
1.0,
1.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic"
],
"shortest_path_cycles": [
1.649999976158142,
1.0,
1.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
2.0,
1.0,
1.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 2,
"work_registers_used": 3
}
}
}
},
"flutter/impeller/entity/gles/texture_fill_strict_src.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/texture_fill_strict_src.frag.gles",
"has_side_effects": false,
"has_uniform_computation": false,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 33,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"varying"
],
"longest_path_cycles": [
0.109375,
0.03125,
0.109375,
0.0,
0.0,
0.375,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.078125,
0.03125,
0.078125,
0.0,
0.0,
0.375,
0.25
],
"total_bound_pipelines": [
"varying"
],
"total_cycles": [
0.109375,
0.03125,
0.109375,
0.0,
0.0,
0.375,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 4,
"work_registers_used": 20
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/texture_fill_strict_src.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic",
"load_store",
"texture"
],
"longest_path_cycles": [
1.0,
1.0,
1.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_cycles": [
1.0,
1.0,
1.0
],
"total_bound_pipelines": [
"arithmetic",
"load_store",
"texture"
],
"total_cycles": [
1.0,
1.0,
1.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 1,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/tiled_texture_fill.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/tiled_texture_fill.frag.gles",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 33,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"varying"
],
"longest_path_cycles": [
0.25,
0.03125,
0.25,
0.0,
0.0,
0.375,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.046875,
0.03125,
0.046875,
0.0,
0.0,
0.375,
0.25
],
"total_bound_pipelines": [
"varying"
],
"total_cycles": [
0.25,
0.03125,
0.25,
0.0,
0.0,
0.375,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 4,
"work_registers_used": 19
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/tiled_texture_fill.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic"
],
"longest_path_cycles": [
3.299999952316284,
2.0,
1.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
1.3200000524520874,
2.0,
0.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
3.6666667461395264,
2.0,
1.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 1,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/tiled_texture_fill_external.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/tiled_texture_fill_external.frag.gles",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 70,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"longest_path_cycles": [
0.421875,
0.328125,
0.421875,
0.0,
0.0,
0.25,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.09375,
0.03125,
0.09375,
0.0,
0.0,
0.25,
0.0
],
"total_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"total_cycles": [
0.515625,
0.359375,
0.515625,
0.0,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 20,
"work_registers_used": 22
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/tiled_texture_fill_external.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic"
],
"longest_path_cycles": [
7.920000076293945,
2.0,
1.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
1.3200000524520874,
2.0,
0.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
9.0,
2.0,
1.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 2,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/vertices.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/vertices.frag.gles",
"has_side_effects": false,
"has_uniform_computation": false,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 100,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"varying"
],
"longest_path_cycles": [
0.03125,
0.03125,
0.03125,
0.0,
0.0,
0.25,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.03125,
0.03125,
0.0,
0.0,
0.0,
0.25,
0.0
],
"total_bound_pipelines": [
"varying"
],
"total_cycles": [
0.03125,
0.03125,
0.03125,
0.0,
0.0,
0.25,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 2,
"work_registers_used": 19
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/vertices.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic",
"load_store"
],
"longest_path_cycles": [
1.0,
1.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic",
"load_store"
],
"shortest_path_cycles": [
1.0,
1.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.6666666865348816,
1.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 1,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/yuv_to_rgb_filter.frag.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/yuv_to_rgb_filter.frag.gles",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 100,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"texture"
],
"longest_path_cycles": [
0.15625,
0.15625,
0.046875,
0.0,
0.0,
0.25,
0.5
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"texture"
],
"shortest_path_cycles": [
0.15625,
0.15625,
0.015625,
0.0,
0.0,
0.25,
0.5
],
"total_bound_pipelines": [
"texture"
],
"total_cycles": [
0.15625,
0.15625,
0.046875,
0.0,
0.0,
0.25,
0.5
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 12,
"work_registers_used": 19
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/yuv_to_rgb_filter.frag.gles",
"has_uniform_computation": false,
"type": "Fragment",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arithmetic"
],
"longest_path_cycles": [
2.309999942779541,
1.0,
2.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arithmetic"
],
"shortest_path_cycles": [
2.309999942779541,
1.0,
2.0
],
"total_bound_pipelines": [
"arithmetic"
],
"total_cycles": [
2.6666667461395264,
1.0,
2.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 3,
"work_registers_used": 2
}
}
}
},
"flutter/impeller/entity/gles/yuv_to_rgb_filter.vert.gles": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gles/yuv_to_rgb_filter.vert.gles",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.15625,
0.15625,
0.0,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 20,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 10,
"work_registers_used": 8
}
}
},
"Mali-T880": {
"core": "Mali-T880",
"filename": "flutter/impeller/entity/gles/yuv_to_rgb_filter.vert.gles",
"has_uniform_computation": false,
"type": "Vertex",
"variants": {
"Main": {
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
2.9700000286102295,
4.0,
0.0
],
"pipelines": [
"arithmetic",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
2.9700000286102295,
4.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
3.0,
4.0,
0.0
]
},
"thread_occupancy": 100,
"uniform_registers_used": 6,
"work_registers_used": 3
}
}
}
},
"flutter/impeller/entity/glyph_atlas.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/glyph_atlas.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": false,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 100,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"varying"
],
"longest_path_cycles": [
0.03125,
0.03125,
0.0,
0.0,
0.0,
0.5,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.03125,
0.03125,
0.0,
0.0,
0.0,
0.5,
0.25
],
"total_bound_pipelines": [
"varying"
],
"total_cycles": [
0.03125,
0.03125,
0.0,
0.0,
0.0,
0.5,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 4,
"work_registers_used": 6
}
}
}
},
"flutter/impeller/entity/glyph_atlas.vert.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/glyph_atlas.vert.vkspv",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.484375,
0.484375,
0.15625,
0.0625,
4.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.453125,
0.453125,
0.046875,
0.0625,
4.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.699999988079071,
0.699999988079071,
0.171875,
0.0625,
4.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 52,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.15625,
0.15625,
0.0625,
0.0,
5.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.15625,
0.15625,
0.0625,
0.0,
5.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.15625,
0.15625,
0.0625,
0.0,
5.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 44,
"work_registers_used": 13
}
}
}
},
"flutter/impeller/entity/glyph_atlas_color.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/glyph_atlas_color.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 100,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"varying"
],
"longest_path_cycles": [
0.0625,
0.0625,
0.03125,
0.0,
0.0,
0.5,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.0625,
0.0625,
0.03125,
0.0,
0.0,
0.5,
0.25
],
"total_bound_pipelines": [
"varying"
],
"total_cycles": [
0.0625,
0.0625,
0.03125,
0.0,
0.0,
0.5,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 4,
"work_registers_used": 8
}
}
}
},
"flutter/impeller/entity/gradient_fill.vert.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/gradient_fill.vert.vkspv",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 40,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.125,
0.125,
0.0,
0.0625,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.125,
0.125,
0.0,
0.0625,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.125,
0.125,
0.0,
0.0625,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 34,
"work_registers_used": 11
}
}
}
},
"flutter/impeller/entity/kernel_decal.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/kernel_decal.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 66,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
null
],
"longest_path_cycles": [
null,
null,
null,
null,
null,
null,
null
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"shortest_path_cycles": [
0.09375,
0.0,
0.09375,
0.0,
0.0,
0.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.34375,
0.0625,
0.34375,
0.1875,
1.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 4,
"work_registers_used": 17
}
}
}
},
"flutter/impeller/entity/kernel_nodecal.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/kernel_nodecal.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 50,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
null
],
"longest_path_cycles": [
null,
null,
null,
null,
null,
null,
null
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"shortest_path_cycles": [
0.09375,
0.0,
0.09375,
0.0,
0.0,
0.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.21875,
0.0625,
0.21875,
0.0,
1.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 4,
"work_registers_used": 11
}
}
}
},
"flutter/impeller/entity/linear_gradient_fill.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/linear_gradient_fill.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 90,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_cvt",
"varying",
"texture"
],
"longest_path_cycles": [
0.25,
0.234375,
0.25,
0.0,
0.0,
0.25,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.140625,
0.140625,
0.140625,
0.0,
0.0,
0.25,
0.0
],
"total_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"total_cycles": [
0.34375,
0.265625,
0.34375,
0.0,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 16,
"work_registers_used": 7
}
}
}
},
"flutter/impeller/entity/linear_gradient_ssbo_fill.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/linear_gradient_ssbo_fill.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 35,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
null
],
"longest_path_cycles": [
null,
null,
null,
null,
null,
null,
null
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_sfu"
],
"shortest_path_cycles": [
0.5625,
0.203125,
0.296875,
0.5625,
0.0,
0.25,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.78125,
0.421875,
0.78125,
0.625,
4.0,
0.25,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 24,
"work_registers_used": 20
}
}
}
},
"flutter/impeller/entity/linear_to_srgb_filter.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/linear_to_srgb_filter.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 20,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_sfu"
],
"longest_path_cycles": [
0.4375,
0.296875,
0.359375,
0.4375,
0.0,
0.25,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying",
"texture"
],
"shortest_path_cycles": [
0.234375,
0.203125,
0.234375,
0.1875,
0.0,
0.25,
0.25
],
"total_bound_pipelines": [
"arith_total",
"arith_sfu"
],
"total_cycles": [
0.4375,
0.328125,
0.359375,
0.4375,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 10,
"work_registers_used": 12
}
}
}
},
"flutter/impeller/entity/linear_to_srgb_filter.vert.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/linear_to_srgb_filter.vert.vkspv",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 24,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 20,
"work_registers_used": 8
}
}
}
},
"flutter/impeller/entity/morphology_filter.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/morphology_filter.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 44,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
null
],
"longest_path_cycles": [
null,
null,
null,
null,
null,
null,
null
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"shortest_path_cycles": [
0.109375,
0.0,
0.109375,
0.0,
0.0,
0.0,
0.0
],
"total_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"total_cycles": [
0.265625,
0.046875,
0.265625,
0.0,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 8,
"work_registers_used": 11
}
}
}
},
"flutter/impeller/entity/morphology_filter.vert.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/morphology_filter.vert.vkspv",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.125,
0.125,
0.0,
0.0,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.125,
0.125,
0.0,
0.0,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.125,
0.125,
0.0,
0.0,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 30,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 22,
"work_registers_used": 8
}
}
}
},
"flutter/impeller/entity/points.comp.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/points.comp.vkspv",
"has_uniform_computation": true,
"type": "Compute",
"variants": {
"Main": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
null
],
"longest_path_cycles": [
null,
null,
null,
null,
null,
null
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"shortest_path_cycles": [
0.046875,
0.0,
0.046875,
0.0,
0.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.296875,
0.296875,
0.28125,
0.1875,
5.0,
0.0
]
},
"shared_storage_used": 0,
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 20,
"work_registers_used": 16
}
}
}
},
"flutter/impeller/entity/porter_duff_blend.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/porter_duff_blend.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 100,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"varying"
],
"longest_path_cycles": [
0.21875,
0.21875,
0.0,
0.0,
0.0,
0.5,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.21875,
0.21875,
0.0,
0.0,
0.0,
0.5,
0.25
],
"total_bound_pipelines": [
"varying"
],
"total_cycles": [
0.21875,
0.21875,
0.0,
0.0,
0.0,
0.5,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 14,
"work_registers_used": 11
}
}
}
},
"flutter/impeller/entity/porter_duff_blend.vert.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/porter_duff_blend.vert.vkspv",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 24,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
5.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
5.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
5.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 20,
"work_registers_used": 10
}
}
}
},
"flutter/impeller/entity/position_color.vert.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/position_color.vert.vkspv",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 24,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": null,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.0,
0.0,
0.0,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.0,
0.0,
0.0,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.0,
0.0,
0.0,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 18,
"work_registers_used": 9
}
}
}
},
"flutter/impeller/entity/radial_gradient_fill.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/radial_gradient_fill.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 64,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"longest_path_cycles": [
0.28125,
0.25,
0.28125,
0.0625,
0.0,
0.25,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.171875,
0.15625,
0.171875,
0.0625,
0.0,
0.25,
0.0
],
"total_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"total_cycles": [
0.375,
0.28125,
0.375,
0.0625,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 16,
"work_registers_used": 7
}
}
}
},
"flutter/impeller/entity/radial_gradient_ssbo_fill.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/radial_gradient_ssbo_fill.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 54,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
null
],
"longest_path_cycles": [
null,
null,
null,
null,
null,
null,
null
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_sfu"
],
"shortest_path_cycles": [
0.5625,
0.21875,
0.3125,
0.5625,
0.0,
0.25,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.75,
0.421875,
0.75,
0.625,
4.0,
0.25,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 22,
"work_registers_used": 20
}
}
}
},
"flutter/impeller/entity/rrect_blur.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/rrect_blur.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_fma"
],
"longest_path_cycles": [
1.65625,
1.65625,
0.421875,
1.5,
0.0,
0.25,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_fma"
],
"shortest_path_cycles": [
1.65625,
1.65625,
0.421875,
1.5,
0.0,
0.25,
0.0
],
"total_bound_pipelines": [
"arith_total",
"arith_fma"
],
"total_cycles": [
1.65625,
1.65625,
0.421875,
1.5,
0.0,
0.25,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 22,
"work_registers_used": 32
}
}
}
},
"flutter/impeller/entity/rrect_blur.vert.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/rrect_blur.vert.vkspv",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 24,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": null,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.0,
0.0,
0.0,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.0,
0.0,
0.0,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.0,
0.0,
0.0,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 18,
"work_registers_used": 7
}
}
}
},
"flutter/impeller/entity/runtime_effect.vert.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/runtime_effect.vert.vkspv",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 24,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": null,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.0,
0.0,
0.0,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.0,
0.0,
0.0,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.0,
0.0,
0.0,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 18,
"work_registers_used": 7
}
}
}
},
"flutter/impeller/entity/solid_fill.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/solid_fill.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": false,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": null,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"varying"
],
"longest_path_cycles": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.25,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.25,
0.0
],
"total_bound_pipelines": [
"varying"
],
"total_cycles": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.25,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 0,
"work_registers_used": 3
}
}
}
},
"flutter/impeller/entity/solid_fill.vert.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/solid_fill.vert.vkspv",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 28,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": null,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.0625,
0.0,
0.0625,
0.0,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.0625,
0.0,
0.0625,
0.0,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.0625,
0.0,
0.0625,
0.0,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 22,
"work_registers_used": 7
}
}
}
},
"flutter/impeller/entity/srgb_to_linear_filter.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/srgb_to_linear_filter.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 20,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_sfu"
],
"longest_path_cycles": [
0.4375,
0.28125,
0.390625,
0.4375,
0.0,
0.25,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying",
"texture"
],
"shortest_path_cycles": [
0.15625,
0.140625,
0.15625,
0.0625,
0.0,
0.25,
0.25
],
"total_bound_pipelines": [
"arith_total",
"arith_sfu"
],
"total_cycles": [
0.4375,
0.328125,
0.390625,
0.4375,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 10,
"work_registers_used": 9
}
}
}
},
"flutter/impeller/entity/srgb_to_linear_filter.vert.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/srgb_to_linear_filter.vert.vkspv",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 24,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 20,
"work_registers_used": 8
}
}
}
},
"flutter/impeller/entity/sweep_gradient_fill.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/sweep_gradient_fill.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 34,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_fma"
],
"longest_path_cycles": [
0.421875,
0.421875,
0.3125,
0.25,
0.0,
0.25,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_fma"
],
"shortest_path_cycles": [
0.328125,
0.328125,
0.203125,
0.25,
0.0,
0.25,
0.0
],
"total_bound_pipelines": [
"arith_total",
"arith_fma"
],
"total_cycles": [
0.453125,
0.453125,
0.40625,
0.25,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 20,
"work_registers_used": 13
}
}
}
},
"flutter/impeller/entity/sweep_gradient_ssbo_fill.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/sweep_gradient_ssbo_fill.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
null
],
"longest_path_cycles": [
null,
null,
null,
null,
null,
null,
null
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_sfu"
],
"shortest_path_cycles": [
0.8125,
0.421875,
0.359375,
0.8125,
0.0,
0.25,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.875,
0.6875,
0.800000011920929,
0.875,
4.0,
0.25,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 28,
"work_registers_used": 23
}
}
}
},
"flutter/impeller/entity/texture_fill.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/texture_fill.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": false,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 100,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"varying"
],
"longest_path_cycles": [
0.03125,
0.03125,
0.015625,
0.0,
0.0,
0.375,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.03125,
0.03125,
0.015625,
0.0,
0.0,
0.375,
0.25
],
"total_bound_pipelines": [
"varying"
],
"total_cycles": [
0.03125,
0.03125,
0.015625,
0.0,
0.0,
0.375,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 2,
"work_registers_used": 6
}
}
}
},
"flutter/impeller/entity/texture_fill.vert.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/texture_fill.vert.vkspv",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 24,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.046875,
0.015625,
0.046875,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.046875,
0.015625,
0.046875,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.046875,
0.015625,
0.046875,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 20,
"work_registers_used": 10
}
}
}
},
"flutter/impeller/entity/texture_fill_external.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/texture_fill_external.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": false,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"varying"
],
"longest_path_cycles": [
0.0625,
0.0625,
0.0,
0.0,
0.0,
0.375,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.0625,
0.0625,
0.0,
0.0,
0.0,
0.375,
0.25
],
"total_bound_pipelines": [
"varying"
],
"total_cycles": [
0.0625,
0.0625,
0.0,
0.0,
0.0,
0.375,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 4,
"work_registers_used": 10
}
}
}
},
"flutter/impeller/entity/texture_fill_strict_src.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/texture_fill_strict_src.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 33,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"varying"
],
"longest_path_cycles": [
0.078125,
0.03125,
0.078125,
0.0,
0.0,
0.375,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.078125,
0.03125,
0.078125,
0.0,
0.0,
0.375,
0.25
],
"total_bound_pipelines": [
"varying"
],
"total_cycles": [
0.078125,
0.03125,
0.078125,
0.0,
0.0,
0.375,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 6,
"work_registers_used": 6
}
}
}
},
"flutter/impeller/entity/tiled_texture_fill.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/tiled_texture_fill.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 33,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"varying"
],
"longest_path_cycles": [
0.25,
0.03125,
0.25,
0.0625,
0.0,
0.375,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.140625,
0.03125,
0.140625,
0.0625,
0.0,
0.375,
0.0
],
"total_bound_pipelines": [
"varying"
],
"total_cycles": [
0.25,
0.03125,
0.25,
0.0625,
0.0,
0.375,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 4,
"work_registers_used": 8
}
}
}
},
"flutter/impeller/entity/tiled_texture_fill_external.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/tiled_texture_fill_external.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 100,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"longest_path_cycles": [
0.328125,
0.1875,
0.328125,
0.0,
0.0,
0.25,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.109375,
0.03125,
0.109375,
0.0,
0.0,
0.25,
0.0
],
"total_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"total_cycles": [
0.390625,
0.21875,
0.390625,
0.0,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 6,
"work_registers_used": 7
}
}
}
},
"flutter/impeller/entity/uv.comp.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/uv.comp.vkspv",
"has_uniform_computation": true,
"type": "Compute",
"variants": {
"Main": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.1875,
0.1875,
0.125,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"shortest_path_cycles": [
0.046875,
0.0,
0.046875,
0.0,
0.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.1875,
0.1875,
0.125,
0.0625,
2.0,
0.0
]
},
"shared_storage_used": 0,
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 24,
"work_registers_used": 10
}
}
}
},
"flutter/impeller/entity/vertices.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/vertices.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 100,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"varying"
],
"longest_path_cycles": [
0.03125,
0.03125,
0.0,
0.0,
0.0,
0.25,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying"
],
"shortest_path_cycles": [
0.03125,
0.03125,
0.0,
0.0,
0.0,
0.25,
0.0
],
"total_bound_pipelines": [
"varying"
],
"total_cycles": [
0.03125,
0.03125,
0.0,
0.0,
0.0,
0.25,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 2,
"work_registers_used": 4
}
}
}
},
"flutter/impeller/entity/yuv_to_rgb_filter.frag.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/yuv_to_rgb_filter.frag.vkspv",
"has_side_effects": false,
"has_uniform_computation": true,
"modifies_coverage": false,
"reads_color_buffer": false,
"type": "Fragment",
"uses_late_zs_test": false,
"uses_late_zs_update": false,
"variants": {
"Main": {
"fp16_arithmetic": 100,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"varying",
"texture"
],
"longest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0,
0.0,
0.25,
0.25
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"varying",
"texture"
],
"shortest_path_bound_pipelines": [
"varying",
"texture"
],
"shortest_path_cycles": [
0.15625,
0.15625,
0.0,
0.0,
0.0,
0.25,
0.25
],
"total_bound_pipelines": [
"varying",
"texture"
],
"total_cycles": [
0.15625,
0.15625,
0.0,
0.0,
0.0,
0.25,
0.25
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 12,
"work_registers_used": 6
}
}
}
},
"flutter/impeller/entity/yuv_to_rgb_filter.vert.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/entity/yuv_to_rgb_filter.vert.vkspv",
"has_uniform_computation": true,
"type": "Vertex",
"variants": {
"Position": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.140625,
0.140625,
0.015625,
0.0625,
2.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 24,
"work_registers_used": 32
},
"Varying": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.015625,
0.015625,
0.015625,
0.0,
3.0,
0.0
]
},
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 20,
"work_registers_used": 8
}
}
}
},
"flutter/impeller/renderer/path_polyline.comp.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/renderer/path_polyline.comp.vkspv",
"has_uniform_computation": true,
"type": "Compute",
"variants": {
"Main": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
null
],
"longest_path_cycles": [
null,
null,
null,
null,
null,
null
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.609375,
0.0,
0.609375,
0.3125,
4.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
5.9375,
2.737499952316284,
4.987500190734863,
5.9375,
37.20000076293945,
0.0
]
},
"shared_storage_used": 12288,
"stack_spill_bytes": 0,
"thread_occupancy": 50,
"uniform_registers_used": 32,
"work_registers_used": 51
}
}
}
},
"flutter/impeller/renderer/prefix_sum_test.comp.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/renderer/prefix_sum_test.comp.vkspv",
"has_uniform_computation": true,
"type": "Compute",
"variants": {
"Main": {
"fp16_arithmetic": null,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
2.450000047683716,
0.0,
2.450000047683716,
1.0,
72.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"shortest_path_cycles": [
0.762499988079071,
0.0,
0.762499988079071,
0.0,
0.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
2.46875,
0.0,
2.46875,
1.0,
72.0,
0.0
]
},
"shared_storage_used": 4096,
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 8,
"work_registers_used": 18
}
}
}
},
"flutter/impeller/renderer/stroke.comp.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/renderer/stroke.comp.vkspv",
"has_uniform_computation": true,
"type": "Compute",
"variants": {
"Main": {
"fp16_arithmetic": 0,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.3125,
0.3125,
0.1875,
0.125,
7.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"arith_total",
"arith_cvt"
],
"shortest_path_cycles": [
0.0625,
0.0,
0.0625,
0.0,
0.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.3125,
0.3125,
0.1875,
0.125,
7.0,
0.0
]
},
"shared_storage_used": 0,
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 10,
"work_registers_used": 24
}
}
}
},
"flutter/impeller/renderer/threadgroup_sizing_test.comp.vkspv": {
"Mali-G78": {
"core": "Mali-G78",
"filename": "flutter/impeller/renderer/threadgroup_sizing_test.comp.vkspv",
"has_uniform_computation": true,
"type": "Compute",
"variants": {
"Main": {
"fp16_arithmetic": null,
"has_stack_spilling": false,
"performance": {
"longest_path_bound_pipelines": [
"load_store"
],
"longest_path_cycles": [
0.03125,
0.0,
0.03125,
0.0,
1.0,
0.0
],
"pipelines": [
"arith_total",
"arith_fma",
"arith_cvt",
"arith_sfu",
"load_store",
"texture"
],
"shortest_path_bound_pipelines": [
"load_store"
],
"shortest_path_cycles": [
0.03125,
0.0,
0.03125,
0.0,
1.0,
0.0
],
"total_bound_pipelines": [
"load_store"
],
"total_cycles": [
0.03125,
0.0,
0.03125,
0.0,
1.0,
0.0
]
},
"shared_storage_used": 0,
"stack_spill_bytes": 0,
"thread_occupancy": 100,
"uniform_registers_used": 2,
"work_registers_used": 4
}
}
}
}
} | engine/impeller/tools/malioc.json/0 | {
"file_path": "engine/impeller/tools/malioc.json",
"repo_id": "engine",
"token_count": 192161
} | 230 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_TYPOGRAPHER_BACKENDS_STB_GLYPH_ATLAS_CONTEXT_STB_H_
#define FLUTTER_IMPELLER_TYPOGRAPHER_BACKENDS_STB_GLYPH_ATLAS_CONTEXT_STB_H_
#include "impeller/base/backend_cast.h"
#include "impeller/typographer/glyph_atlas.h"
namespace impeller {
class BitmapSTB {
public:
BitmapSTB();
~BitmapSTB();
BitmapSTB(size_t width, size_t height, size_t bytes_per_pixel);
uint8_t* GetPixels();
uint8_t* GetPixelAddress(TPoint<size_t> coords);
size_t GetRowBytes() const;
size_t GetWidth() const;
size_t GetHeight() const;
size_t GetSize() const;
private:
size_t width_ = 0;
size_t height_ = 0;
size_t bytes_per_pixel_ = 0;
std::vector<uint8_t> pixels_;
};
class GlyphAtlasContextSTB
: public GlyphAtlasContext,
public BackendCast<GlyphAtlasContextSTB, GlyphAtlasContext> {
public:
GlyphAtlasContextSTB();
~GlyphAtlasContextSTB() override;
//----------------------------------------------------------------------------
/// @brief Retrieve the previous (if any) BitmapSTB instance.
std::shared_ptr<BitmapSTB> GetBitmap() const;
void UpdateBitmap(std::shared_ptr<BitmapSTB> bitmap);
private:
std::shared_ptr<BitmapSTB> bitmap_;
GlyphAtlasContextSTB(const GlyphAtlasContextSTB&) = delete;
GlyphAtlasContextSTB& operator=(const GlyphAtlasContextSTB&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_TYPOGRAPHER_BACKENDS_STB_GLYPH_ATLAS_CONTEXT_STB_H_
| engine/impeller/typographer/backends/stb/glyph_atlas_context_stb.h/0 | {
"file_path": "engine/impeller/typographer/backends/stb/glyph_atlas_context_stb.h",
"repo_id": "engine",
"token_count": 616
} | 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_TYPOGRAPHER_LAZY_GLYPH_ATLAS_H_
#define FLUTTER_IMPELLER_TYPOGRAPHER_LAZY_GLYPH_ATLAS_H_
#include <unordered_map>
#include "flutter/fml/macros.h"
#include "impeller/renderer/context.h"
#include "impeller/typographer/glyph_atlas.h"
#include "impeller/typographer/text_frame.h"
#include "impeller/typographer/typographer_context.h"
namespace impeller {
class LazyGlyphAtlas {
public:
explicit LazyGlyphAtlas(
std::shared_ptr<TypographerContext> typographer_context);
~LazyGlyphAtlas();
void AddTextFrame(const TextFrame& frame, Scalar scale);
void ResetTextFrames();
const std::shared_ptr<GlyphAtlas>& CreateOrGetGlyphAtlas(
Context& context,
GlyphAtlas::Type type) const;
private:
std::shared_ptr<TypographerContext> typographer_context_;
FontGlyphMap alpha_glyph_map_;
FontGlyphMap color_glyph_map_;
std::shared_ptr<GlyphAtlasContext> alpha_context_;
std::shared_ptr<GlyphAtlasContext> color_context_;
mutable std::shared_ptr<GlyphAtlas> alpha_atlas_;
mutable std::shared_ptr<GlyphAtlas> color_atlas_;
LazyGlyphAtlas(const LazyGlyphAtlas&) = delete;
LazyGlyphAtlas& operator=(const LazyGlyphAtlas&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_TYPOGRAPHER_LAZY_GLYPH_ATLAS_H_
| engine/impeller/typographer/lazy_glyph_atlas.h/0 | {
"file_path": "engine/impeller/typographer/lazy_glyph_atlas.h",
"repo_id": "engine",
"token_count": 569
} | 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/lib/gpu/context.h"
#include <future>
#include "flutter/lib/gpu/formats.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "fml/make_copyable.h"
#include "tonic/converter/dart_converter.h"
namespace flutter {
namespace gpu {
IMPLEMENT_WRAPPERTYPEINFO(flutter_gpu, Context);
std::shared_ptr<impeller::Context> Context::default_context_;
void Context::SetOverrideContext(std::shared_ptr<impeller::Context> context) {
default_context_ = std::move(context);
}
std::shared_ptr<impeller::Context> Context::GetOverrideContext() {
return default_context_;
}
std::shared_ptr<impeller::Context> Context::GetDefaultContext(
std::optional<std::string>& out_error) {
auto override_context = GetOverrideContext();
if (override_context) {
return override_context;
}
auto dart_state = flutter::UIDartState::Current();
if (!dart_state->IsImpellerEnabled()) {
out_error =
"Flutter GPU requires the Impeller rendering backend to be enabled.";
return nullptr;
}
// Grab the Impeller context from the IO manager.
std::promise<std::shared_ptr<impeller::Context>> context_promise;
auto impeller_context_future = context_promise.get_future();
fml::TaskRunner::RunNowOrPostTask(
dart_state->GetTaskRunners().GetIOTaskRunner(),
fml::MakeCopyable([promise = std::move(context_promise),
io_manager = dart_state->GetIOManager()]() mutable {
promise.set_value(io_manager ? io_manager->GetImpellerContext()
: nullptr);
}));
auto context = impeller_context_future.get();
if (!context) {
out_error = "Unable to retrieve the Impeller context.";
}
return context;
}
Context::Context(std::shared_ptr<impeller::Context> context)
: context_(std::move(context)) {}
Context::~Context() = default;
std::shared_ptr<impeller::Context> Context::GetContext() {
return context_;
}
} // namespace gpu
} // namespace flutter
//----------------------------------------------------------------------------
/// Exports
///
Dart_Handle InternalFlutterGpu_Context_InitializeDefault(Dart_Handle wrapper) {
std::optional<std::string> out_error;
auto impeller_context = flutter::gpu::Context::GetDefaultContext(out_error);
if (out_error.has_value()) {
return tonic::ToDart(out_error.value());
}
auto res = fml::MakeRefCounted<flutter::gpu::Context>(impeller_context);
res->AssociateWithDartWrapper(wrapper);
return Dart_Null();
}
extern int InternalFlutterGpu_Context_GetDefaultColorFormat(
flutter::gpu::Context* wrapper) {
return static_cast<int>(flutter::gpu::FromImpellerPixelFormat(
wrapper->GetContext()->GetCapabilities()->GetDefaultColorFormat()));
}
extern int InternalFlutterGpu_Context_GetDefaultStencilFormat(
flutter::gpu::Context* wrapper) {
return static_cast<int>(flutter::gpu::FromImpellerPixelFormat(
wrapper->GetContext()->GetCapabilities()->GetDefaultStencilFormat()));
}
extern int InternalFlutterGpu_Context_GetDefaultDepthStencilFormat(
flutter::gpu::Context* wrapper) {
return static_cast<int>(flutter::gpu::FromImpellerPixelFormat(
wrapper->GetContext()
->GetCapabilities()
->GetDefaultDepthStencilFormat()));
}
| engine/lib/gpu/context.cc/0 | {
"file_path": "engine/lib/gpu/context.cc",
"repo_id": "engine",
"token_count": 1199
} | 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.
// ignore_for_file: public_member_api_docs
part of flutter_gpu;
// ATTENTION! ATTENTION! ATTENTION!
// All enum classes defined in this file must exactly match the contents and
// order of the corresponding enums defined in `gpu/formats.h`.
/// Specifies where an allocation resides and how it may be used.
enum StorageMode {
/// Allocations can be mapped onto the hosts address space and also be used by
/// the device.
hostVisible,
/// Allocations can only be used by the device. This location is optimal for
/// use by the device. If the host needs to access these allocations, the
/// data must first be copied into a host visible allocation.
devicePrivate,
/// Used by the device for temporary render targets. These allocations cannot
/// be copied to or from other allocations. This storage mode is only valid
/// for Textures.
///
/// These allocations reside in tile memory which has higher bandwidth, lower
/// latency and lower power consumption. The total device memory usage is
/// also lower as a separate allocation does not need to be created in
/// device memory. Prefer using these allocations for intermediates like depth
/// and stencil buffers.
deviceTransient,
}
enum PixelFormat {
unknown,
a8UNormInt,
r8UNormInt,
r8g8UNormInt,
r8g8b8a8UNormInt,
r8g8b8a8UNormIntSRGB,
b8g8r8a8UNormInt,
b8g8r8a8UNormIntSRGB,
r32g32b32a32Float,
r16g16b16a16Float,
b10g10r10XR,
b10g10r10XRSRGB,
b10g10r10a10XR,
// Depth and stencil formats.
s8UInt,
d24UnormS8Uint,
d32FloatS8UInt,
}
enum TextureCoordinateSystem {
/// Alternative coordinate system used when uploading texture data from the
/// host.
/// (0, 0) is the bottom-left of the image with +Y going up.
uploadFromHost,
/// Default coordinate system.
/// (0, 0) is the top-left of the image with +Y going down.
renderToTexture,
}
enum BlendFactor {
zero,
one,
sourceColor,
oneMinusSourceColor,
sourceAlpha,
oneMinusSourceAlpha,
destinationColor,
oneMinusDestinationColor,
destinationAlpha,
oneMinusDestinationAlpha,
sourceAlphaSaturated,
blendColor,
oneMinusBlendColor,
blendAlpha,
oneMinusBlendAlpha,
}
enum BlendOperation {
add,
subtract,
reverseSubtract,
}
enum LoadAction {
dontCare,
load,
clear,
}
enum StoreAction {
dontCare,
store,
multisampleResolve,
storeAndMultisampleResolve,
}
enum ShaderStage {
vertex,
fragment,
}
enum MinMagFilter {
nearest,
linear,
}
enum MipFilter {
nearest,
linear,
}
enum SamplerAddressMode {
clampToEdge,
repeat,
mirror,
}
enum IndexType {
int16,
int32,
}
enum PrimitiveType {
triangle,
triangleStrip,
line,
lineStrip,
point,
}
enum CompareFunction {
/// Comparison test never passes.
never,
/// Comparison test passes always passes.
always,
/// Comparison test passes if new_value < current_value.
less,
/// Comparison test passes if new_value == current_value.
equal,
/// Comparison test passes if new_value <= current_value.
lessEqual,
/// Comparison test passes if new_value > current_value.
greater,
/// Comparison test passes if new_value != current_value.
notEqual,
/// Comparison test passes if new_value >= current_value.
greaterEqual,
}
enum StencilOperation {
/// Don't modify the current stencil value.
keep,
/// Reset the stencil value to zero.
zero,
/// Reset the stencil value to the reference value.
setToReferenceValue,
/// Increment the current stencil value by 1. Clamp it to the maximum.
incrementClamp,
/// Decrement the current stencil value by 1. Clamp it to zero.
decrementClamp,
/// Perform a logical bitwise invert on the current stencil value.
invert,
/// Increment the current stencil value by 1. If at maximum, set to zero.
incrementWrap,
/// Decrement the current stencil value by 1. If at zero, set to maximum.
decrementWrap,
}
| engine/lib/gpu/lib/src/formats.dart/0 | {
"file_path": "engine/lib/gpu/lib/src/formats.dart",
"repo_id": "engine",
"token_count": 1276
} | 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 "flutter/lib/gpu/smoketest.h"
#include "flutter/fml/memory/ref_ptr.h"
#include "flutter/lib/ui/dart_wrapper.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "third_party/dart/runtime/include/dart_api.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_state.h"
#include "third_party/tonic/dart_wrappable.h"
#include "third_party/tonic/dart_wrapper_info.h"
#include "third_party/tonic/logging/dart_invoke.h"
namespace flutter {
// TODO(131346): Remove this once we migrate the Dart GPU API into this space.
IMPLEMENT_WRAPPERTYPEINFO(flutter_gpu, FlutterGpuTestClass);
// TODO(131346): Remove this once we migrate the Dart GPU API into this space.
FlutterGpuTestClass::~FlutterGpuTestClass() = default;
} // namespace flutter
//----------------------------------------------------------------------------
/// Exports
///
// TODO(131346): Remove this once we migrate the Dart GPU API into this space.
uint32_t InternalFlutterGpuTestProc() {
return 1;
}
// TODO(131346): Remove this once we migrate the Dart GPU API into this space.
Dart_Handle InternalFlutterGpuTestProcWithCallback(Dart_Handle callback) {
flutter::UIDartState::ThrowIfUIOperationsProhibited();
if (!Dart_IsClosure(callback)) {
return tonic::ToDart("Callback must be a function");
}
tonic::DartInvoke(callback, {tonic::ToDart(1234)});
return Dart_Null();
}
// TODO(131346): Remove this once we migrate the Dart GPU API into this space.
void InternalFlutterGpuTestClass_Create(Dart_Handle wrapper) {
auto res = fml::MakeRefCounted<flutter::FlutterGpuTestClass>();
res->AssociateWithDartWrapper(wrapper);
FML_LOG(INFO) << "FlutterGpuTestClass Wrapped.";
}
// TODO(131346): Remove this once we migrate the Dart GPU API into this space.
void InternalFlutterGpuTestClass_Method(flutter::FlutterGpuTestClass* self,
int something) {
FML_LOG(INFO) << "Something: " << something;
}
| engine/lib/gpu/smoketest.cc/0 | {
"file_path": "engine/lib/gpu/smoketest.cc",
"repo_id": "engine",
"token_count": 741
} | 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.
// KEEP THIS SYNCHRONIZED WITH ../web_ui/lib/channel_buffers.dart
part of dart.ui;
/// Deprecated. Migrate to [ChannelCallback] instead.
///
/// Signature for [ChannelBuffers.drain]'s `callback` argument.
///
/// The first argument is the data sent by the plugin.
///
/// The second argument is a closure that, when called, will send messages
/// back to the plugin.
@Deprecated(
'Migrate to ChannelCallback instead. '
'This feature was deprecated after v3.11.0-20.0.pre.',
)
typedef DrainChannelCallback = Future<void> Function(ByteData? data, PlatformMessageResponseCallback callback);
/// Signature for [ChannelBuffers.setListener]'s `callback` argument.
///
/// The first argument is the data sent by the plugin.
///
/// The second argument is a closure that, when called, will send messages
/// back to the plugin.
///
/// See also:
///
/// * [PlatformMessageResponseCallback], the type used for replies.
typedef ChannelCallback = void Function(ByteData? data, PlatformMessageResponseCallback callback);
/// The data and logic required to store and invoke a callback.
///
/// This tracks (and applies) the [Zone].
class _ChannelCallbackRecord {
_ChannelCallbackRecord(this._callback) : _zone = Zone.current;
final ChannelCallback _callback;
final Zone _zone;
/// Call [callback] in [zone], using the given arguments.
void invoke(ByteData? dataArg, PlatformMessageResponseCallback callbackArg) {
_invoke2<ByteData?, PlatformMessageResponseCallback>(_callback, _zone, dataArg, callbackArg);
}
}
/// A saved platform message for a channel with its callback.
class _StoredMessage {
/// Wraps the data and callback for a platform message into
/// a [_StoredMessage] instance.
///
/// The first argument is a [ByteData] that represents the
/// payload of the message and a [PlatformMessageResponseCallback]
/// that represents the callback that will be called when the message
/// is handled.
_StoredMessage(this.data, this._callback) : _zone = Zone.current;
/// Representation of the message's payload.
final ByteData? data;
/// Callback to be used when replying to the message.
final PlatformMessageResponseCallback _callback;
final Zone _zone;
void invoke(ByteData? dataArg) {
_invoke1(_callback, _zone, dataArg);
}
}
/// The internal storage for a platform channel.
///
/// This consists of a fixed-size circular queue of [_StoredMessage]s,
/// and the channel's callback, if any has been registered.
class _Channel {
_Channel([ this._capacity = ChannelBuffers.kDefaultBufferSize ])
: _queue = collection.ListQueue<_StoredMessage>(_capacity);
/// The underlying data for the buffered messages.
final collection.ListQueue<_StoredMessage> _queue;
/// The number of messages currently in the [_Channel].
///
/// This is equal to or less than the [capacity].
int get length => _queue.length;
/// Whether to dump messages to the console when a message is
/// discarded due to the channel overflowing.
///
/// Has no effect in release builds.
bool debugEnableDiscardWarnings = true;
/// The number of messages that _can_ be stored in the [_Channel].
///
/// When additional messages are stored, earlier ones are discarded,
/// in a first-in-first-out fashion.
int get capacity => _capacity;
int _capacity;
/// Set the [capacity] of the channel to the given size.
///
/// If the new size is smaller than the [length], the oldest
/// messages are discarded until the capacity is reached. No
/// message is shown in case of overflow, regardless of the
/// value of [debugEnableDiscardWarnings].
set capacity(int newSize) {
_capacity = newSize;
_dropOverflowMessages(newSize);
}
/// Whether a microtask is queued to call [_drainStep].
///
/// This is used to queue messages received while draining, rather
/// than sending them out of order. This generally cannot happen in
/// production but is possible in test scenarios.
///
/// This is also necessary to avoid situations where multiple drains are
/// invoked simultaneously. For example, if a listener is set
/// (queuing a drain), then unset, then set again (which would queue
/// a drain again), all in one stack frame (not allowing the drain
/// itself an opportunity to check if a listener is set).
bool _draining = false;
/// Adds a message to the channel.
///
/// If the channel overflows, earlier messages are discarded, in a
/// first-in-first-out fashion. See [capacity]. If
/// [debugEnableDiscardWarnings] is true, this method returns true
/// on overflow. It is the responsibility of the caller to show the
/// warning message.
bool push(_StoredMessage message) {
if (!_draining && _channelCallbackRecord != null) {
assert(_queue.isEmpty);
_channelCallbackRecord!.invoke(message.data, message.invoke);
return false;
}
if (_capacity <= 0) {
return debugEnableDiscardWarnings;
}
final bool result = _dropOverflowMessages(_capacity - 1);
_queue.addLast(message);
return result;
}
/// Returns the first message in the channel and removes it.
///
/// Throws when empty.
_StoredMessage pop() => _queue.removeFirst();
/// Removes messages until [length] reaches `lengthLimit`.
///
/// The callback of each removed message is invoked with null
/// as its argument.
///
/// If any messages are removed, and [debugEnableDiscardWarnings] is
/// true, then returns true. The caller is responsible for showing
/// the warning message in that case.
bool _dropOverflowMessages(int lengthLimit) {
bool result = false;
while (_queue.length > lengthLimit) {
final _StoredMessage message = _queue.removeFirst();
message.invoke(null); // send empty reply to the plugin side
result = true;
}
return result;
}
_ChannelCallbackRecord? _channelCallbackRecord;
/// Sets the listener for this channel.
///
/// When there is a listener, messages are sent immediately.
///
/// If any messages were queued before the listener is added,
/// they are drained asynchronously after this method returns.
/// (See [_drain].)
///
/// Only one listener may be set at a time. Setting a
/// new listener clears the previous one.
///
/// Callbacks are invoked in their own stack frame and
/// use the zone that was current when the callback was
/// registered.
void setListener(ChannelCallback callback) {
final bool needDrain = _channelCallbackRecord == null;
_channelCallbackRecord = _ChannelCallbackRecord(callback);
if (needDrain && !_draining) {
_drain();
}
}
/// Clears the listener for this channel.
///
/// When there is no listener, messages are queued, up to [capacity],
/// and then discarded in a first-in-first-out fashion.
void clearListener() {
_channelCallbackRecord = null;
}
/// Drains all the messages in the channel (invoking the currently
/// registered listener for each one).
///
/// Each message is handled in its own microtask. No messages can
/// be queued by plugins while the queue is being drained, but any
/// microtasks queued by the handler itself will be processed before
/// the next message is handled.
///
/// The draining stops if the listener is removed.
///
/// See also:
///
/// * [setListener], which is used to register the callback.
/// * [clearListener], which removes it.
void _drain() {
assert(!_draining);
_draining = true;
scheduleMicrotask(_drainStep);
}
/// Drains a single message and then reinvokes itself asynchronously.
///
/// See [_drain] for more details.
void _drainStep() {
assert(_draining);
if (_queue.isNotEmpty && _channelCallbackRecord != null) {
final _StoredMessage message = pop();
_channelCallbackRecord!.invoke(message.data, message.invoke);
scheduleMicrotask(_drainStep);
} else {
_draining = false;
}
}
}
/// The buffering and dispatch mechanism for messages sent by plugins
/// on the engine side to their corresponding plugin code on the
/// framework side.
///
/// Messages for a channel are stored until a listener is provided for that channel,
/// using [setListener]. Only one listener may be configured per channel.
///
/// Typically these buffers are drained once a callback is set up on
/// the [BinaryMessenger] in the Flutter framework. (See [setListener].)
///
/// ## Channel names
///
/// By convention, channels are normally named with a reverse-DNS prefix, a
/// slash, and then a domain-specific name. For example, `com.example/demo`.
///
/// Channel names cannot contain the U+0000 NULL character, because they
/// are passed through APIs that use null-terminated strings.
///
/// ## Buffer capacity and overflow
///
/// Each channel has a finite buffer capacity and messages will
/// be deleted in a first-in-first-out (FIFO) manner if the capacity is exceeded.
///
/// By default buffers store one message per channel, and when a
/// message overflows, in debug mode, a message is printed to the
/// console. The message looks like the following:
///
/// > A message on the com.example channel was discarded before it could be
/// > handled.
/// > This happens when a plugin sends messages to the framework side before the
/// > framework has had an opportunity to register a listener. See the
/// > ChannelBuffers API documentation for details on how to configure the channel
/// > to expect more messages, or to expect messages to get discarded:
/// > https://api.flutter.dev/flutter/dart-ui/ChannelBuffers-class.html
///
/// There are tradeoffs associated with any size. The correct size
/// should be chosen for the semantics of the channel. To change the
/// size a plugin can send a message using the control channel,
/// as described below.
///
/// Size 0 is appropriate for channels where messages sent before
/// the engine and framework are ready should be ignored. For
/// example, a plugin that notifies the framework any time a
/// radiation sensor detects an ionization event might set its size
/// to zero since past ionization events are typically not
/// interesting, only instantaneous readings are worth tracking.
///
/// Size 1 is appropriate for level-triggered plugins. For example,
/// a plugin that notifies the framework of the current value of a
/// pressure sensor might leave its size at one (the default), while
/// sending messages continually; once the framework side of the plugin
/// registers with the channel, it will immediately receive the most
/// up to date value and earlier messages will have been discarded.
///
/// Sizes greater than one are appropriate for plugins where every
/// message is important. For example, a plugin that itself
/// registers with another system that has been buffering events,
/// and immediately forwards all the previously-buffered events,
/// would likely wish to avoid having any messages dropped on the
/// floor. In such situations, it is important to select a size that
/// will avoid overflows. It is also important to consider the
/// potential for the framework side to never fully initialize (e.g. if
/// the user starts the application, but terminates it soon
/// afterwards, leaving time for the platform side of a plugin to
/// run but not the framework side).
///
/// ## The control channel
///
/// A plugin can configure its channel's buffers by sending messages to the
/// control channel, `dev.flutter/channel-buffers` (see [kControlChannelName]).
///
/// There are two messages that can be sent to this control channel, to adjust
/// the buffer size and to disable the overflow warnings. See [handleMessage]
/// for details on these messages.
class ChannelBuffers {
/// Create a buffer pool for platform messages.
///
/// It is generally not necessary to create an instance of this class;
/// the global [channelBuffers] instance is the one used by the engine.
ChannelBuffers();
/// The number of messages that channel buffers will store by default.
static const int kDefaultBufferSize = 1;
/// The name of the channel that plugins can use to communicate with the
/// channel buffers system.
///
/// These messages are handled by [handleMessage].
static const String kControlChannelName = 'dev.flutter/channel-buffers';
/// A mapping between a channel name and its associated [_Channel].
final Map<String, _Channel> _channels = <String, _Channel>{};
/// Adds a message (`data`) to the named channel buffer (`name`).
///
/// The `callback` argument is a closure that, when called, will send messages
/// back to the plugin.
///
/// If a message overflows the channel, and the channel has not been
/// configured to expect overflow, then, in debug mode, a message
/// will be printed to the console warning about the overflow.
///
/// Channel names cannot contain the U+0000 NULL character, because they
/// are passed through APIs that use null-terminated strings.
void push(String name, ByteData? data, PlatformMessageResponseCallback callback) {
assert(!name.contains('\u0000'), 'Channel names must not contain U+0000 NULL characters.');
final _Channel channel = _channels.putIfAbsent(name, () => _Channel());
if (channel.push(_StoredMessage(data, callback))) {
_printDebug(
'A message on the $name channel was discarded before it could be handled.\n'
'This happens when a plugin sends messages to the framework side before the '
'framework has had an opportunity to register a listener. See the ChannelBuffers '
'API documentation for details on how to configure the channel to expect more '
'messages, or to expect messages to get discarded:\n'
' https://api.flutter.dev/flutter/dart-ui/ChannelBuffers-class.html\n'
'The capacity of the $name channel is ${channel._capacity} message${channel._capacity != 1 ? 's' : ''}.',
);
}
}
/// Sets the listener for the specified channel.
///
/// When there is a listener, messages are sent immediately.
///
/// Each channel may have up to one listener set at a time. Setting
/// a new listener on a channel with an existing listener clears the
/// previous one.
///
/// Callbacks are invoked in their own stack frame and
/// use the zone that was current when the callback was
/// registered.
///
/// ## Draining
///
/// If any messages were queued before the listener is added,
/// they are drained asynchronously after this method returns.
///
/// Each message is handled in its own microtask. No messages can
/// be queued by plugins while the queue is being drained, but any
/// microtasks queued by the handler itself will be processed before
/// the next message is handled.
///
/// The draining stops if the listener is removed.
void setListener(String name, ChannelCallback callback) {
assert(!name.contains('\u0000'), 'Channel names must not contain U+0000 NULL characters.');
final _Channel channel = _channels.putIfAbsent(name, () => _Channel());
channel.setListener(callback);
sendChannelUpdate(name, listening: true);
}
/// Clears the listener for the specified channel.
///
/// When there is no listener, messages on that channel are queued,
/// up to [kDefaultBufferSize] (or the size configured via the
/// control channel), and then discarded in a first-in-first-out
/// fashion.
void clearListener(String name) {
final _Channel? channel = _channels[name];
if (channel != null) {
channel.clearListener();
sendChannelUpdate(name, listening: false);
}
}
@Native<Void Function(Handle, Bool)>(symbol: 'PlatformConfigurationNativeApi::SendChannelUpdate')
external static void _sendChannelUpdate(String name, bool listening);
void sendChannelUpdate(String name, {required bool listening}) => _sendChannelUpdate(name, listening);
/// Deprecated. Migrate to [setListener] instead.
///
/// Remove and process all stored messages for a given channel.
///
/// This should be called once a channel is prepared to handle messages
/// (i.e. when a message handler is set up in the framework).
///
/// The messages are processed by calling the given `callback`. Each message
/// is processed in its own microtask.
@Deprecated(
'Migrate to setListener instead. '
'This feature was deprecated after v3.11.0-20.0.pre.',
)
Future<void> drain(String name, DrainChannelCallback callback) async {
final _Channel? channel = _channels[name];
while (channel != null && !channel._queue.isEmpty) {
final _StoredMessage message = channel.pop();
await callback(message.data, message.invoke);
}
}
/// Handle a control message.
///
/// This is intended to be called by the platform messages dispatcher, forwarding
/// messages from plugins to the [kControlChannelName] channel.
///
/// Messages use the [StandardMethodCodec] format. There are two methods
/// supported: `resize` and `overflow`. The `resize` method changes the size
/// of the buffer, and the `overflow` method controls whether overflow is
/// expected or not.
///
/// ## `resize`
///
/// The `resize` method takes as its argument a list with two values, first
/// the channel name (a UTF-8 string less than 254 bytes long and not
/// containing any null bytes), and second the allowed size of the channel
/// buffer (an integer between 0 and 2147483647).
///
/// Upon receiving the message, the channel's buffer is resized. If necessary,
/// messages are silently discarded to ensure the buffer is no bigger than
/// specified.
///
/// For historical reasons, this message can also be sent using a bespoke
/// format consisting of a UTF-8-encoded string with three parts separated
/// from each other by U+000D CARRIAGE RETURN (CR) characters, the three parts
/// being the string `resize`, the string giving the channel name, and then
/// the string giving the decimal serialization of the new channel buffer
/// size. For example: `resize\rchannel\r1`
///
/// ## `overflow`
///
/// The `overflow` method takes as its argument a list with two values, first
/// the channel name (a UTF-8 string less than 254 bytes long and not
/// containing any null bytes), and second a boolean which is true if overflow
/// is expected and false if it is not.
///
/// This sets a flag on the channel in debug mode. In release mode the message
/// is silently ignored. The flag indicates whether overflow is expected on this
/// channel. When the flag is set, messages are discarded silently. When the
/// flag is cleared (the default), any overflow on the channel causes a message
/// to be printed to the console, warning that a message was lost.
void handleMessage(ByteData data) {
// We hard-code the deserialization here because the StandardMethodCodec class
// is part of the framework, not dart:ui.
final Uint8List bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
if (bytes[0] == 0x07) { // 7 = value code for string
final int methodNameLength = bytes[1];
if (methodNameLength >= 254) { // lengths greater than 253 have more elaborate encoding
throw Exception('Unrecognized message sent to $kControlChannelName (method name too long)');
}
int index = 2; // where we are in reading the bytes
final String methodName = utf8.decode(bytes.sublist(index, index + methodNameLength));
index += methodNameLength;
switch (methodName) {
case 'resize':
if (bytes[index] != 0x0C) { // 12 = value code for list
throw Exception("Invalid arguments for 'resize' method sent to $kControlChannelName (arguments must be a two-element list, channel name and new capacity)");
}
index += 1;
if (bytes[index] < 0x02) { // We ignore extra arguments, in case we need to support them in the future, hence <2 rather than !=2.
throw Exception("Invalid arguments for 'resize' method sent to $kControlChannelName (arguments must be a two-element list, channel name and new capacity)");
}
index += 1;
if (bytes[index] != 0x07) { // 7 = value code for string
throw Exception("Invalid arguments for 'resize' method sent to $kControlChannelName (first argument must be a string)");
}
index += 1;
final int channelNameLength = bytes[index];
if (channelNameLength >= 254) { // lengths greater than 253 have more elaborate encoding
throw Exception("Invalid arguments for 'resize' method sent to $kControlChannelName (channel name must be less than 254 characters long)");
}
index += 1;
final String channelName = utf8.decode(bytes.sublist(index, index + channelNameLength));
if (channelName.contains('\u0000')) {
throw Exception("Invalid arguments for 'resize' method sent to $kControlChannelName (channel name must not contain any null bytes)");
}
index += channelNameLength;
if (bytes[index] != 0x03) { // 3 = value code for uint32
throw Exception("Invalid arguments for 'resize' method sent to $kControlChannelName (second argument must be an integer in the range 0 to 2147483647)");
}
index += 1;
resize(channelName, data.getUint32(index, Endian.host));
case 'overflow':
if (bytes[index] != 0x0C) { // 12 = value code for list
throw Exception("Invalid arguments for 'overflow' method sent to $kControlChannelName (arguments must be a two-element list, channel name and flag state)");
}
index += 1;
if (bytes[index] < 0x02) { // We ignore extra arguments, in case we need to support them in the future, hence <2 rather than !=2.
throw Exception("Invalid arguments for 'overflow' method sent to $kControlChannelName (arguments must be a two-element list, channel name and flag state)");
}
index += 1;
if (bytes[index] != 0x07) { // 7 = value code for string
throw Exception("Invalid arguments for 'overflow' method sent to $kControlChannelName (first argument must be a string)");
}
index += 1;
final int channelNameLength = bytes[index];
if (channelNameLength >= 254) { // lengths greater than 253 have more elaborate encoding
throw Exception("Invalid arguments for 'overflow' method sent to $kControlChannelName (channel name must be less than 254 characters long)");
}
index += 1;
final String channelName = utf8.decode(bytes.sublist(index, index + channelNameLength));
index += channelNameLength;
if (bytes[index] != 0x01 && bytes[index] != 0x02) { // 1 = value code for true, 2 = value code for false
throw Exception("Invalid arguments for 'overflow' method sent to $kControlChannelName (second argument must be a boolean)");
}
allowOverflow(channelName, bytes[index] == 0x01);
default:
throw Exception("Unrecognized method '$methodName' sent to $kControlChannelName");
}
} else {
final List<String> parts = utf8.decode(bytes).split('\r');
if (parts.length == 1 + /*arity=*/2 && parts[0] == 'resize') {
resize(parts[1], int.parse(parts[2]));
} else {
// If the message couldn't be decoded as UTF-8, a FormatException will
// have been thrown by utf8.decode() above.
throw Exception('Unrecognized message $parts sent to $kControlChannelName.');
}
}
}
/// Changes the capacity of the queue associated with the given channel.
///
/// This could result in the dropping of messages if newSize is less
/// than the current length of the queue.
///
/// This is expected to be called by platform-specific plugin code (indirectly
/// via the control channel), not by code on the framework side. See
/// [handleMessage].
///
/// Calling this from framework code is redundant since by the time framework
/// code can be running, it can just subscribe to the relevant channel and
/// there is therefore no need for any buffering.
void resize(String name, int newSize) {
_Channel? channel = _channels[name];
if (channel == null) {
assert(!name.contains('\u0000'), 'Channel names must not contain U+0000 NULL characters.');
channel = _Channel(newSize);
_channels[name] = channel;
} else {
channel.capacity = newSize;
}
}
/// Toggles whether the channel should show warning messages when discarding
/// messages due to overflow.
///
/// This is expected to be called by platform-specific plugin code (indirectly
/// via the control channel), not by code on the framework side. See
/// [handleMessage].
///
/// Calling this from framework code is redundant since by the time framework
/// code can be running, it can just subscribe to the relevant channel and
/// there is therefore no need for any messages to overflow.
///
/// This method has no effect in release builds.
void allowOverflow(String name, bool allowed) {
assert(() {
_Channel? channel = _channels[name];
if (channel == null && allowed) {
assert(!name.contains('\u0000'), 'Channel names must not contain U+0000 NULL characters.');
channel = _Channel();
_channels[name] = channel;
}
channel?.debugEnableDiscardWarnings = !allowed;
return true;
}());
}
}
/// [ChannelBuffers] that allow the storage of messages between the
/// Engine and the Framework. Typically messages that can't be delivered
/// are stored here until the Framework is able to process them.
///
/// See also:
///
/// * [BinaryMessenger], where [ChannelBuffers] are typically read.
final ChannelBuffers channelBuffers = ChannelBuffers();
| engine/lib/ui/channel_buffers.dart/0 | {
"file_path": "engine/lib/ui/channel_buffers.dart",
"repo_id": "engine",
"token_count": 7541
} | 236 |
#version 320 es
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
precision highp float;
layout(location = 0) out vec4 fragColor;
layout(location = 0) uniform float a;
void main() {
fragColor =
vec4(0.0,
// e^0.0 = 1.0
exp(a * 0.0), 0.0,
// e^2.0 - 6.38905609893 = 7.38905609893 - 6.38905609893 = 1.0
exp(a * 2.0) - 6.38905609893);
}
| engine/lib/ui/fixtures/shaders/supported_glsl_op_shaders/27_exp.frag/0 | {
"file_path": "engine/lib/ui/fixtures/shaders/supported_glsl_op_shaders/27_exp.frag",
"repo_id": "engine",
"token_count": 224
} | 237 |
#version 320 es
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
precision highp float;
layout(location = 0) out vec4 fragColor;
layout(location = 0) uniform float a;
void main() {
fragColor =
vec4(0.0,
// normalized result is x = [3/5, 4/5], so add 2/5 to x1 to make 1.0
normalize(vec2(a * 3.0, 4.0))[0] + 0.4, 0.0,
// normalized result is x = [3/5, 4/5], so add 1/5 to x2 to make 1.0
normalize(vec2(a * 3.0, 4.0))[1] + 0.2);
}
| engine/lib/ui/fixtures/shaders/supported_glsl_op_shaders/69_normalize.frag/0 | {
"file_path": "engine/lib/ui/fixtures/shaders/supported_glsl_op_shaders/69_normalize.frag",
"repo_id": "engine",
"token_count": 259
} | 238 |
#version 320 es
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
precision highp float;
layout(location = 0) out vec4 fragColor;
layout(location = 0) uniform float a;
void main() {
float sum = 0.0;
for (float i = 0.0; i < 6.0; i++) {
if (i > a * 5.0) {
break;
}
if (i < 1.0) {
continue;
}
if (a > 0.0) {
sum += a * 0.25;
}
}
fragColor = vec4(0.0, sum, 0.0, 1.0);
}
| engine/lib/ui/fixtures/shaders/supported_op_shaders/246_OpLoopMerge.frag/0 | {
"file_path": "engine/lib/ui/fixtures/shaders/supported_op_shaders/246_OpLoopMerge.frag",
"repo_id": "engine",
"token_count": 229
} | 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 "flutter/lib/ui/isolate_name_server/isolate_name_server_natives.h"
#include <string>
#include "flutter/lib/ui/isolate_name_server/isolate_name_server.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "third_party/tonic/dart_binding_macros.h"
#include "third_party/tonic/dart_library_natives.h"
namespace flutter {
Dart_Handle IsolateNameServerNatives::LookupPortByName(
const std::string& name) {
auto name_server = UIDartState::Current()->GetIsolateNameServer();
if (!name_server) {
return Dart_Null();
}
Dart_Port port = name_server->LookupIsolatePortByName(name);
if (port == ILLEGAL_PORT) {
return Dart_Null();
}
return Dart_NewSendPort(port);
}
bool IsolateNameServerNatives::RegisterPortWithName(Dart_Handle port_handle,
const std::string& name) {
auto name_server = UIDartState::Current()->GetIsolateNameServer();
if (!name_server) {
return false;
}
Dart_Port port = ILLEGAL_PORT;
Dart_SendPortGetId(port_handle, &port);
if (!name_server->RegisterIsolatePortWithName(port, name)) {
return false;
}
return true;
}
bool IsolateNameServerNatives::RemovePortNameMapping(const std::string& name) {
auto name_server = UIDartState::Current()->GetIsolateNameServer();
if (!name_server || !name_server->RemoveIsolateNameMapping(name)) {
return false;
}
return true;
}
} // namespace flutter
| engine/lib/ui/isolate_name_server/isolate_name_server_natives.cc/0 | {
"file_path": "engine/lib/ui/isolate_name_server/isolate_name_server_natives.cc",
"repo_id": "engine",
"token_count": 589
} | 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.
#ifndef FLUTTER_LIB_UI_PAINTING_DISPLAY_LIST_DEFERRED_IMAGE_GPU_SKIA_H_
#define FLUTTER_LIB_UI_PAINTING_DISPLAY_LIST_DEFERRED_IMAGE_GPU_SKIA_H_
#include <memory>
#include <mutex>
#include "flutter/common/graphics/texture.h"
#include "flutter/display_list/display_list.h"
#include "flutter/display_list/image/dl_image.h"
#include "flutter/flow/layers/layer_tree.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/memory/weak_ptr.h"
#include "flutter/lib/ui/io_manager.h"
#include "flutter/lib/ui/snapshot_delegate.h"
#include "third_party/skia/include/gpu/GrBackendSurface.h"
namespace flutter {
class DlDeferredImageGPUSkia final : public DlImage {
public:
static sk_sp<DlDeferredImageGPUSkia> Make(
const SkImageInfo& image_info,
sk_sp<DisplayList> display_list,
fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate,
const fml::RefPtr<fml::TaskRunner>& raster_task_runner,
fml::RefPtr<SkiaUnrefQueue> unref_queue);
static sk_sp<DlDeferredImageGPUSkia> MakeFromLayerTree(
const SkImageInfo& image_info,
std::unique_ptr<LayerTree> layer_tree,
fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate,
const fml::RefPtr<fml::TaskRunner>& raster_task_runner,
fml::RefPtr<SkiaUnrefQueue> unref_queue);
// |DlImage|
~DlDeferredImageGPUSkia() override;
// |DlImage|
// This method is only safe to call from the raster thread.
// Callers must not hold long term references to this image and
// only use it for the immediate painting operation. It must be
// collected on the raster task runner.
sk_sp<SkImage> skia_image() const override;
// |DlImage|
std::shared_ptr<impeller::Texture> impeller_texture() const override;
// |DlImage|
bool isOpaque() const override;
// |DlImage|
bool isTextureBacked() const override;
// |DlImage|
bool isUIThreadSafe() const override;
// |DlImage|
SkISize dimensions() const override;
// |DlImage|
virtual size_t GetApproximateByteSize() const override;
// |DlImage|
// This method is safe to call from any thread.
std::optional<std::string> get_error() const override;
// |DlImage|
OwningContext owning_context() const override {
return OwningContext::kRaster;
}
private:
class ImageWrapper final : public std::enable_shared_from_this<ImageWrapper>,
public ContextListener {
public:
static std::shared_ptr<ImageWrapper> Make(
const SkImageInfo& image_info,
sk_sp<DisplayList> display_list,
fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate,
fml::RefPtr<fml::TaskRunner> raster_task_runner,
fml::RefPtr<SkiaUnrefQueue> unref_queue);
static std::shared_ptr<ImageWrapper> MakeFromLayerTree(
const SkImageInfo& image_info,
std::unique_ptr<LayerTree> layer_tree,
fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate,
fml::RefPtr<fml::TaskRunner> raster_task_runner,
fml::RefPtr<SkiaUnrefQueue> unref_queue);
const SkImageInfo image_info() const { return image_info_; }
const GrBackendTexture& texture() const { return texture_; }
bool isTextureBacked() const;
std::optional<std::string> get_error();
sk_sp<SkImage> CreateSkiaImage() const;
void Unregister();
void DeleteTexture();
private:
const SkImageInfo image_info_;
sk_sp<DisplayList> display_list_;
fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate_;
fml::RefPtr<fml::TaskRunner> raster_task_runner_;
fml::RefPtr<SkiaUnrefQueue> unref_queue_;
std::shared_ptr<TextureRegistry> texture_registry_;
mutable std::mutex error_mutex_;
std::optional<std::string> error_;
GrBackendTexture texture_;
sk_sp<GrDirectContext> context_;
// May be used if this image is not texture backed.
sk_sp<SkImage> image_;
ImageWrapper(
const SkImageInfo& image_info,
sk_sp<DisplayList> display_list,
fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate,
fml::RefPtr<fml::TaskRunner> raster_task_runner,
fml::RefPtr<SkiaUnrefQueue> unref_queue);
// If a layer tree is provided, it will be flattened during the raster
// thread task spawned by this method. After being flattened into a display
// list, the image wrapper will be updated to hold this display list and the
// layer tree can be dropped.
void SnapshotDisplayList(std::unique_ptr<LayerTree> layer_tree = nullptr);
// |ContextListener|
void OnGrContextCreated() override;
// |ContextListener|
void OnGrContextDestroyed() override;
};
const std::shared_ptr<ImageWrapper> image_wrapper_;
fml::RefPtr<fml::TaskRunner> raster_task_runner_;
DlDeferredImageGPUSkia(std::shared_ptr<ImageWrapper> image_wrapper,
fml::RefPtr<fml::TaskRunner> raster_task_runner);
FML_DISALLOW_COPY_AND_ASSIGN(DlDeferredImageGPUSkia);
};
} // namespace flutter
#endif // FLUTTER_LIB_UI_PAINTING_DISPLAY_LIST_DEFERRED_IMAGE_GPU_SKIA_H_
| engine/lib/ui/painting/display_list_deferred_image_gpu_skia.h/0 | {
"file_path": "engine/lib/ui/painting/display_list_deferred_image_gpu_skia.h",
"repo_id": "engine",
"token_count": 1974
} | 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_LIB_UI_PAINTING_IMAGE_DECODER_IMPELLER_H_
#define FLUTTER_LIB_UI_PAINTING_IMAGE_DECODER_IMPELLER_H_
#include <future>
#include "flutter/fml/macros.h"
#include "flutter/lib/ui/painting/image_decoder.h"
#include "impeller/core/formats.h"
#include "impeller/geometry/size.h"
#include "third_party/skia/include/core/SkBitmap.h"
namespace impeller {
class Context;
class Allocator;
class DeviceBuffer;
} // namespace impeller
namespace flutter {
class ImpellerAllocator : public SkBitmap::Allocator {
public:
explicit ImpellerAllocator(std::shared_ptr<impeller::Allocator> allocator);
~ImpellerAllocator() = default;
// |Allocator|
bool allocPixelRef(SkBitmap* bitmap) override;
std::shared_ptr<impeller::DeviceBuffer> GetDeviceBuffer() const;
private:
std::shared_ptr<impeller::Allocator> allocator_;
std::shared_ptr<impeller::DeviceBuffer> buffer_;
};
struct DecompressResult {
std::shared_ptr<impeller::DeviceBuffer> device_buffer;
std::shared_ptr<SkBitmap> sk_bitmap;
SkImageInfo image_info;
std::string decode_error;
};
class ImageDecoderImpeller final : public ImageDecoder {
public:
ImageDecoderImpeller(
const TaskRunners& runners,
std::shared_ptr<fml::ConcurrentTaskRunner> concurrent_task_runner,
const fml::WeakPtr<IOManager>& io_manager,
bool supports_wide_gamut,
const std::shared_ptr<fml::SyncSwitch>& gpu_disabled_switch);
~ImageDecoderImpeller() override;
// |ImageDecoder|
void Decode(fml::RefPtr<ImageDescriptor> descriptor,
uint32_t target_width,
uint32_t target_height,
const ImageResult& result) override;
static DecompressResult DecompressTexture(
ImageDescriptor* descriptor,
SkISize target_size,
impeller::ISize max_texture_size,
bool supports_wide_gamut,
const std::shared_ptr<impeller::Allocator>& allocator);
/// @brief Create a device private texture from the provided host buffer.
/// This method is only suported on the metal backend.
/// @param context The Impeller graphics context.
/// @param buffer A host buffer containing the image to be uploaded.
/// @param image_info Format information about the particular image.
/// @param bitmap A bitmap containg the image to be uploaded.
/// @param gpu_disabled_switch Whether the GPU is available command encoding.
/// @return A DlImage.
static std::pair<sk_sp<DlImage>, std::string> UploadTextureToPrivate(
const std::shared_ptr<impeller::Context>& context,
const std::shared_ptr<impeller::DeviceBuffer>& buffer,
const SkImageInfo& image_info,
const std::shared_ptr<SkBitmap>& bitmap,
const std::shared_ptr<fml::SyncSwitch>& gpu_disabled_switch);
/// @brief Create a host visible texture from the provided bitmap.
/// @param context The Impeller graphics context.
/// @param bitmap A bitmap containg the image to be uploaded.
/// @param create_mips Whether mipmaps should be generated for the given
/// image.
/// @param gpu_disabled_switch Whether the GPU is available for mipmap
/// creation.
/// @return A DlImage.
static std::pair<sk_sp<DlImage>, std::string> UploadTextureToStorage(
const std::shared_ptr<impeller::Context>& context,
std::shared_ptr<SkBitmap> bitmap,
const std::shared_ptr<fml::SyncSwitch>& gpu_disabled_switch,
impeller::StorageMode storage_mode,
bool create_mips = true);
private:
using FutureContext = std::shared_future<std::shared_ptr<impeller::Context>>;
FutureContext context_;
const bool supports_wide_gamut_;
std::shared_ptr<fml::SyncSwitch> gpu_disabled_switch_;
FML_DISALLOW_COPY_AND_ASSIGN(ImageDecoderImpeller);
};
} // namespace flutter
#endif // FLUTTER_LIB_UI_PAINTING_IMAGE_DECODER_IMPELLER_H_
| engine/lib/ui/painting/image_decoder_impeller.h/0 | {
"file_path": "engine/lib/ui/painting/image_decoder_impeller.h",
"repo_id": "engine",
"token_count": 1438
} | 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 "flutter/lib/ui/painting/image_encoding.h"
#include "flutter/lib/ui/painting/image_encoding_impl.h"
#include "flutter/common/task_runners.h"
#include "flutter/fml/synchronization/waitable_event.h"
#include "flutter/lib/ui/painting/image.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 "gmock/gmock.h"
#include "gtest/gtest.h"
#if IMPELLER_SUPPORTS_RENDERING
#include "flutter/lib/ui/painting/image_encoding_impeller.h"
#include "impeller/renderer/testing/mocks.h"
#endif // IMPELLER_SUPPORTS_RENDERING
// CREATE_NATIVE_ENTRY is leaky by design
// NOLINTBEGIN(clang-analyzer-core.StackAddressEscape)
#pragma GCC diagnostic ignored "-Wunreachable-code"
namespace flutter {
namespace testing {
namespace {
fml::AutoResetWaitableEvent message_latch;
class MockDlImage : public DlImage {
public:
MOCK_METHOD(sk_sp<SkImage>, skia_image, (), (const, override));
MOCK_METHOD(std::shared_ptr<impeller::Texture>,
impeller_texture,
(),
(const, override));
MOCK_METHOD(bool, isOpaque, (), (const, override));
MOCK_METHOD(bool, isTextureBacked, (), (const, override));
MOCK_METHOD(bool, isUIThreadSafe, (), (const, override));
MOCK_METHOD(SkISize, dimensions, (), (const, override));
MOCK_METHOD(size_t, GetApproximateByteSize, (), (const, override));
};
} // namespace
class MockSyncSwitch {
public:
struct Handlers {
Handlers& SetIfTrue(const std::function<void()>& handler) {
true_handler = handler;
return *this;
}
Handlers& SetIfFalse(const std::function<void()>& handler) {
false_handler = handler;
return *this;
}
std::function<void()> true_handler = [] {};
std::function<void()> false_handler = [] {};
};
MOCK_METHOD(void, Execute, (const Handlers& handlers), (const));
MOCK_METHOD(void, SetSwitch, (bool value));
};
TEST_F(ShellTest, EncodeImageGivesExternalTypedData) {
auto native_encode_image = [&](Dart_NativeArguments args) {
auto image_handle = Dart_GetNativeArgument(args, 0);
image_handle =
Dart_GetField(image_handle, Dart_NewStringFromCString("_image"));
ASSERT_FALSE(Dart_IsError(image_handle)) << Dart_GetError(image_handle);
ASSERT_FALSE(Dart_IsNull(image_handle));
auto format_handle = Dart_GetNativeArgument(args, 1);
auto callback_handle = Dart_GetNativeArgument(args, 2);
intptr_t peer = 0;
Dart_Handle result = Dart_GetNativeInstanceField(
image_handle, tonic::DartWrappable::kPeerIndex, &peer);
ASSERT_FALSE(Dart_IsError(result));
CanvasImage* canvas_image = reinterpret_cast<CanvasImage*>(peer);
int64_t format = -1;
result = Dart_IntegerToInt64(format_handle, &format);
ASSERT_FALSE(Dart_IsError(result));
result = EncodeImage(canvas_image, format, callback_handle);
ASSERT_TRUE(Dart_IsNull(result));
};
auto nativeValidateExternal = [&](Dart_NativeArguments args) {
auto handle = Dart_GetNativeArgument(args, 0);
auto typed_data_type = Dart_GetTypeOfExternalTypedData(handle);
EXPECT_EQ(typed_data_type, Dart_TypedData_kUint8);
message_latch.Signal();
};
Settings settings = CreateSettingsForFixture();
TaskRunners task_runners("test", // label
GetCurrentTaskRunner(), // platform
CreateNewThread(), // raster
CreateNewThread(), // ui
CreateNewThread() // io
);
AddNativeCallback("EncodeImage", CREATE_NATIVE_ENTRY(native_encode_image));
AddNativeCallback("ValidateExternal",
CREATE_NATIVE_ENTRY(nativeValidateExternal));
std::unique_ptr<Shell> shell = CreateShell(settings, task_runners);
ASSERT_TRUE(shell->IsSetup());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("encodeImageProducesExternalUint8List");
shell->RunEngine(std::move(configuration), [&](auto result) {
ASSERT_EQ(result, Engine::RunStatus::Success);
});
message_latch.Wait();
DestroyShell(std::move(shell), task_runners);
}
TEST_F(ShellTest, EncodeImageAccessesSyncSwitch) {
Settings settings = CreateSettingsForFixture();
TaskRunners task_runners("test", // label
GetCurrentTaskRunner(), // platform
CreateNewThread(), // raster
CreateNewThread(), // ui
CreateNewThread() // io
);
auto native_encode_image = [&](Dart_NativeArguments args) {
auto image_handle = Dart_GetNativeArgument(args, 0);
image_handle =
Dart_GetField(image_handle, Dart_NewStringFromCString("_image"));
ASSERT_FALSE(Dart_IsError(image_handle)) << Dart_GetError(image_handle);
ASSERT_FALSE(Dart_IsNull(image_handle));
auto format_handle = Dart_GetNativeArgument(args, 1);
intptr_t peer = 0;
Dart_Handle result = Dart_GetNativeInstanceField(
image_handle, tonic::DartWrappable::kPeerIndex, &peer);
ASSERT_FALSE(Dart_IsError(result));
CanvasImage* canvas_image = reinterpret_cast<CanvasImage*>(peer);
int64_t format = -1;
result = Dart_IntegerToInt64(format_handle, &format);
ASSERT_FALSE(Dart_IsError(result));
auto io_manager = UIDartState::Current()->GetIOManager();
fml::AutoResetWaitableEvent latch;
task_runners.GetIOTaskRunner()->PostTask([&]() {
auto is_gpu_disabled_sync_switch =
std::make_shared<const MockSyncSwitch>();
EXPECT_CALL(*is_gpu_disabled_sync_switch, Execute)
.WillOnce([](const MockSyncSwitch::Handlers& handlers) {
handlers.true_handler();
});
ConvertToRasterUsingResourceContext(canvas_image->image()->skia_image(),
io_manager->GetResourceContext(),
is_gpu_disabled_sync_switch);
latch.Signal();
});
latch.Wait();
message_latch.Signal();
};
AddNativeCallback("EncodeImage", CREATE_NATIVE_ENTRY(native_encode_image));
std::unique_ptr<Shell> shell = CreateShell(settings, task_runners);
ASSERT_TRUE(shell->IsSetup());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("encodeImageProducesExternalUint8List");
shell->RunEngine(std::move(configuration), [&](auto result) {
ASSERT_EQ(result, Engine::RunStatus::Success);
});
message_latch.Wait();
DestroyShell(std::move(shell), task_runners);
}
#if IMPELLER_SUPPORTS_RENDERING
using ::impeller::testing::MockAllocator;
using ::impeller::testing::MockBlitPass;
using ::impeller::testing::MockCommandBuffer;
using ::impeller::testing::MockCommandQueue;
using ::impeller::testing::MockDeviceBuffer;
using ::impeller::testing::MockImpellerContext;
using ::impeller::testing::MockTexture;
using ::testing::_;
using ::testing::DoAll;
using ::testing::Invoke;
using ::testing::InvokeArgument;
using ::testing::Return;
namespace {
std::shared_ptr<impeller::Context> MakeConvertDlImageToSkImageContext(
std::vector<uint8_t>& buffer) {
auto context = std::make_shared<MockImpellerContext>();
auto command_buffer = std::make_shared<MockCommandBuffer>(context);
auto allocator = std::make_shared<MockAllocator>();
auto blit_pass = std::make_shared<MockBlitPass>();
auto command_queue = std::make_shared<MockCommandQueue>();
impeller::DeviceBufferDescriptor device_buffer_desc;
device_buffer_desc.size = buffer.size();
auto device_buffer = std::make_shared<MockDeviceBuffer>(device_buffer_desc);
EXPECT_CALL(*allocator, OnCreateBuffer).WillOnce(Return(device_buffer));
EXPECT_CALL(*blit_pass, IsValid).WillRepeatedly(Return(true));
EXPECT_CALL(*command_buffer, IsValid).WillRepeatedly(Return(true));
EXPECT_CALL(*command_buffer, OnCreateBlitPass).WillOnce(Return(blit_pass));
EXPECT_CALL(*context, GetResourceAllocator).WillRepeatedly(Return(allocator));
EXPECT_CALL(*context, CreateCommandBuffer).WillOnce(Return(command_buffer));
EXPECT_CALL(*device_buffer, OnGetContents).WillOnce(Return(buffer.data()));
EXPECT_CALL(*command_queue, Submit(_, _))
.WillRepeatedly(
DoAll(InvokeArgument<1>(impeller::CommandBuffer::Status::kCompleted),
Return(fml::Status())));
EXPECT_CALL(*context, GetCommandQueue).WillRepeatedly(Return(command_queue));
return context;
}
} // namespace
TEST_F(ShellTest, EncodeImageRetries) {
#ifndef FML_OS_MACOSX
// Only works on macos currently.
GTEST_SKIP();
#endif
Settings settings = CreateSettingsForFixture();
settings.enable_impeller = true;
TaskRunners task_runners("test", // label
GetCurrentTaskRunner(), // platform
CreateNewThread(), // raster
CreateNewThread(), // ui
CreateNewThread() // io
);
std::unique_ptr<Shell> shell = CreateShell({
.settings = settings,
.task_runners = task_runners,
});
auto turn_off_gpu = [&](Dart_NativeArguments args) {
auto handle = Dart_GetNativeArgument(args, 0);
bool value = true;
ASSERT_TRUE(Dart_IsBoolean(handle));
Dart_BooleanValue(handle, &value);
TurnOffGPU(shell.get(), value);
};
AddNativeCallback("TurnOffGPU", CREATE_NATIVE_ENTRY(turn_off_gpu));
auto validate_not_null = [&](Dart_NativeArguments args) {
auto handle = Dart_GetNativeArgument(args, 0);
EXPECT_FALSE(Dart_IsNull(handle));
message_latch.Signal();
};
AddNativeCallback("ValidateNotNull", CREATE_NATIVE_ENTRY(validate_not_null));
ASSERT_TRUE(shell->IsSetup());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("toByteDataRetries");
shell->RunEngine(std::move(configuration), [&](auto result) {
ASSERT_EQ(result, Engine::RunStatus::Success);
});
message_latch.Wait();
DestroyShell(std::move(shell), task_runners);
}
TEST_F(ShellTest, EncodeImageFailsWithoutGPUImpeller) {
#ifndef FML_OS_MACOSX
// Only works on macos currently.
GTEST_SKIP();
#endif
Settings settings = CreateSettingsForFixture();
settings.enable_impeller = true;
TaskRunners task_runners("test", // label
GetCurrentTaskRunner(), // platform
CreateNewThread(), // raster
CreateNewThread(), // ui
CreateNewThread() // io
);
auto native_validate_error = [&](Dart_NativeArguments args) {
auto handle = Dart_GetNativeArgument(args, 0);
EXPECT_FALSE(Dart_IsNull(handle));
message_latch.Signal();
};
AddNativeCallback("ValidateError",
CREATE_NATIVE_ENTRY(native_validate_error));
std::unique_ptr<Shell> shell = CreateShell({
.settings = settings,
.task_runners = task_runners,
});
auto turn_off_gpu = [&](Dart_NativeArguments args) {
auto handle = Dart_GetNativeArgument(args, 0);
bool value = true;
ASSERT_TRUE(Dart_IsBoolean(handle));
Dart_BooleanValue(handle, &value);
TurnOffGPU(shell.get(), true);
};
AddNativeCallback("TurnOffGPU", CREATE_NATIVE_ENTRY(turn_off_gpu));
auto flush_awaiting_tasks = [&](Dart_NativeArguments args) {
task_runners.GetIOTaskRunner()->PostTask([&] {
std::shared_ptr<impeller::Context> impeller_context =
shell->GetIOManager()->GetImpellerContext();
// This will cause the stored tasks to overflow and start throwing them
// away.
for (int i = 0; i < impeller::Context::kMaxTasksAwaitingGPU; ++i) {
impeller_context->StoreTaskForGPU([] {});
}
});
};
AddNativeCallback("FlushGpuAwaitingTasks",
CREATE_NATIVE_ENTRY(flush_awaiting_tasks));
ASSERT_TRUE(shell->IsSetup());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("toByteDataWithoutGPU");
shell->RunEngine(std::move(configuration), [&](auto result) {
ASSERT_EQ(result, Engine::RunStatus::Success);
});
message_latch.Wait();
DestroyShell(std::move(shell), task_runners);
}
TEST(ImageEncodingImpellerTest, ConvertDlImageToSkImage16Float) {
sk_sp<MockDlImage> image(new MockDlImage());
EXPECT_CALL(*image, dimensions)
.WillRepeatedly(Return(SkISize::Make(100, 100)));
impeller::TextureDescriptor desc;
desc.format = impeller::PixelFormat::kR16G16B16A16Float;
auto texture = std::make_shared<MockTexture>(desc);
EXPECT_CALL(*image, impeller_texture).WillOnce(Return(texture));
std::vector<uint8_t> buffer;
buffer.reserve(100 * 100 * 8);
auto context = MakeConvertDlImageToSkImageContext(buffer);
bool did_call = false;
ImageEncodingImpeller::ConvertDlImageToSkImage(
image,
[&did_call](const fml::StatusOr<sk_sp<SkImage>>& image) {
did_call = true;
ASSERT_TRUE(image.ok());
ASSERT_TRUE(image.value());
EXPECT_EQ(100, image.value()->width());
EXPECT_EQ(100, image.value()->height());
EXPECT_EQ(kRGBA_F16_SkColorType, image.value()->colorType());
EXPECT_EQ(nullptr, image.value()->colorSpace());
},
context);
EXPECT_TRUE(did_call);
}
TEST(ImageEncodingImpellerTest, ConvertDlImageToSkImage10XR) {
sk_sp<MockDlImage> image(new MockDlImage());
EXPECT_CALL(*image, dimensions)
.WillRepeatedly(Return(SkISize::Make(100, 100)));
impeller::TextureDescriptor desc;
desc.format = impeller::PixelFormat::kB10G10R10XR;
auto texture = std::make_shared<MockTexture>(desc);
EXPECT_CALL(*image, impeller_texture).WillOnce(Return(texture));
std::vector<uint8_t> buffer;
buffer.reserve(100 * 100 * 4);
auto context = MakeConvertDlImageToSkImageContext(buffer);
bool did_call = false;
ImageEncodingImpeller::ConvertDlImageToSkImage(
image,
[&did_call](const fml::StatusOr<sk_sp<SkImage>>& image) {
did_call = true;
ASSERT_TRUE(image.ok());
ASSERT_TRUE(image.value());
EXPECT_EQ(100, image.value()->width());
EXPECT_EQ(100, image.value()->height());
EXPECT_EQ(kBGR_101010x_XR_SkColorType, image.value()->colorType());
EXPECT_EQ(nullptr, image.value()->colorSpace());
},
context);
EXPECT_TRUE(did_call);
}
TEST(ImageEncodingImpellerTest, PngEncoding10XR) {
int width = 100;
int height = 100;
SkImageInfo info = SkImageInfo::Make(
width, height, kBGR_101010x_XR_SkColorType, kUnpremul_SkAlphaType);
auto surface = SkSurfaces::Raster(info);
SkCanvas* canvas = surface->getCanvas();
SkPaint paint;
paint.setColor(SK_ColorBLUE);
paint.setAntiAlias(true);
canvas->clear(SK_ColorWHITE);
canvas->drawCircle(width / 2, height / 2, 100, paint);
sk_sp<SkImage> image = surface->makeImageSnapshot();
sk_sp<SkData> png = EncodeImage(image, ImageByteFormat::kPNG);
EXPECT_TRUE(png);
}
#endif // IMPELLER_SUPPORTS_RENDERING
} // namespace testing
} // namespace flutter
// NOLINTEND(clang-analyzer-core.StackAddressEscape)
| engine/lib/ui/painting/image_encoding_unittests.cc/0 | {
"file_path": "engine/lib/ui/painting/image_encoding_unittests.cc",
"repo_id": "engine",
"token_count": 6085
} | 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.
#include "flutter/lib/ui/painting/multi_frame_codec.h"
#include <utility>
#include "flutter/fml/make_copyable.h"
#include "flutter/lib/ui/painting/display_list_image_gpu.h"
#include "flutter/lib/ui/painting/image.h"
#if IMPELLER_SUPPORTS_RENDERING
#include "flutter/lib/ui/painting/image_decoder_impeller.h"
#endif // IMPELLER_SUPPORTS_RENDERING
#include "third_party/dart/runtime/include/dart_api.h"
#include "third_party/skia/include/codec/SkCodecAnimation.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkPixelRef.h"
#include "third_party/skia/include/gpu/ganesh/SkImageGanesh.h"
#include "third_party/tonic/logging/dart_invoke.h"
namespace flutter {
MultiFrameCodec::MultiFrameCodec(std::shared_ptr<ImageGenerator> generator)
: state_(new State(std::move(generator))) {}
MultiFrameCodec::~MultiFrameCodec() = default;
MultiFrameCodec::State::State(std::shared_ptr<ImageGenerator> generator)
: generator_(std::move(generator)),
frameCount_(generator_->GetFrameCount()),
repetitionCount_(generator_->GetPlayCount() ==
ImageGenerator::kInfinitePlayCount
? -1
: generator_->GetPlayCount() - 1),
is_impeller_enabled_(UIDartState::Current()->IsImpellerEnabled()) {}
static void InvokeNextFrameCallback(
const fml::RefPtr<CanvasImage>& image,
int duration,
const std::string& decode_error,
std::unique_ptr<tonic::DartPersistentValue> callback,
size_t trace_id) {
std::shared_ptr<tonic::DartState> dart_state = callback->dart_state().lock();
if (!dart_state) {
FML_DLOG(ERROR) << "Could not acquire Dart state while attempting to fire "
"next frame callback.";
return;
}
tonic::DartState::Scope scope(dart_state);
tonic::DartInvoke(callback->value(),
{tonic::ToDart(image), tonic::ToDart(duration),
tonic::ToDart(decode_error)});
}
std::pair<sk_sp<DlImage>, std::string>
MultiFrameCodec::State::GetNextFrameImage(
fml::WeakPtr<GrDirectContext> resourceContext,
const std::shared_ptr<const fml::SyncSwitch>& gpu_disable_sync_switch,
const std::shared_ptr<impeller::Context>& impeller_context,
fml::RefPtr<flutter::SkiaUnrefQueue> unref_queue) {
SkBitmap bitmap = SkBitmap();
SkImageInfo info = generator_->GetInfo().makeColorType(kN32_SkColorType);
if (info.alphaType() == kUnpremul_SkAlphaType) {
SkImageInfo updated = info.makeAlphaType(kPremul_SkAlphaType);
info = updated;
}
if (!bitmap.tryAllocPixels(info)) {
std::ostringstream ostr;
ostr << "Failed to allocate memory for bitmap of size "
<< info.computeMinByteSize() << "B";
std::string decode_error = ostr.str();
FML_LOG(ERROR) << decode_error;
return std::make_pair(nullptr, decode_error);
}
ImageGenerator::FrameInfo frameInfo =
generator_->GetFrameInfo(nextFrameIndex_);
const int requiredFrameIndex =
frameInfo.required_frame.value_or(SkCodec::kNoFrame);
if (requiredFrameIndex != SkCodec::kNoFrame) {
// We are here when the frame said |disposal_method| is
// `DisposalMethod::kKeep` or `DisposalMethod::kRestorePrevious` and
// |requiredFrameIndex| is set to ex-frame or ex-ex-frame.
if (!lastRequiredFrame_.has_value()) {
FML_DLOG(INFO)
<< "Frame " << nextFrameIndex_ << " depends on frame "
<< requiredFrameIndex
<< " and no required frames are cached. Using blank slate instead.";
} else {
// Copy the previous frame's output buffer into the current frame as the
// starting point.
bitmap.writePixels(lastRequiredFrame_->pixmap());
if (restoreBGColorRect_.has_value()) {
bitmap.erase(SK_ColorTRANSPARENT, restoreBGColorRect_.value());
}
}
}
// Write the new frame to the output buffer. The bitmap pixels as supplied
// are already set in accordance with the previous frame's disposal policy.
if (!generator_->GetPixels(info, bitmap.getPixels(), bitmap.rowBytes(),
nextFrameIndex_, requiredFrameIndex)) {
std::ostringstream ostr;
ostr << "Could not getPixels for frame " << nextFrameIndex_;
std::string decode_error = ostr.str();
FML_LOG(ERROR) << decode_error;
return std::make_pair(nullptr, decode_error);
}
const bool keep_current_frame =
frameInfo.disposal_method == SkCodecAnimation::DisposalMethod::kKeep;
const bool restore_previous_frame =
frameInfo.disposal_method ==
SkCodecAnimation::DisposalMethod::kRestorePrevious;
const bool previous_frame_available = lastRequiredFrame_.has_value();
// Store the current frame in `lastRequiredFrame_` if the frame's disposal
// method indicates we should do so.
// * When the disposal method is "Keep", the stored frame should always be
// overwritten with the new frame we just crafted.
// * When the disposal method is "RestorePrevious", the previously stored
// frame should be retained and used as the backdrop for the next frame
// again. If there isn't already a stored frame, that means we haven't
// rendered any frames yet! When this happens, we just fall back to "Keep"
// behavior and store the current frame as the backdrop of the next frame.
if (keep_current_frame ||
(previous_frame_available && !restore_previous_frame)) {
// Replace the stored frame. The `lastRequiredFrame_` will get used as the
// starting backdrop for the next frame.
lastRequiredFrame_ = bitmap;
lastRequiredFrameIndex_ = nextFrameIndex_;
}
if (frameInfo.disposal_method ==
SkCodecAnimation::DisposalMethod::kRestoreBGColor) {
restoreBGColorRect_ = frameInfo.disposal_rect;
} else {
restoreBGColorRect_.reset();
}
#if IMPELLER_SUPPORTS_RENDERING
if (is_impeller_enabled_) {
// This is safe regardless of whether the GPU is available or not because
// without mipmap creation there is no command buffer encoding done.
return ImageDecoderImpeller::UploadTextureToStorage(
impeller_context, std::make_shared<SkBitmap>(bitmap),
std::make_shared<fml::SyncSwitch>(),
impeller::StorageMode::kHostVisible,
/*create_mips=*/false);
}
#endif // IMPELLER_SUPPORTS_RENDERING
sk_sp<SkImage> skImage;
gpu_disable_sync_switch->Execute(
fml::SyncSwitch::Handlers()
.SetIfTrue([&skImage, &bitmap] {
// Defer decoding until time of draw later on the raster thread.
// Can happen when GL operations are currently forbidden such as
// in the background on iOS.
skImage = SkImages::RasterFromBitmap(bitmap);
})
.SetIfFalse([&skImage, &resourceContext, &bitmap] {
if (resourceContext) {
SkPixmap pixmap(bitmap.info(), bitmap.pixelRef()->pixels(),
bitmap.pixelRef()->rowBytes());
skImage = SkImages::CrossContextTextureFromPixmap(
resourceContext.get(), pixmap, true);
} else {
// Defer decoding until time of draw later on the raster thread.
// Can happen when GL operations are currently forbidden such as
// in the background on iOS.
skImage = SkImages::RasterFromBitmap(bitmap);
}
}));
return std::make_pair(DlImageGPU::Make({skImage, std::move(unref_queue)}),
std::string());
}
void MultiFrameCodec::State::GetNextFrameAndInvokeCallback(
std::unique_ptr<tonic::DartPersistentValue> callback,
const fml::RefPtr<fml::TaskRunner>& ui_task_runner,
fml::WeakPtr<GrDirectContext> resourceContext,
fml::RefPtr<flutter::SkiaUnrefQueue> unref_queue,
const std::shared_ptr<const fml::SyncSwitch>& gpu_disable_sync_switch,
size_t trace_id,
const std::shared_ptr<impeller::Context>& impeller_context) {
fml::RefPtr<CanvasImage> image = nullptr;
int duration = 0;
sk_sp<DlImage> dlImage;
std::string decode_error;
std::tie(dlImage, decode_error) =
GetNextFrameImage(std::move(resourceContext), gpu_disable_sync_switch,
impeller_context, std::move(unref_queue));
if (dlImage) {
image = CanvasImage::Create();
image->set_image(dlImage);
ImageGenerator::FrameInfo frameInfo =
generator_->GetFrameInfo(nextFrameIndex_);
duration = frameInfo.duration;
}
nextFrameIndex_ = (nextFrameIndex_ + 1) % frameCount_;
// The static leak checker gets confused by the use of fml::MakeCopyable.
// NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks)
ui_task_runner->PostTask(fml::MakeCopyable(
[callback = std::move(callback), image = std::move(image),
decode_error = std::move(decode_error), duration, trace_id]() mutable {
InvokeNextFrameCallback(image, duration, decode_error,
std::move(callback), trace_id);
}));
}
Dart_Handle MultiFrameCodec::getNextFrame(Dart_Handle callback_handle) {
static size_t trace_counter = 1;
const size_t trace_id = trace_counter++;
if (!Dart_IsClosure(callback_handle)) {
return tonic::ToDart("Callback must be a function");
}
auto* dart_state = UIDartState::Current();
const auto& task_runners = dart_state->GetTaskRunners();
if (state_->frameCount_ == 0) {
std::string decode_error("Could not provide any frame.");
FML_LOG(ERROR) << decode_error;
task_runners.GetUITaskRunner()->PostTask(fml::MakeCopyable(
[trace_id, decode_error = std::move(decode_error),
callback = std::make_unique<tonic::DartPersistentValue>(
tonic::DartState::Current(), callback_handle)]() mutable {
InvokeNextFrameCallback(nullptr, 0, decode_error, std::move(callback),
trace_id);
}));
return Dart_Null();
}
task_runners.GetIOTaskRunner()->PostTask(fml::MakeCopyable(
[callback = std::make_unique<tonic::DartPersistentValue>(
tonic::DartState::Current(), callback_handle),
weak_state = std::weak_ptr<MultiFrameCodec::State>(state_), trace_id,
ui_task_runner = task_runners.GetUITaskRunner(),
io_manager = dart_state->GetIOManager()]() mutable {
auto state = weak_state.lock();
if (!state) {
ui_task_runner->PostTask(fml::MakeCopyable(
[callback = std::move(callback)]() { callback->Clear(); }));
return;
}
state->GetNextFrameAndInvokeCallback(
std::move(callback), ui_task_runner,
io_manager->GetResourceContext(), io_manager->GetSkiaUnrefQueue(),
io_manager->GetIsGpuDisabledSyncSwitch(), trace_id,
io_manager->GetImpellerContext());
}));
return Dart_Null();
// The static leak checker gets confused by the control flow, unique
// pointers and closures in this function.
// NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks)
}
int MultiFrameCodec::frameCount() const {
return state_->frameCount_;
}
int MultiFrameCodec::repetitionCount() const {
return state_->repetitionCount_;
}
} // namespace flutter
| engine/lib/ui/painting/multi_frame_codec.cc/0 | {
"file_path": "engine/lib/ui/painting/multi_frame_codec.cc",
"repo_id": "engine",
"token_count": 4384
} | 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.
#include "flutter/lib/ui/painting/scene/scene_node.h"
#include <memory>
#include <sstream>
#include "flutter/assets/asset_manager.h"
#include "flutter/fml/make_copyable.h"
#include "flutter/fml/trace_event.h"
#include "flutter/lib/ui/dart_wrapper.h"
#include "flutter/lib/ui/painting/scene/scene_shader.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "flutter/lib/ui/window/platform_configuration.h"
#include "impeller/geometry/matrix.h"
#include "impeller/scene/animation/property_resolver.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/typed_data/typed_list.h"
namespace flutter {
IMPLEMENT_WRAPPERTYPEINFO(ui, SceneNode);
void SceneNode::Create(Dart_Handle wrapper) {
auto res = fml::MakeRefCounted<SceneNode>();
res->AssociateWithDartWrapper(wrapper);
}
std::string SceneNode::initFromAsset(const std::string& asset_name,
Dart_Handle completion_callback_handle) {
FML_TRACE_EVENT("flutter", "SceneNode::initFromAsset", "asset", asset_name);
if (!Dart_IsClosure(completion_callback_handle)) {
return "Completion callback must be a function.";
}
auto dart_state = UIDartState::Current();
if (!dart_state->IsImpellerEnabled()) {
return "3D scenes require the Impeller rendering backend to be enabled.";
}
std::shared_ptr<AssetManager> asset_manager =
dart_state->platform_configuration()->client()->GetAssetManager();
std::unique_ptr<fml::Mapping> data = asset_manager->GetAsMapping(asset_name);
if (data == nullptr) {
return std::string("Asset '") + asset_name + std::string("' not found.");
}
auto& task_runners = dart_state->GetTaskRunners();
std::promise<std::shared_ptr<impeller::Context>> context_promise;
auto impeller_context_promise = context_promise.get_future();
task_runners.GetIOTaskRunner()->PostTask(
fml::MakeCopyable([promise = std::move(context_promise),
io_manager = dart_state->GetIOManager()]() mutable {
promise.set_value(io_manager ? io_manager->GetImpellerContext()
: nullptr);
}));
auto persistent_completion_callback =
std::make_unique<tonic::DartPersistentValue>(dart_state,
completion_callback_handle);
auto ui_task = fml::MakeCopyable(
[this, callback = std::move(persistent_completion_callback)](
std::shared_ptr<impeller::scene::Node> node) mutable {
auto dart_state = callback->dart_state().lock();
if (!dart_state) {
// The root isolate could have died in the meantime.
return;
}
tonic::DartState::Scope scope(dart_state);
node_ = std::move(node);
tonic::DartInvoke(callback->Get(), {Dart_TypeVoid()});
// callback is associated with the Dart isolate and must be
// deleted on the UI thread.
callback.reset();
});
task_runners.GetRasterTaskRunner()->PostTask(
fml::MakeCopyable([ui_task = std::move(ui_task), task_runners,
impeller_context = impeller_context_promise.get(),
data = std::move(data)]() {
auto node = impeller::scene::Node::MakeFromFlatbuffer(
*data, *impeller_context->GetResourceAllocator());
task_runners.GetUITaskRunner()->PostTask(
[ui_task, node = std::move(node)]() { ui_task(node); });
}));
return "";
}
static impeller::Matrix ToMatrix(const tonic::Float64List& matrix4) {
return impeller::Matrix(static_cast<impeller::Scalar>(matrix4[0]),
static_cast<impeller::Scalar>(matrix4[1]),
static_cast<impeller::Scalar>(matrix4[2]),
static_cast<impeller::Scalar>(matrix4[3]),
static_cast<impeller::Scalar>(matrix4[4]),
static_cast<impeller::Scalar>(matrix4[5]),
static_cast<impeller::Scalar>(matrix4[6]),
static_cast<impeller::Scalar>(matrix4[7]),
static_cast<impeller::Scalar>(matrix4[8]),
static_cast<impeller::Scalar>(matrix4[9]),
static_cast<impeller::Scalar>(matrix4[10]),
static_cast<impeller::Scalar>(matrix4[11]),
static_cast<impeller::Scalar>(matrix4[12]),
static_cast<impeller::Scalar>(matrix4[13]),
static_cast<impeller::Scalar>(matrix4[14]),
static_cast<impeller::Scalar>(matrix4[15]));
}
void SceneNode::initFromTransform(const tonic::Float64List& matrix4) {
node_ = std::make_shared<impeller::scene::Node>();
node_->SetLocalTransform(ToMatrix(matrix4));
}
void SceneNode::AddChild(Dart_Handle scene_node_handle) {
if (!node_) {
return;
}
auto* scene_node =
tonic::DartConverter<SceneNode*>::FromDart(scene_node_handle);
if (!scene_node) {
return;
}
node_->AddChild(scene_node->node_);
children_.push_back(fml::Ref(scene_node));
}
void SceneNode::SetTransform(const tonic::Float64List& matrix4) {
impeller::scene::Node::MutationLog::SetTransformEntry entry = {
ToMatrix(matrix4)};
node_->AddMutation(entry);
}
void SceneNode::SetAnimationState(const std::string& animation_name,
bool playing,
bool loop,
double weight,
double time_scale) {
impeller::scene::Node::MutationLog::SetAnimationStateEntry entry = {
.animation_name = animation_name,
.playing = playing,
.loop = loop,
.weight = static_cast<float>(weight),
.time_scale = static_cast<float>(time_scale),
};
node_->AddMutation(entry);
}
void SceneNode::SeekAnimation(const std::string& animation_name, double time) {
impeller::scene::Node::MutationLog::SeekAnimationEntry entry = {
.animation_name = animation_name,
.time = static_cast<float>(time),
};
node_->AddMutation(entry);
}
SceneNode::SceneNode() = default;
SceneNode::~SceneNode() = default;
} // namespace flutter
| engine/lib/ui/painting/scene/scene_node.cc/0 | {
"file_path": "engine/lib/ui/painting/scene/scene_node.cc",
"repo_id": "engine",
"token_count": 2914
} | 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.
part of dart.ui;
/// How the pointer has changed since the last report.
enum PointerChange {
/// The input from the pointer is no longer directed towards this receiver.
cancel,
/// The device has started tracking the pointer.
///
/// For example, the pointer might be hovering above the device, having not yet
/// made contact with the surface of the device.
add,
/// The device is no longer tracking the pointer.
///
/// For example, the pointer might have drifted out of the device's hover
/// detection range or might have been disconnected from the system entirely.
remove,
/// The pointer has moved with respect to the device while not in contact with
/// the device.
hover,
/// The pointer has made contact with the device.
down,
/// The pointer has moved with respect to the device while in contact with the
/// device.
move,
/// The pointer has stopped making contact with the device.
up,
/// A pan/zoom has started on this pointer.
///
/// This type of event will always have kind [PointerDeviceKind.trackpad].
panZoomStart,
/// The pan/zoom on this pointer has updated.
///
/// This type of event will always have kind [PointerDeviceKind.trackpad].
panZoomUpdate,
/// The pan/zoom on this pointer has ended.
///
/// This type of event will always have kind [PointerDeviceKind.trackpad].
panZoomEnd,
}
/// The kind of pointer device.
enum PointerDeviceKind {
/// A touch-based pointer device.
///
/// The most common case is a touch screen.
///
/// When the user is operating with a trackpad on iOS, clicking will also
/// dispatch events with kind [touch] if
/// `UIApplicationSupportsIndirectInputEvents` is not present in `Info.plist`
/// or returns NO.
///
/// See also:
///
/// * [UIApplicationSupportsIndirectInputEvents](https://developer.apple.com/documentation/bundleresources/information_property_list/uiapplicationsupportsindirectinputevents?language=objc).
touch,
/// A mouse-based pointer device.
///
/// The most common case is a mouse on the desktop or Web.
///
/// When the user is operating with a trackpad on iOS, moving the pointing
/// cursor will also dispatch events with kind [mouse], and clicking will
/// dispatch events with kind [mouse] if
/// `UIApplicationSupportsIndirectInputEvents` is not present in `Info.plist`
/// or returns NO.
///
/// See also:
///
/// * [UIApplicationSupportsIndirectInputEvents](https://developer.apple.com/documentation/bundleresources/information_property_list/uiapplicationsupportsindirectinputevents?language=objc).
mouse,
/// A pointer device with a stylus.
stylus,
/// A pointer device with a stylus that has been inverted.
invertedStylus,
/// Gestures from a trackpad.
///
/// A trackpad here is defined as a touch-based pointer device with an
/// indirect surface (the user operates the screen by touching something that
/// is not the screen).
///
/// When the user makes zoom, pan, scroll or rotate gestures with a physical
/// trackpad, supporting platforms dispatch events with kind [trackpad].
///
/// Events with kind [trackpad] can only have a [PointerChange] of `add`,
/// `remove`, and pan-zoom related values.
///
/// Some platforms don't support (or don't fully support) trackpad
/// gestures, and might convert trackpad gestures into fake pointer events
/// that simulate dragging. These events typically have kind [touch] or
/// [mouse] instead of [trackpad]. This includes (but is not limited to) Web,
/// and iOS when `UIApplicationSupportsIndirectInputEvents` isn't present in
/// `Info.plist` or returns NO.
///
/// Moving the pointing cursor or clicking with a trackpad typically triggers
/// [touch] or [mouse] events, but never triggers [trackpad] events.
///
/// See also:
///
/// * [UIApplicationSupportsIndirectInputEvents](https://developer.apple.com/documentation/bundleresources/information_property_list/uiapplicationsupportsindirectinputevents?language=objc).
trackpad,
/// An unknown pointer device.
unknown
}
/// The kind of pointer signal event.
enum PointerSignalKind {
/// The event is not associated with a pointer signal.
none,
/// A pointer-generated scroll (e.g., mouse wheel or trackpad scroll).
scroll,
/// A pointer-generated scroll-inertia cancel.
scrollInertiaCancel,
/// A pointer-generated scale event (e.g. trackpad pinch).
scale,
/// An unknown pointer signal kind.
unknown
}
/// Information about the state of a pointer.
class PointerData {
/// Creates an object that represents the state of a pointer.
const PointerData({
this.viewId = 0,
this.embedderId = 0,
this.timeStamp = Duration.zero,
this.change = PointerChange.cancel,
this.kind = PointerDeviceKind.touch,
this.signalKind,
this.device = 0,
this.pointerIdentifier = 0,
this.physicalX = 0.0,
this.physicalY = 0.0,
this.physicalDeltaX = 0.0,
this.physicalDeltaY = 0.0,
this.buttons = 0,
this.obscured = false,
this.synthesized = false,
this.pressure = 0.0,
this.pressureMin = 0.0,
this.pressureMax = 0.0,
this.distance = 0.0,
this.distanceMax = 0.0,
this.size = 0.0,
this.radiusMajor = 0.0,
this.radiusMinor = 0.0,
this.radiusMin = 0.0,
this.radiusMax = 0.0,
this.orientation = 0.0,
this.tilt = 0.0,
this.platformData = 0,
this.scrollDeltaX = 0.0,
this.scrollDeltaY = 0.0,
this.panX = 0.0,
this.panY = 0.0,
this.panDeltaX = 0.0,
this.panDeltaY = 0.0,
this.scale = 0.0,
this.rotation = 0.0,
});
/// The ID of the [FlutterView] this [PointerEvent] originated from.
final int viewId;
/// Unique identifier that ties the [PointerEvent] to the embedder
/// event that created it.
/// it.
///
/// No two pointer events can have the same [embedderId]. This is different
/// from [pointerIdentifier] - used for hit-testing, whereas [embedderId] is
/// used to identify the platform event.
final int embedderId;
/// Time of event dispatch, relative to an arbitrary timeline.
final Duration timeStamp;
/// How the pointer has changed since the last report.
final PointerChange change;
/// The kind of input device for which the event was generated.
final PointerDeviceKind kind;
/// The kind of signal for a pointer signal event.
final PointerSignalKind? signalKind;
/// Unique identifier for the pointing device, reused across interactions.
final int device;
/// Unique identifier for the pointer.
///
/// This field changes for each new pointer down event. Framework uses this
/// identifier to determine hit test result.
final int pointerIdentifier;
/// X coordinate of the position of the pointer, in physical pixels in the
/// global coordinate space.
final double physicalX;
/// Y coordinate of the position of the pointer, in physical pixels in the
/// global coordinate space.
final double physicalY;
/// The distance of pointer movement on X coordinate in physical pixels.
final double physicalDeltaX;
/// The distance of pointer movement on Y coordinate in physical pixels.
final double physicalDeltaY;
/// Bit field using the *Button constants (primaryMouseButton,
/// secondaryStylusButton, etc). For example, if this has the value 6 and the
/// [kind] is [PointerDeviceKind.invertedStylus], then this indicates an
/// upside-down stylus with both its primary and secondary buttons pressed.
final int buttons;
/// Set if an application from a different security domain is in any way
/// obscuring this application's window. (Aspirational; not currently
/// implemented.)
final bool obscured;
/// Set if this pointer data was synthesized by pointer data packet converter.
/// pointer data packet converter will synthesize additional pointer datas if
/// the input sequence of pointer data is illegal.
///
/// For example, a down pointer data will be synthesized if the converter receives
/// a move pointer data while the pointer is not previously down.
final bool synthesized;
/// The pressure of the touch as a number ranging from 0.0, indicating a touch
/// with no discernible pressure, to 1.0, indicating a touch with "normal"
/// pressure, and possibly beyond, indicating a stronger touch. For devices
/// that do not detect pressure (e.g. mice), returns 1.0.
final double pressure;
/// The minimum value that [pressure] can return for this pointer. For devices
/// that do not detect pressure (e.g. mice), returns 1.0. This will always be
/// a number less than or equal to 1.0.
final double pressureMin;
/// The maximum value that [pressure] can return for this pointer. For devices
/// that do not detect pressure (e.g. mice), returns 1.0. This will always be
/// a greater than or equal to 1.0.
final double pressureMax;
/// The distance of the detected object from the input surface (e.g. the
/// distance of a stylus or finger from a touch screen), in arbitrary units on
/// an arbitrary (not necessarily linear) scale. If the pointer is down, this
/// is 0.0 by definition.
final double distance;
/// The maximum value that a distance can return for this pointer. If this
/// input device cannot detect "hover touch" input events, then this will be
/// 0.0.
final double distanceMax;
/// The area of the screen being pressed, scaled to a value between 0 and 1.
/// The value of size can be used to determine fat touch events. This value
/// is only set on Android, and is a device specific approximation within
/// the range of detectable values. So, for example, the value of 0.1 could
/// mean a touch with the tip of the finger, 0.2 a touch with full finger,
/// and 0.3 the full palm.
final double size;
/// The radius of the contact ellipse along the major axis, in logical pixels.
final double radiusMajor;
/// The radius of the contact ellipse along the minor axis, in logical pixels.
final double radiusMinor;
/// The minimum value that could be reported for radiusMajor and radiusMinor
/// for this pointer, in logical pixels.
final double radiusMin;
/// The minimum value that could be reported for radiusMajor and radiusMinor
/// for this pointer, in logical pixels.
final double radiusMax;
/// For PointerDeviceKind.touch events:
///
/// The angle of the contact ellipse, in radius in the range:
///
/// -pi/2 < orientation <= pi/2
///
/// ...giving the angle of the major axis of the ellipse with the y-axis
/// (negative angles indicating an orientation along the top-left /
/// bottom-right diagonal, positive angles indicating an orientation along the
/// top-right / bottom-left diagonal, and zero indicating an orientation
/// parallel with the y-axis).
///
/// For PointerDeviceKind.stylus and PointerDeviceKind.invertedStylus events:
///
/// The angle of the stylus, in radians in the range:
///
/// -pi < orientation <= pi
///
/// ...giving the angle of the axis of the stylus projected onto the input
/// surface, relative to the positive y-axis of that surface (thus 0.0
/// indicates the stylus, if projected onto that surface, would go from the
/// contact point vertically up in the positive y-axis direction, pi would
/// indicate that the stylus would go down in the negative y-axis direction;
/// pi/4 would indicate that the stylus goes up and to the right, -pi/2 would
/// indicate that the stylus goes to the left, etc).
final double orientation;
/// For PointerDeviceKind.stylus and PointerDeviceKind.invertedStylus events:
///
/// The angle of the stylus, in radians in the range:
///
/// 0 <= tilt <= pi/2
///
/// ...giving the angle of the axis of the stylus, relative to the axis
/// perpendicular to the input surface (thus 0.0 indicates the stylus is
/// orthogonal to the plane of the input surface, while pi/2 indicates that
/// the stylus is flat on that surface).
final double tilt;
/// Opaque platform-specific data associated with the event.
final int platformData;
/// For events with signalKind of PointerSignalKind.scroll:
///
/// The amount to scroll in the x direction, in physical pixels.
final double scrollDeltaX;
/// For events with signalKind of PointerSignalKind.scroll:
///
/// The amount to scroll in the y direction, in physical pixels.
final double scrollDeltaY;
/// For events with change of PointerChange.panZoomUpdate:
///
/// The current panning magnitude of the pan/zoom in the x direction, in
/// physical pixels.
final double panX;
/// For events with change of PointerChange.panZoomUpdate:
///
/// The current panning magnitude of the pan/zoom in the y direction, in
/// physical pixels.
final double panY;
/// For events with change of PointerChange.panZoomUpdate:
///
/// The difference in panning of the pan/zoom in the x direction since the
/// latest panZoomUpdate event, in physical pixels.
final double panDeltaX;
/// For events with change of PointerChange.panZoomUpdate:
///
/// The difference in panning of the pan/zoom in the y direction since the
/// last panZoomUpdate event, in physical pixels.
final double panDeltaY;
/// For events with change of PointerChange.panZoomUpdate:
///
/// The current scale of the pan/zoom (unitless), with 1.0 as the initial scale.
final double scale;
/// For events with change of PointerChange.panZoomUpdate:
///
/// The current angle of the pan/zoom in radians, with 0.0 as the initial angle.
final double rotation;
@override
String toString() => 'PointerData(viewId: $viewId, x: $physicalX, y: $physicalY)';
/// Returns a complete textual description of the information in this object.
String toStringFull() {
return '$runtimeType('
'embedderId: $embedderId, '
'timeStamp: $timeStamp, '
'change: $change, '
'kind: $kind, '
'signalKind: $signalKind, '
'device: $device, '
'pointerIdentifier: $pointerIdentifier, '
'physicalX: $physicalX, '
'physicalY: $physicalY, '
'physicalDeltaX: $physicalDeltaX, '
'physicalDeltaY: $physicalDeltaY, '
'buttons: $buttons, '
'synthesized: $synthesized, '
'pressure: $pressure, '
'pressureMin: $pressureMin, '
'pressureMax: $pressureMax, '
'distance: $distance, '
'distanceMax: $distanceMax, '
'size: $size, '
'radiusMajor: $radiusMajor, '
'radiusMinor: $radiusMinor, '
'radiusMin: $radiusMin, '
'radiusMax: $radiusMax, '
'orientation: $orientation, '
'tilt: $tilt, '
'platformData: $platformData, '
'scrollDeltaX: $scrollDeltaX, '
'scrollDeltaY: $scrollDeltaY, '
'panX: $panX, '
'panY: $panY, '
'panDeltaX: $panDeltaX, '
'panDeltaY: $panDeltaY, '
'scale: $scale, '
'rotation: $rotation, '
'viewId: $viewId'
')';
}
}
/// A sequence of reports about the state of pointers.
class PointerDataPacket {
/// Creates a packet of pointer data reports.
const PointerDataPacket({ this.data = const <PointerData>[] });
/// Data about the individual pointers in this packet.
///
/// This list might contain multiple pieces of data about the same pointer.
final List<PointerData> data;
}
| engine/lib/ui/pointer.dart/0 | {
"file_path": "engine/lib/ui/pointer.dart",
"repo_id": "engine",
"token_count": 4840
} | 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 "flutter/lib/ui/text/asset_manager_font_provider.h"
#include <utility>
#include "flutter/fml/logging.h"
#include "third_party/skia/include/core/SkData.h"
#include "third_party/skia/include/core/SkFontMgr.h"
#include "third_party/skia/include/core/SkStream.h"
#include "third_party/skia/include/core/SkString.h"
#include "third_party/skia/include/core/SkTypeface.h"
#include "txt/platform.h"
namespace flutter {
namespace {
void MappingReleaseProc(const void* ptr, void* context) {
delete reinterpret_cast<fml::Mapping*>(context);
}
} // anonymous namespace
AssetManagerFontProvider::AssetManagerFontProvider(
std::shared_ptr<AssetManager> asset_manager)
: asset_manager_(std::move(asset_manager)) {}
AssetManagerFontProvider::~AssetManagerFontProvider() = default;
// |FontAssetProvider|
size_t AssetManagerFontProvider::GetFamilyCount() const {
return family_names_.size();
}
// |FontAssetProvider|
std::string AssetManagerFontProvider::GetFamilyName(int index) const {
FML_DCHECK(index >= 0 && static_cast<size_t>(index) < family_names_.size());
return family_names_[index];
}
// |FontAssetProvider|
sk_sp<SkFontStyleSet> AssetManagerFontProvider::MatchFamily(
const std::string& family_name) {
auto found = registered_families_.find(CanonicalFamilyName(family_name));
if (found == registered_families_.end()) {
return nullptr;
}
return found->second;
}
void AssetManagerFontProvider::RegisterAsset(const std::string& family_name,
const std::string& asset) {
std::string canonical_name = CanonicalFamilyName(family_name);
auto family_it = registered_families_.find(canonical_name);
if (family_it == registered_families_.end()) {
family_names_.push_back(family_name);
auto value = std::make_pair(
canonical_name,
sk_make_sp<AssetManagerFontStyleSet>(asset_manager_, family_name));
family_it = registered_families_.emplace(value).first;
}
family_it->second->registerAsset(asset);
}
AssetManagerFontStyleSet::AssetManagerFontStyleSet(
std::shared_ptr<AssetManager> asset_manager,
std::string family_name)
: asset_manager_(std::move(asset_manager)),
family_name_(std::move(family_name)) {}
AssetManagerFontStyleSet::~AssetManagerFontStyleSet() = default;
void AssetManagerFontStyleSet::registerAsset(const std::string& asset) {
assets_.emplace_back(asset);
}
int AssetManagerFontStyleSet::count() {
return assets_.size();
}
void AssetManagerFontStyleSet::getStyle(int index,
SkFontStyle* style,
SkString* name) {
FML_DCHECK(index < static_cast<int>(assets_.size()));
if (style) {
sk_sp<SkTypeface> typeface(createTypeface(index));
if (typeface) {
*style = typeface->fontStyle();
}
}
if (name) {
*name = family_name_.c_str();
}
}
auto AssetManagerFontStyleSet::createTypeface(int i) -> CreateTypefaceRet {
size_t index = i;
if (index >= assets_.size()) {
return nullptr;
}
TypefaceAsset& asset = assets_[index];
if (!asset.typeface) {
std::unique_ptr<fml::Mapping> asset_mapping =
asset_manager_->GetAsMapping(asset.asset);
if (asset_mapping == nullptr) {
return nullptr;
}
fml::Mapping* asset_mapping_ptr = asset_mapping.release();
sk_sp<SkData> asset_data = SkData::MakeWithProc(
asset_mapping_ptr->GetMapping(), asset_mapping_ptr->GetSize(),
MappingReleaseProc, asset_mapping_ptr);
std::unique_ptr<SkMemoryStream> stream = SkMemoryStream::Make(asset_data);
sk_sp<SkFontMgr> font_mgr = txt::GetDefaultFontManager();
// Ownership of the stream is transferred.
asset.typeface = font_mgr->makeFromStream(std::move(stream));
if (!asset.typeface) {
FML_DLOG(ERROR) << "Unable to load font asset for family: "
<< family_name_;
return nullptr;
}
}
return CreateTypefaceRet(SkRef(asset.typeface.get()));
}
auto AssetManagerFontStyleSet::matchStyle(const SkFontStyle& pattern)
-> MatchStyleRet {
return matchStyleCSS3(pattern);
}
AssetManagerFontStyleSet::TypefaceAsset::TypefaceAsset(std::string a)
: asset(std::move(a)) {}
AssetManagerFontStyleSet::TypefaceAsset::TypefaceAsset(
const AssetManagerFontStyleSet::TypefaceAsset& other) = default;
AssetManagerFontStyleSet::TypefaceAsset::~TypefaceAsset() = default;
} // namespace flutter
| engine/lib/ui/text/asset_manager_font_provider.cc/0 | {
"file_path": "engine/lib/ui/text/asset_manager_font_provider.cc",
"repo_id": "engine",
"token_count": 1706
} | 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.
#ifndef FLUTTER_LIB_UI_WINDOW_KEY_DATA_H_
#define FLUTTER_LIB_UI_WINDOW_KEY_DATA_H_
#include <cstdint>
namespace flutter {
// If this value changes, update the encoding code in the following files:
//
// * KeyData.java (KeyData.FIELD_COUNT)
// * platform_dispatcher.dart (_kKeyDataFieldCount)
static constexpr int kKeyDataFieldCount = 6;
static constexpr int kBytesPerKeyField = sizeof(int64_t);
// The change of the key event, used by KeyData.
//
// Must match the KeyEventType enum in ui/key.dart.
enum class KeyEventType : int64_t {
kDown = 0,
kUp,
kRepeat,
};
// The source device for the key event.
//
// Not all platforms supply an accurate source.
//
// Defaults to [keyboard].
// Must match the KeyEventDeviceType enum in ui/key.dart.
enum class KeyEventDeviceType : int64_t {
// The source is a keyboard.
kKeyboard = 0,
// The source is a directional pad on something like a television remote
// control or similar.
kDirectionalPad,
// The source is a gamepad button.
kGamepad,
// The source is a joystick button.
kJoystick,
// The source is a device connected to an HDMI bus.
kHdmi,
};
// The fixed-length sections of a KeyDataPacket.
//
// KeyData does not contain `character`, for variable-length data are stored in
// a different way in KeyDataPacket.
//
// This structure is unpacked by hooks.dart.
//
// Changes to this struct must also be made to
// io/flutter/embedding/android/KeyData.java.
struct alignas(8) KeyData {
// Timestamp in microseconds from an arbitrary and consistent start point
uint64_t timestamp;
KeyEventType type;
uint64_t physical;
uint64_t logical;
// True if the event does not correspond to a native event.
//
// The value is 1 for true, and 0 for false.
uint64_t synthesized;
KeyEventDeviceType device_type;
// Sets all contents of `Keydata` to 0.
void Clear();
};
} // namespace flutter
#endif // FLUTTER_LIB_UI_WINDOW_KEY_DATA_H_
| engine/lib/ui/window/key_data.h/0 | {
"file_path": "engine/lib/ui/window/key_data.h",
"repo_id": "engine",
"token_count": 672
} | 248 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/common/task_runners.h"
#include "flutter/fml/mapping.h"
#include "flutter/fml/synchronization/waitable_event.h"
#include "flutter/lib/ui/window/platform_message_response_dart_port.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"
namespace flutter {
namespace testing {
TEST_F(ShellTest, PlatformMessageResponseDartPort) {
bool did_pass = false;
auto message_latch = std::make_shared<fml::AutoResetWaitableEvent>();
TaskRunners task_runners("test", // label
GetCurrentTaskRunner(), // platform
CreateNewThread(), // raster
CreateNewThread(), // ui
CreateNewThread() // io
);
auto nativeCallPlatformMessageResponseDartPort =
[ui_task_runner =
task_runners.GetUITaskRunner()](Dart_NativeArguments args) {
auto dart_state = std::make_shared<tonic::DartState>();
auto response = fml::MakeRefCounted<PlatformMessageResponseDartPort>(
tonic::DartConverter<int64_t>::FromDart(
Dart_GetNativeArgument(args, 0)),
123, "foobar");
uint8_t* data = static_cast<uint8_t*>(malloc(100));
auto mapping = std::make_unique<fml::MallocMapping>(data, 100);
response->Complete(std::move(mapping));
};
AddNativeCallback(
"CallPlatformMessageResponseDartPort",
CREATE_NATIVE_ENTRY(nativeCallPlatformMessageResponseDartPort));
auto nativeFinishCallResponse = [message_latch,
&did_pass](Dart_NativeArguments args) {
did_pass =
tonic::DartConverter<bool>::FromDart(Dart_GetNativeArgument(args, 0));
message_latch->Signal();
};
AddNativeCallback("FinishCallResponse",
CREATE_NATIVE_ENTRY(nativeFinishCallResponse));
Settings settings = CreateSettingsForFixture();
std::unique_ptr<Shell> shell = CreateShell(settings, task_runners);
ASSERT_TRUE(shell->IsSetup());
auto configuration = RunConfiguration::InferFromSettings(settings);
configuration.SetEntrypoint("platformMessagePortResponseTest");
shell->RunEngine(std::move(configuration), [](auto result) {
ASSERT_EQ(result, Engine::RunStatus::Success);
});
message_latch->Wait();
ASSERT_TRUE(did_pass);
DestroyShell(std::move(shell), task_runners);
}
} // namespace testing
} // namespace flutter
| engine/lib/ui/window/platform_message_response_dart_port_unittests.cc/0 | {
"file_path": "engine/lib/ui/window/platform_message_response_dart_port_unittests.cc",
"repo_id": "engine",
"token_count": 1079
} | 249 |
# For more information on test and runner configurations:
#
# * https://github.com/dart-lang/test/blob/master/pkgs/test/doc/configuration.md#platforms
platforms:
- chrome
- vm
| engine/lib/web_ui/dart_test_chrome.yaml/0 | {
"file_path": "engine/lib/web_ui/dart_test_chrome.yaml",
"repo_id": "engine",
"token_count": 61
} | 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.
class BrowserInstallerException implements Exception {
BrowserInstallerException(this.message);
final String message;
@override
String toString() => message;
}
/// Throw this exception in felt command to exit felt with a message and a
/// non-zero exit code.
class ToolExit implements Exception {
ToolExit(this.message, { this.exitCode = 1 });
final String message;
final int exitCode;
@override
String toString() => message;
}
| engine/lib/web_ui/dev/exceptions.dart/0 | {
"file_path": "engine/lib/web_ui/dev/exceptions.dart",
"repo_id": "engine",
"token_count": 162
} | 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.
import 'dart:convert' show JsonEncoder;
import 'dart:io' as io;
import 'package:path/path.dart' as pathlib;
import '../environment.dart';
import '../exceptions.dart';
import '../felt_config.dart';
import '../pipeline.dart';
import '../utils.dart';
class CopyArtifactsStep implements PipelineStep {
CopyArtifactsStep(this.artifactDeps, { required this.runtimeMode });
final ArtifactDependencies artifactDeps;
final RuntimeMode runtimeMode;
@override
String get description => 'copy_artifacts';
@override
bool get isSafeToInterrupt => true;
@override
Future<void> interrupt() async {
await cleanup();
}
@override
Future<void> run() async {
await environment.webTestsArtifactsDir.create(recursive: true);
await buildHostPage();
await copyTestFonts();
await copySkiaTestImages();
await copyFlutterJsFiles();
if (artifactDeps.canvasKit) {
print('Copying CanvasKit...');
await copyCanvasKitFiles('canvaskit', 'canvaskit');
}
if (artifactDeps.canvasKitChromium) {
print('Copying CanvasKit (Chromium)...');
await copyCanvasKitFiles('canvaskit_chromium', 'canvaskit/chromium');
}
if (artifactDeps.skwasm) {
print('Copying Skwasm...');
await copySkwasm();
}
}
Future<void> copyTestFonts() async {
const Map<String, String> testFonts = <String, String>{
'Ahem': 'ahem.ttf',
'Roboto': 'Roboto-Regular.ttf',
'RobotoVariable': 'RobotoSlab-VariableFont_wght.ttf',
'Noto Naskh Arabic UI': 'NotoNaskhArabic-Regular.ttf',
'Noto Color Emoji': 'NotoColorEmoji.ttf',
};
final String fontsPath = pathlib.join(
environment.flutterDirectory.path,
'third_party',
'txt',
'third_party',
'fonts',
);
final List<dynamic> fontManifest = <dynamic>[];
for (final MapEntry<String, String> fontEntry in testFonts.entries) {
final String family = fontEntry.key;
final String fontFile = fontEntry.value;
fontManifest.add(<String, dynamic>{
'family': family,
'fonts': <dynamic>[
<String, String>{
'asset': 'fonts/$fontFile',
},
],
});
final io.File sourceTtf = io.File(pathlib.join(fontsPath, fontFile));
final io.File destinationTtf = io.File(pathlib.join(
environment.webTestsArtifactsDir.path,
'assets',
'fonts',
fontFile,
));
await destinationTtf.create(recursive: true);
await sourceTtf.copy(destinationTtf.path);
}
final io.File fontManifestFile = io.File(pathlib.join(
environment.webTestsArtifactsDir.path,
'assets',
'FontManifest.json',
));
await fontManifestFile.create(recursive: true);
await fontManifestFile.writeAsString(
const JsonEncoder.withIndent(' ').convert(fontManifest),
);
final io.Directory fallbackFontsSource = io.Directory(pathlib.join(
environment.engineSrcDir.path,
'flutter',
'third_party',
'google_fonts_for_unit_tests',
));
final String fallbackFontsDestinationPath = pathlib.join(
environment.webTestsArtifactsDir.path,
'assets',
'fallback_fonts',
);
for (final io.File file in
fallbackFontsSource.listSync(recursive: true).whereType<io.File>()
) {
final String relativePath = pathlib.relative(file.path, from: fallbackFontsSource.path);
final io.File destinationFile = io.File(pathlib.join(fallbackFontsDestinationPath, relativePath));
if (!destinationFile.parent.existsSync()) {
destinationFile.parent.createSync(recursive: true);
}
file.copySync(destinationFile.path);
}
}
Future<void> copySkiaTestImages() async {
final io.Directory testImagesDir = io.Directory(pathlib.join(
environment.engineSrcDir.path,
'flutter',
'third_party',
'skia',
'resources',
'images',
));
for (final io.File imageFile in testImagesDir.listSync(recursive: true).whereType<io.File>()) {
final io.File destination = io.File(pathlib.join(
environment.webTestsArtifactsDir.path,
'test_images',
pathlib.relative(imageFile.path, from: testImagesDir.path),
));
destination.createSync(recursive: true);
await imageFile.copy(destination.path);
}
}
Future<void> copyFlutterJsFiles() async {
final io.Directory flutterJsInputDirectory = io.Directory(pathlib.join(
outBuildPath,
'flutter_web_sdk',
'flutter_js',
));
final String targetDirectoryPath = pathlib.join(
environment.webTestsArtifactsDir.path,
'flutter_js',
);
for (final io.File sourceFile in flutterJsInputDirectory
.listSync(recursive: true)
.whereType<io.File>()
) {
final String relativePath = pathlib.relative(
sourceFile.path,
from: flutterJsInputDirectory.path
);
final String targetPath = pathlib.join(
targetDirectoryPath,
relativePath,
);
final io.File targetFile = io.File(targetPath);
if (!targetFile.parent.existsSync()) {
targetFile.parent.createSync(recursive: true);
}
sourceFile.copySync(targetPath);
}
}
Future<void> copyCanvasKitFiles(String sourcePath, String destinationPath) async {
final String sourceDirectoryPath = pathlib.join(
outBuildPath,
sourcePath,
);
final String targetDirectoryPath = pathlib.join(
environment.webTestsArtifactsDir.path,
destinationPath,
);
for (final String filename in <String>[
'canvaskit.js',
'canvaskit.wasm',
'canvaskit.wasm.map',
]) {
final io.File sourceFile = io.File(pathlib.join(
sourceDirectoryPath,
filename,
));
final io.File targetFile = io.File(pathlib.join(
targetDirectoryPath,
filename,
));
if (!sourceFile.existsSync()) {
if (filename.endsWith('.map')) {
// Sourcemaps are only generated under certain build conditions, so
// they are optional.
continue;
} {
throw ToolExit('Built CanvasKit artifact not found at path "$sourceFile".');
}
}
await targetFile.create(recursive: true);
await sourceFile.copy(targetFile.path);
}
}
String get outBuildPath => getBuildDirectoryForRuntimeMode(runtimeMode).path;
Future<void> copySkwasm() async {
final io.Directory targetDir = io.Directory(pathlib.join(
environment.webTestsArtifactsDir.path,
'canvaskit',
));
await targetDir.create(recursive: true);
for (final String fileName in <String>[
'skwasm.wasm',
'skwasm.wasm.map',
'skwasm.js',
'skwasm.worker.js',
]) {
final io.File sourceFile = io.File(pathlib.join(
outBuildPath,
'flutter_web_sdk',
'canvaskit',
fileName,
));
if (!sourceFile.existsSync()) {
if (fileName.endsWith('.map')) {
// Sourcemaps are only generated under certain build conditions, so
// they are optional.
continue;
} {
throw ToolExit('Built Skwasm artifact not found at path "$sourceFile".');
}
}
final io.File targetFile = io.File(pathlib.join(
targetDir.path,
fileName,
));
await sourceFile.copy(targetFile.path);
}
}
Future<void> buildHostPage() async {
final String hostDartPath = pathlib.join('lib', 'static', 'host.dart');
final io.File hostDartFile = io.File(pathlib.join(
environment.webEngineTesterRootDir.path,
hostDartPath,
));
final String targetDirectoryPath = pathlib.join(
environment.webTestsArtifactsDir.path,
'host',
);
io.Directory(targetDirectoryPath).createSync(recursive: true);
final String targetFilePath = pathlib.join(
targetDirectoryPath,
'host.dart',
);
const List<String> staticFiles = <String>[
'favicon.ico',
'host.css',
'index.html',
];
for (final String staticFilePath in staticFiles) {
final io.File source = io.File(pathlib.join(
environment.webEngineTesterRootDir.path,
'lib',
'static',
staticFilePath,
));
final io.File destination = io.File(pathlib.join(
targetDirectoryPath,
staticFilePath,
));
await source.copy(destination.path);
}
final io.File timestampFile = io.File(pathlib.join(
environment.webEngineTesterRootDir.path,
'$targetFilePath.js.timestamp',
));
final String timestamp =
hostDartFile.statSync().modified.millisecondsSinceEpoch.toString();
if (timestampFile.existsSync()) {
final String lastBuildTimestamp = timestampFile.readAsStringSync();
if (lastBuildTimestamp == timestamp) {
// The file is still fresh. No need to rebuild.
return;
} else {
// Record new timestamp, but don't return. We need to rebuild.
print('${hostDartFile.path} timestamp changed. Rebuilding.');
}
} else {
print('Building ${hostDartFile.path}.');
}
int exitCode = await runProcess(
environment.dartExecutable,
<String>[
'pub',
'get',
],
workingDirectory: environment.webEngineTesterRootDir.path
);
if (exitCode != 0) {
throw ToolExit(
'Failed to run pub get for web_engine_tester, exit code $exitCode',
exitCode: exitCode,
);
}
exitCode = await runProcess(
environment.dartExecutable,
<String>[
'compile',
'js',
hostDartPath,
'-o',
'$targetFilePath.js',
],
workingDirectory: environment.webEngineTesterRootDir.path,
);
if (exitCode != 0) {
throw ToolExit(
'Failed to compile ${hostDartFile.path}. Compiler '
'exited with exit code $exitCode',
exitCode: exitCode,
);
}
// Record the timestamp to avoid rebuilding unless the file changes.
timestampFile.writeAsStringSync(timestamp);
}
}
| engine/lib/web_ui/dev/steps/copy_artifacts_step.dart/0 | {
"file_path": "engine/lib/web_ui/dev/steps/copy_artifacts_step.dart",
"repo_id": "engine",
"token_count": 4222
} | 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.
import { browserEnvironment } from './browser_environment.js';
import { FlutterEntrypointLoader } from './entrypoint_loader.js';
import { FlutterServiceWorkerLoader } from './service_worker_loader.js';
import { FlutterTrustedTypesPolicy } from './trusted_types.js';
import { loadCanvasKit } from './canvaskit_loader.js';
import { loadSkwasm } from './skwasm_loader.js';
/**
* The public interface of _flutter.loader. Exposes two methods:
* * loadEntrypoint (which coordinates the default Flutter web loading procedure)
* * didCreateEngineInitializer (which is called by Flutter to notify that its
* Engine is ready to be initialized)
*/
export class FlutterLoader {
/**
* @deprecated Use `load` instead.
* Initializes the Flutter web app.
* @param {*} options
* @returns {Promise?} a (Deprecated) Promise that will eventually resolve
* with an EngineInitializer, or will be rejected with
* any error caused by the loader. Or Null, if the user
* supplies an `onEntrypointLoaded` Function as an option.
*/
async loadEntrypoint(options) {
const { serviceWorker, ...entrypoint } = options || {};
// A Trusted Types policy that is going to be used by the loader.
const flutterTT = new FlutterTrustedTypesPolicy();
// The FlutterServiceWorkerLoader instance could be injected as a dependency
// (and dynamically imported from a module if not present).
const serviceWorkerLoader = new FlutterServiceWorkerLoader();
serviceWorkerLoader.setTrustedTypesPolicy(flutterTT.policy);
await serviceWorkerLoader.loadServiceWorker(serviceWorker).catch(e => {
// Regardless of what happens with the injection of the SW, the show must go on
console.warn("Exception while loading service worker:", e);
});
// The FlutterEntrypointLoader instance could be injected as a dependency
// (and dynamically imported from a module if not present).
const entrypointLoader = new FlutterEntrypointLoader();
entrypointLoader.setTrustedTypesPolicy(flutterTT.policy);
// Install the `didCreateEngineInitializer` listener where Flutter web expects it to be.
this.didCreateEngineInitializer =
entrypointLoader.didCreateEngineInitializer.bind(entrypointLoader);
return entrypointLoader.loadEntrypoint(entrypoint);
}
/**
* Loads and initializes a flutter application.
* @param {Object} options
* @param {import("/.types".ServiceWorkerSettings?)} options.serviceWorkerSettings
* Settings for the service worker to be loaded. Can pass `undefined` or
* `null` to not launch a service worker at all.
* @param {import("/.types".OnEntryPointLoadedCallback)} options.onEntrypointLoaded
* An optional callback to invoke
* @param {string} options.nonce
* A nonce to be applied to the main JS script when loading it, which may
* be required by the sites Content-Security-Policy.
* For more details, see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src here}.
* @param {import("./types".FlutterConfiguration)} arg.config
*/
async load({
serviceWorkerSettings,
onEntrypointLoaded,
nonce,
config,
} = {}) {
config ??= {};
/** @type {import("./types").BuildConfig} */
const buildConfig = _flutter.buildConfig;
if (!buildConfig) {
throw "FlutterLoader.load requires _flutter.buildConfig to be set";
}
const rendererIsCompatible = (renderer) => {
switch (renderer) {
case "skwasm":
return browserEnvironment.crossOriginIsolated
&& browserEnvironment.hasChromiumBreakIterators
&& browserEnvironment.hasImageCodecs
&& browserEnvironment.supportsWasmGC;
default:
return true;
}
}
const buildIsCompatible = (build) => {
if (build.compileTarget === "dart2wasm" && !browserEnvironment.supportsWasmGC) {
return false;
}
if (config.renderer && config.renderer != build.renderer) {
return false;
}
return rendererIsCompatible(build.renderer);
};
const build = buildConfig.builds.find(buildIsCompatible);
if (!build) {
throw "FlutterLoader could not find a build compatible with configuration and environment.";
}
const deps = {};
deps.flutterTT = new FlutterTrustedTypesPolicy();
if (serviceWorkerSettings) {
deps.serviceWorkerLoader = new FlutterServiceWorkerLoader();
deps.serviceWorkerLoader.setTrustedTypesPolicy(deps.flutterTT.policy);
await deps.serviceWorkerLoader.loadServiceWorker(serviceWorkerSettings).catch(e => {
// Regardless of what happens with the injection of the SW, the show must go on
console.warn("Exception while loading service worker:", e);
});
}
if (build.renderer === "canvaskit") {
deps.canvasKit = loadCanvasKit(deps, config, browserEnvironment, buildConfig.engineRevision);
} else if (build.renderer === "skwasm") {
deps.skwasm = loadSkwasm(deps, config, browserEnvironment, buildConfig.engineRevision);
}
// The FlutterEntrypointLoader instance could be injected as a dependency
// (and dynamically imported from a module if not present).
const entrypointLoader = new FlutterEntrypointLoader();
entrypointLoader.setTrustedTypesPolicy(deps.flutterTT.policy);
// Install the `didCreateEngineInitializer` listener where Flutter web expects it to be.
this.didCreateEngineInitializer =
entrypointLoader.didCreateEngineInitializer.bind(entrypointLoader);
return entrypointLoader.load(build, deps, config, nonce, onEntrypointLoaded);
}
}
| engine/lib/web_ui/flutter_js/src/loader.js/0 | {
"file_path": "engine/lib/web_ui/flutter_js/src/loader.js",
"repo_id": "engine",
"token_count": 1970
} | 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.
// For documentation see https://github.com/flutter/engine/blob/main/lib/ui/painting.dart
part of ui;
void _validateColorStops(List<Color> colors, List<double>? colorStops) {
if (colorStops == null) {
if (colors.length != 2) {
throw ArgumentError('"colors" must have length 2 if "colorStops" is omitted.');
}
} else {
if (colors.length != colorStops.length) {
throw ArgumentError('"colors" and "colorStops" arguments must have equal length.');
}
}
}
Color _scaleAlpha(Color a, double factor) {
return a.withAlpha(engine.clampInt((a.alpha * factor).round(), 0, 255));
}
class Color {
const Color(int value) : value = value & 0xFFFFFFFF;
const Color.fromARGB(int a, int r, int g, int b)
: value = (((a & 0xff) << 24) |
((r & 0xff) << 16) |
((g & 0xff) << 8) |
((b & 0xff) << 0)) &
0xFFFFFFFF;
const Color.fromRGBO(int r, int g, int b, double opacity)
: value = ((((opacity * 0xff ~/ 1) & 0xff) << 24) |
((r & 0xff) << 16) |
((g & 0xff) << 8) |
((b & 0xff) << 0)) &
0xFFFFFFFF;
final int value;
int get alpha => (0xff000000 & value) >> 24;
double get opacity => alpha / 0xFF;
int get red => (0x00ff0000 & value) >> 16;
int get green => (0x0000ff00 & value) >> 8;
int get blue => (0x000000ff & value) >> 0;
Color withAlpha(int a) {
return Color.fromARGB(a, red, green, blue);
}
Color withOpacity(double opacity) {
assert(opacity >= 0.0 && opacity <= 1.0);
return withAlpha((255.0 * opacity).round());
}
Color withRed(int r) {
return Color.fromARGB(alpha, r, green, blue);
}
Color withGreen(int g) {
return Color.fromARGB(alpha, red, g, blue);
}
Color withBlue(int b) {
return Color.fromARGB(alpha, red, green, b);
}
// See <https://www.w3.org/TR/WCAG20/#relativeluminancedef>
static double _linearizeColorComponent(double component) {
if (component <= 0.03928) {
return component / 12.92;
}
return math.pow((component + 0.055) / 1.055, 2.4) as double;
}
double computeLuminance() {
// See <https://www.w3.org/TR/WCAG20/#relativeluminancedef>
final double R = _linearizeColorComponent(red / 0xFF);
final double G = _linearizeColorComponent(green / 0xFF);
final double B = _linearizeColorComponent(blue / 0xFF);
return 0.2126 * R + 0.7152 * G + 0.0722 * B;
}
static Color? lerp(Color? a, Color? b, double t) {
if (b == null) {
if (a == null) {
return null;
} else {
return _scaleAlpha(a, 1.0 - t);
}
} else {
if (a == null) {
return _scaleAlpha(b, t);
} else {
return Color.fromARGB(
engine.clampInt(_lerpInt(a.alpha, b.alpha, t).toInt(), 0, 255),
engine.clampInt(_lerpInt(a.red, b.red, t).toInt(), 0, 255),
engine.clampInt(_lerpInt(a.green, b.green, t).toInt(), 0, 255),
engine.clampInt(_lerpInt(a.blue, b.blue, t).toInt(), 0, 255),
);
}
}
}
static Color alphaBlend(Color foreground, Color background) {
final int alpha = foreground.alpha;
if (alpha == 0x00) {
// Foreground completely transparent.
return background;
}
final int invAlpha = 0xff - alpha;
int backAlpha = background.alpha;
if (backAlpha == 0xff) {
// Opaque background case
return Color.fromARGB(
0xff,
(alpha * foreground.red + invAlpha * background.red) ~/ 0xff,
(alpha * foreground.green + invAlpha * background.green) ~/ 0xff,
(alpha * foreground.blue + invAlpha * background.blue) ~/ 0xff,
);
} else {
// General case
backAlpha = (backAlpha * invAlpha) ~/ 0xff;
final int outAlpha = alpha + backAlpha;
assert(outAlpha != 0x00);
return Color.fromARGB(
outAlpha,
(foreground.red * alpha + background.red * backAlpha) ~/ outAlpha,
(foreground.green * alpha + background.green * backAlpha) ~/ outAlpha,
(foreground.blue * alpha + background.blue * backAlpha) ~/ outAlpha,
);
}
}
static int getAlphaFromOpacity(double opacity) {
return (clampDouble(opacity, 0.0, 1.0) * 255).round();
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is Color && other.value == value;
}
@override
int get hashCode => value.hashCode;
@override
String toString() {
return 'Color(0x${value.toRadixString(16).padLeft(8, '0')})';
}
}
enum StrokeCap {
butt,
round,
square,
}
// These enum values must be kept in sync with SkPaint::Join.
enum StrokeJoin {
miter,
round,
bevel,
}
enum PaintingStyle {
fill,
stroke,
}
enum BlendMode {
// This list comes from Skia's SkXfermode.h and the values (order) should be
// kept in sync.
// See: https://skia.org/user/api/skpaint#SkXfermode
clear,
src,
dst,
srcOver,
dstOver,
srcIn,
dstIn,
srcOut,
dstOut,
srcATop,
dstATop,
xor,
plus,
modulate,
// Following blend modes are defined in the CSS Compositing standard.
screen, // The last coeff mode.
overlay,
darken,
lighten,
colorDodge,
colorBurn,
hardLight,
softLight,
difference,
exclusion,
multiply, // The last separable mode.
hue,
saturation,
color,
luminosity,
}
enum Clip {
none,
hardEdge,
antiAlias,
antiAliasWithSaveLayer,
}
abstract class Paint {
factory Paint() => engine.renderer.createPaint();
BlendMode get blendMode;
set blendMode(BlendMode value);
PaintingStyle get style;
set style(PaintingStyle value);
double get strokeWidth;
set strokeWidth(double value);
StrokeCap get strokeCap;
set strokeCap(StrokeCap value);
StrokeJoin get strokeJoin;
set strokeJoin(StrokeJoin value);
bool get isAntiAlias;
set isAntiAlias(bool value);
Color get color;
set color(Color value);
bool get invertColors;
set invertColors(bool value);
Shader? get shader;
set shader(Shader? value);
MaskFilter? get maskFilter;
set maskFilter(MaskFilter? value);
// TODO(ianh): verify that the image drawing methods actually respect this
FilterQuality get filterQuality;
set filterQuality(FilterQuality value);
ColorFilter? get colorFilter;
set colorFilter(ColorFilter? value);
double get strokeMiterLimit;
set strokeMiterLimit(double value);
ImageFilter? get imageFilter;
set imageFilter(ImageFilter? value);
}
abstract class Shader {
Shader._();
void dispose();
bool get debugDisposed;
}
abstract class Gradient implements Shader {
factory Gradient.linear(
Offset from,
Offset to,
List<Color> colors, [
List<double>? colorStops,
TileMode tileMode = TileMode.clamp,
Float64List? matrix4,
]) {
final Float32List? matrix = matrix4 == null ? null : engine.toMatrix32(matrix4);
return engine.renderer.createLinearGradient(
from,
to,
colors,
colorStops,
tileMode,
matrix);
}
factory Gradient.radial(
Offset center,
double radius,
List<Color> colors, [
List<double>? colorStops,
TileMode tileMode = TileMode.clamp,
Float64List? matrix4,
Offset? focal,
double focalRadius = 0.0,
]) {
_validateColorStops(colors, colorStops);
// If focal is null or focal radius is null, this should be treated as a regular radial gradient
// If focal == center and the focal radius is 0.0, it's still a regular radial gradient
final Float32List? matrix32 = matrix4 != null ? engine.toMatrix32(matrix4) : null;
if (focal == null || (focal == center && focalRadius == 0.0)) {
return engine.renderer.createRadialGradient(
center, radius, colors, colorStops, tileMode, matrix32);
} else {
assert(center != Offset.zero ||
focal != Offset.zero); // will result in exception(s) in Skia side
return engine.renderer.createConicalGradient(
focal, focalRadius, center, radius, colors, colorStops, tileMode, matrix32);
}
}
factory Gradient.sweep(
Offset center,
List<Color> colors, [
List<double>? colorStops,
TileMode tileMode = TileMode.clamp,
double startAngle = 0.0,
double endAngle = math.pi * 2,
Float64List? matrix4,
]) => engine.renderer.createSweepGradient(
center,
colors,
colorStops,
tileMode,
startAngle,
endAngle,
matrix4 != null ? engine.toMatrix32(matrix4) : null);
}
typedef ImageEventCallback = void Function(Image image);
abstract class Image {
static ImageEventCallback? onCreate;
static ImageEventCallback? onDispose;
int get width;
int get height;
Future<ByteData?> toByteData({ImageByteFormat format = ImageByteFormat.rawRgba});
void dispose();
bool get debugDisposed;
Image clone() => this;
bool isCloneOf(Image other) => other == this;
List<StackTrace>? debugGetOpenHandleStackTraces() => null;
ColorSpace get colorSpace => ColorSpace.sRGB;
@override
String toString() => '[$width\u00D7$height]';
}
class ColorFilter implements ImageFilter {
const factory ColorFilter.mode(Color color, BlendMode blendMode) = engine.EngineColorFilter.mode;
const factory ColorFilter.matrix(List<double> matrix) = engine.EngineColorFilter.matrix;
const factory ColorFilter.linearToSrgbGamma() = engine.EngineColorFilter.linearToSrgbGamma;
const factory ColorFilter.srgbToLinearGamma() = engine.EngineColorFilter.srgbToLinearGamma;
}
// These enum values must be kept in sync with SkBlurStyle.
enum BlurStyle {
// These mirror SkBlurStyle and must be kept in sync.
normal,
solid,
outer,
inner,
}
class MaskFilter {
const MaskFilter.blur(
this._style,
this._sigma,
);
final BlurStyle _style;
final double _sigma;
double get webOnlySigma => _sigma;
BlurStyle get webOnlyBlurStyle => _style;
@override
bool operator ==(Object other) {
return other is MaskFilter
&& other._style == _style
&& other._sigma == _sigma;
}
@override
int get hashCode => Object.hash(_style, _sigma);
@override
String toString() => 'MaskFilter.blur($_style, ${_sigma.toStringAsFixed(1)})';
}
// This needs to be kept in sync with the "_FilterQuality" enum in skwasm's canvas.cpp
enum FilterQuality {
none,
low,
medium,
high,
}
class ImageFilter {
factory ImageFilter.blur({
double sigmaX = 0.0,
double sigmaY = 0.0,
TileMode tileMode = TileMode.clamp
}) => engine.renderer.createBlurImageFilter(
sigmaX: sigmaX,
sigmaY: sigmaY,
tileMode: tileMode
);
factory ImageFilter.dilate({ double radiusX = 0.0, double radiusY = 0.0 }) =>
engine.renderer.createDilateImageFilter(radiusX: radiusX, radiusY: radiusY);
factory ImageFilter.erode({ double radiusX = 0.0, double radiusY = 0.0 }) =>
engine.renderer.createErodeImageFilter(radiusX: radiusX, radiusY: radiusY);
factory ImageFilter.matrix(Float64List matrix4, {FilterQuality filterQuality = FilterQuality.low}) {
if (matrix4.length != 16) {
throw ArgumentError('"matrix4" must have 16 entries.');
}
return engine.renderer.createMatrixImageFilter(matrix4, filterQuality: filterQuality);
}
factory ImageFilter.compose({required ImageFilter outer, required ImageFilter inner}) =>
engine.renderer.composeImageFilters(outer: outer, inner: inner);
}
enum ColorSpace {
sRGB,
extendedSRGB,
}
// This must be kept in sync with the `ImageByteFormat` enum in Skwasm's surface.cpp.
enum ImageByteFormat {
rawRgba,
rawStraightRgba,
rawUnmodified,
png,
}
// This must be kept in sync with the `PixelFormat` enum in Skwasm's image.cpp.
enum PixelFormat {
rgba8888,
bgra8888,
rgbaFloat32,
}
typedef ImageDecoderCallback = void Function(Image result);
abstract class FrameInfo {
FrameInfo._();
Duration get duration => Duration(milliseconds: _durationMillis);
int get _durationMillis => 0;
Image get image;
}
class Codec {
Codec._();
int get frameCount => 0;
int get repetitionCount => 0;
Future<FrameInfo> getNextFrame() {
return engine.futurize<FrameInfo>(_getNextFrame);
}
String? _getNextFrame(engine.Callback<FrameInfo> callback) => null;
void dispose() {}
}
Future<Codec> instantiateImageCodec(
Uint8List list, {
int? targetWidth,
int? targetHeight,
bool allowUpscaling = true,
}) => engine.renderer.instantiateImageCodec(
list,
targetWidth: targetWidth,
targetHeight: targetHeight,
allowUpscaling: allowUpscaling);
Future<Codec> instantiateImageCodecFromBuffer(
ImmutableBuffer buffer, {
int? targetWidth,
int? targetHeight,
bool allowUpscaling = true,
}) => engine.renderer.instantiateImageCodec(
buffer._list!,
targetWidth: targetWidth,
targetHeight: targetHeight,
allowUpscaling: allowUpscaling);
Future<Codec> instantiateImageCodecWithSize(
ImmutableBuffer buffer, {
TargetImageSizeCallback? getTargetSize,
}) async {
if (getTargetSize == null) {
return engine.renderer.instantiateImageCodec(buffer._list!);
} else {
final Codec codec = await engine.renderer.instantiateImageCodec(buffer._list!);
try {
final FrameInfo info = await codec.getNextFrame();
try {
final int width = info.image.width;
final int height = info.image.height;
final TargetImageSize targetSize = getTargetSize(width, height);
return engine.renderer.instantiateImageCodec(buffer._list!,
targetWidth: targetSize.width, targetHeight: targetSize.height, allowUpscaling: false);
} finally {
info.image.dispose();
}
} finally {
codec.dispose();
}
}
}
typedef TargetImageSizeCallback = TargetImageSize Function(int intrinsicWidth, int intrinsicHeight);
class TargetImageSize {
const TargetImageSize({this.width, this.height})
: assert(width == null || width > 0),
assert(height == null || height > 0);
final int? width;
final int? height;
}
// TODO(mdebbar): Deprecate this and remove it.
// https://github.com/flutter/flutter/issues/127395
Future<Codec> webOnlyInstantiateImageCodecFromUrl(
Uri uri, {
ui_web.ImageCodecChunkCallback? chunkCallback,
}) {
assert(() {
engine.printWarning(
'The webOnlyInstantiateImageCodecFromUrl API is deprecated and will be '
'removed in a future release. Please use `createImageCodecFromUrl` from '
'`dart:ui_web` instead.',
);
return true;
}());
return ui_web.createImageCodecFromUrl(uri, chunkCallback: chunkCallback);
}
void decodeImageFromList(Uint8List list, ImageDecoderCallback callback) {
_decodeImageFromListAsync(list, callback);
}
Future<void> _decodeImageFromListAsync(Uint8List list, ImageDecoderCallback callback) async {
final Codec codec = await instantiateImageCodec(list);
final FrameInfo frameInfo = await codec.getNextFrame();
callback(frameInfo.image);
}
// Encodes the input pixels into a BMP file that supports transparency.
//
// The `pixels` should be the scanlined raw pixels, 4 bytes per pixel, from left
// to right, then from top to down. The order of the 4 bytes of pixels is
// decided by `format`.
Future<Codec> createBmp(
Uint8List pixels,
int width,
int height,
int rowBytes,
PixelFormat format,
) {
late bool swapRedBlue;
switch (format) {
case PixelFormat.bgra8888:
swapRedBlue = true;
case PixelFormat.rgba8888:
swapRedBlue = false;
case PixelFormat.rgbaFloat32:
throw UnimplementedError('RGB conversion from rgbaFloat32 data is not implemented');
}
// See https://en.wikipedia.org/wiki/BMP_file_format for format examples.
// The header is in the 108-byte BITMAPV4HEADER format, or as called by
// Chromium, WindowsV4. Do not use the 56-byte or 52-byte Adobe formats, since
// they're not supported.
const int dibSize = 0x6C /* 108: BITMAPV4HEADER */;
const int headerSize = dibSize + 0x0E;
final int bufferSize = headerSize + (width * height * 4);
final ByteData bmpData = ByteData(bufferSize);
// 'BM' header
bmpData.setUint16(0x00, 0x424D);
// Size of data
bmpData.setUint32(0x02, bufferSize, Endian.little);
// Offset where pixel array begins
bmpData.setUint32(0x0A, headerSize, Endian.little);
// Bytes in DIB header
bmpData.setUint32(0x0E, dibSize, Endian.little);
// Width
bmpData.setUint32(0x12, width, Endian.little);
// Height
bmpData.setUint32(0x16, height, Endian.little);
// Color panes (always 1)
bmpData.setUint16(0x1A, 0x01, Endian.little);
// bpp: 32
bmpData.setUint16(0x1C, 32, Endian.little);
// Compression method is BITFIELDS to enable bit fields
bmpData.setUint32(0x1E, 3, Endian.little);
// Raw bitmap data size
bmpData.setUint32(0x22, width * height, Endian.little);
// Print DPI width
bmpData.setUint32(0x26, width, Endian.little);
// Print DPI height
bmpData.setUint32(0x2A, height, Endian.little);
// Colors in the palette
bmpData.setUint32(0x2E, 0x00, Endian.little);
// Important colors
bmpData.setUint32(0x32, 0x00, Endian.little);
// Bitmask R
bmpData.setUint32(0x36, swapRedBlue ? 0x00FF0000 : 0x000000FF, Endian.little);
// Bitmask G
bmpData.setUint32(0x3A, 0x0000FF00, Endian.little);
// Bitmask B
bmpData.setUint32(0x3E, swapRedBlue ? 0x000000FF : 0x00FF0000, Endian.little);
// Bitmask A
bmpData.setUint32(0x42, 0xFF000000, Endian.little);
int destinationByte = headerSize;
final Uint32List combinedPixels = Uint32List.sublistView(pixels);
// BMP is scanlined from bottom to top. Rearrange here.
for (int rowCount = height - 1; rowCount >= 0; rowCount -= 1) {
int sourcePixel = rowCount * rowBytes;
for (int colCount = 0; colCount < width; colCount += 1) {
bmpData.setUint32(destinationByte, combinedPixels[sourcePixel], Endian.little);
destinationByte += 4;
sourcePixel += 1;
}
}
return instantiateImageCodec(
bmpData.buffer.asUint8List(),
);
}
void decodeImageFromPixels(
Uint8List pixels,
int width,
int height,
PixelFormat format,
ImageDecoderCallback callback, {
int? rowBytes,
int? targetWidth,
int? targetHeight,
bool allowUpscaling = true,
}) => engine.renderer.decodeImageFromPixels(
pixels,
width,
height,
format,
callback,
rowBytes: rowBytes,
targetWidth: targetWidth,
targetHeight: targetHeight,
allowUpscaling: allowUpscaling);
class Shadow {
const Shadow({
this.color = const Color(_kColorDefault),
this.offset = Offset.zero,
this.blurRadius = 0.0,
}) : assert(blurRadius >= 0.0, 'Text shadow blur radius should be non-negative.');
static const int _kColorDefault = 0xFF000000;
final Color color;
final Offset offset;
final double blurRadius;
// See SkBlurMask::ConvertRadiusToSigma().
// <https://github.com/google/skia/blob/bb5b77db51d2e149ee66db284903572a5aac09be/src/effects/SkBlurMask.cpp#L23>
static double convertRadiusToSigma(double radius) {
return radius > 0 ? radius * 0.57735 + 0.5 : 0;
}
double get blurSigma => convertRadiusToSigma(blurRadius);
Paint toPaint() {
return Paint()
..color = color
..maskFilter = MaskFilter.blur(BlurStyle.normal, blurSigma);
}
Shadow scale(double factor) {
return Shadow(
color: color,
offset: offset * factor,
blurRadius: blurRadius * factor,
);
}
static Shadow? lerp(Shadow? a, Shadow? b, double t) {
if (b == null) {
if (a == null) {
return null;
} else {
return a.scale(1.0 - t);
}
} else {
if (a == null) {
return b.scale(t);
} else {
return Shadow(
color: Color.lerp(a.color, b.color, t)!,
offset: Offset.lerp(a.offset, b.offset, t)!,
blurRadius: _lerpDouble(a.blurRadius, b.blurRadius, t),
);
}
}
}
static List<Shadow>? lerpList(List<Shadow>? a, List<Shadow>? b, double t) {
if (a == null && b == null) {
return null;
}
a ??= <Shadow>[];
b ??= <Shadow>[];
final List<Shadow> result = <Shadow>[];
final int commonLength = math.min(a.length, b.length);
for (int i = 0; i < commonLength; i += 1) {
result.add(Shadow.lerp(a[i], b[i], t)!);
}
for (int i = commonLength; i < a.length; i += 1) {
result.add(a[i].scale(1.0 - t));
}
for (int i = commonLength; i < b.length; i += 1) {
result.add(b[i].scale(t));
}
return result;
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is Shadow &&
other.color == color &&
other.offset == offset &&
other.blurRadius == blurRadius;
}
@override
int get hashCode => Object.hash(color, offset, blurRadius);
@override
String toString() => 'TextShadow($color, $offset, $blurRadius)';
}
abstract class ImageShader implements Shader {
factory ImageShader(
Image image,
TileMode tmx,
TileMode tmy,
Float64List matrix4, {
FilterQuality? filterQuality,
}) => engine.renderer.createImageShader(
image,
tmx,
tmy,
matrix4,
filterQuality
);
@override
void dispose();
@override
bool get debugDisposed;
}
class ImmutableBuffer {
ImmutableBuffer._(this._length);
static Future<ImmutableBuffer> fromUint8List(Uint8List list) async {
final ImmutableBuffer instance = ImmutableBuffer._(list.length);
instance._list = list;
return instance;
}
static Future<ImmutableBuffer> fromAsset(String assetKey) async {
throw UnsupportedError('ImmutableBuffer.fromAsset is not supported on the web.');
}
static Future<ImmutableBuffer> fromFilePath(String path) async {
throw UnsupportedError('ImmutableBuffer.fromFilePath is not supported on the web.');
}
Uint8List? _list;
int get length => _length;
final int _length;
bool get debugDisposed {
late bool disposed;
assert(() {
disposed = _list == null;
return true;
}());
return disposed;
}
void dispose() => _list = null;
}
class ImageDescriptor {
// Not async because there's no expensive work to do here.
ImageDescriptor.raw(
ImmutableBuffer buffer, {
required int width,
required int height,
int? rowBytes,
required PixelFormat pixelFormat,
}) : _width = width,
_height = height,
_rowBytes = rowBytes,
_format = pixelFormat {
_data = buffer._list;
}
ImageDescriptor._()
: _width = null,
_height = null,
_rowBytes = null,
_format = null;
static Future<ImageDescriptor> encoded(ImmutableBuffer buffer) async {
final ImageDescriptor descriptor = ImageDescriptor._();
descriptor._data = buffer._list;
return descriptor;
}
Uint8List? _data;
final int? _width;
final int? _height;
final int? _rowBytes;
final PixelFormat? _format;
Never _throw(String parameter) {
throw UnsupportedError('ImageDescriptor.$parameter is not supported on web.');
}
int get width => _width ?? _throw('width');
int get height => _height ?? _throw('height');
int get bytesPerPixel =>
throw UnsupportedError('ImageDescriptor.bytesPerPixel is not supported on web.');
void dispose() => _data = null;
Future<Codec> instantiateCodec({int? targetWidth, int? targetHeight}) async {
if (_data == null) {
throw StateError('Object is disposed');
}
if (_width == null) {
return instantiateImageCodec(
_data!,
targetWidth: targetWidth,
targetHeight: targetHeight,
allowUpscaling: false,
);
}
return createBmp(_data!, width, height, _rowBytes ?? width, _format!);
}
}
abstract class FragmentProgram {
static Future<FragmentProgram> fromAsset(String assetKey) {
return engine.renderer.createFragmentProgram(assetKey);
}
FragmentShader fragmentShader();
}
abstract class FragmentShader implements Shader {
void setFloat(int index, double value);
void setImageSampler(int index, Image image);
@override
void dispose();
@override
bool get debugDisposed;
}
| engine/lib/web_ui/lib/painting.dart/0 | {
"file_path": "engine/lib/web_ui/lib/painting.dart",
"repo_id": "engine",
"token_count": 9029
} | 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.
import 'package:meta/meta.dart';
import '../../engine.dart';
/// Caches canvases used to display Skia-drawn content.
class DisplayCanvasFactory<T extends DisplayCanvas> {
DisplayCanvasFactory({required this.createCanvas}) {
assert(() {
registerHotRestartListener(dispose);
return true;
}());
}
/// A function which is passed in as a constructor parameter which is used to
/// create new display canvases.
final T Function() createCanvas;
/// The base canvas to paint on. This is the default canvas which will be
/// painted to. If there are no platform views, then this canvas will render
/// the entire scene.
late final T baseCanvas = createCanvas()..initialize();
/// Canvases created by this factory which are currently in use.
final List<T> _liveCanvases = <T>[];
/// Canvases created by this factory which are no longer in use. These can be
/// reused.
final List<T> _cache = <T>[];
/// The number of canvases which have been created by this factory.
int get _canvasCount => _liveCanvases.length + _cache.length + 1;
/// The number of surfaces created by this factory. Used for testing.
@visibleForTesting
int get debugSurfaceCount => _canvasCount;
/// Returns the number of cached surfaces.
///
/// Useful in tests.
int get debugCacheSize => _cache.length;
/// Gets a display canvas from the cache or creates a new one if there are
/// none in the cache.
T getCanvas() {
if (_cache.isNotEmpty) {
final T canvas = _cache.removeLast();
_liveCanvases.add(canvas);
return canvas;
} else {
final T canvas = createCanvas();
canvas.initialize();
_liveCanvases.add(canvas);
return canvas;
}
}
/// Releases all surfaces so they can be reused in the next frame.
///
/// If a released surface is in the DOM, it is not removed. This allows the
/// engine to release the surfaces at the end of the frame so they are ready
/// to be used in the next frame, but still used for painting in the current
/// frame.
void releaseCanvases() {
_cache.addAll(_liveCanvases);
_liveCanvases.clear();
}
/// Removes all canvases except the base canvas from the DOM.
///
/// This is called at the beginning of the frame to prepare for painting into
/// the new canvases.
void removeCanvasesFromDom() {
_cache.forEach(_removeFromDom);
_liveCanvases.forEach(_removeFromDom);
}
/// Calls [callback] on each canvas created by this factory.
void forEachCanvas(void Function(T canvas) callback) {
callback(baseCanvas);
_cache.forEach(callback);
_liveCanvases.forEach(callback);
}
// Removes [canvas] from the DOM.
void _removeFromDom(T canvas) {
canvas.hostElement.remove();
}
/// Signals that a canvas is no longer being used. It can be reused.
void releaseCanvas(T canvas) {
assert(canvas != baseCanvas, 'Attempting to release the base canvas');
assert(
_liveCanvases.contains(canvas),
'Attempting to release a Canvas which '
'was not created by this factory');
canvas.hostElement.remove();
_liveCanvases.remove(canvas);
_cache.add(canvas);
}
/// Returns [true] if [canvas] is currently being used to paint content.
///
/// The base canvas always counts as live.
///
/// If a canvas is not live, then it must be in the cache and ready to be
/// reused.
bool isLive(T canvas) {
if (canvas == baseCanvas || _liveCanvases.contains(canvas)) {
return true;
}
assert(_cache.contains(canvas));
return false;
}
/// Dispose all canvases created by this factory.
void dispose() {
for (final T canvas in _cache) {
canvas.dispose();
}
for (final T canvas in _liveCanvases) {
canvas.dispose();
}
baseCanvas.dispose();
_liveCanvases.clear();
_cache.clear();
}
}
| engine/lib/web_ui/lib/src/engine/canvaskit/display_canvas_factory.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/canvaskit/display_canvas_factory.dart",
"repo_id": "engine",
"token_count": 1311
} | 255 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'package:meta/meta.dart';
import 'package:ui/ui.dart' as ui;
import '../color_filter.dart';
import '../shader_data.dart';
import '../vector_math.dart';
import 'canvaskit_api.dart';
import 'color_filter.dart';
import 'image_filter.dart';
import 'mask_filter.dart';
import 'native_memory.dart';
import 'shader.dart';
/// The implementation of [ui.Paint] used by the CanvasKit backend.
///
/// This class is backed by a Skia object that must be explicitly
/// deleted to avoid a memory leak. This is done by extending [SkiaObject].
class CkPaint implements ui.Paint {
CkPaint() : skiaObject = SkPaint() {
skiaObject.setAntiAlias(_isAntiAlias);
skiaObject.setColorInt(_defaultPaintColor.toDouble());
_ref = UniqueRef<SkPaint>(this, skiaObject, 'Paint');
}
final SkPaint skiaObject;
late final UniqueRef<SkPaint> _ref;
CkManagedSkImageFilterConvertible? _imageFilter;
static const int _defaultPaintColor = 0xFF000000;
/// Returns the native reference to the underlying [SkPaint] object.
///
/// This should only be used in tests.
@visibleForTesting
UniqueRef<SkPaint> get debugRef => _ref;
@override
ui.BlendMode get blendMode => _blendMode;
@override
set blendMode(ui.BlendMode value) {
if (_blendMode == value) {
return;
}
_blendMode = value;
skiaObject.setBlendMode(toSkBlendMode(value));
}
ui.BlendMode _blendMode = ui.BlendMode.srcOver;
@override
ui.PaintingStyle get style => _style;
@override
set style(ui.PaintingStyle value) {
if (_style == value) {
return;
}
_style = value;
skiaObject.setStyle(toSkPaintStyle(value));
}
ui.PaintingStyle _style = ui.PaintingStyle.fill;
@override
double get strokeWidth => _strokeWidth;
@override
set strokeWidth(double value) {
if (_strokeWidth == value) {
return;
}
_strokeWidth = value;
skiaObject.setStrokeWidth(value);
}
double _strokeWidth = 0.0;
@override
ui.StrokeCap get strokeCap => _strokeCap;
@override
set strokeCap(ui.StrokeCap value) {
if (_strokeCap == value) {
return;
}
_strokeCap = value;
skiaObject.setStrokeCap(toSkStrokeCap(value));
}
ui.StrokeCap _strokeCap = ui.StrokeCap.butt;
@override
ui.StrokeJoin get strokeJoin => _strokeJoin;
@override
set strokeJoin(ui.StrokeJoin value) {
if (_strokeJoin == value) {
return;
}
_strokeJoin = value;
skiaObject.setStrokeJoin(toSkStrokeJoin(value));
}
ui.StrokeJoin _strokeJoin = ui.StrokeJoin.miter;
@override
bool get isAntiAlias => _isAntiAlias;
@override
set isAntiAlias(bool value) {
if (_isAntiAlias == value) {
return;
}
_isAntiAlias = value;
skiaObject.setAntiAlias(value);
}
bool _isAntiAlias = true;
@override
ui.Color get color => ui.Color(_color);
@override
set color(ui.Color value) {
if (_color == value.value) {
return;
}
_color = value.value;
skiaObject.setColorInt(value.value.toDouble());
}
int _color = _defaultPaintColor;
@override
bool get invertColors => _invertColors;
@override
set invertColors(bool value) {
if (value == _invertColors) {
return;
}
if (!value) {
_effectiveColorFilter = _originalColorFilter;
_originalColorFilter = null;
} else {
_originalColorFilter = _effectiveColorFilter;
if (_effectiveColorFilter == null) {
_effectiveColorFilter = _invertColorFilter;
} else {
_effectiveColorFilter = ManagedSkColorFilter(
CkComposeColorFilter(_invertColorFilter, _effectiveColorFilter!)
);
}
}
skiaObject.setColorFilter(_effectiveColorFilter?.skiaObject);
_invertColors = value;
}
bool _invertColors = false;
// The original color filter before we inverted colors. If we set
// `invertColors` back to `false`, then restore this filter rather than
// invert the color filter again.
ManagedSkColorFilter? _originalColorFilter;
@override
ui.Shader? get shader => _shader;
@override
set shader(ui.Shader? value) {
if (_shader == value) {
return;
}
_shader = value as CkShader?;
skiaObject.setShader(_shader?.getSkShader(_filterQuality));
}
CkShader? _shader;
@override
ui.MaskFilter? get maskFilter => _maskFilter;
@override
set maskFilter(ui.MaskFilter? value) {
if (value == _maskFilter) {
return;
}
_maskFilter = value;
if (value != null) {
// CanvasKit returns `null` if the sigma is `0` or infinite.
if (!(value.webOnlySigma.isFinite && value.webOnlySigma > 0)) {
// Don't create a [CkMaskFilter].
_ckMaskFilter = null;
} else {
_ckMaskFilter = CkMaskFilter.blur(
value.webOnlyBlurStyle,
value.webOnlySigma,
);
}
} else {
_ckMaskFilter = null;
}
skiaObject.setMaskFilter(_ckMaskFilter?.skiaObject);
}
ui.MaskFilter? _maskFilter;
CkMaskFilter? _ckMaskFilter;
@override
ui.FilterQuality get filterQuality => _filterQuality;
@override
set filterQuality(ui.FilterQuality value) {
if (_filterQuality == value) {
return;
}
_filterQuality = value;
skiaObject.setShader(_shader?.getSkShader(value));
}
ui.FilterQuality _filterQuality = ui.FilterQuality.none;
EngineColorFilter? _engineColorFilter;
@override
ui.ColorFilter? get colorFilter => _engineColorFilter;
@override
set colorFilter(ui.ColorFilter? value) {
if (_engineColorFilter == value) {
return;
}
_engineColorFilter = value as EngineColorFilter?;
_originalColorFilter = null;
if (value == null) {
_effectiveColorFilter = null;
} else {
final CkColorFilter ckColorFilter = createCkColorFilter(value)!;
_effectiveColorFilter = ManagedSkColorFilter(ckColorFilter);
}
if (invertColors) {
_originalColorFilter = _effectiveColorFilter;
if (_effectiveColorFilter == null) {
_effectiveColorFilter = _invertColorFilter;
} else {
_effectiveColorFilter = ManagedSkColorFilter(
CkComposeColorFilter(_invertColorFilter, _effectiveColorFilter!)
);
}
}
skiaObject.setColorFilter(_effectiveColorFilter?.skiaObject);
}
/// The effective color filter.
///
/// This is a combination of the `colorFilter` and `invertColors` properties.
ManagedSkColorFilter? _effectiveColorFilter;
@override
double get strokeMiterLimit => _strokeMiterLimit;
@override
set strokeMiterLimit(double value) {
if (_strokeMiterLimit == value) {
return;
}
_strokeMiterLimit = value;
skiaObject.setStrokeMiter(value);
}
double _strokeMiterLimit = 0.0;
@override
ui.ImageFilter? get imageFilter => _imageFilter;
@override
set imageFilter(ui.ImageFilter? value) {
if (_imageFilter == value) {
return;
}
final CkManagedSkImageFilterConvertible? filter;
if (value is ui.ColorFilter) {
filter = createCkColorFilter(value as EngineColorFilter);
}
else {
filter = value as CkManagedSkImageFilterConvertible?;
}
if (filter != null) {
filter.imageFilter((SkImageFilter skImageFilter) {
skiaObject.setImageFilter(skImageFilter);
});
}
_imageFilter = filter;
}
/// Disposes of this paint object.
///
/// This object cannot be used again after calling this method.
void dispose() {
_ref.dispose();
}
// Must be kept in sync with the default in paint.cc.
static const double _kStrokeMiterLimitDefault = 4.0;
// Must be kept in sync with the default in paint.cc.
static const int _kColorDefault = 0xFF000000;
// Must be kept in sync with the default in paint.cc.
static final int _kBlendModeDefault = ui.BlendMode.srcOver.index;
@override
String toString() {
String resultString = 'Paint()';
assert(() {
final StringBuffer result = StringBuffer();
String semicolon = '';
result.write('Paint(');
if (style == ui.PaintingStyle.stroke) {
result.write('$style');
if (strokeWidth != 0.0) {
result.write(' ${strokeWidth.toStringAsFixed(1)}');
} else {
result.write(' hairline');
}
if (strokeCap != ui.StrokeCap.butt) {
result.write(' $strokeCap');
}
if (strokeJoin == ui.StrokeJoin.miter) {
if (strokeMiterLimit != _kStrokeMiterLimitDefault) {
result.write(' $strokeJoin up to ${strokeMiterLimit.toStringAsFixed(1)}');
}
} else {
result.write(' $strokeJoin');
}
semicolon = '; ';
}
if (!isAntiAlias) {
result.write('${semicolon}antialias off');
semicolon = '; ';
}
if (color != const ui.Color(_kColorDefault)) {
result.write('$semicolon$color');
semicolon = '; ';
}
if (blendMode.index != _kBlendModeDefault) {
result.write('$semicolon$blendMode');
semicolon = '; ';
}
if (colorFilter != null) {
result.write('${semicolon}colorFilter: $colorFilter');
semicolon = '; ';
}
if (maskFilter != null) {
result.write('${semicolon}maskFilter: $maskFilter');
semicolon = '; ';
}
if (filterQuality != ui.FilterQuality.none) {
result.write('${semicolon}filterQuality: $filterQuality');
semicolon = '; ';
}
if (shader != null) {
result.write('${semicolon}shader: $shader');
semicolon = '; ';
}
if (imageFilter != null) {
result.write('${semicolon}imageFilter: $imageFilter');
semicolon = '; ';
}
if (invertColors) {
result.write('${semicolon}invert: $invertColors');
}
result.write(')');
resultString = result.toString();
return true;
}());
return resultString;
}
}
final Float32List _invertColorMatrix = Float32List.fromList(const <double>[
-1.0, 0, 0, 1.0, 0, // row
0, -1.0, 0, 1.0, 0, // row
0, 0, -1.0, 1.0, 0, // row
1.0, 1.0, 1.0, 1.0, 0
]);
final ManagedSkColorFilter _invertColorFilter = ManagedSkColorFilter(CkMatrixColorFilter(_invertColorMatrix));
class CkFragmentProgram implements ui.FragmentProgram {
CkFragmentProgram(this.name, this.effect, this.uniforms, this.floatCount,
this.textureCount);
factory CkFragmentProgram.fromBytes(String name, Uint8List data) {
final ShaderData shaderData = ShaderData.fromBytes(data);
final SkRuntimeEffect? effect = MakeRuntimeEffect(shaderData.source);
if (effect == null) {
throw const FormatException('Invalid Shader Source');
}
return CkFragmentProgram(
name,
effect,
shaderData.uniforms,
shaderData.floatCount,
shaderData.textureCount,
);
}
final String name;
final SkRuntimeEffect effect;
final List<UniformData> uniforms;
final int floatCount;
final int textureCount;
@override
ui.FragmentShader fragmentShader() {
return CkFragmentShader(name, effect, floatCount, textureCount);
}
}
class CkFragmentShader implements ui.FragmentShader, CkShader {
CkFragmentShader(this.name, this.effect, int floatCount, int textureCount)
: floats = List<double>.filled(floatCount + textureCount * 2, 0),
samplers = List<SkShader?>.filled(textureCount, null),
lastFloatIndex = floatCount;
final String name;
final SkRuntimeEffect effect;
final int lastFloatIndex;
final List<double> floats;
final List<SkShader?> samplers;
@visibleForTesting
UniqueRef<SkShader>? ref;
@override
SkShader getSkShader(ui.FilterQuality contextualQuality) {
assert(!_debugDisposed, 'FragmentShader has been disposed of.');
ref?.dispose();
final SkShader? result = samplers.isEmpty
? effect.makeShader(floats)
: effect.makeShaderWithChildren(floats, samplers);
if (result == null) {
throw Exception('Invalid uniform data for shader $name:'
' floatUniforms: $floats \n'
' samplerUniforms: $samplers \n');
}
ref = UniqueRef<SkShader>(this, result, 'FragmentShader');
return result;
}
@override
void setFloat(int index, double value) {
assert(!_debugDisposed, 'FragmentShader has been disposed of.');
floats[index] = value;
}
@override
void setImageSampler(int index, ui.Image image) {
assert(!_debugDisposed, 'FragmentShader has been disposed of.');
final ui.ImageShader sampler = ui.ImageShader(image, ui.TileMode.clamp,
ui.TileMode.clamp, toMatrix64(Matrix4.identity().storage));
samplers[index] = (sampler as CkShader).getSkShader(ui.FilterQuality.none);
setFloat(lastFloatIndex + 2 * index, (sampler as CkImageShader).imageWidth.toDouble());
setFloat(lastFloatIndex + 2 * index + 1, sampler.imageHeight.toDouble());
}
@override
void dispose() {
assert(!_debugDisposed, 'Cannot dispose FragmentShader more than once.');
assert(() {
_debugDisposed = true;
return true;
}());
ref?.dispose();
ref = null;
}
bool _debugDisposed = false;
@override
bool get debugDisposed => _debugDisposed;
}
| engine/lib/web_ui/lib/src/engine/canvaskit/painting.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/canvaskit/painting.dart",
"repo_id": "engine",
"token_count": 5244
} | 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.
import 'package:ui/ui.dart' as ui;
import 'browser_detection.dart';
import 'dom.dart';
import 'services.dart';
/// Handles clipboard related platform messages.
class ClipboardMessageHandler {
/// Helper to handle copy to clipboard functionality.
CopyToClipboardStrategy _copyToClipboardStrategy = CopyToClipboardStrategy();
/// Helper to handle copy to clipboard functionality.
PasteFromClipboardStrategy _pasteFromClipboardStrategy =
PasteFromClipboardStrategy();
/// Handles the platform message which stores the given text to the clipboard.
void setDataMethodCall(
MethodCall methodCall, ui.PlatformMessageResponseCallback? callback) {
const MethodCodec codec = JSONMethodCodec();
bool errorEnvelopeEncoded = false;
_copyToClipboardStrategy
.setData(methodCall.arguments['text'] as String?)
.then((bool success) {
if (success) {
callback!(codec.encodeSuccessEnvelope(true));
} else {
callback!(codec.encodeErrorEnvelope(
code: 'copy_fail', message: 'Clipboard.setData failed'));
errorEnvelopeEncoded = true;
}
}).catchError((dynamic _) {
// Don't encode a duplicate reply if we already failed and an error
// was already encoded.
if (!errorEnvelopeEncoded) {
callback!(codec.encodeErrorEnvelope(
code: 'copy_fail', message: 'Clipboard.setData failed'));
}
});
}
/// Handles the platform message which retrieves text data from the clipboard.
void getDataMethodCall(ui.PlatformMessageResponseCallback? callback) {
const MethodCodec codec = JSONMethodCodec();
_pasteFromClipboardStrategy.getData().then((String data) {
final Map<String, dynamic> map = <String, dynamic>{'text': data};
callback!(codec.encodeSuccessEnvelope(map));
}).catchError((dynamic error) {
if (error is UnimplementedError) {
// Clipboard.getData not supported.
// Passing [null] to [callback] indicates that the platform message isn't
// implemented. Look at [MethodChannel.invokeMethod] to see how [null] is
// handled.
Future<void>.delayed(Duration.zero).then((_) {
if (callback != null) {
callback(null);
}
});
return;
}
_reportGetDataFailure(callback, codec, error);
});
}
/// Handles the platform message which asks if the clipboard contains
/// pasteable strings.
void hasStringsMethodCall(ui.PlatformMessageResponseCallback? callback) {
const MethodCodec codec = JSONMethodCodec();
_pasteFromClipboardStrategy.getData().then((String data) {
final Map<String, dynamic> map = <String, dynamic>{'value': data.isNotEmpty};
callback!(codec.encodeSuccessEnvelope(map));
}).catchError((dynamic error) {
if (error is UnimplementedError) {
// Clipboard.hasStrings not supported.
// Passing [null] to [callback] indicates that the platform message isn't
// implemented. Look at [MethodChannel.invokeMethod] to see how [null] is
// handled.
Future<void>.delayed(Duration.zero).then((_) {
if (callback != null) {
callback(null);
}
});
return;
}
final Map<String, dynamic> map = <String, dynamic>{'value': false};
callback!(codec.encodeSuccessEnvelope(map));
});
}
void _reportGetDataFailure(ui.PlatformMessageResponseCallback? callback,
MethodCodec codec, dynamic error) {
print('Could not get text from clipboard: $error');
callback!(codec.encodeErrorEnvelope(
code: 'paste_fail', message: 'Clipboard.getData failed'));
}
/// Methods used by tests.
set pasteFromClipboardStrategy(PasteFromClipboardStrategy strategy) {
_pasteFromClipboardStrategy = strategy;
}
set copyToClipboardStrategy(CopyToClipboardStrategy strategy) {
_copyToClipboardStrategy = strategy;
}
}
/// Provides functionality for writing text to clipboard.
///
/// A concrete implementation is picked at runtime based on the available
/// APIs and the browser.
abstract class CopyToClipboardStrategy {
factory CopyToClipboardStrategy() {
return domWindow.navigator.clipboard != null
? ClipboardAPICopyStrategy()
: ExecCommandCopyStrategy();
}
/// Places the text onto the browser Clipboard.
///
/// Returns `true` for a successful action.
///
/// Returns `false` for an uncessful action or when there is an excaption.
Future<bool> setData(String? text);
}
/// Provides functionality for reading text from clipboard.
///
/// A concrete implementation is picked at runtime based on the available
/// APIs and the browser.
abstract class PasteFromClipboardStrategy {
factory PasteFromClipboardStrategy() {
return (browserEngine == BrowserEngine.firefox ||
domWindow.navigator.clipboard == null)
? ExecCommandPasteStrategy()
: ClipboardAPIPasteStrategy();
}
/// Returns text from the system Clipboard.
Future<String> getData();
}
/// Provides copy functionality for browsers which supports ClipboardAPI.
///
/// Works on Chrome and Firefox browsers.
/// See: https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API
class ClipboardAPICopyStrategy implements CopyToClipboardStrategy {
@override
Future<bool> setData(String? text) async {
try {
await domWindow.navigator.clipboard!.writeText(text!);
} catch (error) {
print('copy is not successful $error');
return Future<bool>.value(false);
}
return Future<bool>.value(true);
}
}
/// Provides paste functionality for browsers which supports `clipboard.readText`.
///
/// Works on Chrome. Firefox only supports `readText` if the target element is
/// in content editable mode.
/// See: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Editable_content
/// See: https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API
class ClipboardAPIPasteStrategy implements PasteFromClipboardStrategy {
@override
Future<String> getData() async {
return domWindow.navigator.clipboard!.readText();
}
}
/// Provides a fallback strategy for browsers which does not support ClipboardAPI.
class ExecCommandCopyStrategy implements CopyToClipboardStrategy {
@override
Future<bool> setData(String? text) {
return Future<bool>.value(_setDataSync(text));
}
bool _setDataSync(String? text) {
// Copy content to clipboard with execCommand.
// See: https://developers.google.com/web/updates/2015/04/cut-and-copy-commands
final DomHTMLTextAreaElement tempTextArea = _appendTemporaryTextArea();
tempTextArea.value = text;
tempTextArea.focus();
tempTextArea.select();
bool result = false;
try {
result = domDocument.execCommand('copy');
if (!result) {
print('copy is not successful');
}
} catch (error) {
print('copy is not successful $error');
} finally {
_removeTemporaryTextArea(tempTextArea);
}
return result;
}
DomHTMLTextAreaElement _appendTemporaryTextArea() {
final DomHTMLTextAreaElement tempElement = createDomHTMLTextAreaElement();
final DomCSSStyleDeclaration elementStyle = tempElement.style;
elementStyle
..position = 'absolute'
..top = '-99999px'
..left = '-99999px'
..opacity = '0'
..color = 'transparent'
..backgroundColor = 'transparent'
..background = 'transparent';
domDocument.body!.append(tempElement);
return tempElement;
}
void _removeTemporaryTextArea(DomHTMLElement element) {
element.remove();
}
}
/// Provides a fallback strategy for browsers which does not support ClipboardAPI.
class ExecCommandPasteStrategy implements PasteFromClipboardStrategy {
@override
Future<String> getData() {
// TODO(mdebbar): https://github.com/flutter/flutter/issues/48581
return Future<String>.error(
UnimplementedError('Paste is not implemented for this browser.'));
}
}
| engine/lib/web_ui/lib/src/engine/clipboard.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/clipboard.dart",
"repo_id": "engine",
"token_count": 2791
} | 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.
import 'package:ui/ui.dart' as ui;
import '../../engine/color_filter.dart';
import '../browser_detection.dart';
import '../dom.dart';
import '../svg.dart';
import '../util.dart';
import 'bitmap_canvas.dart';
import 'path_to_svg_clip.dart';
import 'resource_manager.dart';
import 'shaders/shader.dart';
import 'surface.dart';
/// A surface that applies an [ColorFilter] to its children.
class PersistedColorFilter extends PersistedContainerSurface
implements ui.ColorFilterEngineLayer {
PersistedColorFilter(PersistedColorFilter? super.oldLayer, this.filter);
@override
DomElement? get childContainer => _childContainer;
/// The dedicated child container element that's separate from the
/// [rootElement] is used to compensate for the coordinate system shift
/// introduced by the [rootElement] translation.
DomElement? _childContainer;
/// Color filter to apply to this surface.
final ui.ColorFilter filter;
DomElement? _filterElement;
bool containerVisible = true;
@override
void adoptElements(PersistedColorFilter oldSurface) {
super.adoptElements(oldSurface);
_childContainer = oldSurface._childContainer;
_filterElement = oldSurface._filterElement;
oldSurface._childContainer = null;
}
@override
void preroll(PrerollSurfaceContext prerollContext) {
++prerollContext.activeColorFilterCount;
super.preroll(prerollContext);
--prerollContext.activeColorFilterCount;
}
@override
void discard() {
super.discard();
ResourceManager.instance.removeResource(_filterElement);
_filterElement = 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
DomElement createElement() {
final DomElement element = defaultCreateElement('flt-color-filter');
final DomElement container = createDomElement('flt-filter-interior');
container.style.position = 'absolute';
_childContainer = container;
element.append(_childContainer!);
return element;
}
@override
void apply() {
ResourceManager.instance.removeResource(_filterElement);
_filterElement = null;
final EngineHtmlColorFilter? engineValue = createHtmlColorFilter(filter as EngineColorFilter);
if (engineValue == null) {
rootElement!.style.backgroundColor = '';
childContainer?.style.visibility = 'visible';
return;
}
if (engineValue is ModeHtmlColorFilter) {
_applyBlendModeFilter(engineValue);
} else if (engineValue is MatrixHtmlColorFilter) {
_applyMatrixColorFilter(engineValue);
} else {
childContainer?.style.visibility = 'visible';
}
}
void _applyBlendModeFilter(ModeHtmlColorFilter colorFilter) {
_filterElement = colorFilter.makeSvgFilter(childContainer);
/// Some blendModes do not make an svgFilter. See [EngineHtmlColorFilter.makeSvgFilter()]
if (_filterElement == null) {
return;
}
childContainer!.style.filter = colorFilter.filterAttribute;
}
void _applyMatrixColorFilter(MatrixHtmlColorFilter colorFilter) {
_filterElement = colorFilter.makeSvgFilter(childContainer);
childContainer!.style.filter = colorFilter.filterAttribute;
}
@override
void update(PersistedColorFilter oldSurface) {
super.update(oldSurface);
if (oldSurface.filter != filter) {
apply();
}
}
}
SvgFilter svgFilterFromBlendMode(
ui.Color? filterColor, ui.BlendMode colorFilterBlendMode) {
final SvgFilter svgFilter;
switch (colorFilterBlendMode) {
case ui.BlendMode.srcIn:
case ui.BlendMode.srcATop:
svgFilter = _srcInColorFilterToSvg(filterColor);
case ui.BlendMode.srcOut:
svgFilter = _srcOutColorFilterToSvg(filterColor);
case ui.BlendMode.dstATop:
svgFilter = _dstATopColorFilterToSvg(filterColor);
case ui.BlendMode.xor:
svgFilter = _xorColorFilterToSvg(filterColor);
case ui.BlendMode.plus:
// Porter duff source + destination.
svgFilter = _compositeColorFilterToSvg(filterColor, 0, 1, 1, 0);
case ui.BlendMode.modulate:
// Porter duff source * destination but preserves alpha.
svgFilter = _modulateColorFilterToSvg(filterColor!);
case ui.BlendMode.overlay:
// Since overlay is the same as hard-light by swapping layers,
// pass hard-light blend function.
svgFilter = _blendColorFilterToSvg(
filterColor,
blendModeToSvgEnum(ui.BlendMode.hardLight)!,
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 = _blendColorFilterToSvg(
filterColor, blendModeToSvgEnum(colorFilterBlendMode)!);
case ui.BlendMode.src:
case ui.BlendMode.dst:
case ui.BlendMode.dstIn:
case ui.BlendMode.dstOut:
case ui.BlendMode.dstOver:
case ui.BlendMode.clear:
case ui.BlendMode.srcOver:
throw UnimplementedError(
'Blend mode not supported in HTML renderer: $colorFilterBlendMode',
);
}
return svgFilter;
}
// See: https://www.w3.org/TR/SVG11/types.html#InterfaceSVGUnitTypes
const int kObjectBoundingBox = 2;
// See: https://www.w3.org/TR/SVG11/filters.html#InterfaceSVGFEColorMatrixElement
const int kMatrixType = 1;
// See: https://www.w3.org/TR/SVG11/filters.html#InterfaceSVGFECompositeElement
const int kOperatorOut = 3;
const int kOperatorAtop = 4;
const int kOperatorXor = 5;
const int kOperatorArithmetic = 6;
/// Builds an [SvgFilter].
class SvgFilterBuilder {
SvgFilterBuilder() : id = '_fcf${++_filterIdCounter}' {
filter.id = id;
// SVG filters that contain `<feImage>` will fail on several browsers
// (e.g. Firefox) if bounds are not specified.
filter.filterUnits!.baseVal = kObjectBoundingBox;
// On Firefox percentage width/height 100% works however fails in Chrome 88.
filter.x!.baseVal!.valueAsString = '0%';
filter.y!.baseVal!.valueAsString = '0%';
filter.width!.baseVal!.valueAsString = '100%';
filter.height!.baseVal!.valueAsString = '100%';
}
static int _filterIdCounter = 0;
final String id;
final SVGSVGElement root = kSvgResourceHeader.cloneNode(false) as
SVGSVGElement;
final SVGFilterElement filter = createSVGFilterElement();
set colorInterpolationFilters(String filters) {
filter.setAttribute('color-interpolation-filters', filters);
}
void setFeColorMatrix(List<double> matrix, { required String result }) {
final SVGFEColorMatrixElement element = createSVGFEColorMatrixElement();
element.type!.baseVal = kMatrixType;
element.result!.baseVal = result;
final SVGNumberList value = element.values!.baseVal!;
for (int i = 0; i < matrix.length; i++) {
value.appendItem(root.createSVGNumber()..value = matrix[i]);
}
filter.append(element);
}
void setFeFlood({
required String floodColor,
required String floodOpacity,
required String result,
}) {
final SVGFEFloodElement element = createSVGFEFloodElement();
element.setAttribute('flood-color', floodColor);
element.setAttribute('flood-opacity', floodOpacity);
element.result!.baseVal = result;
filter.append(element);
}
void setFeBlend({
required String in1,
required String in2,
required int mode,
}) {
final SVGFEBlendElement element = createSVGFEBlendElement();
element.in1!.baseVal = in1;
element.in2!.baseVal = in2;
element.mode!.baseVal = mode;
filter.append(element);
}
void setFeComposite({
required String in1,
required String in2,
required int operator,
num? k1,
num? k2,
num? k3,
num? k4,
required String result,
}) {
final SVGFECompositeElement element = createSVGFECompositeElement();
element.in1!.baseVal = in1;
element.in2!.baseVal = in2;
element.operator!.baseVal = operator;
if (k1 != null) {
element.k1!.baseVal = k1;
}
if (k2 != null) {
element.k2!.baseVal = k2;
}
if (k3 != null) {
element.k3!.baseVal = k3;
}
if (k4 != null) {
element.k4!.baseVal = k4;
}
element.result!.baseVal = result;
filter.append(element);
}
void setFeImage({
required String href,
required String result,
required double width,
required double height,
}) {
final SVGFEImageElement element = createSVGFEImageElement();
element.href!.baseVal = href;
element.result!.baseVal = result;
// WebKit will not render if x/y/width/height is specified. So we return
// explicit size here unless running on WebKit.
if (browserEngine != BrowserEngine.webkit) {
element.x!.baseVal!.newValueSpecifiedUnits(svgLengthTypeNumber, 0);
element.y!.baseVal!.newValueSpecifiedUnits(svgLengthTypeNumber, 0);
element.width!.baseVal!.newValueSpecifiedUnits(svgLengthTypeNumber, width);
element.height!.baseVal!.newValueSpecifiedUnits(svgLengthTypeNumber, height);
}
filter.append(element);
}
SvgFilter build() {
root.append(filter);
return SvgFilter._(id, root);
}
}
class SvgFilter {
SvgFilter._(this.id, this.element);
final String id;
final SVGSVGElement element;
}
SvgFilter svgFilterFromColorMatrix(List<double> matrix) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeColorMatrix(matrix, result: 'comp');
return builder.build();
}
// 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 _srcInColorFilterToSvg(ui.Color? color) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.colorInterpolationFilters = 'sRGB';
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.setFeFlood(
floodColor: color?.toCssString() ?? '',
floodOpacity: '1',
result: 'flood',
);
builder.setFeComposite(
in1: 'flood',
in2: 'destalpha',
operator: kOperatorArithmetic,
k1: 1,
k2: 0,
k3: 0,
k4: 0,
result: 'comp',
);
return builder.build();
}
/// The destination that overlaps the source is composited with the source and
/// replaces the destination. dst-atop CR = CB*αB*αA+CA*αA*(1-αB) αR=αA
SvgFilter _dstATopColorFilterToSvg(ui.Color? color) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeFlood(
floodColor: color?.toCssString() ?? '',
floodOpacity: '1',
result: 'flood',
);
builder.setFeComposite(
in1: 'SourceGraphic',
in2: 'flood',
operator: kOperatorAtop,
result: 'comp',
);
return builder.build();
}
SvgFilter _srcOutColorFilterToSvg(ui.Color? color) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeFlood(
floodColor: color?.toCssString() ?? '',
floodOpacity: '1',
result: 'flood',
);
builder.setFeComposite(
in1: 'flood',
in2: 'SourceGraphic',
operator: kOperatorOut,
result: 'comp',
);
return builder.build();
}
SvgFilter _xorColorFilterToSvg(ui.Color? color) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeFlood(
floodColor: color?.toCssString() ?? '',
floodOpacity: '1',
result: 'flood',
);
builder.setFeComposite(
in1: 'flood',
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 _compositeColorFilterToSvg(
ui.Color? color, double k1, double k2, double k3, double k4) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeFlood(
floodColor: color?.toCssString() ?? '',
floodOpacity: '1',
result: 'flood',
);
builder.setFeComposite(
in1: 'flood',
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 _modulateColorFilterToSvg(ui.Color color) {
final double r = color.red / 255.0;
final double b = color.blue / 255.0;
final double g = color.green / 255.0;
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeColorMatrix(
<double>[
0, 0, 0, 0, r,
0, 0, 0, 0, g,
0, 0, 0, 0, b,
0, 0, 0, 1, 0,
],
result: 'recolor',
);
builder.setFeComposite(
in1: 'recolor',
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 _blendColorFilterToSvg(ui.Color? color, SvgBlendMode svgBlendMode,
{bool swapLayers = false}) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeFlood(
floodColor: color?.toCssString() ?? '',
floodOpacity: '1',
result: 'flood',
);
if (swapLayers) {
builder.setFeBlend(
in1: 'SourceGraphic',
in2: 'flood',
mode: svgBlendMode.blendMode,
);
} else {
builder.setFeBlend(
in1: 'flood',
in2: 'SourceGraphic',
mode: svgBlendMode.blendMode,
);
}
return builder.build();
}
| engine/lib/web_ui/lib/src/engine/html/color_filter.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/html/color_filter.dart",
"repo_id": "engine",
"token_count": 5712
} | 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.
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import 'conic.dart';
import 'cubic.dart';
import 'path_utils.dart';
/// Computes tangent at point x,y on a line.
void tangentLine(
Float32List pts, double x, double y, List<ui.Offset> tangents) {
final double y0 = pts[1];
final double y1 = pts[3];
if (!SPath.between(y0, y, y1)) {
return;
}
final double x0 = pts[0];
final double x1 = pts[2];
if (!SPath.between(x0, x, x1)) {
return;
}
final double dx = x1 - x0;
final double dy = y1 - y0;
if (!SPath.nearlyEqual((x - x0) * dy, dx * (y - y0))) {
return;
}
tangents.add(ui.Offset(dx, dy));
}
/// Computes tangent at point x,y on a quadratic curve.
void tangentQuad(
Float32List pts, double x, double y, List<ui.Offset> tangents) {
final double y0 = pts[1];
final double y1 = pts[3];
final double y2 = pts[5];
if (!SPath.between(y0, y, y1) && !SPath.between(y1, y, y2)) {
return;
}
final double x0 = pts[0];
final double x1 = pts[2];
final double x2 = pts[4];
if (!SPath.between(x0, x, x1) && !SPath.between(x1, x, x2)) {
return;
}
final QuadRoots roots = QuadRoots();
final int n = roots.findRoots(y0 - 2 * y1 + y2, 2 * (y1 - y0), y0 - y);
for (int index = 0; index < n; ++index) {
final double t = index == 0 ? roots.root0! : roots.root1!;
final double C = x0;
final double A = x2 - 2 * x1 + C;
final double B = 2 * (x1 - C);
final double xt = polyEval(A, B, C, t);
if (!SPath.nearlyEqual(x, xt)) {
continue;
}
tangents.add(_evalQuadTangentAt(x0, y0, x1, y1, x2, y2, t));
}
}
ui.Offset _evalQuadTangentAt(double x0, double y0, double x1, double y1,
double x2, double y2, double t) {
// The derivative of a quad equation is 2(b - a +(a - 2b +c)t).
// This returns a zero tangent vector when t is 0 or 1, and the control
// point is equal to the end point. In this case, use the quad end points to
// compute the tangent.
if ((t == 0 && x0 == x1 && y0 == y1) || (t == 1 && x1 == x2 && y1 == y2)) {
return ui.Offset(x2 - x0, y2 - y0);
}
assert(t >= 0 && t <= 1.0);
final double bx = x1 - x0;
final double by = y1 - y0;
final double ax = x2 - x1 - bx;
final double ay = y2 - y1 - by;
final double tx = ax * t + bx;
final double ty = ay * t + by;
return ui.Offset(tx * 2, ty * 2);
}
/// Computes tangent at point x,y on a conic curve.
void tangentConic(Float32List pts, double x, double y, double weight,
List<ui.Offset> tangents) {
final double y0 = pts[1];
final double y1 = pts[3];
final double y2 = pts[5];
if (!SPath.between(y0, y, y1) && !SPath.between(y1, y, y2)) {
return;
}
final double x0 = pts[0];
final double x1 = pts[2];
final double x2 = pts[4];
if (!SPath.between(x0, x, x1) && !SPath.between(x1, x, x2)) {
return;
}
// Check extrema.
double A = y2;
double B = y1 * weight - y * weight + y;
double C = y0;
// A = a + c - 2*(b*w - yCept*w + yCept)
A += C - 2 * B;
// B = b*w - w * yCept + yCept - a
B -= C;
C -= y;
final QuadRoots quadRoots = QuadRoots();
final int n = quadRoots.findRoots(A, 2 * B, C);
for (int index = 0; index < n; ++index) {
final double t = index == 0 ? quadRoots.root0! : quadRoots.root1!;
final double xt = Conic.evalNumerator(x0, x1, x2, weight, t) /
Conic.evalDenominator(weight, t);
if (!SPath.nearlyEqual(x, xt)) {
continue;
}
final Conic conic = Conic(x0, y0, x1, y1, x2, y2, weight);
tangents.add(conic.evalTangentAt(t));
}
}
/// Computes tangent at point x,y on a cubic curve.
void tangentCubic(
Float32List pts, double x, double y, List<ui.Offset> tangents) {
final double y3 = pts[7];
final double y0 = pts[1];
final double y1 = pts[3];
final double y2 = pts[5];
if (!SPath.between(y0, y, y1) &&
!SPath.between(y1, y, y2) &&
!SPath.between(y2, y, y3)) {
return;
}
final double x0 = pts[0];
final double x1 = pts[2];
final double x2 = pts[4];
final double x3 = pts[6];
if (!SPath.between(x0, x, x1) &&
!SPath.between(x1, x, x2) &&
!SPath.between(x2, x, x3)) {
return;
}
final Float32List dst = Float32List(20);
final int n = chopCubicAtYExtrema(pts, dst);
for (int i = 0; i <= n; ++i) {
final int bufferPos = i * 6;
final double? t = chopMonoAtY(dst, i * 6, y);
if (t == null) {
continue;
}
final double xt = evalCubicPts(dst[bufferPos], dst[bufferPos + 2],
dst[bufferPos + 4], dst[bufferPos + 6], t);
if (!SPath.nearlyEqual(x, xt)) {
continue;
}
tangents.add(_evalCubicTangentAt(dst, bufferPos, t));
}
}
ui.Offset _evalCubicTangentAt(Float32List points, int bufferPos, double t) {
assert(t >= 0 && t <= 1.0);
final double y3 = points[7 + bufferPos];
final double y0 = points[1 + bufferPos];
final double y1 = points[3 + bufferPos];
final double y2 = points[5 + bufferPos];
final double x0 = points[0 + bufferPos];
final double x1 = points[2 + bufferPos];
final double x2 = points[4 + bufferPos];
final double x3 = points[6 + bufferPos];
// The derivative equation returns a zero tangent vector when t is 0 or 1,
// and the adjacent control point is equal to the end point. In this case,
// use the next control point or the end points to compute the tangent.
if ((t == 0 && x0 == x1 && y0 == y1) || (t == 1 && x2 == x3 && y2 == y3)) {
double dx, dy;
if (t == 0) {
dx = x2 - x0;
dy = y2 - y0;
} else {
dx = x3 - x1;
dy = y3 - y1;
}
if (dx == 0 && dy == 0) {
dx = x3 - x0;
dy = y3 - y0;
}
return ui.Offset(dx, dy);
} else {
return _evalCubicDerivative(x0, y0, x1, y1, x2, y2, x3, y3, t);
}
}
ui.Offset _evalCubicDerivative(double x0, double y0, double x1, double y1,
double x2, double y2, double x3, double y3, double t) {
final SkQuadCoefficients coeff = SkQuadCoefficients(
x3 + 3 * (x1 - x2) - x0,
y3 + 3 * (y1 - y2) - y0,
2 * (x2 - (2 * x1) + x0),
2 * (y2 - (2 * y1) + y0),
x1 - x0,
y1 - y0,
);
return ui.Offset(coeff.evalX(t), coeff.evalY(t));
}
| engine/lib/web_ui/lib/src/engine/html/path/tangent.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/html/path/tangent.dart",
"repo_id": "engine",
"token_count": 2733
} | 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.
import 'package:meta/meta.dart';
import 'package:ui/ui.dart' as ui;
import '../dom.dart';
import '../frame_reference.dart';
import '../onscreen_logging.dart';
import '../semantics.dart';
import '../util.dart';
import '../vector_math.dart';
import 'picture.dart';
import 'scene.dart';
import 'surface_stats.dart';
/// When `true` prints statistics about what happened to the surface tree when
/// it was composited.
///
/// Also paints an on-screen overlay with the numbers visualized as a timeline.
const bool debugExplainSurfaceStats = false;
/// When `true` shows an overlay that contains stats about canvas reuse.
///
/// The overlay also includes a button to reset the stats.
const bool debugShowCanvasReuseStats = false;
/// When `true` renders the outlines of clip layers on the screen instead of
/// clipping the contents.
///
/// This is useful when visually debugging clipping behavior.
bool debugShowClipLayers = false;
/// The threshold for the canvas pixel count to screen pixel count ratio, beyond
/// which in debug mode a warning is issued to the console.
///
/// As we improve canvas utilization we should decrease this number. It is
/// unlikely that we will hit 1.0, but something around 3.0 should be
/// reasonable.
const double kScreenPixelRatioWarningThreshold = 6.0;
/// Performs any outstanding painting work enqueued by [PersistedPicture]s.
void commitScene(PersistedScene scene) {
if (paintQueue.isNotEmpty) {
try {
if (paintQueue.length > 1) {
// Sort paint requests in decreasing canvas size order. Paint requests
// attempt to reuse canvases. For efficiency we want the biggest pictures
// to find canvases before the smaller ones claim them.
paintQueue.sort((PaintRequest a, PaintRequest b) {
final double aSize = a.canvasSize.height * a.canvasSize.width;
final double bSize = b.canvasSize.height * b.canvasSize.width;
return bSize.compareTo(aSize);
});
}
for (final PaintRequest request in paintQueue) {
request.paintCallback();
}
} finally {
paintQueue = <PaintRequest>[];
}
}
// After the update the retained surfaces are back to active.
if (retainedSurfaces.isNotEmpty) {
for (int i = 0; i < retainedSurfaces.length; i++) {
final PersistedSurface retainedSurface = retainedSurfaces[i];
assert(debugAssertSurfaceState(
retainedSurface, PersistedSurfaceState.pendingRetention));
retainedSurface.state = PersistedSurfaceState.active;
}
retainedSurfaces = <PersistedSurface>[];
}
if (debugExplainSurfaceStats) {
debugPrintSurfaceStats(scene, debugFrameNumber);
debugRepaintSurfaceStatsOverlay(scene);
}
assert(() {
final List<String> validationErrors = <String>[];
scene.debugValidate(validationErrors);
if (validationErrors.isNotEmpty) {
print('ENGINE LAYER TREE INCONSISTENT:\n'
'${validationErrors.map((String e) => ' - $e\n').join()}');
}
return true;
}());
for (int i = 0; i < frameReferences.length; i++) {
frameReferences[i].value = null;
}
frameReferences = <FrameReference<dynamic>>[];
if (debugExplainSurfaceStats) {
surfaceStats = <PersistedSurface, DebugSurfaceStats>{};
}
assert(() {
debugFrameNumber++;
return true;
}());
}
/// Signature of a function that receives a [PersistedSurface].
///
/// This is used to traverse surfaces using [PersistedSurface.visitChildren].
typedef PersistedSurfaceVisitor = void Function(PersistedSurface);
/// Controls the algorithm used to reuse a previously rendered surface.
enum PersistedSurfaceState {
/// A new or revived surface that does not have a
/// [PersistedSurface.rootElement].
///
/// Surfaces in this state acquire an element either by creating a new element
/// or by adopting an element from an [active] surface.
created,
/// The surface has DOM resources that are attached to the live DOM tree.
///
/// During update surfaces in this state come from the previous frame. This is
/// also the state that all surfaces that are attached to the new frame's
/// scene acquire at the end of the frame.
///
/// In this state the surface has a non-null [PersistedSurface.rootElement].
/// The element may be adopted by a new surface by matching to it during
/// update (see [PersistedSurface.matchForUpdate]).
active,
/// The surface object will be reused along with all its descendants.
///
/// This strategy relies on Flutter's retained-mode layer system (see
/// [EngineLayer]).
pendingRetention,
/// The surface's DOM elements will be reused and updated.
///
/// The surface in this state must have been rendered in a previous frame, it
/// must have non-null [PersistedSurface.rootElement], and there must be a new
/// surface that points to this surface via
/// [PersistedContainerSurface.oldLayer]. The new surface will adopt this
/// surface's DOM elements and update them.
pendingUpdate,
/// This state indicates that all DOM resources of this surface have been
/// released and cannot be reused anymore.
///
/// There are two ways a surface may be released:
///
/// - When the surface is updated its DOM elements are adopted by a new
/// surface. This can happen either via [PersistedContainerSurface.oldLayer]
/// or by matching.
/// - When the surface is removed from the tree because it is no longer in the
/// scene, nor its elements are reused by another surface.
///
/// A surface may be revived from this state back into [created] state via
/// [PersistedSurface.revive].
released,
}
class PersistedSurfaceException implements Exception {
PersistedSurfaceException(this.surface, this.message);
final PersistedSurface surface;
final String message;
@override
String toString() {
String result = super.toString();
assert(() {
result = '${surface.runtimeType}: $message';
return true;
}());
return result;
}
}
/// Verifies that the [surface] is in one of the valid states.
///
/// This function should be used inside an assertion expression.
bool debugAssertSurfaceState(
PersistedSurface surface, PersistedSurfaceState state1,
[PersistedSurfaceState? state2, PersistedSurfaceState? state3]) {
final List<PersistedSurfaceState?> validStates = <PersistedSurfaceState?>[state1, state2, state3];
if (validStates.contains(surface.state)) {
return true;
}
throw PersistedSurfaceException(
surface,
'is in an unexpected state.\n'
'Expected one of: ${validStates.whereType<PersistedSurfaceState>().join(', ')}\n'
'But was: ${surface.state}',
);
}
/// A node in the tree built by [SceneBuilder] that contains information used to
/// compute the fewest amount of mutations necessary to update the browser DOM.
abstract class PersistedSurface implements ui.EngineLayer {
/// Creates a persisted surface.
PersistedSurface(PersistedSurface? oldLayer)
: _oldLayer = FrameReference<PersistedSurface>(
oldLayer != null && oldLayer.isActive ? oldLayer : null);
/// The surface that is being updated using this surface.
///
/// If not null this surface will reuse the old surface's HTML [element].
///
/// This value is set to null at the end of the frame.
PersistedSurface? get oldLayer => _oldLayer.value;
final FrameReference<PersistedSurface> _oldLayer;
/// The index of this surface in its parent's [PersistedContainerSurface._children]
/// list.
///
/// This index is used to detect whether any child nodes moved within a
/// container layer. The index is cached by the child to avoid a linear
/// look-up in the parent's child list.
///
/// This index is updated by [PersistedContainerSurface.update].
int _index = -1;
/// Controls the algorithm that reuses the DOM resources owned by this
/// surface.
PersistedSurfaceState get state => _state;
set state(PersistedSurfaceState newState) {
assert(newState != _state,
'Attempted to set state that the surface is already in. This likely indicates a bug in the compositor.');
assert(_debugValidateStateTransition(newState));
_state = newState;
}
PersistedSurfaceState _state = PersistedSurfaceState.created;
bool _debugValidateStateTransition(PersistedSurfaceState newState) {
if (newState == PersistedSurfaceState.created) {
assert(isReleased, 'Only released surfaces may be revived.');
} else {
assert(!isReleased,
'Released surfaces may only be revived, but caught attempt to set $newState.');
}
if (newState == PersistedSurfaceState.active) {
assert(
isCreated || isPendingRetention || isPendingUpdate,
'Surface is $state. Only created, pending retention, and pending update surfaces may be activated.',
);
}
if (newState == PersistedSurfaceState.pendingRetention) {
assert(isActive,
'Surface is not active. Only active surfaces may be retained.');
}
if (newState == PersistedSurfaceState.pendingUpdate) {
assert(isActive,
'Surface is not active. Only active surfaces may be updated.');
}
if (newState == PersistedSurfaceState.released) {
assert(isActive || isPendingUpdate,
'A surface may only be released if it is currently active or pending update, but it is in $state.');
}
return true;
}
/// Attempts to retain this surface along with its descendants.
///
/// If the surface is currently active this surface is retained. If the
/// surface is released, it means that the surface's DOM resources have been
/// reused before the request to retain it came in. In this case, the surface
/// is [revive]d and rebuilt from scratch.
void tryRetain() {
assert(debugAssertSurfaceState(
this, PersistedSurfaceState.active, PersistedSurfaceState.released));
// Request that the layer is retained, but only if it's still active. It
// could have been released.
if (isActive) {
state = PersistedSurfaceState.pendingRetention;
} else {
// The surface is released. This means that by the time addRetained was
// called this surface's DOM elements have been reused for something else.
// In this case, we reset the surface back to "created" state.
revive();
}
}
/// Turns a previously released surface and all its descendants into a
/// [PersistedSurfaceState.created] one.
///
/// This is used to rebuild surfaces that were released before a request to
/// retain came in.
@mustCallSuper
@visibleForTesting
void revive() {
assert(debugAssertSurfaceState(this, PersistedSurfaceState.released));
state = PersistedSurfaceState.created;
}
/// The surface is in the [PersistedSurfaceState.created] state;
bool get isCreated => _state == PersistedSurfaceState.created;
/// The surface is in the [PersistedSurfaceState.active] state;
bool get isActive => _state == PersistedSurfaceState.active;
/// The surface is in the [PersistedSurfaceState.pendingRetention] state;
bool get isPendingRetention =>
_state == PersistedSurfaceState.pendingRetention;
/// The surface is in the [PersistedSurfaceState.pendingUpdate] state;
bool get isPendingUpdate => _state == PersistedSurfaceState.pendingUpdate;
/// The surface is in the [PersistedSurfaceState.released] state;
bool get isReleased => _state == PersistedSurfaceState.released;
/// The root element that renders this surface to the DOM.
///
/// This element can be reused across frames. See also, [childContainer],
/// which is the element used to manage child nodes.
DomElement? rootElement;
/// Whether this surface can update an existing [oldSurface].
@mustCallSuper
bool canUpdateAsMatch(PersistedSurface oldSurface) {
return oldSurface.isActive && runtimeType == oldSurface.runtimeType;
}
/// The element that contains child surface elements.
///
/// By default this is the same as the [rootElement]. However, specialized
/// surface implementations may choose to override this and provide a
/// different element for nesting children.
DomElement? get childContainer => rootElement;
/// This surface's immediate parent.
PersistedContainerSurface? parent;
/// Visits immediate children.
///
/// Does not recurse.
void visitChildren(PersistedSurfaceVisitor visitor);
/// Computes how expensive it would be to update an [existingSurface]'s DOM
/// resources using this surface's data.
///
/// The returned value is a score between 0.0 and 1.0, inclusive. 0.0 is the
/// perfect score, meaning that the update is free. 1.0 is the worst score,
/// indicating that the DOM resources cannot be reused, and if an update is
/// performed, will result in reallocation.
///
/// Values that fall strictly between 0.0 and 1.0 are used to communicate
/// the efficiency of updates, with lower scores having better efficiency
/// compared to higher scores. For example, when matching a picture with a
/// bitmap canvas the score is higher for a canvas that's bigger in size than
/// a smaller canvas that also fits the picture.
double matchForUpdate(covariant PersistedSurface? existingSurface);
/// Creates a new element and sets the necessary HTML and CSS attributes.
///
/// This is called when we failed to locate an existing DOM element to reuse,
/// such as on the very first frame.
@mustCallSuper
void build() {
assert(() {
final DomElement? existingElement = rootElement;
if (existingElement != null) {
throw PersistedSurfaceException(
this,
'Attempted to build a $runtimeType, but it already has an HTML '
'element ${existingElement.tagName}.',
);
}
return true;
}());
assert(debugAssertSurfaceState(this, PersistedSurfaceState.created));
rootElement = createElement();
assert(rootElement != null);
applyWebkitClipFix(rootElement);
if (debugExplainSurfaceStats) {
surfaceStatsFor(this).allocatedDomNodeCount++;
}
apply();
state = PersistedSurfaceState.active;
}
/// Instructs this surface to adopt HTML DOM elements of another surface.
///
/// This is done for efficiency. Instead of creating new DOM elements on every
/// frame, we reuse old ones as much as possible. This method should only be
/// called when [isTotalMatchFor] returns true for the [oldSurface]. Otherwise
/// adopting the [oldSurface]'s elements could lead to correctness issues.
@mustCallSuper
void adoptElements(covariant PersistedSurface oldSurface) {
assert(oldSurface.rootElement != null);
assert(debugAssertSurfaceState(oldSurface, PersistedSurfaceState.active,
PersistedSurfaceState.pendingUpdate));
assert(() {
if (oldSurface.isPendingUpdate) {
final PersistedContainerSurface self =
this as PersistedContainerSurface;
assert(identical(self.oldLayer, oldSurface));
}
return true;
}());
rootElement = oldSurface.rootElement;
if (debugExplainSurfaceStats) {
surfaceStatsFor(this).reuseElementCount++;
}
// We took ownership of the old element.
oldSurface.rootElement = null;
// Make sure the old surface object is no longer usable.
oldSurface.state = PersistedSurfaceState.released;
}
/// Updates the attributes of this surface's element.
///
/// Attempts to reuse [oldSurface]'s DOM element, if possible. Otherwise,
/// creates a new element by calling [build].
@mustCallSuper
void update(covariant PersistedSurface oldSurface) {
assert(!identical(oldSurface, this));
assert(debugAssertSurfaceState(this, PersistedSurfaceState.created));
assert(debugAssertSurfaceState(oldSurface, PersistedSurfaceState.active,
PersistedSurfaceState.pendingUpdate));
adoptElements(oldSurface);
assert(() {
rootElement!.setAttribute('flt-layer-state', 'updated');
return true;
}());
state = PersistedSurfaceState.active;
assert(rootElement != null);
}
/// Reuses a [PersistedSurface] rendered in the previous frame.
///
/// This is different from [update], which reuses another surface's elements,
/// i.e. it was not requested to be retained by the framework.
///
/// This is also different from [build], which constructs a brand new surface
/// sub-tree.
@mustCallSuper
void retain() {
assert(rootElement != null);
if (isPendingRetention) {
// Adding to the list of retained surfaces so that at the end of the frame
// it is set to active state. We do not set the state to active
// immediately. Otherwise, another surface could match on it and steal
// this surface's DOM elements.
retainedSurfaces.add(this);
}
assert(() {
rootElement!.setAttribute('flt-layer-state', 'retained');
return true;
}());
if (debugExplainSurfaceStats) {
surfaceStatsFor(this).retainSurfaceCount++;
}
}
/// Removes the [element] of this surface from the tree and makes this
/// surface released.
///
/// This method may be overridden by concrete implementations, for example, to
/// recycle the resources owned by this surface.
@mustCallSuper
void discard() {
assert(debugAssertSurfaceState(this, PersistedSurfaceState.active));
assert(rootElement != null);
// TODO(yjbanov): it may be wasteful to recursively disassemble the DOM tree
// node by node. It should be sufficient to detach the root
// of the tree and let the browser handle the rest. Note,
// element.isConnected might be a poor choice to drive this
// decision because it is sensitive to the timing of when a
// scene's element is attached to the document. We might want
// to use a custom tracking mechanism, such as pass a boolean
// to `discard`, which would be `true` for the root, and
// `false` for children. Or, which might be cleaner, we could
// split this method into two methods. One method will detach
// the DOM, and the second method will disassociate the
// surface from the DOM and release it irrespective of
// whether the DOM itself gets detached or not.
rootElement!.remove();
rootElement = null;
state = PersistedSurfaceState.released;
}
@override
@mustCallSuper
void dispose() {}
@mustCallSuper
void debugValidate(List<String> validationErrors) {
if (rootElement == null) {
validationErrors.add('${debugIdentify(this)} has null rootElement.');
}
if (!isActive) {
validationErrors.add('${debugIdentify(this)} is in the wrong state.\n'
'It is in the live DOM tree expectec to be in ${PersistedSurfaceState.active}.\n'
'However, it is currently in $state.');
}
}
/// Creates a DOM element for this surface.
DomElement createElement();
/// Creates a DOM element for this surface preconfigured with common
/// attributes, such as absolute positioning and debug information.
DomElement defaultCreateElement(String tagName) {
final DomElement element = createDomElement(tagName);
element.style.position = 'absolute';
assert(() {
element.setAttribute('flt-layer-state', 'new');
return true;
}());
return element;
}
/// Sets the HTML and CSS properties appropriate for this surface's
/// implementation.
///
/// For example, [PersistedTransform] sets the "transform" CSS attribute.
void apply();
/// The effective transform at this surface level.
///
/// This value is computed by concatenating transforms of all ancestor
/// transforms as well as this layer's transform (if any).
///
/// The value is update by [recomputeTransformAndClip].
Matrix4? transform;
/// The intersection at this surface level.
///
/// This value is the intersection of clips in the ancestor chain, including
/// the clip added by this layer (if any).
///
/// The value is update by [recomputeTransformAndClip].
ui.Rect? projectedClip;
/// Bounds of clipping performed by this layer.
ui.Rect? localClipBounds;
/// The inverse of the local transform that this surface applies to its children.
///
/// The default implementation is identity transform. Concrete
/// implementations may override this getter to supply a different transform.
Matrix4? get localTransformInverse => null;
/// Recomputes [transform] and [globalClip] fields.
///
/// The default implementation inherits the values from the parent. Concrete
/// surface implementations may override this with their custom transform and
/// clip behaviors.
///
/// This method is called by the [preroll] method.
void recomputeTransformAndClip() {
transform = parent!.transform;
localClipBounds = null;
projectedClip = null;
}
/// Performs computations before [build], [update], or [retain] are called.
///
/// The computations prepare data needed for efficient scene diffing. For
/// example, as part of a preroll we compute transforms and cull rects, which
/// are used to find the best matching canvases.
///
/// This method recursively walks the surface tree calling `preroll` on all
/// descendants.
void preroll(PrerollSurfaceContext prerollContext) {
recomputeTransformAndClip();
}
/// Prints this surface into a [buffer] in a human-readable format.
void debugPrint(StringBuffer buffer, int indent) {
if (rootElement != null) {
buffer.write('${' ' * indent}<${rootElement!.tagName.toLowerCase()} ');
} else {
buffer.write('${' ' * indent}<$runtimeType recycled ');
}
debugPrintAttributes(buffer);
buffer.writeln('>');
debugPrintChildren(buffer, indent);
if (rootElement != null) {
buffer
.writeln('${' ' * indent}</${rootElement!.tagName.toLowerCase()}>');
} else {
buffer.writeln('${' ' * indent}</$runtimeType>');
}
}
@mustCallSuper
void debugPrintAttributes(StringBuffer buffer) {
if (rootElement != null) {
buffer.write('@${rootElement!.hashCode} ');
}
}
@mustCallSuper
void debugPrintChildren(StringBuffer buffer, int indent) {}
@override
String toString() {
String result = super.toString();
assert(() {
final StringBuffer log = StringBuffer();
debugPrint(log, 0);
result = log.toString();
return true;
}());
return result;
}
}
/// A surface that doesn't have child surfaces.
abstract class PersistedLeafSurface extends PersistedSurface {
PersistedLeafSurface() : super(null);
@override
void visitChildren(PersistedSurfaceVisitor visitor) {
// Does not have children.
}
}
/// A surface that has a flat list of child surfaces.
abstract class PersistedContainerSurface extends PersistedSurface {
/// Creates a container surface.
///
/// `oldLayer` points to the surface rendered in the previous frame that's
/// being updated by this layer.
PersistedContainerSurface(PersistedSurface? oldLayer) : super(oldLayer) {
assert(oldLayer == null || runtimeType == oldLayer.runtimeType);
}
final List<PersistedSurface> _children = <PersistedSurface>[];
@override
void visitChildren(PersistedSurfaceVisitor visitor) {
_children.forEach(visitor);
}
/// Adds a child to this container.
void appendChild(PersistedSurface child) {
assert(debugAssertSurfaceState(
child,
PersistedSurfaceState.created,
PersistedSurfaceState.pendingRetention,
PersistedSurfaceState.pendingUpdate));
_children.add(child);
child.parent = this;
}
@override
void preroll(PrerollSurfaceContext prerollContext) {
super.preroll(prerollContext);
final int length = _children.length;
for (int i = 0; i < length; i += 1) {
_children[i].preroll(prerollContext);
}
}
@override
void recomputeTransformAndClip() {
transform = parent!.transform;
localClipBounds = null;
projectedClip = null;
}
@override
void build() {
super.build();
// Memoize length for efficiency.
final int len = _children.length;
// Memoize container element for efficiency. [childContainer] is polymorphic
final DomElement? containerElement = childContainer;
for (int i = 0; i < len; i++) {
final PersistedSurface child = _children[i];
if (child.isPendingRetention) {
assert(child.rootElement != null);
child.retain();
} else if (child is PersistedContainerSurface && child.oldLayer != null) {
final PersistedSurface oldLayer = child.oldLayer!;
assert(oldLayer.rootElement != null);
assert(debugAssertSurfaceState(
oldLayer, PersistedSurfaceState.pendingUpdate));
child.update(oldLayer as PersistedContainerSurface);
} else {
assert(debugAssertSurfaceState(child, PersistedSurfaceState.created));
assert(child.rootElement == null);
child.build();
}
containerElement!.append(child.rootElement!);
child._index = i;
}
_debugValidateContainerNewState();
}
@override
double matchForUpdate(PersistedContainerSurface? existingSurface) {
assert(existingSurface!.runtimeType == runtimeType);
// Intermediate container nodes don't have many resources worth comparing,
// so we always return 1.0 to signal that it doesn't matter which one to
// choose.
// TODO(yjbanov): while the container doesn't have own resources, imperfect
// matching can lead to unnecessary reparenting of DOM
// subtrees. One trick we could try is to look at children's
// oldLayer values and see if we can use those to match
// intermediate surfaces better.
return 1.0;
}
@override
void update(PersistedContainerSurface oldSurface) {
assert(debugAssertSurfaceState(oldSurface, PersistedSurfaceState.active,
PersistedSurfaceState.pendingUpdate));
assert(runtimeType == oldSurface.runtimeType);
super.update(oldSurface);
assert(debugAssertSurfaceState(oldSurface, PersistedSurfaceState.released));
if (oldSurface._children.isEmpty) {
_updateZeroToMany(oldSurface);
} else if (_children.length == 1) {
_updateManyToOne(oldSurface);
} else if (_children.isEmpty) {
_discardActiveChildren(oldSurface);
} else {
_updateManyToMany(oldSurface);
}
assert(() {
_debugValidateContainerUpdate(oldSurface);
return true;
}());
}
// Children should override if they are performing clipping.
//
// Used by BackdropFilter to locate it's ancestor clip element.
bool get isClipping => false;
void _debugValidateContainerUpdate(PersistedContainerSurface oldSurface) {
// At the end of this all children should have an element each, and it
// should be attached to this container's element.
assert(() {
for (int i = 0; i < oldSurface._children.length; i++) {
final PersistedSurface oldChild = oldSurface._children[i];
assert(!oldChild.isActive && !oldChild.isCreated,
'Old child is in incorrect state ${oldChild.state}');
if (oldChild.isReleased) {
assert(oldChild.rootElement == null);
assert(oldChild.childContainer == null);
}
}
_debugValidateContainerNewState();
return true;
}());
}
void _debugValidateContainerNewState() {
assert(() {
for (int i = 0; i < _children.length; i++) {
final PersistedSurface newChild = _children[i];
assert(newChild._index == i);
assert(debugAssertSurfaceState(newChild, PersistedSurfaceState.active,
PersistedSurfaceState.pendingRetention));
assert(newChild.rootElement != null);
assert(newChild.rootElement!.parent == childContainer);
}
return true;
}());
}
/// This is a fast path update for the case when an empty container is being
/// populated with children.
///
/// This method does not do any matching.
void _updateZeroToMany(PersistedContainerSurface oldSurface) {
assert(oldSurface._children.isEmpty);
// Memoizing variables for efficiency.
final DomElement? containerElement = childContainer;
final int length = _children.length;
for (int i = 0; i < length; i++) {
final PersistedSurface newChild = _children[i];
if (newChild.isPendingRetention) {
newChild.retain();
assert(debugAssertSurfaceState(
newChild, PersistedSurfaceState.pendingRetention));
} else if (newChild is PersistedContainerSurface &&
newChild.oldLayer != null) {
final PersistedContainerSurface oldLayer =
newChild.oldLayer! as PersistedContainerSurface;
assert(debugAssertSurfaceState(
oldLayer, PersistedSurfaceState.pendingUpdate));
newChild.update(oldLayer);
assert(
debugAssertSurfaceState(oldLayer, PersistedSurfaceState.released));
assert(debugAssertSurfaceState(newChild, PersistedSurfaceState.active));
} else {
newChild.build();
assert(debugAssertSurfaceState(newChild, PersistedSurfaceState.active));
}
newChild._index = i;
assert(newChild.rootElement != null);
containerElement!.append(newChild.rootElement!);
}
}
/// Called to release children that were not reused this frame.
static void _discardActiveChildren(PersistedContainerSurface surface) {
final int length = surface._children.length;
for (int i = 0; i < length; i += 1) {
final PersistedSurface child = surface._children[i];
// Only release active children that are currently active (i.e. they are
// not pending retention or update).
if (child.isActive) {
child.discard();
}
assert(!child.isCreated && !child.isActive);
}
}
/// This is a fast path update for the common case when there's only one child
/// active in this frame.
void _updateManyToOne(PersistedContainerSurface oldSurface) {
assert(_children.length == 1);
final PersistedSurface newChild = _children[0];
newChild._index = 0;
// Retained child is moved to the correct location in the tree; all others
// are released.
if (newChild.isPendingRetention) {
assert(newChild.rootElement != null);
// Move the HTML node if necessary.
if (newChild.rootElement!.parent != childContainer) {
childContainer!.append(newChild.rootElement!);
}
newChild.retain();
_discardActiveChildren(oldSurface);
assert(debugAssertSurfaceState(
newChild, PersistedSurfaceState.pendingRetention));
return;
}
// Updated child is moved to the correct location in the tree; all others
// are released.
if (newChild is PersistedContainerSurface && newChild.oldLayer != null) {
assert(debugAssertSurfaceState(
newChild.oldLayer!, PersistedSurfaceState.pendingUpdate));
assert(newChild.rootElement == null);
assert(newChild.oldLayer!.rootElement != null);
final PersistedContainerSurface oldLayer =
newChild.oldLayer! as PersistedContainerSurface;
// Move the HTML node if necessary.
if (oldLayer.rootElement!.parent != childContainer) {
childContainer!.append(oldLayer.rootElement!);
}
newChild.update(oldLayer);
_discardActiveChildren(oldSurface);
assert(debugAssertSurfaceState(oldLayer, PersistedSurfaceState.released));
assert(debugAssertSurfaceState(newChild, PersistedSurfaceState.active));
return;
}
assert(debugAssertSurfaceState(newChild, PersistedSurfaceState.created));
PersistedSurface? bestMatch;
double bestScore = 2.0;
for (int i = 0; i < oldSurface._children.length; i++) {
final PersistedSurface candidate = oldSurface._children[i];
if (!newChild.canUpdateAsMatch(candidate)) {
continue;
}
final double score = newChild.matchForUpdate(candidate);
if (score < bestScore) {
bestMatch = candidate;
bestScore = score;
}
}
if (bestMatch != null) {
assert(debugAssertSurfaceState(bestMatch, PersistedSurfaceState.active));
newChild.update(bestMatch);
// Move the HTML node if necessary.
if (newChild.rootElement!.parent != childContainer) {
childContainer!.append(newChild.rootElement!);
}
assert(
debugAssertSurfaceState(bestMatch, PersistedSurfaceState.released));
} else {
newChild.build();
childContainer!.append(newChild.rootElement!);
assert(debugAssertSurfaceState(newChild, PersistedSurfaceState.active));
}
// Child nodes that were not used this frame that are still active and not
// explicitly retained or updated are discarded.
for (int i = 0; i < oldSurface._children.length; i++) {
final PersistedSurface oldChild = oldSurface._children[i];
if (!identical(oldChild, bestMatch) && oldChild.isActive) {
oldChild.discard();
}
assert(!oldChild.isCreated && !oldChild.isActive);
}
}
/// This is the general case when multiple children are matched against
/// multiple children.
void _updateManyToMany(PersistedContainerSurface oldSurface) {
assert(_children.isNotEmpty && oldSurface._children.isNotEmpty);
// Memoize container element for efficiency. [childContainer] is polymorphic
final DomElement? containerElement = childContainer;
final Map<PersistedSurface?, PersistedSurface> matches =
_matchChildren(oldSurface);
// This pair of lists maps from _children indices to oldSurface._children indices.
// These lists are initialized lazily, only when we discover that we will need to
// move nodes around. Otherwise, these lists remain null.
List<int>? indexMapNew;
List<int>? indexMapOld;
// Whether children need to move around the DOM. It is common for children
// to be updated/retained but never move. Knowing this allows us to bypass
// the expensive logic that figures out the minimal number of moves.
bool requiresDomInserts = false;
for (int topInNew = 0; topInNew < _children.length; topInNew += 1) {
final PersistedSurface newChild = _children[topInNew];
// The old child surface that `newChild` was updated or retained from.
PersistedSurface? matchedOldChild;
// Whether the child is getting a new parent. This happens in the
// following situations:
// - It's a new child and is being attached for the first time.
// - It's an existing child is being updated or retained and at the same
// time moved to another parent.
bool isReparenting = true;
if (newChild.isPendingRetention) {
isReparenting = newChild.rootElement!.parent != containerElement;
newChild.retain();
matchedOldChild = newChild;
assert(debugAssertSurfaceState(
newChild, PersistedSurfaceState.pendingRetention));
} else if (newChild is PersistedContainerSurface &&
newChild.oldLayer != null) {
final PersistedContainerSurface oldLayer =
newChild.oldLayer! as PersistedContainerSurface;
isReparenting = oldLayer.rootElement!.parent != containerElement;
matchedOldChild = oldLayer;
assert(debugAssertSurfaceState(
oldLayer, PersistedSurfaceState.pendingUpdate));
newChild.update(oldLayer);
assert(
debugAssertSurfaceState(oldLayer, PersistedSurfaceState.released));
assert(debugAssertSurfaceState(newChild, PersistedSurfaceState.active));
} else {
matchedOldChild = matches[newChild];
if (matchedOldChild != null) {
assert(debugAssertSurfaceState(
matchedOldChild, PersistedSurfaceState.active));
isReparenting =
matchedOldChild.rootElement!.parent != containerElement;
newChild.update(matchedOldChild);
assert(debugAssertSurfaceState(
matchedOldChild, PersistedSurfaceState.released));
assert(
debugAssertSurfaceState(newChild, PersistedSurfaceState.active));
} else {
newChild.build();
assert(
debugAssertSurfaceState(newChild, PersistedSurfaceState.active));
}
}
int indexInOld = -1;
if (matchedOldChild != null && !isReparenting) {
assert(
matchedOldChild._index != -1,
'Invalid index ${matchedOldChild._index} of child layer ${matchedOldChild.runtimeType}',
);
indexInOld = matchedOldChild._index;
}
// indexInOld != topInNew indicates that at least one child has moved and
// therefore we'll need to find the minimum moves necessary to update the
// child list.
if (!requiresDomInserts && indexInOld != topInNew) {
requiresDomInserts = true;
indexMapNew = <int>[];
indexMapOld = <int>[];
// Because up until this moment we haven't been populating the
// indexMapNew and indexMapOld, we backfill them with indices up until
// the current index.
for (int backfill = 0; backfill < topInNew; backfill++) {
indexMapNew.add(backfill);
indexMapOld.add(backfill);
}
}
if (requiresDomInserts && indexInOld != -1) {
indexMapNew!.add(topInNew);
indexMapOld!.add(indexInOld);
}
newChild._index = topInNew;
assert(newChild.rootElement != null);
assert(debugAssertSurfaceState(newChild, PersistedSurfaceState.active,
PersistedSurfaceState.pendingRetention));
}
// Avoid calling `_insertChildDomNodes` unnecessarily. Only call it if we
// actually need to move DOM nodes around.
if (requiresDomInserts) {
assert(indexMapNew!.length == indexMapOld!.length);
_insertChildDomNodes(indexMapNew, indexMapOld!);
} else {
// The fast path, where nothing needs to move, should not intialize the
// mapping lists at all.
assert(indexMapNew == null);
assert(indexMapOld == null);
}
// Remove elements that were not reused this frame.
_discardActiveChildren(oldSurface);
}
/// Performs the minimum number of DOM moves necessary to put all children in
/// the right place in the DOM.
void _insertChildDomNodes(List<int>? indexMapNew, List<int> indexMapOld) {
final List<int?> stationaryIndices =
longestIncreasingSubsequence(indexMapOld);
// Convert to stationary new indices
for (int i = 0; i < stationaryIndices.length; i++) {
stationaryIndices[i] = indexMapNew![stationaryIndices[i]!];
}
DomHTMLElement? refNode;
final DomElement? containerElement = childContainer;
for (int i = _children.length - 1; i >= 0; i -= 1) {
final int indexInNew = indexMapNew!.indexOf(i);
final bool isStationary =
indexInNew != -1 && stationaryIndices.contains(i);
final PersistedSurface child = _children[i];
final DomHTMLElement childElement =
child.rootElement! as DomHTMLElement;
if (!isStationary) {
if (refNode == null) {
containerElement!.append(childElement);
} else {
containerElement!.insertBefore(childElement, refNode);
}
}
refNode = childElement;
assert(child.rootElement!.parent == childContainer);
}
}
Map<PersistedSurface?, PersistedSurface> _matchChildren(
PersistedContainerSurface oldSurface) {
final int newUnfilteredChildCount = _children.length;
final int oldUnfilteredChildCount = oldSurface._children.length;
// Extract new nodes that need to be matched.
final List<PersistedSurface> newChildren = <PersistedSurface>[];
for (int i = 0; i < newUnfilteredChildCount; i++) {
final PersistedSurface child = _children[i];
// If child has an old layer, it means it's scheduled for an explicit
// update, and therefore there's no need to try to match it.
if (child.isCreated && child.oldLayer == null) {
newChildren.add(child);
}
}
// Extract old nodes that can be matched against.
final List<PersistedSurface?> oldChildren = <PersistedSurface?>[];
for (int i = 0; i < oldUnfilteredChildCount; i++) {
final PersistedSurface child = oldSurface._children[i];
if (child.isActive) {
oldChildren.add(child);
}
}
final int newChildCount = newChildren.length;
final int oldChildCount = oldChildren.length;
if (newChildCount == 0 || oldChildCount == 0) {
// Nothing to match.
return const <PersistedSurface, PersistedSurface>{};
}
final List<_PersistedSurfaceMatch> allMatches = <_PersistedSurfaceMatch>[];
// This is worst-case O(N*M) but it only happens when:
// - most of the children are newly created (N)
// - the old container is not empty (M)
//
// The choice here is between recreating all DOM nodes from scratch, or try
// finding matches and reusing their elements.
for (int indexInNew = 0; indexInNew < newChildCount; indexInNew += 1) {
final PersistedSurface newChild = newChildren[indexInNew];
for (int indexInOld = 0; indexInOld < oldChildCount; indexInOld += 1) {
final PersistedSurface? oldChild = oldChildren[indexInOld];
final bool childAlreadyClaimed = oldChild == null;
if (childAlreadyClaimed || !newChild.canUpdateAsMatch(oldChild)) {
continue;
}
allMatches.add(_PersistedSurfaceMatch(
matchQuality: newChild.matchForUpdate(oldChild),
newChild: newChild,
oldChildIndex: indexInOld,
));
}
}
allMatches.sort((_PersistedSurfaceMatch m1, _PersistedSurfaceMatch m2) {
return m1.matchQuality!.compareTo(m2.matchQuality!);
});
final Map<PersistedSurface?, PersistedSurface> result =
<PersistedSurface?, PersistedSurface>{};
for (int i = 0; i < allMatches.length; i += 1) {
final _PersistedSurfaceMatch match = allMatches[i];
// This may be null if it has been claimed.
final PersistedSurface? matchedChild = oldChildren[match.oldChildIndex!];
// Whether the new child hasn't found a match yet.
final bool newChildNeedsMatch = result[match.newChild] == null;
if (matchedChild != null && newChildNeedsMatch) {
oldChildren[match.oldChildIndex!] = null;
result[match.newChild] = matchedChild; // claim it
}
}
assert(result.length == Set<PersistedSurface>.from(result.values).length);
return result;
}
@override
void retain() {
super.retain();
final int len = _children.length;
for (int i = 0; i < len; i++) {
_children[i].retain();
}
}
@override
void revive() {
super.revive();
final int len = _children.length;
for (int i = 0; i < len; i++) {
_children[i].revive();
}
}
@override
void discard() {
super.discard();
_discardActiveChildren(this);
}
@override
@mustCallSuper
void debugValidate(List<String> validationErrors) {
super.debugValidate(validationErrors);
for (int i = 0; i < _children.length; i++) {
final PersistedSurface child = _children[i];
if (child.parent != this) {
validationErrors.add(
'${debugIdentify(child)} parent is ${debugIdentify(child.parent)} but expected the parent to be ${debugIdentify(this)}');
}
}
for (int i = 0; i < _children.length; i++) {
_children[i].debugValidate(validationErrors);
}
}
@override
void debugPrintChildren(StringBuffer buffer, int indent) {
super.debugPrintChildren(buffer, indent);
for (int i = 0; i < _children.length; i++) {
_children[i].debugPrint(buffer, indent + 1);
}
}
}
/// A custom class used by [PersistedContainerSurface._matchChildren].
class _PersistedSurfaceMatch {
_PersistedSurfaceMatch({
this.newChild,
this.oldChildIndex,
this.matchQuality,
});
/// The child in the new scene who we are trying to match to an existing
/// child.
final PersistedSurface? newChild;
/// The index pointing at the old child that matched [newChild] in the old
/// child list.
///
/// The indirection is intentional because when matches are traversed old
/// children are claimed and nulled out in the array.
final int? oldChildIndex;
/// The score of how well [newChild] matched the old child as computed by
/// [PersistedSurface.matchForUpdate].
final double? matchQuality;
@override
String toString() {
String result = super.toString();
assert(() {
result = '_PersistedSurfaceMatch(${newChild!.runtimeType}#${newChild!.hashCode}: $oldChildIndex, quality: $matchQuality)';
return true;
}());
return result;
}
}
/// Data used during preroll to pass rendering hints efficiently to children
/// by optimizing (prevent parent lookups) and in cases like svg filters
/// drive the decision on whether canvas elements can be used to render.
class PrerollSurfaceContext {
/// Number of active color filters in parent surfaces.
int activeColorFilterCount = 0;
/// Number of active shader masks in parent surfaces.
int activeShaderMaskCount = 0;
}
| engine/lib/web_ui/lib/src/engine/html/surface.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/html/surface.dart",
"repo_id": "engine",
"token_count": 15316
} | 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.
import 'package:meta/meta.dart';
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import '../dom.dart';
import '../platform_dispatcher.dart';
import '../services/message_codec.dart';
import '../services/message_codecs.dart';
/// Infers the history mode from the existing browser history state, then
/// creates the appropriate instance of [BrowserHistory] for it.
///
/// If it can't infer, it creates a [MultiEntriesBrowserHistory] by default.
BrowserHistory createHistoryForExistingState(ui_web.UrlStrategy? urlStrategy) {
if (urlStrategy != null) {
final Object? state = urlStrategy.getState();
if (SingleEntryBrowserHistory._isOriginEntry(state) || SingleEntryBrowserHistory._isFlutterEntry(state)) {
return SingleEntryBrowserHistory(urlStrategy: urlStrategy);
}
}
return MultiEntriesBrowserHistory(urlStrategy: urlStrategy);
}
/// An abstract class that provides the API for [EngineWindow] to delegate its
/// navigating events.
///
/// Subclasses will have access to [BrowserHistory.locationStrategy] to
/// interact with the html browser history and should come up with their own
/// ways to manage the states in the browser history.
///
/// There should only be one global instance among all subclasses.
///
/// See also:
///
/// * [SingleEntryBrowserHistory]: which creates a single fake browser history
/// entry and delegates all browser navigating events to the flutter
/// framework.
/// * [MultiEntriesBrowserHistory]: which creates a set of states that records
/// the navigating events happened in the framework.
abstract class BrowserHistory {
late ui.VoidCallback _unsubscribe;
/// The strategy to interact with html browser history.
ui_web.UrlStrategy? get urlStrategy;
bool _isTornDown = false;
bool _isDisposed = false;
void _setupStrategy(ui_web.UrlStrategy strategy) {
_unsubscribe = strategy.addPopStateListener(onPopState);
}
/// Release any resources held by this [BrowserHistory] instance.
///
/// This method has no effect on the browser history entries. Use [tearDown]
/// instead to revert this instance's modifications to browser history
/// entries.
@mustCallSuper
void dispose() {
if (_isDisposed || urlStrategy == null) {
return;
}
_isDisposed = true;
_unsubscribe();
}
/// Exit this application and return to the previous page.
Future<void> exit() async {
if (urlStrategy != null) {
await tearDown();
// Now the history should be in the original state, back one more time to
// exit the application.
await urlStrategy!.go(-1);
}
}
/// This method does the same thing as the browser back button.
Future<void> back() async {
return urlStrategy?.go(-1);
}
/// The path of the current location of the user's browser.
String get currentPath => urlStrategy?.getPath() ?? '/';
/// The state of the current location of the user's browser.
Object? get currentState => urlStrategy?.getState();
/// Update the url with the given `routeName` and `state`.
///
/// If `replace` is false, the caller wants to push a new `routeName` and
/// `state` on top of the existing ones; otherwise, the caller wants to replace
/// the current `routeName` and `state` with the new ones.
void setRouteName(String? routeName, {Object? state, bool replace = false});
/// A callback method to handle browser backward or forward buttons.
///
/// Subclasses should send appropriate system messages to update the flutter
/// applications accordingly.
void onPopState(Object? state);
/// Restore any modifications to the html browser history during the lifetime
/// of this class.
Future<void> tearDown();
}
/// A browser history class that creates a set of browser history entries to
/// support browser backward and forward button natively.
///
/// This class pushes a browser history entry every time the framework reports
/// a route change and sends a `pushRouteInformation` method call to the
/// framework when the browser jumps to a specific browser history entry.
///
/// The web engine uses this class to manage its browser history when the
/// framework uses a Router for routing.
///
/// See also:
///
/// * [SingleEntryBrowserHistory], which is used when the framework does not use
/// a Router for routing.
class MultiEntriesBrowserHistory extends BrowserHistory {
MultiEntriesBrowserHistory({required this.urlStrategy}) {
final ui_web.UrlStrategy? strategy = urlStrategy;
if (strategy == null) {
return;
}
_setupStrategy(strategy);
if (!_hasSerialCount(currentState)) {
strategy.replaceState(
_tagWithSerialCount(currentState, 0), 'flutter', currentPath);
}
// If we restore from a page refresh, the _currentSerialCount may not be 0.
_lastSeenSerialCount = _currentSerialCount;
}
@override
final ui_web.UrlStrategy? urlStrategy;
late int _lastSeenSerialCount;
int get _currentSerialCount {
if (_hasSerialCount(currentState)) {
final Map<dynamic, dynamic> stateMap =
currentState! as Map<dynamic, dynamic>;
return (stateMap['serialCount'] as double).toInt();
}
return 0;
}
Object _tagWithSerialCount(Object? originialState, int count) {
return <dynamic, dynamic>{
'serialCount': count.toDouble(),
'state': originialState,
};
}
bool _hasSerialCount(Object? state) {
return state is Map && state['serialCount'] != null;
}
@override
void setRouteName(String? routeName, {Object? state, bool replace = false}) {
if (urlStrategy != null) {
assert(routeName != null);
if (replace) {
urlStrategy!.replaceState(
_tagWithSerialCount(state, _lastSeenSerialCount),
'flutter',
routeName!,
);
} else {
_lastSeenSerialCount += 1;
urlStrategy!.pushState(
_tagWithSerialCount(state, _lastSeenSerialCount),
'flutter',
routeName!,
);
}
}
}
@override
void onPopState(Object? state) {
assert(urlStrategy != null);
// May be a result of direct url access while the flutter application is
// already running.
if (!_hasSerialCount(state)) {
// In this case we assume this will be the next history entry from the
// last seen entry.
urlStrategy!.replaceState(
_tagWithSerialCount(state, _lastSeenSerialCount + 1),
'flutter',
currentPath);
}
_lastSeenSerialCount = _currentSerialCount;
EnginePlatformDispatcher.instance.invokeOnPlatformMessage(
'flutter/navigation',
const JSONMethodCodec().encodeMethodCall(
MethodCall('pushRouteInformation', <dynamic, dynamic>{
'location': currentPath,
'state': (state as Map<dynamic, dynamic>?)?['state'],
})),
(_) {},
);
}
@override
Future<void> tearDown() async {
dispose();
if (_isTornDown || urlStrategy == null) {
return;
}
_isTornDown = true;
// Restores the html browser history.
assert(
_hasSerialCount(currentState),
currentState == null
? 'unexpected null history state'
: "history state is missing field 'serialCount'",
);
final int backCount = _currentSerialCount;
if (backCount > 0) {
await urlStrategy!.go(-backCount);
}
// Unwrap state.
assert(_hasSerialCount(currentState) && _currentSerialCount == 0);
final Map<dynamic, dynamic> stateMap =
currentState! as Map<dynamic, dynamic>;
urlStrategy!.replaceState(
stateMap['state'],
'flutter',
currentPath,
);
}
}
/// The browser history class is responsible for integrating Flutter Web apps
/// with the browser history so that the back button works as expected.
///
/// It does that by always keeping a single entry (conventionally called the
/// "flutter" entry) at the top of the browser history. That way, the browser's
/// back button always triggers a `popstate` event and never closes the app (we
/// close the app programmatically by calling [SystemNavigator.pop] when there
/// are no more app routes to be popped).
///
/// The web engine uses this class when the framework does not use Router for
/// routing, and it does not support browser forward button.
///
/// See also:
///
/// * [MultiEntriesBrowserHistory], which is used when the framework uses a
/// Router for routing.
class SingleEntryBrowserHistory extends BrowserHistory {
SingleEntryBrowserHistory({required this.urlStrategy}) {
final ui_web.UrlStrategy? strategy = urlStrategy;
if (strategy == null) {
return;
}
_setupStrategy(strategy);
final String path = currentPath;
if (!_isFlutterEntry(domWindow.history.state)) {
// An entry may not have come from Flutter, for example, when the user
// refreshes the page. They land directly on the "flutter" entry, so
// there's no need to set up the "origin" and "flutter" entries, we can
// safely assume they are already set up.
_setupOriginEntry(strategy);
_setupFlutterEntry(strategy, path: path);
}
}
@override
final ui_web.UrlStrategy? urlStrategy;
static const MethodCall _popRouteMethodCall = MethodCall('popRoute');
static const String _kFlutterTag = 'flutter';
static const String _kOriginTag = 'origin';
Map<String, dynamic> _wrapOriginState(Object? state) {
return <String, dynamic>{_kOriginTag: true, 'state': state};
}
Object? _unwrapOriginState(Object? state) {
assert(_isOriginEntry(state));
final Map<dynamic, dynamic> originState = state! as Map<dynamic, dynamic>;
return originState['state'];
}
final Map<String, bool> _flutterState = <String, bool>{_kFlutterTag: true};
/// The origin entry is the history entry that the Flutter app landed on. It's
/// created by the browser when the user navigates to the url of the app.
static bool _isOriginEntry(Object? state) {
return state is Map && state[_kOriginTag] == true;
}
/// The flutter entry is a history entry that we maintain on top of the origin
/// entry. It allows us to catch popstate events when the user hits the back
/// button.
static bool _isFlutterEntry(Object? state) {
return state is Map && state[_kFlutterTag] == true;
}
@override
void setRouteName(String? routeName, {Object? state, bool replace = false}) {
if (urlStrategy != null) {
_setupFlutterEntry(urlStrategy!, replace: true, path: routeName);
}
}
String? _userProvidedRouteName;
@override
void onPopState(Object? state) {
if (_isOriginEntry(state)) {
_setupFlutterEntry(urlStrategy!);
// 2. Send a 'popRoute' platform message so the app can handle it accordingly.
EnginePlatformDispatcher.instance.invokeOnPlatformMessage(
'flutter/navigation',
const JSONMethodCodec().encodeMethodCall(_popRouteMethodCall),
(_) {},
);
} else if (_isFlutterEntry(state)) {
// We get into this scenario when the user changes the url manually. It
// causes a new entry to be pushed on top of our "flutter" one. When this
// happens it first goes to the "else" section below where we capture the
// path into `_userProvidedRouteName` then trigger a history back which
// brings us here.
assert(_userProvidedRouteName != null);
final String newRouteName = _userProvidedRouteName!;
_userProvidedRouteName = null;
// Send a 'pushRoute' platform message so the app handles it accordingly.
EnginePlatformDispatcher.instance.invokeOnPlatformMessage(
'flutter/navigation',
const JSONMethodCodec().encodeMethodCall(
MethodCall('pushRoute', newRouteName),
),
(_) {},
);
} else {
// The user has pushed a new entry on top of our flutter entry. This could
// happen when the user modifies the hash part of the url directly, for
// example.
// 1. We first capture the user's desired path.
_userProvidedRouteName = currentPath;
// 2. Then we remove the new entry.
// This will take us back to our "flutter" entry and it causes a new
// popstate event that will be handled in the "else if" section above.
urlStrategy!.go(-1);
}
}
/// This method should be called when the Origin Entry is active. It just
/// replaces the state of the entry so that we can recognize it later using
/// [_isOriginEntry] inside [_popStateListener].
void _setupOriginEntry(ui_web.UrlStrategy strategy) {
strategy.replaceState(_wrapOriginState(currentState), 'origin', '');
}
/// This method is used manipulate the Flutter Entry which is always the
/// active entry while the Flutter app is running.
void _setupFlutterEntry(
ui_web.UrlStrategy strategy, {
bool replace = false,
String? path,
}) {
path ??= currentPath;
if (replace) {
strategy.replaceState(_flutterState, 'flutter', path);
} else {
strategy.pushState(_flutterState, 'flutter', path);
}
}
@override
Future<void> tearDown() async {
dispose();
if (_isTornDown || urlStrategy == null) {
return;
}
_isTornDown = true;
// We need to remove the flutter entry that we pushed in setup.
await urlStrategy!.go(-1);
// Restores original state.
urlStrategy!
.replaceState(_unwrapOriginState(currentState), 'flutter', currentPath);
}
}
| engine/lib/web_ui/lib/src/engine/navigation/history.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/navigation/history.dart",
"repo_id": "engine",
"token_count": 4457
} | 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.
import 'dart:async';
import 'dart:js_interop';
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import 'util.dart';
// TODO(mdebbar): Deprecate this and remove it.
// https://github.com/flutter/flutter/issues/127395
@JS('window._flutter_internal_on_benchmark')
external JSExportedDartFunction? get jsBenchmarkValueCallback;
ui_web.BenchmarkValueCallback? engineBenchmarkValueCallback;
/// A function that computes a value of type [R].
///
/// Functions of this signature can be passed to [timeAction] for performance
/// profiling.
typedef Action<R> = R Function();
/// Uses the [Profiler] to time a synchronous [action] function and reports the
/// result under the give metric [name].
///
/// If profiling is disabled, simply calls [action] and returns the result.
///
/// Use this for situations when the cost of an extra closure is negligible.
/// This function reduces the boilerplate associated with checking if profiling
/// is enabled and exercising the stopwatch.
///
/// Example:
///
/// ```
/// final result = timeAction('expensive_operation', () {
/// ... expensive work ...
/// return someValue;
/// });
/// ```
R timeAction<R>(String name, Action<R> action) {
if (!Profiler.isBenchmarkMode) {
return action();
} else {
final Stopwatch stopwatch = Stopwatch()..start();
final R result = action();
stopwatch.stop();
Profiler.instance.benchmark(name, stopwatch.elapsedMicroseconds.toDouble());
return result;
}
}
/// The purpose of this class is to facilitate communication of
/// profiling/benchmark data to the outside world (e.g. a macrobenchmark that's
/// running a flutter app).
///
/// To use the [Profiler]:
///
/// 1. Set the environment variable `FLUTTER_WEB_ENABLE_PROFILING` to true.
///
/// 2. Using JS interop, assign a listener function to
/// `window._flutter_internal_on_benchmark` in the browser.
///
/// The listener function will be called every time a new benchmark number is
/// calculated. The signature is `Function(String name, num value)`.
class Profiler {
Profiler._() {
_checkBenchmarkMode();
}
static bool isBenchmarkMode = const bool.fromEnvironment(
'FLUTTER_WEB_ENABLE_PROFILING',
);
static Profiler ensureInitialized() {
_checkBenchmarkMode();
return Profiler._instance ??= Profiler._();
}
static Profiler get instance {
_checkBenchmarkMode();
final Profiler? profiler = _instance;
if (profiler == null) {
throw Exception(
'Profiler has not been properly initialized. '
'Make sure Profiler.ensureInitialized() is being called before you '
'access Profiler.instance',
);
}
return profiler;
}
static Profiler? _instance;
static void _checkBenchmarkMode() {
if (!isBenchmarkMode) {
throw Exception(
'Cannot use Profiler unless benchmark mode is enabled. '
'You can enable it by setting the `FLUTTER_WEB_ENABLE_PROFILING` '
'environment variable to true.',
);
}
}
/// Used to send benchmark data to whoever is listening to them.
void benchmark(String name, double value) {
_checkBenchmarkMode();
final ui_web.BenchmarkValueCallback? callback =
jsBenchmarkValueCallback?.toDart as ui_web.BenchmarkValueCallback?;
if (callback != null) {
printWarning(
'The JavaScript benchmarking API (i.e. `window._flutter_internal_on_benchmark`) '
'is deprecated and will be removed in a future release. Please use '
'`benchmarkValueCallback` from `dart:ui_web` instead.',
);
callback(name, value);
}
if (engineBenchmarkValueCallback != null) {
engineBenchmarkValueCallback!(name, value);
}
}
}
/// Counts various events that take place while the app is running.
///
/// This class will slow down the app, and therefore should be disabled while
/// benchmarking. For example, avoid using it in conjunction with [Profiler].
class Instrumentation {
Instrumentation._() {
_checkInstrumentationEnabled();
}
/// Whether instrumentation is enabled.
///
/// Check this value before calling any other methods in this class.
static bool get enabled => _enabled;
static set enabled(bool value) {
if (_enabled == value) {
return;
}
if (!value) {
_instance._counters.clear();
_instance._printTimer = null;
}
_enabled = value;
}
static bool _enabled = const bool.fromEnvironment(
'FLUTTER_WEB_ENABLE_INSTRUMENTATION',
);
/// Returns the singleton that provides instrumentation API.
static Instrumentation get instance {
_checkInstrumentationEnabled();
return _instance;
}
static final Instrumentation _instance = Instrumentation._();
static void _checkInstrumentationEnabled() {
if (!enabled) {
throw StateError(
'Cannot use Instrumentation unless it is enabled. '
'You can enable it by setting the `FLUTTER_WEB_ENABLE_INSTRUMENTATION` '
'environment variable to true, or by passing '
'--dart-define=FLUTTER_WEB_ENABLE_INSTRUMENTATION=true to the flutter '
'tool.',
);
}
}
Map<String, int> get debugCounters => _counters;
final Map<String, int> _counters = <String, int>{};
Timer? get debugPrintTimer => _printTimer;
Timer? _printTimer;
/// Increments the count of a particular event by one.
void incrementCounter(String event) {
_checkInstrumentationEnabled();
final int currentCount = _counters[event] ?? 0;
_counters[event] = currentCount + 1;
_printTimer ??= Timer(
const Duration(seconds: 2),
() {
if (_printTimer == null || !_enabled) {
return;
}
final StringBuffer message = StringBuffer('Engine counters:\n');
// Entries are sorted for readability and testability.
final List<MapEntry<String, int>> entries = _counters.entries.toList()
..sort((MapEntry<String, int> a, MapEntry<String, int> b) {
return a.key.compareTo(b.key);
});
for (final MapEntry<String, int> entry in entries) {
message.writeln(' ${entry.key}: ${entry.value}');
}
print(message);
_printTimer = null;
},
);
}
}
| engine/lib/web_ui/lib/src/engine/profiler.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/profiler.dart",
"repo_id": "engine",
"token_count": 2160
} | 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.
import '../dom.dart';
import '../semantics.dart';
/// Provides accessibility for links.
class Link extends PrimaryRoleManager {
Link(SemanticsObject semanticsObject) : super.withBasics(
PrimaryRole.link,
semanticsObject,
labelRepresentation: LeafLabelRepresentation.domText,
) {
addTappable();
}
@override
DomElement createElement() {
final DomElement element = domDocument.createElement('a');
// TODO(chunhtai): Fill in the real link once the framework sends entire uri.
// https://github.com/flutter/flutter/issues/102535.
element.setAttribute('href', '#');
element.style.display = 'block';
return element;
}
@override
bool focusAsRouteDefault() => focusable?.focusAsRouteDefault() ?? false;
}
| engine/lib/web_ui/lib/src/engine/semantics/link.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/semantics/link.dart",
"repo_id": "engine",
"token_count": 286
} | 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.
import 'dart:ffi';
import 'dart:typed_data';
import 'package:ui/src/engine.dart';
import 'package:ui/src/engine/skwasm/skwasm_impl.dart';
import 'package:ui/ui.dart' as ui;
class SkwasmCanvas implements SceneCanvas {
factory SkwasmCanvas(SkwasmPictureRecorder recorder, ui.Rect cullRect) =>
SkwasmCanvas.fromHandle(withStackScope((StackScope s) =>
pictureRecorderBeginRecording(
recorder.handle, s.convertRectToNative(cullRect))));
SkwasmCanvas.fromHandle(this._handle);
CanvasHandle _handle;
// Note that we do not need to deal with the finalizer registry here, because
// the underlying native skia object is tied directly to the lifetime of the
// associated SkPictureRecorder.
@override
void save() {
canvasSave(_handle);
}
@override
void saveLayer(ui.Rect? bounds, ui.Paint paint) {
paint as SkwasmPaint;
if (bounds != null) {
withStackScope((StackScope s) {
canvasSaveLayer(_handle, s.convertRectToNative(bounds), paint.handle, nullptr);
});
} else {
canvasSaveLayer(_handle, nullptr, paint.handle, nullptr);
}
}
@override
void saveLayerWithFilter(ui.Rect? bounds, ui.Paint paint, ui.ImageFilter imageFilter) {
final SkwasmImageFilter nativeFilter = SkwasmImageFilter.fromUiFilter(imageFilter);
paint as SkwasmPaint;
if (bounds != null) {
withStackScope((StackScope s) {
canvasSaveLayer(_handle, s.convertRectToNative(bounds), paint.handle, nativeFilter.handle);
});
} else {
canvasSaveLayer(_handle, nullptr, paint.handle, nativeFilter.handle);
}
}
@override
void restore() {
canvasRestore(_handle);
}
@override
void restoreToCount(int count) {
canvasRestoreToCount(_handle, count);
}
@override
int getSaveCount() => canvasGetSaveCount(_handle);
@override
void translate(double dx, double dy) => canvasTranslate(_handle, dx, dy);
@override
void scale(double sx, [double? sy]) => canvasScale(_handle, sx, sy ?? sx);
@override
void rotate(double radians) => canvasRotate(_handle, ui.toDegrees(radians));
@override
void skew(double sx, double sy) => canvasSkew(_handle, sx, sy);
@override
void transform(Float64List matrix4) {
withStackScope((StackScope s) {
canvasTransform(_handle, s.convertMatrix44toNative(matrix4));
});
}
@override
void clipRect(ui.Rect rect,
{ui.ClipOp clipOp = ui.ClipOp.intersect, bool doAntiAlias = true}) {
withStackScope((StackScope s) {
canvasClipRect(_handle, s.convertRectToNative(rect), clipOp.index, doAntiAlias);
});
}
@override
void clipRRect(ui.RRect rrect, {bool doAntiAlias = true}) {
withStackScope((StackScope s) {
canvasClipRRect(_handle, s.convertRRectToNative(rrect), doAntiAlias);
});
}
@override
void clipPath(ui.Path path, {bool doAntiAlias = true}) {
path as SkwasmPath;
canvasClipPath(_handle, path.handle, doAntiAlias);
}
@override
void drawColor(ui.Color color, ui.BlendMode blendMode) =>
canvasDrawColor(_handle, color.value, blendMode.index);
@override
void drawLine(ui.Offset p1, ui.Offset p2, ui.Paint paint) {
paint as SkwasmPaint;
canvasDrawLine(_handle, p1.dx, p1.dy, p2.dx, p2.dy, paint.handle);
}
@override
void drawPaint(ui.Paint paint) {
paint as SkwasmPaint;
canvasDrawPaint(_handle, paint.handle);
}
@override
void drawRect(ui.Rect rect, ui.Paint paint) {
paint as SkwasmPaint;
withStackScope((StackScope s) {
canvasDrawRect(
_handle,
s.convertRectToNative(rect),
paint.handle
);
});
}
@override
void drawRRect(ui.RRect rrect, ui.Paint paint) {
paint as SkwasmPaint;
withStackScope((StackScope s) {
canvasDrawRRect(
_handle,
s.convertRRectToNative(rrect),
paint.handle
);
});
}
@override
void drawDRRect(ui.RRect outer, ui.RRect inner, ui.Paint paint) {
paint as SkwasmPaint;
withStackScope((StackScope s) {
canvasDrawDRRect(
_handle,
s.convertRRectToNative(outer),
s.convertRRectToNative(inner),
paint.handle
);
});
}
@override
void drawOval(ui.Rect rect, ui.Paint paint) {
paint as SkwasmPaint;
withStackScope((StackScope s) {
canvasDrawOval(_handle, s.convertRectToNative(rect), paint.handle);
});
}
@override
void drawCircle(ui.Offset center, double radius, ui.Paint paint) {
paint as SkwasmPaint;
canvasDrawCircle(_handle, center.dx, center.dy, radius, paint.handle);
}
@override
void drawArc(ui.Rect rect, double startAngle, double sweepAngle,
bool useCenter, ui.Paint paint) {
paint as SkwasmPaint;
withStackScope((StackScope s) {
canvasDrawArc(
_handle,
s.convertRectToNative(rect),
ui.toDegrees(startAngle),
ui.toDegrees(sweepAngle),
useCenter,
paint.handle
);
});
}
@override
void drawPath(ui.Path path, ui.Paint paint) {
paint as SkwasmPaint;
path as SkwasmPath;
canvasDrawPath(_handle, path.handle, paint.handle);
}
@override
void drawImage(ui.Image image, ui.Offset offset, ui.Paint paint) =>
canvasDrawImage(
_handle,
(image as SkwasmImage).handle,
offset.dx,
offset.dy,
(paint as SkwasmPaint).handle,
paint.filterQuality.index,
);
@override
void drawImageRect(
ui.Image image,
ui.Rect src,
ui.Rect dst,
ui.Paint paint) => withStackScope((StackScope scope) {
final Pointer<Float> sourceRect = scope.convertRectToNative(src);
final Pointer<Float> destRect = scope.convertRectToNative(dst);
canvasDrawImageRect(
_handle,
(image as SkwasmImage).handle,
sourceRect,
destRect,
(paint as SkwasmPaint).handle,
paint.filterQuality.index,
);
});
@override
void drawImageNine(
ui.Image image,
ui.Rect center,
ui.Rect dst,
ui.Paint paint) => withStackScope((StackScope scope) {
final Pointer<Int32> centerRect = scope.convertIRectToNative(center);
final Pointer<Float> destRect = scope.convertRectToNative(dst);
canvasDrawImageNine(
_handle,
(image as SkwasmImage).handle,
centerRect,
destRect,
(paint as SkwasmPaint).handle,
paint.filterQuality.index,
);
});
@override
void drawPicture(ui.Picture picture) {
canvasDrawPicture(_handle, (picture as SkwasmPicture).handle);
}
@override
void drawParagraph(ui.Paragraph paragraph, ui.Offset offset) {
canvasDrawParagraph(
_handle,
(paragraph as SkwasmParagraph).handle,
offset.dx,
offset.dy,
);
}
@override
void drawPoints(
ui.PointMode pointMode,
List<ui.Offset> points,
ui.Paint paint
) => withStackScope((StackScope scope) {
final RawPointArray rawPoints = scope.convertPointArrayToNative(points);
canvasDrawPoints(
_handle,
pointMode.index,
rawPoints,
points.length,
(paint as SkwasmPaint).handle,
);
});
@override
void drawRawPoints(
ui.PointMode pointMode,
Float32List points,
ui.Paint paint
) => withStackScope((StackScope scope) {
final RawPointArray rawPoints = scope.convertDoublesToNative(points);
canvasDrawPoints(
_handle,
pointMode.index,
rawPoints,
points.length ~/ 2,
(paint as SkwasmPaint).handle,
);
});
@override
void drawVertices(
ui.Vertices vertices,
ui.BlendMode blendMode,
ui.Paint paint,
) => canvasDrawVertices(
_handle,
(vertices as SkwasmVertices).handle,
blendMode.index,
(paint as SkwasmPaint).handle,
);
@override
void drawAtlas(
ui.Image atlas,
List<ui.RSTransform> transforms,
List<ui.Rect> rects,
List<ui.Color>? colors,
ui.BlendMode? blendMode,
ui.Rect? cullRect,
ui.Paint paint,
) => withStackScope((StackScope scope) {
final RawRSTransformArray rawTransforms = scope.convertRSTransformsToNative(transforms);
final RawRect rawRects = scope.convertRectsToNative(rects);
final RawColorArray rawColors = colors != null
? scope.convertColorArrayToNative(colors)
: nullptr;
final RawRect rawCullRect = cullRect != null
? scope.convertRectToNative(cullRect)
: nullptr;
canvasDrawAtlas(
_handle,
(atlas as SkwasmImage).handle,
rawTransforms,
rawRects,
rawColors,
transforms.length,
(blendMode ?? ui.BlendMode.src).index,
rawCullRect,
(paint as SkwasmPaint).handle,
);
});
@override
void drawRawAtlas(
ui.Image atlas,
Float32List rstTransforms,
Float32List rects,
Int32List? colors,
ui.BlendMode? blendMode,
ui.Rect? cullRect,
ui.Paint paint,
) => withStackScope((StackScope scope) {
final RawRSTransformArray rawTransforms = scope.convertDoublesToNative(rstTransforms);
final RawRect rawRects = scope.convertDoublesToNative(rects);
final RawColorArray rawColors = colors != null
? scope.convertIntsToUint32Native(colors)
: nullptr;
final RawRect rawCullRect = cullRect != null
? scope.convertRectToNative(cullRect)
: nullptr;
canvasDrawAtlas(
_handle,
(atlas as SkwasmImage).handle,
rawTransforms,
rawRects,
rawColors,
rstTransforms.length ~/ 4,
(blendMode ?? ui.BlendMode.src).index,
rawCullRect,
(paint as SkwasmPaint).handle,
);
});
@override
void drawShadow(
ui.Path path,
ui.Color color,
double elevation,
bool transparentOccluder,
) {
path as SkwasmPath;
canvasDrawShadow(
_handle,
path.handle,
elevation,
EngineFlutterDisplay.instance.devicePixelRatio,
color.value,
transparentOccluder);
}
@override
ui.Rect getDestinationClipBounds() {
return withStackScope((StackScope scope) {
final Pointer<Int32> outRect = scope.allocInt32Array(4);
canvasGetDeviceClipBounds(_handle, outRect);
return scope.convertIRectFromNative(outRect);
});
}
@override
ui.Rect getLocalClipBounds() {
final Float64List transform = getTransform();
final Matrix4 matrix = Matrix4.fromFloat32List(Float32List.fromList(transform));
if (matrix.invert() == 0) {
// non-invertible transforms collapse space to a line or point
return ui.Rect.zero;
}
return matrix.transformRect(getDestinationClipBounds());
}
@override
Float64List getTransform() {
return withStackScope((StackScope scope) {
final Pointer<Float> outMatrix = scope.allocFloatArray(16);
canvasGetTransform(_handle, outMatrix);
return scope.convertMatrix44FromNative(outMatrix);
});
}
}
| engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/canvas.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/canvas.dart",
"repo_id": "engine",
"token_count": 4418
} | 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.
@DefaultAsset('skwasm')
library skwasm_impl;
import 'dart:_wasm';
import 'dart:ffi';
import 'dart:js_interop';
import 'package:ui/src/engine/skwasm/skwasm_impl.dart';
final class RawImage extends Opaque {}
typedef ImageHandle = Pointer<RawImage>;
@Native<ImageHandle Function(
PictureHandle,
Int32,
Int32,
)>(symbol: 'image_createFromPicture', isLeaf: true)
external ImageHandle imageCreateFromPicture(
PictureHandle handle,
int width,
int height,
);
@Native<ImageHandle Function(
SkDataHandle,
Int,
Int,
Int,
Size
)>(symbol: 'image_createFromPixels', isLeaf: true)
external ImageHandle imageCreateFromPixels(
SkDataHandle pixelData,
int width,
int height,
int pixelFormat,
int rowByteCount,
);
// We use a wasm import directly here instead of @Native since this uses an externref
// in the function signature.
ImageHandle imageCreateFromTextureSource(
JSAny frame,
int width,
int height,
SurfaceHandle handle
) => ImageHandle.fromAddress(
imageCreateFromTextureSourceImpl(
externRefForJSAny(frame),
width.toWasmI32(),
height.toWasmI32(),
handle.address.toWasmI32(),
).toIntUnsigned()
);
@pragma('wasm:import', 'skwasm.image_createFromTextureSource')
external WasmI32 imageCreateFromTextureSourceImpl(
WasmExternRef? frame,
WasmI32 width,
WasmI32 height,
WasmI32 surfaceHandle,
);
@Native<Void Function(ImageHandle)>(symbol:'image_ref', isLeaf: true)
external void imageRef(ImageHandle handle);
@Native<Void Function(ImageHandle)>(symbol: 'image_dispose', isLeaf: true)
external void imageDispose(ImageHandle handle);
@Native<Int Function(ImageHandle)>(symbol: 'image_getWidth', isLeaf: true)
external int imageGetWidth(ImageHandle handle);
@Native<Int Function(ImageHandle)>(symbol: 'image_getHeight', isLeaf: true)
external int imageGetHeight(ImageHandle handle);
| engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_image.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_image.dart",
"repo_id": "engine",
"token_count": 664
} | 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.
@DefaultAsset('skwasm')
library skwasm_impl;
import 'dart:ffi';
import 'package:ui/src/engine/skwasm/skwasm_impl.dart';
final class RawStrutStyle extends Opaque {}
typedef StrutStyleHandle = Pointer<RawStrutStyle>;
@Native<StrutStyleHandle Function()>(symbol: 'strutStyle_create', isLeaf: true)
external StrutStyleHandle strutStyleCreate();
@Native<Void Function(StrutStyleHandle)>(symbol: 'strutStyle_dispose', isLeaf: true)
external void strutStyleDispose(StrutStyleHandle handle);
@Native<Void Function(
StrutStyleHandle,
Pointer<SkStringHandle> families,
Int count
)>(symbol: 'strutStyle_setFontFamilies', isLeaf: true)
external void strutStyleSetFontFamilies(
StrutStyleHandle handle,
Pointer<SkStringHandle> families,
int count
);
@Native<Void Function(StrutStyleHandle, Float)>(symbol: 'strutStyle_setFontSize', isLeaf: true)
external void strutStyleSetFontSize(StrutStyleHandle handle, double fontSize);
@Native<Void Function(StrutStyleHandle, Float)>(symbol: 'strutStyle_setHeight', isLeaf: true)
external void strutStyleSetHeight(StrutStyleHandle handle, double height);
@Native<Void Function(StrutStyleHandle, Bool)>(symbol: 'strutStyle_setHalfLeading', isLeaf: true)
external void strutStyleSetHalfLeading(StrutStyleHandle handle, bool height);
@Native<Void Function(StrutStyleHandle, Float)>(symbol: 'strutStyle_setLeading', isLeaf: true)
external void strutStyleSetLeading(StrutStyleHandle handle, double leading);
@Native<Void Function(
StrutStyleHandle,
Int,
Int,
)>(symbol: 'strutStyle_setFontStyle', isLeaf: true)
external void strutStyleSetFontStyle(
StrutStyleHandle handle,
int weight,
int slant,
);
@Native<Void Function(StrutStyleHandle, Bool)>(symbol: 'strutStyle_setForceStrutHeight', isLeaf: true)
external void strutStyleSetForceStrutHeight(StrutStyleHandle handle, bool forceStrutHeight);
| engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/text/raw_strut_style.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/text/raw_strut_style.dart",
"repo_id": "engine",
"token_count": 647
} | 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.
import 'package:web_unicode/web_unicode.dart';
import 'unicode_range.dart';
export 'package:web_unicode/web_unicode.dart' show LineCharProperty;
UnicodePropertyLookup<LineCharProperty> get lineLookup => ensureLineLookupInitialized();
/// Initializes [lineLookup], if it's not already initialized.
///
/// Use this function to trigger the initialization before [lineLookup] is
/// actually used. For example, triggering it before the first application
/// frame is rendered will reduce jank by moving the initialization out of
/// the frame.
UnicodePropertyLookup<LineCharProperty> ensureLineLookupInitialized() {
return _lineLookup ??=
UnicodePropertyLookup<LineCharProperty>.fromPackedData(
packedLineBreakProperties,
singleLineBreakRangesCount,
LineCharProperty.values,
defaultLineCharProperty,
);
}
UnicodePropertyLookup<LineCharProperty>? _lineLookup;
| engine/lib/web_ui/lib/src/engine/text/line_break_properties.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/text/line_break_properties.dart",
"repo_id": "engine",
"token_count": 309
} | 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.
import 'dart:async';
import 'dart:collection';
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:meta/meta.dart';
import 'package:ui/ui.dart' as ui;
import 'browser_detection.dart';
import 'dom.dart';
import 'safe_browser_api.dart';
import 'services.dart';
import 'vector_math.dart';
/// Generic callback signature, used by [_futurize].
typedef Callback<T> = void Function(T result);
/// Signature for a method that receives a [_Callback].
///
/// Return value should be null on success, and a string error message on
/// failure.
typedef Callbacker<T> = String? Function(Callback<T> callback);
/// Converts a method that receives a value-returning callback to a method that
/// returns a Future.
///
/// Return a [String] to cause an [Exception] to be synchronously thrown with
/// that string as a message.
///
/// If the callback is called with null, the future completes with an error.
///
/// Example usage:
///
/// ```dart
/// typedef IntCallback = void Function(int result);
///
/// String _doSomethingAndCallback(IntCallback callback) {
/// Timer(const Duration(seconds: 1), () { callback(1); });
/// }
///
/// Future<int> doSomething() {
/// return futurize(_doSomethingAndCallback);
/// }
/// ```
// Keep this in sync with _futurize in lib/ui/fixtures/ui_test.dart.
Future<T> futurize<T>(Callbacker<T> callbacker) {
final Completer<T> completer = Completer<T>.sync();
// If the callback synchronously throws an error, then synchronously
// rethrow that error instead of adding it to the completer. This
// prevents the Zone from receiving an uncaught exception.
bool isSync = true;
final String? error = callbacker((T? t) {
if (t == null) {
if (isSync) {
throw Exception('operation failed');
} else {
completer.completeError(Exception('operation failed'));
}
} else {
completer.complete(t);
}
});
isSync = false;
if (error != null) {
throw Exception(error);
}
return completer.future;
}
/// Converts [matrix] to CSS transform value.
String matrix4ToCssTransform(Matrix4 matrix) {
return float64ListToCssTransform(matrix.storage);
}
/// Applies a transform to the [element].
///
/// See [float64ListToCssTransform] for details on how the CSS value is chosen.
void setElementTransform(DomElement element, Float32List matrix4) {
element.style
..transformOrigin = '0 0 0'
..transform = float64ListToCssTransform(matrix4);
}
/// Converts [matrix] to CSS transform value.
///
/// To avoid blurry text on some screens this function uses a 2D CSS transform
/// if it detects that [matrix] is a 2D transform. Otherwise, it uses a 3D CSS
/// transform.
///
/// See also:
/// * https://github.com/flutter/flutter/issues/32274
/// * https://bugs.chromium.org/p/chromium/issues/detail?id=1040222
String float64ListToCssTransform(List<double> matrix) {
assert(matrix.length == 16);
final TransformKind transformKind = transformKindOf(matrix);
if (transformKind == TransformKind.transform2d) {
return float64ListToCssTransform2d(matrix);
} else if (transformKind == TransformKind.complex) {
return float64ListToCssTransform3d(matrix);
} else {
assert(transformKind == TransformKind.identity);
return 'none';
}
}
/// The kind of effect a transform matrix performs.
enum TransformKind {
/// No effect.
///
/// We do not want to set any CSS properties in this case.
identity,
/// A transform that contains only 2d scale, rotation, and translation.
///
/// We prefer to use "matrix" instead of "matrix3d" in this case.
transform2d,
/// All other kinds of transforms.
///
/// In this case we will use "matrix3d".
complex,
}
/// Detects the kind of transform the [matrix] performs.
TransformKind transformKindOf(List<double> matrix) {
assert(matrix.length == 16);
final List<double> m = matrix;
// If matrix contains scaling, rotation, z translation or
// perspective transform, it is not considered simple.
final bool isSimple2dTransform = m[15] ==
1.0 && // start reading from the last element to eliminate range checks in subsequent reads.
m[14] == 0.0 && // z translation is NOT simple
// m[13] - y translation is simple
// m[12] - x translation is simple
m[11] == 0.0 &&
m[10] == 1.0 &&
m[9] == 0.0 &&
m[8] == 0.0 &&
m[7] == 0.0 &&
m[6] == 0.0 &&
// m[5] - scale y is simple
// m[4] - 2D rotation is simple
m[3] == 0.0 &&
m[2] == 0.0;
// m[1] - 2D rotation is simple
// m[0] - scale x is simple
if (!isSimple2dTransform) {
return TransformKind.complex;
}
// From this point on we're sure the transform is 2D, but we don't know if
// it's identity or not. To check, we need to look at the remaining elements
// that were not checked above.
final bool isIdentityTransform = m[0] == 1.0 &&
m[1] == 0.0 &&
m[4] == 0.0 &&
m[5] == 1.0 &&
m[12] == 0.0 &&
m[13] == 0.0;
if (isIdentityTransform) {
return TransformKind.identity;
} else {
return TransformKind.transform2d;
}
}
/// Returns `true` is the [matrix] describes an identity transformation.
bool isIdentityFloat32ListTransform(Float32List matrix) {
assert(matrix.length == 16);
return transformKindOf(matrix) == TransformKind.identity;
}
/// Converts [matrix] to CSS transform 2D matrix value.
///
/// The [matrix] must not be a [TransformKind.complex] transform, because CSS
/// `matrix` can only express 2D transforms. [TransformKind.identity] is
/// permitted. However, it is inefficient to construct a matrix for an identity
/// transform. Consider removing the CSS `transform` property from elements
/// that apply identity transform.
String float64ListToCssTransform2d(List<double> matrix) {
assert(transformKindOf(matrix) != TransformKind.complex);
return 'matrix(${matrix[0]},${matrix[1]},${matrix[4]},${matrix[5]},${matrix[12]},${matrix[13]})';
}
/// Converts [matrix] to a 3D CSS transform value.
String float64ListToCssTransform3d(List<double> matrix) {
assert(matrix.length == 16);
final List<double> m = matrix;
if (m[0] == 1.0 &&
m[1] == 0.0 &&
m[2] == 0.0 &&
m[3] == 0.0 &&
m[4] == 0.0 &&
m[5] == 1.0 &&
m[6] == 0.0 &&
m[7] == 0.0 &&
m[8] == 0.0 &&
m[9] == 0.0 &&
m[10] == 1.0 &&
m[11] == 0.0 &&
// 12 can be anything
// 13 can be anything
m[14] == 0.0 &&
m[15] == 1.0) {
final double tx = m[12];
final double ty = m[13];
return 'translate3d(${tx}px, ${ty}px, 0px)';
} else {
return 'matrix3d(${m[0]},${m[1]},${m[2]},${m[3]},${m[4]},${m[5]},${m[6]},${m[7]},${m[8]},${m[9]},${m[10]},${m[11]},${m[12]},${m[13]},${m[14]},${m[15]})';
}
}
final Float32List _tempRectData = Float32List(4);
/// Transforms a [ui.Rect] given the effective [transform].
///
/// The resulting rect is aligned to the pixel grid, i.e. two of
/// its sides are vertical and two are horizontal. In the presence of rotations
/// the rectangle is inflated such that it fits the rotated rectangle.
ui.Rect transformRectWithMatrix(Matrix4 transform, ui.Rect rect) {
_tempRectData[0] = rect.left;
_tempRectData[1] = rect.top;
_tempRectData[2] = rect.right;
_tempRectData[3] = rect.bottom;
transformLTRB(transform, _tempRectData);
return ui.Rect.fromLTRB(
_tempRectData[0],
_tempRectData[1],
_tempRectData[2],
_tempRectData[3],
);
}
/// Temporary storage for intermediate data used by [transformLTRB].
///
/// WARNING: do not use this outside [transformLTRB]. Sharing this variable in
/// other contexts will lead to bugs.
final Float32List _tempPointData = Float32List(16);
final Matrix4 _tempPointMatrix = Matrix4.fromFloat32List(_tempPointData);
/// Transforms a rectangle given the effective [transform].
///
/// This is the same as [transformRect], except that the rect is specified
/// in terms of left, top, right, and bottom edge offsets.
void transformLTRB(Matrix4 transform, Float32List ltrb) {
// Construct a matrix where each row represents a vector pointing at
// one of the four corners of the (left, top, right, bottom) rectangle.
// Using the row-major order allows us to multiply the matrix in-place
// by the transposed current transformation matrix. The vector_math
// library has a convenience function `multiplyTranspose` that performs
// the multiplication without copying. This way we compute the positions
// of all four points in a single matrix-by-matrix multiplication at the
// cost of one `Matrix4` instance and one `Float32List` instance.
//
// The rejected alternative was to use `Vector3` for each point and
// multiply by the current transform. However, that would cost us four
// `Vector3` instances, four `Float32List` instances, and four
// matrix-by-vector multiplications.
//
// `Float32List` initializes the array with zeros, so we do not have to
// fill in every single element.
// Row 0: top-left
_tempPointData[0] = ltrb[0];
_tempPointData[4] = ltrb[1];
_tempPointData[8] = 0;
_tempPointData[12] = 1;
// Row 1: top-right
_tempPointData[1] = ltrb[2];
_tempPointData[5] = ltrb[1];
_tempPointData[9] = 0;
_tempPointData[13] = 1;
// Row 2: bottom-left
_tempPointData[2] = ltrb[0];
_tempPointData[6] = ltrb[3];
_tempPointData[10] = 0;
_tempPointData[14] = 1;
// Row 3: bottom-right
_tempPointData[3] = ltrb[2];
_tempPointData[7] = ltrb[3];
_tempPointData[11] = 0;
_tempPointData[15] = 1;
_tempPointMatrix.multiplyTranspose(transform);
// Handle non-homogenous matrices.
double w = transform[15];
if (w == 0.0) {
w = 1.0;
}
ltrb[0] = math.min(
math.min(math.min(_tempPointData[0], _tempPointData[1]),
_tempPointData[2]),
_tempPointData[3]) /
w;
ltrb[1] = math.min(
math.min(math.min(_tempPointData[4], _tempPointData[5]),
_tempPointData[6]),
_tempPointData[7]) /
w;
ltrb[2] = math.max(
math.max(math.max(_tempPointData[0], _tempPointData[1]),
_tempPointData[2]),
_tempPointData[3]) /
w;
ltrb[3] = math.max(
math.max(math.max(_tempPointData[4], _tempPointData[5]),
_tempPointData[6]),
_tempPointData[7]) /
w;
}
/// Returns true if [rect] contains every point that is also contained by the
/// [other] rect.
///
/// Points on the edges of both rectangles are also considered. For example,
/// this returns true when the two rects are equal to each other.
bool rectContainsOther(ui.Rect rect, ui.Rect other) {
return rect.left <= other.left &&
rect.top <= other.top &&
rect.right >= other.right &&
rect.bottom >= other.bottom;
}
extension CssColor on ui.Color {
/// Converts color to a css compatible attribute value.
String toCssString() {
return colorValueToCssString(value);
}
}
// Converts a color value (as an int) into a CSS-compatible value.
String colorValueToCssString(int value) {
if (value == 0xFF000000) {
return '#000000';
}
if ((0xff000000 & value) == 0xff000000) {
final String hexValue = (value & 0xFFFFFF).toRadixString(16);
final int hexValueLength = hexValue.length;
switch (hexValueLength) {
case 1:
return '#00000$hexValue';
case 2:
return '#0000$hexValue';
case 3:
return '#000$hexValue';
case 4:
return '#00$hexValue';
case 5:
return '#0$hexValue';
default:
return '#$hexValue';
}
} else {
final double alpha = ((value >> 24) & 0xFF) / 255.0;
final StringBuffer sb = StringBuffer();
sb.write('rgba(');
sb.write(((value >> 16) & 0xFF).toString());
sb.write(',');
sb.write(((value >> 8) & 0xFF).toString());
sb.write(',');
sb.write((value & 0xFF).toString());
sb.write(',');
sb.write(alpha.toString());
sb.write(')');
return sb.toString();
}
}
/// Converts color components to a CSS compatible attribute value.
String colorComponentsToCssString(int r, int g, int b, int a) {
if (a == 255) {
return 'rgb($r,$g,$b)';
} else {
final double alphaRatio = a / 255;
return 'rgba($r,$g,$b,${alphaRatio.toStringAsFixed(2)})';
}
}
/// Determines if the (dynamic) exception passed in is a NS_ERROR_FAILURE
/// (from Firefox).
///
/// NS_ERROR_FAILURE (0x80004005) is the most general of all the (Firefox)
/// errors and occurs for all errors for which a more specific error code does
/// not apply. (https://developer.mozilla.org/en-US/docs/Mozilla/Errors)
///
/// Other browsers do not throw this exception.
///
/// In Flutter, this exception happens when we try to perform some operations on
/// a Canvas when the application is rendered in a display:none iframe.
///
/// We need this in [BitmapCanvas] and [RecordingCanvas] to swallow this
/// Firefox exception without interfering with others (potentially useful
/// for the programmer).
bool isNsErrorFailureException(Object e) {
return getJsProperty<dynamic>(e, 'name') == 'NS_ERROR_FAILURE';
}
/// From: https://developer.mozilla.org/en-US/docs/Web/CSS/font-family#Syntax
///
/// Generic font families are a fallback mechanism, a means of preserving some
/// of the style sheet author's intent when none of the specified fonts are
/// available. Generic family names are keywords and must not be quoted. A
/// generic font family should be the last item in the list of font family
/// names.
const Set<String> _genericFontFamilies = <String>{
'serif',
'sans-serif',
'monospace',
'cursive',
'fantasy',
'system-ui',
'math',
'emoji',
'fangsong',
};
/// A default fallback font family in case an unloaded font has been requested.
///
/// -apple-system targets San Francisco in Safari (on Mac OS X and iOS),
/// and it targets Neue Helvetica and Lucida Grande on older versions of
/// Mac OS X. It properly selects between San Francisco Text and
/// San Francisco Display depending on the text’s size.
///
/// For iOS, default to -apple-system, where it should be available, otherwise
/// default to Arial. BlinkMacSystemFont is used for Chrome on iOS.
String get _fallbackFontFamily {
if (isIOS15) {
// Remove the "-apple-system" fallback font because it causes a crash in
// iOS 15.
//
// See github issue: https://github.com/flutter/flutter/issues/90705
// See webkit bug: https://bugs.webkit.org/show_bug.cgi?id=231686
return 'BlinkMacSystemFont';
}
if (isMacOrIOS) {
return '-apple-system, BlinkMacSystemFont';
}
return 'Arial';
}
/// Create a font-family string appropriate for CSS.
///
/// If the given [fontFamily] is a generic font-family, then just return it.
/// Otherwise, wrap the family name in quotes and add a fallback font family.
String? canonicalizeFontFamily(String? fontFamily) {
if (_genericFontFamilies.contains(fontFamily)) {
return fontFamily;
}
if (isMacOrIOS) {
// Unlike Safari, Chrome on iOS does not correctly fallback to cupertino
// on sans-serif.
// Map to San Francisco Text/Display fonts, use -apple-system,
// BlinkMacSystemFont.
if (fontFamily == '.SF Pro Text' ||
fontFamily == '.SF Pro Display' ||
fontFamily == '.SF UI Text' ||
fontFamily == '.SF UI Display') {
return _fallbackFontFamily;
}
}
return '"$fontFamily", $_fallbackFontFamily, sans-serif';
}
/// Converts a list of [Offset] to a typed array of floats.
Float32List offsetListToFloat32List(List<ui.Offset> offsetList) {
final int length = offsetList.length;
final Float32List floatList = Float32List(length * 2);
for (int i = 0, destIndex = 0; i < length; i++, destIndex += 2) {
floatList[destIndex] = offsetList[i].dx;
floatList[destIndex + 1] = offsetList[i].dy;
}
return floatList;
}
/// Apply this function to container elements in the HTML render tree (this is
/// not relevant to semantics tree).
///
/// On WebKit browsers this will apply `z-order: 0` to ensure that clips are
/// applied correctly. Otherwise, the browser will refuse to clip its contents.
///
/// Other possible fixes that were rejected:
///
/// * Use 3D transform instead of 2D: this does not work because it causes text
/// blurriness: https://github.com/flutter/flutter/issues/32274
void applyWebkitClipFix(DomElement? containerElement) {
if (browserEngine == BrowserEngine.webkit) {
containerElement!.style.zIndex = '0';
}
}
/// Roughly the inverse of [ui.Shadow.convertRadiusToSigma].
///
/// This does not inverse [ui.Shadow.convertRadiusToSigma] exactly, because on
/// the Web the difference between sigma and blur radius is different from
/// Flutter mobile.
double convertSigmaToRadius(double sigma) {
return sigma * 2.0;
}
int clampInt(int value, int min, int max) {
assert(min <= max);
if (value < min) {
return min;
} else if (value > max) {
return max;
} else {
return value;
}
}
/// Prints a warning message to the console.
///
/// This function can be overridden in tests. This could be useful, for example,
/// to verify that warnings are printed under certain circumstances.
void Function(String) printWarning = domWindow.console.warn;
/// Converts a 4x4 matrix into a human-readable String.
String matrixString(List<num> matrix) {
final StringBuffer sb = StringBuffer();
for (int i = 0; i < 16; i++) {
sb.write(matrix[i]);
if ((i + 1) % 4 == 0) {
sb.write('\n');
} else {
sb.write(' ');
}
}
return sb.toString();
}
/// Determines if lists [a] and [b] are deep equivalent.
///
/// Returns true if the lists are both null, or if they are both non-null, have
/// the same length, and contain the same elements in the same order. Returns
/// false otherwise.
bool listEquals<T>(List<T>? a, List<T>? b) {
if (a == null) {
return b == null;
}
if (b == null || a.length != b.length) {
return false;
}
for (int index = 0; index < a.length; index += 1) {
if (a[index] != b[index]) {
return false;
}
}
return true;
}
// HTML only supports a single radius, but Flutter ImageFilter supports separate
// horizontal and vertical radii. The best approximation we can provide is to
// average the two radii together for a single compromise value.
String blurSigmasToCssString(double sigmaX, double sigmaY) {
return 'blur(${(sigmaX + sigmaY) * 0.5}px)';
}
/// Extensions to [Map] that make it easier to treat it as a JSON object. The
/// keys are `dynamic` because when JSON is deserialized from method channels
/// it arrives as `Map<dynamic, dynamic>`.
// TODO(yjbanov): use Json typedef when type aliases are shipped
extension JsonExtensions on Map<dynamic, dynamic> {
Map<String, dynamic> readJson(String propertyName) {
return this[propertyName] as Map<String, dynamic>;
}
Map<String, dynamic>? tryJson(String propertyName) {
return this[propertyName] as Map<String, dynamic>?;
}
Map<dynamic, dynamic> readDynamicJson(String propertyName) {
return this[propertyName] as Map<dynamic, dynamic>;
}
Map<dynamic, dynamic>? tryDynamicJson(String propertyName) {
return this[propertyName] as Map<dynamic, dynamic>?;
}
List<dynamic> readList(String propertyName) {
return this[propertyName] as List<dynamic>;
}
List<dynamic>? tryList(String propertyName) {
return this[propertyName] as List<dynamic>?;
}
List<T> castList<T>(String propertyName) {
return (this[propertyName] as List<dynamic>).cast<T>();
}
List<T>? tryCastList<T>(String propertyName) {
final List<dynamic>? rawList = tryList(propertyName);
if (rawList == null) {
return null;
}
return rawList.cast<T>();
}
String readString(String propertyName) {
return this[propertyName] as String;
}
String? tryString(String propertyName) {
return this[propertyName] as String?;
}
bool readBool(String propertyName) {
return this[propertyName] as bool;
}
bool? tryBool(String propertyName) {
return this[propertyName] as bool?;
}
int readInt(String propertyName) {
return (this[propertyName] as num).toInt();
}
int? tryInt(String propertyName) {
return (this[propertyName] as num?)?.toInt();
}
double readDouble(String propertyName) {
return (this[propertyName] as num).toDouble();
}
double? tryDouble(String propertyName) {
return (this[propertyName] as num?)?.toDouble();
}
}
/// Extracts view ID from the [MethodCall.arguments] map.
///
/// Throws if the view ID is not present or if [arguments] is not a map.
int readViewId(Object? arguments) {
final int? viewId = tryViewId(arguments);
if (viewId == null) {
throw Exception('Could not find a `viewId` in the arguments: $arguments');
}
return viewId;
}
/// Extracts view ID from the [MethodCall.arguments] map.
///
/// Returns null if the view ID is not present or if [arguments] is not a map.
int? tryViewId(Object? arguments) {
if (arguments is Map) {
return arguments.tryInt('viewId');
}
return null;
}
/// Prints a list of bytes in hex format.
///
/// Bytes are separated by one space and are padded on the left to always show
/// two digits.
///
/// Example:
///
/// Input: [0, 1, 2, 3]
/// Output: 0x00 0x01 0x02 0x03
String bytesToHexString(List<int> data) {
return data
.map((int byte) => '0x${byte.toRadixString(16).padLeft(2, '0')}')
.join(' ');
}
/// Sets a style property on [element].
///
/// [name] is the name of the property. [value] is the value of the property.
/// If [value] is null, removes the style property.
void setElementStyle(DomElement element, String name, String? value) {
if (value == null) {
element.style.removeProperty(name);
} else {
element.style.setProperty(name, value);
}
}
void setClipPath(DomElement element, String? value) {
if (browserEngine == BrowserEngine.webkit) {
if (value == null) {
element.style.removeProperty('-webkit-clip-path');
} else {
element.style.setProperty('-webkit-clip-path', value);
}
}
if (value == null) {
element.style.removeProperty('clip-path');
} else {
element.style.setProperty('clip-path', value);
}
}
void setThemeColor(ui.Color? color) {
DomHTMLMetaElement? theme =
domDocument.querySelector('#flutterweb-theme') as DomHTMLMetaElement?;
if (color != null) {
if (theme == null) {
theme = createDomHTMLMetaElement()
..id = 'flutterweb-theme'
..name = 'theme-color';
domDocument.head!.append(theme);
}
theme.content = color.toCssString();
} else {
theme?.remove();
}
}
bool? _ellipseFeatureDetected;
/// Draws CanvasElement ellipse with fallback.
void drawEllipse(
DomCanvasRenderingContext2D context,
double centerX,
double centerY,
double radiusX,
double radiusY,
double rotation,
double startAngle,
double endAngle,
bool antiClockwise) {
_ellipseFeatureDetected ??=
getJsProperty<Object?>(context, 'ellipse') != null;
if (_ellipseFeatureDetected!) {
context.ellipse(centerX, centerY, radiusX, radiusY, rotation, startAngle,
endAngle, antiClockwise);
} else {
context.save();
context.translate(centerX, centerY);
context.rotate(rotation);
context.scale(radiusX, radiusY);
context.arc(0, 0, 1, startAngle, endAngle, antiClockwise);
context.restore();
}
}
/// Removes all children of a DOM node.
void removeAllChildren(DomNode node) {
while (node.lastChild != null) {
node.lastChild!.remove();
}
}
/// A helper that finds an element in an iterable that satisfy a predicate, or
/// returns null otherwise.
///
/// This is mostly useful for iterables containing non-null elements.
extension FirstWhereOrNull<T> on Iterable<T> {
T? firstWhereOrNull(bool Function(T element) test) {
for (final T element in this) {
if (test(element)) {
return element;
}
}
return null;
}
}
typedef _LruCacheEntry<K extends Object, V extends Object> = ({K key, V value});
/// Caches up to a [maximumSize] key-value pairs.
///
/// Call [cache] to cache a key-value pair.
class LruCache<K extends Object, V extends Object> {
LruCache(this.maximumSize);
/// The maximum number of key/value pairs this cache can contain.
///
/// To avoid exceeding this limit the cache remove least recently used items.
final int maximumSize;
/// A doubly linked list of the objects in the cache.
///
/// This makes it fast to move a recently used object to the front.
final DoubleLinkedQueue<_LruCacheEntry<K, V>> _itemQueue =
DoubleLinkedQueue<_LruCacheEntry<K, V>>();
@visibleForTesting
DoubleLinkedQueue<_LruCacheEntry<K, V>> get debugItemQueue => _itemQueue;
/// A map of objects to their associated node in the [_itemQueue].
///
/// This makes it fast to find the node in the queue when we need to
/// move the object to the front of the queue.
final Map<K, DoubleLinkedQueueEntry<_LruCacheEntry<K, V>>> _itemMap =
<K, DoubleLinkedQueueEntry<_LruCacheEntry<K, V>>>{};
@visibleForTesting
Map<K, DoubleLinkedQueueEntry<_LruCacheEntry<K, V>>> get itemMap => _itemMap;
/// The number of objects in the cache.
int get length => _itemQueue.length;
/// Whether or not [object] is in the cache.
///
/// This is only for testing.
@visibleForTesting
bool debugContainsValue(V object) {
return _itemMap.containsValue(object);
}
@visibleForTesting
bool debugContainsKey(K key) {
return _itemMap.containsKey(key);
}
/// Returns the cached value associated with the [key].
///
/// If the value is not in the cache, returns null.
V? operator [](K key) {
return _itemMap[key]?.element.value;
}
/// Caches the given [key]/[value] pair in this cache.
///
/// If the pair is not already in the cache, adds it to the cache as the most
/// recently used pair.
///
/// If the [key] is already in the cache, moves it to the most recently used
/// position. If the [value] corresponding to the [key] is different from
/// what's in the cache, updates the value.
void cache(K key, V value) {
final DoubleLinkedQueueEntry<_LruCacheEntry<K, V>>? item = _itemMap[key];
if (item == null) {
// New key-value pair, just add.
_add(key, value);
} else if (item.element.value != value) {
// Key already in the cache, but value is new. Re-add.
item.remove();
_add(key, value);
} else {
// Key-value pair already in the cache, move to most recently used.
item.remove();
_itemQueue.addFirst(item.element);
_itemMap[key] = _itemQueue.firstEntry()!;
}
}
void clear() {
_itemQueue.clear();
_itemMap.clear();
}
void _add(K key, V value) {
_itemQueue.addFirst((key: key, value: value));
_itemMap[key] = _itemQueue.firstEntry()!;
if (_itemQueue.length > maximumSize) {
_removeLeastRecentlyUsedValue();
}
}
void _removeLeastRecentlyUsedValue() {
final bool didRemove = _itemMap.remove(_itemQueue.last.key) != null;
assert(didRemove);
_itemQueue.removeLast();
}
}
/// Returns the VM-compatible string for the tile mode.
String tileModeString(ui.TileMode tileMode) {
switch (tileMode) {
case ui.TileMode.clamp:
return 'clamp';
case ui.TileMode.mirror:
return 'mirror';
case ui.TileMode.repeated:
return 'repeated';
case ui.TileMode.decal:
return 'decal';
}
}
| engine/lib/web_ui/lib/src/engine/util.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/util.dart",
"repo_id": "engine",
"token_count": 9703
} | 268 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.