Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- flutter/engine/src/flutter/common/BUILD.gnAdded+26
- flutter/engine/src/flutter/common/README.mdAdded+5
- flutter/engine/src/flutter/common/config.gniAdded+162
- flutter/engine/src/flutter/common/constants.hAdded+38
- flutter/engine/src/flutter/common/exported_symbols.symAdded+10
- flutter/engine/src/flutter/common/exported_symbols_mac.symAdded+8
- flutter/engine/src/flutter/common/exported_test_symbols.symAdded+14
- flutter/engine/src/flutter/common/exported_test_symbols_mac.symAdded+12
- flutter/engine/src/flutter/common/fuchsia_config.gniAdded+12
- flutter/engine/src/flutter/common/macros.hAdded+20
- flutter/engine/src/flutter/common/settings.ccAdded+19
- flutter/engine/src/flutter/common/settings.hAdded+367
- flutter/engine/src/flutter/common/task_runners.ccAdded+50
- flutter/engine/src/flutter/common/task_runners.hAdded+49
- flutter/engine/src/flutter/display_list/BUILD.gnAdded+316
- flutter/engine/src/flutter/display_list/display_list.ccAdded+481
- flutter/engine/src/flutter/display_list/display_list.hAdded+566
- flutter/engine/src/flutter/display_list/display_list_unittests.ccAdded
- flutter/engine/src/flutter/display_list/dl_attributes.hAdded+111
- flutter/engine/src/flutter/display_list/dl_blend_mode.ccAdded+7
- flutter/engine/src/flutter/display_list/dl_blend_mode.hAdded+16
- flutter/engine/src/flutter/display_list/dl_builder.ccAdded+2119
- flutter/engine/src/flutter/display_list/dl_builder.hAdded+858
- flutter/engine/src/flutter/display_list/dl_canvas.ccAdded+24
- flutter/engine/src/flutter/display_list/dl_canvas.hAdded+248
- flutter/engine/src/flutter/display_list/dl_color.ccAdded+75
- flutter/engine/src/flutter/display_list/dl_color.hAdded+198
- flutter/engine/src/flutter/display_list/dl_color_unittests.ccAdded+301
- flutter/engine/src/flutter/display_list/dl_op_flags.ccAdded+11
- flutter/engine/src/flutter/display_list/dl_op_flags.hAdded+421
- flutter/engine/src/flutter/display_list/dl_op_receiver.ccAdded+11
- flutter/engine/src/flutter/display_list/dl_op_receiver.hAdded+373
- flutter/engine/src/flutter/display_list/dl_op_records.ccAdded+11
- flutter/engine/src/flutter/display_list/dl_op_records.hAdded+1075
- flutter/engine/src/flutter/display_list/dl_paint.ccAdded+40
- flutter/engine/src/flutter/display_list/dl_paint.hAdded+225
- flutter/engine/src/flutter/display_list/dl_paint_unittests.ccAdded+199
- flutter/engine/src/flutter/display_list/dl_sampling_options.hAdded+26
- flutter/engine/src/flutter/display_list/dl_storage.ccAdded+62
- flutter/engine/src/flutter/display_list/dl_storage.hAdded+60
- flutter/engine/src/flutter/display_list/dl_storage_unittests.ccAdded+47
- flutter/engine/src/flutter/display_list/dl_tile_mode.hAdded+33
- flutter/engine/src/flutter/display_list/dl_types.ccAdded+11
- flutter/engine/src/flutter/display_list/dl_types.hAdded+28
- flutter/engine/src/flutter/display_list/dl_vertices.ccAdded+322
- flutter/engine/src/flutter/display_list/dl_vertices.hAdded+288
- flutter/engine/src/flutter/display_list/dl_vertices_unittests.ccAdded+983
- flutter/engine/src/flutter/docs/Crashes.mdAdded+172
- flutter/engine/src/flutter/docs/Custom-Flutter-Engine-Embedders.mdAdded+22
- flutter/engine/src/flutter/docs/Custom-Flutter-Engine-Embedding-in-AOT-Mode.mdAdded+132
1234567891011121314151617181920212223242526# Copyright 2013 The Flutter 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("config.gni")
config("flutter_config") { defines = feature_defines_list}
source_set("common") { sources = [ "macros.h", "settings.cc", "settings.h", "task_runners.cc", "task_runners.h", ]
deps = [ "//flutter/fml" ]
public_configs = [ ":flutter_config", "//flutter:config", ]}12345Flutter Common==============
The bottom of the dependency graph for Flutter. Useful for static constants.Please don't put too much in here.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162# Copyright 2013 The Flutter Authors. All rights reserved.# Use of this source code is governed by a BSD-style license that can be# found in the LICENSE file.
if (is_android) { import("//build/config/android/config.gni")}
if (target_cpu == "arm" || target_cpu == "arm64") { import("//build/config/arm.gni")}
declare_args() { # The runtime mode ("debug", "profile", "release", or "jit_release") flutter_runtime_mode = "debug"
# Whether to use a prebuilt Dart SDK instead of building one. flutter_prebuilt_dart_sdk = false
# Whether to build host-side development artifacts. flutter_build_engine_artifacts = true
# Whether to include backtrace support. enable_backtrace = true
# Whether binary size optimizations with the assumption that Impeller is the # only supported rendering engine are enabled. # # See [go/slimpeller-dashboard](https://github.com/orgs/flutter/projects/21) # for details. slimpeller = false}
# feature_defines_list ---------------------------------------------------------
feature_defines_list = [ "FLUTTER_RUNTIME_MODE_DEBUG=1", "FLUTTER_RUNTIME_MODE_PROFILE=2", "FLUTTER_RUNTIME_MODE_RELEASE=3", "FLUTTER_RUNTIME_MODE_JIT_RELEASE=4", "DART_LEGACY_API=[[deprecated]]",]
if (flutter_runtime_mode == "debug") { feature_defines_list += [ "FLUTTER_RUNTIME_MODE=1", "FLUTTER_JIT_RUNTIME=1", ]} else if (flutter_runtime_mode == "profile") { feature_defines_list += [ "FLUTTER_RUNTIME_MODE=2" ]} else if (flutter_runtime_mode == "release") { feature_defines_list += [ "FLUTTER_RUNTIME_MODE=3", "FLUTTER_RELEASE=1", ]} else if (flutter_runtime_mode == "jit_release") { feature_defines_list += [ "FLUTTER_RUNTIME_MODE=4", "FLUTTER_RELEASE=1", "FLUTTER_JIT_RUNTIME=1", ]} else { feature_defines_list += [ "FLUTTER_RUNTIME_MODE=0" ]}
if (slimpeller) { feature_defines_list += [ "SLIMPELLER=1" ]}
if (is_ios || is_mac) { flutter_cflags_objc = [ "-Werror=overriding-method-mismatch", "-Werror=undeclared-selector", "-fobjc-arc", ] if (is_mac) { flutter_cflags_objc += [ "-fapplication-extension" ] }
flutter_cflags_objcc = flutter_cflags_objc}
# A combo of host os name and cpu is used in several locations to# generate the names of the archived artifacts.platform_name = host_osif (platform_name == "mac") { platform_name = "darwin"} else if (platform_name == "win") { platform_name = "windows"}
full_platform_name = "$platform_name-$host_cpu"
target_platform_name = target_osif (target_platform_name == "mac") { platform_target_name = "darwin"} else if (target_platform_name == "win") { target_platform_name = "windows"}
full_target_platform_name = "$target_platform_name-$target_cpu"
# Prebuilt Dart SDK location_target_os_name = target_osif (_target_os_name == "mac") { _target_os_name = "macos"} else if (_target_os_name == "win") { _target_os_name = "windows"}
_host_os_name = host_osif (_host_os_name == "mac") { _host_os_name = "macos"} else if (_host_os_name == "win") { _host_os_name = "windows"}
# When building 32-bit Android development artifacts for Windows host (like# gen_snapshot), the host_cpu is set to x86. However, the correct prebuilt# Dart SDK to use during this build is still the 64-bit one._host_cpu = host_cpuif (host_os == "win" && host_cpu == "x86") { _host_cpu = "x64"}
_target_prebuilt_config = "$_target_os_name-$target_cpu"_host_prebuilt_config = "$_host_os_name-$_host_cpu"
target_prebuilts_path = "//flutter/prebuilts/$_target_prebuilt_config"host_prebuilts_path = "//flutter/prebuilts/$_host_prebuilt_config"
if (flutter_prebuilt_dart_sdk) { target_prebuilt_dart_sdk = "$target_prebuilts_path/dart-sdk" host_prebuilt_dart_sdk = "$host_prebuilts_path/dart-sdk"
# There is no prebuilt Dart SDK targeting Fuchsia, iOS, and Android, but we # also don't need one, so even when the build is targeting one of these # platforms, we use the prebuilt Dart SDK for the host. if (current_toolchain == host_toolchain || target_os == "android" || target_os == "fuchsia" || target_os == "ios" || target_os == "wasm") { prebuilt_dart_sdk = host_prebuilt_dart_sdk prebuilt_dart_sdk_config = _host_prebuilt_config } else { prebuilt_dart_sdk = target_prebuilt_dart_sdk prebuilt_dart_sdk_config = _target_prebuilt_config }}
# Flutter SDK artifacts should only be built when either doing host builds, or# for cross-compiled desktop targets.## !is_android is necessary because of the way that Android 32-bit arm# gen_snapshot is built on Windows using the host toolchain, since we have no# 32-bit arm toolchain for Windows. See comments in //flutter/tools/gn for# details.## TODO: We can't build the engine artifacts for arm (32-bit) right now;# see https://github.com/flutter/flutter/issues/74322.build_engine_artifacts = flutter_build_engine_artifacts && !is_android && (current_toolchain == host_toolchain || (is_linux && !is_chromeos && current_cpu != "arm") || is_mac || is_win)1234567891011121314151617181920212223242526272829303132333435363738// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#ifndef FLUTTER_COMMON_CONSTANTS_H_#define FLUTTER_COMMON_CONSTANTS_H_
namespace flutter {constexpr double kMegaByteSizeInBytes = (1 << 20);
// The ID for the implicit view if the implicit view is enabled.//// The implicit view is a compatibility mechanism to help the transition from// the older single-view APIs to the newer multi-view APIs. The two sets of APIs// use different models for view management. The implicit view mechanism allows// single-view APIs to operate a special view as if other views don't exist.//// In the regular multi-view model, all views should be created by// `Shell::AddView` before being used, and removed by `Shell::RemoveView` to// signify that they are gone. If a view is added or removed, the framework// (`PlatformDispatcher`) will be notified. New view IDs are always unique,// never reused. Operating a non-existing view is an error.//// The implicit view is another special view in addition to the "regular views"// as above. The shell starts up having the implicit view, which has a fixed// view ID of `kFlutterImplicitViewId` and is available throughout the lifetime// of the shell. `Shell::AddView` or `RemoveView` must not be called for this// view. Even when the window that shows the view is closed, the framework is// unaware and might continue rendering into or operating this view.//// The single-view APIs, which are APIs that do not specify view IDs, operate// the implicit view. The multi-view APIs can operate all views, including the// implicit view if the target ID is `kFlutterImplicitViewId`, unless specified// otherwise.constexpr int64_t kFlutterImplicitViewId = 0;} // namespace flutter
#endif // FLUTTER_COMMON_CONSTANTS_H_12345678910# These symbols are looked up from within the executable at runtime and must# be exported in the dynamic symbol table.{ kDartVmSnapshotData; kDartVmSnapshotInstructions; kDartIsolateSnapshotData; kDartIsolateSnapshotInstructions; InternalFlutterGpu*; kInternalFlutterGpu*;};12345678# These symbols are looked up from within the executable at runtime and must# be exported in the dynamic symbol table._kDartVmSnapshotData_kDartVmSnapshotInstructions_kDartIsolateSnapshotData_kDartIsolateSnapshotInstructions_InternalFlutterGpu*_kInternalFlutterGpu*1234567891011121314# These symbols are looked up from within the executable at runtime and must# be exported in the dynamic symbol table.{ kDartVmSnapshotData; kDartVmSnapshotInstructions; kDartIsolateSnapshotData; kDartIsolateSnapshotInstructions; InternalFlutterGpu*; kInternalFlutterGpu*; Spawn; LoadLibraryFromKernel; LookupEntryPoint; ForceShutdownIsolate;};123456789101112# These symbols are looked up from within the executable at runtime and must# be exported in the dynamic symbol table._kDartVmSnapshotData_kDartVmSnapshotInstructions_kDartIsolateSnapshotData_kDartIsolateSnapshotInstructions_InternalFlutterGpu*_kInternalFlutterGpu*_Spawn_LoadLibraryFromKernel_LookupEntryPoint_ForceShutdownIsolate123456789101112# Copyright 2013 The Flutter 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("config.gni")
if (is_fuchsia) { dart_tools_root = "//flutter/tools/fuchsia/dart" fuchsia_base = "//flutter/shell/platform/fuchsia" flutter_runner_base = "$fuchsia_base/flutter/" dart_runner_base = "$fuchsia_base/dart_runner/"}1234567891011121314151617181920// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#ifndef FLUTTER_COMMON_MACROS_H_#define FLUTTER_COMMON_MACROS_H_
#if SLIMPELLER
#define ONLY_IN_SLIMPELLER(code) code#define NOT_SLIMPELLER(code)
#else // SLIMPELLER
#define ONLY_IN_SLIMPELLER(code)#define NOT_SLIMPELLER(code) code
#endif // SLIMPELLER
#endif // FLUTTER_COMMON_MACROS_H_12345678910111213141516171819// Copyright 2013 The Flutter Authors. 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/settings.h"
#include <sstream>
namespace flutter {
constexpr FrameTiming::Phase FrameTiming::kPhases[FrameTiming::kCount];
Settings::Settings() = default;
Settings::Settings(const Settings& other) = default;
Settings::~Settings() = default;
} // namespace flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#ifndef FLUTTER_COMMON_SETTINGS_H_#define FLUTTER_COMMON_SETTINGS_H_
#include <fcntl.h>
#include <cstdint>#include <memory>#include <optional>#include <string>#include <vector>
#include "flutter/fml/build_config.h"#include "flutter/fml/closure.h"#include "flutter/fml/mapping.h"#include "flutter/fml/time/time_point.h"#include "flutter/fml/unique_fd.h"
namespace flutter {
class FrameTiming { public: enum Phase { kVsyncStart, kBuildStart, kBuildFinish, kRasterStart, kRasterFinish, kRasterFinishWallTime, kCount };
static constexpr Phase kPhases[kCount] = { kVsyncStart, kBuildStart, kBuildFinish, kRasterStart, kRasterFinish, kRasterFinishWallTime};
static constexpr int kStatisticsCount = kCount + 5;
fml::TimePoint Get(Phase phase) const { return data_[phase]; } fml::TimePoint Set(Phase phase, fml::TimePoint value) { return data_[phase] = value; }
uint64_t GetFrameNumber() const { return frame_number_; } void SetFrameNumber(uint64_t frame_number) { frame_number_ = frame_number; } uint64_t GetLayerCacheCount() const { return layer_cache_count_; } uint64_t GetLayerCacheBytes() const { return layer_cache_bytes_; } uint64_t GetPictureCacheCount() const { return picture_cache_count_; } uint64_t GetPictureCacheBytes() const { return picture_cache_bytes_; } void SetRasterCacheStatistics(size_t layer_cache_count, size_t layer_cache_bytes, size_t picture_cache_count, size_t picture_cache_bytes) { layer_cache_count_ = layer_cache_count; layer_cache_bytes_ = layer_cache_bytes; picture_cache_count_ = picture_cache_count; picture_cache_bytes_ = picture_cache_bytes; }
private: fml::TimePoint data_[kCount]; uint64_t frame_number_; size_t layer_cache_count_; size_t layer_cache_bytes_; size_t picture_cache_count_; size_t picture_cache_bytes_;};
using TaskObserverAdd = std::function<void(intptr_t /* key */, fml::closure /* callback */)>;using TaskObserverRemove = std::function<void(intptr_t /* key */)>;using UnhandledExceptionCallback = std::function<bool(const std::string& /* error */, const std::string& /* stack trace */)>;using LogMessageCallback = std::function<void(const std::string& /* tag */, const std::string& /* message */)>;
// TODO(26783): Deprecate all the "path" struct members in favor of the// callback that generates the mapping from these paths.using MappingCallback = std::function<std::unique_ptr<fml::Mapping>(void)>;using Mappings = std::vector<std::unique_ptr<const fml::Mapping>>;using MappingsCallback = std::function<Mappings(void)>;
using FrameRasterizedCallback = std::function<void(const FrameTiming&)>;
class DartIsolate;
// TODO(https://github.com/flutter/flutter/issues/138750): Re-order fields to// reduce padding.// NOLINTNEXTLINE(clang-analyzer-optin.performance.Padding)struct Settings { Settings();
Settings(const Settings& other);
~Settings();
/// Determines if attempts at grabbing the Surface's SurfaceData can be /// attempted. static constexpr bool kSurfaceDataAccessible =#ifdef _NDEBUG false;#else true;#endif
// VM settings std::string vm_snapshot_data_path; // deprecated MappingCallback vm_snapshot_data; std::string vm_snapshot_instr_path; // deprecated MappingCallback vm_snapshot_instr;
std::string isolate_snapshot_data_path; // deprecated MappingCallback isolate_snapshot_data; std::string isolate_snapshot_instr_path; // deprecated MappingCallback isolate_snapshot_instr;
std::string route;
// Returns the Mapping to a kernel buffer which contains sources for dart:* // libraries. MappingCallback dart_library_sources_kernel;
// Path to a library containing the application's compiled Dart code. // This is a vector so that the embedder can provide fallback paths in // case the primary path to the library can not be loaded. std::vector<std::string> application_library_path;
// Path to a library containing compiled Dart code usable for launching // the VM service isolate. std::vector<std::string> vmservice_snapshot_library_path;
std::string application_kernel_asset; // deprecated std::string application_kernel_list_asset; // deprecated MappingsCallback application_kernels;
std::string temp_directory_path; std::vector<std::string> dart_flags; // Isolate settings bool enable_checked_mode = false; bool start_paused = false; bool trace_skia = false; std::vector<std::string> trace_allowlist; std::optional<std::vector<std::string>> trace_skia_allowlist; bool trace_startup = false; bool trace_systrace = false; std::string trace_to_file; bool enable_timeline_event_handler = true; bool dump_skp_on_shader_compilation = false; bool cache_sksl = false; bool purge_persistent_cache = false; bool endless_trace_buffer = false; bool enable_dart_profiling = false; bool disable_dart_asserts = false; bool enable_serial_gc = false;
// Whether embedder only allows secure connections. bool may_insecurely_connect_to_all_domains = true; // JSON-formatted domain network policy. std::string domain_network_policy;
// Used as the script URI in debug messages. Does not affect how the Dart code // is executed. std::string advisory_script_uri = "main.dart"; // Used as the script entrypoint in debug messages. Does not affect how the // Dart code is executed. std::string advisory_script_entrypoint = "main";
// The executable path associated with this process. This is returned by // Platform.executable from dart:io. If unknown, defaults to "Flutter". std::string executable_name = "Flutter";
// VM Service settings
// Whether the Dart VM service should be enabled. bool enable_vm_service = false;
// Whether to publish the VM Service URL over mDNS. // On iOS 14 this prompts a local network permission dialog, // which cannot be accepted or dismissed in a CI environment. bool enable_vm_service_publication = true;
// The IP address to which the Dart VM service is bound. std::string vm_service_host;
// The port to which the Dart VM service is bound. When set to `0`, a free // port will be automatically selected by the OS. A message is logged on the // target indicating the URL at which the VM service can be accessed. uint32_t vm_service_port = 0;
// Determines whether an authentication code is required to communicate with // the VM service. bool disable_service_auth_codes = true;
// Determine whether the vmservice should fallback to automatic port selection // after failing to bind to a specified port. bool enable_service_port_fallback = false;
// Font settings bool use_test_fonts = false;
bool use_asset_fonts = true;
// Indicates whether the embedding started a prefetch of the default font // manager before creating the engine. bool prefetched_default_font_manager = false;
// Enable the rendering of colors outside of the sRGB gamut. bool enable_wide_gamut = false;
// Enable the Impeller renderer on supported platforms. Ignored if Impeller is // not supported on the platform.#if FML_OS_ANDROID || FML_OS_IOS || FML_OS_IOS_SIMULATOR // On iOS devices, Impeller is the default with no opt-out and this field is // const.#if FML_OS_IOS || FML_OS_IOS_SIMULATOR static constexpr const#endif // FML_OS_IOS && !FML_OS_IOS_SIMULATOR bool enable_impeller = true; // NOLINT(readability-identifier-naming)#else bool enable_impeller = false;#endif
// Enable android surface control swapchains where supported. bool enable_surface_control = false;
// Whether to lazily initialize impeller PSO state. bool impeller_enable_lazy_shader_mode = false;
// An experimental mode that antialiases lines. bool impeller_antialiased_lines = false;
// Log a warning during shell initialization if Impeller is not enabled. bool warn_on_impeller_opt_out = false;
// Requests a specific rendering backend. std::optional<std::string> requested_rendering_backend;
// Enable Vulkan validation on backends that support it. The validation layers // must be available to the application. bool enable_vulkan_validation = false;
// Enable GPU tracing in GLES backends. // Some devices claim to support the required APIs but crash on their usage. bool enable_opengl_gpu_tracing = false;
// Enable GPU tracing in Vulkan backends. bool enable_vulkan_gpu_tracing = false;
// Data set by platform-specific embedders for use in font initialization. uint32_t font_initialization_data = 0;
// All shells in the process share the same VM. The last shell to shutdown // should typically shut down the VM as well. However, applications depend on // the behavior of "warming-up" the VM by creating a shell that does not do // anything. This used to work earlier when the VM could not be shut down (and // hence never was). Shutting down the VM now breaks such assumptions in // existing embedders. To keep this behavior consistent and allow existing // embedders the chance to migrate, this flag defaults to true. Any shell // launched with this flag set to true will leak the VM in the process. There // is no way to shut down the VM once such a shell has been started. All // shells in the platform (via their embedding APIs) should cooperate to make // sure this flag is never set if they want the VM to shutdown and free all // associated resources. // It can be customized by application, more detail: // https://github.com/flutter/flutter/issues/95903 bool leak_vm = true;
// Engine settings TaskObserverAdd task_observer_add; TaskObserverRemove task_observer_remove; // The main isolate is current when this callback is made. This is a good spot // to perform native Dart bindings for libraries not built in. std::function<void(const DartIsolate&)> root_isolate_create_callback; // TODO(68738): Update isolate callbacks in settings to accept an additional // DartIsolate parameter. fml::closure isolate_create_callback; // The isolate is not current and may have already been destroyed when this // call is made. fml::closure root_isolate_shutdown_callback; fml::closure isolate_shutdown_callback; // A callback made in the isolate scope of the service isolate when it is // launched. Care must be taken to ensure that callers are assigning callbacks // to the settings object used to launch the VM. If an existing VM is used to // launch an isolate using these settings, the callback will be ignored as the // service isolate has already been launched. Also, this callback will only be // made in the modes in which the service isolate is eligible for launch // (debug and profile). fml::closure service_isolate_create_callback; // The callback made on the UI thread in an isolate scope when the engine // detects that the framework is idle. The VM also uses this time to perform // tasks suitable when idling. Due to this, embedders are still advised to be // as fast as possible in returning from this callback. Long running // operations in this callback do have the capability of introducing jank. std::function<void(int64_t)> idle_notification_callback; // A callback given to the embedder to react to unhandled exceptions in the // running Flutter application. This callback is made on an internal engine // managed thread and embedders must re-thread as necessary. Performing // blocking calls in this callback will cause applications to jank. UnhandledExceptionCallback unhandled_exception_callback; // A callback given to the embedder to log print messages from the running // Flutter application. This callback is made on an internal engine managed // thread and embedders must re-thread if necessary. Performing blocking // calls in this callback will cause applications to jank. LogMessageCallback log_message_callback; bool enable_software_rendering = false; bool skia_deterministic_rendering_on_cpu = false; bool verbose_logging = false; std::string log_tag = "flutter";
// The icu_initialization_required setting does not have a corresponding // switch because it is intended to be decided during build time, not runtime. // Some companies apply source modification here because their build system // brings its own ICU data files. bool icu_initialization_required = true; std::string icu_data_path; MappingCallback icu_mapper;
// Assets settings fml::UniqueFD::element_type assets_dir = fml::UniqueFD::traits_type::InvalidValue(); std::string assets_path;
// Callback to handle the timings of a rasterized frame. This is called as // soon as a frame is rasterized. FrameRasterizedCallback frame_rasterized_callback;
// This data will be available to the isolate immediately on launch via the // PlatformDispatcher.getPersistentIsolateData callback. This is meant for // information that the isolate cannot request asynchronously (platform // messages can be used for that purpose). This data is held for the lifetime // of the shell and is available on isolate restarts in the shell instance. // Due to this, the buffer must be as small as possible. std::shared_ptr<const fml::Mapping> persistent_isolate_data;
/// Max size of old gen heap size in MB, or 0 for unlimited, -1 for default /// value. /// /// See also: /// https://github.com/dart-lang/sdk/blob/ca64509108b3e7219c50d6c52877c85ab6a35ff2/runtime/vm/flag_list.h#L150 int64_t old_gen_heap_size = -1;
// Max bytes threshold of resource cache, or 0 for unlimited. size_t resource_cache_max_bytes_threshold = 0;
/// Enable embedder api on the embedder. /// /// This is currently only used by iOS. bool enable_embedder_api = false;
/// Enable support for isolates that run on the platform thread. /// /// This is used by the runOnPlatformThread API. bool enable_platform_isolates = false;
// If true, the UI thread is the platform thread on supported // platforms. bool merged_platform_ui_thread = true;};
} // namespace flutter
#endif // FLUTTER_COMMON_SETTINGS_H_1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950// Copyright 2013 The Flutter Authors. 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 <utility>
namespace flutter {
TaskRunners::TaskRunners(std::string label, fml::RefPtr<fml::TaskRunner> platform, fml::RefPtr<fml::TaskRunner> raster, fml::RefPtr<fml::TaskRunner> ui, fml::RefPtr<fml::TaskRunner> io) : label_(std::move(label)), platform_(std::move(platform)), raster_(std::move(raster)), ui_(std::move(ui)), io_(std::move(io)) {}
TaskRunners::TaskRunners(const TaskRunners& other) = default;
TaskRunners::~TaskRunners() = default;
const std::string& TaskRunners::GetLabel() const { return label_;}
fml::RefPtr<fml::TaskRunner> TaskRunners::GetPlatformTaskRunner() const { return platform_;}
fml::RefPtr<fml::TaskRunner> TaskRunners::GetUITaskRunner() const { return ui_;}
fml::RefPtr<fml::TaskRunner> TaskRunners::GetIOTaskRunner() const { return io_;}
fml::RefPtr<fml::TaskRunner> TaskRunners::GetRasterTaskRunner() const { return raster_;}
bool TaskRunners::IsValid() const { return platform_ && raster_ && ui_ && io_;}
} // namespace flutter12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#ifndef FLUTTER_COMMON_TASK_RUNNERS_H_#define FLUTTER_COMMON_TASK_RUNNERS_H_
#include <string>
#include "flutter/fml/macros.h"#include "flutter/fml/task_runner.h"
namespace flutter {
class TaskRunners { public: TaskRunners(std::string label, fml::RefPtr<fml::TaskRunner> platform, fml::RefPtr<fml::TaskRunner> raster, fml::RefPtr<fml::TaskRunner> ui, fml::RefPtr<fml::TaskRunner> io);
TaskRunners(const TaskRunners& other);
~TaskRunners();
const std::string& GetLabel() const;
fml::RefPtr<fml::TaskRunner> GetPlatformTaskRunner() const;
fml::RefPtr<fml::TaskRunner> GetUITaskRunner() const;
fml::RefPtr<fml::TaskRunner> GetIOTaskRunner() const;
fml::RefPtr<fml::TaskRunner> GetRasterTaskRunner() const;
bool IsValid() const;
private: const std::string label_; fml::RefPtr<fml::TaskRunner> platform_; fml::RefPtr<fml::TaskRunner> raster_; fml::RefPtr<fml::TaskRunner> ui_; fml::RefPtr<fml::TaskRunner> io_;};
} // namespace flutter
#endif // FLUTTER_COMMON_TASK_RUNNERS_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316# Copyright 2013 The Flutter Authors. All rights reserved.# Use of this source code is governed by a BSD-style license that can be# found in the LICENSE file.
import("//flutter/common/config.gni")import("//flutter/impeller/tools/impeller.gni")import("//flutter/testing/testing.gni")
if (is_fuchsia) { import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni")}
config("display_list_config") { defines = []}
source_set("display_list") { sources = [ "benchmarking/dl_complexity.cc", "benchmarking/dl_complexity.h", "benchmarking/dl_complexity_gl.cc", "benchmarking/dl_complexity_gl.h", "benchmarking/dl_complexity_metal.cc", "benchmarking/dl_complexity_metal.h", "display_list.cc", "display_list.h", "dl_attributes.h", "dl_blend_mode.cc", "dl_blend_mode.h", "dl_builder.cc", "dl_builder.h", "dl_canvas.cc", "dl_canvas.h", "dl_color.cc", "dl_color.h", "dl_op_flags.cc", "dl_op_flags.h", "dl_op_receiver.cc", "dl_op_receiver.h", "dl_op_records.cc", "dl_op_records.h", "dl_paint.cc", "dl_paint.h", "dl_sampling_options.h", "dl_storage.cc", "dl_storage.h", "dl_tile_mode.h", "dl_types.cc", "dl_types.h", "dl_vertices.cc", "dl_vertices.h", "effects/color_filters/dl_blend_color_filter.cc", "effects/color_filters/dl_blend_color_filter.h", "effects/color_filters/dl_linear_to_srgb_gamma_color_filter.cc", "effects/color_filters/dl_linear_to_srgb_gamma_color_filter.h", "effects/color_filters/dl_matrix_color_filter.cc", "effects/color_filters/dl_matrix_color_filter.h", "effects/color_filters/dl_srgb_to_linear_gamma_color_filter.cc", "effects/color_filters/dl_srgb_to_linear_gamma_color_filter.h", "effects/color_sources/dl_conical_gradient_color_source.cc", "effects/color_sources/dl_conical_gradient_color_source.h", "effects/color_sources/dl_image_color_source.cc", "effects/color_sources/dl_image_color_source.h", "effects/color_sources/dl_linear_gradient_color_source.cc", "effects/color_sources/dl_linear_gradient_color_source.h", "effects/color_sources/dl_radial_gradient_color_source.cc", "effects/color_sources/dl_radial_gradient_color_source.h", "effects/color_sources/dl_runtime_effect_color_source.cc", "effects/color_sources/dl_runtime_effect_color_source.h", "effects/color_sources/dl_sweep_gradient_color_source.cc", "effects/color_sources/dl_sweep_gradient_color_source.h", "effects/dl_color_filter.cc", "effects/dl_color_filter.h", "effects/dl_color_filters.h", "effects/dl_color_source.cc", "effects/dl_color_source.h", "effects/dl_color_sources.h", "effects/dl_image_filter.cc", "effects/dl_image_filter.h", "effects/dl_image_filters.h", "effects/dl_mask_filter.cc", "effects/dl_mask_filter.h", "effects/dl_runtime_effect.cc", "effects/dl_runtime_effect.h", "effects/image_filters/dl_blur_image_filter.cc", "effects/image_filters/dl_blur_image_filter.h", "effects/image_filters/dl_color_filter_image_filter.cc", "effects/image_filters/dl_color_filter_image_filter.h", "effects/image_filters/dl_compose_image_filter.cc", "effects/image_filters/dl_compose_image_filter.h", "effects/image_filters/dl_dilate_image_filter.cc", "effects/image_filters/dl_dilate_image_filter.h", "effects/image_filters/dl_erode_image_filter.cc", "effects/image_filters/dl_erode_image_filter.h", "effects/image_filters/dl_local_matrix_image_filter.cc", "effects/image_filters/dl_local_matrix_image_filter.h", "effects/image_filters/dl_matrix_image_filter.cc", "effects/image_filters/dl_matrix_image_filter.h", "effects/image_filters/dl_runtime_effect_image_filter.cc", "effects/image_filters/dl_runtime_effect_image_filter.h", "geometry/dl_geometry_types.h", "geometry/dl_path.cc", "geometry/dl_path.h", "geometry/dl_region.cc", "geometry/dl_region.h", "geometry/dl_rtree.cc", "geometry/dl_rtree.h", "image/dl_image.cc", "image/dl_image.h", "image/dl_image_skia.cc", "image/dl_image_skia.h", "skia/dl_sk_canvas.cc", "skia/dl_sk_canvas.h", "skia/dl_sk_conversions.cc", "skia/dl_sk_conversions.h", "skia/dl_sk_dispatcher.cc", "skia/dl_sk_dispatcher.h", "skia/dl_sk_paint_dispatcher.cc", "skia/dl_sk_paint_dispatcher.h", "skia/dl_sk_types.h", "utils/dl_accumulation_rect.cc", "utils/dl_accumulation_rect.h", "utils/dl_matrix_clip_tracker.cc", "utils/dl_matrix_clip_tracker.h", "utils/dl_receiver_utils.cc", "utils/dl_receiver_utils.h", ]
public_configs = [ ":display_list_config" ]
public_deps = [ "//flutter/fml", "//flutter/impeller/runtime_stage", "//flutter/impeller/typographer", "//flutter/skia", ]
if (!defined(defines)) { defines = [] }}
test_fixtures("display_list_fixtures") { fixtures = [ "//flutter/txt/third_party/fonts/Roboto-Regular.ttf" ]}
if (enable_unittests) { executable("display_list_unittests") { testonly = true
sources = [ "benchmarking/dl_complexity_unittests.cc", "display_list_unittests.cc", "dl_color_unittests.cc", "dl_paint_unittests.cc", "dl_storage_unittests.cc", "dl_vertices_unittests.cc", "effects/dl_color_filter_unittests.cc", "effects/dl_color_source_unittests.cc", "effects/dl_image_filter_unittests.cc", "effects/dl_mask_filter_unittests.cc", "geometry/dl_geometry_types_unittests.cc", "geometry/dl_path_unittests.cc", "geometry/dl_region_unittests.cc", "geometry/dl_rtree_unittests.cc", "skia/dl_sk_conversions_unittests.cc", "skia/dl_sk_paint_dispatcher_unittests.cc", "utils/dl_accumulation_rect_unittests.cc", "utils/dl_matrix_clip_tracker_unittests.cc", ]
deps = [ ":display_list", ":display_list_fixtures", "//flutter/display_list/testing:display_list_testing", "//flutter/impeller/typographer/backends/skia:typographer_skia_backend", "//flutter/testing", "//flutter/testing:skia", ]
if (!defined(defines)) { defines = [] } if (is_win) { # Required for M_PI and others. defines += [ "_USE_MATH_DEFINES" ] }
# This is needed for //flutter/third_party/googletest for linking zircon # symbols. if (is_fuchsia) { libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ] } }
executable("display_list_rendertests") { testonly = true
sources = [ "testing/dl_rendering_unittests.cc" ]
deps = [ ":display_list", ":display_list_fixtures", "//flutter/common/graphics", "//flutter/display_list/testing:display_list_surface_provider", "//flutter/display_list/testing:display_list_testing", "//flutter/impeller/typographer/backends/skia:typographer_skia_backend", "//flutter/testing", "//flutter/txt", ]
if (!defined(defines)) { defines = [] } if (is_win) { # Required for M_PI and others. defines += [ "_USE_MATH_DEFINES" ] }
# This is needed for //flutter/third_party/googletest for linking zircon # symbols. if (is_fuchsia) { libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ] } }
executable("display_list_builder_benchmarks") { testonly = true
sources = [ "benchmarking/dl_builder_benchmarks.cc" ]
deps = [ ":display_list", ":display_list_fixtures", "//flutter/benchmarking", "//flutter/display_list/testing:display_list_testing", "//flutter/testing:testing_lib", ] }
executable("display_list_region_benchmarks") { testonly = true
sources = [ "benchmarking/dl_region_benchmarks.cc" ]
deps = [ ":display_list_fixtures", "//flutter/benchmarking", "//flutter/testing:testing_lib", ] }
executable("display_list_transform_benchmarks") { testonly = true
sources = [ "benchmarking/dl_transform_benchmarks.cc" ]
deps = [ ":display_list_fixtures", "//flutter/benchmarking", "//flutter/testing:testing_lib", ] }}
source_set("display_list_benchmarks_source") { testonly = true
sources = [ "benchmarking/dl_benchmarks.cc", "benchmarking/dl_benchmarks.h", ]
deps = [ ":display_list", ":display_list_fixtures", "$dart_src/runtime:libdart_jit", # for tracing "//flutter/benchmarking", "//flutter/common/graphics", "//flutter/display_list/testing:display_list_surface_provider", "//flutter/display_list/testing:display_list_testing", "//flutter/fml", "//flutter/skia", "//flutter/testing:skia", "//flutter/testing:testing_lib", ]}
executable("display_list_benchmarks") { testonly = true
deps = [ ":display_list_benchmarks_source" ]}
if (is_ios) { shared_library("ios_display_list_benchmarks") { testonly = true visibility = [ ":*" ]
configs -= [ "//build/config/gcc:symbol_visibility_hidden", "//build/config:symbol_visibility_hidden", ] configs += [ "//flutter/benchmarking:benchmark_library_config" ] cflags = [ "-fobjc-arc", "-mios-simulator-version-min=$ios_testing_deployment_target", ] ldflags = [ "-Wl,-install_name,@rpath/libios_display_list_benchmarks.dylib" ] deps = [ ":display_list_benchmarks_source", "//flutter/benchmarking:benchmarking_library", ] }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#include <type_traits>
#include "flutter/display_list/display_list.h"#include "flutter/display_list/dl_op_records.h"#include "flutter/fml/trace_event.h"
namespace flutter {
const SaveLayerOptions SaveLayerOptions::kNoAttributes = SaveLayerOptions();const SaveLayerOptions SaveLayerOptions::kWithAttributes = kNoAttributes.with_renders_with_attributes();
DisplayList::DisplayList() : op_count_(0), nested_byte_count_(0), nested_op_count_(0), total_depth_(0), unique_id_(0), can_apply_group_opacity_(true), is_ui_thread_safe_(true), modifies_transparent_black_(false), root_has_backdrop_filter_(false), root_is_unbounded_(false), max_root_blend_mode_(DlBlendMode::kClear) { FML_DCHECK(offsets_.size() == 0u); FML_DCHECK(storage_.size() == 0u);}
DisplayList::DisplayList(DisplayListStorage&& storage, std::vector<size_t>&& offsets, uint32_t op_count, size_t nested_byte_count, uint32_t nested_op_count, uint32_t total_depth, const DlRect& bounds, bool can_apply_group_opacity, bool is_ui_thread_safe, bool modifies_transparent_black, DlBlendMode max_root_blend_mode, bool root_has_backdrop_filter, bool root_is_unbounded, sk_sp<const DlRTree> rtree) : storage_(std::move(storage)), offsets_(std::move(offsets)), op_count_(op_count), nested_byte_count_(nested_byte_count), nested_op_count_(nested_op_count), total_depth_(total_depth), unique_id_(next_unique_id()), bounds_(bounds), can_apply_group_opacity_(can_apply_group_opacity), is_ui_thread_safe_(is_ui_thread_safe), modifies_transparent_black_(modifies_transparent_black), root_has_backdrop_filter_(root_has_backdrop_filter), root_is_unbounded_(root_is_unbounded), max_root_blend_mode_(max_root_blend_mode), rtree_(std::move(rtree)) { FML_DCHECK(storage_.capacity() == storage_.size());}
DisplayList::~DisplayList() { DisposeOps(storage_, offsets_);}
uint32_t DisplayList::next_unique_id() { static std::atomic<uint32_t> next_id{1}; uint32_t id; do { id = next_id.fetch_add(+1, std::memory_order_relaxed); } while (id == 0); return id;}
struct SaveInfo { SaveInfo(DlIndex previous_restore_index, bool save_was_needed) : previous_restore_index(previous_restore_index), save_was_needed(save_was_needed) {}
DlIndex previous_restore_index; bool save_was_needed;};
void DisplayList::RTreeResultsToIndexVector( std::vector<DlIndex>& indices, const std::vector<int>& rtree_results) const { FML_DCHECK(rtree_); auto cur_rect = rtree_results.begin(); auto end_rect = rtree_results.end(); if (cur_rect >= end_rect) { return; } DlIndex next_render_index = rtree_->id(*cur_rect++); DlIndex next_restore_index = std::numeric_limits<DlIndex>::max(); std::vector<SaveInfo> save_infos; for (DlIndex index = 0u; index < offsets_.size(); index++) { while (index > next_render_index) { if (cur_rect < end_rect) { next_render_index = rtree_->id(*cur_rect++); } else { // Nothing left to render. // Nothing left to do, but match our restores from the stack. while (!save_infos.empty()) { SaveInfo& info = save_infos.back(); // stack top boolean tells us whether the local variable // next_restore_index should be executed. The local variable // then gets reset to the value stored in the stack top if (info.save_was_needed) { FML_DCHECK(next_restore_index < offsets_.size()); indices.push_back(next_restore_index); } next_restore_index = info.previous_restore_index; save_infos.pop_back(); } return; } } const uint8_t* ptr = storage_.base() + offsets_[index]; const DLOp* op = reinterpret_cast<const DLOp*>(ptr); switch (GetOpCategory(op->type)) { case DisplayListOpCategory::kAttribute: // Attributes are always needed indices.push_back(index); break;
case DisplayListOpCategory::kTransform: case DisplayListOpCategory::kClip: if (next_render_index < next_restore_index) { indices.push_back(index); } break;
case DisplayListOpCategory::kRendering: case DisplayListOpCategory::kSubDisplayList: if (index == next_render_index) { indices.push_back(index); } break;
case DisplayListOpCategory::kSave: case DisplayListOpCategory::kSaveLayer: { bool needed = (next_render_index < next_restore_index); save_infos.emplace_back(next_restore_index, needed); switch (op->type) { case DisplayListOpType::kSave: case DisplayListOpType::kSaveLayer: case DisplayListOpType::kSaveLayerBackdrop: next_restore_index = static_cast<const SaveOpBase*>(op)->restore_index; break; default: FML_UNREACHABLE(); } if (needed) { indices.push_back(index); } break; }
case DisplayListOpCategory::kRestore: { FML_DCHECK(!save_infos.empty()); FML_DCHECK(index == next_restore_index); SaveInfo& info = save_infos.back(); next_restore_index = info.previous_restore_index; if (info.save_was_needed) { indices.push_back(index); } save_infos.pop_back(); break; }
case DisplayListOpCategory::kInvalidCategory: FML_UNREACHABLE(); } }}
void DisplayList::Dispatch(DlOpReceiver& receiver) const { const uint8_t* base = storage_.base(); for (size_t offset : offsets_) { DispatchOneOp(receiver, base + offset); }}
void DisplayList::Dispatch(DlOpReceiver& receiver, const DlIRect& cull_rect) const { Dispatch(receiver, DlRect::Make(cull_rect));}
void DisplayList::Dispatch(DlOpReceiver& receiver, const DlRect& cull_rect) const { if (cull_rect.IsEmpty()) { return; } if (!has_rtree() || cull_rect.Contains(GetBounds())) { Dispatch(receiver); } else { auto op_indices = GetCulledIndices(cull_rect); const uint8_t* base = storage_.base(); for (DlIndex index : op_indices) { DispatchOneOp(receiver, base + offsets_[index]); } }}
void DisplayList::DispatchOneOp(DlOpReceiver& receiver, const uint8_t* ptr) const { auto op = reinterpret_cast<const DLOp*>(ptr); switch (op->type) {#define DL_OP_DISPATCH(name) \ case DisplayListOpType::k##name: \ static_cast<const name##Op*>(op)->dispatch(receiver); \ break;
FOR_EACH_DISPLAY_LIST_OP(DL_OP_DISPATCH)
#undef DL_OP_DISPATCH
case DisplayListOpType::kInvalidOp: default: FML_DCHECK(false) << "Unrecognized op type: " << static_cast<int>(op->type); }}
void DisplayList::DisposeOps(const DisplayListStorage& storage, const std::vector<size_t>& offsets) { const uint8_t* base = storage.base(); if (!base) { return; } for (size_t offset : offsets) { auto op = reinterpret_cast<const DLOp*>(base + offset); switch (op->type) {#define DL_OP_DISPOSE(name) \ case DisplayListOpType::k##name: \ if (!std::is_trivially_destructible_v<name##Op>) { \ static_cast<const name##Op*>(op)->~name##Op(); \ } \ break;
FOR_EACH_DISPLAY_LIST_OP(DL_OP_DISPOSE)
#undef DL_OP_DISPOSE
default: FML_UNREACHABLE(); } }}
DisplayListOpCategory DisplayList::GetOpCategory(DlIndex index) const { return GetOpCategory(GetOpType(index));}
DisplayListOpCategory DisplayList::GetOpCategory(DisplayListOpType type) { switch (type) { case DisplayListOpType::kSetAntiAlias: case DisplayListOpType::kSetInvertColors: case DisplayListOpType::kSetStrokeCap: case DisplayListOpType::kSetStrokeJoin: case DisplayListOpType::kSetStyle: case DisplayListOpType::kSetStrokeWidth: case DisplayListOpType::kSetStrokeMiter: case DisplayListOpType::kSetColor: case DisplayListOpType::kSetBlendMode: case DisplayListOpType::kClearColorFilter: case DisplayListOpType::kSetPodColorFilter: case DisplayListOpType::kClearColorSource: case DisplayListOpType::kSetPodColorSource: case DisplayListOpType::kSetImageColorSource: case DisplayListOpType::kSetRuntimeEffectColorSource: case DisplayListOpType::kClearImageFilter: case DisplayListOpType::kSetPodImageFilter: case DisplayListOpType::kSetSharedImageFilter: case DisplayListOpType::kClearMaskFilter: case DisplayListOpType::kSetPodMaskFilter: return DisplayListOpCategory::kAttribute;
case DisplayListOpType::kSave: return DisplayListOpCategory::kSave; case DisplayListOpType::kSaveLayer: case DisplayListOpType::kSaveLayerBackdrop: return DisplayListOpCategory::kSaveLayer; case DisplayListOpType::kRestore: return DisplayListOpCategory::kRestore;
case DisplayListOpType::kTranslate: case DisplayListOpType::kScale: case DisplayListOpType::kRotate: case DisplayListOpType::kSkew: case DisplayListOpType::kTransform2DAffine: case DisplayListOpType::kTransformFullPerspective: case DisplayListOpType::kTransformReset: return DisplayListOpCategory::kTransform;
case DisplayListOpType::kClipIntersectRect: case DisplayListOpType::kClipIntersectOval: case DisplayListOpType::kClipIntersectRoundRect: case DisplayListOpType::kClipIntersectRoundSuperellipse: case DisplayListOpType::kClipIntersectPath: case DisplayListOpType::kClipDifferenceRect: case DisplayListOpType::kClipDifferenceOval: case DisplayListOpType::kClipDifferenceRoundRect: case DisplayListOpType::kClipDifferenceRoundSuperellipse: case DisplayListOpType::kClipDifferencePath: return DisplayListOpCategory::kClip;
case DisplayListOpType::kDrawPaint: case DisplayListOpType::kDrawColor: case DisplayListOpType::kDrawLine: case DisplayListOpType::kDrawDashedLine: case DisplayListOpType::kDrawRect: case DisplayListOpType::kDrawOval: case DisplayListOpType::kDrawCircle: case DisplayListOpType::kDrawRoundRect: case DisplayListOpType::kDrawDiffRoundRect: case DisplayListOpType::kDrawRoundSuperellipse: case DisplayListOpType::kDrawArc: case DisplayListOpType::kDrawPath: case DisplayListOpType::kDrawPoints: case DisplayListOpType::kDrawLines: case DisplayListOpType::kDrawPolygon: case DisplayListOpType::kDrawVertices: case DisplayListOpType::kDrawImage: case DisplayListOpType::kDrawImageWithAttr: case DisplayListOpType::kDrawImageRect: case DisplayListOpType::kDrawImageNine: case DisplayListOpType::kDrawImageNineWithAttr: case DisplayListOpType::kDrawAtlas: case DisplayListOpType::kDrawAtlasCulled: case DisplayListOpType::kDrawTextBlob: case DisplayListOpType::kDrawTextFrame: case DisplayListOpType::kDrawShadow: case DisplayListOpType::kDrawShadowTransparentOccluder: return DisplayListOpCategory::kRendering;
case DisplayListOpType::kDrawDisplayList: return DisplayListOpCategory::kSubDisplayList;
case DisplayListOpType::kInvalidOp: return DisplayListOpCategory::kInvalidCategory; }}
DisplayListOpType DisplayList::GetOpType(DlIndex index) const { // Assert unsigned type so we can eliminate >= 0 comparison static_assert(std::is_unsigned_v<DlIndex>); if (index >= offsets_.size()) { return DisplayListOpType::kInvalidOp; }
size_t offset = offsets_[index]; FML_DCHECK(offset < storage_.size()); auto ptr = storage_.base() + offset; auto op = reinterpret_cast<const DLOp*>(ptr); return op->type;}
static void FillAllIndices(std::vector<DlIndex>& indices, DlIndex size) { indices.reserve(size); for (DlIndex i = 0u; i < size; i++) { indices.push_back(i); }}
std::vector<DlIndex> DisplayList::GetCulledIndices( const DlRect& cull_rect) const { std::vector<DlIndex> indices; if (!cull_rect.IsEmpty()) { if (rtree_) { std::vector<int> rect_indices; rtree_->search(cull_rect, &rect_indices); RTreeResultsToIndexVector(indices, rect_indices); } else { FillAllIndices(indices, offsets_.size()); } } return indices;}
bool DisplayList::Dispatch(DlOpReceiver& receiver, DlIndex index) const { // Assert unsigned type so we can eliminate >= 0 comparison static_assert(std::is_unsigned_v<DlIndex>); if (index >= offsets_.size()) { return false; }
size_t offset = offsets_[index]; FML_DCHECK(offset < storage_.size()); auto ptr = storage_.base() + offset;
DispatchOneOp(receiver, ptr);
return true;}
static bool CompareOps(const DisplayListStorage& storageA, const std::vector<size_t>& offsetsA, const DisplayListStorage& storageB, const std::vector<size_t>& offsetsB) { const uint8_t* base_a = storageA.base(); const uint8_t* base_b = storageB.base(); // These conditions are checked by the caller... FML_DCHECK(offsetsA.size() == offsetsB.size()); FML_DCHECK(base_a != base_b); size_t bulk_start = 0u; for (size_t i = 0; i < offsetsA.size(); i++) { size_t offset = offsetsA[i]; FML_DCHECK(offsetsB[i] == offset); auto opA = reinterpret_cast<const DLOp*>(base_a + offset); auto opB = reinterpret_cast<const DLOp*>(base_b + offset); if (opA->type != opB->type) { return false; } DisplayListCompare result; switch (opA->type) {#define DL_OP_EQUALS(name) \ case DisplayListOpType::k##name: \ result = static_cast<const name##Op*>(opA)->equals( \ static_cast<const name##Op*>(opB)); \ break;
FOR_EACH_DISPLAY_LIST_OP(DL_OP_EQUALS)
#undef DL_OP_EQUALS
default: FML_DCHECK(false); return false; } switch (result) { case DisplayListCompare::kNotEqual: return false; case DisplayListCompare::kUseBulkCompare: break; case DisplayListCompare::kEqual: // Check if we have a backlog of bytes to bulk compare and then // reset the bulk compare pointers to the address following this op if (bulk_start < offset) { const uint8_t* bulk_start_a = base_a + bulk_start; const uint8_t* bulk_start_b = base_b + bulk_start; if (memcmp(bulk_start_a, bulk_start_b, offset - bulk_start) != 0) { return false; } } bulk_start = i + 1 < offsetsA.size() ? offsetsA[i + 1] : storageA.size(); break; } } if (bulk_start < storageA.size()) { // Perform a final bulk compare if we have remaining bytes waiting const uint8_t* bulk_start_a = base_a + bulk_start; const uint8_t* bulk_start_b = base_b + bulk_start; if (memcmp(bulk_start_a, bulk_start_b, storageA.size() - bulk_start) != 0) { return false; } } return true;}
bool DisplayList::Equals(const DisplayList* other) const { if (this == other) { return true; } if (offsets_.size() != other->offsets_.size() || storage_.size() != other->storage_.size() || op_count_ != other->op_count_) { return false; } if (storage_.base() == other->storage_.base()) { return true; } return CompareOps(storage_, offsets_, other->storage_, other->offsets_);}
} // namespace flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#ifndef FLUTTER_DISPLAY_LIST_DISPLAY_LIST_H_#define FLUTTER_DISPLAY_LIST_DISPLAY_LIST_H_
#include "flutter/display_list/dl_blend_mode.h"#include "flutter/display_list/dl_storage.h"#include "flutter/display_list/geometry/dl_geometry_types.h"#include "flutter/display_list/geometry/dl_rtree.h"
// The Flutter DisplayList mechanism encapsulates a persistent sequence of// rendering operations.//// This file contains the definitions for:// DisplayList: the base class that holds the information about the// sequence of operations and can dispatch them to a DlOpReceiver// DlOpReceiver: a pure virtual interface which can be implemented to field// the requests for purposes such as sending them to an SkCanvas// or detecting various rendering optimization scenarios// DisplayListBuilder: a class for constructing a DisplayList from DlCanvas// method calls and which can act as a DlOpReceiver as well//// Other files include various class definitions for dealing with display// lists, such as:// skia/dl_sk_*.h: classes to interact between SkCanvas and DisplayList// (SkCanvas->DisplayList adapter and vice versa)//// display_list_utils.h: various utility classes to ease implementing// a DlOpReceiver, including NOP implementations of// the attribute, clip, and transform methods,// classes to track attributes, clips, and transforms// and a class to compute the bounds of a DisplayList// Any class implementing DlOpReceiver can inherit from// these utility classes to simplify its creation//// The Flutter DisplayList mechanism is used in a similar manner to the Skia// SkPicture mechanism.//// A DisplayList must be created using a DisplayListBuilder using its stateless// methods inherited from DlCanvas.//// A DisplayList can be read back by implementing the DlOpReceiver virtual// methods (with help from some of the classes in the utils file) and// passing an instance to the Dispatch() method, or it can be rendered// to Skia using a DlSkCanvasDispatcher.//// The mechanism is inspired by the SkLiteDL class that is not directly// supported by Skia, but has been recommended as a basis for custom// display lists for a number of their customers.
namespace flutter {
#define FOR_EACH_DISPLAY_LIST_OP(V) \ V(SetAntiAlias) \ V(SetInvertColors) \ \ V(SetStrokeCap) \ V(SetStrokeJoin) \ \ V(SetStyle) \ V(SetStrokeWidth) \ V(SetStrokeMiter) \ \ V(SetColor) \ V(SetBlendMode) \ \ V(ClearColorFilter) \ V(SetPodColorFilter) \ \ V(ClearColorSource) \ V(SetPodColorSource) \ V(SetImageColorSource) \ V(SetRuntimeEffectColorSource) \ \ V(ClearImageFilter) \ V(SetPodImageFilter) \ V(SetSharedImageFilter) \ \ V(ClearMaskFilter) \ V(SetPodMaskFilter) \ \ V(Save) \ V(SaveLayer) \ V(SaveLayerBackdrop) \ V(Restore) \ \ V(Translate) \ V(Scale) \ V(Rotate) \ V(Skew) \ V(Transform2DAffine) \ V(TransformFullPerspective) \ V(TransformReset) \ \ V(ClipIntersectRect) \ V(ClipIntersectOval) \ V(ClipIntersectRoundRect) \ V(ClipIntersectRoundSuperellipse) \ V(ClipIntersectPath) \ V(ClipDifferenceRect) \ V(ClipDifferenceOval) \ V(ClipDifferenceRoundRect) \ V(ClipDifferenceRoundSuperellipse) \ V(ClipDifferencePath) \ \ V(DrawPaint) \ V(DrawColor) \ \ V(DrawLine) \ V(DrawDashedLine) \ V(DrawRect) \ V(DrawOval) \ V(DrawCircle) \ V(DrawRoundRect) \ V(DrawDiffRoundRect) \ V(DrawRoundSuperellipse) \ V(DrawArc) \ V(DrawPath) \ \ V(DrawPoints) \ V(DrawLines) \ V(DrawPolygon) \ V(DrawVertices) \ \ V(DrawImage) \ V(DrawImageWithAttr) \ V(DrawImageRect) \ V(DrawImageNine) \ V(DrawImageNineWithAttr) \ V(DrawAtlas) \ V(DrawAtlasCulled) \ \ V(DrawDisplayList) \ V(DrawTextBlob) \ V(DrawTextFrame) \ \ V(DrawShadow) \ V(DrawShadowTransparentOccluder)
#define DL_OP_TO_ENUM_VALUE(name) k##name,enum class DisplayListOpType { FOR_EACH_DISPLAY_LIST_OP(DL_OP_TO_ENUM_VALUE)
// empty comment to make formatter happy kInvalidOp, kMaxOp = kInvalidOp,};#undef DL_OP_TO_ENUM_VALUE
enum class DisplayListOpCategory { kAttribute, kTransform, kClip, kSave, kSaveLayer, kRestore, kRendering, kSubDisplayList, kInvalidCategory, kMaxCategory = kInvalidCategory,};
class DlOpReceiver;class DisplayListBuilder;
class SaveLayerOptions { public: static const SaveLayerOptions kWithAttributes; static const SaveLayerOptions kNoAttributes;
SaveLayerOptions() : flags_(0) {} SaveLayerOptions(const SaveLayerOptions& options) : flags_(options.flags_) {} explicit SaveLayerOptions(const SaveLayerOptions* options) : flags_(options->flags_) {}
SaveLayerOptions without_optimizations() const { SaveLayerOptions options; options.fRendersWithAttributes = fRendersWithAttributes; options.fBoundsFromCaller = fBoundsFromCaller; return options; }
bool renders_with_attributes() const { return fRendersWithAttributes; } SaveLayerOptions with_renders_with_attributes() const { SaveLayerOptions options(this); options.fRendersWithAttributes = true; return options; }
bool can_distribute_opacity() const { return fCanDistributeOpacity; } SaveLayerOptions with_can_distribute_opacity() const { SaveLayerOptions options(this); options.fCanDistributeOpacity = true; return options; }
// Returns true iff the bounds for the saveLayer operation were provided // by the caller, otherwise the bounds will have been computed by the // DisplayListBuilder and provided for reference. bool bounds_from_caller() const { return fBoundsFromCaller; } SaveLayerOptions with_bounds_from_caller() const { SaveLayerOptions options(this); options.fBoundsFromCaller = true; return options; } SaveLayerOptions without_bounds_from_caller() const { SaveLayerOptions options(this); options.fBoundsFromCaller = false; return options; } bool bounds_were_calculated() const { return !fBoundsFromCaller; }
// Returns true iff the bounds for the saveLayer do not fully cover the // contained rendering operations. This will only occur if the original // caller supplied bounds and those bounds were not a strict superset // of the content bounds computed by the DisplayListBuilder. bool content_is_clipped() const { return fContentIsClipped; } SaveLayerOptions with_content_is_clipped() const { SaveLayerOptions options(this); options.fContentIsClipped = true; return options; }
bool contains_backdrop_filter() const { return fHasBackdropFilter; } SaveLayerOptions with_contains_backdrop_filter() const { SaveLayerOptions options(this); options.fHasBackdropFilter = true; return options; }
bool content_is_unbounded() const { return fContentIsUnbounded; } SaveLayerOptions with_content_is_unbounded() const { SaveLayerOptions options(this); options.fContentIsUnbounded = true; return options; }
SaveLayerOptions& operator=(const SaveLayerOptions& other) { flags_ = other.flags_; return *this; } bool operator==(const SaveLayerOptions& other) const { return flags_ == other.flags_; } bool operator!=(const SaveLayerOptions& other) const { return flags_ != other.flags_; }
private: union { struct { unsigned fRendersWithAttributes : 1; unsigned fCanDistributeOpacity : 1; unsigned fBoundsFromCaller : 1; unsigned fContentIsClipped : 1; unsigned fHasBackdropFilter : 1; unsigned fContentIsUnbounded : 1; }; uint32_t flags_; };};
using DlIndex = uint32_t;
// The base class that contains a sequence of rendering operations// for dispatch to a DlOpReceiver. These objects must be instantiated// through an instance of DisplayListBuilder::build().class DisplayList : public SkRefCnt { public: DisplayList();
~DisplayList();
void Dispatch(DlOpReceiver& ctx) const; void Dispatch(DlOpReceiver& ctx, const SkRect& cull_rect) const { Dispatch(ctx, ToDlRect(cull_rect)); } void Dispatch(DlOpReceiver& ctx, const SkIRect& cull_rect) const { Dispatch(ctx, ToDlIRect(cull_rect)); } void Dispatch(DlOpReceiver& ctx, const DlRect& cull_rect) const; void Dispatch(DlOpReceiver& ctx, const DlIRect& cull_rect) const;
// From historical behavior, SkPicture always included nested bytes, // but nested ops are only included if requested. The defaults used // here for these accessors follow that pattern. size_t bytes(bool nested = true) const { return sizeof(DisplayList) + storage_.size() + (nested ? nested_byte_count_ : 0); }
uint32_t op_count(bool nested = false) const { return op_count_ + (nested ? nested_op_count_ : 0); }
uint32_t total_depth() const { return total_depth_; }
uint32_t unique_id() const { return unique_id_; }
const SkRect& bounds() const { return ToSkRect(bounds_); } const DlRect& GetBounds() const { return bounds_; }
bool has_rtree() const { return rtree_ != nullptr; } sk_sp<const DlRTree> rtree() const { return rtree_; }
bool Equals(const DisplayList* other) const; bool Equals(const DisplayList& other) const { return Equals(&other); } bool Equals(const sk_sp<const DisplayList>& other) const { return Equals(other.get()); }
bool can_apply_group_opacity() const { return can_apply_group_opacity_; } bool isUIThreadSafe() const { return is_ui_thread_safe_; }
/// @brief Indicates if there are any rendering operations in this /// DisplayList that will modify a surface of transparent black /// pixels. /// /// This condition can be used to determine whether to create a cleared /// surface, render a DisplayList into it, and then composite the /// result into a scene. It is not uncommon for code in the engine to /// come across such degenerate DisplayList objects when slicing up a /// frame between platform views. bool modifies_transparent_black() const { return modifies_transparent_black_; }
const DisplayListStorage& GetStorage() const { return storage_; }
/// @brief Indicates if there are any saveLayer operations at the root /// surface level of the DisplayList that use a backdrop filter. /// /// This condition can be used to determine what kind of surface to create /// for the root layer into which to render the DisplayList as some GPUs /// can support surfaces that do or do not support the readback that would /// be required for the backdrop filter to do its work. bool root_has_backdrop_filter() const { return root_has_backdrop_filter_; }
/// @brief Indicates if a rendering operation at the root level of the /// DisplayList had an unbounded result, not otherwise limited by /// a clip operation. /// /// This condition can occur in a number of situations. The most common /// situation is when there is a drawPaint or drawColor rendering /// operation which fills out the entire drawable surface unless it is /// bounded by a clip. Other situations include an operation rendered /// through an ImageFilter that cannot compute the resulting bounds or /// when an unclipped backdrop filter is applied by a save layer. bool root_is_unbounded() const { return root_is_unbounded_; }
/// @brief Indicates the maximum DlBlendMode used on any rendering op /// in the root surface of the DisplayList. /// /// This condition can be used to determine what kind of surface to create /// for the root layer into which to render the DisplayList as some GPUs /// can support surfaces that do or do not support the readback that would /// be required for the indicated blend mode to do its work. DlBlendMode max_root_blend_mode() const { return max_root_blend_mode_; }
/// @brief Iterator utility class used for the |DisplayList::begin| /// and |DisplayList::end| methods. It implements just the /// basic methods to enable iteration-style for loops. class Iterator { public: DlIndex operator*() const { return value_; } bool operator!=(const Iterator& other) { return value_ != other.value_; } Iterator& operator++() { value_++; return *this; }
private: explicit Iterator(DlIndex value) : value_(value) {}
DlIndex value_;
friend class DisplayList; };
/// @brief Return the number of stored records in the DisplayList. /// /// Each stored record represents a dispatchable operation that will be /// sent to a |DlOpReceiver| by the |Dispatch| method. You can directly /// simulate the |Dispatch| method using a simple for loop on the indices: /// /// { /// for (DlIndex i = 0u; i < display_list->GetRecordCount(); i++) { /// display_list->Dispatch(my_receiver, i); /// } /// } /// /// @see |Dispatch(receiver, index)| /// @see |begin| /// @see |end| /// @see |GetCulledIndices| DlIndex GetRecordCount() const { return offsets_.size(); }
/// @brief Return an iterator to the start of the stored records, /// enabling the iteration form of a for loop. /// /// Each stored record represents a dispatchable operation that will be /// sent to a |DlOpReceiver| by the |Dispatch| method. You can directly /// simulate the |Dispatch| method using a simple for loop on the indices: /// /// { /// for (DlIndex i : *display_list) { /// display_list->Dispatch(my_receiver, i); /// } /// } /// /// @see |end| /// @see |GetCulledIndices| Iterator begin() const { return Iterator(0u); }
/// @brief Return an iterator to the end of the stored records, /// enabling the iteration form of a for loop. /// /// Each stored record represents a dispatchable operation that will be /// sent to a |DlOpReceiver| by the |Dispatch| method. You can directly /// simulate the |Dispatch| method using a simple for loop on the indices: /// /// { /// for (DlIndex i : *display_list) { /// display_list->Dispatch(my_receiver, i); /// } /// } /// /// @see |begin| /// @see |GetCulledIndices| Iterator end() const { return Iterator(offsets_.size()); }
/// @brief Dispatch a single stored operation by its index. /// /// Each stored record represents a dispatchable operation that will be /// sent to a |DlOpReceiver| by the |Dispatch| method. You can use this /// method to dispatch a single operation to your receiver with an index /// between |0u| (inclusive) and |GetRecordCount()| (exclusive), as in: /// /// { /// for (DlIndex i = 0u; i < display_list->GetRecordCount(); i++) { /// display_list->Dispatch(my_receiver, i); /// } /// } /// /// If the index is out of the range of the stored records, this method /// will not call any methods on the receiver and return false. You can /// check the return value for true if you want to make sure you are /// using valid indices. /// /// @see |GetRecordCount| /// @see |begin| /// @see |end| /// @see |GetCulledIndices| bool Dispatch(DlOpReceiver& receiver, DlIndex index) const;
/// @brief Return an enum describing the specific op type stored at /// the indicated index. /// /// The specific types of the records are subject to change without notice /// as the DisplayList code is developed and optimized. These values are /// useful mostly for debugging purposes and should not be used in /// production code. /// /// @see |GetOpCategory| for a more stable description of the records DisplayListOpType GetOpType(DlIndex index) const;
/// @brief Return an enum describing the general category of the /// operation record stored at the indicated index. /// /// The categories are general and stable and can be used fairly safely /// in production code to plan how to dispatch or reorder ops during /// final rendering. /// /// @see |GetOpType| for a more detailed description of the records /// primarily for debugging use DisplayListOpCategory GetOpCategory(DlIndex index) const;
/// @brief Return an enum describing the general category of the /// operation record with the given type. /// /// @see |GetOpType| for a more detailed description of the records /// primarily for debugging use static DisplayListOpCategory GetOpCategory(DisplayListOpType type);
/// @brief Return a vector of valid indices for records stored in /// the DisplayList that must be dispatched if you are /// restricted to the indicated cull_rect. /// /// This method can be used along with indexed dispatching to implement /// RTree culling while still maintaining control over planning of /// operations to be rendered, as in: /// /// { /// std::vector<DlIndex> indices = /// display_list->GetCulledIndices(cull-rect); /// for (DlIndex i : indices) { /// display_list->Dispatch(my_receiver, i); /// } /// } /// /// The indices returned in the vector will automatically deal with /// including or culling related operations such as attributes, clips /// and transforms that will provide state for any rendering operations /// selected by the culling checks. /// /// @see |GetOpType| for a more detailed description of the records /// primarily for debugging use /// /// @see |Dispatch(receiver, index)| std::vector<DlIndex> GetCulledIndices(const DlRect& cull_rect) const;
private: DisplayList(DisplayListStorage&& ptr, std::vector<size_t>&& offsets, uint32_t op_count, size_t nested_byte_count, uint32_t nested_op_count, uint32_t total_depth, const DlRect& bounds, bool can_apply_group_opacity, bool is_ui_thread_safe, bool modifies_transparent_black, DlBlendMode max_root_blend_mode, bool root_has_backdrop_filter, bool root_is_unbounded, sk_sp<const DlRTree> rtree);
static uint32_t next_unique_id();
static void DisposeOps(const DisplayListStorage& storage, const std::vector<size_t>& offsets);
const DisplayListStorage storage_; const std::vector<size_t> offsets_;
const uint32_t op_count_; const size_t nested_byte_count_; const uint32_t nested_op_count_;
const uint32_t total_depth_;
const uint32_t unique_id_; const DlRect bounds_;
const bool can_apply_group_opacity_; const bool is_ui_thread_safe_; const bool modifies_transparent_black_; const bool root_has_backdrop_filter_; const bool root_is_unbounded_; const DlBlendMode max_root_blend_mode_;
const sk_sp<const DlRTree> rtree_;
void DispatchOneOp(DlOpReceiver& receiver, const uint8_t* ptr) const;
void RTreeResultsToIndexVector(std::vector<DlIndex>& indices, const std::vector<int>& rtree_results) const;
friend class DisplayListBuilder;};
} // namespace flutter
#endif // FLUTTER_DISPLAY_LIST_DISPLAY_LIST_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#ifndef FLUTTER_DISPLAY_LIST_DL_ATTRIBUTES_H_#define FLUTTER_DISPLAY_LIST_DL_ATTRIBUTES_H_
#include <memory>
namespace flutter {
// ===========================================================================
// The base class for a family of DisplayList attribute classes.//// This class is designed to support the following properties for any// attribute to facilitate the storage of the attribute in a DisplayList// and for use in code that inspects or creates DisplayList objects://// - Typed:// Even though most references and pointers are passed around as the// attribute's base class, a Type property can be queried using the |type|// method to determine which type of the attribute is being used. For// example, the Blend type of ColorFilter will return DlColorFilter::kBlend// from its type method.//// - Inspectable:// Any parameters required to full specify the action of the attribute are// provided on the type-specific classes.//// - Safely Downcast:// For the subclasses that have specific data to query, methods are// provided to safely downcast the reference for inspection. The down// casting method will either return a pointer to the instance with// its type-specific class type, or nullptr if it is executed on the// wrong type of instance.// (eg. DlColorFilter::asBlend() or DlMaskFilter::asBlur())//// - Immutable:// Neither the base class or any of the subclasses specify any mutation// methods. Instances are often passed around as const as a reminder,// but the classes have no mutation methods anyway.//// - Flat and Embeddable:// Bulk freed + bulk compared + zero memory fragmentation.//// All of these classes are designed to be stored in the DisplayList// buffer allocated in-line with the rest of the data to avoid dangling// pointers that require explicit freeing when the DisplayList goes// away, or that fragment the memory needed to read the operations in// the DisplayList. Furthermore, the data in the classes can be bulk// compared using a |memcmp| when performing a |DisplayList::Equals|.//// - Passed by Pointer:// The data shared via the |DlOpReceiver::set<Attribute>| calls are stored// in the buffer itself and so their lifetime is controlled by the// DisplayList. That memory cannot be shared as by a |shared_ptr|// because the memory may be freed outside the control of the shared// pointer. Creating a shared version of the object would require a// new instantiation which we'd like to avoid on every dispatch call,// so a raw (const) pointer is shared in those dispatch calls instead,// with all of the responsibilities of non-ownership in the called method.//// But, for methods that need to keep a copy of the data...//// - Shared_Ptr-able:// The classes support a method to return a |std::shared_ptr| version of// themselves, safely instantiating a new copy of the object into a// shared_ptr using |std::make_shared|. For those receiver objects// that may want to hold on to the contents of the object (typically// in a |current_attribute_| field), they can obtain a shared_ptr// copy safely and easily using the |shared| method.
// ===========================================================================
// |D| is the base type for the attribute// (i.e. DlColorFilter, etc.)// |T| is the enum that describes the specific subclasses// (i.e DlColorFilterType, etc.)template <class D, typename T>class DlAttribute { public: // Return the recognized specific type of the attribute. virtual T type() const = 0;
// Return the size of the instantiated data (typically used to allocate) // storage in the DisplayList buffer. virtual size_t size() const = 0;
// Return a shared version of |this| attribute. The |shared_ptr| returned // will reference a copy of this object so that the lifetime of the shared // version is not tied to the storage of this particular instance. virtual std::shared_ptr<D> shared() const = 0;
// Perform a content aware |==| comparison of the Attribute. bool operator==(D const& other) const { return type() == other.type() && equals_(other); } // Perform a content aware |!=| comparison of the Attribute. bool operator!=(D const& other) const { return !(*this == other); }
virtual ~DlAttribute() = default;
protected: // Virtual comparison method to support |==| and |!=|. virtual bool equals_(D const& other) const = 0;};
} // namespace flutter
#endif // FLUTTER_DISPLAY_LIST_DL_ATTRIBUTES_H_1234567// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#include "flutter/display_list/dl_blend_mode.h"
namespace flutter {} // namespace flutter12345678910111213141516// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#ifndef FLUTTER_DISPLAY_LIST_DL_BLEND_MODE_H_#define FLUTTER_DISPLAY_LIST_DL_BLEND_MODE_H_
#include "flutter/impeller/geometry/color.h"
namespace flutter {
using DlBlendMode = impeller::BlendMode;
} // namespace flutter
#endif // FLUTTER_DISPLAY_LIST_DL_BLEND_MODE_H_1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#include "flutter/display_list/dl_builder.h"
#include "flutter/display_list/display_list.h"#include "flutter/display_list/dl_blend_mode.h"#include "flutter/display_list/dl_op_flags.h"#include "flutter/display_list/dl_op_records.h"#include "flutter/display_list/effects/dl_color_filters.h"#include "flutter/display_list/effects/dl_color_source.h"#include "flutter/display_list/effects/dl_image_filters.h"#include "flutter/display_list/utils/dl_accumulation_rect.h"#include "fml/logging.h"
namespace flutter {
// CopyV(dst, src,n, src,n, ...) copies any number of typed srcs into dst.static void CopyV(void* dst) {}
template <typename S, typename... Rest>static void CopyV(void* dst, const S* src, int n, Rest&&... rest) { FML_DCHECK(((uintptr_t)dst & (alignof(S) - 1)) == 0) << "Expected " << dst << " to be aligned for at least " << alignof(S) << " bytes."; // If n is 0, there is nothing to copy into dst from src. if (n > 0) { memcpy(dst, src, n * sizeof(S)); dst = reinterpret_cast<void*>(reinterpret_cast<uint8_t*>(dst) + n * sizeof(S)); } // Repeat for the next items, if any CopyV(dst, std::forward<Rest>(rest)...);}
template <typename T, typename... Args>void* DisplayListBuilder::Push(size_t pod, Args&&... args) { // Plan out where and how large a space we need size_t size = SkAlignPtr(sizeof(T) + pod); size_t offset = storage_.size();
// Allocate the space auto ptr = storage_.allocate(size); FML_CHECK(ptr);
// Initialize the space via the constructor auto op = reinterpret_cast<T*>(ptr); new (op) T{std::forward<Args>(args)...}; FML_DCHECK(op->type == T::kType);
// Adjust the counters and offsets (the memory is mostly initialized // at this point except that the caller might do some pod-based copying // past the end of the DlOp structure itself when we return) offsets_.push_back(offset); render_op_count_ += T::kRenderOpInc; depth_ += T::kDepthInc * render_op_depth_cost_; op_index_++;
return op + 1;}
sk_sp<DisplayList> DisplayListBuilder::Build() { while (save_stack_.size() > 1) { restore(); }
int count = render_op_count_; size_t nested_bytes = nested_bytes_; int nested_count = nested_op_count_; uint32_t total_depth = depth_; bool opacity_compatible = current_layer().is_group_opacity_compatible(); bool is_safe = is_ui_thread_safe_; bool affects_transparency = current_layer().affects_transparent_layer; bool root_has_backdrop_filter = current_layer().contains_backdrop_filter; bool root_is_unbounded = current_layer().is_unbounded; DlBlendMode max_root_blend_mode = current_layer().max_blend_mode;
sk_sp<DlRTree> rtree; DlRect bounds; if (rtree_data_.has_value()) { auto& rects = rtree_data_->rects; auto& indices = rtree_data_->indices; rtree = sk_make_sp<DlRTree>(rects.data(), rects.size(), indices.data(), [](int id) { return id >= 0; }); // RTree bounds may be tighter due to applying filter bounds // adjustments to each op as we restore layers rather than to // the entire layer bounds. bounds = rtree->bounds(); rtree_data_.reset(); } else { bounds = current_layer().global_space_accumulator.GetBounds(); }
render_op_count_ = op_index_ = 0; nested_bytes_ = nested_op_count_ = 0; depth_ = 0; is_ui_thread_safe_ = true; current_opacity_compatibility_ = true; render_op_depth_cost_ = 1u; current_ = DlPaint();
save_stack_.pop_back(); Init(rtree != nullptr);
storage_.trim(); DisplayListStorage storage; std::vector<size_t> offsets; std::swap(offsets, offsets_); std::swap(storage, storage_);
return sk_sp<DisplayList>(new DisplayList( std::move(storage), std::move(offsets), count, nested_bytes, nested_count, total_depth, bounds, opacity_compatible, is_safe, affects_transparency, max_root_blend_mode, root_has_backdrop_filter, root_is_unbounded, std::move(rtree)));}
static constexpr DlRect kEmpty = DlRect();
static const DlRect& ProtectEmpty(const DlRect& rect) { // isEmpty protects us against NaN while we normalize any empty cull rects return rect.IsEmpty() ? kEmpty : rect;}
DisplayListBuilder::DisplayListBuilder(const DlRect& cull_rect, bool prepare_rtree) : original_cull_rect_(ProtectEmpty(cull_rect)) { Init(prepare_rtree);}
void DisplayListBuilder::Init(bool prepare_rtree) { FML_DCHECK(save_stack_.empty()); FML_DCHECK(!rtree_data_.has_value());
save_stack_.emplace_back(original_cull_rect_); current_info().is_nop = original_cull_rect_.IsEmpty(); if (prepare_rtree) { rtree_data_.emplace(); }}
DisplayListBuilder::~DisplayListBuilder() { DisplayList::DisposeOps(storage_, offsets_);}
DlISize DisplayListBuilder::GetBaseLayerDimensions() const { return DlIRect::RoundOut(original_cull_rect_).GetSize();}
SkImageInfo DisplayListBuilder::GetImageInfo() const { DlISize size = GetBaseLayerDimensions(); return SkImageInfo::MakeUnknown(size.width, size.height);}
void DisplayListBuilder::onSetAntiAlias(bool aa) { current_.setAntiAlias(aa); Push<SetAntiAliasOp>(0, aa);}void DisplayListBuilder::onSetInvertColors(bool invert) { current_.setInvertColors(invert); Push<SetInvertColorsOp>(0, invert); UpdateCurrentOpacityCompatibility();}void DisplayListBuilder::onSetStrokeCap(DlStrokeCap cap) { current_.setStrokeCap(cap); Push<SetStrokeCapOp>(0, cap);}void DisplayListBuilder::onSetStrokeJoin(DlStrokeJoin join) { current_.setStrokeJoin(join); Push<SetStrokeJoinOp>(0, join);}void DisplayListBuilder::onSetDrawStyle(DlDrawStyle style) { current_.setDrawStyle(style); Push<SetStyleOp>(0, style);}void DisplayListBuilder::onSetStrokeWidth(float width) { current_.setStrokeWidth(width); Push<SetStrokeWidthOp>(0, width);}void DisplayListBuilder::onSetStrokeMiter(float limit) { current_.setStrokeMiter(limit); Push<SetStrokeMiterOp>(0, limit);}void DisplayListBuilder::onSetColor(DlColor color) { current_.setColor(color); Push<SetColorOp>(0, color);}void DisplayListBuilder::onSetBlendMode(DlBlendMode mode) { current_.setBlendMode(mode); Push<SetBlendModeOp>(0, mode); UpdateCurrentOpacityCompatibility();}
void DisplayListBuilder::onSetColorSource(const DlColorSource* source) { if (source == nullptr) { current_.setColorSource(nullptr); Push<ClearColorSourceOp>(0); } else { current_.setColorSource(source->shared()); is_ui_thread_safe_ = is_ui_thread_safe_ && source->isUIThreadSafe(); switch (source->type()) { case DlColorSourceType::kImage: { const DlImageColorSource* image_source = source->asImage(); FML_DCHECK(image_source); Push<SetImageColorSourceOp>(0, image_source); break; } case DlColorSourceType::kLinearGradient: { const DlLinearGradientColorSource* linear = source->asLinearGradient(); FML_DCHECK(linear); void* pod = Push<SetPodColorSourceOp>(linear->size()); new (pod) DlLinearGradientColorSource(linear); break; } case DlColorSourceType::kRadialGradient: { const DlRadialGradientColorSource* radial = source->asRadialGradient(); FML_DCHECK(radial); void* pod = Push<SetPodColorSourceOp>(radial->size()); new (pod) DlRadialGradientColorSource(radial); break; } case DlColorSourceType::kConicalGradient: { const DlConicalGradientColorSource* conical = source->asConicalGradient(); FML_DCHECK(conical); void* pod = Push<SetPodColorSourceOp>(conical->size()); new (pod) DlConicalGradientColorSource(conical); break; } case DlColorSourceType::kSweepGradient: { const DlSweepGradientColorSource* sweep = source->asSweepGradient(); FML_DCHECK(sweep); void* pod = Push<SetPodColorSourceOp>(sweep->size()); new (pod) DlSweepGradientColorSource(sweep); break; } case DlColorSourceType::kRuntimeEffect: { const DlRuntimeEffectColorSource* effect = source->asRuntimeEffect(); FML_DCHECK(effect); Push<SetRuntimeEffectColorSourceOp>(0, effect); break; } } } UpdateCurrentOpacityCompatibility();}void DisplayListBuilder::onSetImageFilter(const DlImageFilter* filter) { if (filter == nullptr) { current_.setImageFilter(nullptr); Push<ClearImageFilterOp>(0); } else { current_.setImageFilter(filter->shared()); switch (filter->type()) { case DlImageFilterType::kBlur: { const DlBlurImageFilter* blur_filter = filter->asBlur(); FML_DCHECK(blur_filter); void* pod = Push<SetPodImageFilterOp>(blur_filter->size()); new (pod) DlBlurImageFilter(blur_filter); break; } case DlImageFilterType::kDilate: { const DlDilateImageFilter* dilate_filter = filter->asDilate(); FML_DCHECK(dilate_filter); void* pod = Push<SetPodImageFilterOp>(dilate_filter->size()); new (pod) DlDilateImageFilter(dilate_filter); break; } case DlImageFilterType::kErode: { const DlErodeImageFilter* erode_filter = filter->asErode(); FML_DCHECK(erode_filter); void* pod = Push<SetPodImageFilterOp>(erode_filter->size()); new (pod) DlErodeImageFilter(erode_filter); break; } case DlImageFilterType::kMatrix: { const DlMatrixImageFilter* matrix_filter = filter->asMatrix(); FML_DCHECK(matrix_filter); void* pod = Push<SetPodImageFilterOp>(matrix_filter->size()); new (pod) DlMatrixImageFilter(matrix_filter); break; } case DlImageFilterType::kCompose: case DlImageFilterType::kLocalMatrix: case DlImageFilterType::kColorFilter: case DlImageFilterType::kRuntimeEffect: { Push<SetSharedImageFilterOp>(0, filter); break; } } } UpdateCurrentOpacityCompatibility();}void DisplayListBuilder::onSetColorFilter(const DlColorFilter* filter) { if (filter == nullptr) { current_.setColorFilter(nullptr); Push<ClearColorFilterOp>(0); } else { current_.setColorFilter(filter->shared()); switch (filter->type()) { case DlColorFilterType::kBlend: { const DlBlendColorFilter* blend_filter = filter->asBlend(); FML_DCHECK(blend_filter); void* pod = Push<SetPodColorFilterOp>(blend_filter->size()); new (pod) DlBlendColorFilter(blend_filter); break; } case DlColorFilterType::kMatrix: { const DlMatrixColorFilter* matrix_filter = filter->asMatrix(); FML_DCHECK(matrix_filter); void* pod = Push<SetPodColorFilterOp>(matrix_filter->size()); new (pod) DlMatrixColorFilter(matrix_filter); break; } case DlColorFilterType::kSrgbToLinearGamma: { void* pod = Push<SetPodColorFilterOp>(filter->size()); new (pod) DlSrgbToLinearGammaColorFilter(); break; } case DlColorFilterType::kLinearToSrgbGamma: { void* pod = Push<SetPodColorFilterOp>(filter->size()); new (pod) DlLinearToSrgbGammaColorFilter(); break; } } } UpdateCurrentOpacityCompatibility();}void DisplayListBuilder::onSetMaskFilter(const DlMaskFilter* filter) { if (filter == nullptr) { current_.setMaskFilter(nullptr); render_op_depth_cost_ = 1u; Push<ClearMaskFilterOp>(0); } else { current_.setMaskFilter(filter->shared()); render_op_depth_cost_ = 2u; switch (filter->type()) { case DlMaskFilterType::kBlur: { const DlBlurMaskFilter* blur_filter = filter->asBlur(); FML_DCHECK(blur_filter); void* pod = Push<SetPodMaskFilterOp>(blur_filter->size()); new (pod) DlBlurMaskFilter(blur_filter); break; } } }}
void DisplayListBuilder::SetAttributesFromPaint( const DlPaint& paint, const DisplayListAttributeFlags flags) { if (flags.applies_anti_alias()) { setAntiAlias(paint.isAntiAlias()); } if (flags.applies_alpha_or_color()) { setColor(paint.getColor()); } if (flags.applies_blend()) { setBlendMode(paint.getBlendMode()); } if (flags.applies_style()) { setDrawStyle(paint.getDrawStyle()); } if (flags.is_stroked(paint.getDrawStyle())) { setStrokeWidth(paint.getStrokeWidth()); setStrokeMiter(paint.getStrokeMiter()); setStrokeCap(paint.getStrokeCap()); setStrokeJoin(paint.getStrokeJoin()); } if (flags.applies_shader()) { setColorSource(paint.getColorSource().get()); } if (flags.applies_color_filter()) { setInvertColors(paint.isInvertColors()); setColorFilter(paint.getColorFilter().get()); } if (flags.applies_image_filter()) { setImageFilter(paint.getImageFilter().get()); } if (flags.applies_mask_filter()) { setMaskFilter(paint.getMaskFilter().get()); }}
void DisplayListBuilder::checkForDeferredSave() { if (current_info().has_deferred_save_op) { size_t save_offset = storage_.size(); Push<SaveOp>(0); current_info().save_offset = save_offset; current_info().save_depth = depth_; current_info().has_deferred_save_op = false; }}
void DisplayListBuilder::Save() { bool was_nop = current_info().is_nop; save_stack_.emplace_back(¤t_info()); current_info().is_nop = was_nop;
FML_DCHECK(save_stack_.size() >= 2u); FML_DCHECK(current_info().has_deferred_save_op);}
void DisplayListBuilder::saveLayer(const DlRect& bounds, const SaveLayerOptions in_options, const DlImageFilter* backdrop, std::optional<int64_t> backdrop_id) { SaveLayerOptions options = in_options.without_optimizations(); DisplayListAttributeFlags flags = options.renders_with_attributes() ? kSaveLayerWithPaintFlags : kSaveLayerFlags; OpResult result = PaintResult(current_, flags); if (result == OpResult::kNoEffect) { // If we can't render, whether because we were already in a no-render // state from the parent or because our own attributes make us a nop, // we can just simplify this whole layer to a regular save that has // nop state. We need to have a SaveInfo for the eventual restore(), // but no rendering ops should be accepted between now and then so // it doesn't need any of the data associated with a layer SaveInfo. Save(); current_info().is_nop = true; return; }
if (backdrop != nullptr) { current_layer().contains_backdrop_filter = true; }
// Snapshot these values before we do any work as we need the values // from before the method was called, but some of the operations below // might update them. size_t save_offset = storage_.size(); uint32_t save_depth = depth_;
// A backdrop will affect up to the entire surface, bounded by the clip bool will_be_unbounded = (backdrop != nullptr); std::shared_ptr<DlImageFilter> filter;
if (options.renders_with_attributes()) { if (!paint_nops_on_transparency()) { // We will fill the clip of the outer layer when we restore. will_be_unbounded = true; } filter = current_.getImageFilter(); CheckLayerOpacityCompatibility(true); UpdateLayerResult(result, true); } else { CheckLayerOpacityCompatibility(false); UpdateLayerResult(result, false); }
// The actual flood of the outer layer clip will occur after the // (eventual) corresponding restore is called, but rather than // remember this information in the LayerInfo until the restore // method is processed, we just mark the unbounded state up front. // Another reason to accumulate the clip here rather than in // restore is so that this savelayer will be tagged in the rtree // with its full bounds and the right op_index so that it doesn't // get culled during rendering. if (will_be_unbounded) { // Accumulate should always return true here because if the // clip was empty then that would have been caught up above // when we tested the PaintResult. [[maybe_unused]] bool unclipped = AccumulateUnbounded(); FML_DCHECK(unclipped); }
// Accumulate information for the SaveInfo we are about to push onto the // stack. { size_t rtree_index = rtree_data_.has_value() ? rtree_data_->rects.size() : 0u;
save_stack_.emplace_back(¤t_info(), filter, rtree_index); FML_DCHECK(current_info().is_save_layer); FML_DCHECK(!current_info().is_nop); FML_DCHECK(!current_info().has_deferred_save_op); current_info().save_offset = save_offset; current_info().save_depth = save_depth;
// If we inherit some culling bounds and we have a filter then we need // to adjust them so that we cull for the correct input space for the // output of the filter. if (filter) { DlRect outer_cull_rect = current_info().global_state.GetDeviceCullCoverage(); DlMatrix matrix = current_info().global_state.matrix();
DlIRect output_bounds = DlIRect::RoundOut(outer_cull_rect); DlIRect input_bounds; if (filter->get_input_device_bounds(output_bounds, matrix, input_bounds)) { current_info().global_state.resetDeviceCullRect( DlRect::Make(input_bounds)); } else { // Filter could not make any promises about the bounds it needs to // fill the output space, so we use a maximal rect to accumulate // the layer bounds. current_info().global_state.resetDeviceCullRect(kMaxCullRect); } }
// We always want to cull based on user provided bounds, though, as // that is legacy behavior even if it doesn't always work precisely // in a rotated or skewed coordinate system (but it will work // conservatively). if (in_options.bounds_from_caller()) { current_info().global_state.clipRect(bounds, DlClipOp::kIntersect, false); } }
// Accumulate options to store in the SaveLayer op record. { DlRect record_bounds; if (in_options.bounds_from_caller()) { options = options.with_bounds_from_caller(); record_bounds = bounds; } else { FML_DCHECK(record_bounds.IsEmpty()); }
if (backdrop) { Push<SaveLayerBackdropOp>(0, options, record_bounds, backdrop, backdrop_id); } else { Push<SaveLayerOp>(0, options, record_bounds); } }
if (options.renders_with_attributes()) { // |current_opacity_compatibility_| does not take an ImageFilter into // account because an individual primitive with an ImageFilter can apply // opacity on top of it. But, if the layer is applying the ImageFilter // then it cannot pass the opacity on. if (!current_opacity_compatibility_ || filter) { UpdateLayerOpacityCompatibility(false); } }}void DisplayListBuilder::SaveLayer(const std::optional<DlRect>& bounds, const DlPaint* paint, const DlImageFilter* backdrop, std::optional<int64_t> backdrop_id) { SaveLayerOptions options; DlRect temp_bounds; if (bounds.has_value()) { options = options.with_bounds_from_caller(); temp_bounds = *bounds; } else { FML_DCHECK(temp_bounds.IsEmpty()); } if (paint != nullptr) { options = options.with_renders_with_attributes(); SetAttributesFromPaint(*paint, DisplayListOpFlags::kSaveLayerWithPaintFlags); } saveLayer(temp_bounds, options, backdrop, backdrop_id);}
void DisplayListBuilder::Restore() { if (save_stack_.size() <= 1) { return; }
if (!current_info().has_deferred_save_op) { SaveOpBase* op = reinterpret_cast<SaveOpBase*>(storage_.base() + current_info().save_offset); FML_CHECK(op->type == DisplayListOpType::kSave || op->type == DisplayListOpType::kSaveLayer || op->type == DisplayListOpType::kSaveLayerBackdrop);
op->restore_index = op_index_; op->total_content_depth = depth_ - current_info().save_depth;
if (current_info().is_save_layer) { RestoreLayer(); }
// Wait until all outgoing bounds information for the saveLayer is // recorded before pushing the record to the buffer so that any rtree // bounds will be attributed to the op_index of the restore op. Push<RestoreOp>(0); } else { FML_DCHECK(!current_info().is_save_layer); }
save_stack_.pop_back();}
void DisplayListBuilder::RestoreLayer() { FML_DCHECK(save_stack_.size() > 1); FML_DCHECK(current_info().is_save_layer); FML_DCHECK(!current_info().has_deferred_save_op);
// A saveLayer will usually do a final copy to the main buffer in // addition to its content, but that is accounted for outside of // the total content depth computed above in Restore. depth_ += render_op_depth_cost_;
DlRect content_bounds = current_layer().layer_local_accumulator.GetBounds();
SaveLayerOpBase* layer_op = reinterpret_cast<SaveLayerOpBase*>( storage_.base() + current_info().save_offset); FML_CHECK(layer_op->type == DisplayListOpType::kSaveLayer || layer_op->type == DisplayListOpType::kSaveLayerBackdrop);
if (layer_op->options.bounds_from_caller()) { DlRect user_bounds = layer_op->rect; if (!content_bounds.IsEmpty() && !user_bounds.Contains(content_bounds)) { layer_op->options = layer_op->options.with_content_is_clipped(); content_bounds = content_bounds.IntersectionOrEmpty(user_bounds); } } layer_op->rect = content_bounds; layer_op->max_blend_mode = current_layer().max_blend_mode;
if (current_layer().contains_backdrop_filter) { layer_op->options = layer_op->options.with_contains_backdrop_filter(); }
if (current_layer().is_group_opacity_compatible()) { layer_op->options = layer_op->options.with_can_distribute_opacity(); }
if (current_layer().is_unbounded) { layer_op->options = layer_op->options.with_content_is_unbounded(); }
// Ensure that the bounds transferred in the following call will be // attributed to the index of the restore op. FML_DCHECK(layer_op->restore_index == op_index_); TransferLayerBounds(content_bounds);}
// There are a few different conditions and corresponding operations to// consider when transferring bounds from one layer to another. The current// layer will have accumulated its bounds into 2 potential places://// - Its own private layer local bounds, which were potentially clipped by// the supplied bounds and passed here as the content_bounds.//// - Either the rtree rect list, or the global space accumulator, one or// the other.//// If there is no filter then the private layer bounds are complete and// they simply need to be passed along to the parent into its layer local// accumulator. Also, if there was no filter then the existing bounds// recorded in either the rtree rects or the layer's global space accumulator// (shared with its parent) need no updating so no global space transfer// has to occur.//// If there is a filter then the global content bounds will need to be// adjusted in one of two ways (rtree vs non-rtree)://// - If we are accumulating rtree rects then each of the rects accumulated// during this current layer will need to be updated by the filter in the// global coordinate space in which they were accumulated. In this mode// we should never have a global space accumulator on the layer.//// - Otherwise we were accumulating global bounds into our own private// global space accumulator which need to be adjusted in the global space// coordinate system by the filter.//// Finally, we will have to adjust the layer's content bounds by the filter// and accumulate those into the parent layer's local bounds.void DisplayListBuilder::TransferLayerBounds(const DlRect& content_bounds) { auto& filter = current_layer().filter;
if (!filter) { // We either accumulate global bounds into the rtree_data if there // is one, or into the global_space_accumulator, but not both. FML_DCHECK(!rtree_data_.has_value() || current_layer().global_space_accumulator.is_empty());
parent_info().AccumulateBoundsLocal(content_bounds); parent_layer().global_space_accumulator.accumulate( current_layer().global_space_accumulator); return; }
bool parent_is_flooded = false; DlRect bounds_for_parent = content_bounds;
// First, let's adjust or transfer the global/rtree bounds by the filter.
// Matrix and Clip for the filter adjustment are the global values from // just before our saveLayer and should still be the current values // present in the parent layer. const DlRect clip = parent_info().global_state.GetDeviceCullCoverage(); const DlMatrix matrix = parent_info().global_state.matrix();
if (rtree_data_.has_value()) { // Neither current or parent layer should have any global bounds in // their accumulator FML_DCHECK(current_layer().global_space_accumulator.is_empty()); FML_DCHECK(parent_layer().global_space_accumulator.is_empty());
// The rtree rects were accumulated without the bounds modification of // the filter applied to the layer so they may fail to trigger on a // culled dispatch if their filter "fringes" are in the dispatch scope // but their base rendering bounds are not. (Also, they will not // contribute fully when we compute the overall bounds of this DL.) // // To make sure they are rendered in the culled dispatch situation, we // revisit all of the RTree rects accumulated during the current layer // (indicated by rtree_rects_start_index) and expand them by the filter.
if (AdjustRTreeRects(rtree_data_.value(), *filter, matrix, clip, current_layer().rtree_rects_start_index)) { parent_is_flooded = true; } } else { DlRect global_bounds = current_layer().global_space_accumulator.GetBounds(); if (!global_bounds.IsEmpty()) { DlIRect global_ibounds = DlIRect::RoundOut(global_bounds); if (!filter->map_device_bounds(global_ibounds, matrix, global_ibounds)) { parent_is_flooded = true; } else { global_bounds = DlRect::Make(global_ibounds); std::optional<DlRect> clipped_bounds = global_bounds.Intersection(clip); if (clipped_bounds.has_value()) { parent_layer().global_space_accumulator.accumulate( clipped_bounds.value()); } } } }
// Now we visit the layer bounds which are in the layer's local coordinate // system must be accumulated into the parent layer's bounds while // adjusting them by the layer's local coordinate system (handled by the // Accumulate() methods).
// A filter will happily adjust empty bounds to be non-empty, so we // specifically avoid that case here. Also, if we are already planning // to flood the parent due to any of the cases above, we don't need to // run the filter on the content bounds only to discover the same // condition. if (!parent_is_flooded && !bounds_for_parent.IsEmpty()) { DlRect mappable_bounds = bounds_for_parent; if (filter->map_local_bounds(mappable_bounds, mappable_bounds)) { bounds_for_parent = mappable_bounds; } else { parent_is_flooded = true; } }
if (parent_is_flooded) { // All of the above computations deferred the flooded parent status // to here. We need to mark the parent as flooded in both its layer // and global accumulators. Note that even though the rtree rects // were expanded to the size of the clip above, this method will still // add one more rect to the rtree with the op index of the restore // command to prevent the saveLayer itself from being elided in the // rare case that there are no rendering ops in it, or somehow none // of them were chosen by the rtree search (unlikely). The saveLayer // must be processed for the parent flood to happen. AccumulateUnbounded(parent_info()); } else { parent_info().AccumulateBoundsLocal(bounds_for_parent); }}
bool DisplayListBuilder::AdjustRTreeRects(RTreeData& data, const DlImageFilter& filter, const DlMatrix& matrix, const DlRect& clip, size_t rect_start_index) { auto& rects = data.rects; auto& indices = data.indices; FML_DCHECK(rects.size() == indices.size()); int ret = false; auto rect_keep = rect_start_index; for (size_t i = rect_start_index; i < rects.size(); i++) { DlRect bounds = rects[i]; DlIRect ibounds = DlIRect::RoundOut(bounds); if (filter.map_device_bounds(ibounds, matrix, ibounds)) { bounds = DlRect::Make(ibounds); } else { bounds = clip; ret = true; } auto clipped_bounds = bounds.Intersection(clip); if (clipped_bounds.has_value()) { indices[rect_keep] = indices[i]; rects[rect_keep] = clipped_bounds.value(); rect_keep++; } } indices.resize(rect_keep); rects.resize(rect_keep); return ret;}
void DisplayListBuilder::RestoreToCount(int restore_count) { FML_DCHECK(restore_count <= GetSaveCount()); while (restore_count < GetSaveCount() && GetSaveCount() > 1) { restore(); }}
void DisplayListBuilder::Translate(DlScalar tx, DlScalar ty) { if (std::isfinite(tx) && std::isfinite(ty) && (tx != 0.0 || ty != 0.0)) { checkForDeferredSave(); Push<TranslateOp>(0, tx, ty); global_state().translate(tx, ty); layer_local_state().translate(tx, ty); }}void DisplayListBuilder::Scale(DlScalar sx, DlScalar sy) { if (std::isfinite(sx) && std::isfinite(sy) && (sx != 1.0 || sy != 1.0)) { checkForDeferredSave(); Push<ScaleOp>(0, sx, sy); global_state().scale(sx, sy); layer_local_state().scale(sx, sy); }}void DisplayListBuilder::Rotate(DlScalar degrees) { if (SkScalarMod(degrees, 360.0) != 0.0) { checkForDeferredSave(); Push<RotateOp>(0, degrees); global_state().rotate(DlDegrees(degrees)); layer_local_state().rotate(DlDegrees(degrees)); }}void DisplayListBuilder::Skew(DlScalar sx, DlScalar sy) { if (std::isfinite(sx) && std::isfinite(sy) && (sx != 0.0 || sy != 0.0)) { checkForDeferredSave(); Push<SkewOp>(0, sx, sy); global_state().skew(sx, sy); layer_local_state().skew(sx, sy); }}
// clang-format off
// 2x3 2D affine subset of a 4x4 transform in row major ordervoid DisplayListBuilder::Transform2DAffine( DlScalar mxx, DlScalar mxy, DlScalar mxt, DlScalar myx, DlScalar myy, DlScalar myt) { if (std::isfinite(mxx) && std::isfinite(myx) && std::isfinite(mxy) && std::isfinite(myy) && std::isfinite(mxt) && std::isfinite(myt)) { if (mxx == 1 && mxy == 0 && myx == 0 && myy == 1) { Translate(mxt, myt); } else { checkForDeferredSave(); Push<Transform2DAffineOp>(0, mxx, mxy, mxt, myx, myy, myt); global_state().transform2DAffine(mxx, mxy, mxt, myx, myy, myt); layer_local_state().transform2DAffine(mxx, mxy, mxt, myx, myy, myt); } }}// full 4x4 transform in row major ordervoid DisplayListBuilder::TransformFullPerspective( DlScalar mxx, DlScalar mxy, DlScalar mxz, DlScalar mxt, DlScalar myx, DlScalar myy, DlScalar myz, DlScalar myt, DlScalar mzx, DlScalar mzy, DlScalar mzz, DlScalar mzt, DlScalar mwx, DlScalar mwy, DlScalar mwz, DlScalar mwt) { if ( mxz == 0 && myz == 0 && mzx == 0 && mzy == 0 && mzz == 1 && mzt == 0 && mwx == 0 && mwy == 0 && mwz == 0 && mwt == 1) { transform2DAffine(mxx, mxy, mxt, myx, myy, myt); } else if (std::isfinite(mxx) && std::isfinite(mxy) && std::isfinite(mxz) && std::isfinite(mxt) && std::isfinite(myx) && std::isfinite(myy) && std::isfinite(myz) && std::isfinite(myt) && std::isfinite(mzx) && std::isfinite(mzy) && std::isfinite(mzz) && std::isfinite(mzt) && std::isfinite(mwx) && std::isfinite(mwy) && std::isfinite(mwz) && std::isfinite(mwt)) { checkForDeferredSave(); Push<TransformFullPerspectiveOp>(0, mxx, mxy, mxz, mxt, myx, myy, myz, myt, mzx, mzy, mzz, mzt, mwx, mwy, mwz, mwt); global_state().transformFullPerspective(mxx, mxy, mxz, mxt, myx, myy, myz, myt, mzx, mzy, mzz, mzt, mwx, mwy, mwz, mwt); layer_local_state().transformFullPerspective(mxx, mxy, mxz, mxt, myx, myy, myz, myt, mzx, mzy, mzz, mzt, mwx, mwy, mwz, mwt); }}// clang-format onvoid DisplayListBuilder::TransformReset() { checkForDeferredSave(); Push<TransformResetOp>(0);
// The matrices in layer_tracker_ and tracker_ are similar, but // start at a different base transform. The tracker_ potentially // has some number of transform operations on it that prefix the // operations accumulated in layer_tracker_. So we can't set them both // to identity in parallel as they would no longer maintain their // relationship to each other. // Instead we reinterpret this operation as transforming by the // inverse of the current transform. Doing so to tracker_ sets it // to identity so we can avoid the math there, but we must do the // math the long way for layer_tracker_. This becomes: // layer_tracker_.transform(tracker_.inverse()); if (!layer_local_state().inverseTransform(global_state())) { // If the inverse operation failed then that means that either // the matrix above the current layer was singular, or the matrix // became singular while we were accumulating the current layer. // In either case, we should no longer be accumulating any // contents so we set the layer tracking transform to a singular one. layer_local_state().setTransform(DlMatrix::MakeScale({0.0f, 0.0f, 0.0f})); }
global_state().setIdentity();}void DisplayListBuilder::Transform(const DlMatrix& matrix) { TransformFullPerspective( matrix.e[0][0], matrix.e[1][0], matrix.e[2][0], matrix.e[3][0], matrix.e[0][1], matrix.e[1][1], matrix.e[2][1], matrix.e[3][1], matrix.e[0][2], matrix.e[1][2], matrix.e[2][2], matrix.e[3][2], matrix.e[0][3], matrix.e[1][3], matrix.e[2][3], matrix.e[3][3]);}
void DisplayListBuilder::ClipRect(const DlRect& rect, DlClipOp clip_op, bool is_aa) { if (!rect.IsFinite()) { return; } if (current_info().is_nop) { return; } if (current_info().has_valid_clip && clip_op == DlClipOp::kIntersect && layer_local_state().rect_covers_cull(rect)) { return; } global_state().clipRect(rect, clip_op, is_aa); layer_local_state().clipRect(rect, clip_op, is_aa); if (global_state().is_cull_rect_empty() || layer_local_state().is_cull_rect_empty()) { current_info().is_nop = true; return; } current_info().has_valid_clip = true; checkForDeferredSave(); switch (clip_op) { case DlClipOp::kIntersect: Push<ClipIntersectRectOp>(0, rect, is_aa); break; case DlClipOp::kDifference: Push<ClipDifferenceRectOp>(0, rect, is_aa); break; }}void DisplayListBuilder::ClipOval(const DlRect& bounds, DlClipOp clip_op, bool is_aa) { if (!bounds.IsFinite()) { return; } if (current_info().is_nop) { return; } if (current_info().has_valid_clip && clip_op == DlClipOp::kIntersect && layer_local_state().oval_covers_cull(bounds)) { return; } global_state().clipOval(bounds, clip_op, is_aa); layer_local_state().clipOval(bounds, clip_op, is_aa); if (global_state().is_cull_rect_empty() || layer_local_state().is_cull_rect_empty()) { current_info().is_nop = true; return; } current_info().has_valid_clip = true; checkForDeferredSave(); switch (clip_op) { case DlClipOp::kIntersect: Push<ClipIntersectOvalOp>(0, bounds, is_aa); break; case DlClipOp::kDifference: Push<ClipDifferenceOvalOp>(0, bounds, is_aa); break; }}void DisplayListBuilder::ClipRoundRect(const DlRoundRect& rrect, DlClipOp clip_op, bool is_aa) { if (rrect.IsRect()) { ClipRect(rrect.GetBounds(), clip_op, is_aa); return; } if (rrect.IsOval()) { ClipOval(rrect.GetBounds(), clip_op, is_aa); return; } if (current_info().is_nop) { return; } if (current_info().has_valid_clip && clip_op == DlClipOp::kIntersect && layer_local_state().rrect_covers_cull(rrect)) { return; } global_state().clipRRect(rrect, clip_op, is_aa); layer_local_state().clipRRect(rrect, clip_op, is_aa); if (global_state().is_cull_rect_empty() || layer_local_state().is_cull_rect_empty()) { current_info().is_nop = true; return; } current_info().has_valid_clip = true; checkForDeferredSave(); switch (clip_op) { case DlClipOp::kIntersect: Push<ClipIntersectRoundRectOp>(0, rrect, is_aa); break; case DlClipOp::kDifference: Push<ClipDifferenceRoundRectOp>(0, rrect, is_aa); break; }}void DisplayListBuilder::ClipRoundSuperellipse(const DlRoundSuperellipse& rse, DlClipOp clip_op, bool is_aa) { if (rse.IsRect()) { ClipRect(rse.GetBounds(), clip_op, is_aa); return; } if (rse.IsOval()) { ClipOval(rse.GetBounds(), clip_op, is_aa); return; } if (current_info().is_nop) { return; } if (current_info().has_valid_clip && clip_op == DlClipOp::kIntersect && layer_local_state().rsuperellipse_covers_cull(rse)) { return; } global_state().clipRSuperellipse(rse, clip_op, is_aa); layer_local_state().clipRSuperellipse(rse, clip_op, is_aa); if (global_state().is_cull_rect_empty() || layer_local_state().is_cull_rect_empty()) { current_info().is_nop = true; return; } current_info().has_valid_clip = true; checkForDeferredSave(); switch (clip_op) { case DlClipOp::kIntersect: Push<ClipIntersectRoundSuperellipseOp>(0, rse, is_aa); break; case DlClipOp::kDifference: Push<ClipDifferenceRoundSuperellipseOp>(0, rse, is_aa); break; }}void DisplayListBuilder::ClipPath(const DlPath& path, DlClipOp clip_op, bool is_aa) { if (current_info().is_nop) { return; } { DlRect rect; if (path.IsRect(&rect)) { ClipRect(rect, clip_op, is_aa); return; } if (path.IsOval(&rect)) { ClipOval(rect, clip_op, is_aa); return; } DlRoundRect rrect; if (path.IsRoundRect(&rrect)) { ClipRoundRect(rrect, clip_op, is_aa); return; } } global_state().clipPath(path, clip_op, is_aa); layer_local_state().clipPath(path, clip_op, is_aa); if (global_state().is_cull_rect_empty() || layer_local_state().is_cull_rect_empty()) { current_info().is_nop = true; return; } current_info().has_valid_clip = true; checkForDeferredSave(); switch (clip_op) { case DlClipOp::kIntersect: Push<ClipIntersectPathOp>(0, path, is_aa); break; case DlClipOp::kDifference: Push<ClipDifferencePathOp>(0, path, is_aa); break; }}
bool DisplayListBuilder::QuickReject(const DlRect& bounds) const { return global_state().content_culled(bounds);}
void DisplayListBuilder::drawPaint() { OpResult result = PaintResult(current_, kDrawPaintFlags); if (result != OpResult::kNoEffect && AccumulateUnbounded()) { Push<DrawPaintOp>(0); CheckLayerOpacityCompatibility(); UpdateLayerResult(result); }}void DisplayListBuilder::DrawPaint(const DlPaint& paint) { SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawPaintFlags); drawPaint();}void DisplayListBuilder::DrawColor(DlColor color, DlBlendMode mode) { OpResult result = PaintResult(DlPaint(color).setBlendMode(mode)); if (result != OpResult::kNoEffect && AccumulateUnbounded()) { Push<DrawColorOp>(0, color, mode); CheckLayerOpacityCompatibility(mode); UpdateLayerResult(result, mode); }}void DisplayListBuilder::drawLine(const DlPoint& p0, const DlPoint& p1) { DlRect bounds = DlRect::MakeLTRB(p0.x, p0.y, p1.x, p1.y).GetPositive(); DisplayListAttributeFlags flags = bounds.IsEmpty() ? kDrawHVLineFlags : kDrawLineFlags; OpResult result = PaintResult(current_, flags); if (result != OpResult::kNoEffect && AccumulateOpBounds(bounds, flags)) { Push<DrawLineOp>(0, p0, p1); CheckLayerOpacityCompatibility(); UpdateLayerResult(result); }}void DisplayListBuilder::DrawLine(const DlPoint& p0, const DlPoint& p1, const DlPaint& paint) { SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawLineFlags); drawLine(p0, p1);}void DisplayListBuilder::drawDashedLine(const DlPoint& p0, const DlPoint& p1, DlScalar on_length, DlScalar off_length) { DlRect bounds = DlRect::MakeLTRB(p0.x, p0.y, p1.x, p1.y).GetPositive(); DisplayListAttributeFlags flags = bounds.IsEmpty() ? kDrawHVLineFlags : kDrawLineFlags; OpResult result = PaintResult(current_, flags); if (result != OpResult::kNoEffect && AccumulateOpBounds(bounds, flags)) { Push<DrawDashedLineOp>(0, p0, p1, on_length, off_length); CheckLayerOpacityCompatibility(); UpdateLayerResult(result); }}void DisplayListBuilder::DrawDashedLine(const DlPoint& p0, const DlPoint& p1, DlScalar on_length, DlScalar off_length, const DlPaint& paint) { SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawLineFlags); drawDashedLine(p0, p1, on_length, off_length);}void DisplayListBuilder::drawRect(const DlRect& rect) { DisplayListAttributeFlags flags = kDrawRectFlags; OpResult result = PaintResult(current_, flags); if (result != OpResult::kNoEffect && AccumulateOpBounds(rect.GetPositive(), flags)) { Push<DrawRectOp>(0, rect); CheckLayerOpacityCompatibility(); UpdateLayerResult(result); }}void DisplayListBuilder::DrawRect(const DlRect& rect, const DlPaint& paint) { SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawRectFlags); drawRect(rect);}void DisplayListBuilder::drawOval(const DlRect& bounds) { DisplayListAttributeFlags flags = kDrawOvalFlags; OpResult result = PaintResult(current_, flags); if (result != OpResult::kNoEffect && AccumulateOpBounds(bounds.GetPositive(), flags)) { Push<DrawOvalOp>(0, bounds); CheckLayerOpacityCompatibility(); UpdateLayerResult(result); }}void DisplayListBuilder::DrawOval(const DlRect& bounds, const DlPaint& paint) { SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawOvalFlags); drawOval(bounds);}void DisplayListBuilder::drawCircle(const DlPoint& center, DlScalar radius) { DisplayListAttributeFlags flags = kDrawCircleFlags; OpResult result = PaintResult(current_, flags); if (result != OpResult::kNoEffect) { DlRect bounds = DlRect::MakeLTRB(center.x - radius, center.y - radius, center.x + radius, center.y + radius); if (AccumulateOpBounds(bounds, flags)) { Push<DrawCircleOp>(0, center, radius); CheckLayerOpacityCompatibility(); UpdateLayerResult(result); } }}void DisplayListBuilder::DrawCircle(const DlPoint& center, DlScalar radius, const DlPaint& paint) { SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawCircleFlags); drawCircle(center, radius);}void DisplayListBuilder::drawRoundRect(const DlRoundRect& rrect) { if (rrect.IsRect()) { drawRect(rrect.GetBounds()); } else if (rrect.IsOval()) { drawOval(rrect.GetBounds()); } else { DisplayListAttributeFlags flags = kDrawRRectFlags; OpResult result = PaintResult(current_, flags); if (result != OpResult::kNoEffect && AccumulateOpBounds(rrect.GetBounds(), flags)) { Push<DrawRoundRectOp>(0, rrect); CheckLayerOpacityCompatibility(); UpdateLayerResult(result); } }}void DisplayListBuilder::DrawRoundRect(const DlRoundRect& rrect, const DlPaint& paint) { SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawRRectFlags); drawRoundRect(rrect);}void DisplayListBuilder::drawDiffRoundRect(const DlRoundRect& outer, const DlRoundRect& inner) { DisplayListAttributeFlags flags = kDrawDRRectFlags; OpResult result = PaintResult(current_, flags); if (result != OpResult::kNoEffect && AccumulateOpBounds(outer.GetBounds(), flags)) { Push<DrawDiffRoundRectOp>(0, outer, inner); CheckLayerOpacityCompatibility(); UpdateLayerResult(result); }}void DisplayListBuilder::DrawDiffRoundRect(const DlRoundRect& outer, const DlRoundRect& inner, const DlPaint& paint) { SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawDRRectFlags); drawDiffRoundRect(outer, inner);}void DisplayListBuilder::drawRoundSuperellipse(const DlRoundSuperellipse& rse) { if (rse.IsRect()) { drawRect(rse.GetBounds()); } else if (rse.IsOval()) { drawOval(rse.GetBounds()); } else { DisplayListAttributeFlags flags = kDrawRSuperellipseFlags; OpResult result = PaintResult(current_, flags); if (result != OpResult::kNoEffect && AccumulateOpBounds(rse.GetBounds(), flags)) { // DrawRoundSuperellipseOp only supports filling. Anything related to // stroking must use path approximation. if (current_.getDrawStyle() == DlDrawStyle::kFill) { Push<DrawRoundSuperellipseOp>(0, rse); } else { DlPathBuilder builder; builder.SetConvexity(impeller::Convexity::kConvex); builder.SetBounds(rse.GetBounds()); builder.AddRoundSuperellipse(DlRoundSuperellipse::MakeRectRadii( rse.GetBounds(), rse.GetRadii())); Push<DrawPathOp>(0, DlPath(builder.TakePath())); } CheckLayerOpacityCompatibility(); UpdateLayerResult(result); } }}void DisplayListBuilder::DrawRoundSuperellipse(const DlRoundSuperellipse& rse, const DlPaint& paint) { SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawRSuperellipseFlags); drawRoundSuperellipse(rse);}void DisplayListBuilder::drawPath(const DlPath& path) { DisplayListAttributeFlags flags = kDrawPathFlags; OpResult result = PaintResult(current_, flags); if (result != OpResult::kNoEffect) { bool is_visible = AccumulateOpBounds(path.GetBounds(), flags); if (is_visible) { Push<DrawPathOp>(0, path); CheckLayerOpacityHairlineCompatibility(); UpdateLayerResult(result); } }}void DisplayListBuilder::DrawPath(const DlPath& path, const DlPaint& paint) { SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawPathFlags); drawPath(path);}
void DisplayListBuilder::drawArc(const DlRect& bounds, DlScalar start, DlScalar sweep, bool useCenter) { DisplayListAttributeFlags flags = // useCenter // ? kDrawArcWithCenterFlags : kDrawArcNoCenterFlags; OpResult result = PaintResult(current_, flags); // This could be tighter if we compute where the start and end // angles are and then also consider the quadrants swept and // the center if specified. if (result != OpResult::kNoEffect && AccumulateOpBounds(bounds, flags)) { Push<DrawArcOp>(0, bounds, start, sweep, useCenter); if (useCenter) { CheckLayerOpacityHairlineCompatibility(); } else { CheckLayerOpacityCompatibility(); } UpdateLayerResult(result); }}void DisplayListBuilder::DrawArc(const DlRect& bounds, DlScalar start, DlScalar sweep, bool useCenter, const DlPaint& paint) { SetAttributesFromPaint( paint, useCenter ? kDrawArcWithCenterFlags : kDrawArcNoCenterFlags); drawArc(bounds, start, sweep, useCenter);}
DisplayListAttributeFlags DisplayListBuilder::FlagsForPointMode( DlPointMode mode) { switch (mode) { case DlPointMode::kPoints: return kDrawPointsAsPointsFlags; case DlPointMode::kLines: return kDrawPointsAsLinesFlags; case DlPointMode::kPolygon: return kDrawPointsAsPolygonFlags; } FML_UNREACHABLE();}void DisplayListBuilder::drawPoints(DlPointMode mode, uint32_t count, const DlPoint pts[]) { if (count == 0) { return; } DisplayListAttributeFlags flags = FlagsForPointMode(mode); OpResult result = PaintResult(current_, flags); if (result == OpResult::kNoEffect) { return; }
FML_DCHECK(count < DlOpReceiver::kMaxDrawPointsCount); int bytes = count * sizeof(DlPoint); AccumulationRect accumulator; for (size_t i = 0; i < count; i++) { accumulator.accumulate(pts[i]); } if (!AccumulateOpBounds(accumulator.GetBounds(), flags)) { return; }
void* data_ptr; switch (mode) { case DlPointMode::kPoints: data_ptr = Push<DrawPointsOp>(bytes, count); break; case DlPointMode::kLines: data_ptr = Push<DrawLinesOp>(bytes, count); break; case DlPointMode::kPolygon: data_ptr = Push<DrawPolygonOp>(bytes, count); break; default: FML_UNREACHABLE(); return; } CopyV(data_ptr, pts, count); // drawPoints treats every point or line (or segment of a polygon) // as a completely separate operation meaning we cannot ensure // distribution of group opacity without analyzing the mode and the // bounds of every sub-primitive. // See: https://fiddle.skia.org/c/228459001d2de8db117ce25ef5cedb0c current_layer().layer_local_accumulator.record_overlapping_bounds(); // Even though we've eliminated the possibility of opacity peephole // optimizations above, we still set the appropriate flags based on // the rendering attributes in case we solve the overlapping points // problem above. CheckLayerOpacityCompatibility(); UpdateLayerResult(result);}void DisplayListBuilder::DrawPoints(DlPointMode mode, uint32_t count, const DlPoint pts[], const DlPaint& paint) { SetAttributesFromPaint(paint, FlagsForPointMode(mode)); drawPoints(mode, count, pts);}void DisplayListBuilder::drawVertices( const std::shared_ptr<DlVertices>& vertices, DlBlendMode mode) { DisplayListAttributeFlags flags = kDrawVerticesFlags; OpResult result = PaintResult(current_, flags); if (result != OpResult::kNoEffect && AccumulateOpBounds(vertices->GetBounds(), flags)) { Push<DrawVerticesOp>(0, vertices, mode); // DrawVertices applies its colors to the paint so we have no way // of controlling opacity using the current paint attributes. // Although, examination of the |mode| might find some predictable // cases. UpdateLayerOpacityCompatibility(false); UpdateLayerResult(result); // Even though we already eliminated opacity peephole optimization // due to the color issues identified above, drawVertices also fails // based on the fact that the vertices are rendered independently // so we cannot guarantee the non-overlapping condition. We record // both conditions in case a solution is found to applying the // colors above - both conditions must be analyzed sufficiently // and implemented accordingly before drawVertices is compatible with // opacity peephole optimizations. current_layer().layer_local_accumulator.record_overlapping_bounds(); }}void DisplayListBuilder::DrawVertices( const std::shared_ptr<DlVertices>& vertices, DlBlendMode mode, const DlPaint& paint) { SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawVerticesFlags); drawVertices(vertices, mode);}
void DisplayListBuilder::drawImage(const sk_sp<DlImage> image, const DlPoint& point, DlImageSampling sampling, bool render_with_attributes) { DisplayListAttributeFlags flags = render_with_attributes // ? kDrawImageWithPaintFlags : kDrawImageFlags; OpResult result = PaintResult(current_, flags); if (result == OpResult::kNoEffect) { return; } DlRect bounds = DlRect::MakeXYWH(point.x, point.y, // image->width(), image->height()); if (AccumulateOpBounds(bounds, flags)) { render_with_attributes ? Push<DrawImageWithAttrOp>(0, image, point, sampling) : Push<DrawImageOp>(0, image, point, sampling); CheckLayerOpacityCompatibility(render_with_attributes); UpdateLayerResult(result, render_with_attributes); is_ui_thread_safe_ = is_ui_thread_safe_ && image->isUIThreadSafe(); }}void DisplayListBuilder::DrawImage(const sk_sp<DlImage>& image, const DlPoint& point, DlImageSampling sampling, const DlPaint* paint) { if (paint != nullptr) { SetAttributesFromPaint(*paint, DisplayListOpFlags::kDrawImageWithPaintFlags); drawImage(image, point, sampling, true); } else { drawImage(image, point, sampling, false); }}void DisplayListBuilder::drawImageRect(const sk_sp<DlImage> image, const DlRect& src, const DlRect& dst, DlImageSampling sampling, bool render_with_attributes, DlSrcRectConstraint constraint) { DisplayListAttributeFlags flags = render_with_attributes ? kDrawImageRectWithPaintFlags : kDrawImageRectFlags; OpResult result = PaintResult(current_, flags); if (result != OpResult::kNoEffect && AccumulateOpBounds(dst, flags)) { Push<DrawImageRectOp>(0, image, src, dst, sampling, render_with_attributes, constraint); CheckLayerOpacityCompatibility(render_with_attributes); UpdateLayerResult(result, render_with_attributes); is_ui_thread_safe_ = is_ui_thread_safe_ && image->isUIThreadSafe(); }}void DisplayListBuilder::DrawImageRect(const sk_sp<DlImage>& image, const DlRect& src, const DlRect& dst, DlImageSampling sampling, const DlPaint* paint, DlSrcRectConstraint constraint) { if (paint != nullptr) { SetAttributesFromPaint(*paint, DisplayListOpFlags::kDrawImageRectWithPaintFlags); drawImageRect(image, src, dst, sampling, true, constraint); } else { drawImageRect(image, src, dst, sampling, false, constraint); }}void DisplayListBuilder::drawImageNine(const sk_sp<DlImage> image, const DlIRect& center, const DlRect& dst, DlFilterMode filter, bool render_with_attributes) { DisplayListAttributeFlags flags = render_with_attributes ? kDrawImageNineWithPaintFlags : kDrawImageNineFlags; OpResult result = PaintResult(current_, flags); if (result != OpResult::kNoEffect && AccumulateOpBounds(dst, flags)) { render_with_attributes ? Push<DrawImageNineWithAttrOp>(0, image, center, dst, filter) : Push<DrawImageNineOp>(0, image, center, dst, filter); CheckLayerOpacityCompatibility(render_with_attributes); UpdateLayerResult(result, render_with_attributes); is_ui_thread_safe_ = is_ui_thread_safe_ && image->isUIThreadSafe(); }}void DisplayListBuilder::DrawImageNine(const sk_sp<DlImage>& image, const DlIRect& center, const DlRect& dst, DlFilterMode filter, const DlPaint* paint) { if (paint != nullptr) { SetAttributesFromPaint(*paint, DisplayListOpFlags::kDrawImageNineWithPaintFlags); drawImageNine(image, center, dst, filter, true); } else { drawImageNine(image, center, dst, filter, false); }}void DisplayListBuilder::drawAtlas(const sk_sp<DlImage> atlas, const DlRSTransform xform[], const DlRect tex[], const DlColor colors[], int count, DlBlendMode mode, DlImageSampling sampling, const DlRect* cull_rect, bool render_with_attributes) { DisplayListAttributeFlags flags = render_with_attributes // ? kDrawAtlasWithPaintFlags : kDrawAtlasFlags; OpResult result = PaintResult(current_, flags); if (result == OpResult::kNoEffect) { return; } DlQuad quad; AccumulationRect accumulator; for (int i = 0; i < count; i++) { const DlRect& src = tex[i]; xform[i].GetQuad(src.GetWidth(), src.GetHeight(), quad); for (int j = 0; j < 4; j++) { accumulator.accumulate(quad[j]); } } if (accumulator.is_empty() || !AccumulateOpBounds(accumulator.GetBounds(), flags)) { return; }
// Accumulating the bounds might not trip the overlap condition if the // whole atlas operation is separated from other rendering calls, but // since each atlas op is treated as an independent operation, we have // to pass along our locally computed overlap condition for the individual // atlas operations to the layer accumulator. // Note that the above accumulation may falsely trigger the overlapping // state as it is done quad corner by quad corner and an entire quad may // be non-overlapping with the layer bounds, but as we add each point // independently it might expand the bounds on one corner and then flag // the condition when the next corner is added. if (accumulator.overlap_detected()) { current_layer().layer_local_accumulator.record_overlapping_bounds(); }
int bytes = count * (sizeof(DlRSTransform) + sizeof(DlRect)); void* data_ptr; if (colors != nullptr) { bytes += count * sizeof(DlColor); if (cull_rect != nullptr) { data_ptr = Push<DrawAtlasCulledOp>(bytes, atlas, count, mode, sampling, true, *cull_rect, render_with_attributes); } else { data_ptr = Push<DrawAtlasOp>(bytes, atlas, count, mode, sampling, true, render_with_attributes); } CopyV(data_ptr, xform, count, tex, count, colors, count); } else { if (cull_rect != nullptr) { data_ptr = Push<DrawAtlasCulledOp>(bytes, atlas, count, mode, sampling, false, *cull_rect, render_with_attributes); } else { data_ptr = Push<DrawAtlasOp>(bytes, atlas, count, mode, sampling, false, render_with_attributes); } CopyV(data_ptr, xform, count, tex, count); } // drawAtlas treats each image as a separate operation so we cannot rely // on it to distribute the opacity without overlap without checking all // of the transforms and texture rectangles. UpdateLayerOpacityCompatibility(false); UpdateLayerResult(result, render_with_attributes); is_ui_thread_safe_ = is_ui_thread_safe_ && atlas->isUIThreadSafe();}void DisplayListBuilder::DrawAtlas(const sk_sp<DlImage>& atlas, const DlRSTransform xform[], const DlRect tex[], const DlColor colors[], int count, DlBlendMode mode, DlImageSampling sampling, const DlRect* cull_rect, const DlPaint* paint) { if (paint != nullptr) { SetAttributesFromPaint(*paint, DisplayListOpFlags::kDrawAtlasWithPaintFlags); drawAtlas(atlas, xform, tex, colors, count, mode, sampling, cull_rect, true); } else { drawAtlas(atlas, xform, tex, colors, count, mode, sampling, cull_rect, false); }}
void DisplayListBuilder::DrawDisplayList(const sk_sp<DisplayList> display_list, DlScalar opacity) { if (!std::isfinite(opacity) || opacity <= SK_ScalarNearlyZero || display_list->op_count() == 0 || display_list->bounds().isEmpty() || current_info().is_nop) { return; } const DlRect bounds = display_list->GetBounds(); bool accumulated; sk_sp<const DlRTree> rtree; if (display_list->root_is_unbounded()) { accumulated = AccumulateUnbounded(); } else if (!rtree_data_.has_value() || !(rtree = display_list->rtree())) { accumulated = AccumulateOpBounds(bounds, kDrawDisplayListFlags); } else { std::list<DlRect> rects = rtree->searchAndConsolidateRects(GetLocalClipCoverage(), false); accumulated = false; for (const DlRect& rect : rects) { // TODO (https://github.com/flutter/flutter/issues/114919): Attributes // are not necessarily `kDrawDisplayListFlags`. if (AccumulateOpBounds(rect, kDrawDisplayListFlags)) { accumulated = true; } } } if (!accumulated) { return; }
DlPaint current_paint = current_; Push<DrawDisplayListOp>(0, display_list, opacity < SK_Scalar1 ? opacity : SK_Scalar1);
// This depth increment accounts for every draw call in the child // DisplayList and is in addition to the implicit depth increment // that was performed when we pushed the DrawDisplayListOp. The // eventual dispatcher can use or ignore the implicit depth increment // as it sees fit depending on whether it needs to do rendering // before or after the drawDisplayList op, but it must be accounted // for if the depth value accounting is to remain consistent between // the recording and dispatching process. depth_ += display_list->total_depth();
is_ui_thread_safe_ = is_ui_thread_safe_ && display_list->isUIThreadSafe(); // Not really necessary if the developer is interacting with us via // our attribute-state-less DlCanvas methods, but this avoids surprises // for those who may have been using the stateful Dispatcher methods. SetAttributesFromPaint(current_paint, DisplayListOpFlags::kSaveLayerWithPaintFlags);
// The non-nested op count accumulated in the |Push| method will include // this call to |drawDisplayList| for non-nested op count metrics. // But, for nested op count metrics we want the |drawDisplayList| call itself // to be transparent. So we subtract 1 from our accumulated nested count to // balance out against the 1 that was accumulated into the regular count. // This behavior is identical to the way SkPicture computed nested op counts. nested_op_count_ += display_list->op_count(true) - 1; nested_bytes_ += display_list->bytes(true); UpdateLayerOpacityCompatibility(display_list->can_apply_group_opacity()); // Nop DisplayLists are eliminated above so we either affect transparent // pixels or we do not. We should not have [kNoEffect]. UpdateLayerResult(display_list->modifies_transparent_black() ? OpResult::kAffectsAll : OpResult::kPreservesTransparency, display_list->max_root_blend_mode()); if (display_list->root_has_backdrop_filter()) { current_layer().contains_backdrop_filter = true; }}void DisplayListBuilder::drawTextBlob(const sk_sp<SkTextBlob> blob, DlScalar x, DlScalar y) { DisplayListAttributeFlags flags = kDrawTextBlobFlags; OpResult result = PaintResult(current_, flags); if (result == OpResult::kNoEffect) { return; } DlRect bounds = ToDlRect(blob->bounds().makeOffset(x, y)); bool unclipped = AccumulateOpBounds(bounds, flags); // TODO(https://github.com/flutter/flutter/issues/82202): Remove once the // unit tests can use Fuchsia's font manager instead of the empty default. // Until then we might encounter empty bounds for otherwise valid text and // thus we ignore the results from AccumulateOpBounds.#if defined(OS_FUCHSIA) unclipped = true;#endif // OS_FUCHSIA if (unclipped) { Push<DrawTextBlobOp>(0, blob, x, y); // There is no way to query if the glyphs of a text blob overlap and // there are no current guarantees from either Skia or Impeller that // they will protect overlapping glyphs from the effects of overdraw // so we must make the conservative assessment that this DL layer is // not compatible with group opacity inheritance. UpdateLayerOpacityCompatibility(false); UpdateLayerResult(result); }}void DisplayListBuilder::DrawTextBlob(const sk_sp<SkTextBlob>& blob, DlScalar x, DlScalar y, const DlPaint& paint) { SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawTextBlobFlags); drawTextBlob(blob, x, y);}
void DisplayListBuilder::drawTextFrame( const std::shared_ptr<impeller::TextFrame>& text_frame, DlScalar x, DlScalar y) { DisplayListAttributeFlags flags = kDrawTextBlobFlags; OpResult result = PaintResult(current_, flags); if (result == OpResult::kNoEffect) { return; } DlRect bounds = text_frame->GetBounds().Shift(x, y); bool unclipped = AccumulateOpBounds(bounds, flags); // TODO(https://github.com/flutter/flutter/issues/82202): Remove once the // unit tests can use Fuchsia's font manager instead of the empty default. // Until then we might encounter empty bounds for otherwise valid text and // thus we ignore the results from AccumulateOpBounds.#if defined(OS_FUCHSIA) unclipped = true;#endif // OS_FUCHSIA if (unclipped) { Push<DrawTextFrameOp>(0, text_frame, x, y); // There is no way to query if the glyphs of a text blob overlap and // there are no current guarantees from either Skia or Impeller that // they will protect overlapping glyphs from the effects of overdraw // so we must make the conservative assessment that this DL layer is // not compatible with group opacity inheritance. UpdateLayerOpacityCompatibility(false); UpdateLayerResult(result); }}
void DisplayListBuilder::DrawTextFrame( const std::shared_ptr<impeller::TextFrame>& text_frame, DlScalar x, DlScalar y, const DlPaint& paint) { SetAttributesFromPaint(paint, DisplayListOpFlags::kDrawTextBlobFlags); drawTextFrame(text_frame, x, y);}
void DisplayListBuilder::DrawShadow(const DlPath& path, const DlColor color, const DlScalar elevation, bool transparent_occluder, DlScalar dpr) { OpResult result = PaintResult(DlPaint(color)); if (result != OpResult::kNoEffect) { DlRect shadow_bounds = DlCanvas::ComputeShadowBounds(path, elevation, dpr, GetMatrix()); if (AccumulateOpBounds(shadow_bounds, kDrawShadowFlags)) { transparent_occluder // ? Push<DrawShadowTransparentOccluderOp>(0, path, color, elevation, dpr) : Push<DrawShadowOp>(0, path, color, elevation, dpr); UpdateLayerOpacityCompatibility(false); UpdateLayerResult(result, DlBlendMode::kSrcOver); } }}
bool DisplayListBuilder::AdjustBoundsForPaint(DlRect& bounds, DisplayListAttributeFlags flags) { if (flags.ignores_paint()) { return true; }
if (flags.is_geometric()) { bool is_stroked = flags.is_stroked(current_.getDrawStyle());
// Path effect occurs before stroking... DisplayListSpecialGeometryFlags special_flags = flags.GeometryFlags(is_stroked);
if (is_stroked) { // Determine the max multiplier to the stroke width first. DlScalar pad = 1.0f; if (current_.getStrokeJoin() == DlStrokeJoin::kMiter && special_flags.may_have_acute_joins()) { pad = std::max(pad, current_.getStrokeMiter()); } if (current_.getStrokeCap() == DlStrokeCap::kSquare && special_flags.may_have_diagonal_caps()) { pad = std::max(pad, SK_ScalarSqrt2); } DlScalar min_stroke_width = 0.01; pad *= std::max(current_.getStrokeWidth() * 0.5f, min_stroke_width); bounds = bounds.Expand(pad, pad); } }
if (flags.applies_mask_filter()) { auto filter = current_.getMaskFilter(); if (filter) { switch (filter->type()) { case DlMaskFilterType::kBlur: { FML_DCHECK(filter->asBlur()); DlScalar mask_sigma_pad = filter->asBlur()->sigma() * 3.0; bounds = bounds.Expand(mask_sigma_pad, mask_sigma_pad); } } } }
// Color filter does not modify bounds even if it affects transparent // black because it is clipped by the "mask" of the primitive. That // property only comes into play when it is applied to something like // a layer.
if (flags.applies_image_filter()) { auto filter = current_.getImageFilterPtr(); if (filter) { DlRect dl_bounds; if (!filter->map_local_bounds(bounds, dl_bounds)) { return false; } bounds = dl_bounds; } }
return true;}
bool DisplayListBuilder::AccumulateUnbounded(const SaveInfo& save) { if (!save.has_valid_clip) { save.layer_info->is_unbounded = true; } DlRect global_clip = save.global_state.GetDeviceCullCoverage(); DlRect layer_clip = save.global_state.GetLocalCullCoverage(); if (global_clip.IsEmpty() || !save.layer_state.mapAndClipRect(&layer_clip)) { return false; } if (rtree_data_.has_value()) { FML_DCHECK(save.layer_info->global_space_accumulator.is_empty()); rtree_data_->rects.push_back(global_clip); rtree_data_->indices.push_back(op_index_); } else { save.layer_info->global_space_accumulator.accumulate(global_clip); } save.layer_info->layer_local_accumulator.accumulate(layer_clip); return true;}
bool DisplayListBuilder::AccumulateOpBounds(DlRect& bounds, DisplayListAttributeFlags flags) { if (AdjustBoundsForPaint(bounds, flags)) { return AccumulateBounds(bounds); } else { return AccumulateUnbounded(); }}
bool DisplayListBuilder::AccumulateBounds(const DlRect& bounds, SaveInfo& layer, int id) { if (bounds.IsEmpty()) { return false; } DlRect global_bounds; DlRect layer_bounds; if (!layer.global_state.mapAndClipRect(bounds, &global_bounds) || !layer.layer_state.mapAndClipRect(bounds, &layer_bounds)) { return false; } if (rtree_data_.has_value()) { FML_DCHECK(layer.layer_info->global_space_accumulator.is_empty()); if (id >= 0) { rtree_data_->rects.push_back(global_bounds); rtree_data_->indices.push_back(id); } } else { layer.layer_info->global_space_accumulator.accumulate(global_bounds); } layer.layer_info->layer_local_accumulator.accumulate(layer_bounds); return true;}
bool DisplayListBuilder::SaveInfo::AccumulateBoundsLocal(const DlRect& bounds) { if (bounds.IsEmpty()) { return false; } DlRect local_bounds; if (!layer_state.mapAndClipRect(bounds, &local_bounds)) { return false; } layer_info->layer_local_accumulator.accumulate(local_bounds); return true;}
bool DisplayListBuilder::paint_nops_on_transparency() { // SkImageFilter::canComputeFastBounds tests for transparency behavior // This test assumes that the blend mode checked down below will // NOP on transparent black. if (current_.getImageFilterPtr() && current_.getImageFilterPtr()->modifies_transparent_black()) { return false; }
// We filter the transparent black that is used for the background of a // saveLayer and make sure it returns transparent black. If it does, then // the color filter will leave all area surrounding the contents of the // save layer untouched out to the edge of the output surface. // This test assumes that the blend mode checked down below will // NOP on transparent black. if (current_.getColorFilterPtr() && current_.getColorFilterPtr()->modifies_transparent_black()) { return false; }
// Unusual blendmodes require us to process a saved layer // even with operations outside the clip. // For example, DstIn is used by masking layers. // https://code.google.com/p/skia/issues/detail?id=1291 // https://crbug.com/401593 switch (current_.getBlendMode()) { // For each of the following transfer modes, if the source // alpha is zero (our transparent black), the resulting // blended pixel is not necessarily equal to the original // destination pixel. // Mathematically, any time in the following equations where // the result is not d assuming source is 0 case DlBlendMode::kClear: // r = 0 case DlBlendMode::kSrc: // r = s case DlBlendMode::kSrcIn: // r = s * da case DlBlendMode::kDstIn: // r = d * sa case DlBlendMode::kSrcOut: // r = s * (1-da) case DlBlendMode::kDstATop: // r = d*sa + s*(1-da) case DlBlendMode::kModulate: // r = s*d return false; break;
// And in these equations, the result must be d if the // source is 0 case DlBlendMode::kDst: // r = d case DlBlendMode::kSrcOver: // r = s + (1-sa)*d case DlBlendMode::kDstOver: // r = d + (1-da)*s case DlBlendMode::kDstOut: // r = d * (1-sa) case DlBlendMode::kSrcATop: // r = s*da + d*(1-sa) case DlBlendMode::kXor: // r = s*(1-da) + d*(1-sa) case DlBlendMode::kPlus: // r = min(s + d, 1) case DlBlendMode::kScreen: // r = s + d - s*d case DlBlendMode::kOverlay: // multiply or screen, depending on dest case DlBlendMode::kDarken: // rc = s + d - max(s*da, d*sa), // ra = kSrcOver case DlBlendMode::kLighten: // rc = s + d - min(s*da, d*sa), // ra = kSrcOver case DlBlendMode::kColorDodge: // brighten destination to reflect source case DlBlendMode::kColorBurn: // darken destination to reflect source case DlBlendMode::kHardLight: // multiply or screen, depending on source case DlBlendMode::kSoftLight: // lighten or darken, depending on source case DlBlendMode::kDifference: // rc = s + d - 2*(min(s*da, d*sa)), // ra = kSrcOver case DlBlendMode::kExclusion: // rc = s + d - two(s*d), ra = kSrcOver case DlBlendMode::kMultiply: // r = s*(1-da) + d*(1-sa) + s*d case DlBlendMode::kHue: // ra = kSrcOver case DlBlendMode::kSaturation: // ra = kSrcOver case DlBlendMode::kColor: // ra = kSrcOver case DlBlendMode::kLuminosity: // ra = kSrcOver return true; break; }}
DlColor DisplayListBuilder::GetEffectiveColor(const DlPaint& paint, DisplayListAttributeFlags flags) { DlColor color; if (flags.applies_color()) { const DlColorSource* source = paint.getColorSourcePtr(); if (source) { // Suspecting that we need to modulate the ColorSource color by the // color property, see https://github.com/flutter/flutter/issues/159507 color = source->is_opaque() ? DlColor::kBlack() : kAnyColor; } else { color = paint.getColor(); } } else if (flags.applies_alpha()) { // If the operation applies alpha, but not color, then the only impact // of the alpha is to modulate the output towards transparency. // We can not guarantee an opaque source even if the alpha is opaque // since that would require knowing something about the colors that // the alpha is modulating, but we can guarantee a transparent source // if the alpha is 0. color = (paint.getAlpha() == 0) ? DlColor::kTransparent() : kAnyColor; } else { color = kAnyColor; } if (flags.applies_image_filter()) { auto filter = paint.getImageFilterPtr(); if (filter) { if (!color.isTransparent() || filter->modifies_transparent_black()) { color = kAnyColor; } } } if (flags.applies_color_filter()) { auto filter = paint.getColorFilterPtr(); if (filter) { if (!color.isTransparent() || filter->modifies_transparent_black()) { color = kAnyColor; } } } return color;}
DisplayListBuilder::OpResult DisplayListBuilder::PaintResult( const DlPaint& paint, DisplayListAttributeFlags flags) { if (current_info().is_nop) { return OpResult::kNoEffect; } if (flags.applies_blend()) { switch (paint.getBlendMode()) { // Nop blend mode (singular, there is only one) case DlBlendMode::kDst: return OpResult::kNoEffect;
// Always clears pixels blend mode (singular, there is only one) case DlBlendMode::kClear: return OpResult::kPreservesTransparency;
case DlBlendMode::kHue: case DlBlendMode::kSaturation: case DlBlendMode::kColor: case DlBlendMode::kLuminosity: case DlBlendMode::kColorBurn: return GetEffectiveColor(paint, flags).isTransparent() ? OpResult::kNoEffect : OpResult::kAffectsAll;
// kSrcIn modifies pixels towards transparency case DlBlendMode::kSrcIn: return OpResult::kPreservesTransparency;
// These blend modes preserve destination alpha case DlBlendMode::kSrcATop: case DlBlendMode::kDstOut: return GetEffectiveColor(paint, flags).isTransparent() ? OpResult::kNoEffect : OpResult::kPreservesTransparency;
// Always destructive blend modes, potentially not affecting transparency case DlBlendMode::kSrc: case DlBlendMode::kSrcOut: case DlBlendMode::kDstATop: return GetEffectiveColor(paint, flags).isTransparent() ? OpResult::kPreservesTransparency : OpResult::kAffectsAll;
// The kDstIn blend mode modifies the destination unless the // source color is opaque. case DlBlendMode::kDstIn: return GetEffectiveColor(paint, flags).isOpaque() ? OpResult::kNoEffect : OpResult::kPreservesTransparency;
// The next group of blend modes modifies the destination unless the // source color is transparent. case DlBlendMode::kSrcOver: case DlBlendMode::kDstOver: case DlBlendMode::kXor: case DlBlendMode::kPlus: case DlBlendMode::kScreen: case DlBlendMode::kMultiply: case DlBlendMode::kOverlay: case DlBlendMode::kDarken: case DlBlendMode::kLighten: case DlBlendMode::kColorDodge: case DlBlendMode::kHardLight: case DlBlendMode::kSoftLight: case DlBlendMode::kDifference: case DlBlendMode::kExclusion: return GetEffectiveColor(paint, flags).isTransparent() ? OpResult::kNoEffect : OpResult::kAffectsAll;
// Modulate only leaves the pixel alone when the source is white. case DlBlendMode::kModulate: return GetEffectiveColor(paint, flags) == DlColor::kWhite() ? OpResult::kNoEffect : OpResult::kPreservesTransparency; } } return OpResult::kAffectsAll;}
} // namespace flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#ifndef FLUTTER_DISPLAY_LIST_DL_BUILDER_H_#define FLUTTER_DISPLAY_LIST_DL_BUILDER_H_
#include "flutter/display_list/display_list.h"#include "flutter/display_list/dl_blend_mode.h"#include "flutter/display_list/dl_canvas.h"#include "flutter/display_list/dl_op_flags.h"#include "flutter/display_list/dl_op_receiver.h"#include "flutter/display_list/dl_paint.h"#include "flutter/display_list/dl_sampling_options.h"#include "flutter/display_list/geometry/dl_geometry_types.h"#include "flutter/display_list/image/dl_image.h"#include "flutter/display_list/utils/dl_accumulation_rect.h"#include "flutter/display_list/utils/dl_comparable.h"#include "flutter/display_list/utils/dl_matrix_clip_tracker.h"#include "flutter/fml/macros.h"
namespace flutter {
// The primary class used to build a display list. The list of methods// here matches the list of methods invoked on a |DlOpReceiver| combined// with the list of methods invoked on a |DlCanvas|.class DisplayListBuilder final : public virtual DlCanvas, public SkRefCnt, virtual DlOpReceiver, DisplayListOpFlags { public: static constexpr DlRect kMaxCullRect = DlRect::MakeLTRB(-1E9F, -1E9F, 1E9F, 1E9F);
explicit DisplayListBuilder(bool prepare_rtree) : DisplayListBuilder(kMaxCullRect, prepare_rtree) {}
explicit DisplayListBuilder(const DlRect& cull_rect = kMaxCullRect, bool prepare_rtree = false);
DisplayListBuilder(DlScalar width, DlScalar height) : DisplayListBuilder(DlRect::MakeWH(width, height)) {}
~DisplayListBuilder();
// |DlCanvas| DlISize GetBaseLayerDimensions() const override; // |DlCanvas| SkImageInfo GetImageInfo() const override;
// |DlCanvas| void Save() override;
// |DlCanvas| void SaveLayer(const std::optional<DlRect>& bounds, const DlPaint* paint = nullptr, const DlImageFilter* backdrop = nullptr, std::optional<int64_t> backdrop_id = std::nullopt) override; // |DlCanvas| void Restore() override; // |DlCanvas| int GetSaveCount() const override { return save_stack_.size(); } // |DlCanvas| void RestoreToCount(int restore_count) override;
// |DlCanvas| void Translate(DlScalar tx, DlScalar ty) override; // |DlCanvas| void Scale(DlScalar sx, DlScalar sy) override; // |DlCanvas| void Rotate(DlScalar degrees) override; // |DlCanvas| void Skew(DlScalar sx, DlScalar sy) override;
// clang-format off // 2x3 2D affine subset of a 4x4 transform in row major order // |DlCanvas| void Transform2DAffine(DlScalar mxx, DlScalar mxy, DlScalar mxt, DlScalar myx, DlScalar myy, DlScalar myt) override; // full 4x4 transform in row major order // |DlCanvas| void TransformFullPerspective( DlScalar mxx, DlScalar mxy, DlScalar mxz, DlScalar mxt, DlScalar myx, DlScalar myy, DlScalar myz, DlScalar myt, DlScalar mzx, DlScalar mzy, DlScalar mzz, DlScalar mzt, DlScalar mwx, DlScalar mwy, DlScalar mwz, DlScalar mwt) override; // clang-format on // |DlCanvas| void TransformReset() override; // |DlCanvas| void Transform(const DlMatrix& matrix) override; // |DlCanvas| void SetTransform(const DlMatrix& matrix) override { TransformReset(); Transform(matrix); }
/// Returns the 4x4 full perspective transform representing all transform /// operations executed so far in this DisplayList within the enclosing /// save stack. // |DlCanvas| DlMatrix GetMatrix() const override { return global_state().matrix(); }
// |DlCanvas| void ClipRect(const DlRect& rect, DlClipOp clip_op = DlClipOp::kIntersect, bool is_aa = false) override; // |DlCanvas| void ClipOval(const DlRect& bounds, DlClipOp clip_op = DlClipOp::kIntersect, bool is_aa = false) override; // |DlCanvas| void ClipRoundRect(const DlRoundRect& rrect, DlClipOp clip_op = DlClipOp::kIntersect, bool is_aa = false) override; // |DlCanvas| void ClipRoundSuperellipse(const DlRoundSuperellipse& rse, DlClipOp clip_op = DlClipOp::kIntersect, bool is_aa = false) override; // |DlCanvas| void ClipPath(const DlPath& path, DlClipOp clip_op = DlClipOp::kIntersect, bool is_aa = false) override;
/// Conservative estimate of the bounds of all outstanding clip operations /// measured in the coordinate space within which this DisplayList will /// be rendered. // |DlCanvas| DlRect GetDestinationClipCoverage() const override { return global_state().GetDeviceCullCoverage(); } /// Conservative estimate of the bounds of all outstanding clip operations /// transformed into the local coordinate space in which currently /// recorded rendering operations are interpreted. // |DlCanvas| DlRect GetLocalClipCoverage() const override { return global_state().GetLocalCullCoverage(); }
/// Return true iff the supplied bounds are easily shown to be outside /// of the current clip bounds. This method may conservatively return /// false if it cannot make the determination. // |DlCanvas| bool QuickReject(const DlRect& bounds) const override;
// |DlCanvas| void DrawPaint(const DlPaint& paint) override; // |DlCanvas| void DrawColor(DlColor color, DlBlendMode mode) override; // |DlCanvas| void DrawLine(const DlPoint& p0, const DlPoint& p1, const DlPaint& paint) override; // |DlCanvas| void DrawDashedLine(const DlPoint& p0, const DlPoint& p1, DlScalar on_length, DlScalar off_length, const DlPaint& paint) override; // |DlCanvas| void DrawRect(const DlRect& rect, const DlPaint& paint) override; // |DlCanvas| void DrawOval(const DlRect& bounds, const DlPaint& paint) override; // |DlCanvas| void DrawCircle(const DlPoint& center, DlScalar radius, const DlPaint& paint) override; // |DlCanvas| void DrawRoundRect(const DlRoundRect& rrect, const DlPaint& paint) override; // |DlCanvas| void DrawDiffRoundRect(const DlRoundRect& outer, const DlRoundRect& inner, const DlPaint& paint) override; // |DlCanvas| void DrawRoundSuperellipse(const DlRoundSuperellipse& rse, const DlPaint& paint) override; // |DlCanvas| void DrawPath(const DlPath& path, const DlPaint& paint) override; // |DlCanvas| void DrawArc(const DlRect& bounds, DlScalar start, DlScalar sweep, bool useCenter, const DlPaint& paint) override; // |DlCanvas| void DrawPoints(DlPointMode mode, uint32_t count, const DlPoint pts[], const DlPaint& paint) override; // |DlCanvas| void DrawVertices(const std::shared_ptr<DlVertices>& vertices, DlBlendMode mode, const DlPaint& paint) override; // |DlCanvas| void DrawImage(const sk_sp<DlImage>& image, const DlPoint& point, DlImageSampling sampling, const DlPaint* paint = nullptr) override; // |DlCanvas| void DrawImageRect( const sk_sp<DlImage>& image, const DlRect& src, const DlRect& dst, DlImageSampling sampling, const DlPaint* paint = nullptr, DlSrcRectConstraint constraint = DlSrcRectConstraint::kFast) override; // include overloads from the virtual base class using DlCanvas::DrawImageRect;
// |DlCanvas| void DrawImageNine(const sk_sp<DlImage>& image, const DlIRect& center, const DlRect& dst, DlFilterMode filter, const DlPaint* paint = nullptr) override; // |DlCanvas| void DrawAtlas(const sk_sp<DlImage>& atlas, const DlRSTransform xform[], const DlRect tex[], const DlColor colors[], int count, DlBlendMode mode, DlImageSampling sampling, const DlRect* cullRect, const DlPaint* paint = nullptr) override; // |DlCanvas| void DrawDisplayList(const sk_sp<DisplayList> display_list, DlScalar opacity = SK_Scalar1) override; // |DlCanvas| void DrawTextBlob(const sk_sp<SkTextBlob>& blob, DlScalar x, DlScalar y, const DlPaint& paint) override;
void drawTextFrame(const std::shared_ptr<impeller::TextFrame>& text_frame, DlScalar x, DlScalar y) override;
void DrawTextFrame(const std::shared_ptr<impeller::TextFrame>& text_frame, DlScalar x, DlScalar y, const DlPaint& paint) override;
// |DlCanvas| void DrawShadow(const DlPath& path, const DlColor color, const DlScalar elevation, bool transparent_occluder, DlScalar dpr) override;
// |DlCanvas| void Flush() override {}
sk_sp<DisplayList> Build();
private: void Init(bool prepare_rtree);
// This method exposes the internal stateful DlOpReceiver implementation // of the DisplayListBuilder, primarily for testing purposes. Its use // is obsolete and forbidden in every other case and is only shared to a // pair of "friend" accessors in the benchmark/unittest files. DlOpReceiver& asReceiver() { return *this; }
friend DlOpReceiver& DisplayListBuilderBenchmarkAccessor( DisplayListBuilder& builder); friend DlOpReceiver& DisplayListBuilderTestingAccessor( DisplayListBuilder& builder); friend DlPaint DisplayListBuilderTestingAttributes( DisplayListBuilder& builder); friend int DisplayListBuilderTestingLastOpIndex(DisplayListBuilder& builder);
void SetAttributesFromPaint(const DlPaint& paint, const DisplayListAttributeFlags flags);
// |DlOpReceiver| void setAntiAlias(bool aa) override { if (current_.isAntiAlias() != aa) { onSetAntiAlias(aa); } } // |DlOpReceiver| void setInvertColors(bool invert) override { if (current_.isInvertColors() != invert) { onSetInvertColors(invert); } } // |DlOpReceiver| void setStrokeCap(DlStrokeCap cap) override { if (current_.getStrokeCap() != cap) { onSetStrokeCap(cap); } } // |DlOpReceiver| void setStrokeJoin(DlStrokeJoin join) override { if (current_.getStrokeJoin() != join) { onSetStrokeJoin(join); } } // |DlOpReceiver| void setDrawStyle(DlDrawStyle style) override { if (current_.getDrawStyle() != style) { onSetDrawStyle(style); } } // |DlOpReceiver| void setStrokeWidth(float width) override { if (current_.getStrokeWidth() != width) { onSetStrokeWidth(width); } } // |DlOpReceiver| void setStrokeMiter(float limit) override { if (current_.getStrokeMiter() != limit) { onSetStrokeMiter(limit); } } // |DlOpReceiver| void setColor(DlColor color) override { if (current_.getColor() != color) { onSetColor(color); } } // |DlOpReceiver| void setBlendMode(DlBlendMode mode) override { if (current_.getBlendMode() != mode) { onSetBlendMode(mode); } } // |DlOpReceiver| void setColorSource(const DlColorSource* source) override { if (NotEquals(current_.getColorSource(), source)) { onSetColorSource(source); } } // |DlOpReceiver| void setImageFilter(const DlImageFilter* filter) override { if (NotEquals(current_.getImageFilter(), filter)) { onSetImageFilter(filter); } } // |DlOpReceiver| void setColorFilter(const DlColorFilter* filter) override { if (NotEquals(current_.getColorFilter(), filter)) { onSetColorFilter(filter); } } // |DlOpReceiver| void setMaskFilter(const DlMaskFilter* filter) override { if (NotEquals(current_.getMaskFilter(), filter)) { onSetMaskFilter(filter); } }
DlPaint CurrentAttributes() const { return current_; } int LastOpIndex() const { return op_index_ - 1; }
// |DlOpReceiver| void save() override { Save(); } // Only the |renders_with_attributes()| option will be accepted here. Any // other flags will be ignored and calculated anew as the DisplayList is // built. Alternatively, use the |saveLayer(DlRect, bool)| method. // |DlOpReceiver| void saveLayer(const DlRect& bounds, const SaveLayerOptions options, const DlImageFilter* backdrop, std::optional<int64_t> backdrop_id) override; // |DlOpReceiver| void restore() override { Restore(); }
// |DlOpReceiver| void translate(DlScalar tx, DlScalar ty) override { Translate(tx, ty); } // |DlOpReceiver| void scale(DlScalar sx, DlScalar sy) override { Scale(sx, sy); } // |DlOpReceiver| void rotate(DlScalar degrees) override { Rotate(degrees); } // |DlOpReceiver| void skew(DlScalar sx, DlScalar sy) override { Skew(sx, sy); }
// clang-format off // |DlOpReceiver| void transform2DAffine(DlScalar mxx, DlScalar mxy, DlScalar mxt, DlScalar myx, DlScalar myy, DlScalar myt) override { Transform2DAffine(mxx, mxy, mxt, myx, myy, myt); } // |DlOpReceiver| void transformFullPerspective( DlScalar mxx, DlScalar mxy, DlScalar mxz, DlScalar mxt, DlScalar myx, DlScalar myy, DlScalar myz, DlScalar myt, DlScalar mzx, DlScalar mzy, DlScalar mzz, DlScalar mzt, DlScalar mwx, DlScalar mwy, DlScalar mwz, DlScalar mwt) override { TransformFullPerspective(mxx, mxy, mxz, mxt, myx, myy, myz, myt, mzx, mzy, mzz, mzt, mwx, mwy, mwz, mwt); } // clang-format off // |DlOpReceiver| void transformReset() override { TransformReset(); }
// |DlOpReceiver| void clipRect(const DlRect& rect, DlClipOp clip_op, bool is_aa) override { ClipRect(rect, clip_op, is_aa); } // |DlOpReceiver| void clipOval(const DlRect& bounds, DlClipOp clip_op, bool is_aa) override { ClipOval(bounds, clip_op, is_aa); } // |DlOpReceiver| void clipRoundRect(const DlRoundRect& rrect, DlClipOp clip_op, bool is_aa) override { ClipRoundRect(rrect, clip_op, is_aa); } // |DlOpReceiver| void clipRoundSuperellipse(const DlRoundSuperellipse& rse, DlClipOp clip_op, bool is_aa) override { ClipRoundSuperellipse(rse, clip_op, is_aa); } // |DlOpReceiver| void clipPath(const DlPath& path, DlClipOp clip_op, bool is_aa) override { ClipPath(path, clip_op, is_aa); }
// |DlOpReceiver| void drawPaint() override; // |DlOpReceiver| void drawColor(DlColor color, DlBlendMode mode) override { DrawColor(color, mode); } // |DlOpReceiver| void drawLine(const DlPoint& p0, const DlPoint& p1) override; // |DlOpReceiver| void drawDashedLine(const DlPoint& p0, const DlPoint& p1, DlScalar on_length, DlScalar off_length) override; // |DlOpReceiver| void drawRect(const DlRect& rect) override; // |DlOpReceiver| void drawOval(const DlRect& bounds) override; // |DlOpReceiver| void drawCircle(const DlPoint& center, DlScalar radius) override; // |DlOpReceiver| void drawRoundRect(const DlRoundRect& rrect) override; // |DlOpReceiver| void drawDiffRoundRect(const DlRoundRect& outer, const DlRoundRect& inner) override; // |DlOpReceiver| void drawRoundSuperellipse(const DlRoundSuperellipse& rse) override; // |DlOpReceiver| void drawPath(const DlPath& path) override; // |DlOpReceiver| void drawArc(const DlRect& bounds, DlScalar start, DlScalar sweep, bool useCenter) override; // |DlOpReceiver| void drawPoints(DlPointMode mode, uint32_t count, const DlPoint pts[]) override; // |DlOpReceiver| void drawVertices(const std::shared_ptr<DlVertices>& vertices, DlBlendMode mode) override;
// |DlOpReceiver| void drawImage(const sk_sp<DlImage> image, const DlPoint& point, DlImageSampling sampling, bool render_with_attributes) override; // |DlOpReceiver| void drawImageRect( const sk_sp<DlImage> image, const DlRect& src, const DlRect& dst, DlImageSampling sampling, bool render_with_attributes, DlSrcRectConstraint constraint = DlSrcRectConstraint::kFast) override; // |DlOpReceiver| void drawImageNine(const sk_sp<DlImage> image, const DlIRect& center, const DlRect& dst, DlFilterMode filter, bool render_with_attributes) override; // |DlOpReceiver| void drawAtlas(const sk_sp<DlImage> atlas, const DlRSTransform xform[], const DlRect tex[], const DlColor colors[], int count, DlBlendMode mode, DlImageSampling sampling, const DlRect* cullRect, bool render_with_attributes) override;
// |DlOpReceiver| void drawDisplayList(const sk_sp<DisplayList> display_list, DlScalar opacity) override { DrawDisplayList(display_list, opacity); } // |DlOpReceiver| void drawTextBlob(const sk_sp<SkTextBlob> blob, DlScalar x, DlScalar y) override; // |DlOpReceiver| void drawShadow(const DlPath& path, const DlColor color, const DlScalar elevation, bool transparent_occluder, DlScalar dpr) override { DrawShadow(path, color, elevation, transparent_occluder, dpr); }
void checkForDeferredSave();
DisplayListStorage storage_; std::vector<size_t> offsets_; uint32_t render_op_count_ = 0u; uint32_t depth_ = 0u; // Most rendering ops will use 1 depth value, but some attributes may // require an additional depth value (due to implicit saveLayers) uint32_t render_op_depth_cost_ = 1u; DlIndex op_index_ = 0;
// bytes and ops from |drawPicture| and |drawDisplayList| size_t nested_bytes_ = 0; uint32_t nested_op_count_ = 0;
bool is_ui_thread_safe_ = true;
template <typename T, typename... Args> void* Push(size_t extra, Args&&... args);
struct RTreeData { std::vector<DlRect> rects; std::vector<int> indices; };
struct LayerInfo { LayerInfo(const std::shared_ptr<DlImageFilter>& filter, size_t rtree_rects_start_index) : filter(filter), rtree_rects_start_index(rtree_rects_start_index) {}
// The filter that will be applied to the contents of the saveLayer // when it is restored into the parent layer. const std::shared_ptr<DlImageFilter> filter;
// The index of the rtree rects when the saveLayer was called, used // only in the case that the saveLayer has a filter so that the // accumulated rects can be updated in the corresponding restore call. const size_t rtree_rects_start_index = 0;
// The bounds accumulator for the entire DisplayList, relative to its root // (not used when accumulating rects for an rtree, though) AccumulationRect global_space_accumulator;
// The bounds accumulator to set/verify the bounds of the most recently // invoked saveLayer call, relative to the root of that saveLayer AccumulationRect layer_local_accumulator;
DlBlendMode max_blend_mode = DlBlendMode::kClear;
bool opacity_incompatible_op_detected = false; bool affects_transparent_layer = false; bool contains_backdrop_filter = false; bool is_unbounded = false;
bool is_group_opacity_compatible() const { return !opacity_incompatible_op_detected && !layer_local_accumulator.overlap_detected(); }
void update_blend_mode(DlBlendMode mode) { if (max_blend_mode < mode) { max_blend_mode = mode; } } };
// The SaveInfo class stores internal data common to both Save and // SaveLayer calls class SaveInfo { public: // For vector reallocation calls to copy vector data SaveInfo(const SaveInfo& copy) = default; SaveInfo(SaveInfo&& copy) = default;
// For constructor (root layer) initialization explicit SaveInfo(const DlRect& cull_rect) : is_save_layer(true), has_valid_clip(false), global_state(cull_rect), layer_state(cull_rect), layer_info(new LayerInfo(nullptr, 0u)) {}
// For regular save calls: // Passing a pointer to the parent_info so as to distinguish this // call from the copy constructors used during vector reallocations explicit SaveInfo(const SaveInfo* parent_info) : is_save_layer(false), has_deferred_save_op(true), has_valid_clip(parent_info->has_valid_clip), global_state(parent_info->global_state), layer_state(parent_info->layer_state), layer_info(parent_info->layer_info) {}
// For saveLayer calls: explicit SaveInfo(const SaveInfo* parent_info, const std::shared_ptr<DlImageFilter>& filter, int rtree_rect_index) : is_save_layer(true), has_valid_clip(false), global_state(parent_info->global_state), layer_state(kMaxCullRect), layer_info(new LayerInfo(filter, rtree_rect_index)) {}
const bool is_save_layer;
bool has_deferred_save_op = false; bool is_nop = false; bool has_valid_clip;
// The depth when the save call is recorded, used to compute the total // depth of its content when the associated restore is called. uint32_t save_depth = 0;
// The offset into the buffer where the associated save op is recorded // (which is not necessarily the same as when the Save() method is called // due to deferred saves) size_t save_offset = 0;
// The transform and clip accumulated since the root of the DisplayList DisplayListMatrixClipState global_state;
// The transform and clip accumulated since the most recent saveLayer, // used to compute and update its bounds when the restore is called. DisplayListMatrixClipState layer_state;
std::shared_ptr<LayerInfo> layer_info;
// Records the given bounds after transforming by the global and // layer matrices. bool AccumulateBoundsLocal(const DlRect& bounds);
// Simply transfers the local bounds to the parent void TransferBoundsToParent(const SaveInfo& parent); };
const DlRect original_cull_rect_; std::vector<SaveInfo> save_stack_; std::optional<RTreeData> rtree_data_;
DlPaint current_;
// Returns a reference to the SaveInfo structure at the top of the current // save_stack vector. Note that the clip and matrix state can be accessed // more directly through global_state() and layer_state(). SaveInfo& current_info() { return save_stack_.back(); } const SaveInfo& current_info() const { return save_stack_.back(); }
// Returns a reference to the SaveInfo structure just below the top // of the current save_stack state. SaveInfo& parent_info() { return *std::prev(save_stack_.end(), 2); } const SaveInfo& parent_info() const { return *std::prev(save_stack_.end(), 2); }
// Returns a reference to the LayerInfo structure at the top of the current // save_stack vector. Note that the clip and matrix state can be accessed // more directly through global_state() and layer_state(). LayerInfo& current_layer() { return *save_stack_.back().layer_info; } const LayerInfo& current_layer() const { return *save_stack_.back().layer_info; }
// Returns a reference to the LayerInfo structure just below the top // of the current save_stack state. LayerInfo& parent_layer() { return *std::prev(save_stack_.end(), 2)->layer_info; } const LayerInfo& parent_layer() const { return *std::prev(save_stack_.end(), 2)->layer_info; }
// Returns a reference to the matrix and clip state for the entire // DisplayList. The initial transform of this state is identity and // the initial cull_rect is the root original_cull_rect supplied // in the constructor. It is a summary of all transform and clip // calls that have happened since the DisplayList was created // (and have not yet been removed by a restore() call). DisplayListMatrixClipState& global_state() { return current_info().global_state; } const DisplayListMatrixClipState& global_state() const { return current_info().global_state; }
// Returns a reference to the matrix and clip state relative to the // current layer, whether that is defined by the most recent saveLayer // call, or by the initial root state of the entire DisplayList for // calls not surrounded by a saveLayer/restore pair. It is a summary // of only those transform and clip calls that have happened since // the creation of the DisplayList or since the most recent saveLayer // (and have not yet been removed by a restore() call). DisplayListMatrixClipState& layer_local_state() { return current_info().layer_state; } const DisplayListMatrixClipState& layer_local_state() const { return current_info().layer_state; }
void RestoreLayer(); void TransferLayerBounds(const DlRect& content_bounds); bool AdjustRTreeRects(RTreeData& data, const DlImageFilter& filter, const DlMatrix& matrix, const DlRect& clip, size_t rect_index);
// This flag indicates whether or not the current rendering attributes // are compatible with rendering ops applying an inherited opacity. bool current_opacity_compatibility_ = true;
// Returns the compatibility of a given blend mode for applying an // inherited opacity value to modulate the visibility of the op. // For now we only accept SrcOver blend modes but this could be expanded // in the future to include other (rarely used) modes that also modulate // the opacity of a rendering operation at the cost of a switch statement // or lookup table. static bool IsOpacityCompatible(DlBlendMode mode) { return (mode == DlBlendMode::kSrcOver); }
void UpdateCurrentOpacityCompatibility() { current_opacity_compatibility_ = // current_.getColorFilter() == nullptr && // !current_.isInvertColors() && // !current_.usesRuntimeEffect() && // IsOpacityCompatible(current_.getBlendMode()); }
// Update the opacity compatibility flags of the current layer for an op // that has determined its compatibility as indicated by |compatible|. void UpdateLayerOpacityCompatibility(bool compatible) { if (!compatible) { current_layer().opacity_incompatible_op_detected = true; } }
// Check for opacity compatibility for an op that may or may not use the // current rendering attributes as indicated by |uses_blend_attribute|. // If the flag is false then the rendering op will be able to substitute // a default Paint object with the opacity applied using the default SrcOver // blend mode which is always compatible with applying an inherited opacity. void CheckLayerOpacityCompatibility(bool uses_blend_attribute = true) { UpdateLayerOpacityCompatibility(!uses_blend_attribute || current_opacity_compatibility_); }
void CheckLayerOpacityHairlineCompatibility() { UpdateLayerOpacityCompatibility( current_opacity_compatibility_ && (current_.getDrawStyle() == DlDrawStyle::kFill || current_.getStrokeWidth() > 0)); }
// Check for opacity compatibility for an op that ignores the current // attributes and uses the indicated blend |mode| to render to the layer. // This is only used by |drawColor| currently. void CheckLayerOpacityCompatibility(DlBlendMode mode) { UpdateLayerOpacityCompatibility(IsOpacityCompatible(mode)); }
void onSetAntiAlias(bool aa); void onSetInvertColors(bool invert); void onSetStrokeCap(DlStrokeCap cap); void onSetStrokeJoin(DlStrokeJoin join); void onSetDrawStyle(DlDrawStyle style); void onSetStrokeWidth(DlScalar width); void onSetStrokeMiter(DlScalar limit); void onSetColor(DlColor color); void onSetBlendMode(DlBlendMode mode); void onSetColorSource(const DlColorSource* source); void onSetImageFilter(const DlImageFilter* filter); void onSetColorFilter(const DlColorFilter* filter); void onSetMaskFilter(const DlMaskFilter* filter);
static DisplayListAttributeFlags FlagsForPointMode(DlPointMode mode);
enum class OpResult { kNoEffect, kPreservesTransparency, kAffectsAll, };
bool paint_nops_on_transparency(); OpResult PaintResult(const DlPaint& paint, DisplayListAttributeFlags flags = kDrawPaintFlags);
void UpdateLayerResult(OpResult result, DlBlendMode mode) { switch (result) { case OpResult::kNoEffect: case OpResult::kPreservesTransparency: break; case OpResult::kAffectsAll: current_layer().affects_transparent_layer = true; break; } current_layer().update_blend_mode(mode); } void UpdateLayerResult(OpResult result, bool uses_attributes = true) { UpdateLayerResult(result, uses_attributes ? current_.getBlendMode() : DlBlendMode::kSrcOver); }
// kAnyColor is a non-opaque and non-transparent color that will not // trigger any short-circuit tests about the results of a blend. static constexpr DlColor kAnyColor = DlColor::kMidGrey().withAlphaF(0.5f); static_assert(!kAnyColor.isOpaque()); static_assert(!kAnyColor.isTransparent()); static DlColor GetEffectiveColor(const DlPaint& paint, DisplayListAttributeFlags flags);
// Adjusts the indicated bounds for the given flags and returns true if // the calculation was possible, or false if it could not be estimated. bool AdjustBoundsForPaint(DlRect& bounds, DisplayListAttributeFlags flags);
// Records the fact that we encountered an op that either could not // estimate its bounds or that fills all of the destination space. bool AccumulateUnbounded(const SaveInfo& save); bool AccumulateUnbounded() { return AccumulateUnbounded(current_info()); }
// Records the bounds for an op after modifying them according to the // supplied attribute flags and transforming by the current matrix. bool AccumulateOpBounds(const DlRect& bounds, DisplayListAttributeFlags flags) { DlRect safe_bounds = bounds; return AccumulateOpBounds(safe_bounds, flags); }
// Records the bounds for an op after modifying them according to the // supplied attribute flags and transforming by the current matrix // and clipping against the current clip. bool AccumulateOpBounds(DlRect& bounds, DisplayListAttributeFlags flags);
// Records the given bounds after transforming by the current matrix // and clipping against the current clip. bool AccumulateBounds(const DlRect& bounds, SaveInfo& layer, int id); bool AccumulateBounds(const DlRect& bounds) { return AccumulateBounds(bounds, current_info(), op_index_); }};
} // namespace flutter
#endif // FLUTTER_DISPLAY_LIST_DL_BUILDER_H_123456789101112131415161718192021222324// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#include "flutter/display_list/dl_canvas.h"
#include "third_party/skia/include/core/SkPoint3.h"#include "third_party/skia/include/utils/SkShadowUtils.h"
namespace flutter {
DlRect DlCanvas::ComputeShadowBounds(const DlPath& path, float elevation, DlScalar dpr, const DlMatrix& ctm) { SkRect shadow_bounds(path.GetSkBounds()); SkShadowUtils::GetLocalBounds( ToSkMatrix(ctm), path.GetSkPath(), SkPoint3::Make(0, 0, dpr * elevation), SkPoint3::Make(0, -1, 1), kShadowLightRadius / kShadowLightHeight, SkShadowFlags::kDirectionalLight_ShadowFlag, &shadow_bounds); return ToDlRect(shadow_bounds);}
} // namespace flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#ifndef FLUTTER_DISPLAY_LIST_DL_CANVAS_H_#define FLUTTER_DISPLAY_LIST_DL_CANVAS_H_
#include "flutter/display_list/display_list.h"#include "flutter/display_list/dl_blend_mode.h"#include "flutter/display_list/dl_paint.h"#include "flutter/display_list/dl_types.h"#include "flutter/display_list/dl_vertices.h"#include "flutter/display_list/geometry/dl_geometry_types.h"#include "flutter/display_list/geometry/dl_path.h"#include "flutter/display_list/image/dl_image.h"
#include "third_party/skia/include/core/SkTextBlob.h"
#include "impeller/typographer/text_frame.h"
namespace flutter {
//------------------------------------------------------------------------------/// @brief Developer-facing API for rendering anything *within* the engine.////// |DlCanvas| should be used to render anything in the framework classes (i.e./// `lib/ui`), flow and flow layers, embedders, shell, and elsewhere.////// The only state carried by implementations of this interface are the clip/// and transform which are saved and restored by the |save|, |saveLayer|, and/// |restore| calls.////// @note The interface resembles closely the familiar |SkCanvas| interface/// used throughout the engine.class DlCanvas { public: virtual ~DlCanvas() = default;
virtual DlISize GetBaseLayerDimensions() const = 0; virtual SkImageInfo GetImageInfo() const = 0;
virtual void Save() = 0; virtual void SaveLayer(const std::optional<DlRect>& bounds, const DlPaint* paint = nullptr, const DlImageFilter* backdrop = nullptr, std::optional<int64_t> backdrop_id = std::nullopt) = 0; virtual void Restore() = 0; virtual int GetSaveCount() const = 0; virtual void RestoreToCount(int restore_count) = 0;
virtual void Translate(DlScalar tx, DlScalar ty) = 0; virtual void Scale(DlScalar sx, DlScalar sy) = 0; virtual void Rotate(DlScalar degrees) = 0; virtual void Skew(DlScalar sx, DlScalar sy) = 0;
// clang-format off
// 2x3 2D affine subset of a 4x4 transform in row major order virtual void Transform2DAffine(DlScalar mxx, DlScalar mxy, DlScalar mxt, DlScalar myx, DlScalar myy, DlScalar myt) = 0; // full 4x4 transform in row major order virtual void TransformFullPerspective( DlScalar mxx, DlScalar mxy, DlScalar mxz, DlScalar mxt, DlScalar myx, DlScalar myy, DlScalar myz, DlScalar myt, DlScalar mzx, DlScalar mzy, DlScalar mzz, DlScalar mzt, DlScalar mwx, DlScalar mwy, DlScalar mwz, DlScalar mwt) = 0; // clang-format on virtual void TransformReset() = 0; virtual void Transform(const DlMatrix& matrix) = 0; virtual void SetTransform(const DlMatrix& matrix) = 0;
virtual DlMatrix GetMatrix() const = 0;
virtual void ClipRect(const DlRect& rect, DlClipOp clip_op = DlClipOp::kIntersect, bool is_aa = false) = 0; virtual void ClipOval(const DlRect& bounds, DlClipOp clip_op = DlClipOp::kIntersect, bool is_aa = false) = 0; virtual void ClipRoundRect(const DlRoundRect& rrect, DlClipOp clip_op = DlClipOp::kIntersect, bool is_aa = false) = 0; virtual void ClipRoundSuperellipse(const DlRoundSuperellipse& rse, DlClipOp clip_op = DlClipOp::kIntersect, bool is_aa = false) = 0; virtual void ClipPath(const DlPath& path, DlClipOp clip_op = DlClipOp::kIntersect, bool is_aa = false) = 0;
/// Conservative estimate of the bounds of all outstanding clip operations /// measured in the coordinate space within which this DisplayList will /// be rendered. virtual DlRect GetDestinationClipCoverage() const = 0; /// Conservative estimate of the bounds of all outstanding clip operations /// transformed into the local coordinate space in which currently /// recorded rendering operations are interpreted. virtual DlRect GetLocalClipCoverage() const = 0;
/// Return true iff the supplied bounds are easily shown to be outside /// of the current clip bounds. This method may conservatively return /// false if it cannot make the determination. virtual bool QuickReject(const DlRect& bounds) const = 0;
virtual void DrawPaint(const DlPaint& paint) = 0; virtual void DrawColor(DlColor color, DlBlendMode mode = DlBlendMode::kSrcOver) = 0; void Clear(DlColor color) { DrawColor(color, DlBlendMode::kSrc); } virtual void DrawLine(const DlPoint& p0, const DlPoint& p1, const DlPaint& paint) = 0; virtual void DrawDashedLine(const DlPoint& p0, const DlPoint& p1, DlScalar on_length, DlScalar off_length, const DlPaint& paint) = 0; virtual void DrawRect(const DlRect& rect, const DlPaint& paint) = 0; virtual void DrawOval(const DlRect& bounds, const DlPaint& paint) = 0; virtual void DrawCircle(const DlPoint& center, DlScalar radius, const DlPaint& paint) = 0; virtual void DrawRoundRect(const DlRoundRect& rrect, const DlPaint& paint) = 0; virtual void DrawDiffRoundRect(const DlRoundRect& outer, const DlRoundRect& inner, const DlPaint& paint) = 0; virtual void DrawRoundSuperellipse(const DlRoundSuperellipse& rse, const DlPaint& paint) = 0; virtual void DrawPath(const DlPath& path, const DlPaint& paint) = 0; virtual void DrawArc(const DlRect& bounds, DlScalar start, DlScalar sweep, bool useCenter, const DlPaint& paint) = 0; virtual void DrawPoints(DlPointMode mode, uint32_t count, const DlPoint pts[], const DlPaint& paint) = 0; virtual void DrawVertices(const std::shared_ptr<DlVertices>& vertices, DlBlendMode mode, const DlPaint& paint) = 0; virtual void DrawImage(const sk_sp<DlImage>& image, const DlPoint& point, DlImageSampling sampling, const DlPaint* paint = nullptr) = 0; virtual void DrawImageRect( const sk_sp<DlImage>& image, const DlRect& src, const DlRect& dst, DlImageSampling sampling, const DlPaint* paint = nullptr, DlSrcRectConstraint constraint = DlSrcRectConstraint::kFast) = 0; virtual void DrawImageRect( const sk_sp<DlImage>& image, const DlIRect& src, const DlRect& dst, DlImageSampling sampling, const DlPaint* paint = nullptr, DlSrcRectConstraint constraint = DlSrcRectConstraint::kFast) { auto float_src = DlRect::MakeLTRB(src.GetLeft(), src.GetTop(), src.GetRight(), src.GetBottom()); DrawImageRect(image, float_src, dst, sampling, paint, constraint); } void DrawImageRect( const sk_sp<DlImage>& image, const DlRect& dst, DlImageSampling sampling, const DlPaint* paint = nullptr, DlSrcRectConstraint constraint = DlSrcRectConstraint::kFast) { DrawImageRect(image, image->GetBounds(), dst, sampling, paint, constraint); } virtual void DrawImageNine(const sk_sp<DlImage>& image, const DlIRect& center, const DlRect& dst, DlFilterMode filter, const DlPaint* paint = nullptr) = 0; virtual void DrawAtlas(const sk_sp<DlImage>& atlas, const DlRSTransform xform[], const DlRect tex[], const DlColor colors[], int count, DlBlendMode mode, DlImageSampling sampling, const DlRect* cullRect, const DlPaint* paint = nullptr) = 0; virtual void DrawDisplayList(const sk_sp<DisplayList> display_list, DlScalar opacity = SK_Scalar1) = 0;
virtual void DrawTextFrame( const std::shared_ptr<impeller::TextFrame>& text_frame, DlScalar x, DlScalar y, const DlPaint& paint) = 0;
virtual void DrawTextBlob(const sk_sp<SkTextBlob>& blob, DlScalar x, DlScalar y, const DlPaint& paint) = 0; virtual void DrawShadow(const DlPath& path, const DlColor color, const DlScalar elevation, bool transparent_occluder, DlScalar dpr) = 0;
virtual void Flush() = 0;
static constexpr DlScalar kShadowLightHeight = 600; static constexpr DlScalar kShadowLightRadius = 800;
static DlRect ComputeShadowBounds(const DlPath& path, float elevation, DlScalar dpr, const DlMatrix& ctm);};
class DlAutoCanvasRestore { public: DlAutoCanvasRestore(DlCanvas* canvas, bool do_save) : canvas_(canvas) { if (canvas) { canvas_ = canvas; restore_count_ = canvas->GetSaveCount(); if (do_save) { canvas_->Save(); } } else { canvas_ = nullptr; restore_count_ = 0; } }
~DlAutoCanvasRestore() { Restore(); }
void Restore() { if (canvas_) { canvas_->RestoreToCount(restore_count_); canvas_ = nullptr; } }
private: DlCanvas* canvas_; int restore_count_;
FML_DISALLOW_COPY_ASSIGN_AND_MOVE(DlAutoCanvasRestore);};
} // namespace flutter
#endif // FLUTTER_DISPLAY_LIST_DL_CANVAS_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#include "flutter/display_list/dl_color.h"
namespace flutter {
namespace {const std::array<DlScalar, 12> kP3ToSrgb = { 1.306671048092539, -0.298061942172353, 0.213228303487995, -0.213580156254466, // -0.117390025596251, 1.127722006101976, 0.109727644608938, -0.109450321455370, // 0.214813187718391, 0.054268702864647, 1.406898424029350, -0.364892765879631};
DlColor transform(const DlColor& color, const std::array<DlScalar, 12>& matrix, DlColorSpace color_space) { return DlColor(color.getAlphaF(), matrix[0] * color.getRedF() + // matrix[1] * color.getGreenF() + // matrix[2] * color.getBlueF() + // matrix[3], // matrix[4] * color.getRedF() + // matrix[5] * color.getGreenF() + // matrix[6] * color.getBlueF() + // matrix[7], // matrix[8] * color.getRedF() + // matrix[9] * color.getGreenF() + // matrix[10] * color.getBlueF() + // matrix[11], // color_space);}} // namespace
DlColor DlColor::withColorSpace(DlColorSpace color_space) const { switch (color_space_) { case DlColorSpace::kSRGB: switch (color_space) { case DlColorSpace::kSRGB: return *this; case DlColorSpace::kExtendedSRGB: return DlColor(alpha_, red_, green_, blue_, DlColorSpace::kExtendedSRGB); case DlColorSpace::kDisplayP3: FML_CHECK(false) << "not implemented"; return *this; } case DlColorSpace::kExtendedSRGB: switch (color_space) { case DlColorSpace::kSRGB: FML_CHECK(false) << "not implemented"; return *this; case DlColorSpace::kExtendedSRGB: return *this; case DlColorSpace::kDisplayP3: FML_CHECK(false) << "not implemented"; return *this; } case DlColorSpace::kDisplayP3: switch (color_space) { case DlColorSpace::kSRGB: FML_CHECK(false) << "not implemented"; return *this; case DlColorSpace::kExtendedSRGB: return transform(*this, kP3ToSrgb, DlColorSpace::kExtendedSRGB); case DlColorSpace::kDisplayP3: return *this; } }}
} // namespace flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#ifndef FLUTTER_DISPLAY_LIST_DL_COLOR_H_#define FLUTTER_DISPLAY_LIST_DL_COLOR_H_
#include "flutter/display_list/geometry/dl_geometry_types.h"
namespace flutter {
// These should match the enumerations defined in //lib/ui/painting.dart.enum class DlColorSpace { kSRGB = 0, kExtendedSRGB = 1, kDisplayP3 = 2 };
/// A representation of a color.////// The color belongs to a DlColorSpace. Using deprecated integer data accessors/// on colors not in the kSRGB colorspace can lead to data loss. Using the/// floating point accessors and constructors that were added for wide-gamut/// support are preferred.struct DlColor { public: constexpr DlColor() : alpha_(1.f), red_(0.f), green_(0.f), blue_(0.f), color_space_(DlColorSpace::kSRGB) {} constexpr explicit DlColor(uint32_t argb) : alpha_(toF((argb >> 24) & 0xff)), red_(toF((argb >> 16) & 0xff)), green_(toF((argb >> 8) & 0xff)), blue_(toF((argb >> 0) & 0xff)), color_space_(DlColorSpace::kSRGB) {} constexpr DlColor(DlScalar alpha, DlScalar red, DlScalar green, DlScalar blue, DlColorSpace colorspace) : alpha_(alpha), red_(red), green_(green), blue_(blue), color_space_(colorspace) {}
/// @brief Construct a 32 bit color from floating point R, G, B, and A color /// channels. static constexpr DlColor RGBA(DlScalar r, DlScalar g, DlScalar b, DlScalar a) { return ARGB(a, r, g, b); }
/// @brief Construct a 32 bit color from floating point A, R, G, and B color /// channels. static constexpr DlColor ARGB(DlScalar a, DlScalar r, DlScalar g, DlScalar b) { return DlColor(a, r, g, b, DlColorSpace::kSRGB); }
static constexpr uint8_t toAlpha(DlScalar opacity) { return toC(opacity); } static constexpr DlScalar toOpacity(uint8_t alpha) { return toF(alpha); }
// clang-format off static constexpr DlColor kTransparent() {return DlColor(0x00000000);}; static constexpr DlColor kBlack() {return DlColor(0xFF000000);}; static constexpr DlColor kWhite() {return DlColor(0xFFFFFFFF);}; static constexpr DlColor kRed() {return DlColor(0xFFFF0000);}; static constexpr DlColor kGreen() {return DlColor(0xFF00FF00);}; static constexpr DlColor kBlue() {return DlColor(0xFF0000FF);}; static constexpr DlColor kCyan() {return DlColor(0xFF00FFFF);}; static constexpr DlColor kMagenta() {return DlColor(0xFFFF00FF);}; static constexpr DlColor kYellow() {return DlColor(0xFFFFFF00);}; static constexpr DlColor kDarkGrey() {return DlColor(0xFF3F3F3F);}; static constexpr DlColor kMidGrey() {return DlColor(0xFF808080);}; static constexpr DlColor kLightGrey() {return DlColor(0xFFC0C0C0);}; static constexpr DlColor kAliceBlue() {return DlColor(0xFFF0F8FF);}; static constexpr DlColor kFuchsia() {return DlColor(0xFFFF00FF);}; static constexpr DlColor kMaroon() {return DlColor(0xFF800000);}; static constexpr DlColor kSkyBlue() {return DlColor(0xFF87CEEB);}; static constexpr DlColor kCornflowerBlue() {return DlColor(0xFF6495ED);}; static constexpr DlColor kCrimson() {return DlColor(0xFFFF5733);}; static constexpr DlColor kAqua() {return DlColor(0xFF00FFFF);}; static constexpr DlColor kOrange() {return DlColor(0xFFFFA500);}; static constexpr DlColor kPurple() {return DlColor(0xFF800080);}; static constexpr DlColor kLimeGreen() {return DlColor(0xFF32CD32);}; static constexpr DlColor kGreenYellow() {return DlColor(0xFFADFF2F);}; static constexpr DlColor kDarkMagenta() {return DlColor(0xFF8B008B);}; static constexpr DlColor kOrangeRed() {return DlColor(0xFFFF4500);}; static constexpr DlColor kDarkGreen() {return DlColor(0xFF006400);}; static constexpr DlColor kChartreuse() {return DlColor(0xFF7FFF00);}; // clang-format on
constexpr bool isOpaque() const { return alpha_ >= 1.f; } constexpr bool isTransparent() const { return alpha_ <= 0.f; }
///\deprecated Use floating point accessors to avoid data loss when using wide /// gamut colors. constexpr int getAlpha() const { return toC(alpha_); } ///\deprecated Use floating point accessors to avoid data loss when using wide /// gamut colors. constexpr int getRed() const { return toC(red_); } ///\deprecated Use floating point accessors to avoid data loss when using wide /// gamut colors. constexpr int getGreen() const { return toC(green_); } ///\deprecated Use floating point accessors to avoid data loss when using wide /// gamut colors. constexpr int getBlue() const { return toC(blue_); }
constexpr DlScalar getAlphaF() const { return alpha_; } constexpr DlScalar getRedF() const { return red_; } constexpr DlScalar getGreenF() const { return green_; } constexpr DlScalar getBlueF() const { return blue_; }
constexpr DlColorSpace getColorSpace() const { return color_space_; }
constexpr DlColor withAlpha(uint8_t alpha) const { // return DlColor((argb() & 0x00FFFFFF) | (alpha << 24)); } constexpr DlColor withRed(uint8_t red) const { // return DlColor((argb() & 0xFF00FFFF) | (red << 16)); } constexpr DlColor withGreen(uint8_t green) const { // return DlColor((argb() & 0xFFFF00FF) | (green << 8)); } constexpr DlColor withBlue(uint8_t blue) const { // return DlColor((argb() & 0xFFFFFF00) | (blue << 0)); } constexpr DlColor withAlphaF(float alpha) const { // return DlColor(alpha, red_, green_, blue_, color_space_); } constexpr DlColor withRedF(float red) const { // return DlColor(alpha_, red, green_, blue_, color_space_); } constexpr DlColor withGreenF(float green) const { // return DlColor(alpha_, red_, green, blue_, color_space_); } constexpr DlColor withBlueF(float blue) const { // return DlColor(alpha_, red_, green_, blue, color_space_); } /// Performs a colorspace transformation. /// /// This isn't just a replacement of the color space field, the new color /// components are calculated. DlColor withColorSpace(DlColorSpace color_space) const;
constexpr DlColor modulateOpacity(DlScalar opacity) const { return opacity <= 0 ? withAlpha(0) : opacity >= 1 ? *this : withAlpha(round(getAlpha() * opacity)); }
///\deprecated Use floating point accessors to avoid data loss when using wide /// gamut colors. constexpr uint32_t argb() const { return toC(alpha_) << 24 | // toC(red_) << 16 | // toC(green_) << 8 | // toC(blue_) << 0; }
/// Checks that no difference in color components exceeds the delta. /// /// This doesn't check against the actual distance between the colors in some /// space. bool isClose(DlColor const& other, DlScalar delta = 1.0f / 256.0f) { return color_space_ == other.color_space_ && std::abs(alpha_ - other.alpha_) < delta && std::abs(red_ - other.red_) < delta && std::abs(green_ - other.green_) < delta && std::abs(blue_ - other.blue_) < delta; } bool operator==(DlColor const& other) const { return alpha_ == other.alpha_ && red_ == other.red_ && green_ == other.green_ && blue_ == other.blue_ && color_space_ == other.color_space_; } bool operator!=(DlColor const& other) const { return !this->operator==(other); }
private: DlScalar alpha_; DlScalar red_; DlScalar green_; DlScalar blue_; DlColorSpace color_space_;
static constexpr DlScalar toF(uint8_t comp) { return comp * (1.0f / 255); } static constexpr uint8_t toC(DlScalar fComp) { return round(fComp * 255); }};
} // namespace flutter
#endif // FLUTTER_DISPLAY_LIST_DL_COLOR_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#include "flutter/display_list/dl_color.h"#include "flutter/testing/display_list_testing.h"#include "flutter/testing/testing.h"
namespace flutter {namespace testing {
static void arraysEqual(const uint32_t* ints, const DlColor* colors, int count) { for (int i = 0; i < count; i++) { EXPECT_EQ(ints[i], colors[i].argb()) << " index:" << i; }}
TEST(DisplayListColor, DefaultValue) { DlColor color; EXPECT_EQ(color.getAlphaF(), 1.f); EXPECT_EQ(color.getRedF(), 0.f); EXPECT_EQ(color.getGreenF(), 0.f); EXPECT_EQ(color.getBlueF(), 0.f); EXPECT_EQ(color.getColorSpace(), DlColorSpace::kSRGB);}
TEST(DisplayListColor, ArrayInterchangeableWithUint32) { uint32_t ints[5] = { 0xFF000000, // 0xFFFF0000, // 0xFF00FF00, // 0xFF0000FF, // 0xF1F2F3F4, }; DlColor colors[5] = { DlColor::kBlack(), // DlColor::kRed(), // DlColor::kGreen(), // DlColor::kBlue(), // DlColor(0xF1F2F3F4), }; arraysEqual(ints, colors, 5);}
TEST(DisplayListColor, DlColorFloatConstructor) { EXPECT_EQ(DlColor::ARGB(1.0f, 1.0f, 1.0f, 1.0f), DlColor(0xFFFFFFFF)); EXPECT_EQ(DlColor::ARGB(0.0f, 0.0f, 0.0f, 0.0f), DlColor(0x00000000)); EXPECT_TRUE( DlColor::ARGB(0.5f, 0.5f, 0.5f, 0.5f).isClose(DlColor(0x80808080))); EXPECT_TRUE( DlColor::ARGB(1.0f, 0.0f, 0.5f, 1.0f).isClose(DlColor(0xFF0080FF)));
EXPECT_EQ(DlColor::RGBA(1.0f, 1.0f, 1.0f, 1.0f), DlColor(0xFFFFFFFF)); EXPECT_EQ(DlColor::RGBA(0.0f, 0.0f, 0.0f, 0.0f), DlColor(0x00000000)); EXPECT_TRUE( DlColor::RGBA(0.5f, 0.5f, 0.5f, 0.5f).isClose(DlColor(0x80808080))); EXPECT_TRUE( DlColor::RGBA(1.0f, 0.0f, 0.5f, 1.0f).isClose(DlColor(0xFFFF0080)));}
TEST(DisplayListColor, DlColorComponentGetters) { { DlColor test(0xFFFFFFFF);
EXPECT_EQ(test.getAlpha(), 0xFF); EXPECT_EQ(test.getRed(), 0xFF); EXPECT_EQ(test.getGreen(), 0xFF); EXPECT_EQ(test.getBlue(), 0xFF);
EXPECT_EQ(test.getAlphaF(), 1.0f); EXPECT_EQ(test.getRedF(), 1.0f); EXPECT_EQ(test.getGreenF(), 1.0f); EXPECT_EQ(test.getBlueF(), 1.0f); }
{ DlColor test = DlColor::ARGB(1.0f, 1.0f, 1.0f, 1.0f);
EXPECT_EQ(test.getAlpha(), 0xFF); EXPECT_EQ(test.getRed(), 0xFF); EXPECT_EQ(test.getGreen(), 0xFF); EXPECT_EQ(test.getBlue(), 0xFF);
EXPECT_EQ(test.getAlphaF(), 1.0f); EXPECT_EQ(test.getRedF(), 1.0f); EXPECT_EQ(test.getGreenF(), 1.0f); EXPECT_EQ(test.getBlueF(), 1.0f); }
{ DlColor test(0x00000000);
EXPECT_EQ(test.getAlpha(), 0x00); EXPECT_EQ(test.getRed(), 0x00); EXPECT_EQ(test.getGreen(), 0x00); EXPECT_EQ(test.getBlue(), 0x00);
EXPECT_EQ(test.getAlphaF(), 0.0f); EXPECT_EQ(test.getRedF(), 0.0f); EXPECT_EQ(test.getGreenF(), 0.0f); EXPECT_EQ(test.getBlueF(), 0.0f); }
{ DlColor test = DlColor::ARGB(0.0f, 0.0f, 0.0f, 0.0f);
EXPECT_EQ(test.getAlpha(), 0x00); EXPECT_EQ(test.getRed(), 0x00); EXPECT_EQ(test.getGreen(), 0x00); EXPECT_EQ(test.getBlue(), 0x00);
EXPECT_EQ(test.getAlphaF(), 0.0f); EXPECT_EQ(test.getRedF(), 0.0f); EXPECT_EQ(test.getGreenF(), 0.0f); EXPECT_EQ(test.getBlueF(), 0.0f); }
{ DlColor test(0x7F7F7F7F);
EXPECT_EQ(test.getAlpha(), 0x7F); EXPECT_EQ(test.getRed(), 0x7F); EXPECT_EQ(test.getGreen(), 0x7F); EXPECT_EQ(test.getBlue(), 0x7F);
const DlScalar half = 127.0f * (1.0f / 255.0f);
EXPECT_NEAR(test.getAlphaF(), half, 0.00001); EXPECT_NEAR(test.getRedF(), half, 0.00001); EXPECT_NEAR(test.getGreenF(), half, 0.00001); EXPECT_NEAR(test.getBlueF(), half, 0.00001); }
{ DlColor test = DlColor::ARGB(0.5f, 0.5f, 0.5f, 0.5f);
EXPECT_EQ(test.getAlpha(), 0x80); EXPECT_EQ(test.getRed(), 0x80); EXPECT_EQ(test.getGreen(), 0x80); EXPECT_EQ(test.getBlue(), 0x80);
EXPECT_EQ(test.getAlphaF(), 0.5); EXPECT_EQ(test.getRedF(), 0.5); EXPECT_EQ(test.getGreenF(), 0.5); EXPECT_EQ(test.getBlueF(), 0.5); }
{ DlColor test(0x1F2F3F4F);
EXPECT_EQ(test.getAlpha(), 0x1F); EXPECT_EQ(test.getRed(), 0x2F); EXPECT_EQ(test.getGreen(), 0x3F); EXPECT_EQ(test.getBlue(), 0x4F);
EXPECT_NEAR(test.getAlphaF(), 0x1f * (1.0f / 255.0f), 0.00001); EXPECT_NEAR(test.getRedF(), 0x2f * (1.0f / 255.0f), 0.00001); EXPECT_NEAR(test.getGreenF(), 0x3f * (1.0f / 255.0f), 0.00001); EXPECT_NEAR(test.getBlueF(), 0x4f * (1.0f / 255.0f), 0.00001); }
{ DlColor test = DlColor::ARGB(0.1f, 0.2f, 0.3f, 0.4f);
EXPECT_EQ(test.getAlpha(), round(0.1f * 255)); EXPECT_EQ(test.getRed(), round(0.2f * 255)); EXPECT_EQ(test.getGreen(), round(0.3f * 255)); EXPECT_EQ(test.getBlue(), round(0.4f * 255));
EXPECT_EQ(test.getAlphaF(), 0.1f); EXPECT_EQ(test.getRedF(), 0.2f); EXPECT_EQ(test.getGreenF(), 0.3f); EXPECT_EQ(test.getBlueF(), 0.4f); }
{ DlColor test = DlColor::RGBA(0.2f, 0.3f, 0.4f, 0.1f);
EXPECT_EQ(test.getAlpha(), round(0.1f * 255)); EXPECT_EQ(test.getRed(), round(0.2f * 255)); EXPECT_EQ(test.getGreen(), round(0.3f * 255)); EXPECT_EQ(test.getBlue(), round(0.4f * 255));
EXPECT_EQ(test.getAlphaF(), 0.1f); EXPECT_EQ(test.getRedF(), 0.2f); EXPECT_EQ(test.getGreenF(), 0.3f); EXPECT_EQ(test.getBlueF(), 0.4f); }}
TEST(DisplayListColor, DlColorOpaqueTransparent) { auto test_argb = [](int a, int r, int g, int b) { ASSERT_TRUE(a >= 0 && a <= 255); ASSERT_TRUE(r >= 0 && r <= 255); ASSERT_TRUE(g >= 0 && g <= 255); ASSERT_TRUE(b >= 0 && b <= 255);
int argb = ((a << 24) | (r << 16) | (g << 8) | b); bool is_opaque = (a == 255); bool is_transprent = (a == 0);
EXPECT_EQ(DlColor(argb).isOpaque(), is_opaque); EXPECT_EQ(DlColor(argb).isTransparent(), is_transprent);
DlScalar aF = a * (1.0f / 255.0f); DlScalar rF = r * (1.0f / 255.0f); DlScalar gF = g * (1.0f / 255.0f); DlScalar bF = b * (1.0f / 255.0f);
EXPECT_EQ(DlColor::ARGB(aF, rF, gF, bF).isOpaque(), is_opaque); EXPECT_EQ(DlColor::ARGB(aF, rF, gF, bF).isTransparent(), is_transprent);
EXPECT_EQ(DlColor::RGBA(rF, gF, bF, aF).isOpaque(), is_opaque); EXPECT_EQ(DlColor::RGBA(rF, gF, bF, aF).isTransparent(), is_transprent); };
for (int r = 0; r <= 255; r += 15) { for (int g = 0; g <= 255; g += 15) { for (int b = 0; b <= 255; b += 15) { test_argb(0, r, g, b); for (int a = 15; a < 255; a += 15) { test_argb(a, r, g, b); } test_argb(255, r, g, b); } } }}
TEST(DisplayListColor, EqualityWithColorspace) { EXPECT_TRUE(DlColor(0.9, 0.8, 0.7, 0.6, DlColorSpace::kSRGB) == DlColor(0.9, 0.8, 0.7, 0.6, DlColorSpace::kSRGB)); EXPECT_FALSE(DlColor(0.9, 0.8, 0.7, 0.6, DlColorSpace::kSRGB) == DlColor(0.9, 0.8, 0.7, 0.6, DlColorSpace::kExtendedSRGB)); EXPECT_FALSE(DlColor(0.9, 0.8, 0.7, 0.6, DlColorSpace::kSRGB) != DlColor(0.9, 0.8, 0.7, 0.6, DlColorSpace::kSRGB)); EXPECT_TRUE(DlColor(0.9, 0.8, 0.7, 0.6, DlColorSpace::kSRGB) != DlColor(0.9, 0.8, 0.7, 0.6, DlColorSpace::kExtendedSRGB));}
TEST(DisplayListColor, EqualityWithExtendedSRGB) { EXPECT_TRUE(DlColor(1.0, 1.1, -0.2, 0.1, DlColorSpace::kExtendedSRGB) == DlColor(1.0, 1.1, -0.2, 0.1, DlColorSpace::kExtendedSRGB)); EXPECT_FALSE(DlColor(1.0, 1.1, -0.2, 0.1, DlColorSpace::kExtendedSRGB) == DlColor(1.0, 1.0, 0.0, 0.0, DlColorSpace::kExtendedSRGB));}
TEST(DisplayListColor, ColorSpaceSRGBtoSRGB) { DlColor srgb(0.9, 0.8, 0.7, 0.6, DlColorSpace::kSRGB); EXPECT_EQ(srgb, srgb.withColorSpace(DlColorSpace::kSRGB));}
TEST(DisplayListColor, ColorSpaceSRGBtoExtendedSRGB) { DlColor srgb(0.9, 0.8, 0.7, 0.6, DlColorSpace::kSRGB); EXPECT_EQ(DlColor(0.9, 0.8, 0.7, 0.6, DlColorSpace::kExtendedSRGB), srgb.withColorSpace(DlColorSpace::kExtendedSRGB));}
TEST(DisplayListColor, ColorSpaceExtendedSRGBtoExtendedSRGB) { DlColor xsrgb(0.9, 0.8, 0.7, 0.6, DlColorSpace::kExtendedSRGB); EXPECT_EQ(DlColor(0.9, 0.8, 0.7, 0.6, DlColorSpace::kExtendedSRGB), xsrgb.withColorSpace(DlColorSpace::kExtendedSRGB));}
TEST(DisplayListColor, ColorSpaceP3ToP3) { DlColor p3(0.9, 0.8, 0.7, 0.6, DlColorSpace::kDisplayP3); EXPECT_EQ(DlColor(0.9, 0.8, 0.7, 0.6, DlColorSpace::kDisplayP3), p3.withColorSpace(DlColorSpace::kDisplayP3));}
TEST(DisplayListColor, ColorSpaceP3ToExtendedSRGB) { DlColor red(0.9, 1.0, 0.0, 0.0, DlColorSpace::kDisplayP3); EXPECT_TRUE( DlColor(0.9, 1.0931, -0.2268, -0.1501, DlColorSpace::kExtendedSRGB) .isClose(red.withColorSpace(DlColorSpace::kExtendedSRGB))) << red.withColorSpace(DlColorSpace::kExtendedSRGB);
DlColor green(0.9, 0.0, 1.0, 0.0, DlColorSpace::kDisplayP3); EXPECT_TRUE( DlColor(0.9, -0.5116, 1.0183, -0.3106, DlColorSpace::kExtendedSRGB) .isClose(green.withColorSpace(DlColorSpace::kExtendedSRGB))) << green.withColorSpace(DlColorSpace::kExtendedSRGB);
DlColor blue(0.9, 0.0, 0.0, 1.0, DlColorSpace::kDisplayP3); EXPECT_TRUE(DlColor(0.9, -0.0004, 0.0003, 1.0420, DlColorSpace::kExtendedSRGB) .isClose(blue.withColorSpace(DlColorSpace::kExtendedSRGB))) << blue.withColorSpace(DlColorSpace::kExtendedSRGB);}
TEST(DisplayListColor, isClose) { EXPECT_TRUE(DlColor(0xffaabbcc).isClose(DlColor(0xffaabbcc)));}
TEST(DisplayListColor, isNotClose) { EXPECT_FALSE(DlColor(0xffaabbcc).isClose(DlColor(0xffaabbcd)));}
} // namespace testing} // namespace flutter1234567891011// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#include "flutter/display_list/dl_op_flags.h"
namespace flutter {
// Just exists to ensure that the header can be cleanly imported.
} // namespace flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#ifndef FLUTTER_DISPLAY_LIST_DL_OP_FLAGS_H_#define FLUTTER_DISPLAY_LIST_DL_OP_FLAGS_H_
#include "flutter/display_list/dl_paint.h"#include "flutter/fml/logging.h"
namespace flutter {
/// The base class for the classes that maintain a list of/// attributes that might be important for a number of operations/// including which rendering attributes need to be set before/// calling a rendering method (all |drawSomething| calls),/// or for determining which exceptional conditions may need/// to be accounted for in bounds calculations./// This class contains only protected definitions and helper methods/// for the public classes |DisplayListAttributeFlags| and/// |DisplayListSpecialGeometryFlags|.class DisplayListFlags { protected: // A drawing operation that is not geometric in nature (but which // may still apply a MaskFilter - see |kUsesMaskFilter| below). static constexpr int kIsNonGeometric = 0;
// A geometric operation that is defined as a fill operation // regardless of what the current paint Style is set to. // This flag will automatically assume |kUsesMaskFilter|. static constexpr int kIsFilledGeometry = 1 << 0;
// A geometric operation that is defined as a stroke operation // regardless of what the current paint Style is set to. // This flag will automatically assume |kUsesMaskFilter|. static constexpr int kIsStrokedGeometry = 1 << 1;
// A geometric operation that may be a stroke or fill operation // depending on the current state of the paint Style attribute. // This flag will automatically assume |kUsesMaskFilter|. static constexpr int kIsDrawnGeometry = 1 << 2;
static constexpr int kIsAnyGeometryMask = // kIsFilledGeometry | // kIsStrokedGeometry | // kIsDrawnGeometry;
// A primitive that floods the surface (or clip) with no // natural bounds, such as |drawColor| or |drawPaint|. static constexpr int kFloodsSurface = 1 << 3;
static constexpr int kMayHaveCaps = 1 << 4; static constexpr int kMayHaveJoins = 1 << 5; static constexpr int kButtCapIsSquare = 1 << 6;
// A geometric operation which has a path that might have // end caps that are not rectilinear which means that square // end caps might project further than half the stroke width // from the geometry bounds. // A rectilinear path such as |drawRect| will not have // diagonal end caps. |drawLine| might have diagonal end // caps depending on the angle of the line, and more likely // |drawPath| will often have such end caps. static constexpr int kMayHaveDiagonalCaps = 1 << 7;
// A geometric operation which has joined vertices that are // not guaranteed to be smooth (angles of incoming and outgoing) // segments at some joins may not have the same angle) or // rectilinear (squares have right angles at the corners, but // those corners will never extend past the bounding box of // the geometry pre-transform). // |drawRect|, |drawOval| and |drawRRect| all have well // behaved joins, but |drawPath| might have joins that cause // mitered extensions outside the pre-transformed bounding box. static constexpr int kMayHaveAcuteJoins = 1 << 8;
static constexpr int kAnySpecialGeometryMask = // kMayHaveCaps | kMayHaveJoins | kButtCapIsSquare | // kMayHaveDiagonalCaps | kMayHaveAcuteJoins;
// clang-format off static constexpr int kUsesAntiAlias = 1 << 10; static constexpr int kUsesAlpha = 1 << 11; static constexpr int kUsesColor = 1 << 12; static constexpr int kUsesBlend = 1 << 13; static constexpr int kUsesShader = 1 << 14; static constexpr int kUsesColorFilter = 1 << 15; static constexpr int kUsesMaskFilter = 1 << 16; static constexpr int kUsesImageFilter = 1 << 17;
// Some ops have an optional paint argument. If the version // stored in the DisplayList ignores the paint, but there // is an option to render the same op with a paint then // both of the following flags are set to indicate that // a default paint object can be constructed when rendering // the op to carry information imposed from outside the // DisplayList (for example, the opacity override). static constexpr int kIgnoresPaint = 1 << 30; // clang-format on
static constexpr int kAnyAttributeMask = // kUsesAntiAlias | kUsesAlpha | kUsesColor | kUsesBlend | kUsesShader | kUsesColorFilter | kUsesMaskFilter | kUsesImageFilter;};
class DisplayListFlagsBase : protected DisplayListFlags { protected: explicit constexpr DisplayListFlagsBase(int flags) : flags_(flags) {}
const int flags_;
constexpr bool has_any(int qFlags) const { return (flags_ & qFlags) != 0; } constexpr bool has_all(int qFlags) const { return (flags_ & qFlags) == qFlags; } constexpr bool has_none(int qFlags) const { return (flags_ & qFlags) == 0; }};
/// An attribute class for advertising specific properties of/// a geometric attribute that can affect the computation of/// the bounds of the primitive.class DisplayListSpecialGeometryFlags : DisplayListFlagsBase { public: /// The geometry may have segments that end without closing the path. constexpr bool may_have_end_caps() const { return has_any(kMayHaveCaps); }
/// The geometry may have segments connect non-continuously. constexpr bool may_have_joins() const { return has_any(kMayHaveJoins); }
/// Mainly for drawPoints(PointMode) where Butt caps are rendered as squares. constexpr bool butt_cap_becomes_square() const { return has_any(kButtCapIsSquare); }
/// The geometry may have segments that end on a diagonal /// such that their end caps extend further than the default /// |strokeWidth * 0.5| margin around the geometry. constexpr bool may_have_diagonal_caps() const { return has_any(kMayHaveDiagonalCaps); }
/// The geometry may have segments that meet at vertices at /// an acute angle such that the miter joins will extend /// further than the default |strokeWidth * 0.5| margin around /// the geometry. constexpr bool may_have_acute_joins() const { return has_any(kMayHaveAcuteJoins); }
private: explicit constexpr DisplayListSpecialGeometryFlags(int flags) : DisplayListFlagsBase(flags) { FML_DCHECK((flags & kAnySpecialGeometryMask) == flags); }
const DisplayListSpecialGeometryFlags with(int extra) const { return extra == 0 ? *this : DisplayListSpecialGeometryFlags(flags_ | extra); }
friend class DisplayListAttributeFlags;};
class DisplayListAttributeFlags : DisplayListFlagsBase { public: const DisplayListSpecialGeometryFlags GeometryFlags(bool is_stroked) const { return special_flags_; }
constexpr bool ignores_paint() const { return has_any(kIgnoresPaint); }
constexpr bool applies_anti_alias() const { return has_any(kUsesAntiAlias); } constexpr bool applies_color() const { return has_any(kUsesColor); } constexpr bool applies_alpha() const { return has_any(kUsesAlpha); } constexpr bool applies_alpha_or_color() const { return has_any(kUsesAlpha | kUsesColor); }
/// The primitive dynamically determines whether it is a stroke or fill /// operation (or both) based on the setting of the |Style| attribute. constexpr bool applies_style() const { return has_any(kIsDrawnGeometry); } /// The primitive can use any of the stroke attributes, such as /// StrokeWidth, StrokeMiter, StrokeCap, or StrokeJoin. This /// method will return if the primitive is defined as one that /// strokes its geometry (such as |drawLine|) or if it is defined /// as one that honors the Style attribute. If the Style attribute /// is known then a more accurate answer can be returned from /// the |is_stroked| method by supplying the actual setting of /// the style. // bool applies_stroke_attributes() const { return is_stroked(); }
constexpr bool applies_shader() const { return has_any(kUsesShader); } /// The primitive honors the current DlColorFilter, including /// the related attribute InvertColors constexpr bool applies_color_filter() const { return has_any(kUsesColorFilter); } /// The primitive honors the DlBlendMode constexpr bool applies_blend() const { return has_any(kUsesBlend); } /// The primitive honors the DlMaskFilter whether set using the /// filter object or using the convenience method |setMaskBlurFilter| constexpr bool applies_mask_filter() const { return has_any(kUsesMaskFilter); } constexpr bool applies_image_filter() const { return has_any(kUsesImageFilter); }
constexpr bool is_geometric() const { return has_any(kIsAnyGeometryMask); } constexpr bool always_stroked() const { return has_any(kIsStrokedGeometry); } constexpr bool is_stroked(DlDrawStyle style = DlDrawStyle::kStroke) const { return (has_any(kIsStrokedGeometry) || (style != DlDrawStyle::kFill && has_any(kIsDrawnGeometry))); }
constexpr bool is_flood() const { return has_any(kFloodsSurface); }
constexpr bool operator==(DisplayListAttributeFlags const& other) const { return flags_ == other.flags_; }
private: explicit constexpr DisplayListAttributeFlags(int flags) : DisplayListFlagsBase(flags), special_flags_(flags & kAnySpecialGeometryMask) { FML_DCHECK((flags & kIsAnyGeometryMask) == kIsNonGeometric || (flags & kIsAnyGeometryMask) == kIsFilledGeometry || (flags & kIsAnyGeometryMask) == kIsStrokedGeometry || (flags & kIsAnyGeometryMask) == kIsDrawnGeometry); FML_DCHECK(((flags & kAnyAttributeMask) == 0) != ((flags & kIgnoresPaint) == 0)); FML_DCHECK((flags & kIsAnyGeometryMask) != 0 || (flags & kAnySpecialGeometryMask) == 0); }
constexpr DisplayListAttributeFlags operator+(int extra) const { return extra == 0 ? *this : DisplayListAttributeFlags(flags_ | extra); }
constexpr DisplayListAttributeFlags operator-(int remove) const { FML_DCHECK(has_all(remove)); return DisplayListAttributeFlags(flags_ & ~remove); }
const DisplayListSpecialGeometryFlags special_flags_;
friend class DisplayListOpFlags;};
class DisplayListOpFlags : DisplayListFlags { private: // Flags common to all primitives that apply colors static constexpr int kBasePaintFlags = (kUsesColor | // kUsesAlpha | // kUsesBlend | // kUsesShader | // kUsesColorFilter | // kUsesImageFilter);
// Flags common to all primitives that stroke or fill static constexpr int kBaseStrokeOrFillFlags = (kIsDrawnGeometry | // kUsesAntiAlias | // kUsesMaskFilter);
// Flags common to primitives that stroke geometry static constexpr int kBaseStrokeFlags = (kIsStrokedGeometry | // kUsesAntiAlias | // kUsesMaskFilter);
// Flags common to primitives that render an image with paint attributes static constexpr int kBaseImageFlags = (kIsNonGeometric | // kUsesAlpha | // kUsesBlend | // kUsesColorFilter | // kUsesImageFilter);
public: static constexpr DisplayListAttributeFlags kSaveLayerFlags{ kIgnoresPaint // }; static constexpr DisplayListAttributeFlags kSaveLayerWithPaintFlags{ kIsNonGeometric | // kUsesAlpha | // kUsesBlend | // kUsesColorFilter | // kUsesImageFilter // }; static constexpr DisplayListAttributeFlags kDrawColorFlags{ kFloodsSurface | // kIgnoresPaint // }; static constexpr DisplayListAttributeFlags kDrawPaintFlags{ kBasePaintFlags | // kFloodsSurface // }; // Special case flags for horizonal and vertical lines static constexpr DisplayListAttributeFlags kDrawHVLineFlags{ kBasePaintFlags | // kBaseStrokeFlags | // kMayHaveCaps // }; static constexpr DisplayListAttributeFlags kDrawLineFlags{ kDrawHVLineFlags // + kMayHaveDiagonalCaps // }; static constexpr DisplayListAttributeFlags kDrawRectFlags{ kBasePaintFlags | // kBaseStrokeOrFillFlags | // kMayHaveJoins // }; static constexpr DisplayListAttributeFlags kDrawOvalFlags{ kBasePaintFlags | // kBaseStrokeOrFillFlags // }; static constexpr DisplayListAttributeFlags kDrawCircleFlags{ kBasePaintFlags | // kBaseStrokeOrFillFlags // }; static constexpr DisplayListAttributeFlags kDrawRRectFlags{ kBasePaintFlags | // kBaseStrokeOrFillFlags // }; static constexpr DisplayListAttributeFlags kDrawDRRectFlags{ kBasePaintFlags | // kBaseStrokeOrFillFlags // }; static constexpr DisplayListAttributeFlags kDrawRSuperellipseFlags{ kBasePaintFlags | // kBaseStrokeOrFillFlags // }; static constexpr DisplayListAttributeFlags kDrawPathFlags{ kBasePaintFlags | // kBaseStrokeOrFillFlags | // kMayHaveCaps | // kMayHaveDiagonalCaps | // kMayHaveJoins | // kMayHaveAcuteJoins // }; static constexpr DisplayListAttributeFlags kDrawArcNoCenterFlags{ kBasePaintFlags | // kBaseStrokeOrFillFlags | // kMayHaveCaps | // kMayHaveDiagonalCaps // }; static constexpr DisplayListAttributeFlags kDrawArcWithCenterFlags{ kBasePaintFlags | // kBaseStrokeOrFillFlags | // kMayHaveJoins | // kMayHaveAcuteJoins // }; static constexpr DisplayListAttributeFlags kDrawPointsAsPointsFlags{ kBasePaintFlags | // kBaseStrokeFlags | // kMayHaveCaps | // kButtCapIsSquare // }; static constexpr DisplayListAttributeFlags kDrawPointsAsLinesFlags{ kBasePaintFlags | // kBaseStrokeFlags | // kMayHaveCaps | // kMayHaveDiagonalCaps // }; // Polygon mode just draws (count-1) separate lines, no joins static constexpr DisplayListAttributeFlags kDrawPointsAsPolygonFlags{ kBasePaintFlags | // kBaseStrokeFlags | // kMayHaveCaps | // kMayHaveDiagonalCaps // }; static constexpr DisplayListAttributeFlags kDrawVerticesFlags{ kIsNonGeometric | // kUsesAlpha | // kUsesShader | // kUsesBlend | // kUsesColorFilter | // kUsesImageFilter // }; static constexpr DisplayListAttributeFlags kDrawImageFlags{ kIgnoresPaint // }; static constexpr DisplayListAttributeFlags kDrawImageWithPaintFlags{ kBaseImageFlags | // kUsesAntiAlias | // kUsesMaskFilter // }; static constexpr DisplayListAttributeFlags kDrawImageRectFlags{ kIgnoresPaint // }; static constexpr DisplayListAttributeFlags kDrawImageRectWithPaintFlags{ kBaseImageFlags | // kUsesAntiAlias | // kUsesMaskFilter // }; static constexpr DisplayListAttributeFlags kDrawImageNineFlags{ kIgnoresPaint // }; static constexpr DisplayListAttributeFlags kDrawImageNineWithPaintFlags{ kBaseImageFlags // }; static constexpr DisplayListAttributeFlags kDrawAtlasFlags{ kIgnoresPaint // }; static constexpr DisplayListAttributeFlags kDrawAtlasWithPaintFlags{ kBaseImageFlags // }; static constexpr DisplayListAttributeFlags kDrawDisplayListFlags{ kIgnoresPaint // }; static constexpr DisplayListAttributeFlags kDrawTextBlobFlags{ DisplayListAttributeFlags(kBasePaintFlags | // kBaseStrokeOrFillFlags | // kMayHaveJoins) // - kUsesAntiAlias // }; static constexpr DisplayListAttributeFlags kDrawShadowFlags{ kIgnoresPaint // };};
} // namespace flutter
#endif // FLUTTER_DISPLAY_LIST_DL_OP_FLAGS_H_1234567891011// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#include "flutter/display_list/dl_op_receiver.h"
namespace flutter {
// Just exists to ensure that the header can be cleanly imported.
} // namespace flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#ifndef FLUTTER_DISPLAY_LIST_DL_OP_RECEIVER_H_#define FLUTTER_DISPLAY_LIST_DL_OP_RECEIVER_H_
#include "flutter/display_list/display_list.h"#include "flutter/display_list/dl_blend_mode.h"#include "flutter/display_list/dl_canvas.h"#include "flutter/display_list/dl_paint.h"#include "flutter/display_list/dl_sampling_options.h"#include "flutter/display_list/dl_vertices.h"#include "flutter/display_list/effects/dl_color_filter.h"#include "flutter/display_list/effects/dl_color_source.h"#include "flutter/display_list/effects/dl_image_filter.h"#include "flutter/display_list/effects/dl_mask_filter.h"#include "flutter/display_list/image/dl_image.h"
namespace flutter {
class DisplayList;
//------------------------------------------------------------------------------/// @brief Internal API for rendering recorded display lists to backends.////// The |DisplayList| object will play back recorded operations in this format./// Most developers should not need to deal with this interface unless they are/// writing a utility that needs to examine the contents of a display list.////// Similar to |DlCanvas|, this interface carries clip and transform state/// which are saved and restored by the |save|, |saveLayer|, and |restore|/// calls.////// Unlike DlCanvas, this interface has attribute state which is global across/// an entire DisplayList (not affected by save/restore).////// DISPLAYLIST DEPTH TRACKING////// Each rendering call in the DisplayList stream is assumed to have a "depth"/// value relative to the beginning of its DisplayList. The depth value is/// implicitly allocated during recording and only reported in 2 places so/// it is important for a dispatcher to perform the same internal allocations/// if it is to make sense of the information reported by the save/saveLayer/// calls. This depth value is maintained as follows:////// - The absolute depth value is never reported, only the total depth/// size of the entire DisplayList or one of its save/restore pairs/// is reported. Since the DisplayList might be dispatched recursively/// due to embedded drawDisplayList calls, these depth size values/// will often be relative to things like:/// - the start of a given save/saveLayer group/// - the start of a DisplayList dispatch or recursion/// as such, only totals for groups of DisplayList dispatched calls/// will be reported. These totals will be reported in:/// - the `DisplayList::total_depth()` method reporting the total/// depth accumulated for every operation in the DisplayList/// - the save/saveLayer dispatch calls will report the total/// depth accumulated for every call until their corresponding/// restore call./// - The depth value is incremented for every drawing operation, including:/// - all draw* calls (including drawDisplayList)/// - drawDisplayList will also accumulate the total_depth() of the/// DisplayList object it is drawing (in other words it will skip enough/// depth values for each drawing call in the child)./// This bump is in addition to the depth value it records for being/// a rendering operation. Some implementations may need to surround/// the actual drawDisplayList with a protective saveLayer, but others/// may not - so the implicit depth value assigned to the drawDisplayList/// call itself may go unused, but must be accounted for./// - a saveLayer call will also increment the depth value just like a/// rendering call. This is in addition to the depth of its content./// It is doing so to reserve a depth for the drawing operation that/// copies its layer back to the parent./// - Each save() or saveLayer() call will report the total depth of all/// rendering calls within its content (recorded before the corresponding/// restore) and report this total during dispatch. This information might/// be needed to assign depths to the clip operations that occur within/// its content. As there is no enclosing saveLayer/restore pair around/// the root of a DisplayList, the total depth of the DisplayList can/// be used to determine the appropriate clip depths for any clip ops/// appearing before the first save/saveLayer or after the last restore.////// @see DlSkCanvasDispatcher/// @see impeller::DlDispatcher/// @see DlOpSpyclass DlOpReceiver { public: // MaxDrawPointsCount * sizeof(DlPoint) must be less than 1 << 32 static constexpr int kMaxDrawPointsCount = ((1 << 29) - 1);
// The following methods are nearly 1:1 with the methods on DlPaint and // carry the same meanings. Each method sets a persistent value for the // attribute for the rest of the display list or until it is reset by // another method that changes the same attribute. The current set of // attributes is not affected by |save| and |restore|. virtual void setAntiAlias(bool aa) = 0; virtual void setDrawStyle(DlDrawStyle style) = 0; virtual void setColor(DlColor color) = 0; virtual void setStrokeWidth(float width) = 0; virtual void setStrokeMiter(float limit) = 0; virtual void setStrokeCap(DlStrokeCap cap) = 0; virtual void setStrokeJoin(DlStrokeJoin join) = 0; virtual void setColorSource(const DlColorSource* source) = 0; virtual void setColorFilter(const DlColorFilter* filter) = 0; // setInvertColors is a quick way to set a ColorFilter that inverts the // rgb values of all rendered colors. // It is not reset by |setColorFilter|, but instead composed with that // filter so that the color inversion happens after the ColorFilter. virtual void setInvertColors(bool invert) = 0; virtual void setBlendMode(DlBlendMode mode) = 0; virtual void setMaskFilter(const DlMaskFilter* filter) = 0; virtual void setImageFilter(const DlImageFilter* filter) = 0;
// All of the following methods are nearly 1:1 with their counterparts // in |SkCanvas| and have the same behavior and output. virtual void save() = 0; // Optional variant of save() that passes the total depth count of // all rendering operations that occur until the next restore() call. virtual void save(uint32_t total_content_depth) { save(); } // The |options| parameter can specify whether the existing rendering // attributes will be applied to the save layer surface while rendering // it back to the current surface. If the flag is false then this method // is equivalent to |SkCanvas::saveLayer| with a null paint object. // // The |options| parameter can also specify whether the bounds came from // the caller who recorded the operation, or whether they were calculated // by the DisplayListBuilder. // // The |options| parameter may contain other options that indicate some // specific optimizations may be made by the underlying implementation // to avoid creating a temporary layer, these optimization options will // be determined as the |DisplayList| is constructed and should not be // specified in calling a |DisplayListBuilder| as they will be ignored. // The |backdrop| filter, if not null, is used to initialize the new // layer before further rendering happens. virtual void saveLayer(const DlRect& bounds, const SaveLayerOptions options, const DlImageFilter* backdrop = nullptr, std::optional<int64_t> backdrop_id = std::nullopt) = 0; // Optional variant of saveLayer() that passes the total depth count of // all rendering operations that occur until the next restore() call. virtual void saveLayer(const DlRect& bounds, const SaveLayerOptions& options, uint32_t total_content_depth, DlBlendMode max_content_blend_mode, const DlImageFilter* backdrop = nullptr, std::optional<int64_t> backdrop_id = std::nullopt) { saveLayer(bounds, options, backdrop, backdrop_id); } virtual void restore() = 0;
// --------------------------------------------------------------------- // Legacy helper method for older callers that use the null-ness of // the bounds to indicate if they should be recorded or computed. // This method will not be called on a |DlOpReceiver| that is passed // to the |DisplayList::Dispatch()| method, so client receivers should // ignore it for their implementation purposes. // // DlOpReceiver methods are generally meant to ONLY be output from a // previously recorded DisplayList so this method is really only used // from testing methods that bypass the public builder APIs for legacy // convenience or for internal white-box testing of the DisplayList // internals. Such methods should eventually be converted to using the // public DisplayListBuilder/DlCanvas public interfaces where possible, // as tracked in: // https://github.com/flutter/flutter/issues/144070 virtual void saveLayer( const DlRect* bounds, const SaveLayerOptions options, const DlImageFilter* backdrop = nullptr, std::optional<int64_t> backdrop_id = std::nullopt) final { if (bounds) { saveLayer(*bounds, options.with_bounds_from_caller(), backdrop, backdrop_id); } else { saveLayer(DlRect(), options.without_bounds_from_caller(), backdrop, backdrop_id); } } // ---------------------------------------------------------------------
virtual void translate(DlScalar tx, DlScalar ty) = 0; virtual void scale(DlScalar sx, DlScalar sy) = 0; virtual void rotate(DlScalar degrees) = 0; virtual void skew(DlScalar sx, DlScalar sy) = 0;
// The transform methods all assume the following math for transforming // an arbitrary 3D homogenous point (x, y, z, w). // All coordinates in the rendering methods (and DlPoint and DlRect objects) // represent a simplified coordinate (x, y, 0, 1). // x' = x * mxx + y * mxy + z * mxz + w * mxt // y' = x * myx + y * myy + z * myz + w * myt // z' = x * mzx + y * mzy + z * mzz + w * mzt // w' = x * mwx + y * mwy + z * mwz + w * mwt // Note that for non-homogenous 2D coordinates, the last column in those // equations is multiplied by 1 and is simply adding a translation and // so is referred to with the final letter "t" here instead of "w". // // In 2D coordinates, z=0 and so the 3rd column always evaluates to 0. // // In non-perspective transforms, the 4th row has identity values // and so w` = w. (i.e. w'=1 for 2d points transformed by a matrix // with identity values in the last row). // // In affine 2D transforms, the 3rd and 4th row and 3rd column are all // identity values and so z` = z (which is 0 for 2D coordinates) and // the x` and y` equations don't see a contribution from a z coordinate // and the w' ends up being the same as the w from the source coordinate // (which is 1 for a 2D coordinate). // // Here is the math for transforming a 2D source coordinate and // looking for the destination 2D coordinate (for a surface that // does not have a Z buffer or track the Z coordinates in any way) // Source coordinate = (x, y, 0, 1) // x' = x * mxx + y * mxy + 0 * mxz + 1 * mxt // y' = x * myx + y * myy + 0 * myz + 1 * myt // z' = x * mzx + y * mzy + 0 * mzz + 1 * mzt // w' = x * mwx + y * mwy + 0 * mwz + 1 * mwt // Destination coordinate does not need z', so this reduces to: // x' = x * mxx + y * mxy + mxt // y' = x * myx + y * myy + myt // w' = x * mwx + y * mwy + mwt // Destination coordinate is (x' / w', y' / w', 0, 1) // Note that these are the matrix values in SkMatrix which means that // an SkMatrix contains enough data to transform a 2D source coordinate // and place it on a 2D surface, but is otherwise not enough to continue // concatenating with further matrices as its missing elements will not // be able to model the interplay between the rows and columns that // happens during a full 4x4 by 4x4 matrix multiplication. // // If the transform doesn't have any perspective parts (the last // row is identity - 0, 0, 0, 1), then this further simplifies to: // x' = x * mxx + y * mxy + mxt // y' = x * myx + y * myy + myt // w' = x * 0 + y * 0 + 1 = 1 // // In short, while the full 4x4 set of matrix entries needs to be // maintained for accumulating transform mutations accurately, the // actual end work of transforming a single 2D coordinate (or, in // the case of bounds transformations, 4 of them) can be accomplished // with the 9 values from transform3x3 or SkMatrix. // // The only need for the w value here is for homogenous coordinates // which only come up if the perspective elements (the 4th row) of // a transform are non-identity. Otherwise the w always ends up // being 1 in all calculations. If the matrix has perspecitve elements // then the final transformed coordinates will have a w that is not 1 // and the actual coordinates are determined by dividing out that w // factor resulting in a real-world point expressed as (x, y, z, 1). // // Because of the predominance of 2D affine transforms the // 2x3 subset of the 4x4 transform matrix is special cased with // its own dispatch method that omits the last 2 rows and the 3rd // column. Even though a 3x3 subset is enough for transforming // leaf coordinates as shown above, no method is provided for // representing a 3x3 transform in the DisplayList since if there // is perspective involved then a full 4x4 matrix should be provided // for accurate concatenations. Providing a 3x3 method or record // in the stream would encourage developers to prematurely subset // a full perspective matrix.
// clang-format off
// |transform2DAffine| is equivalent to concatenating the internal // 4x4 transform with the following row major transform matrix: // [ mxx mxy 0 mxt ] // [ myx myy 0 myt ] // [ 0 0 1 0 ] // [ 0 0 0 1 ] virtual void transform2DAffine(DlScalar mxx, DlScalar mxy, DlScalar mxt, DlScalar myx, DlScalar myy, DlScalar myt) = 0; // |transformFullPerspective| is equivalent to concatenating the internal // 4x4 transform with the following row major transform matrix: // [ mxx mxy mxz mxt ] // [ myx myy myz myt ] // [ mzx mzy mzz mzt ] // [ mwx mwy mwz mwt ] virtual void transformFullPerspective( DlScalar mxx, DlScalar mxy, DlScalar mxz, DlScalar mxt, DlScalar myx, DlScalar myy, DlScalar myz, DlScalar myt, DlScalar mzx, DlScalar mzy, DlScalar mzz, DlScalar mzt, DlScalar mwx, DlScalar mwy, DlScalar mwz, DlScalar mwt) = 0; // clang-format on
// Clears the transformation stack. virtual void transformReset() = 0;
virtual void clipRect(const DlRect& rect, DlClipOp clip_op, bool is_aa) = 0; virtual void clipOval(const DlRect& bounds, DlClipOp clip_op, bool is_aa) = 0; virtual void clipRoundRect(const DlRoundRect& rrect, DlClipOp clip_op, bool is_aa) = 0; virtual void clipRoundSuperellipse(const DlRoundSuperellipse& rse, DlClipOp clip_op, bool is_aa) = 0; virtual void clipPath(const DlPath& path, DlClipOp clip_op, bool is_aa) = 0;
// The following rendering methods all take their rendering attributes // from the last value set by the attribute methods above (regardless // of any |save| or |restore| operations which do not affect attributes). // In cases where a paint object may have been optional in the SkCanvas // method, the methods here will generally offer a boolean parameter // which specifies whether to honor the attributes of the display list // stream, or assume default attributes. virtual void drawColor(DlColor color, DlBlendMode mode) = 0; virtual void drawPaint() = 0; virtual void drawLine(const DlPoint& p0, const DlPoint& p1) = 0; virtual void drawDashedLine(const DlPoint& p0, const DlPoint& p1, DlScalar on_length, DlScalar off_length) = 0; virtual void drawRect(const DlRect& rect) = 0; virtual void drawOval(const DlRect& bounds) = 0; virtual void drawCircle(const DlPoint& center, DlScalar radius) = 0; virtual void drawRoundRect(const DlRoundRect& rrect) = 0; virtual void drawDiffRoundRect(const DlRoundRect& outer, const DlRoundRect& inner) = 0; virtual void drawRoundSuperellipse(const DlRoundSuperellipse& rse) = 0; virtual void drawPath(const DlPath& path) = 0; virtual void drawArc(const DlRect& oval_bounds, DlScalar start_degrees, DlScalar sweep_degrees, bool use_center) = 0; virtual void drawPoints(DlPointMode mode, uint32_t count, const DlPoint points[]) = 0; virtual void drawVertices(const std::shared_ptr<DlVertices>& vertices, DlBlendMode mode) = 0; virtual void drawImage(const sk_sp<DlImage> image, const DlPoint& point, DlImageSampling sampling, bool render_with_attributes) = 0; virtual void drawImageRect( const sk_sp<DlImage> image, const DlRect& src, const DlRect& dst, DlImageSampling sampling, bool render_with_attributes, DlSrcRectConstraint constraint = DlSrcRectConstraint::kFast) = 0; virtual void drawImageNine(const sk_sp<DlImage> image, const DlIRect& center, const DlRect& dst, DlFilterMode filter, bool render_with_attributes) = 0; virtual void drawAtlas(const sk_sp<DlImage> atlas, const DlRSTransform xform[], const DlRect tex[], const DlColor colors[], int count, DlBlendMode mode, DlImageSampling sampling, const DlRect* cull_rect, bool render_with_attributes) = 0; virtual void drawDisplayList(const sk_sp<DisplayList> display_list, DlScalar opacity = SK_Scalar1) = 0; virtual void drawTextBlob(const sk_sp<SkTextBlob> blob, DlScalar x, DlScalar y) = 0; virtual void drawTextFrame( const std::shared_ptr<impeller::TextFrame>& text_frame, DlScalar x, DlScalar y) = 0; virtual void drawShadow(const DlPath& path, const DlColor color, const DlScalar elevation, bool transparent_occluder, DlScalar dpr) = 0;};
} // namespace flutter
#endif // FLUTTER_DISPLAY_LIST_DL_OP_RECEIVER_H_1234567891011// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#include "flutter/display_list/dl_op_records.h"
namespace flutter {
// Just exists to ensure that the header can be cleanly imported.
} // namespace flutter1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#ifndef FLUTTER_DISPLAY_LIST_DL_OP_RECORDS_H_#define FLUTTER_DISPLAY_LIST_DL_OP_RECORDS_H_
#include "flutter/display_list/display_list.h"#include "flutter/display_list/dl_blend_mode.h"#include "flutter/display_list/dl_op_receiver.h"#include "flutter/display_list/dl_sampling_options.h"#include "flutter/display_list/effects/dl_color_sources.h"#include "flutter/display_list/utils/dl_comparable.h"#include "flutter/fml/macros.h"
#include "flutter/impeller/geometry/path.h"#include "flutter/impeller/typographer/text_frame.h"
namespace flutter {
// Most Ops can be bulk compared using memcmp because they contain// only numeric values or constructs that are constructed from numeric// values.//// Some contain sk_sp<> references which can also be bulk compared// to see if they are pointing to the same reference. (Note that// two sk_sp<> that refer to the same object are themselves ==.)//// Only a DLOp that wants to do a deep compare needs to override the// DLOp::equals() method and return a value of kEqual or kNotEqual.enum class DisplayListCompare { // The Op is deferring comparisons to a bulk memcmp performed lazily // across all bulk-comparable ops. kUseBulkCompare,
// The Op provided a specific equals method that spotted a difference kNotEqual,
// The Op provided a specific equals method that saw no differences kEqual,};
// "DLOpPackLabel" is just a label for the pack pragma so it can be popped// later.#pragma pack(push, DLOpPackLabel, 8)
// Assuming a 64-bit platform (most of our platforms at this time?)// the following comments are a "worst case" assessment of how well// these structures pack into memory. They may be packed more tightly// on some of the 32-bit platforms that we see in older phones.//// Struct allocation in the DL memory is aligned to a void* boundary// which means that the minimum (aligned) struct size will be 8 bytes.// The DLOp base uses 4 bytes so each Op-specific struct gets 4 bytes// of data for "free" and works best when it packs well into an 8-byte// aligned size.struct DLOp { static constexpr uint32_t kDepthInc = 0; static constexpr uint32_t kRenderOpInc = 0;
explicit DLOp(DisplayListOpType type) : type(type) {}
const DisplayListOpType type;
DisplayListCompare equals(const DLOp* other) const { return DisplayListCompare::kUseBulkCompare; }};
// 4 byte header + 4 byte payload packs into minimum 8 bytes#define DEFINE_SET_BOOL_OP(name) \ struct Set##name##Op final : DLOp { \ static constexpr auto kType = DisplayListOpType::kSet##name; \ \ explicit Set##name##Op(bool value) : DLOp(kType), value(value) {} \ \ const bool value; \ \ void dispatch(DlOpReceiver& receiver) const { \ receiver.set##name(value); \ } \ };DEFINE_SET_BOOL_OP(AntiAlias)DEFINE_SET_BOOL_OP(InvertColors)#undef DEFINE_SET_BOOL_OP
// 4 byte header + 4 byte payload packs into minimum 8 bytes#define DEFINE_SET_ENUM_OP(name) \ struct SetStroke##name##Op final : DLOp { \ static constexpr auto kType = DisplayListOpType::kSetStroke##name; \ \ explicit SetStroke##name##Op(DlStroke##name value) \ : DLOp(kType), value(value) {} \ \ const DlStroke##name value; \ \ void dispatch(DlOpReceiver& receiver) const { \ receiver.setStroke##name(value); \ } \ };DEFINE_SET_ENUM_OP(Cap)DEFINE_SET_ENUM_OP(Join)#undef DEFINE_SET_ENUM_OP
// 4 byte header + 4 byte payload packs into minimum 8 bytesstruct SetStyleOp final : DLOp { static constexpr auto kType = DisplayListOpType::kSetStyle;
explicit SetStyleOp(DlDrawStyle style) : DLOp(kType), style(style) {}
const DlDrawStyle style;
void dispatch(DlOpReceiver& receiver) const { // receiver.setDrawStyle(style); }};// 4 byte header + 4 byte payload packs into minimum 8 bytesstruct SetStrokeWidthOp final : DLOp { static constexpr auto kType = DisplayListOpType::kSetStrokeWidth;
explicit SetStrokeWidthOp(float width) : DLOp(kType), width(width) {}
const float width;
void dispatch(DlOpReceiver& receiver) const { receiver.setStrokeWidth(width); }};// 4 byte header + 4 byte payload packs into minimum 8 bytesstruct SetStrokeMiterOp final : DLOp { static constexpr auto kType = DisplayListOpType::kSetStrokeMiter;
explicit SetStrokeMiterOp(float limit) : DLOp(kType), limit(limit) {}
const float limit;
void dispatch(DlOpReceiver& receiver) const { receiver.setStrokeMiter(limit); }};
// 4 byte header + 20 byte payload packs into minimum 24 bytesstruct SetColorOp final : DLOp { static constexpr auto kType = DisplayListOpType::kSetColor;
explicit SetColorOp(DlColor color) : DLOp(kType), color(color) {}
const DlColor color;
void dispatch(DlOpReceiver& receiver) const { receiver.setColor(color); }};// 4 byte header + 4 byte payload packs into minimum 8 bytesstruct SetBlendModeOp final : DLOp { static constexpr auto kType = DisplayListOpType::kSetBlendMode;
explicit SetBlendModeOp(DlBlendMode mode) : DLOp(kType), mode(mode) {}
const DlBlendMode mode;
void dispatch(DlOpReceiver& receiver) const { // receiver.setBlendMode(mode); }};
// Clear: 4 byte header + unused 4 byte payload uses 8 bytes// (4 bytes unused)// Set: 4 byte header + unused 4 byte struct padding + Dl<name>// instance copied to the memory following the record// yields a size and efficiency that has somewhere between// 4 and 8 bytes unused#define DEFINE_SET_CLEAR_DLATTR_OP(name, field) \ struct Clear##name##Op final : DLOp { \ static constexpr auto kType = DisplayListOpType::kClear##name; \ \ Clear##name##Op() : DLOp(kType) {} \ \ void dispatch(DlOpReceiver& receiver) const { \ receiver.set##name(nullptr); \ } \ }; \ struct SetPod##name##Op final : DLOp { \ static constexpr auto kType = DisplayListOpType::kSetPod##name; \ \ SetPod##name##Op() : DLOp(kType) {} \ \ void dispatch(DlOpReceiver& receiver) const { \ const Dl##name* filter = reinterpret_cast<const Dl##name*>(this + 1); \ receiver.set##name(filter); \ } \ };DEFINE_SET_CLEAR_DLATTR_OP(ColorFilter, filter)DEFINE_SET_CLEAR_DLATTR_OP(ImageFilter, filter)DEFINE_SET_CLEAR_DLATTR_OP(MaskFilter, filter)DEFINE_SET_CLEAR_DLATTR_OP(ColorSource, source)#undef DEFINE_SET_CLEAR_DLATTR_OP
// 4 byte header + 96 bytes for the embedded DlImageColorSource// uses 104 total bytes (4 bytes unused)struct SetImageColorSourceOp : DLOp { static constexpr auto kType = DisplayListOpType::kSetImageColorSource;
explicit SetImageColorSourceOp(const DlImageColorSource* source) : DLOp(kType), source(source->image(), source->horizontal_tile_mode(), source->vertical_tile_mode(), source->sampling(), source->matrix_ptr()) {}
const DlImageColorSource source;
void dispatch(DlOpReceiver& receiver) const { receiver.setColorSource(&source); }};
// 56 bytes: 4 byte header, 4 byte padding, 8 for vtable, 8 * 2 for sk_sps, 24// for the std::vector.struct SetRuntimeEffectColorSourceOp : DLOp { static constexpr auto kType = DisplayListOpType::kSetRuntimeEffectColorSource;
explicit SetRuntimeEffectColorSourceOp( const DlRuntimeEffectColorSource* source) : DLOp(kType), source(source->runtime_effect(), source->samplers(), source->uniform_data()) {}
const DlRuntimeEffectColorSource source;
void dispatch(DlOpReceiver& receiver) const { receiver.setColorSource(&source); }
DisplayListCompare equals(const SetRuntimeEffectColorSourceOp* other) const { return (source == other->source) ? DisplayListCompare::kEqual : DisplayListCompare::kNotEqual; }};
// 4 byte header + 16 byte payload uses 24 total bytes (4 bytes unused)struct SetSharedImageFilterOp : DLOp { static constexpr auto kType = DisplayListOpType::kSetSharedImageFilter;
explicit SetSharedImageFilterOp(const DlImageFilter* filter) : DLOp(kType), filter(filter->shared()) {}
const std::shared_ptr<DlImageFilter> filter;
void dispatch(DlOpReceiver& receiver) const { receiver.setImageFilter(filter.get()); }
DisplayListCompare equals(const SetSharedImageFilterOp* other) const { return Equals(filter, other->filter) ? DisplayListCompare::kEqual : DisplayListCompare::kNotEqual; }};
// The base struct for all save() and saveLayer() ops// 4 byte header + 12 byte payload packs exactly into 16 bytesstruct SaveOpBase : DLOp { static constexpr uint32_t kDepthInc = 0; static constexpr uint32_t kRenderOpInc = 1;
explicit SaveOpBase(DisplayListOpType type) : DLOp(type), options(), restore_index(0), total_content_depth(0) {}
SaveOpBase(DisplayListOpType type, const SaveLayerOptions& options) : DLOp(type), options(options), restore_index(0), total_content_depth(0) {}
// options parameter is only used by saveLayer operations, but since // it packs neatly into the empty space created by laying out the rest // of the data here, it can be stored for free and defaulted to 0 for // save operations. SaveLayerOptions options; DlIndex restore_index; uint32_t total_content_depth;};// 16 byte SaveOpBase with no additional data (options is unsed here)struct SaveOp final : SaveOpBase { static constexpr auto kType = DisplayListOpType::kSave;
SaveOp() : SaveOpBase(kType) {}
void dispatch(DlOpReceiver& receiver) const { receiver.save(total_content_depth); }};// The base struct for all saveLayer() ops// 16 byte SaveOpBase + 20 byte payload packs into 36 bytesstruct SaveLayerOpBase : SaveOpBase { SaveLayerOpBase(DisplayListOpType type, const SaveLayerOptions& options, const DlRect& rect) : SaveOpBase(type, options), rect(rect) {}
DlRect rect; DlBlendMode max_blend_mode = DlBlendMode::kClear;};// 36 byte SaveLayerOpBase with no additional data packs into 40 bytes// of buffer storage with 4 bytes unused.struct SaveLayerOp final : SaveLayerOpBase { static constexpr auto kType = DisplayListOpType::kSaveLayer;
SaveLayerOp(const SaveLayerOptions& options, const DlRect& rect) : SaveLayerOpBase(kType, options, rect) {}
void dispatch(DlOpReceiver& receiver) const { receiver.saveLayer(rect, options, total_content_depth, max_blend_mode); }};// 36 byte SaveLayerOpBase + 4 bytes for alignment + 16 byte payload packs// into minimum 56 bytesstruct SaveLayerBackdropOp final : SaveLayerOpBase { static constexpr auto kType = DisplayListOpType::kSaveLayerBackdrop;
SaveLayerBackdropOp(const SaveLayerOptions& options, const DlRect& rect, const DlImageFilter* backdrop, std::optional<int64_t> backdrop_id) : SaveLayerOpBase(kType, options, rect), backdrop(backdrop->shared()), backdrop_id_(backdrop_id) {}
const std::shared_ptr<DlImageFilter> backdrop; std::optional<int64_t> backdrop_id_;
void dispatch(DlOpReceiver& receiver) const { receiver.saveLayer(rect, options, total_content_depth, max_blend_mode, backdrop.get(), backdrop_id_); }
DisplayListCompare equals(const SaveLayerBackdropOp* other) const { return (options == other->options && rect == other->rect && Equals(backdrop, other->backdrop) && backdrop_id_ == other->backdrop_id_) ? DisplayListCompare::kEqual : DisplayListCompare::kNotEqual; }};// 4 byte header + no payload uses minimum 8 bytes (4 bytes unused)struct RestoreOp final : DLOp { static constexpr auto kType = DisplayListOpType::kRestore; static constexpr uint32_t kDepthInc = 0; static constexpr uint32_t kRenderOpInc = 1;
RestoreOp() : DLOp(kType) {}
void dispatch(DlOpReceiver& receiver) const { // receiver.restore(); }};
struct TransformClipOpBase : DLOp { static constexpr uint32_t kDepthInc = 0; static constexpr uint32_t kRenderOpInc = 1;
explicit TransformClipOpBase(DisplayListOpType type) : DLOp(type) {}};// 4 byte header + 8 byte payload uses 12 bytes but is rounded up to 16 bytes// (4 bytes unused)struct TranslateOp final : TransformClipOpBase { static constexpr auto kType = DisplayListOpType::kTranslate;
TranslateOp(DlScalar tx, DlScalar ty) : TransformClipOpBase(kType), tx(tx), ty(ty) {}
const DlScalar tx; const DlScalar ty;
void dispatch(DlOpReceiver& receiver) const { // receiver.translate(tx, ty); }};// 4 byte header + 8 byte payload uses 12 bytes but is rounded up to 16 bytes// (4 bytes unused)struct ScaleOp final : TransformClipOpBase { static constexpr auto kType = DisplayListOpType::kScale;
ScaleOp(DlScalar sx, DlScalar sy) : TransformClipOpBase(kType), sx(sx), sy(sy) {}
const DlScalar sx; const DlScalar sy;
void dispatch(DlOpReceiver& receiver) const { // receiver.scale(sx, sy); }};// 4 byte header + 4 byte payload packs into minimum 8 bytesstruct RotateOp final : TransformClipOpBase { static constexpr auto kType = DisplayListOpType::kRotate;
explicit RotateOp(DlScalar degrees) : TransformClipOpBase(kType), degrees(degrees) {}
const DlScalar degrees;
void dispatch(DlOpReceiver& receiver) const { // receiver.rotate(degrees); }};// 4 byte header + 8 byte payload uses 12 bytes but is rounded up to 16 bytes// (4 bytes unused)struct SkewOp final : TransformClipOpBase { static constexpr auto kType = DisplayListOpType::kSkew;
SkewOp(DlScalar sx, DlScalar sy) : TransformClipOpBase(kType), sx(sx), sy(sy) {}
const DlScalar sx; const DlScalar sy;
void dispatch(DlOpReceiver& receiver) const { // receiver.skew(sx, sy); }};// 4 byte header + 24 byte payload uses 28 bytes but is rounded up to 32 bytes// (4 bytes unused)struct Transform2DAffineOp final : TransformClipOpBase { static constexpr auto kType = DisplayListOpType::kTransform2DAffine;
// clang-format off Transform2DAffineOp(DlScalar mxx, DlScalar mxy, DlScalar mxt, DlScalar myx, DlScalar myy, DlScalar myt) : TransformClipOpBase(kType), mxx(mxx), mxy(mxy), mxt(mxt), myx(myx), myy(myy), myt(myt) {} // clang-format on
const DlScalar mxx, mxy, mxt; const DlScalar myx, myy, myt;
void dispatch(DlOpReceiver& receiver) const { receiver.transform2DAffine(mxx, mxy, mxt, // myx, myy, myt); }};// 4 byte header + 64 byte payload uses 68 bytes which is rounded up to 72 bytes// (4 bytes unused)struct TransformFullPerspectiveOp final : TransformClipOpBase { static constexpr auto kType = DisplayListOpType::kTransformFullPerspective;
// clang-format off TransformFullPerspectiveOp( DlScalar mxx, DlScalar mxy, DlScalar mxz, DlScalar mxt, DlScalar myx, DlScalar myy, DlScalar myz, DlScalar myt, DlScalar mzx, DlScalar mzy, DlScalar mzz, DlScalar mzt, DlScalar mwx, DlScalar mwy, DlScalar mwz, DlScalar mwt) : TransformClipOpBase(kType), mxx(mxx), mxy(mxy), mxz(mxz), mxt(mxt), myx(myx), myy(myy), myz(myz), myt(myt), mzx(mzx), mzy(mzy), mzz(mzz), mzt(mzt), mwx(mwx), mwy(mwy), mwz(mwz), mwt(mwt) {} // clang-format on
const DlScalar mxx, mxy, mxz, mxt; const DlScalar myx, myy, myz, myt; const DlScalar mzx, mzy, mzz, mzt; const DlScalar mwx, mwy, mwz, mwt;
void dispatch(DlOpReceiver& receiver) const { receiver.transformFullPerspective(mxx, mxy, mxz, mxt, // myx, myy, myz, myt, // mzx, mzy, mzz, mzt, // mwx, mwy, mwz, mwt); }};
// 4 byte header with no payload.struct TransformResetOp final : TransformClipOpBase { static constexpr auto kType = DisplayListOpType::kTransformReset;
TransformResetOp() : TransformClipOpBase(kType) {}
void dispatch(DlOpReceiver& receiver) const { // receiver.transformReset(); }};
// 4 byte header + 4 byte common payload packs into minimum 8 bytes// DlRect is 16 more bytes, which packs efficiently into 24 bytes total// DlRoundRect is 48 more bytes, which rounds up to 48 bytes// which packs into 56 bytes total// DlRoundSuperellipse is the same as DlRoundRect// CacheablePath is 128 more bytes, which packs efficiently into 136 bytes total//// We could pack the clip_op and the bool both into the free 4 bytes after// the header, but the Windows compiler keeps wanting to expand that// packing into more bytes than needed (even when they are declared as// packed bit fields!)#define DEFINE_CLIP_SHAPE_OP(shapename, shapetype, clipop) \ struct Clip##clipop##shapename##Op final : TransformClipOpBase { \ static constexpr auto kType = DisplayListOpType::kClip##clipop##shapename; \ \ Clip##clipop##shapename##Op(shapetype shape, bool is_aa) \ : TransformClipOpBase(kType), is_aa(is_aa), shape(shape) {} \ \ const bool is_aa; \ const shapetype shape; \ \ void dispatch(DlOpReceiver& receiver) const { \ receiver.clip##shapename(shape, DlClipOp::k##clipop, is_aa); \ } \ };DEFINE_CLIP_SHAPE_OP(Rect, DlRect, Intersect)DEFINE_CLIP_SHAPE_OP(Oval, DlRect, Intersect)DEFINE_CLIP_SHAPE_OP(RoundRect, DlRoundRect, Intersect)DEFINE_CLIP_SHAPE_OP(RoundSuperellipse, DlRoundSuperellipse, Intersect)DEFINE_CLIP_SHAPE_OP(Rect, DlRect, Difference)DEFINE_CLIP_SHAPE_OP(Oval, DlRect, Difference)DEFINE_CLIP_SHAPE_OP(RoundRect, DlRoundRect, Difference)DEFINE_CLIP_SHAPE_OP(RoundSuperellipse, DlRoundSuperellipse, Difference)#undef DEFINE_CLIP_SHAPE_OP
// 4 byte header + 20 byte payload packs evenly into 24 bytes#define DEFINE_CLIP_PATH_OP(clipop) \ struct Clip##clipop##PathOp final : TransformClipOpBase { \ static constexpr auto kType = DisplayListOpType::kClip##clipop##Path; \ \ Clip##clipop##PathOp(const DlPath& path, bool is_aa) \ : TransformClipOpBase(kType), is_aa(is_aa), path(path) {} \ \ const bool is_aa; \ const DlPath path; \ \ void dispatch(DlOpReceiver& receiver) const { \ receiver.clipPath(path, DlClipOp::k##clipop, is_aa); \ } \ \ DisplayListCompare equals(const Clip##clipop##PathOp* other) const { \ return is_aa == other->is_aa && path == other->path \ ? DisplayListCompare::kEqual \ : DisplayListCompare::kNotEqual; \ } \ };DEFINE_CLIP_PATH_OP(Intersect)DEFINE_CLIP_PATH_OP(Difference)#undef DEFINE_CLIP_PATH_OP
struct DrawOpBase : DLOp { static constexpr uint32_t kDepthInc = 1; static constexpr uint32_t kRenderOpInc = 1;
explicit DrawOpBase(DisplayListOpType type) : DLOp(type) {}};
// 4 byte header + no payload uses minimum 8 bytes (4 bytes unused)struct DrawPaintOp final : DrawOpBase { static constexpr auto kType = DisplayListOpType::kDrawPaint;
DrawPaintOp() : DrawOpBase(kType) {}
void dispatch(DlOpReceiver& receiver) const { // receiver.drawPaint(); }};// 4 byte header + 8 byte payload uses 12 bytes but is rounded up to 16 bytes// (4 bytes unused)struct DrawColorOp final : DrawOpBase { static constexpr auto kType = DisplayListOpType::kDrawColor;
DrawColorOp(DlColor color, DlBlendMode mode) : DrawOpBase(kType), color(color), mode(mode) {}
const DlColor color; const DlBlendMode mode;
void dispatch(DlOpReceiver& receiver) const { receiver.drawColor(color, mode); }};
// The common data is a 4 byte header with an unused 4 bytes// DlRect is 16 more bytes, using 20 bytes which rounds up to 24 bytes total// (4 bytes unused)// SkOval is same as DlRect// DlRoundRect is 48 more bytes, using 52 bytes which rounds up to 56 bytes// total (4 bytes unused)// DlRoundSuperellipse is the same as DlRoundRect#define DEFINE_DRAW_1ARG_OP(op_name, arg_type, arg_name) \ struct Draw##op_name##Op final : DrawOpBase { \ static constexpr auto kType = DisplayListOpType::kDraw##op_name; \ \ explicit Draw##op_name##Op(arg_type arg_name) \ : DrawOpBase(kType), arg_name(arg_name) {} \ \ const arg_type arg_name; \ \ void dispatch(DlOpReceiver& receiver) const { \ receiver.draw##op_name(arg_name); \ } \ };DEFINE_DRAW_1ARG_OP(Rect, DlRect, rect)DEFINE_DRAW_1ARG_OP(Oval, DlRect, oval)DEFINE_DRAW_1ARG_OP(RoundRect, DlRoundRect, rrect)DEFINE_DRAW_1ARG_OP(RoundSuperellipse, DlRoundSuperellipse, rse)#undef DEFINE_DRAW_1ARG_OP
// 4 byte header + 16 byte payload uses 20 bytes but is rounded// up to 24 bytes (4 bytes unused)struct DrawPathOp final : DrawOpBase { static constexpr auto kType = DisplayListOpType::kDrawPath;
explicit DrawPathOp(const DlPath& path) : DrawOpBase(kType), path(path) {}
const DlPath path;
void dispatch(DlOpReceiver& receiver) const { // receiver.drawPath(path); }
DisplayListCompare equals(const DrawPathOp* other) const { return path == other->path ? DisplayListCompare::kEqual : DisplayListCompare::kNotEqual; }};
// The common data is a 4 byte header with an unused 4 bytes// 2 x DlPoint is 16 more bytes, using 20 bytes rounding up to 24 bytes total// (4 bytes unused)// DlPoint + DlScalar is 12 more bytes, packing efficiently into 16 bytes total// 2 x DlRoundRect is 96 more bytes, using 100 and rounding up to 104 bytes// total (4 bytes unused)#define DEFINE_DRAW_2ARG_OP(op_name, type1, name1, type2, name2) \ struct Draw##op_name##Op final : DrawOpBase { \ static constexpr auto kType = DisplayListOpType::kDraw##op_name; \ \ Draw##op_name##Op(type1 name1, type2 name2) \ : DrawOpBase(kType), name1(name1), name2(name2) {} \ \ const type1 name1; \ const type2 name2; \ \ void dispatch(DlOpReceiver& receiver) const { \ receiver.draw##op_name(name1, name2); \ } \ };DEFINE_DRAW_2ARG_OP(Line, DlPoint, p0, DlPoint, p1)DEFINE_DRAW_2ARG_OP(Circle, DlPoint, center, DlScalar, radius)DEFINE_DRAW_2ARG_OP(DiffRoundRect, DlRoundRect, outer, DlRoundRect, inner)#undef DEFINE_DRAW_2ARG_OP
// 4 byte header + 24 byte payload packs into 32 bytes (4 bytes unused)struct DrawDashedLineOp final : DrawOpBase { static constexpr auto kType = DisplayListOpType::kDrawDashedLine;
DrawDashedLineOp(const DlPoint& p0, const DlPoint& p1, DlScalar on_length, DlScalar off_length) : DrawOpBase(kType), p0(p0), p1(p1), on_length(on_length), off_length(off_length) {}
const DlPoint p0; const DlPoint p1; const DlScalar on_length; const DlScalar off_length;
void dispatch(DlOpReceiver& receiver) const { receiver.drawDashedLine(p0, p1, on_length, off_length); }};
// 4 byte header + 28 byte payload packs efficiently into 32 bytesstruct DrawArcOp final : DrawOpBase { static constexpr auto kType = DisplayListOpType::kDrawArc;
DrawArcOp(DlRect bounds, DlScalar start, DlScalar sweep, bool center) : DrawOpBase(kType), bounds(bounds), start(start), sweep(sweep), center(center) {}
const DlRect bounds; const DlScalar start; const DlScalar sweep; const bool center;
void dispatch(DlOpReceiver& receiver) const { receiver.drawArc(bounds, start, sweep, center); }};
// 4 byte header + 4 byte fixed payload packs efficiently into 8 bytes// But then there is a list of points following the structure which// is guaranteed to be a multiple of 8 bytes (DlPoint is 8 bytes)// so this op will always pack efficiently// The point type is packed into 3 different OpTypes to avoid expanding// the fixed payload beyond the 8 bytes#define DEFINE_DRAW_POINTS_OP(name, mode) \ struct Draw##name##Op final : DrawOpBase { \ static constexpr auto kType = DisplayListOpType::kDraw##name; \ \ explicit Draw##name##Op(uint32_t count) \ : DrawOpBase(kType), count(count) {} \ \ const uint32_t count; \ \ void dispatch(DlOpReceiver& receiver) const { \ const DlPoint* pts = reinterpret_cast<const DlPoint*>(this + 1); \ receiver.drawPoints(DlPointMode::mode, count, pts); \ } \ };DEFINE_DRAW_POINTS_OP(Points, kPoints);DEFINE_DRAW_POINTS_OP(Lines, kLines);DEFINE_DRAW_POINTS_OP(Polygon, kPolygon);#undef DEFINE_DRAW_POINTS_OP
// 4 byte header + 20 byte payload packs efficiently into 24 bytesstruct DrawVerticesOp final : DrawOpBase { static constexpr auto kType = DisplayListOpType::kDrawVertices;
explicit DrawVerticesOp(const std::shared_ptr<DlVertices>& vertices, DlBlendMode mode) : DrawOpBase(kType), mode(mode), vertices(vertices) {}
const DlBlendMode mode; const std::shared_ptr<DlVertices> vertices;
void dispatch(DlOpReceiver& receiver) const { receiver.drawVertices(vertices, mode); }};
// 4 byte header + 40 byte payload uses 44 bytes but is rounded up to 48 bytes// (4 bytes unused)#define DEFINE_DRAW_IMAGE_OP(name, with_attributes) \ struct name##Op final : DrawOpBase { \ static constexpr auto kType = DisplayListOpType::k##name; \ \ name##Op(const sk_sp<DlImage>& image, \ const DlPoint& point, \ DlImageSampling sampling) \ : DrawOpBase(kType), \ point(point), \ sampling(sampling), \ image(std::move(image)) {} \ \ const DlPoint point; \ const DlImageSampling sampling; \ const sk_sp<DlImage> image; \ \ void dispatch(DlOpReceiver& receiver) const { \ receiver.drawImage(image, point, sampling, with_attributes); \ } \ \ DisplayListCompare equals(const name##Op* other) const { \ return (point == other->point && sampling == other->sampling && \ image->Equals(other->image)) \ ? DisplayListCompare::kEqual \ : DisplayListCompare::kNotEqual; \ } \ };DEFINE_DRAW_IMAGE_OP(DrawImage, false)DEFINE_DRAW_IMAGE_OP(DrawImageWithAttr, true)#undef DEFINE_DRAW_IMAGE_OP
// 4 byte header + 72 byte payload uses 76 bytes but is rounded up to 80 bytes// (4 bytes unused)struct DrawImageRectOp final : DrawOpBase { static constexpr auto kType = DisplayListOpType::kDrawImageRect;
DrawImageRectOp(const sk_sp<DlImage>& image, const DlRect& src, const DlRect& dst, DlImageSampling sampling, bool render_with_attributes, DlSrcRectConstraint constraint) : DrawOpBase(kType), src(src), dst(dst), sampling(sampling), render_with_attributes(render_with_attributes), constraint(constraint), image(image) {}
const DlRect src; const DlRect dst; const DlImageSampling sampling; const bool render_with_attributes; const DlSrcRectConstraint constraint; const sk_sp<DlImage> image;
void dispatch(DlOpReceiver& receiver) const { receiver.drawImageRect(image, src, dst, sampling, render_with_attributes, constraint); }
DisplayListCompare equals(const DrawImageRectOp* other) const { return (src == other->src && dst == other->dst && sampling == other->sampling && render_with_attributes == other->render_with_attributes && constraint == other->constraint && image->Equals(other->image)) ? DisplayListCompare::kEqual : DisplayListCompare::kNotEqual; }};
// 4 byte header + 44 byte payload packs efficiently into 48 bytes#define DEFINE_DRAW_IMAGE_NINE_OP(name, render_with_attributes) \ struct name##Op final : DrawOpBase { \ static constexpr auto kType = DisplayListOpType::k##name; \ static constexpr uint32_t kDepthInc = 9; \ \ name##Op(const sk_sp<DlImage>& image, \ const DlIRect& center, \ const DlRect& dst, \ DlFilterMode mode) \ : DrawOpBase(kType), \ center(center), \ dst(dst), \ mode(mode), \ image(std::move(image)) {} \ \ const DlIRect center; \ const DlRect dst; \ const DlFilterMode mode; \ const sk_sp<DlImage> image; \ \ void dispatch(DlOpReceiver& receiver) const { \ receiver.drawImageNine(image, center, dst, mode, \ render_with_attributes); \ } \ \ DisplayListCompare equals(const name##Op* other) const { \ return (center == other->center && dst == other->dst && \ mode == other->mode && image->Equals(other->image)) \ ? DisplayListCompare::kEqual \ : DisplayListCompare::kNotEqual; \ } \ };DEFINE_DRAW_IMAGE_NINE_OP(DrawImageNine, false)DEFINE_DRAW_IMAGE_NINE_OP(DrawImageNineWithAttr, true)#undef DEFINE_DRAW_IMAGE_NINE_OP
// 4 byte header + 40 byte payload uses 44 bytes but is rounded up to 48 bytes// (4 bytes unused)// Each of these is then followed by a number of lists.// DlRSTransform list is a multiple of 16 bytes so it is always packed well// DlRect list is also a multiple of 16 bytes so it also packs well// DlColor list only packs well if the count is even, otherwise there// can be 4 unusued bytes at the end.struct DrawAtlasBaseOp : DrawOpBase { DrawAtlasBaseOp(DisplayListOpType type, const sk_sp<DlImage>& atlas, int count, DlBlendMode mode, DlImageSampling sampling, bool has_colors, bool render_with_attributes) : DrawOpBase(type), count(count), mode_index(static_cast<uint16_t>(mode)), has_colors(has_colors), render_with_attributes(render_with_attributes), sampling(sampling), atlas(atlas) {}
const int count; const uint16_t mode_index; const uint8_t has_colors; const uint8_t render_with_attributes; const DlImageSampling sampling; const sk_sp<DlImage> atlas;
bool equals(const DrawAtlasBaseOp* other, const void* pod_this, const void* pod_other) const { bool ret = (count == other->count && mode_index == other->mode_index && has_colors == other->has_colors && render_with_attributes == other->render_with_attributes && sampling == other->sampling && atlas->Equals(other->atlas)); if (ret) { size_t bytes = count * (sizeof(DlRSTransform) + sizeof(DlRect)); if (has_colors) { bytes += count * sizeof(DlColor); } ret = (memcmp(pod_this, pod_other, bytes) == 0); } return ret; }};
// Packs into 48 bytes as per DrawAtlasBaseOp// with array data following the struct also as per DrawAtlasBaseOpstruct DrawAtlasOp final : DrawAtlasBaseOp { static constexpr auto kType = DisplayListOpType::kDrawAtlas;
DrawAtlasOp(const sk_sp<DlImage>& atlas, int count, DlBlendMode mode, DlImageSampling sampling, bool has_colors, bool render_with_attributes) : DrawAtlasBaseOp(kType, atlas, count, mode, sampling, has_colors, render_with_attributes) {}
void dispatch(DlOpReceiver& receiver) const { const DlRSTransform* xform = reinterpret_cast<const DlRSTransform*>(this + 1); const DlRect* tex = reinterpret_cast<const DlRect*>(xform + count); const DlColor* colors = has_colors ? reinterpret_cast<const DlColor*>(tex + count) : nullptr; const DlBlendMode mode = static_cast<DlBlendMode>(mode_index); receiver.drawAtlas(atlas, xform, tex, colors, count, mode, sampling, nullptr, render_with_attributes); }
DisplayListCompare equals(const DrawAtlasOp* other) const { const void* pod_this = reinterpret_cast<const void*>(this + 1); const void* pod_other = reinterpret_cast<const void*>(other + 1); return (DrawAtlasBaseOp::equals(other, pod_this, pod_other)) ? DisplayListCompare::kEqual : DisplayListCompare::kNotEqual; }};
// Packs into 48 bytes as per DrawAtlasBaseOp plus// an additional 16 bytes for the cull rect resulting in a total// of 56 bytes for the Culled drawAtlas.// Also with array data following the struct as per DrawAtlasBaseOpstruct DrawAtlasCulledOp final : DrawAtlasBaseOp { static constexpr auto kType = DisplayListOpType::kDrawAtlasCulled;
DrawAtlasCulledOp(const sk_sp<DlImage>& atlas, int count, DlBlendMode mode, DlImageSampling sampling, bool has_colors, const DlRect& cull_rect, bool render_with_attributes) : DrawAtlasBaseOp(kType, atlas, count, mode, sampling, has_colors, render_with_attributes), cull_rect(cull_rect) {}
const DlRect cull_rect;
void dispatch(DlOpReceiver& receiver) const { const DlRSTransform* xform = reinterpret_cast<const DlRSTransform*>(this + 1); const DlRect* tex = reinterpret_cast<const DlRect*>(xform + count); const DlColor* colors = has_colors ? reinterpret_cast<const DlColor*>(tex + count) : nullptr; const DlBlendMode mode = static_cast<DlBlendMode>(mode_index); receiver.drawAtlas(atlas, xform, tex, colors, count, mode, sampling, &cull_rect, render_with_attributes); }
DisplayListCompare equals(const DrawAtlasCulledOp* other) const { const void* pod_this = reinterpret_cast<const void*>(this + 1); const void* pod_other = reinterpret_cast<const void*>(other + 1); return (cull_rect == other->cull_rect && DrawAtlasBaseOp::equals(other, pod_this, pod_other)) ? DisplayListCompare::kEqual : DisplayListCompare::kNotEqual; }};
// 4 byte header + ptr aligned payload uses 12 bytes round up to 16// (4 bytes unused)struct DrawDisplayListOp final : DrawOpBase { static constexpr auto kType = DisplayListOpType::kDrawDisplayList;
explicit DrawDisplayListOp(const sk_sp<DisplayList>& display_list, DlScalar opacity) : DrawOpBase(kType), opacity(opacity), display_list(display_list) {}
DlScalar opacity; const sk_sp<DisplayList> display_list;
void dispatch(DlOpReceiver& receiver) const { receiver.drawDisplayList(display_list, opacity); }
DisplayListCompare equals(const DrawDisplayListOp* other) const { return (opacity == other->opacity && display_list->Equals(other->display_list)) ? DisplayListCompare::kEqual : DisplayListCompare::kNotEqual; }};
// 4 byte header + 8 payload bytes + an aligned pointer take 24 bytes// (4 unused to align the pointer)struct DrawTextBlobOp final : DrawOpBase { static constexpr auto kType = DisplayListOpType::kDrawTextBlob;
DrawTextBlobOp(const sk_sp<SkTextBlob>& blob, DlScalar x, DlScalar y) : DrawOpBase(kType), x(x), y(y), blob(blob) {}
const DlScalar x; const DlScalar y; const sk_sp<SkTextBlob> blob;
void dispatch(DlOpReceiver& receiver) const { receiver.drawTextBlob(blob, x, y); }};
struct DrawTextFrameOp final : DrawOpBase { static constexpr auto kType = DisplayListOpType::kDrawTextFrame;
DrawTextFrameOp(const std::shared_ptr<impeller::TextFrame>& text_frame, DlScalar x, DlScalar y) : DrawOpBase(kType), x(x), y(y), text_frame(text_frame) {}
const DlScalar x; const DlScalar y; const std::shared_ptr<impeller::TextFrame> text_frame;
void dispatch(DlOpReceiver& receiver) const { receiver.drawTextFrame(text_frame, x, y); }};
// 4 byte header + 44 byte payload packs evenly into 48 bytes#define DEFINE_DRAW_SHADOW_OP(name, transparent_occluder) \ struct Draw##name##Op final : DrawOpBase { \ static constexpr auto kType = DisplayListOpType::kDraw##name; \ \ Draw##name##Op(const DlPath& path, \ DlColor color, \ DlScalar elevation, \ DlScalar dpr) \ : DrawOpBase(kType), \ color(color), \ elevation(elevation), \ dpr(dpr), \ path(path) {} \ \ const DlColor color; \ const DlScalar elevation; \ const DlScalar dpr; \ const DlPath path; \ \ void dispatch(DlOpReceiver& receiver) const { \ receiver.drawShadow(path, color, elevation, transparent_occluder, dpr); \ } \ \ DisplayListCompare equals(const Draw##name##Op* other) const { \ return color == other->color && elevation == other->elevation && \ dpr == other->dpr && path == other->path \ ? DisplayListCompare::kEqual \ : DisplayListCompare::kNotEqual; \ } \ };DEFINE_DRAW_SHADOW_OP(Shadow, false)DEFINE_DRAW_SHADOW_OP(ShadowTransparentOccluder, true)#undef DEFINE_DRAW_SHADOW_OP
#pragma pack(pop, DLOpPackLabel)
} // namespace flutter
#endif // FLUTTER_DISPLAY_LIST_DL_OP_RECORDS_H_12345678910111213141516171819202122232425262728293031323334353637383940// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#include "flutter/display_list/dl_paint.h"
#include "flutter/display_list/utils/dl_comparable.h"
namespace flutter {
DlPaint::DlPaint(DlColor color) : blend_mode_(static_cast<unsigned>(DlBlendMode::kDefaultMode)), draw_style_(static_cast<unsigned>(DlDrawStyle::kDefaultStyle)), stroke_cap_(static_cast<unsigned>(DlStrokeCap::kDefaultCap)), stroke_join_(static_cast<unsigned>(DlStrokeJoin::kDefaultJoin)), is_anti_alias_(false), is_invert_colors_(false), color_(color), stroke_width_(kDefaultWidth), stroke_miter_(kDefaultMiter) {}
bool DlPaint::operator==(DlPaint const& other) const { return blend_mode_ == other.blend_mode_ && // draw_style_ == other.draw_style_ && // stroke_cap_ == other.stroke_cap_ && // stroke_join_ == other.stroke_join_ && // is_anti_alias_ == other.is_anti_alias_ && // is_invert_colors_ == other.is_invert_colors_ && // color_ == other.color_ && // stroke_width_ == other.stroke_width_ && // stroke_miter_ == other.stroke_miter_ && // Equals(color_source_, other.color_source_) && // Equals(color_filter_, other.color_filter_) && // Equals(image_filter_, other.image_filter_) && // Equals(mask_filter_, other.mask_filter_);}
const DlPaint DlPaint::kDefault;
} // namespace flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#ifndef FLUTTER_DISPLAY_LIST_DL_PAINT_H_#define FLUTTER_DISPLAY_LIST_DL_PAINT_H_
#include <memory>#include <utility>#include "flutter/display_list/dl_blend_mode.h"#include "flutter/display_list/dl_color.h"#include "flutter/display_list/effects/dl_color_filter.h"#include "flutter/display_list/effects/dl_color_source.h"#include "flutter/display_list/effects/dl_image_filter.h"#include "flutter/display_list/effects/dl_mask_filter.h"
namespace flutter {
enum class DlDrawStyle { kFill, //!< fills interior of shapes kStroke, //!< strokes boundary of shapes kStrokeAndFill, //!< both strokes and fills shapes
kLastStyle = kStrokeAndFill, kDefaultStyle = kFill,};
enum class DlStrokeCap { kButt, //!< no stroke extension kRound, //!< adds circle kSquare, //!< adds square
kLastCap = kSquare, kDefaultCap = kButt,};
enum class DlStrokeJoin { kMiter, //!< extends to miter limit kRound, //!< adds circle kBevel, //!< connects outside edges
kLastJoin = kBevel, kDefaultJoin = kMiter,};
class DlPaint { public: static constexpr DlColor kDefaultColor = DlColor::kBlack(); static constexpr float kDefaultWidth = 0.0; static constexpr float kDefaultMiter = 4.0;
static const DlPaint kDefault;
DlPaint() : DlPaint(DlColor::kBlack()) {} explicit DlPaint(DlColor color);
bool isAntiAlias() const { return is_anti_alias_; } DlPaint& setAntiAlias(bool isAntiAlias) { is_anti_alias_ = isAntiAlias; return *this; }
bool isInvertColors() const { return is_invert_colors_; } DlPaint& setInvertColors(bool isInvertColors) { is_invert_colors_ = isInvertColors; return *this; }
DlColor getColor() const { return color_; } DlPaint& setColor(DlColor color) { color_ = color; return *this; }
uint8_t getAlpha() const { return color_.argb() >> 24; } DlPaint& setAlpha(uint8_t alpha) { return setColor(color_.withAlpha(alpha)); } DlScalar getOpacity() const { return color_.getAlphaF(); } DlPaint& setOpacity(DlScalar opacity) { return setAlpha(DlColor::toAlpha(opacity)); }
DlBlendMode getBlendMode() const { return static_cast<DlBlendMode>(blend_mode_); } DlPaint& setBlendMode(DlBlendMode mode) { blend_mode_ = static_cast<unsigned>(mode); return *this; }
DlDrawStyle getDrawStyle() const { return static_cast<DlDrawStyle>(draw_style_); } DlPaint& setDrawStyle(DlDrawStyle style) { draw_style_ = static_cast<unsigned>(style); return *this; }
DlStrokeCap getStrokeCap() const { return static_cast<DlStrokeCap>(stroke_cap_); } DlPaint& setStrokeCap(DlStrokeCap cap) { stroke_cap_ = static_cast<unsigned>(cap); return *this; }
DlStrokeJoin getStrokeJoin() const { return static_cast<DlStrokeJoin>(stroke_join_); } DlPaint& setStrokeJoin(DlStrokeJoin join) { stroke_join_ = static_cast<unsigned>(join); return *this; }
float getStrokeWidth() const { return stroke_width_; } DlPaint& setStrokeWidth(float width) { stroke_width_ = width; return *this; }
float getStrokeMiter() const { return stroke_miter_; } DlPaint& setStrokeMiter(float miter) { stroke_miter_ = miter; return *this; }
std::shared_ptr<const DlColorSource> getColorSource() const { return color_source_; } const DlColorSource* getColorSourcePtr() const { return color_source_.get(); } DlPaint& setColorSource(std::shared_ptr<const DlColorSource> source) { color_source_ = std::move(source); return *this; } DlPaint& setColorSource(const DlColorSource* source) { color_source_ = source ? source->shared() : nullptr; return *this; }
std::shared_ptr<const DlColorFilter> getColorFilter() const { return color_filter_; } const DlColorFilter* getColorFilterPtr() const { return color_filter_.get(); } DlPaint& setColorFilter(const std::shared_ptr<const DlColorFilter>& filter) { color_filter_ = filter; return *this; } DlPaint& setColorFilter(const DlColorFilter* filter) { color_filter_ = filter ? filter->shared() : nullptr; return *this; }
std::shared_ptr<DlImageFilter> getImageFilter() const { return image_filter_; } const DlImageFilter* getImageFilterPtr() const { return image_filter_.get(); } DlPaint& setImageFilter(const std::shared_ptr<DlImageFilter>& filter) { image_filter_ = filter; return *this; } DlPaint& setImageFilter(const DlImageFilter* filter) { image_filter_ = filter ? filter->shared() : nullptr; return *this; }
std::shared_ptr<const DlMaskFilter> getMaskFilter() const { return mask_filter_; } const DlMaskFilter* getMaskFilterPtr() const { return mask_filter_.get(); } DlPaint& setMaskFilter(const std::shared_ptr<DlMaskFilter>& filter) { mask_filter_ = filter; return *this; } DlPaint& setMaskFilter(const DlMaskFilter* filter) { mask_filter_ = filter ? filter->shared() : nullptr; return *this; }
bool isDefault() const { return *this == kDefault; }
bool usesRuntimeEffect() const { return ((color_source_ && color_source_->asRuntimeEffect()) || (image_filter_ && image_filter_->asRuntimeEffectFilter())); }
bool operator==(DlPaint const& other) const; bool operator!=(DlPaint const& other) const { return !(*this == other); }
private:#define ASSERT_ENUM_FITS(last_enum, num_bits) \ static_assert(static_cast<int>(last_enum) < (1 << num_bits) && \ static_cast<int>(last_enum) * 2 >= (1 << num_bits))
static constexpr int kBlendModeBits = 5; static constexpr int kDrawStyleBits = 2; static constexpr int kStrokeCapBits = 2; static constexpr int kStrokeJoinBits = 2; ASSERT_ENUM_FITS(DlBlendMode::kLastMode, kBlendModeBits); ASSERT_ENUM_FITS(DlDrawStyle::kLastStyle, kDrawStyleBits); ASSERT_ENUM_FITS(DlStrokeCap::kLastCap, kStrokeCapBits); ASSERT_ENUM_FITS(DlStrokeJoin::kLastJoin, kStrokeJoinBits);
union { struct { unsigned blend_mode_ : kBlendModeBits; unsigned draw_style_ : kDrawStyleBits; unsigned stroke_cap_ : kStrokeCapBits; unsigned stroke_join_ : kStrokeJoinBits; unsigned is_anti_alias_ : 1; unsigned is_invert_colors_ : 1; }; };
DlColor color_; float stroke_width_; float stroke_miter_;
std::shared_ptr<const DlColorSource> color_source_; std::shared_ptr<const DlColorFilter> color_filter_; std::shared_ptr<DlImageFilter> image_filter_; std::shared_ptr<const DlMaskFilter> mask_filter_;};
} // namespace flutter
#endif // FLUTTER_DISPLAY_LIST_DL_PAINT_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#include "flutter/display_list/dl_paint.h"
#include "flutter/display_list/testing/dl_test_equality.h"#include "flutter/display_list/testing/dl_test_snippets.h"#include "flutter/display_list/utils/dl_comparable.h"#include "gtest/gtest.h"
namespace flutter {namespace testing {
TEST(DisplayListPaint, ConstructorDefaults) { DlPaint paint; EXPECT_FALSE(paint.isAntiAlias()); EXPECT_FALSE(paint.isInvertColors()); EXPECT_EQ(paint.getColor(), DlPaint::kDefaultColor); EXPECT_EQ(paint.getAlpha(), 0xFF); EXPECT_EQ(paint.getBlendMode(), DlBlendMode::kDefaultMode); EXPECT_EQ(paint.getDrawStyle(), DlDrawStyle::kDefaultStyle); EXPECT_EQ(paint.getStrokeCap(), DlStrokeCap::kDefaultCap); EXPECT_EQ(paint.getStrokeJoin(), DlStrokeJoin::kDefaultJoin); EXPECT_EQ(paint.getStrokeWidth(), DlPaint::kDefaultWidth); EXPECT_EQ(paint.getStrokeMiter(), DlPaint::kDefaultMiter); EXPECT_EQ(paint.getColorSource(), nullptr); EXPECT_EQ(paint.getColorFilter(), nullptr); EXPECT_EQ(paint.getImageFilter(), nullptr); EXPECT_EQ(paint.getMaskFilter(), nullptr); EXPECT_TRUE(paint.isDefault()); EXPECT_EQ(paint, DlPaint::kDefault);
EXPECT_EQ(DlBlendMode::kDefaultMode, DlBlendMode::kSrcOver); EXPECT_EQ(DlDrawStyle::kDefaultStyle, DlDrawStyle::kFill); EXPECT_EQ(DlStrokeCap::kDefaultCap, DlStrokeCap::kButt); EXPECT_EQ(DlStrokeJoin::kDefaultJoin, DlStrokeJoin::kMiter);
EXPECT_EQ(DlPaint::kDefaultColor, DlColor::kBlack()); EXPECT_EQ(DlPaint::kDefaultWidth, 0.0); EXPECT_EQ(DlPaint::kDefaultMiter, 4.0);
EXPECT_EQ(paint, DlPaint()); EXPECT_EQ(paint, DlPaint(DlColor::kBlack())); EXPECT_EQ(paint, DlPaint(DlColor(0xFF000000)));
EXPECT_NE(paint, DlPaint().setAntiAlias(true)); EXPECT_NE(paint, DlPaint().setInvertColors(true)); EXPECT_NE(paint, DlPaint().setColor(DlColor::kGreen())); EXPECT_NE(paint, DlPaint(DlColor::kGreen())); EXPECT_NE(paint, DlPaint(DlColor(0xFF00FF00))); EXPECT_NE(paint, DlPaint().setAlpha(0x7f)); EXPECT_NE(paint, DlPaint().setBlendMode(DlBlendMode::kDstIn)); EXPECT_NE(paint, DlPaint().setDrawStyle(DlDrawStyle::kStrokeAndFill)); EXPECT_NE(paint, DlPaint().setStrokeCap(DlStrokeCap::kRound)); EXPECT_NE(paint, DlPaint().setStrokeJoin(DlStrokeJoin::kRound)); EXPECT_NE(paint, DlPaint().setStrokeWidth(6)); EXPECT_NE(paint, DlPaint().setStrokeMiter(7));
DlColor colors[2] = { DlColor::kGreen(), DlColor::kBlue(), }; float stops[2] = { 0.0f, 1.0f, }; auto color_source = DlColorSource::MakeLinear({0, 0}, {10, 10}, 2, colors, stops, DlTileMode::kClamp); EXPECT_NE(paint, DlPaint().setColorSource(color_source));
auto color_filter = DlColorFilter::MakeBlend(DlColor::kYellow(), DlBlendMode::kDstATop); EXPECT_NE(paint, DlPaint().setColorFilter(color_filter));
auto image_filter = DlImageFilter::MakeBlur(1.3, 4.7, DlTileMode::kClamp); EXPECT_NE(paint, DlPaint().setImageFilter(image_filter));
DlBlurMaskFilter mask_filter(DlBlurStyle::kInner, 3.14); EXPECT_NE(paint, DlPaint().setMaskFilter(mask_filter.shared()));}
TEST(DisplayListPaint, NullPointerSetGet) { DlColorSource* null_color_source = nullptr; DlColorFilter* null_color_filter = nullptr; DlImageFilter* null_image_filter = nullptr; DlMaskFilter* null_mask_filter = nullptr; DlPaint paint; EXPECT_EQ(paint.setColorSource(null_color_source).getColorSource(), nullptr); EXPECT_EQ(paint.setColorFilter(null_color_filter).getColorFilter(), nullptr); EXPECT_EQ(paint.setImageFilter(null_image_filter).getImageFilter(), nullptr); EXPECT_EQ(paint.setMaskFilter(null_mask_filter).getMaskFilter(), nullptr);}
TEST(DisplayListPaint, NullSharedPointerSetGet) { std::shared_ptr<DlColorSource> null_color_source; std::shared_ptr<DlColorFilter> null_color_filter; std::shared_ptr<DlImageFilter> null_image_filter; std::shared_ptr<DlMaskFilter> null_mask_filter; DlPaint paint; EXPECT_EQ(paint.setColorSource(null_color_source).getColorSource(), nullptr); EXPECT_EQ(paint.setColorFilter(null_color_filter).getColorFilter(), nullptr); EXPECT_EQ(paint.setImageFilter(null_image_filter).getImageFilter(), nullptr); EXPECT_EQ(paint.setMaskFilter(null_mask_filter).getMaskFilter(), nullptr);}
TEST(DisplayListPaint, ChainingConstructor) { DlColor colors[2] = { DlColor::kGreen(), DlColor::kBlue(), }; float stops[2] = { 0.0f, 1.0f, }; DlPaint paint = DlPaint() // .setAntiAlias(true) // .setInvertColors(true) // .setColor(DlColor::kGreen()) // .setAlpha(0x7F) // .setBlendMode(DlBlendMode::kLuminosity) // .setDrawStyle(DlDrawStyle::kStrokeAndFill) // .setStrokeCap(DlStrokeCap::kSquare) // .setStrokeJoin(DlStrokeJoin::kBevel) // .setStrokeWidth(42) // .setStrokeMiter(1.5) // .setColorSource(DlColorSource::MakeLinear( // {0, 0}, {10, 10}, 2, colors, stops, DlTileMode::kClamp)) // .setColorFilter( DlColorFilter::MakeBlend(DlColor::kYellow(), DlBlendMode::kDstIn)) .setImageFilter(DlImageFilter::MakeBlur(1.3, 4.7, DlTileMode::kClamp)) .setMaskFilter(DlBlurMaskFilter(DlBlurStyle::kInner, 3.14).shared()); EXPECT_TRUE(paint.isAntiAlias()); EXPECT_TRUE(paint.isInvertColors()); EXPECT_EQ(paint.getColor(), DlColor::kGreen().withAlpha(0x7F)); EXPECT_EQ(paint.getAlpha(), 0x7F); EXPECT_EQ(paint.getBlendMode(), DlBlendMode::kLuminosity); EXPECT_EQ(paint.getDrawStyle(), DlDrawStyle::kStrokeAndFill); EXPECT_EQ(paint.getStrokeCap(), DlStrokeCap::kSquare); EXPECT_EQ(paint.getStrokeJoin(), DlStrokeJoin::kBevel); EXPECT_EQ(paint.getStrokeWidth(), 42); EXPECT_EQ(paint.getStrokeMiter(), 1.5); EXPECT_TRUE(Equals(paint.getColorSource(), DlColorSource::MakeLinear({0, 0}, {10, 10}, 2, colors, stops, DlTileMode::kClamp))); EXPECT_TRUE(Equals( paint.getColorFilter(), DlColorFilter::MakeBlend(DlColor::kYellow(), DlBlendMode::kDstIn))); EXPECT_TRUE(Equals(paint.getImageFilter(), DlImageFilter::MakeBlur(1.3, 4.7, DlTileMode::kClamp))); EXPECT_EQ(*paint.getMaskFilter(), DlBlurMaskFilter(DlBlurStyle::kInner, 3.14));
EXPECT_NE(paint, DlPaint());}
TEST(DisplayListPaint, PaintDetectsRuntimeEffects) { auto color_source = DlColorSource::MakeRuntimeEffect( kTestRuntimeEffect1, {}, std::make_shared<std::vector<uint8_t>>()); auto image_filter = DlImageFilter::MakeRuntimeEffect( kTestRuntimeEffect1, {}, std::make_shared<std::vector<uint8_t>>()); DlPaint paint;
EXPECT_FALSE(paint.usesRuntimeEffect()); paint.setColorSource(color_source); EXPECT_TRUE(paint.usesRuntimeEffect()); paint.setColorSource(nullptr); EXPECT_FALSE(paint.usesRuntimeEffect());
EXPECT_FALSE(paint.usesRuntimeEffect()); paint.setImageFilter(image_filter); EXPECT_TRUE(paint.usesRuntimeEffect()); paint.setImageFilter(nullptr); EXPECT_FALSE(paint.usesRuntimeEffect());
EXPECT_FALSE(paint.usesRuntimeEffect()); paint.setColorSource(color_source); EXPECT_TRUE(paint.usesRuntimeEffect()); paint.setImageFilter(image_filter); EXPECT_TRUE(paint.usesRuntimeEffect()); paint.setImageFilter(nullptr); EXPECT_TRUE(paint.usesRuntimeEffect()); paint.setColorSource(nullptr); EXPECT_FALSE(paint.usesRuntimeEffect());
EXPECT_FALSE(paint.usesRuntimeEffect()); paint.setColorSource(color_source); EXPECT_TRUE(paint.usesRuntimeEffect()); paint.setImageFilter(image_filter); EXPECT_TRUE(paint.usesRuntimeEffect()); paint.setColorSource(nullptr); EXPECT_TRUE(paint.usesRuntimeEffect()); paint.setImageFilter(nullptr); EXPECT_FALSE(paint.usesRuntimeEffect());}
} // namespace testing} // namespace flutter1234567891011121314151617181920212223242526// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#ifndef FLUTTER_DISPLAY_LIST_DL_SAMPLING_OPTIONS_H_#define FLUTTER_DISPLAY_LIST_DL_SAMPLING_OPTIONS_H_
namespace flutter {
enum class DlFilterMode { kNearest, // single sample point (nearest neighbor) kLinear, // interporate between 2x2 sample points (bilinear interpolation)
kLast = kLinear,};
enum class DlImageSampling { kNearestNeighbor, kLinear, kMipmapLinear, kCubic,};
} // namespace flutter
#endif // FLUTTER_DISPLAY_LIST_DL_SAMPLING_OPTIONS_H_1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#include "flutter/display_list/dl_storage.h"
namespace flutter {
static constexpr inline bool is_power_of_two(int value) { return (value & (value - 1)) == 0;}
void DisplayListStorage::realloc(size_t count) { ptr_.reset(static_cast<uint8_t*>(std::realloc(ptr_.release(), count))); FML_CHECK(ptr_); allocated_ = count;}
uint8_t* DisplayListStorage::allocate(size_t needed) { if (used_ + needed > allocated_) { static_assert(is_power_of_two(kDLPageSize), "This math needs updating for non-pow2."); // Next greater multiple of DL_BUILDER_PAGE. size_t new_size = (used_ + needed + kDLPageSize) & ~(kDLPageSize - 1); size_t old_size = allocated_; realloc(new_size); FML_CHECK(ptr_.get()); FML_CHECK(allocated_ == new_size); FML_CHECK(allocated_ >= old_size); FML_CHECK(used_ + needed <= allocated_); memset(ptr_.get() + used_, 0, allocated_ - old_size); } uint8_t* ret = ptr_.get() + used_; used_ += needed; FML_CHECK(used_ <= allocated_); return ret;}
DisplayListStorage::DisplayListStorage(DisplayListStorage&& source) { ptr_ = std::move(source.ptr_); used_ = source.used_; allocated_ = source.allocated_; source.used_ = 0u; source.allocated_ = 0u;}
void DisplayListStorage::reset() { ptr_.reset(); used_ = 0u; allocated_ = 0u;}
DisplayListStorage& DisplayListStorage::operator=(DisplayListStorage&& source) { ptr_ = std::move(source.ptr_); used_ = source.used_; allocated_ = source.allocated_; source.used_ = 0u; source.allocated_ = 0u; return *this;}
} // namespace flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#ifndef FLUTTER_DISPLAY_LIST_DL_STORAGE_H_#define FLUTTER_DISPLAY_LIST_DL_STORAGE_H_
#include <memory>
#include "flutter/fml/logging.h"
namespace flutter {
// Manages a buffer allocated with malloc.class DisplayListStorage { public: static const constexpr size_t kDLPageSize = 4096u;
DisplayListStorage() = default; DisplayListStorage(DisplayListStorage&&);
/// Returns a pointer to the base of the storage. uint8_t* base() { return ptr_.get(); } const uint8_t* base() const { return ptr_.get(); }
/// Returns the currently allocated size size_t size() const { return used_; }
/// Returns the maximum currently allocated space size_t capacity() const { return allocated_; }
/// Ensures the indicated number of bytes are available and returns /// a pointer to that memory within the storage while also invalidating /// any other outstanding pointers into the storage. uint8_t* allocate(size_t needed);
/// Trims the storage to the currently allocated size and invalidates /// any outstanding pointers into the storage. void trim() { realloc(used_); }
/// Resets the storage and allocation of the object to an empty state void reset();
DisplayListStorage& operator=(DisplayListStorage&& other);
private: void realloc(size_t count);
struct FreeDeleter { void operator()(uint8_t* p) { std::free(p); } }; std::unique_ptr<uint8_t, FreeDeleter> ptr_;
size_t used_ = 0u; size_t allocated_ = 0u;};
} // namespace flutter
#endif // FLUTTER_DISPLAY_LIST_DL_STORAGE_H_1234567891011121314151617181920212223242526272829303132333435363738394041424344454647// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#include "flutter/display_list/dl_storage.h"
#include "flutter/testing/testing.h"
namespace flutter {namespace testing {
TEST(DisplayListStorage, DefaultConstructed) { DisplayListStorage storage; EXPECT_EQ(storage.base(), nullptr); EXPECT_EQ(storage.size(), 0u); EXPECT_EQ(storage.capacity(), 0u);}
TEST(DisplayListStorage, Allocation) { DisplayListStorage storage; EXPECT_NE(storage.allocate(10u), nullptr); EXPECT_NE(storage.base(), nullptr); EXPECT_EQ(storage.size(), 10u); EXPECT_EQ(storage.capacity(), DisplayListStorage::kDLPageSize);}
TEST(DisplayListStorage, PostMove) { DisplayListStorage original; EXPECT_NE(original.allocate(10u), nullptr);
DisplayListStorage moved = std::move(original);
// NOLINTBEGIN(bugprone-use-after-move) // NOLINTBEGIN(clang-analyzer-cplusplus.Move) EXPECT_EQ(original.base(), nullptr); EXPECT_EQ(original.size(), 0u); EXPECT_EQ(original.capacity(), 0u); // NOLINTEND(clang-analyzer-cplusplus.Move) // NOLINTEND(bugprone-use-after-move)
EXPECT_NE(moved.base(), nullptr); EXPECT_EQ(moved.size(), 10u); EXPECT_EQ(moved.capacity(), DisplayListStorage::kDLPageSize);}
} // namespace testing} // namespace flutter123456789101112131415161718192021222324252627282930313233// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#ifndef FLUTTER_DISPLAY_LIST_DL_TILE_MODE_H_#define FLUTTER_DISPLAY_LIST_DL_TILE_MODE_H_
namespace flutter {
// 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 geoetry of a gradient).enum class DlTileMode { // Replicate the edge color if the |DlColorSource| draws outside of the // defined bounds. kClamp,
// Repeat the |DlColorSource|'s defined colors both horizontally and // vertically (or both along and perpendicular to a gradient's geometry). kRepeat,
// Repeat the |DlColorSource|'s colors horizontally and vertically, // alternating mirror images so that adjacent images always seam. kMirror,
// Only draw within the original domain, return transparent-black everywhere // else. kDecal,};
} // namespace flutter
#endif // FLUTTER_DISPLAY_LIST_DL_TILE_MODE_H_1234567891011// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#include "flutter/display_list/dl_types.h"
namespace flutter {
// Only exists to verify that the types can be cleanly included.
} // namespace flutter12345678910111213141516171819202122232425262728// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#ifndef FLUTTER_DISPLAY_LIST_DL_TYPES_H_#define FLUTTER_DISPLAY_LIST_DL_TYPES_H_
namespace flutter {
enum class DlClipOp { kDifference, kIntersect,};
enum class DlPointMode { kPoints, //!< draw each point separately kLines, //!< draw each separate pair of points as a line segment kPolygon, //!< draw each pair of overlapping points as a line segment};
enum class DlSrcRectConstraint { kStrict, kFast,};
} // namespace flutter
#endif // FLUTTER_DISPLAY_LIST_DL_TYPES_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#include "flutter/display_list/dl_vertices.h"
#include "flutter/display_list/utils/dl_accumulation_rect.h"#include "flutter/fml/logging.h"
namespace flutter {
using Flags = DlVertices::Builder::Flags;
static void DlVerticesDeleter(void* p) { // Some of our target environments would prefer a sized delete, // but other target environments do not have that operator. // Use an unsized delete until we get better agreement in the // environments. // See https://github.com/flutter/flutter/issues/100327 ::operator delete(p);}
static size_t bytes_needed(int vertex_count, Flags flags, int index_count) { int needed = sizeof(DlVertices); // We always have vertices needed += vertex_count * sizeof(DlPoint); if (flags.has_texture_coordinates) { needed += vertex_count * sizeof(DlPoint); } if (flags.has_colors) { needed += vertex_count * sizeof(DlColor); } if (index_count > 0) { needed += index_count * sizeof(uint16_t); } return needed;}
std::shared_ptr<DlVertices> DlVertices::Make( DlVertexMode mode, int vertex_count, const DlPoint vertices[], const DlPoint texture_coordinates[], const DlColor colors[], int index_count, const uint16_t indices[], const DlRect* bounds) { if (!vertices || vertex_count <= 0) { vertex_count = 0; texture_coordinates = nullptr; colors = nullptr; } if (!indices || index_count <= 0) { index_count = 0; indices = nullptr; }
Flags flags; FML_DCHECK(!flags.has_texture_coordinates); FML_DCHECK(!flags.has_colors); if (texture_coordinates) { flags |= Builder::kHasTextureCoordinates; } if (colors) { flags |= Builder::kHasColors; } Builder builder(mode, vertex_count, flags, index_count);
builder.store_vertices(vertices); if (texture_coordinates) { builder.store_texture_coordinates(texture_coordinates); } if (colors) { builder.store_colors(colors); } if (indices) { builder.store_indices(indices); } if (bounds != nullptr) { builder.store_bounds(*bounds); }
return builder.build();}
size_t DlVertices::size() const { return bytes_needed(vertex_count_, {{texture_coordinates_offset_ > 0, colors_offset_ > 0}}, index_count_);}
static DlRect compute_bounds(const DlPoint* points, int count) { AccumulationRect accumulator; for (int i = 0; i < count; i++) { accumulator.accumulate(points[i]); } return accumulator.GetBounds();}
DlVertices::DlVertices(DlVertexMode mode, int unchecked_vertex_count, const DlPoint* vertices, const DlPoint* texture_coordinates, const DlColor* colors, int unchecked_index_count, const uint16_t* indices, const DlRect* bounds) : mode_(mode), vertex_count_(std::max(unchecked_vertex_count, 0)), index_count_(indices ? std::max(unchecked_index_count, 0) : 0) { bounds_ = bounds ? *bounds : compute_bounds(vertices, vertex_count_);
char* pod = reinterpret_cast<char*>(this); size_t offset = sizeof(DlVertices);
auto advance = [pod, &offset](auto* src, int count) { if (src != nullptr && count > 0) { size_t bytes = count * sizeof(*src); memcpy(pod + offset, src, bytes); size_t ret = offset; offset += bytes; return ret; } else { return static_cast<size_t>(0); } };
vertices_offset_ = advance(vertices, vertex_count_); texture_coordinates_offset_ = advance(texture_coordinates, vertex_count_); colors_offset_ = advance(colors, vertex_count_); indices_offset_ = advance(indices, index_count_); FML_DCHECK(offset == bytes_needed(vertex_count_, {{!!texture_coordinates, !!colors}}, index_count_));}
DlVertices::DlVertices(const DlVertices* other) : DlVertices(other->mode_, other->vertex_count_, other->vertex_data(), other->texture_coordinate_data(), other->colors(), other->index_count_, other->indices(), &other->bounds_) {}
DlVertices::DlVertices(DlVertexMode mode, int unchecked_vertex_count, Flags flags, int unchecked_index_count) : mode_(mode), vertex_count_(std::max(unchecked_vertex_count, 0)), index_count_(std::max(unchecked_index_count, 0)) { char* pod = reinterpret_cast<char*>(this); size_t offset = sizeof(DlVertices);
auto advance = [pod, &offset](size_t size, int count) { if (count > 0) { size_t bytes = count * size; memset(pod + offset, 0, bytes); size_t ret = offset; offset += bytes; return ret; } else { return static_cast<size_t>(0); } };
vertices_offset_ = advance(sizeof(DlPoint), vertex_count_); texture_coordinates_offset_ = advance( sizeof(DlPoint), flags.has_texture_coordinates ? vertex_count_ : 0); colors_offset_ = advance(sizeof(DlColor), flags.has_colors ? vertex_count_ : 0); indices_offset_ = advance(sizeof(uint16_t), index_count_); FML_DCHECK(offset == bytes_needed(vertex_count_, flags, index_count_)); FML_DCHECK((vertex_count_ != 0) == (vertex_data() != nullptr)); FML_DCHECK((vertex_count_ != 0 && flags.has_texture_coordinates) == (texture_coordinate_data() != nullptr)); FML_DCHECK((vertex_count_ != 0 && flags.has_colors) == (colors() != nullptr)); FML_DCHECK((index_count_ != 0) == (indices() != nullptr));}
bool DlVertices::operator==(DlVertices const& other) const { auto lists_equal = [](auto* a, auto* b, int count) { if (a == nullptr || b == nullptr) { return a == b; } for (int i = 0; i < count; i++) { if (a[i] != b[i]) { return false; } } return true; }; return // mode_ == other.mode_ && // vertex_count_ == other.vertex_count_ && // lists_equal(vertex_data(), other.vertex_data(), vertex_count_) && // lists_equal(texture_coordinate_data(), // other.texture_coordinate_data(), // vertex_count_) && // lists_equal(colors(), other.colors(), vertex_count_) && // index_count_ == other.index_count_ && // lists_equal(indices(), other.indices(), index_count_);}
DlVertices::Builder::Builder(DlVertexMode mode, int vertex_count, Flags flags, int index_count) : needs_texture_coords_(flags.has_texture_coordinates), needs_colors_(flags.has_colors), needs_indices_(index_count > 0) { vertex_count = std::max(vertex_count, 0); index_count = std::max(index_count, 0); void* storage = ::operator new(bytes_needed(vertex_count, flags, index_count)); vertices_.reset(new (storage) DlVertices(mode, vertex_count, flags, index_count), DlVerticesDeleter);}
static void store_points(char* dst, int offset, const float* src, int count) { DlPoint* points = reinterpret_cast<DlPoint*>(dst + offset); for (int i = 0; i < count; i++) { points[i] = DlPoint(src[i * 2], src[i * 2 + 1]); }}
void DlVertices::Builder::store_vertices(const DlPoint vertices[]) { FML_DCHECK(is_valid()); FML_DCHECK(needs_vertices_); char* pod = reinterpret_cast<char*>(vertices_.get()); size_t bytes = vertices_->vertex_count_ * sizeof(vertices[0]); memcpy(pod + vertices_->vertices_offset_, vertices, bytes); needs_vertices_ = false;}
void DlVertices::Builder::store_vertices(const float vertices[]) { FML_DCHECK(is_valid()); FML_DCHECK(needs_vertices_); char* pod = reinterpret_cast<char*>(vertices_.get()); store_points(pod, vertices_->vertices_offset_, vertices, vertices_->vertex_count_); needs_vertices_ = false;}
void DlVertices::Builder::store_texture_coordinates(const DlPoint coords[]) { FML_DCHECK(is_valid()); FML_DCHECK(needs_texture_coords_); char* pod = reinterpret_cast<char*>(vertices_.get()); size_t bytes = vertices_->vertex_count_ * sizeof(coords[0]); memcpy(pod + vertices_->texture_coordinates_offset_, coords, bytes); needs_texture_coords_ = false;}
void DlVertices::Builder::store_texture_coordinates(const float coords[]) { FML_DCHECK(is_valid()); FML_DCHECK(needs_texture_coords_); char* pod = reinterpret_cast<char*>(vertices_.get()); store_points(pod, vertices_->texture_coordinates_offset_, coords, vertices_->vertex_count_); needs_texture_coords_ = false;}
void DlVertices::Builder::store_colors(const DlColor colors[]) { FML_DCHECK(is_valid()); FML_DCHECK(needs_colors_); char* pod = reinterpret_cast<char*>(vertices_.get()); size_t bytes = vertices_->vertex_count_ * sizeof(colors[0]); memcpy(pod + vertices_->colors_offset_, colors, bytes); needs_colors_ = false;}
void DlVertices::Builder::store_colors(const uint32_t colors[]) { FML_DCHECK(is_valid()); FML_DCHECK(needs_colors_); char* pod = reinterpret_cast<char*>(vertices_.get()); DlColor* dlcolors_ptr = reinterpret_cast<DlColor*>(pod + vertices_->colors_offset_); for (int i = 0; i < vertices_->vertex_count_; ++i) { *dlcolors_ptr++ = DlColor(colors[i]); } needs_colors_ = false;}
void DlVertices::Builder::store_indices(const uint16_t indices[]) { FML_DCHECK(is_valid()); FML_DCHECK(needs_indices_); char* pod = reinterpret_cast<char*>(vertices_.get()); size_t bytes = vertices_->index_count_ * sizeof(indices[0]); memcpy(pod + vertices_->indices_offset_, indices, bytes); needs_indices_ = false;}
void DlVertices::Builder::store_bounds(DlRect bounds) { vertices_->bounds_ = bounds; needs_bounds_ = false;}
std::shared_ptr<DlVertices> DlVertices::Builder::build() { FML_DCHECK(is_valid()); if (vertices_->vertex_count() <= 0) { // We set this to true in the constructor to make sure that they // call store_vertices() only once, but if there are no vertices // then we will not object to them never having stored any vertices needs_vertices_ = false; } FML_DCHECK(!needs_vertices_); FML_DCHECK(!needs_texture_coords_); FML_DCHECK(!needs_colors_); FML_DCHECK(!needs_indices_);
if (needs_bounds_) { vertices_->bounds_ = compute_bounds(vertices_->vertex_data(), vertices_->vertex_count_); }
return std::move(vertices_);}
} // namespace flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#ifndef FLUTTER_DISPLAY_LIST_DL_VERTICES_H_#define FLUTTER_DISPLAY_LIST_DL_VERTICES_H_
#include <memory>
#include "flutter/display_list/dl_color.h"
namespace flutter {
//------------------------------------------------------------------------------/// @brief Defines the way in which the vertices of a DlVertices object/// are separated into triangles into which to render.///enum class DlVertexMode { /// The vertices are taken 3 at a time to form a triangle. kTriangles,
/// The vertices are taken in overlapping triplets to form triangles, with /// each triplet sharing 2 of its vertices with the preceding and following /// triplets. /// vertices [ABCDE] yield 3 triangles ABC,BCD,CDE kTriangleStrip,
/// The vertices are taken in overlapping pairs and combined with the first /// vertex to form triangles that radiate outward from the initial point. /// vertices [ABCDE] yield 3 triangles ABC,ACD,ADE kTriangleFan,};
//------------------------------------------------------------------------------/// @brief Holds all of the data (both required and optional) for a/// DisplayList drawVertices call.////// There are 4 main pices of data:/// - vertices():/// the points on the rendering surface that define the pixels/// being rendered to in a series of triangles. These points/// can map to triangles in various ways depending on the/// supplied |DlVertexMode|./// - texture_coordinates():/// the points in the DlColorSource to map to the coordinates/// of the triangles in the vertices(). If missing, the/// vertex coordinates themselves will be used to map the/// source colors to the vertices./// - colors():/// colors to map to each triangle vertex. Note that each/// vertex is mapped to exactly 1 color even if the DlVertex/// - indices():/// An indirection based on indices into the array of vertices/// (and by extension, their associated texture_coordinates and/// colors). Note that the DLVertexMode will still apply to the/// indices in the same way (and instead of the way) that it/// would normally be applied to the vertices themselves. The/// indices are useful, for example, to fill the vertices with/// a grid of points and then use the indices to define a/// triangular mesh that covers that grid without having to/// repeat the vertex (and texture coordinate and color)/// information for the times when a given grid coordinate/// gets reused in up to 4 mesh triangles.////// Note that each vertex is mapped to exactly 1 texture_coordinate and/// color even if the DlVertexMode or indices specify that it contributes/// to more than one output triangle.///class DlVertices { public: /// @brief A utility class to build up a |DlVertices| object /// one set of data at a time. class Builder { public: /// @brief flags to indicate/promise which of the optional /// texture coordinates or colors will be supplied /// during the build phase. union Flags { struct { unsigned has_texture_coordinates : 1; unsigned has_colors : 1; }; uint32_t mask = 0;
inline Flags operator|(const Flags& rhs) const { return {.mask = (mask | rhs.mask)}; }
inline Flags& operator|=(const Flags& rhs) { mask = mask | rhs.mask; return *this; } }; static constexpr Flags kNone = {{false, false}}; static constexpr Flags kHasTextureCoordinates = {{true, false}}; static constexpr Flags kHasColors = {{false, true}};
//-------------------------------------------------------------------------- /// @brief Constructs a Builder and prepares room for the /// required and optional data. /// /// Vertices are always required. Optional texture coordinates /// and optional colors are reserved depending on the |Flags|. /// Optional indices will be reserved if the index_count is /// positive (>0). /// /// The caller must provide all data that is promised by the /// supplied |flags| and |index_count| parameters before /// calling the |build()| method. Builder(DlVertexMode mode, int vertex_count, Flags flags, int index_count);
/// Returns true iff the underlying object was successfully allocated. bool is_valid() const { return vertices_ != nullptr; }
/// @brief Copies the indicated list of points as vertices. /// /// fails if vertices have already been supplied. void store_vertices(const DlPoint vertices[]);
/// @brief Copies the indicated list of float pairs as vertices. /// /// fails if vertices have already been supplied. void store_vertices(const float coordinates[]);
/// @brief Copies the indicated list of points as texture coordinates. /// /// fails if texture coordinates have already been supplied or if they /// were not promised by the flags.has_texture_coordinates. void store_texture_coordinates(const DlPoint points[]);
/// @brief Copies the indicated list of float pairs as texture coordinates. /// /// fails if texture coordinates have already been supplied or if they /// were not promised by the flags.has_texture_coordinates. void store_texture_coordinates(const float coordinates[]);
/// @brief Copies the indicated list of colors as vertex colors. /// /// fails if colors have already been supplied or if they were not /// promised by the flags.has_colors. void store_colors(const DlColor colors[]);
/// @brief Copies the indicated list of unsigned ints as vertex colors /// in the 32-bit RGBA format. /// /// fails if colors have already been supplied or if they were not /// promised by the flags.has_colors. void store_colors(const uint32_t colors[]);
/// @brief Copies the indicated list of 16-bit indices as vertex indices. /// /// fails if indices have already been supplied or if they were not /// promised by (index_count > 0). void store_indices(const uint16_t indices[]);
/// @brief Overwrite the internal bounds with a precomputed bounding rect. void store_bounds(DlRect bounds);
/// @brief Finalizes and the constructed DlVertices object. /// /// fails if any of the optional data promised in the constructor is /// missing. std::shared_ptr<DlVertices> build();
private: std::shared_ptr<DlVertices> vertices_; bool needs_vertices_ = true; bool needs_texture_coords_; bool needs_colors_; bool needs_indices_; bool needs_bounds_ = true; };
//-------------------------------------------------------------------------- /// @brief Constructs a DlVector with compact inline storage for all /// of its required and optional lists of data. /// /// Vertices are always required. Optional texture coordinates /// and optional colors are stored if the arguments are non-null. /// Optional indices will be stored iff the array argument is /// non-null and the index_count is positive (>0). static std::shared_ptr<DlVertices> Make(DlVertexMode mode, int vertex_count, const DlPoint vertices[], const DlPoint texture_coordinates[], const DlColor colors[], int index_count = 0, const uint16_t indices[] = nullptr, const DlRect* bounds = nullptr);
/// Returns the size of the object including all of the inlined data. size_t size() const;
/// Returns the bounds of the vertices. DlRect GetBounds() const { return bounds_; }
/// Returns the vertex mode that defines how the vertices (or the indices) /// are turned into triangles. DlVertexMode mode() const { return mode_; }
/// Returns the number of vertices, which also applies to the number of /// texture coordinate and colors if they are provided. int vertex_count() const { return vertex_count_; }
/// Returns a pointer to the vertex information. Should be non-null. const DlPoint* vertex_data() const { return static_cast<const DlPoint*>(pod(vertices_offset_)); }
/// Returns a pointer to the vertex texture coordinate /// or null if none were provided. const DlPoint* texture_coordinate_data() const { return static_cast<const DlPoint*>(pod(texture_coordinates_offset_)); }
/// Returns a pointer to the vertex colors /// or null if none were provided. const DlColor* colors() const { return static_cast<const DlColor*>(pod(colors_offset_)); }
/// Returns a pointer to the count of vertex indices /// or 0 if none were provided. int index_count() const { return index_count_; }
/// Returns a pointer to the vertex indices /// or null if none were provided. const uint16_t* indices() const { return static_cast<const uint16_t*>(pod(indices_offset_)); }
bool operator==(DlVertices const& other) const;
bool operator!=(DlVertices const& other) const { return !(*this == other); }
private: // Constructors are designed to encapsulate arrays sequentially in memory // which means they can only be called by intantiations that use the // new (ptr) paradigm which precomputes and preallocates the memory for // the class body and all of its arrays, such as in Builder. DlVertices(DlVertexMode mode, int vertex_count, const DlPoint vertices[], const DlPoint texture_coordinates[], const DlColor colors[], int index_count, const uint16_t indices[], const DlRect* bounds = nullptr);
// This constructor is specifically used by the DlVertices::Builder to // establish the object before the copying of data is requested. DlVertices(DlVertexMode mode, int vertex_count, Builder::Flags flags, int index_count);
// The copy constructor has the same memory pre-allocation requirements // as this other constructors. This particular version is used by the // DisplaylistBuilder to copy the instance into pre-allocated pod memory // in the display list buffer. explicit DlVertices(const DlVertices* other);
DlVertexMode mode_;
int vertex_count_; size_t vertices_offset_; size_t texture_coordinates_offset_; size_t colors_offset_;
int index_count_; size_t indices_offset_;
DlRect bounds_;
const void* pod(int offset) const { if (offset <= 0) { return nullptr; } const void* base = static_cast<const void*>(this); return static_cast<const char*>(base) + offset; }
friend class DisplayListBuilder;};
} // namespace flutter
#endif // FLUTTER_DISPLAY_LIST_DL_VERTICES_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983// Copyright 2013 The Flutter Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.
#include "flutter/display_list/dl_builder.h"#include "flutter/display_list/dl_vertices.h"#include "flutter/display_list/testing/dl_test_equality.h"#include "flutter/display_list/utils/dl_comparable.h"#include "gtest/gtest.h"
namespace flutter {namespace testing {
TEST(DisplayListVertices, MakeWithZeroAndNegativeVerticesAndIndices) { std::shared_ptr<DlVertices> vertices1 = DlVertices::Make( DlVertexMode::kTriangles, 0, nullptr, nullptr, nullptr, 0, nullptr); EXPECT_NE(vertices1, nullptr); EXPECT_EQ(vertices1->vertex_count(), 0); EXPECT_EQ(vertices1->vertex_data(), nullptr); EXPECT_EQ(vertices1->texture_coordinate_data(), nullptr); EXPECT_EQ(vertices1->colors(), nullptr); EXPECT_EQ(vertices1->index_count(), 0); EXPECT_EQ(vertices1->indices(), nullptr);
std::shared_ptr<DlVertices> vertices2 = DlVertices::Make( DlVertexMode::kTriangles, -1, nullptr, nullptr, nullptr, -1, nullptr); EXPECT_NE(vertices2, nullptr); EXPECT_EQ(vertices2->vertex_count(), 0); EXPECT_EQ(vertices2->vertex_data(), nullptr); EXPECT_EQ(vertices2->texture_coordinate_data(), nullptr); EXPECT_EQ(vertices2->colors(), nullptr); EXPECT_EQ(vertices2->index_count(), 0); EXPECT_EQ(vertices2->indices(), nullptr);
TestEquals(*vertices1, *vertices2);}
TEST(DisplayListVertices, MakeWithTexAndColorAndIndices) { DlPoint coords[3] = { DlPoint(2, 3), DlPoint(5, 6), DlPoint(15, 20), }; DlPoint texture_coords[3] = { DlPoint(102, 103), DlPoint(105, 106), DlPoint(115, 120), }; DlColor colors[3] = { DlColor::kRed(), DlColor::kCyan(), DlColor::kGreen(), }; uint16_t indices[6] = { 2, 1, 0, // 1, 2, 0, };
std::shared_ptr<DlVertices> vertices = DlVertices::Make( DlVertexMode::kTriangles, 3, coords, texture_coords, colors, 6, indices);
ASSERT_NE(vertices, nullptr); ASSERT_NE(vertices->vertex_data(), nullptr); ASSERT_NE(vertices->texture_coordinate_data(), nullptr); ASSERT_NE(vertices->colors(), nullptr); ASSERT_NE(vertices->indices(), nullptr);
ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); ASSERT_EQ(vertices->vertex_count(), 3); for (int i = 0; i < 3; i++) { ASSERT_EQ(vertices->vertex_data()[i], coords[i]); ASSERT_EQ(vertices->texture_coordinate_data()[i], texture_coords[i]); ASSERT_EQ(vertices->colors()[i], colors[i]); } ASSERT_EQ(vertices->index_count(), 6); for (int i = 0; i < 6; i++) { ASSERT_EQ(vertices->indices()[i], indices[i]); }}
TEST(DisplayListVertices, MakeWithTexAndColor) { DlPoint coords[3] = { DlPoint(2, 3), DlPoint(5, 6), DlPoint(15, 20), }; DlPoint texture_coords[3] = { DlPoint(102, 103), DlPoint(105, 106), DlPoint(115, 120), }; DlColor colors[3] = { DlColor::kRed(), DlColor::kCyan(), DlColor::kGreen(), };
std::shared_ptr<DlVertices> vertices = DlVertices::Make( DlVertexMode::kTriangles, 3, coords, texture_coords, colors, 6, nullptr);
ASSERT_NE(vertices, nullptr); ASSERT_NE(vertices->vertex_data(), nullptr); ASSERT_NE(vertices->texture_coordinate_data(), nullptr); ASSERT_NE(vertices->colors(), nullptr); ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); ASSERT_EQ(vertices->vertex_count(), 3); for (int i = 0; i < 3; i++) { ASSERT_EQ(vertices->vertex_data()[i], coords[i]); ASSERT_EQ(vertices->texture_coordinate_data()[i], texture_coords[i]); ASSERT_EQ(vertices->colors()[i], colors[i]); } ASSERT_EQ(vertices->index_count(), 0);}
TEST(DisplayListVertices, MakeWithTexAndIndices) { DlPoint coords[3] = { DlPoint(2, 3), DlPoint(5, 6), DlPoint(15, 20), }; DlPoint texture_coords[3] = { DlPoint(102, 103), DlPoint(105, 106), DlPoint(115, 120), }; uint16_t indices[6] = { 2, 1, 0, // 1, 2, 0, };
std::shared_ptr<DlVertices> vertices = DlVertices::Make( DlVertexMode::kTriangles, 3, coords, texture_coords, nullptr, 6, indices);
ASSERT_NE(vertices, nullptr); ASSERT_NE(vertices->vertex_data(), nullptr); ASSERT_NE(vertices->texture_coordinate_data(), nullptr); ASSERT_EQ(vertices->colors(), nullptr); ASSERT_NE(vertices->indices(), nullptr);
ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); ASSERT_EQ(vertices->vertex_count(), 3); for (int i = 0; i < 3; i++) { ASSERT_EQ(vertices->vertex_data()[i], coords[i]); ASSERT_EQ(vertices->texture_coordinate_data()[i], texture_coords[i]); } ASSERT_EQ(vertices->index_count(), 6); for (int i = 0; i < 6; i++) { ASSERT_EQ(vertices->indices()[i], indices[i]); }}
TEST(DisplayListVertices, MakeWithColorAndIndices) { DlPoint coords[3] = { DlPoint(2, 3), DlPoint(5, 6), DlPoint(15, 20), }; DlColor colors[3] = { DlColor::kRed(), DlColor::kCyan(), DlColor::kGreen(), }; uint16_t indices[6] = { 2, 1, 0, // 1, 2, 0, };
std::shared_ptr<DlVertices> vertices = DlVertices::Make( DlVertexMode::kTriangles, 3, coords, nullptr, colors, 6, indices);
ASSERT_NE(vertices, nullptr); ASSERT_NE(vertices->vertex_data(), nullptr); ASSERT_EQ(vertices->texture_coordinate_data(), nullptr); ASSERT_NE(vertices->colors(), nullptr); ASSERT_NE(vertices->indices(), nullptr);
ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); ASSERT_EQ(vertices->vertex_count(), 3); for (int i = 0; i < 3; i++) { ASSERT_EQ(vertices->vertex_data()[i], coords[i]); ASSERT_EQ(vertices->colors()[i], colors[i]); } ASSERT_EQ(vertices->index_count(), 6); for (int i = 0; i < 6; i++) { ASSERT_EQ(vertices->indices()[i], indices[i]); }}
TEST(DisplayListVertices, MakeWithTex) { DlPoint coords[3] = { DlPoint(2, 3), DlPoint(5, 6), DlPoint(15, 20), }; DlPoint texture_coords[3] = { DlPoint(102, 103), DlPoint(105, 106), DlPoint(115, 120), };
std::shared_ptr<DlVertices> vertices = DlVertices::Make( DlVertexMode::kTriangles, 3, coords, texture_coords, nullptr, 6, nullptr);
ASSERT_NE(vertices, nullptr); ASSERT_NE(vertices->vertex_data(), nullptr); ASSERT_NE(vertices->texture_coordinate_data(), nullptr); ASSERT_EQ(vertices->colors(), nullptr); ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); ASSERT_EQ(vertices->vertex_count(), 3); for (int i = 0; i < 3; i++) { ASSERT_EQ(vertices->vertex_data()[i], coords[i]); ASSERT_EQ(vertices->texture_coordinate_data()[i], texture_coords[i]); } ASSERT_EQ(vertices->index_count(), 0);}
TEST(DisplayListVertices, MakeWithColor) { DlPoint coords[3] = { DlPoint(2, 3), DlPoint(5, 6), DlPoint(15, 20), }; DlColor colors[3] = { DlColor::kRed(), DlColor::kCyan(), DlColor::kGreen(), };
std::shared_ptr<DlVertices> vertices = DlVertices::Make( DlVertexMode::kTriangles, 3, coords, nullptr, colors, 6, nullptr);
ASSERT_NE(vertices, nullptr); ASSERT_NE(vertices->vertex_data(), nullptr); ASSERT_EQ(vertices->texture_coordinate_data(), nullptr); ASSERT_NE(vertices->colors(), nullptr); ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); ASSERT_EQ(vertices->vertex_count(), 3); for (int i = 0; i < 3; i++) { ASSERT_EQ(vertices->vertex_data()[i], coords[i]); ASSERT_EQ(vertices->colors()[i], colors[i]); } ASSERT_EQ(vertices->index_count(), 0);}
TEST(DisplayListVertices, MakeWithIndices) { DlPoint coords[3] = { DlPoint(2, 3), DlPoint(5, 6), DlPoint(15, 20), }; uint16_t indices[6] = { 2, 1, 0, // 1, 2, 0, };
std::shared_ptr<DlVertices> vertices = DlVertices::Make( DlVertexMode::kTriangles, 3, coords, nullptr, nullptr, 6, indices);
ASSERT_NE(vertices, nullptr); ASSERT_NE(vertices->vertex_data(), nullptr); ASSERT_EQ(vertices->texture_coordinate_data(), nullptr); ASSERT_EQ(vertices->colors(), nullptr); ASSERT_NE(vertices->indices(), nullptr);
ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); ASSERT_EQ(vertices->vertex_count(), 3); for (int i = 0; i < 3; i++) { ASSERT_EQ(vertices->vertex_data()[i], coords[i]); } ASSERT_EQ(vertices->index_count(), 6); for (int i = 0; i < 6; i++) { ASSERT_EQ(vertices->indices()[i], indices[i]); }}
TEST(DisplayListVertices, MakeWithNoOptionalData) { DlPoint coords[3] = { DlPoint(2, 3), DlPoint(5, 6), DlPoint(15, 20), };
std::shared_ptr<DlVertices> vertices = DlVertices::Make( DlVertexMode::kTriangles, 3, coords, nullptr, nullptr, 6, nullptr);
ASSERT_NE(vertices, nullptr); ASSERT_NE(vertices->vertex_data(), nullptr); ASSERT_EQ(vertices->texture_coordinate_data(), nullptr); ASSERT_EQ(vertices->colors(), nullptr); ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); ASSERT_EQ(vertices->vertex_count(), 3); for (int i = 0; i < 3; i++) { ASSERT_EQ(vertices->vertex_data()[i], coords[i]); } ASSERT_EQ(vertices->index_count(), 0);}
TEST(DisplayListVertices, MakeWithIndicesButZeroIndexCount) { DlPoint coords[3] = { DlPoint(2, 3), DlPoint(5, 6), DlPoint(15, 20), }; uint16_t indices[6] = { 2, 1, 0, // 1, 2, 0, };
std::shared_ptr<DlVertices> vertices = DlVertices::Make( DlVertexMode::kTriangles, 3, coords, nullptr, nullptr, 0, indices);
ASSERT_NE(vertices, nullptr); ASSERT_NE(vertices->vertex_data(), nullptr); ASSERT_EQ(vertices->texture_coordinate_data(), nullptr); ASSERT_EQ(vertices->colors(), nullptr); ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); ASSERT_EQ(vertices->vertex_count(), 3); for (int i = 0; i < 3; i++) { ASSERT_EQ(vertices->vertex_data()[i], coords[i]); } ASSERT_EQ(vertices->index_count(), 0);}
TEST(DisplayListVertices, MakeWithIndicesButNegativeIndexCount) { DlPoint coords[3] = { DlPoint(2, 3), DlPoint(5, 6), DlPoint(15, 20), }; uint16_t indices[6] = { 2, 1, 0, // 1, 2, 0, };
std::shared_ptr<DlVertices> vertices = DlVertices::Make( DlVertexMode::kTriangles, 3, coords, nullptr, nullptr, -5, indices);
ASSERT_NE(vertices, nullptr); ASSERT_NE(vertices->vertex_data(), nullptr); ASSERT_EQ(vertices->texture_coordinate_data(), nullptr); ASSERT_EQ(vertices->colors(), nullptr); ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); ASSERT_EQ(vertices->vertex_count(), 3); for (int i = 0; i < 3; i++) { ASSERT_EQ(vertices->vertex_data()[i], coords[i]); } ASSERT_EQ(vertices->index_count(), 0);}
using Builder = DlVertices::Builder;
TEST(DisplayListVertices, BuilderFlags) { Builder::Flags flags; EXPECT_FALSE(flags.has_texture_coordinates); EXPECT_FALSE(flags.has_colors);
flags |= Builder::kHasTextureCoordinates; EXPECT_TRUE(flags.has_texture_coordinates); EXPECT_FALSE(flags.has_colors);
flags |= Builder::kHasColors; EXPECT_TRUE(flags.has_texture_coordinates); EXPECT_TRUE(flags.has_colors);
flags = Builder::Flags(); EXPECT_FALSE(flags.has_texture_coordinates); EXPECT_FALSE(flags.has_colors);
flags |= Builder::kHasColors; EXPECT_FALSE(flags.has_texture_coordinates); EXPECT_TRUE(flags.has_colors);
flags |= Builder::kHasTextureCoordinates; EXPECT_TRUE(flags.has_texture_coordinates); EXPECT_TRUE(flags.has_colors);
EXPECT_FALSE(Builder::kNone.has_texture_coordinates); EXPECT_FALSE(Builder::kNone.has_colors);
EXPECT_TRUE(Builder::kHasTextureCoordinates.has_texture_coordinates); EXPECT_FALSE(Builder::kHasTextureCoordinates.has_colors);
EXPECT_FALSE(Builder::kHasColors.has_texture_coordinates); EXPECT_TRUE(Builder::kHasColors.has_colors);
EXPECT_TRUE((Builder::kHasTextureCoordinates | Builder::kHasColors) // .has_texture_coordinates); EXPECT_TRUE((Builder::kHasTextureCoordinates | Builder::kHasColors) // .has_colors);}
TEST(DisplayListVertices, BuildWithZeroAndNegativeVerticesAndIndices) { Builder builder1(DlVertexMode::kTriangles, 0, Builder::kNone, 0); EXPECT_TRUE(builder1.is_valid()); std::shared_ptr<DlVertices> vertices1 = builder1.build(); EXPECT_NE(vertices1, nullptr); EXPECT_EQ(vertices1->vertex_count(), 0); EXPECT_EQ(vertices1->vertex_data(), nullptr); EXPECT_EQ(vertices1->texture_coordinate_data(), nullptr); EXPECT_EQ(vertices1->colors(), nullptr); EXPECT_EQ(vertices1->index_count(), 0); EXPECT_EQ(vertices1->indices(), nullptr);
Builder builder2(DlVertexMode::kTriangles, -1, Builder::kNone, -1); EXPECT_TRUE(builder2.is_valid()); std::shared_ptr<DlVertices> vertices2 = builder2.build(); EXPECT_NE(vertices2, nullptr); EXPECT_EQ(vertices2->vertex_count(), 0); EXPECT_EQ(vertices2->vertex_data(), nullptr); EXPECT_EQ(vertices2->texture_coordinate_data(), nullptr); EXPECT_EQ(vertices2->colors(), nullptr); EXPECT_EQ(vertices2->index_count(), 0); EXPECT_EQ(vertices2->indices(), nullptr);
TestEquals(*vertices1, *vertices2);}
TEST(DisplayListVertices, BuildWithTexAndColorAndIndices) { DlPoint coords[3] = { DlPoint(2, 3), DlPoint(5, 6), DlPoint(15, 20), }; DlPoint texture_coords[3] = { DlPoint(102, 103), DlPoint(105, 106), DlPoint(115, 120), }; DlColor colors[3] = { DlColor::kRed(), DlColor::kCyan(), DlColor::kGreen(), }; uint16_t indices[6] = { 2, 1, 0, // 1, 2, 0, };
Builder builder(DlVertexMode::kTriangles, 3, // Builder::kHasTextureCoordinates | Builder::kHasColors, 6); builder.store_vertices(coords); builder.store_texture_coordinates(texture_coords); builder.store_colors(colors); builder.store_indices(indices); std::shared_ptr<DlVertices> vertices = builder.build();
ASSERT_NE(vertices, nullptr); ASSERT_NE(vertices->vertex_data(), nullptr); ASSERT_NE(vertices->texture_coordinate_data(), nullptr); ASSERT_NE(vertices->colors(), nullptr); ASSERT_NE(vertices->indices(), nullptr);
ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); ASSERT_EQ(vertices->vertex_count(), 3); for (int i = 0; i < 3; i++) { ASSERT_EQ(vertices->vertex_data()[i], coords[i]); ASSERT_EQ(vertices->texture_coordinate_data()[i], texture_coords[i]); ASSERT_EQ(vertices->colors()[i], colors[i]); } ASSERT_EQ(vertices->index_count(), 6); for (int i = 0; i < 6; i++) { ASSERT_EQ(vertices->indices()[i], indices[i]); }
Builder builder2(DlVertexMode::kTriangles, 3, // Builder::kHasTextureCoordinates | Builder::kHasColors, 6); builder2.store_vertices(coords); builder2.store_texture_coordinates(texture_coords); builder2.store_colors(colors); builder2.store_indices(indices); std::shared_ptr<DlVertices> vertices2 = builder2.build();
TestEquals(*vertices, *vertices2);
std::shared_ptr<DlVertices> vertices3 = DlVertices::Make( DlVertexMode::kTriangles, 3, coords, texture_coords, colors, 6, indices);
TestEquals(*vertices, *vertices3);}
TEST(DisplayListVertices, BuildWithTexAndColor) { DlPoint coords[3] = { DlPoint(2, 3), DlPoint(5, 6), DlPoint(15, 20), }; DlPoint texture_coords[3] = { DlPoint(102, 103), DlPoint(105, 106), DlPoint(115, 120), }; DlColor colors[3] = { DlColor::kRed(), DlColor::kCyan(), DlColor::kGreen(), };
Builder builder(DlVertexMode::kTriangles, 3, // Builder::kHasTextureCoordinates | Builder::kHasColors, 0); builder.store_vertices(coords); builder.store_texture_coordinates(texture_coords); builder.store_colors(colors); std::shared_ptr<DlVertices> vertices = builder.build();
ASSERT_NE(vertices, nullptr); ASSERT_NE(vertices->vertex_data(), nullptr); ASSERT_NE(vertices->texture_coordinate_data(), nullptr); ASSERT_NE(vertices->colors(), nullptr); ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); ASSERT_EQ(vertices->vertex_count(), 3); for (int i = 0; i < 3; i++) { ASSERT_EQ(vertices->vertex_data()[i], coords[i]); ASSERT_EQ(vertices->texture_coordinate_data()[i], texture_coords[i]); ASSERT_EQ(vertices->colors()[i], colors[i]); } ASSERT_EQ(vertices->index_count(), 0);}
TEST(DisplayListVertices, BuildWithTexAndIndices) { DlPoint coords[3] = { DlPoint(2, 3), DlPoint(5, 6), DlPoint(15, 20), }; DlPoint texture_coords[3] = { DlPoint(102, 103), DlPoint(105, 106), DlPoint(115, 120), }; uint16_t indices[6] = { 2, 1, 0, // 1, 2, 0, };
Builder builder(DlVertexMode::kTriangles, 3, // Builder::kHasTextureCoordinates, 6); builder.store_vertices(coords); builder.store_texture_coordinates(texture_coords); builder.store_indices(indices); std::shared_ptr<DlVertices> vertices = builder.build();
ASSERT_NE(vertices, nullptr); ASSERT_NE(vertices->vertex_data(), nullptr); ASSERT_NE(vertices->texture_coordinate_data(), nullptr); ASSERT_EQ(vertices->colors(), nullptr); ASSERT_NE(vertices->indices(), nullptr);
ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); ASSERT_EQ(vertices->vertex_count(), 3); for (int i = 0; i < 3; i++) { ASSERT_EQ(vertices->vertex_data()[i], coords[i]); ASSERT_EQ(vertices->texture_coordinate_data()[i], texture_coords[i]); } ASSERT_EQ(vertices->index_count(), 6); for (int i = 0; i < 6; i++) { ASSERT_EQ(vertices->indices()[i], indices[i]); }}
TEST(DisplayListVertices, BuildWithColorAndIndices) { DlPoint coords[3] = { DlPoint(2, 3), DlPoint(5, 6), DlPoint(15, 20), }; uint32_t colors[3] = { 0xffff0000, 0xff00ffff, 0xff00ff00, }; uint16_t indices[6] = { 2, 1, 0, // 1, 2, 0, };
Builder builder(DlVertexMode::kTriangles, 3, // Builder::kHasColors, 6); builder.store_vertices(coords); builder.store_colors(colors); builder.store_indices(indices); std::shared_ptr<DlVertices> vertices = builder.build();
ASSERT_NE(vertices, nullptr); ASSERT_NE(vertices->vertex_data(), nullptr); ASSERT_EQ(vertices->texture_coordinate_data(), nullptr); ASSERT_NE(vertices->colors(), nullptr); ASSERT_NE(vertices->indices(), nullptr);
ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); ASSERT_EQ(vertices->vertex_count(), 3); for (int i = 0; i < 3; i++) { ASSERT_EQ(vertices->vertex_data()[i], coords[i]); ASSERT_EQ(vertices->colors()[i].argb(), colors[i]); } ASSERT_EQ(vertices->index_count(), 6); for (int i = 0; i < 6; i++) { ASSERT_EQ(vertices->indices()[i], indices[i]); }}
TEST(DisplayListVertices, BuildWithTexUsingPoints) { DlPoint coords[3] = { DlPoint(2, 3), DlPoint(5, 6), DlPoint(15, 20), }; DlPoint texture_coords[3] = { DlPoint(102, 103), DlPoint(105, 106), DlPoint(115, 120), };
Builder builder(DlVertexMode::kTriangles, 3, // Builder::kHasTextureCoordinates, 0); builder.store_vertices(coords); builder.store_texture_coordinates(texture_coords); std::shared_ptr<DlVertices> vertices = builder.build();
ASSERT_NE(vertices, nullptr); ASSERT_NE(vertices->vertex_data(), nullptr); ASSERT_NE(vertices->texture_coordinate_data(), nullptr); ASSERT_EQ(vertices->colors(), nullptr); ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); ASSERT_EQ(vertices->vertex_count(), 3); for (int i = 0; i < 3; i++) { ASSERT_EQ(vertices->vertex_data()[i], coords[i]); ASSERT_EQ(vertices->texture_coordinate_data()[i], texture_coords[i]); } ASSERT_EQ(vertices->index_count(), 0);}
TEST(DisplayListVertices, BuildWithTexUsingFloats) { float coords[6] = { 2, 3, // 5, 6, // 15, 20, }; float texture_coords[6] = { 102, 103, // 105, 106, // 115, 120, };
Builder builder(DlVertexMode::kTriangles, 3, // Builder::kHasTextureCoordinates, 0); builder.store_vertices(coords); builder.store_texture_coordinates(texture_coords); std::shared_ptr<DlVertices> vertices = builder.build();
ASSERT_NE(vertices, nullptr); ASSERT_NE(vertices->vertex_data(), nullptr); ASSERT_NE(vertices->texture_coordinate_data(), nullptr); ASSERT_EQ(vertices->colors(), nullptr); ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); ASSERT_EQ(vertices->vertex_count(), 3); for (int i = 0; i < 3; i++) { ASSERT_EQ(vertices->vertex_data()[i].x, coords[i * 2 + 0]); ASSERT_EQ(vertices->vertex_data()[i].y, coords[i * 2 + 1]); ASSERT_EQ(vertices->texture_coordinate_data()[i].x, texture_coords[i * 2 + 0]); ASSERT_EQ(vertices->texture_coordinate_data()[i].y, texture_coords[i * 2 + 1]); } ASSERT_EQ(vertices->index_count(), 0);}
TEST(DisplayListVertices, BuildUsingFloatsSameAsPoints) { DlPoint coord_points[3] = { DlPoint(2, 3), DlPoint(5, 6), DlPoint(15, 20), }; DlPoint texture_coord_points[3] = { DlPoint(102, 103), DlPoint(105, 106), DlPoint(115, 120), };
float coord_floats[6] = { 2, 3, // 5, 6, // 15, 20, }; float texture_coord_floats[6] = { 102, 103, // 105, 106, // 115, 120, };
Builder builder_points(DlVertexMode::kTriangles, 3, // Builder::kHasTextureCoordinates, 0); builder_points.store_vertices(coord_points); builder_points.store_texture_coordinates(texture_coord_points); std::shared_ptr<DlVertices> vertices_points = builder_points.build();
Builder builder_floats(DlVertexMode::kTriangles, 3, // Builder::kHasTextureCoordinates, 0); builder_floats.store_vertices(coord_floats); builder_floats.store_texture_coordinates(texture_coord_floats); std::shared_ptr<DlVertices> vertices_floats = builder_floats.build();
TestEquals(*vertices_points, *vertices_floats);}
TEST(DisplayListVertices, BuildWithColor) { DlPoint coords[3] = { DlPoint(2, 3), DlPoint(5, 6), DlPoint(15, 20), }; uint32_t colors[3] = { 0xffff0000, 0xff00ffff, 0xff00ff00, };
Builder builder(DlVertexMode::kTriangles, 3, // Builder::kHasColors, 0); builder.store_vertices(coords); builder.store_colors(colors); std::shared_ptr<DlVertices> vertices = builder.build();
ASSERT_NE(vertices, nullptr); ASSERT_NE(vertices->vertex_data(), nullptr); ASSERT_EQ(vertices->texture_coordinate_data(), nullptr); ASSERT_NE(vertices->colors(), nullptr); ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); ASSERT_EQ(vertices->vertex_count(), 3); for (int i = 0; i < 3; i++) { ASSERT_EQ(vertices->vertex_data()[i], coords[i]); ASSERT_EQ(vertices->colors()[i].argb(), colors[i]); } ASSERT_EQ(vertices->index_count(), 0);}
TEST(DisplayListVertices, BuildWithIndices) { DlPoint coords[3] = { DlPoint(2, 3), DlPoint(5, 6), DlPoint(15, 20), }; uint16_t indices[6] = { 2, 1, 0, // 1, 2, 0, };
Builder builder(DlVertexMode::kTriangles, 3, Builder::kNone, 6); builder.store_vertices(coords); builder.store_indices(indices); std::shared_ptr<DlVertices> vertices = builder.build();
ASSERT_NE(vertices, nullptr); ASSERT_NE(vertices->vertex_data(), nullptr); ASSERT_EQ(vertices->texture_coordinate_data(), nullptr); ASSERT_EQ(vertices->colors(), nullptr); ASSERT_NE(vertices->indices(), nullptr);
ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); ASSERT_EQ(vertices->vertex_count(), 3); for (int i = 0; i < 3; i++) { ASSERT_EQ(vertices->vertex_data()[i], coords[i]); } ASSERT_EQ(vertices->index_count(), 6); for (int i = 0; i < 6; i++) { ASSERT_EQ(vertices->indices()[i], indices[i]); }}
TEST(DisplayListVertices, BuildWithNoOptionalData) { DlPoint coords[3] = { DlPoint(2, 3), DlPoint(5, 6), DlPoint(15, 20), };
Builder builder(DlVertexMode::kTriangles, 3, Builder::kNone, 0); builder.store_vertices(coords); std::shared_ptr<DlVertices> vertices = builder.build();
ASSERT_NE(vertices, nullptr); ASSERT_NE(vertices->vertex_data(), nullptr); ASSERT_EQ(vertices->texture_coordinate_data(), nullptr); ASSERT_EQ(vertices->colors(), nullptr); ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); ASSERT_EQ(vertices->vertex_count(), 3); for (int i = 0; i < 3; i++) { ASSERT_EQ(vertices->vertex_data()[i], coords[i]); } ASSERT_EQ(vertices->index_count(), 0);}
TEST(DisplayListVertices, BuildWithNegativeIndexCount) { DlPoint coords[3] = { DlPoint(2, 3), DlPoint(5, 6), DlPoint(15, 20), };
Builder builder(DlVertexMode::kTriangles, 3, Builder::kNone, -5); builder.store_vertices(coords); std::shared_ptr<DlVertices> vertices = builder.build();
ASSERT_NE(vertices, nullptr); ASSERT_NE(vertices->vertex_data(), nullptr); ASSERT_EQ(vertices->texture_coordinate_data(), nullptr); ASSERT_EQ(vertices->colors(), nullptr); ASSERT_EQ(vertices->indices(), nullptr);
ASSERT_EQ(vertices->GetBounds(), DlRect::MakeLTRB(2, 3, 15, 20)); ASSERT_EQ(vertices->mode(), DlVertexMode::kTriangles); ASSERT_EQ(vertices->vertex_count(), 3); for (int i = 0; i < 3; i++) { ASSERT_EQ(vertices->vertex_data()[i], coords[i]); } ASSERT_EQ(vertices->index_count(), 0);}
TEST(DisplayListVertices, TestEquals) { DlPoint coords[3] = { DlPoint(2, 3), DlPoint(5, 6), DlPoint(15, 20), }; DlPoint texture_coords[3] = { DlPoint(102, 103), DlPoint(105, 106), DlPoint(115, 120), }; DlColor colors[3] = { DlColor::kRed(), DlColor::kCyan(), DlColor::kGreen(), }; uint16_t indices[6] = { 2, 1, 0, // 1, 2, 0, };
std::shared_ptr<DlVertices> vertices1 = DlVertices::Make( DlVertexMode::kTriangles, 3, coords, texture_coords, colors, 6, indices); std::shared_ptr<DlVertices> vertices2 = DlVertices::Make( DlVertexMode::kTriangles, 3, coords, texture_coords, colors, 6, indices); TestEquals(*vertices1, *vertices2);}
TEST(DisplayListVertices, TestNotEquals) { DlPoint coords[4] = { DlPoint(2, 3), DlPoint(5, 6), DlPoint(15, 20), DlPoint(53, 62), }; DlPoint wrong_coords[4] = { DlPoint(2, 3), DlPoint(5, 6), DlPoint(15, 20), DlPoint(57, 62), }; DlPoint texture_coords[4] = { DlPoint(102, 103), DlPoint(105, 106), DlPoint(115, 120), DlPoint(153, 162), }; DlPoint wrong_texture_coords[4] = { DlPoint(102, 103), DlPoint(105, 106), DlPoint(115, 121), DlPoint(153, 162), }; DlColor colors[4] = { DlColor::kRed(), DlColor::kCyan(), DlColor::kGreen(), DlColor::kMagenta(), }; DlColor wrong_colors[4] = { DlColor::kRed(), DlColor::kBlue(), DlColor::kGreen(), DlColor::kMagenta(), }; uint16_t indices[9] = { 2, 1, 0, // 1, 2, 0, // 1, 2, 3, }; uint16_t wrong_indices[9] = { 2, 1, 0, // 1, 2, 0, // 2, 3, 1, };
std::shared_ptr<DlVertices> vertices1 = DlVertices::Make( DlVertexMode::kTriangles, 4, coords, texture_coords, colors, 9, indices);
{ std::shared_ptr<DlVertices> vertices2 = DlVertices::Make(DlVertexMode::kTriangleFan, 4, coords, // texture_coords, colors, 9, indices); TestNotEquals(*vertices1, *vertices2, "vertex mode differs"); } { std::shared_ptr<DlVertices> vertices2 = DlVertices::Make(DlVertexMode::kTriangles, 3, coords, // texture_coords, colors, 9, indices); TestNotEquals(*vertices1, *vertices2, "vertex count differs"); } { std::shared_ptr<DlVertices> vertices2 = DlVertices::Make(DlVertexMode::kTriangles, 4, wrong_coords, // texture_coords, colors, 9, indices); TestNotEquals(*vertices1, *vertices2, "vertex coordinates differ"); } { std::shared_ptr<DlVertices> vertices2 = DlVertices::Make(DlVertexMode::kTriangles, 4, coords, // wrong_texture_coords, colors, 9, indices); TestNotEquals(*vertices1, *vertices2, "texture coordinates differ"); } { std::shared_ptr<DlVertices> vertices2 = DlVertices::Make(DlVertexMode::kTriangles, 4, coords, // texture_coords, wrong_colors, 9, indices); TestNotEquals(*vertices1, *vertices2, "colors differ"); } { std::shared_ptr<DlVertices> vertices2 = DlVertices::Make(DlVertexMode::kTriangles, 4, coords, // texture_coords, colors, 6, indices); TestNotEquals(*vertices1, *vertices2, "index count differs"); } { std::shared_ptr<DlVertices> vertices2 = DlVertices::Make(DlVertexMode::kTriangles, 4, coords, // texture_coords, colors, 9, wrong_indices); TestNotEquals(*vertices1, *vertices2, "indices differ"); }}
} // namespace testing} // namespace flutter123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172# Symbolicating stack traces for engine crashes
iOS app archives produced using Flutter 3.24 or later embed engine debugging symbols and thus crashes are symbolicated by default.
The easiest way to symbolicate stack traces for Android and older iOS apps is to run the [dart_ci symbolizer locally](https://github.com/dart-lang/dart_ci/blob/main/github-label-notifier/symbolizer/README.md#using-this-locally). If that is not an option, the steps below explain how to do it manually.
## Android
### Get the symbols
1. Get the Flutter Framework or Flutter Engine revision from the report. If you have the Engine revision, skip to step 3.
2. Get the Engine revision from the Framework (this could be automated). `flutter/blob/main/bin/cache/engine.stamp` is the file which contains the information. Substitute the framework hash for `main` in that url.
3. With the full engine revision (e.g. cea5ed2b9be42a981eac762af3664e4a17d0a53f), you can now get the proper symbol files:
To view the available artifacts for a build, visit this URL in a browser (replacing the engine hash with your hash): `https://console.cloud.google.com/storage/browser/flutter_infra_release/flutter/cea5ed2b9be42a981eac762af3664e4a17d0a53f`
To download the symbols for android-arm, download this URL _using your browser_ (replacing the hash again, and noting that this URL is on a different host, "storage", compared to the one above, which uses "console"): `https://storage.cloud.google.com/flutter_infra_release/flutter/cea5ed2b9be42a981eac762af3664e4a17d0a53f/android-arm/symbols.zip`.
Please be aware that the type of the symbol must match your Apps release type. In above example, this refers to a android-arm **debug** build. If you work with a **release** or **profile** build, the URLs would look like this:
* <https://storage.cloud.google.com/flutter_infra_release/flutter/cea5ed2b9be42a981eac762af3664e4a17d0a53f/android-arm-release/symbols.zip> * <https://storage.cloud.google.com/flutter_infra_release/flutter/cea5ed2b9be42a981eac762af3664e4a17d0a53f/android-arm-profile/symbols.zip>
You have to use your browser because it does authentication.
### Symbolicate with ndk-stack
Once you have the symbols unzipped, you can use ndk-stack from your Android NDK. Suppose `stack.txt` contains the stack (including the leading `*** *** ***` line from the crash):
```bash.../ndk/prebuilt/linux-x86_64/bin/ndk-stack -sym .../path/to/downloaded/symbols < stack.txt```
Or on macOS:```bash.../ndk/prebuilt/darwin-x86_64/bin/ndk-stack -sym .../path/to/downloaded/symbols < stack.txt```
Some debugging tools, like _pidcat_ may not show the full tombstone logs. In that case, please use `adb logcat` directly and copy the full output.
### Symbolicate with addr2line
A alternative way to symbolicate is by using the addr2line tool. It is bundled with the NDK.To use it, simply call it with a path to the .so file downloaded above and feed the stack addresses to it manually. For example, on macOS:
```% $ANDROID_HOME/ndk/20.0.5594570/toolchains/llvm/prebuilt/darwin-x86_64/bin/aarch64-linux-android-addr2line -e ~/Downloads/libflutter.so```_The tool is now awaiting your input, so let's feed it a memory address_:```0x00000000006a26ec/b/s/w/ir/cache/builder/src/out/android_release_arm64/../../third_party/dart/runtime/vm/dart_api_impl.cc:1366```This revealed address `0x00000000006a26ec` to correspond with `dart_api_impl.cc:1366`.
### Making sure you got the right libflutter.so
The build system sets a build id for each `libflutter.so` file. In the tombstones, you would see the ID like so:
```#00 pc 000000000062d6e0 /data/app/com.app-tARy3eLH2Y-QN8J0d0WFog==/lib/arm64/libflutter.so!libflutter.so (offset 0x270000) (BuildId: 34ad5bdf0830d77a)```
This equals to a build id of **34ad5bdf0830d77a**. The `libflutter.so` debug files downloaded as shown above could be verified using the `file` command:
```sh% file ~/Downloads/libflutter.so/Users/user/Downloads/libflutter.so: ELF 64-bit LSB shared object, ARM aarch64, version 1 (SYSV), dynamically linked, BuildID[xxHash]=34ad5bdf0830d77a, with debug_info, not stripped```
Ensure the build IDs match, else you will not be able to symbolicate.
### Expanding Git Revisions
Go to a commit page with the short commit as the last fragment of the URL:(e.g. https://github.com/flutter/flutter/commit/9cb914df1 or https://github.com/flutter/engine/commit/2a13567) and then find the full revision on the page.
### Symbolicating local builds (Android)
If you have made your own builds, you can use ndk-stack directly:
```sh# dev/engine is where your engine's .gclient file is# android_debug_unopt is whatever build of your engine you are usingadb logcat | ~/dev/engine/src/third_party/android_tools/ndk/prebuilt/linux-x86_64/bin/ndk-stack -sym ~/dev/engine/src/out/android_debug_unopt```
### iOS
Since Flutter 3.24, symbols can be found in the Flutter framework's artifactcache, within the xcframework bundle at`bin/cache/artifacts/engine/ios-release/Flutter.xcframework`.
* Symbols for device builds are in the `ios-arm64/dSYMs/Flutter.framework.dSYM` bundle.* Symbols for simulator builds are in the `ios-arm64_x86_64-simulator/dSYMs/Flutter.framework.dSYM` bundle.
For versions prior to Flutter 3.24, the dSYM bundle can downloaded from GoogleCloud Storage. Follow the steps from the Android section in this guide, but inthe last step use a download url following this schema:`https://storage.cloud.google.com/flutter_infra_release/flutter/38a646e14cc25f5a56a989c6a5787bf74e0ea386/ios-release/Flutter.dSYM.zip`(replace the engine hash with your hash).
For release since Flutter 3.24, these symbols are no longer uploaded as aseparate archive and should be obtained from the artifact cache as describedabove. The artifact cache can be downloaded direcly using a URL following thisschema:`https://storage.googleapis.com/flutter_infra_release/flutter/c11fe483947c95553610ab59210af643f031f5f4/ios-release/artifacts.zip`(replace the engine hash with your hash).
### macOS
Since Flutter 3.27, symbols can be found in the Flutter framework's artifactcache, within the xcframework bundle at`bin/cache/artifacts/engine/darwin-x64-release/Flutter.xcframework`.
* Symbols for device builds are in the `macos-arm64_x86_64/dSYMs/FlutterMacOS.framework.dSYM` bundle.
For versions prior to Flutter 3.27, the dSYM bundle can downloaded from GoogleCloud Storage. Follow the steps from the Android section in this guide, but inthe last step use a download url following this schema:`https://storage.cloud.google.com/flutter_infra_release/flutter/cf4507ae1008c11c6155d31e852999d75670afcf/darwin-x64-release/FlutterMacOS.dSYM.zip`(replace the engine hash with your hash).
For release since Flutter 3.27, these symbols are no longer uploaded as aseparate archive and should be obtained from the artifact cache as describedabove. The artifact cache can be downloaded direcly using a URL following thisschema:`https://storage.googleapis.com/flutter_infra_release/flutter/cf4507ae1008c11c6155d31e852999d75670afcf/darwin-x64-release/framework.zip`(replace the engine hash with your hash).
### Symbolicating local builds (macOS)
If you built your local engine in debug or profile Dart modes, the framework's dylib's symbols aren't stripped and are available by default.
### Crashes in Dart AOT code
If the crash is in AOT Dart code (in `--release` or `--profile` builds) on iOS, and you can build your own engine, these steps will be helpful for the VM team to fix the bug:
* Prepare a reduced test case.* Compile the engine in profile mode and disable optimizations for symbolicated traces. * `sky/tools/gn --ios --unopt --runtime-mode profile; ninja -C out/ios_profile_unopt -j800`.* Launch the application via the Xcode project and make it crash in the debugger.* File a bug on [dart-lang/sdk](https://github.com/dart-lang/sdk/issues/new).* Dump the register state and paste it into the bug. * In `lldb`, `register read`.* Copy the backtrace and paste it into the bug. * In `lldb`, `thread backtrace`. Assumes you are on the thread that crashed. If not, `thread select n`.* Disassemble the last frame and paste it into the bug. * In `lldb`, `frame select 0` then `disassemble --frame`.* Disassemble using the `gen_snapshot` and paste the function into the bug for more detailed information. * In the backtrace, look for the name of the precompiled function that caused the crash. * Open `SnapshotterInvoke` from Xcode and to the `RunCommand ... Snapshotter` call, add the `--disassemble` flags. * Modify the `RunCommand` function to dump to a file. * Build again. The results should end up in the file. * Look for the function name (by substring match) in this file and copy out that information to the bug.* Ping someone on dart-lang/sdk.
## Android Local Engine Builds
When running with a local engine build, the symbolization workflow can be cumbersome and unecessary. Instead, it is possible to build the engine itself with symbols and disable Gradle's automatic symbol stripping. This is also required to see symbol names in Android Studio CPU profiles.
1. In the android engine configuration, provide a --no-stripped argument to gn. For example: `gn --android --android-cpu=arm64 --unopt --no-stripped`
2. In the flutter project file `android/app/build.gradle`, add the following line under the `android` block:
```gradlepackagingOptions{ doNotStrip "**/*.so"}```12345678910111213141516171819202122The Flutter Engine is window toolkit agnostic. If you want to build Flutter embedders on one of the platforms not supported out of the box (i.e, iOS & Android), this page is for you.
This is a very low level API and is not suitable for beginners.
* The window toolkit agnostic component of the Flutter engine is available as a dynamic library in the `flutter_engine` GN target in [`//shell/platform/embedder:flutter_engine`](https://github.com/flutter/flutter/blob/5517cc9b3b3bcf12431b47f495e342a30b738835/engine/src/flutter/shell/platform/embedder/BUILD.gn#L558).* That target must be built as part of the host GN build. Such builds are already available for desktop Linux & Mac. If you want to target another platform, you will have to configure a GN toolchain for the same.* You may build this target yourself or download the same artifacts uploaded by the buildbots on each commit. * The Mac buildbot uploads the artifacts to a known location. Access it here [`https://storage.googleapis.com/flutter_infra_release/flutter/FLUTTER_HASH/darwin-x64/FlutterEmbedder.framework.zip`](https://storage.googleapis.com/flutter_infra_release/flutter/e672b006cb34c921db85b8e2f482ed3144a4574b/darwin-x64/FlutterEmbedder.framework.zip). * Replace `FLUTTER_HASH` with the SHA of the Flutter commit you wish to use. * The Linux buildbot uploads the artifacts to a known location. Access it here [`https://storage.googleapis.com/flutter_infra_release/flutter/FLUTTER_HASH/linux-x64/linux-x64-embedder.zip`](https://storage.googleapis.com/flutter_infra_release/flutter/e672b006cb34c921db85b8e2f482ed3144a4574b/linux-x64/linux-x64-embedder.zip) * Replace `FLUTTER_HASH` with the SHA of the Flutter commit you wish to use. * The binary is not stripped and contains debug information. Embedders are advised to strip the binary before deployment. * The Windows buildbot uploads the artifacts to a known location. Access it here [`https://storage.googleapis.com/flutter_infra_release/flutter/FLUTTER_HASH/windows-x64/windows-x64-embedder.zip`](https://storage.googleapis.com/flutter_infra_release/flutter/e672b006cb34c921db85b8e2f482ed3144a4574b/windows-x64/windows-x64-embedder.zip) * Replace `FLUTTER_HASH` with the SHA of the Flutter commit you wish to use.* The Flutter engine API has no platform specific dependencies, has a stable ABI and is available in its entirety in a [single C header file available here](https://github.com/flutter/engine/blob/master/engine/src/flutter/shell/platform/embedder/embedder.h).* To use as a guide, you may use [this example embedder that uses GLFW](https://github.com/flutter/engine/blob/master/engine/src/flutter/examples/glfw/FlutterEmbedderGLFW.cc) for window management and rendering.
While we do not object to teams creating custom builds of the Flutter engine for their purposes, we do not support this configuration. Not supporting it means that we do not commit to any timelines for fixing bugs that may come up in such a configuration, even for customers for which we would usually be willing to make commitments (see the [Issue Hygiene](../contributing/issue_hygiene/README.md) page). It also means that we encourage teams to view such configurations as short-term solutions only and encourage teams to transition away from such configurations at the earliest possible opportunity.
We do not expect custom engine builds to be long-term sustainable. They are not supported on any platform where we plan to be the publisher of a Flutter runtime distinct from the applications that run on the runtime, and they require significant effort to port to our new target platforms such as Web and desktop. There is also an expensive maintenance burden (for example, if we add new features, a custom engine build would need to be updated to support that feature).
We would generally recommend using custom engine builds only when porting Flutter to platforms that are not supported out of the box, for example in embedded hardware.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132This document is intended for developers of third party embedders who wish to package and ship their Flutter applications for AOT mode operation. A third party embedder uses [the stable C embedder API](https://github.com/flutter/engine/blob/869d9f528503778be1e5ab27ba53502f0cb20de2/shell/platform/embedder/embedder.h) to embed Flutter applications on their platform.
## Building an AOT Flutter Engine
By default, the Flutter engine packaged for embedders assumes that the mode of operation is JIT. An engine configured for JIT packages a VM that is incompatible with AOT snapshots. Build an AOT engine using the following invocation. This is also the invocation where custom target, sysroot and toolchain selection flags can be specified.
```./flutter/tools/gn --runtime-mode release <custom target flags as necessary>```
**Note:** Throughout this document, the `gn` flags mentioned work fine with other non-runtime mode or configuration selection options (stuff like `--no-lto`,` --unoptimized`, etc..). Such options are particularly useful during development and their use is highly encouraged.
This will produce a Flutter engine configured for AOT mode targeting the host. Note that we are repurposing Flutter’s “release” mode policy to prepare an AOT engine. The application of this policy to third party embedders is optional and a decision the authors of such embedders need to make themselves.
## Building the Architecture Specific `gen_snapshot`
The binary that converts Dart code to architecture specific AOT instructions is called `gen_snapshot`. A successful invocation of `gen_snapshot` should produce four binary blobs. These are the Dart VM heap and instructions snapshots as well as the isolate heap and instruction snapshots. Refer to the [wiki article on engine operation in AOT mode](Flutter-engine-operation-in-AOT-Mode.md) for the purpose of these snapshots.
A specific `gen_snapshot` can only produce AOT instructions for one target architecture. To verify that the `gen_snapshot` you have is producing instructions for the architecture you care about, invoke the same with the `--version` flag. It should produce something like the following.
```Dart VM version: 2.1.1-dev.2.0.flutter-ac1bf656c4 (Thu Jan 17 16:55:19 2019 +0000) on "macos_x64"```
The final string denotes the host/target pair. In the case of the example above, the host is `macos` and the target `x64`. An example of a `gen_snapshot` that produces instructions for `aarch64` would read “macos_simarm64” (the author is on MacOS X).
It is easiest to just pick the supported Flutter target whose architecture is closest to the one of the embedder. For example, if the target is `armv7`, the following invocation will generate a `gen_snapshot` that is suitably configured for that target.
```./flutter/tools/gn --android --runtime-mode release```
Another useful invocation for aarch64 AOT targeted `gen_snapshot` is:
```./flutter/tools/gn --android --runtime-mode release --android-cpu arm64```
**Important:** Calling convention and alignment must be the same (in addition to just the target architecture) for the AOT instructions generated by `gen_snapshot` and the target. Repurposing Flutter’s build targets makes sure that all those subtleties are taken care of. But it is still up to the embedder to pick and match the AOT instructions. For example, the `--android` --android-cpu arm64`configured`gen_snapshot`will not generate completely compatible instructions for iOS on`aarch64` (even though the target architectures are the same). A mismatch between the snapshot's architecture/ABI and the device's architecture/ABI will be detected when the snapshot is loaded and clearly reported.
## Building the AOT Snapshot
There are two separate steps involved in the generation of AOT instructions for the target architecture. First, a target architecture agnostic kernel snapshot (~AST) of the Flutter Dart application needs to be generated. Then, this snapshot is given to `gen_snaphost` which generates the AOT snapshot in the form of the four blobs (~machine code) listed above (and detailed on the wiki page).
### The Short and Easy Way
Both iOS and Android AOT modes need to do this step when they build their artifacts. So, if the embedder targets are similar, the workflow supported by the Flutter tooling can be repurposed for custom AOT embedders. For example, in the case of `aarch64` AOT instructions for Android like targets, the following instructions will generated the four AOT blobs in the intermediates.
```bashflutter --local-engine <local_engine_configuration> --local-engine-host <local_host_engine_configuration> build aot --target-platform android-arm64 --release```
**Note:** The `--local-engine` (and `--local-engine-host`) flag is technically optional. However, not specifying the flag will make the tools pick the released version on of the Flutter engine. This version may contain subtle version mismatches with the engine you are using to prepare the `gen_snapshot` binary. So it is safer to just make sure the version are the same.See [running with a local engine](Debugging-the-engine.md#running-a-flutter-app-with-a-local-engine) for more details.
The result of the invocation will be the generation of the following binary blobs in the `build/aot directory`:
- `vm_snapshot_data`: The VM snapshot data.- `vm_snapshot_instr`: The VM snapshot instructions.- `isolate_snapshot_data`: The Isolate snapshot data.- `isolate_snapshot_instr`: The isolate snapshot instructions.
### The Hard Way
To generate the four AOT snapshot blobs directly, you will have to generate the kernel snapshot and then prepare the AOT snapshot manually. The exact flags to use are rather esoteric but self explanatory. And, when necessary, the `-v` flag can be passed to the `flutter build aot` instruction to dump the exact flags used by Flutter. These can then be modified as necessary for the target architecture.
#### Generating the Kernel Snapshot
The following invocation will generate a file called `kernel_snapshot.dill` in the build directory. Make sure you run `flutter packages get` in your project first to fetch all package dependencies.
```$FLUTTER_ENGINE_OUT_DIR/dart \ $FLUTTER_ENGINE_OUT_DIR/frontend_server.dart.snapshot \ --sdk-root $FLUTTER_ENGINE_OUT_DIR/flutter_patched_sdk/ \ --strong \ --target=flutter \ --aot \ --tfa \ -Ddart.vm.product=true \ --packages .packages \ --output-dill build/kernel_snapshot.dill \ package:flutter_gallery/main.dart```
#### Generating the AOT Snapshot
Once the `kernel_snapshot.dill` file has been obtained, `gen_snapshot` can be invoked with the following arguments to generate the four blobs that form the AOT snapshot.
```$FLUTTER_ENGINE_OUT_DIR/gen_snapshot \ --causal_async_stacks \ --packages=.packages \ --deterministic \ --snapshot_kind=app-aot-blobs \ --vm_snapshot_data=build/vm_snapshot_data \ --isolate_snapshot_data=build/isolate_snapshot_data \ --vm_snapshot_instructions=build/vm_snapshot_instr \ --isolate_snapshot_instructions=build/isolate_snapshot_instr \ --no-sim-use-hardfp \ --no-use-integer-division \ build/kernel_snapshot.dill```
**Note:** The `-no*` flags in the invocation above may not be necessary for all targets and can be skipped. As always, when in doubt, call `flutter build aot -v` after selecting the most similar target and see the flags used by Flutter.
## Packaging the AOT Blobs
The four AOT blobs need to be shipped with the application and are necessary for the `FlutterEngineRun` call. Embedders have to make a decision about how best to package and ship these blobs to the target.
On the target at runtime, these blobs need to be mapped into the address space with the following restrictions:
- `vm_snapshot_data`: Read-Only.- `vm_snapshot_instr`: Read-Execute.- `isolate_snapshot_data`: Read-Only.- `isolate_snapshot_instr`: Read-Execute.
The responsibility of keeping the mappings alive is upto the embedder. The mappings must be maintained as long as the `FlutterEngine` is running and alive.
## Configuring the Engine for AOT Operation
In the `FlutterProjectArgs` struct given the `FlutterEngineRun` call, provide the following options:
- `vm_snapshot_data`: Pointer to the read-only VM snapshot mapping.- `vm_snapshot_data_size`: Size of the VM snapshot mapping.- `vm_snapshot_instructions`: Pointer to the read-execute VM instructions mapping.- `vm_snapshot_instructions_size`: Size of the VM instructions mapping.- `isolate_snapshot_data`: Pointer to the read-only isolate snapshot mapping.- `isolate_snapshot_data_size`: Size of the isolate snapshot mapping.- `isolate_snapshot_instructions`: Pointer to the read-execute isolate instructions mapping.- `isolate_snapshot_instructions_size`: Size of the isolate instructions mapping.
Flutter Engine is now running in AOT mode!flutter/engine/src/flutter/common/BUILD.gnAdded+26
flutter/engine/src/flutter/common/README.mdAdded+5
flutter/engine/src/flutter/common/config.gniAdded+162
flutter/engine/src/flutter/common/constants.hAdded+38
flutter/engine/src/flutter/common/exported_symbols.symAdded+10
flutter/engine/src/flutter/common/exported_symbols_mac.symAdded+8
flutter/engine/src/flutter/common/exported_test_symbols.symAdded+14
flutter/engine/src/flutter/common/exported_test_symbols_mac.symAdded+12
flutter/engine/src/flutter/common/fuchsia_config.gniAdded+12
flutter/engine/src/flutter/common/macros.hAdded+20
flutter/engine/src/flutter/common/settings.ccAdded+19
flutter/engine/src/flutter/common/settings.hAdded+367
flutter/engine/src/flutter/common/task_runners.ccAdded+50
flutter/engine/src/flutter/common/task_runners.hAdded+49
flutter/engine/src/flutter/display_list/BUILD.gnAdded+316
flutter/engine/src/flutter/display_list/display_list.ccAdded+481
flutter/engine/src/flutter/display_list/display_list.hAdded+566
flutter/engine/src/flutter/display_list/display_list_unittests.ccAdded
flutter/engine/src/flutter/display_list/dl_attributes.hAdded+111
flutter/engine/src/flutter/display_list/dl_blend_mode.ccAdded+7
flutter/engine/src/flutter/display_list/dl_blend_mode.hAdded+16
flutter/engine/src/flutter/display_list/dl_builder.ccAdded+2119
flutter/engine/src/flutter/display_list/dl_builder.hAdded+858
flutter/engine/src/flutter/display_list/dl_canvas.ccAdded+24
flutter/engine/src/flutter/display_list/dl_canvas.hAdded+248
flutter/engine/src/flutter/display_list/dl_color.ccAdded+75
flutter/engine/src/flutter/display_list/dl_color.hAdded+198
flutter/engine/src/flutter/display_list/dl_color_unittests.ccAdded+301
flutter/engine/src/flutter/display_list/dl_op_flags.ccAdded+11
flutter/engine/src/flutter/display_list/dl_op_flags.hAdded+421
flutter/engine/src/flutter/display_list/dl_op_receiver.ccAdded+11
flutter/engine/src/flutter/display_list/dl_op_receiver.hAdded+373
flutter/engine/src/flutter/display_list/dl_op_records.ccAdded+11
flutter/engine/src/flutter/display_list/dl_op_records.hAdded+1075
flutter/engine/src/flutter/display_list/dl_paint.ccAdded+40
flutter/engine/src/flutter/display_list/dl_paint.hAdded+225
flutter/engine/src/flutter/display_list/dl_paint_unittests.ccAdded+199
flutter/engine/src/flutter/display_list/dl_sampling_options.hAdded+26
flutter/engine/src/flutter/display_list/dl_storage.ccAdded+62
flutter/engine/src/flutter/display_list/dl_storage.hAdded+60
flutter/engine/src/flutter/display_list/dl_storage_unittests.ccAdded+47
flutter/engine/src/flutter/display_list/dl_tile_mode.hAdded+33
flutter/engine/src/flutter/display_list/dl_types.ccAdded+11
flutter/engine/src/flutter/display_list/dl_types.hAdded+28
flutter/engine/src/flutter/display_list/dl_vertices.ccAdded+322
flutter/engine/src/flutter/display_list/dl_vertices.hAdded+288
flutter/engine/src/flutter/display_list/dl_vertices_unittests.ccAdded+983
flutter/engine/src/flutter/docs/Crashes.mdAdded+172
flutter/engine/src/flutter/docs/Custom-Flutter-Engine-Embedders.mdAdded+22
flutter/engine/src/flutter/docs/Custom-Flutter-Engine-Embedding-in-AOT-Mode.mdAdded+132