text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_DISPLAY_LIST_TESTING_DL_TEST_SURFACE_PROVIDER_H_
#define FLUTTER_DISPLAY_LIST_TESTING_DL_TEST_SURFACE_PROVIDER_H_
#include <utility>
#include "flutter/display_list/display_list.h"
#include "flutter/display_list/image/dl_image.h"
#include "flutter/fml/mapping.h"
#include "flutter/testing/testing.h"
#include "third_party/skia/include/core/SkSurface.h"
namespace flutter {
namespace testing {
class DlPixelData : public SkRefCnt {
public:
virtual ~DlPixelData() = default;
virtual const uint32_t* addr32(int x, int y) const = 0;
virtual size_t width() const = 0;
virtual size_t height() const = 0;
virtual void write(const std::string& path) const = 0;
};
class DlSurfaceInstance {
public:
virtual ~DlSurfaceInstance() = default;
virtual sk_sp<SkSurface> sk_surface() const = 0;
int width() const { return sk_surface()->width(); }
int height() const { return sk_surface()->height(); }
};
class DlSurfaceInstanceBase : public DlSurfaceInstance {
public:
explicit DlSurfaceInstanceBase(sk_sp<SkSurface> surface)
: surface_(std::move(surface)) {}
~DlSurfaceInstanceBase() = default;
sk_sp<SkSurface> sk_surface() const override { return surface_; }
private:
sk_sp<SkSurface> surface_;
};
class DlSurfaceProvider {
public:
typedef enum { kN32PremulPixelFormat, k565PixelFormat } PixelFormat;
typedef enum { kSoftwareBackend, kOpenGlBackend, kMetalBackend } BackendType;
static SkImageInfo MakeInfo(PixelFormat format, int w, int h) {
switch (format) {
case kN32PremulPixelFormat:
return SkImageInfo::MakeN32Premul(w, h);
case k565PixelFormat:
return SkImageInfo::Make(SkISize::Make(w, h), kRGB_565_SkColorType,
kOpaque_SkAlphaType);
}
FML_DCHECK(false);
}
static std::string BackendName(BackendType type);
static std::unique_ptr<DlSurfaceProvider> Create(BackendType backend_type);
virtual ~DlSurfaceProvider() = default;
virtual const std::string backend_name() const = 0;
virtual BackendType backend_type() const = 0;
virtual bool supports(PixelFormat format) const = 0;
virtual bool supports_impeller() const { return false; }
virtual bool InitializeSurface(
size_t width,
size_t height,
PixelFormat format = kN32PremulPixelFormat) = 0;
virtual std::shared_ptr<DlSurfaceInstance> GetPrimarySurface() const = 0;
virtual std::shared_ptr<DlSurfaceInstance> MakeOffscreenSurface(
size_t width,
size_t height,
PixelFormat format = kN32PremulPixelFormat) const = 0;
virtual bool Snapshot(std::string& filename) const;
virtual sk_sp<DlPixelData> ImpellerSnapshot(const sk_sp<DisplayList>& list,
int width,
int height) const {
return nullptr;
}
virtual sk_sp<DlImage> MakeImpellerImage(const sk_sp<DisplayList>& list,
int width,
int height) const {
return nullptr;
}
protected:
DlSurfaceProvider() = default;
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_DISPLAY_LIST_TESTING_DL_TEST_SURFACE_PROVIDER_H_
| engine/display_list/testing/dl_test_surface_provider.h/0 | {
"file_path": "engine/display_list/testing/dl_test_surface_provider.h",
"repo_id": "engine",
"token_count": 1328
} | 154 |
#!/bin/bash
set -e # Exit if any program returns an error.
#################################################################
# Make the host C++ project.
#################################################################
if [ ! -d debug ]; then
mkdir debug
fi
cd debug
cmake -DCMAKE_BUILD_TYPE=Debug ..
make
#################################################################
# Make the guest Flutter project.
#################################################################
if [ ! -d myapp ]; then
flutter create myapp
cd myapp
flutter pub add flutter_spinkit
cd ..
fi
cd myapp
cp ../../main.dart lib/main.dart
flutter build bundle \
--local-engine-src-path ../../../../../ \
--local-engine=host_debug_unopt \
--local-engine-host=host_debug_unopt
cd -
#################################################################
# Run the Flutter Engine Embedder
#################################################################
./flutter_glfw ./myapp ../../../../third_party/icu/common/icudtl.dat
| engine/examples/glfw_drm/run.sh/0 | {
"file_path": "engine/examples/glfw_drm/run.sh",
"repo_id": "engine",
"token_count": 282
} | 155 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/fml/backtrace.h"
#include "flutter/fml/build_config.h"
#include "flutter/fml/command_line.h"
#include "flutter/fml/logging.h"
#include "gtest/gtest.h"
#include "flow_test_utils.h"
int main(int argc, char** argv) {
fml::InstallCrashHandler();
testing::InitGoogleTest(&argc, argv);
fml::CommandLine cmd = fml::CommandLineFromPlatformOrArgcArgv(argc, argv);
#if defined(OS_FUCHSIA)
flutter::SetGoldenDir(cmd.GetOptionValueWithDefault(
"golden-dir", "/pkg/data/flutter/testing/resources"));
#else
flutter::SetGoldenDir(
cmd.GetOptionValueWithDefault("golden-dir", "flutter/testing/resources"));
#endif
flutter::SetFontFile(cmd.GetOptionValueWithDefault(
"font-file",
"flutter/third_party/txt/third_party/fonts/Roboto-Regular.ttf"));
return RUN_ALL_TESTS();
}
| engine/flow/flow_run_all_unittests.cc/0 | {
"file_path": "engine/flow/flow_run_all_unittests.cc",
"repo_id": "engine",
"token_count": 362
} | 156 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FLOW_LAYERS_CLIP_PATH_LAYER_H_
#define FLUTTER_FLOW_LAYERS_CLIP_PATH_LAYER_H_
#include "flutter/flow/layers/clip_shape_layer.h"
namespace flutter {
class ClipPathLayer : public ClipShapeLayer<SkPath> {
public:
explicit ClipPathLayer(const SkPath& clip_path,
Clip clip_behavior = Clip::kAntiAlias);
protected:
const SkRect& clip_shape_bounds() const override;
void ApplyClip(LayerStateStack::MutatorContext& mutator) const override;
private:
FML_DISALLOW_COPY_AND_ASSIGN(ClipPathLayer);
};
} // namespace flutter
#endif // FLUTTER_FLOW_LAYERS_CLIP_PATH_LAYER_H_
| engine/flow/layers/clip_path_layer.h/0 | {
"file_path": "engine/flow/layers/clip_path_layer.h",
"repo_id": "engine",
"token_count": 295
} | 157 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FLOW_LAYERS_DISPLAY_LIST_LAYER_H_
#define FLUTTER_FLOW_LAYERS_DISPLAY_LIST_LAYER_H_
#include <memory>
#include "flutter/display_list/display_list.h"
#include "flutter/flow/layers/display_list_raster_cache_item.h"
#include "flutter/flow/layers/layer.h"
#include "flutter/flow/raster_cache_item.h"
namespace flutter {
class DisplayListLayer : public Layer {
public:
static constexpr size_t kMaxBytesToCompare = 10000;
DisplayListLayer(const SkPoint& offset,
sk_sp<DisplayList> display_list,
bool is_complex,
bool will_change);
DisplayList* display_list() const { return display_list_.get(); }
bool IsReplacing(DiffContext* context, const Layer* layer) const override;
void Diff(DiffContext* context, const Layer* old_layer) override;
const DisplayListLayer* as_display_list_layer() const override {
return this;
}
void Preroll(PrerollContext* frame) override;
void Paint(PaintContext& context) const override;
const DisplayListRasterCacheItem* raster_cache_item() const {
return display_list_raster_cache_item_.get();
}
RasterCacheKeyID caching_key_id() const override {
return RasterCacheKeyID(display_list()->unique_id(),
RasterCacheKeyType::kDisplayList);
}
private:
std::unique_ptr<DisplayListRasterCacheItem> display_list_raster_cache_item_;
SkPoint offset_;
SkRect bounds_;
sk_sp<DisplayList> display_list_;
static bool Compare(DiffContext::Statistics& statistics,
const DisplayListLayer* l1,
const DisplayListLayer* l2);
FML_DISALLOW_COPY_AND_ASSIGN(DisplayListLayer);
};
} // namespace flutter
#endif // FLUTTER_FLOW_LAYERS_DISPLAY_LIST_LAYER_H_
| engine/flow/layers/display_list_layer.h/0 | {
"file_path": "engine/flow/layers/display_list_layer.h",
"repo_id": "engine",
"token_count": 725
} | 158 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include "flutter/flow/layers/layer_tree.h"
#include "flutter/flow/compositor_context.h"
#include "flutter/flow/layers/container_layer.h"
#include "flutter/flow/raster_cache.h"
#include "flutter/flow/testing/mock_layer.h"
#include "flutter/fml/macros.h"
#include "flutter/testing/canvas_test.h"
#include "flutter/testing/mock_canvas.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
class LayerTreeTest : public CanvasTest {
public:
LayerTreeTest()
: root_transform_(SkMatrix::Translate(1.0f, 1.0f)),
scoped_frame_(compositor_context_.AcquireFrame(nullptr,
&mock_canvas(),
nullptr,
root_transform_,
false,
true,
nullptr,
nullptr)) {}
CompositorContext::ScopedFrame& frame() { return *scoped_frame_.get(); }
const SkMatrix& root_transform() { return root_transform_; }
std::unique_ptr<LayerTree> BuildLayerTree(const LayerTree::Config& config) {
return std::make_unique<LayerTree>(config, SkISize::Make(64, 64));
}
private:
CompositorContext compositor_context_;
SkMatrix root_transform_;
std::unique_ptr<CompositorContext::ScopedFrame> scoped_frame_;
};
TEST_F(LayerTreeTest, PaintingEmptyLayerDies) {
auto layer = std::make_shared<ContainerLayer>();
auto layer_tree = BuildLayerTree(LayerTree::Config{
.root_layer = layer,
});
layer_tree->Preroll(frame());
EXPECT_EQ(layer->paint_bounds(), SkRect::MakeEmpty());
EXPECT_TRUE(layer->is_empty());
layer_tree->Paint(frame());
}
TEST_F(LayerTreeTest, PaintBeforePrerollDies) {
const SkRect child_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 20.5f, 21.5f);
SkPath child_path;
child_path.addRect(child_bounds);
auto mock_layer = std::make_shared<MockLayer>(child_path);
auto layer = std::make_shared<ContainerLayer>();
layer->Add(mock_layer);
auto layer_tree = BuildLayerTree(LayerTree::Config{
.root_layer = layer,
});
EXPECT_EQ(mock_layer->paint_bounds(), kEmptyRect);
EXPECT_EQ(layer->paint_bounds(), kEmptyRect);
EXPECT_TRUE(mock_layer->is_empty());
EXPECT_TRUE(layer->is_empty());
layer_tree->Paint(frame());
EXPECT_EQ(mock_canvas().draw_calls(), std::vector<MockCanvas::DrawCall>());
}
TEST_F(LayerTreeTest, Simple) {
const SkRect child_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 20.5f, 21.5f);
const SkPath child_path = SkPath().addRect(child_bounds);
const DlPaint child_paint = DlPaint(DlColor::kCyan());
auto mock_layer = std::make_shared<MockLayer>(child_path, child_paint);
auto layer = std::make_shared<ContainerLayer>();
layer->Add(mock_layer);
auto layer_tree = BuildLayerTree(LayerTree::Config{
.root_layer = layer,
});
layer_tree->Preroll(frame());
EXPECT_EQ(mock_layer->paint_bounds(), child_bounds);
EXPECT_EQ(layer->paint_bounds(), mock_layer->paint_bounds());
EXPECT_FALSE(mock_layer->is_empty());
EXPECT_FALSE(layer->is_empty());
EXPECT_EQ(mock_layer->parent_matrix(), root_transform());
layer_tree->Paint(frame());
EXPECT_EQ(mock_canvas().draw_calls(),
std::vector({MockCanvas::DrawCall{
0, MockCanvas::DrawPathData{child_path, child_paint}}}));
}
TEST_F(LayerTreeTest, Multiple) {
const SkPath child_path1 = SkPath().addRect(5.0f, 6.0f, 20.5f, 21.5f);
const SkPath child_path2 = SkPath().addRect(8.0f, 2.0f, 16.5f, 14.5f);
const DlPaint child_paint1 = DlPaint(DlColor::kMidGrey());
const DlPaint child_paint2 = DlPaint(DlColor::kGreen());
auto mock_layer1 = std::make_shared<MockLayer>(child_path1, child_paint1);
mock_layer1->set_fake_has_platform_view(true);
auto mock_layer2 = std::make_shared<MockLayer>(child_path2, child_paint2);
auto layer = std::make_shared<ContainerLayer>();
layer->Add(mock_layer1);
layer->Add(mock_layer2);
SkRect expected_total_bounds = child_path1.getBounds();
expected_total_bounds.join(child_path2.getBounds());
auto layer_tree = BuildLayerTree(LayerTree::Config{
.root_layer = layer,
});
layer_tree->Preroll(frame());
EXPECT_EQ(mock_layer1->paint_bounds(), child_path1.getBounds());
EXPECT_EQ(mock_layer2->paint_bounds(), child_path2.getBounds());
EXPECT_EQ(layer->paint_bounds(), expected_total_bounds);
EXPECT_FALSE(mock_layer1->is_empty());
EXPECT_FALSE(mock_layer2->is_empty());
EXPECT_FALSE(layer->is_empty());
EXPECT_EQ(mock_layer1->parent_matrix(), root_transform());
EXPECT_EQ(mock_layer2->parent_matrix(), root_transform());
EXPECT_EQ(mock_layer1->parent_cull_rect(), kGiantRect);
EXPECT_EQ(mock_layer2->parent_cull_rect(),
kGiantRect); // Siblings are independent
layer_tree->Paint(frame());
EXPECT_EQ(
mock_canvas().draw_calls(),
std::vector({MockCanvas::DrawCall{
0, MockCanvas::DrawPathData{child_path1, child_paint1}},
MockCanvas::DrawCall{0, MockCanvas::DrawPathData{
child_path2, child_paint2}}}));
}
TEST_F(LayerTreeTest, MultipleWithEmpty) {
const SkPath child_path1 = SkPath().addRect(5.0f, 6.0f, 20.5f, 21.5f);
const DlPaint child_paint1 = DlPaint(DlColor::kMidGrey());
const DlPaint child_paint2 = DlPaint(DlColor::kGreen());
auto mock_layer1 = std::make_shared<MockLayer>(child_path1, child_paint1);
auto mock_layer2 = std::make_shared<MockLayer>(SkPath(), child_paint2);
auto layer = std::make_shared<ContainerLayer>();
layer->Add(mock_layer1);
layer->Add(mock_layer2);
auto layer_tree = BuildLayerTree(LayerTree::Config{
.root_layer = layer,
});
layer_tree->Preroll(frame());
EXPECT_EQ(mock_layer1->paint_bounds(), child_path1.getBounds());
EXPECT_EQ(mock_layer2->paint_bounds(), SkPath().getBounds());
EXPECT_EQ(layer->paint_bounds(), child_path1.getBounds());
EXPECT_FALSE(mock_layer1->is_empty());
EXPECT_TRUE(mock_layer2->is_empty());
EXPECT_FALSE(layer->is_empty());
EXPECT_EQ(mock_layer1->parent_matrix(), root_transform());
EXPECT_EQ(mock_layer2->parent_matrix(), root_transform());
EXPECT_EQ(mock_layer1->parent_cull_rect(), kGiantRect);
EXPECT_EQ(mock_layer2->parent_cull_rect(), kGiantRect);
layer_tree->Paint(frame());
EXPECT_EQ(mock_canvas().draw_calls(),
std::vector({MockCanvas::DrawCall{
0, MockCanvas::DrawPathData{child_path1, child_paint1}}}));
}
TEST_F(LayerTreeTest, NeedsSystemComposite) {
const SkPath child_path1 = SkPath().addRect(5.0f, 6.0f, 20.5f, 21.5f);
const SkPath child_path2 = SkPath().addRect(8.0f, 2.0f, 16.5f, 14.5f);
const DlPaint child_paint1 = DlPaint(DlColor::kMidGrey());
const DlPaint child_paint2 = DlPaint(DlColor::kGreen());
auto mock_layer1 = std::make_shared<MockLayer>(child_path1, child_paint1);
auto mock_layer2 = std::make_shared<MockLayer>(child_path2, child_paint2);
auto layer = std::make_shared<ContainerLayer>();
layer->Add(mock_layer1);
layer->Add(mock_layer2);
SkRect expected_total_bounds = child_path1.getBounds();
expected_total_bounds.join(child_path2.getBounds());
auto layer_tree = BuildLayerTree(LayerTree::Config{
.root_layer = layer,
});
layer_tree->Preroll(frame());
EXPECT_EQ(mock_layer1->paint_bounds(), child_path1.getBounds());
EXPECT_EQ(mock_layer2->paint_bounds(), child_path2.getBounds());
EXPECT_EQ(layer->paint_bounds(), expected_total_bounds);
EXPECT_FALSE(mock_layer1->is_empty());
EXPECT_FALSE(mock_layer2->is_empty());
EXPECT_FALSE(layer->is_empty());
EXPECT_EQ(mock_layer1->parent_matrix(), root_transform());
EXPECT_EQ(mock_layer2->parent_matrix(), root_transform());
EXPECT_EQ(mock_layer1->parent_cull_rect(), kGiantRect);
EXPECT_EQ(mock_layer2->parent_cull_rect(), kGiantRect);
layer_tree->Paint(frame());
EXPECT_EQ(
mock_canvas().draw_calls(),
std::vector({MockCanvas::DrawCall{
0, MockCanvas::DrawPathData{child_path1, child_paint1}},
MockCanvas::DrawCall{0, MockCanvas::DrawPathData{
child_path2, child_paint2}}}));
}
TEST_F(LayerTreeTest, PrerollContextInitialization) {
LayerStateStack state_stack;
state_stack.set_preroll_delegate(kGiantRect, SkMatrix::I());
FixedRefreshRateStopwatch mock_raster_time;
FixedRefreshRateStopwatch mock_ui_time;
std::shared_ptr<TextureRegistry> mock_registry;
auto expect_defaults = [&state_stack, &mock_raster_time, &mock_ui_time,
&mock_registry](const PrerollContext& context) {
EXPECT_EQ(context.raster_cache, nullptr);
EXPECT_EQ(context.gr_context, nullptr);
EXPECT_EQ(context.view_embedder, nullptr);
EXPECT_EQ(&context.state_stack, &state_stack);
EXPECT_EQ(context.dst_color_space, nullptr);
EXPECT_EQ(context.state_stack.device_cull_rect(), kGiantRect);
EXPECT_EQ(context.state_stack.transform_3x3(), SkMatrix::I());
EXPECT_EQ(context.state_stack.transform_4x4(), SkM44());
EXPECT_EQ(context.surface_needs_readback, false);
EXPECT_EQ(&context.raster_time, &mock_raster_time);
EXPECT_EQ(&context.ui_time, &mock_ui_time);
EXPECT_EQ(context.texture_registry.get(), mock_registry.get());
EXPECT_EQ(context.has_platform_view, false);
EXPECT_EQ(context.has_texture_layer, false);
EXPECT_EQ(context.renderable_state_flags, 0);
EXPECT_EQ(context.raster_cached_entries, nullptr);
};
// These 4 initializers are required because they are handled by reference
PrerollContext context{
.state_stack = state_stack,
.raster_time = mock_raster_time,
.ui_time = mock_ui_time,
.texture_registry = mock_registry,
};
expect_defaults(context);
}
TEST_F(LayerTreeTest, PaintContextInitialization) {
LayerStateStack state_stack;
FixedRefreshRateStopwatch mock_raster_time;
FixedRefreshRateStopwatch mock_ui_time;
std::shared_ptr<TextureRegistry> mock_registry;
auto expect_defaults = [&state_stack, &mock_raster_time, &mock_ui_time,
&mock_registry](const PaintContext& context) {
EXPECT_EQ(&context.state_stack, &state_stack);
EXPECT_EQ(context.canvas, nullptr);
EXPECT_EQ(context.gr_context, nullptr);
EXPECT_EQ(context.view_embedder, nullptr);
EXPECT_EQ(&context.raster_time, &mock_raster_time);
EXPECT_EQ(&context.ui_time, &mock_ui_time);
EXPECT_EQ(context.texture_registry.get(), mock_registry.get());
EXPECT_EQ(context.raster_cache, nullptr);
EXPECT_EQ(context.state_stack.checkerboard_func(), nullptr);
EXPECT_EQ(context.enable_leaf_layer_tracing, false);
EXPECT_EQ(context.layer_snapshot_store, nullptr);
};
// These 4 initializers are required because they are handled by reference
PaintContext context{
.state_stack = state_stack,
.raster_time = mock_raster_time,
.ui_time = mock_ui_time,
.texture_registry = mock_registry,
};
expect_defaults(context);
}
} // namespace testing
} // namespace flutter
| engine/flow/layers/layer_tree_unittests.cc/0 | {
"file_path": "engine/flow/layers/layer_tree_unittests.cc",
"repo_id": "engine",
"token_count": 4859
} | 159 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/flow/layers/texture_layer.h"
#include "flutter/common/graphics/texture.h"
namespace flutter {
TextureLayer::TextureLayer(const SkPoint& offset,
const SkSize& size,
int64_t texture_id,
bool freeze,
DlImageSampling sampling)
: offset_(offset),
size_(size),
texture_id_(texture_id),
freeze_(freeze),
sampling_(sampling) {}
void TextureLayer::Diff(DiffContext* context, const Layer* old_layer) {
DiffContext::AutoSubtreeRestore subtree(context);
if (!context->IsSubtreeDirty()) {
FML_DCHECK(old_layer);
auto prev = old_layer->as_texture_layer();
// TODO(knopp) It would be nice to be able to determine that a texture is
// dirty
context->MarkSubtreeDirty(context->GetOldLayerPaintRegion(prev));
}
// Make sure DiffContext knows there is a TextureLayer in this subtree.
// This prevents ContainerLayer from skipping TextureLayer diffing when
// TextureLayer is inside retained layer.
// See ContainerLayer::DiffChildren
// https://github.com/flutter/flutter/issues/92925
context->MarkSubtreeHasTextureLayer();
context->AddLayerBounds(SkRect::MakeXYWH(offset_.x(), offset_.y(),
size_.width(), size_.height()));
context->SetLayerPaintRegion(this, context->CurrentSubtreeRegion());
}
void TextureLayer::Preroll(PrerollContext* context) {
set_paint_bounds(SkRect::MakeXYWH(offset_.x(), offset_.y(), size_.width(),
size_.height()));
context->has_texture_layer = true;
context->renderable_state_flags = LayerStateStack::kCallerCanApplyOpacity;
}
void TextureLayer::Paint(PaintContext& context) const {
FML_DCHECK(needs_painting(context));
std::shared_ptr<Texture> texture =
context.texture_registry
? context.texture_registry->GetTexture(texture_id_)
: nullptr;
if (!texture) {
TRACE_EVENT_INSTANT0("flutter", "null texture");
return;
}
DlPaint paint;
Texture::PaintContext ctx{
.canvas = context.canvas,
.gr_context = context.gr_context,
.aiks_context = context.aiks_context,
.paint = context.state_stack.fill(paint),
};
texture->Paint(ctx, paint_bounds(), freeze_, sampling_);
}
} // namespace flutter
| engine/flow/layers/texture_layer.cc/0 | {
"file_path": "engine/flow/layers/texture_layer.cc",
"repo_id": "engine",
"token_count": 979
} | 160 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/display_list/benchmarking/dl_complexity.h"
#include "flutter/display_list/display_list.h"
#include "flutter/display_list/dl_builder.h"
#include "flutter/display_list/testing/dl_test_snippets.h"
#include "flutter/flow/layers/container_layer.h"
#include "flutter/flow/layers/display_list_layer.h"
#include "flutter/flow/layers/image_filter_layer.h"
#include "flutter/flow/layers/layer_tree.h"
#include "flutter/flow/layers/transform_layer.h"
#include "flutter/flow/raster_cache.h"
#include "flutter/flow/raster_cache_item.h"
#include "flutter/flow/testing/layer_test.h"
#include "flutter/flow/testing/mock_raster_cache.h"
#include "flutter/testing/assertions_skia.h"
#include "gtest/gtest.h"
#include "third_party/skia/include/core/SkMatrix.h"
#include "third_party/skia/include/core/SkPoint.h"
// TODO(zanderso): https://github.com/flutter/flutter/issues/127701
// NOLINTBEGIN(bugprone-unchecked-optional-access)
namespace flutter {
namespace testing {
TEST(RasterCache, SimpleInitialization) {
flutter::RasterCache cache;
ASSERT_TRUE(true);
}
TEST(RasterCache, MetricsOmitUnpopulatedEntries) {
size_t threshold = 2;
flutter::RasterCache cache(threshold);
SkMatrix matrix = SkMatrix::I();
auto display_list = GetSampleDisplayList();
MockCanvas dummy_canvas(1000, 1000);
DlPaint paint;
LayerStateStack preroll_state_stack;
preroll_state_stack.set_preroll_delegate(kGiantRect, matrix);
LayerStateStack paint_state_stack;
preroll_state_stack.set_delegate(&dummy_canvas);
FixedRefreshRateStopwatch raster_time;
FixedRefreshRateStopwatch ui_time;
PrerollContextHolder preroll_context_holder = GetSamplePrerollContextHolder(
preroll_state_stack, &cache, &raster_time, &ui_time);
PaintContextHolder paint_context_holder = GetSamplePaintContextHolder(
paint_state_stack, &cache, &raster_time, &ui_time);
auto& preroll_context = preroll_context_holder.preroll_context;
auto& paint_context = paint_context_holder.paint_context;
cache.BeginFrame();
DisplayListRasterCacheItem display_list_item(display_list, SkPoint(), true,
false);
// 1st access.
ASSERT_FALSE(RasterCacheItemPrerollAndTryToRasterCache(
display_list_item, preroll_context, paint_context, matrix));
ASSERT_FALSE(display_list_item.Draw(paint_context, &dummy_canvas, &paint));
cache.EndFrame();
ASSERT_EQ(cache.picture_metrics().total_count(), 0u);
ASSERT_EQ(cache.picture_metrics().total_bytes(), 0u);
cache.BeginFrame();
// 2nd access.
ASSERT_FALSE(RasterCacheItemPrerollAndTryToRasterCache(
display_list_item, preroll_context, paint_context, matrix));
ASSERT_FALSE(display_list_item.Draw(paint_context, &dummy_canvas, &paint));
cache.EndFrame();
ASSERT_EQ(cache.picture_metrics().total_count(), 0u);
ASSERT_EQ(cache.picture_metrics().total_bytes(), 0u);
cache.BeginFrame();
// Now Prepare should cache it.
ASSERT_TRUE(RasterCacheItemPrerollAndTryToRasterCache(
display_list_item, preroll_context, paint_context, matrix));
ASSERT_TRUE(display_list_item.Draw(paint_context, &dummy_canvas, &paint));
cache.EndFrame();
ASSERT_EQ(cache.picture_metrics().total_count(), 1u);
// 80w * 80h * 4bpp + image object overhead
ASSERT_EQ(cache.picture_metrics().total_bytes(), 25624u);
}
TEST(RasterCache, ThresholdIsRespectedForDisplayList) {
size_t threshold = 2;
flutter::RasterCache cache(threshold);
SkMatrix matrix = SkMatrix::I();
auto display_list = GetSampleDisplayList();
MockCanvas dummy_canvas(1000, 1000);
DlPaint paint;
LayerStateStack preroll_state_stack;
preroll_state_stack.set_preroll_delegate(kGiantRect, matrix);
LayerStateStack paint_state_stack;
preroll_state_stack.set_delegate(&dummy_canvas);
FixedRefreshRateStopwatch raster_time;
FixedRefreshRateStopwatch ui_time;
PrerollContextHolder preroll_context_holder = GetSamplePrerollContextHolder(
preroll_state_stack, &cache, &raster_time, &ui_time);
PaintContextHolder paint_context_holder = GetSamplePaintContextHolder(
paint_state_stack, &cache, &raster_time, &ui_time);
auto& preroll_context = preroll_context_holder.preroll_context;
auto& paint_context = paint_context_holder.paint_context;
cache.BeginFrame();
DisplayListRasterCacheItem display_list_item(display_list, SkPoint(), true,
false);
// 1st access.
ASSERT_FALSE(RasterCacheItemPrerollAndTryToRasterCache(
display_list_item, preroll_context, paint_context, matrix));
ASSERT_FALSE(display_list_item.Draw(paint_context, &dummy_canvas, &paint));
cache.EndFrame();
cache.BeginFrame();
// 2nd access.
ASSERT_FALSE(RasterCacheItemPrerollAndTryToRasterCache(
display_list_item, preroll_context, paint_context, matrix));
ASSERT_FALSE(display_list_item.Draw(paint_context, &dummy_canvas, &paint));
cache.EndFrame();
cache.BeginFrame();
// Now Prepare should cache it.
ASSERT_TRUE(RasterCacheItemPrerollAndTryToRasterCache(
display_list_item, preroll_context, paint_context, matrix));
ASSERT_TRUE(display_list_item.Draw(paint_context, &dummy_canvas, &paint));
}
TEST(RasterCache, SetCheckboardCacheImages) {
size_t threshold = 1;
flutter::RasterCache cache(threshold);
SkMatrix matrix = SkMatrix::I();
auto display_list = GetSampleDisplayList();
LayerStateStack preroll_state_stack;
preroll_state_stack.set_preroll_delegate(kGiantRect, matrix);
FixedRefreshRateStopwatch raster_time;
FixedRefreshRateStopwatch ui_time;
PaintContextHolder paint_context_holder = GetSamplePaintContextHolder(
preroll_state_stack, &cache, &raster_time, &ui_time);
auto& paint_context = paint_context_holder.paint_context;
auto dummy_draw_function = [](DlCanvas* canvas) {};
bool did_draw_checkerboard = false;
auto draw_checkerboard = [&](DlCanvas* canvas, const SkRect&) {
did_draw_checkerboard = true;
};
RasterCache::Context r_context = {
// clang-format off
.gr_context = paint_context.gr_context,
.dst_color_space = paint_context.dst_color_space,
.matrix = matrix,
.logical_rect = display_list->bounds(),
.flow_type = "RasterCacheFlow::DisplayList",
// clang-format on
};
cache.SetCheckboardCacheImages(false);
cache.Rasterize(r_context, nullptr, dummy_draw_function, draw_checkerboard);
ASSERT_FALSE(did_draw_checkerboard);
cache.SetCheckboardCacheImages(true);
cache.Rasterize(r_context, nullptr, dummy_draw_function, draw_checkerboard);
ASSERT_TRUE(did_draw_checkerboard);
}
TEST(RasterCache, AccessThresholdOfZeroDisablesCachingForDisplayList) {
size_t threshold = 0;
flutter::RasterCache cache(threshold);
SkMatrix matrix = SkMatrix::I();
auto display_list = GetSampleDisplayList();
MockCanvas dummy_canvas(1000, 1000);
DlPaint paint;
LayerStateStack preroll_state_stack;
preroll_state_stack.set_preroll_delegate(kGiantRect, matrix);
LayerStateStack paint_state_stack;
preroll_state_stack.set_delegate(&dummy_canvas);
FixedRefreshRateStopwatch raster_time;
FixedRefreshRateStopwatch ui_time;
PrerollContextHolder preroll_context_holder = GetSamplePrerollContextHolder(
preroll_state_stack, &cache, &raster_time, &ui_time);
PaintContextHolder paint_context_holder = GetSamplePaintContextHolder(
paint_state_stack, &cache, &raster_time, &ui_time);
auto& preroll_context = preroll_context_holder.preroll_context;
auto& paint_context = paint_context_holder.paint_context;
cache.BeginFrame();
DisplayListRasterCacheItem display_list_item(display_list, SkPoint(), true,
false);
ASSERT_FALSE(RasterCacheItemPrerollAndTryToRasterCache(
display_list_item, preroll_context, paint_context, matrix));
ASSERT_FALSE(display_list_item.Draw(paint_context, &dummy_canvas, &paint));
}
TEST(RasterCache, PictureCacheLimitPerFrameIsRespectedWhenZeroForDisplayList) {
size_t picture_cache_limit_per_frame = 0;
flutter::RasterCache cache(3, picture_cache_limit_per_frame);
SkMatrix matrix = SkMatrix::I();
auto display_list = GetSampleDisplayList();
MockCanvas dummy_canvas(1000, 1000);
DlPaint paint;
LayerStateStack preroll_state_stack;
preroll_state_stack.set_preroll_delegate(kGiantRect, matrix);
LayerStateStack paint_state_stack;
preroll_state_stack.set_delegate(&dummy_canvas);
FixedRefreshRateStopwatch raster_time;
FixedRefreshRateStopwatch ui_time;
PrerollContextHolder preroll_context_holder = GetSamplePrerollContextHolder(
preroll_state_stack, &cache, &raster_time, &ui_time);
PaintContextHolder paint_context_holder = GetSamplePaintContextHolder(
paint_state_stack, &cache, &raster_time, &ui_time);
auto& preroll_context = preroll_context_holder.preroll_context;
auto& paint_context = paint_context_holder.paint_context;
cache.BeginFrame();
DisplayListRasterCacheItem display_list_item(display_list, SkPoint(), true,
false);
// 1st access.
ASSERT_FALSE(RasterCacheItemPrerollAndTryToRasterCache(
display_list_item, preroll_context, paint_context, matrix));
ASSERT_FALSE(display_list_item.Draw(paint_context, &dummy_canvas, &paint));
// 2nd access.
ASSERT_FALSE(RasterCacheItemPrerollAndTryToRasterCache(
display_list_item, preroll_context, paint_context, matrix));
ASSERT_FALSE(display_list_item.Draw(paint_context, &dummy_canvas, &paint));
// the picture_cache_limit_per_frame = 0, so don't cache it
ASSERT_FALSE(RasterCacheItemPrerollAndTryToRasterCache(
display_list_item, preroll_context, paint_context, matrix));
ASSERT_FALSE(display_list_item.Draw(paint_context, &dummy_canvas, &paint));
}
TEST(RasterCache, EvictUnusedCacheEntries) {
size_t threshold = 1;
flutter::RasterCache cache(threshold);
SkMatrix matrix = SkMatrix::I();
auto display_list_1 = GetSampleDisplayList();
auto display_list_2 = GetSampleDisplayList();
MockCanvas dummy_canvas(1000, 1000);
DlPaint paint;
LayerStateStack preroll_state_stack;
preroll_state_stack.set_preroll_delegate(kGiantRect, matrix);
LayerStateStack paint_state_stack;
preroll_state_stack.set_delegate(&dummy_canvas);
FixedRefreshRateStopwatch raster_time;
FixedRefreshRateStopwatch ui_time;
PrerollContextHolder preroll_context_holder = GetSamplePrerollContextHolder(
preroll_state_stack, &cache, &raster_time, &ui_time);
PaintContextHolder paint_context_holder = GetSamplePaintContextHolder(
paint_state_stack, &cache, &raster_time, &ui_time);
auto& preroll_context = preroll_context_holder.preroll_context;
auto& paint_context = paint_context_holder.paint_context;
DisplayListRasterCacheItem display_list_item_1(display_list_1, SkPoint(),
true, false);
DisplayListRasterCacheItem display_list_item_2(display_list_2, SkPoint(),
true, false);
cache.BeginFrame();
RasterCacheItemPreroll(display_list_item_1, preroll_context, matrix);
RasterCacheItemPreroll(display_list_item_2, preroll_context, matrix);
cache.EvictUnusedCacheEntries();
ASSERT_EQ(cache.EstimatePictureCacheByteSize(), 0u);
ASSERT_FALSE(
RasterCacheItemTryToRasterCache(display_list_item_1, paint_context));
ASSERT_FALSE(
RasterCacheItemTryToRasterCache(display_list_item_2, paint_context));
ASSERT_EQ(cache.EstimatePictureCacheByteSize(), 0u);
ASSERT_FALSE(display_list_item_1.Draw(paint_context, &dummy_canvas, &paint));
ASSERT_FALSE(display_list_item_2.Draw(paint_context, &dummy_canvas, &paint));
cache.EndFrame();
ASSERT_EQ(cache.EstimatePictureCacheByteSize(), 0u);
ASSERT_EQ(cache.picture_metrics().total_count(), 0u);
ASSERT_EQ(cache.picture_metrics().total_bytes(), 0u);
cache.BeginFrame();
RasterCacheItemPreroll(display_list_item_1, preroll_context, matrix);
RasterCacheItemPreroll(display_list_item_2, preroll_context, matrix);
cache.EvictUnusedCacheEntries();
ASSERT_EQ(cache.EstimatePictureCacheByteSize(), 0u);
ASSERT_TRUE(
RasterCacheItemTryToRasterCache(display_list_item_1, paint_context));
ASSERT_TRUE(
RasterCacheItemTryToRasterCache(display_list_item_2, paint_context));
ASSERT_EQ(cache.EstimatePictureCacheByteSize(), 51248u);
ASSERT_TRUE(display_list_item_1.Draw(paint_context, &dummy_canvas, &paint));
ASSERT_TRUE(display_list_item_2.Draw(paint_context, &dummy_canvas, &paint));
cache.EndFrame();
ASSERT_EQ(cache.EstimatePictureCacheByteSize(), 51248u);
ASSERT_EQ(cache.picture_metrics().total_count(), 2u);
ASSERT_EQ(cache.picture_metrics().total_bytes(), 51248u);
cache.BeginFrame();
RasterCacheItemPreroll(display_list_item_1, preroll_context, matrix);
cache.EvictUnusedCacheEntries();
ASSERT_EQ(cache.EstimatePictureCacheByteSize(), 25624u);
ASSERT_TRUE(
RasterCacheItemTryToRasterCache(display_list_item_1, paint_context));
ASSERT_EQ(cache.EstimatePictureCacheByteSize(), 25624u);
ASSERT_TRUE(display_list_item_1.Draw(paint_context, &dummy_canvas, &paint));
cache.EndFrame();
ASSERT_EQ(cache.EstimatePictureCacheByteSize(), 25624u);
ASSERT_EQ(cache.picture_metrics().total_count(), 1u);
ASSERT_EQ(cache.picture_metrics().total_bytes(), 25624u);
cache.BeginFrame();
cache.EvictUnusedCacheEntries();
ASSERT_EQ(cache.EstimatePictureCacheByteSize(), 0u);
cache.EndFrame();
ASSERT_EQ(cache.EstimatePictureCacheByteSize(), 0u);
ASSERT_EQ(cache.picture_metrics().total_count(), 0u);
ASSERT_EQ(cache.picture_metrics().total_bytes(), 0u);
cache.BeginFrame();
ASSERT_FALSE(
cache.Draw(display_list_item_1.GetId().value(), dummy_canvas, &paint));
ASSERT_FALSE(display_list_item_1.Draw(paint_context, &dummy_canvas, &paint));
ASSERT_FALSE(
cache.Draw(display_list_item_2.GetId().value(), dummy_canvas, &paint));
ASSERT_FALSE(display_list_item_2.Draw(paint_context, &dummy_canvas, &paint));
cache.EndFrame();
}
TEST(RasterCache, ComputeDeviceRectBasedOnFractionalTranslation) {
SkRect logical_rect = SkRect::MakeLTRB(0, 0, 300.2, 300.3);
SkMatrix ctm = SkMatrix::MakeAll(2.0, 0, 0, 0, 2.0, 0, 0, 0, 1);
auto result = RasterCacheUtil::GetDeviceBounds(logical_rect, ctm);
ASSERT_EQ(result, SkRect::MakeLTRB(0.0, 0.0, 600.4, 600.6));
}
// Construct a cache result whose device target rectangle rounds out to be one
// pixel wider than the cached image. Verify that it can be drawn without
// triggering any assertions.
TEST(RasterCache, DeviceRectRoundOutForDisplayList) {
size_t threshold = 1;
flutter::RasterCache cache(threshold);
SkRect logical_rect = SkRect::MakeLTRB(28, 0, 354.56731, 310.288);
DisplayListBuilder builder(logical_rect);
builder.DrawRect(logical_rect, DlPaint(DlColor::kRed()));
sk_sp<DisplayList> display_list = builder.Build();
SkMatrix ctm = SkMatrix::MakeAll(1.3312, 0, 233, 0, 1.3312, 206, 0, 0, 1);
DlPaint paint;
MockCanvas canvas(1000, 1000);
canvas.SetTransform(ctm);
LayerStateStack preroll_state_stack;
preroll_state_stack.set_preroll_delegate(kGiantRect, ctm);
LayerStateStack paint_state_stack;
preroll_state_stack.set_delegate(&canvas);
FixedRefreshRateStopwatch raster_time;
FixedRefreshRateStopwatch ui_time;
PrerollContextHolder preroll_context_holder = GetSamplePrerollContextHolder(
preroll_state_stack, &cache, &raster_time, &ui_time);
PaintContextHolder paint_context_holder = GetSamplePaintContextHolder(
paint_state_stack, &cache, &raster_time, &ui_time);
auto& preroll_context = preroll_context_holder.preroll_context;
auto& paint_context = paint_context_holder.paint_context;
cache.BeginFrame();
DisplayListRasterCacheItem display_list_item(display_list, SkPoint(), true,
false);
ASSERT_FALSE(RasterCacheItemPrerollAndTryToRasterCache(
display_list_item, preroll_context, paint_context, ctm));
ASSERT_FALSE(display_list_item.Draw(paint_context, &canvas, &paint));
cache.EndFrame();
cache.BeginFrame();
ASSERT_TRUE(RasterCacheItemPrerollAndTryToRasterCache(
display_list_item, preroll_context, paint_context, ctm));
ASSERT_TRUE(display_list_item.Draw(paint_context, &canvas, &paint));
canvas.Translate(248, 0);
ASSERT_TRUE(cache.Draw(display_list_item.GetId().value(), canvas, &paint));
ASSERT_TRUE(display_list_item.Draw(paint_context, &canvas, &paint));
}
TEST(RasterCache, NestedOpCountMetricUsedForDisplayList) {
size_t threshold = 1;
flutter::RasterCache cache(threshold);
SkMatrix matrix = SkMatrix::I();
auto display_list = GetSampleNestedDisplayList();
ASSERT_EQ(display_list->op_count(), 1u);
ASSERT_EQ(display_list->op_count(true), 36u);
MockCanvas dummy_canvas(1000, 1000);
DlPaint paint;
LayerStateStack preroll_state_stack;
preroll_state_stack.set_preroll_delegate(kGiantRect, matrix);
LayerStateStack paint_state_stack;
preroll_state_stack.set_delegate(&dummy_canvas);
FixedRefreshRateStopwatch raster_time;
FixedRefreshRateStopwatch ui_time;
PrerollContextHolder preroll_context_holder = GetSamplePrerollContextHolder(
preroll_state_stack, &cache, &raster_time, &ui_time);
PaintContextHolder paint_context_holder = GetSamplePaintContextHolder(
paint_state_stack, &cache, &raster_time, &ui_time);
auto& preroll_context = preroll_context_holder.preroll_context;
auto& paint_context = paint_context_holder.paint_context;
cache.BeginFrame();
DisplayListRasterCacheItem display_list_item(display_list, SkPoint(), false,
false);
ASSERT_FALSE(RasterCacheItemPrerollAndTryToRasterCache(
display_list_item, preroll_context, paint_context, matrix));
ASSERT_FALSE(display_list_item.Draw(paint_context, &dummy_canvas, &paint));
cache.EndFrame();
cache.BeginFrame();
ASSERT_TRUE(RasterCacheItemPrerollAndTryToRasterCache(
display_list_item, preroll_context, paint_context, matrix));
ASSERT_TRUE(display_list_item.Draw(paint_context, &dummy_canvas, &paint));
}
TEST(RasterCache, NaiveComplexityScoringDisplayList) {
DisplayListComplexityCalculator* calculator =
DisplayListNaiveComplexityCalculator::GetInstance();
size_t threshold = 1;
flutter::RasterCache cache(threshold);
SkMatrix matrix = SkMatrix::I();
// Five raster ops will not be cached
auto display_list = GetSampleDisplayList(5);
unsigned int complexity_score = calculator->Compute(display_list.get());
ASSERT_EQ(complexity_score, 5u);
ASSERT_EQ(display_list->op_count(), 5u);
ASSERT_FALSE(calculator->ShouldBeCached(complexity_score));
MockCanvas dummy_canvas(1000, 1000);
DlPaint paint;
LayerStateStack preroll_state_stack;
preroll_state_stack.set_preroll_delegate(kGiantRect, matrix);
LayerStateStack paint_state_stack;
preroll_state_stack.set_delegate(&dummy_canvas);
FixedRefreshRateStopwatch raster_time;
FixedRefreshRateStopwatch ui_time;
PrerollContextHolder preroll_context_holder = GetSamplePrerollContextHolder(
preroll_state_stack, &cache, &raster_time, &ui_time);
PaintContextHolder paint_context_holder = GetSamplePaintContextHolder(
paint_state_stack, &cache, &raster_time, &ui_time);
auto& preroll_context = preroll_context_holder.preroll_context;
auto& paint_context = paint_context_holder.paint_context;
cache.BeginFrame();
DisplayListRasterCacheItem display_list_item(display_list, SkPoint(), false,
false);
ASSERT_FALSE(RasterCacheItemPrerollAndTryToRasterCache(
display_list_item, preroll_context, paint_context, matrix));
ASSERT_FALSE(display_list_item.Draw(paint_context, &dummy_canvas, &paint));
cache.EndFrame();
cache.BeginFrame();
ASSERT_FALSE(RasterCacheItemPrerollAndTryToRasterCache(
display_list_item, preroll_context, paint_context, matrix));
ASSERT_FALSE(display_list_item.Draw(paint_context, &dummy_canvas, &paint));
// Six raster ops should be cached
display_list = GetSampleDisplayList(6);
complexity_score = calculator->Compute(display_list.get());
ASSERT_EQ(complexity_score, 6u);
ASSERT_EQ(display_list->op_count(), 6u);
ASSERT_TRUE(calculator->ShouldBeCached(complexity_score));
DisplayListRasterCacheItem display_list_item_2 =
DisplayListRasterCacheItem(display_list, SkPoint(), false, false);
cache.BeginFrame();
ASSERT_FALSE(RasterCacheItemPrerollAndTryToRasterCache(
display_list_item_2, preroll_context, paint_context, matrix));
ASSERT_FALSE(display_list_item_2.Draw(paint_context, &dummy_canvas, &paint));
cache.EndFrame();
cache.BeginFrame();
ASSERT_TRUE(RasterCacheItemPrerollAndTryToRasterCache(
display_list_item_2, preroll_context, paint_context, matrix));
ASSERT_TRUE(display_list_item_2.Draw(paint_context, &dummy_canvas, &paint));
}
TEST(RasterCache, DisplayListWithSingularMatrixIsNotCached) {
size_t threshold = 2;
flutter::RasterCache cache(threshold);
SkMatrix matrices[] = {
SkMatrix::Scale(0, 1),
SkMatrix::Scale(1, 0),
SkMatrix::Skew(1, 1),
};
int matrix_count = sizeof(matrices) / sizeof(matrices[0]);
auto display_list = GetSampleDisplayList();
MockCanvas dummy_canvas(1000, 1000);
DlPaint paint;
LayerStateStack preroll_state_stack;
preroll_state_stack.set_preroll_delegate(kGiantRect, SkMatrix::I());
LayerStateStack paint_state_stack;
preroll_state_stack.set_delegate(&dummy_canvas);
FixedRefreshRateStopwatch raster_time;
FixedRefreshRateStopwatch ui_time;
PrerollContextHolder preroll_context_holder = GetSamplePrerollContextHolder(
preroll_state_stack, &cache, &raster_time, &ui_time);
PaintContextHolder paint_context_holder = GetSamplePaintContextHolder(
paint_state_stack, &cache, &raster_time, &ui_time);
auto& preroll_context = preroll_context_holder.preroll_context;
auto& paint_context = paint_context_holder.paint_context;
DisplayListRasterCacheItem display_list_item(display_list, SkPoint(), true,
false);
for (int i = 0; i < 10; i++) {
cache.BeginFrame();
for (int j = 0; j < matrix_count; j++) {
display_list_item.set_matrix(matrices[j]);
ASSERT_FALSE(RasterCacheItemPrerollAndTryToRasterCache(
display_list_item, preroll_context, paint_context, matrices[j]));
}
for (int j = 0; j < matrix_count; j++) {
dummy_canvas.SetTransform(matrices[j]);
ASSERT_FALSE(
display_list_item.Draw(paint_context, &dummy_canvas, &paint));
}
cache.EndFrame();
}
}
TEST(RasterCache, PrepareLayerTransform) {
SkRect child_bounds = SkRect::MakeLTRB(10, 10, 50, 50);
SkPath child_path = SkPath().addOval(child_bounds);
auto child_layer = MockLayer::Make(child_path);
auto blur_filter =
std::make_shared<DlBlurImageFilter>(5, 5, DlTileMode::kClamp);
auto blur_layer = std::make_shared<ImageFilterLayer>(blur_filter);
SkMatrix matrix = SkMatrix::Scale(2, 2);
auto transform_layer = std::make_shared<TransformLayer>(matrix);
SkMatrix cache_matrix = SkMatrix::Translate(-20, -20);
cache_matrix.preConcat(matrix);
child_layer->set_expected_paint_matrix(cache_matrix);
blur_layer->Add(child_layer);
transform_layer->Add(blur_layer);
size_t threshold = 2;
MockRasterCache cache(threshold);
MockCanvas dummy_canvas(1000, 1000);
LayerStateStack preroll_state_stack;
preroll_state_stack.set_preroll_delegate(kGiantRect, matrix);
LayerStateStack paint_state_stack;
preroll_state_stack.set_delegate(&dummy_canvas);
FixedRefreshRateStopwatch raster_time;
FixedRefreshRateStopwatch ui_time;
std::vector<RasterCacheItem*> cache_items;
cache.BeginFrame();
auto preroll_holder = GetSamplePrerollContextHolder(
preroll_state_stack, &cache, &raster_time, &ui_time);
preroll_holder.preroll_context.raster_cached_entries = &cache_items;
transform_layer->Preroll(&preroll_holder.preroll_context);
auto paint_holder = GetSamplePaintContextHolder(paint_state_stack, &cache,
&raster_time, &ui_time);
cache.EvictUnusedCacheEntries();
LayerTree::TryToRasterCache(
*preroll_holder.preroll_context.raster_cached_entries,
&paint_holder.paint_context);
// Condition tested inside MockLayer::Paint against expected paint matrix.
}
TEST(RasterCache, RasterCacheKeyHashFunction) {
RasterCacheKey::Map<int> map;
auto hash_function = map.hash_function();
SkMatrix matrix = SkMatrix::I();
uint64_t id = 5;
RasterCacheKey layer_key(id, RasterCacheKeyType::kLayer, matrix);
RasterCacheKey display_list_key(id, RasterCacheKeyType::kDisplayList, matrix);
RasterCacheKey layer_children_key(id, RasterCacheKeyType::kLayerChildren,
matrix);
auto layer_cache_key_id = RasterCacheKeyID(id, RasterCacheKeyType::kLayer);
auto layer_hash_code = hash_function(layer_key);
ASSERT_EQ(layer_hash_code, layer_cache_key_id.GetHash());
auto display_list_cache_key_id =
RasterCacheKeyID(id, RasterCacheKeyType::kDisplayList);
auto display_list_hash_code = hash_function(display_list_key);
ASSERT_EQ(display_list_hash_code, display_list_cache_key_id.GetHash());
auto layer_children_cache_key_id =
RasterCacheKeyID(id, RasterCacheKeyType::kLayerChildren);
auto layer_children_hash_code = hash_function(layer_children_key);
ASSERT_EQ(layer_children_hash_code, layer_children_cache_key_id.GetHash());
}
TEST(RasterCache, RasterCacheKeySameID) {
RasterCacheKey::Map<int> map;
SkMatrix matrix = SkMatrix::I();
uint64_t id = 5;
RasterCacheKey layer_key(id, RasterCacheKeyType::kLayer, matrix);
RasterCacheKey display_list_key(id, RasterCacheKeyType::kDisplayList, matrix);
RasterCacheKey layer_children_key(id, RasterCacheKeyType::kLayerChildren,
matrix);
map[layer_key] = 100;
map[display_list_key] = 300;
map[layer_children_key] = 400;
ASSERT_EQ(map[layer_key], 100);
ASSERT_EQ(map[display_list_key], 300);
ASSERT_EQ(map[layer_children_key], 400);
}
TEST(RasterCache, RasterCacheKeySameType) {
RasterCacheKey::Map<int> map;
SkMatrix matrix = SkMatrix::I();
RasterCacheKeyType type = RasterCacheKeyType::kLayer;
RasterCacheKey layer_first_key(5, type, matrix);
RasterCacheKey layer_second_key(10, type, matrix);
RasterCacheKey layer_third_key(15, type, matrix);
map[layer_first_key] = 50;
map[layer_second_key] = 100;
map[layer_third_key] = 150;
ASSERT_EQ(map[layer_first_key], 50);
ASSERT_EQ(map[layer_second_key], 100);
ASSERT_EQ(map[layer_third_key], 150);
type = RasterCacheKeyType::kDisplayList;
RasterCacheKey picture_first_key(20, type, matrix);
RasterCacheKey picture_second_key(25, type, matrix);
RasterCacheKey picture_third_key(30, type, matrix);
map[picture_first_key] = 200;
map[picture_second_key] = 250;
map[picture_third_key] = 300;
ASSERT_EQ(map[picture_first_key], 200);
ASSERT_EQ(map[picture_second_key], 250);
ASSERT_EQ(map[picture_third_key], 300);
type = RasterCacheKeyType::kDisplayList;
RasterCacheKey display_list_first_key(35, type, matrix);
RasterCacheKey display_list_second_key(40, type, matrix);
RasterCacheKey display_list_third_key(45, type, matrix);
map[display_list_first_key] = 350;
map[display_list_second_key] = 400;
map[display_list_third_key] = 450;
ASSERT_EQ(map[display_list_first_key], 350);
ASSERT_EQ(map[display_list_second_key], 400);
ASSERT_EQ(map[display_list_third_key], 450);
type = RasterCacheKeyType::kLayerChildren;
RasterCacheKeyID foo = RasterCacheKeyID(10, RasterCacheKeyType::kLayer);
RasterCacheKeyID bar = RasterCacheKeyID(20, RasterCacheKeyType::kLayer);
RasterCacheKeyID baz = RasterCacheKeyID(30, RasterCacheKeyType::kLayer);
RasterCacheKey layer_children_first_key(
RasterCacheKeyID({foo, bar, baz}, type), matrix);
RasterCacheKey layer_children_second_key(
RasterCacheKeyID({foo, baz, bar}, type), matrix);
RasterCacheKey layer_children_third_key(
RasterCacheKeyID({baz, bar, foo}, type), matrix);
map[layer_children_first_key] = 100;
map[layer_children_second_key] = 200;
map[layer_children_third_key] = 300;
ASSERT_EQ(map[layer_children_first_key], 100);
ASSERT_EQ(map[layer_children_second_key], 200);
ASSERT_EQ(map[layer_children_third_key], 300);
}
TEST(RasterCache, RasterCacheKeyIDEqual) {
RasterCacheKeyID first = RasterCacheKeyID(1, RasterCacheKeyType::kLayer);
RasterCacheKeyID second = RasterCacheKeyID(2, RasterCacheKeyType::kLayer);
RasterCacheKeyID third =
RasterCacheKeyID(1, RasterCacheKeyType::kLayerChildren);
ASSERT_NE(first, second);
ASSERT_NE(first, third);
ASSERT_NE(second, third);
RasterCacheKeyID fourth =
RasterCacheKeyID({first, second}, RasterCacheKeyType::kLayer);
RasterCacheKeyID fifth =
RasterCacheKeyID({first, second}, RasterCacheKeyType::kLayerChildren);
RasterCacheKeyID sixth =
RasterCacheKeyID({second, first}, RasterCacheKeyType::kLayerChildren);
ASSERT_NE(fourth, fifth);
ASSERT_NE(fifth, sixth);
}
TEST(RasterCache, RasterCacheKeyIDHashCode) {
uint64_t foo = 1;
uint64_t bar = 2;
RasterCacheKeyID first = RasterCacheKeyID(foo, RasterCacheKeyType::kLayer);
RasterCacheKeyID second = RasterCacheKeyID(bar, RasterCacheKeyType::kLayer);
std::size_t first_hash = first.GetHash();
std::size_t second_hash = second.GetHash();
ASSERT_EQ(first_hash, fml::HashCombine(foo, RasterCacheKeyType::kLayer));
ASSERT_EQ(second_hash, fml::HashCombine(bar, RasterCacheKeyType::kLayer));
RasterCacheKeyID third =
RasterCacheKeyID({first, second}, RasterCacheKeyType::kLayerChildren);
RasterCacheKeyID fourth =
RasterCacheKeyID({second, first}, RasterCacheKeyType::kLayerChildren);
std::size_t third_hash = third.GetHash();
std::size_t fourth_hash = fourth.GetHash();
ASSERT_EQ(third_hash, fml::HashCombine(RasterCacheKeyID::kDefaultUniqueID,
RasterCacheKeyType::kLayerChildren,
first.GetHash(), second.GetHash()));
ASSERT_EQ(fourth_hash, fml::HashCombine(RasterCacheKeyID::kDefaultUniqueID,
RasterCacheKeyType::kLayerChildren,
second.GetHash(), first.GetHash()));
// Verify that the cached hash code is correct.
ASSERT_EQ(first_hash, first.GetHash());
ASSERT_EQ(second_hash, second.GetHash());
ASSERT_EQ(third_hash, third.GetHash());
ASSERT_EQ(fourth_hash, fourth.GetHash());
}
using RasterCacheTest = LayerTest;
TEST_F(RasterCacheTest, RasterCacheKeyIDLayerChildrenIds) {
auto layer = std::make_shared<ContainerLayer>();
const SkPath child_path = SkPath().addRect(SkRect::MakeWH(5.0f, 5.0f));
auto mock_layer = std::make_shared<MockLayer>(child_path);
layer->Add(mock_layer);
auto display_list = GetSampleDisplayList();
auto display_list_layer = std::make_shared<DisplayListLayer>(
SkPoint::Make(0.0f, 0.0f), display_list, false, false);
layer->Add(display_list_layer);
auto ids = RasterCacheKeyID::LayerChildrenIds(layer.get()).value();
std::vector<RasterCacheKeyID> expected_ids;
expected_ids.emplace_back(
RasterCacheKeyID(mock_layer->unique_id(), RasterCacheKeyType::kLayer));
expected_ids.emplace_back(RasterCacheKeyID(display_list->unique_id(),
RasterCacheKeyType::kDisplayList));
ASSERT_EQ(expected_ids[0], mock_layer->caching_key_id());
ASSERT_EQ(expected_ids[1], display_list_layer->caching_key_id());
ASSERT_EQ(ids, expected_ids);
}
TEST(RasterCacheUtilsTest, SkMatrixIntegralTransCTM) {
#define EXPECT_EQ_WITH_TRANSLATE(test, expected, expected_tx, expected_ty) \
do { \
EXPECT_EQ(test[SkMatrix::kMScaleX], expected[SkMatrix::kMScaleX]); \
EXPECT_EQ(test[SkMatrix::kMSkewX], expected[SkMatrix::kMSkewX]); \
EXPECT_EQ(test[SkMatrix::kMScaleY], expected[SkMatrix::kMScaleY]); \
EXPECT_EQ(test[SkMatrix::kMSkewY], expected[SkMatrix::kMSkewY]); \
EXPECT_EQ(test[SkMatrix::kMSkewX], expected[SkMatrix::kMSkewX]); \
EXPECT_EQ(test[SkMatrix::kMPersp0], expected[SkMatrix::kMPersp0]); \
EXPECT_EQ(test[SkMatrix::kMPersp1], expected[SkMatrix::kMPersp1]); \
EXPECT_EQ(test[SkMatrix::kMPersp2], expected[SkMatrix::kMPersp2]); \
EXPECT_EQ(test[SkMatrix::kMTransX], expected_tx); \
EXPECT_EQ(test[SkMatrix::kMTransY], expected_ty); \
} while (0)
#define EXPECT_NON_INTEGER_TRANSLATION(matrix) \
EXPECT_TRUE(SkScalarFraction(matrix[SkMatrix::kMTransX]) != 0.0f || \
SkScalarFraction(matrix[SkMatrix::kMTransY]) != 0.0f)
{
// Identity
SkMatrix matrix = SkMatrix::I();
SkMatrix get = RasterCacheUtil::GetIntegralTransCTM(matrix);
SkMatrix compute;
EXPECT_FALSE(RasterCacheUtil::ComputeIntegralTransCTM(matrix, &compute));
EXPECT_EQ(get, matrix);
}
{
// Integer translate
SkMatrix matrix = SkMatrix::Translate(10.0f, 12.0f);
SkMatrix get = RasterCacheUtil::GetIntegralTransCTM(matrix);
SkMatrix compute;
EXPECT_FALSE(RasterCacheUtil::ComputeIntegralTransCTM(matrix, &compute));
EXPECT_EQ(get, matrix);
}
{
// Fractional x translate
SkMatrix matrix = SkMatrix::Translate(10.2f, 12.0f);
EXPECT_NON_INTEGER_TRANSLATION(matrix);
SkMatrix get = RasterCacheUtil::GetIntegralTransCTM(matrix);
SkMatrix compute;
EXPECT_TRUE(RasterCacheUtil::ComputeIntegralTransCTM(matrix, &compute));
EXPECT_EQ_WITH_TRANSLATE(get, matrix, 10.0f, 12.0f);
EXPECT_EQ(get, compute);
}
{
// Fractional y translate
SkMatrix matrix = SkMatrix::Translate(10.0f, 12.3f);
EXPECT_NON_INTEGER_TRANSLATION(matrix);
SkMatrix get = RasterCacheUtil::GetIntegralTransCTM(matrix);
SkMatrix compute;
EXPECT_TRUE(RasterCacheUtil::ComputeIntegralTransCTM(matrix, &compute));
EXPECT_EQ_WITH_TRANSLATE(get, matrix, 10.0f, 12.0f);
EXPECT_EQ(get, compute);
}
{
// Fractional x & y translate
SkMatrix matrix = SkMatrix::Translate(10.7f, 12.3f);
EXPECT_NON_INTEGER_TRANSLATION(matrix);
SkMatrix get = RasterCacheUtil::GetIntegralTransCTM(matrix);
SkMatrix compute;
EXPECT_TRUE(RasterCacheUtil::ComputeIntegralTransCTM(matrix, &compute));
EXPECT_EQ_WITH_TRANSLATE(get, matrix, 11.0f, 12.0f);
EXPECT_EQ(get, compute);
}
{
// Scale
SkMatrix matrix = SkMatrix::Scale(2.0f, 3.0f);
SkMatrix get = RasterCacheUtil::GetIntegralTransCTM(matrix);
SkMatrix compute;
EXPECT_FALSE(RasterCacheUtil::ComputeIntegralTransCTM(matrix, &compute));
EXPECT_EQ(get, matrix);
}
{
// Scale, Integer translate
SkMatrix matrix = SkMatrix::Scale(2.0f, 3.0f);
matrix.preTranslate(10.0f, 12.0f);
SkMatrix get = RasterCacheUtil::GetIntegralTransCTM(matrix);
SkMatrix compute;
EXPECT_FALSE(RasterCacheUtil::ComputeIntegralTransCTM(matrix, &compute));
EXPECT_EQ(get, matrix);
}
{
// Scale, Fractional translate
SkMatrix matrix = SkMatrix::Scale(2.0f, 3.0f);
matrix.preTranslate(10.7f, 12.1f);
EXPECT_NON_INTEGER_TRANSLATION(matrix);
SkMatrix get = RasterCacheUtil::GetIntegralTransCTM(matrix);
SkMatrix compute;
EXPECT_TRUE(RasterCacheUtil::ComputeIntegralTransCTM(matrix, &compute));
EXPECT_EQ_WITH_TRANSLATE(get, matrix, 21.0f, 36.0f);
EXPECT_EQ(get, compute);
}
{
// Skew
SkMatrix matrix = SkMatrix::Skew(0.5f, 0.1f);
SkMatrix get = RasterCacheUtil::GetIntegralTransCTM(matrix);
SkMatrix compute;
EXPECT_FALSE(RasterCacheUtil::ComputeIntegralTransCTM(matrix, &compute));
EXPECT_EQ(get, matrix);
}
{
// Skew, Fractional translate - should be NOP
SkMatrix matrix = SkMatrix::Skew(0.5f, 0.1f);
matrix.preTranslate(10.7f, 12.1f);
EXPECT_NON_INTEGER_TRANSLATION(matrix);
SkMatrix get = RasterCacheUtil::GetIntegralTransCTM(matrix);
SkMatrix compute;
EXPECT_FALSE(RasterCacheUtil::ComputeIntegralTransCTM(matrix, &compute));
EXPECT_EQ(get, matrix);
}
{
// Rotate
SkMatrix matrix = SkMatrix::RotateDeg(45);
SkMatrix get = RasterCacheUtil::GetIntegralTransCTM(matrix);
SkMatrix compute;
EXPECT_FALSE(RasterCacheUtil::ComputeIntegralTransCTM(matrix, &compute));
EXPECT_EQ(get, matrix);
}
{
// Rotate, Fractional Translate - should be NOP
SkMatrix matrix = SkMatrix::RotateDeg(45);
matrix.preTranslate(10.7f, 12.1f);
EXPECT_NON_INTEGER_TRANSLATION(matrix);
SkMatrix get = RasterCacheUtil::GetIntegralTransCTM(matrix);
SkMatrix compute;
EXPECT_FALSE(RasterCacheUtil::ComputeIntegralTransCTM(matrix, &compute));
EXPECT_EQ(get, matrix);
}
{
// Perspective x
SkMatrix matrix = SkMatrix::I();
matrix.setPerspX(0.1);
SkMatrix get = RasterCacheUtil::GetIntegralTransCTM(matrix);
SkMatrix compute;
EXPECT_FALSE(RasterCacheUtil::ComputeIntegralTransCTM(matrix, &compute));
EXPECT_EQ(get, matrix);
}
{
// Perspective x, Fractional Translate - should be NOP
SkMatrix matrix = SkMatrix::I();
matrix.setPerspX(0.1);
matrix.preTranslate(10.7f, 12.1f);
EXPECT_NON_INTEGER_TRANSLATION(matrix);
SkMatrix get = RasterCacheUtil::GetIntegralTransCTM(matrix);
SkMatrix compute;
EXPECT_FALSE(RasterCacheUtil::ComputeIntegralTransCTM(matrix, &compute));
EXPECT_EQ(get, matrix);
}
{
// Perspective y
SkMatrix matrix = SkMatrix::I();
matrix.setPerspY(0.1);
SkMatrix get = RasterCacheUtil::GetIntegralTransCTM(matrix);
SkMatrix compute;
EXPECT_FALSE(RasterCacheUtil::ComputeIntegralTransCTM(matrix, &compute));
EXPECT_EQ(get, matrix);
}
{
// Perspective y, Fractional Translate - should be NOP
SkMatrix matrix = SkMatrix::I();
matrix.setPerspY(0.1);
matrix.preTranslate(10.7f, 12.1f);
EXPECT_NON_INTEGER_TRANSLATION(matrix);
SkMatrix get = RasterCacheUtil::GetIntegralTransCTM(matrix);
SkMatrix compute;
EXPECT_FALSE(RasterCacheUtil::ComputeIntegralTransCTM(matrix, &compute));
EXPECT_EQ(get, matrix);
}
{
// Perspective weight
// clang-format off
SkMatrix matrix = SkMatrix::MakeAll(
1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.9f);
// clang-format on
SkMatrix get = RasterCacheUtil::GetIntegralTransCTM(matrix);
SkMatrix compute;
EXPECT_FALSE(RasterCacheUtil::ComputeIntegralTransCTM(matrix, &compute));
EXPECT_EQ(get, matrix);
}
{
// Perspective weight, Fractional Translate - should be NOP
// clang-format off
SkMatrix matrix = SkMatrix::MakeAll(
1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.9f);
// clang-format on
matrix.preTranslate(10.7f, 12.1f);
EXPECT_NON_INTEGER_TRANSLATION(matrix);
SkMatrix get = RasterCacheUtil::GetIntegralTransCTM(matrix);
SkMatrix compute;
EXPECT_FALSE(RasterCacheUtil::ComputeIntegralTransCTM(matrix, &compute));
EXPECT_EQ(get, matrix);
}
#undef EXPECT_NON_INTEGER_TRANSLATION
#undef EXPECT_EQ_WITH_TRANSLATE
}
TEST(RasterCacheUtilsTest, SkM44IntegralTransCTM) {
#define EXPECT_EQ_WITH_TRANSLATE(test, expected, tx, ty, label) \
do { \
EXPECT_EQ(test.rc(0, 0), expected.rc(0, 0)) << label; \
EXPECT_EQ(test.rc(0, 1), expected.rc(0, 1)) << label; \
EXPECT_EQ(test.rc(0, 2), expected.rc(0, 2)) << label; \
EXPECT_EQ(test.rc(0, 3), tx) << label; \
EXPECT_EQ(test.rc(1, 0), expected.rc(1, 0)) << label; \
EXPECT_EQ(test.rc(1, 1), expected.rc(1, 1)) << label; \
EXPECT_EQ(test.rc(1, 2), expected.rc(1, 2)) << label; \
EXPECT_EQ(test.rc(1, 3), ty) << label; \
EXPECT_EQ(test.rc(2, 0), expected.rc(2, 0)) << label; \
EXPECT_EQ(test.rc(2, 1), expected.rc(2, 1)) << label; \
EXPECT_EQ(test.rc(2, 2), expected.rc(2, 2)) << label; \
EXPECT_EQ(test.rc(2, 3), expected.rc(2, 3)) << label; \
EXPECT_EQ(test.rc(3, 0), expected.rc(3, 0)) << label; \
EXPECT_EQ(test.rc(3, 1), expected.rc(3, 1)) << label; \
EXPECT_EQ(test.rc(3, 2), expected.rc(3, 2)) << label; \
EXPECT_EQ(test.rc(3, 3), expected.rc(3, 3)) << label; \
} while (0)
#define EXPECT_NON_INTEGER_TRANSLATION(matrix) \
EXPECT_TRUE(SkScalarFraction(matrix.rc(0, 3)) != 0.0f || \
SkScalarFraction(matrix.rc(1, 3)) != 0.0f)
for (int r = 0; r < 4; r++) {
for (int c = 0; c < 4; c++) {
bool snaps;
switch (r) {
case 0: // X equation
if (c == 3) {
continue; // TranslateX, the value we are testing, skip
}
snaps = (c == 0); // X Scale value yes, Skew by Y or Z no
break;
case 1: // Y equation
if (c == 3) {
continue; // TranslateY, the value we are testing, skip
}
snaps = (c == 1); // Y Scale value yes, Skew by X or Z no
break;
case 2: // Z equation, ignored, will snap
snaps = true;
break;
case 3: // W equation, modifications prevent snapping
snaps = false;
break;
default:
FML_UNREACHABLE();
}
auto label = std::to_string(r) + ", " + std::to_string(c);
SkM44 matrix = SkM44::Translate(10.7f, 12.1f);
EXPECT_NON_INTEGER_TRANSLATION(matrix) << label;
matrix.setRC(r, c, 0.5f);
if (snaps) {
SkM44 compute;
SkM44 get = RasterCacheUtil::GetIntegralTransCTM(matrix);
EXPECT_TRUE(RasterCacheUtil::ComputeIntegralTransCTM(matrix, &compute))
<< label;
EXPECT_EQ_WITH_TRANSLATE(get, matrix, 11.0f, 12.0f, label);
EXPECT_EQ(get, compute) << label;
} else {
SkM44 compute;
SkM44 get = RasterCacheUtil::GetIntegralTransCTM(matrix);
EXPECT_FALSE(RasterCacheUtil::ComputeIntegralTransCTM(matrix, &compute))
<< label;
EXPECT_EQ(get, matrix) << label;
}
}
}
#undef EXPECT_NON_INTEGER_TRANSLATION
#undef EXPECT_EQ_WITH_TRANSLATE
}
} // namespace testing
} // namespace flutter
// NOLINTEND(bugprone-unchecked-optional-access)
| engine/flow/raster_cache_unittests.cc/0 | {
"file_path": "engine/flow/raster_cache_unittests.cc",
"repo_id": "engine",
"token_count": 17094
} | 161 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FLOW_SURFACE_FRAME_H_
#define FLUTTER_FLOW_SURFACE_FRAME_H_
#include <memory>
#include <optional>
#include "flutter/common/graphics/gl_context_switch.h"
#include "flutter/display_list/dl_builder.h"
#include "flutter/display_list/skia/dl_sk_canvas.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/time/time_point.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkSurface.h"
namespace flutter {
// This class represents a frame that has been fully configured for the
// underlying client rendering API. A frame may only be submitted once.
class SurfaceFrame {
public:
using SubmitCallback =
std::function<bool(SurfaceFrame& surface_frame, DlCanvas* canvas)>;
// Information about the underlying framebuffer
struct FramebufferInfo {
// Indicates whether or not the surface supports pixel readback as used in
// circumstances such as a BackdropFilter.
bool supports_readback = false;
// Indicates that target device supports partial repaint. At very minimum
// this means that the surface will provide valid existing damage.
bool supports_partial_repaint = false;
// For some targets it may be beneficial or even required to snap clip
// rect to tile grid. I.e. repainting part of a tile may cause performance
// degradation if the tile needs to be decompressed first.
int vertical_clip_alignment = 1;
int horizontal_clip_alignment = 1;
// This is the area of framebuffer that lags behind the front buffer.
//
// Correctly providing exiting_damage is necessary for supporting double and
// triple buffering. Embedder is responsible for tracking this area for each
// of the back buffers used. When doing partial redraw, this area will be
// repainted alongside of dirty area determined by diffing current and
// last successfully rasterized layer tree;
//
// If existing damage is unspecified (nullopt), entire frame will be
// rasterized (no partial redraw). To signal that there is no existing
// damage use an empty SkIRect.
std::optional<SkIRect> existing_damage = std::nullopt;
};
SurfaceFrame(sk_sp<SkSurface> surface,
FramebufferInfo framebuffer_info,
const SubmitCallback& submit_callback,
SkISize frame_size,
std::unique_ptr<GLContextResult> context_result = nullptr,
bool display_list_fallback = false);
struct SubmitInfo {
// The frame damage for frame n is the difference between frame n and
// frame (n-1), and represents the area that a compositor must recompose.
//
// Corresponds to EGL_KHR_swap_buffers_with_damage
std::optional<SkIRect> frame_damage;
// The buffer damage for a frame is the area changed since that same buffer
// was last used. If the buffer has not been used before, the buffer damage
// is the entire area of the buffer.
//
// Corresponds to EGL_KHR_partial_update
std::optional<SkIRect> buffer_damage;
// Time at which this frame is scheduled to be presented. This is a hint
// that can be passed to the platform to drop queued frames.
std::optional<fml::TimePoint> presentation_time;
};
bool Submit();
bool IsSubmitted() const;
sk_sp<SkSurface> SkiaSurface() const;
DlCanvas* Canvas();
const FramebufferInfo& framebuffer_info() const { return framebuffer_info_; }
void set_submit_info(const SubmitInfo& submit_info) {
submit_info_ = submit_info;
}
const SubmitInfo& submit_info() const { return submit_info_; }
sk_sp<DisplayList> BuildDisplayList();
private:
bool submitted_ = false;
DlSkCanvasAdapter adapter_;
sk_sp<DisplayListBuilder> dl_builder_;
sk_sp<SkSurface> surface_;
DlCanvas* canvas_ = nullptr;
FramebufferInfo framebuffer_info_;
SubmitInfo submit_info_;
SubmitCallback submit_callback_;
std::unique_ptr<GLContextResult> context_result_;
bool PerformSubmit();
FML_DISALLOW_COPY_AND_ASSIGN(SurfaceFrame);
};
} // namespace flutter
#endif // FLUTTER_FLOW_SURFACE_FRAME_H_
| engine/flow/surface_frame.h/0 | {
"file_path": "engine/flow/surface_frame.h",
"repo_id": "engine",
"token_count": 1376
} | 162 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/flow/testing/mock_texture.h"
#include "flutter/display_list/dl_builder.h"
#include "flutter/testing/display_list_testing.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
TEST(MockTextureTest, Callbacks) {
auto texture = std::make_shared<MockTexture>(0);
ASSERT_FALSE(texture->gr_context_created());
texture->OnGrContextCreated();
ASSERT_TRUE(texture->gr_context_created());
ASSERT_FALSE(texture->gr_context_destroyed());
texture->OnGrContextDestroyed();
ASSERT_TRUE(texture->gr_context_destroyed());
ASSERT_FALSE(texture->unregistered());
texture->OnTextureUnregistered();
ASSERT_TRUE(texture->unregistered());
}
TEST(MockTextureTest, PaintCalls) {
DisplayListBuilder builder;
const SkRect paint_bounds1 = SkRect::MakeWH(1.0f, 1.0f);
const SkRect paint_bounds2 = SkRect::MakeWH(2.0f, 2.0f);
const DlImageSampling sampling = DlImageSampling::kNearestNeighbor;
const auto texture_image = MockTexture::MakeTestTexture(20, 20, 5);
auto texture = std::make_shared<MockTexture>(0, texture_image);
Texture::PaintContext context{
.canvas = &builder,
};
texture->Paint(context, paint_bounds1, false, sampling);
texture->Paint(context, paint_bounds2, true, sampling);
SkRect src1 = SkRect::Make(texture_image->bounds());
SkRect src2 = src1.makeInset(1.0, 1.0f);
DisplayListBuilder expected_builder;
expected_builder.DrawImageRect(texture_image, src1, paint_bounds1, sampling);
expected_builder.DrawImageRect(texture_image, src2, paint_bounds2, sampling);
EXPECT_TRUE(
DisplayListsEQ_Verbose(builder.Build(), expected_builder.Build()));
}
TEST(MockTextureTest, PaintCallsWithLinearSampling) {
DisplayListBuilder builder;
const SkRect paint_bounds1 = SkRect::MakeWH(1.0f, 1.0f);
const SkRect paint_bounds2 = SkRect::MakeWH(2.0f, 2.0f);
const auto sampling = DlImageSampling::kLinear;
const auto texture_image = MockTexture::MakeTestTexture(20, 20, 5);
auto texture = std::make_shared<MockTexture>(0, texture_image);
Texture::PaintContext context{
.canvas = &builder,
};
texture->Paint(context, paint_bounds1, false, sampling);
texture->Paint(context, paint_bounds2, true, sampling);
SkRect src1 = SkRect::Make(texture_image->bounds());
SkRect src2 = src1.makeInset(1.0, 1.0f);
DisplayListBuilder expected_builder;
expected_builder.DrawImageRect(texture_image, src1, paint_bounds1, sampling);
expected_builder.DrawImageRect(texture_image, src2, paint_bounds2, sampling);
EXPECT_TRUE(
DisplayListsEQ_Verbose(builder.Build(), expected_builder.Build()));
}
} // namespace testing
} // namespace flutter
| engine/flow/testing/mock_texture_unittests.cc/0 | {
"file_path": "engine/flow/testing/mock_texture_unittests.cc",
"repo_id": "engine",
"token_count": 967
} | 163 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/fml/ascii_trie.h"
#include "flutter/fml/logging.h"
namespace fml {
typedef AsciiTrie::TrieNode TrieNode;
typedef AsciiTrie::TrieNodePtr TrieNodePtr;
namespace {
void Add(TrieNodePtr* trie, const char* entry) {
int ch = entry[0];
FML_DCHECK(ch < AsciiTrie::kMaxAsciiValue);
if (ch != 0) {
if (!*trie) {
*trie = std::make_unique<TrieNode>();
}
Add(&(*trie)->children[ch], entry + 1);
}
}
TrieNodePtr MakeTrie(const std::vector<std::string>& entries) {
TrieNodePtr result;
for (const std::string& entry : entries) {
Add(&result, entry.c_str());
}
return result;
}
} // namespace
void AsciiTrie::Fill(const std::vector<std::string>& entries) {
node_ = MakeTrie(entries);
}
bool AsciiTrie::Query(TrieNode* trie, const char* query) {
FML_DCHECK(trie);
const char* char_position = query;
TrieNode* trie_position = trie;
TrieNode* child = nullptr;
int ch;
while ((ch = *char_position) && (child = trie_position->children[ch].get())) {
char_position++;
trie_position = child;
}
return !child && trie_position != trie;
}
} // namespace fml
| engine/fml/ascii_trie.cc/0 | {
"file_path": "engine/fml/ascii_trie.cc",
"repo_id": "engine",
"token_count": 502
} | 164 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FML_COMPILER_SPECIFIC_H_
#define FLUTTER_FML_COMPILER_SPECIFIC_H_
#if !defined(__GNUC__) && !defined(__clang__) && !defined(_MSC_VER)
#error Unsupported compiler.
#endif
// Annotate a variable indicating it's ok if the variable is not used.
// (Typically used to silence a compiler warning when the assignment
// is important for some other reason.)
// Use like:
// int x = ...;
// FML_ALLOW_UNUSED_LOCAL(x);
#define FML_ALLOW_UNUSED_LOCAL(x) false ? (void)x : (void)0
// Annotate a typedef or function indicating it's ok if it's not used.
// Use like:
// typedef Foo Bar ALLOW_UNUSED_TYPE;
#if defined(__GNUC__) || defined(__clang__)
#define FML_ALLOW_UNUSED_TYPE __attribute__((unused))
#else
#define FML_ALLOW_UNUSED_TYPE
#endif
#endif // FLUTTER_FML_COMPILER_SPECIFIC_H_
| engine/fml/compiler_specific.h/0 | {
"file_path": "engine/fml/compiler_specific.h",
"repo_id": "engine",
"token_count": 345
} | 165 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FML_FILE_H_
#define FLUTTER_FML_FILE_H_
#include <functional>
#include <initializer_list>
#include <string>
#include <vector>
#include "flutter/fml/macros.h"
#include "flutter/fml/unique_fd.h"
#ifdef ERROR
#undef ERROR
#endif
namespace fml {
class Mapping;
enum class FilePermission {
kRead,
kWrite,
kReadWrite,
};
std::string CreateTemporaryDirectory();
/// This can open a directory on POSIX, but not on Windows.
fml::UniqueFD OpenFile(const char* path,
bool create_if_necessary,
FilePermission permission);
/// This can open a directory on POSIX, but not on Windows.
fml::UniqueFD OpenFile(const fml::UniqueFD& base_directory,
const char* path,
bool create_if_necessary,
FilePermission permission);
/// Helper method that calls `OpenFile` with create_if_necessary = false
/// and permission = kRead.
///
/// This can open a directory on POSIX, but not on Windows.
fml::UniqueFD OpenFileReadOnly(const fml::UniqueFD& base_directory,
const char* path);
fml::UniqueFD OpenDirectory(const char* path,
bool create_if_necessary,
FilePermission permission);
fml::UniqueFD OpenDirectory(const fml::UniqueFD& base_directory,
const char* path,
bool create_if_necessary,
FilePermission permission);
/// Helper method that calls `OpenDirectory` with create_if_necessary = false
/// and permission = kRead.
fml::UniqueFD OpenDirectoryReadOnly(const fml::UniqueFD& base_directory,
const char* path);
fml::UniqueFD Duplicate(fml::UniqueFD::element_type descriptor);
bool IsDirectory(const fml::UniqueFD& directory);
bool IsDirectory(const fml::UniqueFD& base_directory, const char* path);
// Returns whether the given path is a file.
bool IsFile(const std::string& path);
bool TruncateFile(const fml::UniqueFD& file, size_t size);
bool FileExists(const fml::UniqueFD& base_directory, const char* path);
bool UnlinkDirectory(const char* path);
bool UnlinkDirectory(const fml::UniqueFD& base_directory, const char* path);
bool UnlinkFile(const char* path);
bool UnlinkFile(const fml::UniqueFD& base_directory, const char* path);
fml::UniqueFD CreateDirectory(const fml::UniqueFD& base_directory,
const std::vector<std::string>& components,
FilePermission permission);
bool WriteAtomically(const fml::UniqueFD& base_directory,
const char* file_name,
const Mapping& mapping);
/// Signature of a callback on a file in `directory` with `filename` (relative
/// to `directory`). The returned bool should be false if and only if further
/// traversal should be stopped. For example, a file-search visitor may return
/// false when the file is found so no more visiting is needed.
using FileVisitor = std::function<bool(const fml::UniqueFD& directory,
const std::string& filename)>;
/// Call `visitor` on all files inside the `directory` non-recursively. The
/// trivial file "." and ".." will not be visited.
///
/// Return false if and only if the visitor returns false during the
/// traversal.
///
/// If recursive visiting is needed, call `VisitFiles` inside the `visitor`, or
/// use our helper method `VisitFilesRecursively`.
///
/// @see `VisitFilesRecursively`.
/// @note Procedure doesn't copy all closures.
bool VisitFiles(const fml::UniqueFD& directory, const FileVisitor& visitor);
/// Recursively call `visitor` on all files inside the `directory`. Return false
/// if and only if the visitor returns false during the traversal.
///
/// This is a helper method that wraps the general `VisitFiles` method. The
/// `VisitFiles` is strictly more powerful as it has the access of the recursion
/// stack to the file. For example, `VisitFiles` may be able to maintain a
/// vector of directory names that lead to a file. That could be useful to
/// compute the relative path between the root directory and the visited file.
///
/// @see `VisitFiles`.
/// @note Procedure doesn't copy all closures.
bool VisitFilesRecursively(const fml::UniqueFD& directory,
const FileVisitor& visitor);
/// Helper method to recursively remove files and subdirectories inside the
/// directory. The directory itself will not be removed.
///
/// Return true if and only if all files have been successfully removed.
bool RemoveFilesInDirectory(const fml::UniqueFD& directory);
/// Helper method to recursively remove files and subdirectories inside the
/// directory. The directory itself will also be removed.
///
/// Return true if and only if all files have been successfully removed.
bool RemoveDirectoryRecursively(const fml::UniqueFD& parent,
const char* directory_name);
class ScopedTemporaryDirectory {
public:
ScopedTemporaryDirectory();
~ScopedTemporaryDirectory();
const std::string& path() const { return path_; }
const UniqueFD& fd() { return dir_fd_; }
private:
std::string path_;
UniqueFD dir_fd_;
};
} // namespace fml
#endif // FLUTTER_FML_FILE_H_
| engine/fml/file.h/0 | {
"file_path": "engine/fml/file.h",
"repo_id": "engine",
"token_count": 1915
} | 166 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FML_MACROS_H_
#define FLUTTER_FML_MACROS_H_
#ifndef FML_USED_ON_EMBEDDER
#define FML_EMBEDDER_ONLY [[deprecated]]
#else // FML_USED_ON_EMBEDDER
#define FML_EMBEDDER_ONLY
#endif // FML_USED_ON_EMBEDDER
#define FML_DISALLOW_COPY(TypeName) TypeName(const TypeName&) = delete
#define FML_DISALLOW_ASSIGN(TypeName) \
TypeName& operator=(const TypeName&) = delete
#define FML_DISALLOW_MOVE(TypeName) \
TypeName(TypeName&&) = delete; \
TypeName& operator=(TypeName&&) = delete
#define FML_DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&) = delete; \
TypeName& operator=(const TypeName&) = delete
#define FML_DISALLOW_COPY_ASSIGN_AND_MOVE(TypeName) \
TypeName(const TypeName&) = delete; \
TypeName(TypeName&&) = delete; \
TypeName& operator=(const TypeName&) = delete; \
TypeName& operator=(TypeName&&) = delete
#define FML_DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
TypeName() = delete; \
FML_DISALLOW_COPY_ASSIGN_AND_MOVE(TypeName)
#define FML_FRIEND_TEST(test_case_name, test_name) \
friend class test_case_name##_##test_name##_Test
#endif // FLUTTER_FML_MACROS_H_
| engine/fml/macros.h/0 | {
"file_path": "engine/fml/macros.h",
"repo_id": "engine",
"token_count": 581
} | 167 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// A class for checking that the current thread is/isn't the same as an initial
// thread.
#ifndef FLUTTER_FML_MEMORY_THREAD_CHECKER_H_
#define FLUTTER_FML_MEMORY_THREAD_CHECKER_H_
#include "flutter/fml/build_config.h"
#include "flutter/fml/logging.h"
#include "flutter/fml/macros.h"
#if defined(FML_OS_WIN)
#include <windows.h>
#else
#include <pthread.h>
#endif
namespace fml {
// A simple class that records the identity of the thread that it was created
// on, and at later points can tell if the current thread is the same as its
// creation thread. This class is thread-safe.
//
// Note: Unlike Chromium's |base::ThreadChecker|, this is *not* Debug-only (so
// #ifdef it out if you want something Debug-only). (Rationale: Having a
// |CalledOnValidThread()| that lies in Release builds seems bad. Moreover,
// there's a small space cost to having even an empty class. )
class ThreadChecker final {
public:
static void DisableNextThreadCheckFailure() { disable_next_failure_ = true; }
private:
static thread_local bool disable_next_failure_;
public:
#if defined(FML_OS_WIN)
ThreadChecker() : self_(GetCurrentThreadId()) {}
~ThreadChecker() {}
bool IsCreationThreadCurrent() const {
bool result = GetCurrentThreadId() == self_;
if (!result && disable_next_failure_) {
disable_next_failure_ = false;
return true;
}
return result;
}
private:
DWORD self_;
#else
ThreadChecker() : self_(pthread_self()) {}
~ThreadChecker() {}
// Returns true if the current thread is the thread this object was created
// on and false otherwise.
bool IsCreationThreadCurrent() const {
pthread_t current_thread = pthread_self();
bool is_creation_thread_current = !!pthread_equal(current_thread, self_);
if (disable_next_failure_ && !is_creation_thread_current) {
disable_next_failure_ = false;
return true;
}
#ifdef __APPLE__
// TODO(https://github.com/flutter/flutter/issues/45272): Implement for
// other platforms.
if (!is_creation_thread_current) {
static const int buffer_length = 128;
char expected_thread[buffer_length];
char actual_thread[buffer_length];
if (0 == pthread_getname_np(current_thread, actual_thread,
buffer_length) &&
0 == pthread_getname_np(self_, expected_thread, buffer_length)) {
FML_DLOG(ERROR) << "Object referenced on a thread other than the one "
"on which it was created. Expected thread: '"
<< expected_thread << "'. Actual thread: '"
<< actual_thread << "'.";
}
}
#endif // __APPLE__
return is_creation_thread_current;
}
private:
pthread_t self_;
#endif
};
#if !defined(NDEBUG)
#define FML_DECLARE_THREAD_CHECKER(c) fml::ThreadChecker c
#define FML_DCHECK_CREATION_THREAD_IS_CURRENT(c) \
FML_DCHECK((c).IsCreationThreadCurrent())
#else
#define FML_DECLARE_THREAD_CHECKER(c)
#define FML_DCHECK_CREATION_THREAD_IS_CURRENT(c) ((void)0)
#endif
} // namespace fml
#endif // FLUTTER_FML_MEMORY_THREAD_CHECKER_H_
| engine/fml/memory/thread_checker.h/0 | {
"file_path": "engine/fml/memory/thread_checker.h",
"repo_id": "engine",
"token_count": 1212
} | 168 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/fml/paths.h"
#include <sstream>
#include "flutter/fml/build_config.h"
namespace fml {
namespace paths {
std::string JoinPaths(std::initializer_list<std::string> components) {
std::stringstream stream;
size_t i = 0;
const size_t size = components.size();
for (const auto& component : components) {
i++;
stream << component;
if (i != size) {
#if FML_OS_WIN
stream << "\\";
#else // FML_OS_WIN
stream << "/";
#endif // FML_OS_WIN
}
}
return stream.str();
}
std::string SanitizeURIEscapedCharacters(const std::string& str) {
std::string result;
result.reserve(str.size());
for (std::string::size_type i = 0; i < str.size(); ++i) {
if (str[i] == '%') {
if (i > str.size() - 3 || !isxdigit(str[i + 1]) ||
!isxdigit(str[i + 2])) {
return "";
}
const std::string hex = str.substr(i + 1, 2);
const unsigned char c = strtoul(hex.c_str(), nullptr, 16);
if (!c) {
return "";
}
result += c;
i += 2;
} else {
result += str[i];
}
}
return result;
}
std::pair<bool, std::string> GetExecutableDirectoryPath() {
auto path = GetExecutablePath();
if (!path.first) {
return {false, ""};
}
return {true, fml::paths::GetDirectoryName(path.second)};
}
} // namespace paths
} // namespace fml
| engine/fml/paths.cc/0 | {
"file_path": "engine/fml/paths.cc",
"repo_id": "engine",
"token_count": 618
} | 169 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FML_PLATFORM_DARWIN_CF_UTILS_H_
#define FLUTTER_FML_PLATFORM_DARWIN_CF_UTILS_H_
#include <CoreFoundation/CoreFoundation.h>
#include "flutter/fml/macros.h"
namespace fml {
template <class T>
class CFRef {
public:
CFRef() : instance_(nullptr) {}
// NOLINTNEXTLINE(google-explicit-constructor)
CFRef(T instance) : instance_(instance) {}
CFRef(const CFRef& other) : instance_(other.instance_) {
if (instance_) {
CFRetain(instance_);
}
}
CFRef(CFRef&& other) : instance_(other.instance_) {
other.instance_ = nullptr;
}
CFRef& operator=(CFRef&& other) {
Reset(other.Release());
return *this;
}
~CFRef() {
if (instance_ != nullptr) {
CFRelease(instance_);
}
instance_ = nullptr;
}
void Reset(T instance = nullptr) {
if (instance_ != nullptr) {
CFRelease(instance_);
}
instance_ = instance;
}
[[nodiscard]] T Release() {
auto instance = instance_;
instance_ = nullptr;
return instance;
}
// NOLINTNEXTLINE(google-explicit-constructor)
operator T() const { return instance_; }
explicit operator bool() const { return instance_ != nullptr; }
private:
T instance_;
CFRef& operator=(const CFRef&) = delete;
};
} // namespace fml
#endif // FLUTTER_FML_PLATFORM_DARWIN_CF_UTILS_H_
| engine/fml/platform/darwin/cf_utils.h/0 | {
"file_path": "engine/fml/platform/darwin/cf_utils.h",
"repo_id": "engine",
"token_count": 560
} | 170 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FML_PLATFORM_DARWIN_SCOPED_POLICY_H_
#define FLUTTER_FML_PLATFORM_DARWIN_SCOPED_POLICY_H_
namespace fml {
namespace scoped_policy {
// Defines the ownership policy for a scoped object.
enum OwnershipPolicy {
// The scoped object takes ownership of an object by taking over an existing
// ownership claim.
kAssume,
// The scoped object will retain the the object and any initial ownership is
// not changed.
kRetain
};
} // namespace scoped_policy
} // namespace fml
#endif // FLUTTER_FML_PLATFORM_DARWIN_SCOPED_POLICY_H_
| engine/fml/platform/darwin/scoped_policy.h/0 | {
"file_path": "engine/fml/platform/darwin/scoped_policy.h",
"repo_id": "engine",
"token_count": 239
} | 171 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/fml/file.h"
#include "flutter/fml/paths.h"
namespace fml {
namespace paths {
std::pair<bool, std::string> GetExecutablePath() {
return {false, ""};
}
fml::UniqueFD GetCachesDirectory() {
return OpenDirectory("/cache", false, fml::FilePermission::kRead);
}
} // namespace paths
} // namespace fml
| engine/fml/platform/fuchsia/paths_fuchsia.cc/0 | {
"file_path": "engine/fml/platform/fuchsia/paths_fuchsia.cc",
"repo_id": "engine",
"token_count": 158
} | 172 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FML_PLATFORM_POSIX_SHARED_MUTEX_POSIX_H_
#define FLUTTER_FML_PLATFORM_POSIX_SHARED_MUTEX_POSIX_H_
#include <shared_mutex>
#include "flutter/fml/synchronization/shared_mutex.h"
namespace fml {
class SharedMutexPosix : public SharedMutex {
public:
virtual void Lock();
virtual void LockShared();
virtual void Unlock();
virtual void UnlockShared();
private:
friend SharedMutex* SharedMutex::Create();
SharedMutexPosix();
pthread_rwlock_t rwlock_;
};
} // namespace fml
#endif // FLUTTER_FML_PLATFORM_POSIX_SHARED_MUTEX_POSIX_H_
| engine/fml/platform/posix/shared_mutex_posix.h/0 | {
"file_path": "engine/fml/platform/posix/shared_mutex_posix.h",
"repo_id": "engine",
"token_count": 265
} | 173 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FML_POSIX_WRAPPERS_H_
#define FLUTTER_FML_POSIX_WRAPPERS_H_
#include "flutter/fml/build_config.h"
// Provides wrappers for POSIX functions that have been renamed on Windows.
// See
// https://docs.microsoft.com/en-us/cpp/error-messages/compiler-warnings/compiler-warning-level-3-c4996?view=vs-2019#posix-function-names
// for context.
namespace fml {
char* strdup(const char* str1);
} // namespace fml
#endif // FLUTTER_FML_POSIX_WRAPPERS_H_
| engine/fml/posix_wrappers.h/0 | {
"file_path": "engine/fml/posix_wrappers.h",
"repo_id": "engine",
"token_count": 222
} | 174 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/fml/synchronization/count_down_latch.h"
#include <chrono>
#include <thread>
#include "flutter/fml/build_config.h"
#include "flutter/fml/thread.h"
#include "flutter/testing/testing.h"
namespace fml {
TEST(CountDownLatchTest, CanWaitOnZero) {
CountDownLatch latch(0);
latch.Wait();
}
TEST(CountDownLatchTest, CanWait) {
fml::Thread thread("test_thread");
const size_t count = 100;
size_t current_count = 0;
CountDownLatch latch(count);
auto decrement_latch_on_thread = [runner = thread.GetTaskRunner(), &latch,
¤t_count]() {
runner->PostTask([&latch, ¤t_count]() {
std::this_thread::sleep_for(std::chrono::microseconds(100));
current_count++;
latch.CountDown();
});
};
for (size_t i = 0; i < count; ++i) {
decrement_latch_on_thread();
}
latch.Wait();
ASSERT_EQ(current_count, count);
}
} // namespace fml
| engine/fml/synchronization/count_down_latch_unittests.cc/0 | {
"file_path": "engine/fml/synchronization/count_down_latch_unittests.cc",
"repo_id": "engine",
"token_count": 430
} | 175 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#define FML_USED_ON_EMBEDDER
#include "flutter/fml/task_source.h"
namespace fml {
TaskSource::TaskSource(TaskQueueId task_queue_id)
: task_queue_id_(task_queue_id) {}
TaskSource::~TaskSource() {
ShutDown();
}
void TaskSource::ShutDown() {
primary_task_queue_ = {};
secondary_task_queue_ = {};
}
void TaskSource::RegisterTask(const DelayedTask& task) {
switch (task.GetTaskSourceGrade()) {
case TaskSourceGrade::kUserInteraction:
primary_task_queue_.push(task);
break;
case TaskSourceGrade::kUnspecified:
primary_task_queue_.push(task);
break;
case TaskSourceGrade::kDartEventLoop:
secondary_task_queue_.push(task);
break;
}
}
void TaskSource::PopTask(TaskSourceGrade grade) {
switch (grade) {
case TaskSourceGrade::kUserInteraction:
primary_task_queue_.pop();
break;
case TaskSourceGrade::kUnspecified:
primary_task_queue_.pop();
break;
case TaskSourceGrade::kDartEventLoop:
secondary_task_queue_.pop();
break;
}
}
size_t TaskSource::GetNumPendingTasks() const {
size_t size = primary_task_queue_.size();
if (secondary_pause_requests_ == 0) {
size += secondary_task_queue_.size();
}
return size;
}
bool TaskSource::IsEmpty() const {
return GetNumPendingTasks() == 0;
}
TaskSource::TopTask TaskSource::Top() const {
FML_CHECK(!IsEmpty());
if (secondary_pause_requests_ > 0 || secondary_task_queue_.empty()) {
const auto& primary_top = primary_task_queue_.top();
return {
.task_queue_id = task_queue_id_,
.task = primary_top,
};
} else if (primary_task_queue_.empty()) {
const auto& secondary_top = secondary_task_queue_.top();
return {
.task_queue_id = task_queue_id_,
.task = secondary_top,
};
} else {
const auto& primary_top = primary_task_queue_.top();
const auto& secondary_top = secondary_task_queue_.top();
if (primary_top > secondary_top) {
return {
.task_queue_id = task_queue_id_,
.task = secondary_top,
};
} else {
return {
.task_queue_id = task_queue_id_,
.task = primary_top,
};
}
}
}
void TaskSource::PauseSecondary() {
secondary_pause_requests_++;
}
void TaskSource::ResumeSecondary() {
secondary_pause_requests_--;
FML_DCHECK(secondary_pause_requests_ >= 0);
}
} // namespace fml
| engine/fml/task_source.cc/0 | {
"file_path": "engine/fml/task_source.cc",
"repo_id": "engine",
"token_count": 1001
} | 176 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/fml/trace_event.h"
#include <algorithm>
#include <atomic>
#include <utility>
#include "flutter/fml/ascii_trie.h"
#include "flutter/fml/build_config.h"
#include "flutter/fml/logging.h"
namespace fml {
namespace tracing {
#if FLUTTER_TIMELINE_ENABLED
namespace {
int64_t DefaultMicrosSource() {
return -1;
}
AsciiTrie gAllowlist;
std::atomic<TimelineEventHandler> gTimelineEventHandler;
std::atomic<TimelineMicrosSource> gTimelineMicrosSource = DefaultMicrosSource;
inline void FlutterTimelineEvent(const char* label,
int64_t timestamp0,
int64_t timestamp1_or_async_id,
intptr_t flow_id_count,
const int64_t* flow_ids,
Dart_Timeline_Event_Type type,
intptr_t argument_count,
const char** argument_names,
const char** argument_values) {
TimelineEventHandler handler =
gTimelineEventHandler.load(std::memory_order_relaxed);
if (handler && gAllowlist.Query(label)) {
handler(label, timestamp0, timestamp1_or_async_id, flow_id_count, flow_ids,
type, argument_count, argument_names, argument_values);
}
}
} // namespace
void TraceSetAllowlist(const std::vector<std::string>& allowlist) {
gAllowlist.Fill(allowlist);
}
void TraceSetTimelineEventHandler(TimelineEventHandler handler) {
gTimelineEventHandler = handler;
}
bool TraceHasTimelineEventHandler() {
return static_cast<bool>(
gTimelineEventHandler.load(std::memory_order_relaxed));
}
int64_t TraceGetTimelineMicros() {
return gTimelineMicrosSource.load()();
}
void TraceSetTimelineMicrosSource(TimelineMicrosSource source) {
gTimelineMicrosSource = source;
}
size_t TraceNonce() {
static std::atomic_size_t last_item;
return ++last_item;
}
void TraceTimelineEvent(TraceArg category_group,
TraceArg name,
int64_t timestamp_micros,
TraceIDArg identifier,
size_t flow_id_count,
const uint64_t* flow_ids,
Dart_Timeline_Event_Type type,
const std::vector<const char*>& c_names,
const std::vector<std::string>& values) {
const auto argument_count = std::min(c_names.size(), values.size());
std::vector<const char*> c_values;
c_values.resize(argument_count, nullptr);
for (size_t i = 0; i < argument_count; i++) {
c_values[i] = values[i].c_str();
}
FlutterTimelineEvent(
name, // label
timestamp_micros, // timestamp0
identifier, // timestamp1_or_async_id
flow_id_count, // flow_id_count
reinterpret_cast<const int64_t*>(flow_ids), // flow_ids
type, // event type
argument_count, // argument_count
const_cast<const char**>(c_names.data()), // argument_names
c_values.data() // argument_values
);
}
void TraceTimelineEvent(TraceArg category_group,
TraceArg name,
TraceIDArg identifier,
size_t flow_id_count,
const uint64_t* flow_ids,
Dart_Timeline_Event_Type type,
const std::vector<const char*>& c_names,
const std::vector<std::string>& values) {
TraceTimelineEvent(category_group, // group
name, // name
gTimelineMicrosSource.load()(), // timestamp_micros
identifier, // identifier
flow_id_count, // flow_id_count
flow_ids, // flow_ids
type, // type
c_names, // names
values // values
);
}
void TraceEvent0(TraceArg category_group,
TraceArg name,
size_t flow_id_count,
const uint64_t* flow_ids) {
FlutterTimelineEvent(name, // label
gTimelineMicrosSource.load()(), // timestamp0
0, // timestamp1_or_async_id
flow_id_count, // flow_id_count
reinterpret_cast<const int64_t*>(flow_ids), // flow_ids
Dart_Timeline_Event_Begin, // event type
0, // argument_count
nullptr, // argument_names
nullptr // argument_values
);
}
void TraceEvent1(TraceArg category_group,
TraceArg name,
size_t flow_id_count,
const uint64_t* flow_ids,
TraceArg arg1_name,
TraceArg arg1_val) {
const char* arg_names[] = {arg1_name};
const char* arg_values[] = {arg1_val};
FlutterTimelineEvent(name, // label
gTimelineMicrosSource.load()(), // timestamp0
0, // timestamp1_or_async_id
flow_id_count, // flow_id_count
reinterpret_cast<const int64_t*>(flow_ids), // flow_ids
Dart_Timeline_Event_Begin, // event type
1, // argument_count
arg_names, // argument_names
arg_values // argument_values
);
}
void TraceEvent2(TraceArg category_group,
TraceArg name,
size_t flow_id_count,
const uint64_t* flow_ids,
TraceArg arg1_name,
TraceArg arg1_val,
TraceArg arg2_name,
TraceArg arg2_val) {
const char* arg_names[] = {arg1_name, arg2_name};
const char* arg_values[] = {arg1_val, arg2_val};
FlutterTimelineEvent(name, // label
gTimelineMicrosSource.load()(), // timestamp0
0, // timestamp1_or_async_id
flow_id_count, // flow_id_count
reinterpret_cast<const int64_t*>(flow_ids), // flow_ids
Dart_Timeline_Event_Begin, // event type
2, // argument_count
arg_names, // argument_names
arg_values // argument_values
);
}
void TraceEventEnd(TraceArg name) {
FlutterTimelineEvent(name, // label
gTimelineMicrosSource.load()(), // timestamp0
0, // timestamp1_or_async_id
0, // flow_id_count
nullptr, // flow_ids
Dart_Timeline_Event_End, // event type
0, // argument_count
nullptr, // argument_names
nullptr // argument_values
);
}
void TraceEventAsyncBegin0(TraceArg category_group,
TraceArg name,
TraceIDArg id,
size_t flow_id_count,
const uint64_t* flow_ids) {
FlutterTimelineEvent(name, // label
gTimelineMicrosSource.load()(), // timestamp0
id, // timestamp1_or_async_id
flow_id_count, // flow_id_count
reinterpret_cast<const int64_t*>(flow_ids), // flow_ids
Dart_Timeline_Event_Async_Begin, // event type
0, // argument_count
nullptr, // argument_names
nullptr // argument_values
);
}
void TraceEventAsyncEnd0(TraceArg category_group,
TraceArg name,
TraceIDArg id) {
FlutterTimelineEvent(name, // label
gTimelineMicrosSource.load()(), // timestamp0
id, // timestamp1_or_async_id
0, // flow_id_count
nullptr, // flow_ids
Dart_Timeline_Event_Async_End, // event type
0, // argument_count
nullptr, // argument_names
nullptr // argument_values
);
}
void TraceEventAsyncBegin1(TraceArg category_group,
TraceArg name,
TraceIDArg id,
size_t flow_id_count,
const uint64_t* flow_ids,
TraceArg arg1_name,
TraceArg arg1_val) {
const char* arg_names[] = {arg1_name};
const char* arg_values[] = {arg1_val};
FlutterTimelineEvent(name, // label
gTimelineMicrosSource.load()(), // timestamp0
id, // timestamp1_or_async_id
flow_id_count, // flow_id_count
reinterpret_cast<const int64_t*>(flow_ids), // flow_ids
Dart_Timeline_Event_Async_Begin, // event type
1, // argument_count
arg_names, // argument_names
arg_values // argument_values
);
}
void TraceEventAsyncEnd1(TraceArg category_group,
TraceArg name,
TraceIDArg id,
TraceArg arg1_name,
TraceArg arg1_val) {
const char* arg_names[] = {arg1_name};
const char* arg_values[] = {arg1_val};
FlutterTimelineEvent(name, // label
gTimelineMicrosSource.load()(), // timestamp0
id, // timestamp1_or_async_id
0, // flow_id_count
nullptr, // flow_ids
Dart_Timeline_Event_Async_End, // event type
1, // argument_count
arg_names, // argument_names
arg_values // argument_values
);
}
void TraceEventInstant0(TraceArg category_group,
TraceArg name,
size_t flow_id_count,
const uint64_t* flow_ids) {
FlutterTimelineEvent(name, // label
gTimelineMicrosSource.load()(), // timestamp0
0, // timestamp1_or_async_id
flow_id_count, // flow_id_count
reinterpret_cast<const int64_t*>(flow_ids), // flow_ids
Dart_Timeline_Event_Instant, // event type
0, // argument_count
nullptr, // argument_names
nullptr // argument_values
);
}
void TraceEventInstant1(TraceArg category_group,
TraceArg name,
size_t flow_id_count,
const uint64_t* flow_ids,
TraceArg arg1_name,
TraceArg arg1_val) {
const char* arg_names[] = {arg1_name};
const char* arg_values[] = {arg1_val};
FlutterTimelineEvent(name, // label
gTimelineMicrosSource.load()(), // timestamp0
0, // timestamp1_or_async_id
flow_id_count, // flow_id_count
reinterpret_cast<const int64_t*>(flow_ids), // flow_ids
Dart_Timeline_Event_Instant, // event type
1, // argument_count
arg_names, // argument_names
arg_values // argument_values
);
}
void TraceEventInstant2(TraceArg category_group,
TraceArg name,
size_t flow_id_count,
const uint64_t* flow_ids,
TraceArg arg1_name,
TraceArg arg1_val,
TraceArg arg2_name,
TraceArg arg2_val) {
const char* arg_names[] = {arg1_name, arg2_name};
const char* arg_values[] = {arg1_val, arg2_val};
FlutterTimelineEvent(name, // label
gTimelineMicrosSource.load()(), // timestamp0
0, // timestamp1_or_async_id
flow_id_count, // flow_id_count
reinterpret_cast<const int64_t*>(flow_ids), // flow_ids
Dart_Timeline_Event_Instant, // event type
2, // argument_count
arg_names, // argument_names
arg_values // argument_values
);
}
void TraceEventFlowBegin0(TraceArg category_group,
TraceArg name,
TraceIDArg id) {
FlutterTimelineEvent(name, // label
gTimelineMicrosSource.load()(), // timestamp0
id, // timestamp1_or_async_id
0, // flow_id_count
nullptr, // flow_ids
Dart_Timeline_Event_Flow_Begin, // event type
0, // argument_count
nullptr, // argument_names
nullptr // argument_values
);
}
void TraceEventFlowStep0(TraceArg category_group,
TraceArg name,
TraceIDArg id) {
FlutterTimelineEvent(name, // label
gTimelineMicrosSource.load()(), // timestamp0
id, // timestamp1_or_async_id
0, // flow_id_count
nullptr, // flow_ids
Dart_Timeline_Event_Flow_Step, // event type
0, // argument_count
nullptr, // argument_names
nullptr // argument_values
);
}
void TraceEventFlowEnd0(TraceArg category_group, TraceArg name, TraceIDArg id) {
FlutterTimelineEvent(name, // label
gTimelineMicrosSource.load()(), // timestamp0
id, // timestamp1_or_async_id
0, // flow_id_count
nullptr, // flow_ids
Dart_Timeline_Event_Flow_End, // event type
0, // argument_count
nullptr, // argument_names
nullptr // argument_values
);
}
#else // FLUTTER_TIMELINE_ENABLED
void TraceSetAllowlist(const std::vector<std::string>& allowlist) {}
void TraceSetTimelineEventHandler(TimelineEventHandler handler) {}
bool TraceHasTimelineEventHandler() {
return false;
}
int64_t TraceGetTimelineMicros() {
return -1;
}
void TraceSetTimelineMicrosSource(TimelineMicrosSource source) {}
size_t TraceNonce() {
return 0;
}
void TraceTimelineEvent(TraceArg category_group,
TraceArg name,
int64_t timestamp_micros,
TraceIDArg identifier,
size_t flow_id_count,
const uint64_t* flow_ids,
Dart_Timeline_Event_Type type,
const std::vector<const char*>& c_names,
const std::vector<std::string>& values) {}
void TraceTimelineEvent(TraceArg category_group,
TraceArg name,
TraceIDArg identifier,
size_t flow_id_count,
const uint64_t* flow_ids,
Dart_Timeline_Event_Type type,
const std::vector<const char*>& c_names,
const std::vector<std::string>& values) {}
void TraceEvent0(TraceArg category_group,
TraceArg name,
size_t flow_id_count,
const uint64_t* flow_ids) {}
void TraceEvent1(TraceArg category_group,
TraceArg name,
size_t flow_id_count,
const uint64_t* flow_ids,
TraceArg arg1_name,
TraceArg arg1_val) {}
void TraceEvent2(TraceArg category_group,
TraceArg name,
size_t flow_id_count,
const uint64_t* flow_ids,
TraceArg arg1_name,
TraceArg arg1_val,
TraceArg arg2_name,
TraceArg arg2_val) {}
void TraceEventEnd(TraceArg name) {}
void TraceEventAsyncComplete(TraceArg category_group,
TraceArg name,
TimePoint begin,
TimePoint end) {}
void TraceEventAsyncBegin0(TraceArg category_group,
TraceArg name,
TraceIDArg id,
size_t flow_id_count,
const uint64_t* flow_ids) {}
void TraceEventAsyncEnd0(TraceArg category_group,
TraceArg name,
TraceIDArg id) {}
void TraceEventAsyncBegin1(TraceArg category_group,
TraceArg name,
TraceIDArg id,
size_t flow_id_count,
const uint64_t* flow_ids,
TraceArg arg1_name,
TraceArg arg1_val) {}
void TraceEventAsyncEnd1(TraceArg category_group,
TraceArg name,
TraceIDArg id,
TraceArg arg1_name,
TraceArg arg1_val) {}
void TraceEventInstant0(TraceArg category_group,
TraceArg name,
size_t flow_id_count,
const uint64_t* flow_ids) {}
void TraceEventInstant1(TraceArg category_group,
TraceArg name,
size_t flow_id_count,
const uint64_t* flow_ids,
TraceArg arg1_name,
TraceArg arg1_val) {}
void TraceEventInstant2(TraceArg category_group,
TraceArg name,
size_t flow_id_count,
const uint64_t* flow_ids,
TraceArg arg1_name,
TraceArg arg1_val,
TraceArg arg2_name,
TraceArg arg2_val) {}
void TraceEventFlowBegin0(TraceArg category_group,
TraceArg name,
TraceIDArg id) {}
void TraceEventFlowStep0(TraceArg category_group,
TraceArg name,
TraceIDArg id) {}
void TraceEventFlowEnd0(TraceArg category_group, TraceArg name, TraceIDArg id) {
}
#endif // FLUTTER_TIMELINE_ENABLED
} // namespace tracing
} // namespace fml
| engine/fml/trace_event.cc/0 | {
"file_path": "engine/fml/trace_event.cc",
"repo_id": "engine",
"token_count": 12655
} | 177 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/aiks/aiks_playground.h"
#include <memory>
#include "impeller/aiks/aiks_context.h"
#include "impeller/typographer/backends/skia/typographer_context_skia.h"
#include "impeller/typographer/typographer_context.h"
namespace impeller {
AiksPlayground::AiksPlayground()
: typographer_context_(TypographerContextSkia::Make()) {}
AiksPlayground::~AiksPlayground() = default;
void AiksPlayground::SetTypographerContext(
std::shared_ptr<TypographerContext> typographer_context) {
typographer_context_ = std::move(typographer_context);
}
void AiksPlayground::TearDown() {
inspector_.HackResetDueToTextureLeaks();
PlaygroundTest::TearDown();
}
bool AiksPlayground::OpenPlaygroundHere(Picture picture) {
return OpenPlaygroundHere([&picture](AiksContext& renderer) -> Picture {
return std::move(picture);
});
}
bool AiksPlayground::OpenPlaygroundHere(AiksPlaygroundCallback callback) {
if (!switches_.enable_playground) {
return true;
}
AiksContext renderer(GetContext(), typographer_context_);
if (!renderer.IsValid()) {
return false;
}
return Playground::OpenPlaygroundHere(
[this, &renderer, &callback](RenderTarget& render_target) -> bool {
const std::optional<Picture>& picture = inspector_.RenderInspector(
renderer, [&]() { return callback(renderer); });
if (!picture.has_value()) {
return false;
}
return renderer.Render(*picture, render_target, true);
});
}
bool AiksPlayground::ImGuiBegin(const char* name,
bool* p_open,
ImGuiWindowFlags flags) {
ImGui::Begin(name, p_open, flags);
return true;
}
} // namespace impeller
| engine/impeller/aiks/aiks_playground.cc/0 | {
"file_path": "engine/impeller/aiks/aiks_playground.cc",
"repo_id": "engine",
"token_count": 702
} | 178 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_AIKS_COLOR_SOURCE_H_
#define FLUTTER_IMPELLER_AIKS_COLOR_SOURCE_H_
#include <functional>
#include <memory>
#include <vector>
#include "flutter/fml/macros.h"
#include "impeller/entity/contents/runtime_effect_contents.h"
#include "impeller/entity/entity.h"
#include "impeller/geometry/color.h"
#include "impeller/geometry/matrix.h"
#include "impeller/geometry/point.h"
#include "impeller/runtime_stage/runtime_stage.h"
#if IMPELLER_ENABLE_3D
#include "impeller/scene/node.h" // nogncheck
#endif // IMPELLER_ENABLE_3D
namespace impeller {
struct Paint;
class ColorSource {
public:
enum class Type {
kColor,
kImage,
kLinearGradient,
kRadialGradient,
kConicalGradient,
kSweepGradient,
kRuntimeEffect,
kScene,
};
using ColorSourceProc =
std::function<std::shared_ptr<ColorSourceContents>(const Paint& paint)>;
ColorSource() noexcept;
~ColorSource();
static ColorSource MakeColor();
static ColorSource MakeLinearGradient(Point start_point,
Point end_point,
std::vector<Color> colors,
std::vector<Scalar> stops,
Entity::TileMode tile_mode,
Matrix effect_transform);
static ColorSource MakeConicalGradient(Point center,
Scalar radius,
std::vector<Color> colors,
std::vector<Scalar> stops,
Point focus_center,
Scalar focus_radius,
Entity::TileMode tile_mode,
Matrix effect_transform);
static ColorSource MakeRadialGradient(Point center,
Scalar radius,
std::vector<Color> colors,
std::vector<Scalar> stops,
Entity::TileMode tile_mode,
Matrix effect_transform);
static ColorSource MakeSweepGradient(Point center,
Degrees start_angle,
Degrees end_angle,
std::vector<Color> colors,
std::vector<Scalar> stops,
Entity::TileMode tile_mode,
Matrix effect_transform);
static ColorSource MakeImage(std::shared_ptr<Texture> texture,
Entity::TileMode x_tile_mode,
Entity::TileMode y_tile_mode,
SamplerDescriptor sampler_descriptor,
Matrix effect_transform);
static ColorSource MakeRuntimeEffect(
std::shared_ptr<RuntimeStage> runtime_stage,
std::shared_ptr<std::vector<uint8_t>> uniform_data,
std::vector<RuntimeEffectContents::TextureInput> texture_inputs);
#if IMPELLER_ENABLE_3D
static ColorSource MakeScene(std::shared_ptr<scene::Node> scene_node,
Matrix camera_transform);
#endif // IMPELLER_ENABLE_3D
Type GetType() const;
std::shared_ptr<ColorSourceContents> GetContents(const Paint& paint) const;
private:
Type type_ = Type::kColor;
ColorSourceProc proc_;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_AIKS_COLOR_SOURCE_H_
| engine/impeller/aiks/color_source.h/0 | {
"file_path": "engine/impeller/aiks/color_source.h",
"repo_id": "engine",
"token_count": 2016
} | 179 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/aiks/trace_serializer.h"
#include "flutter/fml/logging.h"
namespace impeller {
namespace {
class ImageFilterTraceVisitor : public ImageFilterVisitor {
public:
explicit ImageFilterTraceVisitor(std::ostream& os) : os_(os) {}
void Visit(const BlurImageFilter& filter) override {
os_ << "BlurImageFilter";
}
void Visit(const LocalMatrixImageFilter& filter) override {
os_ << "LocalMatrixImageFilter";
}
void Visit(const DilateImageFilter& filter) override {
os_ << "DilateImageFilter";
}
void Visit(const ErodeImageFilter& filter) override {
os_ << "ErodeImageFilter";
}
void Visit(const MatrixImageFilter& filter) override {
os_ << "{MatrixImageFilter matrix: " << filter.GetMatrix() << "}";
}
void Visit(const ComposeImageFilter& filter) override {
os_ << "ComposeImageFilter";
}
void Visit(const ColorImageFilter& filter) override {
os_ << "ColorImageFilter";
}
private:
std::ostream& os_;
};
std::ostream& operator<<(std::ostream& os,
const std::shared_ptr<ImageFilter>& image_filter) {
if (image_filter) {
os << "[";
ImageFilterTraceVisitor visitor(os);
image_filter->Visit(visitor);
os << "]";
} else {
os << "[None]";
}
return os;
}
std::ostream& operator<<(std::ostream& os, const ColorSource& color_source) {
os << "{ type: ";
switch (color_source.GetType()) {
case ColorSource::Type::kColor:
os << "kColor";
break;
case ColorSource::Type::kImage:
os << "kImage";
break;
case ColorSource::Type::kLinearGradient:
os << "kLinearGradient";
break;
case ColorSource::Type::kRadialGradient:
os << "kRadialGradient";
break;
case ColorSource::Type::kConicalGradient:
os << "kConicalGradient";
break;
case ColorSource::Type::kSweepGradient:
os << "kSweepGradient";
break;
case ColorSource::Type::kRuntimeEffect:
os << "kRuntimeEffect";
break;
case ColorSource::Type::kScene:
os << "kScene";
break;
}
os << " }";
return os;
}
std::ostream& operator<<(std::ostream& os, const Paint& paint) {
os << "{" << std::endl;
os << " color: [" << paint.color << "]" << std::endl;
os << " color_source:" << "[" << paint.color_source << "]" << std::endl;
os << " dither: [" << paint.dither << "]" << std::endl;
os << " stroke_width: [" << paint.stroke_width << "]" << std::endl;
os << " stroke_cap: " << "[Paint::Cap]" << std::endl;
os << " stroke_join: " << "[Paint::Join]" << std::endl;
os << " stroke_miter: [" << paint.stroke_miter << "]" << std::endl;
os << " style:" << "[Paint::Style]" << std::endl;
os << " blend_mode: [" << BlendModeToString(paint.blend_mode) << "]"
<< std::endl;
os << " invert_colors: [" << paint.invert_colors << "]" << std::endl;
os << " image_filter: " << paint.image_filter << std::endl;
os << " color_filter: " << paint.color_filter << std::endl;
os << " mask_blur_descriptor: " << "[std::optional<MaskBlurDescriptor>]"
<< std::endl;
os << "}";
return os;
}
} // namespace
#define FLT_CANVAS_RECORDER_OP_TO_STRING(name) \
case CanvasRecorderOp::name: \
return #name
namespace {
std::string_view CanvasRecorderOpToString(CanvasRecorderOp op) {
switch (op) {
FLT_CANVAS_RECORDER_OP_TO_STRING(kNew);
FLT_CANVAS_RECORDER_OP_TO_STRING(kSave);
FLT_CANVAS_RECORDER_OP_TO_STRING(kSaveLayer);
FLT_CANVAS_RECORDER_OP_TO_STRING(kRestore);
FLT_CANVAS_RECORDER_OP_TO_STRING(kRestoreToCount);
FLT_CANVAS_RECORDER_OP_TO_STRING(kResetTransform);
FLT_CANVAS_RECORDER_OP_TO_STRING(kTransform);
FLT_CANVAS_RECORDER_OP_TO_STRING(kConcat);
FLT_CANVAS_RECORDER_OP_TO_STRING(kPreConcat);
FLT_CANVAS_RECORDER_OP_TO_STRING(kTranslate);
FLT_CANVAS_RECORDER_OP_TO_STRING(kScale2);
FLT_CANVAS_RECORDER_OP_TO_STRING(kScale3);
FLT_CANVAS_RECORDER_OP_TO_STRING(kSkew);
FLT_CANVAS_RECORDER_OP_TO_STRING(kRotate);
FLT_CANVAS_RECORDER_OP_TO_STRING(kDrawPath);
FLT_CANVAS_RECORDER_OP_TO_STRING(kDrawPaint);
FLT_CANVAS_RECORDER_OP_TO_STRING(kDrawLine);
FLT_CANVAS_RECORDER_OP_TO_STRING(kDrawRect);
FLT_CANVAS_RECORDER_OP_TO_STRING(kDrawOval);
FLT_CANVAS_RECORDER_OP_TO_STRING(kDrawRRect);
FLT_CANVAS_RECORDER_OP_TO_STRING(kDrawCircle);
FLT_CANVAS_RECORDER_OP_TO_STRING(kDrawPoints);
FLT_CANVAS_RECORDER_OP_TO_STRING(kDrawImage);
FLT_CANVAS_RECORDER_OP_TO_STRING(kDrawImageRect);
FLT_CANVAS_RECORDER_OP_TO_STRING(kClipPath);
FLT_CANVAS_RECORDER_OP_TO_STRING(kClipRect);
FLT_CANVAS_RECORDER_OP_TO_STRING(kClipOval);
FLT_CANVAS_RECORDER_OP_TO_STRING(kClipRRect);
FLT_CANVAS_RECORDER_OP_TO_STRING(kDrawTextFrame);
FLT_CANVAS_RECORDER_OP_TO_STRING(kDrawVertices);
FLT_CANVAS_RECORDER_OP_TO_STRING(kDrawAtlas);
}
}
} // namespace
TraceSerializer::TraceSerializer() {}
void TraceSerializer::Write(CanvasRecorderOp op) {
if (op == CanvasRecorderOp::kNew) {
FML_LOG(ERROR) << "######################################################";
} else {
FML_LOG(ERROR) << CanvasRecorderOpToString(op) << ":" << buffer_.str();
buffer_.str("");
buffer_.clear();
}
}
void TraceSerializer::Write(const Paint& paint) {
buffer_ << "[" << paint << "] ";
}
void TraceSerializer::Write(const std::optional<Rect> optional_rect) {
if (optional_rect.has_value()) {
buffer_ << "[" << optional_rect.value() << "] ";
} else {
buffer_ << "[None] ";
}
}
void TraceSerializer::Write(const std::shared_ptr<ImageFilter>& image_filter) {
buffer_ << image_filter << " ";
}
void TraceSerializer::Write(size_t size) {
buffer_ << "[" << size << "] ";
}
void TraceSerializer::Write(const Matrix& matrix) {
buffer_ << "[" << matrix << "] ";
}
void TraceSerializer::Write(const Vector3& vec3) {
buffer_ << "[" << vec3 << "] ";
}
void TraceSerializer::Write(const Vector2& vec2) {
buffer_ << "[" << vec2 << "] ";
}
void TraceSerializer::Write(const Radians& radians) {
buffer_ << "[" << radians.radians << "] ";
}
void TraceSerializer::Write(const Path& path) {
buffer_ << "[Path] ";
}
void TraceSerializer::Write(const std::vector<Point>& points) {
buffer_ << "[std::vector<Point>] ";
}
void TraceSerializer::Write(const PointStyle& point_style) {
buffer_ << "[PointStyle] ";
}
void TraceSerializer::Write(const std::shared_ptr<Image>& image) {
buffer_ << "[std::shared_ptr<Image>] ";
}
void TraceSerializer::Write(const SamplerDescriptor& sampler) {
buffer_ << "[SamplerDescriptor] ";
}
void TraceSerializer::Write(const Entity::ClipOperation& clip_op) {
switch (clip_op) {
case Entity::ClipOperation::kDifference:
buffer_ << "[kDifference] ";
break;
case Entity::ClipOperation::kIntersect:
buffer_ << "[kIntersect] ";
break;
}
}
void TraceSerializer::Write(const Picture& clip_op) {
buffer_ << "[Picture] ";
}
void TraceSerializer::Write(const std::shared_ptr<TextFrame>& text_frame) {
buffer_ << "[std::shared_ptr<TextFrame>] ";
}
void TraceSerializer::Write(const std::shared_ptr<VerticesGeometry>& vertices) {
buffer_ << "[std::shared_ptr<VerticesGeometry>] ";
}
void TraceSerializer::Write(const BlendMode& blend_mode) {
buffer_ << "[" << BlendModeToString(blend_mode) << "] ";
}
void TraceSerializer::Write(const std::vector<Matrix>& matrices) {
buffer_ << "[std::vector<Matrix>] ";
}
void TraceSerializer::Write(const std::vector<Rect>& matrices) {
buffer_ << "[std::vector<Rect>] ";
}
void TraceSerializer::Write(const std::vector<Color>& matrices) {
buffer_ << "[std::vector<Color>] ";
}
void TraceSerializer::Write(const SourceRectConstraint& src_rect_constraint) {
buffer_ << "[SourceRectConstraint] ";
}
void TraceSerializer::Write(const ContentBoundsPromise& promise) {
buffer_ << "[SaveLayerBoundsPromise]";
}
} // namespace impeller
| engine/impeller/aiks/trace_serializer.cc/0 | {
"file_path": "engine/impeller/aiks/trace_serializer.cc",
"repo_id": "engine",
"token_count": 3268
} | 180 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_BASE_STRINGS_H_
#define FLUTTER_IMPELLER_BASE_STRINGS_H_
#include <string>
#include "impeller/base/config.h"
namespace impeller {
IMPELLER_PRINTF_FORMAT(1, 2)
std::string SPrintF(const char* format, ...);
bool HasPrefix(const std::string& string, const std::string& prefix);
bool HasSuffix(const std::string& string, const std::string& suffix);
std::string StripPrefix(const std::string& string, const std::string& to_strip);
} // namespace impeller
#endif // FLUTTER_IMPELLER_BASE_STRINGS_H_
| engine/impeller/base/strings.h/0 | {
"file_path": "engine/impeller/base/strings.h",
"repo_id": "engine",
"token_count": 245
} | 181 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_COMPILER_COMPILER_BACKEND_H_
#define FLUTTER_IMPELLER_COMPILER_COMPILER_BACKEND_H_
#include <cstdint>
#include <memory>
#include <variant>
#include "flutter/fml/logging.h"
#include "flutter/fml/macros.h"
#include "spirv_glsl.hpp"
#include "spirv_msl.hpp"
#include "spirv_sksl.h"
namespace impeller {
namespace compiler {
struct CompilerBackend {
using MSLCompiler = std::shared_ptr<spirv_cross::CompilerMSL>;
using GLSLCompiler = std::shared_ptr<spirv_cross::CompilerGLSL>;
using SkSLCompiler = std::shared_ptr<CompilerSkSL>;
using Compiler = std::variant<MSLCompiler, GLSLCompiler, SkSLCompiler>;
enum class Type {
kMSL,
kGLSL,
kGLSLVulkan,
kSkSL,
};
explicit CompilerBackend(MSLCompiler compiler);
explicit CompilerBackend(GLSLCompiler compiler);
explicit CompilerBackend(SkSLCompiler compiler);
CompilerBackend(Type type, Compiler compiler);
CompilerBackend();
~CompilerBackend();
Type GetType() const;
const spirv_cross::Compiler* operator->() const;
spirv_cross::Compiler* GetCompiler();
explicit operator bool() const;
enum class ExtendedResourceIndex {
kPrimary,
kSecondary,
};
uint32_t GetExtendedMSLResourceBinding(ExtendedResourceIndex index,
spirv_cross::ID id) const;
const spirv_cross::Compiler* GetCompiler() const;
private:
Type type_ = Type::kMSL;
Compiler compiler_;
const spirv_cross::CompilerMSL* GetMSLCompiler() const;
const spirv_cross::CompilerGLSL* GetGLSLCompiler() const;
const CompilerSkSL* GetSkSLCompiler() const;
};
} // namespace compiler
} // namespace impeller
#endif // FLUTTER_IMPELLER_COMPILER_COMPILER_BACKEND_H_
| engine/impeller/compiler/compiler_backend.h/0 | {
"file_path": "engine/impeller/compiler/compiler_backend.h",
"repo_id": "engine",
"token_count": 717
} | 182 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_COMPILER_SHADER_BUNDLE_H_
#define FLUTTER_IMPELLER_COMPILER_SHADER_BUNDLE_H_
#include "impeller/compiler/source_options.h"
#include "impeller/compiler/switches.h"
#include "impeller/shader_bundle/shader_bundle_flatbuffers.h"
namespace impeller {
namespace compiler {
/// @brief Parse a shader bundle configuration from a given JSON string.
///
/// @note Exposed only for testing purposes. Use `GenerateShaderBundle`
/// directly.
std::optional<ShaderBundleConfig> ParseShaderBundleConfig(
const std::string& bundle_config_json,
std::ostream& error_stream);
/// @brief Parses the JSON shader bundle configuration and invokes the
/// compiler multiple times to produce a shader bundle flatbuffer.
///
/// @note Exposed only for testing purposes. Use `GenerateShaderBundle`
/// directly.
std::optional<fb::shaderbundle::ShaderBundleT> GenerateShaderBundleFlatbuffer(
const std::string& bundle_config_json,
const SourceOptions& options);
/// @brief Parses the JSON shader bundle configuration and invokes the
/// compiler multiple times to produce a shader bundle flatbuffer, which
/// is then output to the `sl` file.
bool GenerateShaderBundle(Switches& switches);
} // namespace compiler
} // namespace impeller
#endif // FLUTTER_IMPELLER_COMPILER_SHADER_BUNDLE_H_
| engine/impeller/compiler/shader_bundle.h/0 | {
"file_path": "engine/impeller/compiler/shader_bundle.h",
"repo_id": "engine",
"token_count": 521
} | 183 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef GRADIENT_GLSL_
#define GRADIENT_GLSL_
#include <impeller/texture.glsl>
#include <impeller/transform.glsl>
mat3 IPMapToUnitX(vec2 p0, vec2 p1) {
// Returns a matrix that maps [p0, p1] to [(0, 0), (1, 0)]. Results are
// undefined if p0 = p1.
return mat3(0.0, -1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0) *
IPMat3Inverse(mat3(p1.y - p0.y, p0.x - p1.x, 0.0, p1.x - p0.x,
p1.y - p0.y, 0.0, p0.x, p0.y, 1.0));
}
/// Compute the t value for a conical gradient at point `p` between the 2
/// circles defined by (c0, r0) and (c1, r1). The returned vec2 encapsulates 't'
/// as its x component and validity status as its y component, with positive y
/// indicating a valid result.
///
/// The code is migrated from Skia Graphite. See
/// https://github.com/google/skia/blob/ddf987d2ab3314ee0e80ac1ae7dbffb44a87d394/src/sksl/sksl_graphite_frag.sksl#L541-L666.
vec2 IPComputeConicalT(vec2 c0, float r0, vec2 c1, float r1, vec2 pos) {
const float scalar_nearly_zero = 1.0 / float(1 << 12);
float d_center = distance(c0, c1);
float d_radius = r1 - r0;
// Degenerate case: a radial gradient (p0 = p1).
bool radial = d_center < scalar_nearly_zero;
// Degenerate case: a strip with bandwidth 2r (r0 = r1).
bool strip = abs(d_radius) < scalar_nearly_zero;
if (radial) {
if (strip) {
// The start and end inputs are the same in both position and radius.
// We don't expect to see this input, but just in case we avoid dividing
// by zero.
return vec2(0.0, -1.0);
}
float scale = 1.0 / d_radius;
float scale_sign = sign(d_radius);
float bias = r0 / d_radius;
vec2 pt = (pos - c0) * scale;
float t = length(pt) * scale_sign - bias;
return vec2(t, 1.0);
} else if (strip) {
mat3 transform = IPMapToUnitX(c0, c1);
float r = r0 / d_center;
float r_2 = r * r;
vec2 pt = (transform * vec3(pos.xy, 1.0)).xy;
float t = r_2 - pt.y * pt.y;
if (t < 0.0) {
return vec2(0.0, -1.0);
}
t = pt.x + sqrt(t);
return vec2(t, 1.0);
} else {
// See https://skia.org/docs/dev/design/conical/ for details on how this
// algorithm works. Calculate f and swap inputs if necessary (steps 1 and
// 2).
float f = r0 / (r0 - r1);
bool is_swapped = abs(f - 1.0) < scalar_nearly_zero;
if (is_swapped) {
vec2 tmp_pt = c0;
c0 = c1;
c1 = tmp_pt;
f = 0.0;
}
// Apply mapping from [Cf, C1] to unit x, and apply the precalculations from
// steps 3 and 4, all in the same transform.
vec2 cf = c0 * (1.0 - f) + c1 * f;
mat3 transform = IPMapToUnitX(cf, c1);
float scale_x = abs(1.0 - f);
float scale_y = scale_x;
float r1 = abs(r1 - r0) / d_center;
bool is_focal_on_circle = abs(r1 - 1.0) < scalar_nearly_zero;
if (is_focal_on_circle) {
scale_x *= 0.5;
scale_y *= 0.5;
} else {
scale_x *= r1 / (r1 * r1 - 1.0);
scale_y /= sqrt(abs(r1 * r1 - 1.0));
}
transform =
mat3(scale_x, 0.0, 0.0, 0.0, scale_y, 0.0, 0.0, 0.0, 1.0) * transform;
vec2 pt = (transform * vec3(pos.xy, 1.0)).xy;
// Continue with step 5 onward.
float inv_r1 = 1.0 / r1;
float d_radius_sign = sign(1.0 - f);
bool is_well_behaved = !is_focal_on_circle && r1 > 1.0;
float x_t = -1.0;
if (is_focal_on_circle) {
x_t = dot(pt, pt) / pt.x;
} else if (is_well_behaved) {
x_t = length(pt) - pt.x * inv_r1;
} else {
float temp = pt.x * pt.x - pt.y * pt.y;
if (temp >= 0.0) {
if (is_swapped || d_radius_sign < 0.0) {
x_t = -sqrt(temp) - pt.x * inv_r1;
} else {
x_t = sqrt(temp) - pt.x * inv_r1;
}
}
}
if (!is_well_behaved && x_t < 0.0) {
return vec2(0.0, -1.0);
}
float t = f + d_radius_sign * x_t;
if (is_swapped) {
t = 1.0 - t;
}
return vec2(t, 1.0);
}
}
/// Compute the indexes and mix coefficient used to mix colors for an
/// arbitrarily sized color gradient.
///
/// The returned values are the lower index, upper index, and mix
/// coefficient.
vec3 IPComputeFixedGradientValues(float t, float colors_length) {
float rough_index = (colors_length - 1) * t;
float lower_index = floor(rough_index);
float upper_index = ceil(rough_index);
float scale = rough_index - lower_index;
return vec3(lower_index, upper_index, scale);
}
#endif
| engine/impeller/compiler/shader_lib/impeller/gradient.glsl/0 | {
"file_path": "engine/impeller/compiler/shader_lib/impeller/gradient.glsl",
"repo_id": "engine",
"token_count": 2098
} | 184 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/compiler/types.h"
#include <cctype>
#include <filesystem>
#include <sstream>
#include "flutter/fml/logging.h"
#include "impeller/compiler/utilities.h"
namespace impeller {
namespace compiler {
static bool StringEndWith(const std::string& string,
const std::string& suffix) {
if (suffix.size() > string.size()) {
return false;
}
if (suffix.empty() || suffix.empty()) {
return false;
}
return string.rfind(suffix) == (string.size() - suffix.size());
}
SourceType SourceTypeFromFileName(const std::string& file_name) {
if (StringEndWith(file_name, ".vert")) {
return SourceType::kVertexShader;
}
if (StringEndWith(file_name, ".frag")) {
return SourceType::kFragmentShader;
}
if (StringEndWith(file_name, ".comp")) {
return SourceType::kComputeShader;
}
return SourceType::kUnknown;
}
SourceType SourceTypeFromString(std::string name) {
name = ToLowerCase(name);
if (name == "vertex") {
return SourceType::kVertexShader;
}
if (name == "fragment") {
return SourceType::kFragmentShader;
}
if (name == "compute") {
return SourceType::kComputeShader;
}
return SourceType::kUnknown;
}
SourceLanguage ToSourceLanguage(const std::string& source_language) {
if (source_language == "glsl") {
return SourceLanguage::kGLSL;
}
if (source_language == "hlsl") {
return SourceLanguage::kHLSL;
}
return SourceLanguage::kUnknown;
}
std::string TargetPlatformToString(TargetPlatform platform) {
switch (platform) {
case TargetPlatform::kUnknown:
return "Unknown";
case TargetPlatform::kMetalDesktop:
return "MetalDesktop";
case TargetPlatform::kMetalIOS:
return "MetaliOS";
case TargetPlatform::kOpenGLES:
return "OpenGLES";
case TargetPlatform::kOpenGLDesktop:
return "OpenGLDesktop";
case TargetPlatform::kVulkan:
return "Vulkan";
case TargetPlatform::kRuntimeStageMetal:
return "RuntimeStageMetal";
case TargetPlatform::kRuntimeStageGLES:
return "RuntimeStageGLES";
case TargetPlatform::kRuntimeStageVulkan:
return "RuntimeStageVulkan";
case TargetPlatform::kSkSL:
return "SkSL";
}
FML_UNREACHABLE();
}
std::string SourceLanguageToString(SourceLanguage source_language) {
switch (source_language) {
case SourceLanguage::kUnknown:
return "Unknown";
case SourceLanguage::kGLSL:
return "GLSL";
case SourceLanguage::kHLSL:
return "HLSL";
}
}
std::string EntryPointFunctionNameFromSourceName(
const std::string& file_name,
SourceType type,
SourceLanguage source_language,
const std::string& entry_point_name) {
if (source_language == SourceLanguage::kHLSL) {
return entry_point_name;
}
std::stringstream stream;
std::filesystem::path file_path(file_name);
stream << ConvertToEntrypointName(Utf8FromPath(file_path.stem())) << "_";
switch (type) {
case SourceType::kUnknown:
stream << "unknown";
break;
case SourceType::kVertexShader:
stream << "vertex";
break;
case SourceType::kFragmentShader:
stream << "fragment";
break;
case SourceType::kComputeShader:
stream << "compute";
break;
}
stream << "_main";
return stream.str();
}
bool TargetPlatformNeedsReflection(TargetPlatform platform) {
switch (platform) {
case TargetPlatform::kMetalIOS:
case TargetPlatform::kMetalDesktop:
case TargetPlatform::kOpenGLES:
case TargetPlatform::kOpenGLDesktop:
case TargetPlatform::kRuntimeStageMetal:
case TargetPlatform::kRuntimeStageGLES:
case TargetPlatform::kRuntimeStageVulkan:
case TargetPlatform::kVulkan:
return true;
case TargetPlatform::kUnknown:
case TargetPlatform::kSkSL:
return false;
}
FML_UNREACHABLE();
}
std::string ShaderCErrorToString(shaderc_compilation_status status) {
using Status = shaderc_compilation_status;
switch (status) {
case Status::shaderc_compilation_status_success:
return "Success";
case Status::shaderc_compilation_status_invalid_stage:
return "Invalid shader stage specified";
case Status::shaderc_compilation_status_compilation_error:
return "Compilation error";
case Status::shaderc_compilation_status_internal_error:
return "Internal error";
case Status::shaderc_compilation_status_null_result_object:
return "Internal error. Null result object";
case Status::shaderc_compilation_status_invalid_assembly:
return "Invalid assembly";
case Status::shaderc_compilation_status_validation_error:
return "Validation error";
case Status::shaderc_compilation_status_transformation_error:
return "Transform error";
case Status::shaderc_compilation_status_configuration_error:
return "Configuration error";
}
return "Unknown internal error";
}
shaderc_shader_kind ToShaderCShaderKind(SourceType type) {
switch (type) {
case SourceType::kVertexShader:
return shaderc_shader_kind::shaderc_vertex_shader;
case SourceType::kFragmentShader:
return shaderc_shader_kind::shaderc_fragment_shader;
case SourceType::kComputeShader:
return shaderc_shader_kind::shaderc_compute_shader;
case SourceType::kUnknown:
break;
}
return shaderc_shader_kind::shaderc_glsl_infer_from_source;
}
spv::ExecutionModel ToExecutionModel(SourceType type) {
switch (type) {
case SourceType::kVertexShader:
return spv::ExecutionModel::ExecutionModelVertex;
case SourceType::kFragmentShader:
return spv::ExecutionModel::ExecutionModelFragment;
case SourceType::kComputeShader:
return spv::ExecutionModel::ExecutionModelGLCompute;
case SourceType::kUnknown:
break;
}
return spv::ExecutionModel::ExecutionModelMax;
}
spirv_cross::CompilerMSL::Options::Platform TargetPlatformToMSLPlatform(
TargetPlatform platform) {
switch (platform) {
case TargetPlatform::kMetalIOS:
case TargetPlatform::kRuntimeStageMetal:
return spirv_cross::CompilerMSL::Options::Platform::iOS;
case TargetPlatform::kMetalDesktop:
return spirv_cross::CompilerMSL::Options::Platform::macOS;
case TargetPlatform::kSkSL:
case TargetPlatform::kOpenGLES:
case TargetPlatform::kOpenGLDesktop:
case TargetPlatform::kRuntimeStageGLES:
case TargetPlatform::kRuntimeStageVulkan:
case TargetPlatform::kVulkan:
case TargetPlatform::kUnknown:
return spirv_cross::CompilerMSL::Options::Platform::macOS;
}
FML_UNREACHABLE();
}
std::string SourceTypeToString(SourceType type) {
switch (type) {
case SourceType::kUnknown:
return "unknown";
case SourceType::kVertexShader:
return "vert";
case SourceType::kFragmentShader:
return "frag";
case SourceType::kComputeShader:
return "comp";
}
FML_UNREACHABLE();
}
std::string TargetPlatformSLExtension(TargetPlatform platform) {
switch (platform) {
case TargetPlatform::kUnknown:
return "unknown";
case TargetPlatform::kMetalDesktop:
case TargetPlatform::kMetalIOS:
case TargetPlatform::kRuntimeStageMetal:
return "metal";
case TargetPlatform::kSkSL:
case TargetPlatform::kOpenGLES:
case TargetPlatform::kOpenGLDesktop:
case TargetPlatform::kRuntimeStageGLES:
return "glsl";
case TargetPlatform::kVulkan:
case TargetPlatform::kRuntimeStageVulkan:
return "vk.spirv";
}
FML_UNREACHABLE();
}
bool TargetPlatformIsOpenGL(TargetPlatform platform) {
switch (platform) {
case TargetPlatform::kOpenGLES:
case TargetPlatform::kOpenGLDesktop:
case TargetPlatform::kRuntimeStageGLES:
return true;
case TargetPlatform::kMetalDesktop:
case TargetPlatform::kRuntimeStageMetal:
case TargetPlatform::kRuntimeStageVulkan:
case TargetPlatform::kMetalIOS:
case TargetPlatform::kUnknown:
case TargetPlatform::kSkSL:
case TargetPlatform::kVulkan:
return false;
}
FML_UNREACHABLE();
}
bool TargetPlatformIsMetal(TargetPlatform platform) {
switch (platform) {
case TargetPlatform::kMetalDesktop:
case TargetPlatform::kMetalIOS:
case TargetPlatform::kRuntimeStageMetal:
return true;
case TargetPlatform::kUnknown:
case TargetPlatform::kSkSL:
case TargetPlatform::kOpenGLES:
case TargetPlatform::kOpenGLDesktop:
case TargetPlatform::kRuntimeStageGLES:
case TargetPlatform::kRuntimeStageVulkan:
case TargetPlatform::kVulkan:
return false;
}
FML_UNREACHABLE();
}
bool TargetPlatformIsVulkan(TargetPlatform platform) {
switch (platform) {
case TargetPlatform::kRuntimeStageVulkan:
case TargetPlatform::kVulkan:
return true;
case TargetPlatform::kMetalDesktop:
case TargetPlatform::kMetalIOS:
case TargetPlatform::kRuntimeStageMetal:
case TargetPlatform::kUnknown:
case TargetPlatform::kSkSL:
case TargetPlatform::kOpenGLES:
case TargetPlatform::kOpenGLDesktop:
case TargetPlatform::kRuntimeStageGLES:
return false;
}
FML_UNREACHABLE();
}
bool TargetPlatformBundlesSkSL(TargetPlatform platform) {
switch (platform) {
case TargetPlatform::kSkSL:
case TargetPlatform::kRuntimeStageMetal:
case TargetPlatform::kRuntimeStageGLES:
case TargetPlatform::kRuntimeStageVulkan:
return true;
case TargetPlatform::kMetalDesktop:
case TargetPlatform::kMetalIOS:
case TargetPlatform::kUnknown:
case TargetPlatform::kOpenGLES:
case TargetPlatform::kOpenGLDesktop:
case TargetPlatform::kVulkan:
return false;
}
FML_UNREACHABLE();
}
} // namespace compiler
} // namespace impeller
| engine/impeller/compiler/types.cc/0 | {
"file_path": "engine/impeller/compiler/types.cc",
"repo_id": "engine",
"token_count": 3492
} | 185 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/core/sampler_descriptor.h"
#include "fml/logging.h"
namespace impeller {
SamplerDescriptor::SamplerDescriptor() = default;
SamplerDescriptor::SamplerDescriptor(std::string label,
MinMagFilter min_filter,
MinMagFilter mag_filter,
MipFilter mip_filter)
: min_filter(min_filter),
mag_filter(mag_filter),
mip_filter(mip_filter),
label(std::move(label)) {}
} // namespace impeller
| engine/impeller/core/sampler_descriptor.cc/0 | {
"file_path": "engine/impeller/core/sampler_descriptor.cc",
"repo_id": "engine",
"token_count": 315
} | 186 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_DISPLAY_LIST_DL_PLAYGROUND_H_
#define FLUTTER_IMPELLER_DISPLAY_LIST_DL_PLAYGROUND_H_
#include "flutter/display_list/display_list.h"
#include "flutter/display_list/dl_builder.h"
#include "impeller/playground/playground_test.h"
#include "third_party/skia/include/core/SkFont.h"
namespace impeller {
class DlPlayground : public PlaygroundTest {
public:
using DisplayListPlaygroundCallback =
std::function<sk_sp<flutter::DisplayList>()>;
DlPlayground();
~DlPlayground();
bool OpenPlaygroundHere(flutter::DisplayListBuilder& builder);
bool OpenPlaygroundHere(sk_sp<flutter::DisplayList> list);
bool OpenPlaygroundHere(DisplayListPlaygroundCallback callback);
SkFont CreateTestFontOfSize(SkScalar scalar);
SkFont CreateTestFont();
private:
DlPlayground(const DlPlayground&) = delete;
DlPlayground& operator=(const DlPlayground&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_DISPLAY_LIST_DL_PLAYGROUND_H_
| engine/impeller/display_list/dl_playground.h/0 | {
"file_path": "engine/impeller/display_list/dl_playground.h",
"repo_id": "engine",
"token_count": 388
} | 187 |
# Writing efficient shaders
When it comes to optimizing shaders for a wide range of devices, there is no
perfect strategy. The reality of different drivers written by different vendors
targeting different hardware is that they will vary in behavior. Any attempt at
optimizing against a specific driver will likely result in a performance loss
for some other drivers that end users will run Flutter apps against.
That being said, newer graphics devices have architectures that allow for both
simpler shader compilation and better handling of traditionally slow shader
code. In fact, ostensibly "unoptimized" shader code filled with branches may
significantly outperform the equivalent branchless optimized shader code when
targeting newer GPU architectures. (See the "Don't flatten simple varying
branches" recommendation for an explanation of this with respect to different
architectures).
Flutter actively supports mobile devices that are more than a decade old, which
requires us to write shaders that perform well across multiple generations of
GPU architectures featuring radically different behavior. Most optimization
choices are direct tradeoffs between these GPU architectures, and so having an
accurate mental model for how these common architectures maximize parallelism is
essential for making good decisions while authoring shaders.
For these reasons, it's also important to profile shaders against some of the
older devices that Flutter can target (such as the iPhone 6s) when making
changes intended to improve shader performance.
Also, even though the branching behavior is largely architecture dependent and
should remain the same when using different graphics APIs, it's still also a
good idea to test changes against the different backends supported by Impeller
(Metal and GLES). Early stage shader compilation (as well as the high level
shader code generated by ImpellerC) may vary quite a bit between APIs.
## GPU architecture primer
GPUs are designed to have functional units running single instructions over many
elements (the "data path") each clock cycle. This is the fundamental aspect of
GPUs that makes them work well for massively parallel compute work; they're
essentially specialized SIMD engines.
GPU parallelism generally comes in two broad architectural flavors:
**Instruction-level parallelism** and **Thread-level parallelism** -- these
architecture designs handle shader branching very differently and are covered
in the sections below. In general, older GPU architectures (on some products
released before ~2015) leverage instruction-level parallelism, while most if not
all newer GPUs leverage thread-level parallelism.
Some of the earliest GPU architectures had no runtime control flow primitives at
all (i.e. jump instructions), and compilers for these architectures needed to
handle branches ahead of time by unrolling loops, compiling a different program
for every possible branch combination, and then executing all of them. However,
virtually all GPU architectures in use today have instruction-level support for
dynamic branching, and it's quite unlikely that we'll come across a mobile
device capable of running Flutter that doesn't. For example, the old devices we
test against in CI (iPhone 6s and Moto G4) run GPUs that support dynamic
runtime branching. For these reasons, the optimization advice in this document
isn't aimed at branchless architectures.
### Instruction-level parallelism
Some older GPUs (including the PowerVR GT7600 GPU on the iPhone 6s SoC) rely on
SIMD vector or array instructions to maximize the number of computations
performed per clock cycle on each functional unit. This means that the shader
compiler must figure out which parts of the program are safe to parallelize
ahead of time and emit appropriate instructions. This presents a problem for
certain kinds of branches: If the compiler doesn't know that the same decision
will always be taken by all of the data lanes at runtime (meaning the branch is
_varying_), it can't safely emit SIMD instructions while compiling the branch.
The result is that instructions within non-uniform branches incur a
`1/[data width]` performance penalty when compared to non-branched instructions
because they can't be parallelized.
VLIW ("Very Long Instruction Width") is another common instruction-level
parallelism design that suffers from the same compile time reasoning
disadvantage that SIMD does.
### Thread-level parallelism
Newer GPUs (but also some older hardware such as the Adreno 306 GPU found on the
Moto G4's Snapdragon SoC) use scalar functional units (no SIMD/VLIW/MIMD) and
parallelize instructions at runtime by running the same instruction over many
threads in groups often referred to as "warps" (Nvidia terminology) or
"wavefronts" (AMD terminology), usually consisting of 32 or 64 threads per
warp/wavefront. This design is also commonly referred to as SIMT ("Single
Instruction Multiple Thread").
To handle branching, SIMT programs use special instructions to write a thread
mask that determines which threads are activated/deactivated in the warp; only
the warp's activated threads will actually execute instructions. Given this
setup, the program can first deactivate threads that failed the branch
condition, run the positive path, invert the mask, run the negative path, and
finally restore the mask to its original state prior to the branch. The compiler
may also insert mask checks to skip over branches when all of the threads have
been deactivated.
Therefore, the best case scenario for a SIMT branch is that it only incurs the
cost of the conditional. The worst case scenario is that some of the warp's
threads fail the conditional and the rest succeed, requiring the program to
execute both paths of the branch back-to-back in the warp. Note that this is
very favorable to the SIMD scenario with non-uniform/varying branches, as SIMT
is able to retain significant parallelism in all cases, whereas SIMD cannot.
## Recommendations
### Don't flatten uniform or constant branches
Uniforms are pipeline variables accessible within a shader which are guaranteed
to not vary during a GPU program's invocation.
Example of a uniform branch in action:
```glsl
uniform struct FrameInfo {
mat4 mvp;
bool invert_y;
} frame_info;
in vec2 position;
void main() {
gl_Position = frame_info.mvp * vec4(position, 0, 1)
if (frame_info.invert_y) {
gl_Position *= vec4(1, -1, 1, 1);
}
}
```
While it's true that driver stacks have the opportunity to generate multiple
pipeline variants ahead of time to handle these branches, this advanced
functionality isn't actually necessary to achieve for good runtime performance
of uniform branches on widely used mobile architectures:
* On SIMT architectures, branching on a uniform means that every thread in every
warp will resolve to the same path, so only one path in the branch will ever
execute.
* On VLIW/SIMD architectures, the compiler can be certain that all of the
elements in the data path for every functional unit will resolve to the same
path, and so it can safely emit fully parallelized instructions for the
contents of the branch!
### Don't flatten simple varying branches
Widely used mobile GPU architectures generally don't benefit from flattening
simple varying branches. While it's true that compilers for VLIW/SIMD-based
architectures can't emit efficient instructions for these branches, the
detrimental effects of this are minimal with small branches. For modern SIMT
architectures, flattened branches can actually perform measurably worse than
straight forward branch solutions. Also, some shader compilers can collapse
small branches automatically.
Instead of this:
```glsl
vec3 ColorBurn(vec3 dst, vec3 src) {
vec3 color = 1 - min(vec3(1), (1 - dst) / src);
color = mix(color, vec3(1), 1 - abs(sign(dst - 1)));
color = mix(color, vec3(0), 1 - abs(sign(src - 0)));
return color;
}
```
...just do this:
```glsl
vec3 ColorBurn(vec3 dst, vec3 src) {
vec3 color = 1 - min(vec3(1), (1 - dst) / src);
if (1 - dst.r < kEhCloseEnough) {
color.r = 1;
}
if (1 - dst.g < kEhCloseEnough) {
color.g = 1;
}
if (1 - dst.b < kEhCloseEnough) {
color.b = 1;
}
if (src.r < kEhCloseEnough) {
color.r = 0;
}
if (src.g < kEhCloseEnough) {
color.g = 0;
}
if (src.b < kEhCloseEnough) {
color.b = 0;
}
return color;
}
```
It's easier to understand, doesn't prevent compiler optimizations, runs
measurably faster on SIMT devices, and works out to be at most marginally slower
on older VLIW devices.
### Avoid complex varying branches
Consider the following fragment shader:
```glsl
in vec4 color;
out vec4 frag_color;
void main() {
vec4 result;
if (color.a == 0) {
result = vec4(0);
} else {
result = DoExtremelyExpensiveThing(color);
}
frag_color = result;
}
```
Note that `color` is _varying_. Specifically, it's an interpolated output from a
vertex shader -- so the value may change from fragment to fragment (as opposed
to a _uniform_ or _constant_, which will remain the same for the whole draw
call).
On SIMT architectures, this branch incurs very little overhead because
`DoExtremelyExpensiveThing` will be skipped over if `color.a == 0` across all
the threads in a given warp.
However, architectures that use instruction-level parallelism (VLIW or SIMD)
can't handle this branch efficiently because the compiler can't safely emit
parallelized instructions on either side of the branch.
To achieve maximum parallelism across all of these architectures, one possible
solution is to unbranch the more complex path:
```glsl
in vec4 color;
out vec4 frag_color;
void main() {
frag_color = DoExtremelyExpensiveThing(color);
if (color.a == 0) {
frag_color = vec4(0);
}
}
```
However, this may be a big tradeoff depending on how this shader is used -- this
solution will perform worse on SIMT devices in cases where `color.a == 0` across
all threads in a given warp, since `DoExtremelyExpensiveThing` will no longer be
skipped with this solution! So if the cheap branch path covers a large solid
portion of a draw call's coverage area, alternative designs may be favorable.
### Beware of return branching
Consider the following glsl function:
```glsl
vec4 FrobnicateColor(vec4 color) {
if (color.a == 0) {
return vec4(0);
}
return DoExtremelyExpensiveThing(color);
}
```
At first glance, this may appear cheap due to its simple contents, but this
branch has two exclusive paths in practice, and the generated shader assembly
will reflect the same behavior as this code:
```glsl
vec4 FrobnicateColor(vec4 color) {
vec4 result;
if (color.a == 0) {
result = vec4(0);
} else {
result = DoExtremelyExpensiveThing(color);
}
return result;
}
```
The same concerns and advice apply to this branch as the scenario under "Avoid
complex varying branches".
### Use lower precision whenever possible
Most desktop GPUs don't support 16 bit (mediump) or 8 bit (lowp) floating point
operations. But many mobile GPUs (such as the Qualcomm Adreno series) do, and
according to the
[Adreno documentation](https://developer.qualcomm.com/sites/default/files/docs/adreno-gpu/developer-guide/gpu/best_practices_shaders.html#use-medium-precision-where-possible),
using lower precision floating point operations is more efficient on these
devices.
| engine/impeller/docs/shader_optimization.md/0 | {
"file_path": "engine/impeller/docs/shader_optimization.md",
"repo_id": "engine",
"token_count": 2908
} | 188 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_COLOR_SOURCE_CONTENTS_H_
#define FLUTTER_IMPELLER_ENTITY_CONTENTS_COLOR_SOURCE_CONTENTS_H_
#include "fml/logging.h"
#include "impeller/entity/contents/clip_contents.h"
#include "impeller/entity/contents/content_context.h"
#include "impeller/entity/contents/contents.h"
#include "impeller/entity/geometry/geometry.h"
#include "impeller/entity/geometry/rect_geometry.h"
#include "impeller/geometry/matrix.h"
namespace impeller {
//------------------------------------------------------------------------------
/// Color sources are geometry-ignostic `Contents` capable of shading any area
/// defined by an `impeller::Geometry`. Conceptually,
/// `impeller::ColorSourceContents` implement a particular color shading
/// behavior.
///
/// This separation of concerns between geometry and color source output allows
/// Impeller to handle most possible draw combinations in a consistent way.
/// For example: There are color sources for handling solid colors, gradients,
/// textures, custom runtime effects, and even 3D scenes.
///
/// There are some special rendering exceptions that deviate from this pattern
/// and cross geometry and color source concerns, such as text atlas and image
/// atlas rendering. Special `Contents` exist for rendering these behaviors
/// which don't implement `ColorSourceContents`.
///
/// @see `impeller::Geometry`
///
class ColorSourceContents : public Contents {
public:
ColorSourceContents();
~ColorSourceContents() override;
//----------------------------------------------------------------------------
/// @brief Set the geometry that this contents will use to render.
///
void SetGeometry(std::shared_ptr<Geometry> geometry);
//----------------------------------------------------------------------------
/// @brief Get the geometry that this contents will use to render.
///
const std::shared_ptr<Geometry>& GetGeometry() const;
//----------------------------------------------------------------------------
/// @brief Set the effect transform for this color source.
///
/// The effect transform is a transform matrix that is applied to
/// the shaded color output and does not impact geometry in any way.
///
/// For example: With repeat tiling, any gradient or
/// `TiledTextureContents` could be used with an effect transform to
/// inexpensively draw an infinite scrolling background pattern.
///
void SetEffectTransform(Matrix matrix);
//----------------------------------------------------------------------------
/// @brief Set the inverted effect transform for this color source.
///
/// When the effect transform is set via `SetEffectTransform`, the
/// value is inverted upon storage. The reason for this is that most
/// color sources internally use the inverted transform.
///
/// @return The inverse of the transform set by `SetEffectTransform`.
///
/// @see `SetEffectTransform`
///
const Matrix& GetInverseEffectTransform() const;
//----------------------------------------------------------------------------
/// @brief Set the opacity factor for this color source.
///
void SetOpacityFactor(Scalar opacity);
//----------------------------------------------------------------------------
/// @brief Get the opacity factor for this color source.
///
/// This value is is factored into the output of the color source in
/// addition to opacity information that may be supplied any other
/// inputs.
///
/// @note If set, the output of this method factors factors in the inherited
/// opacity of this `Contents`.
///
/// @see `Contents::CanInheritOpacity`
///
Scalar GetOpacityFactor() const;
virtual bool IsSolidColor() const;
// |Contents|
std::optional<Rect> GetCoverage(const Entity& entity) const override;
// |Contents|
bool CanInheritOpacity(const Entity& entity) const override;
// |Contents|
void SetInheritedOpacity(Scalar opacity) override;
protected:
using BindFragmentCallback = std::function<bool(RenderPass& pass)>;
using PipelineBuilderMethod = std::shared_ptr<Pipeline<PipelineDescriptor>> (
impeller::ContentContext::*)(ContentContextOptions) const;
using PipelineBuilderCallback =
std::function<std::shared_ptr<Pipeline<PipelineDescriptor>>(
ContentContextOptions)>;
template <typename VertexShaderT>
bool DrawGeometry(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass,
const PipelineBuilderCallback& pipeline_callback,
typename VertexShaderT::FrameInfo frame_info,
const BindFragmentCallback& bind_fragment_callback,
bool enable_uvs = false,
Rect texture_coverage = {},
const Matrix& effect_transform = {}) const {
auto options = OptionsFromPassAndEntity(pass, entity);
GeometryResult::Mode geometry_mode = GetGeometry()->GetResultMode();
Geometry& geometry = *GetGeometry();
const bool is_stencil_then_cover =
geometry_mode == GeometryResult::Mode::kNonZero ||
geometry_mode == GeometryResult::Mode::kEvenOdd;
if (is_stencil_then_cover) {
pass.SetStencilReference(0);
/// Stencil preparation draw.
GeometryResult stencil_geometry_result =
GetGeometry()->GetPositionBuffer(renderer, entity, pass);
pass.SetVertexBuffer(std::move(stencil_geometry_result.vertex_buffer));
options.primitive_type = stencil_geometry_result.type;
options.blend_mode = BlendMode::kDestination;
switch (stencil_geometry_result.mode) {
case GeometryResult::Mode::kNonZero:
pass.SetCommandLabel("Stencil preparation (NonZero)");
options.stencil_mode =
ContentContextOptions::StencilMode::kStencilNonZeroFill;
break;
case GeometryResult::Mode::kEvenOdd:
pass.SetCommandLabel("Stencil preparation (EvenOdd)");
options.stencil_mode =
ContentContextOptions::StencilMode::kStencilEvenOddFill;
break;
default:
FML_UNREACHABLE();
}
pass.SetPipeline(renderer.GetClipPipeline(options));
ClipPipeline::VertexShader::FrameInfo clip_frame_info;
clip_frame_info.depth = entity.GetShaderClipDepth();
clip_frame_info.mvp = stencil_geometry_result.transform;
ClipPipeline::VertexShader::BindFrameInfo(
pass, renderer.GetTransientsBuffer().EmplaceUniform(clip_frame_info));
if (!pass.Draw().ok()) {
return false;
}
/// Cover draw.
options.blend_mode = entity.GetBlendMode();
options.stencil_mode = ContentContextOptions::StencilMode::kCoverCompare;
std::optional<Rect> maybe_cover_area = GetGeometry()->GetCoverage({});
if (!maybe_cover_area.has_value()) {
return true;
}
geometry = RectGeometry(maybe_cover_area.value());
}
GeometryResult geometry_result =
enable_uvs
? geometry.GetPositionUVBuffer(texture_coverage, effect_transform,
renderer, entity, pass)
: geometry.GetPositionBuffer(renderer, entity, pass);
pass.SetVertexBuffer(std::move(geometry_result.vertex_buffer));
options.primitive_type = geometry_result.type;
// Take the pre-populated vertex shader uniform struct and set managed
// values.
frame_info.depth = entity.GetShaderClipDepth();
frame_info.mvp = geometry_result.transform;
// If overdraw prevention is enabled (like when drawing stroke paths), we
// increment the stencil buffer as we draw, preventing overlapping fragments
// from drawing. Afterwards, we need to append another draw call to clean up
// the stencil buffer (happens below in this method).
if (geometry_result.mode == GeometryResult::Mode::kPreventOverdraw) {
options.stencil_mode =
ContentContextOptions::StencilMode::kLegacyClipIncrement;
}
if constexpr (ContentContext::kEnableStencilThenCover) {
pass.SetStencilReference(0);
} else {
pass.SetStencilReference(entity.GetClipDepth());
}
VertexShaderT::BindFrameInfo(
pass, renderer.GetTransientsBuffer().EmplaceUniform(frame_info));
// The reason we need to have a callback mechanism here is that this routine
// may insert draw calls before the main draw call below. For example, for
// sufficiently complex paths we may opt to use stencil-then-cover to avoid
// tessellation.
if (!bind_fragment_callback(pass)) {
return false;
}
pass.SetPipeline(pipeline_callback(options));
if (!pass.Draw().ok()) {
return false;
}
// If we performed overdraw prevention, a subsection of the clip heightmap
// was incremented by 1 in order to self-clip. So simply append a clip
// restore to clean it up.
if (geometry_result.mode == GeometryResult::Mode::kPreventOverdraw) {
auto restore = ClipRestoreContents();
restore.SetRestoreCoverage(GetCoverage(entity));
if constexpr (ContentContext::kEnableStencilThenCover) {
Entity restore_entity = entity.Clone();
restore_entity.SetClipDepth(0);
return restore.Render(renderer, restore_entity, pass);
} else {
return restore.Render(renderer, entity, pass);
}
}
return true;
}
private:
std::shared_ptr<Geometry> geometry_;
Matrix inverse_matrix_;
Scalar opacity_ = 1.0;
Scalar inherited_opacity_ = 1.0;
ColorSourceContents(const ColorSourceContents&) = delete;
ColorSourceContents& operator=(const ColorSourceContents&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_COLOR_SOURCE_CONTENTS_H_
| engine/impeller/entity/contents/color_source_contents.h/0 | {
"file_path": "engine/impeller/entity/contents/color_source_contents.h",
"repo_id": "engine",
"token_count": 3368
} | 189 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/entity/contents/filters/filter_contents.h"
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <memory>
#include <optional>
#include <tuple>
#include <utility>
#include "flutter/fml/logging.h"
#include "impeller/core/formats.h"
#include "impeller/entity/contents/content_context.h"
#include "impeller/entity/contents/filters/border_mask_blur_filter_contents.h"
#include "impeller/entity/contents/filters/gaussian_blur_filter_contents.h"
#include "impeller/entity/contents/filters/inputs/filter_input.h"
#include "impeller/entity/contents/filters/local_matrix_filter_contents.h"
#include "impeller/entity/contents/filters/matrix_filter_contents.h"
#include "impeller/entity/contents/filters/morphology_filter_contents.h"
#include "impeller/entity/contents/filters/yuv_to_rgb_filter_contents.h"
#include "impeller/entity/contents/texture_contents.h"
#include "impeller/entity/entity.h"
#include "impeller/geometry/path_builder.h"
#include "impeller/renderer/command_buffer.h"
#include "impeller/renderer/render_pass.h"
namespace impeller {
const int32_t FilterContents::kBlurFilterRequiredMipCount =
GaussianBlurFilterContents::kBlurFilterRequiredMipCount;
std::shared_ptr<FilterContents> FilterContents::MakeGaussianBlur(
const FilterInput::Ref& input,
Sigma sigma_x,
Sigma sigma_y,
Entity::TileMode tile_mode,
FilterContents::BlurStyle mask_blur_style,
const std::shared_ptr<Geometry>& mask_geometry) {
auto blur = std::make_shared<GaussianBlurFilterContents>(
sigma_x.sigma, sigma_y.sigma, tile_mode, mask_blur_style, mask_geometry);
blur->SetInputs({input});
return blur;
}
std::shared_ptr<FilterContents> FilterContents::MakeBorderMaskBlur(
FilterInput::Ref input,
Sigma sigma_x,
Sigma sigma_y,
BlurStyle blur_style) {
auto filter = std::make_shared<BorderMaskBlurFilterContents>();
filter->SetInputs({std::move(input)});
filter->SetSigma(sigma_x, sigma_y);
filter->SetBlurStyle(blur_style);
return filter;
}
std::shared_ptr<FilterContents> FilterContents::MakeDirectionalMorphology(
FilterInput::Ref input,
Radius radius,
Vector2 direction,
MorphType morph_type) {
auto filter = std::make_shared<DirectionalMorphologyFilterContents>();
filter->SetInputs({std::move(input)});
filter->SetRadius(radius);
filter->SetDirection(direction);
filter->SetMorphType(morph_type);
return filter;
}
std::shared_ptr<FilterContents> FilterContents::MakeMorphology(
FilterInput::Ref input,
Radius radius_x,
Radius radius_y,
MorphType morph_type) {
auto x_morphology = MakeDirectionalMorphology(std::move(input), radius_x,
Point(1, 0), morph_type);
auto y_morphology = MakeDirectionalMorphology(
FilterInput::Make(x_morphology), radius_y, Point(0, 1), morph_type);
return y_morphology;
}
std::shared_ptr<FilterContents> FilterContents::MakeMatrixFilter(
FilterInput::Ref input,
const Matrix& matrix,
const SamplerDescriptor& desc) {
auto filter = std::make_shared<MatrixFilterContents>();
filter->SetInputs({std::move(input)});
filter->SetMatrix(matrix);
filter->SetSamplerDescriptor(desc);
return filter;
}
std::shared_ptr<FilterContents> FilterContents::MakeLocalMatrixFilter(
FilterInput::Ref input,
const Matrix& matrix) {
auto filter = std::make_shared<LocalMatrixFilterContents>();
filter->SetInputs({std::move(input)});
filter->SetMatrix(matrix);
return filter;
}
std::shared_ptr<FilterContents> FilterContents::MakeYUVToRGBFilter(
std::shared_ptr<Texture> y_texture,
std::shared_ptr<Texture> uv_texture,
YUVColorSpace yuv_color_space) {
auto filter = std::make_shared<impeller::YUVToRGBFilterContents>();
filter->SetInputs({impeller::FilterInput::Make(y_texture),
impeller::FilterInput::Make(uv_texture)});
filter->SetYUVColorSpace(yuv_color_space);
return filter;
}
FilterContents::FilterContents() = default;
FilterContents::~FilterContents() = default;
void FilterContents::SetInputs(FilterInput::Vector inputs) {
inputs_ = std::move(inputs);
}
void FilterContents::SetEffectTransform(const Matrix& effect_transform) {
effect_transform_ = effect_transform;
for (auto& input : inputs_) {
input->SetEffectTransform(effect_transform);
}
}
bool FilterContents::Render(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
auto filter_coverage = GetCoverage(entity);
if (!filter_coverage.has_value()) {
return true;
}
// Run the filter.
auto maybe_entity = GetEntity(renderer, entity, GetCoverageHint());
if (!maybe_entity.has_value()) {
return true;
}
maybe_entity->SetNewClipDepth(entity.GetNewClipDepth());
return maybe_entity->Render(renderer, pass);
}
std::optional<Rect> FilterContents::GetLocalCoverage(
const Entity& local_entity) const {
auto coverage = GetFilterCoverage(inputs_, local_entity, effect_transform_);
auto coverage_hint = GetCoverageHint();
if (coverage_hint.has_value() && coverage.has_value()) {
coverage = coverage->Intersection(coverage_hint.value());
}
return coverage;
}
std::optional<Rect> FilterContents::GetCoverage(const Entity& entity) const {
Entity entity_with_local_transform = entity.Clone();
entity_with_local_transform.SetTransform(GetTransform(entity.GetTransform()));
return GetLocalCoverage(entity_with_local_transform);
}
void FilterContents::PopulateGlyphAtlas(
const std::shared_ptr<LazyGlyphAtlas>& lazy_glyph_atlas,
Scalar scale) {
for (auto& input : inputs_) {
input->PopulateGlyphAtlas(lazy_glyph_atlas, scale);
}
}
std::optional<Rect> FilterContents::GetFilterCoverage(
const FilterInput::Vector& inputs,
const Entity& entity,
const Matrix& effect_transform) const {
// The default coverage of FilterContents is just the union of its inputs'
// coverage. FilterContents implementations may choose to adjust this
// coverage depending on the use case.
if (inputs_.empty()) {
return std::nullopt;
}
std::optional<Rect> result;
for (const auto& input : inputs) {
auto coverage = input->GetCoverage(entity);
if (!coverage.has_value()) {
continue;
}
if (!result.has_value()) {
result = coverage;
continue;
}
result = result->Union(coverage.value());
}
return result;
}
std::optional<Rect> FilterContents::GetSourceCoverage(
const Matrix& effect_transform,
const Rect& output_limit) const {
auto filter_input_coverage =
GetFilterSourceCoverage(effect_transform_, output_limit);
if (!filter_input_coverage.has_value()) {
return std::nullopt;
}
std::optional<Rect> inputs_coverage;
for (const auto& input : inputs_) {
auto input_coverage = input->GetSourceCoverage(
effect_transform, filter_input_coverage.value());
if (!input_coverage.has_value()) {
return std::nullopt;
}
inputs_coverage = Rect::Union(inputs_coverage, input_coverage.value());
}
return inputs_coverage;
}
std::optional<Entity> FilterContents::GetEntity(
const ContentContext& renderer,
const Entity& entity,
const std::optional<Rect>& coverage_hint) const {
Entity entity_with_local_transform = entity.Clone();
entity_with_local_transform.SetTransform(GetTransform(entity.GetTransform()));
auto coverage = GetLocalCoverage(entity_with_local_transform);
if (!coverage.has_value() || coverage->IsEmpty()) {
return std::nullopt;
}
return RenderFilter(inputs_, renderer, entity_with_local_transform,
effect_transform_, coverage.value(), coverage_hint);
}
std::optional<Snapshot> FilterContents::RenderToSnapshot(
const ContentContext& renderer,
const Entity& entity,
std::optional<Rect> coverage_limit,
const std::optional<SamplerDescriptor>& sampler_descriptor,
bool msaa_enabled,
int32_t mip_count,
const std::string& label) const {
// Resolve the render instruction (entity) from the filter and render it to a
// snapshot.
if (std::optional<Entity> result =
GetEntity(renderer, entity, coverage_limit);
result.has_value()) {
return result->GetContents()->RenderToSnapshot(
renderer, // renderer
result.value(), // entity
coverage_limit, // coverage_limit
std::nullopt, // sampler_descriptor
true, // msaa_enabled
/*mip_count=*/mip_count,
label); // label
}
return std::nullopt;
}
const FilterContents* FilterContents::AsFilter() const {
return this;
}
Matrix FilterContents::GetLocalTransform(const Matrix& parent_transform) const {
return Matrix();
}
Matrix FilterContents::GetTransform(const Matrix& parent_transform) const {
return parent_transform * GetLocalTransform(parent_transform);
}
bool FilterContents::IsTranslationOnly() const {
for (auto& input : inputs_) {
if (!input->IsTranslationOnly()) {
return false;
}
}
return true;
}
bool FilterContents::IsLeaf() const {
for (auto& input : inputs_) {
if (!input->IsLeaf()) {
return false;
}
}
return true;
}
void FilterContents::SetLeafInputs(const FilterInput::Vector& inputs) {
if (IsLeaf()) {
inputs_ = inputs;
return;
}
for (auto& input : inputs_) {
input->SetLeafInputs(inputs);
}
}
void FilterContents::SetRenderingMode(Entity::RenderingMode rendering_mode) {
for (auto& input : inputs_) {
input->SetRenderingMode(rendering_mode);
}
}
} // namespace impeller
| engine/impeller/entity/contents/filters/filter_contents.cc/0 | {
"file_path": "engine/impeller/entity/contents/filters/filter_contents.cc",
"repo_id": "engine",
"token_count": 3480
} | 190 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/entity/contents/filters/linear_to_srgb_filter_contents.h"
#include "impeller/entity/contents/anonymous_contents.h"
#include "impeller/entity/contents/content_context.h"
#include "impeller/entity/contents/contents.h"
#include "impeller/geometry/point.h"
#include "impeller/renderer/render_pass.h"
#include "impeller/renderer/vertex_buffer_builder.h"
namespace impeller {
LinearToSrgbFilterContents::LinearToSrgbFilterContents() = default;
LinearToSrgbFilterContents::~LinearToSrgbFilterContents() = default;
std::optional<Entity> LinearToSrgbFilterContents::RenderFilter(
const FilterInput::Vector& inputs,
const ContentContext& renderer,
const Entity& entity,
const Matrix& effect_transform,
const Rect& coverage,
const std::optional<Rect>& coverage_hint) const {
if (inputs.empty()) {
return std::nullopt;
}
using VS = LinearToSrgbFilterPipeline::VertexShader;
using FS = LinearToSrgbFilterPipeline::FragmentShader;
auto input_snapshot =
inputs[0]->GetSnapshot("LinearToSrgb", renderer, entity);
if (!input_snapshot.has_value()) {
return std::nullopt;
}
//----------------------------------------------------------------------------
/// Create AnonymousContents for rendering.
///
RenderProc render_proc = [input_snapshot,
absorb_opacity = GetAbsorbOpacity()](
const ContentContext& renderer,
const Entity& entity, RenderPass& pass) -> bool {
pass.SetCommandLabel("Linear to sRGB Filter");
pass.SetStencilReference(entity.GetClipDepth());
auto options = OptionsFromPassAndEntity(pass, entity);
options.primitive_type = PrimitiveType::kTriangleStrip;
pass.SetPipeline(renderer.GetLinearToSrgbFilterPipeline(options));
auto size = input_snapshot->texture->GetSize();
VertexBufferBuilder<VS::PerVertexData> vtx_builder;
vtx_builder.AddVertices({
{Point(0, 0)},
{Point(1, 0)},
{Point(0, 1)},
{Point(1, 1)},
});
auto& host_buffer = renderer.GetTransientsBuffer();
pass.SetVertexBuffer(vtx_builder.CreateVertexBuffer(host_buffer));
VS::FrameInfo frame_info;
frame_info.depth = entity.GetShaderClipDepth();
frame_info.mvp = pass.GetOrthographicTransform() * entity.GetTransform() *
input_snapshot->transform *
Matrix::MakeScale(Vector2(size));
frame_info.texture_sampler_y_coord_scale =
input_snapshot->texture->GetYCoordScale();
FS::FragInfo frag_info;
frag_info.input_alpha =
absorb_opacity == ColorFilterContents::AbsorbOpacity::kYes
? input_snapshot->opacity
: 1.0f;
FS::BindInputTexture(
pass, input_snapshot->texture,
renderer.GetContext()->GetSamplerLibrary()->GetSampler({}));
FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info));
VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info));
return pass.Draw().ok();
};
CoverageProc coverage_proc =
[coverage](const Entity& entity) -> std::optional<Rect> {
return coverage.TransformBounds(entity.GetTransform());
};
auto contents = AnonymousContents::Make(render_proc, coverage_proc);
Entity sub_entity;
sub_entity.SetContents(std::move(contents));
sub_entity.SetClipDepth(entity.GetClipDepth());
sub_entity.SetBlendMode(entity.GetBlendMode());
return sub_entity;
}
} // namespace impeller
| engine/impeller/entity/contents/filters/linear_to_srgb_filter_contents.cc/0 | {
"file_path": "engine/impeller/entity/contents/filters/linear_to_srgb_filter_contents.cc",
"repo_id": "engine",
"token_count": 1377
} | 191 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/testing/testing.h"
#include "impeller/core/host_buffer.h"
#include "impeller/entity/entity_playground.h"
namespace impeller {
namespace testing {
using HostBufferTest = EntityPlayground;
INSTANTIATE_PLAYGROUND_SUITE(HostBufferTest);
TEST_P(HostBufferTest, CanEmplace) {
struct Length2 {
uint8_t pad[2];
};
static_assert(sizeof(Length2) == 2u);
auto buffer = HostBuffer::Create(GetContext()->GetResourceAllocator());
for (size_t i = 0; i < 12500; i++) {
auto view = buffer->Emplace(Length2{});
ASSERT_TRUE(view);
ASSERT_EQ(view.range, Range(i * sizeof(Length2), 2u));
}
}
TEST_P(HostBufferTest, CanEmplaceWithAlignment) {
struct Length2 {
uint8_t pad[2];
};
static_assert(sizeof(Length2) == 2);
struct alignas(16) Align16 {
uint8_t pad[2];
};
static_assert(alignof(Align16) == 16);
static_assert(sizeof(Align16) == 16);
auto buffer = HostBuffer::Create(GetContext()->GetResourceAllocator());
ASSERT_TRUE(buffer);
{
auto view = buffer->Emplace(Length2{});
ASSERT_TRUE(view);
ASSERT_EQ(view.range, Range(0u, 2u));
}
{
auto view = buffer->Emplace(Align16{});
ASSERT_TRUE(view);
ASSERT_EQ(view.range.offset, 16u);
ASSERT_EQ(view.range.length, 16u);
}
{
auto view = buffer->Emplace(Length2{});
ASSERT_TRUE(view);
ASSERT_EQ(view.range, Range(32u, 2u));
}
{
auto view = buffer->Emplace(Align16{});
ASSERT_TRUE(view);
ASSERT_EQ(view.range.offset, 48u);
ASSERT_EQ(view.range.length, 16u);
}
}
TEST_P(HostBufferTest, HostBufferInitialState) {
auto buffer = HostBuffer::Create(GetContext()->GetResourceAllocator());
EXPECT_EQ(buffer->GetStateForTest().current_buffer, 0u);
EXPECT_EQ(buffer->GetStateForTest().current_frame, 0u);
EXPECT_EQ(buffer->GetStateForTest().total_buffer_count, 1u);
}
TEST_P(HostBufferTest, ResetIncrementsFrameCounter) {
auto buffer = HostBuffer::Create(GetContext()->GetResourceAllocator());
EXPECT_EQ(buffer->GetStateForTest().current_frame, 0u);
buffer->Reset();
EXPECT_EQ(buffer->GetStateForTest().current_frame, 1u);
buffer->Reset();
EXPECT_EQ(buffer->GetStateForTest().current_frame, 2u);
buffer->Reset();
EXPECT_EQ(buffer->GetStateForTest().current_frame, 0u);
}
TEST_P(HostBufferTest,
EmplacingLargerThanBlockSizeCreatesOneOffBufferCallback) {
auto buffer = HostBuffer::Create(GetContext()->GetResourceAllocator());
// Emplace an amount larger than the block size, to verify that the host
// buffer does not create a buffer.
auto buffer_view = buffer->Emplace(1024000 + 10, 0, [](uint8_t* data) {});
EXPECT_EQ(buffer->GetStateForTest().current_buffer, 0u);
EXPECT_EQ(buffer->GetStateForTest().current_frame, 0u);
EXPECT_EQ(buffer->GetStateForTest().total_buffer_count, 1u);
}
TEST_P(HostBufferTest, EmplacingLargerThanBlockSizeCreatesOneOffBuffer) {
auto buffer = HostBuffer::Create(GetContext()->GetResourceAllocator());
// Emplace an amount larger than the block size, to verify that the host
// buffer does not create a buffer.
auto buffer_view = buffer->Emplace(nullptr, 1024000 + 10, 0);
EXPECT_EQ(buffer->GetStateForTest().current_buffer, 0u);
EXPECT_EQ(buffer->GetStateForTest().current_frame, 0u);
EXPECT_EQ(buffer->GetStateForTest().total_buffer_count, 1u);
}
TEST_P(HostBufferTest, UnusedBuffersAreDiscardedWhenResetting) {
auto buffer = HostBuffer::Create(GetContext()->GetResourceAllocator());
// Emplace two large allocations to force the allocation of a second buffer.
auto buffer_view_a = buffer->Emplace(1020000, 0, [](uint8_t* data) {});
auto buffer_view_b = buffer->Emplace(1020000, 0, [](uint8_t* data) {});
EXPECT_EQ(buffer->GetStateForTest().current_buffer, 1u);
EXPECT_EQ(buffer->GetStateForTest().total_buffer_count, 2u);
EXPECT_EQ(buffer->GetStateForTest().current_frame, 0u);
// Reset until we get back to this frame.
for (auto i = 0; i < 3; i++) {
buffer->Reset();
}
EXPECT_EQ(buffer->GetStateForTest().current_buffer, 0u);
EXPECT_EQ(buffer->GetStateForTest().total_buffer_count, 2u);
EXPECT_EQ(buffer->GetStateForTest().current_frame, 0u);
// Now when we reset, the buffer should get dropped.
// Reset until we get back to this frame.
for (auto i = 0; i < 3; i++) {
buffer->Reset();
}
EXPECT_EQ(buffer->GetStateForTest().current_buffer, 0u);
EXPECT_EQ(buffer->GetStateForTest().total_buffer_count, 1u);
EXPECT_EQ(buffer->GetStateForTest().current_frame, 0u);
}
TEST_P(HostBufferTest, EmplaceWithProcIsAligned) {
auto buffer = HostBuffer::Create(GetContext()->GetResourceAllocator());
BufferView view = buffer->Emplace(std::array<char, 21>());
EXPECT_EQ(view.range, Range(0, 21));
view = buffer->Emplace(64, 16, [](uint8_t*) {});
EXPECT_EQ(view.range, Range(32, 64));
}
} // namespace testing
} // namespace impeller
| engine/impeller/entity/contents/host_buffer_unittests.cc/0 | {
"file_path": "engine/impeller/entity/contents/host_buffer_unittests.cc",
"repo_id": "engine",
"token_count": 1846
} | 192 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_TEST_CONTENTS_TEST_HELPERS_H_
#define FLUTTER_IMPELLER_ENTITY_CONTENTS_TEST_CONTENTS_TEST_HELPERS_H_
#include "impeller/renderer/command.h"
namespace impeller {
/// @brief Retrieve the [VertInfo] struct data from the provided [command].
template <typename T>
typename T::VertInfo* GetVertInfo(const Command& command) {
auto resource = std::find_if(command.vertex_bindings.buffers.begin(),
command.vertex_bindings.buffers.end(),
[](const BufferAndUniformSlot& data) {
return data.slot.ext_res_0 == 0u;
});
if (resource == command.vertex_bindings.buffers.end()) {
return nullptr;
}
auto data = (resource->view.resource.buffer->OnGetContents() +
resource->view.resource.range.offset);
return reinterpret_cast<typename T::VertInfo*>(data);
}
/// @brief Retrieve the [FragInfo] struct data from the provided [command].
template <typename T>
typename T::FragInfo* GetFragInfo(const Command& command) {
auto resource = std::find_if(command.fragment_bindings.buffers.begin(),
command.fragment_bindings.buffers.end(),
[](const BufferAndUniformSlot& data) {
return data.slot.ext_res_0 == 0u ||
data.slot.binding == 64;
});
if (resource == command.fragment_bindings.buffers.end()) {
return nullptr;
}
auto data = (resource->view.resource.buffer->OnGetContents() +
resource->view.resource.range.offset);
return reinterpret_cast<typename T::FragInfo*>(data);
}
} // namespace impeller
#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_TEST_CONTENTS_TEST_HELPERS_H_
| engine/impeller/entity/contents/test/contents_test_helpers.h/0 | {
"file_path": "engine/impeller/entity/contents/test/contents_test_helpers.h",
"repo_id": "engine",
"token_count": 899
} | 193 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_ENTITY_ENTITY_PASS_H_
#define FLUTTER_IMPELLER_ENTITY_ENTITY_PASS_H_
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <vector>
#include "impeller/entity/contents/contents.h"
#include "impeller/entity/contents/filters/filter_contents.h"
#include "impeller/entity/entity.h"
#include "impeller/entity/entity_pass_delegate.h"
#include "impeller/entity/inline_pass_context.h"
#include "impeller/renderer/render_target.h"
namespace impeller {
class ContentContext;
class EntityPassClipRecorder;
/// Specifies how much to trust the bounds rectangle provided for a list
/// of contents. Used by both |EntityPass| and |Canvas::SaveLayer|.
enum class ContentBoundsPromise {
/// @brief The caller makes no claims related to the size of the bounds.
kUnknown,
/// @brief The caller claims the bounds are a reasonably tight estimate
/// of the coverage of the contents and should contain all of the
/// contents.
kContainsContents,
/// @brief The caller claims the bounds are a subset of an estimate of
/// the reasonably tight bounds but likely clips off some of the
/// contents.
kMayClipContents,
};
class EntityPass {
public:
/// Elements are renderable items in the `EntityPass`. Each can either be an
/// `Entity` or a child `EntityPass`.
///
/// When the element is a child `EntityPass`, it may be rendered to an
/// offscreen texture and converted into an `Entity` that draws the texture
/// into the current pass, or its children may be collapsed into the current
///
/// `EntityPass`. Elements are converted to Entities in
/// `GetEntityForElement()`.
using Element = std::variant<Entity, std::unique_ptr<EntityPass>>;
static const std::string kCaptureDocumentName;
using BackdropFilterProc = std::function<std::shared_ptr<FilterContents>(
FilterInput::Ref,
const Matrix& effect_transform,
Entity::RenderingMode rendering_mode)>;
struct ClipCoverageLayer {
std::optional<Rect> coverage;
size_t clip_depth;
};
using ClipCoverageStack = std::vector<ClipCoverageLayer>;
EntityPass();
~EntityPass();
void SetDelegate(std::shared_ptr<EntityPassDelegate> delgate);
/// @brief Set the bounds limit, which is provided by the user when creating
/// a SaveLayer. This is a hint that allows the user to communicate
/// that it's OK to not render content outside of the bounds.
///
/// For consistency with Skia, we effectively treat this like a
/// rectangle clip by forcing the subpass texture size to never exceed
/// it.
///
/// The entity pass will assume that these bounds cause a clipping
/// effect on the layer unless this call is followed up with a
/// call to |SetBoundsClipsContent()| specifying otherwise.
void SetBoundsLimit(
std::optional<Rect> bounds_limit,
ContentBoundsPromise bounds_promise = ContentBoundsPromise::kUnknown);
/// @brief Get the bounds limit, which is provided by the user when creating
/// a SaveLayer.
std::optional<Rect> GetBoundsLimit() const;
/// @brief Indicates if the bounds limit set using |SetBoundsLimit()|
/// might clip the contents of the pass.
bool GetBoundsLimitMightClipContent() const;
/// @brief Indicates if the bounds limit set using |SetBoundsLimit()|
/// is a reasonably tight estimate of the bounds of the contents.
bool GetBoundsLimitIsSnug() const;
size_t GetSubpassesDepth() const;
/// @brief Add an entity to the current entity pass.
void AddEntity(Entity entity);
void PushClip(Entity entity);
void PopClips(size_t num_clips, uint64_t depth);
void PopAllClips(uint64_t depth);
void SetElements(std::vector<Element> elements);
//----------------------------------------------------------------------------
/// @brief Appends a given pass as a subpass.
///
EntityPass* AddSubpass(std::unique_ptr<EntityPass> pass);
//----------------------------------------------------------------------------
/// @brief Merges a given pass into this pass. Useful for drawing
/// pre-recorded pictures that don't require rendering into a separate
/// subpass.
///
void AddSubpassInline(std::unique_ptr<EntityPass> pass);
EntityPass* GetSuperpass() const;
bool Render(ContentContext& renderer,
const RenderTarget& render_target) const;
/// @brief Iterate all elements (entities and subpasses) in this pass,
/// recursively including elements of child passes. The iteration
/// order is depth-first. Whenever a subpass elements is encountered,
/// it's included in the stream before its children.
void IterateAllElements(const std::function<bool(Element&)>& iterator);
void IterateAllElements(
const std::function<bool(const Element&)>& iterator) const;
//----------------------------------------------------------------------------
/// @brief Iterate all entities in this pass, recursively including entities
/// of child passes. The iteration order is depth-first.
///
void IterateAllEntities(const std::function<bool(Entity&)>& iterator);
//----------------------------------------------------------------------------
/// @brief Iterate all entities in this pass, recursively including entities
/// of child passes. The iteration order is depth-first and does not
/// allow modification of the entities.
///
void IterateAllEntities(
const std::function<bool(const Entity&)>& iterator) const;
//----------------------------------------------------------------------------
/// @brief Iterate entities in this pass up until the first subpass is found.
/// This is useful for limiting look-ahead optimizations.
///
/// @return Returns whether a subpass was encountered.
///
bool IterateUntilSubpass(const std::function<bool(Entity&)>& iterator);
//----------------------------------------------------------------------------
/// @brief Return the number of elements on this pass.
///
size_t GetElementCount() const;
void SetTransform(Matrix transform);
void SetClipDepth(size_t clip_depth);
size_t GetClipDepth() const;
void SetNewClipDepth(size_t clip_depth);
uint32_t GetNewClipDepth() const;
void SetBlendMode(BlendMode blend_mode);
/// @brief Return the premultiplied clear color of the pass entities, if any.
std::optional<Color> GetClearColor(ISize size = ISize::Infinite()) const;
/// @brief Return the premultiplied clear color of the pass entities.
///
/// If the entity pass has no clear color, this will return transparent black.
Color GetClearColorOrDefault(ISize size = ISize::Infinite()) const;
void SetBackdropFilter(BackdropFilterProc proc);
void SetEnableOffscreenCheckerboard(bool enabled);
int32_t GetRequiredMipCount() const { return required_mip_count_; }
void SetRequiredMipCount(int32_t mip_count) {
required_mip_count_ = mip_count;
}
//----------------------------------------------------------------------------
/// @brief Computes the coverage of a given subpass. This is used to
/// determine the texture size of a given subpass before it's rendered
/// to and passed through the subpass ImageFilter, if any.
///
/// @param[in] subpass The EntityPass for which to compute
/// pre-filteredcoverage.
/// @param[in] coverage_limit Confines coverage to a specified area. This
/// hint is used to trim coverage to the root
/// framebuffer area. `std::nullopt` means there
/// is no limit.
///
/// @return The screen space pixel area that the subpass contents will render
/// into, prior to being transformed by the subpass ImageFilter, if
/// any. `std::nullopt` means rendering the subpass will have no
/// effect on the color attachment.
///
std::optional<Rect> GetSubpassCoverage(
const EntityPass& subpass,
std::optional<Rect> coverage_limit) const;
std::optional<Rect> GetElementsCoverage(
std::optional<Rect> coverage_limit) const;
/// Exposed for testing purposes only.
const EntityPassClipRecorder& GetEntityPassClipRecorder() const;
private:
struct EntityResult {
enum Status {
/// The entity was successfully resolved and can be rendered.
kSuccess,
/// An unexpected rendering error occurred while resolving the Entity.
kFailure,
/// The entity should be skipped because rendering it will contribute
/// nothing to the frame.
kSkip,
};
/// @brief The resulting entity that should be rendered. If `std::nullopt`,
/// there is nothing to render.
Entity entity;
/// @brief This is set to `false` if there was an unexpected rendering
/// error while resolving the Entity.
Status status = kFailure;
static EntityResult Success(Entity e) { return {std::move(e), kSuccess}; }
static EntityResult Failure() { return {{}, kFailure}; }
static EntityResult Skip() { return {{}, kSkip}; }
};
bool RenderElement(Entity& element_entity,
size_t clip_depth_floor,
InlinePassContext& pass_context,
int32_t pass_depth,
ContentContext& renderer,
ClipCoverageStack& clip_coverage_stack,
Point global_pass_position) const;
EntityResult GetEntityForElement(const EntityPass::Element& element,
ContentContext& renderer,
Capture& capture,
InlinePassContext& pass_context,
ISize root_pass_size,
Point global_pass_position,
uint32_t pass_depth,
ClipCoverageStack& clip_coverage_stack,
size_t clip_depth_floor) const;
//----------------------------------------------------------------------------
/// @brief OnRender is the internal command recording routine for
/// `EntityPass`. Its job is to walk through each `Element` which
/// was appended to the scene (either an `Entity` via `AddEntity()`
/// or a child `EntityPass` via `AddSubpass()`) and render them to
/// the given `pass_target`.
/// @param[in] renderer The Contents context, which manages
/// pipeline state.
/// @param[in] root_pass_size The size of the texture being
/// rendered into at the root of the
/// `EntityPass` tree. This is the size
/// of the `RenderTarget` color
/// attachment passed to the public
/// `EntityPass::Render` method.
/// @param[out] pass_target Stores the render target that should
/// be used for rendering.
/// @param[in] global_pass_position The position that this `EntityPass`
/// will be drawn to the parent pass
/// relative to the root pass origin.
/// Used for offsetting drawn `Element`s,
/// whose origins are all in root
/// pass/screen space,
/// @param[in] local_pass_position The position that this `EntityPass`
/// will be drawn to the parent pass
/// relative to the parent pass origin.
/// Used for positioning backdrop
/// filters.
/// @param[in] pass_depth The tree depth of the `EntityPass` at
/// render time. Only used for labeling
/// and debugging purposes. This can vary
/// depending on whether passes are
/// collapsed or not.
/// @param[in] clip_coverage_stack A global stack of coverage rectangles
/// for the clip buffer at each depth.
/// Higher depths are more restrictive.
/// Used to cull Elements that we
/// know won't result in a visible
/// change.
/// @param[in] clip_depth_floor The clip depth that a value of
/// zero corresponds to in the given
/// `pass_target` clip buffer.
/// When new `pass_target`s are created
/// for subpasses, their clip buffers are
/// initialized at zero, and so this
/// value is used to offset Entity clip
/// depths to match the clip buffer.
/// @param[in] backdrop_filter_contents Optional. Is supplied, this contents
/// is rendered prior to anything else in
/// the `EntityPass`, offset by the
/// `local_pass_position`.
/// @param[in] collapsed_parent_pass Optional. If supplied, this
/// `InlinePassContext` state is used to
/// begin rendering elements instead of
/// creating a new `RenderPass`. This
/// "collapses" the Elements into the
/// parent pass.
///
bool OnRender(ContentContext& renderer,
Capture& capture,
ISize root_pass_size,
EntityPassTarget& pass_target,
Point global_pass_position,
Point local_pass_position,
uint32_t pass_depth,
ClipCoverageStack& clip_coverage_stack,
size_t clip_depth_floor = 0,
std::shared_ptr<Contents> backdrop_filter_contents = nullptr,
const std::optional<InlinePassContext::RenderPassResult>&
collapsed_parent_pass = std::nullopt) const;
/// The list of renderable items in the scene. Each of these items is
/// evaluated and recorded to an `EntityPassTarget` by the `OnRender` method.
std::vector<Element> elements_;
/// The stack of currently active clips (during Aiks recording time). Each
/// entry is an index into the `elements_` list. The depth value of a clip is
/// the max of all the entities it affects, so assignment of the depth value
/// is deferred until clip restore or end of the EntityPass.
std::vector<size_t> active_clips_;
EntityPass* superpass_ = nullptr;
Matrix transform_;
size_t clip_depth_ = 0u;
uint32_t new_clip_depth_ = 1u;
BlendMode blend_mode_ = BlendMode::kSourceOver;
bool flood_clip_ = false;
bool enable_offscreen_debug_checkerboard_ = false;
std::optional<Rect> bounds_limit_;
ContentBoundsPromise bounds_promise_ = ContentBoundsPromise::kUnknown;
std::unique_ptr<EntityPassClipRecorder> clip_replay_ =
std::make_unique<EntityPassClipRecorder>();
int32_t required_mip_count_ = 1;
/// These values are incremented whenever something is added to the pass that
/// requires reading from the backdrop texture. Currently, this can happen in
/// the following scenarios:
/// 1. An entity with an "advanced blend" is added to the pass.
/// 2. A subpass with a backdrop filter is added to the pass.
/// These are tracked as separate values because we may ignore
/// blend_reads_from_pass_texture_ if the device supports framebuffer based
/// advanced blends.
uint32_t advanced_blend_reads_from_pass_texture_ = 0;
uint32_t backdrop_filter_reads_from_pass_texture_ = 0;
uint32_t GetTotalPassReads(ContentContext& renderer) const;
BackdropFilterProc backdrop_filter_proc_ = nullptr;
std::shared_ptr<EntityPassDelegate> delegate_ =
EntityPassDelegate::MakeDefault();
EntityPass(const EntityPass&) = delete;
EntityPass& operator=(const EntityPass&) = delete;
};
/// @brief A class that tracks all clips that have been recorded in the current
/// entity pass stencil.
///
/// These clips are replayed when restoring the backdrop so that the
/// stencil buffer is left in an identical state.
class EntityPassClipRecorder {
public:
EntityPassClipRecorder();
~EntityPassClipRecorder() = default;
/// @brief Record the entity based on the provided coverage [type].
void RecordEntity(const Entity& entity, Contents::ClipCoverage::Type type);
const std::vector<Entity>& GetReplayEntities() const;
private:
std::vector<Entity> rendered_clip_entities_;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_ENTITY_ENTITY_PASS_H_
| engine/impeller/entity/entity_pass.h/0 | {
"file_path": "engine/impeller/entity/entity_pass.h",
"repo_id": "engine",
"token_count": 6862
} | 194 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/entity/inline_pass_context.h"
#include <utility>
#include "flutter/fml/status.h"
#include "impeller/base/allocation.h"
#include "impeller/base/validation.h"
#include "impeller/core/formats.h"
#include "impeller/entity/contents/content_context.h"
#include "impeller/entity/entity_pass_target.h"
#include "impeller/renderer/command_buffer.h"
#include "impeller/renderer/texture_mipmap.h"
namespace impeller {
InlinePassContext::InlinePassContext(
const ContentContext& renderer,
EntityPassTarget& pass_target,
uint32_t pass_texture_reads,
uint32_t entity_count,
std::optional<RenderPassResult> collapsed_parent_pass)
: renderer_(renderer),
pass_target_(pass_target),
entity_count_(entity_count),
is_collapsed_(collapsed_parent_pass.has_value()) {
if (collapsed_parent_pass.has_value()) {
pass_ = collapsed_parent_pass.value().pass;
}
}
InlinePassContext::~InlinePassContext() {
if (!is_collapsed_) {
EndPass();
}
}
bool InlinePassContext::IsValid() const {
return pass_target_.IsValid();
}
bool InlinePassContext::IsActive() const {
return pass_ != nullptr;
}
std::shared_ptr<Texture> InlinePassContext::GetTexture() {
if (!IsValid()) {
return nullptr;
}
return pass_target_.GetRenderTarget().GetRenderTargetTexture();
}
bool InlinePassContext::EndPass() {
if (!IsActive()) {
return true;
}
FML_DCHECK(command_buffer_);
if (!pass_->EncodeCommands()) {
VALIDATION_LOG << "Failed to encode and submit command buffer while ending "
"render pass.";
return false;
}
const std::shared_ptr<Texture>& target_texture =
GetPassTarget().GetRenderTarget().GetRenderTargetTexture();
if (target_texture->GetMipCount() > 1) {
fml::Status mip_status = AddMipmapGeneration(
command_buffer_, renderer_.GetContext(), target_texture);
if (!mip_status.ok()) {
return false;
}
}
if (!renderer_.GetContext()
->GetCommandQueue()
->Submit({std::move(command_buffer_)})
.ok()) {
return false;
}
pass_ = nullptr;
command_buffer_ = nullptr;
return true;
}
EntityPassTarget& InlinePassContext::GetPassTarget() const {
return pass_target_;
}
InlinePassContext::RenderPassResult InlinePassContext::GetRenderPass(
uint32_t pass_depth) {
if (IsActive()) {
return {.pass = pass_};
}
/// Create a new render pass if one isn't active. This path will run the first
/// time this method is called, but it'll also run if the pass has been
/// previously ended via `EndPass`.
command_buffer_ = renderer_.GetContext()->CreateCommandBuffer();
if (!command_buffer_) {
VALIDATION_LOG << "Could not create command buffer.";
return {};
}
if (pass_target_.GetRenderTarget().GetColorAttachments().empty()) {
VALIDATION_LOG << "Color attachment unexpectedly missing from the "
"EntityPass render target.";
return {};
}
command_buffer_->SetLabel(
"EntityPass Command Buffer: Depth=" + std::to_string(pass_depth) +
" Count=" + std::to_string(pass_count_));
RenderPassResult result;
{
// If the pass target has a resolve texture, then we're using MSAA.
bool is_msaa = pass_target_.GetRenderTarget()
.GetColorAttachments()
.find(0)
->second.resolve_texture != nullptr;
if (pass_count_ > 0 && is_msaa) {
result.backdrop_texture =
pass_target_.Flip(*renderer_.GetContext()->GetResourceAllocator());
if (!result.backdrop_texture) {
VALIDATION_LOG << "Could not flip the EntityPass render target.";
}
}
}
// Find the color attachment a second time, since the target may have just
// flipped.
auto color0 =
pass_target_.GetRenderTarget().GetColorAttachments().find(0)->second;
bool is_msaa = color0.resolve_texture != nullptr;
if (pass_count_ > 0) {
// When MSAA is being used, we end up overriding the entire backdrop by
// drawing the previous pass texture, and so we don't have to clear it and
// can use kDontCare.
color0.load_action = is_msaa ? LoadAction::kDontCare : LoadAction::kLoad;
} else {
color0.load_action = LoadAction::kClear;
}
color0.store_action =
is_msaa ? StoreAction::kMultisampleResolve : StoreAction::kStore;
if (ContentContext::kEnableStencilThenCover) {
auto depth = pass_target_.GetRenderTarget().GetDepthAttachment();
if (!depth.has_value()) {
VALIDATION_LOG << "Depth attachment unexpectedly missing from the "
"EntityPass render target.";
return {};
}
depth->load_action = LoadAction::kClear;
depth->store_action = StoreAction::kDontCare;
pass_target_.target_.SetDepthAttachment(depth.value());
}
auto depth = pass_target_.GetRenderTarget().GetDepthAttachment();
auto stencil = pass_target_.GetRenderTarget().GetStencilAttachment();
if (!depth.has_value() || !stencil.has_value()) {
VALIDATION_LOG << "Stencil/Depth attachment unexpectedly missing from the "
"EntityPass render target.";
return {};
}
stencil->load_action = LoadAction::kClear;
stencil->store_action = StoreAction::kDontCare;
depth->load_action = LoadAction::kClear;
depth->store_action = StoreAction::kDontCare;
pass_target_.target_.SetDepthAttachment(depth);
pass_target_.target_.SetStencilAttachment(stencil.value());
pass_target_.target_.SetColorAttachment(color0, 0);
pass_ = command_buffer_->CreateRenderPass(pass_target_.GetRenderTarget());
if (!pass_) {
VALIDATION_LOG << "Could not create render pass.";
return {};
}
// Commands are fairly large (500B) objects, so re-allocation of the command
// buffer while encoding can add a surprising amount of overhead. We make a
// conservative npot estimate to avoid this case.
pass_->ReserveCommands(Allocation::NextPowerOfTwoSize(entity_count_));
pass_->SetLabel(
"EntityPass Render Pass: Depth=" + std::to_string(pass_depth) +
" Count=" + std::to_string(pass_count_));
result.pass = pass_;
result.just_created = true;
if (!renderer_.GetContext()->GetCapabilities()->SupportsReadFromResolve() &&
result.backdrop_texture ==
result.pass->GetRenderTarget().GetRenderTargetTexture()) {
VALIDATION_LOG << "EntityPass backdrop restore configuration is not valid "
"for the current graphics backend.";
}
++pass_count_;
return result;
}
uint32_t InlinePassContext::GetPassCount() const {
return pass_count_;
}
} // namespace impeller
| engine/impeller/entity/inline_pass_context.cc/0 | {
"file_path": "engine/impeller/entity/inline_pass_context.cc",
"repo_id": "engine",
"token_count": 2451
} | 195 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <impeller/texture.glsl>
#include <impeller/types.glsl>
// Unused, see See PointFieldGeometry::GetPositionBuffer
layout(local_size_x = 16) in;
layout(std430) readonly buffer GeometryData {
// Size of this input data is frame_info.count;
vec2 points[];
}
geometry_data;
layout(std430) writeonly buffer GeometryUVData {
// Size of this output data is frame_info.count;
// x,y is the original geometry.
// u,v is the texture UV.
vec4 points_uv[];
}
geometry_uv_data;
uniform FrameInfo {
uint count;
mat4 effect_transform;
vec2 texture_origin;
vec2 texture_size;
}
frame_info;
vec2 project_point(mat4 m, vec2 v) {
float w = v.x * m[0][3] + v.y * m[1][3] + m[3][3];
vec2 result = vec2(v.x * m[0][0] + v.y * m[1][0] + m[3][0],
v.x * m[0][1] + v.y * m[1][1] + m[3][1]);
// This is Skia's behavior, but it may be reasonable to allow UB for the w=0
// case.
if (w != 0) {
w = 1 / w;
}
return result * w;
}
void main() {
uint ident = gl_GlobalInvocationID.x;
if (ident >= frame_info.count) {
return;
}
vec2 point = geometry_data.points[ident];
vec2 coverage_coords =
(point - frame_info.texture_origin) / frame_info.texture_size;
vec2 texture_coords =
project_point(frame_info.effect_transform, coverage_coords);
geometry_uv_data.points_uv[ident] = vec4(point, texture_coords);
}
| engine/impeller/entity/shaders/geometry/uv.comp/0 | {
"file_path": "engine/impeller/entity/shaders/geometry/uv.comp",
"repo_id": "engine",
"token_count": 601
} | 196 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <impeller/types.glsl>
uniform FrameInfo {
mat4 mvp;
float depth;
}
frame_info;
in vec2 position;
// Note: The GLES backend uses name matching for attribute locations. This name
// must match the name of the attribute input in:
// impeller/compiler/shader_lib/flutter/runtime_effect.glsl
out vec2 _fragCoord;
void main() {
gl_Position = frame_info.mvp * vec4(position, 0.0, 1.0);
gl_Position /= gl_Position.w;
gl_Position.z = frame_info.depth;
_fragCoord = position;
}
| engine/impeller/entity/shaders/runtime_effect.vert/0 | {
"file_path": "engine/impeller/entity/shaders/runtime_effect.vert",
"repo_id": "engine",
"token_count": 220
} | 197 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//flutter/impeller/tools/impeller.gni")
import("//flutter/testing/testing.gni")
impeller_shaders("shader_fixtures") {
name = "fixtures"
# 2.3 adds support for framebuffer fetch in Metal.
metal_version = "2.3"
# Not analyzing because they are not performance critical, and mipmap uses
# textureLod, which uses an extension that malioc does not support.
analyze = false
shaders = [
"array.frag",
"array.vert",
"box_fade.frag",
"box_fade.vert",
"colors.frag",
"colors.vert",
"half.frag",
"impeller.frag",
"impeller.vert",
"inactive_uniforms.frag",
"inactive_uniforms.vert",
"instanced_draw.frag",
"instanced_draw.vert",
"mipmaps.frag",
"mipmaps.vert",
"sample.comp",
"sepia.frag",
"sepia.vert",
"simple.vert",
"stage1.comp",
"stage2.comp",
"swizzle.frag",
"test_texture.frag",
"test_texture.vert",
"texture.frag",
"texture.vert",
]
if (impeller_enable_opengles) {
gles_exclusions = [
"sample.comp",
"stage1.comp",
"stage2.comp",
"half.frag",
]
}
}
scenec("scene_fixtures") {
geometry = [
"flutter_logo_baked.glb",
"two_triangles.glb",
]
type = "gltf"
}
impellerc("runtime_stages") {
shaders = [
"ink_sparkle.frag",
"runtime_stage_example.frag",
"gradient.frag",
]
sl_file_extension = "iplr"
shader_target_flags = [
"--runtime-stage-metal",
"--runtime-stage-gles",
"--runtime-stage-vulkan",
]
iplr = true
}
test_fixtures("file_fixtures") {
fixtures = [
"//flutter/third_party/txt/third_party/fonts/HomemadeApple.ttf",
"//flutter/third_party/txt/third_party/fonts/NotoColorEmoji.ttf",
"//flutter/third_party/txt/third_party/fonts/Roboto-Regular.ttf",
"airplane.jpg",
"bay_bridge.jpg",
"blend_mode_dst.png",
"blend_mode_src.png",
"blue_noise.png",
"boston.jpg",
"embarcadero.jpg",
"flutter_gpu_texture.frag",
"flutter_gpu_texture.vert",
"flutter_gpu_unlit.frag",
"flutter_gpu_unlit.vert",
"flutter_logo_baked.glb",
"kalimba.jpg",
"monkey.png",
"multiple_stages.hlsl",
"nine_patch_corners.png",
"resources_limit.vert",
"sample.comp",
"sample.frag",
"sample.vert",
"sample_with_binding.vert",
"simple.vert.hlsl",
"sa%m#ple.vert",
"stage1.comp",
"stage2.comp",
"struct_def_bug.vert",
"struct_internal.frag",
"table_mountain_nx.png",
"table_mountain_ny.png",
"table_mountain_nz.png",
"table_mountain_px.png",
"table_mountain_py.png",
"table_mountain_pz.png",
"test_texture.frag",
"two_triangles.glb",
"types.h",
"wtf.otf",
"texture_lookup.frag",
]
if (host_os == "mac") {
fixtures += [ "/System/Library/Fonts/Apple Color Emoji.ttc" ]
}
fixtures +=
filter_include(get_target_outputs(":runtime_stages"), [ "*.iplr" ]) +
filter_include(get_target_outputs(":scene_fixtures"), [ "*.ipscene" ])
deps = [
":runtime_stages",
":scene_fixtures",
]
}
impellerc("flutter_gpu_shaders") {
shaders = [
# Temporarily build Flutter GPU test shaders as runtime stages.
"flutter_gpu_unlit.frag",
"flutter_gpu_unlit.vert",
"flutter_gpu_texture.frag",
"flutter_gpu_texture.vert",
]
fixtures = rebase_path("//flutter/impeller/fixtures")
shader_bundle = "{\"UnlitFragment\": {\"type\": \"fragment\", \"file\": \"${fixtures}/flutter_gpu_unlit.frag\"}, \"UnlitVertex\": {\"type\": \"vertex\", \"file\": \"${fixtures}/flutter_gpu_unlit.vert\"}, \"TextureFragment\": {\"type\": \"fragment\", \"file\": \"${fixtures}/flutter_gpu_texture.frag\"}, \"TextureVertex\": {\"type\": \"vertex\", \"file\": \"${fixtures}/flutter_gpu_texture.vert\"}}"
shader_bundle_output = "playground.shaderbundle"
}
test_fixtures("flutter_gpu_fixtures") {
dart_main = "dart_tests.dart"
fixtures = filter_include(get_target_outputs(":flutter_gpu_shaders"),
[
"*.iplr",
"*.shaderbundle",
])
deps = [ ":flutter_gpu_shaders" ]
}
group("fixtures") {
testonly = true
public_deps = [
":file_fixtures",
":scene_fixtures",
":shader_fixtures",
]
}
| engine/impeller/fixtures/BUILD.gn/0 | {
"file_path": "engine/impeller/fixtures/BUILD.gn",
"repo_id": "engine",
"token_count": 2017
} | 198 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
uniform FragInfo {
float lod;
}
frag_info;
uniform sampler2D tex;
in vec2 v_uv;
out vec4 frag_color;
void main() {
frag_color = textureLod(tex, v_uv, frag_info.lod);
}
| engine/impeller/fixtures/mipmaps.frag/0 | {
"file_path": "engine/impeller/fixtures/mipmaps.frag",
"repo_id": "engine",
"token_count": 120
} | 199 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/geometry/matrix.h"
#include <climits>
#include <sstream>
namespace impeller {
Matrix::Matrix(const MatrixDecomposition& d) : Matrix() {
/*
* Apply perspective.
*/
for (int i = 0; i < 4; i++) {
e[i][3] = d.perspective.e[i];
}
/*
* Apply translation.
*/
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
e[3][i] += d.translation.e[j] * e[j][i];
}
}
/*
* Apply rotation.
*/
Matrix rotation;
const auto x = -d.rotation.x;
const auto y = -d.rotation.y;
const auto z = -d.rotation.z;
const auto w = d.rotation.w;
/*
* Construct a composite rotation matrix from the quaternion values.
*/
rotation.e[0][0] = 1.0 - 2.0 * (y * y + z * z);
rotation.e[0][1] = 2.0 * (x * y - z * w);
rotation.e[0][2] = 2.0 * (x * z + y * w);
rotation.e[1][0] = 2.0 * (x * y + z * w);
rotation.e[1][1] = 1.0 - 2.0 * (x * x + z * z);
rotation.e[1][2] = 2.0 * (y * z - x * w);
rotation.e[2][0] = 2.0 * (x * z - y * w);
rotation.e[2][1] = 2.0 * (y * z + x * w);
rotation.e[2][2] = 1.0 - 2.0 * (x * x + y * y);
*this = *this * rotation;
/*
* Apply shear.
*/
Matrix shear;
if (d.shear.e[2] != 0) {
shear.e[2][1] = d.shear.e[2];
*this = *this * shear;
}
if (d.shear.e[1] != 0) {
shear.e[2][1] = 0.0;
shear.e[2][0] = d.shear.e[1];
*this = *this * shear;
}
if (d.shear.e[0] != 0) {
shear.e[2][0] = 0.0;
shear.e[1][0] = d.shear.e[0];
*this = *this * shear;
}
/*
* Apply scale.
*/
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
e[i][j] *= d.scale.e[i];
}
}
}
Matrix Matrix::operator+(const Matrix& o) const {
return Matrix(
m[0] + o.m[0], m[1] + o.m[1], m[2] + o.m[2], m[3] + o.m[3], //
m[4] + o.m[4], m[5] + o.m[5], m[6] + o.m[6], m[7] + o.m[7], //
m[8] + o.m[8], m[9] + o.m[9], m[10] + o.m[10], m[11] + o.m[11], //
m[12] + o.m[12], m[13] + o.m[13], m[14] + o.m[14], m[15] + o.m[15] //
);
}
Matrix Matrix::Invert() const {
Matrix tmp{
m[5] * m[10] * m[15] - m[5] * m[11] * m[14] - m[9] * m[6] * m[15] +
m[9] * m[7] * m[14] + m[13] * m[6] * m[11] - m[13] * m[7] * m[10],
-m[1] * m[10] * m[15] + m[1] * m[11] * m[14] + m[9] * m[2] * m[15] -
m[9] * m[3] * m[14] - m[13] * m[2] * m[11] + m[13] * m[3] * m[10],
m[1] * m[6] * m[15] - m[1] * m[7] * m[14] - m[5] * m[2] * m[15] +
m[5] * m[3] * m[14] + m[13] * m[2] * m[7] - m[13] * m[3] * m[6],
-m[1] * m[6] * m[11] + m[1] * m[7] * m[10] + m[5] * m[2] * m[11] -
m[5] * m[3] * m[10] - m[9] * m[2] * m[7] + m[9] * m[3] * m[6],
-m[4] * m[10] * m[15] + m[4] * m[11] * m[14] + m[8] * m[6] * m[15] -
m[8] * m[7] * m[14] - m[12] * m[6] * m[11] + m[12] * m[7] * m[10],
m[0] * m[10] * m[15] - m[0] * m[11] * m[14] - m[8] * m[2] * m[15] +
m[8] * m[3] * m[14] + m[12] * m[2] * m[11] - m[12] * m[3] * m[10],
-m[0] * m[6] * m[15] + m[0] * m[7] * m[14] + m[4] * m[2] * m[15] -
m[4] * m[3] * m[14] - m[12] * m[2] * m[7] + m[12] * m[3] * m[6],
m[0] * m[6] * m[11] - m[0] * m[7] * m[10] - m[4] * m[2] * m[11] +
m[4] * m[3] * m[10] + m[8] * m[2] * m[7] - m[8] * m[3] * m[6],
m[4] * m[9] * m[15] - m[4] * m[11] * m[13] - m[8] * m[5] * m[15] +
m[8] * m[7] * m[13] + m[12] * m[5] * m[11] - m[12] * m[7] * m[9],
-m[0] * m[9] * m[15] + m[0] * m[11] * m[13] + m[8] * m[1] * m[15] -
m[8] * m[3] * m[13] - m[12] * m[1] * m[11] + m[12] * m[3] * m[9],
m[0] * m[5] * m[15] - m[0] * m[7] * m[13] - m[4] * m[1] * m[15] +
m[4] * m[3] * m[13] + m[12] * m[1] * m[7] - m[12] * m[3] * m[5],
-m[0] * m[5] * m[11] + m[0] * m[7] * m[9] + m[4] * m[1] * m[11] -
m[4] * m[3] * m[9] - m[8] * m[1] * m[7] + m[8] * m[3] * m[5],
-m[4] * m[9] * m[14] + m[4] * m[10] * m[13] + m[8] * m[5] * m[14] -
m[8] * m[6] * m[13] - m[12] * m[5] * m[10] + m[12] * m[6] * m[9],
m[0] * m[9] * m[14] - m[0] * m[10] * m[13] - m[8] * m[1] * m[14] +
m[8] * m[2] * m[13] + m[12] * m[1] * m[10] - m[12] * m[2] * m[9],
-m[0] * m[5] * m[14] + m[0] * m[6] * m[13] + m[4] * m[1] * m[14] -
m[4] * m[2] * m[13] - m[12] * m[1] * m[6] + m[12] * m[2] * m[5],
m[0] * m[5] * m[10] - m[0] * m[6] * m[9] - m[4] * m[1] * m[10] +
m[4] * m[2] * m[9] + m[8] * m[1] * m[6] - m[8] * m[2] * m[5]};
Scalar det =
m[0] * tmp.m[0] + m[1] * tmp.m[4] + m[2] * tmp.m[8] + m[3] * tmp.m[12];
if (det == 0) {
return {};
}
det = 1.0 / det;
return {tmp.m[0] * det, tmp.m[1] * det, tmp.m[2] * det, tmp.m[3] * det,
tmp.m[4] * det, tmp.m[5] * det, tmp.m[6] * det, tmp.m[7] * det,
tmp.m[8] * det, tmp.m[9] * det, tmp.m[10] * det, tmp.m[11] * det,
tmp.m[12] * det, tmp.m[13] * det, tmp.m[14] * det, tmp.m[15] * det};
}
Scalar Matrix::GetDeterminant() const {
auto a00 = e[0][0];
auto a01 = e[0][1];
auto a02 = e[0][2];
auto a03 = e[0][3];
auto a10 = e[1][0];
auto a11 = e[1][1];
auto a12 = e[1][2];
auto a13 = e[1][3];
auto a20 = e[2][0];
auto a21 = e[2][1];
auto a22 = e[2][2];
auto a23 = e[2][3];
auto a30 = e[3][0];
auto a31 = e[3][1];
auto a32 = e[3][2];
auto a33 = e[3][3];
auto b00 = a00 * a11 - a01 * a10;
auto b01 = a00 * a12 - a02 * a10;
auto b02 = a00 * a13 - a03 * a10;
auto b03 = a01 * a12 - a02 * a11;
auto b04 = a01 * a13 - a03 * a11;
auto b05 = a02 * a13 - a03 * a12;
auto b06 = a20 * a31 - a21 * a30;
auto b07 = a20 * a32 - a22 * a30;
auto b08 = a20 * a33 - a23 * a30;
auto b09 = a21 * a32 - a22 * a31;
auto b10 = a21 * a33 - a23 * a31;
auto b11 = a22 * a33 - a23 * a32;
return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
}
Scalar Matrix::GetMaxBasisLength() const {
Scalar max = 0;
for (int i = 0; i < 3; i++) {
max = std::max(max,
e[i][0] * e[i][0] + e[i][1] * e[i][1] + e[i][2] * e[i][2]);
}
return std::sqrt(max);
}
Scalar Matrix::GetMaxBasisLengthXY() const {
Scalar max = 0;
for (int i = 0; i < 3; i++) {
max = std::max(max, e[i][0] * e[i][0] + e[i][1] * e[i][1]);
}
return std::sqrt(max);
}
/*
* Adapted for Impeller from Graphics Gems:
* http://www.realtimerendering.com/resources/GraphicsGems/gemsii/unmatrix.c
*/
std::optional<MatrixDecomposition> Matrix::Decompose() const {
/*
* Normalize the matrix.
*/
Matrix self = *this;
if (self.e[3][3] == 0) {
return std::nullopt;
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
self.e[i][j] /= self.e[3][3];
}
}
/*
* `perspectiveMatrix` is used to solve for perspective, but it also provides
* an easy way to test for singularity of the upper 3x3 component.
*/
Matrix perpectiveMatrix = self;
for (int i = 0; i < 3; i++) {
perpectiveMatrix.e[i][3] = 0;
}
perpectiveMatrix.e[3][3] = 1;
if (perpectiveMatrix.GetDeterminant() == 0.0) {
return std::nullopt;
}
MatrixDecomposition result;
/*
* ==========================================================================
* First, isolate perspective.
* ==========================================================================
*/
if (self.e[0][3] != 0.0 || self.e[1][3] != 0.0 || self.e[2][3] != 0.0) {
/*
* prhs is the right hand side of the equation.
*/
const Vector4 rightHandSide(self.e[0][3], //
self.e[1][3], //
self.e[2][3], //
self.e[3][3]);
/*
* Solve the equation by inverting `perspectiveMatrix` and multiplying
* prhs by the inverse.
*/
result.perspective = perpectiveMatrix.Invert().Transpose() * rightHandSide;
/*
* Clear the perspective partition.
*/
self.e[0][3] = self.e[1][3] = self.e[2][3] = 0;
self.e[3][3] = 1;
}
/*
* ==========================================================================
* Next, the translation.
* ==========================================================================
*/
result.translation = {self.e[3][0], self.e[3][1], self.e[3][2]};
self.e[3][0] = self.e[3][1] = self.e[3][2] = 0.0;
/*
* ==========================================================================
* Next, the scale and shear.
* ==========================================================================
*/
Vector3 row[3];
for (int i = 0; i < 3; i++) {
row[i].x = self.e[i][0];
row[i].y = self.e[i][1];
row[i].z = self.e[i][2];
}
/*
* Compute X scale factor and normalize first row.
*/
result.scale.x = row[0].Length();
row[0] = row[0].Normalize();
/*
* Compute XY shear factor and make 2nd row orthogonal to 1st.
*/
result.shear.xy = row[0].Dot(row[1]);
row[1] = Vector3::Combine(row[1], 1.0, row[0], -result.shear.xy);
/*
* Compute Y scale and normalize 2nd row.
*/
result.scale.y = row[1].Length();
row[1] = row[1].Normalize();
result.shear.xy /= result.scale.y;
/*
* Compute XZ and YZ shears, orthogonalize 3rd row.
*/
result.shear.xz = row[0].Dot(row[2]);
row[2] = Vector3::Combine(row[2], 1.0, row[0], -result.shear.xz);
result.shear.yz = row[1].Dot(row[2]);
row[2] = Vector3::Combine(row[2], 1.0, row[1], -result.shear.yz);
/*
* Next, get Z scale and normalize 3rd row.
*/
result.scale.z = row[2].Length();
row[2] = row[2].Normalize();
result.shear.xz /= result.scale.z;
result.shear.yz /= result.scale.z;
/*
* At this point, the matrix (in rows[]) is orthonormal.
* Check for a coordinate system flip. If the determinant
* is -1, then negate the matrix and the scaling factors.
*/
if (row[0].Dot(row[1].Cross(row[2])) < 0) {
result.scale.x *= -1;
result.scale.y *= -1;
result.scale.z *= -1;
for (int i = 0; i < 3; i++) {
row[i].x *= -1;
row[i].y *= -1;
row[i].z *= -1;
}
}
/*
* ==========================================================================
* Finally, get the rotations out.
* ==========================================================================
*/
result.rotation.x =
0.5 * sqrt(fmax(1.0 + row[0].x - row[1].y - row[2].z, 0.0));
result.rotation.y =
0.5 * sqrt(fmax(1.0 - row[0].x + row[1].y - row[2].z, 0.0));
result.rotation.z =
0.5 * sqrt(fmax(1.0 - row[0].x - row[1].y + row[2].z, 0.0));
result.rotation.w =
0.5 * sqrt(fmax(1.0 + row[0].x + row[1].y + row[2].z, 0.0));
if (row[2].y > row[1].z) {
result.rotation.x = -result.rotation.x;
}
if (row[0].z > row[2].x) {
result.rotation.y = -result.rotation.y;
}
if (row[1].x > row[0].y) {
result.rotation.z = -result.rotation.z;
}
return result;
}
uint64_t MatrixDecomposition::GetComponentsMask() const {
uint64_t mask = 0;
Quaternion noRotation(0.0, 0.0, 0.0, 1.0);
if (rotation != noRotation) {
mask = mask | static_cast<uint64_t>(Component::kRotation);
}
Vector4 defaultPerspective(0.0, 0.0, 0.0, 1.0);
if (perspective != defaultPerspective) {
mask = mask | static_cast<uint64_t>(Component::kPerspective);
}
Shear noShear(0.0, 0.0, 0.0);
if (shear != noShear) {
mask = mask | static_cast<uint64_t>(Component::kShear);
}
Vector3 defaultScale(1.0, 1.0, 1.0);
if (scale != defaultScale) {
mask = mask | static_cast<uint64_t>(Component::kScale);
}
Vector3 defaultTranslation(0.0, 0.0, 0.0);
if (translation != defaultTranslation) {
mask = mask | static_cast<uint64_t>(Component::kTranslation);
}
return mask;
}
} // namespace impeller
| engine/impeller/geometry/matrix.cc/0 | {
"file_path": "engine/impeller/geometry/matrix.cc",
"repo_id": "engine",
"token_count": 6077
} | 200 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/impeller/golden_tests/metal_screenshotter.h"
#include <CoreImage/CoreImage.h>
#include "impeller/renderer/backend/metal/context_mtl.h"
#include "impeller/renderer/backend/metal/texture_mtl.h"
#define GLFW_INCLUDE_NONE
#include "third_party/glfw/include/GLFW/glfw3.h"
namespace impeller {
namespace testing {
MetalScreenshotter::MetalScreenshotter() {
FML_CHECK(::glfwInit() == GLFW_TRUE);
playground_ =
PlaygroundImpl::Create(PlaygroundBackend::kMetal, PlaygroundSwitches{});
}
std::unique_ptr<Screenshot> MetalScreenshotter::MakeScreenshot(
AiksContext& aiks_context,
const Picture& picture,
const ISize& size,
bool scale_content) {
Vector2 content_scale =
scale_content ? playground_->GetContentScale() : Vector2{1, 1};
std::shared_ptr<Image> image = picture.ToImage(
aiks_context,
ISize(size.width * content_scale.x, size.height * content_scale.y));
std::shared_ptr<Texture> texture = image->GetTexture();
id<MTLTexture> metal_texture =
std::static_pointer_cast<TextureMTL>(texture)->GetMTLTexture();
if (metal_texture.pixelFormat != MTLPixelFormatBGRA8Unorm) {
return {};
}
CGColorSpaceRef color_space = CGColorSpaceCreateDeviceRGB();
CIImage* ciImage = [[CIImage alloc]
initWithMTLTexture:metal_texture
options:@{kCIImageColorSpace : (__bridge id)color_space}];
CGColorSpaceRelease(color_space);
FML_CHECK(ciImage);
std::shared_ptr<Context> context = playground_->GetContext();
std::shared_ptr<ContextMTL> context_mtl =
std::static_pointer_cast<ContextMTL>(context);
CIContext* cicontext =
[CIContext contextWithMTLDevice:context_mtl->GetMTLDevice()];
FML_CHECK(context);
CIImage* flipped = [ciImage
imageByApplyingOrientation:kCGImagePropertyOrientationDownMirrored];
CGImageRef cgImage = [cicontext createCGImage:flipped
fromRect:[ciImage extent]];
return std::unique_ptr<MetalScreenshot>(new MetalScreenshot(cgImage));
}
} // namespace testing
} // namespace impeller
| engine/impeller/golden_tests/metal_screenshotter.mm/0 | {
"file_path": "engine/impeller/golden_tests/metal_screenshotter.mm",
"repo_id": "engine",
"token_count": 819
} | 201 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_PLAYGROUND_BACKEND_VULKAN_SWIFTSHADER_UTILITIES_H_
#define FLUTTER_IMPELLER_PLAYGROUND_BACKEND_VULKAN_SWIFTSHADER_UTILITIES_H_
namespace impeller {
//------------------------------------------------------------------------------
/// @brief Find and setup the installable client driver for a locally built
/// SwiftShader at known paths. The option to use SwiftShader can
/// only be used once in the process. While calling this method
/// multiple times is fine, specifying a different use_swiftshader
/// value will trip an assertion.
///
/// @warning This call must be made before any Vulkan contexts are created in
/// the process.
///
/// @param[in] use_swiftshader If SwiftShader should be used.
///
void SetupSwiftshaderOnce(bool use_swiftshader);
} // namespace impeller
#endif // FLUTTER_IMPELLER_PLAYGROUND_BACKEND_VULKAN_SWIFTSHADER_UTILITIES_H_
| engine/impeller/playground/backend/vulkan/swiftshader_utilities.h/0 | {
"file_path": "engine/impeller/playground/backend/vulkan/swiftshader_utilities.h",
"repo_id": "engine",
"token_count": 382
} | 202 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <array>
#include <memory>
#include <optional>
#include <sstream>
#include "fml/time/time_point.h"
#include "impeller/playground/image/backends/skia/compressed_image_skia.h"
#include "impeller/playground/image/decompressed_image.h"
#include "impeller/renderer/command_buffer.h"
#include "impeller/runtime_stage/runtime_stage.h"
#define GLFW_INCLUDE_NONE
#include "third_party/glfw/include/GLFW/glfw3.h"
#include "flutter/fml/paths.h"
#include "impeller/base/validation.h"
#include "impeller/core/allocator.h"
#include "impeller/core/formats.h"
#include "impeller/playground/backend/vulkan/swiftshader_utilities.h"
#include "impeller/playground/image/compressed_image.h"
#include "impeller/playground/imgui/imgui_impl_impeller.h"
#include "impeller/playground/playground.h"
#include "impeller/playground/playground_impl.h"
#include "impeller/renderer/context.h"
#include "impeller/renderer/render_pass.h"
#include "impeller/renderer/renderer.h"
#include "third_party/imgui/backends/imgui_impl_glfw.h"
#include "third_party/imgui/imgui.h"
#if FML_OS_MACOSX
#include "fml/platform/darwin/scoped_nsautorelease_pool.h"
#endif // FML_OS_MACOSX
#if IMPELLER_ENABLE_VULKAN
#include "impeller/playground/backend/vulkan/playground_impl_vk.h"
#endif // IMPELLER_ENABLE_VULKAN
namespace impeller {
std::string PlaygroundBackendToString(PlaygroundBackend backend) {
switch (backend) {
case PlaygroundBackend::kMetal:
return "Metal";
case PlaygroundBackend::kOpenGLES:
return "OpenGLES";
case PlaygroundBackend::kVulkan:
return "Vulkan";
}
FML_UNREACHABLE();
}
static void InitializeGLFWOnce() {
// This guard is a hack to work around a problem where glfwCreateWindow
// hangs when opening a second window after GLFW has been reinitialized (for
// example, when flipping through multiple playground tests).
//
// Explanation:
// * glfwCreateWindow calls [NSApp run], which begins running the event
// loop on the current thread.
// * GLFW then immediately stops the loop when
// applicationDidFinishLaunching is fired.
// * applicationDidFinishLaunching is only ever fired once during the
// application's lifetime, so subsequent calls to [NSApp run] will always
// hang with this setup.
// * glfwInit resets the flag that guards against [NSApp run] being
// called a second time, which causes the subsequent `glfwCreateWindow`
// to hang indefinitely in the event loop, because
// applicationDidFinishLaunching is never fired.
static std::once_flag sOnceInitializer;
std::call_once(sOnceInitializer, []() {
::glfwSetErrorCallback([](int code, const char* description) {
FML_LOG(ERROR) << "GLFW Error '" << description << "' (" << code << ").";
});
FML_CHECK(::glfwInit() == GLFW_TRUE);
});
}
Playground::Playground(PlaygroundSwitches switches) : switches_(switches) {
InitializeGLFWOnce();
SetupSwiftshaderOnce(switches_.use_swiftshader);
}
Playground::~Playground() = default;
std::shared_ptr<Context> Playground::GetContext() const {
return context_;
}
std::shared_ptr<Context> Playground::MakeContext() const {
// Playgrounds are already making a context for each test, so we can just
// return the `context_`.
return context_;
}
bool Playground::SupportsBackend(PlaygroundBackend backend) {
switch (backend) {
case PlaygroundBackend::kMetal:
#if IMPELLER_ENABLE_METAL
return true;
#else // IMPELLER_ENABLE_METAL
return false;
#endif // IMPELLER_ENABLE_METAL
case PlaygroundBackend::kOpenGLES:
#if IMPELLER_ENABLE_OPENGLES
return true;
#else // IMPELLER_ENABLE_OPENGLES
return false;
#endif // IMPELLER_ENABLE_OPENGLES
case PlaygroundBackend::kVulkan:
#if IMPELLER_ENABLE_VULKAN
return PlaygroundImplVK::IsVulkanDriverPresent();
#else // IMPELLER_ENABLE_VULKAN
return false;
#endif // IMPELLER_ENABLE_VULKAN
}
FML_UNREACHABLE();
}
void Playground::SetupContext(PlaygroundBackend backend) {
FML_CHECK(SupportsBackend(backend));
impl_ = PlaygroundImpl::Create(backend, switches_);
if (!impl_) {
FML_LOG(WARNING) << "PlaygroundImpl::Create failed.";
return;
}
context_ = impl_->GetContext();
}
void Playground::SetupWindow() {
if (!context_) {
FML_LOG(WARNING) << "Asked to set up a window with no context (call "
"SetupContext first).";
return;
}
auto renderer = std::make_unique<Renderer>(context_);
if (!renderer->IsValid()) {
return;
}
renderer_ = std::move(renderer);
start_time_ = fml::TimePoint::Now().ToEpochDelta();
}
void Playground::TeardownWindow() {
if (context_) {
context_->Shutdown();
}
context_.reset();
renderer_.reset();
impl_.reset();
}
static std::atomic_bool gShouldOpenNewPlaygrounds = true;
bool Playground::ShouldOpenNewPlaygrounds() {
return gShouldOpenNewPlaygrounds;
}
static void PlaygroundKeyCallback(GLFWwindow* window,
int key,
int scancode,
int action,
int mods) {
if ((key == GLFW_KEY_ESCAPE) && action == GLFW_RELEASE) {
if (mods & (GLFW_MOD_CONTROL | GLFW_MOD_SUPER | GLFW_MOD_SHIFT)) {
gShouldOpenNewPlaygrounds = false;
}
::glfwSetWindowShouldClose(window, GLFW_TRUE);
}
}
Point Playground::GetCursorPosition() const {
return cursor_position_;
}
ISize Playground::GetWindowSize() const {
return window_size_;
}
Point Playground::GetContentScale() const {
return impl_->GetContentScale();
}
Scalar Playground::GetSecondsElapsed() const {
return (fml::TimePoint::Now().ToEpochDelta() - start_time_).ToSecondsF();
}
void Playground::SetCursorPosition(Point pos) {
cursor_position_ = pos;
}
bool Playground::OpenPlaygroundHere(
const Renderer::RenderCallback& render_callback) {
if (!switches_.enable_playground) {
return true;
}
if (!render_callback) {
return true;
}
if (!renderer_ || !renderer_->IsValid()) {
return false;
}
IMGUI_CHECKVERSION();
ImGui::CreateContext();
fml::ScopedCleanupClosure destroy_imgui_context(
[]() { ImGui::DestroyContext(); });
ImGui::StyleColorsDark();
auto& io = ImGui::GetIO();
io.IniFilename = nullptr;
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
io.ConfigWindowsResizeFromEdges = true;
auto window = reinterpret_cast<GLFWwindow*>(impl_->GetWindowHandle());
if (!window) {
return false;
}
::glfwSetWindowTitle(window, GetWindowTitle().c_str());
::glfwSetWindowUserPointer(window, this);
::glfwSetWindowSizeCallback(
window, [](GLFWwindow* window, int width, int height) -> void {
auto playground =
reinterpret_cast<Playground*>(::glfwGetWindowUserPointer(window));
if (!playground) {
return;
}
playground->SetWindowSize(ISize{width, height}.Max({}));
});
::glfwSetKeyCallback(window, &PlaygroundKeyCallback);
::glfwSetCursorPosCallback(window, [](GLFWwindow* window, double x,
double y) {
reinterpret_cast<Playground*>(::glfwGetWindowUserPointer(window))
->SetCursorPosition({static_cast<Scalar>(x), static_cast<Scalar>(y)});
});
ImGui_ImplGlfw_InitForOther(window, true);
fml::ScopedCleanupClosure shutdown_imgui([]() { ImGui_ImplGlfw_Shutdown(); });
ImGui_ImplImpeller_Init(renderer_->GetContext());
fml::ScopedCleanupClosure shutdown_imgui_impeller(
[]() { ImGui_ImplImpeller_Shutdown(); });
ImGui::SetNextWindowPos({10, 10});
::glfwSetWindowSize(window, GetWindowSize().width, GetWindowSize().height);
::glfwSetWindowPos(window, 200, 100);
::glfwShowWindow(window);
while (true) {
#if FML_OS_MACOSX
fml::ScopedNSAutoreleasePool pool;
#endif
::glfwPollEvents();
if (::glfwWindowShouldClose(window)) {
return true;
}
ImGui_ImplGlfw_NewFrame();
Renderer::RenderCallback wrapped_callback =
[render_callback,
&renderer = renderer_](RenderTarget& render_target) -> bool {
ImGui::NewFrame();
ImGui::DockSpaceOverViewport(ImGui::GetMainViewport(),
ImGuiDockNodeFlags_PassthruCentralNode);
bool result = render_callback(render_target);
ImGui::Render();
// Render ImGui overlay.
{
auto buffer = renderer->GetContext()->CreateCommandBuffer();
if (!buffer) {
return false;
}
buffer->SetLabel("ImGui Command Buffer");
if (render_target.GetColorAttachments().empty()) {
return false;
}
auto color0 = render_target.GetColorAttachments().find(0)->second;
color0.load_action = LoadAction::kLoad;
if (color0.resolve_texture) {
color0.texture = color0.resolve_texture;
color0.resolve_texture = nullptr;
color0.store_action = StoreAction::kStore;
}
render_target.SetColorAttachment(color0, 0);
render_target.SetStencilAttachment(std::nullopt);
render_target.SetDepthAttachment(std::nullopt);
auto pass = buffer->CreateRenderPass(render_target);
if (!pass) {
return false;
}
pass->SetLabel("ImGui Render Pass");
ImGui_ImplImpeller_RenderDrawData(ImGui::GetDrawData(), *pass);
pass->EncodeCommands();
if (!renderer->GetContext()->GetCommandQueue()->Submit({buffer}).ok()) {
return false;
}
}
return result;
};
if (!renderer_->Render(impl_->AcquireSurfaceFrame(renderer_->GetContext()),
wrapped_callback)) {
VALIDATION_LOG << "Could not render into the surface.";
return false;
}
if (!ShouldKeepRendering()) {
break;
}
}
::glfwHideWindow(window);
return true;
}
bool Playground::OpenPlaygroundHere(SinglePassCallback pass_callback) {
return OpenPlaygroundHere(
[context = GetContext(), &pass_callback](RenderTarget& render_target) {
auto buffer = context->CreateCommandBuffer();
if (!buffer) {
return false;
}
buffer->SetLabel("Playground Command Buffer");
auto pass = buffer->CreateRenderPass(render_target);
if (!pass) {
return false;
}
pass->SetLabel("Playground Render Pass");
if (!pass_callback(*pass)) {
return false;
}
pass->EncodeCommands();
if (!context->GetCommandQueue()->Submit({buffer}).ok()) {
return false;
}
return true;
});
}
std::shared_ptr<CompressedImage> Playground::LoadFixtureImageCompressed(
std::shared_ptr<fml::Mapping> mapping) {
auto compressed_image = CompressedImageSkia::Create(std::move(mapping));
if (!compressed_image) {
VALIDATION_LOG << "Could not create compressed image.";
return nullptr;
}
return compressed_image;
}
std::optional<DecompressedImage> Playground::DecodeImageRGBA(
const std::shared_ptr<CompressedImage>& compressed) {
if (compressed == nullptr) {
return std::nullopt;
}
// The decoded image is immediately converted into RGBA as that format is
// known to be supported everywhere. For image sources that don't need 32
// bit pixel strides, this is overkill. Since this is a test fixture we
// aren't necessarily trying to eke out memory savings here and instead
// favor simplicity.
auto image = compressed->Decode().ConvertToRGBA();
if (!image.IsValid()) {
VALIDATION_LOG << "Could not decode image.";
return std::nullopt;
}
return image;
}
static std::shared_ptr<Texture> CreateTextureForDecompressedImage(
const std::shared_ptr<Context>& context,
DecompressedImage& decompressed_image,
bool enable_mipmapping) {
auto texture_descriptor = TextureDescriptor{};
texture_descriptor.storage_mode = StorageMode::kHostVisible;
texture_descriptor.format = PixelFormat::kR8G8B8A8UNormInt;
texture_descriptor.size = decompressed_image.GetSize();
texture_descriptor.mip_count =
enable_mipmapping ? decompressed_image.GetSize().MipCount() : 1u;
auto texture =
context->GetResourceAllocator()->CreateTexture(texture_descriptor);
if (!texture) {
VALIDATION_LOG << "Could not allocate texture for fixture.";
return nullptr;
}
auto uploaded = texture->SetContents(decompressed_image.GetAllocation());
if (!uploaded) {
VALIDATION_LOG << "Could not upload texture to device memory for fixture.";
return nullptr;
}
if (enable_mipmapping) {
auto command_buffer = context->CreateCommandBuffer();
if (!command_buffer) {
FML_DLOG(ERROR)
<< "Could not create command buffer for mipmap generation.";
return nullptr;
}
command_buffer->SetLabel("Mipmap Command Buffer");
auto blit_pass = command_buffer->CreateBlitPass();
blit_pass->SetLabel("Mipmap Blit Pass");
blit_pass->GenerateMipmap(texture);
blit_pass->EncodeCommands(context->GetResourceAllocator());
if (!context->GetCommandQueue()->Submit({command_buffer}).ok()) {
FML_DLOG(ERROR) << "Failed to submit blit pass command buffer.";
return nullptr;
}
}
return texture;
}
std::shared_ptr<Texture> Playground::CreateTextureForMapping(
const std::shared_ptr<Context>& context,
std::shared_ptr<fml::Mapping> mapping,
bool enable_mipmapping) {
auto image = Playground::DecodeImageRGBA(
Playground::LoadFixtureImageCompressed(std::move(mapping)));
if (!image.has_value()) {
return nullptr;
}
return CreateTextureForDecompressedImage(context, image.value(),
enable_mipmapping);
}
std::shared_ptr<Texture> Playground::CreateTextureForFixture(
const char* fixture_name,
bool enable_mipmapping) const {
auto texture = CreateTextureForMapping(renderer_->GetContext(),
OpenAssetAsMapping(fixture_name),
enable_mipmapping);
if (texture == nullptr) {
return nullptr;
}
texture->SetLabel(fixture_name);
return texture;
}
std::shared_ptr<Texture> Playground::CreateTextureCubeForFixture(
std::array<const char*, 6> fixture_names) const {
std::array<DecompressedImage, 6> images;
for (size_t i = 0; i < fixture_names.size(); i++) {
auto image = DecodeImageRGBA(
LoadFixtureImageCompressed(OpenAssetAsMapping(fixture_names[i])));
if (!image.has_value()) {
return nullptr;
}
images[i] = image.value();
}
auto texture_descriptor = TextureDescriptor{};
texture_descriptor.storage_mode = StorageMode::kHostVisible;
texture_descriptor.type = TextureType::kTextureCube;
texture_descriptor.format = PixelFormat::kR8G8B8A8UNormInt;
texture_descriptor.size = images[0].GetSize();
texture_descriptor.mip_count = 1u;
auto texture = renderer_->GetContext()->GetResourceAllocator()->CreateTexture(
texture_descriptor);
if (!texture) {
VALIDATION_LOG << "Could not allocate texture cube.";
return nullptr;
}
texture->SetLabel("Texture cube");
for (size_t i = 0; i < fixture_names.size(); i++) {
auto uploaded =
texture->SetContents(images[i].GetAllocation()->GetMapping(),
images[i].GetAllocation()->GetSize(), i);
if (!uploaded) {
VALIDATION_LOG << "Could not upload texture to device memory.";
return nullptr;
}
}
return texture;
}
void Playground::SetWindowSize(ISize size) {
window_size_ = size;
}
bool Playground::ShouldKeepRendering() const {
return true;
}
fml::Status Playground::SetCapabilities(
const std::shared_ptr<Capabilities>& capabilities) {
return impl_->SetCapabilities(capabilities);
}
bool Playground::WillRenderSomething() const {
return switches_.enable_playground;
}
} // namespace impeller
| engine/impeller/playground/playground.cc/0 | {
"file_path": "engine/impeller/playground/playground.cc",
"repo_id": "engine",
"token_count": 6175
} | 203 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_BLIT_COMMAND_GLES_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_BLIT_COMMAND_GLES_H_
#include "impeller/base/backend_cast.h"
#include "impeller/renderer/backend/gles/reactor_gles.h"
#include "impeller/renderer/blit_command.h"
namespace impeller {
/// Mixin for dispatching GLES commands.
struct BlitEncodeGLES : BackendCast<BlitEncodeGLES, BlitCommand> {
virtual ~BlitEncodeGLES();
virtual std::string GetLabel() const = 0;
[[nodiscard]] virtual bool Encode(const ReactorGLES& reactor) const = 0;
};
struct BlitCopyTextureToTextureCommandGLES
: public BlitEncodeGLES,
public BlitCopyTextureToTextureCommand {
~BlitCopyTextureToTextureCommandGLES() override;
std::string GetLabel() const override;
[[nodiscard]] bool Encode(const ReactorGLES& reactor) const override;
};
struct BlitCopyTextureToBufferCommandGLES
: public BlitEncodeGLES,
public BlitCopyTextureToBufferCommand {
~BlitCopyTextureToBufferCommandGLES() override;
std::string GetLabel() const override;
[[nodiscard]] bool Encode(const ReactorGLES& reactor) const override;
};
struct BlitGenerateMipmapCommandGLES : public BlitEncodeGLES,
public BlitGenerateMipmapCommand {
~BlitGenerateMipmapCommandGLES() override;
std::string GetLabel() const override;
[[nodiscard]] bool Encode(const ReactorGLES& reactor) const override;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_BLIT_COMMAND_GLES_H_
| engine/impeller/renderer/backend/gles/blit_command_gles.h/0 | {
"file_path": "engine/impeller/renderer/backend/gles/blit_command_gles.h",
"repo_id": "engine",
"token_count": 621
} | 204 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_FORMATS_GLES_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_FORMATS_GLES_H_
#include <optional>
#include "flutter/fml/logging.h"
#include "flutter/fml/macros.h"
#include "impeller/core/formats.h"
#include "impeller/core/shader_types.h"
#include "impeller/renderer/backend/gles/gles.h"
namespace impeller {
constexpr GLenum ToMode(PrimitiveType primitive_type) {
switch (primitive_type) {
case PrimitiveType::kTriangle:
return GL_TRIANGLES;
case PrimitiveType::kTriangleStrip:
return GL_TRIANGLE_STRIP;
case PrimitiveType::kLine:
return GL_LINES;
case PrimitiveType::kLineStrip:
return GL_LINE_STRIP;
case PrimitiveType::kPoint:
return GL_POINTS;
}
FML_UNREACHABLE();
}
constexpr GLenum ToIndexType(IndexType type) {
switch (type) {
case IndexType::kUnknown:
case IndexType::kNone:
FML_UNREACHABLE();
case IndexType::k16bit:
return GL_UNSIGNED_SHORT;
case IndexType::k32bit:
return GL_UNSIGNED_INT;
}
FML_UNREACHABLE();
}
constexpr GLenum ToStencilOp(StencilOperation op) {
switch (op) {
case StencilOperation::kKeep:
return GL_KEEP;
case StencilOperation::kZero:
return GL_ZERO;
case StencilOperation::kSetToReferenceValue:
return GL_REPLACE;
case StencilOperation::kIncrementClamp:
return GL_INCR;
case StencilOperation::kDecrementClamp:
return GL_DECR;
case StencilOperation::kInvert:
return GL_INVERT;
case StencilOperation::kIncrementWrap:
return GL_INCR_WRAP;
case StencilOperation::kDecrementWrap:
return GL_DECR_WRAP;
}
FML_UNREACHABLE();
}
constexpr GLenum ToCompareFunction(CompareFunction func) {
switch (func) {
case CompareFunction::kNever:
return GL_NEVER;
case CompareFunction::kAlways:
return GL_ALWAYS;
case CompareFunction::kLess:
return GL_LESS;
case CompareFunction::kEqual:
return GL_EQUAL;
case CompareFunction::kLessEqual:
return GL_LEQUAL;
case CompareFunction::kGreater:
return GL_GREATER;
case CompareFunction::kNotEqual:
return GL_NOTEQUAL;
case CompareFunction::kGreaterEqual:
return GL_GEQUAL;
}
FML_UNREACHABLE();
}
constexpr GLenum ToBlendFactor(BlendFactor factor) {
switch (factor) {
case BlendFactor::kZero:
return GL_ZERO;
case BlendFactor::kOne:
return GL_ONE;
case BlendFactor::kSourceColor:
return GL_SRC_COLOR;
case BlendFactor::kOneMinusSourceColor:
return GL_ONE_MINUS_SRC_COLOR;
case BlendFactor::kSourceAlpha:
return GL_SRC_ALPHA;
case BlendFactor::kOneMinusSourceAlpha:
return GL_ONE_MINUS_SRC_ALPHA;
case BlendFactor::kDestinationColor:
return GL_DST_COLOR;
case BlendFactor::kOneMinusDestinationColor:
return GL_ONE_MINUS_DST_COLOR;
case BlendFactor::kDestinationAlpha:
return GL_DST_ALPHA;
case BlendFactor::kOneMinusDestinationAlpha:
return GL_ONE_MINUS_DST_ALPHA;
case BlendFactor::kSourceAlphaSaturated:
return GL_SRC_ALPHA_SATURATE;
case BlendFactor::kBlendColor:
return GL_CONSTANT_COLOR;
case BlendFactor::kOneMinusBlendColor:
return GL_ONE_MINUS_CONSTANT_COLOR;
case BlendFactor::kBlendAlpha:
return GL_CONSTANT_ALPHA;
case BlendFactor::kOneMinusBlendAlpha:
return GL_ONE_MINUS_CONSTANT_ALPHA;
}
FML_UNREACHABLE();
}
constexpr GLenum ToBlendOperation(BlendOperation op) {
switch (op) {
case BlendOperation::kAdd:
return GL_FUNC_ADD;
case BlendOperation::kSubtract:
return GL_FUNC_SUBTRACT;
case BlendOperation::kReverseSubtract:
return GL_FUNC_REVERSE_SUBTRACT;
}
FML_UNREACHABLE();
}
constexpr std::optional<GLenum> ToVertexAttribType(ShaderType type) {
switch (type) {
case ShaderType::kSignedByte:
return GL_BYTE;
case ShaderType::kUnsignedByte:
return GL_UNSIGNED_BYTE;
case ShaderType::kSignedShort:
return GL_SHORT;
case ShaderType::kUnsignedShort:
return GL_UNSIGNED_SHORT;
case ShaderType::kFloat:
return GL_FLOAT;
case ShaderType::kUnknown:
case ShaderType::kVoid:
case ShaderType::kBoolean:
case ShaderType::kSignedInt:
case ShaderType::kUnsignedInt:
case ShaderType::kSignedInt64:
case ShaderType::kUnsignedInt64:
case ShaderType::kAtomicCounter:
case ShaderType::kHalfFloat:
case ShaderType::kDouble:
case ShaderType::kStruct:
case ShaderType::kImage:
case ShaderType::kSampledImage:
case ShaderType::kSampler:
return std::nullopt;
}
FML_UNREACHABLE();
}
constexpr GLenum ToTextureType(TextureType type) {
switch (type) {
case TextureType::kTexture2D:
return GL_TEXTURE_2D;
case TextureType::kTexture2DMultisample:
return GL_TEXTURE_2D_MULTISAMPLE;
case TextureType::kTextureCube:
return GL_TEXTURE_CUBE_MAP;
case TextureType::kTextureExternalOES:
return GL_TEXTURE_EXTERNAL_OES;
}
FML_UNREACHABLE();
}
constexpr std::optional<GLenum> ToTextureTarget(TextureType type) {
switch (type) {
case TextureType::kTexture2D:
return GL_TEXTURE_2D;
case TextureType::kTexture2DMultisample:
return GL_TEXTURE_2D;
case TextureType::kTextureCube:
return GL_TEXTURE_CUBE_MAP;
case TextureType::kTextureExternalOES:
return GL_TEXTURE_EXTERNAL_OES;
}
FML_UNREACHABLE();
}
std::string DebugToFramebufferError(int status);
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_FORMATS_GLES_H_
| engine/impeller/renderer/backend/gles/formats_gles.h/0 | {
"file_path": "engine/impeller/renderer/backend/gles/formats_gles.h",
"repo_id": "engine",
"token_count": 2388
} | 205 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/gles/sampler_gles.h"
#include "impeller/base/validation.h"
#include "impeller/core/formats.h"
#include "impeller/renderer/backend/gles/formats_gles.h"
#include "impeller/renderer/backend/gles/proc_table_gles.h"
#include "impeller/renderer/backend/gles/texture_gles.h"
namespace impeller {
SamplerGLES::SamplerGLES(SamplerDescriptor desc) : Sampler(std::move(desc)) {}
SamplerGLES::~SamplerGLES() = default;
static GLint ToParam(MinMagFilter minmag_filter,
std::optional<MipFilter> mip_filter = std::nullopt) {
if (!mip_filter.has_value()) {
switch (minmag_filter) {
case MinMagFilter::kNearest:
return GL_NEAREST;
case MinMagFilter::kLinear:
return GL_LINEAR;
}
FML_UNREACHABLE();
}
switch (mip_filter.value()) {
case MipFilter::kNearest:
switch (minmag_filter) {
case MinMagFilter::kNearest:
return GL_NEAREST_MIPMAP_NEAREST;
case MinMagFilter::kLinear:
return GL_LINEAR_MIPMAP_NEAREST;
}
case MipFilter::kLinear:
switch (minmag_filter) {
case MinMagFilter::kNearest:
return GL_NEAREST_MIPMAP_LINEAR;
case MinMagFilter::kLinear:
return GL_LINEAR_MIPMAP_LINEAR;
}
}
FML_UNREACHABLE();
}
static GLint ToAddressMode(SamplerAddressMode mode,
bool supports_decal_sampler_address_mode) {
switch (mode) {
case SamplerAddressMode::kClampToEdge:
return GL_CLAMP_TO_EDGE;
case SamplerAddressMode::kRepeat:
return GL_REPEAT;
case SamplerAddressMode::kMirror:
return GL_MIRRORED_REPEAT;
case SamplerAddressMode::kDecal:
if (supports_decal_sampler_address_mode) {
return IMPELLER_GL_CLAMP_TO_BORDER;
} else {
return GL_CLAMP_TO_EDGE;
}
}
FML_UNREACHABLE();
}
bool SamplerGLES::ConfigureBoundTexture(const TextureGLES& texture,
const ProcTableGLES& gl) const {
if (texture.NeedsMipmapGeneration()) {
VALIDATION_LOG
<< "Texture mip count is > 1, but the mipmap has not been generated. "
"Texture can not be sampled safely.";
return false;
}
auto target = ToTextureTarget(texture.GetTextureDescriptor().type);
if (!target.has_value()) {
return false;
}
const auto& desc = GetDescriptor();
std::optional<MipFilter> mip_filter = std::nullopt;
if (texture.GetTextureDescriptor().mip_count > 1) {
mip_filter = desc.mip_filter;
}
gl.TexParameteri(*target, GL_TEXTURE_MIN_FILTER,
ToParam(desc.min_filter, mip_filter));
gl.TexParameteri(*target, GL_TEXTURE_MAG_FILTER, ToParam(desc.mag_filter));
const auto supports_decal_mode =
gl.GetCapabilities()->SupportsDecalSamplerAddressMode();
const auto wrap_s =
ToAddressMode(desc.width_address_mode, supports_decal_mode);
const auto wrap_t =
ToAddressMode(desc.height_address_mode, supports_decal_mode);
gl.TexParameteri(*target, GL_TEXTURE_WRAP_S, wrap_s);
gl.TexParameteri(*target, GL_TEXTURE_WRAP_T, wrap_t);
if (wrap_s == IMPELLER_GL_CLAMP_TO_BORDER ||
wrap_t == IMPELLER_GL_CLAMP_TO_BORDER) {
// Transparent black.
const GLfloat border_color[4] = {0.0f, 0.0f, 0.0f, 0.0f};
gl.TexParameterfv(*target, IMPELLER_GL_TEXTURE_BORDER_COLOR, border_color);
}
return true;
}
} // namespace impeller
| engine/impeller/renderer/backend/gles/sampler_gles.cc/0 | {
"file_path": "engine/impeller/renderer/backend/gles/sampler_gles.cc",
"repo_id": "engine",
"token_count": 1538
} | 206 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/testing/testing.h" // IWYU pragma: keep
#include "gtest/gtest.h"
#include "impeller/renderer/backend/gles/proc_table_gles.h"
#include "impeller/renderer/backend/gles/test/mock_gles.h"
namespace impeller {
namespace testing {
// This test just checks that the proc table is initialized correctly.
//
// If this test doesn't pass, no test that uses the proc table will pass.
TEST(MockGLES, CanInitialize) {
auto mock_gles = MockGLES::Init();
std::string_view vendor(reinterpret_cast<const char*>(
mock_gles->GetProcTable().GetString(GL_VENDOR)));
EXPECT_EQ(vendor, "MockGLES");
}
// Tests we can call two functions and capture the calls.
TEST(MockGLES, CapturesPushAndPopDebugGroup) {
auto mock_gles = MockGLES::Init();
auto& gl = mock_gles->GetProcTable();
gl.PushDebugGroupKHR(GL_DEBUG_SOURCE_APPLICATION_KHR, 0, -1, "test");
gl.PopDebugGroupKHR();
auto calls = mock_gles->GetCapturedCalls();
EXPECT_EQ(calls, std::vector<std::string>(
{"PushDebugGroupKHR", "PopDebugGroupKHR"}));
}
// Tests that if we call a function we have not mocked, it's OK.
TEST(MockGLES, CanCallUnmockedFunction) {
auto mock_gles = MockGLES::Init();
auto& gl = mock_gles->GetProcTable();
gl.DeleteFramebuffers(1, nullptr);
// Test should still complete.
// If we end up mocking DeleteFramebuffers, delete this test.
}
} // namespace testing
} // namespace impeller
| engine/impeller/renderer/backend/gles/test/mock_gles_unittests.cc/0 | {
"file_path": "engine/impeller/renderer/backend/gles/test/mock_gles_unittests.cc",
"repo_id": "engine",
"token_count": 568
} | 207 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_COMPUTE_PASS_MTL_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_COMPUTE_PASS_MTL_H_
#include <Metal/Metal.h>
#include "flutter/fml/macros.h"
#include "impeller/renderer/backend/metal/compute_pass_bindings_cache_mtl.h"
#include "impeller/renderer/compute_pass.h"
#include "impeller/renderer/pipeline_descriptor.h"
namespace impeller {
class ComputePassMTL final : public ComputePass {
public:
// |RenderPass|
~ComputePassMTL() override;
private:
friend class CommandBufferMTL;
id<MTLCommandBuffer> buffer_ = nil;
id<MTLComputeCommandEncoder> encoder_ = nil;
ComputePassBindingsCacheMTL pass_bindings_cache_ =
ComputePassBindingsCacheMTL();
bool is_valid_ = false;
bool has_label_ = false;
ComputePassMTL(std::shared_ptr<const Context> context,
id<MTLCommandBuffer> buffer);
// |ComputePass|
bool IsValid() const override;
// |ComputePass|
fml::Status Compute(const ISize& grid_size) override;
// |ComputePass|
void SetCommandLabel(std::string_view label) override;
// |ComputePass|
void OnSetLabel(const std::string& label) override;
// |ComputePass|
void SetPipeline(const std::shared_ptr<Pipeline<ComputePipelineDescriptor>>&
pipeline) override;
// |ComputePass|
bool BindResource(ShaderStage stage,
DescriptorType type,
const ShaderUniformSlot& slot,
const ShaderMetadata& metadata,
BufferView view) override;
// |ComputePass|
bool BindResource(ShaderStage stage,
DescriptorType type,
const SampledImageSlot& slot,
const ShaderMetadata& metadata,
std::shared_ptr<const Texture> texture,
const std::unique_ptr<const Sampler>& sampler) override;
// |ComputePass|
bool EncodeCommands() const override;
// |ComputePass|
void AddBufferMemoryBarrier() override;
// |ComputePass|
void AddTextureMemoryBarrier() override;
ComputePassMTL(const ComputePassMTL&) = delete;
ComputePassMTL& operator=(const ComputePassMTL&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_COMPUTE_PASS_MTL_H_
| engine/impeller/renderer/backend/metal/compute_pass_mtl.h/0 | {
"file_path": "engine/impeller/renderer/backend/metal/compute_pass_mtl.h",
"repo_id": "engine",
"token_count": 992
} | 208 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_PIPELINE_LIBRARY_MTL_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_PIPELINE_LIBRARY_MTL_H_
#include <Metal/Metal.h>
#include "flutter/fml/macros.h"
#include "impeller/renderer/pipeline_library.h"
namespace impeller {
class ContextMTL;
class PipelineLibraryMTL final : public PipelineLibrary {
public:
PipelineLibraryMTL();
// |PipelineLibrary|
~PipelineLibraryMTL() override;
private:
friend ContextMTL;
id<MTLDevice> device_ = nullptr;
PipelineMap pipelines_;
ComputePipelineMap compute_pipelines_;
explicit PipelineLibraryMTL(id<MTLDevice> device);
// |PipelineLibrary|
bool IsValid() const override;
// |PipelineLibrary|
PipelineFuture<PipelineDescriptor> GetPipeline(
PipelineDescriptor descriptor) override;
// |PipelineLibrary|
PipelineFuture<ComputePipelineDescriptor> GetPipeline(
ComputePipelineDescriptor descriptor) override;
// |PipelineLibrary|
void RemovePipelinesWithEntryPoint(
std::shared_ptr<const ShaderFunction> function) override;
PipelineLibraryMTL(const PipelineLibraryMTL&) = delete;
PipelineLibraryMTL& operator=(const PipelineLibraryMTL&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_PIPELINE_LIBRARY_MTL_H_
| engine/impeller/renderer/backend/metal/pipeline_library_mtl.h/0 | {
"file_path": "engine/impeller/renderer/backend/metal/pipeline_library_mtl.h",
"repo_id": "engine",
"token_count": 516
} | 209 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_TEXTURE_MTL_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_TEXTURE_MTL_H_
#include <Metal/Metal.h>
#include "flutter/fml/macros.h"
#include "impeller/base/backend_cast.h"
#include "impeller/core/texture.h"
namespace impeller {
class TextureMTL final : public Texture,
public BackendCast<TextureMTL, Texture> {
public:
/// @brief This callback needs to always return the same texture when called
/// multiple times.
using AcquireTextureProc = std::function<id<MTLTexture>()>;
TextureMTL(TextureDescriptor desc,
const AcquireTextureProc& aquire_proc,
bool wrapped = false,
bool drawable = false);
static std::shared_ptr<TextureMTL> Wrapper(
TextureDescriptor desc,
id<MTLTexture> texture,
std::function<void()> deletion_proc = nullptr);
static std::shared_ptr<TextureMTL> Create(TextureDescriptor desc,
id<MTLTexture> texture);
// |Texture|
~TextureMTL() override;
id<MTLTexture> GetMTLTexture() const;
bool IsWrapped() const;
/// @brief Whether or not this texture is wrapping a Metal drawable.
bool IsDrawable() const;
// |Texture|
bool IsValid() const override;
bool GenerateMipmap(id<MTLBlitCommandEncoder> encoder);
private:
AcquireTextureProc aquire_proc_ = {};
bool is_valid_ = false;
bool is_wrapped_ = false;
bool is_drawable_ = false;
// |Texture|
void SetLabel(std::string_view label) override;
// |Texture|
bool OnSetContents(const uint8_t* contents,
size_t length,
size_t slice) override;
// |Texture|
bool OnSetContents(std::shared_ptr<const fml::Mapping> mapping,
size_t slice) override;
// |Texture|
ISize GetSize() const override;
TextureMTL(const TextureMTL&) = delete;
TextureMTL& operator=(const TextureMTL&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_TEXTURE_MTL_H_
| engine/impeller/renderer/backend/metal/texture_mtl.h/0 | {
"file_path": "engine/impeller/renderer/backend/metal/texture_mtl.h",
"repo_id": "engine",
"token_count": 876
} | 210 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_BLIT_COMMAND_VK_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_BLIT_COMMAND_VK_H_
#include <memory>
#include "impeller/base/backend_cast.h"
#include "impeller/renderer/backend/vulkan/context_vk.h"
#include "impeller/renderer/blit_command.h"
#include "impeller/renderer/context.h"
namespace impeller {
class CommandEncoderVK;
// TODO(csg): Should these be backend castable to blit command?
/// Mixin for dispatching Vulkan commands.
struct BlitEncodeVK : BackendCast<BlitEncodeVK, BlitCommand> {
virtual ~BlitEncodeVK();
virtual std::string GetLabel() const = 0;
[[nodiscard]] virtual bool Encode(CommandEncoderVK& encoder) const = 0;
};
struct BlitCopyTextureToTextureCommandVK
: public BlitCopyTextureToTextureCommand,
public BlitEncodeVK {
~BlitCopyTextureToTextureCommandVK() override;
std::string GetLabel() const override;
[[nodiscard]] bool Encode(CommandEncoderVK& encoder) const override;
};
struct BlitCopyTextureToBufferCommandVK : public BlitCopyTextureToBufferCommand,
public BlitEncodeVK {
~BlitCopyTextureToBufferCommandVK() override;
std::string GetLabel() const override;
[[nodiscard]] bool Encode(CommandEncoderVK& encoder) const override;
};
struct BlitCopyBufferToTextureCommandVK : public BlitCopyBufferToTextureCommand,
public BlitEncodeVK {
~BlitCopyBufferToTextureCommandVK() override;
std::string GetLabel() const override;
[[nodiscard]] bool Encode(CommandEncoderVK& encoder) const override;
};
struct BlitGenerateMipmapCommandVK : public BlitGenerateMipmapCommand,
public BlitEncodeVK {
~BlitGenerateMipmapCommandVK() override;
std::string GetLabel() const override;
[[nodiscard]] bool Encode(CommandEncoderVK& encoder) const override;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_BLIT_COMMAND_VK_H_
| engine/impeller/renderer/backend/vulkan/blit_command_vk.h/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/blit_command_vk.h",
"repo_id": "engine",
"token_count": 808
} | 211 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/compute_pass_vk.h"
#include "impeller/renderer/backend/vulkan/command_buffer_vk.h"
#include "impeller/renderer/backend/vulkan/compute_pipeline_vk.h"
#include "impeller/renderer/backend/vulkan/formats_vk.h"
#include "impeller/renderer/backend/vulkan/sampler_vk.h"
#include "impeller/renderer/backend/vulkan/texture_vk.h"
#include "vulkan/vulkan_structs.hpp"
namespace impeller {
ComputePassVK::ComputePassVK(std::shared_ptr<const Context> context,
std::shared_ptr<CommandBufferVK> command_buffer)
: ComputePass(std::move(context)),
command_buffer_(std::move(command_buffer)) {
// TOOD(dnfield): This should be moved to caps. But for now keeping this
// in parallel with Metal.
max_wg_size_ = ContextVK::Cast(*context_)
.GetPhysicalDevice()
.getProperties()
.limits.maxComputeWorkGroupSize;
is_valid_ = true;
}
ComputePassVK::~ComputePassVK() = default;
bool ComputePassVK::IsValid() const {
return is_valid_;
}
void ComputePassVK::OnSetLabel(const std::string& label) {
if (label.empty()) {
return;
}
label_ = label;
}
// |RenderPass|
void ComputePassVK::SetCommandLabel(std::string_view label) {
#ifdef IMPELLER_DEBUG
command_buffer_->GetEncoder()->PushDebugGroup(label);
has_label_ = true;
#endif // IMPELLER_DEBUG
}
// |ComputePass|
void ComputePassVK::SetPipeline(
const std::shared_ptr<Pipeline<ComputePipelineDescriptor>>& pipeline) {
const auto& pipeline_vk = ComputePipelineVK::Cast(*pipeline);
const vk::CommandBuffer& command_buffer_vk =
command_buffer_->GetEncoder()->GetCommandBuffer();
command_buffer_vk.bindPipeline(vk::PipelineBindPoint::eCompute,
pipeline_vk.GetPipeline());
pipeline_layout_ = pipeline_vk.GetPipelineLayout();
auto descriptor_result =
command_buffer_->GetEncoder()->AllocateDescriptorSets(
pipeline_vk.GetDescriptorSetLayout(), ContextVK::Cast(*context_));
if (!descriptor_result.ok()) {
return;
}
descriptor_set_ = descriptor_result.value();
pipeline_valid_ = true;
}
// |ComputePass|
fml::Status ComputePassVK::Compute(const ISize& grid_size) {
if (grid_size.IsEmpty() || !pipeline_valid_) {
bound_image_offset_ = 0u;
bound_buffer_offset_ = 0u;
descriptor_write_offset_ = 0u;
has_label_ = false;
pipeline_valid_ = false;
return fml::Status(fml::StatusCode::kCancelled,
"Invalid pipeline or empty grid.");
}
const ContextVK& context_vk = ContextVK::Cast(*context_);
for (auto i = 0u; i < descriptor_write_offset_; i++) {
write_workspace_[i].dstSet = descriptor_set_;
}
context_vk.GetDevice().updateDescriptorSets(descriptor_write_offset_,
write_workspace_.data(), 0u, {});
const vk::CommandBuffer& command_buffer_vk =
command_buffer_->GetEncoder()->GetCommandBuffer();
command_buffer_vk.bindDescriptorSets(
vk::PipelineBindPoint::eCompute, // bind point
pipeline_layout_, // layout
0, // first set
1, // set count
&descriptor_set_, // sets
0, // offset count
nullptr // offsets
);
int64_t width = grid_size.width;
int64_t height = grid_size.height;
// Special case for linear processing.
if (height == 1) {
command_buffer_vk.dispatch(width, 1, 1);
} else {
while (width > max_wg_size_[0]) {
width = std::max(static_cast<int64_t>(1), width / 2);
}
while (height > max_wg_size_[1]) {
height = std::max(static_cast<int64_t>(1), height / 2);
}
command_buffer_vk.dispatch(width, height, 1);
}
#ifdef IMPELLER_DEBUG
if (has_label_) {
command_buffer_->GetEncoder()->PopDebugGroup();
}
has_label_ = false;
#endif // IMPELLER_DEBUG
bound_image_offset_ = 0u;
bound_buffer_offset_ = 0u;
descriptor_write_offset_ = 0u;
has_label_ = false;
pipeline_valid_ = false;
return fml::Status();
}
// |ResourceBinder|
bool ComputePassVK::BindResource(ShaderStage stage,
DescriptorType type,
const ShaderUniformSlot& slot,
const ShaderMetadata& metadata,
BufferView view) {
return BindResource(slot.binding, type, view);
}
// |ResourceBinder|
bool ComputePassVK::BindResource(
ShaderStage stage,
DescriptorType type,
const SampledImageSlot& slot,
const ShaderMetadata& metadata,
std::shared_ptr<const Texture> texture,
const std::unique_ptr<const Sampler>& sampler) {
if (bound_image_offset_ >= kMaxBindings) {
return false;
}
if (!texture->IsValid() || !sampler) {
return false;
}
const TextureVK& texture_vk = TextureVK::Cast(*texture);
const SamplerVK& sampler_vk = SamplerVK::Cast(*sampler);
if (!command_buffer_->GetEncoder()->Track(texture)) {
return false;
}
vk::DescriptorImageInfo image_info;
image_info.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
image_info.sampler = sampler_vk.GetSampler();
image_info.imageView = texture_vk.GetImageView();
image_workspace_[bound_image_offset_++] = image_info;
vk::WriteDescriptorSet write_set;
write_set.dstBinding = slot.binding;
write_set.descriptorCount = 1u;
write_set.descriptorType = ToVKDescriptorType(type);
write_set.pImageInfo = &image_workspace_[bound_image_offset_ - 1];
write_workspace_[descriptor_write_offset_++] = write_set;
return true;
}
bool ComputePassVK::BindResource(size_t binding,
DescriptorType type,
const BufferView& view) {
if (bound_buffer_offset_ >= kMaxBindings) {
return false;
}
const std::shared_ptr<const DeviceBuffer>& device_buffer = view.buffer;
auto buffer = DeviceBufferVK::Cast(*device_buffer).GetBuffer();
if (!buffer) {
return false;
}
if (!command_buffer_->GetEncoder()->Track(device_buffer)) {
return false;
}
uint32_t offset = view.range.offset;
vk::DescriptorBufferInfo buffer_info;
buffer_info.buffer = buffer;
buffer_info.offset = offset;
buffer_info.range = view.range.length;
buffer_workspace_[bound_buffer_offset_++] = buffer_info;
vk::WriteDescriptorSet write_set;
write_set.dstBinding = binding;
write_set.descriptorCount = 1u;
write_set.descriptorType = ToVKDescriptorType(type);
write_set.pBufferInfo = &buffer_workspace_[bound_buffer_offset_ - 1];
write_workspace_[descriptor_write_offset_++] = write_set;
return true;
}
// Note:
// https://github.com/KhronosGroup/Vulkan-Docs/wiki/Synchronization-Examples
// Seems to suggest that anything more finely grained than a global memory
// barrier is likely to be weakened into a global barrier. Confirming this on
// mobile devices will require some experimentation.
// |ComputePass|
void ComputePassVK::AddBufferMemoryBarrier() {
vk::MemoryBarrier barrier;
barrier.srcAccessMask = vk::AccessFlagBits::eShaderWrite;
barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead;
command_buffer_->GetEncoder()->GetCommandBuffer().pipelineBarrier(
vk::PipelineStageFlagBits::eComputeShader,
vk::PipelineStageFlagBits::eComputeShader, {}, 1, &barrier, 0, {}, 0, {});
}
// |ComputePass|
void ComputePassVK::AddTextureMemoryBarrier() {
vk::MemoryBarrier barrier;
barrier.srcAccessMask = vk::AccessFlagBits::eShaderWrite;
barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead;
command_buffer_->GetEncoder()->GetCommandBuffer().pipelineBarrier(
vk::PipelineStageFlagBits::eComputeShader,
vk::PipelineStageFlagBits::eComputeShader, {}, 1, &barrier, 0, {}, 0, {});
}
// |ComputePass|
bool ComputePassVK::EncodeCommands() const {
// Since we only use global memory barrier, we don't have to worry about
// compute to compute dependencies across cmd buffers. Instead, we pessimize
// here and assume that we wrote to a storage image or buffer and that a
// render pass will read from it. if there are ever scenarios where we end up
// with compute to compute dependencies this should be revisited.
// This does not currently handle image barriers as we do not use them
// for anything.
vk::MemoryBarrier barrier;
barrier.srcAccessMask = vk::AccessFlagBits::eShaderWrite;
barrier.dstAccessMask =
vk::AccessFlagBits::eIndexRead | vk::AccessFlagBits::eVertexAttributeRead;
command_buffer_->GetEncoder()->GetCommandBuffer().pipelineBarrier(
vk::PipelineStageFlagBits::eComputeShader,
vk::PipelineStageFlagBits::eVertexInput, {}, 1, &barrier, 0, {}, 0, {});
return true;
}
} // namespace impeller
| engine/impeller/renderer/backend/vulkan/compute_pass_vk.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/compute_pass_vk.cc",
"repo_id": "engine",
"token_count": 3596
} | 212 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DRIVER_INFO_VK_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DRIVER_INFO_VK_H_
#include "impeller/base/version.h"
#include "impeller/renderer/backend/vulkan/vk.h"
namespace impeller {
enum class VendorVK {
kUnknown,
//----------------------------------------------------------------------------
/// Includes the SwiftShader CPU implementation.
///
kGoogle,
kQualcomm,
kARM,
kImgTec,
kPowerVR = kImgTec,
kAMD,
kNvidia,
kIntel,
//----------------------------------------------------------------------------
/// Includes the LLVM Pipe CPU implementation.
///
kMesa,
//----------------------------------------------------------------------------
/// Includes Vulkan on Metal via MoltenVK.
///
kApple,
};
enum class DeviceTypeVK {
kUnknown,
//----------------------------------------------------------------------------
/// The device is an integrated GPU. Typically mobile GPUs.
///
kIntegratedGPU,
//----------------------------------------------------------------------------
/// The device is a discrete GPU. Typically desktop GPUs.
///
kDiscreteGPU,
//----------------------------------------------------------------------------
/// The device is a GPU in a virtualized environment.
///
kVirtualGPU,
//----------------------------------------------------------------------------
/// There is no GPU. Vulkan is implemented on the CPU. This is typically
/// emulators like SwiftShader and LLVMPipe.
///
kCPU,
};
//------------------------------------------------------------------------------
/// @brief Get information about the Vulkan driver.
///
/// @warning Be extremely cautious about the information reported here. This
/// is self-reported information (by the driver) and may be
/// inaccurate and or inconsistent.
///
/// Before gating features behind any of the information reported by
/// the driver, consider alternatives (extensions checks perhaps)
/// and try to get a reviewer buddy to convince you to avoid using
/// this.
///
class DriverInfoVK {
public:
explicit DriverInfoVK(const vk::PhysicalDevice& device);
~DriverInfoVK();
DriverInfoVK(const DriverInfoVK&) = delete;
DriverInfoVK& operator=(const DriverInfoVK&) = delete;
//----------------------------------------------------------------------------
/// @brief Gets the Vulkan API version. Should be at or above Vulkan 1.1
/// which is the Impeller baseline.
///
/// @return The Vulkan API version.
///
const Version& GetAPIVersion() const;
//----------------------------------------------------------------------------
/// @brief Get the vendor of the Vulkan implementation. This is a broad
/// check and includes multiple drivers and platforms.
///
/// @return The vendor.
///
const VendorVK& GetVendor() const;
//----------------------------------------------------------------------------
/// @brief Get the device type. Typical use might be to check if the
/// device is a CPU implementation.
///
/// @return The device type.
///
const DeviceTypeVK& GetDeviceType() const;
//----------------------------------------------------------------------------
/// @brief Get the self-reported name of the graphics driver.
///
/// @return The driver name.
///
const std::string& GetDriverName() const;
private:
bool is_valid_ = false;
Version api_version_;
VendorVK vendor_ = VendorVK::kUnknown;
DeviceTypeVK type_ = DeviceTypeVK::kUnknown;
std::string driver_name_;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DRIVER_INFO_VK_H_
| engine/impeller/renderer/backend/vulkan/driver_info_vk.h/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/driver_info_vk.h",
"repo_id": "engine",
"token_count": 1100
} | 213 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/queue_vk.h"
#include "impeller/renderer/backend/vulkan/context_vk.h"
namespace impeller {
QueueVK::QueueVK(QueueIndexVK index, vk::Queue queue)
: index_(index), queue_(queue) {}
QueueVK::~QueueVK() = default;
const QueueIndexVK& QueueVK::GetIndex() const {
return index_;
}
vk::Result QueueVK::Submit(const vk::SubmitInfo& submit_info,
const vk::Fence& fence) const {
Lock lock(queue_mutex_);
return queue_.submit(submit_info, fence);
}
vk::Result QueueVK::Present(const vk::PresentInfoKHR& present_info) {
Lock lock(queue_mutex_);
return queue_.presentKHR(present_info);
}
void QueueVK::InsertDebugMarker(std::string_view label) const {
if (!HasValidationLayers()) {
return;
}
vk::DebugUtilsLabelEXT label_info;
label_info.pLabelName = label.data();
Lock lock(queue_mutex_);
queue_.insertDebugUtilsLabelEXT(label_info);
}
QueuesVK::QueuesVK() = default;
QueuesVK::QueuesVK(const vk::Device& device,
QueueIndexVK graphics,
QueueIndexVK compute,
QueueIndexVK transfer) {
auto vk_graphics = device.getQueue(graphics.family, graphics.index);
auto vk_compute = device.getQueue(compute.family, compute.index);
auto vk_transfer = device.getQueue(transfer.family, transfer.index);
// Always set up the graphics queue.
graphics_queue = std::make_shared<QueueVK>(graphics, vk_graphics);
ContextVK::SetDebugName(device, vk_graphics, "ImpellerGraphicsQ");
// Setup the compute queue if its different from the graphics queue.
if (compute == graphics) {
compute_queue = graphics_queue;
} else {
compute_queue = std::make_shared<QueueVK>(compute, vk_compute);
ContextVK::SetDebugName(device, vk_compute, "ImpellerComputeQ");
}
// Setup the transfer queue if its different from the graphics or compute
// queues.
if (transfer == graphics) {
transfer_queue = graphics_queue;
} else if (transfer == compute) {
transfer_queue = compute_queue;
} else {
transfer_queue = std::make_shared<QueueVK>(transfer, vk_transfer);
ContextVK::SetDebugName(device, vk_transfer, "ImpellerTransferQ");
}
}
bool QueuesVK::IsValid() const {
return graphics_queue && compute_queue && transfer_queue;
}
} // namespace impeller
| engine/impeller/renderer/backend/vulkan/queue_vk.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/queue_vk.cc",
"repo_id": "engine",
"token_count": 894
} | 214 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/shader_library_vk.h"
#include <cstdint>
#include "flutter/fml/logging.h"
#include "flutter/fml/trace_event.h"
#include "impeller/renderer/backend/vulkan/context_vk.h"
#include "impeller/renderer/backend/vulkan/shader_function_vk.h"
#include "impeller/shader_archive/multi_arch_shader_archive.h"
#include "impeller/shader_archive/shader_archive.h"
namespace impeller {
static ShaderStage ToShaderStage(ArchiveShaderType type) {
switch (type) {
case ArchiveShaderType::kVertex:
return ShaderStage::kVertex;
case ArchiveShaderType::kFragment:
return ShaderStage::kFragment;
case ArchiveShaderType::kCompute:
return ShaderStage::kCompute;
}
FML_UNREACHABLE();
}
static std::string VKShaderNameToShaderKeyName(const std::string& name,
ShaderStage stage) {
std::stringstream stream;
stream << name;
switch (stage) {
case ShaderStage::kUnknown:
stream << "_unknown_";
break;
case ShaderStage::kVertex:
stream << "_vertex_";
break;
case ShaderStage::kFragment:
stream << "_fragment_";
break;
case ShaderStage::kCompute:
stream << "_compute_";
break;
}
stream << "main";
return stream.str();
}
ShaderLibraryVK::ShaderLibraryVK(
std::weak_ptr<DeviceHolderVK> device_holder,
const std::vector<std::shared_ptr<fml::Mapping>>& shader_libraries_data)
: device_holder_(std::move(device_holder)) {
TRACE_EVENT0("impeller", "CreateShaderLibrary");
bool success = true;
auto iterator = [&](auto type, //
const auto& name, //
const auto& code //
) -> bool {
const auto stage = ToShaderStage(type);
if (!RegisterFunction(VKShaderNameToShaderKeyName(name, stage), stage,
code)) {
success = false;
return false;
}
return true;
};
for (const auto& library_data : shader_libraries_data) {
auto vulkan_library = MultiArchShaderArchive::CreateArchiveFromMapping(
library_data, ArchiveRenderingBackend::kVulkan);
if (!vulkan_library || !vulkan_library->IsValid()) {
VALIDATION_LOG << "Could not construct Vulkan shader library archive.";
return;
}
vulkan_library->IterateAllShaders(iterator);
}
if (!success) {
VALIDATION_LOG << "Could not create shader modules for all shader blobs.";
return;
}
is_valid_ = true;
}
ShaderLibraryVK::~ShaderLibraryVK() = default;
bool ShaderLibraryVK::IsValid() const {
return is_valid_;
}
// |ShaderLibrary|
std::shared_ptr<const ShaderFunction> ShaderLibraryVK::GetFunction(
std::string_view name,
ShaderStage stage) {
ReaderLock lock(functions_mutex_);
const auto key = ShaderKey{{name.data(), name.size()}, stage};
auto found = functions_.find(key);
if (found != functions_.end()) {
return found->second;
}
return nullptr;
}
// |ShaderLibrary|
void ShaderLibraryVK::RegisterFunction(std::string name,
ShaderStage stage,
std::shared_ptr<fml::Mapping> code,
RegistrationCallback callback) {
const auto result = RegisterFunction(name, stage, code);
if (callback) {
callback(result);
}
}
static bool IsMappingSPIRV(const fml::Mapping& mapping) {
// https://registry.khronos.org/SPIR-V/specs/1.0/SPIRV.html#Magic
const uint32_t kSPIRVMagic = 0x07230203;
if (mapping.GetSize() < sizeof(kSPIRVMagic)) {
return false;
}
uint32_t magic = 0u;
::memcpy(&magic, mapping.GetMapping(), sizeof(magic));
return magic == kSPIRVMagic;
}
bool ShaderLibraryVK::RegisterFunction(
const std::string& name,
ShaderStage stage,
const std::shared_ptr<fml::Mapping>& code) {
if (!code) {
return false;
}
if (!IsMappingSPIRV(*code)) {
VALIDATION_LOG << "Shader is not valid SPIRV.";
return false;
}
vk::ShaderModuleCreateInfo shader_module_info;
shader_module_info.setPCode(
reinterpret_cast<const uint32_t*>(code->GetMapping()));
shader_module_info.setCodeSize(code->GetSize());
auto device_holder = device_holder_.lock();
if (!device_holder) {
return false;
}
FML_DCHECK(device_holder->GetDevice());
auto module =
device_holder->GetDevice().createShaderModuleUnique(shader_module_info);
if (module.result != vk::Result::eSuccess) {
VALIDATION_LOG << "Could not create shader module: "
<< vk::to_string(module.result);
return false;
}
vk::UniqueShaderModule shader_module = std::move(module.value);
ContextVK::SetDebugName(device_holder->GetDevice(), *shader_module,
"Shader " + name);
WriterLock lock(functions_mutex_);
functions_[ShaderKey{name, stage}] = std::shared_ptr<ShaderFunctionVK>(
new ShaderFunctionVK(device_holder_,
library_id_, //
name, //
stage, //
std::move(shader_module) //
));
return true;
}
// |ShaderLibrary|
void ShaderLibraryVK::UnregisterFunction(std::string name, ShaderStage stage) {
WriterLock lock(functions_mutex_);
const auto key = ShaderKey{name, stage};
auto found = functions_.find(key);
if (found == functions_.end()) {
VALIDATION_LOG << "Library function named " << name
<< " was not found, so it couldn't be unregistered.";
return;
}
functions_.erase(found);
return;
}
} // namespace impeller
| engine/impeller/renderer/backend/vulkan/shader_library_vk.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/shader_library_vk.cc",
"repo_id": "engine",
"token_count": 2445
} | 215 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include "flutter/testing/testing.h" // IWYU pragma: keep
#include "fml/synchronization/count_down_latch.h"
#include "gtest/gtest.h"
#include "impeller/renderer//backend/vulkan/command_encoder_vk.h"
#include "impeller/renderer/backend/vulkan/context_vk.h"
#include "impeller/renderer/backend/vulkan/gpu_tracer_vk.h"
#include "impeller/renderer/backend/vulkan/test/mock_vulkan.h"
namespace impeller {
namespace testing {
#ifdef IMPELLER_DEBUG
TEST(GPUTracerVK, CanBeDisabled) {
auto const context =
MockVulkanContextBuilder()
.SetSettingsCallback([](ContextVK::Settings& settings) {
settings.enable_gpu_tracing = false;
})
.Build();
auto tracer = context->GetGPUTracer();
ASSERT_FALSE(tracer->IsEnabled());
}
TEST(GPUTracerVK, DisabledFrameCycle) {
auto const context =
MockVulkanContextBuilder()
.SetSettingsCallback([](ContextVK::Settings& settings) {
settings.enable_gpu_tracing = false;
})
.Build();
auto tracer = context->GetGPUTracer();
// Check that a repeated frame start/end cycle does not fail any assertions.
for (int i = 0; i < 2; i++) {
tracer->MarkFrameStart();
tracer->MarkFrameEnd();
}
}
TEST(GPUTracerVK, CanTraceCmdBuffer) {
auto const context =
MockVulkanContextBuilder()
.SetSettingsCallback([](ContextVK::Settings& settings) {
settings.enable_gpu_tracing = true;
})
.Build();
auto tracer = context->GetGPUTracer();
ASSERT_TRUE(tracer->IsEnabled());
tracer->MarkFrameStart();
auto cmd_buffer = context->CreateCommandBuffer();
auto blit_pass = cmd_buffer->CreateBlitPass();
blit_pass->EncodeCommands(context->GetResourceAllocator());
auto latch = std::make_shared<fml::CountDownLatch>(1u);
if (!context->GetCommandQueue()
->Submit(
{cmd_buffer},
[latch](CommandBuffer::Status status) { latch->CountDown(); })
.ok()) {
GTEST_FAIL() << "Failed to submit cmd buffer";
}
tracer->MarkFrameEnd();
latch->Wait();
auto called = GetMockVulkanFunctions(context->GetDevice());
ASSERT_NE(called, nullptr);
ASSERT_TRUE(std::find(called->begin(), called->end(), "vkCreateQueryPool") !=
called->end());
ASSERT_TRUE(std::find(called->begin(), called->end(),
"vkGetQueryPoolResults") != called->end());
}
TEST(GPUTracerVK, DoesNotTraceOutsideOfFrameWorkload) {
auto const context =
MockVulkanContextBuilder()
.SetSettingsCallback([](ContextVK::Settings& settings) {
settings.enable_gpu_tracing = true;
})
.Build();
auto tracer = context->GetGPUTracer();
ASSERT_TRUE(tracer->IsEnabled());
auto cmd_buffer = context->CreateCommandBuffer();
auto blit_pass = cmd_buffer->CreateBlitPass();
blit_pass->EncodeCommands(context->GetResourceAllocator());
auto latch = std::make_shared<fml::CountDownLatch>(1u);
if (!context->GetCommandQueue()
->Submit(
{cmd_buffer},
[latch](CommandBuffer::Status status) { latch->CountDown(); })
.ok()) {
GTEST_FAIL() << "Failed to submit cmd buffer";
}
latch->Wait();
auto called = GetMockVulkanFunctions(context->GetDevice());
ASSERT_NE(called, nullptr);
ASSERT_TRUE(std::find(called->begin(), called->end(),
"vkGetQueryPoolResults") == called->end());
}
// This cmd buffer starts when there is a frame but finishes when there is none.
// This should result in the same recorded work.
TEST(GPUTracerVK, TracesWithPartialFrameOverlap) {
auto const context =
MockVulkanContextBuilder()
.SetSettingsCallback([](ContextVK::Settings& settings) {
settings.enable_gpu_tracing = true;
})
.Build();
auto tracer = context->GetGPUTracer();
ASSERT_TRUE(tracer->IsEnabled());
tracer->MarkFrameStart();
auto cmd_buffer = context->CreateCommandBuffer();
auto blit_pass = cmd_buffer->CreateBlitPass();
blit_pass->EncodeCommands(context->GetResourceAllocator());
tracer->MarkFrameEnd();
auto latch = std::make_shared<fml::CountDownLatch>(1u);
if (!context->GetCommandQueue()
->Submit(
{cmd_buffer},
[latch](CommandBuffer::Status status) { latch->CountDown(); })
.ok()) {
GTEST_FAIL() << "Failed to submit cmd buffer";
}
latch->Wait();
auto called = GetMockVulkanFunctions(context->GetDevice());
ASSERT_NE(called, nullptr);
ASSERT_TRUE(std::find(called->begin(), called->end(), "vkCreateQueryPool") !=
called->end());
ASSERT_TRUE(std::find(called->begin(), called->end(),
"vkGetQueryPoolResults") != called->end());
}
#endif // IMPELLER_DEBUG
} // namespace testing
} // namespace impeller
| engine/impeller/renderer/backend/vulkan/test/gpu_tracer_unittests.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/test/gpu_tracer_unittests.cc",
"repo_id": "engine",
"token_count": 1966
} | 216 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/yuv_conversion_library_vk.h"
#include "impeller/base/validation.h"
#include "impeller/renderer/backend/vulkan/device_holder_vk.h"
namespace impeller {
YUVConversionLibraryVK::YUVConversionLibraryVK(
std::weak_ptr<DeviceHolderVK> device_holder)
: device_holder_(std::move(device_holder)) {}
YUVConversionLibraryVK::~YUVConversionLibraryVK() = default;
std::shared_ptr<YUVConversionVK> YUVConversionLibraryVK::GetConversion(
const YUVConversionDescriptorVK& desc) {
Lock lock(conversions_mutex_);
auto found = conversions_.find(desc);
if (found != conversions_.end()) {
return found->second;
}
auto device_holder = device_holder_.lock();
if (!device_holder) {
VALIDATION_LOG << "Context loss during creation of YUV conversion.";
return nullptr;
}
return (conversions_[desc] = std::shared_ptr<YUVConversionVK>(
new YUVConversionVK(device_holder->GetDevice(), desc)));
}
} // namespace impeller
| engine/impeller/renderer/backend/vulkan/yuv_conversion_library_vk.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/yuv_conversion_library_vk.cc",
"repo_id": "engine",
"token_count": 400
} | 217 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/command_queue.h"
#include "impeller/renderer/command_buffer.h"
namespace impeller {
CommandQueue::CommandQueue() = default;
CommandQueue::~CommandQueue() = default;
fml::Status CommandQueue::Submit(
const std::vector<std::shared_ptr<CommandBuffer>>& buffers,
const CompletionCallback& completion_callback) {
if (buffers.empty()) {
if (completion_callback) {
completion_callback(CommandBuffer::Status::kError);
}
return fml::Status(fml::StatusCode::kInvalidArgument,
"No command buffers provided.");
}
for (const std::shared_ptr<CommandBuffer>& buffer : buffers) {
if (!buffer->SubmitCommands(completion_callback)) {
return fml::Status(fml::StatusCode::kCancelled,
"Failed to submit command buffer.");
}
}
return fml::Status();
}
} // namespace impeller
| engine/impeller/renderer/command_queue.cc/0 | {
"file_path": "engine/impeller/renderer/command_queue.cc",
"repo_id": "engine",
"token_count": 369
} | 218 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/pipeline.h"
#include <optional>
#include "compute_pipeline_descriptor.h"
#include "impeller/base/promise.h"
#include "impeller/renderer/compute_pipeline_descriptor.h"
#include "impeller/renderer/context.h"
#include "impeller/renderer/pipeline_library.h"
#include "pipeline_descriptor.h"
namespace impeller {
template <typename T>
Pipeline<T>::Pipeline(std::weak_ptr<PipelineLibrary> library, T desc)
: library_(std::move(library)), desc_(std::move(desc)) {}
template <typename T>
Pipeline<T>::~Pipeline() = default;
PipelineFuture<PipelineDescriptor> CreatePipelineFuture(
const Context& context,
std::optional<PipelineDescriptor> desc) {
if (!context.IsValid()) {
return {desc, RealizedFuture<std::shared_ptr<Pipeline<PipelineDescriptor>>>(
nullptr)};
}
return context.GetPipelineLibrary()->GetPipeline(std::move(desc));
}
PipelineFuture<ComputePipelineDescriptor> CreatePipelineFuture(
const Context& context,
std::optional<ComputePipelineDescriptor> desc) {
if (!context.IsValid()) {
return {
desc,
RealizedFuture<std::shared_ptr<Pipeline<ComputePipelineDescriptor>>>(
nullptr)};
}
return context.GetPipelineLibrary()->GetPipeline(std::move(desc));
}
template <typename T>
const T& Pipeline<T>::GetDescriptor() const {
return desc_;
}
template <typename T>
PipelineFuture<T> Pipeline<T>::CreateVariant(
std::function<void(T& desc)> descriptor_callback) const {
if (!descriptor_callback) {
return {std::nullopt,
RealizedFuture<std::shared_ptr<Pipeline<T>>>(nullptr)};
}
auto copied_desc = desc_;
descriptor_callback(copied_desc);
auto library = library_.lock();
if (!library) {
VALIDATION_LOG << "The library from which this pipeline was created was "
"already collected.";
return {desc_, RealizedFuture<std::shared_ptr<Pipeline<T>>>(nullptr)};
}
return library->GetPipeline(std::move(copied_desc));
}
template class Pipeline<PipelineDescriptor>;
template class Pipeline<ComputePipelineDescriptor>;
} // namespace impeller
| engine/impeller/renderer/pipeline.cc/0 | {
"file_path": "engine/impeller/renderer/pipeline.cc",
"repo_id": "engine",
"token_count": 870
} | 219 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/renderer.h"
#include <algorithm>
#include "flutter/fml/trace_event.h"
#include "impeller/renderer/command_buffer.h"
#include "impeller/renderer/surface.h"
namespace impeller {
Renderer::Renderer(std::shared_ptr<Context> context,
size_t max_frames_in_flight)
: frames_in_flight_sema_(std::make_shared<fml::Semaphore>(
std::max<std::size_t>(1u, max_frames_in_flight))),
context_(std::move(context)) {
if (!context_ || !context_->IsValid()) {
return;
}
is_valid_ = true;
}
Renderer::~Renderer() = default;
bool Renderer::IsValid() const {
return is_valid_;
}
bool Renderer::Render(std::unique_ptr<Surface> surface,
const RenderCallback& render_callback) const {
TRACE_EVENT0("impeller", "Renderer::Render");
if (!IsValid()) {
return false;
}
if (!surface || !surface->IsValid()) {
return false;
}
RenderTarget render_target = surface->GetTargetRenderPassDescriptor();
if (render_callback && !render_callback(render_target)) {
return false;
}
if (!frames_in_flight_sema_->Wait()) {
return false;
}
const auto present_result = surface->Present();
frames_in_flight_sema_->Signal();
return present_result;
}
std::shared_ptr<Context> Renderer::GetContext() const {
return context_;
}
} // namespace impeller
| engine/impeller/renderer/renderer.cc/0 | {
"file_path": "engine/impeller/renderer/renderer.cc",
"repo_id": "engine",
"token_count": 569
} | 220 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_SURFACE_H_
#define FLUTTER_IMPELLER_RENDERER_SURFACE_H_
#include <functional>
#include <memory>
#include "flutter/fml/macros.h"
#include "impeller/renderer/context.h"
#include "impeller/renderer/render_pass.h"
#include "impeller/renderer/render_target.h"
namespace impeller {
class Surface {
public:
Surface();
explicit Surface(const RenderTarget& target_desc);
virtual ~Surface();
const ISize& GetSize() const;
bool IsValid() const;
const RenderTarget& GetTargetRenderPassDescriptor() const;
virtual bool Present() const;
private:
RenderTarget desc_;
ISize size_;
bool is_valid_ = false;
Surface(const Surface&) = delete;
Surface& operator=(const Surface&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_SURFACE_H_
| engine/impeller/renderer/surface.h/0 | {
"file_path": "engine/impeller/renderer/surface.h",
"repo_id": "engine",
"token_count": 336
} | 221 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <future>
#include "flutter/fml/make_copyable.h"
#include "flutter/testing/testing.h"
#include "gmock/gmock.h"
#include "impeller/base/allocation.h"
#include "impeller/base/validation.h"
#include "impeller/core/runtime_types.h"
#include "impeller/core/shader_types.h"
#include "impeller/entity/runtime_effect.vert.h"
#include "impeller/playground/playground.h"
#include "impeller/renderer/pipeline_descriptor.h"
#include "impeller/renderer/pipeline_library.h"
#include "impeller/renderer/shader_library.h"
#include "impeller/runtime_stage/runtime_stage.h"
#include "impeller/runtime_stage/runtime_stage_playground.h"
namespace impeller {
namespace testing {
using RuntimeStageTest = RuntimeStagePlayground;
INSTANTIATE_PLAYGROUND_SUITE(RuntimeStageTest);
TEST_P(RuntimeStageTest, CanReadValidBlob) {
const std::shared_ptr<fml::Mapping> fixture =
flutter::testing::OpenFixtureAsMapping("ink_sparkle.frag.iplr");
ASSERT_TRUE(fixture);
ASSERT_GT(fixture->GetSize(), 0u);
auto stages = RuntimeStage::DecodeRuntimeStages(fixture);
auto stage = stages[PlaygroundBackendToRuntimeStageBackend(GetBackend())];
ASSERT_TRUE(stage->IsValid());
ASSERT_EQ(stage->GetShaderStage(), RuntimeShaderStage::kFragment);
}
TEST_P(RuntimeStageTest, CanRejectInvalidBlob) {
ScopedValidationDisable disable_validation;
const std::shared_ptr<fml::Mapping> fixture =
flutter::testing::OpenFixtureAsMapping("ink_sparkle.frag.iplr");
ASSERT_TRUE(fixture);
auto junk_allocation = std::make_shared<Allocation>();
ASSERT_TRUE(junk_allocation->Truncate(fixture->GetSize(), false));
// Not meant to be secure. Just reject obviously bad blobs using magic
// numbers.
::memset(junk_allocation->GetBuffer(), 127, junk_allocation->GetLength());
auto stages = RuntimeStage::DecodeRuntimeStages(
CreateMappingFromAllocation(junk_allocation));
ASSERT_FALSE(stages[PlaygroundBackendToRuntimeStageBackend(GetBackend())]);
}
TEST_P(RuntimeStageTest, CanReadUniforms) {
const std::shared_ptr<fml::Mapping> fixture =
flutter::testing::OpenFixtureAsMapping("ink_sparkle.frag.iplr");
ASSERT_TRUE(fixture);
ASSERT_GT(fixture->GetSize(), 0u);
auto stages = RuntimeStage::DecodeRuntimeStages(fixture);
auto stage = stages[PlaygroundBackendToRuntimeStageBackend(GetBackend())];
ASSERT_TRUE(stage->IsValid());
switch (GetBackend()) {
case PlaygroundBackend::kMetal:
case PlaygroundBackend::kOpenGLES: {
ASSERT_EQ(stage->GetUniforms().size(), 17u);
{
auto uni = stage->GetUniform("u_color");
ASSERT_NE(uni, nullptr);
EXPECT_EQ(uni->dimensions.rows, 4u);
EXPECT_EQ(uni->dimensions.cols, 1u);
EXPECT_EQ(uni->location, 0u);
EXPECT_EQ(uni->type, RuntimeUniformType::kFloat);
}
{
auto uni = stage->GetUniform("u_alpha");
ASSERT_NE(uni, nullptr);
EXPECT_EQ(uni->dimensions.rows, 1u);
EXPECT_EQ(uni->dimensions.cols, 1u);
EXPECT_EQ(uni->location, 1u);
EXPECT_EQ(uni->type, RuntimeUniformType::kFloat);
}
{
auto uni = stage->GetUniform("u_sparkle_color");
ASSERT_NE(uni, nullptr);
EXPECT_EQ(uni->dimensions.rows, 4u);
EXPECT_EQ(uni->dimensions.cols, 1u);
EXPECT_EQ(uni->location, 2u);
EXPECT_EQ(uni->type, RuntimeUniformType::kFloat);
}
{
auto uni = stage->GetUniform("u_sparkle_alpha");
ASSERT_NE(uni, nullptr);
EXPECT_EQ(uni->dimensions.rows, 1u);
EXPECT_EQ(uni->dimensions.cols, 1u);
EXPECT_EQ(uni->location, 3u);
EXPECT_EQ(uni->type, RuntimeUniformType::kFloat);
}
{
auto uni = stage->GetUniform("u_blur");
ASSERT_NE(uni, nullptr);
EXPECT_EQ(uni->dimensions.rows, 1u);
EXPECT_EQ(uni->dimensions.cols, 1u);
EXPECT_EQ(uni->location, 4u);
EXPECT_EQ(uni->type, RuntimeUniformType::kFloat);
}
{
auto uni = stage->GetUniform("u_radius_scale");
ASSERT_NE(uni, nullptr);
EXPECT_EQ(uni->dimensions.rows, 1u);
EXPECT_EQ(uni->dimensions.cols, 1u);
EXPECT_EQ(uni->location, 6u);
EXPECT_EQ(uni->type, RuntimeUniformType::kFloat);
}
{
auto uni = stage->GetUniform("u_max_radius");
ASSERT_NE(uni, nullptr);
EXPECT_EQ(uni->dimensions.rows, 1u);
EXPECT_EQ(uni->dimensions.cols, 1u);
EXPECT_EQ(uni->location, 7u);
EXPECT_EQ(uni->type, RuntimeUniformType::kFloat);
}
{
auto uni = stage->GetUniform("u_resolution_scale");
ASSERT_NE(uni, nullptr);
EXPECT_EQ(uni->dimensions.rows, 2u);
EXPECT_EQ(uni->dimensions.cols, 1u);
EXPECT_EQ(uni->location, 8u);
EXPECT_EQ(uni->type, RuntimeUniformType::kFloat);
}
{
auto uni = stage->GetUniform("u_noise_scale");
ASSERT_NE(uni, nullptr);
EXPECT_EQ(uni->dimensions.rows, 2u);
EXPECT_EQ(uni->dimensions.cols, 1u);
EXPECT_EQ(uni->location, 9u);
EXPECT_EQ(uni->type, RuntimeUniformType::kFloat);
}
{
auto uni = stage->GetUniform("u_noise_phase");
ASSERT_NE(uni, nullptr);
EXPECT_EQ(uni->dimensions.rows, 1u);
EXPECT_EQ(uni->dimensions.cols, 1u);
EXPECT_EQ(uni->location, 10u);
EXPECT_EQ(uni->type, RuntimeUniformType::kFloat);
}
{
auto uni = stage->GetUniform("u_circle1");
ASSERT_NE(uni, nullptr);
EXPECT_EQ(uni->dimensions.rows, 2u);
EXPECT_EQ(uni->dimensions.cols, 1u);
EXPECT_EQ(uni->location, 11u);
EXPECT_EQ(uni->type, RuntimeUniformType::kFloat);
}
{
auto uni = stage->GetUniform("u_circle2");
ASSERT_NE(uni, nullptr);
EXPECT_EQ(uni->dimensions.rows, 2u);
EXPECT_EQ(uni->dimensions.cols, 1u);
EXPECT_EQ(uni->location, 12u);
EXPECT_EQ(uni->type, RuntimeUniformType::kFloat);
}
{
auto uni = stage->GetUniform("u_circle3");
ASSERT_NE(uni, nullptr);
EXPECT_EQ(uni->dimensions.rows, 2u);
EXPECT_EQ(uni->dimensions.cols, 1u);
EXPECT_EQ(uni->location, 13u);
EXPECT_EQ(uni->type, RuntimeUniformType::kFloat);
}
{
auto uni = stage->GetUniform("u_rotation1");
ASSERT_NE(uni, nullptr);
EXPECT_EQ(uni->dimensions.rows, 2u);
EXPECT_EQ(uni->dimensions.cols, 1u);
EXPECT_EQ(uni->location, 14u);
EXPECT_EQ(uni->type, RuntimeUniformType::kFloat);
}
{
auto uni = stage->GetUniform("u_rotation2");
ASSERT_NE(uni, nullptr);
EXPECT_EQ(uni->dimensions.rows, 2u);
EXPECT_EQ(uni->dimensions.cols, 1u);
EXPECT_EQ(uni->location, 15u);
EXPECT_EQ(uni->type, RuntimeUniformType::kFloat);
}
{
auto uni = stage->GetUniform("u_rotation3");
ASSERT_NE(uni, nullptr);
EXPECT_EQ(uni->dimensions.rows, 2u);
EXPECT_EQ(uni->dimensions.cols, 1u);
EXPECT_EQ(uni->location, 16u);
EXPECT_EQ(uni->type, RuntimeUniformType::kFloat);
}
break;
}
case PlaygroundBackend::kVulkan: {
EXPECT_EQ(stage->GetUniforms().size(), 1u);
auto uni = stage->GetUniform(RuntimeStage::kVulkanUBOName);
ASSERT_TRUE(uni);
EXPECT_EQ(uni->type, RuntimeUniformType::kStruct);
EXPECT_EQ(uni->struct_float_count, 32u);
// There are 36 4 byte chunks in the UBO: 32 for the 32 floats, and 4 for
// padding. Initialize a vector as if they'll all be floats, then manually
// set the few padding bytes. If the shader changes, the padding locations
// will change as well. For example, if `u_alpha` was moved to the end,
// three bytes of padding could potentially be dropped - or if some of the
// scalar floats were changed to vec2 or vec4s, or if any vec3s are
// introduced.
// This means 36 * 4 = 144 bytes total.
EXPECT_EQ(uni->GetSize(), 144u);
std::vector<uint8_t> layout(uni->GetSize() / sizeof(float), 1);
layout[5] = 0;
layout[6] = 0;
layout[7] = 0;
layout[23] = 0;
EXPECT_THAT(uni->struct_layout, ::testing::ElementsAreArray(layout));
break;
}
}
}
TEST_P(RuntimeStageTest, CanRegisterStage) {
const std::shared_ptr<fml::Mapping> fixture =
flutter::testing::OpenFixtureAsMapping("ink_sparkle.frag.iplr");
ASSERT_TRUE(fixture);
ASSERT_GT(fixture->GetSize(), 0u);
auto stages = RuntimeStage::DecodeRuntimeStages(fixture);
auto stage = stages[PlaygroundBackendToRuntimeStageBackend(GetBackend())];
ASSERT_TRUE(stage->IsValid());
std::promise<bool> registration;
auto future = registration.get_future();
auto library = GetContext()->GetShaderLibrary();
library->RegisterFunction(
stage->GetEntrypoint(), //
ToShaderStage(stage->GetShaderStage()), //
stage->GetCodeMapping(), //
fml::MakeCopyable([reg = std::move(registration)](bool result) mutable {
reg.set_value(result);
}));
ASSERT_TRUE(future.get());
{
auto function =
library->GetFunction(stage->GetEntrypoint(), ShaderStage::kFragment);
ASSERT_NE(function, nullptr);
}
// Check if unregistering works.
library->UnregisterFunction(stage->GetEntrypoint(), ShaderStage::kFragment);
{
auto function =
library->GetFunction(stage->GetEntrypoint(), ShaderStage::kFragment);
ASSERT_EQ(function, nullptr);
}
}
TEST_P(RuntimeStageTest, CanCreatePipelineFromRuntimeStage) {
auto stages = OpenAssetAsRuntimeStage("ink_sparkle.frag.iplr");
auto stage = stages[PlaygroundBackendToRuntimeStageBackend(GetBackend())];
ASSERT_TRUE(stage);
ASSERT_NE(stage, nullptr);
ASSERT_TRUE(RegisterStage(*stage));
auto library = GetContext()->GetShaderLibrary();
using VS = RuntimeEffectVertexShader;
PipelineDescriptor desc;
desc.SetLabel("Runtime Stage InkSparkle");
desc.AddStageEntrypoint(
library->GetFunction(VS::kEntrypointName, ShaderStage::kVertex));
desc.AddStageEntrypoint(
library->GetFunction(stage->GetEntrypoint(), ShaderStage::kFragment));
auto vertex_descriptor = std::make_shared<VertexDescriptor>();
vertex_descriptor->SetStageInputs(VS::kAllShaderStageInputs,
VS::kInterleavedBufferLayout);
vertex_descriptor->RegisterDescriptorSetLayouts(VS::kDescriptorSetLayouts);
desc.SetVertexDescriptor(std::move(vertex_descriptor));
ColorAttachmentDescriptor color0;
color0.format = GetContext()->GetCapabilities()->GetDefaultColorFormat();
StencilAttachmentDescriptor stencil0;
stencil0.stencil_compare = CompareFunction::kEqual;
desc.SetColorAttachmentDescriptor(0u, color0);
desc.SetStencilAttachmentDescriptors(stencil0);
const auto stencil_fmt =
GetContext()->GetCapabilities()->GetDefaultStencilFormat();
desc.SetStencilPixelFormat(stencil_fmt);
auto pipeline = GetContext()->GetPipelineLibrary()->GetPipeline(desc).Get();
ASSERT_NE(pipeline, nullptr);
}
TEST_P(RuntimeStageTest, ContainsExpectedShaderTypes) {
auto stages = OpenAssetAsRuntimeStage("ink_sparkle.frag.iplr");
// Right now, SkSL gets implicitly bundled regardless of what the build rule
// for this test requested. After
// https://github.com/flutter/flutter/issues/138919, this may require a build
// rule change or a new test.
EXPECT_TRUE(stages[RuntimeStageBackend::kSkSL]);
EXPECT_TRUE(stages[RuntimeStageBackend::kOpenGLES]);
EXPECT_TRUE(stages[RuntimeStageBackend::kMetal]);
EXPECT_TRUE(stages[RuntimeStageBackend::kVulkan]);
}
} // namespace testing
} // namespace impeller
| engine/impeller/runtime_stage/runtime_stage_unittests.cc/0 | {
"file_path": "engine/impeller/runtime_stage/runtime_stage_unittests.cc",
"repo_id": "engine",
"token_count": 5047
} | 222 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//flutter/impeller/tools/impeller.gni")
import("//flutter/shell/version/version.gni")
import("//flutter/third_party/flatbuffers/flatbuffers.gni")
config("runtime_stage_config") {
configs = [ "//flutter/impeller:impeller_public_config" ]
include_dirs = [ "$root_gen_dir/flutter" ]
}
flatbuffers("importer_flatbuffers") {
flatbuffers = [ "scene.fbs" ]
public_configs = [ ":runtime_stage_config" ]
public_deps = [ "//flutter/third_party/flatbuffers" ]
}
impeller_component("conversions") {
sources = [
"conversions.cc",
"conversions.h",
]
public_deps = [
":importer_flatbuffers",
"../../base",
"../../geometry",
"//flutter/fml",
]
}
impeller_component("importer_lib") {
# Current versions of libcxx have deprecated some of the UTF-16 string
# conversion APIs.
defines = [ "_LIBCPP_DISABLE_DEPRECATION_WARNINGS" ]
sources = [
"importer.h",
"importer_gltf.cc",
"switches.cc",
"switches.h",
"types.h",
"vertices_builder.cc",
"vertices_builder.h",
]
public_deps = [
":conversions",
":importer_flatbuffers",
"../../base",
"../../compiler:utilities",
"../../geometry",
"//flutter/fml",
# All third_party deps must be reflected below in the scenec_license
# target.
"//flutter/third_party/tinygltf",
]
}
generated_file("scenec_license") {
source_path = rebase_path(".", "//flutter")
git_url = "https://github.com/flutter/engine/tree/$engine_version"
outputs = [ "$target_gen_dir/LICENSE.scenec.md" ]
contents = [
"# scenec",
"",
"This tool is used by the Flutter SDK to import 3D geometry.",
"",
"Source code for this tool: [flutter/engine/$source_path]($git_url/$source_path).",
"",
"## Licenses",
"",
"### scenec",
"",
read_file("//flutter/sky/packages/sky_engine/LICENSE", "string"),
"",
# These licenses are ignored by the main license checker, since they are not
# shipped to end-application binaries and only shipped as part of developer
# tooling in scenec. Add them here.
"## Additional open source licenses",
"",
"### tinygltf",
"",
read_file("//flutter/third_party/tinygltf/LICENSE", "string"),
]
}
group("importer") {
deps = [
":scenec",
":scenec_license",
]
}
impeller_component("scenec") {
target_type = "executable"
sources = [ "scenec_main.cc" ]
deps = [ ":importer_lib" ]
metadata = {
entitlement_file_path = [ "scenec" ]
}
}
impeller_component("importer_unittests") {
testonly = true
output_name = "scenec_unittests"
sources = [ "importer_unittests.cc" ]
deps = [
":importer_lib",
"../../fixtures",
"../../geometry:geometry_asserts",
"//flutter/testing:testing_lib",
]
}
| engine/impeller/scene/importer/BUILD.gn/0 | {
"file_path": "engine/impeller/scene/importer/BUILD.gn",
"repo_id": "engine",
"token_count": 1167
} | 223 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_SCENE_MESH_H_
#define FLUTTER_IMPELLER_SCENE_MESH_H_
#include <memory>
#include <type_traits>
#include "flutter/fml/macros.h"
#include "impeller/scene/geometry.h"
#include "impeller/scene/material.h"
#include "impeller/scene/scene_encoder.h"
namespace impeller {
namespace scene {
class Skin;
class Mesh final {
public:
struct Primitive {
std::shared_ptr<Geometry> geometry;
std::shared_ptr<Material> material;
};
Mesh();
~Mesh();
Mesh(Mesh&& mesh);
Mesh& operator=(Mesh&& mesh);
void AddPrimitive(Primitive mesh_);
std::vector<Primitive>& GetPrimitives();
bool Render(SceneEncoder& encoder,
const Matrix& transform,
const std::shared_ptr<Texture>& joints) const;
private:
std::vector<Primitive> primitives_;
Mesh(const Mesh&) = delete;
Mesh& operator=(const Mesh&) = delete;
};
} // namespace scene
} // namespace impeller
#endif // FLUTTER_IMPELLER_SCENE_MESH_H_
| engine/impeller/scene/mesh.h/0 | {
"file_path": "engine/impeller/scene/mesh.h",
"repo_id": "engine",
"token_count": 416
} | 224 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_SCENE_SKIN_H_
#define FLUTTER_IMPELLER_SCENE_SKIN_H_
#include <memory>
#include <optional>
#include "flutter/fml/macros.h"
#include "impeller/core/allocator.h"
#include "impeller/core/texture.h"
#include "impeller/scene/importer/scene_flatbuffers.h"
#include "impeller/scene/node.h"
namespace impeller {
namespace scene {
class Skin final {
public:
static std::unique_ptr<Skin> MakeFromFlatbuffer(
const fb::Skin& skin,
const std::vector<std::shared_ptr<Node>>& scene_nodes);
~Skin();
Skin(Skin&&);
Skin& operator=(Skin&&);
std::shared_ptr<Texture> GetJointsTexture(Allocator& allocator);
private:
Skin();
std::vector<std::shared_ptr<Node>> joints_;
std::vector<Matrix> inverse_bind_matrices_;
Skin(const Skin&) = delete;
Skin& operator=(const Skin&) = delete;
};
} // namespace scene
} // namespace impeller
#endif // FLUTTER_IMPELLER_SCENE_SKIN_H_
| engine/impeller/scene/skin.h/0 | {
"file_path": "engine/impeller/scene/skin.h",
"repo_id": "engine",
"token_count": 401
} | 225 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
namespace impeller.fb.shaderbundle;
enum ShaderStage:byte {
kVertex,
kFragment,
kCompute,
}
// The subset of impeller::ShaderType that may be used for vertex attributes.
enum InputDataType:uint32 {
kBoolean,
kSignedByte,
kUnsignedByte,
kSignedShort,
kUnsignedShort,
kSignedInt,
kUnsignedInt,
kSignedInt64,
kUnsignedInt64,
kFloat,
kDouble,
}
// The subset of impeller::ShaderType that may be used for uniform bindings.
enum UniformDataType:uint32 {
kBoolean,
kSignedByte,
kUnsignedByte,
kSignedShort,
kUnsignedShort,
kSignedInt,
kUnsignedInt,
kSignedInt64,
kUnsignedInt64,
kHalfFloat,
kFloat,
kDouble,
kSampledImage,
}
// This contains the same attribute reflection data as
// impeller::ShaderStageIOSlot.
table ShaderInput {
name: string;
location: uint64;
set: uint64;
binding: uint64;
type: InputDataType;
bit_width: uint64;
vec_size: uint64;
columns: uint64;
offset: uint64;
}
table ShaderUniformStructField {
name: string;
type: UniformDataType;
offset_in_bytes: uint64;
element_size_in_bytes: uint64;
total_size_in_bytes: uint64;
// Zero indicates that this field is not an array element.
array_elements: uint64;
}
table ShaderUniformStruct {
name: string;
ext_res_0: uint64;
set: uint64;
binding: uint64;
size_in_bytes: uint64; // Includes all alignment padding.
fields: [ShaderUniformStructField];
}
table ShaderUniformTexture {
name: string;
ext_res_0: uint64;
set: uint64;
binding: uint64;
}
table BackendShader {
stage: ShaderStage;
entrypoint: string;
inputs: [ShaderInput];
uniform_structs: [ShaderUniformStruct];
uniform_textures: [ShaderUniformTexture];
shader: [ubyte];
}
table Shader {
name: string;
metal_ios: BackendShader;
metal_desktop: BackendShader;
opengl_es: BackendShader;
opengl_desktop: BackendShader;
vulkan: BackendShader;
}
table ShaderBundle {
shaders: [Shader];
}
root_type ShaderBundle;
file_identifier "IPSB";
| engine/impeller/shader_bundle/shader_bundle.fbs/0 | {
"file_path": "engine/impeller/shader_bundle/shader_bundle.fbs",
"repo_id": "engine",
"token_count": 784
} | 226 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_TOOLKIT_ANDROID_NATIVE_WINDOW_H_
#define FLUTTER_IMPELLER_TOOLKIT_ANDROID_NATIVE_WINDOW_H_
#include "flutter/fml/unique_object.h"
#include "impeller/geometry/size.h"
#include "impeller/toolkit/android/proc_table.h"
namespace impeller::android {
//------------------------------------------------------------------------------
/// @brief A wrapper for ANativeWindow
/// https://developer.android.com/ndk/reference/group/a-native-window
///
/// This wrapper is only available on Android.
///
class NativeWindow {
public:
explicit NativeWindow(ANativeWindow* window);
~NativeWindow();
NativeWindow(const NativeWindow&) = delete;
NativeWindow& operator=(const NativeWindow&) = delete;
bool IsValid() const;
//----------------------------------------------------------------------------
/// @return The current size of the native window.
///
ISize GetSize() const;
ANativeWindow* GetHandle() const;
private:
struct UniqueANativeWindowTraits {
static ANativeWindow* InvalidValue() { return nullptr; }
static bool IsValid(ANativeWindow* value) {
return value != InvalidValue();
}
static void Free(ANativeWindow* value) {
GetProcTable().ANativeWindow_release(value);
}
};
fml::UniqueObject<ANativeWindow*, UniqueANativeWindowTraits> window_;
};
} // namespace impeller::android
#endif // FLUTTER_IMPELLER_TOOLKIT_ANDROID_NATIVE_WINDOW_H_
| engine/impeller/toolkit/android/native_window.h/0 | {
"file_path": "engine/impeller/toolkit/android/native_window.h",
"repo_id": "engine",
"token_count": 522
} | 227 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_TOOLKIT_EGL_EGL_H_
#define FLUTTER_IMPELLER_TOOLKIT_EGL_EGL_H_
#include <EGL/egl.h>
#define EGL_EGLEXT_PROTOTYPES
#include <EGL/eglext.h>
#include <functional>
namespace impeller {
namespace egl {
std::function<void*(const char*)> CreateProcAddressResolver();
#define IMPELLER_LOG_EGL_ERROR LogEGLError(__FILE__, __LINE__);
void LogEGLError(const char* file, int line);
} // namespace egl
} // namespace impeller
#endif // FLUTTER_IMPELLER_TOOLKIT_EGL_EGL_H_
| engine/impeller/toolkit/egl/egl.h/0 | {
"file_path": "engine/impeller/toolkit/egl/egl.h",
"repo_id": "engine",
"token_count": 263
} | 228 |
#!/usr/bin/env vpython3
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import difflib
import json
import os
import sys
# This script detects performance impacting changes to shaders.
#
# When the GN build is configured with the path to the `malioc` tool, the
# results of its analysis will be placed under `out/$CONFIG/gen/malioc` in
# separate .json files. That path should be supplied to this script as the
# `--after` argument. This script compares those results against previous
# results in a golden file checked in to the tree under
# `flutter/impeller/tools/malioc.json`. That file should be passed to this
# script as the `--before` argument. To create or update the golden file,
# passing the `--update` flag will cause the data from the `--after` path to
# overwrite the file at the `--before` path.
#
# Configure and build:
# $ flutter/tools/gn --malioc-path path/to/malioc
# $ ninja -C out/host_debug
#
# Analyze
# $ flutter/impeller/tools/malioc_diff.py \
# --before flutter/impeller/tools/malioc.json \
# --after out/host_debug/gen/malioc
#
# If there are differences between before and after, whether positive or
# negative, the exit code for this script will be 1, and 0 otherwise.
SRC_ROOT = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
)
CORES = [
'Mali-G78', # Pixel 6 / 2020
'Mali-T880', # 2016
]
# Path to the engine root checkout. This is used to calculate absolute
# paths if relative ones are passed to the script.
BUILD_ROOT_DIR = os.path.abspath(os.path.join(os.path.realpath(__file__), '..', '..', '..', '..'))
def parse_args(argv):
parser = argparse.ArgumentParser(
description='A script that compares before/after malioc analysis results',
)
parser.add_argument(
'--after',
'-a',
type=str,
help='The path to a directory tree containing new malioc results in json files.',
)
parser.add_argument(
'--before',
'-b',
type=str,
help='The path to a json file containing existing malioc results.',
)
parser.add_argument(
'--after-relative-to-src',
type=str,
help=(
'A relative path calculated from the engine src directory to '
'a directory tree containing new malioc results in json files'
),
)
parser.add_argument(
'--before-relative-to-src',
type=str,
help=(
'A relative path calculated from the engine src directory to '
'a json file containing existing malioc results in json files'
),
)
parser.add_argument(
'--print-diff',
'-p',
default=False,
action='store_true',
help='Print a unified diff to stdout when differences are found.',
)
parser.add_argument(
'--update',
'-u',
default=False,
action='store_true',
help='Write results from the --after tree to the --before file.',
)
parser.add_argument(
'--verbose',
'-v',
default=False,
action='store_true',
help='Emit verbose output.',
)
return parser.parse_args(argv)
def validate_args(args):
if not args.after and not args.after_relative_to_src:
print('--after argument or --after-relative-to-src must be specified.')
return False
if not args.before and not args.before_relative_to_src:
print('--before argument or --before-relative-to-src must be specified.')
return False
# Generate full paths if relative ones are provided with before and
# after taking precedence.
args.before = (args.before or os.path.join(BUILD_ROOT_DIR, args.before_relative_to_src))
args.after = (args.after or os.path.join(BUILD_ROOT_DIR, args.after_relative_to_src))
if not args.after or not os.path.isdir(args.after):
print('The --after argument must refer to a directory.')
return False
if not args.before or (not args.update and not os.path.isfile(args.before)):
print('The --before argument must refer to an existing file.')
return False
return True
# Reads the 'performance' section of the malioc analysis results.
def read_malioc_file_performance(performance_json):
performance = {}
performance['pipelines'] = performance_json['pipelines']
longest_path_cycles = performance_json['longest_path_cycles']
performance['longest_path_cycles'] = longest_path_cycles['cycle_count']
performance['longest_path_bound_pipelines'] = longest_path_cycles['bound_pipelines']
shortest_path_cycles = performance_json['shortest_path_cycles']
performance['shortest_path_cycles'] = shortest_path_cycles['cycle_count']
performance['shortest_path_bound_pipelines'] = shortest_path_cycles['bound_pipelines']
total_cycles = performance_json['total_cycles']
performance['total_cycles'] = total_cycles['cycle_count']
performance['total_bound_pipelines'] = total_cycles['bound_pipelines']
return performance
# Parses the json output from malioc, which follows the schema defined in
# `mali_offline_compiler/samples/json_schemas/performance-schema.json`.
def read_malioc_file(malioc_tree, json_file):
with open(json_file, 'r') as file:
json_obj = json.load(file)
build_gen_dir = os.path.dirname(malioc_tree)
results = []
for shader in json_obj['shaders']:
# Ignore cores not in the allowlist above.
if shader['hardware']['core'] not in CORES:
continue
result = {}
filename = os.path.relpath(shader['filename'], build_gen_dir)
if filename.startswith('../..'):
filename = filename[6:]
if filename.startswith('../'):
filename = filename[3:]
result['filename'] = filename
result['core'] = shader['hardware']['core']
result['type'] = shader['shader']['type']
for prop in shader['properties']:
result[prop['name']] = prop['value']
result['variants'] = {}
for variant in shader['variants']:
variant_result = {}
for prop in variant['properties']:
variant_result[prop['name']] = prop['value']
performance_json = variant['performance']
performance = read_malioc_file_performance(performance_json)
variant_result['performance'] = performance
result['variants'][variant['name']] = variant_result
results.append(result)
return results
# Parses a tree of malioc performance json files.
#
# The parsing results are returned in a map keyed by the shader file name, whose
# values are maps keyed by the core type. The values in these maps are the
# performance properties of the shader on the core reported by malioc. This
# structure allows for a fast lookup and comparison against the golen file.
def read_malioc_tree(malioc_tree):
results = {}
for root, _, files in os.walk(malioc_tree):
for file in files:
if not file.endswith('.json'):
continue
full_path = os.path.join(root, file)
for shader in read_malioc_file(malioc_tree, full_path):
if shader['filename'] not in results:
results[shader['filename']] = {}
results[shader['filename']][shader['core']] = shader
return results
# Converts a list to a string in which each list element is left-aligned in
# a space of `width` characters, and separated by `sep`. The separator does not
# count against the `width`. If `width` is 0, then the width is unconstrained.
def pretty_list(lst, fmt='s', sep='', width=12):
formats = ['{:<{width}{fmt}}' if ele is not None else '{:<{width}s}' for ele in lst]
sanitized_list = [x if x is not None else 'null' for x in lst]
return (sep.join(formats)).format(width='' if width == 0 else width, fmt=fmt, *sanitized_list)
def compare_performance(variant, before, after):
cycles = [['longest_path_cycles', 'longest_path_bound_pipelines'],
['shortest_path_cycles', 'shortest_path_bound_pipelines'],
['total_cycles', 'total_bound_pipelines']]
differences = []
for cycle in cycles:
if before[cycle[0]] == after[cycle[0]]:
continue
before_cycles = before[cycle[0]]
before_bounds = before[cycle[1]]
after_cycles = after[cycle[0]]
after_bounds = after[cycle[1]]
differences += [
'{} in variant {}\n{}{}\n{:<8}{}{}\n{:<8}{}{}\n'.format(
cycle[0],
variant,
' ' * 8,
pretty_list(before['pipelines'] + ['bound']), # Column labels.
'before',
pretty_list(before_cycles, fmt='f'),
pretty_list(before_bounds, sep=',', width=0),
'after',
pretty_list(after_cycles, fmt='f'),
pretty_list(after_bounds, sep=',', width=0),
)
]
return differences
def compare_variants(befores, afters):
differences = []
for variant_name, before_variant in befores.items():
after_variant = afters[variant_name]
for variant_key, before_variant_val in before_variant.items():
after_variant_val = after_variant[variant_key]
if variant_key == 'performance':
differences += compare_performance(variant_name, before_variant_val, after_variant_val)
elif before_variant_val != after_variant_val:
differences += [
'In variant {}:\n {vkey}: {} <- before\n {vkey}: {} <- after'.format(
variant_name,
before_variant_val,
after_variant_val,
vkey=variant_key,
)
]
return differences
# Compares two shaders. Prints a report and returns True if there are
# differences, and returns False otherwise.
def compare_shaders(malioc_tree, before_shader, after_shader):
differences = []
for key, before_val in before_shader.items():
after_val = after_shader[key]
if key == 'variants':
differences += compare_variants(before_val, after_val)
elif key == 'performance':
differences += compare_performance('Default', before_val, after_val)
elif before_val != after_val:
differences += ['{}:\n {} <- before\n {} <- after'.format(key, before_val, after_val)]
if bool(differences):
build_gen_dir = os.path.dirname(malioc_tree)
filename = before_shader['filename']
core = before_shader['core']
typ = before_shader['type']
print('Changes found in shader {} on core {}:'.format(filename, core))
for diff in differences:
print(diff)
print(
'\nFor a full report, run:\n $ malioc --{} --core {} {}/{}\n'.format(
typ.lower(), core, build_gen_dir, filename
)
)
return bool(differences)
def main(argv):
args = parse_args(argv[1:])
if not validate_args(args):
return 1
after_json = read_malioc_tree(args.after)
if not bool(after_json):
print('Did not find any malioc results under {}.'.format(args.after))
return 1
if args.update:
# Write the new results to the file given by --before, then exit.
with open(args.before, 'w') as file:
json.dump(after_json, file, sort_keys=True, indent=2)
return 0
with open(args.before, 'r') as file:
before_json = json.load(file)
changed = False
for filename, shaders in before_json.items():
if filename not in after_json.keys():
print('Shader "{}" has been removed.'.format(filename))
changed = True
continue
for core, before_shader in shaders.items():
if core not in after_json[filename].keys():
continue
after_shader = after_json[filename][core]
if compare_shaders(args.after, before_shader, after_shader):
changed = True
for filename, shaders in after_json.items():
if filename not in before_json:
print('Shader "{}" is new.'.format(filename))
changed = True
if changed:
print(
'There are new shaders, shaders have been removed, or performance '
'changes to existing shaders. The golden file must be updated after a '
'build of android_debug_unopt using the --malioc-path flag to the '
'flutter/tools/gn script.\n\n'
'$ ./flutter/impeller/tools/malioc_diff.py --before {} --after {} --update'.format(
args.before, args.after
)
)
if args.print_diff:
before_lines = json.dumps(before_json, sort_keys=True, indent=2).splitlines(keepends=True)
after_lines = json.dumps(after_json, sort_keys=True, indent=2).splitlines(keepends=True)
before_path = os.path.relpath(os.path.abspath(args.before), start=SRC_ROOT)
diff = difflib.unified_diff(before_lines, after_lines, fromfile=before_path)
print('\nYou can alternately apply the diff below:')
print('patch -p0 <<DONE')
print(*diff, sep='')
print('DONE')
return 1 if changed else 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
| engine/impeller/tools/malioc_diff.py/0 | {
"file_path": "engine/impeller/tools/malioc_diff.py",
"repo_id": "engine",
"token_count": 4726
} | 229 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_TYPOGRAPHER_BACKENDS_STB_TEXT_FRAME_STB_H_
#define FLUTTER_IMPELLER_TYPOGRAPHER_BACKENDS_STB_TEXT_FRAME_STB_H_
#include "flutter/fml/macros.h"
#include "impeller/typographer/backends/stb/typeface_stb.h"
#include "impeller/typographer/text_frame.h"
namespace impeller {
std::shared_ptr<TextFrame> MakeTextFrameSTB(
const std::shared_ptr<TypefaceSTB>& typeface_stb,
Font::Metrics metrics,
const std::string& text);
} // namespace impeller
#endif // FLUTTER_IMPELLER_TYPOGRAPHER_BACKENDS_STB_TEXT_FRAME_STB_H_
| engine/impeller/typographer/backends/stb/text_frame_stb.h/0 | {
"file_path": "engine/impeller/typographer/backends/stb/text_frame_stb.h",
"repo_id": "engine",
"token_count": 285
} | 230 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_TYPOGRAPHER_RECTANGLE_PACKER_H_
#define FLUTTER_IMPELLER_TYPOGRAPHER_RECTANGLE_PACKER_H_
#include "flutter/fml/logging.h"
#include <cstdint>
namespace impeller {
struct IPoint16 {
int16_t x() const { return x_; }
int16_t y() const { return y_; }
int16_t x_;
int16_t y_;
};
//------------------------------------------------------------------------------
/// @brief Packs rectangles into a specified area without rotating them.
///
class RectanglePacker {
public:
//----------------------------------------------------------------------------
/// @brief Return an empty packer with area specified by width and height.
///
static std::unique_ptr<RectanglePacker> Factory(int width, int height);
virtual ~RectanglePacker() {}
//----------------------------------------------------------------------------
/// @brief Attempt to add a rect without moving already placed rectangles.
///
/// @param[in] width The width of the rectangle to add.
/// @param[in] height The height of the rectangle to add.
/// @param[out] loc If successful, will be set to the position of the
/// upper-left corner of the rectangle.
///
/// @return Return true on success; false on failure.
///
virtual bool addRect(int width, int height, IPoint16* loc) = 0;
//----------------------------------------------------------------------------
/// @brief Returns how much area has been filled with rectangles.
///
/// @return Percentage as a decimal between 0.0 and 1.0
///
virtual float percentFull() const = 0;
//----------------------------------------------------------------------------
/// @brief Empty out all previously added rectangles.
///
virtual void reset() = 0;
protected:
RectanglePacker(int width, int height) : width_(width), height_(height) {
FML_DCHECK(width >= 0);
FML_DCHECK(height >= 0);
}
int width() const { return width_; }
int height() const { return height_; }
private:
const int width_;
const int height_;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_TYPOGRAPHER_RECTANGLE_PACKER_H_
| engine/impeller/typographer/rectangle_packer.h/0 | {
"file_path": "engine/impeller/typographer/rectangle_packer.h",
"repo_id": "engine",
"token_count": 698
} | 231 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/lib/gpu/device_buffer.h"
#include "dart_api.h"
#include "flutter/lib/gpu/formats.h"
#include "fml/mapping.h"
#include "impeller/core/device_buffer.h"
#include "impeller/core/device_buffer_descriptor.h"
#include "impeller/core/formats.h"
#include "impeller/core/platform.h"
#include "impeller/core/range.h"
#include "third_party/tonic/typed_data/dart_byte_data.h"
#include "tonic/converter/dart_converter.h"
namespace flutter {
namespace gpu {
IMPLEMENT_WRAPPERTYPEINFO(flutter_gpu, DeviceBuffer);
DeviceBuffer::DeviceBuffer(
std::shared_ptr<impeller::DeviceBuffer> device_buffer)
: device_buffer_(std::move(device_buffer)) {}
DeviceBuffer::~DeviceBuffer() = default;
std::shared_ptr<impeller::DeviceBuffer> DeviceBuffer::GetBuffer() {
return device_buffer_;
}
bool DeviceBuffer::Overwrite(const tonic::DartByteData& source_bytes,
size_t destination_offset_in_bytes) {
if (!device_buffer_->CopyHostBuffer(
reinterpret_cast<const uint8_t*>(source_bytes.data()),
impeller::Range(0, source_bytes.length_in_bytes()),
destination_offset_in_bytes)) {
return false;
}
return true;
}
} // namespace gpu
} // namespace flutter
//----------------------------------------------------------------------------
/// Exports
///
bool InternalFlutterGpu_DeviceBuffer_Initialize(
Dart_Handle wrapper,
flutter::gpu::Context* gpu_context,
int storage_mode,
int size_in_bytes) {
impeller::DeviceBufferDescriptor desc;
desc.storage_mode = flutter::gpu::ToImpellerStorageMode(storage_mode);
desc.size = size_in_bytes;
auto device_buffer =
gpu_context->GetContext()->GetResourceAllocator()->CreateBuffer(desc);
if (!device_buffer) {
FML_LOG(ERROR) << "Failed to create device buffer.";
return false;
}
auto res =
fml::MakeRefCounted<flutter::gpu::DeviceBuffer>(std::move(device_buffer));
res->AssociateWithDartWrapper(wrapper);
return true;
}
bool InternalFlutterGpu_DeviceBuffer_InitializeWithHostData(
Dart_Handle wrapper,
flutter::gpu::Context* gpu_context,
Dart_Handle byte_data) {
auto data = tonic::DartByteData(byte_data);
auto mapping = fml::NonOwnedMapping(reinterpret_cast<uint8_t*>(data.data()),
data.length_in_bytes());
auto device_buffer =
gpu_context->GetContext()->GetResourceAllocator()->CreateBufferWithCopy(
mapping);
if (!device_buffer) {
FML_LOG(ERROR) << "Failed to create device buffer with copy.";
return false;
}
auto res =
fml::MakeRefCounted<flutter::gpu::DeviceBuffer>(std::move(device_buffer));
res->AssociateWithDartWrapper(wrapper);
return true;
}
bool InternalFlutterGpu_DeviceBuffer_Overwrite(
flutter::gpu::DeviceBuffer* device_buffer,
Dart_Handle source_byte_data,
int destination_offset_in_bytes) {
return device_buffer->Overwrite(tonic::DartByteData(source_byte_data),
destination_offset_in_bytes);
}
| engine/lib/gpu/device_buffer.cc/0 | {
"file_path": "engine/lib/gpu/device_buffer.cc",
"repo_id": "engine",
"token_count": 1196
} | 232 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
part of flutter_gpu;
base class RenderPipeline extends NativeFieldWrapperClass1 {
/// Creates a new RenderPipeline.
RenderPipeline._(
GpuContext gpuContext, Shader vertexShader, Shader fragmentShader)
: vertexShader = vertexShader,
fragmentShader = fragmentShader {
String? error = _initialize(gpuContext, vertexShader, fragmentShader);
if (error != null) {
throw Exception(error);
}
}
final Shader vertexShader;
final Shader fragmentShader;
/// Wrap with native counterpart.
@Native<Handle Function(Handle, Pointer<Void>, Pointer<Void>, Pointer<Void>)>(
symbol: 'InternalFlutterGpu_RenderPipeline_Initialize')
external String? _initialize(
GpuContext gpuContext, Shader vertexShader, Shader fragmentShader);
}
| engine/lib/gpu/lib/src/render_pipeline.dart/0 | {
"file_path": "engine/lib/gpu/lib/src/render_pipeline.dart",
"repo_id": "engine",
"token_count": 325
} | 233 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/lib/gpu/texture.h"
#include "flutter/lib/gpu/formats.h"
#include "flutter/lib/ui/painting/image.h"
#include "fml/mapping.h"
#include "impeller/core/allocator.h"
#include "impeller/core/formats.h"
#include "impeller/core/texture.h"
#include "impeller/display_list/dl_image_impeller.h"
#include "third_party/tonic/typed_data/dart_byte_data.h"
namespace flutter {
namespace gpu {
IMPLEMENT_WRAPPERTYPEINFO(flutter_gpu, Texture);
Texture::Texture(std::shared_ptr<impeller::Texture> texture)
: texture_(std::move(texture)) {}
Texture::~Texture() = default;
std::shared_ptr<impeller::Texture> Texture::GetTexture() {
return texture_;
}
void Texture::SetCoordinateSystem(
impeller::TextureCoordinateSystem coordinate_system) {
texture_->SetCoordinateSystem(coordinate_system);
}
bool Texture::Overwrite(const tonic::DartByteData& source_bytes) {
const uint8_t* data = static_cast<const uint8_t*>(source_bytes.data());
auto copy = std::vector<uint8_t>(data, data + source_bytes.length_in_bytes());
// Texture::SetContents is a bit funky right now. It takes a shared_ptr of a
// mapping and we're forced to copy here.
auto mapping = std::make_shared<fml::DataMapping>(copy);
if (!texture_->SetContents(mapping)) {
return false;
}
return true;
}
size_t Texture::GetBytesPerTexel() {
return impeller::BytesPerPixelForPixelFormat(
texture_->GetTextureDescriptor().format);
}
Dart_Handle Texture::AsImage() const {
// DlImageImpeller isn't compiled in builds with Impeller disabled. If
// Impeller is disabled, it's impossible to get here anyhow, so just ifdef it
// out.
#if IMPELLER_SUPPORTS_RENDERING
auto image = flutter::CanvasImage::Create();
auto dl_image = impeller::DlImageImpeller::Make(texture_);
image->set_image(dl_image);
auto wrapped = image->CreateOuterWrapping();
return wrapped;
#else
return Dart_Null();
#endif
}
} // namespace gpu
} // namespace flutter
//----------------------------------------------------------------------------
/// Exports
///
bool InternalFlutterGpu_Texture_Initialize(Dart_Handle wrapper,
flutter::gpu::Context* gpu_context,
int storage_mode,
int format,
int width,
int height,
int sample_count,
int coordinate_system,
bool enable_render_target_usage,
bool enable_shader_read_usage,
bool enable_shader_write_usage) {
impeller::TextureDescriptor desc;
desc.storage_mode = flutter::gpu::ToImpellerStorageMode(storage_mode);
desc.size = {width, height};
desc.format = flutter::gpu::ToImpellerPixelFormat(format);
desc.usage = {};
if (enable_render_target_usage) {
desc.usage |= impeller::TextureUsage::kRenderTarget;
}
if (enable_shader_read_usage) {
desc.usage |= impeller::TextureUsage::kShaderRead;
}
if (enable_shader_write_usage) {
desc.usage |= impeller::TextureUsage::kShaderWrite;
}
switch (sample_count) {
case 1:
desc.type = impeller::TextureType::kTexture2D;
desc.sample_count = impeller::SampleCount::kCount1;
break;
case 4:
desc.type = impeller::TextureType::kTexture2DMultisample;
desc.sample_count = impeller::SampleCount::kCount4;
break;
default:
return false;
}
auto texture =
gpu_context->GetContext()->GetResourceAllocator()->CreateTexture(desc);
if (!texture) {
FML_LOG(ERROR) << "Failed to create texture.";
return false;
}
texture->SetCoordinateSystem(
flutter::gpu::ToImpellerTextureCoordinateSystem(coordinate_system));
auto res = fml::MakeRefCounted<flutter::gpu::Texture>(std::move(texture));
res->AssociateWithDartWrapper(wrapper);
return true;
}
void InternalFlutterGpu_Texture_SetCoordinateSystem(
flutter::gpu::Texture* wrapper,
int coordinate_system) {
return wrapper->SetCoordinateSystem(
flutter::gpu::ToImpellerTextureCoordinateSystem(coordinate_system));
}
bool InternalFlutterGpu_Texture_Overwrite(flutter::gpu::Texture* texture,
Dart_Handle source_byte_data) {
return texture->Overwrite(tonic::DartByteData(source_byte_data));
}
extern int InternalFlutterGpu_Texture_BytesPerTexel(
flutter::gpu::Texture* wrapper) {
return wrapper->GetBytesPerTexel();
}
Dart_Handle InternalFlutterGpu_Texture_AsImage(flutter::gpu::Texture* wrapper) {
return wrapper->AsImage();
}
| engine/lib/gpu/texture.cc/0 | {
"file_path": "engine/lib/gpu/texture.cc",
"repo_id": "engine",
"token_count": 1984
} | 234 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/lib/ui/compositing/scene.h"
#include "flutter/fml/trace_event.h"
#include "flutter/lib/ui/painting/display_list_deferred_image_gpu_skia.h"
#include "flutter/lib/ui/painting/image.h"
#include "flutter/lib/ui/painting/picture.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "flutter/lib/ui/window/platform_configuration.h"
#if IMPELLER_SUPPORTS_RENDERING
#include "flutter/lib/ui/painting/display_list_deferred_image_gpu_impeller.h"
#endif // IMPELLER_SUPPORTS_RENDERING
#include "third_party/skia/include/core/SkImageInfo.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_args.h"
#include "third_party/tonic/dart_binding_macros.h"
#include "third_party/tonic/dart_library_natives.h"
namespace flutter {
IMPLEMENT_WRAPPERTYPEINFO(ui, Scene);
void Scene::create(Dart_Handle scene_handle,
std::shared_ptr<flutter::Layer> rootLayer,
uint32_t rasterizerTracingThreshold,
bool checkerboardRasterCacheImages,
bool checkerboardOffscreenLayers) {
auto scene = fml::MakeRefCounted<Scene>(
std::move(rootLayer), rasterizerTracingThreshold,
checkerboardRasterCacheImages, checkerboardOffscreenLayers);
scene->AssociateWithDartWrapper(scene_handle);
}
Scene::Scene(std::shared_ptr<flutter::Layer> rootLayer,
uint32_t rasterizerTracingThreshold,
bool checkerboardRasterCacheImages,
bool checkerboardOffscreenLayers) {
layer_tree_config_.root_layer = std::move(rootLayer);
layer_tree_config_.rasterizer_tracing_threshold = rasterizerTracingThreshold;
layer_tree_config_.checkerboard_raster_cache_images =
checkerboardRasterCacheImages;
layer_tree_config_.checkerboard_offscreen_layers =
checkerboardOffscreenLayers;
}
Scene::~Scene() {}
bool Scene::valid() {
return layer_tree_config_.root_layer != nullptr;
}
void Scene::dispose() {
layer_tree_config_.root_layer.reset();
ClearDartWrapper();
}
Dart_Handle Scene::toImageSync(uint32_t width,
uint32_t height,
Dart_Handle raw_image_handle) {
TRACE_EVENT0("flutter", "Scene::toImageSync");
if (!valid()) {
return tonic::ToDart("Scene has been disposed.");
}
Scene::RasterizeToImage(width, height, raw_image_handle);
return Dart_Null();
}
Dart_Handle Scene::toImage(uint32_t width,
uint32_t height,
Dart_Handle raw_image_callback) {
TRACE_EVENT0("flutter", "Scene::toImage");
if (!valid()) {
return tonic::ToDart("Scene has been disposed.");
}
return Picture::RasterizeLayerTreeToImage(BuildLayerTree(width, height),
raw_image_callback);
}
static sk_sp<DlImage> CreateDeferredImage(
bool impeller,
std::unique_ptr<LayerTree> layer_tree,
fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate,
fml::RefPtr<fml::TaskRunner> raster_task_runner,
fml::RefPtr<SkiaUnrefQueue> unref_queue) {
#if IMPELLER_SUPPORTS_RENDERING
if (impeller) {
return DlDeferredImageGPUImpeller::Make(std::move(layer_tree),
std::move(snapshot_delegate),
std::move(raster_task_runner));
}
#endif // IMPELLER_SUPPORTS_RENDERING
const auto& frame_size = layer_tree->frame_size();
const SkImageInfo image_info =
SkImageInfo::Make(frame_size.width(), frame_size.height(),
kRGBA_8888_SkColorType, kPremul_SkAlphaType);
return DlDeferredImageGPUSkia::MakeFromLayerTree(
image_info, std::move(layer_tree), std::move(snapshot_delegate),
raster_task_runner, std::move(unref_queue));
}
void Scene::RasterizeToImage(uint32_t width,
uint32_t height,
Dart_Handle raw_image_handle) {
auto* dart_state = UIDartState::Current();
if (!dart_state) {
return;
}
auto unref_queue = dart_state->GetSkiaUnrefQueue();
auto snapshot_delegate = dart_state->GetSnapshotDelegate();
auto raster_task_runner = dart_state->GetTaskRunners().GetRasterTaskRunner();
auto image = CanvasImage::Create();
auto dl_image = CreateDeferredImage(
dart_state->IsImpellerEnabled(), BuildLayerTree(width, height),
std::move(snapshot_delegate), std::move(raster_task_runner),
std::move(unref_queue));
image->set_image(dl_image);
image->AssociateWithDartWrapper(raw_image_handle);
}
std::unique_ptr<flutter::LayerTree> Scene::takeLayerTree(uint64_t width,
uint64_t height) {
return BuildLayerTree(width, height);
}
std::unique_ptr<LayerTree> Scene::BuildLayerTree(uint32_t width,
uint32_t height) {
if (!valid()) {
return nullptr;
}
return std::make_unique<LayerTree>(layer_tree_config_,
SkISize::Make(width, height));
}
} // namespace flutter
| engine/lib/ui/compositing/scene.cc/0 | {
"file_path": "engine/lib/ui/compositing/scene.cc",
"repo_id": "engine",
"token_count": 2289
} | 235 |
#version 100 core
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
precision highp float;
layout(location = 0) out vec4 oColor;
layout(location = 1) uniform float floatArray[2];
layout(location = 3) uniform vec2 vec2Array[2];
layout(location = 7) uniform vec3 vec3Array[2];
layout(location = 13) uniform mat2 mat2Array[2];
void main() {
vec4 badColor = vec4(1.0, 0, 0, 1.0);
vec4 goodColor = vec4(0, 1.0, 0, 1.0);
// The test populates the uniforms with strictly increasing values, so if
// out-of-order values are read out of the uniforms, then the bad color that
// causes the test to fail is returned.
if (floatArray[0] >= floatArray[1] || floatArray[1] >= vec2Array[0].x ||
vec2Array[0].x >= vec2Array[0].y || vec2Array[0].y >= vec2Array[1].x ||
vec2Array[1].x >= vec2Array[1].y || vec2Array[1].y >= vec3Array[0].x ||
vec3Array[0].x >= vec3Array[0].y || vec3Array[0].y >= vec3Array[0].z ||
vec3Array[0].z >= vec3Array[1].x || vec3Array[1].x >= vec3Array[1].y ||
vec3Array[1].y >= vec3Array[1].z ||
vec3Array[1].z >= mat2Array[0][0][0] ||
mat2Array[0][0][0] >= mat2Array[0][0][1] ||
mat2Array[0][0][1] >= mat2Array[0][1][0] ||
mat2Array[0][1][0] >= mat2Array[0][1][1] ||
mat2Array[0][1][1] >= mat2Array[1][0][0] ||
mat2Array[1][0][0] >= mat2Array[1][0][1] ||
mat2Array[1][0][1] >= mat2Array[1][1][0] ||
mat2Array[1][1][0] >= mat2Array[1][1][1]) {
oColor = badColor;
} else {
oColor = goodColor;
}
}
| engine/lib/ui/fixtures/shaders/general_shaders/uniform_arrays.frag/0 | {
"file_path": "engine/lib/ui/fixtures/shaders/general_shaders/uniform_arrays.frag",
"repo_id": "engine",
"token_count": 685
} | 236 |
#version 320 es
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
precision highp float;
layout(location = 0) out vec4 fragColor;
layout(location = 0) uniform float a;
void main() {
fragColor =
vec4(0.0,
// dot product of incident vector (2nd param) and reference vector
// (3rd param) is non-negative, so the negated first param is
// returned, and its first value is 1.0.
faceforward(vec2(-a, 5.0), vec2(1.0, 2.0), vec2(3.0, 4.0))[0], 0.0,
// dot product of incident vector (2nd param) and reference vector
// (3rd param) is negative, so the original first param is returned,
// and its second value is 5.0, so subtract 4.0 to get 1.0.
faceforward(vec2(a, 5.0), vec2(1.0, -2.0), vec2(3.0, 4.0))[1] - 4.0);
}
| engine/lib/ui/fixtures/shaders/supported_glsl_op_shaders/70_faceforward.frag/0 | {
"file_path": "engine/lib/ui/fixtures/shaders/supported_glsl_op_shaders/70_faceforward.frag",
"repo_id": "engine",
"token_count": 375
} | 237 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_LIB_UI_PAINTING_DISPLAY_LIST_IMAGE_GPU_H_
#define FLUTTER_LIB_UI_PAINTING_DISPLAY_LIST_IMAGE_GPU_H_
#include "flutter/display_list/image/dl_image.h"
#include "flutter/flow/skia_gpu_object.h"
#include "flutter/fml/macros.h"
namespace flutter {
class DlImageGPU final : public DlImage {
public:
static sk_sp<DlImageGPU> Make(SkiaGPUObject<SkImage> image);
// |DlImage|
~DlImageGPU() override;
// |DlImage|
sk_sp<SkImage> skia_image() const override;
// |DlImage|
std::shared_ptr<impeller::Texture> impeller_texture() const override;
// |DlImage|
bool isOpaque() const override;
// |DlImage|
bool isTextureBacked() const override;
// |DlImage|
bool isUIThreadSafe() const override;
// |DlImage|
SkISize dimensions() const override;
// |DlImage|
virtual size_t GetApproximateByteSize() const override;
private:
SkiaGPUObject<SkImage> image_;
explicit DlImageGPU(SkiaGPUObject<SkImage> image);
FML_DISALLOW_COPY_AND_ASSIGN(DlImageGPU);
};
} // namespace flutter
#endif // FLUTTER_LIB_UI_PAINTING_DISPLAY_LIST_IMAGE_GPU_H_
| engine/lib/ui/painting/display_list_image_gpu.h/0 | {
"file_path": "engine/lib/ui/painting/display_list_image_gpu.h",
"repo_id": "engine",
"token_count": 466
} | 238 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_LIB_UI_PAINTING_IMAGE_DECODER_NO_GL_UNITTESTS_H_
#define FLUTTER_LIB_UI_PAINTING_IMAGE_DECODER_NO_GL_UNITTESTS_H_
#include <stdint.h>
#include "flutter/impeller/core/allocator.h"
#include "flutter/impeller/core/device_buffer.h"
#include "flutter/impeller/core/formats.h"
#include "flutter/impeller/geometry/size.h"
#include "flutter/lib/ui/painting/image_decoder.h"
#include "flutter/lib/ui/painting/image_decoder_impeller.h"
#include "flutter/testing/testing.h"
namespace impeller {
class TestImpellerTexture : public Texture {
public:
explicit TestImpellerTexture(TextureDescriptor desc) : Texture(desc) {}
void SetLabel(std::string_view label) override {}
bool IsValid() const override { return true; }
ISize GetSize() const { return GetTextureDescriptor().size; }
bool OnSetContents(const uint8_t* contents, size_t length, size_t slice) {
return true;
}
bool OnSetContents(std::shared_ptr<const fml::Mapping> mapping,
size_t slice) {
return true;
}
};
class TestImpellerDeviceBuffer : public DeviceBuffer {
public:
explicit TestImpellerDeviceBuffer(DeviceBufferDescriptor desc)
: DeviceBuffer(desc) {
bytes_ = static_cast<uint8_t*>(malloc(desc.size));
}
~TestImpellerDeviceBuffer() { free(bytes_); }
private:
std::shared_ptr<Texture> AsTexture(Allocator& allocator,
const TextureDescriptor& descriptor,
uint16_t row_bytes) const override {
return nullptr;
}
bool SetLabel(const std::string& label) override { return true; }
bool SetLabel(const std::string& label, Range range) override { return true; }
uint8_t* OnGetContents() const override { return bytes_; }
bool OnCopyHostBuffer(const uint8_t* source,
Range source_range,
size_t offset) override {
for (auto i = source_range.offset; i < source_range.length; i++, offset++) {
bytes_[offset] = source[i];
}
return true;
}
uint8_t* bytes_;
};
class TestImpellerAllocator : public impeller::Allocator {
public:
TestImpellerAllocator() {}
~TestImpellerAllocator() = default;
private:
uint16_t MinimumBytesPerRow(PixelFormat format) const override { return 0; }
ISize GetMaxTextureSizeSupported() const override {
return ISize{2048, 2048};
}
std::shared_ptr<DeviceBuffer> OnCreateBuffer(
const DeviceBufferDescriptor& desc) override {
return std::make_shared<TestImpellerDeviceBuffer>(desc);
}
std::shared_ptr<Texture> OnCreateTexture(
const TextureDescriptor& desc) override {
return std::make_shared<TestImpellerTexture>(desc);
}
};
} // namespace impeller
namespace flutter {
namespace testing {
float HalfToFloat(uint16_t half);
float DecodeBGR10(uint32_t x);
} // namespace testing
} // namespace flutter
#endif // FLUTTER_LIB_UI_PAINTING_IMAGE_DECODER_NO_GL_UNITTESTS_H_
| engine/lib/ui/painting/image_decoder_no_gl_unittests.h/0 | {
"file_path": "engine/lib/ui/painting/image_decoder_no_gl_unittests.h",
"repo_id": "engine",
"token_count": 1173
} | 239 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_LIB_UI_PAINTING_IMAGE_FILTER_H_
#define FLUTTER_LIB_UI_PAINTING_IMAGE_FILTER_H_
#include "flutter/display_list/dl_sampling_options.h"
#include "flutter/display_list/effects/dl_image_filter.h"
#include "flutter/lib/ui/dart_wrapper.h"
#include "flutter/lib/ui/painting/color_filter.h"
#include "third_party/tonic/typed_data/typed_list.h"
namespace tonic {
class DartLibraryNatives;
} // namespace tonic
namespace flutter {
class ImageFilter : public RefCountedDartWrappable<ImageFilter> {
DEFINE_WRAPPERTYPEINFO();
FML_FRIEND_MAKE_REF_COUNTED(ImageFilter);
public:
~ImageFilter() override;
static void Create(Dart_Handle wrapper);
static DlImageSampling SamplingFromIndex(int filterQualityIndex);
static DlFilterMode FilterModeFromIndex(int index);
void initBlur(double sigma_x, double sigma_y, DlTileMode tile_mode);
void initDilate(double radius_x, double radius_y);
void initErode(double radius_x, double radius_y);
void initMatrix(const tonic::Float64List& matrix4, int filter_quality_index);
void initColorFilter(ColorFilter* colorFilter);
void initComposeFilter(ImageFilter* outer, ImageFilter* inner);
const std::shared_ptr<const DlImageFilter> filter() const { return filter_; }
static void RegisterNatives(tonic::DartLibraryNatives* natives);
private:
ImageFilter();
std::shared_ptr<const DlImageFilter> filter_;
};
} // namespace flutter
#endif // FLUTTER_LIB_UI_PAINTING_IMAGE_FILTER_H_
| engine/lib/ui/painting/image_filter.h/0 | {
"file_path": "engine/lib/ui/painting/image_filter.h",
"repo_id": "engine",
"token_count": 550
} | 240 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/lib/ui/painting/paint.h"
#include "flutter/display_list/dl_builder.h"
#include "flutter/fml/logging.h"
#include "flutter/lib/ui/floating_point.h"
#include "flutter/lib/ui/painting/color_filter.h"
#include "flutter/lib/ui/painting/image_filter.h"
#include "flutter/lib/ui/painting/shader.h"
#include "third_party/skia/include/core/SkColorFilter.h"
#include "third_party/skia/include/core/SkImageFilter.h"
#include "third_party/skia/include/core/SkMaskFilter.h"
#include "third_party/skia/include/core/SkShader.h"
#include "third_party/skia/include/core/SkString.h"
#include "third_party/tonic/typed_data/dart_byte_data.h"
#include "third_party/tonic/typed_data/typed_list.h"
namespace flutter {
// Indices for 32bit values.
constexpr int kIsAntiAliasIndex = 0;
constexpr int kColorIndex = 1;
constexpr int kBlendModeIndex = 2;
constexpr int kStyleIndex = 3;
constexpr int kStrokeWidthIndex = 4;
constexpr int kStrokeCapIndex = 5;
constexpr int kStrokeJoinIndex = 6;
constexpr int kStrokeMiterLimitIndex = 7;
constexpr int kFilterQualityIndex = 8;
constexpr int kMaskFilterIndex = 9;
constexpr int kMaskFilterBlurStyleIndex = 10;
constexpr int kMaskFilterSigmaIndex = 11;
constexpr int kInvertColorIndex = 12;
constexpr size_t kDataByteCount = 52; // 4 * (last index + 1)
static_assert(kDataByteCount == sizeof(uint32_t) * (kInvertColorIndex + 1),
"kDataByteCount must match the size of the data array.");
// Indices for objects.
constexpr int kShaderIndex = 0;
constexpr int kColorFilterIndex = 1;
constexpr int kImageFilterIndex = 2;
constexpr int kObjectCount = 3; // One larger than largest object index.
// Must be kept in sync with the default in painting.dart.
constexpr uint32_t kColorDefault = 0xFF000000;
// Must be kept in sync with the default in painting.dart.
constexpr uint32_t kBlendModeDefault =
static_cast<uint32_t>(SkBlendMode::kSrcOver);
// Must be kept in sync with the default in painting.dart, and also with the
// default SkPaintDefaults_MiterLimit in Skia (which is not in a public header).
constexpr float kStrokeMiterLimitDefault = 4.0f;
// Must be kept in sync with the MaskFilter private constants in painting.dart.
enum MaskFilterType { kNull, kBlur };
Paint::Paint(Dart_Handle paint_objects, Dart_Handle paint_data)
: paint_objects_(paint_objects), paint_data_(paint_data) {}
const DlPaint* Paint::paint(DlPaint& paint,
const DisplayListAttributeFlags& flags) const {
if (isNull()) {
return nullptr;
}
tonic::DartByteData byte_data(paint_data_);
FML_CHECK(byte_data.length_in_bytes() == kDataByteCount);
const uint32_t* uint_data = static_cast<const uint32_t*>(byte_data.data());
const float* float_data = static_cast<const float*>(byte_data.data());
Dart_Handle values[kObjectCount];
if (Dart_IsNull(paint_objects_)) {
if (flags.applies_shader()) {
paint.setColorSource(nullptr);
}
if (flags.applies_color_filter()) {
paint.setColorFilter(nullptr);
}
if (flags.applies_image_filter()) {
paint.setImageFilter(nullptr);
}
} else {
FML_DCHECK(Dart_IsList(paint_objects_));
intptr_t length = 0;
Dart_ListLength(paint_objects_, &length);
FML_CHECK(length == kObjectCount);
if (Dart_IsError(
Dart_ListGetRange(paint_objects_, 0, kObjectCount, values))) {
return nullptr;
}
if (flags.applies_shader()) {
Dart_Handle shader = values[kShaderIndex];
if (Dart_IsNull(shader)) {
paint.setColorSource(nullptr);
} else {
if (Shader* decoded = tonic::DartConverter<Shader*>::FromDart(shader)) {
auto sampling =
ImageFilter::SamplingFromIndex(uint_data[kFilterQualityIndex]);
paint.setColorSource(decoded->shader(sampling));
} else {
paint.setColorSource(nullptr);
}
}
}
if (flags.applies_color_filter()) {
Dart_Handle color_filter = values[kColorFilterIndex];
if (Dart_IsNull(color_filter)) {
paint.setColorFilter(nullptr);
} else {
ColorFilter* decoded =
tonic::DartConverter<ColorFilter*>::FromDart(color_filter);
paint.setColorFilter(decoded->filter());
}
}
if (flags.applies_image_filter()) {
Dart_Handle image_filter = values[kImageFilterIndex];
if (Dart_IsNull(image_filter)) {
paint.setImageFilter(nullptr);
} else {
ImageFilter* decoded =
tonic::DartConverter<ImageFilter*>::FromDart(image_filter);
paint.setImageFilter(decoded->filter());
}
}
}
if (flags.applies_anti_alias()) {
paint.setAntiAlias(uint_data[kIsAntiAliasIndex] == 0);
}
if (flags.applies_alpha_or_color()) {
uint32_t encoded_color = uint_data[kColorIndex];
paint.setColor(DlColor(encoded_color ^ kColorDefault));
}
if (flags.applies_blend()) {
uint32_t encoded_blend_mode = uint_data[kBlendModeIndex];
uint32_t blend_mode = encoded_blend_mode ^ kBlendModeDefault;
paint.setBlendMode(static_cast<DlBlendMode>(blend_mode));
}
if (flags.applies_style()) {
uint32_t style = uint_data[kStyleIndex];
paint.setDrawStyle(static_cast<DlDrawStyle>(style));
}
if (flags.is_stroked(paint.getDrawStyle())) {
float stroke_width = float_data[kStrokeWidthIndex];
paint.setStrokeWidth(stroke_width);
float stroke_miter_limit = float_data[kStrokeMiterLimitIndex];
paint.setStrokeMiter(stroke_miter_limit + kStrokeMiterLimitDefault);
uint32_t stroke_cap = uint_data[kStrokeCapIndex];
paint.setStrokeCap(static_cast<DlStrokeCap>(stroke_cap));
uint32_t stroke_join = uint_data[kStrokeJoinIndex];
paint.setStrokeJoin(static_cast<DlStrokeJoin>(stroke_join));
}
if (flags.applies_color_filter()) {
paint.setInvertColors(uint_data[kInvertColorIndex] != 0);
}
if (flags.applies_path_effect()) {
// The paint API exposed to Dart does not support path effects. But other
// operations such as text may set a path effect, which must be cleared.
paint.setPathEffect(nullptr);
}
if (flags.applies_mask_filter()) {
switch (uint_data[kMaskFilterIndex]) {
case kNull:
paint.setMaskFilter(nullptr);
break;
case kBlur:
DlBlurStyle blur_style =
static_cast<DlBlurStyle>(uint_data[kMaskFilterBlurStyleIndex]);
double sigma = float_data[kMaskFilterSigmaIndex];
paint.setMaskFilter(
DlBlurMaskFilter::Make(blur_style, SafeNarrow(sigma)));
break;
}
}
return &paint;
}
void Paint::toDlPaint(DlPaint& paint) const {
if (isNull()) {
return;
}
FML_DCHECK(paint == DlPaint());
tonic::DartByteData byte_data(paint_data_);
FML_CHECK(byte_data.length_in_bytes() == kDataByteCount);
const uint32_t* uint_data = static_cast<const uint32_t*>(byte_data.data());
const float* float_data = static_cast<const float*>(byte_data.data());
Dart_Handle values[kObjectCount];
if (!Dart_IsNull(paint_objects_)) {
FML_DCHECK(Dart_IsList(paint_objects_));
intptr_t length = 0;
Dart_ListLength(paint_objects_, &length);
FML_CHECK(length == kObjectCount);
if (Dart_IsError(
Dart_ListGetRange(paint_objects_, 0, kObjectCount, values))) {
return;
}
Dart_Handle shader = values[kShaderIndex];
if (!Dart_IsNull(shader)) {
if (Shader* decoded = tonic::DartConverter<Shader*>::FromDart(shader)) {
auto sampling =
ImageFilter::SamplingFromIndex(uint_data[kFilterQualityIndex]);
paint.setColorSource(decoded->shader(sampling));
}
}
Dart_Handle color_filter = values[kColorFilterIndex];
if (!Dart_IsNull(color_filter)) {
ColorFilter* decoded =
tonic::DartConverter<ColorFilter*>::FromDart(color_filter);
paint.setColorFilter(decoded->filter());
}
Dart_Handle image_filter = values[kImageFilterIndex];
if (!Dart_IsNull(image_filter)) {
ImageFilter* decoded =
tonic::DartConverter<ImageFilter*>::FromDart(image_filter);
paint.setImageFilter(decoded->filter());
}
}
paint.setAntiAlias(uint_data[kIsAntiAliasIndex] == 0);
uint32_t encoded_color = uint_data[kColorIndex];
paint.setColor(DlColor(encoded_color ^ kColorDefault));
uint32_t encoded_blend_mode = uint_data[kBlendModeIndex];
uint32_t blend_mode = encoded_blend_mode ^ kBlendModeDefault;
paint.setBlendMode(static_cast<DlBlendMode>(blend_mode));
uint32_t style = uint_data[kStyleIndex];
paint.setDrawStyle(static_cast<DlDrawStyle>(style));
float stroke_width = float_data[kStrokeWidthIndex];
paint.setStrokeWidth(stroke_width);
float stroke_miter_limit = float_data[kStrokeMiterLimitIndex];
paint.setStrokeMiter(stroke_miter_limit + kStrokeMiterLimitDefault);
uint32_t stroke_cap = uint_data[kStrokeCapIndex];
paint.setStrokeCap(static_cast<DlStrokeCap>(stroke_cap));
uint32_t stroke_join = uint_data[kStrokeJoinIndex];
paint.setStrokeJoin(static_cast<DlStrokeJoin>(stroke_join));
paint.setInvertColors(uint_data[kInvertColorIndex] != 0);
switch (uint_data[kMaskFilterIndex]) {
case kNull:
break;
case kBlur:
DlBlurStyle blur_style =
static_cast<DlBlurStyle>(uint_data[kMaskFilterBlurStyleIndex]);
float sigma = SafeNarrow(float_data[kMaskFilterSigmaIndex]);
// Make could return a nullptr here if the values are NOP or
// do not make sense. We could interpret that as if there was
// no value passed from Dart at all (i.e. don't change the
// setting in the paint object as in the kNull branch right
// above here), but the maskfilter flag was actually set
// indicating that the developer "tried" to set a mask, so we
// should set the null value rather than do nothing.
paint.setMaskFilter(DlBlurMaskFilter::Make(blur_style, sigma));
break;
}
}
} // namespace flutter
namespace tonic {
flutter::Paint DartConverter<flutter::Paint>::FromArguments(
Dart_NativeArguments args,
int index,
Dart_Handle& exception) {
Dart_Handle paint_objects = Dart_GetNativeArgument(args, index);
FML_DCHECK(!CheckAndHandleError(paint_objects));
Dart_Handle paint_data = Dart_GetNativeArgument(args, index + 1);
FML_DCHECK(!CheckAndHandleError(paint_data));
return flutter::Paint(paint_objects, paint_data);
}
flutter::PaintData DartConverter<flutter::PaintData>::FromArguments(
Dart_NativeArguments args,
int index,
Dart_Handle& exception) {
return flutter::PaintData();
}
} // namespace tonic
| engine/lib/ui/painting/paint.cc/0 | {
"file_path": "engine/lib/ui/painting/paint.cc",
"repo_id": "engine",
"token_count": 4195
} | 241 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/lib/ui/painting/scene/scene_shader.h"
#include <memory>
#include <utility>
#include "flutter/display_list/dl_tile_mode.h"
#include "flutter/display_list/effects/dl_color_source.h"
#include "flutter/lib/ui/dart_wrapper.h"
#include "flutter/lib/ui/painting/scene/scene_node.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "impeller/geometry/scalar.h"
#include "impeller/geometry/size.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_args.h"
#include "third_party/tonic/dart_binding_macros.h"
#include "third_party/tonic/dart_library_natives.h"
#include "third_party/tonic/typed_data/typed_list.h"
namespace flutter {
IMPLEMENT_WRAPPERTYPEINFO(ui, SceneShader);
SceneShader::SceneShader(fml::RefPtr<SceneNode> scene_node)
: scene_node_(std::move(scene_node)) {}
void SceneShader::Create(Dart_Handle wrapper, Dart_Handle scene_node_handle) {
auto* scene_node =
tonic::DartConverter<SceneNode*>::FromDart(scene_node_handle);
if (!scene_node) {
return;
}
auto res = fml::MakeRefCounted<SceneShader>(fml::Ref(scene_node));
res->AssociateWithDartWrapper(wrapper);
}
void SceneShader::SetCameraTransform(const tonic::Float64List& matrix4) {
camera_transform_ =
impeller::Matrix(static_cast<impeller::Scalar>(matrix4[0]),
static_cast<impeller::Scalar>(matrix4[1]),
static_cast<impeller::Scalar>(matrix4[2]),
static_cast<impeller::Scalar>(matrix4[3]),
static_cast<impeller::Scalar>(matrix4[4]),
static_cast<impeller::Scalar>(matrix4[5]),
static_cast<impeller::Scalar>(matrix4[6]),
static_cast<impeller::Scalar>(matrix4[7]),
static_cast<impeller::Scalar>(matrix4[8]),
static_cast<impeller::Scalar>(matrix4[9]),
static_cast<impeller::Scalar>(matrix4[10]),
static_cast<impeller::Scalar>(matrix4[11]),
static_cast<impeller::Scalar>(matrix4[12]),
static_cast<impeller::Scalar>(matrix4[13]),
static_cast<impeller::Scalar>(matrix4[14]),
static_cast<impeller::Scalar>(matrix4[15]));
}
static impeller::Matrix DefaultCameraTransform() {
// TODO(bdero): There's no way to know what the draw area will be yet, so
// make the DlSceneColorSource camera transform optional and
// defer this default (or parameterize the camera instead).
return impeller::Matrix::MakePerspective(
impeller::Degrees(45), impeller::ISize{800, 600}, 0.1f, 1000) *
impeller::Matrix::MakeLookAt({0, 0, -5}, {0, 0, 0}, {0, 1, 0});
}
std::shared_ptr<DlColorSource> SceneShader::shader(DlImageSampling sampling) {
FML_CHECK(scene_node_);
if (!scene_node_->node_) {
return nullptr;
}
// TODO(bdero): Gather the mutation log and include it in the scene color
// source.
auto source = std::make_shared<DlSceneColorSource>(
scene_node_->node_, camera_transform_.IsIdentity()
? DefaultCameraTransform()
: camera_transform_);
// Just a sanity check, all scene shaders should be thread-safe
FML_DCHECK(source->isUIThreadSafe());
return source;
}
void SceneShader::Dispose() {
scene_node_ = nullptr;
ClearDartWrapper();
}
SceneShader::~SceneShader() = default;
} // namespace flutter
| engine/lib/ui/painting/scene/scene_shader.cc/0 | {
"file_path": "engine/lib/ui/painting/scene/scene_shader.cc",
"repo_id": "engine",
"token_count": 1660
} | 242 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/lib/ui/text/font_collection.h"
#include <mutex>
#include "flutter/lib/ui/text/asset_manager_font_provider.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "flutter/lib/ui/window/platform_configuration.h"
#include "flutter/runtime/test_font_data.h"
#include "rapidjson/document.h"
#include "rapidjson/rapidjson.h"
#include "third_party/skia/include/core/SkFontMgr.h"
#include "third_party/skia/include/core/SkGraphics.h"
#include "third_party/skia/include/core/SkStream.h"
#include "third_party/skia/include/core/SkTypeface.h"
#include "third_party/tonic/dart_args.h"
#include "third_party/tonic/dart_library_natives.h"
#include "third_party/tonic/logging/dart_invoke.h"
#include "third_party/tonic/typed_data/typed_list.h"
#include "txt/asset_font_manager.h"
#include "txt/platform.h"
#include "txt/test_font_manager.h"
#if FML_OS_MACOSX || FML_OS_IOS
#include "txt/platform_mac.h"
#endif
namespace flutter {
FontCollection::FontCollection()
: collection_(std::make_shared<txt::FontCollection>()) {
dynamic_font_manager_ = sk_make_sp<txt::DynamicFontManager>();
collection_->SetDynamicFontManager(dynamic_font_manager_);
}
FontCollection::~FontCollection() {
collection_.reset();
SkGraphics::PurgeFontCache();
}
std::shared_ptr<txt::FontCollection> FontCollection::GetFontCollection() const {
return collection_;
}
void FontCollection::SetupDefaultFontManager(
uint32_t font_initialization_data) {
collection_->SetupDefaultFontManager(font_initialization_data);
}
// Font manifest yaml format:
//
// flutter:
// fonts:
// - family: Raleway
// fonts:
// - asset: fonts/Raleway-Regular.ttf
// - asset: fonts/Raleway-Italic.ttf
// style: italic
// - family: RobotoMono
// fonts:
// - asset: fonts/RobotoMono-Regular.ttf
// - asset: fonts/RobotoMono-Bold.ttf
// weight: 700
//
// Structure described in https://docs.flutter.dev/cookbook/design/fonts
void FontCollection::RegisterFonts(
const std::shared_ptr<AssetManager>& asset_manager) {
#if FML_OS_MACOSX || FML_OS_IOS
RegisterSystemFonts(*dynamic_font_manager_);
#endif
std::unique_ptr<fml::Mapping> manifest_mapping =
asset_manager->GetAsMapping("FontManifest.json");
if (manifest_mapping == nullptr) {
FML_DLOG(WARNING) << "Could not find the font manifest in the asset store.";
return;
}
rapidjson::Document document;
static_assert(sizeof(decltype(document)::Ch) == sizeof(uint8_t), "");
document.Parse(reinterpret_cast<const decltype(document)::Ch*>(
manifest_mapping->GetMapping()),
manifest_mapping->GetSize());
if (document.HasParseError()) {
FML_DLOG(WARNING) << "Error parsing the font manifest in the asset store.";
return;
}
if (!document.IsArray()) {
return;
}
auto font_provider =
std::make_unique<AssetManagerFontProvider>(asset_manager);
for (const auto& family : document.GetArray()) {
auto family_name = family.FindMember("family");
if (family_name == family.MemberEnd() || !family_name->value.IsString()) {
continue;
}
auto family_fonts = family.FindMember("fonts");
if (family_fonts == family.MemberEnd() || !family_fonts->value.IsArray()) {
continue;
}
for (const auto& family_font : family_fonts->value.GetArray()) {
if (!family_font.IsObject()) {
continue;
}
auto font_asset = family_font.FindMember("asset");
if (font_asset == family_font.MemberEnd() ||
!font_asset->value.IsString()) {
continue;
}
// TODO(chinmaygarde): Handle weights and styles.
font_provider->RegisterAsset(family_name->value.GetString(),
font_asset->value.GetString());
}
}
collection_->SetAssetFontManager(
sk_make_sp<txt::AssetFontManager>(std::move(font_provider)));
}
void FontCollection::RegisterTestFonts() {
std::vector<sk_sp<SkTypeface>> test_typefaces = GetTestFontData();
std::unique_ptr<txt::TypefaceFontAssetProvider> font_provider =
std::make_unique<txt::TypefaceFontAssetProvider>();
size_t index = 0;
std::vector<std::string> names = GetTestFontFamilyNames();
for (sk_sp<SkTypeface> typeface : test_typefaces) {
if (typeface) {
font_provider->RegisterTypeface(std::move(typeface), names[index]);
}
index++;
}
collection_->SetTestFontManager(
sk_make_sp<txt::TestFontManager>(std::move(font_provider), names));
collection_->DisableFontFallback();
}
void FontCollection::LoadFontFromList(Dart_Handle font_data_handle,
Dart_Handle callback,
const std::string& family_name) {
tonic::Uint8List font_data(font_data_handle);
UIDartState::ThrowIfUIOperationsProhibited();
FontCollection& font_collection = UIDartState::Current()
->platform_configuration()
->client()
->GetFontCollection();
std::unique_ptr<SkStreamAsset> font_stream = std::make_unique<SkMemoryStream>(
font_data.data(), font_data.num_elements(), true);
sk_sp<SkFontMgr> font_mgr = txt::GetDefaultFontManager();
sk_sp<SkTypeface> typeface = font_mgr->makeFromStream(std::move(font_stream));
txt::TypefaceFontAssetProvider& font_provider =
font_collection.dynamic_font_manager_->font_provider();
if (family_name.empty()) {
font_provider.RegisterTypeface(typeface);
} else {
font_provider.RegisterTypeface(typeface, family_name);
}
font_collection.collection_->ClearFontFamilyCache();
font_data.Release();
tonic::DartInvoke(callback, {tonic::ToDart(0)});
}
} // namespace flutter
| engine/lib/ui/text/font_collection.cc/0 | {
"file_path": "engine/lib/ui/text/font_collection.cc",
"repo_id": "engine",
"token_count": 2343
} | 243 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_LIB_UI_WINDOW_KEY_DATA_PACKET_H_
#define FLUTTER_LIB_UI_WINDOW_KEY_DATA_PACKET_H_
#include <functional>
#include <vector>
#include "flutter/fml/macros.h"
#include "flutter/lib/ui/window/key_data.h"
namespace flutter {
// A byte stream representing a key event, to be sent to the framework.
//
// Changes to the marshalling format here must also be made to
// io/flutter/embedding/android/KeyData.java.
class KeyDataPacket {
public:
// Build the key data packet by providing information.
//
// The `character` is a nullable C-string that ends with a '\0'.
KeyDataPacket(const KeyData& event, const char* character);
~KeyDataPacket();
// Prevent copying.
KeyDataPacket(KeyDataPacket const&) = delete;
KeyDataPacket& operator=(KeyDataPacket const&) = delete;
const std::vector<uint8_t>& data() const { return data_; }
private:
// Packet structure:
// | CharDataSize | (1 field)
// | Key Data | (kKeyDataFieldCount fields)
// | CharData | (CharDataSize bits)
uint8_t* CharacterSizeStart() { return data_.data(); }
uint8_t* KeyDataStart() { return CharacterSizeStart() + sizeof(uint64_t); }
uint8_t* CharacterStart() { return KeyDataStart() + sizeof(KeyData); }
std::vector<uint8_t> data_;
};
} // namespace flutter
#endif // FLUTTER_LIB_UI_WINDOW_KEY_DATA_PACKET_H_
| engine/lib/ui/window/key_data_packet.h/0 | {
"file_path": "engine/lib/ui/window/key_data_packet.h",
"repo_id": "engine",
"token_count": 522
} | 244 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/lib/ui/window/pointer_data.h"
#include <cstring>
namespace flutter {
// The number of fields of PointerData.
//
// If kPointerDataFieldCount changes, update the corresponding values to:
//
// * _kPointerDataFieldCount in platform_dispatcher.dart
// * POINTER_DATA_FIELD_COUNT in AndroidTouchProcessor.java
//
// (This is a centralized list of all locations that should be kept up-to-date.)
static constexpr int kPointerDataFieldCount = 36;
static constexpr int kBytesPerField = sizeof(int64_t);
static_assert(sizeof(PointerData) == kBytesPerField * kPointerDataFieldCount,
"PointerData has the wrong size");
void PointerData::Clear() {
memset(this, 0, sizeof(PointerData));
}
} // namespace flutter
| engine/lib/ui/window/pointer_data.cc/0 | {
"file_path": "engine/lib/ui/window/pointer_data.cc",
"repo_id": "engine",
"token_count": 287
} | 245 |
# For more information on test and runner configurations:
#
# * https://github.com/dart-lang/test/blob/master/pkgs/test/doc/configuration.md#platforms
platforms:
- firefox
- vm
| engine/lib/web_ui/dart_test_firefox.yaml/0 | {
"file_path": "engine/lib/web_ui/dart_test_firefox.yaml",
"repo_id": "engine",
"token_count": 62
} | 246 |
:: felt: a command-line utility for Windows for building and testing
:: Flutter web engine.
:: FELT stands for Flutter Engine Local Tester.
@ECHO OFF
SETLOCAL
:: Starting from this script's path, walk up to engine source directory.
SET SCRIPT_DIR=%~dp0
FOR %%a IN ("%SCRIPT_DIR:~0,-1%") DO SET TMP=%%~dpa
FOR %%a IN ("%TMP:~0,-1%") DO SET TMP=%%~dpa
FOR %%a IN ("%TMP:~0,-1%") DO SET TMP=%%~dpa
FOR %%a IN ("%TMP:~0,-1%") DO SET ENGINE_SRC_DIR=%%~dpa
SET ENGINE_SRC_DIR=%ENGINE_SRC_DIR:~0,-1%
SET FLUTTER_DIR=%ENGINE_SRC_DIR%\flutter
SET WEB_UI_DIR=%FLUTTER_DIR%\lib\web_ui
SET SDK_PREBUILTS_DIR=%FLUTTER_DIR%\prebuilts
SET PREBUILT_TARGET=windows-x64
IF NOT DEFINED DART_SDK_DIR (
SET DART_SDK_DIR=%SDK_PREBUILTS_DIR%\%PREBUILT_TARGET%\dart-sdk
)
SET DART_BIN=%DART_SDK_DIR%\bin\dart
cd %WEB_UI_DIR%
:: We need to invoke pub get here before we actually invoke felt.
%DART_BIN% pub get
%DART_BIN% run dev/felt.dart %*
EXIT /B %ERRORLEVEL%
| engine/lib/web_ui/dev/felt.bat/0 | {
"file_path": "engine/lib/web_ui/dev/felt.bat",
"repo_id": "engine",
"token_count": 425
} | 247 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' as io;
import 'felt_config.dart';
class SuiteFilterResult {
SuiteFilterResult.accepted();
SuiteFilterResult.rejected(String reason) : rejectReason = reason;
String? rejectReason;
bool get isAccepted => rejectReason == null;
}
abstract class SuiteFilter {
SuiteFilterResult filterSuite(TestSuite suite);
}
abstract class AllowListSuiteFilter<T> implements SuiteFilter {
AllowListSuiteFilter({ required this.allowList });
final Set<T> allowList;
T getAttributeForSuite(TestSuite suite);
String rejectReason(TestSuite suite) {
return '${getAttributeForSuite(suite)} does not match filter.';
}
@override
SuiteFilterResult filterSuite(TestSuite suite) {
if (allowList.contains(getAttributeForSuite(suite))) {
return SuiteFilterResult.accepted();
} else {
return SuiteFilterResult.rejected(rejectReason(suite));
}
}
}
class BrowserSuiteFilter extends AllowListSuiteFilter<BrowserName> {
BrowserSuiteFilter({required super.allowList});
@override
BrowserName getAttributeForSuite(TestSuite suite) => suite.runConfig.browser;
}
class SuiteNameFilter extends AllowListSuiteFilter<String> {
SuiteNameFilter({required super.allowList});
@override
String getAttributeForSuite(TestSuite suite) => suite.name;
}
class BundleNameFilter extends AllowListSuiteFilter<String> {
BundleNameFilter({required super.allowList});
@override
String getAttributeForSuite(TestSuite suite) => suite.testBundle.name;
}
class FileFilter extends BundleNameFilter {
FileFilter({required super.allowList});
@override
String rejectReason(TestSuite suite) {
return "Doesn't contain any of the indicated files.";
}
}
class CompilerFilter extends SuiteFilter {
CompilerFilter({required this.allowList});
final Set<Compiler> allowList;
@override
SuiteFilterResult filterSuite(TestSuite suite) => suite.testBundle.compileConfigs.any(
(CompileConfiguration config) => allowList.contains(config.compiler)
) ? SuiteFilterResult.accepted()
: SuiteFilterResult.rejected('Selected compilers not used in suite.');
}
class RendererFilter extends SuiteFilter {
RendererFilter({required this.allowList});
final Set<Renderer> allowList;
@override
SuiteFilterResult filterSuite(TestSuite suite) => suite.testBundle.compileConfigs.any(
(CompileConfiguration config) => allowList.contains(config.renderer)
) ? SuiteFilterResult.accepted()
: SuiteFilterResult.rejected('Selected renderers not used in suite.');
}
class CanvasKitVariantFilter extends AllowListSuiteFilter<CanvasKitVariant> {
CanvasKitVariantFilter({required super.allowList});
@override
// TODO(jackson): Is this the right default?
CanvasKitVariant getAttributeForSuite(TestSuite suite) => suite.runConfig.variant ?? CanvasKitVariant.full;
}
Set<BrowserName> get _supportedPlatformBrowsers {
if (io.Platform.isLinux) {
return <BrowserName>{
BrowserName.chrome,
BrowserName.firefox
};
} else if (io.Platform.isMacOS) {
return <BrowserName>{
BrowserName.chrome,
BrowserName.firefox,
BrowserName.safari,
};
} else if (io.Platform.isWindows) {
return <BrowserName>{
BrowserName.chrome,
BrowserName.edge,
};
} else {
throw AssertionError('Unsupported OS: ${io.Platform.operatingSystem}');
}
}
class PlatformBrowserFilter extends BrowserSuiteFilter {
PlatformBrowserFilter() : super(allowList: _supportedPlatformBrowsers);
@override
String rejectReason(TestSuite suite) =>
'Current platform (${io.Platform.operatingSystem}) does not support browser ${suite.runConfig.browser}';
}
| engine/lib/web_ui/dev/suite_filter.dart/0 | {
"file_path": "engine/lib/web_ui/dev/suite_filter.dart",
"repo_id": "engine",
"token_count": 1200
} | 248 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import { createWasmInstantiator } from "./instantiate_wasm.js";
export const loadSkwasm = (deps, config, browserEnvironment, engineRevision) => {
return new Promise((resolve, reject) => {
const baseUrl = config.canvasKitBaseUrl ?? `https://www.gstatic.com/flutter-canvaskit/${engineRevision}/`;
let skwasmUrl = `${baseUrl}skwasm.js`;
if (deps.flutterTT.policy) {
skwasmUrl = deps.flutterTT.policy.createScriptURL(skwasmUrl);
}
const wasmInstantiator = createWasmInstantiator(`${baseUrl}skwasm.wasm`);
const script = document.createElement("script");
script.src = skwasmUrl;
if (config.nonce) {
script.nonce = config.nonce;
}
script.addEventListener('load', async () => {
try {
const skwasmInstance = await skwasm({
instantiateWasm: wasmInstantiator,
locateFile: (fileName, scriptDirectory) => {
// When hosted via a CDN or some other url that is not the same
// origin as the main script of the page, we will fail to create
// a web worker with the .worker.js script. This workaround will
// make sure that the worker JS can be loaded regardless of where
// it is hosted.
const url = scriptDirectory + fileName;
if (url.endsWith('.worker.js')) {
return URL.createObjectURL(new Blob(
[`importScripts('${url}');`],
{ 'type': 'application/javascript' }));
}
return url;
}
});
resolve(skwasmInstance);
} catch (e) {
reject(e);
}
});
script.addEventListener('error', reject);
document.head.appendChild(script);
});
}
| engine/lib/web_ui/flutter_js/src/skwasm_loader.js/0 | {
"file_path": "engine/lib/web_ui/flutter_js/src/skwasm_loader.js",
"repo_id": "engine",
"token_count": 774
} | 249 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
part of ui;
abstract class PathMetrics extends collection.IterableBase<PathMetric> {
@override
Iterator<PathMetric> get iterator;
}
abstract class PathMetricIterator implements Iterator<PathMetric> {
@override
PathMetric get current;
@override
bool moveNext();
}
abstract class PathMetric {
double get length;
int get contourIndex;
Tangent? getTangentForOffset(double distance);
Path extractPath(double start, double end, {bool startWithMoveTo = true});
bool get isClosed;
}
class Tangent {
const Tangent(this.position, this.vector);
factory Tangent.fromAngle(Offset position, double angle) {
return Tangent(position, Offset(math.cos(angle), math.sin(angle)));
}
final Offset position;
final Offset vector;
// flip the sign to be consistent with [Path.arcTo]'s `sweepAngle`
double get angle => -math.atan2(vector.dy, vector.dx);
}
| engine/lib/web_ui/lib/path_metrics.dart/0 | {
"file_path": "engine/lib/web_ui/lib/path_metrics.dart",
"repo_id": "engine",
"token_count": 324
} | 250 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:typed_data';
import 'package:ui/src/engine.dart';
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
// This URL was found by using the Google Fonts Developer API to find the URL
// for Roboto. The API warns that this URL is not stable. In order to update
// this, list out all of the fonts and find the URL for the regular
// Roboto font. The API reference is here:
// https://developers.google.com/fonts/docs/developer_api
const String _robotoUrl =
'https://fonts.gstatic.com/s/roboto/v20/KFOmCnqEu92Fr1Me5WZLCzYlKw.ttf';
/// Manages the fonts used in the Skia-based backend.
class SkiaFontCollection implements FlutterFontCollection {
final Set<String> _downloadedFontFamilies = <String>{};
@override
late FontFallbackManager fontFallbackManager =
FontFallbackManager(SkiaFallbackRegistry(this));
/// Fonts that started the download process, but are not yet registered.
///
/// /// Once downloaded successfully, this map is cleared and the resulting
/// [UnregisteredFont]s are added to [_registeredFonts].
final List<UnregisteredFont> _unregisteredFonts = <UnregisteredFont>[];
final List<RegisteredFont> _registeredFonts = <RegisteredFont>[];
final List<RegisteredFont> registeredFallbackFonts = <RegisteredFont>[];
/// Returns fonts that have been downloaded, registered, and parsed.
///
/// This should only be used in tests.
List<RegisteredFont>? get debugRegisteredFonts {
List<RegisteredFont>? result;
assert(() {
result = _registeredFonts;
return true;
}());
return result;
}
final Map<String, List<SkFont>> familyToFontMap = <String, List<SkFont>>{};
void _registerWithFontProvider() {
if (_fontProvider != null) {
_fontProvider!.delete();
_fontProvider = null;
skFontCollection?.delete();
skFontCollection = null;
}
_fontProvider = canvasKit.TypefaceFontProvider.Make();
skFontCollection = canvasKit.FontCollection.Make();
skFontCollection!.enableFontFallback();
skFontCollection!.setDefaultFontManager(_fontProvider);
familyToFontMap.clear();
for (final RegisteredFont font in _registeredFonts) {
_fontProvider!.registerFont(font.bytes, font.family);
familyToFontMap
.putIfAbsent(font.family, () => <SkFont>[])
.add(SkFont(font.typeface));
}
for (final RegisteredFont font in registeredFallbackFonts) {
_fontProvider!.registerFont(font.bytes, font.family);
familyToFontMap
.putIfAbsent(font.family, () => <SkFont>[])
.add(SkFont(font.typeface));
}
}
@override
Future<bool> loadFontFromList(Uint8List list, {String? fontFamily}) async {
if (fontFamily == null) {
fontFamily = _readActualFamilyName(list);
if (fontFamily == null) {
printWarning('Failed to read font family name. Aborting font load.');
return false;
}
}
// Make sure CanvasKit is actually loaded
await renderer.initialize();
final SkTypeface? typeface =
canvasKit.Typeface.MakeFreeTypeFaceFromData(list.buffer);
if (typeface != null) {
_registeredFonts.add(RegisteredFont(list, fontFamily, typeface));
_registerWithFontProvider();
} else {
printWarning('Failed to parse font family "$fontFamily"');
return false;
}
return true;
}
/// Loads fonts from `FontManifest.json`.
@override
Future<AssetFontsResult> loadAssetFonts(FontManifest manifest) async {
final List<Future<FontDownloadResult>> pendingDownloads = <Future<FontDownloadResult>>[];
bool loadedRoboto = false;
for (final FontFamily family in manifest.families) {
if (family.name == 'Roboto') {
loadedRoboto = true;
}
for (final FontAsset fontAsset in family.fontAssets) {
final String url = ui_web.assetManager.getAssetUrl(fontAsset.asset);
pendingDownloads.add(_downloadFont(fontAsset.asset, url, family.name));
}
}
/// We need a default fallback font for CanvasKit, in order to avoid
/// crashing while laying out text with an unregistered font. We chose
/// Roboto to match Android.
if (!loadedRoboto) {
// Download Roboto and add it to the font buffers.
pendingDownloads.add(_downloadFont('Roboto', _robotoUrl, 'Roboto'));
}
final Map<String, FontLoadError> fontFailures = <String, FontLoadError>{};
final List<(String, UnregisteredFont)> downloadedFonts = <(String, UnregisteredFont)>[];
for (final FontDownloadResult result in await Future.wait(pendingDownloads)) {
if (result.font != null) {
downloadedFonts.add((result.assetName, result.font!));
} else {
fontFailures[result.assetName] = result.error!;
}
}
// Make sure CanvasKit is actually loaded
await renderer.initialize();
final List<String> loadedFonts = <String>[];
for (final (String assetName, UnregisteredFont unregisteredFont) in downloadedFonts) {
final Uint8List bytes = unregisteredFont.bytes.asUint8List();
final SkTypeface? typeface =
canvasKit.Typeface.MakeFreeTypeFaceFromData(bytes.buffer);
if (typeface != null) {
loadedFonts.add(assetName);
_registeredFonts.add(RegisteredFont(bytes, unregisteredFont.family, typeface));
} else {
printWarning('Failed to load font ${unregisteredFont.family} at ${unregisteredFont.url}');
printWarning('Verify that ${unregisteredFont.url} contains a valid font.');
fontFailures[assetName] = FontInvalidDataError(unregisteredFont.url);
}
}
registerDownloadedFonts();
return AssetFontsResult(loadedFonts, fontFailures);
}
void registerDownloadedFonts() {
RegisteredFont? makeRegisterFont(ByteBuffer buffer, String url, String family) {
final Uint8List bytes = buffer.asUint8List();
final SkTypeface? typeface =
canvasKit.Typeface.MakeFreeTypeFaceFromData(bytes.buffer);
if (typeface != null) {
return RegisteredFont(bytes, family, typeface);
} else {
printWarning('Failed to load font $family at $url');
printWarning('Verify that $url contains a valid font.');
return null;
}
}
for (final UnregisteredFont unregisteredFont in _unregisteredFonts) {
final RegisteredFont? registeredFont = makeRegisterFont(
unregisteredFont.bytes,
unregisteredFont.url,
unregisteredFont.family
);
if (registeredFont != null) {
_registeredFonts.add(registeredFont);
}
}
_unregisteredFonts.clear();
_registerWithFontProvider();
}
Future<FontDownloadResult> _downloadFont(
String assetName,
String url,
String fontFamily
) async {
final ByteBuffer fontData;
// Try to get the font leniently. Do not crash the app when failing to
// fetch the font in the spirit of "gradual degradation of functionality".
try {
final HttpFetchResponse response = await httpFetch(url);
if (!response.hasPayload) {
printWarning('Font family $fontFamily not found (404) at $url');
return FontDownloadResult.fromError(assetName, FontNotFoundError(url));
}
fontData = await response.asByteBuffer();
} catch (e) {
printWarning('Failed to load font $fontFamily at $url');
printWarning(e.toString());
return FontDownloadResult.fromError(assetName, FontDownloadError(url, e));
}
_downloadedFontFamilies.add(fontFamily);
return FontDownloadResult.fromFont(assetName, UnregisteredFont(fontData, url, fontFamily));
}
String? _readActualFamilyName(Uint8List bytes) {
final SkFontMgr tmpFontMgr =
canvasKit.FontMgr.FromData(<Uint8List>[bytes])!;
final String? actualFamily = tmpFontMgr.getFamilyName(0);
tmpFontMgr.delete();
return actualFamily;
}
TypefaceFontProvider? _fontProvider;
SkFontCollection? skFontCollection;
@override
void clear() {}
@override
void debugResetFallbackFonts() {
fontFallbackManager = FontFallbackManager(SkiaFallbackRegistry(this));
registeredFallbackFonts.clear();
}
}
/// Represents a font that has been registered.
class RegisteredFont {
RegisteredFont(this.bytes, this.family, this.typeface) {
// This is a hack which causes Skia to cache the decoded font.
final SkFont skFont = SkFont(typeface);
skFont.getGlyphBounds(<int>[0], null, null);
}
/// The font family name for this font.
final String family;
/// The byte data for this font.
final Uint8List bytes;
/// The [SkTypeface] created from this font's [bytes].
///
/// This is used to determine which code points are supported by this font.
final SkTypeface typeface;
}
/// Represents a font that has been downloaded but not registered.
class UnregisteredFont {
const UnregisteredFont(this.bytes, this.url, this.family);
final ByteBuffer bytes;
final String url;
final String family;
}
class FontDownloadResult {
FontDownloadResult.fromFont(this.assetName, UnregisteredFont this.font) : error = null;
FontDownloadResult.fromError(this.assetName, FontLoadError this.error) : font = null;
final String assetName;
final UnregisteredFont? font;
final FontLoadError? error;
}
class SkiaFallbackRegistry implements FallbackFontRegistry {
SkiaFallbackRegistry(this.fontCollection);
SkiaFontCollection fontCollection;
@override
List<int> getMissingCodePoints(List<int> codeUnits, List<String> fontFamilies) {
final List<SkFont> fonts = <SkFont>[];
for (final String font in fontFamilies) {
final List<SkFont>? typefacesForFamily = fontCollection.familyToFontMap[font];
if (typefacesForFamily != null) {
fonts.addAll(typefacesForFamily);
}
}
final List<bool> codePointsSupported =
List<bool>.filled(codeUnits.length, false);
final String testString = String.fromCharCodes(codeUnits);
for (final SkFont font in fonts) {
final Uint16List glyphs = font.getGlyphIDs(testString);
assert(glyphs.length == codePointsSupported.length);
for (int i = 0; i < glyphs.length; i++) {
codePointsSupported[i] |= glyphs[i] != 0;
}
}
final List<int> missingCodeUnits = <int>[];
for (int i = 0; i < codePointsSupported.length; i++) {
if (!codePointsSupported[i]) {
missingCodeUnits.add(codeUnits[i]);
}
}
return missingCodeUnits;
}
@override
Future<void> loadFallbackFont(String familyName, String url) async {
final ByteBuffer buffer = await httpFetchByteBuffer(url);
final SkTypeface? typeface =
canvasKit.Typeface.MakeFreeTypeFaceFromData(buffer);
if (typeface == null) {
printWarning('Failed to parse fallback font $familyName as a font.');
return;
}
fontCollection.registeredFallbackFonts.add(
RegisteredFont(buffer.asUint8List(), familyName, typeface)
);
}
@override
void updateFallbackFontFamilies(List<String> families) {
fontCollection.registerDownloadedFonts();
}
}
| engine/lib/web_ui/lib/src/engine/canvaskit/fonts.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/canvaskit/fonts.dart",
"repo_id": "engine",
"token_count": 3920
} | 251 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:collection';
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import 'canvaskit_api.dart';
import 'native_memory.dart';
import 'path.dart';
class CkPathMetrics extends IterableBase<ui.PathMetric> implements ui.PathMetrics {
CkPathMetrics(this._path, this._forceClosed);
final CkPath _path;
final bool _forceClosed;
/// The [CkPath.isEmpty] case is special-cased to avoid booting the WASM machinery just to find out there are no contours.
@override
late final Iterator<ui.PathMetric> iterator = _path.isEmpty
? const CkPathMetricIteratorEmpty._()
: CkContourMeasureIter(this);
}
class CkContourMeasureIter implements Iterator<ui.PathMetric> {
CkContourMeasureIter(this._metrics) {
_ref = UniqueRef<SkContourMeasureIter>(this, SkContourMeasureIter(
_metrics._path.skiaObject,
_metrics._forceClosed,
1.0,
), 'Iterator<PathMetric>');
}
final CkPathMetrics _metrics;
late final UniqueRef<SkContourMeasureIter> _ref;
SkContourMeasureIter get skiaObject => _ref.nativeObject;
/// A monotonically increasing counter used to generate [ui.PathMetric.contourIndex].
///
/// CanvasKit does not supply the contour index. We have to add it ourselves.
int _contourIndexCounter = 0;
@override
ui.PathMetric get current {
final ui.PathMetric? currentMetric = _current;
if (currentMetric == null) {
throw RangeError(
'PathMetricIterator is not pointing to a PathMetric. This can happen in two situations:\n'
'- The iteration has not started yet. If so, call "moveNext" to start iteration.\n'
'- The iterator ran out of elements. If so, check that "moveNext" returns true prior to calling "current".');
}
return currentMetric;
}
CkContourMeasure? _current;
@override
bool moveNext() {
final SkContourMeasure? skContourMeasure = skiaObject.next();
if (skContourMeasure == null) {
_current = null;
return false;
}
_current =
CkContourMeasure(_metrics, skContourMeasure, _contourIndexCounter);
_contourIndexCounter += 1;
return true;
}
}
class CkContourMeasure implements ui.PathMetric {
CkContourMeasure(this._metrics, SkContourMeasure skiaObject, this.contourIndex) {
_ref = UniqueRef<SkContourMeasure>(this, skiaObject, 'PathMetric');
}
/// The path metrics used to create this measure.
///
/// This is used to resurrect the object if it is deleted prematurely.
final CkPathMetrics _metrics;
late final UniqueRef<SkContourMeasure> _ref;
SkContourMeasure get skiaObject => _ref.nativeObject;
@override
final int contourIndex;
@override
ui.Path extractPath(double start, double end, {bool startWithMoveTo = true}) {
final SkPath skPath = skiaObject.getSegment(start, end, startWithMoveTo);
return CkPath.fromSkPath(skPath, _metrics._path.fillType);
}
@override
ui.Tangent getTangentForOffset(double distance) {
final Float32List posTan = skiaObject.getPosTan(distance);
return ui.Tangent(
ui.Offset(posTan[0], posTan[1]),
ui.Offset(posTan[2], posTan[3]),
);
}
@override
bool get isClosed {
return skiaObject.isClosed();
}
@override
double get length {
return skiaObject.length();
}
}
class CkPathMetricIteratorEmpty implements Iterator<ui.PathMetric> {
const CkPathMetricIteratorEmpty._();
@override
ui.PathMetric get current {
throw RangeError('PathMetric iterator is empty.');
}
@override
bool moveNext() {
return false;
}
}
| engine/lib/web_ui/lib/src/engine/canvaskit/path_metrics.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/canvaskit/path_metrics.dart",
"repo_id": "engine",
"token_count": 1307
} | 252 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// JavaScript API a Flutter Web application can use to configure the Web
/// Engine.
///
/// The configuration is passed from JavaScript to the engine as part of the
/// bootstrap process, through the `FlutterEngineInitializer.initializeEngine`
/// JS method, with an (optional) object of type [JsFlutterConfiguration].
///
/// This library also supports the legacy method of setting a plain JavaScript
/// object set as the `flutterConfiguration` property of the top-level `window`
/// object, but that approach is now deprecated and will warn users.
///
/// Both methods are **disallowed** to be used at the same time.
///
/// Example:
///
/// _flutter.loader.loadEntrypoint({
/// // ...
/// onEntrypointLoaded: async function(engineInitializer) {
/// let appRunner = await engineInitializer.initializeEngine({
/// // JsFlutterConfiguration goes here...
/// canvasKitBaseUrl: "https://example.com/my-custom-canvaskit/",
/// });
/// appRunner.runApp();
/// }
/// });
///
/// Example of the **deprecated** style (this will issue a JS console warning!):
///
/// <script>
/// window.flutterConfiguration = {
/// canvasKitBaseUrl: "https://example.com/my-custom-canvaskit/"
/// };
/// </script>
///
/// Configuration properties supplied via this object override those supplied
/// using the corresponding environment variables. For example, if both the
/// `canvasKitBaseUrl` config entry and the `FLUTTER_WEB_CANVASKIT_URL`
/// environment variables are provided, the `canvasKitBaseUrl` entry is used.
@JS()
library configuration;
import 'dart:js_interop';
import 'package:meta/meta.dart';
import 'canvaskit/renderer.dart';
import 'dom.dart';
/// The Web Engine configuration for the current application.
FlutterConfiguration get configuration {
if (_debugConfiguration != null) {
return _debugConfiguration!;
}
return _configuration ??= FlutterConfiguration.legacy(_jsConfiguration);
}
FlutterConfiguration? _configuration;
FlutterConfiguration? _debugConfiguration;
/// Overrides the initial test configuration with new values coming from `newConfig`.
///
/// The initial test configuration (AKA `_jsConfiguration`) is set in the
/// `test_platform.dart` file. See: `window.flutterConfiguration` in `_testBootstrapHandler`.
///
/// The result of calling this method each time is:
///
/// [configuration] = _jsConfiguration + newConfig
///
/// Subsequent calls to this method don't *add* more to an already overridden
/// configuration; this method always starts from an original `_jsConfiguration`,
/// and adds `newConfig` to it.
///
/// If `newConfig` is null, [configuration] resets to the initial `_jsConfiguration`.
///
/// This must be called before the engine is initialized. Calling it after the
/// engine is initialized will result in some of the properties not taking
/// effect because they are consumed during initialization.
@visibleForTesting
void debugOverrideJsConfiguration(JsFlutterConfiguration? newConfig) {
if (newConfig != null) {
_debugConfiguration = configuration.withOverrides(newConfig);
} else {
_debugConfiguration = null;
}
}
/// Supplies Web Engine configuration properties.
class FlutterConfiguration {
/// Constructs an unitialized configuration object.
@visibleForTesting
FlutterConfiguration();
/// Constucts a "tainted by JS globals" configuration object.
///
/// This configuration style is deprecated. It will warn the user about the
/// new API (if used)
FlutterConfiguration.legacy(JsFlutterConfiguration? config) {
if (config != null) {
_usedLegacyConfigStyle = true;
_configuration = config;
}
// Warn the user of the deprecated behavior.
assert(() {
if (config != null) {
domWindow.console.warn('window.flutterConfiguration is now deprecated.\n'
'Use engineInitializer.initializeEngine(config) instead.\n'
'See: https://docs.flutter.dev/development/platform-integration/web/initialization');
}
if (_requestedRendererType != null) {
domWindow.console.warn('window.flutterWebRenderer is now deprecated.\n'
'Use engineInitializer.initializeEngine(config) instead.\n'
'See: https://docs.flutter.dev/development/platform-integration/web/initialization');
}
return true;
}());
}
FlutterConfiguration withOverrides(JsFlutterConfiguration? overrides) {
final JsFlutterConfiguration newJsConfig = objectConstructor.assign(
<String, Object>{}.jsify(),
_configuration.jsify(),
overrides.jsify(),
) as JsFlutterConfiguration;
final FlutterConfiguration newConfig = FlutterConfiguration();
newConfig._configuration = newJsConfig;
return newConfig;
}
bool _usedLegacyConfigStyle = false;
JsFlutterConfiguration? _configuration;
/// Sets a value for [_configuration].
///
/// This method is called by the engine initialization process, through the
/// [initEngineServices] method.
///
/// This method throws an AssertionError, if the _configuration object has
/// been set to anything non-null through the [FlutterConfiguration.legacy]
/// constructor.
void setUserConfiguration(JsFlutterConfiguration? configuration) {
if (configuration != null) {
assert(!_usedLegacyConfigStyle,
'Use engineInitializer.initializeEngine(config) only. '
'Using the (deprecated) window.flutterConfiguration and initializeEngine '
'configuration simultaneously is not supported.');
assert(_requestedRendererType == null || configuration.renderer == null,
'Use engineInitializer.initializeEngine(config) only. '
'Using the (deprecated) window.flutterWebRenderer and initializeEngine '
'configuration simultaneously is not supported.');
_configuration = configuration;
}
}
// Static constant parameters.
//
// These properties affect tree shaking and therefore cannot be supplied at
// runtime. They must be static constants for the compiler to remove dead code
// effectively.
/// Auto detect which rendering backend to use.
///
/// Using flutter tools option "--web-render=auto" or not specifying one
/// would set the value to true. Otherwise, it would be false.
static const bool flutterWebAutoDetect =
bool.fromEnvironment('FLUTTER_WEB_AUTO_DETECT', defaultValue: true);
static const bool flutterWebUseSkwasm =
bool.fromEnvironment('FLUTTER_WEB_USE_SKWASM');
/// Enable the Skia-based rendering backend.
///
/// Using flutter tools option "--web-render=canvaskit" would set the value to
/// true.
///
/// Using flutter tools option "--web-render=html" would set the value to false.
static const bool useSkia =
bool.fromEnvironment('FLUTTER_WEB_USE_SKIA');
// Runtime parameters.
//
// These parameters can be supplied either as environment variables, or at
// runtime. Runtime-supplied values take precedence over environment
// variables.
/// The absolute base URL of the location of the `assets` directory of the app.
///
/// This value is useful when Flutter web assets are deployed to a separate
/// domain (or subdirectory) from which the index.html is served, for example:
///
/// * Application: https://www.my-app.com/
/// * Flutter Assets: https://cdn.example.com/my-app/build-hash/assets/
///
/// The `assetBase` value would be set to:
///
/// * `'https://cdn.example.com/my-app/build-hash/'`
///
/// It is also useful in the case that a Flutter web application is embedded
/// into another web app, in a way that the `<base>` tag of the index.html
/// cannot be set (because it'd break the host app), for example:
///
/// * Application: https://www.my-app.com/
/// * Flutter Assets: https://www.my-app.com/static/companion/flutter/assets/
///
/// The `assetBase` would be set to:
///
/// * `'/static/companion/flutter/'`
///
/// Do not confuse this configuration value with [canvasKitBaseUrl].
String? get assetBase => _configuration?.assetBase;
/// The base URL to use when downloading the CanvasKit script and associated
/// wasm.
///
/// The expected directory structure nested under this URL is as follows:
///
/// /canvaskit.js - the build of CanvasKit JS API bindings
/// /canvaskit.wasm - the build of CanvasKit WASM module
///
/// The base URL can be overridden using the `FLUTTER_WEB_CANVASKIT_URL`
/// environment variable or using the configuration API for JavaScript.
///
/// When specifying using the environment variable set it in the Flutter tool
/// using the `--dart-define` option. The value must end with a `/`.
///
/// Example:
///
/// ```
/// flutter run \
/// -d chrome \
/// --web-renderer=canvaskit \
/// --dart-define=FLUTTER_WEB_CANVASKIT_URL=https://example.com/custom-canvaskit-build/
/// ```
String get canvasKitBaseUrl => _configuration?.canvasKitBaseUrl ?? _defaultCanvasKitBaseUrl;
static const String _defaultCanvasKitBaseUrl = String.fromEnvironment(
'FLUTTER_WEB_CANVASKIT_URL',
defaultValue: 'canvaskit/',
);
/// The variant of CanvasKit to download.
///
/// Available values are:
///
/// * `auto` - the default value. The engine will automatically detect the
/// best variant to use based on the browser.
///
/// * `full` - the full variant of CanvasKit that can be used in any browser.
///
/// * `chromium` - the lite variant of CanvasKit that can be used in
/// Chromium-based browsers.
CanvasKitVariant get canvasKitVariant {
final String variant = _configuration?.canvasKitVariant ?? 'auto';
return CanvasKitVariant.values.byName(variant);
}
/// If set to true, forces CPU-only rendering in CanvasKit (i.e. the engine
/// won't use WebGL).
///
/// This is mainly used for testing or for apps that want to ensure they
/// run on devices which don't support WebGL.
bool get canvasKitForceCpuOnly => _configuration?.canvasKitForceCpuOnly ?? _defaultCanvasKitForceCpuOnly;
static const bool _defaultCanvasKitForceCpuOnly = bool.fromEnvironment(
'FLUTTER_WEB_CANVASKIT_FORCE_CPU_ONLY',
);
/// Set this flag to `true` to cause the engine to visualize the semantics tree
/// on the screen for debugging.
///
/// This only works in profile and release modes. Debug mode does not support
/// passing compile-time constants.
///
/// Example:
///
/// ```
/// flutter run -d chrome --profile --dart-define=FLUTTER_WEB_DEBUG_SHOW_SEMANTICS=true
/// ```
bool get debugShowSemanticsNodes => _configuration?.debugShowSemanticsNodes ?? _defaultDebugShowSemanticsNodes;
static const bool _defaultDebugShowSemanticsNodes = bool.fromEnvironment(
'FLUTTER_WEB_DEBUG_SHOW_SEMANTICS',
);
/// Returns the [hostElement] in which the Flutter Application is supposed
/// to render, or `null` if the user hasn't specified anything.
DomElement? get hostElement => _configuration?.hostElement;
/// Sets Flutter Web in "multi-view" mode.
///
/// Multi-view mode allows apps to:
///
/// * Start without a `hostElement`.
/// * Add/remove views (`hostElements`) from JS while the application is running.
/// * ...
/// * PROFIT?
bool get multiViewEnabled => _configuration?.multiViewEnabled ?? false;
/// Returns a `nonce` to allowlist the inline styles that Flutter web needs.
///
/// See: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce
String? get nonce => _configuration?.nonce;
/// Returns the [requestedRendererType] to be used with the current Flutter
/// application, normally 'canvaskit' or 'auto'.
///
/// This value may come from the JS configuration, but also a specific JS value:
/// `window.flutterWebRenderer`.
///
/// This is used by the Renderer class to decide how to initialize the engine.
String? get requestedRendererType => _configuration?.renderer ?? _requestedRendererType;
/// Whether to use color emojis or not.
///
/// The font used to render color emojis is large (~24MB). This configuration
/// gives developers the ability to decide for their app.
bool get useColorEmoji => _configuration?.useColorEmoji ?? false;
}
@JS('window.flutterConfiguration')
external JsFlutterConfiguration? get _jsConfiguration;
/// The JS bindings for the object that's set as `window.flutterConfiguration`.
@JS()
@anonymous
@staticInterop
class JsFlutterConfiguration {
external factory JsFlutterConfiguration();
}
extension JsFlutterConfigurationExtension on JsFlutterConfiguration {
@JS('assetBase')
external JSString? get _assetBase;
String? get assetBase => _assetBase?.toDart;
@JS('canvasKitBaseUrl')
external JSString? get _canvasKitBaseUrl;
String? get canvasKitBaseUrl => _canvasKitBaseUrl?.toDart;
@JS('canvasKitVariant')
external JSString? get _canvasKitVariant;
String? get canvasKitVariant => _canvasKitVariant?.toDart;
@JS('canvasKitForceCpuOnly')
external JSBoolean? get _canvasKitForceCpuOnly;
bool? get canvasKitForceCpuOnly => _canvasKitForceCpuOnly?.toDart;
@JS('debugShowSemanticsNodes')
external JSBoolean? get _debugShowSemanticsNodes;
bool? get debugShowSemanticsNodes => _debugShowSemanticsNodes?.toDart;
external DomElement? get hostElement;
@JS('multiViewEnabled')
external JSBoolean? get _multiViewEnabled;
bool? get multiViewEnabled => _multiViewEnabled?.toDart;
@JS('nonce')
external JSString? get _nonce;
String? get nonce => _nonce?.toDart;
@JS('renderer')
external JSString? get _renderer;
String? get renderer => _renderer?.toDart;
@JS('useColorEmoji')
external JSBoolean? get _useColorEmoji;
bool? get useColorEmoji => _useColorEmoji?.toDart;
}
/// A JavaScript entrypoint that allows developer to set rendering backend
/// at runtime before launching the application.
@JS('window.flutterWebRenderer')
external JSString? get __requestedRendererType;
String? get _requestedRendererType => __requestedRendererType?.toDart;
| engine/lib/web_ui/lib/src/engine/configuration.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/configuration.dart",
"repo_id": "engine",
"token_count": 4387
} | 253 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.