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. #include "flutter/display_list/dl_tile_mode.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/testing/diff_context_test.h" #include "flutter/flow/testing/layer_test.h" #include "flutter/flow/testing/mock_layer.h" #include "flutter/fml/macros.h" #include "gtest/gtest.h" #include "include/core/SkPath.h" #include "third_party/skia/include/effects/SkImageFilters.h" // TODO(zanderso): https://github.com/flutter/flutter/issues/127701 // NOLINTBEGIN(bugprone-unchecked-optional-access) namespace flutter { namespace testing { using ImageFilterLayerTest = LayerTest; #ifndef NDEBUG TEST_F(ImageFilterLayerTest, PaintingEmptyLayerDies) { auto layer = std::make_shared<ImageFilterLayer>(nullptr); layer->Preroll(preroll_context()); EXPECT_EQ(layer->paint_bounds(), kEmptyRect); EXPECT_FALSE(layer->needs_painting(paint_context())); EXPECT_DEATH_IF_SUPPORTED(layer->Paint(paint_context()), "needs_painting\\(context\\)"); } TEST_F(ImageFilterLayerTest, PaintBeforePrerollDies) { const SkRect child_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 20.5f, 21.5f); const SkPath child_path = SkPath().addRect(child_bounds); auto mock_layer = std::make_shared<MockLayer>(child_path); auto layer = std::make_shared<ImageFilterLayer>(nullptr); layer->Add(mock_layer); EXPECT_EQ(layer->paint_bounds(), kEmptyRect); EXPECT_EQ(layer->child_paint_bounds(), kEmptyRect); EXPECT_DEATH_IF_SUPPORTED(layer->Paint(paint_context()), "needs_painting\\(context\\)"); } #endif TEST_F(ImageFilterLayerTest, EmptyFilter) { const SkMatrix initial_transform = SkMatrix::Translate(0.5f, 1.0f); 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::kYellow()); auto mock_layer = std::make_shared<MockLayer>(child_path, child_paint); auto layer = std::make_shared<ImageFilterLayer>(nullptr); layer->Add(mock_layer); preroll_context()->state_stack.set_preroll_delegate(initial_transform); layer->Preroll(preroll_context()); EXPECT_EQ(layer->paint_bounds(), child_bounds); EXPECT_EQ(layer->child_paint_bounds(), child_bounds); EXPECT_TRUE(layer->needs_painting(paint_context())); EXPECT_EQ(mock_layer->parent_matrix(), initial_transform); layer->Paint(display_list_paint_context()); DisplayListBuilder expected_builder; /* (ImageFilter)layer::Paint */ { expected_builder.Save(); /* mock_layer1::Paint */ { expected_builder.DrawPath(child_path, child_paint); } expected_builder.Restore(); } EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } TEST_F(ImageFilterLayerTest, SimpleFilter) { const SkMatrix initial_transform = SkMatrix::Translate(0.5f, 1.0f); 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::kYellow()); auto dl_image_filter = std::make_shared<DlMatrixImageFilter>( SkMatrix(), DlImageSampling::kMipmapLinear); auto mock_layer = std::make_shared<MockLayer>(child_path, child_paint); auto layer = std::make_shared<ImageFilterLayer>(dl_image_filter); layer->Add(mock_layer); const SkRect child_rounded_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 21.0f, 22.0f); preroll_context()->state_stack.set_preroll_delegate(initial_transform); layer->Preroll(preroll_context()); EXPECT_EQ(layer->paint_bounds(), child_rounded_bounds); EXPECT_EQ(layer->child_paint_bounds(), child_bounds); EXPECT_TRUE(layer->needs_painting(paint_context())); EXPECT_EQ(mock_layer->parent_matrix(), initial_transform); DisplayListBuilder expected_builder; /* ImageFilterLayer::Paint() */ { DlPaint dl_paint; dl_paint.setImageFilter(dl_image_filter.get()); expected_builder.SaveLayer(&child_bounds, &dl_paint); { /* MockLayer::Paint() */ { expected_builder.DrawPath(child_path, DlPaint(DlColor::kYellow())); } } } expected_builder.Restore(); auto expected_display_list = expected_builder.Build(); layer->Paint(display_list_paint_context()); EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_display_list)); } TEST_F(ImageFilterLayerTest, SimpleFilterWithOffset) { const SkMatrix initial_transform = SkMatrix::Translate(0.5f, 1.0f); const SkRect initial_cull_rect = SkRect::MakeLTRB(0, 0, 100, 100); 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::kYellow()); const SkPoint layer_offset = SkPoint::Make(5.5, 6.5); auto dl_image_filter = std::make_shared<DlMatrixImageFilter>( SkMatrix(), DlImageSampling::kMipmapLinear); auto mock_layer = std::make_shared<MockLayer>(child_path, child_paint); auto layer = std::make_shared<ImageFilterLayer>(dl_image_filter, layer_offset); layer->Add(mock_layer); SkMatrix child_matrix = initial_transform; child_matrix.preTranslate(layer_offset.fX, layer_offset.fY); const SkRect child_rounded_bounds = SkRect::MakeLTRB(10.5f, 12.5f, 26.5f, 28.5f); preroll_context()->state_stack.set_preroll_delegate(initial_cull_rect, initial_transform); layer->Preroll(preroll_context()); EXPECT_EQ(layer->paint_bounds(), child_rounded_bounds); EXPECT_EQ(layer->child_paint_bounds(), child_bounds); EXPECT_TRUE(layer->needs_painting(paint_context())); EXPECT_EQ(mock_layer->parent_matrix(), child_matrix); EXPECT_EQ(preroll_context()->state_stack.device_cull_rect(), initial_cull_rect); DisplayListBuilder expected_builder; /* ImageFilterLayer::Paint() */ { expected_builder.Save(); { expected_builder.Translate(layer_offset.fX, layer_offset.fY); DlPaint dl_paint; dl_paint.setImageFilter(dl_image_filter.get()); expected_builder.SaveLayer(&child_bounds, &dl_paint); { /* MockLayer::Paint() */ { expected_builder.DrawPath(child_path, DlPaint(DlColor::kYellow())); } } expected_builder.Restore(); } expected_builder.Restore(); } auto expected_display_list = expected_builder.Build(); layer->Paint(display_list_paint_context()); EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_display_list)); } TEST_F(ImageFilterLayerTest, SimpleFilterBounds) { const SkMatrix initial_transform = SkMatrix::Translate(0.5f, 1.0f); 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::kYellow()); const SkMatrix filter_transform = SkMatrix::Scale(2.0, 2.0); auto dl_image_filter = std::make_shared<DlMatrixImageFilter>( filter_transform, DlImageSampling::kMipmapLinear); auto mock_layer = std::make_shared<MockLayer>(child_path, child_paint); auto layer = std::make_shared<ImageFilterLayer>(dl_image_filter); layer->Add(mock_layer); const SkRect filter_bounds = SkRect::MakeLTRB(10.0f, 12.0f, 42.0f, 44.0f); preroll_context()->state_stack.set_preroll_delegate(initial_transform); layer->Preroll(preroll_context()); EXPECT_EQ(layer->paint_bounds(), filter_bounds); EXPECT_EQ(layer->child_paint_bounds(), child_bounds); EXPECT_TRUE(layer->needs_painting(paint_context())); EXPECT_EQ(mock_layer->parent_matrix(), initial_transform); DisplayListBuilder expected_builder; /* ImageFilterLayer::Paint() */ { DlPaint dl_paint; dl_paint.setImageFilter(dl_image_filter.get()); expected_builder.SaveLayer(&child_bounds, &dl_paint); { /* MockLayer::Paint() */ { expected_builder.DrawPath(child_path, DlPaint(DlColor::kYellow())); } } } expected_builder.Restore(); auto expected_display_list = expected_builder.Build(); layer->Paint(display_list_paint_context()); EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_display_list)); } TEST_F(ImageFilterLayerTest, MultipleChildren) { const SkMatrix initial_transform = SkMatrix::Translate(0.5f, 1.0f); const SkRect child_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 2.5f, 3.5f); const SkPath child_path1 = SkPath().addRect(child_bounds); const SkPath child_path2 = SkPath().addRect(child_bounds.makeOffset(3.0f, 0.0f)); const DlPaint child_paint1 = DlPaint(DlColor::kYellow()); const DlPaint child_paint2 = DlPaint(DlColor::kCyan()); auto dl_image_filter = std::make_shared<DlMatrixImageFilter>( SkMatrix(), DlImageSampling::kMipmapLinear); 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<ImageFilterLayer>(dl_image_filter); layer->Add(mock_layer1); layer->Add(mock_layer2); SkRect children_bounds = child_path1.getBounds(); children_bounds.join(child_path2.getBounds()); SkRect children_rounded_bounds = SkRect::Make(children_bounds.roundOut()); preroll_context()->state_stack.set_preroll_delegate(initial_transform); layer->Preroll(preroll_context()); EXPECT_EQ(mock_layer1->paint_bounds(), child_path1.getBounds()); EXPECT_EQ(mock_layer2->paint_bounds(), child_path2.getBounds()); EXPECT_EQ(layer->paint_bounds(), children_rounded_bounds); EXPECT_EQ(layer->child_paint_bounds(), children_bounds); EXPECT_TRUE(mock_layer1->needs_painting(paint_context())); EXPECT_TRUE(mock_layer2->needs_painting(paint_context())); EXPECT_TRUE(layer->needs_painting(paint_context())); EXPECT_EQ(mock_layer1->parent_matrix(), initial_transform); EXPECT_EQ(mock_layer2->parent_matrix(), initial_transform); DisplayListBuilder expected_builder; /* ImageFilterLayer::Paint() */ { DlPaint dl_paint; dl_paint.setImageFilter(dl_image_filter.get()); expected_builder.SaveLayer(&children_bounds, &dl_paint); { /* MockLayer::Paint() */ { expected_builder.DrawPath(child_path1, DlPaint(DlColor::kYellow())); } /* MockLayer::Paint() */ { expected_builder.DrawPath(child_path2, DlPaint(DlColor::kCyan())); } } } expected_builder.Restore(); auto expected_display_list = expected_builder.Build(); layer->Paint(display_list_paint_context()); EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_display_list)); } TEST_F(ImageFilterLayerTest, Nested) { const SkMatrix initial_transform = SkMatrix::Translate(0.5f, 1.0f); const SkRect child_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 2.5f, 3.5f); const SkPath child_path1 = SkPath().addRect(child_bounds); const SkPath child_path2 = SkPath().addRect(child_bounds.makeOffset(3.0f, 0.0f)); const DlPaint child_paint1 = DlPaint(DlColor::kYellow()); const DlPaint child_paint2 = DlPaint(DlColor::kCyan()); auto dl_image_filter1 = std::make_shared<DlMatrixImageFilter>( SkMatrix(), DlImageSampling::kMipmapLinear); auto dl_image_filter2 = std::make_shared<DlMatrixImageFilter>( SkMatrix(), DlImageSampling::kMipmapLinear); auto mock_layer1 = std::make_shared<MockLayer>(child_path1, child_paint1); auto mock_layer2 = std::make_shared<MockLayer>(child_path2, child_paint2); auto layer1 = std::make_shared<ImageFilterLayer>(dl_image_filter1); auto layer2 = std::make_shared<ImageFilterLayer>(dl_image_filter2); layer2->Add(mock_layer2); layer1->Add(mock_layer1); layer1->Add(layer2); SkRect children_bounds = child_path1.getBounds(); children_bounds.join(SkRect::Make(child_path2.getBounds().roundOut())); const SkRect children_rounded_bounds = SkRect::Make(children_bounds.roundOut()); const SkRect mock_layer2_rounded_bounds = SkRect::Make(child_path2.getBounds().roundOut()); preroll_context()->state_stack.set_preroll_delegate(initial_transform); layer1->Preroll(preroll_context()); EXPECT_EQ(mock_layer1->paint_bounds(), child_path1.getBounds()); EXPECT_EQ(mock_layer2->paint_bounds(), child_path2.getBounds()); EXPECT_EQ(layer1->paint_bounds(), children_rounded_bounds); EXPECT_EQ(layer1->child_paint_bounds(), children_bounds); EXPECT_EQ(layer2->paint_bounds(), mock_layer2_rounded_bounds); EXPECT_EQ(layer2->child_paint_bounds(), child_path2.getBounds()); EXPECT_TRUE(mock_layer1->needs_painting(paint_context())); EXPECT_TRUE(mock_layer2->needs_painting(paint_context())); EXPECT_TRUE(layer1->needs_painting(paint_context())); EXPECT_TRUE(layer2->needs_painting(paint_context())); EXPECT_EQ(mock_layer1->parent_matrix(), initial_transform); EXPECT_EQ(mock_layer2->parent_matrix(), initial_transform); DisplayListBuilder expected_builder; /* ImageFilterLayer::Paint() */ { DlPaint dl_paint; dl_paint.setImageFilter(dl_image_filter1.get()); expected_builder.SaveLayer(&children_bounds, &dl_paint); { /* MockLayer::Paint() */ { expected_builder.DrawPath(child_path1, DlPaint(DlColor::kYellow())); } /* ImageFilterLayer::Paint() */ { DlPaint child_paint; child_paint.setImageFilter(dl_image_filter2.get()); expected_builder.SaveLayer(&child_path2.getBounds(), &child_paint); /* MockLayer::Paint() */ { expected_builder.DrawPath(child_path2, DlPaint(DlColor::kCyan())); } expected_builder.Restore(); } } } expected_builder.Restore(); auto expected_display_list = expected_builder.Build(); layer1->Paint(display_list_paint_context()); EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_display_list)); } TEST_F(ImageFilterLayerTest, Readback) { auto dl_image_filter = std::make_shared<DlMatrixImageFilter>( SkMatrix(), DlImageSampling::kLinear); // ImageFilterLayer does not read from surface auto layer = std::make_shared<ImageFilterLayer>(dl_image_filter); preroll_context()->surface_needs_readback = false; layer->Preroll(preroll_context()); EXPECT_FALSE(preroll_context()->surface_needs_readback); // ImageFilterLayer blocks child with readback auto mock_layer = std::make_shared<MockLayer>(SkPath(), DlPaint()); mock_layer->set_fake_reads_surface(true); layer->Add(mock_layer); preroll_context()->surface_needs_readback = false; layer->Preroll(preroll_context()); EXPECT_FALSE(preroll_context()->surface_needs_readback); } TEST_F(ImageFilterLayerTest, CacheChild) { auto dl_image_filter = std::make_shared<DlMatrixImageFilter>( SkMatrix(), DlImageSampling::kMipmapLinear); auto initial_transform = SkMatrix::Translate(50.0, 25.5); auto other_transform = SkMatrix::Scale(1.0, 2.0); const SkPath child_path = SkPath().addRect(SkRect::MakeWH(5.0f, 5.0f)); auto mock_layer = std::make_shared<MockLayer>(child_path); auto layer = std::make_shared<ImageFilterLayer>(dl_image_filter); layer->Add(mock_layer); SkMatrix cache_ctm = initial_transform; DisplayListBuilder cache_canvas; cache_canvas.Transform(cache_ctm); DisplayListBuilder other_canvas; other_canvas.Transform(other_transform); DlPaint paint; use_mock_raster_cache(); const auto* cacheable_image_filter_item = layer->raster_cache_item(); EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)0); // ImageFilterLayer default cache itself. EXPECT_EQ(cacheable_image_filter_item->cache_state(), RasterCacheItem::CacheState::kNone); EXPECT_FALSE(cacheable_image_filter_item->Draw(paint_context(), &paint)); preroll_context()->state_stack.set_preroll_delegate(initial_transform); layer->Preroll(preroll_context()); LayerTree::TryToRasterCache(cacheable_items(), &paint_context()); EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)1); // The layer_cache_item's strategy is Children, mean we will must cache // his children EXPECT_EQ(cacheable_image_filter_item->cache_state(), RasterCacheItem::CacheState::kChildren); EXPECT_TRUE(raster_cache()->Draw(cacheable_image_filter_item->GetId().value(), cache_canvas, &paint)); EXPECT_FALSE(raster_cache()->Draw( cacheable_image_filter_item->GetId().value(), other_canvas, &paint)); } TEST_F(ImageFilterLayerTest, CacheChildren) { auto dl_image_filter = std::make_shared<DlMatrixImageFilter>( SkMatrix(), DlImageSampling::kMipmapLinear); auto initial_transform = SkMatrix::Translate(50.0, 25.5); auto other_transform = SkMatrix::Scale(1.0, 2.0); DlPaint paint; const SkPath child_path1 = SkPath().addRect(SkRect::MakeWH(5.0f, 5.0f)); const SkPath child_path2 = SkPath().addRect(SkRect::MakeWH(5.0f, 5.0f)); auto mock_layer1 = std::make_shared<MockLayer>(child_path1); auto mock_layer2 = std::make_shared<MockLayer>(child_path2); auto offset = SkPoint::Make(54, 24); auto layer = std::make_shared<ImageFilterLayer>(dl_image_filter, offset); layer->Add(mock_layer1); layer->Add(mock_layer2); SkMatrix cache_ctm = initial_transform; DisplayListBuilder cache_canvas; cache_canvas.Transform(cache_ctm); DisplayListBuilder other_canvas; other_canvas.Transform(other_transform); use_mock_raster_cache(); const auto* cacheable_image_filter_item = layer->raster_cache_item(); EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)0); // ImageFilterLayer default cache itself. EXPECT_EQ(cacheable_image_filter_item->cache_state(), RasterCacheItem::CacheState::kNone); EXPECT_FALSE(cacheable_image_filter_item->Draw(paint_context(), &paint)); preroll_context()->state_stack.set_preroll_delegate(initial_transform); layer->Preroll(preroll_context()); LayerTree::TryToRasterCache(cacheable_items(), &paint_context()); EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)1); // The layer_cache_item's strategy is Children, mean we will must cache his // children EXPECT_EQ(cacheable_image_filter_item->cache_state(), RasterCacheItem::CacheState::kChildren); EXPECT_TRUE(raster_cache()->Draw(cacheable_image_filter_item->GetId().value(), cache_canvas, &paint)); EXPECT_FALSE(raster_cache()->Draw( cacheable_image_filter_item->GetId().value(), other_canvas, &paint)); layer->Preroll(preroll_context()); SkRect children_bounds = child_path1.getBounds(); children_bounds.join(child_path2.getBounds()); SkMatrix snapped_matrix = SkMatrix::MakeAll( // 1, 0, SkScalarRoundToScalar(offset.fX), // 0, 1, SkScalarRoundToScalar(offset.fY), // 0, 0, 1); SkMatrix cache_matrix = initial_transform; cache_matrix.preConcat(snapped_matrix); auto transformed_filter = dl_image_filter->makeWithLocalMatrix(cache_matrix); layer->Paint(display_list_paint_context()); DisplayListBuilder expected_builder; /* (ImageFilter)layer::Paint() */ { expected_builder.Save(); { expected_builder.Translate(offset.fX, offset.fY); // translation components already snapped to pixels, intent to // use raster cache won't change them DlPaint dl_paint; dl_paint.setImageFilter(transformed_filter.get()); raster_cache()->Draw(cacheable_image_filter_item->GetId().value(), expected_builder, &dl_paint); } expected_builder.Restore(); } expected_builder.Restore(); EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } TEST_F(ImageFilterLayerTest, CacheImageFilterLayerSelf) { auto dl_image_filter = std::make_shared<DlMatrixImageFilter>( SkMatrix(), DlImageSampling::kMipmapLinear); auto initial_transform = SkMatrix::Translate(50.0, 25.5); auto other_transform = SkMatrix::Scale(1.0, 2.0); auto child_rect = SkRect::MakeWH(5.0f, 5.0f); const SkPath child_path = SkPath().addRect(child_rect); auto mock_layer = std::make_shared<MockLayer>(child_path); auto offset = SkPoint::Make(53.8, 24.4); auto layer = std::make_shared<ImageFilterLayer>(dl_image_filter, offset); layer->Add(mock_layer); SkMatrix cache_ctm = initial_transform; DisplayListBuilder cache_canvas; cache_canvas.Transform(cache_ctm); DisplayListBuilder other_canvas; other_canvas.Transform(other_transform); DlPaint paint; SkMatrix snapped_matrix = SkMatrix::MakeAll( // 1, 0, SkScalarRoundToScalar(offset.fX), // 0, 1, SkScalarRoundToScalar(offset.fY), // 0, 0, 1); use_mock_raster_cache(); preroll_context()->state_stack.set_preroll_delegate(initial_transform); const auto* cacheable_image_filter_item = layer->raster_cache_item(); // frame 1. layer->Preroll(preroll_context()); layer->Paint(display_list_paint_context()); { DisplayListBuilder expected_builder; /* (ImageFilter)layer::Paint */ { expected_builder.Save(); { expected_builder.Translate(offset.fX, offset.fY); // Snap to pixel translation due to use of raster cache expected_builder.TransformReset(); expected_builder.Transform(snapped_matrix); DlPaint save_paint = DlPaint().setImageFilter(dl_image_filter); expected_builder.SaveLayer(&child_rect, &save_paint); { /* mock_layer::Paint */ { expected_builder.DrawPath(child_path, DlPaint()); } } expected_builder.Restore(); } expected_builder.Restore(); } EXPECT_TRUE( DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } // frame 2. layer->Preroll(preroll_context()); layer->Paint(display_list_paint_context()); // frame 3. layer->Preroll(preroll_context()); layer->Paint(display_list_paint_context()); LayerTree::TryToRasterCache(cacheable_items(), &paint_context()); // frame1,2 cache the ImageFilter's children layer, frame3 cache the // ImageFilterLayer EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)2); // ImageFilterLayer default cache itself. EXPECT_EQ(cacheable_image_filter_item->cache_state(), RasterCacheItem::CacheState::kCurrent); EXPECT_EQ(cacheable_image_filter_item->GetId(), RasterCacheKeyID(layer->unique_id(), RasterCacheKeyType::kLayer)); EXPECT_TRUE(raster_cache()->Draw(cacheable_image_filter_item->GetId().value(), cache_canvas, &paint)); EXPECT_FALSE(raster_cache()->Draw( cacheable_image_filter_item->GetId().value(), other_canvas, &paint)); layer->Preroll(preroll_context()); reset_display_list(); layer->Paint(display_list_paint_context()); { DisplayListBuilder expected_builder; /* (ImageFilter)layer::Paint */ { expected_builder.Save(); { EXPECT_TRUE( raster_cache()->Draw(cacheable_image_filter_item->GetId().value(), expected_builder, nullptr)); } expected_builder.Restore(); } EXPECT_TRUE( DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } } TEST_F(ImageFilterLayerTest, OpacityInheritance) { const SkMatrix initial_transform = SkMatrix::Translate(0.5f, 1.0f); 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::kYellow()); auto dl_image_filter = std::make_shared<DlMatrixImageFilter>( SkMatrix(), DlImageSampling::kMipmapLinear); // The mock_layer child will not be compatible with opacity auto mock_layer = MockLayer::Make(child_path, child_paint); auto image_filter_layer = std::make_shared<ImageFilterLayer>(dl_image_filter); image_filter_layer->Add(mock_layer); PrerollContext* context = preroll_context(); context->state_stack.set_preroll_delegate(initial_transform); image_filter_layer->Preroll(preroll_context()); // ImageFilterLayers can always inherit opacity whether or not their // children are compatible. EXPECT_EQ(context->renderable_state_flags, LayerStateStack::kCallerCanApplyOpacity | LayerStateStack::kCallerCanApplyColorFilter); int opacity_alpha = 0x7F; SkPoint offset = SkPoint::Make(10, 10); auto opacity_layer = std::make_shared<OpacityLayer>(opacity_alpha, offset); opacity_layer->Add(image_filter_layer); context->state_stack.set_preroll_delegate(SkMatrix::I()); opacity_layer->Preroll(context); EXPECT_TRUE(opacity_layer->children_can_accept_opacity()); DisplayListBuilder expected_builder; /* OpacityLayer::Paint() */ { expected_builder.Save(); { expected_builder.Translate(offset.fX, offset.fY); /* ImageFilterLayer::Paint() */ { DlPaint image_filter_paint; image_filter_paint.setColor(DlColor(opacity_alpha << 24)); image_filter_paint.setImageFilter(dl_image_filter.get()); expected_builder.SaveLayer(&child_path.getBounds(), &image_filter_paint); /* MockLayer::Paint() */ { expected_builder.DrawPath(child_path, DlPaint(child_paint.getColor())); } expected_builder.Restore(); } } expected_builder.Restore(); } opacity_layer->Paint(display_list_paint_context()); EXPECT_TRUE(DisplayListsEQ_Verbose(expected_builder.Build(), display_list())); } using ImageFilterLayerDiffTest = DiffContextTest; TEST_F(ImageFilterLayerDiffTest, ImageFilterLayer) { auto dl_blur_filter = std::make_shared<DlBlurImageFilter>(10, 10, DlTileMode::kClamp); { // tests later assume 30px paint area, fail early if that's not the case SkIRect input_bounds; dl_blur_filter->get_input_device_bounds(SkIRect::MakeWH(10, 10), SkMatrix::I(), input_bounds); EXPECT_EQ(input_bounds, SkIRect::MakeLTRB(-30, -30, 40, 40)); } MockLayerTree l1; auto filter_layer = std::make_shared<ImageFilterLayer>(dl_blur_filter); auto path = SkPath().addRect(SkRect::MakeLTRB(100, 100, 110, 110)); filter_layer->Add(std::make_shared<MockLayer>(path)); l1.root()->Add(filter_layer); auto damage = DiffLayerTree(l1, MockLayerTree()); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(70, 70, 140, 140)); MockLayerTree l2; auto scale = std::make_shared<TransformLayer>(SkMatrix::Scale(2.0, 2.0)); scale->Add(filter_layer); l2.root()->Add(scale); damage = DiffLayerTree(l2, MockLayerTree()); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(140, 140, 280, 280)); MockLayerTree l3; l3.root()->Add(scale); // path outside of ImageFilterLayer auto path1 = SkPath().addRect(SkRect::MakeLTRB(130, 130, 140, 140)); l3.root()->Add(std::make_shared<MockLayer>(path1)); damage = DiffLayerTree(l3, l2); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(130, 130, 140, 140)); // path intersecting ImageFilterLayer, shouldn't trigger entire // ImageFilterLayer repaint MockLayerTree l4; l4.root()->Add(scale); auto path2 = SkPath().addRect(SkRect::MakeLTRB(130, 130, 141, 141)); l4.root()->Add(std::make_shared<MockLayer>(path2)); damage = DiffLayerTree(l4, l3); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(130, 130, 141, 141)); } TEST_F(ImageFilterLayerDiffTest, ImageFilterLayerInflatestChildSize) { auto dl_blur_filter = std::make_shared<DlBlurImageFilter>(10, 10, DlTileMode::kClamp); { // tests later assume 30px paint area, fail early if that's not the case SkIRect input_bounds; dl_blur_filter->get_input_device_bounds(SkIRect::MakeWH(10, 10), SkMatrix::I(), input_bounds); EXPECT_EQ(input_bounds, SkIRect::MakeLTRB(-30, -30, 40, 40)); } MockLayerTree l1; // Use nested filter layers to check if both contribute to child bounds auto filter_layer_1_1 = std::make_shared<ImageFilterLayer>(dl_blur_filter); auto filter_layer_1_2 = std::make_shared<ImageFilterLayer>(dl_blur_filter); filter_layer_1_1->Add(filter_layer_1_2); auto path = SkPath().addRect(SkRect::MakeLTRB(100, 100, 110, 110)); filter_layer_1_2->Add( std::make_shared<MockLayer>(path, DlPaint(DlColor::kYellow()))); l1.root()->Add(filter_layer_1_1); // second layer tree with identical filter layers but different child layer MockLayerTree l2; auto filter_layer2_1 = std::make_shared<ImageFilterLayer>(dl_blur_filter); filter_layer2_1->AssignOldLayer(filter_layer_1_1.get()); auto filter_layer2_2 = std::make_shared<ImageFilterLayer>(dl_blur_filter); filter_layer2_2->AssignOldLayer(filter_layer_1_2.get()); filter_layer2_1->Add(filter_layer2_2); filter_layer2_2->Add( std::make_shared<MockLayer>(path, DlPaint(DlColor::kRed()))); l2.root()->Add(filter_layer2_1); DiffLayerTree(l1, MockLayerTree()); auto damage = DiffLayerTree(l2, l1); // ensure that filter properly inflated child size EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(40, 40, 170, 170)); } TEST_F(ImageFilterLayerTest, EmptyFilterWithOffset) { const SkRect child_bounds = SkRect::MakeLTRB(10.0f, 11.0f, 19.0f, 20.0f); const SkPath child_path = SkPath().addRect(child_bounds); const DlPaint child_paint = DlPaint(DlColor::kYellow()); auto mock_layer = std::make_shared<MockLayer>(child_path, child_paint); const SkPoint offset = SkPoint::Make(5.0f, 6.0f); auto layer = std::make_shared<ImageFilterLayer>(nullptr, offset); layer->Add(mock_layer); layer->Preroll(preroll_context()); EXPECT_EQ(layer->paint_bounds(), child_bounds.makeOffset(offset)); } } // namespace testing } // namespace flutter // NOLINTEND(bugprone-unchecked-optional-access)
engine/flow/layers/image_filter_layer_unittests.cc/0
{ "file_path": "engine/flow/layers/image_filter_layer_unittests.cc", "repo_id": "engine", "token_count": 11616 }
300
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/flow/layers/opacity_layer.h" #include "flutter/flow/layers/clip_rect_layer.h" #include "flutter/flow/layers/image_filter_layer.h" #include "flutter/flow/layers/layer_tree.h" #include "flutter/flow/layers/platform_view_layer.h" #include "flutter/flow/layers/transform_layer.h" #include "flutter/flow/raster_cache_util.h" #include "flutter/flow/testing/diff_context_test.h" #include "flutter/flow/testing/layer_test.h" #include "flutter/flow/testing/mock_embedder.h" #include "flutter/flow/testing/mock_layer.h" #include "flutter/fml/macros.h" #include "flutter/testing/display_list_testing.h" #include "gtest/gtest.h" // TODO(zanderso): https://github.com/flutter/flutter/issues/127701 // NOLINTBEGIN(bugprone-unchecked-optional-access) namespace flutter { namespace testing { using OpacityLayerTest = LayerTest; #ifndef NDEBUG TEST_F(OpacityLayerTest, PaintingEmptyLayerDies) { auto mock_layer = std::make_shared<MockLayer>(SkPath()); auto layer = std::make_shared<OpacityLayer>(SK_AlphaOPAQUE, SkPoint::Make(0.0f, 0.0f)); layer->Add(mock_layer); layer->Preroll(preroll_context()); EXPECT_EQ(mock_layer->paint_bounds(), SkPath().getBounds()); EXPECT_EQ(layer->paint_bounds(), mock_layer->paint_bounds()); EXPECT_EQ(layer->child_paint_bounds(), mock_layer->paint_bounds()); EXPECT_FALSE(mock_layer->needs_painting(paint_context())); EXPECT_FALSE(layer->needs_painting(paint_context())); EXPECT_DEATH_IF_SUPPORTED(layer->Paint(paint_context()), "needs_painting\\(context\\)"); } TEST_F(OpacityLayerTest, PaintBeforePrerollDies) { SkPath child_path; child_path.addRect(5.0f, 6.0f, 20.5f, 21.5f); auto mock_layer = std::make_shared<MockLayer>(child_path); auto layer = std::make_shared<OpacityLayer>(SK_AlphaOPAQUE, SkPoint::Make(0.0f, 0.0f)); layer->Add(mock_layer); EXPECT_DEATH_IF_SUPPORTED(layer->Paint(paint_context()), "needs_painting\\(context\\)"); } #endif TEST_F(OpacityLayerTest, TranslateChildren) { SkPath child_path1; child_path1.addRect(10.0f, 10.0f, 20.0f, 20.f); DlPaint child_paint1 = DlPaint(DlColor::kMidGrey()); auto layer = std::make_shared<OpacityLayer>(0.5, SkPoint::Make(10, 10)); auto mock_layer1 = std::make_shared<MockLayer>(child_path1, child_paint1); layer->Add(mock_layer1); auto initial_transform = SkMatrix::Scale(2.0, 2.0); preroll_context()->state_stack.set_preroll_delegate(initial_transform); layer->Preroll(preroll_context()); SkRect layer_bounds = mock_layer1->paint_bounds(); mock_layer1->parent_matrix().mapRect(&layer_bounds); EXPECT_EQ(layer_bounds, SkRect::MakeXYWH(40, 40, 20, 20)); } TEST_F(OpacityLayerTest, CacheChild) { const SkAlpha alpha_half = 255 / 2; auto initial_transform = SkMatrix::Translate(50.0, 25.5); auto other_transform = SkMatrix::Scale(1.0, 2.0); const SkPath child_path = SkPath().addRect(SkRect::MakeWH(5.0f, 5.0f)); auto mock_layer = std::make_shared<MockLayer>(child_path); auto layer = std::make_shared<OpacityLayer>(alpha_half, SkPoint::Make(0.0f, 0.0f)); layer->Add(mock_layer); DlPaint paint; SkMatrix cache_ctm = initial_transform; DisplayListBuilder cache_canvas; cache_canvas.Transform(cache_ctm); DisplayListBuilder other_canvas; other_canvas.Transform(other_transform); use_mock_raster_cache(); EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)0); const auto* cacheable_opacity_item = layer->raster_cache_item(); EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)0); EXPECT_EQ(cacheable_opacity_item->cache_state(), RasterCacheItem::CacheState::kNone); EXPECT_FALSE(cacheable_opacity_item->GetId().has_value()); preroll_context()->state_stack.set_preroll_delegate(initial_transform); layer->Preroll(preroll_context()); LayerTree::TryToRasterCache(cacheable_items(), &paint_context()); EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)1); EXPECT_EQ(cacheable_opacity_item->cache_state(), RasterCacheItem::CacheState::kChildren); EXPECT_EQ( cacheable_opacity_item->GetId().value(), RasterCacheKeyID(RasterCacheKeyID::LayerChildrenIds(layer.get()).value(), RasterCacheKeyType::kLayerChildren)); EXPECT_FALSE(raster_cache()->Draw(cacheable_opacity_item->GetId().value(), other_canvas, &paint)); EXPECT_TRUE(raster_cache()->Draw(cacheable_opacity_item->GetId().value(), cache_canvas, &paint)); } TEST_F(OpacityLayerTest, CacheChildren) { const SkAlpha alpha_half = 255 / 2; auto initial_transform = SkMatrix::Translate(50.0, 25.5); auto other_transform = SkMatrix::Scale(1.0, 2.0); const SkPath child_path1 = SkPath().addRect(SkRect::MakeWH(5.0f, 5.0f)); const SkPath child_path2 = SkPath().addRect(SkRect::MakeWH(5.0f, 5.0f)); DlPaint paint; auto mock_layer1 = std::make_shared<MockLayer>(child_path1); auto mock_layer2 = std::make_shared<MockLayer>(child_path2); auto layer = std::make_shared<OpacityLayer>(alpha_half, SkPoint::Make(0.0f, 0.0f)); layer->Add(mock_layer1); layer->Add(mock_layer2); SkMatrix cache_ctm = initial_transform; DisplayListBuilder cache_canvas; cache_canvas.Transform(cache_ctm); DisplayListBuilder other_canvas; other_canvas.Transform(other_transform); use_mock_raster_cache(); EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)0); const auto* cacheable_opacity_item = layer->raster_cache_item(); EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)0); EXPECT_EQ(cacheable_opacity_item->cache_state(), RasterCacheItem::CacheState::kNone); EXPECT_FALSE(cacheable_opacity_item->GetId().has_value()); preroll_context()->state_stack.set_preroll_delegate(initial_transform); layer->Preroll(preroll_context()); LayerTree::TryToRasterCache(cacheable_items(), &paint_context()); EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)1); EXPECT_EQ(cacheable_opacity_item->cache_state(), RasterCacheItem::CacheState::kChildren); EXPECT_EQ( cacheable_opacity_item->GetId().value(), RasterCacheKeyID(RasterCacheKeyID::LayerChildrenIds(layer.get()).value(), RasterCacheKeyType::kLayerChildren)); EXPECT_FALSE(raster_cache()->Draw(cacheable_opacity_item->GetId().value(), other_canvas, &paint)); EXPECT_TRUE(raster_cache()->Draw(cacheable_opacity_item->GetId().value(), cache_canvas, &paint)); } TEST_F(OpacityLayerTest, ShouldNotCacheChildren) { DlPaint paint; auto opacity_layer = std::make_shared<OpacityLayer>(128, SkPoint::Make(20, 20)); auto mock_layer = MockLayer::MakeOpacityCompatible(SkPath()); opacity_layer->Add(mock_layer); PrerollContext* context = preroll_context(); use_mock_raster_cache(); EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)0); const auto* cacheable_opacity_item = opacity_layer->raster_cache_item(); EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)0); EXPECT_EQ(cacheable_opacity_item->cache_state(), RasterCacheItem::CacheState::kNone); EXPECT_FALSE(cacheable_opacity_item->GetId().has_value()); opacity_layer->Preroll(preroll_context()); EXPECT_EQ(context->renderable_state_flags, LayerStateStack::kCallerCanApplyOpacity); EXPECT_TRUE(opacity_layer->children_can_accept_opacity()); LayerTree::TryToRasterCache(cacheable_items(), &paint_context()); EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)0); EXPECT_EQ(cacheable_opacity_item->cache_state(), RasterCacheItem::CacheState::kNone); EXPECT_FALSE(cacheable_opacity_item->Draw(paint_context(), &paint)); } TEST_F(OpacityLayerTest, FullyOpaque) { const SkPath child_path = SkPath().addRect(SkRect::MakeWH(5.0f, 5.0f)); const SkPoint layer_offset = SkPoint::Make(0.5f, 1.5f); const SkMatrix initial_transform = SkMatrix::Translate(0.5f, 0.5f); const SkMatrix layer_transform = SkMatrix::Translate(layer_offset.fX, layer_offset.fY); const DlPaint child_paint = DlPaint(DlColor::kGreen()); const SkRect expected_layer_bounds = layer_transform.mapRect(child_path.getBounds()); auto mock_layer = std::make_shared<MockLayer>(child_path, child_paint); auto layer = std::make_shared<OpacityLayer>(SK_AlphaOPAQUE, layer_offset); layer->Add(mock_layer); preroll_context()->state_stack.set_preroll_delegate(initial_transform); layer->Preroll(preroll_context()); EXPECT_EQ(mock_layer->paint_bounds(), child_path.getBounds()); EXPECT_EQ(layer->paint_bounds(), expected_layer_bounds); EXPECT_EQ(layer->child_paint_bounds(), child_path.getBounds()); EXPECT_TRUE(mock_layer->needs_painting(paint_context())); EXPECT_TRUE(layer->needs_painting(paint_context())); EXPECT_EQ(mock_layer->parent_matrix(), SkMatrix::Concat(initial_transform, layer_transform)); EXPECT_EQ(mock_layer->parent_mutators(), std::vector({Mutator(layer_transform)})); DisplayListBuilder expected_builder; /* (Opacity)layer::Paint */ { expected_builder.Save(); { expected_builder.Translate(layer_offset.fX, layer_offset.fY); // Opaque alpha needs no SaveLayer, just recurse into painting mock_layer /* mock_layer::Paint */ { expected_builder.DrawPath(child_path, child_paint); } } expected_builder.Restore(); } layer->Paint(display_list_paint_context()); EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } TEST_F(OpacityLayerTest, FullyTransparent) { const SkRect child_bounds = SkRect::MakeWH(5.0f, 5.0f); const SkPath child_path = SkPath().addRect(child_bounds); const SkPoint layer_offset = SkPoint::Make(0.5f, 1.5f); const SkMatrix initial_transform = SkMatrix::Translate(0.5f, 0.5f); const SkMatrix layer_transform = SkMatrix::Translate(layer_offset.fX, layer_offset.fY); const DlPaint child_paint = DlPaint(DlColor::kGreen()); const SkRect expected_layer_bounds = layer_transform.mapRect(child_path.getBounds()); auto mock_layer = std::make_shared<MockLayer>(child_path, child_paint); auto layer = std::make_shared<OpacityLayer>(SK_AlphaTRANSPARENT, layer_offset); layer->Add(mock_layer); preroll_context()->state_stack.set_preroll_delegate(initial_transform); layer->Preroll(preroll_context()); EXPECT_EQ(mock_layer->paint_bounds(), child_path.getBounds()); EXPECT_EQ(layer->paint_bounds(), expected_layer_bounds); EXPECT_EQ(layer->child_paint_bounds(), child_path.getBounds()); EXPECT_TRUE(mock_layer->needs_painting(paint_context())); EXPECT_TRUE(layer->needs_painting(paint_context())); EXPECT_EQ(mock_layer->parent_matrix(), SkMatrix::Concat(initial_transform, layer_transform)); EXPECT_EQ( mock_layer->parent_mutators(), std::vector({Mutator(layer_transform), Mutator(SK_AlphaTRANSPARENT)})); DisplayListBuilder expected_builder; /* (Opacity)layer::Paint */ { expected_builder.Save(); { expected_builder.Translate(layer_offset.fX, layer_offset.fY); /* (Opacity)layer::PaintChildren */ { DlPaint save_paint(DlPaint().setOpacity(layer->opacity())); expected_builder.SaveLayer(&child_bounds, &save_paint); /* mock_layer::Paint */ { expected_builder.DrawPath(child_path, child_paint); } expected_builder.Restore(); } } expected_builder.Restore(); } layer->Paint(display_list_paint_context()); EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } TEST_F(OpacityLayerTest, HalfTransparent) { const SkPath child_path = SkPath().addRect(SkRect::MakeWH(5.0f, 5.0f)); const SkPoint layer_offset = SkPoint::Make(0.5f, 1.5f); const SkMatrix initial_transform = SkMatrix::Translate(0.5f, 0.5f); const SkMatrix layer_transform = SkMatrix::Translate(layer_offset.fX, layer_offset.fY); const DlPaint child_paint = DlPaint(DlColor::kGreen()); const SkRect expected_layer_bounds = layer_transform.mapRect(child_path.getBounds()); const SkAlpha alpha_half = 255 / 2; auto mock_layer = std::make_shared<MockLayer>(child_path, child_paint); auto layer = std::make_shared<OpacityLayer>(alpha_half, layer_offset); layer->Add(mock_layer); preroll_context()->state_stack.set_preroll_delegate(initial_transform); layer->Preroll(preroll_context()); EXPECT_EQ(mock_layer->paint_bounds(), child_path.getBounds()); EXPECT_EQ(layer->paint_bounds(), expected_layer_bounds); EXPECT_EQ(layer->child_paint_bounds(), child_path.getBounds()); EXPECT_TRUE(mock_layer->needs_painting(paint_context())); EXPECT_TRUE(layer->needs_painting(paint_context())); EXPECT_EQ(mock_layer->parent_matrix(), SkMatrix::Concat(initial_transform, layer_transform)); EXPECT_EQ(mock_layer->parent_mutators(), std::vector({Mutator(layer_transform), Mutator(alpha_half)})); SkRect opacity_bounds; expected_layer_bounds.makeOffset(-layer_offset.fX, -layer_offset.fY) .roundOut(&opacity_bounds); DlPaint save_paint = DlPaint().setAlpha(alpha_half); DlPaint child_dl_paint = DlPaint(DlColor::kGreen()); auto expected_builder = DisplayListBuilder(); /* (Opacity)layer::Paint */ { expected_builder.Save(); expected_builder.Translate(layer_offset.fX, layer_offset.fY); /* (Opacity)layer::PaintChildren */ { expected_builder.SaveLayer(&opacity_bounds, &save_paint); /* mock_layer::Paint */ { expected_builder.DrawPath(child_path, child_dl_paint); } expected_builder.Restore(); } expected_builder.Restore(); } sk_sp<DisplayList> expected_display_list = expected_builder.Build(); layer->Paint(display_list_paint_context()); EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_display_list)); } TEST_F(OpacityLayerTest, Nested) { const SkPath child1_path = SkPath().addRect(SkRect::MakeWH(5.0f, 6.0f)); const SkPath child2_path = SkPath().addRect(SkRect::MakeWH(2.0f, 7.0f)); const SkPath child3_path = SkPath().addRect(SkRect::MakeWH(6.0f, 6.0f)); const SkPoint layer1_offset = SkPoint::Make(0.5f, 1.5f); const SkPoint layer2_offset = SkPoint::Make(2.5f, 0.5f); const SkMatrix initial_transform = SkMatrix::Translate(0.5f, 0.5f); const SkMatrix layer1_transform = SkMatrix::Translate(layer1_offset.fX, layer1_offset.fY); const SkMatrix layer2_transform = SkMatrix::Translate(layer2_offset.fX, layer2_offset.fY); const DlPaint child1_paint = DlPaint(DlColor::kRed()); const DlPaint child2_paint = DlPaint(DlColor::kBlue()); const DlPaint child3_paint = DlPaint(DlColor::kGreen()); const SkAlpha alpha1 = 155; const SkAlpha alpha2 = 224; auto mock_layer1 = std::make_shared<MockLayer>(child1_path, child1_paint); auto mock_layer2 = std::make_shared<MockLayer>(child2_path, child2_paint); auto mock_layer3 = std::make_shared<MockLayer>(child3_path, child3_paint); auto layer1 = std::make_shared<OpacityLayer>(alpha1, layer1_offset); auto layer2 = std::make_shared<OpacityLayer>(alpha2, layer2_offset); layer2->Add(mock_layer2); layer1->Add(mock_layer1); layer1->Add(layer2); layer1->Add(mock_layer3); // Ensure something is processed after recursion const SkRect expected_layer2_bounds = layer2_transform.mapRect(child2_path.getBounds()); SkRect layer1_child_bounds = expected_layer2_bounds; layer1_child_bounds.join(child1_path.getBounds()); layer1_child_bounds.join(child3_path.getBounds()); SkRect expected_layer1_bounds = layer1_transform.mapRect(layer1_child_bounds); preroll_context()->state_stack.set_preroll_delegate(initial_transform); layer1->Preroll(preroll_context()); EXPECT_EQ(mock_layer1->paint_bounds(), child1_path.getBounds()); EXPECT_EQ(mock_layer2->paint_bounds(), child2_path.getBounds()); EXPECT_EQ(mock_layer3->paint_bounds(), child3_path.getBounds()); EXPECT_EQ(layer1->paint_bounds(), expected_layer1_bounds); EXPECT_EQ(layer1->child_paint_bounds(), layer1_child_bounds); EXPECT_EQ(layer2->paint_bounds(), expected_layer2_bounds); EXPECT_EQ(layer2->child_paint_bounds(), child2_path.getBounds()); EXPECT_TRUE(mock_layer1->needs_painting(paint_context())); EXPECT_TRUE(mock_layer2->needs_painting(paint_context())); EXPECT_TRUE(mock_layer3->needs_painting(paint_context())); EXPECT_TRUE(layer1->needs_painting(paint_context())); EXPECT_TRUE(layer2->needs_painting(paint_context())); EXPECT_EQ(mock_layer1->parent_matrix(), SkMatrix::Concat(initial_transform, layer1_transform)); EXPECT_EQ(mock_layer1->parent_mutators(), std::vector({Mutator(layer1_transform), Mutator(alpha1)})); EXPECT_EQ( mock_layer2->parent_matrix(), SkMatrix::Concat(SkMatrix::Concat(initial_transform, layer1_transform), layer2_transform)); EXPECT_EQ(mock_layer2->parent_mutators(), std::vector({Mutator(layer1_transform), Mutator(alpha1), Mutator(layer2_transform), Mutator(alpha2)})); EXPECT_EQ(mock_layer3->parent_matrix(), SkMatrix::Concat(initial_transform, layer1_transform)); EXPECT_EQ(mock_layer3->parent_mutators(), std::vector({Mutator(layer1_transform), Mutator(alpha1)})); SkRect opacity1_bounds = expected_layer1_bounds.makeOffset(-layer1_offset.fX, -layer1_offset.fY); SkRect opacity2_bounds = expected_layer2_bounds.makeOffset(-layer2_offset.fX, -layer2_offset.fY); DlPaint opacity1_paint; opacity1_paint.setOpacity(alpha1 * (1.0 / SK_AlphaOPAQUE)); DlPaint opacity2_paint; opacity2_paint.setOpacity(alpha2 * (1.0 / SK_AlphaOPAQUE)); DisplayListBuilder expected_builder; /* (Opacity)layer1::Paint */ { expected_builder.Save(); { expected_builder.Translate(layer1_offset.fX, layer1_offset.fY); /* (Opacity)layer1::PaintChildren */ { expected_builder.SaveLayer(&opacity1_bounds, &opacity1_paint); /* mock_layer1::Paint */ { expected_builder.DrawPath(child1_path, child1_paint); } /* (Opacity)layer2::Paint */ { expected_builder.Save(); { expected_builder.Translate(layer2_offset.fX, layer2_offset.fY); /* (Opacity)layer2::PaintChidren */ { expected_builder.SaveLayer(&opacity2_bounds, &opacity2_paint); { /* mock_layer2::Paint */ { expected_builder.DrawPath(child2_path, child2_paint); } } expected_builder.Restore(); } } expected_builder.Restore(); } /* mock_layer3::Paint */ { expected_builder.DrawPath(child3_path, child3_paint); } expected_builder.Restore(); } } expected_builder.Restore(); } layer1->Paint(display_list_paint_context()); EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_builder.Build())); } TEST_F(OpacityLayerTest, Readback) { auto layer = std::make_shared<OpacityLayer>(kOpaque_SkAlphaType, SkPoint()); layer->Add(std::make_shared<MockLayer>(SkPath())); // OpacityLayer does not read from surface preroll_context()->surface_needs_readback = false; layer->Preroll(preroll_context()); EXPECT_FALSE(preroll_context()->surface_needs_readback); // OpacityLayer blocks child with readback auto mock_layer = std::make_shared<MockLayer>(SkPath(), DlPaint()); mock_layer->set_fake_reads_surface(true); layer->Add(mock_layer); preroll_context()->surface_needs_readback = false; layer->Preroll(preroll_context()); EXPECT_FALSE(preroll_context()->surface_needs_readback); } TEST_F(OpacityLayerTest, CullRectIsTransformed) { auto clip_rect_layer = std::make_shared<ClipRectLayer>( SkRect::MakeLTRB(0, 0, 10, 10), Clip::kHardEdge); auto opacity_layer = std::make_shared<OpacityLayer>(128, SkPoint::Make(20, 20)); auto mock_layer = std::make_shared<MockLayer>(SkPath()); clip_rect_layer->Add(opacity_layer); opacity_layer->Add(mock_layer); clip_rect_layer->Preroll(preroll_context()); EXPECT_EQ(mock_layer->parent_cull_rect().fLeft, -20); EXPECT_EQ(mock_layer->parent_cull_rect().fTop, -20); } TEST_F(OpacityLayerTest, OpacityInheritanceCompatibleChild) { auto opacity_layer = std::make_shared<OpacityLayer>(128, SkPoint::Make(20, 20)); auto mock_layer = MockLayer::MakeOpacityCompatible(SkPath()); opacity_layer->Add(mock_layer); PrerollContext* context = preroll_context(); opacity_layer->Preroll(context); EXPECT_EQ(context->renderable_state_flags, LayerStateStack::kCallerCanApplyOpacity); EXPECT_TRUE(opacity_layer->children_can_accept_opacity()); } TEST_F(OpacityLayerTest, OpacityInheritanceIncompatibleChild) { auto opacity_layer = std::make_shared<OpacityLayer>(128, SkPoint::Make(20, 20)); auto mock_layer = MockLayer::Make(SkPath()); opacity_layer->Add(mock_layer); PrerollContext* context = preroll_context(); opacity_layer->Preroll(context); EXPECT_EQ(context->renderable_state_flags, LayerStateStack::kCallerCanApplyOpacity); EXPECT_FALSE(opacity_layer->children_can_accept_opacity()); } TEST_F(OpacityLayerTest, OpacityInheritanceThroughContainer) { auto opacity_layer = std::make_shared<OpacityLayer>(128, SkPoint::Make(20, 20)); auto container_layer = std::make_shared<ContainerLayer>(); auto mock_layer = MockLayer::MakeOpacityCompatible(SkPath()); container_layer->Add(mock_layer); opacity_layer->Add(container_layer); PrerollContext* context = preroll_context(); opacity_layer->Preroll(context); EXPECT_EQ(context->renderable_state_flags, LayerStateStack::kCallerCanApplyOpacity); EXPECT_TRUE(opacity_layer->children_can_accept_opacity()); } TEST_F(OpacityLayerTest, OpacityInheritanceThroughTransform) { auto opacity_layer = std::make_shared<OpacityLayer>(128, SkPoint::Make(20, 20)); auto transformLayer = std::make_shared<TransformLayer>(SkMatrix::Scale(2, 2)); auto mock_layer = MockLayer::MakeOpacityCompatible(SkPath()); transformLayer->Add(mock_layer); opacity_layer->Add(transformLayer); PrerollContext* context = preroll_context(); opacity_layer->Preroll(context); EXPECT_EQ(context->renderable_state_flags, LayerStateStack::kCallerCanApplyOpacity); EXPECT_TRUE(opacity_layer->children_can_accept_opacity()); } TEST_F(OpacityLayerTest, OpacityInheritanceThroughImageFilter) { auto opacity_layer = std::make_shared<OpacityLayer>(128, SkPoint::Make(20, 20)); auto filter_layer = std::make_shared<ImageFilterLayer>( std::make_shared<DlBlurImageFilter>(5.0, 5.0, DlTileMode::kClamp)); auto mock_layer = MockLayer::MakeOpacityCompatible(SkPath()); filter_layer->Add(mock_layer); opacity_layer->Add(filter_layer); PrerollContext* context = preroll_context(); opacity_layer->Preroll(context); EXPECT_EQ(context->renderable_state_flags, LayerStateStack::kCallerCanApplyOpacity); EXPECT_TRUE(opacity_layer->children_can_accept_opacity()); } TEST_F(OpacityLayerTest, OpacityInheritanceNestedWithCompatibleChild) { SkPoint offset1 = SkPoint::Make(10, 20); SkPoint offset2 = SkPoint::Make(20, 10); SkPath mock_path = SkPath::Rect({10, 10, 20, 20}); auto opacity_layer_1 = std::make_shared<OpacityLayer>(128, offset1); auto opacity_layer_2 = std::make_shared<OpacityLayer>(64, offset2); auto mock_layer = MockLayer::MakeOpacityCompatible(mock_path); opacity_layer_2->Add(mock_layer); opacity_layer_1->Add(opacity_layer_2); PrerollContext* context = preroll_context(); opacity_layer_1->Preroll(context); EXPECT_EQ(context->renderable_state_flags, LayerStateStack::kCallerCanApplyOpacity); EXPECT_TRUE(opacity_layer_1->children_can_accept_opacity()); EXPECT_TRUE(opacity_layer_2->children_can_accept_opacity()); DlPaint savelayer_paint; SkScalar inherited_opacity = 128 * 1.0 / SK_AlphaOPAQUE; inherited_opacity *= 64 * 1.0 / SK_AlphaOPAQUE; savelayer_paint.setOpacity(inherited_opacity); DisplayListBuilder expected_builder; /* opacity_layer_1::Paint */ { expected_builder.Save(); { expected_builder.Translate(offset1.fX, offset1.fY); /* opacity_layer_2::Paint */ { expected_builder.Save(); { expected_builder.Translate(offset2.fX, offset2.fY); /* mock_layer::Paint */ { expected_builder.DrawPath(mock_path, DlPaint().setOpacity(inherited_opacity)); } } expected_builder.Restore(); } } expected_builder.Restore(); } opacity_layer_1->Paint(display_list_paint_context()); EXPECT_TRUE(DisplayListsEQ_Verbose(expected_builder.Build(), display_list())); } TEST_F(OpacityLayerTest, OpacityInheritanceNestedWithIncompatibleChild) { SkPoint offset1 = SkPoint::Make(10, 20); SkPoint offset2 = SkPoint::Make(20, 10); SkPath mock_path = SkPath::Rect({10, 10, 20, 20}); auto opacity_layer_1 = std::make_shared<OpacityLayer>(128, offset1); auto opacity_layer_2 = std::make_shared<OpacityLayer>(64, offset2); auto mock_layer = MockLayer::Make(mock_path); opacity_layer_2->Add(mock_layer); opacity_layer_1->Add(opacity_layer_2); PrerollContext* context = preroll_context(); opacity_layer_1->Preroll(context); EXPECT_EQ(context->renderable_state_flags, LayerStateStack::kCallerCanApplyOpacity); EXPECT_TRUE(opacity_layer_1->children_can_accept_opacity()); EXPECT_FALSE(opacity_layer_2->children_can_accept_opacity()); DlPaint savelayer_paint; SkScalar inherited_opacity = 128 * 1.0 / SK_AlphaOPAQUE; inherited_opacity *= 64 * 1.0 / SK_AlphaOPAQUE; savelayer_paint.setOpacity(inherited_opacity); DisplayListBuilder expected_builder; /* opacity_layer_1::Paint */ { expected_builder.Save(); { expected_builder.Translate(offset1.fX, offset1.fY); /* opacity_layer_2::Paint */ { expected_builder.Save(); { expected_builder.Translate(offset2.fX, offset2.fY); expected_builder.SaveLayer(&mock_layer->paint_bounds(), &savelayer_paint); /* mock_layer::Paint */ { expected_builder.DrawPath(mock_path, DlPaint()); } } expected_builder.Restore(); } } expected_builder.Restore(); } opacity_layer_1->Paint(display_list_paint_context()); EXPECT_TRUE(DisplayListsEQ_Verbose(expected_builder.Build(), display_list())); } using OpacityLayerDiffTest = DiffContextTest; TEST_F(OpacityLayerDiffTest, FractionalTranslation) { auto picture = CreateDisplayListLayer( CreateDisplayList(SkRect::MakeLTRB(10, 10, 60, 60))); auto layer = CreateOpacityLater({picture}, 128, SkPoint::Make(0.5, 0.5)); MockLayerTree tree1; tree1.root()->Add(layer); auto damage = DiffLayerTree(tree1, MockLayerTree(), SkIRect::MakeEmpty(), 0, 0, /*use_raster_cache=*/false); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(10, 10, 61, 61)); } TEST_F(OpacityLayerDiffTest, FractionalTranslationWithRasterCache) { auto picture = CreateDisplayListLayer( CreateDisplayList(SkRect::MakeLTRB(10, 10, 60, 60))); auto layer = CreateOpacityLater({picture}, 128, SkPoint::Make(0.5, 0.5)); MockLayerTree tree1; tree1.root()->Add(layer); auto damage = DiffLayerTree(tree1, MockLayerTree(), SkIRect::MakeEmpty(), 0, 0, /*use_raster_cache=*/true); EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(11, 11, 61, 61)); } TEST_F(OpacityLayerTest, FullyOpaqueWithFractionalValues) { use_mock_raster_cache(); // Ensure pixel-snapped alignment. const SkPath child_path = SkPath().addRect(SkRect::MakeWH(5.0f, 5.0f)); const SkPoint layer_offset = SkPoint::Make(0.5f, 1.5f); const SkMatrix initial_transform = SkMatrix::Translate(0.5f, 0.5f); const DlPaint child_paint = DlPaint(DlColor::kGreen()); auto mock_layer = std::make_shared<MockLayer>(child_path, child_paint); auto layer = std::make_shared<OpacityLayer>(SK_AlphaOPAQUE, layer_offset); layer->Add(mock_layer); preroll_context()->state_stack.set_preroll_delegate(initial_transform); layer->Preroll(preroll_context()); auto expected_builder = DisplayListBuilder(); /* (Opacity)layer::Paint */ { expected_builder.Save(); expected_builder.Translate(layer_offset.fX, layer_offset.fY); // Opaque alpha needs no SaveLayer, just recurse into painting mock_layer // but since we use the mock raster cache we pixel snap the transform expected_builder.TransformReset(); expected_builder.Transform2DAffine( 1, 0, SkScalarRoundToScalar(layer_offset.fX), // 0, 1, SkScalarRoundToScalar(layer_offset.fY)); /* mock_layer::Paint */ { expected_builder.DrawPath(child_path, child_paint); } expected_builder.Restore(); } sk_sp<DisplayList> expected_display_list = expected_builder.Build(); layer->Paint(display_list_paint_context()); EXPECT_TRUE(DisplayListsEQ_Verbose(display_list(), expected_display_list)); } TEST_F(OpacityLayerTest, FullyTransparentDoesNotCullPlatformView) { const SkPoint opacity_offset = SkPoint::Make(0.5f, 1.5f); const SkPoint view_offset = SkPoint::Make(0.0f, 0.0f); const SkSize view_size = SkSize::Make(8.0f, 8.0f); const int64_t view_id = 42; auto platform_view = std::make_shared<PlatformViewLayer>(view_offset, view_size, view_id); auto opacity = std::make_shared<OpacityLayer>(SK_AlphaTRANSPARENT, opacity_offset); opacity->Add(platform_view); auto embedder = MockViewEmbedder(); DisplayListBuilder fake_overlay_builder; embedder.AddCanvas(&fake_overlay_builder); preroll_context()->view_embedder = &embedder; paint_context().view_embedder = &embedder; opacity->Preroll(preroll_context()); EXPECT_EQ(embedder.prerolled_views(), std::vector<int64_t>({view_id})); opacity->Paint(paint_context()); EXPECT_EQ(embedder.painted_views(), std::vector<int64_t>({view_id})); } } // namespace testing } // namespace flutter // NOLINTEND(bugprone-unchecked-optional-access)
engine/flow/layers/opacity_layer_unittests.cc/0
{ "file_path": "engine/flow/layers/opacity_layer_unittests.cc", "repo_id": "engine", "token_count": 12030 }
301
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/flow/embedded_views.h" #include "gtest/gtest.h" namespace flutter { namespace testing { TEST(MutatorsStack, Initialization) { MutatorsStack stack; ASSERT_TRUE(true); } TEST(MutatorsStack, CopyConstructor) { MutatorsStack stack; auto rrect = SkRRect::MakeEmpty(); auto rect = SkRect::MakeEmpty(); stack.PushClipRect(rect); stack.PushClipRRect(rrect); MutatorsStack copy = MutatorsStack(stack); ASSERT_TRUE(copy == stack); } TEST(MutatorsStack, CopyAndUpdateTheCopy) { MutatorsStack stack; auto rrect = SkRRect::MakeEmpty(); auto rect = SkRect::MakeEmpty(); stack.PushClipRect(rect); stack.PushClipRRect(rrect); MutatorsStack copy = MutatorsStack(stack); copy.Pop(); copy.Pop(); ASSERT_TRUE(copy != stack); ASSERT_TRUE(copy.is_empty()); ASSERT_TRUE(!stack.is_empty()); auto iter = stack.Bottom(); ASSERT_TRUE(iter->get()->GetType() == MutatorType::kClipRRect); ASSERT_TRUE(iter->get()->GetRRect() == rrect); ++iter; ASSERT_TRUE(iter->get()->GetType() == MutatorType::kClipRect); ASSERT_TRUE(iter->get()->GetRect() == rect); } TEST(MutatorsStack, PushClipRect) { MutatorsStack stack; auto rect = SkRect::MakeEmpty(); stack.PushClipRect(rect); auto iter = stack.Bottom(); ASSERT_TRUE(iter->get()->GetType() == MutatorType::kClipRect); ASSERT_TRUE(iter->get()->GetRect() == rect); } TEST(MutatorsStack, PushClipRRect) { MutatorsStack stack; auto rrect = SkRRect::MakeEmpty(); stack.PushClipRRect(rrect); auto iter = stack.Bottom(); ASSERT_TRUE(iter->get()->GetType() == MutatorType::kClipRRect); ASSERT_TRUE(iter->get()->GetRRect() == rrect); } TEST(MutatorsStack, PushClipPath) { MutatorsStack stack; SkPath path; stack.PushClipPath(path); auto iter = stack.Bottom(); ASSERT_TRUE(iter->get()->GetType() == flutter::MutatorType::kClipPath); ASSERT_TRUE(iter->get()->GetPath() == path); } TEST(MutatorsStack, PushTransform) { MutatorsStack stack; SkMatrix matrix; matrix.setIdentity(); stack.PushTransform(matrix); auto iter = stack.Bottom(); ASSERT_TRUE(iter->get()->GetType() == MutatorType::kTransform); ASSERT_TRUE(iter->get()->GetMatrix() == matrix); } TEST(MutatorsStack, PushOpacity) { MutatorsStack stack; int alpha = 240; stack.PushOpacity(alpha); auto iter = stack.Bottom(); ASSERT_TRUE(iter->get()->GetType() == MutatorType::kOpacity); ASSERT_TRUE(iter->get()->GetAlpha() == 240); } TEST(MutatorsStack, PushBackdropFilter) { MutatorsStack stack; const int num_of_mutators = 10; for (int i = 0; i < num_of_mutators; i++) { auto filter = std::make_shared<DlBlurImageFilter>(i, 5, DlTileMode::kClamp); stack.PushBackdropFilter(filter, SkRect::MakeXYWH(i, i, i, i)); } auto iter = stack.Begin(); int i = 0; while (iter != stack.End()) { ASSERT_EQ(iter->get()->GetType(), MutatorType::kBackdropFilter); ASSERT_EQ(iter->get()->GetFilterMutation().GetFilter().asBlur()->sigma_x(), i); ASSERT_EQ(iter->get()->GetFilterMutation().GetFilterRect().x(), i); ASSERT_EQ(iter->get()->GetFilterMutation().GetFilterRect().x(), i); ASSERT_EQ(iter->get()->GetFilterMutation().GetFilterRect().width(), i); ASSERT_EQ(iter->get()->GetFilterMutation().GetFilterRect().height(), i); ++iter; ++i; } ASSERT_EQ(i, num_of_mutators); } TEST(MutatorsStack, Pop) { MutatorsStack stack; SkMatrix matrix; matrix.setIdentity(); stack.PushTransform(matrix); stack.Pop(); auto iter = stack.Bottom(); ASSERT_TRUE(iter == stack.Top()); } TEST(MutatorsStack, Traversal) { MutatorsStack stack; SkMatrix matrix; matrix.setIdentity(); stack.PushTransform(matrix); auto rect = SkRect::MakeEmpty(); stack.PushClipRect(rect); auto rrect = SkRRect::MakeEmpty(); stack.PushClipRRect(rrect); auto iter = stack.Bottom(); int index = 0; while (iter != stack.Top()) { switch (index) { case 0: ASSERT_TRUE(iter->get()->GetType() == MutatorType::kClipRRect); ASSERT_TRUE(iter->get()->GetRRect() == rrect); break; case 1: ASSERT_TRUE(iter->get()->GetType() == MutatorType::kClipRect); ASSERT_TRUE(iter->get()->GetRect() == rect); break; case 2: ASSERT_TRUE(iter->get()->GetType() == MutatorType::kTransform); ASSERT_TRUE(iter->get()->GetMatrix() == matrix); break; default: break; } ++iter; ++index; } } TEST(MutatorsStack, Equality) { MutatorsStack stack; SkMatrix matrix = SkMatrix::Scale(1, 1); stack.PushTransform(matrix); SkRect rect = SkRect::MakeEmpty(); stack.PushClipRect(rect); SkRRect rrect = SkRRect::MakeEmpty(); stack.PushClipRRect(rrect); SkPath path; stack.PushClipPath(path); int alpha = 240; stack.PushOpacity(alpha); auto filter = std::make_shared<DlBlurImageFilter>(5, 5, DlTileMode::kClamp); stack.PushBackdropFilter(filter, SkRect::MakeEmpty()); MutatorsStack stack_other; SkMatrix matrix_other = SkMatrix::Scale(1, 1); stack_other.PushTransform(matrix_other); SkRect rect_other = SkRect::MakeEmpty(); stack_other.PushClipRect(rect_other); SkRRect rrect_other = SkRRect::MakeEmpty(); stack_other.PushClipRRect(rrect_other); SkPath other_path; stack_other.PushClipPath(other_path); int other_alpha = 240; stack_other.PushOpacity(other_alpha); auto other_filter = std::make_shared<DlBlurImageFilter>(5, 5, DlTileMode::kClamp); stack_other.PushBackdropFilter(other_filter, SkRect::MakeEmpty()); ASSERT_TRUE(stack == stack_other); } TEST(Mutator, Initialization) { SkRect rect = SkRect::MakeEmpty(); Mutator mutator = Mutator(rect); ASSERT_TRUE(mutator.GetType() == MutatorType::kClipRect); ASSERT_TRUE(mutator.GetRect() == rect); SkRRect rrect = SkRRect::MakeEmpty(); Mutator mutator2 = Mutator(rrect); ASSERT_TRUE(mutator2.GetType() == MutatorType::kClipRRect); ASSERT_TRUE(mutator2.GetRRect() == rrect); SkPath path; Mutator mutator3 = Mutator(path); ASSERT_TRUE(mutator3.GetType() == MutatorType::kClipPath); ASSERT_TRUE(mutator3.GetPath() == path); SkMatrix matrix; matrix.setIdentity(); Mutator mutator4 = Mutator(matrix); ASSERT_TRUE(mutator4.GetType() == MutatorType::kTransform); ASSERT_TRUE(mutator4.GetMatrix() == matrix); int alpha = 240; Mutator mutator5 = Mutator(alpha); ASSERT_TRUE(mutator5.GetType() == MutatorType::kOpacity); auto filter = std::make_shared<DlBlurImageFilter>(5, 5, DlTileMode::kClamp); Mutator mutator6 = Mutator(filter, SkRect::MakeEmpty()); ASSERT_TRUE(mutator6.GetType() == MutatorType::kBackdropFilter); ASSERT_TRUE(mutator6.GetFilterMutation().GetFilter() == *filter); } TEST(Mutator, CopyConstructor) { SkRect rect = SkRect::MakeEmpty(); Mutator mutator = Mutator(rect); Mutator copy = Mutator(mutator); ASSERT_TRUE(mutator == copy); SkRRect rrect = SkRRect::MakeEmpty(); Mutator mutator2 = Mutator(rrect); Mutator copy2 = Mutator(mutator2); ASSERT_TRUE(mutator2 == copy2); SkPath path; Mutator mutator3 = Mutator(path); Mutator copy3 = Mutator(mutator3); ASSERT_TRUE(mutator3 == copy3); SkMatrix matrix; matrix.setIdentity(); Mutator mutator4 = Mutator(matrix); Mutator copy4 = Mutator(mutator4); ASSERT_TRUE(mutator4 == copy4); int alpha = 240; Mutator mutator5 = Mutator(alpha); Mutator copy5 = Mutator(mutator5); ASSERT_TRUE(mutator5 == copy5); auto filter = std::make_shared<DlBlurImageFilter>(5, 5, DlTileMode::kClamp); Mutator mutator6 = Mutator(filter, SkRect::MakeEmpty()); Mutator copy6 = Mutator(mutator6); ASSERT_TRUE(mutator6 == copy6); } TEST(Mutator, Equality) { SkMatrix matrix; matrix.setIdentity(); Mutator mutator = Mutator(matrix); Mutator other_mutator = Mutator(matrix); ASSERT_TRUE(mutator == other_mutator); SkRect rect = SkRect::MakeEmpty(); Mutator mutator2 = Mutator(rect); Mutator other_mutator2 = Mutator(rect); ASSERT_TRUE(mutator2 == other_mutator2); SkRRect rrect = SkRRect::MakeEmpty(); Mutator mutator3 = Mutator(rrect); Mutator other_mutator3 = Mutator(rrect); ASSERT_TRUE(mutator3 == other_mutator3); SkPath path; flutter::Mutator mutator4 = flutter::Mutator(path); flutter::Mutator other_mutator4 = flutter::Mutator(path); ASSERT_TRUE(mutator4 == other_mutator4); ASSERT_FALSE(mutator2 == mutator); int alpha = 240; Mutator mutator5 = Mutator(alpha); Mutator other_mutator5 = Mutator(alpha); ASSERT_TRUE(mutator5 == other_mutator5); auto filter1 = std::make_shared<DlBlurImageFilter>(5, 5, DlTileMode::kClamp); auto filter2 = std::make_shared<DlBlurImageFilter>(5, 5, DlTileMode::kClamp); Mutator mutator6 = Mutator(filter1, SkRect::MakeEmpty()); Mutator other_mutator6 = Mutator(filter2, SkRect::MakeEmpty()); ASSERT_TRUE(mutator6 == other_mutator6); } TEST(Mutator, UnEquality) { SkRect rect = SkRect::MakeEmpty(); Mutator mutator = Mutator(rect); SkMatrix matrix; matrix.setIdentity(); Mutator not_equal_mutator = Mutator(matrix); ASSERT_TRUE(not_equal_mutator != mutator); int alpha = 240; int alpha2 = 241; Mutator mutator2 = Mutator(alpha); Mutator other_mutator2 = Mutator(alpha2); ASSERT_TRUE(mutator2 != other_mutator2); auto filter = std::make_shared<DlBlurImageFilter>(5, 5, DlTileMode::kClamp); auto filter2 = std::make_shared<DlBlurImageFilter>(10, 10, DlTileMode::kClamp); Mutator mutator3 = Mutator(filter, SkRect::MakeEmpty()); Mutator other_mutator3 = Mutator(filter2, SkRect::MakeEmpty()); ASSERT_TRUE(mutator3 != other_mutator3); } } // namespace testing } // namespace flutter
engine/flow/mutators_stack_unittests.cc/0
{ "file_path": "engine/flow/mutators_stack_unittests.cc", "repo_id": "engine", "token_count": 3723 }
302
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_FLOW_STOPWATCH_H_ #define FLUTTER_FLOW_STOPWATCH_H_ #include <vector> #include "flutter/display_list/dl_canvas.h" #include "flutter/fml/macros.h" #include "flutter/fml/time/time_delta.h" #include "flutter/fml/time/time_point.h" namespace flutter { class Stopwatch { public: /// The refresh rate interface for `Stopwatch`. class RefreshRateUpdater { public: /// Time limit for a smooth frame. /// See: `DisplayManager::GetMainDisplayRefreshRate`. virtual fml::Milliseconds GetFrameBudget() const = 0; }; /// The constructor with a updater parameter, it will update frame_budget /// everytime when `GetFrameBudget()` is called. explicit Stopwatch(const RefreshRateUpdater& updater); ~Stopwatch(); const fml::TimeDelta& GetLap(size_t index) const; /// Return a reference to all the laps. size_t GetLapsCount() const; size_t GetCurrentSample() const; const fml::TimeDelta& LastLap() const; fml::TimeDelta MaxDelta() const; fml::TimeDelta AverageDelta() const; void Start(); void Stop(); void SetLapTime(const fml::TimeDelta& delta); /// All places which want to get frame_budget should call this function. fml::Milliseconds GetFrameBudget() const; private: const RefreshRateUpdater& refresh_rate_updater_; fml::TimePoint start_; std::vector<fml::TimeDelta> laps_; size_t current_sample_ = 0; FML_DISALLOW_COPY_AND_ASSIGN(Stopwatch); }; /// Used for fixed refresh rate query cases. class FixedRefreshRateUpdater : public Stopwatch::RefreshRateUpdater { fml::Milliseconds GetFrameBudget() const override; public: explicit FixedRefreshRateUpdater( fml::Milliseconds fixed_frame_budget = fml::kDefaultFrameBudget); private: fml::Milliseconds fixed_frame_budget_; }; /// Used for fixed refresh rate cases. class FixedRefreshRateStopwatch : public Stopwatch { public: explicit FixedRefreshRateStopwatch( fml::Milliseconds fixed_frame_budget = fml::kDefaultFrameBudget); private: FixedRefreshRateUpdater fixed_delegate_; }; //------------------------------------------------------------------------------ /// @brief Abstract class for visualizing (i.e. drawing) a stopwatch. /// /// @note This was originally folded into the |Stopwatch| class, but /// was separated out to make it easier to change the underlying /// implementation (which relied directly on Skia, not showing on /// Impeller: https://github.com/flutter/flutter/issues/126009). class StopwatchVisualizer { public: explicit StopwatchVisualizer(const Stopwatch& stopwatch) : stopwatch_(stopwatch) { // Looking up the frame budget from the stopwatch delegate class may call // into JNI or make platform calls which are slow. This value is safe to // cache since the StopwatchVisualizer is recreated on each frame. frame_budget_ = stopwatch_.GetFrameBudget(); } virtual ~StopwatchVisualizer() = default; /// @brief Renders the stopwatch as a graph. /// /// @param canvas The canvas to draw on. /// @param[in] rect The rectangle to draw in. virtual void Visualize(DlCanvas* canvas, const SkRect& rect) const = 0; FML_DISALLOW_COPY_AND_ASSIGN(StopwatchVisualizer); protected: /// @brief Converts a raster time to a unit interval. double UnitFrameInterval(double time_ms) const; /// @brief Converts a raster time to a unit height. double UnitHeight(double time_ms, double max_height) const; fml::Milliseconds GetFrameBudget() const { return frame_budget_; } const Stopwatch& stopwatch_; fml::Milliseconds frame_budget_; }; } // namespace flutter #endif // FLUTTER_FLOW_STOPWATCH_H_
engine/flow/stopwatch.h/0
{ "file_path": "engine/flow/stopwatch.h", "repo_id": "engine", "token_count": 1266 }
303
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_FLOW_TESTING_LAYER_TEST_H_ #define FLUTTER_FLOW_TESTING_LAYER_TEST_H_ #include "display_list/dl_color.h" #include "flutter/flow/layer_snapshot_store.h" #include "flutter/flow/layers/layer.h" #include <optional> #include <utility> #include <vector> #include "flutter/flow/testing/mock_raster_cache.h" #include "flutter/fml/macros.h" #include "flutter/testing/canvas_test.h" #include "flutter/testing/display_list_testing.h" #include "flutter/testing/mock_canvas.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkImageInfo.h" #include "third_party/skia/include/utils/SkNWayCanvas.h" namespace flutter { namespace testing { // This fixture allows generating tests which can |Paint()| and |Preroll()| // |Layer|'s. // |LayerTest| is a default implementation based on |::testing::Test|. // // By default the preroll and paint contexts will not use a raster cache. // If a test needs to verify the proper operation of a layer in the presence // of a raster cache then a number of options can be enabled by using the // methods |LayerTestBase::use_null_raster_cache()|, // |LayerTestBase::use_mock_raster_cache()| or // |LayerTestBase::use_skia_raster_cache()| // // |BaseT| should be the base test type, such as |::testing::Test| below. template <typename BaseT> class LayerTestBase : public CanvasTestBase<BaseT> { using TestT = CanvasTestBase<BaseT>; const SkRect k_dl_bounds_ = SkRect::MakeWH(500, 500); public: LayerTestBase() : texture_registry_(std::make_shared<TextureRegistry>()), preroll_context_{ // clang-format off .raster_cache = nullptr, .gr_context = nullptr, .view_embedder = nullptr, .state_stack = preroll_state_stack_, .dst_color_space = TestT::mock_color_space(), .surface_needs_readback = false, .raster_time = raster_time_, .ui_time = ui_time_, .texture_registry = texture_registry_, .has_platform_view = false, .raster_cached_entries = &cacheable_items_, // clang-format on }, paint_context_{ // clang-format off .state_stack = paint_state_stack_, .canvas = &TestT::mock_canvas(), .gr_context = nullptr, .view_embedder = nullptr, .raster_time = raster_time_, .ui_time = ui_time_, .texture_registry = texture_registry_, .raster_cache = nullptr, // clang-format on }, display_list_builder_(k_dl_bounds_), display_list_paint_context_{ // clang-format off .state_stack = display_list_state_stack_, .canvas = &display_list_builder_, .gr_context = nullptr, .view_embedder = nullptr, .raster_time = raster_time_, .ui_time = ui_time_, .texture_registry = texture_registry_, .raster_cache = nullptr, // clang-format on }, checkerboard_context_{ // clang-format off .state_stack = checkerboard_state_stack_, .canvas = &display_list_builder_, .gr_context = nullptr, .view_embedder = nullptr, .raster_time = raster_time_, .ui_time = ui_time_, .texture_registry = texture_registry_, .raster_cache = nullptr, // clang-format on } { use_null_raster_cache(); preroll_state_stack_.set_preroll_delegate(kGiantRect, SkMatrix::I()); paint_state_stack_.set_delegate(&TestT::mock_canvas()); display_list_state_stack_.set_delegate(&display_list_builder_); checkerboard_state_stack_.set_delegate(&display_list_builder_); checkerboard_state_stack_.set_checkerboard_func(draw_checkerboard); checkerboard_paint_.setColor(kCheckerboardColor); } /** * @brief Use no raster cache in the preroll_context() and * paint_context() structures. * * This method must be called before using the preroll_context() and * paint_context() structures in calls to the Layer::Preroll() and * Layer::Paint() methods. This is the default mode of operation. * * @see use_mock_raster_cache() * @see use_skia_raster_cache() */ void use_null_raster_cache() { set_raster_cache_(nullptr); } /** * @brief Use a mock raster cache in the preroll_context() and * paint_context() structures. * * This method must be called before using the preroll_context() and * paint_context() structures in calls to the Layer::Preroll() and * Layer::Paint() methods. The mock raster cache behaves like a normal * raster cache with respect to decisions about when layers and pictures * should be cached, but it does not incur the overhead of rendering the * layers or caching the resulting pixels. * * @see use_null_raster_cache() * @see use_skia_raster_cache() */ void use_mock_raster_cache() { set_raster_cache_(std::make_unique<MockRasterCache>()); } /** * @brief Use a normal raster cache in the preroll_context() and * paint_context() structures. * * This method must be called before using the preroll_context() and * paint_context() structures in calls to the Layer::Preroll() and * Layer::Paint() methods. The Skia raster cache will behave identically * to the raster cache typically used when handling a frame on a device * including rendering the contents of pictures and layers to an * SkImage, but using a software rather than a hardware renderer. * * @see use_null_raster_cache() * @see use_mock_raster_cache() */ void use_skia_raster_cache() { set_raster_cache_(std::make_unique<RasterCache>()); } std::vector<RasterCacheItem*>& cacheable_items() { return cacheable_items_; } std::shared_ptr<TextureRegistry> texture_registry() { return texture_registry_; } RasterCache* raster_cache() { return raster_cache_.get(); } PrerollContext* preroll_context() { return &preroll_context_; } PaintContext& paint_context() { return paint_context_; } PaintContext& display_list_paint_context() { return display_list_paint_context_; } const DlPaint& checkerboard_paint() { return checkerboard_paint_; } PaintContext& checkerboard_context() { return checkerboard_context_; } LayerSnapshotStore& layer_snapshot_store() { return snapshot_store_; } sk_sp<DisplayList> display_list() { if (display_list_ == nullptr) { display_list_ = display_list_builder_.Build(); } return display_list_; } void reset_display_list() { display_list_ = nullptr; // Build() will leave the builder in a state to start recording a new DL display_list_builder_.Build(); // Make sure we are starting from a fresh state stack FML_DCHECK(display_list_state_stack_.is_empty()); } void enable_leaf_layer_tracing() { paint_context_.enable_leaf_layer_tracing = true; paint_context_.layer_snapshot_store = &snapshot_store_; } void disable_leaf_layer_tracing() { paint_context_.enable_leaf_layer_tracing = false; paint_context_.layer_snapshot_store = nullptr; } private: void set_raster_cache_(std::unique_ptr<RasterCache> raster_cache) { raster_cache_ = std::move(raster_cache); preroll_context_.raster_cache = raster_cache_.get(); paint_context_.raster_cache = raster_cache_.get(); display_list_paint_context_.raster_cache = raster_cache_.get(); } static constexpr DlColor kCheckerboardColor = DlColor(0x42424242); static void draw_checkerboard(DlCanvas* canvas, const SkRect& rect) { if (canvas) { DlPaint paint; paint.setColor(kCheckerboardColor); canvas->DrawRect(rect, paint); } } LayerStateStack preroll_state_stack_; LayerStateStack paint_state_stack_; LayerStateStack checkerboard_state_stack_; FixedRefreshRateStopwatch raster_time_; FixedRefreshRateStopwatch ui_time_; std::shared_ptr<TextureRegistry> texture_registry_; std::unique_ptr<RasterCache> raster_cache_; PrerollContext preroll_context_; PaintContext paint_context_; DisplayListBuilder display_list_builder_; LayerStateStack display_list_state_stack_; sk_sp<DisplayList> display_list_; PaintContext display_list_paint_context_; DlPaint checkerboard_paint_; PaintContext checkerboard_context_; LayerSnapshotStore snapshot_store_; std::vector<RasterCacheItem*> cacheable_items_; FML_DISALLOW_COPY_AND_ASSIGN(LayerTestBase); }; using LayerTest = LayerTestBase<::testing::Test>; } // namespace testing } // namespace flutter #endif // FLUTTER_FLOW_TESTING_LAYER_TEST_H_
engine/flow/testing/layer_test.h/0
{ "file_path": "engine/flow/testing/layer_test.h", "repo_id": "engine", "token_count": 4061 }
304
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "backtrace.h" #include "gtest/gtest.h" #include "logging.h" namespace fml { namespace testing { TEST(BacktraceTest, CanGatherBacktrace) { if (!IsCrashHandlingSupported()) { GTEST_SKIP(); return; } { auto trace = BacktraceHere(0); ASSERT_GT(trace.size(), 0u); ASSERT_NE(trace.find("Frame 0"), std::string::npos); } { auto trace = BacktraceHere(1); ASSERT_GT(trace.size(), 0u); ASSERT_NE(trace.find("Frame 0"), std::string::npos); } { auto trace = BacktraceHere(2); ASSERT_GT(trace.size(), 0u); ASSERT_NE(trace.find("Frame 0"), std::string::npos); } } } // namespace testing } // namespace fml
engine/fml/backtrace_unittests.cc/0
{ "file_path": "engine/fml/backtrace_unittests.cc", "repo_id": "engine", "token_count": 321 }
305
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/fml/cpu_affinity.h" #include "flutter/fml/build_config.h" #include <fstream> #include <optional> #include <string> #ifdef FML_OS_ANDROID #include "flutter/fml/platform/android/cpu_affinity.h" #endif // FML_OS_ANDROID namespace fml { std::optional<size_t> EfficiencyCoreCount() { #ifdef FML_OS_ANDROID return AndroidEfficiencyCoreCount(); #else return std::nullopt; #endif } bool RequestAffinity(CpuAffinity affinity) { #ifdef FML_OS_ANDROID return AndroidRequestAffinity(affinity); #else return true; #endif } CPUSpeedTracker::CPUSpeedTracker(std::vector<CpuIndexAndSpeed> data) : cpu_speeds_(std::move(data)) { std::optional<int64_t> max_speed = std::nullopt; std::optional<int64_t> min_speed = std::nullopt; for (const auto& data : cpu_speeds_) { if (!max_speed.has_value() || data.speed > max_speed.value()) { max_speed = data.speed; } if (!min_speed.has_value() || data.speed < min_speed.value()) { min_speed = data.speed; } } if (!max_speed.has_value() || !min_speed.has_value() || min_speed.value() == max_speed.value()) { return; } const int64_t max_speed_value = max_speed.value(); const int64_t min_speed_value = min_speed.value(); for (const auto& data : cpu_speeds_) { if (data.speed == max_speed_value) { performance_.push_back(data.index); } else { not_performance_.push_back(data.index); } if (data.speed == min_speed_value) { efficiency_.push_back(data.index); } } valid_ = true; } bool CPUSpeedTracker::IsValid() const { return valid_; } const std::vector<size_t>& CPUSpeedTracker::GetIndices( CpuAffinity affinity) const { switch (affinity) { case CpuAffinity::kPerformance: return performance_; case CpuAffinity::kEfficiency: return efficiency_; case CpuAffinity::kNotPerformance: return not_performance_; } } // Get the size of the cpuinfo file by reading it until the end. This is // required because files under /proc do not always return a valid size // when using fseek(0, SEEK_END) + ftell(). Nor can they be mmap()-ed. std::optional<int64_t> ReadIntFromFile(const std::string& path) { std::ifstream file; file.open(path.c_str()); // Dont use stoi because if this data isnt a parseable number then it // will abort, as we compile with exceptions disabled. int64_t speed = 0; file >> speed; if (speed > 0) { return speed; } return std::nullopt; } } // namespace fml
engine/fml/cpu_affinity.cc/0
{ "file_path": "engine/fml/cpu_affinity.cc", "repo_id": "engine", "token_count": 985 }
306
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/fml/hex_codec.h" #include <iostream> #include "gtest/gtest.h" TEST(HexCodecTest, CanEncode) { { auto result = fml::HexEncode("hello"); ASSERT_EQ(result, "68656c6c6f"); } { auto result = fml::HexEncode(""); ASSERT_EQ(result, ""); } { auto result = fml::HexEncode("1"); ASSERT_EQ(result, "31"); } { auto result = fml::HexEncode(std::string_view("\xFF\xFE\x00\x01", 4)); ASSERT_EQ(result, "fffe0001"); } }
engine/fml/hex_codec_unittest.cc/0
{ "file_path": "engine/fml/hex_codec_unittest.cc", "repo_id": "engine", "token_count": 275 }
307
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <cmath> #include "flutter/fml/math.h" #include "gtest/gtest.h" namespace flutter { namespace testing { TEST(MathTest, Constants) { // Don't use the constants in cmath as those aren't portable. EXPECT_FLOAT_EQ(std::log2(math::kE), math::kLog2E); EXPECT_FLOAT_EQ(std::log10(math::kE), math::kLog10E); EXPECT_FLOAT_EQ(std::log(2.0f), math::kLogE2); EXPECT_FLOAT_EQ(math::kPi / 2.0f, math::kPiOver2); EXPECT_FLOAT_EQ(math::kPi / 4.0f, math::kPiOver4); EXPECT_FLOAT_EQ(1.0f / math::kPi, math::k1OverPi); EXPECT_FLOAT_EQ(2.0f / math::kPi, math::k2OverPi); EXPECT_FLOAT_EQ(std::sqrt(2.0f), math::kSqrt2); EXPECT_FLOAT_EQ(1.0f / std::sqrt(2.0f), math::k1OverSqrt2); } } // namespace testing } // namespace flutter
engine/fml/math_unittests.cc/0
{ "file_path": "engine/fml/math_unittests.cc", "repo_id": "engine", "token_count": 401 }
308
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_FML_MESSAGE_LOOP_H_ #define FLUTTER_FML_MESSAGE_LOOP_H_ #include "flutter/fml/macros.h" #include "flutter/fml/task_runner.h" namespace fml { class TaskRunner; class MessageLoopImpl; /// An event loop associated with a thread. /// /// This class is the generic front-end to the MessageLoop, differences in /// implementation based on the running platform are in the subclasses of /// flutter::MessageLoopImpl (ex flutter::MessageLoopAndroid). /// /// For scheduling events on the message loop see flutter::TaskRunner. /// /// \see fml::TaskRunner /// \see fml::MessageLoopImpl /// \see fml::MessageLoopTaskQueues /// \see fml::Wakeable class MessageLoop { public: FML_EMBEDDER_ONLY static MessageLoop& GetCurrent(); void Run(); void Terminate(); void AddTaskObserver(intptr_t key, const fml::closure& callback); void RemoveTaskObserver(intptr_t key); fml::RefPtr<fml::TaskRunner> GetTaskRunner() const; // Exposed for the embedder shell which allows clients to poll for events // instead of dedicating a thread to the message loop. void RunExpiredTasksNow(); static void EnsureInitializedForCurrentThread(); /// Returns true if \p EnsureInitializedForCurrentThread has been called on /// this thread already. static bool IsInitializedForCurrentThread(); ~MessageLoop(); /// Gets the unique identifier for the TaskQueue associated with the current /// thread. /// \see fml::MessageLoopTaskQueues static TaskQueueId GetCurrentTaskQueueId(); private: friend class TaskRunner; friend class MessageLoopImpl; fml::RefPtr<MessageLoopImpl> loop_; fml::RefPtr<fml::TaskRunner> task_runner_; MessageLoop(); fml::RefPtr<MessageLoopImpl> GetLoopImpl() const; FML_DISALLOW_COPY_AND_ASSIGN(MessageLoop); }; } // namespace fml #endif // FLUTTER_FML_MESSAGE_LOOP_H_
engine/fml/message_loop.h/0
{ "file_path": "engine/fml/message_loop.h", "repo_id": "engine", "token_count": 609 }
309
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_FML_PLATFORM_ANDROID_JNI_UTIL_H_ #define FLUTTER_FML_PLATFORM_ANDROID_JNI_UTIL_H_ #include <jni.h> #include <vector> #include "flutter/fml/macros.h" #include "flutter/fml/platform/android/scoped_java_ref.h" namespace fml { namespace jni { void InitJavaVM(JavaVM* vm); // Returns a JNI environment for the current thread. // Attaches the thread to JNI if needed. JNIEnv* AttachCurrentThread(); void DetachFromVM(); std::string JavaStringToString(JNIEnv* env, jstring string); ScopedJavaLocalRef<jstring> StringToJavaString(JNIEnv* env, const std::string& str); std::vector<std::string> StringArrayToVector(JNIEnv* env, jobjectArray jargs); std::vector<std::string> StringListToVector(JNIEnv* env, jobject list); ScopedJavaLocalRef<jobjectArray> VectorToStringArray( JNIEnv* env, const std::vector<std::string>& vector); ScopedJavaLocalRef<jobjectArray> VectorToBufferArray( JNIEnv* env, const std::vector<std::vector<uint8_t>>& vector); bool HasException(JNIEnv* env); bool ClearException(JNIEnv* env, bool silent = false); bool CheckException(JNIEnv* env); std::string GetJavaExceptionInfo(JNIEnv* env, jthrowable java_throwable); } // namespace jni } // namespace fml #endif // FLUTTER_FML_PLATFORM_ANDROID_JNI_UTIL_H_
engine/fml/platform/android/jni_util.h/0
{ "file_path": "engine/fml/platform/android/jni_util.h", "repo_id": "engine", "token_count": 573 }
310
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_FML_PLATFORM_DARWIN_PLATFORM_VERSION_H_ #define FLUTTER_FML_PLATFORM_DARWIN_PLATFORM_VERSION_H_ #include <sys/types.h> #include "flutter/fml/macros.h" namespace fml { bool IsPlatformVersionAtLeast(size_t major, size_t minor = 0, size_t patch = 0); } // namespace fml #endif // FLUTTER_FML_PLATFORM_DARWIN_PLATFORM_VERSION_H_
engine/fml/platform/darwin/platform_version.h/0
{ "file_path": "engine/fml/platform/darwin/platform_version.h", "repo_id": "engine", "token_count": 192 }
311
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/fml/platform/darwin/weak_nsobject.h" #include "flutter/fml/platform/darwin/scoped_nsautorelease_pool.h" #include "flutter/fml/platform/darwin/scoped_nsobject.h" namespace { // The key needed by objc_setAssociatedObject. char sentinelObserverKey_; } // namespace namespace fml { WeakContainer::WeakContainer(id object, const debug::DebugThreadChecker& checker) : object_(object), checker_(checker) {} WeakContainer::~WeakContainer() {} } // namespace fml @interface CRBWeakNSProtocolSentinel () // Container to notify on dealloc. @property(readonly, assign) fml::RefPtr<fml::WeakContainer> container; // Designed initializer. - (id)initWithContainer:(fml::RefPtr<fml::WeakContainer>)container; @end @implementation CRBWeakNSProtocolSentinel + (fml::RefPtr<fml::WeakContainer>)containerForObject:(id)object threadChecker:(debug::DebugThreadChecker)checker { if (object == nil) { return nullptr; } // The autoreleasePool is needed here as the call to objc_getAssociatedObject // returns an autoreleased object which is better released sooner than later. fml::ScopedNSAutoreleasePool pool; CRBWeakNSProtocolSentinel* sentinel = objc_getAssociatedObject(object, &sentinelObserverKey_); if (!sentinel) { fml::scoped_nsobject<CRBWeakNSProtocolSentinel> newSentinel([[CRBWeakNSProtocolSentinel alloc] initWithContainer:AdoptRef(new fml::WeakContainer(object, checker))]); sentinel = newSentinel; objc_setAssociatedObject(object, &sentinelObserverKey_, sentinel, OBJC_ASSOCIATION_RETAIN); // The retain count is 2. One retain is due to the alloc, the other to the // association with the weak object. FML_DCHECK(2u == [sentinel retainCount]); } return [sentinel container]; } - (id)initWithContainer:(fml::RefPtr<fml::WeakContainer>)container { FML_DCHECK(container.get()); self = [super init]; if (self) { _container = container; } return self; } - (void)dealloc { _container->nullify(); [super dealloc]; } @end
engine/fml/platform/darwin/weak_nsobject.mm/0
{ "file_path": "engine/fml/platform/darwin/weak_nsobject.mm", "repo_id": "engine", "token_count": 759 }
312
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/fml/platform/linux/timerfd.h" #include <sys/types.h> #include <unistd.h> #include <cstring> #include "flutter/fml/eintr_wrapper.h" #include "flutter/fml/logging.h" #if FML_TIMERFD_AVAILABLE == 0 #include <asm/unistd.h> #include <sys/syscall.h> int timerfd_create(int clockid, int flags) { return syscall(__NR_timerfd_create, clockid, flags); } int timerfd_settime(int ufc, int flags, const struct itimerspec* utmr, struct itimerspec* otmr) { return syscall(__NR_timerfd_settime, ufc, flags, utmr, otmr); } #endif // FML_TIMERFD_AVAILABLE == 0 namespace fml { #ifndef NSEC_PER_SEC #define NSEC_PER_SEC 1000000000 #endif bool TimerRearm(int fd, fml::TimePoint time_point) { uint64_t nano_secs = time_point.ToEpochDelta().ToNanoseconds(); // "0" will disarm the timer, desired behavior is to immediately // trigger the timer. if (nano_secs < 1) { nano_secs = 1; } struct itimerspec spec = {}; spec.it_value.tv_sec = static_cast<time_t>(nano_secs / NSEC_PER_SEC); spec.it_value.tv_nsec = nano_secs % NSEC_PER_SEC; spec.it_interval = spec.it_value; // single expiry. int result = ::timerfd_settime(fd, TFD_TIMER_ABSTIME, &spec, nullptr); if (result != 0) { FML_DLOG(ERROR) << "timerfd_settime err:" << strerror(errno); } return result == 0; } bool TimerDrain(int fd) { // 8 bytes must be read from a signaled timer file descriptor when signaled. uint64_t fire_count = 0; ssize_t size = FML_HANDLE_EINTR(::read(fd, &fire_count, sizeof(uint64_t))); if (size != sizeof(uint64_t)) { return false; } return fire_count > 0; } } // namespace fml
engine/fml/platform/linux/timerfd.cc/0
{ "file_path": "engine/fml/platform/linux/timerfd.cc", "repo_id": "engine", "token_count": 769 }
313
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/fml/mapping.h" #include <fcntl.h> #include <io.h> #include <windows.h> #include <type_traits> #include "flutter/fml/file.h" #include "flutter/fml/platform/win/errors_win.h" #include "flutter/fml/platform/win/wstring_conversion.h" namespace fml { Mapping::Mapping() = default; Mapping::~Mapping() = default; static bool IsWritable( std::initializer_list<FileMapping::Protection> protection_flags) { for (auto protection : protection_flags) { if (protection == FileMapping::Protection::kWrite) { return true; } } return false; } static bool IsExecutable( std::initializer_list<FileMapping::Protection> protection_flags) { for (auto protection : protection_flags) { if (protection == FileMapping::Protection::kExecute) { return true; } } return false; } FileMapping::FileMapping(const fml::UniqueFD& fd, std::initializer_list<Protection> protections) : size_(0), mapping_(nullptr) { if (!fd.is_valid()) { return; } const auto mapping_size = ::GetFileSize(fd.get(), nullptr); if (mapping_size == INVALID_FILE_SIZE) { FML_DLOG(ERROR) << "Invalid file size. " << GetLastErrorMessage(); return; } if (mapping_size == 0) { valid_ = true; return; } DWORD protect_flags = 0; bool read_only = !IsWritable(protections); if (IsExecutable(protections)) { protect_flags = PAGE_EXECUTE_READ; } else if (read_only) { protect_flags = PAGE_READONLY; } else { protect_flags = PAGE_READWRITE; } mapping_handle_.reset(::CreateFileMapping(fd.get(), // hFile nullptr, // lpAttributes protect_flags, // flProtect 0, // dwMaximumSizeHigh 0, // dwMaximumSizeLow nullptr // lpName )); if (!mapping_handle_.is_valid()) { return; } const DWORD desired_access = read_only ? FILE_MAP_READ : FILE_MAP_WRITE; auto mapping = reinterpret_cast<uint8_t*>( MapViewOfFile(mapping_handle_.get(), desired_access, 0, 0, mapping_size)); if (mapping == nullptr) { FML_DLOG(ERROR) << "Could not set up file mapping. " << GetLastErrorMessage(); return; } mapping_ = mapping; size_ = mapping_size; valid_ = true; if (IsWritable(protections)) { mutable_mapping_ = mapping_; } } FileMapping::~FileMapping() { if (mapping_ != nullptr) { UnmapViewOfFile(mapping_); } } size_t FileMapping::GetSize() const { return size_; } const uint8_t* FileMapping::GetMapping() const { return mapping_; } bool FileMapping::IsDontNeedSafe() const { return mutable_mapping_ == nullptr; } bool FileMapping::IsValid() const { return valid_; } } // namespace fml
engine/fml/platform/win/mapping_win.cc/0
{ "file_path": "engine/fml/platform/win/mapping_win.cc", "repo_id": "engine", "token_count": 1376 }
314
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_FML_SHARED_THREAD_MERGER_H_ #define FLUTTER_FML_SHARED_THREAD_MERGER_H_ #include <condition_variable> #include <mutex> #include "flutter/fml/macros.h" #include "flutter/fml/memory/ref_counted.h" #include "flutter/fml/message_loop_task_queues.h" namespace fml { class RasterThreadMerger; typedef void* RasterThreadMergerId; /// Instance of this class is shared between multiple |RasterThreadMerger| /// instances, Most of the callings from |RasterThreadMerger| will be redirected /// to this class with one more caller parameter. class SharedThreadMerger : public fml::RefCountedThreadSafe<SharedThreadMerger> { public: SharedThreadMerger(TaskQueueId owner, TaskQueueId subsumed); // It's called by |RasterThreadMerger::MergeWithLease|. // See the doc of |RasterThreadMerger::MergeWithLease|. bool MergeWithLease(RasterThreadMergerId caller, size_t lease_term); // It's called by |RasterThreadMerger::UnMergeNowIfLastOne|. // See the doc of |RasterThreadMerger::UnMergeNowIfLastOne|. bool UnMergeNowIfLastOne(RasterThreadMergerId caller); // It's called by |RasterThreadMerger::ExtendLeaseTo|. // See the doc of |RasterThreadMerger::ExtendLeaseTo|. void ExtendLeaseTo(RasterThreadMergerId caller, size_t lease_term); // It's called by |RasterThreadMerger::IsMergedUnSafe|. // See the doc of |RasterThreadMerger::IsMergedUnSafe|. bool IsMergedUnSafe() const; // It's called by |RasterThreadMerger::IsEnabledUnSafe|. // See the doc of |RasterThreadMerger::IsEnabledUnSafe|. bool IsEnabledUnSafe() const; // It's called by |RasterThreadMerger::Enable| or // |RasterThreadMerger::Disable|. void SetEnabledUnSafe(bool enabled); // It's called by |RasterThreadMerger::DecrementLease|. // See the doc of |RasterThreadMerger::DecrementLease|. bool DecrementLease(RasterThreadMergerId caller); private: fml::TaskQueueId owner_; fml::TaskQueueId subsumed_; fml::MessageLoopTaskQueues* task_queues_; std::mutex mutex_; bool enabled_ = false; /// The |MergeWithLease| or |ExtendLeaseTo| method will record the caller /// into this lease_term_by_caller_ map, |UnMergeNowIfLastOne| /// method will remove the caller from this lease_term_by_caller_. std::map<RasterThreadMergerId, std::atomic_size_t> lease_term_by_caller_; bool IsAllLeaseTermsZeroUnSafe() const; bool UnMergeNowUnSafe(); FML_DISALLOW_COPY_AND_ASSIGN(SharedThreadMerger); }; } // namespace fml #endif // FLUTTER_FML_SHARED_THREAD_MERGER_H_
engine/fml/shared_thread_merger.h/0
{ "file_path": "engine/fml/shared_thread_merger.h", "repo_id": "engine", "token_count": 921 }
315
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_FML_SYNCHRONIZATION_SHARED_MUTEX_STD_H_ #define FLUTTER_FML_SYNCHRONIZATION_SHARED_MUTEX_STD_H_ #include "flutter/fml/synchronization/shared_mutex.h" #include <shared_mutex> namespace fml { class SharedMutexStd : public SharedMutex { public: virtual void Lock(); virtual void LockShared(); virtual void Unlock(); virtual void UnlockShared(); private: friend SharedMutex* SharedMutex::Create(); SharedMutexStd() = default; std::shared_timed_mutex mutex_; }; } // namespace fml #endif // FLUTTER_FML_SYNCHRONIZATION_SHARED_MUTEX_STD_H_
engine/fml/synchronization/shared_mutex_std.h/0
{ "file_path": "engine/fml/synchronization/shared_mutex_std.h", "repo_id": "engine", "token_count": 266 }
316
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/fml/build_config.h" #include "flutter/fml/thread.h" #if defined(FML_OS_MACOSX) || defined(FML_OS_LINUX) || defined(FML_OS_ANDROID) #define FLUTTER_PTHREAD_SUPPORTED 1 #else #define FLUTTER_PTHREAD_SUPPORTED 0 #endif #if FLUTTER_PTHREAD_SUPPORTED #include <pthread.h> #else #endif #if defined(FML_OS_WIN) #include <windows.h> #endif #include <algorithm> #include <memory> #include "gtest/gtest.h" TEST(Thread, CanStartAndEnd) { fml::Thread thread; ASSERT_TRUE(thread.GetTaskRunner()); } TEST(Thread, CanStartAndEndWithExplicitJoin) { fml::Thread thread; ASSERT_TRUE(thread.GetTaskRunner()); thread.Join(); } TEST(Thread, HasARunningMessageLoop) { fml::Thread thread; bool done = false; thread.GetTaskRunner()->PostTask([&done]() { done = true; }); thread.Join(); ASSERT_TRUE(done); } TEST(Thread, HasExpectedStackSize) { size_t stack_size = 0; fml::Thread thread; thread.GetTaskRunner()->PostTask([&stack_size]() { #if defined(FML_OS_WIN) ULONG_PTR low_limit; ULONG_PTR high_limit; GetCurrentThreadStackLimits(&low_limit, &high_limit); stack_size = high_limit - low_limit; #elif defined(FML_OS_MACOSX) stack_size = pthread_get_stacksize_np(pthread_self()); #else pthread_attr_t attr; pthread_getattr_np(pthread_self(), &attr); pthread_attr_getstacksize(&attr, &stack_size); pthread_attr_destroy(&attr); #endif }); thread.Join(); // Actual stack size will be aligned to page size, this assumes no supported // platform has a page size larger than 16k. On Linux reducing the default // stack size (8MB) does not seem to have any effect. const size_t kPageSize = 16384; ASSERT_TRUE(stack_size / kPageSize >= fml::Thread::GetDefaultStackSize() / kPageSize); } #if FLUTTER_PTHREAD_SUPPORTED TEST(Thread, ThreadNameCreatedWithConfig) { const std::string name = "Thread1"; fml::Thread thread(name); bool done = false; thread.GetTaskRunner()->PostTask([&done, &name]() { done = true; char thread_name[16]; pthread_t current_thread = pthread_self(); pthread_getname_np(current_thread, thread_name, 16); ASSERT_EQ(thread_name, name); }); thread.Join(); ASSERT_TRUE(done); } static int clamp_priority(int priority, int policy) { return std::clamp(priority, sched_get_priority_min(policy), sched_get_priority_max(policy)); } static void MockThreadConfigSetter(const fml::Thread::ThreadConfig& config) { // set thread name fml::Thread::SetCurrentThreadName(config); pthread_t tid = pthread_self(); struct sched_param param; int policy = SCHED_OTHER; switch (config.priority) { case fml::Thread::ThreadPriority::kDisplay: param.sched_priority = clamp_priority(10, policy); break; default: param.sched_priority = clamp_priority(1, policy); } pthread_setschedparam(tid, policy, &param); } TEST(Thread, ThreadPriorityCreatedWithConfig) { const std::string thread1_name = "Thread1"; const std::string thread2_name = "Thread2"; fml::Thread thread(MockThreadConfigSetter, fml::Thread::ThreadConfig( thread1_name, fml::Thread::ThreadPriority::kNormal)); bool done = false; struct sched_param param; int policy; thread.GetTaskRunner()->PostTask([&]() { done = true; char thread_name[16]; pthread_t current_thread = pthread_self(); pthread_getname_np(current_thread, thread_name, 16); pthread_getschedparam(current_thread, &policy, &param); ASSERT_EQ(thread_name, thread1_name); ASSERT_EQ(policy, SCHED_OTHER); ASSERT_EQ(param.sched_priority, clamp_priority(1, policy)); }); fml::Thread thread2(MockThreadConfigSetter, fml::Thread::ThreadConfig( thread2_name, fml::Thread::ThreadPriority::kDisplay)); thread2.GetTaskRunner()->PostTask([&]() { done = true; char thread_name[16]; pthread_t current_thread = pthread_self(); pthread_getname_np(current_thread, thread_name, 16); pthread_getschedparam(current_thread, &policy, &param); ASSERT_EQ(thread_name, thread2_name); ASSERT_EQ(policy, SCHED_OTHER); ASSERT_EQ(param.sched_priority, clamp_priority(10, policy)); }); thread.Join(); ASSERT_TRUE(done); } #endif // FLUTTER_PTHREAD_SUPPORTED #if defined(FML_OS_LINUX) TEST(Thread, LinuxLongThreadNameTruncated) { const std::string name = "VeryLongThreadNameTest"; fml::Thread thread(name); thread.GetTaskRunner()->PostTask([&name]() { constexpr size_t kThreadNameLen = 16; char thread_name[kThreadNameLen]; pthread_getname_np(pthread_self(), thread_name, kThreadNameLen); ASSERT_EQ(thread_name, name.substr(0, kThreadNameLen - 1)); }); thread.Join(); } #endif // FML_OS_LINUX
engine/fml/thread_unittests.cc/0
{ "file_path": "engine/fml/thread_unittests.cc", "repo_id": "engine", "token_count": 1915 }
317
# Defines the Chromium style for automatic reformatting. # http://clang.llvm.org/docs/ClangFormatStyleOptions.html BasedOnStyle: Chromium Standard: c++17 EmptyLineBeforeAccessModifier: Always
engine/impeller/.clang-format/0
{ "file_path": "engine/impeller/.clang-format", "repo_id": "engine", "token_count": 57 }
318
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/aiks/canvas.h" #include <optional> #include <utility> #include "flutter/fml/logging.h" #include "flutter/fml/trace_event.h" #include "impeller/aiks/image_filter.h" #include "impeller/aiks/paint_pass_delegate.h" #include "impeller/entity/contents/atlas_contents.h" #include "impeller/entity/contents/clip_contents.h" #include "impeller/entity/contents/color_source_contents.h" #include "impeller/entity/contents/filters/filter_contents.h" #include "impeller/entity/contents/solid_rrect_blur_contents.h" #include "impeller/entity/contents/text_contents.h" #include "impeller/entity/contents/texture_contents.h" #include "impeller/entity/contents/vertices_contents.h" #include "impeller/entity/geometry/geometry.h" #include "impeller/geometry/constants.h" #include "impeller/geometry/path_builder.h" namespace impeller { namespace { static std::shared_ptr<Contents> CreateContentsForGeometryWithFilters( const Paint& paint, std::shared_ptr<Geometry> geometry) { std::shared_ptr<ColorSourceContents> contents = paint.color_source.GetContents(paint); // Attempt to apply the color filter on the CPU first. // Note: This is not just an optimization; some color sources rely on // CPU-applied color filters to behave properly. bool needs_color_filter = paint.HasColorFilter(); if (needs_color_filter) { auto color_filter = paint.GetColorFilter(); if (contents->ApplyColorFilter(color_filter->GetCPUColorFilterProc())) { needs_color_filter = false; } } contents->SetGeometry(std::move(geometry)); if (paint.mask_blur_descriptor.has_value()) { // If there's a mask blur and we need to apply the color filter on the GPU, // we need to be careful to only apply the color filter to the source // colors. CreateMaskBlur is able to handle this case. return paint.mask_blur_descriptor->CreateMaskBlur( contents, needs_color_filter ? paint.GetColorFilter() : nullptr); } std::shared_ptr<Contents> contents_copy = std::move(contents); // Image input types will directly set their color filter, // if any. See `TiledTextureContents.SetColorFilter`. if (needs_color_filter && paint.color_source.GetType() != ColorSource::Type::kImage) { std::shared_ptr<ColorFilter> color_filter = paint.GetColorFilter(); contents_copy = color_filter->WrapWithGPUColorFilter( FilterInput::Make(std::move(contents_copy)), ColorFilterContents::AbsorbOpacity::kYes); } if (paint.image_filter) { std::shared_ptr<FilterContents> filter = paint.image_filter->WrapInput( FilterInput::Make(std::move(contents_copy))); filter->SetRenderingMode(Entity::RenderingMode::kDirect); return filter; } return contents_copy; } static std::shared_ptr<Contents> CreatePathContentsWithFilters( const Paint& paint, const Path& path) { std::shared_ptr<Geometry> geometry; switch (paint.style) { case Paint::Style::kFill: geometry = Geometry::MakeFillPath(path); break; case Paint::Style::kStroke: geometry = Geometry::MakeStrokePath(path, paint.stroke_width, paint.stroke_miter, paint.stroke_cap, paint.stroke_join); break; } return CreateContentsForGeometryWithFilters(paint, std::move(geometry)); } static std::shared_ptr<Contents> CreateCoverContentsWithFilters( const Paint& paint) { return CreateContentsForGeometryWithFilters(paint, Geometry::MakeCover()); } } // namespace Canvas::Canvas() { Initialize(std::nullopt); } Canvas::Canvas(Rect cull_rect) { Initialize(cull_rect); } Canvas::Canvas(IRect cull_rect) { Initialize(Rect::MakeLTRB(cull_rect.GetLeft(), cull_rect.GetTop(), cull_rect.GetRight(), cull_rect.GetBottom())); } Canvas::~Canvas() = default; void Canvas::Initialize(std::optional<Rect> cull_rect) { initial_cull_rect_ = cull_rect; base_pass_ = std::make_unique<EntityPass>(); base_pass_->SetNewClipDepth(++current_depth_); current_pass_ = base_pass_.get(); transform_stack_.emplace_back(CanvasStackEntry{.cull_rect = cull_rect}); FML_DCHECK(GetSaveCount() == 1u); FML_DCHECK(base_pass_->GetSubpassesDepth() == 1u); } void Canvas::Reset() { base_pass_ = nullptr; current_pass_ = nullptr; current_depth_ = 0u; transform_stack_ = {}; } void Canvas::Save() { Save(false); } namespace { class MipCountVisitor : public ImageFilterVisitor { public: virtual void Visit(const BlurImageFilter& filter) { required_mip_count_ = FilterContents::kBlurFilterRequiredMipCount; } virtual void Visit(const LocalMatrixImageFilter& filter) { required_mip_count_ = 1; } virtual void Visit(const DilateImageFilter& filter) { required_mip_count_ = 1; } virtual void Visit(const ErodeImageFilter& filter) { required_mip_count_ = 1; } virtual void Visit(const MatrixImageFilter& filter) { required_mip_count_ = 1; } virtual void Visit(const ComposeImageFilter& filter) { required_mip_count_ = 1; } virtual void Visit(const ColorImageFilter& filter) { required_mip_count_ = 1; } int32_t GetRequiredMipCount() const { return required_mip_count_; } private: int32_t required_mip_count_ = -1; }; } // namespace void Canvas::Save(bool create_subpass, BlendMode blend_mode, const std::shared_ptr<ImageFilter>& backdrop_filter) { auto entry = CanvasStackEntry{}; entry.transform = transform_stack_.back().transform; entry.cull_rect = transform_stack_.back().cull_rect; entry.clip_depth = transform_stack_.back().clip_depth; if (create_subpass) { entry.rendering_mode = Entity::RenderingMode::kSubpass; auto subpass = std::make_unique<EntityPass>(); subpass->SetEnableOffscreenCheckerboard( debug_options.offscreen_texture_checkerboard); if (backdrop_filter) { EntityPass::BackdropFilterProc backdrop_filter_proc = [backdrop_filter = backdrop_filter->Clone()]( const FilterInput::Ref& input, const Matrix& effect_transform, Entity::RenderingMode rendering_mode) { auto filter = backdrop_filter->WrapInput(input); filter->SetEffectTransform(effect_transform); filter->SetRenderingMode(rendering_mode); return filter; }; subpass->SetBackdropFilter(backdrop_filter_proc); MipCountVisitor mip_count_visitor; backdrop_filter->Visit(mip_count_visitor); current_pass_->SetRequiredMipCount( std::max(current_pass_->GetRequiredMipCount(), mip_count_visitor.GetRequiredMipCount())); } subpass->SetBlendMode(blend_mode); current_pass_ = GetCurrentPass().AddSubpass(std::move(subpass)); current_pass_->SetTransform(transform_stack_.back().transform); current_pass_->SetClipDepth(transform_stack_.back().clip_depth); } transform_stack_.emplace_back(entry); } bool Canvas::Restore() { FML_DCHECK(transform_stack_.size() > 0); if (transform_stack_.size() == 1) { return false; } size_t num_clips = transform_stack_.back().num_clips; current_pass_->PopClips(num_clips, current_depth_); if (transform_stack_.back().rendering_mode == Entity::RenderingMode::kSubpass) { current_pass_->SetNewClipDepth(++current_depth_); current_pass_ = GetCurrentPass().GetSuperpass(); FML_DCHECK(current_pass_); } transform_stack_.pop_back(); if (num_clips > 0) { RestoreClip(); } return true; } void Canvas::Concat(const Matrix& transform) { transform_stack_.back().transform = GetCurrentTransform() * transform; } void Canvas::PreConcat(const Matrix& transform) { transform_stack_.back().transform = transform * GetCurrentTransform(); } void Canvas::ResetTransform() { transform_stack_.back().transform = {}; } void Canvas::Transform(const Matrix& transform) { Concat(transform); } const Matrix& Canvas::GetCurrentTransform() const { return transform_stack_.back().transform; } const std::optional<Rect> Canvas::GetCurrentLocalCullingBounds() const { auto cull_rect = transform_stack_.back().cull_rect; if (cull_rect.has_value()) { Matrix inverse = transform_stack_.back().transform.Invert(); cull_rect = cull_rect.value().TransformBounds(inverse); } return cull_rect; } void Canvas::Translate(const Vector3& offset) { Concat(Matrix::MakeTranslation(offset)); } void Canvas::Scale(const Vector2& scale) { Concat(Matrix::MakeScale(scale)); } void Canvas::Scale(const Vector3& scale) { Concat(Matrix::MakeScale(scale)); } void Canvas::Skew(Scalar sx, Scalar sy) { Concat(Matrix::MakeSkew(sx, sy)); } void Canvas::Rotate(Radians radians) { Concat(Matrix::MakeRotationZ(radians)); } size_t Canvas::GetSaveCount() const { return transform_stack_.size(); } void Canvas::RestoreToCount(size_t count) { while (GetSaveCount() > count) { if (!Restore()) { return; } } } void Canvas::DrawPath(const Path& path, const Paint& paint) { Entity entity; entity.SetTransform(GetCurrentTransform()); entity.SetClipDepth(GetClipDepth()); entity.SetBlendMode(paint.blend_mode); entity.SetContents(CreatePathContentsWithFilters(paint, path)); AddEntityToCurrentPass(std::move(entity)); } void Canvas::DrawPaint(const Paint& paint) { Entity entity; entity.SetTransform(GetCurrentTransform()); entity.SetClipDepth(GetClipDepth()); entity.SetBlendMode(paint.blend_mode); entity.SetContents(CreateCoverContentsWithFilters(paint)); AddEntityToCurrentPass(std::move(entity)); } bool Canvas::AttemptDrawBlurredRRect(const Rect& rect, Size corner_radii, const Paint& paint) { if (paint.color_source.GetType() != ColorSource::Type::kColor || paint.style != Paint::Style::kFill) { return false; } if (!paint.mask_blur_descriptor.has_value()) { return false; } // A blur sigma that is not positive enough should not result in a blur. if (paint.mask_blur_descriptor->sigma.sigma <= kEhCloseEnough) { return false; } // For symmetrically mask blurred solid RRects, absorb the mask blur and use // a faster SDF approximation. Color rrect_color = paint.HasColorFilter() // Absorb the color filter, if any. ? paint.GetColorFilter()->GetCPUColorFilterProc()(paint.color) : paint.color; Paint rrect_paint = {.mask_blur_descriptor = paint.mask_blur_descriptor}; // In some cases, we need to render the mask blur to a separate layer. // // 1. If the blur style is normal, we'll be drawing using one draw call and // no clips. And so we can just wrap the RRect contents with the // ImageFilter, which will get applied to the result as per usual. // // 2. If the blur style is solid, we combine the non-blurred RRect with the // blurred RRect via two separate draw calls, and so we need to defer any // fancy blending, translucency, or image filtering until after these two // draws have been combined in a separate layer. // // 3. If the blur style is outer or inner, we apply the blur style via a // clip. The ImageFilter needs to be applied to the mask blurred result. // And so if there's an ImageFilter, we need to defer applying it until // after the clipped RRect blur has been drawn to a separate texture. // However, since there's only one draw call that produces color, we // don't need to worry about the blend mode or translucency (unlike with // BlurStyle::kSolid). // if ((paint.mask_blur_descriptor->style != FilterContents::BlurStyle::kNormal && paint.image_filter) || (paint.mask_blur_descriptor->style == FilterContents::BlurStyle::kSolid && (!rrect_color.IsOpaque() || paint.blend_mode != BlendMode::kSourceOver))) { // Defer the alpha, blend mode, and image filter to a separate layer. SaveLayer({.color = Color::White().WithAlpha(rrect_color.alpha), .blend_mode = paint.blend_mode, .image_filter = paint.image_filter}); rrect_paint.color = rrect_color.WithAlpha(1); } else { rrect_paint.color = rrect_color; rrect_paint.blend_mode = paint.blend_mode; rrect_paint.image_filter = paint.image_filter; Save(); } auto draw_blurred_rrect = [this, &rect, &corner_radii, &rrect_paint]() { auto contents = std::make_shared<SolidRRectBlurContents>(); contents->SetColor(rrect_paint.color); contents->SetSigma(rrect_paint.mask_blur_descriptor->sigma); contents->SetRRect(rect, corner_radii); Entity blurred_rrect_entity; blurred_rrect_entity.SetTransform(GetCurrentTransform()); blurred_rrect_entity.SetClipDepth(GetClipDepth()); blurred_rrect_entity.SetBlendMode(rrect_paint.blend_mode); rrect_paint.mask_blur_descriptor = std::nullopt; blurred_rrect_entity.SetContents( rrect_paint.WithFilters(std::move(contents))); AddEntityToCurrentPass(std::move(blurred_rrect_entity)); }; switch (rrect_paint.mask_blur_descriptor->style) { case FilterContents::BlurStyle::kNormal: { draw_blurred_rrect(); break; } case FilterContents::BlurStyle::kSolid: { // First, draw the blurred RRect. draw_blurred_rrect(); // Then, draw the non-blurred RRect on top. Entity entity; entity.SetTransform(GetCurrentTransform()); entity.SetClipDepth(GetClipDepth()); entity.SetBlendMode(rrect_paint.blend_mode); entity.SetContents(CreateContentsForGeometryWithFilters( rrect_paint, Geometry::MakeRoundRect(rect, corner_radii))); AddEntityToCurrentPass(std::move(entity)); break; } case FilterContents::BlurStyle::kOuter: { ClipRRect(rect, corner_radii, Entity::ClipOperation::kDifference); draw_blurred_rrect(); break; } case FilterContents::BlurStyle::kInner: { ClipRRect(rect, corner_radii, Entity::ClipOperation::kIntersect); draw_blurred_rrect(); break; } } Restore(); return true; } void Canvas::DrawLine(const Point& p0, const Point& p1, const Paint& paint) { Entity entity; entity.SetTransform(GetCurrentTransform()); entity.SetClipDepth(GetClipDepth()); entity.SetBlendMode(paint.blend_mode); entity.SetContents(CreateContentsForGeometryWithFilters( paint, Geometry::MakeLine(p0, p1, paint.stroke_width, paint.stroke_cap))); AddEntityToCurrentPass(std::move(entity)); } void Canvas::DrawRect(const Rect& rect, const Paint& paint) { if (paint.style == Paint::Style::kStroke) { DrawPath(PathBuilder{}.AddRect(rect).TakePath(), paint); return; } if (AttemptDrawBlurredRRect(rect, {}, paint)) { return; } Entity entity; entity.SetTransform(GetCurrentTransform()); entity.SetClipDepth(GetClipDepth()); entity.SetBlendMode(paint.blend_mode); entity.SetContents( CreateContentsForGeometryWithFilters(paint, Geometry::MakeRect(rect))); AddEntityToCurrentPass(std::move(entity)); } void Canvas::DrawOval(const Rect& rect, const Paint& paint) { if (rect.IsSquare()) { // Circles have slightly less overhead and can do stroking DrawCircle(rect.GetCenter(), rect.GetWidth() * 0.5f, paint); return; } if (paint.style == Paint::Style::kStroke) { // No stroked ellipses yet DrawPath(PathBuilder{}.AddOval(rect).TakePath(), paint); return; } if (AttemptDrawBlurredRRect(rect, rect.GetSize() * 0.5f, paint)) { return; } Entity entity; entity.SetTransform(GetCurrentTransform()); entity.SetClipDepth(GetClipDepth()); entity.SetBlendMode(paint.blend_mode); entity.SetContents( CreateContentsForGeometryWithFilters(paint, Geometry::MakeOval(rect))); AddEntityToCurrentPass(std::move(entity)); } void Canvas::DrawRRect(const Rect& rect, const Size& corner_radii, const Paint& paint) { if (AttemptDrawBlurredRRect(rect, corner_radii, paint)) { return; } if (paint.style == Paint::Style::kFill) { Entity entity; entity.SetTransform(GetCurrentTransform()); entity.SetClipDepth(GetClipDepth()); entity.SetBlendMode(paint.blend_mode); entity.SetContents(CreateContentsForGeometryWithFilters( paint, Geometry::MakeRoundRect(rect, corner_radii))); AddEntityToCurrentPass(std::move(entity)); return; } auto path = PathBuilder{} .SetConvexity(Convexity::kConvex) .AddRoundedRect(rect, corner_radii) .SetBounds(rect) .TakePath(); DrawPath(path, paint); } void Canvas::DrawCircle(const Point& center, Scalar radius, const Paint& paint) { Size half_size(radius, radius); if (AttemptDrawBlurredRRect( Rect::MakeOriginSize(center - half_size, half_size * 2), {radius, radius}, paint)) { return; } Entity entity; entity.SetTransform(GetCurrentTransform()); entity.SetClipDepth(GetClipDepth()); entity.SetBlendMode(paint.blend_mode); auto geometry = paint.style == Paint::Style::kStroke ? Geometry::MakeStrokedCircle(center, radius, paint.stroke_width) : Geometry::MakeCircle(center, radius); entity.SetContents( CreateContentsForGeometryWithFilters(paint, std::move(geometry))); AddEntityToCurrentPass(std::move(entity)); } void Canvas::ClipPath(const Path& path, Entity::ClipOperation clip_op) { auto bounds = path.GetBoundingBox(); ClipGeometry(Geometry::MakeFillPath(path), clip_op); if (clip_op == Entity::ClipOperation::kIntersect) { if (bounds.has_value()) { IntersectCulling(bounds.value()); } } } void Canvas::ClipRect(const Rect& rect, Entity::ClipOperation clip_op) { auto geometry = Geometry::MakeRect(rect); auto& cull_rect = transform_stack_.back().cull_rect; if (clip_op == Entity::ClipOperation::kIntersect && // cull_rect.has_value() && // geometry->CoversArea(transform_stack_.back().transform, *cull_rect) // ) { return; // This clip will do nothing, so skip it. } ClipGeometry(geometry, clip_op); switch (clip_op) { case Entity::ClipOperation::kIntersect: IntersectCulling(rect); break; case Entity::ClipOperation::kDifference: SubtractCulling(rect); break; } } void Canvas::ClipOval(const Rect& bounds, Entity::ClipOperation clip_op) { auto geometry = Geometry::MakeOval(bounds); auto& cull_rect = transform_stack_.back().cull_rect; if (clip_op == Entity::ClipOperation::kIntersect && // cull_rect.has_value() && // geometry->CoversArea(transform_stack_.back().transform, *cull_rect) // ) { return; // This clip will do nothing, so skip it. } ClipGeometry(geometry, clip_op); switch (clip_op) { case Entity::ClipOperation::kIntersect: IntersectCulling(bounds); break; case Entity::ClipOperation::kDifference: break; } } void Canvas::ClipRRect(const Rect& rect, const Size& corner_radii, Entity::ClipOperation clip_op) { // Does the rounded rect have a flat part on the top/bottom or left/right? bool flat_on_TB = corner_radii.width * 2 < rect.GetWidth(); bool flat_on_LR = corner_radii.height * 2 < rect.GetHeight(); auto geometry = Geometry::MakeRoundRect(rect, corner_radii); auto& cull_rect = transform_stack_.back().cull_rect; if (clip_op == Entity::ClipOperation::kIntersect && // cull_rect.has_value() && // geometry->CoversArea(transform_stack_.back().transform, *cull_rect) // ) { return; // This clip will do nothing, so skip it. } ClipGeometry(geometry, clip_op); switch (clip_op) { case Entity::ClipOperation::kIntersect: IntersectCulling(rect); break; case Entity::ClipOperation::kDifference: if (corner_radii.IsEmpty()) { SubtractCulling(rect); } else { // We subtract the inner "tall" and "wide" rectangle pieces // that fit inside the corners which cover the greatest area // without involving the curved corners // Since this is a subtract operation, we can subtract each // rectangle piece individually without fear of interference. if (flat_on_TB) { SubtractCulling(rect.Expand(Size{-corner_radii.width, 0.0})); } if (flat_on_LR) { SubtractCulling(rect.Expand(Size{0.0, -corner_radii.height})); } } break; } } void Canvas::ClipGeometry(const std::shared_ptr<Geometry>& geometry, Entity::ClipOperation clip_op) { auto contents = std::make_shared<ClipContents>(); contents->SetGeometry(geometry); contents->SetClipOperation(clip_op); Entity entity; entity.SetTransform(GetCurrentTransform()); entity.SetContents(std::move(contents)); entity.SetClipDepth(GetClipDepth()); GetCurrentPass().PushClip(std::move(entity)); ++transform_stack_.back().clip_depth; ++transform_stack_.back().num_clips; } void Canvas::IntersectCulling(Rect clip_rect) { clip_rect = clip_rect.TransformBounds(GetCurrentTransform()); std::optional<Rect>& cull_rect = transform_stack_.back().cull_rect; if (cull_rect.has_value()) { cull_rect = cull_rect .value() // .Intersection(clip_rect) // .value_or(Rect{}); } else { cull_rect = clip_rect; } } void Canvas::SubtractCulling(Rect clip_rect) { std::optional<Rect>& cull_rect = transform_stack_.back().cull_rect; if (cull_rect.has_value()) { clip_rect = clip_rect.TransformBounds(GetCurrentTransform()); cull_rect = cull_rect .value() // .Cutout(clip_rect) // .value_or(Rect{}); } // else (no cull) diff (any clip) is non-rectangular } void Canvas::RestoreClip() { Entity entity; entity.SetTransform(GetCurrentTransform()); // This path is empty because ClipRestoreContents just generates a quad that // takes up the full render target. entity.SetContents(std::make_shared<ClipRestoreContents>()); entity.SetClipDepth(GetClipDepth()); AddEntityToCurrentPass(std::move(entity)); } void Canvas::DrawPoints(std::vector<Point> points, Scalar radius, const Paint& paint, PointStyle point_style) { if (radius <= 0) { return; } Entity entity; entity.SetTransform(GetCurrentTransform()); entity.SetClipDepth(GetClipDepth()); entity.SetBlendMode(paint.blend_mode); entity.SetContents(CreateContentsForGeometryWithFilters( paint, Geometry::MakePointField(std::move(points), radius, /*round=*/point_style == PointStyle::kRound))); AddEntityToCurrentPass(std::move(entity)); } void Canvas::DrawImage(const std::shared_ptr<Image>& image, Point offset, const Paint& paint, SamplerDescriptor sampler) { if (!image) { return; } const auto source = Rect::MakeSize(image->GetSize()); const auto dest = source.Shift(offset); DrawImageRect(image, source, dest, paint, std::move(sampler)); } void Canvas::DrawImageRect(const std::shared_ptr<Image>& image, Rect source, Rect dest, const Paint& paint, SamplerDescriptor sampler, SourceRectConstraint src_rect_constraint) { if (!image || source.IsEmpty() || dest.IsEmpty()) { return; } auto size = image->GetSize(); if (size.IsEmpty()) { return; } auto texture_contents = TextureContents::MakeRect(dest); texture_contents->SetTexture(image->GetTexture()); texture_contents->SetSourceRect(source); texture_contents->SetStrictSourceRect(src_rect_constraint == SourceRectConstraint::kStrict); texture_contents->SetSamplerDescriptor(std::move(sampler)); texture_contents->SetOpacity(paint.color.alpha); texture_contents->SetDeferApplyingOpacity(paint.HasColorFilter()); std::shared_ptr<Contents> contents = texture_contents; if (paint.mask_blur_descriptor.has_value()) { contents = paint.mask_blur_descriptor->CreateMaskBlur(texture_contents); } Entity entity; entity.SetBlendMode(paint.blend_mode); entity.SetClipDepth(GetClipDepth()); entity.SetContents(paint.WithFilters(contents)); entity.SetTransform(GetCurrentTransform()); AddEntityToCurrentPass(std::move(entity)); } Picture Canvas::EndRecordingAsPicture() { // Assign clip depths to any outstanding clip entities. while (current_pass_ != nullptr) { current_pass_->PopAllClips(current_depth_); current_pass_ = current_pass_->GetSuperpass(); } Picture picture; picture.pass = std::move(base_pass_); Reset(); Initialize(initial_cull_rect_); return picture; } EntityPass& Canvas::GetCurrentPass() { FML_DCHECK(current_pass_ != nullptr); return *current_pass_; } size_t Canvas::GetClipDepth() const { return transform_stack_.back().clip_depth; } void Canvas::AddEntityToCurrentPass(Entity entity) { entity.SetNewClipDepth(++current_depth_); GetCurrentPass().AddEntity(std::move(entity)); } void Canvas::SaveLayer(const Paint& paint, std::optional<Rect> bounds, const std::shared_ptr<ImageFilter>& backdrop_filter, ContentBoundsPromise bounds_promise) { TRACE_EVENT0("flutter", "Canvas::saveLayer"); Save(true, paint.blend_mode, backdrop_filter); // The DisplayList bounds/rtree doesn't account for filters applied to parent // layers, and so sub-DisplayLists are getting culled as if no filters are // applied. // See also: https://github.com/flutter/flutter/issues/139294 if (paint.image_filter) { transform_stack_.back().cull_rect = std::nullopt; } auto& new_layer_pass = GetCurrentPass(); if (bounds) { new_layer_pass.SetBoundsLimit(bounds, bounds_promise); } if (paint.image_filter) { MipCountVisitor mip_count_visitor; paint.image_filter->Visit(mip_count_visitor); new_layer_pass.SetRequiredMipCount(mip_count_visitor.GetRequiredMipCount()); } // Only apply opacity peephole on default blending. if (paint.blend_mode == BlendMode::kSourceOver) { new_layer_pass.SetDelegate( std::make_shared<OpacityPeepholePassDelegate>(paint)); } else { new_layer_pass.SetDelegate(std::make_shared<PaintPassDelegate>(paint)); } } void Canvas::DrawTextFrame(const std::shared_ptr<TextFrame>& text_frame, Point position, const Paint& paint) { Entity entity; entity.SetClipDepth(GetClipDepth()); entity.SetBlendMode(paint.blend_mode); auto text_contents = std::make_shared<TextContents>(); text_contents->SetTextFrame(text_frame); text_contents->SetColor(paint.color); text_contents->SetForceTextColor(paint.mask_blur_descriptor.has_value()); entity.SetTransform(GetCurrentTransform() * Matrix::MakeTranslation(position)); // TODO(bdero): This mask blur application is a hack. It will always wind up // doing a gaussian blur that affects the color source itself // instead of just the mask. The color filter text support // needs to be reworked in order to interact correctly with // mask filters. // https://github.com/flutter/flutter/issues/133297 entity.SetContents( paint.WithFilters(paint.WithMaskBlur(std::move(text_contents), true))); AddEntityToCurrentPass(std::move(entity)); } static bool UseColorSourceContents( const std::shared_ptr<VerticesGeometry>& vertices, const Paint& paint) { // If there are no vertex color or texture coordinates. Or if there // are vertex coordinates then only if the contents are an image or // a solid color. if (vertices->HasVertexColors()) { return false; } if (vertices->HasTextureCoordinates() && (paint.color_source.GetType() == ColorSource::Type::kImage || paint.color_source.GetType() == ColorSource::Type::kColor)) { return true; } return !vertices->HasTextureCoordinates(); } void Canvas::DrawVertices(const std::shared_ptr<VerticesGeometry>& vertices, BlendMode blend_mode, const Paint& paint) { // Override the blend mode with kDestination in order to match the behavior // of Skia's SK_LEGACY_IGNORE_DRAW_VERTICES_BLEND_WITH_NO_SHADER flag, which // is enabled when the Flutter engine builds Skia. if (paint.color_source.GetType() == ColorSource::Type::kColor) { blend_mode = BlendMode::kDestination; } Entity entity; entity.SetTransform(GetCurrentTransform()); entity.SetClipDepth(GetClipDepth()); entity.SetBlendMode(paint.blend_mode); // If there are no vertex color or texture coordinates. Or if there // are vertex coordinates then only if the contents are an image. if (UseColorSourceContents(vertices, paint)) { entity.SetContents(CreateContentsForGeometryWithFilters(paint, vertices)); AddEntityToCurrentPass(std::move(entity)); return; } auto src_paint = paint; src_paint.color = paint.color.WithAlpha(1.0); std::shared_ptr<Contents> src_contents = src_paint.CreateContentsForGeometry(vertices); if (vertices->HasTextureCoordinates()) { // If the color source has an intrinsic size, then we use that to // create the src contents as a simplification. Otherwise we use // the extent of the texture coordinates to determine how large // the src contents should be. If neither has a value we fall back // to using the geometry coverage data. Rect src_coverage; auto size = src_contents->GetColorSourceSize(); if (size.has_value()) { src_coverage = Rect::MakeXYWH(0, 0, size->width, size->height); } else { auto cvg = vertices->GetCoverage(Matrix{}); FML_CHECK(cvg.has_value()); src_coverage = // Covered by FML_CHECK. // NOLINTNEXTLINE(bugprone-unchecked-optional-access) vertices->GetTextureCoordinateCoverge().value_or(cvg.value()); } src_contents = src_paint.CreateContentsForGeometry(Geometry::MakeRect(src_coverage)); } auto contents = std::make_shared<VerticesContents>(); contents->SetAlpha(paint.color.alpha); contents->SetBlendMode(blend_mode); contents->SetGeometry(vertices); contents->SetSourceContents(std::move(src_contents)); entity.SetContents(paint.WithFilters(std::move(contents))); AddEntityToCurrentPass(std::move(entity)); } void Canvas::DrawAtlas(const std::shared_ptr<Image>& atlas, std::vector<Matrix> transforms, std::vector<Rect> texture_coordinates, std::vector<Color> colors, BlendMode blend_mode, SamplerDescriptor sampler, std::optional<Rect> cull_rect, const Paint& paint) { if (!atlas) { return; } std::shared_ptr<AtlasContents> contents = std::make_shared<AtlasContents>(); contents->SetColors(std::move(colors)); contents->SetTransforms(std::move(transforms)); contents->SetTextureCoordinates(std::move(texture_coordinates)); contents->SetTexture(atlas->GetTexture()); contents->SetSamplerDescriptor(std::move(sampler)); contents->SetBlendMode(blend_mode); contents->SetCullRect(cull_rect); contents->SetAlpha(paint.color.alpha); Entity entity; entity.SetTransform(GetCurrentTransform()); entity.SetClipDepth(GetClipDepth()); entity.SetBlendMode(paint.blend_mode); entity.SetContents(paint.WithFilters(contents)); AddEntityToCurrentPass(std::move(entity)); } } // namespace impeller
engine/impeller/aiks/canvas.cc/0
{ "file_path": "engine/impeller/aiks/canvas.cc", "repo_id": "engine", "token_count": 12507 }
319
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_AIKS_PAINT_H_ #define FLUTTER_IMPELLER_AIKS_PAINT_H_ #include <memory> #include "impeller/aiks/color_filter.h" #include "impeller/aiks/color_source.h" #include "impeller/aiks/image_filter.h" #include "impeller/entity/contents/contents.h" #include "impeller/entity/contents/filters/color_filter_contents.h" #include "impeller/entity/contents/filters/filter_contents.h" #include "impeller/entity/contents/texture_contents.h" #include "impeller/entity/entity.h" #include "impeller/entity/geometry/geometry.h" #include "impeller/geometry/color.h" namespace impeller { struct Paint { using ImageFilterProc = std::function<std::shared_ptr<FilterContents>( FilterInput::Ref, const Matrix& effect_transform, Entity::RenderingMode rendering_mode)>; using MaskFilterProc = std::function<std::shared_ptr<FilterContents>( FilterInput::Ref, bool is_solid_color, const Matrix& effect_transform)>; using ColorSourceProc = std::function<std::shared_ptr<ColorSourceContents>()>; enum class Style { kFill, kStroke, }; struct MaskBlurDescriptor { FilterContents::BlurStyle style; Sigma sigma; std::shared_ptr<FilterContents> CreateMaskBlur( std::shared_ptr<ColorSourceContents> color_source_contents, const std::shared_ptr<ColorFilter>& color_filter) const; std::shared_ptr<FilterContents> CreateMaskBlur( std::shared_ptr<TextureContents> texture_contents) const; std::shared_ptr<FilterContents> CreateMaskBlur( const FilterInput::Ref& input, bool is_solid_color) const; }; Color color = Color::Black(); ColorSource color_source; bool dither = false; Scalar stroke_width = 0.0; Cap stroke_cap = Cap::kButt; Join stroke_join = Join::kMiter; Scalar stroke_miter = 4.0; Style style = Style::kFill; BlendMode blend_mode = BlendMode::kSourceOver; bool invert_colors = false; std::shared_ptr<ImageFilter> image_filter; std::shared_ptr<ColorFilter> color_filter; std::optional<MaskBlurDescriptor> mask_blur_descriptor; std::shared_ptr<ColorFilter> GetColorFilter() const; /// @brief Wrap this paint's configured filters to the given contents. /// @param[in] input The contents to wrap with paint's filters. /// @return The filter-wrapped contents. If there are no filters that need /// to be wrapped for the current paint configuration, the /// original contents is returned. std::shared_ptr<Contents> WithFilters(std::shared_ptr<Contents> input) const; /// @brief Wrap this paint's configured filters to the given contents of /// subpass target. /// @param[in] input The contents of subpass target to wrap with paint's /// filters. /// /// @return The filter-wrapped contents. If there are no filters that need /// to be wrapped for the current paint configuration, the /// original contents is returned. std::shared_ptr<Contents> WithFiltersForSubpassTarget( std::shared_ptr<Contents> input, const Matrix& effect_transform = Matrix()) const; std::shared_ptr<Contents> CreateContentsForGeometry( const std::shared_ptr<Geometry>& geometry) const; /// @brief Whether this paint has a color filter that can apply opacity bool HasColorFilter() const; std::shared_ptr<Contents> WithMaskBlur(std::shared_ptr<Contents> input, bool is_solid_color) const; std::shared_ptr<FilterContents> WithImageFilter( const FilterInput::Variant& input, const Matrix& effect_transform, Entity::RenderingMode rendering_mode) const; private: std::shared_ptr<Contents> WithColorFilter( std::shared_ptr<Contents> input, ColorFilterContents::AbsorbOpacity absorb_opacity = ColorFilterContents::AbsorbOpacity::kNo) const; }; } // namespace impeller #endif // FLUTTER_IMPELLER_AIKS_PAINT_H_
engine/impeller/aiks/paint.h/0
{ "file_path": "engine/impeller/aiks/paint.h", "repo_id": "engine", "token_count": 1503 }
320
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_BASE_ALLOCATION_H_ #define FLUTTER_IMPELLER_BASE_ALLOCATION_H_ #include <cstdint> #include <memory> #include "flutter/fml/mapping.h" namespace impeller { class Allocation { public: Allocation(); ~Allocation(); uint8_t* GetBuffer() const; size_t GetLength() const; size_t GetReservedLength() const; [[nodiscard]] bool Truncate(size_t length, bool npot = true); static uint32_t NextPowerOfTwoSize(uint32_t x); private: uint8_t* buffer_ = nullptr; size_t length_ = 0; size_t reserved_ = 0; [[nodiscard]] bool Reserve(size_t reserved); [[nodiscard]] bool ReserveNPOT(size_t reserved); Allocation(const Allocation&) = delete; Allocation& operator=(const Allocation&) = delete; }; std::shared_ptr<fml::Mapping> CreateMappingWithCopy(const uint8_t* contents, size_t length); std::shared_ptr<fml::Mapping> CreateMappingFromAllocation( const std::shared_ptr<Allocation>& allocation); std::shared_ptr<fml::Mapping> CreateMappingWithString( std::shared_ptr<const std::string> string); std::shared_ptr<fml::Mapping> CreateMappingWithString(std::string string); } // namespace impeller #endif // FLUTTER_IMPELLER_BASE_ALLOCATION_H_
engine/impeller/base/allocation.h/0
{ "file_path": "engine/impeller/base/allocation.h", "repo_id": "engine", "token_count": 533 }
321
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/base/validation.h" #include <atomic> #include "flutter/fml/logging.h" namespace impeller { static std::atomic_int32_t sValidationLogsDisabledCount = 0; static std::atomic_int32_t sValidationLogsAreFatal = 0; void ImpellerValidationErrorsSetFatal(bool fatal) { sValidationLogsAreFatal = fatal; } ScopedValidationDisable::ScopedValidationDisable() { sValidationLogsDisabledCount++; } ScopedValidationDisable::~ScopedValidationDisable() { sValidationLogsDisabledCount--; } ScopedValidationFatal::ScopedValidationFatal() { sValidationLogsAreFatal++; } ScopedValidationFatal::~ScopedValidationFatal() { sValidationLogsAreFatal--; } ValidationLog::ValidationLog() = default; ValidationLog::~ValidationLog() { if (sValidationLogsDisabledCount <= 0) { ImpellerValidationBreak(stream_.str().c_str()); } } std::ostream& ValidationLog::GetStream() { return stream_; } void ImpellerValidationBreak(const char* message) { std::stringstream stream; #if FLUTTER_RELEASE stream << "Impeller validation: " << message; #else stream << "Break on '" << __FUNCTION__ << "' to inspect point of failure: " << message; #endif if (sValidationLogsAreFatal > 0) { FML_LOG(FATAL) << stream.str(); } else { FML_LOG(ERROR) << stream.str(); } } bool ImpellerValidationErrorsAreFatal() { return sValidationLogsAreFatal; } } // namespace impeller
engine/impeller/base/validation.cc/0
{ "file_path": "engine/impeller/base/validation.cc", "repo_id": "engine", "token_count": 554 }
322
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <filesystem> #include <system_error> #include "flutter/fml/backtrace.h" #include "flutter/fml/command_line.h" #include "flutter/fml/file.h" #include "flutter/fml/mapping.h" #include "impeller/compiler/compiler.h" #include "impeller/compiler/runtime_stage_data.h" #include "impeller/compiler/shader_bundle.h" #include "impeller/compiler/source_options.h" #include "impeller/compiler/switches.h" #include "impeller/compiler/types.h" #include "impeller/compiler/utilities.h" namespace impeller { namespace compiler { static Reflector::Options CreateReflectorOptions(const SourceOptions& options, const Switches& switches) { Reflector::Options reflector_options; reflector_options.target_platform = options.target_platform; reflector_options.entry_point_name = options.entry_point_name; reflector_options.shader_name = InferShaderNameFromPath(switches.source_file_name); reflector_options.header_file_name = Utf8FromPath( std::filesystem::path{switches.reflection_header_name}.filename()); return reflector_options; } /// Run the shader compiler to geneate SkSL reflection data. /// If there is an error, prints error text and returns `nullptr`. static std::shared_ptr<RuntimeStageData::Shader> CompileSkSL( std::shared_ptr<fml::Mapping> source_file_mapping, const Switches& switches) { auto options = switches.CreateSourceOptions(TargetPlatform::kSkSL); Reflector::Options sksl_reflector_options = CreateReflectorOptions(options, switches); sksl_reflector_options.target_platform = TargetPlatform::kSkSL; Compiler sksl_compiler = Compiler(std::move(source_file_mapping), options, sksl_reflector_options); if (!sksl_compiler.IsValid()) { std::cerr << "Compilation to SkSL failed." << std::endl; std::cerr << sksl_compiler.GetErrorMessages() << std::endl; return nullptr; } return sksl_compiler.GetReflector()->GetRuntimeStageShaderData(); } static bool OutputIPLR( const Switches& switches, const std::shared_ptr<fml::Mapping>& source_file_mapping) { FML_DCHECK(switches.iplr); RuntimeStageData stages; std::shared_ptr<RuntimeStageData::Shader> sksl_shader; if (TargetPlatformBundlesSkSL(switches.SelectDefaultTargetPlatform())) { sksl_shader = CompileSkSL(source_file_mapping, switches); if (!sksl_shader) { return false; } stages.AddShader(sksl_shader); } for (const auto& platform : switches.PlatformsToCompile()) { if (platform == TargetPlatform::kSkSL) { // Already handled above. continue; } SourceOptions options = switches.CreateSourceOptions(platform); // Invoke the compiler and generate reflection data for a single shader. Reflector::Options reflector_options = CreateReflectorOptions(options, switches); Compiler compiler(source_file_mapping, options, reflector_options); if (!compiler.IsValid()) { std::cerr << "Compilation failed." << std::endl; std::cerr << compiler.GetErrorMessages() << std::endl; return false; } auto reflector = compiler.GetReflector(); if (reflector == nullptr) { std::cerr << "Could not create reflector." << std::endl; return false; } auto stage_data = reflector->GetRuntimeStageShaderData(); if (!stage_data) { std::cerr << "Runtime stage information was nil." << std::endl; return false; } stages.AddShader(stage_data); } auto stage_data_mapping = switches.json_format ? stages.CreateJsonMapping() : stages.CreateMapping(); if (!stage_data_mapping) { std::cerr << "Runtime stage data could not be created." << std::endl; return false; } if (!fml::WriteAtomically(*switches.working_directory, // Utf8FromPath(switches.sl_file_name).c_str(), // *stage_data_mapping // )) { std::cerr << "Could not write file to " << switches.sl_file_name << std::endl; return false; } // Tools that consume the runtime stage data expect the access mode to // be 0644. if (!SetPermissiveAccess(switches.sl_file_name)) { return false; } return true; } static bool OutputSLFile(const Compiler& compiler, const Switches& switches) { // -------------------------------------------------------------------------- /// 2. Output the source file. When in IPLR/RuntimeStage mode, output the /// serialized IPLR flatbuffer. /// auto sl_file_name = std::filesystem::absolute( std::filesystem::current_path() / switches.sl_file_name); if (!fml::WriteAtomically(*switches.working_directory, Utf8FromPath(sl_file_name).c_str(), *compiler.GetSLShaderSource())) { std::cerr << "Could not write file to " << switches.sl_file_name << std::endl; return false; } return true; } static bool OutputReflectionData(const Compiler& compiler, const Switches& switches, const SourceOptions& options) { // -------------------------------------------------------------------------- /// 3. Output shader reflection data. /// May include a JSON file, a C++ header, and/or a C++ TU. /// if (TargetPlatformNeedsReflection(options.target_platform)) { if (!switches.reflection_json_name.empty()) { auto reflection_json_name = std::filesystem::absolute( std::filesystem::current_path() / switches.reflection_json_name); if (!fml::WriteAtomically( *switches.working_directory, Utf8FromPath(reflection_json_name).c_str(), *compiler.GetReflector()->GetReflectionJSON())) { std::cerr << "Could not write reflection json to " << switches.reflection_json_name << std::endl; return false; } } if (!switches.reflection_header_name.empty()) { auto reflection_header_name = std::filesystem::absolute(std::filesystem::current_path() / switches.reflection_header_name.c_str()); if (!fml::WriteAtomically( *switches.working_directory, Utf8FromPath(reflection_header_name).c_str(), *compiler.GetReflector()->GetReflectionHeader())) { std::cerr << "Could not write reflection header to " << switches.reflection_header_name << std::endl; return false; } } if (!switches.reflection_cc_name.empty()) { auto reflection_cc_name = std::filesystem::absolute(std::filesystem::current_path() / switches.reflection_cc_name.c_str()); if (!fml::WriteAtomically(*switches.working_directory, Utf8FromPath(reflection_cc_name).c_str(), *compiler.GetReflector()->GetReflectionCC())) { std::cerr << "Could not write reflection CC to " << switches.reflection_cc_name << std::endl; return false; } } } return true; } static bool OutputDepfile(const Compiler& compiler, const Switches& switches) { // -------------------------------------------------------------------------- /// 4. Output a depfile. /// if (!switches.depfile_path.empty()) { std::string result_file; switch (switches.SelectDefaultTargetPlatform()) { case TargetPlatform::kMetalDesktop: case TargetPlatform::kMetalIOS: case TargetPlatform::kOpenGLES: case TargetPlatform::kOpenGLDesktop: case TargetPlatform::kRuntimeStageMetal: case TargetPlatform::kRuntimeStageGLES: case TargetPlatform::kRuntimeStageVulkan: case TargetPlatform::kSkSL: case TargetPlatform::kVulkan: result_file = switches.sl_file_name; break; case TargetPlatform::kUnknown: result_file = switches.spirv_file_name; break; } auto depfile_path = std::filesystem::absolute( std::filesystem::current_path() / switches.depfile_path.c_str()); if (!fml::WriteAtomically(*switches.working_directory, Utf8FromPath(depfile_path).c_str(), *compiler.CreateDepfileContents({result_file}))) { std::cerr << "Could not write depfile to " << switches.depfile_path << std::endl; return false; } } return true; } bool Main(const fml::CommandLine& command_line) { fml::InstallCrashHandler(); if (command_line.HasOption("help")) { Switches::PrintHelp(std::cout); return true; } Switches switches(command_line); if (!switches.AreValid(std::cerr)) { std::cerr << "Invalid flags specified." << std::endl; Switches::PrintHelp(std::cerr); return false; } if (!switches.shader_bundle.empty()) { // Invoke the compiler multiple times to build a shader bundle with the // given shader_bundle spec. return GenerateShaderBundle(switches); } std::shared_ptr<fml::FileMapping> source_file_mapping = fml::FileMapping::CreateReadOnly(switches.source_file_name); if (!source_file_mapping) { std::cerr << "Could not open input file." << std::endl; return false; } if (switches.iplr && !OutputIPLR(switches, source_file_mapping)) { return false; } // Create at least one compiler to output the SL file, reflection data, and a // depfile. // TODO(dnfield): This seems off. We should more explicitly handle how we // generate reflection and depfile data for the runtime stage case. // https://github.com/flutter/flutter/issues/140841 SourceOptions options = switches.CreateSourceOptions(); // Invoke the compiler and generate reflection data for a single shader. Reflector::Options reflector_options = CreateReflectorOptions(options, switches); Compiler compiler(source_file_mapping, options, reflector_options); if (!compiler.IsValid()) { std::cerr << "Compilation failed." << std::endl; std::cerr << compiler.GetErrorMessages() << std::endl; return false; } auto spriv_file_name = std::filesystem::absolute( std::filesystem::current_path() / switches.spirv_file_name); if (!fml::WriteAtomically(*switches.working_directory, Utf8FromPath(spriv_file_name).c_str(), *compiler.GetSPIRVAssembly())) { std::cerr << "Could not write file to " << switches.spirv_file_name << std::endl; return false; } if (!switches.iplr && !OutputSLFile(compiler, switches)) { return false; } if (!OutputReflectionData(compiler, switches, options)) { return false; } if (!OutputDepfile(compiler, switches)) { return false; } return true; } } // namespace compiler } // namespace impeller int main(int argc, char const* argv[]) { return impeller::compiler::Main( fml::CommandLineFromPlatformOrArgcArgv(argc, argv)) ? EXIT_SUCCESS : EXIT_FAILURE; }
engine/impeller/compiler/impellerc_main.cc/0
{ "file_path": "engine/impeller/compiler/impellerc_main.cc", "repo_id": "engine", "token_count": 4457 }
323
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef RUNTIME_EFFECT_GLSL_ #define RUNTIME_EFFECT_GLSL_ #if defined(IMPELLER_GRAPHICS_BACKEND) // Note: The GLES backend uses name matching for attribute locations. This name // must match the name of the attribute output in: // impeller/entity/shaders/runtime_effect.vert in vec2 _fragCoord; vec2 FlutterFragCoord() { return _fragCoord; } #elif defined(SKIA_GRAPHICS_BACKEND) vec2 FlutterFragCoord() { return gl_FragCoord.xy; } #else #error "Runtime effect builtins are not supported for this graphics backend." #endif #endif
engine/impeller/compiler/shader_lib/flutter/runtime_effect.glsl/0
{ "file_path": "engine/impeller/compiler/shader_lib/flutter/runtime_effect.glsl", "repo_id": "engine", "token_count": 232 }
324
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef TYPES_GLSL_ #define TYPES_GLSL_ #extension GL_AMD_gpu_shader_half_float : enable #extension GL_AMD_gpu_shader_half_float_fetch : enable #extension GL_EXT_shader_explicit_arithmetic_types_float16 : enable #ifdef IMPELLER_TARGET_OPENGLES #define IMPELLER_MAYBE_FLAT #else #define IMPELLER_MAYBE_FLAT flat #endif #ifndef IMPELLER_TARGET_METAL_IOS precision mediump sampler2D; #define float16_t float #define f16vec2 vec2 #define f16vec3 vec3 #define f16vec4 vec4 #define f16mat4 mat4 #define f16sampler2D sampler2D #endif // IMPELLER_TARGET_METAL #define BoolF float #define BoolV2 vec2 #define BoolV3 vec3 #define BoolV4 vec4 #endif
engine/impeller/compiler/shader_lib/impeller/types.glsl/0
{ "file_path": "engine/impeller/compiler/shader_lib/impeller/types.glsl", "repo_id": "engine", "token_count": 319 }
325
# Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import("//flutter/impeller/tools/impeller.gni") impeller_component("core") { sources = [ "allocator.cc", "allocator.h", "buffer_view.cc", "buffer_view.h", "capture.cc", "capture.h", "device_buffer.cc", "device_buffer.h", "device_buffer_descriptor.cc", "device_buffer_descriptor.h", "formats.cc", "formats.h", "host_buffer.cc", "host_buffer.h", "platform.cc", "platform.h", "range.cc", "range.h", "resource_binder.cc", "resource_binder.h", "runtime_types.cc", "runtime_types.h", "sampler.cc", "sampler.h", "sampler_descriptor.cc", "sampler_descriptor.h", "shader_types.cc", "shader_types.h", "texture.cc", "texture.h", "texture_descriptor.cc", "texture_descriptor.h", "vertex_buffer.cc", "vertex_buffer.h", ] deps = [ "../base", "../geometry", "//flutter/fml", ] } impeller_component("allocator_unittests") { testonly = true sources = [ "allocator_unittests.cc" ] deps = [ ":core", "../geometry", "//flutter/testing:testing_lib", ] }
engine/impeller/core/BUILD.gn/0
{ "file_path": "engine/impeller/core/BUILD.gn", "repo_id": "engine", "token_count": 579 }
326
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/core/texture_descriptor.h" #include <sstream> namespace impeller { std::string TextureDescriptorToString(const TextureDescriptor& desc) { std::stringstream stream; stream << "StorageMode=" << StorageModeToString(desc.storage_mode) << ","; stream << "Type=" << TextureTypeToString(desc.type) << ","; stream << "Format=" << PixelFormatToString(desc.format) << ","; stream << "Size=" << desc.size << ","; stream << "MipCount=" << desc.mip_count << ","; stream << "SampleCount=" << static_cast<size_t>(desc.sample_count) << ","; stream << "Compression=" << CompressionTypeToString(desc.compression_type); return stream.str(); } } // namespace impeller
engine/impeller/core/texture_descriptor.cc/0
{ "file_path": "engine/impeller/core/texture_descriptor.cc", "repo_id": "engine", "token_count": 271 }
327
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/display_list/skia_conversions.h" #include "display_list/dl_color.h" #include "third_party/skia/modules/skparagraph/include/Paragraph.h" namespace impeller { namespace skia_conversions { Rect ToRect(const SkRect& rect) { return Rect::MakeLTRB(rect.fLeft, rect.fTop, rect.fRight, rect.fBottom); } std::optional<Rect> ToRect(const SkRect* rect) { if (rect == nullptr) { return std::nullopt; } return Rect::MakeLTRB(rect->fLeft, rect->fTop, rect->fRight, rect->fBottom); } std::vector<Rect> ToRects(const SkRect tex[], int count) { auto result = std::vector<Rect>(); for (int i = 0; i < count; i++) { result.push_back(ToRect(tex[i])); } return result; } std::vector<Point> ToPoints(const SkPoint points[], int count) { std::vector<Point> result(count); for (auto i = 0; i < count; i++) { result[i] = ToPoint(points[i]); } return result; } PathBuilder::RoundingRadii ToRoundingRadii(const SkRRect& rrect) { using Corner = SkRRect::Corner; PathBuilder::RoundingRadii radii; radii.bottom_left = ToPoint(rrect.radii(Corner::kLowerLeft_Corner)); radii.bottom_right = ToPoint(rrect.radii(Corner::kLowerRight_Corner)); radii.top_left = ToPoint(rrect.radii(Corner::kUpperLeft_Corner)); radii.top_right = ToPoint(rrect.radii(Corner::kUpperRight_Corner)); return radii; } Path ToPath(const SkPath& path, Point shift) { auto iterator = SkPath::Iter(path, false); struct PathData { union { SkPoint points[4]; }; }; PathBuilder builder; PathData data; // Reserve a path size with some arbitrarily additional padding. builder.Reserve(path.countPoints() + 8, path.countVerbs() + 8); auto verb = SkPath::Verb::kDone_Verb; do { verb = iterator.next(data.points); switch (verb) { case SkPath::kMove_Verb: builder.MoveTo(ToPoint(data.points[0])); break; case SkPath::kLine_Verb: builder.LineTo(ToPoint(data.points[1])); break; case SkPath::kQuad_Verb: builder.QuadraticCurveTo(ToPoint(data.points[1]), ToPoint(data.points[2])); break; case SkPath::kConic_Verb: { constexpr auto kPow2 = 1; // Only works for sweeps up to 90 degrees. constexpr auto kQuadCount = 1 + (2 * (1 << kPow2)); SkPoint points[kQuadCount]; const auto curve_count = SkPath::ConvertConicToQuads(data.points[0], // data.points[1], // data.points[2], // iterator.conicWeight(), // points, // kPow2 // ); for (int curve_index = 0, point_index = 0; // curve_index < curve_count; // curve_index++, point_index += 2 // ) { builder.QuadraticCurveTo(ToPoint(points[point_index + 1]), ToPoint(points[point_index + 2])); } } break; case SkPath::kCubic_Verb: builder.CubicCurveTo(ToPoint(data.points[1]), ToPoint(data.points[2]), ToPoint(data.points[3])); break; case SkPath::kClose_Verb: builder.Close(); break; case SkPath::kDone_Verb: break; } } while (verb != SkPath::Verb::kDone_Verb); FillType fill_type; switch (path.getFillType()) { case SkPathFillType::kWinding: fill_type = FillType::kNonZero; break; case SkPathFillType::kEvenOdd: fill_type = FillType::kOdd; break; case SkPathFillType::kInverseWinding: case SkPathFillType::kInverseEvenOdd: // Flutter doesn't expose these path fill types. These are only visible // via the receiver interface. We should never get here. fill_type = FillType::kNonZero; break; } builder.SetConvexity(path.isConvex() ? Convexity::kConvex : Convexity::kUnknown); builder.Shift(shift); auto sk_bounds = path.getBounds().makeOutset(shift.x, shift.y); builder.SetBounds(ToRect(sk_bounds)); return builder.TakePath(fill_type); } Path ToPath(const SkRRect& rrect) { return PathBuilder{} .AddRoundedRect(ToRect(rrect.getBounds()), ToRoundingRadii(rrect)) .SetConvexity(Convexity::kConvex) .SetBounds(ToRect(rrect.getBounds())) .TakePath(); } Point ToPoint(const SkPoint& point) { return Point::MakeXY(point.fX, point.fY); } Size ToSize(const SkPoint& point) { return Size(point.fX, point.fY); } Color ToColor(const flutter::DlColor& color) { return { static_cast<Scalar>(color.getRedF()), // static_cast<Scalar>(color.getGreenF()), // static_cast<Scalar>(color.getBlueF()), // static_cast<Scalar>(color.getAlphaF()) // }; } std::vector<Matrix> ToRSXForms(const SkRSXform xform[], int count) { auto result = std::vector<Matrix>(); for (int i = 0; i < count; i++) { auto form = xform[i]; // clang-format off auto matrix = Matrix{ form.fSCos, form.fSSin, 0, 0, -form.fSSin, form.fSCos, 0, 0, 0, 0, 1, 0, form.fTx, form.fTy, 0, 1 }; // clang-format on result.push_back(matrix); } return result; } Path PathDataFromTextBlob(const sk_sp<SkTextBlob>& blob, Point shift) { if (!blob) { return {}; } return ToPath(skia::textlayout::Paragraph::GetPath(blob.get()), shift); } std::optional<impeller::PixelFormat> ToPixelFormat(SkColorType type) { switch (type) { case kRGBA_8888_SkColorType: return impeller::PixelFormat::kR8G8B8A8UNormInt; case kBGRA_8888_SkColorType: return impeller::PixelFormat::kB8G8R8A8UNormInt; case kRGBA_F16_SkColorType: return impeller::PixelFormat::kR16G16B16A16Float; case kBGR_101010x_XR_SkColorType: return impeller::PixelFormat::kB10G10R10XR; default: return std::nullopt; } return std::nullopt; } void ConvertStops(const flutter::DlGradientColorSourceBase* gradient, std::vector<Color>& colors, std::vector<float>& stops) { FML_DCHECK(gradient->stop_count() >= 2); auto* dl_colors = gradient->colors(); auto* dl_stops = gradient->stops(); if (dl_stops[0] != 0.0) { colors.emplace_back(skia_conversions::ToColor(dl_colors[0])); stops.emplace_back(0); } for (auto i = 0; i < gradient->stop_count(); i++) { colors.emplace_back(skia_conversions::ToColor(dl_colors[i])); stops.emplace_back(std::clamp(dl_stops[i], 0.0f, 1.0f)); } if (dl_stops[gradient->stop_count() - 1] != 1.0) { colors.emplace_back(colors.back()); stops.emplace_back(1.0); } for (auto i = 1; i < gradient->stop_count(); i++) { stops[i] = std::clamp(stops[i], stops[i - 1], stops[i]); } } } // namespace skia_conversions } // namespace impeller
engine/impeller/display_list/skia_conversions.cc/0
{ "file_path": "engine/impeller/display_list/skia_conversions.cc", "repo_id": "engine", "token_count": 3282 }
328
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/entity/contents/anonymous_contents.h" #include <memory> namespace impeller { std::shared_ptr<Contents> AnonymousContents::Make(RenderProc render_proc, CoverageProc coverage_proc) { return std::shared_ptr<Contents>( new AnonymousContents(std::move(render_proc), std::move(coverage_proc))); } AnonymousContents::AnonymousContents(RenderProc render_proc, CoverageProc coverage_proc) : render_proc_(std::move(render_proc)), coverage_proc_(std::move(coverage_proc)) {} AnonymousContents::~AnonymousContents() = default; bool AnonymousContents::Render(const ContentContext& renderer, const Entity& entity, RenderPass& pass) const { return render_proc_(renderer, entity, pass); } std::optional<Rect> AnonymousContents::GetCoverage(const Entity& entity) const { return coverage_proc_(entity); } } // namespace impeller
engine/impeller/entity/contents/anonymous_contents.cc/0
{ "file_path": "engine/impeller/entity/contents/anonymous_contents.cc", "repo_id": "engine", "token_count": 452 }
329
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/entity/contents/contents.h" #include <optional> #include "fml/logging.h" #include "impeller/base/strings.h" #include "impeller/base/validation.h" #include "impeller/core/formats.h" #include "impeller/entity/contents/anonymous_contents.h" #include "impeller/entity/contents/content_context.h" #include "impeller/entity/contents/texture_contents.h" #include "impeller/renderer/command_buffer.h" #include "impeller/renderer/render_pass.h" namespace impeller { ContentContextOptions OptionsFromPass(const RenderPass& pass) { ContentContextOptions opts; opts.sample_count = pass.GetSampleCount(); opts.color_attachment_pixel_format = pass.GetRenderTargetPixelFormat(); bool has_depth_stencil_attachments = pass.HasDepthAttachment() && pass.HasStencilAttachment(); FML_DCHECK(pass.HasDepthAttachment() == pass.HasStencilAttachment()); opts.has_depth_stencil_attachments = has_depth_stencil_attachments; if constexpr (ContentContext::kEnableStencilThenCover) { opts.depth_compare = CompareFunction::kGreater; opts.stencil_mode = ContentContextOptions::StencilMode::kIgnore; } return opts; } ContentContextOptions OptionsFromPassAndEntity(const RenderPass& pass, const Entity& entity) { ContentContextOptions opts = OptionsFromPass(pass); opts.blend_mode = entity.GetBlendMode(); return opts; } std::shared_ptr<Contents> Contents::MakeAnonymous( Contents::RenderProc render_proc, Contents::CoverageProc coverage_proc) { return AnonymousContents::Make(std::move(render_proc), std::move(coverage_proc)); } Contents::Contents() = default; Contents::~Contents() = default; bool Contents::IsOpaque() const { return false; } Contents::ClipCoverage Contents::GetClipCoverage( const Entity& entity, const std::optional<Rect>& current_clip_coverage) const { return {.type = ClipCoverage::Type::kNoChange, .coverage = current_clip_coverage}; } std::optional<Snapshot> Contents::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 { auto coverage = GetCoverage(entity); if (!coverage.has_value()) { return std::nullopt; } // Pad Contents snapshots with 1 pixel borders to ensure correct sampling // behavior. Not doing so results in a coverage leak for filters that support // customizing the input sampling mode. Snapshots of contents should be // theoretically treated as infinite size just like layers. coverage = coverage->Expand(1); if (coverage_limit.has_value()) { coverage = coverage->Intersection(*coverage_limit); if (!coverage.has_value()) { return std::nullopt; } } ISize subpass_size = ISize::Ceil(coverage->GetSize()); fml::StatusOr<RenderTarget> render_target = renderer.MakeSubpass( label, subpass_size, [&contents = *this, &entity, &coverage](const ContentContext& renderer, RenderPass& pass) -> bool { Entity sub_entity; sub_entity.SetBlendMode(BlendMode::kSourceOver); sub_entity.SetTransform( Matrix::MakeTranslation(Vector3(-coverage->GetOrigin())) * entity.GetTransform()); return contents.Render(renderer, sub_entity, pass); }, msaa_enabled, /*depth_stencil_enabled=*/true, std::min(mip_count, static_cast<int32_t>(subpass_size.MipCount()))); if (!render_target.ok()) { return std::nullopt; } auto snapshot = Snapshot{ .texture = render_target.value().GetRenderTargetTexture(), .transform = Matrix::MakeTranslation(coverage->GetOrigin()), }; if (sampler_descriptor.has_value()) { snapshot.sampler_descriptor = sampler_descriptor.value(); } return snapshot; } bool Contents::CanInheritOpacity(const Entity& entity) const { return false; } void Contents::SetInheritedOpacity(Scalar opacity) { VALIDATION_LOG << "Contents::SetInheritedOpacity should never be called when " "Contents::CanAcceptOpacity returns false."; } std::optional<Color> Contents::AsBackgroundColor(const Entity& entity, ISize target_size) const { return {}; } const FilterContents* Contents::AsFilter() const { return nullptr; } bool Contents::ApplyColorFilter( const Contents::ColorFilterProc& color_filter_proc) { return false; } bool Contents::ShouldRender(const Entity& entity, const std::optional<Rect> clip_coverage) const { if (!clip_coverage.has_value()) { return false; } auto coverage = GetCoverage(entity); if (!coverage.has_value()) { return false; } if (coverage == Rect::MakeMaximum()) { return true; } return clip_coverage->IntersectsWithRect(coverage.value()); } void Contents::SetCoverageHint(std::optional<Rect> coverage_hint) { coverage_hint_ = coverage_hint; } const std::optional<Rect>& Contents::GetCoverageHint() const { return coverage_hint_; } std::optional<Size> Contents::GetColorSourceSize() const { return color_source_size_; }; void Contents::SetColorSourceSize(Size size) { color_source_size_ = size; } } // namespace impeller
engine/impeller/entity/contents/contents.cc/0
{ "file_path": "engine/impeller/entity/contents/contents.cc", "repo_id": "engine", "token_count": 2031 }
330
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_CONTENTS_FILTER_INPUT_H_ #define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_CONTENTS_FILTER_INPUT_H_ #include "impeller/entity/contents/filters/inputs/filter_input.h" namespace impeller { class ContentsFilterInput final : public FilterInput { public: ~ContentsFilterInput() override; // |FilterInput| Variant GetInput() const override; // |FilterInput| std::optional<Snapshot> GetSnapshot(const std::string& label, const ContentContext& renderer, const Entity& entity, std::optional<Rect> coverage_limit, int32_t mip_count) const override; // |FilterInput| std::optional<Rect> GetCoverage(const Entity& entity) const override; // |FilterInput| void PopulateGlyphAtlas( const std::shared_ptr<LazyGlyphAtlas>& lazy_glyph_atlas, Scalar scale) override; private: ContentsFilterInput(std::shared_ptr<Contents> contents, bool msaa_enabled); std::shared_ptr<Contents> contents_; mutable std::optional<Snapshot> snapshot_; bool msaa_enabled_; friend FilterInput; }; } // namespace impeller #endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_CONTENTS_FILTER_INPUT_H_
engine/impeller/entity/contents/filters/inputs/contents_filter_input.h/0
{ "file_path": "engine/impeller/entity/contents/filters/inputs/contents_filter_input.h", "repo_id": "engine", "token_count": 608 }
331
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/entity/contents/filters/morphology_filter_contents.h" #include <cmath> #include "impeller/core/formats.h" #include "impeller/entity/contents/content_context.h" #include "impeller/entity/contents/contents.h" #include "impeller/renderer/render_pass.h" #include "impeller/renderer/vertex_buffer_builder.h" namespace impeller { DirectionalMorphologyFilterContents::DirectionalMorphologyFilterContents() = default; DirectionalMorphologyFilterContents::~DirectionalMorphologyFilterContents() = default; void DirectionalMorphologyFilterContents::SetRadius(Radius radius) { radius_ = radius; } void DirectionalMorphologyFilterContents::SetDirection(Vector2 direction) { direction_ = direction.Normalize(); if (direction_.IsZero()) { direction_ = Vector2(0, 1); } } void DirectionalMorphologyFilterContents::SetMorphType(MorphType morph_type) { morph_type_ = morph_type; } std::optional<Entity> DirectionalMorphologyFilterContents::RenderFilter( const FilterInput::Vector& inputs, const ContentContext& renderer, const Entity& entity, const Matrix& effect_transform, const Rect& coverage, const std::optional<Rect>& coverage_hint) const { using VS = MorphologyFilterPipeline::VertexShader; using FS = MorphologyFilterPipeline::FragmentShader; //---------------------------------------------------------------------------- /// Handle inputs. /// if (inputs.empty()) { return std::nullopt; } auto input_snapshot = inputs[0]->GetSnapshot("Morphology", renderer, entity); if (!input_snapshot.has_value()) { return std::nullopt; } if (radius_.radius < kEhCloseEnough) { return Entity::FromSnapshot(input_snapshot.value(), entity.GetBlendMode(), entity.GetClipDepth()); } auto maybe_input_uvs = input_snapshot->GetCoverageUVs(coverage); if (!maybe_input_uvs.has_value()) { return std::nullopt; } auto input_uvs = maybe_input_uvs.value(); //---------------------------------------------------------------------------- /// Render to texture. /// ContentContext::SubpassCallback callback = [&](const ContentContext& renderer, RenderPass& pass) { auto& host_buffer = renderer.GetTransientsBuffer(); VertexBufferBuilder<VS::PerVertexData> vtx_builder; vtx_builder.AddVertices({ {Point(0, 0), input_uvs[0]}, {Point(1, 0), input_uvs[1]}, {Point(0, 1), input_uvs[2]}, {Point(1, 1), input_uvs[3]}, }); VS::FrameInfo frame_info; frame_info.mvp = Matrix::MakeOrthographic(ISize(1, 1)); frame_info.texture_sampler_y_coord_scale = input_snapshot->texture->GetYCoordScale(); auto transform = entity.GetTransform() * effect_transform.Basis(); auto transformed_radius = transform.TransformDirection(direction_ * radius_.radius); auto transformed_texture_vertices = Rect::MakeSize(input_snapshot->texture->GetSize()) .GetTransformedPoints(input_snapshot->transform); auto transformed_texture_width = transformed_texture_vertices[0].GetDistance( transformed_texture_vertices[1]); auto transformed_texture_height = transformed_texture_vertices[0].GetDistance( transformed_texture_vertices[2]); FS::FragInfo frag_info; frag_info.radius = std::round(transformed_radius.GetLength()); frag_info.morph_type = static_cast<Scalar>(morph_type_); frag_info.uv_offset = input_snapshot->transform.Invert() .TransformDirection(transformed_radius) .Normalize() / Point(transformed_texture_width, transformed_texture_height); pass.SetCommandLabel("Morphology Filter"); auto options = OptionsFromPass(pass); options.primitive_type = PrimitiveType::kTriangleStrip; options.blend_mode = BlendMode::kSource; pass.SetPipeline(renderer.GetMorphologyFilterPipeline(options)); pass.SetVertexBuffer(vtx_builder.CreateVertexBuffer(host_buffer)); auto sampler_descriptor = input_snapshot->sampler_descriptor; if (renderer.GetDeviceCapabilities().SupportsDecalSamplerAddressMode()) { sampler_descriptor.width_address_mode = SamplerAddressMode::kDecal; sampler_descriptor.height_address_mode = SamplerAddressMode::kDecal; } FS::BindTextureSampler( pass, input_snapshot->texture, renderer.GetContext()->GetSamplerLibrary()->GetSampler( sampler_descriptor)); VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info)); FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); return pass.Draw().ok(); }; fml::StatusOr<RenderTarget> render_target = renderer.MakeSubpass( "Directional Morphology Filter", ISize(coverage.GetSize()), callback); if (!render_target.ok()) { return std::nullopt; } SamplerDescriptor sampler_desc; sampler_desc.min_filter = MinMagFilter::kLinear; sampler_desc.mag_filter = MinMagFilter::kLinear; return Entity::FromSnapshot( Snapshot{.texture = render_target.value().GetRenderTargetTexture(), .transform = Matrix::MakeTranslation(coverage.GetOrigin()), .sampler_descriptor = sampler_desc, .opacity = input_snapshot->opacity}, entity.GetBlendMode(), entity.GetClipDepth()); } std::optional<Rect> DirectionalMorphologyFilterContents::GetFilterCoverage( const FilterInput::Vector& inputs, const Entity& entity, const Matrix& effect_transform) const { if (inputs.empty()) { return std::nullopt; } auto coverage = inputs[0]->GetCoverage(entity); if (!coverage.has_value()) { return std::nullopt; } auto transform = inputs[0]->GetTransform(entity) * effect_transform.Basis(); auto transformed_vector = transform.TransformDirection(direction_ * radius_.radius).Abs(); auto origin = coverage->GetOrigin(); auto size = Vector2(coverage->GetSize()); switch (morph_type_) { case FilterContents::MorphType::kDilate: origin -= transformed_vector; size += transformed_vector * 2; break; case FilterContents::MorphType::kErode: origin += transformed_vector; size -= transformed_vector * 2; break; } if (size.x < 0 || size.y < 0) { return Rect::MakeSize(Size(0, 0)); } return Rect::MakeOriginSize(origin, Size(size.x, size.y)); } std::optional<Rect> DirectionalMorphologyFilterContents::GetFilterSourceCoverage( const Matrix& effect_transform, const Rect& output_limit) const { auto transformed_vector = effect_transform.TransformDirection(direction_ * radius_.radius).Abs(); switch (morph_type_) { case FilterContents::MorphType::kDilate: return output_limit.Expand(-transformed_vector); case FilterContents::MorphType::kErode: return output_limit.Expand(transformed_vector); } } } // namespace impeller
engine/impeller/entity/contents/filters/morphology_filter_contents.cc/0
{ "file_path": "engine/impeller/entity/contents/filters/morphology_filter_contents.cc", "repo_id": "engine", "token_count": 2562 }
332
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_RUNTIME_EFFECT_CONTENTS_H_ #define FLUTTER_IMPELLER_ENTITY_CONTENTS_RUNTIME_EFFECT_CONTENTS_H_ #include <memory> #include <vector> #include "impeller/core/sampler_descriptor.h" #include "impeller/entity/contents/color_source_contents.h" #include "impeller/runtime_stage/runtime_stage.h" namespace impeller { class RuntimeEffectContents final : public ColorSourceContents { public: struct TextureInput { SamplerDescriptor sampler_descriptor; std::shared_ptr<Texture> texture; }; void SetRuntimeStage(std::shared_ptr<RuntimeStage> runtime_stage); void SetUniformData(std::shared_ptr<std::vector<uint8_t>> uniform_data); void SetTextureInputs(std::vector<TextureInput> texture_inputs); // | Contents| bool CanInheritOpacity(const Entity& entity) const override; // |Contents| bool Render(const ContentContext& renderer, const Entity& entity, RenderPass& pass) const override; private: std::shared_ptr<RuntimeStage> runtime_stage_; std::shared_ptr<std::vector<uint8_t>> uniform_data_; std::vector<TextureInput> texture_inputs_; }; } // namespace impeller #endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_RUNTIME_EFFECT_CONTENTS_H_
engine/impeller/entity/contents/runtime_effect_contents.h/0
{ "file_path": "engine/impeller/entity/contents/runtime_effect_contents.h", "repo_id": "engine", "token_count": 488 }
333
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_TEXTURE_CONTENTS_H_ #define FLUTTER_IMPELLER_ENTITY_CONTENTS_TEXTURE_CONTENTS_H_ #include <functional> #include <memory> #include <vector> #include "flutter/fml/macros.h" #include "impeller/core/sampler_descriptor.h" #include "impeller/entity/contents/contents.h" #include "impeller/geometry/path.h" namespace impeller { class Texture; class TextureContents final : public Contents { public: TextureContents(); ~TextureContents() override; /// @brief A common case factory that marks the texture contents as having a /// destination rectangle. In this situation, a subpass can be avoided /// when image filters are applied. static std::shared_ptr<TextureContents> MakeRect(Rect destination); void SetLabel(std::string label); void SetDestinationRect(Rect rect); void SetTexture(std::shared_ptr<Texture> texture); std::shared_ptr<Texture> GetTexture() const; void SetSamplerDescriptor(SamplerDescriptor desc); const SamplerDescriptor& GetSamplerDescriptor() const; void SetSourceRect(const Rect& source_rect); const Rect& GetSourceRect() const; void SetStrictSourceRect(bool strict); bool GetStrictSourceRect() const; void SetOpacity(Scalar opacity); Scalar GetOpacity() const; void SetStencilEnabled(bool enabled); // |Contents| std::optional<Rect> GetCoverage(const Entity& entity) const override; // |Contents| std::optional<Snapshot> RenderToSnapshot( const ContentContext& renderer, const Entity& entity, std::optional<Rect> coverage_limit = std::nullopt, const std::optional<SamplerDescriptor>& sampler_descriptor = std::nullopt, bool msaa_enabled = true, int32_t mip_count = 1, const std::string& label = "Texture Snapshot") const override; // |Contents| bool Render(const ContentContext& renderer, const Entity& entity, RenderPass& pass) const override; // |Contents| bool CanInheritOpacity(const Entity& entity) const override; // |Contents| void SetInheritedOpacity(Scalar opacity) override; void SetDeferApplyingOpacity(bool defer_applying_opacity); private: std::string label_; Rect destination_rect_; bool stencil_enabled_ = true; std::shared_ptr<Texture> texture_; SamplerDescriptor sampler_descriptor_ = {}; Rect source_rect_; bool strict_source_rect_enabled_ = false; Scalar opacity_ = 1.0f; Scalar inherited_opacity_ = 1.0f; bool defer_applying_opacity_ = false; TextureContents(const TextureContents&) = delete; TextureContents& operator=(const TextureContents&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_TEXTURE_CONTENTS_H_
engine/impeller/entity/contents/texture_contents.h/0
{ "file_path": "engine/impeller/entity/contents/texture_contents.h", "repo_id": "engine", "token_count": 954 }
334
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/entity/entity_playground.h" #include "impeller/entity/contents/content_context.h" #include "impeller/typographer/backends/skia/typographer_context_skia.h" #include "third_party/imgui/imgui.h" namespace impeller { EntityPlayground::EntityPlayground() : typographer_context_(TypographerContextSkia::Make()) {} EntityPlayground::~EntityPlayground() = default; void EntityPlayground::SetTypographerContext( std::shared_ptr<TypographerContext> typographer_context) { typographer_context_ = std::move(typographer_context); } bool EntityPlayground::OpenPlaygroundHere(EntityPass& entity_pass) { if (!switches_.enable_playground) { return true; } ContentContext content_context(GetContext(), typographer_context_); if (!content_context.IsValid()) { return false; } // Resolve any lingering tracked clips by assigning an arbitrarily high // number. The number to assign just needs to be at least as high as larger // any previously assigned clip depth in the scene. Normally, Aiks handles // this correctly when wrapping up the base pass as an `impeller::Picture`. entity_pass.PopAllClips(99999); auto callback = [&](RenderTarget& render_target) -> bool { return entity_pass.Render(content_context, render_target); }; return Playground::OpenPlaygroundHere(callback); } std::shared_ptr<ContentContext> EntityPlayground::GetContentContext() const { return std::make_shared<ContentContext>(GetContext(), typographer_context_); } bool EntityPlayground::OpenPlaygroundHere(Entity entity) { if (!switches_.enable_playground) { return true; } auto content_context = GetContentContext(); if (!content_context->IsValid()) { return false; } SinglePassCallback callback = [&](RenderPass& pass) -> bool { content_context->GetRenderTargetCache()->Start(); bool result = entity.Render(*content_context, pass); content_context->GetRenderTargetCache()->End(); content_context->GetTransientsBuffer().Reset(); return result; }; return Playground::OpenPlaygroundHere(callback); } bool EntityPlayground::OpenPlaygroundHere(EntityPlaygroundCallback callback) { if (!switches_.enable_playground) { return true; } ContentContext content_context(GetContext(), typographer_context_); if (!content_context.IsValid()) { return false; } SinglePassCallback pass_callback = [&](RenderPass& pass) -> bool { static bool wireframe = false; if (ImGui::IsKeyPressed(ImGuiKey_Z)) { wireframe = !wireframe; content_context.SetWireframe(wireframe); } content_context.GetRenderTargetCache()->Start(); bool result = callback(content_context, pass); content_context.GetRenderTargetCache()->End(); content_context.GetTransientsBuffer().Reset(); return result; }; return Playground::OpenPlaygroundHere(pass_callback); } } // namespace impeller
engine/impeller/entity/entity_playground.cc/0
{ "file_path": "engine/impeller/entity/entity_playground.cc", "repo_id": "engine", "token_count": 933 }
335
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/entity/geometry/point_field_geometry.h" #include "impeller/geometry/color.h" #include "impeller/renderer/command_buffer.h" namespace impeller { PointFieldGeometry::PointFieldGeometry(std::vector<Point> points, Scalar radius, bool round) : points_(std::move(points)), radius_(radius), round_(round) {} GeometryResult PointFieldGeometry::GetPositionBuffer( const ContentContext& renderer, const Entity& entity, RenderPass& pass) const { if (renderer.GetDeviceCapabilities().SupportsCompute()) { return GetPositionBufferGPU(renderer, entity, pass); } auto vtx_builder = GetPositionBufferCPU(renderer, entity, pass); if (!vtx_builder.has_value()) { return {}; } auto& host_buffer = renderer.GetTransientsBuffer(); return { .type = PrimitiveType::kTriangleStrip, .vertex_buffer = vtx_builder->CreateVertexBuffer(host_buffer), .transform = pass.GetOrthographicTransform() * entity.GetTransform(), }; } GeometryResult PointFieldGeometry::GetPositionUVBuffer( Rect texture_coverage, Matrix effect_transform, const ContentContext& renderer, const Entity& entity, RenderPass& pass) const { if (renderer.GetDeviceCapabilities().SupportsCompute()) { return GetPositionBufferGPU(renderer, entity, pass, texture_coverage, effect_transform); } auto vtx_builder = GetPositionBufferCPU(renderer, entity, pass); if (!vtx_builder.has_value()) { return {}; } auto uv_vtx_builder = ComputeUVGeometryCPU(vtx_builder.value(), {0, 0}, texture_coverage.GetSize(), effect_transform); auto& host_buffer = renderer.GetTransientsBuffer(); return { .type = PrimitiveType::kTriangleStrip, .vertex_buffer = uv_vtx_builder.CreateVertexBuffer(host_buffer), .transform = pass.GetOrthographicTransform() * entity.GetTransform(), }; } std::optional<VertexBufferBuilder<SolidFillVertexShader::PerVertexData>> PointFieldGeometry::GetPositionBufferCPU(const ContentContext& renderer, const Entity& entity, RenderPass& pass) const { if (radius_ < 0.0) { return std::nullopt; } auto transform = entity.GetTransform(); auto determinant = transform.GetDeterminant(); if (determinant == 0) { return std::nullopt; } Scalar min_size = 1.0f / sqrt(std::abs(determinant)); Scalar radius = std::max(radius_, min_size); VertexBufferBuilder<SolidFillVertexShader::PerVertexData> vtx_builder; if (round_) { // Get triangulation relative to {0, 0} so we can translate it to each // point in turn. auto generator = renderer.GetTessellator()->FilledCircle(transform, {}, radius); FML_DCHECK(generator.GetTriangleType() == PrimitiveType::kTriangleStrip); std::vector<Point> circle_vertices; circle_vertices.reserve(generator.GetVertexCount()); generator.GenerateVertices([&circle_vertices](const Point& p) { // circle_vertices.push_back(p); }); FML_DCHECK(circle_vertices.size() == generator.GetVertexCount()); vtx_builder.Reserve((circle_vertices.size() + 2) * points_.size() - 2); for (auto& center : points_) { if (vtx_builder.HasVertices()) { vtx_builder.AppendVertex(vtx_builder.Last()); vtx_builder.AppendVertex({center + circle_vertices[0]}); } for (auto& vertex : circle_vertices) { vtx_builder.AppendVertex({center + vertex}); } } } else { vtx_builder.Reserve(6 * points_.size() - 2); for (auto& point : points_) { auto first = Point(point.x - radius, point.y - radius); if (vtx_builder.HasVertices()) { vtx_builder.AppendVertex(vtx_builder.Last()); vtx_builder.AppendVertex({first}); } // Z pattern from UL -> UR -> LL -> LR vtx_builder.AppendVertex({first}); vtx_builder.AppendVertex({{point.x + radius, point.y - radius}}); vtx_builder.AppendVertex({{point.x - radius, point.y + radius}}); vtx_builder.AppendVertex({{point.x + radius, point.y + radius}}); } } return vtx_builder; } GeometryResult PointFieldGeometry::GetPositionBufferGPU( const ContentContext& renderer, const Entity& entity, RenderPass& pass, std::optional<Rect> texture_coverage, std::optional<Matrix> effect_transform) const { FML_DCHECK(renderer.GetDeviceCapabilities().SupportsCompute()); if (radius_ < 0.0) { return {}; } Scalar determinant = entity.GetTransform().GetDeterminant(); if (determinant == 0) { return {}; } Scalar min_size = 1.0f / sqrt(std::abs(determinant)); Scalar radius = std::max(radius_, min_size); size_t vertices_per_geom = ComputeCircleDivisions( entity.GetTransform().GetMaxBasisLength() * radius, round_); size_t points_per_circle = 3 + (vertices_per_geom - 3) * 3; size_t total = points_per_circle * points_.size(); std::shared_ptr<CommandBuffer> cmd_buffer = renderer.GetContext()->CreateCommandBuffer(); std::shared_ptr<ComputePass> compute_pass = cmd_buffer->CreateComputePass(); HostBuffer& host_buffer = renderer.GetTransientsBuffer(); BufferView points_data = host_buffer.Emplace(points_.data(), points_.size() * sizeof(Point), DefaultUniformAlignment()); BufferView geometry_buffer = host_buffer.Emplace(nullptr, total * sizeof(Point), std::max(DefaultUniformAlignment(), alignof(Point))); BufferView output; { using PS = PointsComputeShader; compute_pass->SetPipeline(renderer.GetPointComputePipeline()); compute_pass->SetCommandLabel("Points Geometry"); PS::FrameInfo frame_info; frame_info.count = points_.size(); frame_info.radius = round_ ? radius : radius * kSqrt2; frame_info.radian_start = round_ ? 0.0f : kPiOver4; frame_info.radian_step = k2Pi / vertices_per_geom; frame_info.points_per_circle = points_per_circle; frame_info.divisions_per_circle = vertices_per_geom; PS::BindFrameInfo(*compute_pass, host_buffer.EmplaceUniform(frame_info)); PS::BindGeometryData(*compute_pass, geometry_buffer); PS::BindPointData(*compute_pass, points_data); if (!compute_pass->Compute(ISize(total, 1)).ok()) { return {}; } output = geometry_buffer; } if (texture_coverage.has_value() && effect_transform.has_value()) { BufferView geometry_uv_buffer = host_buffer.Emplace( nullptr, total * sizeof(Vector4), std::max(DefaultUniformAlignment(), alignof(Vector4))); using UV = UvComputeShader; compute_pass->AddBufferMemoryBarrier(); compute_pass->SetCommandLabel("UV Geometry"); compute_pass->SetPipeline(renderer.GetUvComputePipeline()); UV::FrameInfo frame_info; frame_info.count = total; frame_info.effect_transform = effect_transform.value(); frame_info.texture_origin = {0, 0}; frame_info.texture_size = Vector2(texture_coverage.value().GetSize()); UV::BindFrameInfo(*compute_pass, host_buffer.EmplaceUniform(frame_info)); UV::BindGeometryData(*compute_pass, geometry_buffer); UV::BindGeometryUVData(*compute_pass, geometry_uv_buffer); if (!compute_pass->Compute(ISize(total, 1)).ok()) { return {}; } output = geometry_uv_buffer; } if (!compute_pass->EncodeCommands()) { return {}; } if (!renderer.GetContext() ->GetCommandQueue() ->Submit({std::move(cmd_buffer)}) .ok()) { return {}; } return { .type = PrimitiveType::kTriangle, .vertex_buffer = {.vertex_buffer = std::move(output), .vertex_count = total, .index_type = IndexType::kNone}, .transform = pass.GetOrthographicTransform() * entity.GetTransform(), }; } /// @brief Compute the number of vertices to divide each circle into. /// /// @return the number of vertices. size_t PointFieldGeometry::ComputeCircleDivisions(Scalar scaled_radius, bool round) { if (!round) { return 4; } // Note: these values are approximated based on the values returned from // the decomposition of 4 cubics performed by Path::CreatePolyline. if (scaled_radius < 1.0) { return 4; } if (scaled_radius < 2.0) { return 8; } if (scaled_radius < 12.0) { return 24; } if (scaled_radius < 22.0) { return 34; } return std::min(scaled_radius, 140.0f); } // |Geometry| GeometryVertexType PointFieldGeometry::GetVertexType() const { return GeometryVertexType::kPosition; } // |Geometry| std::optional<Rect> PointFieldGeometry::GetCoverage( const Matrix& transform) const { if (points_.size() > 0) { // Doesn't use MakePointBounds as this isn't resilient to points that // all lie along the same axis. auto first = points_.begin(); auto last = points_.end(); auto left = first->x; auto top = first->y; auto right = first->x; auto bottom = first->y; for (auto it = first + 1; it < last; ++it) { left = std::min(left, it->x); top = std::min(top, it->y); right = std::max(right, it->x); bottom = std::max(bottom, it->y); } auto coverage = Rect::MakeLTRB(left - radius_, top - radius_, right + radius_, bottom + radius_); return coverage.TransformBounds(transform); } return std::nullopt; } } // namespace impeller
engine/impeller/entity/geometry/point_field_geometry.cc/0
{ "file_path": "engine/impeller/entity/geometry/point_field_geometry.cc", "repo_id": "engine", "token_count": 3819 }
336
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <impeller/conversions.glsl> #include <impeller/types.glsl> uniform FrameInfo { mat4 mvp; float dst_y_coord_scale; float src_y_coord_scale; } frame_info; in vec2 vertices; in vec2 dst_texture_coords; in vec2 src_texture_coords; out vec2 v_dst_texture_coords; out vec2 v_src_texture_coords; void main() { gl_Position = frame_info.mvp * vec4(vertices, 0.0, 1.0); v_dst_texture_coords = IPRemapCoords(dst_texture_coords, frame_info.dst_y_coord_scale); v_src_texture_coords = IPRemapCoords(src_texture_coords, frame_info.src_y_coord_scale); }
engine/impeller/entity/shaders/blending/advanced_blend.vert/0
{ "file_path": "engine/impeller/entity/shaders/blending/advanced_blend.vert", "repo_id": "engine", "token_count": 294 }
337
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. precision mediump float; uniform FragInfo { vec4 color; float square_size; } frag_info; out vec4 frag_color; void main() { vec2 square = floor(gl_FragCoord.xy / frag_info.square_size); frag_color = mod(square.x + square.y, 2.0) * frag_info.color; }
engine/impeller/entity/shaders/debug/checkerboard.frag/0
{ "file_path": "engine/impeller/entity/shaders/debug/checkerboard.frag", "repo_id": "engine", "token_count": 145 }
338
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. precision mediump float; #include <impeller/color.glsl> #include <impeller/dithering.glsl> #include <impeller/texture.glsl> #include <impeller/types.glsl> struct ColorPoint { vec4 color; float stop; }; layout(std140) readonly buffer ColorData { ColorPoint colors[]; } color_data; uniform FragInfo { highp vec2 start_point; highp vec2 end_point; float alpha; float tile_mode; vec4 decal_border_color; int colors_length; } frag_info; highp in vec2 v_position; out vec4 frag_color; void main() { highp vec2 start_to_end = frag_info.end_point - frag_info.start_point; highp vec2 start_to_position = v_position - frag_info.start_point; highp float t = dot(start_to_position, start_to_end) / dot(start_to_end, start_to_end); if ((t < 0.0 || t > 1.0) && frag_info.tile_mode == kTileModeDecal) { frag_color = frag_info.decal_border_color; } else { t = IPFloatTile(t, frag_info.tile_mode); for (int i = 1; i < frag_info.colors_length; i++) { ColorPoint prev_point = color_data.colors[i - 1]; ColorPoint current_point = color_data.colors[i]; if (t >= prev_point.stop && t <= current_point.stop) { float delta = (current_point.stop - prev_point.stop); if (delta < 0.001) { frag_color = current_point.color; } else { float ratio = (t - prev_point.stop) / delta; frag_color = mix(prev_point.color, current_point.color, ratio); } break; } } } frag_color = IPPremultiply(frag_color) * frag_info.alpha; frag_color = IPOrderedDither8x8(frag_color, v_position); }
engine/impeller/entity/shaders/linear_gradient_ssbo_fill.frag/0
{ "file_path": "engine/impeller/entity/shaders/linear_gradient_ssbo_fill.frag", "repo_id": "engine", "token_count": 716 }
339
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <impeller/color.glsl> #include <impeller/constants.glsl> #include <impeller/dithering.glsl> #include <impeller/gradient.glsl> #include <impeller/texture.glsl> #include <impeller/types.glsl> struct ColorPoint { vec4 color; float stop; }; layout(std140) readonly buffer ColorData { ColorPoint colors[]; } color_data; uniform FragInfo { highp vec2 center; float bias; float scale; float tile_mode; vec4 decal_border_color; float alpha; int colors_length; } frag_info; highp in vec2 v_position; out vec4 frag_color; void main() { vec2 coord = v_position - frag_info.center; float angle = atan(-coord.y, -coord.x); float t = (angle * k1Over2Pi + 0.5 + frag_info.bias) * frag_info.scale; vec4 result_color = vec4(0); if ((t < 0.0 || t > 1.0) && frag_info.tile_mode == kTileModeDecal) { result_color = frag_info.decal_border_color; } else { t = IPFloatTile(t, frag_info.tile_mode); for (int i = 1; i < frag_info.colors_length; i++) { ColorPoint prev_point = color_data.colors[i - 1]; ColorPoint current_point = color_data.colors[i]; if (t >= prev_point.stop && t <= current_point.stop) { float delta = (current_point.stop - prev_point.stop); if (delta < 0.001) { result_color = current_point.color; } else { float ratio = (t - prev_point.stop) / delta; result_color = mix(prev_point.color, current_point.color, ratio); } break; } } } frag_color = IPPremultiply(result_color) * frag_info.alpha; frag_color = IPOrderedDither8x8(frag_color, v_position); }
engine/impeller/entity/shaders/sweep_gradient_ssbo_fill.frag/0
{ "file_path": "engine/impeller/entity/shaders/sweep_gradient_ssbo_fill.frag", "repo_id": "engine", "token_count": 716 }
340
#include <flutter/runtime_effect.glsl> uniform vec2 uSize; out vec4 fragColor; void main() { float v = FlutterFragCoord().y / uSize.y; fragColor = vec4(v, v, v, 1); }
engine/impeller/fixtures/gradient.frag/0
{ "file_path": "engine/impeller/fixtures/gradient.frag", "repo_id": "engine", "token_count": 73 }
341
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/geometry/color.h" #include <algorithm> #include <cmath> #include <functional> #include <sstream> #include <type_traits> #include "impeller/base/strings.h" #include "impeller/geometry/constants.h" #include "impeller/geometry/scalar.h" #include "impeller/geometry/vector.h" namespace impeller { #define _IMPELLER_ASSERT_BLEND_MODE(blend_mode) \ auto enum_##blend_mode = static_cast<std::underlying_type_t<BlendMode>>( \ BlendMode::k##blend_mode); \ if (i != enum_##blend_mode) { \ return false; \ } \ ++i; static constexpr inline bool ValidateBlendModes() { std::underlying_type_t<BlendMode> i = 0; // Ensure the order of the blend modes match. IMPELLER_FOR_EACH_BLEND_MODE(_IMPELLER_ASSERT_BLEND_MODE) // Ensure the total number of blend modes match. if (i - 1 != static_cast<std::underlying_type_t<BlendMode>>(BlendMode::kLast)) { return false; } return true; } static_assert(ValidateBlendModes(), "IMPELLER_FOR_EACH_BLEND_MODE must match impeller::BlendMode."); #define _IMPELLER_BLEND_MODE_NAME_LIST(blend_mode) #blend_mode, static constexpr const char* kBlendModeNames[] = { IMPELLER_FOR_EACH_BLEND_MODE(_IMPELLER_BLEND_MODE_NAME_LIST)}; const char* BlendModeToString(BlendMode blend_mode) { return kBlendModeNames[static_cast<std::underlying_type_t<BlendMode>>( blend_mode)]; } ColorHSB ColorHSB::FromRGB(Color rgb) { Scalar R = rgb.red; Scalar G = rgb.green; Scalar B = rgb.blue; Scalar v = 0.0; Scalar x = 0.0; Scalar f = 0.0; int64_t i = 0; x = fmin(R, G); x = fmin(x, B); v = fmax(R, G); v = fmax(v, B); if (v == x) { return ColorHSB(0.0, 0.0, v, rgb.alpha); } f = (R == x) ? G - B : ((G == x) ? B - R : R - G); i = (R == x) ? 3 : ((G == x) ? 5 : 1); return ColorHSB(((i - f / (v - x)) / 6.0), (v - x) / v, v, rgb.alpha); } Color ColorHSB::ToRGBA() const { Scalar h = hue * 6.0; Scalar s = saturation; Scalar v = brightness; Scalar m = 0.0; Scalar n = 0.0; Scalar f = 0.0; int64_t i = 0; if (h == 0) { h = 0.01; } if (h == 0.0) { return Color(v, v, v, alpha); } i = static_cast<int64_t>(floor(h)); f = h - i; if (!(i & 1)) { f = 1 - f; } m = v * (1 - s); n = v * (1 - s * f); switch (i) { case 6: case 0: return Color(v, n, m, alpha); case 1: return Color(n, v, m, alpha); case 2: return Color(m, v, n, alpha); case 3: return Color(m, n, v, alpha); case 4: return Color(n, m, v, alpha); case 5: return Color(v, m, n, alpha); } return Color(0, 0, 0, alpha); } Color::Color(const ColorHSB& hsbColor) : Color(hsbColor.ToRGBA()) {} Color::Color(const Vector4& value) : red(value.x), green(value.y), blue(value.z), alpha(value.w) {} static constexpr inline Color Min(Color c, float threshold) { return Color(std::min(c.red, threshold), std::min(c.green, threshold), std::min(c.blue, threshold), std::min(c.alpha, threshold)); } // The following HSV utilities correspond to the W3C blend definitions // implemented in: impeller/compiler/shader_lib/impeller/blending.glsl static constexpr inline Scalar Luminosity(Vector3 color) { return color.x * 0.3f + color.y * 0.59f + color.z * 0.11f; } static constexpr inline Vector3 ClipColor(Vector3 color) { Scalar lum = Luminosity(color); Scalar mn = std::min(std::min(color.x, color.y), color.z); Scalar mx = std::max(std::max(color.x, color.y), color.z); // `lum - mn` and `mx - lum` will always be >= 0 in the following conditions, // so adding a tiny value is enough to make these divisions safe. if (mn < 0.0f) { color = lum + (((color - lum) * lum) / (lum - mn + kEhCloseEnough)); } if (mx > 1.0) { color = lum + (((color - lum) * (1.0f - lum)) / (mx - lum + kEhCloseEnough)); } return color; } static constexpr inline Vector3 SetLuminosity(Vector3 color, Scalar luminosity) { Scalar relative_lum = luminosity - Luminosity(color); return ClipColor(color + relative_lum); } static constexpr inline Scalar Saturation(Vector3 color) { return std::max(std::max(color.x, color.y), color.z) - std::min(std::min(color.x, color.y), color.z); } static constexpr inline Vector3 SetSaturation(Vector3 color, Scalar saturation) { Scalar mn = std::min(std::min(color.x, color.y), color.z); Scalar mx = std::max(std::max(color.x, color.y), color.z); return (mn < mx) ? ((color - mn) * saturation) / (mx - mn) : Vector3(); } static constexpr inline Vector3 ComponentChoose(Vector3 a, Vector3 b, Vector3 value, Scalar cutoff) { return Vector3(value.x > cutoff ? b.x : a.x, // value.y > cutoff ? b.y : a.y, // value.z > cutoff ? b.z : a.z // ); } static constexpr inline Vector3 ToRGB(Color color) { return {color.red, color.green, color.blue}; } static constexpr inline Color FromRGB(Vector3 color, Scalar alpha) { return {color.x, color.y, color.z, alpha}; } /// Composite a blended color onto the destination. /// All three parameters are unpremultiplied. Returns a premultiplied result. /// /// This routine is the same as `IPApplyBlendedColor` in the Impeller shader /// library. static constexpr inline Color ApplyBlendedColor(Color dst, Color src, Vector3 blend_result) { dst = dst.Premultiply(); src = // Use the blended color for areas where the source and destination // colors overlap. FromRGB(blend_result, src.alpha * dst.alpha).Premultiply() + // Use the original source color for any remaining non-overlapping areas. src.Premultiply() * (1.0f - dst.alpha); // Source-over composite the blended source color atop the destination. return src + dst * (1.0f - src.alpha); } static constexpr inline Color DoColorBlend( Color dst, Color src, const std::function<Vector3(Vector3, Vector3)>& blend_rgb_func) { const Vector3 blend_result = blend_rgb_func(ToRGB(dst), ToRGB(src)); return ApplyBlendedColor(dst, src, blend_result).Unpremultiply(); } static constexpr inline Color DoColorBlendComponents( Color dst, Color src, const std::function<Scalar(Scalar, Scalar)>& blend_func) { Vector3 blend_result = Vector3(blend_func(dst.red, src.red), // blend_func(dst.green, src.green), // blend_func(dst.blue, src.blue)); // return ApplyBlendedColor(dst, src, blend_result).Unpremultiply(); } Color Color::Blend(Color src, BlendMode blend_mode) const { Color dst = *this; switch (blend_mode) { case BlendMode::kClear: return Color::BlackTransparent(); case BlendMode::kSource: return src; case BlendMode::kDestination: return dst; case BlendMode::kSourceOver: // r = s + (1-sa)*d return (src.Premultiply() + dst.Premultiply() * (1 - src.alpha)) .Unpremultiply(); case BlendMode::kDestinationOver: // r = d + (1-da)*s return (dst.Premultiply() + src.Premultiply() * (1 - dst.alpha)) .Unpremultiply(); case BlendMode::kSourceIn: // r = s * da return (src.Premultiply() * dst.alpha).Unpremultiply(); case BlendMode::kDestinationIn: // r = d * sa return (dst.Premultiply() * src.alpha).Unpremultiply(); case BlendMode::kSourceOut: // r = s * ( 1- da) return (src.Premultiply() * (1 - dst.alpha)).Unpremultiply(); case BlendMode::kDestinationOut: // r = d * (1-sa) return (dst.Premultiply() * (1 - src.alpha)).Unpremultiply(); case BlendMode::kSourceATop: // r = s*da + d*(1-sa) return (src.Premultiply() * dst.alpha + dst.Premultiply() * (1 - src.alpha)) .Unpremultiply(); case BlendMode::kDestinationATop: // r = d*sa + s*(1-da) return (dst.Premultiply() * src.alpha + src.Premultiply() * (1 - dst.alpha)) .Unpremultiply(); case BlendMode::kXor: // r = s*(1-da) + d*(1-sa) return (src.Premultiply() * (1 - dst.alpha) + dst.Premultiply() * (1 - src.alpha)) .Unpremultiply(); case BlendMode::kPlus: // r = min(s + d, 1) return (Min(src.Premultiply() + dst.Premultiply(), 1)).Unpremultiply(); case BlendMode::kModulate: // r = s*d return (src.Premultiply() * dst.Premultiply()).Unpremultiply(); case BlendMode::kScreen: { return DoColorBlend(dst, src, [](Vector3 d, Vector3 s) -> Vector3 { return s + d - s * d; }); } case BlendMode::kOverlay: return DoColorBlend(dst, src, [](Vector3 d, Vector3 s) -> Vector3 { // The same as HardLight, but with the source and destination reversed. Vector3 screen_src = 2.0 * d - 1.0; Vector3 screen = screen_src + s - screen_src * s; return ComponentChoose(s * (2.0 * d), // screen, // d, // 0.5); }); case BlendMode::kDarken: return DoColorBlend( dst, src, [](Vector3 d, Vector3 s) -> Vector3 { return d.Min(s); }); case BlendMode::kLighten: return DoColorBlend( dst, src, [](Vector3 d, Vector3 s) -> Vector3 { return d.Max(s); }); case BlendMode::kColorDodge: return DoColorBlendComponents(dst, src, [](Scalar d, Scalar s) -> Scalar { if (d < kEhCloseEnough) { return 0.0f; } if (1.0 - s < kEhCloseEnough) { return 1.0f; } return std::min(1.0f, d / (1.0f - s)); }); case BlendMode::kColorBurn: return DoColorBlendComponents(dst, src, [](Scalar d, Scalar s) -> Scalar { if (1.0 - d < kEhCloseEnough) { return 1.0f; } if (s < kEhCloseEnough) { return 0.0f; } return 1.0f - std::min(1.0f, (1.0f - d) / s); }); case BlendMode::kHardLight: return DoColorBlend(dst, src, [](Vector3 d, Vector3 s) -> Vector3 { Vector3 screen_src = 2.0 * s - 1.0; Vector3 screen = screen_src + d - screen_src * d; return ComponentChoose(d * (2.0 * s), // screen, // s, // 0.5); }); case BlendMode::kSoftLight: return DoColorBlend(dst, src, [](Vector3 d, Vector3 s) -> Vector3 { Vector3 D = ComponentChoose(((16.0 * d - 12.0) * d + 4.0) * d, // Vector3(std::sqrt(d.x), std::sqrt(d.y), std::sqrt(d.z)), // d, // 0.25); return ComponentChoose(d - (1.0 - 2.0 * s) * d * (1.0 - d), // d + (2.0 * s - 1.0) * (D - d), // s, // 0.5); }); case BlendMode::kDifference: return DoColorBlend(dst, src, [](Vector3 d, Vector3 s) -> Vector3 { return (d - s).Abs(); }); case BlendMode::kExclusion: return DoColorBlend(dst, src, [](Vector3 d, Vector3 s) -> Vector3 { return d + s - 2.0f * d * s; }); case BlendMode::kMultiply: return DoColorBlend( dst, src, [](Vector3 d, Vector3 s) -> Vector3 { return d * s; }); case BlendMode::kHue: { return DoColorBlend(dst, src, [](Vector3 d, Vector3 s) -> Vector3 { return SetLuminosity(SetSaturation(s, Saturation(d)), Luminosity(d)); }); } case BlendMode::kSaturation: return DoColorBlend(dst, src, [](Vector3 d, Vector3 s) -> Vector3 { return SetLuminosity(SetSaturation(d, Saturation(s)), Luminosity(d)); }); case BlendMode::kColor: return DoColorBlend(dst, src, [](Vector3 d, Vector3 s) -> Vector3 { return SetLuminosity(s, Luminosity(d)); }); case BlendMode::kLuminosity: return DoColorBlend(dst, src, [](Vector3 d, Vector3 s) -> Vector3 { return SetLuminosity(d, Luminosity(s)); }); } } Color Color::ApplyColorMatrix(const ColorMatrix& color_matrix) const { auto* c = color_matrix.array; return Color( c[0] * red + c[1] * green + c[2] * blue + c[3] * alpha + c[4], c[5] * red + c[6] * green + c[7] * blue + c[8] * alpha + c[9], c[10] * red + c[11] * green + c[12] * blue + c[13] * alpha + c[14], c[15] * red + c[16] * green + c[17] * blue + c[18] * alpha + c[19]) .Clamp01(); } Color Color::LinearToSRGB() const { static auto conversion = [](Scalar component) { if (component <= 0.0031308) { return component * 12.92; } return 1.055 * pow(component, (1.0 / 2.4)) - 0.055; }; return Color(conversion(red), conversion(green), conversion(blue), alpha); } Color Color::SRGBToLinear() const { static auto conversion = [](Scalar component) { if (component <= 0.04045) { return component / 12.92; } return pow((component + 0.055) / 1.055, 2.4); }; return Color(conversion(red), conversion(green), conversion(blue), alpha); } std::string ColorToString(const Color& color) { return SPrintF("R=%.1f,G=%.1f,B=%.1f,A=%.1f", // color.red, // color.green, // color.blue, // color.alpha // ); } } // namespace impeller
engine/impeller/geometry/color.cc/0
{ "file_path": "engine/impeller/geometry/color.cc", "repo_id": "engine", "token_count": 6884 }
342
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_GEOMETRY_PATH_H_ #define FLUTTER_IMPELLER_GEOMETRY_PATH_H_ #include <functional> #include <optional> #include <tuple> #include <vector> #include "impeller/geometry/path_component.h" namespace impeller { enum class Cap { kButt, kRound, kSquare, }; enum class Join { kMiter, kRound, kBevel, }; enum class FillType { kNonZero, // The default winding order. kOdd, }; enum class Convexity { kUnknown, kConvex, }; //------------------------------------------------------------------------------ /// @brief Paths are lightweight objects that describe a collection of /// linear, quadratic, or cubic segments. These segments may be /// broken up by move commands, which are effectively linear /// commands that pick up the pen rather than continuing to draw. /// /// All shapes supported by Impeller are paths either directly or /// via approximation (in the case of circles). /// /// Paths are externally immutable once created, Creating paths must /// be done using a path builder. /// class Path { public: enum class ComponentType { kLinear, kQuadratic, kCubic, kContour, }; struct PolylineContour { struct Component { size_t component_start_index; /// Denotes whether this component is a curve. /// /// This is set to true when this component is generated from /// QuadraticComponent or CubicPathComponent. bool is_curve; }; /// Index that denotes the first point of this contour. size_t start_index; /// Denotes whether the last point of this contour is connected to the first /// point of this contour or not. bool is_closed; /// The direction of the contour's start cap. Vector2 start_direction; /// The direction of the contour's end cap. Vector2 end_direction; /// Distinct components in this contour. /// /// If this contour is generated from multiple path components, each /// path component forms a component in this vector. std::vector<Component> components; }; /// One or more contours represented as a series of points and indices in /// the point vector representing the start of a new contour. /// /// Polylines are ephemeral and meant to be used by the tessellator. They do /// not allocate their own point vectors to allow for optimizations around /// allocation and reuse of arenas. struct Polyline { /// The signature of a method called when it is safe to reclaim the point /// buffer provided to the constructor of this object. using PointBufferPtr = std::unique_ptr<std::vector<Point>>; using ReclaimPointBufferCallback = std::function<void(PointBufferPtr)>; /// The buffer will be cleared and returned at the destruction of this /// polyline. Polyline(PointBufferPtr point_buffer, ReclaimPointBufferCallback reclaim); Polyline(Polyline&& other); ~Polyline(); /// Points in the polyline, which may represent multiple contours specified /// by indices in |contours|. PointBufferPtr points; Point& GetPoint(size_t index) const { return (*points)[index]; } /// Contours are disconnected pieces of a polyline, such as when a MoveTo /// was issued on a PathBuilder. std::vector<PolylineContour> contours; /// Convenience method to compute the start (inclusive) and end (exclusive) /// point of the given contour index. /// /// The contour_index parameter is clamped to contours.size(). std::tuple<size_t, size_t> GetContourPointBounds( size_t contour_index) const; private: ReclaimPointBufferCallback reclaim_points_; }; Path(); ~Path(); size_t GetComponentCount(std::optional<ComponentType> type = {}) const; FillType GetFillType() const; bool IsConvex() const; bool IsEmpty() const; template <class T> using Applier = std::function<void(size_t index, const T& component)>; void EnumerateComponents( const Applier<LinearPathComponent>& linear_applier, const Applier<QuadraticPathComponent>& quad_applier, const Applier<CubicPathComponent>& cubic_applier, const Applier<ContourComponent>& contour_applier) const; bool GetLinearComponentAtIndex(size_t index, LinearPathComponent& linear) const; bool GetQuadraticComponentAtIndex(size_t index, QuadraticPathComponent& quadratic) const; bool GetCubicComponentAtIndex(size_t index, CubicPathComponent& cubic) const; bool GetContourComponentAtIndex(size_t index, ContourComponent& contour) const; /// Callers must provide the scale factor for how this path will be /// transformed. /// /// It is suitable to use the max basis length of the matrix used to transform /// the path. If the provided scale is 0, curves will revert to straight /// lines. Polyline CreatePolyline( Scalar scale, Polyline::PointBufferPtr point_buffer = std::make_unique<std::vector<Point>>(), Polyline::ReclaimPointBufferCallback reclaim = nullptr) const; std::optional<Rect> GetBoundingBox() const; std::optional<Rect> GetTransformedBoundingBox(const Matrix& transform) const; private: friend class PathBuilder; struct ComponentIndexPair { ComponentType type = ComponentType::kLinear; size_t index = 0; ComponentIndexPair() {} ComponentIndexPair(ComponentType a_type, size_t a_index) : type(a_type), index(a_index) {} }; // All of the data for the path is stored in this structure which is // held by a shared_ptr. Since they all share the structure, the // copy constructor for Path is very cheap and we don't need to deal // with shared pointers for Path fields and method arguments. // // PathBuilder also uses this structure to accumulate the path data // but the Path constructor used in |TakePath()| will clone the // structure to prevent sharing and future modifications within the // builder from affecting the existing taken paths. struct Data { Data() = default; Data(Data&& other) = default; Data(const Data& other) = default; ~Data() = default; FillType fill = FillType::kNonZero; Convexity convexity = Convexity::kUnknown; std::vector<ComponentIndexPair> components; std::vector<Point> points; std::vector<ContourComponent> contours; std::optional<Rect> bounds; }; explicit Path(Data data); std::shared_ptr<const Data> data_; }; static_assert(sizeof(Path) == sizeof(std::shared_ptr<struct Anonymous>)); } // namespace impeller #endif // FLUTTER_IMPELLER_GEOMETRY_PATH_H_
engine/impeller/geometry/path.h/0
{ "file_path": "engine/impeller/geometry/path.h", "repo_id": "engine", "token_count": 2260 }
343
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/golden_tests/golden_digest.h" #include <fstream> #include <sstream> static const double kMaxDiffPixelsPercent = 0.01; static const int32_t kMaxColorDelta = 8; namespace impeller { namespace testing { GoldenDigest* GoldenDigest::instance_ = nullptr; GoldenDigest* GoldenDigest::Instance() { if (!instance_) { instance_ = new GoldenDigest(); } return instance_; } GoldenDigest::GoldenDigest() {} void GoldenDigest::AddDimension(const std::string& name, const std::string& value) { std::stringstream ss; ss << "\"" << value << "\""; dimensions_[name] = ss.str(); } void GoldenDigest::AddImage(const std::string& test_name, const std::string& filename, int32_t width, int32_t height) { entries_.push_back({test_name, filename, width, height, kMaxDiffPixelsPercent, kMaxColorDelta}); } bool GoldenDigest::Write(WorkingDirectory* working_directory) { std::ofstream fout; fout.open(working_directory->GetFilenamePath("digest.json")); if (!fout.good()) { return false; } fout << "{" << std::endl; fout << " \"dimensions\": {" << std::endl; bool is_first = true; for (const auto& dimension : dimensions_) { if (!is_first) { fout << "," << std::endl; } is_first = false; fout << " \"" << dimension.first << "\": " << dimension.second; } fout << std::endl << " }," << std::endl; fout << " \"entries\":" << std::endl; fout << " [" << std::endl; is_first = true; for (const auto& entry : entries_) { if (!is_first) { fout << "," << std::endl; } is_first = false; fout << " { " << "\"testName\" : \"" << entry.test_name << "\", " << "\"filename\" : \"" << entry.filename << "\", " << "\"width\" : " << entry.width << ", " << "\"height\" : " << entry.height << ", "; if (entry.max_diff_pixels_percent == static_cast<int64_t>(entry.max_diff_pixels_percent)) { fout << "\"maxDiffPixelsPercent\" : " << entry.max_diff_pixels_percent << ".0, "; } else { fout << "\"maxDiffPixelsPercent\" : " << entry.max_diff_pixels_percent << ", "; } fout << "\"maxColorDelta\":" << entry.max_color_delta << " "; fout << "}"; } fout << std::endl << " ]" << std::endl; fout << "}" << std::endl; fout.close(); return true; } } // namespace testing } // namespace impeller
engine/impeller/golden_tests/golden_digest.cc/0
{ "file_path": "engine/impeller/golden_tests/golden_digest.cc", "repo_id": "engine", "token_count": 1124 }
344
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_GOLDEN_TESTS_WORKING_DIRECTORY_H_ #define FLUTTER_IMPELLER_GOLDEN_TESTS_WORKING_DIRECTORY_H_ #include <string> #include "flutter/fml/macros.h" namespace impeller { namespace testing { /// Keeps track of the global variable for the specified working /// directory. class WorkingDirectory { public: static WorkingDirectory* Instance(); std::string GetFilenamePath(const std::string& filename) const; void SetPath(const std::string& path); const std::string& GetPath() const { return path_; } private: WorkingDirectory(const WorkingDirectory&) = delete; WorkingDirectory& operator=(const WorkingDirectory&) = delete; WorkingDirectory(); static WorkingDirectory* instance_; std::string path_; bool did_set_ = false; }; } // namespace testing } // namespace impeller #endif // FLUTTER_IMPELLER_GOLDEN_TESTS_WORKING_DIRECTORY_H_
engine/impeller/golden_tests/working_directory.h/0
{ "file_path": "engine/impeller/golden_tests/working_directory.h", "repo_id": "engine", "token_count": 330 }
345
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_PLAYGROUND_IMAGE_BACKENDS_SKIA_COMPRESSED_IMAGE_SKIA_H_ #define FLUTTER_IMPELLER_PLAYGROUND_IMAGE_BACKENDS_SKIA_COMPRESSED_IMAGE_SKIA_H_ #include "flutter/fml/macros.h" #include "impeller/playground/image/compressed_image.h" namespace impeller { class CompressedImageSkia final : public CompressedImage { public: static std::shared_ptr<CompressedImage> Create( std::shared_ptr<const fml::Mapping> allocation); explicit CompressedImageSkia(std::shared_ptr<const fml::Mapping> allocation); ~CompressedImageSkia() override; // |CompressedImage| DecompressedImage Decode() const override; private: CompressedImageSkia(const CompressedImageSkia&) = delete; CompressedImageSkia& operator=(const CompressedImageSkia&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_PLAYGROUND_IMAGE_BACKENDS_SKIA_COMPRESSED_IMAGE_SKIA_H_
engine/impeller/playground/image/backends/skia/compressed_image_skia.h/0
{ "file_path": "engine/impeller/playground/image/backends/skia/compressed_image_skia.h", "repo_id": "engine", "token_count": 362 }
346
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/playground/switches.h" #include <cstdlib> #include "flutter/fml/build_config.h" namespace impeller { PlaygroundSwitches::PlaygroundSwitches() = default; PlaygroundSwitches::PlaygroundSwitches(const fml::CommandLine& args) { enable_playground = args.HasOption("enable_playground"); std::string timeout_str; if (args.GetOptionValue("playground_timeout_ms", &timeout_str)) { timeout = std::chrono::milliseconds(atoi(timeout_str.c_str())); // Specifying a playground timeout implies you want to enable playgrounds. enable_playground = true; } enable_vulkan_validation = args.HasOption("enable_vulkan_validation"); use_swiftshader = args.HasOption("use_swiftshader"); use_angle = args.HasOption("use_angle"); #if FML_OS_MACOSX // OpenGL on macOS is busted and deprecated. Use Angle there by default. use_angle = true; #endif // FML_OS_MACOSX } } // namespace impeller
engine/impeller/playground/switches.cc/0
{ "file_path": "engine/impeller/playground/switches.cc", "repo_id": "engine", "token_count": 351 }
347
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_CAPABILITIES_GLES_H_ #define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_CAPABILITIES_GLES_H_ #include <cstddef> #include "impeller/base/backend_cast.h" #include "impeller/core/formats.h" #include "impeller/core/shader_types.h" #include "impeller/geometry/size.h" #include "impeller/renderer/capabilities.h" namespace impeller { class ProcTableGLES; //------------------------------------------------------------------------------ /// @brief The Vulkan layers and extensions wrangler. /// class CapabilitiesGLES final : public Capabilities, public BackendCast<CapabilitiesGLES, Capabilities> { public: explicit CapabilitiesGLES(const ProcTableGLES& gl); CapabilitiesGLES(const CapabilitiesGLES&) = delete; CapabilitiesGLES(CapabilitiesGLES&&) = delete; CapabilitiesGLES& operator=(const CapabilitiesGLES&) = delete; CapabilitiesGLES& operator=(CapabilitiesGLES&&) = delete; // Must be at least 8. size_t max_combined_texture_image_units = 8; // Must be at least 16. size_t max_cube_map_texture_size = 16; // Must be at least 16. size_t max_fragment_uniform_vectors = 16; // Must be at least 1. size_t max_renderbuffer_size = 1; // Must be at least 8. size_t max_texture_image_units = 8; // Must be at least 64. ISize max_texture_size = ISize{64, 64}; // Must be at least 8. size_t max_varying_vectors = 8; // Must be at least 8. size_t max_vertex_attribs = 8; // May be 0. size_t max_vertex_texture_image_units = 0; // Must be at least 128. size_t max_vertex_uniform_vectors = 128; // Must be at least display size. ISize max_viewport_dims; // May be 0. size_t num_compressed_texture_formats = 0; // May be 0. size_t num_shader_binary_formats = 0; size_t GetMaxTextureUnits(ShaderStage stage) const; bool IsANGLE() const; // |Capabilities| bool SupportsOffscreenMSAA() const override; // |Capabilities| bool SupportsImplicitResolvingMSAA() const override; // |Capabilities| bool SupportsSSBO() const override; // |Capabilities| bool SupportsBufferToTextureBlits() const override; // |Capabilities| bool SupportsTextureToTextureBlits() const override; // |Capabilities| bool SupportsFramebufferFetch() const override; // |Capabilities| bool SupportsCompute() const override; // |Capabilities| bool SupportsComputeSubgroups() const override; // |Capabilities| bool SupportsReadFromResolve() const override; // |Capabilities| bool SupportsDecalSamplerAddressMode() const override; // |Capabilities| bool SupportsDeviceTransientTextures() const override; // |Capabilities| PixelFormat GetDefaultColorFormat() const override; // |Capabilities| PixelFormat GetDefaultStencilFormat() const override; // |Capabilities| PixelFormat GetDefaultDepthStencilFormat() const override; // |Capabilities| PixelFormat GetDefaultGlyphAtlasFormat() const override; private: bool supports_framebuffer_fetch_ = false; bool supports_decal_sampler_address_mode_ = false; bool supports_offscreen_msaa_ = false; bool supports_implicit_msaa_ = false; bool is_angle_ = false; PixelFormat default_glyph_atlas_format_ = PixelFormat::kUnknown; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_CAPABILITIES_GLES_H_
engine/impeller/renderer/backend/gles/capabilities_gles.h/0
{ "file_path": "engine/impeller/renderer/backend/gles/capabilities_gles.h", "repo_id": "engine", "token_count": 1152 }
348
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/renderer/backend/gles/pipeline_gles.h" namespace impeller { PipelineGLES::PipelineGLES(ReactorGLES::Ref reactor, std::weak_ptr<PipelineLibrary> library, const PipelineDescriptor& desc) : Pipeline(std::move(library), desc), reactor_(std::move(reactor)), handle_(reactor_ ? reactor_->CreateHandle(HandleType::kProgram) : HandleGLES::DeadHandle()), is_valid_(!handle_.IsDead()) { if (is_valid_) { reactor_->SetDebugLabel(handle_, GetDescriptor().GetLabel()); } } // |Pipeline| PipelineGLES::~PipelineGLES() { if (!handle_.IsDead()) { reactor_->CollectHandle(handle_); } } // |Pipeline| bool PipelineGLES::IsValid() const { return is_valid_; } const HandleGLES& PipelineGLES::GetProgramHandle() const { return handle_; } BufferBindingsGLES* PipelineGLES::GetBufferBindings() const { return buffer_bindings_.get(); } bool PipelineGLES::BuildVertexDescriptor(const ProcTableGLES& gl, GLuint program) { if (buffer_bindings_) { return false; } auto vtx_desc = std::make_unique<BufferBindingsGLES>(); if (!vtx_desc->RegisterVertexStageInput( gl, GetDescriptor().GetVertexDescriptor()->GetStageInputs(), GetDescriptor().GetVertexDescriptor()->GetStageLayouts())) { return false; } if (!vtx_desc->ReadUniformsBindings(gl, program)) { return false; } buffer_bindings_ = std::move(vtx_desc); return true; } [[nodiscard]] bool PipelineGLES::BindProgram() const { if (handle_.IsDead()) { return false; } auto handle = reactor_->GetGLHandle(handle_); if (!handle.has_value()) { return false; } reactor_->GetProcTable().UseProgram(handle.value()); return true; } [[nodiscard]] bool PipelineGLES::UnbindProgram() const { if (reactor_) { reactor_->GetProcTable().UseProgram(0u); } return true; } } // namespace impeller
engine/impeller/renderer/backend/gles/pipeline_gles.cc/0
{ "file_path": "engine/impeller/renderer/backend/gles/pipeline_gles.cc", "repo_id": "engine", "token_count": 860 }
349
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/renderer/backend/gles/shader_library_gles.h" #include <sstream> #include "flutter/fml/closure.h" #include "impeller/base/config.h" #include "impeller/base/validation.h" #include "impeller/renderer/backend/gles/shader_function_gles.h" #include "impeller/shader_archive/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 GLESShaderNameToShaderKeyName(const std::string& name, ShaderStage stage) { std::stringstream stream; stream << name; switch (stage) { case ShaderStage::kUnknown: stream << "_unknown_"; break; case ShaderStage::kVertex: stream << "_vertex_"; break; case ShaderStage::kFragment: stream << "_fragment_"; break; case ShaderStage::kCompute: stream << "_compute_"; break; } stream << "main"; return stream.str(); } ShaderLibraryGLES::ShaderLibraryGLES( const std::vector<std::shared_ptr<fml::Mapping>>& shader_libraries) { ShaderFunctionMap functions; auto iterator = [&functions, library_id = library_id_](auto type, // const auto& name, // const auto& mapping // ) -> bool { const auto stage = ToShaderStage(type); const auto key_name = GLESShaderNameToShaderKeyName(name, stage); functions[ShaderKey{key_name, stage}] = std::shared_ptr<ShaderFunctionGLES>( new ShaderFunctionGLES(library_id, // stage, // key_name, // mapping // )); return true; }; for (auto library : shader_libraries) { auto gles_archive = MultiArchShaderArchive::CreateArchiveFromMapping( std::move(library), ArchiveRenderingBackend::kOpenGLES); if (!gles_archive || !gles_archive->IsValid()) { VALIDATION_LOG << "Could not construct shader library."; return; } gles_archive->IterateAllShaders(iterator); } functions_ = functions; is_valid_ = true; } // |ShaderLibrary| ShaderLibraryGLES::~ShaderLibraryGLES() = default; // |ShaderLibrary| bool ShaderLibraryGLES::IsValid() const { return is_valid_; } // |ShaderLibrary| std::shared_ptr<const ShaderFunction> ShaderLibraryGLES::GetFunction( std::string_view name, ShaderStage stage) { ReaderLock lock(functions_mutex_); const auto key = ShaderKey{name, stage}; if (auto found = functions_.find(key); found != functions_.end()) { return found->second; } return nullptr; } // |ShaderLibrary| void ShaderLibraryGLES::RegisterFunction(std::string name, ShaderStage stage, std::shared_ptr<fml::Mapping> code, RegistrationCallback callback) { if (!callback) { callback = [](auto) {}; } fml::ScopedCleanupClosure auto_fail([callback]() { callback(false); }); if (name.empty() || stage == ShaderStage::kUnknown || code == nullptr || code->GetMapping() == nullptr) { VALIDATION_LOG << "Invalid runtime stage registration."; return; } const auto key = ShaderKey{name, stage}; WriterLock lock(functions_mutex_); if (functions_.count(key) != 0) { VALIDATION_LOG << "Runtime stage named " << name << " has already been registered."; return; } functions_[key] = std::shared_ptr<ShaderFunctionGLES>(new ShaderFunctionGLES( library_id_, // stage, // GLESShaderNameToShaderKeyName(name, stage), // code // )); auto_fail.Release(); callback(true); } // |ShaderLibrary| void ShaderLibraryGLES::UnregisterFunction(std::string name, ShaderStage stage) { ReaderLock lock(functions_mutex_); const auto key = ShaderKey{name, stage}; auto found = functions_.find(key); if (found == functions_.end()) { VALIDATION_LOG << "Library function named " << name << " was not found, so it couldn't be unregistered."; return; } functions_.erase(found); return; } } // namespace impeller
engine/impeller/renderer/backend/gles/shader_library_gles.cc/0
{ "file_path": "engine/impeller/renderer/backend/gles/shader_library_gles.cc", "repo_id": "engine", "token_count": 2222 }
350
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_ALLOCATOR_MTL_H_ #define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_ALLOCATOR_MTL_H_ #include <Metal/Metal.h> #include "flutter/fml/macros.h" #include "impeller/core/allocator.h" namespace impeller { class AllocatorMTL final : public Allocator { public: AllocatorMTL(); // |Allocator| ~AllocatorMTL() override; private: friend class ContextMTL; id<MTLDevice> device_; std::string allocator_label_; bool supports_memoryless_targets_ = false; bool supports_uma_ = false; bool is_valid_ = false; ISize max_texture_supported_; AllocatorMTL(id<MTLDevice> device, std::string label); // |Allocator| bool IsValid() const; // |Allocator| std::shared_ptr<DeviceBuffer> OnCreateBuffer( const DeviceBufferDescriptor& desc) override; // |Allocator| std::shared_ptr<Texture> OnCreateTexture( const TextureDescriptor& desc) override; // |Allocator| uint16_t MinimumBytesPerRow(PixelFormat format) const override; // |Allocator| ISize GetMaxTextureSizeSupported() const override; AllocatorMTL(const AllocatorMTL&) = delete; AllocatorMTL& operator=(const AllocatorMTL&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_ALLOCATOR_MTL_H_
engine/impeller/renderer/backend/metal/allocator_mtl.h/0
{ "file_path": "engine/impeller/renderer/backend/metal/allocator_mtl.h", "repo_id": "engine", "token_count": 529 }
351
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_DEVICE_BUFFER_MTL_H_ #define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_DEVICE_BUFFER_MTL_H_ #include <Metal/Metal.h> #include "flutter/fml/macros.h" #include "impeller/base/backend_cast.h" #include "impeller/core/device_buffer.h" namespace impeller { class DeviceBufferMTL final : public DeviceBuffer, public BackendCast<DeviceBufferMTL, DeviceBuffer> { public: DeviceBufferMTL(); // |DeviceBuffer| ~DeviceBufferMTL() override; id<MTLBuffer> GetMTLBuffer() const; private: friend class AllocatorMTL; const id<MTLBuffer> buffer_; const MTLStorageMode storage_mode_; DeviceBufferMTL(DeviceBufferDescriptor desc, id<MTLBuffer> buffer, MTLStorageMode storage_mode); // |DeviceBuffer| uint8_t* OnGetContents() const override; // |DeviceBuffer| std::shared_ptr<Texture> AsTexture(Allocator& allocator, const TextureDescriptor& descriptor, uint16_t row_bytes) const override; // |DeviceBuffer| bool OnCopyHostBuffer(const uint8_t* source, Range source_range, size_t offset) override; // |DeviceBuffer| bool SetLabel(const std::string& label) override; // |DeviceBuffer| bool SetLabel(const std::string& label, Range range) override; // |DeviceBuffer| void Flush(std::optional<Range> range) const override; DeviceBufferMTL(const DeviceBufferMTL&) = delete; DeviceBufferMTL& operator=(const DeviceBufferMTL&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_DEVICE_BUFFER_MTL_H_
engine/impeller/renderer/backend/metal/device_buffer_mtl.h/0
{ "file_path": "engine/impeller/renderer/backend/metal/device_buffer_mtl.h", "repo_id": "engine", "token_count": 738 }
352
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SAMPLER_LIBRARY_MTL_H_ #define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SAMPLER_LIBRARY_MTL_H_ #include <Metal/Metal.h> #include <memory> #include "flutter/fml/macros.h" #include "impeller/base/backend_cast.h" #include "impeller/base/comparable.h" #include "impeller/core/sampler_descriptor.h" #include "impeller/renderer/sampler_library.h" namespace impeller { class SamplerLibraryMTL final : public SamplerLibrary, public BackendCast<SamplerLibraryMTL, SamplerLibrary> { public: // |SamplerLibrary| ~SamplerLibraryMTL() override; private: friend class ContextMTL; id<MTLDevice> device_ = nullptr; SamplerMap samplers_; explicit SamplerLibraryMTL(id<MTLDevice> device); // |SamplerLibrary| const std::unique_ptr<const Sampler>& GetSampler( SamplerDescriptor descriptor) override; SamplerLibraryMTL(const SamplerLibraryMTL&) = delete; SamplerLibraryMTL& operator=(const SamplerLibraryMTL&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SAMPLER_LIBRARY_MTL_H_
engine/impeller/renderer/backend/metal/sampler_library_mtl.h/0
{ "file_path": "engine/impeller/renderer/backend/metal/sampler_library_mtl.h", "repo_id": "engine", "token_count": 472 }
353
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/renderer/backend/metal/vertex_descriptor_mtl.h" #include "flutter/fml/logging.h" #include "impeller/base/validation.h" namespace impeller { VertexDescriptorMTL::VertexDescriptorMTL() = default; VertexDescriptorMTL::~VertexDescriptorMTL() = default; static MTLVertexFormat ReadStageInputFormat(const ShaderStageIOSlot& input) { if (input.columns != 1) { // All matrix types are unsupported as vertex inputs. return MTLVertexFormatInvalid; } switch (input.type) { case ShaderType::kFloat: { if (input.bit_width == 8 * sizeof(float)) { switch (input.vec_size) { case 1: return MTLVertexFormatFloat; case 2: return MTLVertexFormatFloat2; case 3: return MTLVertexFormatFloat3; case 4: return MTLVertexFormatFloat4; } } return MTLVertexFormatInvalid; } case ShaderType::kHalfFloat: { if (input.bit_width == 8 * sizeof(float) / 2) { switch (input.vec_size) { case 1: return MTLVertexFormatHalf; case 2: return MTLVertexFormatHalf2; case 3: return MTLVertexFormatHalf3; case 4: return MTLVertexFormatHalf4; } } return MTLVertexFormatInvalid; } case ShaderType::kDouble: { // Unsupported. return MTLVertexFormatInvalid; } case ShaderType::kBoolean: { if (input.bit_width == 8 * sizeof(bool) && input.vec_size == 1) { return MTLVertexFormatChar; } return MTLVertexFormatInvalid; } case ShaderType::kSignedByte: { if (input.bit_width == 8 * sizeof(char)) { switch (input.vec_size) { case 1: return MTLVertexFormatChar; case 2: return MTLVertexFormatChar2; case 3: return MTLVertexFormatChar3; case 4: return MTLVertexFormatChar4; } } return MTLVertexFormatInvalid; } case ShaderType::kUnsignedByte: { if (input.bit_width == 8 * sizeof(char)) { switch (input.vec_size) { case 1: return MTLVertexFormatUChar; case 2: return MTLVertexFormatUChar2; case 3: return MTLVertexFormatUChar3; case 4: return MTLVertexFormatUChar4; } } return MTLVertexFormatInvalid; } case ShaderType::kSignedShort: { if (input.bit_width == 8 * sizeof(short)) { switch (input.vec_size) { case 1: return MTLVertexFormatShort; case 2: return MTLVertexFormatShort2; case 3: return MTLVertexFormatShort3; case 4: return MTLVertexFormatShort4; } } return MTLVertexFormatInvalid; } case ShaderType::kUnsignedShort: { if (input.bit_width == 8 * sizeof(ushort)) { switch (input.vec_size) { case 1: return MTLVertexFormatUShort; case 2: return MTLVertexFormatUShort2; case 3: return MTLVertexFormatUShort3; case 4: return MTLVertexFormatUShort4; } } return MTLVertexFormatInvalid; } case ShaderType::kSignedInt: { if (input.bit_width == 8 * sizeof(int32_t)) { switch (input.vec_size) { case 1: return MTLVertexFormatInt; case 2: return MTLVertexFormatInt2; case 3: return MTLVertexFormatInt3; case 4: return MTLVertexFormatInt4; } } return MTLVertexFormatInvalid; } case ShaderType::kUnsignedInt: { if (input.bit_width == 8 * sizeof(uint32_t)) { switch (input.vec_size) { case 1: return MTLVertexFormatUInt; case 2: return MTLVertexFormatUInt2; case 3: return MTLVertexFormatUInt3; case 4: return MTLVertexFormatUInt4; } } return MTLVertexFormatInvalid; } case ShaderType::kSignedInt64: { // Unsupported. return MTLVertexFormatInvalid; } case ShaderType::kUnsignedInt64: { // Unsupported. return MTLVertexFormatInvalid; } case ShaderType::kAtomicCounter: case ShaderType::kStruct: case ShaderType::kImage: case ShaderType::kSampledImage: case ShaderType::kUnknown: case ShaderType::kVoid: case ShaderType::kSampler: return MTLVertexFormatInvalid; } } bool VertexDescriptorMTL::SetStageInputsAndLayout( const std::vector<ShaderStageIOSlot>& inputs, const std::vector<ShaderStageBufferLayout>& layouts) { auto descriptor = descriptor_ = [MTLVertexDescriptor vertexDescriptor]; // TODO(jonahwilliams): its odd that we offset buffers from the max index on // metal but not on GLES or Vulkan. We should probably consistently start // these at zero? for (size_t i = 0; i < inputs.size(); i++) { const auto& input = inputs[i]; auto vertex_format = ReadStageInputFormat(input); if (vertex_format == MTLVertexFormatInvalid) { VALIDATION_LOG << "Format for input " << input.name << " not supported."; return false; } auto attrib = descriptor.attributes[input.location]; attrib.format = vertex_format; attrib.offset = input.offset; attrib.bufferIndex = VertexDescriptor::kReservedVertexBufferIndex - input.binding; } for (size_t i = 0; i < layouts.size(); i++) { const auto& layout = layouts[i]; auto vertex_layout = descriptor.layouts[VertexDescriptor::kReservedVertexBufferIndex - layout.binding]; vertex_layout.stride = layout.stride; vertex_layout.stepRate = 1u; vertex_layout.stepFunction = MTLVertexStepFunctionPerVertex; } return true; } MTLVertexDescriptor* VertexDescriptorMTL::GetMTLVertexDescriptor() const { return descriptor_; } } // namespace impeller
engine/impeller/renderer/backend/metal/vertex_descriptor_mtl.mm/0
{ "file_path": "engine/impeller/renderer/backend/metal/vertex_descriptor_mtl.mm", "repo_id": "engine", "token_count": 2875 }
354
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/renderer/backend/vulkan/command_buffer_vk.h" #include <memory> #include <utility> #include "fml/logging.h" #include "impeller/renderer/backend/vulkan/blit_pass_vk.h" #include "impeller/renderer/backend/vulkan/command_encoder_vk.h" #include "impeller/renderer/backend/vulkan/compute_pass_vk.h" #include "impeller/renderer/backend/vulkan/context_vk.h" #include "impeller/renderer/backend/vulkan/render_pass_vk.h" #include "impeller/renderer/command_buffer.h" #include "impeller/renderer/render_target.h" namespace impeller { CommandBufferVK::CommandBufferVK( std::weak_ptr<const Context> context, std::shared_ptr<CommandEncoderFactoryVK> encoder_factory) : CommandBuffer(std::move(context)), encoder_factory_(std::move(encoder_factory)) {} CommandBufferVK::~CommandBufferVK() = default; void CommandBufferVK::SetLabel(const std::string& label) const { if (!encoder_) { encoder_factory_->SetLabel(label); } else { auto context = context_.lock(); if (!context || !encoder_) { return; } ContextVK::Cast(*context).SetDebugName(encoder_->GetCommandBuffer(), label); } } bool CommandBufferVK::IsValid() const { return true; } const std::shared_ptr<CommandEncoderVK>& CommandBufferVK::GetEncoder() { if (!encoder_) { encoder_ = encoder_factory_->Create(); } return encoder_; } bool CommandBufferVK::OnSubmitCommands(CompletionCallback callback) { FML_UNREACHABLE() } void CommandBufferVK::OnWaitUntilScheduled() {} std::shared_ptr<RenderPass> CommandBufferVK::OnCreateRenderPass( RenderTarget target) { auto context = context_.lock(); if (!context) { return nullptr; } auto pass = std::shared_ptr<RenderPassVK>(new RenderPassVK(context, // target, // shared_from_this() // )); if (!pass->IsValid()) { return nullptr; } return pass; } std::shared_ptr<BlitPass> CommandBufferVK::OnCreateBlitPass() { if (!IsValid()) { return nullptr; } auto pass = std::shared_ptr<BlitPassVK>(new BlitPassVK(weak_from_this())); if (!pass->IsValid()) { return nullptr; } return pass; } std::shared_ptr<ComputePass> CommandBufferVK::OnCreateComputePass() { if (!IsValid()) { return nullptr; } auto context = context_.lock(); if (!context) { return nullptr; } auto pass = std::shared_ptr<ComputePassVK>(new ComputePassVK(context, // shared_from_this() // )); if (!pass->IsValid()) { return nullptr; } return pass; } } // namespace impeller
engine/impeller/renderer/backend/vulkan/command_buffer_vk.cc/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/command_buffer_vk.cc", "repo_id": "engine", "token_count": 1278 }
355
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/fml/synchronization/waitable_event.h" #include "flutter/testing/testing.h" // IWYU pragma: keep #include "impeller/base/validation.h" #include "impeller/core/formats.h" #include "impeller/renderer/backend/vulkan/command_pool_vk.h" #include "impeller/renderer/backend/vulkan/context_vk.h" #include "impeller/renderer/backend/vulkan/test/mock_vulkan.h" namespace impeller { namespace testing { TEST(ContextVKTest, CommonHardwareConcurrencyConfigurations) { EXPECT_EQ(ContextVK::ChooseThreadCountForWorkers(100u), 4u); EXPECT_EQ(ContextVK::ChooseThreadCountForWorkers(9u), 4u); EXPECT_EQ(ContextVK::ChooseThreadCountForWorkers(8u), 4u); EXPECT_EQ(ContextVK::ChooseThreadCountForWorkers(7u), 3u); EXPECT_EQ(ContextVK::ChooseThreadCountForWorkers(6u), 3u); EXPECT_EQ(ContextVK::ChooseThreadCountForWorkers(5u), 2u); EXPECT_EQ(ContextVK::ChooseThreadCountForWorkers(4u), 2u); EXPECT_EQ(ContextVK::ChooseThreadCountForWorkers(3u), 1u); EXPECT_EQ(ContextVK::ChooseThreadCountForWorkers(2u), 1u); EXPECT_EQ(ContextVK::ChooseThreadCountForWorkers(1u), 1u); } TEST(ContextVKTest, DeletesCommandPools) { std::weak_ptr<ContextVK> weak_context; std::weak_ptr<CommandPoolVK> weak_pool; { std::shared_ptr<ContextVK> context = MockVulkanContextBuilder().Build(); auto const pool = context->GetCommandPoolRecycler()->Get(); weak_pool = pool; weak_context = context; ASSERT_TRUE(weak_pool.lock()); ASSERT_TRUE(weak_context.lock()); } ASSERT_FALSE(weak_pool.lock()); ASSERT_FALSE(weak_context.lock()); } TEST(ContextVKTest, DeletesCommandPoolsOnAllThreads) { std::weak_ptr<ContextVK> weak_context; std::weak_ptr<CommandPoolVK> weak_pool_main; std::shared_ptr<ContextVK> context = MockVulkanContextBuilder().Build(); weak_pool_main = context->GetCommandPoolRecycler()->Get(); weak_context = context; ASSERT_TRUE(weak_pool_main.lock()); ASSERT_TRUE(weak_context.lock()); // Start a second thread that obtains a command pool. fml::AutoResetWaitableEvent latch1, latch2; std::weak_ptr<CommandPoolVK> weak_pool_thread; std::thread thread([&]() { weak_pool_thread = context->GetCommandPoolRecycler()->Get(); latch1.Signal(); latch2.Wait(); }); // Delete the ContextVK on the main thread. latch1.Wait(); context.reset(); ASSERT_FALSE(weak_pool_main.lock()); ASSERT_FALSE(weak_context.lock()); // Stop the second thread and check that its command pool has been deleted. latch2.Signal(); thread.join(); ASSERT_FALSE(weak_pool_thread.lock()); } TEST(ContextVKTest, DeletePipelineAfterContext) { std::shared_ptr<Pipeline<PipelineDescriptor>> pipeline; std::shared_ptr<std::vector<std::string>> functions; { std::shared_ptr<ContextVK> context = MockVulkanContextBuilder().Build(); PipelineDescriptor pipeline_desc; pipeline_desc.SetVertexDescriptor(std::make_shared<VertexDescriptor>()); PipelineFuture<PipelineDescriptor> pipeline_future = context->GetPipelineLibrary()->GetPipeline(pipeline_desc); pipeline = pipeline_future.Get(); ASSERT_TRUE(pipeline); functions = GetMockVulkanFunctions(context->GetDevice()); ASSERT_TRUE(std::find(functions->begin(), functions->end(), "vkCreateGraphicsPipelines") != functions->end()); } ASSERT_TRUE(std::find(functions->begin(), functions->end(), "vkDestroyDevice") != functions->end()); } TEST(ContextVKTest, DeleteShaderFunctionAfterContext) { std::shared_ptr<const ShaderFunction> shader_function; std::shared_ptr<std::vector<std::string>> functions; { std::shared_ptr<ContextVK> context = MockVulkanContextBuilder().Build(); PipelineDescriptor pipeline_desc; pipeline_desc.SetVertexDescriptor(std::make_shared<VertexDescriptor>()); std::vector<uint8_t> data = {0x03, 0x02, 0x23, 0x07}; context->GetShaderLibrary()->RegisterFunction( "foobar_fragment_main", ShaderStage::kFragment, std::make_shared<fml::DataMapping>(data), [](bool) {}); shader_function = context->GetShaderLibrary()->GetFunction( "foobar_fragment_main", ShaderStage::kFragment); ASSERT_TRUE(shader_function); functions = GetMockVulkanFunctions(context->GetDevice()); ASSERT_TRUE(std::find(functions->begin(), functions->end(), "vkCreateShaderModule") != functions->end()); } ASSERT_TRUE(std::find(functions->begin(), functions->end(), "vkDestroyDevice") != functions->end()); } TEST(ContextVKTest, DeletePipelineLibraryAfterContext) { std::shared_ptr<PipelineLibrary> pipeline_library; std::shared_ptr<std::vector<std::string>> functions; { std::shared_ptr<ContextVK> context = MockVulkanContextBuilder().Build(); PipelineDescriptor pipeline_desc; pipeline_desc.SetVertexDescriptor(std::make_shared<VertexDescriptor>()); pipeline_library = context->GetPipelineLibrary(); functions = GetMockVulkanFunctions(context->GetDevice()); ASSERT_TRUE(std::find(functions->begin(), functions->end(), "vkCreatePipelineCache") != functions->end()); } ASSERT_TRUE(std::find(functions->begin(), functions->end(), "vkDestroyDevice") != functions->end()); } TEST(ContextVKTest, CanCreateContextInAbsenceOfValidationLayers) { // The mocked methods don't report the presence of a validation layer but we // explicitly ask for validation. Context creation should continue anyway. auto context = MockVulkanContextBuilder() .SetSettingsCallback([](auto& settings) { settings.enable_validation = true; }) .Build(); ASSERT_NE(context, nullptr); const CapabilitiesVK* capabilites_vk = reinterpret_cast<const CapabilitiesVK*>(context->GetCapabilities().get()); ASSERT_FALSE(capabilites_vk->AreValidationsEnabled()); } TEST(ContextVKTest, CanCreateContextWithValidationLayers) { auto context = MockVulkanContextBuilder() .SetSettingsCallback( [](auto& settings) { settings.enable_validation = true; }) .SetInstanceExtensions( {"VK_KHR_surface", "VK_MVK_macos_surface", "VK_EXT_debug_utils"}) .SetInstanceLayers({"VK_LAYER_KHRONOS_validation"}) .Build(); ASSERT_NE(context, nullptr); const CapabilitiesVK* capabilites_vk = reinterpret_cast<const CapabilitiesVK*>(context->GetCapabilities().get()); ASSERT_TRUE(capabilites_vk->AreValidationsEnabled()); } // In Impeller's 2D renderer, we no longer use stencil-only formats. They're // less widely supported than combined depth-stencil formats, so make sure we // don't fail initialization if we can't find a suitable stencil format. TEST(CapabilitiesVKTest, ContextInitializesWithNoStencilFormat) { const std::shared_ptr<ContextVK> context = MockVulkanContextBuilder() .SetPhysicalDeviceFormatPropertiesCallback( [](VkPhysicalDevice physicalDevice, VkFormat format, VkFormatProperties* pFormatProperties) { if (format == VK_FORMAT_B8G8R8A8_UNORM) { pFormatProperties->optimalTilingFeatures = static_cast<VkFormatFeatureFlags>( vk::FormatFeatureFlagBits::eColorAttachment); } else if (format == VK_FORMAT_D32_SFLOAT_S8_UINT) { pFormatProperties->optimalTilingFeatures = static_cast<VkFormatFeatureFlags>( vk::FormatFeatureFlagBits::eDepthStencilAttachment); } // Ignore just the stencil format. }) .Build(); ASSERT_NE(context, nullptr); const CapabilitiesVK* capabilites_vk = reinterpret_cast<const CapabilitiesVK*>(context->GetCapabilities().get()); ASSERT_EQ(capabilites_vk->GetDefaultDepthStencilFormat(), PixelFormat::kD32FloatS8UInt); ASSERT_EQ(capabilites_vk->GetDefaultStencilFormat(), PixelFormat::kD32FloatS8UInt); } // Impeller's 2D renderer relies on hardware support for a combined // depth-stencil format (widely supported). So fail initialization if a suitable // one couldn't be found. That way we have an opportunity to fallback to // OpenGLES. TEST(CapabilitiesVKTest, ContextFailsInitializationForNoCombinedDepthStencilFormat) { ScopedValidationDisable disable_validation; const std::shared_ptr<ContextVK> context = MockVulkanContextBuilder() .SetPhysicalDeviceFormatPropertiesCallback( [](VkPhysicalDevice physicalDevice, VkFormat format, VkFormatProperties* pFormatProperties) { if (format == VK_FORMAT_B8G8R8A8_UNORM) { pFormatProperties->optimalTilingFeatures = static_cast<VkFormatFeatureFlags>( vk::FormatFeatureFlagBits::eColorAttachment); } // Ignore combined depth-stencil formats. }) .Build(); ASSERT_EQ(context, nullptr); } TEST(ContextVKTest, WarmUpFunctionCreatesRenderPass) { const std::shared_ptr<ContextVK> context = MockVulkanContextBuilder().Build(); context->SetOffscreenFormat(PixelFormat::kR8G8B8A8UNormInt); context->InitializeCommonlyUsedShadersIfNeeded(); auto functions = GetMockVulkanFunctions(context->GetDevice()); ASSERT_TRUE(std::find(functions->begin(), functions->end(), "vkCreateRenderPass") != functions->end()); } } // namespace testing } // namespace impeller
engine/impeller/renderer/backend/vulkan/context_vk_unittests.cc/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/context_vk_unittests.cc", "repo_id": "engine", "token_count": 3803 }
356
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_FORMATS_VK_H_ #define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_FORMATS_VK_H_ #include <cstdint> #include <ostream> #include "flutter/fml/hash_combine.h" #include "flutter/fml/macros.h" #include "impeller/base/validation.h" #include "impeller/core/formats.h" #include "impeller/core/shader_types.h" #include "impeller/renderer/backend/vulkan/vk.h" #include "vulkan/vulkan_enums.hpp" namespace impeller { constexpr vk::SampleCountFlagBits ToVKSampleCountFlagBits(SampleCount count) { switch (count) { case SampleCount::kCount1: return vk::SampleCountFlagBits::e1; case SampleCount::kCount4: return vk::SampleCountFlagBits::e4; } FML_UNREACHABLE(); } constexpr vk::BlendFactor ToVKBlendFactor(BlendFactor factor) { switch (factor) { case BlendFactor::kZero: return vk::BlendFactor::eZero; case BlendFactor::kOne: return vk::BlendFactor::eOne; case BlendFactor::kSourceColor: return vk::BlendFactor::eSrcColor; case BlendFactor::kOneMinusSourceColor: return vk::BlendFactor::eOneMinusSrcColor; case BlendFactor::kSourceAlpha: return vk::BlendFactor::eSrcAlpha; case BlendFactor::kOneMinusSourceAlpha: return vk::BlendFactor::eOneMinusSrcAlpha; case BlendFactor::kDestinationColor: return vk::BlendFactor::eDstColor; case BlendFactor::kOneMinusDestinationColor: return vk::BlendFactor::eOneMinusDstColor; case BlendFactor::kDestinationAlpha: return vk::BlendFactor::eDstAlpha; case BlendFactor::kOneMinusDestinationAlpha: return vk::BlendFactor::eOneMinusDstAlpha; case BlendFactor::kSourceAlphaSaturated: return vk::BlendFactor::eSrcAlphaSaturate; case BlendFactor::kBlendColor: return vk::BlendFactor::eConstantColor; case BlendFactor::kOneMinusBlendColor: return vk::BlendFactor::eOneMinusConstantColor; case BlendFactor::kBlendAlpha: return vk::BlendFactor::eConstantAlpha; case BlendFactor::kOneMinusBlendAlpha: return vk::BlendFactor::eOneMinusConstantAlpha; } FML_UNREACHABLE(); } constexpr vk::BlendOp ToVKBlendOp(BlendOperation op) { switch (op) { case BlendOperation::kAdd: return vk::BlendOp::eAdd; case BlendOperation::kSubtract: return vk::BlendOp::eSubtract; case BlendOperation::kReverseSubtract: return vk::BlendOp::eReverseSubtract; } FML_UNREACHABLE(); } constexpr vk::ColorComponentFlags ToVKColorComponentFlags(ColorWriteMask type) { vk::ColorComponentFlags mask; if (type & ColorWriteMaskBits::kRed) { mask |= vk::ColorComponentFlagBits::eR; } if (type & ColorWriteMaskBits::kGreen) { mask |= vk::ColorComponentFlagBits::eG; } if (type & ColorWriteMaskBits::kBlue) { mask |= vk::ColorComponentFlagBits::eB; } if (type & ColorWriteMaskBits::kAlpha) { mask |= vk::ColorComponentFlagBits::eA; } return mask; } constexpr vk::PipelineColorBlendAttachmentState ToVKPipelineColorBlendAttachmentState(const ColorAttachmentDescriptor& desc) { vk::PipelineColorBlendAttachmentState res; res.setBlendEnable(desc.blending_enabled); res.setSrcColorBlendFactor(ToVKBlendFactor(desc.src_color_blend_factor)); res.setColorBlendOp(ToVKBlendOp(desc.color_blend_op)); res.setDstColorBlendFactor(ToVKBlendFactor(desc.dst_color_blend_factor)); res.setSrcAlphaBlendFactor(ToVKBlendFactor(desc.src_alpha_blend_factor)); res.setAlphaBlendOp(ToVKBlendOp(desc.alpha_blend_op)); res.setDstAlphaBlendFactor(ToVKBlendFactor(desc.dst_alpha_blend_factor)); res.setColorWriteMask(ToVKColorComponentFlags(desc.write_mask)); return res; } constexpr std::optional<vk::ShaderStageFlagBits> ToVKShaderStageFlagBits( ShaderStage stage) { switch (stage) { case ShaderStage::kUnknown: return std::nullopt; case ShaderStage::kVertex: return vk::ShaderStageFlagBits::eVertex; case ShaderStage::kFragment: return vk::ShaderStageFlagBits::eFragment; case ShaderStage::kCompute: return vk::ShaderStageFlagBits::eCompute; } FML_UNREACHABLE(); } constexpr vk::Format ToVKImageFormat(PixelFormat format) { switch (format) { case PixelFormat::kUnknown: case PixelFormat::kB10G10R10XR: case PixelFormat::kB10G10R10A10XR: case PixelFormat::kB10G10R10XRSRGB: return vk::Format::eUndefined; case PixelFormat::kA8UNormInt: // TODO(csg): This is incorrect. Don't depend on swizzle support for GLES. return vk::Format::eR8Unorm; case PixelFormat::kR8G8B8A8UNormInt: return vk::Format::eR8G8B8A8Unorm; case PixelFormat::kR8G8B8A8UNormIntSRGB: return vk::Format::eR8G8B8A8Srgb; case PixelFormat::kB8G8R8A8UNormInt: return vk::Format::eB8G8R8A8Unorm; case PixelFormat::kB8G8R8A8UNormIntSRGB: return vk::Format::eB8G8R8A8Srgb; case PixelFormat::kR32G32B32A32Float: return vk::Format::eR32G32B32A32Sfloat; case PixelFormat::kR16G16B16A16Float: return vk::Format::eR16G16B16A16Sfloat; case PixelFormat::kS8UInt: return vk::Format::eS8Uint; case PixelFormat::kD24UnormS8Uint: return vk::Format::eD24UnormS8Uint; case PixelFormat::kD32FloatS8UInt: return vk::Format::eD32SfloatS8Uint; case PixelFormat::kR8UNormInt: return vk::Format::eR8Unorm; case PixelFormat::kR8G8UNormInt: return vk::Format::eR8G8Unorm; } FML_UNREACHABLE(); } constexpr PixelFormat ToPixelFormat(vk::Format format) { switch (format) { case vk::Format::eUndefined: return PixelFormat::kUnknown; case vk::Format::eR8G8B8A8Unorm: return PixelFormat::kR8G8B8A8UNormInt; case vk::Format::eR8G8B8A8Srgb: return PixelFormat::kR8G8B8A8UNormIntSRGB; case vk::Format::eB8G8R8A8Unorm: return PixelFormat::kB8G8R8A8UNormInt; case vk::Format::eB8G8R8A8Srgb: return PixelFormat::kB8G8R8A8UNormIntSRGB; case vk::Format::eR32G32B32A32Sfloat: return PixelFormat::kR32G32B32A32Float; case vk::Format::eR16G16B16A16Sfloat: return PixelFormat::kR16G16B16A16Float; case vk::Format::eS8Uint: return PixelFormat::kS8UInt; case vk::Format::eD24UnormS8Uint: return PixelFormat::kD24UnormS8Uint; case vk::Format::eD32SfloatS8Uint: return PixelFormat::kD32FloatS8UInt; case vk::Format::eR8Unorm: return PixelFormat::kR8UNormInt; case vk::Format::eR8G8Unorm: return PixelFormat::kR8G8UNormInt; default: return PixelFormat::kUnknown; } } constexpr vk::SampleCountFlagBits ToVKSampleCount(SampleCount sample_count) { switch (sample_count) { case SampleCount::kCount1: return vk::SampleCountFlagBits::e1; case SampleCount::kCount4: return vk::SampleCountFlagBits::e4; } FML_UNREACHABLE(); } constexpr vk::Filter ToVKSamplerMinMagFilter(MinMagFilter filter) { switch (filter) { case MinMagFilter::kNearest: return vk::Filter::eNearest; case MinMagFilter::kLinear: return vk::Filter::eLinear; } FML_UNREACHABLE(); } constexpr vk::SamplerMipmapMode ToVKSamplerMipmapMode(MipFilter filter) { switch (filter) { case MipFilter::kNearest: return vk::SamplerMipmapMode::eNearest; case MipFilter::kLinear: return vk::SamplerMipmapMode::eLinear; } FML_UNREACHABLE(); } constexpr vk::SamplerAddressMode ToVKSamplerAddressMode( SamplerAddressMode mode) { switch (mode) { case SamplerAddressMode::kRepeat: return vk::SamplerAddressMode::eRepeat; case SamplerAddressMode::kMirror: return vk::SamplerAddressMode::eMirroredRepeat; case SamplerAddressMode::kClampToEdge: return vk::SamplerAddressMode::eClampToEdge; case SamplerAddressMode::kDecal: return vk::SamplerAddressMode::eClampToBorder; } FML_UNREACHABLE(); } constexpr vk::ShaderStageFlags ToVkShaderStage(ShaderStage stage) { switch (stage) { case ShaderStage::kUnknown: return vk::ShaderStageFlagBits::eAll; case ShaderStage::kFragment: return vk::ShaderStageFlagBits::eFragment; case ShaderStage::kCompute: return vk::ShaderStageFlagBits::eCompute; case ShaderStage::kVertex: return vk::ShaderStageFlagBits::eVertex; } FML_UNREACHABLE(); } constexpr vk::DescriptorType ToVKDescriptorType(DescriptorType type) { switch (type) { case DescriptorType::kSampledImage: return vk::DescriptorType::eCombinedImageSampler; break; case DescriptorType::kUniformBuffer: return vk::DescriptorType::eUniformBuffer; break; case DescriptorType::kStorageBuffer: return vk::DescriptorType::eStorageBuffer; break; case DescriptorType::kImage: return vk::DescriptorType::eSampledImage; break; case DescriptorType::kSampler: return vk::DescriptorType::eSampler; break; case DescriptorType::kInputAttachment: return vk::DescriptorType::eInputAttachment; } FML_UNREACHABLE(); } constexpr vk::DescriptorSetLayoutBinding ToVKDescriptorSetLayoutBinding( const DescriptorSetLayout& layout) { vk::DescriptorSetLayoutBinding binding; binding.binding = layout.binding; binding.descriptorCount = 1u; binding.descriptorType = ToVKDescriptorType(layout.descriptor_type); binding.stageFlags = ToVkShaderStage(layout.shader_stage); return binding; } constexpr vk::AttachmentLoadOp ToVKAttachmentLoadOp(LoadAction load_action) { switch (load_action) { case LoadAction::kLoad: return vk::AttachmentLoadOp::eLoad; case LoadAction::kClear: return vk::AttachmentLoadOp::eClear; case LoadAction::kDontCare: return vk::AttachmentLoadOp::eDontCare; } FML_UNREACHABLE(); } constexpr vk::AttachmentStoreOp ToVKAttachmentStoreOp( StoreAction store_action) { switch (store_action) { case StoreAction::kStore: return vk::AttachmentStoreOp::eStore; case StoreAction::kDontCare: return vk::AttachmentStoreOp::eDontCare; case StoreAction::kMultisampleResolve: case StoreAction::kStoreAndMultisampleResolve: return vk::AttachmentStoreOp::eDontCare; } FML_UNREACHABLE(); } constexpr vk::IndexType ToVKIndexType(IndexType index_type) { switch (index_type) { case IndexType::k16bit: return vk::IndexType::eUint16; case IndexType::k32bit: return vk::IndexType::eUint32; case IndexType::kUnknown: return vk::IndexType::eUint32; case IndexType::kNone: FML_UNREACHABLE(); } FML_UNREACHABLE(); } constexpr vk::PolygonMode ToVKPolygonMode(PolygonMode mode) { switch (mode) { case PolygonMode::kFill: return vk::PolygonMode::eFill; case PolygonMode::kLine: return vk::PolygonMode::eLine; } FML_UNREACHABLE(); } constexpr vk::PrimitiveTopology ToVKPrimitiveTopology(PrimitiveType primitive) { switch (primitive) { case PrimitiveType::kTriangle: return vk::PrimitiveTopology::eTriangleList; case PrimitiveType::kTriangleStrip: return vk::PrimitiveTopology::eTriangleStrip; case PrimitiveType::kLine: return vk::PrimitiveTopology::eLineList; case PrimitiveType::kLineStrip: return vk::PrimitiveTopology::eLineStrip; case PrimitiveType::kPoint: return vk::PrimitiveTopology::ePointList; } FML_UNREACHABLE(); } constexpr bool PixelFormatIsDepthStencil(PixelFormat format) { switch (format) { case PixelFormat::kUnknown: case PixelFormat::kA8UNormInt: case PixelFormat::kR8UNormInt: case PixelFormat::kR8G8UNormInt: case PixelFormat::kR8G8B8A8UNormInt: case PixelFormat::kR8G8B8A8UNormIntSRGB: case PixelFormat::kB8G8R8A8UNormInt: case PixelFormat::kB8G8R8A8UNormIntSRGB: case PixelFormat::kR32G32B32A32Float: case PixelFormat::kR16G16B16A16Float: case PixelFormat::kB10G10R10XR: case PixelFormat::kB10G10R10XRSRGB: case PixelFormat::kB10G10R10A10XR: return false; case PixelFormat::kS8UInt: case PixelFormat::kD24UnormS8Uint: case PixelFormat::kD32FloatS8UInt: return true; } return false; } static constexpr vk::AttachmentReference kUnusedAttachmentReference = { VK_ATTACHMENT_UNUSED, vk::ImageLayout::eUndefined}; constexpr vk::CullModeFlags ToVKCullModeFlags(CullMode mode) { switch (mode) { case CullMode::kNone: return vk::CullModeFlagBits::eNone; case CullMode::kFrontFace: return vk::CullModeFlagBits::eFront; case CullMode::kBackFace: return vk::CullModeFlagBits::eBack; } FML_UNREACHABLE(); } constexpr vk::CompareOp ToVKCompareOp(CompareFunction op) { switch (op) { case CompareFunction::kNever: return vk::CompareOp::eNever; case CompareFunction::kAlways: return vk::CompareOp::eAlways; case CompareFunction::kLess: return vk::CompareOp::eLess; case CompareFunction::kEqual: return vk::CompareOp::eEqual; case CompareFunction::kLessEqual: return vk::CompareOp::eLessOrEqual; case CompareFunction::kGreater: return vk::CompareOp::eGreater; case CompareFunction::kNotEqual: return vk::CompareOp::eNotEqual; case CompareFunction::kGreaterEqual: return vk::CompareOp::eGreaterOrEqual; } FML_UNREACHABLE(); } constexpr vk::StencilOp ToVKStencilOp(StencilOperation op) { switch (op) { case StencilOperation::kKeep: return vk::StencilOp::eKeep; case StencilOperation::kZero: return vk::StencilOp::eZero; case StencilOperation::kSetToReferenceValue: return vk::StencilOp::eReplace; case StencilOperation::kIncrementClamp: return vk::StencilOp::eIncrementAndClamp; case StencilOperation::kDecrementClamp: return vk::StencilOp::eDecrementAndClamp; case StencilOperation::kInvert: return vk::StencilOp::eInvert; case StencilOperation::kIncrementWrap: return vk::StencilOp::eIncrementAndWrap; case StencilOperation::kDecrementWrap: return vk::StencilOp::eDecrementAndWrap; break; } FML_UNREACHABLE(); } constexpr vk::StencilOpState ToVKStencilOpState( const StencilAttachmentDescriptor& desc) { vk::StencilOpState state; state.failOp = ToVKStencilOp(desc.stencil_failure); state.passOp = ToVKStencilOp(desc.depth_stencil_pass); state.depthFailOp = ToVKStencilOp(desc.depth_failure); state.compareOp = ToVKCompareOp(desc.stencil_compare); state.compareMask = desc.read_mask; state.writeMask = desc.write_mask; // This is irrelevant as the stencil references are always dynamic state and // will be set in the render pass. state.reference = 1988; return state; } constexpr vk::ImageAspectFlags ToVKImageAspectFlags(PixelFormat format) { switch (format) { case PixelFormat::kUnknown: case PixelFormat::kA8UNormInt: case PixelFormat::kR8UNormInt: case PixelFormat::kR8G8UNormInt: case PixelFormat::kR8G8B8A8UNormInt: case PixelFormat::kR8G8B8A8UNormIntSRGB: case PixelFormat::kB8G8R8A8UNormInt: case PixelFormat::kB8G8R8A8UNormIntSRGB: case PixelFormat::kR32G32B32A32Float: case PixelFormat::kR16G16B16A16Float: case PixelFormat::kB10G10R10XR: case PixelFormat::kB10G10R10XRSRGB: case PixelFormat::kB10G10R10A10XR: return vk::ImageAspectFlagBits::eColor; case PixelFormat::kS8UInt: return vk::ImageAspectFlagBits::eStencil; case PixelFormat::kD24UnormS8Uint: case PixelFormat::kD32FloatS8UInt: return vk::ImageAspectFlagBits::eDepth | vk::ImageAspectFlagBits::eStencil; } FML_UNREACHABLE(); } constexpr uint32_t ToArrayLayerCount(TextureType type) { switch (type) { case TextureType::kTexture2D: case TextureType::kTexture2DMultisample: return 1u; case TextureType::kTextureCube: return 6u; case TextureType::kTextureExternalOES: VALIDATION_LOG << "kTextureExternalOES can not be used with the Vulkan backend."; } FML_UNREACHABLE(); } constexpr vk::ImageViewType ToVKImageViewType(TextureType type) { switch (type) { case TextureType::kTexture2D: case TextureType::kTexture2DMultisample: return vk::ImageViewType::e2D; case TextureType::kTextureCube: return vk::ImageViewType::eCube; case TextureType::kTextureExternalOES: VALIDATION_LOG << "kTextureExternalOES can not be used with the Vulkan backend."; } FML_UNREACHABLE(); } constexpr vk::ImageCreateFlags ToVKImageCreateFlags(TextureType type) { switch (type) { case TextureType::kTexture2D: case TextureType::kTexture2DMultisample: return {}; case TextureType::kTextureCube: return vk::ImageCreateFlagBits::eCubeCompatible; case TextureType::kTextureExternalOES: VALIDATION_LOG << "kTextureExternalOES can not be used with the Vulkan backend."; } FML_UNREACHABLE(); } vk::PipelineDepthStencilStateCreateInfo ToVKPipelineDepthStencilStateCreateInfo( std::optional<DepthAttachmentDescriptor> depth, std::optional<StencilAttachmentDescriptor> front, std::optional<StencilAttachmentDescriptor> back); constexpr vk::ImageAspectFlags ToImageAspectFlags(PixelFormat format) { switch (format) { case PixelFormat::kUnknown: return {}; case PixelFormat::kA8UNormInt: case PixelFormat::kR8UNormInt: case PixelFormat::kR8G8UNormInt: case PixelFormat::kR8G8B8A8UNormInt: case PixelFormat::kR8G8B8A8UNormIntSRGB: case PixelFormat::kB8G8R8A8UNormInt: case PixelFormat::kB8G8R8A8UNormIntSRGB: case PixelFormat::kR32G32B32A32Float: case PixelFormat::kR16G16B16A16Float: case PixelFormat::kB10G10R10XR: case PixelFormat::kB10G10R10XRSRGB: case PixelFormat::kB10G10R10A10XR: return vk::ImageAspectFlagBits::eColor; case PixelFormat::kS8UInt: return vk::ImageAspectFlagBits::eStencil; case PixelFormat::kD24UnormS8Uint: case PixelFormat::kD32FloatS8UInt: return vk::ImageAspectFlagBits::eDepth | vk::ImageAspectFlagBits::eStencil; } FML_UNREACHABLE(); } } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_FORMATS_VK_H_
engine/impeller/renderer/backend/vulkan/formats_vk.h/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/formats_vk.h", "repo_id": "engine", "token_count": 7533 }
357
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_RENDER_PASS_VK_H_ #define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_RENDER_PASS_VK_H_ #include "impeller/core/buffer_view.h" #include "impeller/renderer/backend/vulkan/context_vk.h" #include "impeller/renderer/backend/vulkan/pipeline_vk.h" #include "impeller/renderer/backend/vulkan/shared_object_vk.h" #include "impeller/renderer/command_buffer.h" #include "impeller/renderer/render_pass.h" #include "impeller/renderer/render_target.h" #include "vulkan/vulkan_handles.hpp" namespace impeller { class CommandBufferVK; class SamplerVK; class RenderPassVK final : public RenderPass { public: // |RenderPass| ~RenderPassVK() override; private: friend class CommandBufferVK; std::shared_ptr<CommandBufferVK> command_buffer_; std::string debug_label_; SharedHandleVK<vk::RenderPass> render_pass_; bool is_valid_ = false; vk::CommandBuffer command_buffer_vk_; std::shared_ptr<Texture> color_image_vk_; std::shared_ptr<Texture> resolve_image_vk_; // Per-command state. std::array<vk::DescriptorImageInfo, kMaxBindings> image_workspace_; std::array<vk::DescriptorBufferInfo, kMaxBindings> buffer_workspace_; std::array<vk::WriteDescriptorSet, kMaxBindings + kMaxBindings> write_workspace_; size_t bound_image_offset_ = 0u; size_t bound_buffer_offset_ = 0u; size_t descriptor_write_offset_ = 0u; size_t instance_count_ = 1u; size_t base_vertex_ = 0u; size_t vertex_count_ = 0u; bool has_index_buffer_ = false; bool has_label_ = false; std::shared_ptr<Pipeline<PipelineDescriptor>> pipeline_; bool pipeline_uses_input_attachments_ = false; std::shared_ptr<SamplerVK> immutable_sampler_; RenderPassVK(const std::shared_ptr<const Context>& context, const RenderTarget& target, std::shared_ptr<CommandBufferVK> command_buffer); // |RenderPass| void SetPipeline( const std::shared_ptr<Pipeline<PipelineDescriptor>>& pipeline) override; // |RenderPass| void SetCommandLabel(std::string_view label) override; // |RenderPass| void SetStencilReference(uint32_t value) override; // |RenderPass| void SetBaseVertex(uint64_t value) override; // |RenderPass| void SetViewport(Viewport viewport) override; // |RenderPass| void SetScissor(IRect scissor) override; // |RenderPass| void SetInstanceCount(size_t count) override; // |RenderPass| bool SetVertexBuffer(VertexBuffer buffer) override; // |RenderPass| fml::Status Draw() override; // |RenderPass| void ReserveCommands(size_t command_count) override {} // |ResourceBinder| bool BindResource(ShaderStage stage, DescriptorType type, const ShaderUniformSlot& slot, const ShaderMetadata& metadata, BufferView view) override; // |RenderPass| bool BindResource(ShaderStage stage, DescriptorType type, const ShaderUniformSlot& slot, const std::shared_ptr<const ShaderMetadata>& metadata, BufferView view) override; // |ResourceBinder| 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; bool BindResource(size_t binding, DescriptorType type, const BufferView& view); // |RenderPass| bool IsValid() const override; // |RenderPass| void OnSetLabel(std::string label) override; // |RenderPass| bool OnEncodeCommands(const Context& context) const override; SharedHandleVK<vk::RenderPass> CreateVKRenderPass( const ContextVK& context, const SharedHandleVK<vk::RenderPass>& recycled_renderpass, const std::shared_ptr<CommandBufferVK>& command_buffer) const; SharedHandleVK<vk::Framebuffer> CreateVKFramebuffer( const ContextVK& context, const vk::RenderPass& pass) const; RenderPassVK(const RenderPassVK&) = delete; RenderPassVK& operator=(const RenderPassVK&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_RENDER_PASS_VK_H_
engine/impeller/renderer/backend/vulkan/render_pass_vk.h/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/render_pass_vk.h", "repo_id": "engine", "token_count": 1769 }
358
Vulkan Swapchains ================= Contains implementations of swapchains for Window System Integration (WSI) on different platforms.
engine/impeller/renderer/backend/vulkan/swapchain/README.md/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/swapchain/README.md", "repo_id": "engine", "token_count": 28 }
359
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_TEXTURE_SOURCE_VK_H_ #define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_TEXTURE_SOURCE_VK_H_ #include "flutter/fml/status.h" #include "impeller/base/thread.h" #include "impeller/core/texture_descriptor.h" #include "impeller/renderer/backend/vulkan/barrier_vk.h" #include "impeller/renderer/backend/vulkan/formats_vk.h" #include "impeller/renderer/backend/vulkan/shared_object_vk.h" #include "impeller/renderer/backend/vulkan/vk.h" #include "impeller/renderer/backend/vulkan/yuv_conversion_vk.h" #include "vulkan/vulkan_handles.hpp" namespace impeller { //------------------------------------------------------------------------------ /// @brief Abstract base class that represents a vkImage and an /// vkImageView. /// /// This is intended to be used with an impeller::TextureVK. Example /// implementations represent swapchain images, uploaded textures, /// Android Hardware Buffer backend textures, etc... /// class TextureSourceVK { public: virtual ~TextureSourceVK(); //---------------------------------------------------------------------------- /// @brief Gets the texture descriptor for this image source. /// /// @warning Texture descriptors from texture sources whose capabilities /// are a superset of those that can be expressed with Vulkan /// (like Android Hardware Buffer) are inferred. Stuff like size, /// mip-counts, types is reliable. So use these descriptors as /// advisory. Creating copies of texture sources from these /// descriptors is usually not possible and depends on the /// allocator used. /// /// @return The texture descriptor. /// const TextureDescriptor& GetTextureDescriptor() const; //---------------------------------------------------------------------------- /// @brief Get the image handle for this texture source. /// /// @return The image. /// virtual vk::Image GetImage() const = 0; //---------------------------------------------------------------------------- /// @brief Retrieve the image view used for sampling/blitting/compute /// with this texture source. /// /// @return The image view. /// virtual vk::ImageView GetImageView() const = 0; //---------------------------------------------------------------------------- /// @brief Retrieve the image view used for render target attachments /// with this texture source. /// /// ImageViews used as render target attachments cannot have any /// mip levels. In cases where we want to generate mipmaps with /// the result of this texture, we need to create multiple image /// views. /// /// @return The render target view. /// virtual vk::ImageView GetRenderTargetView() const = 0; //---------------------------------------------------------------------------- /// @brief Encodes the layout transition `barrier` to /// `barrier.cmd_buffer` for the image. /// /// The transition is from the layout stored via /// `SetLayoutWithoutEncoding` to `barrier.new_layout`. /// /// @param[in] barrier The barrier. /// /// @return If the layout transition was successfully made. /// fml::Status SetLayout(const BarrierVK& barrier) const; //---------------------------------------------------------------------------- /// @brief Store the layout of the image. /// /// This just is bookkeeping on the CPU, to actually set the /// layout use `SetLayout`. /// /// @param[in] layout The new layout. /// /// @return The old layout. /// vk::ImageLayout SetLayoutWithoutEncoding(vk::ImageLayout layout) const; //---------------------------------------------------------------------------- /// @brief Get the last layout assigned to the TextureSourceVK. /// /// This value is synchronized with the GPU via SetLayout so it /// may not reflect the actual layout. /// /// @return The last known layout of the texture source. /// vk::ImageLayout GetLayout() const; //---------------------------------------------------------------------------- /// @brief When sampling from textures whose formats are not known to /// Vulkan, a custom conversion is necessary to setup custom /// samplers. This accessor provides this conversion if one is /// present. Most texture source have none. /// /// @return The sampler conversion. /// virtual std::shared_ptr<YUVConversionVK> GetYUVConversion() const; //---------------------------------------------------------------------------- /// @brief Determines if swapchain image. That is, an image used as the /// root render target. /// /// @return Whether or not this is a swapchain image. /// virtual bool IsSwapchainImage() const = 0; // These methods should only be used by render_pass_vk.h /// Store the last framebuffer object used with this texture. /// /// This field is only set if this texture is used as the resolve texture /// of a render pass. By construction, this framebuffer should be compatible /// with any future render passes. void SetCachedFramebuffer(const SharedHandleVK<vk::Framebuffer>& framebuffer); /// Store the last render pass object used with this texture. /// /// This field is only set if this texture is used as the resolve texture /// of a render pass. By construction, this framebuffer should be compatible /// with any future render passes. void SetCachedRenderPass(const SharedHandleVK<vk::RenderPass>& render_pass); /// Retrieve the last framebuffer object used with this texture. /// /// May be nullptr if no previous framebuffer existed. SharedHandleVK<vk::Framebuffer> GetCachedFramebuffer() const; /// Retrieve the last render pass object used with this texture. /// /// May be nullptr if no previous render pass existed. SharedHandleVK<vk::RenderPass> GetCachedRenderPass() const; protected: const TextureDescriptor desc_; explicit TextureSourceVK(TextureDescriptor desc); private: SharedHandleVK<vk::Framebuffer> framebuffer_; SharedHandleVK<vk::RenderPass> render_pass_; mutable RWMutex layout_mutex_; mutable vk::ImageLayout layout_ IPLR_GUARDED_BY(layout_mutex_) = vk::ImageLayout::eUndefined; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_TEXTURE_SOURCE_VK_H_
engine/impeller/renderer/backend/vulkan/texture_source_vk.h/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/texture_source_vk.h", "repo_id": "engine", "token_count": 2114 }
360
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/renderer/blit_pass.h" #include <memory> #include <utility> #include "impeller/base/strings.h" #include "impeller/base/validation.h" #include "impeller/core/formats.h" namespace impeller { BlitPass::BlitPass() {} BlitPass::~BlitPass() = default; void BlitPass::SetLabel(std::string label) { if (label.empty()) { return; } OnSetLabel(std::move(label)); } bool BlitPass::AddCopy(std::shared_ptr<Texture> source, std::shared_ptr<Texture> destination, std::optional<IRect> source_region, IPoint destination_origin, std::string label) { if (!source) { VALIDATION_LOG << "Attempted to add a texture blit with no source."; return false; } if (!destination) { VALIDATION_LOG << "Attempted to add a texture blit with no destination."; return false; } if (source->GetTextureDescriptor().sample_count != destination->GetTextureDescriptor().sample_count) { VALIDATION_LOG << SPrintF( "The source sample count (%d) must match the destination sample count " "(%d) for blits.", static_cast<int>(source->GetTextureDescriptor().sample_count), static_cast<int>(destination->GetTextureDescriptor().sample_count)); return false; } if (source->GetTextureDescriptor().format != destination->GetTextureDescriptor().format) { VALIDATION_LOG << SPrintF( "The source pixel format (%s) must match the destination pixel format " "(%s) " "for blits.", PixelFormatToString(source->GetTextureDescriptor().format), PixelFormatToString(destination->GetTextureDescriptor().format)); return false; } if (!source_region.has_value()) { source_region = IRect::MakeSize(source->GetSize()); } // Clip the source image. source_region = source_region->Intersection(IRect::MakeSize(source->GetSize())); if (!source_region.has_value()) { return true; // Nothing to blit. } // Clip the destination image. source_region = source_region->Intersection( IRect::MakeOriginSize(-destination_origin, destination->GetSize())); if (!source_region.has_value()) { return true; // Nothing to blit. } return OnCopyTextureToTextureCommand( std::move(source), std::move(destination), source_region.value(), destination_origin, std::move(label)); } bool BlitPass::AddCopy(std::shared_ptr<Texture> source, std::shared_ptr<DeviceBuffer> destination, std::optional<IRect> source_region, size_t destination_offset, std::string label) { if (!source) { VALIDATION_LOG << "Attempted to add a texture blit with no source."; return false; } if (!destination) { VALIDATION_LOG << "Attempted to add a texture blit with no destination."; return false; } if (!source_region.has_value()) { source_region = IRect::MakeSize(source->GetSize()); } auto bytes_per_pixel = BytesPerPixelForPixelFormat(source->GetTextureDescriptor().format); auto bytes_per_image = source_region->Area() * bytes_per_pixel; if (destination_offset + bytes_per_image > destination->GetDeviceBufferDescriptor().size) { VALIDATION_LOG << "Attempted to add a texture blit with out of bounds access."; return false; } // Clip the source image. source_region = source_region->Intersection(IRect::MakeSize(source->GetSize())); if (!source_region.has_value()) { return true; // Nothing to blit. } return OnCopyTextureToBufferCommand(std::move(source), std::move(destination), source_region.value(), destination_offset, std::move(label)); } bool BlitPass::AddCopy(BufferView source, std::shared_ptr<Texture> destination, IPoint destination_origin, std::string label) { if (!destination) { VALIDATION_LOG << "Attempted to add a texture blit with no destination."; return false; } auto bytes_per_pixel = BytesPerPixelForPixelFormat(destination->GetTextureDescriptor().format); auto bytes_per_image = destination->GetTextureDescriptor().size.Area() * bytes_per_pixel; if (source.range.length != bytes_per_image) { VALIDATION_LOG << "Attempted to add a texture blit with out of bounds access."; return false; } return OnCopyBufferToTextureCommand(std::move(source), std::move(destination), destination_origin, std::move(label)); } bool BlitPass::GenerateMipmap(std::shared_ptr<Texture> texture, std::string label) { if (!texture) { VALIDATION_LOG << "Attempted to add an invalid mipmap generation command " "with no texture."; return false; } return OnGenerateMipmapCommand(std::move(texture), std::move(label)); } } // namespace impeller
engine/impeller/renderer/blit_pass.cc/0
{ "file_path": "engine/impeller/renderer/blit_pass.cc", "repo_id": "engine", "token_count": 2052 }
361
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/renderer/compute_pipeline_descriptor.h" #include "impeller/core/formats.h" #include "impeller/renderer/shader_function.h" #include "impeller/renderer/shader_library.h" #include "impeller/renderer/vertex_descriptor.h" namespace impeller { ComputePipelineDescriptor::ComputePipelineDescriptor() = default; ComputePipelineDescriptor::~ComputePipelineDescriptor() = default; // Comparable<ComputePipelineDescriptor> std::size_t ComputePipelineDescriptor::GetHash() const { auto seed = fml::HashCombine(); fml::HashCombineSeed(seed, label_); if (entrypoint_) { fml::HashCombineSeed(seed, entrypoint_->GetHash()); } return seed; } // Comparable<ComputePipelineDescriptor> bool ComputePipelineDescriptor::IsEqual( const ComputePipelineDescriptor& other) const { return label_ == other.label_ && DeepComparePointer(entrypoint_, other.entrypoint_); } ComputePipelineDescriptor& ComputePipelineDescriptor::SetLabel( std::string label) { label_ = std::move(label); return *this; } ComputePipelineDescriptor& ComputePipelineDescriptor::SetStageEntrypoint( std::shared_ptr<const ShaderFunction> function) { FML_DCHECK(!function || function->GetStage() == ShaderStage::kCompute); if (!function || function->GetStage() != ShaderStage::kCompute) { return *this; } if (function->GetStage() == ShaderStage::kUnknown) { return *this; } entrypoint_ = std::move(function); return *this; } std::shared_ptr<const ShaderFunction> ComputePipelineDescriptor::GetStageEntrypoint() const { return entrypoint_; } const std::string& ComputePipelineDescriptor::GetLabel() const { return label_; } bool ComputePipelineDescriptor::RegisterDescriptorSetLayouts( const DescriptorSetLayout desc_set_layout[], size_t count) { descriptor_set_layouts_.reserve(descriptor_set_layouts_.size() + count); for (size_t i = 0; i < count; i++) { descriptor_set_layouts_.emplace_back(desc_set_layout[i]); } return true; } const std::vector<DescriptorSetLayout>& ComputePipelineDescriptor::GetDescriptorSetLayouts() const { return descriptor_set_layouts_; } } // namespace impeller
engine/impeller/renderer/compute_pipeline_descriptor.cc/0
{ "file_path": "engine/impeller/renderer/compute_pipeline_descriptor.cc", "repo_id": "engine", "token_count": 829 }
362
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <unordered_set> #include "flutter/testing/testing.h" #include "impeller/renderer/pipeline_descriptor.h" namespace impeller { namespace testing { TEST(PipelineDescriptorTest, PrimitiveTypeHashEquality) { PipelineDescriptor descA; PipelineDescriptor descB; ASSERT_TRUE(descA.IsEqual(descB)); ASSERT_EQ(descA.GetHash(), descB.GetHash()); descA.SetPrimitiveType(PrimitiveType::kTriangleStrip); ASSERT_FALSE(descA.IsEqual(descB)); ASSERT_NE(descA.GetHash(), descB.GetHash()); } } // namespace testing } // namespace impeller
engine/impeller/renderer/pipeline_descriptor_unittests.cc/0
{ "file_path": "engine/impeller/renderer/pipeline_descriptor_unittests.cc", "repo_id": "engine", "token_count": 249 }
363
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/renderer/shader_function.h" namespace impeller { ShaderFunction::ShaderFunction(UniqueID parent_library_id, std::string name, ShaderStage stage) : parent_library_id_(parent_library_id), name_(std::move(name)), stage_(stage) {} ShaderFunction::~ShaderFunction() = default; ShaderStage ShaderFunction::GetStage() const { return stage_; } const std::string& ShaderFunction::GetName() const { return name_; } // |Comparable<ShaderFunction>| std::size_t ShaderFunction::GetHash() const { return fml::HashCombine(parent_library_id_, name_, stage_); } // |Comparable<ShaderFunction>| bool ShaderFunction::IsEqual(const ShaderFunction& other) const { return parent_library_id_ == other.parent_library_id_ && name_ == other.name_ && stage_ == other.stage_; } } // namespace impeller
engine/impeller/renderer/shader_function.cc/0
{ "file_path": "engine/impeller/renderer/shader_function.cc", "repo_id": "engine", "token_count": 396 }
364
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_RENDERER_VERTEX_BUFFER_BUILDER_H_ #define FLUTTER_IMPELLER_RENDERER_VERTEX_BUFFER_BUILDER_H_ #include <initializer_list> #include <map> #include <vector> #include "flutter/fml/macros.h" #include "impeller/base/strings.h" #include "impeller/core/allocator.h" #include "impeller/core/device_buffer.h" #include "impeller/core/formats.h" #include "impeller/core/host_buffer.h" #include "impeller/core/vertex_buffer.h" #include "impeller/geometry/vector.h" namespace impeller { template <class VertexType_, class IndexType_ = uint16_t> class VertexBufferBuilder { public: using VertexType = VertexType_; using IndexType = IndexType_; VertexBufferBuilder() = default; ~VertexBufferBuilder() = default; constexpr impeller::IndexType GetIndexType() const { if (indices_.size() == 0) { return impeller::IndexType::kNone; } if constexpr (sizeof(IndexType) == 2) { return impeller::IndexType::k16bit; } if (sizeof(IndexType) == 4) { return impeller::IndexType::k32bit; } return impeller::IndexType::kUnknown; } void SetLabel(const std::string& label) { label_ = label; } void Reserve(size_t count) { return vertices_.reserve(count); } void ReserveIndices(size_t count) { return indices_.reserve(count); } bool HasVertices() const { return !vertices_.empty(); } size_t GetVertexCount() const { return vertices_.size(); } size_t GetIndexCount() const { return indices_.size() > 0 ? indices_.size() : vertices_.size(); } const VertexType& Last() const { FML_DCHECK(!vertices_.empty()); return vertices_.back(); } VertexBufferBuilder& AppendVertex(VertexType_ vertex) { vertices_.emplace_back(std::move(vertex)); return *this; } VertexBufferBuilder& AddVertices( std::initializer_list<VertexType_> vertices) { vertices_.reserve(vertices.size()); for (auto& vertex : vertices) { vertices_.emplace_back(std::move(vertex)); } return *this; } VertexBufferBuilder& AppendIndex(IndexType_ index) { indices_.emplace_back(index); return *this; } VertexBuffer CreateVertexBuffer(HostBuffer& host_buffer) const { VertexBuffer buffer; buffer.vertex_buffer = CreateVertexBufferView(host_buffer); buffer.index_buffer = CreateIndexBufferView(host_buffer); buffer.vertex_count = GetIndexCount(); buffer.index_type = GetIndexType(); return buffer; }; VertexBuffer CreateVertexBuffer(Allocator& device_allocator) const { VertexBuffer buffer; // This can be merged into a single allocation. buffer.vertex_buffer = CreateVertexBufferView(device_allocator); buffer.index_buffer = CreateIndexBufferView(device_allocator); buffer.vertex_count = GetIndexCount(); buffer.index_type = GetIndexType(); return buffer; }; void IterateVertices(const std::function<void(VertexType&)>& iterator) { for (auto& vertex : vertices_) { iterator(vertex); } } private: std::vector<VertexType> vertices_; std::vector<IndexType> indices_; std::string label_; BufferView CreateVertexBufferView(HostBuffer& buffer) const { return buffer.Emplace(vertices_.data(), vertices_.size() * sizeof(VertexType), alignof(VertexType)); } BufferView CreateVertexBufferView(Allocator& allocator) const { auto buffer = allocator.CreateBufferWithCopy( reinterpret_cast<const uint8_t*>(vertices_.data()), vertices_.size() * sizeof(VertexType)); if (!buffer) { return {}; } if (!label_.empty()) { buffer->SetLabel(SPrintF("%s Vertices", label_.c_str())); } return DeviceBuffer::AsBufferView(buffer); } std::vector<IndexType> CreateIndexBuffer() const { return indices_; } BufferView CreateIndexBufferView(HostBuffer& buffer) const { const auto index_buffer = CreateIndexBuffer(); if (index_buffer.size() == 0) { return {}; } return buffer.Emplace(index_buffer.data(), index_buffer.size() * sizeof(IndexType), alignof(IndexType)); } BufferView CreateIndexBufferView(Allocator& allocator) const { const auto index_buffer = CreateIndexBuffer(); if (index_buffer.size() == 0) { return {}; } auto buffer = allocator.CreateBufferWithCopy( reinterpret_cast<const uint8_t*>(index_buffer.data()), index_buffer.size() * sizeof(IndexType)); if (!buffer) { return {}; } if (!label_.empty()) { buffer->SetLabel(SPrintF("%s Indices", label_.c_str())); } return DeviceBuffer::AsBufferView(buffer); } }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_VERTEX_BUFFER_BUILDER_H_
engine/impeller/renderer/vertex_buffer_builder.h/0
{ "file_path": "engine/impeller/renderer/vertex_buffer_builder.h", "repo_id": "engine", "token_count": 1850 }
365
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_SCENE_ANIMATION_ANIMATION_CLIP_H_ #define FLUTTER_IMPELLER_SCENE_ANIMATION_ANIMATION_CLIP_H_ #include <memory> #include <unordered_map> #include <vector> #include "flutter/fml/macros.h" #include "impeller/scene/animation/animation.h" #include "impeller/scene/animation/animation_transforms.h" namespace impeller { namespace scene { class Node; class AnimationPlayer; class AnimationClip final { public: AnimationClip(std::shared_ptr<Animation> animation, Node* bind_target); ~AnimationClip(); AnimationClip(AnimationClip&&); AnimationClip& operator=(AnimationClip&&); bool IsPlaying() const; void SetPlaying(bool playing); void Play(); void Pause(); void Stop(); bool GetLoop() const; void SetLoop(bool looping); Scalar GetPlaybackTimeScale() const; /// @brief Sets the animation playback speed. Negative values make the clip /// play in reverse. void SetPlaybackTimeScale(Scalar playback_speed); Scalar GetWeight() const; void SetWeight(Scalar weight); /// @brief Get the current playback time of the animation. SecondsF GetPlaybackTime() const; /// @brief Move the animation to the specified time. The given `time` is /// clamped to the animation's playback range. void Seek(SecondsF time); /// @brief Advance the animation by `delta_time` seconds. Negative /// `delta_time` values do nothing. void Advance(SecondsF delta_time); /// @brief Applies the animation to all binded properties in the scene. void ApplyToBindings( std::unordered_map<Node*, AnimationTransforms>& transform_decomps, Scalar weight_multiplier) const; private: void BindToTarget(Node* node); struct ChannelBinding { const Animation::Channel& channel; Node* node; }; std::shared_ptr<Animation> animation_; std::vector<ChannelBinding> bindings_; SecondsF playback_time_; Scalar playback_time_scale_ = 1; // Seconds multiplier, can be negative. Scalar weight_ = 1; bool playing_ = false; bool loop_ = false; AnimationClip(const AnimationClip&) = delete; AnimationClip& operator=(const AnimationClip&) = delete; friend AnimationPlayer; }; } // namespace scene } // namespace impeller #endif // FLUTTER_IMPELLER_SCENE_ANIMATION_ANIMATION_CLIP_H_
engine/impeller/scene/animation/animation_clip.h/0
{ "file_path": "engine/impeller/scene/animation/animation_clip.h", "repo_id": "engine", "token_count": 804 }
366
// Copyright 2013 The Flutter 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; //----------------------------------------------------------------------------- /// Materials. /// struct Color { r: float; g: float; b: float; a: float; } enum ComponentType:byte { k8Bit, k16Bit, } table EmbeddedImage { bytes: [ubyte]; component_count: ubyte = 0; component_type: ComponentType; width: uint; height: uint; } /// The `bytes` field takes precedent over the `uri` field. /// If both the `uri` and `bytes` fields are empty, a fully opaque white /// placeholder will be used. table Texture { /// A Flutter asset URI for a compressed image file to import and decode. uri: string; /// Decompressed image bytes for uploading to the GPU. If this field is not /// empty, it takes precedent over the `uri` field for sourcing the texture. embedded_image: EmbeddedImage; } enum MaterialType:byte { kUnlit, kPhysicallyBased, } /// The final color of each material component is the texture color multiplied /// by the factor of the component. /// Texture fields are indices into the `Scene`->`textures` array. All textures /// are optional -- a texture index value of -1 indicates no texture. table Material { // When the `MaterialType` is `kUnlit`, only the `base_color` fields are used. type: MaterialType; base_color_factor: Color; base_color_texture: int = -1; metallic_factor: float = 0; roughness_factor: float = 0.5; metallic_roughness_texture: int = -1; // Red=Metallic, Green=Roughness. normal_texture: int = -1; // Tangent space normal map. occlusion_texture: int = -1; } //----------------------------------------------------------------------------- /// Geometry. /// struct Vec2 { x: float; y: float; } struct Vec3 { x: float; y: float; z: float; } struct Vec4 { x: float; y: float; z: float; w: float; } // This attribute layout is expected to be identical to that within // `impeller/scene/shaders/geometry.vert`. struct Vertex { position: Vec3; normal: Vec3; tangent: Vec4; // The 4th component determines the handedness of the tangent. texture_coords: Vec2; color: Color; } table UnskinnedVertexBuffer { vertices: [Vertex]; } struct SkinnedVertex { vertex: Vertex; /// Four joint indices corresponding to this mesh's skin transforms. These /// are floats instead of ints because this vertex data is uploaded directly /// to the GPU, and float attributes work for all Impeller backends. joints: Vec4; /// Four weight values that specify the influence of the corresponding /// joints. weights: Vec4; } table SkinnedVertexBuffer { vertices: [SkinnedVertex]; } union VertexBuffer { UnskinnedVertexBuffer, SkinnedVertexBuffer } enum IndexType:byte { k16Bit, k32Bit, } table Indices { data: [ubyte]; count: uint32; type: IndexType; } table MeshPrimitive { vertices: VertexBuffer; indices: Indices; material: Material; } //----------------------------------------------------------------------------- /// Animations. /// table TranslationKeyframes { values: [Vec3]; } table RotationKeyframes { values: [Vec4]; } table ScaleKeyframes { values: [Vec3]; } union Keyframes { TranslationKeyframes, RotationKeyframes, ScaleKeyframes } table Channel { node: int; // Index into `Scene`->`nodes`. timeline: [float]; keyframes: Keyframes; } table Animation { name: string; channels: [Channel]; } table Skin { joints: [int]; // Indices into `Scene`->`nodes`. inverse_bind_matrices: [Matrix]; /// The root joint of the skeleton. skeleton: int; // Index into `Scene`->`nodes`. } //----------------------------------------------------------------------------- /// Scene graph. /// struct Matrix { m: [float:16]; } table Node { name: string; children: [int]; // Indices into `Scene`->`nodes`. transform: Matrix; mesh_primitives: [MeshPrimitive]; skin: Skin; } table Scene { children: [int]; // Indices into `Scene`->`nodes`. transform: Matrix; nodes: [Node]; textures: [Texture]; // Textures may be reused across different materials. animations: [Animation]; } root_type Scene; file_identifier "IPSC";
engine/impeller/scene/importer/scene.fbs/0
{ "file_path": "engine/impeller/scene/importer/scene.fbs", "repo_id": "engine", "token_count": 1317 }
367
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/scene/scene_context.h" #include "impeller/core/formats.h" #include "impeller/core/host_buffer.h" #include "impeller/scene/material.h" #include "impeller/scene/shaders/skinned.vert.h" #include "impeller/scene/shaders/unlit.frag.h" #include "impeller/scene/shaders/unskinned.vert.h" namespace impeller { namespace scene { void SceneContextOptions::ApplyToPipelineDescriptor( const Capabilities& capabilities, PipelineDescriptor& desc) const { DepthAttachmentDescriptor depth; depth.depth_compare = CompareFunction::kLess; depth.depth_write_enabled = true; desc.SetDepthStencilAttachmentDescriptor(depth); desc.SetDepthPixelFormat(capabilities.GetDefaultDepthStencilFormat()); StencilAttachmentDescriptor stencil; stencil.stencil_compare = CompareFunction::kAlways; stencil.depth_stencil_pass = StencilOperation::kKeep; desc.SetStencilAttachmentDescriptors(stencil); desc.SetStencilPixelFormat(capabilities.GetDefaultDepthStencilFormat()); desc.SetSampleCount(sample_count); desc.SetPrimitiveType(primitive_type); desc.SetWindingOrder(WindingOrder::kCounterClockwise); desc.SetCullMode(CullMode::kBackFace); } SceneContext::SceneContext(std::shared_ptr<Context> context) : context_(std::move(context)) { if (!context_ || !context_->IsValid()) { return; } auto unskinned_variant = MakePipelineVariants<UnskinnedVertexShader, UnlitFragmentShader>( *context_); if (!unskinned_variant) { FML_LOG(ERROR) << "Could not create unskinned pipeline variant."; return; } pipelines_[{PipelineKey{GeometryType::kUnskinned, MaterialType::kUnlit}}] = std::move(unskinned_variant); auto skinned_variant = MakePipelineVariants<SkinnedVertexShader, UnlitFragmentShader>(*context_); if (!skinned_variant) { FML_LOG(ERROR) << "Could not create skinned pipeline variant."; return; } pipelines_[{PipelineKey{GeometryType::kSkinned, MaterialType::kUnlit}}] = std::move(skinned_variant); { impeller::TextureDescriptor texture_descriptor; texture_descriptor.storage_mode = impeller::StorageMode::kHostVisible; texture_descriptor.format = PixelFormat::kR8G8B8A8UNormInt; texture_descriptor.size = {1, 1}; texture_descriptor.mip_count = 1u; placeholder_texture_ = context_->GetResourceAllocator()->CreateTexture(texture_descriptor); placeholder_texture_->SetLabel("Placeholder Texture"); if (!placeholder_texture_) { FML_LOG(ERROR) << "Could not create placeholder texture."; return; } uint8_t pixel[] = {0xFF, 0xFF, 0xFF, 0xFF}; if (!placeholder_texture_->SetContents(pixel, 4)) { FML_LOG(ERROR) << "Could not set contents of placeholder texture."; return; } } host_buffer_ = HostBuffer::Create(GetContext()->GetResourceAllocator()); is_valid_ = true; } SceneContext::~SceneContext() = default; std::shared_ptr<Pipeline<PipelineDescriptor>> SceneContext::GetPipeline( PipelineKey key, SceneContextOptions opts) const { if (!IsValid()) { return nullptr; } if (auto found = pipelines_.find(key); found != pipelines_.end()) { return found->second->GetPipeline(*context_, opts); } return nullptr; } bool SceneContext::IsValid() const { return is_valid_; } std::shared_ptr<Context> SceneContext::GetContext() const { return context_; } std::shared_ptr<Texture> SceneContext::GetPlaceholderTexture() const { return placeholder_texture_; } } // namespace scene } // namespace impeller
engine/impeller/scene/scene_context.cc/0
{ "file_path": "engine/impeller/scene/scene_context.cc", "repo_id": "engine", "token_count": 1306 }
368
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_SHADER_ARCHIVE_MULTI_ARCH_SHADER_ARCHIVE_WRITER_H_ #define FLUTTER_IMPELLER_SHADER_ARCHIVE_MULTI_ARCH_SHADER_ARCHIVE_WRITER_H_ #include <map> #include "flutter/fml/macros.h" #include "flutter/fml/mapping.h" #include "impeller/shader_archive/shader_archive_types.h" namespace impeller { class MultiArchShaderArchiveWriter { public: MultiArchShaderArchiveWriter(); ~MultiArchShaderArchiveWriter(); [[nodiscard]] bool RegisterShaderArchive( ArchiveRenderingBackend backend, std::shared_ptr<const fml::Mapping> mapping); std::shared_ptr<fml::Mapping> CreateMapping() const; private: std::map<ArchiveRenderingBackend, std::shared_ptr<const fml::Mapping>> archives_; MultiArchShaderArchiveWriter(const MultiArchShaderArchiveWriter&) = delete; MultiArchShaderArchiveWriter& operator=(const MultiArchShaderArchiveWriter&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_SHADER_ARCHIVE_MULTI_ARCH_SHADER_ARCHIVE_WRITER_H_
engine/impeller/shader_archive/multi_arch_shader_archive_writer.h/0
{ "file_path": "engine/impeller/shader_archive/multi_arch_shader_archive_writer.h", "repo_id": "engine", "token_count": 433 }
369
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/tessellator/tessellator.h" #include "third_party/libtess2/Include/tesselator.h" namespace impeller { static void* HeapAlloc(void* userData, unsigned int size) { return malloc(size); } static void* HeapRealloc(void* userData, void* ptr, unsigned int size) { return realloc(ptr, size); } static void HeapFree(void* userData, void* ptr) { free(ptr); } // Note: these units are "number of entities" for bucket size and not in KB. static const TESSalloc kAlloc = { HeapAlloc, HeapRealloc, HeapFree, 0, /* =userData */ 16, /* =meshEdgeBucketSize */ 16, /* =meshVertexBucketSize */ 16, /* =meshFaceBucketSize */ 16, /* =dictNodeBucketSize */ 16, /* =regionBucketSize */ 0 /* =extraVertices */ }; Tessellator::Tessellator() : point_buffer_(std::make_unique<std::vector<Point>>()), c_tessellator_(nullptr, &DestroyTessellator) { point_buffer_->reserve(2048); TESSalloc alloc = kAlloc; { // libTess2 copies the TESSalloc despite the non-const argument. CTessellator tessellator(::tessNewTess(&alloc), &DestroyTessellator); c_tessellator_ = std::move(tessellator); } } Tessellator::~Tessellator() = default; static int ToTessWindingRule(FillType fill_type) { switch (fill_type) { case FillType::kOdd: return TESS_WINDING_ODD; case FillType::kNonZero: return TESS_WINDING_NONZERO; } return TESS_WINDING_ODD; } Tessellator::Result Tessellator::Tessellate(const Path& path, Scalar tolerance, const BuilderCallback& callback) { if (!callback) { return Result::kInputError; } point_buffer_->clear(); auto polyline = path.CreatePolyline(tolerance, std::move(point_buffer_), [this](Path::Polyline::PointBufferPtr point_buffer) { point_buffer_ = std::move(point_buffer); }); auto fill_type = path.GetFillType(); if (polyline.points->empty()) { return Result::kInputError; } auto tessellator = c_tessellator_.get(); if (!tessellator) { return Result::kTessellationError; } constexpr int kVertexSize = 2; constexpr int kPolygonSize = 3; //---------------------------------------------------------------------------- /// Feed contour information to the tessellator. /// static_assert(sizeof(Point) == 2 * sizeof(float)); for (size_t contour_i = 0; contour_i < polyline.contours.size(); contour_i++) { size_t start_point_index, end_point_index; std::tie(start_point_index, end_point_index) = polyline.GetContourPointBounds(contour_i); ::tessAddContour(tessellator, // the C tessellator kVertexSize, // polyline.points->data() + start_point_index, // sizeof(Point), // end_point_index - start_point_index // ); } //---------------------------------------------------------------------------- /// Let's tessellate. /// auto result = ::tessTesselate(tessellator, // tessellator ToTessWindingRule(fill_type), // winding TESS_POLYGONS, // element type kPolygonSize, // polygon size kVertexSize, // vertex size nullptr // normal (null is automatic) ); if (result != 1) { return Result::kTessellationError; } int element_item_count = tessGetElementCount(tessellator) * kPolygonSize; // We default to using a 16bit index buffer, but in cases where we generate // more tessellated data than this can contain we need to fall back to // dropping the index buffer entirely. Instead code could instead switch to // a uint32 index buffer, but this is done for simplicity with the other // fast path above. if (element_item_count < USHRT_MAX) { int vertex_item_count = tessGetVertexCount(tessellator); auto vertices = tessGetVertices(tessellator); auto elements = tessGetElements(tessellator); // libtess uses an int index internally due to usage of -1 as a sentinel // value. std::vector<uint16_t> indices(element_item_count); for (int i = 0; i < element_item_count; i++) { indices[i] = static_cast<uint16_t>(elements[i]); } if (!callback(vertices, vertex_item_count, indices.data(), element_item_count)) { return Result::kInputError; } } else { std::vector<Point> points; std::vector<float> data; int vertex_item_count = tessGetVertexCount(tessellator) * kVertexSize; auto vertices = tessGetVertices(tessellator); points.reserve(vertex_item_count); for (int i = 0; i < vertex_item_count; i += 2) { points.emplace_back(vertices[i], vertices[i + 1]); } int element_item_count = tessGetElementCount(tessellator) * kPolygonSize; auto elements = tessGetElements(tessellator); data.reserve(element_item_count); for (int i = 0; i < element_item_count; i++) { data.emplace_back(points[elements[i]].x); data.emplace_back(points[elements[i]].y); } if (!callback(data.data(), element_item_count, nullptr, 0u)) { return Result::kInputError; } } return Result::kSuccess; } Path::Polyline Tessellator::CreateTempPolyline(const Path& path, Scalar tolerance) { FML_DCHECK(point_buffer_); point_buffer_->clear(); auto polyline = path.CreatePolyline(tolerance, std::move(point_buffer_), [this](Path::Polyline::PointBufferPtr point_buffer) { point_buffer_ = std::move(point_buffer); }); return polyline; } std::vector<Point> Tessellator::TessellateConvex(const Path& path, Scalar tolerance) { FML_DCHECK(point_buffer_); std::vector<Point> output; point_buffer_->clear(); auto polyline = path.CreatePolyline(tolerance, std::move(point_buffer_), [this](Path::Polyline::PointBufferPtr point_buffer) { point_buffer_ = std::move(point_buffer); }); output.reserve(polyline.points->size() + (4 * (polyline.contours.size() - 1))); bool previous_contour_odd_points = false; for (auto j = 0u; j < polyline.contours.size(); j++) { auto [start, end] = polyline.GetContourPointBounds(j); auto first_point = polyline.GetPoint(start); // Some polygons will not self close and an additional triangle // must be inserted, others will self close and we need to avoid // inserting an extra triangle. if (polyline.GetPoint(end - 1) == first_point) { end--; } if (j > 0) { // Triangle strip break. output.emplace_back(output.back()); output.emplace_back(first_point); output.emplace_back(first_point); // If the contour has an odd number of points, insert an extra point when // bridging to the next contour to preserve the correct triangle winding // order. if (previous_contour_odd_points) { output.emplace_back(first_point); } } else { output.emplace_back(first_point); } size_t a = start + 1; size_t b = end - 1; while (a < b) { output.emplace_back(polyline.GetPoint(a)); output.emplace_back(polyline.GetPoint(b)); a++; b--; } if (a == b) { previous_contour_odd_points = false; output.emplace_back(polyline.GetPoint(a)); } else { previous_contour_odd_points = true; } } return output; } void DestroyTessellator(TESStesselator* tessellator) { if (tessellator != nullptr) { ::tessDeleteTess(tessellator); } } static constexpr int kPrecomputedDivisionCount = 1024; static int kPrecomputedDivisions[kPrecomputedDivisionCount] = { // clang-format off 1, 2, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 57, 57, 57, 57, 57, 57, 57, // clang-format on }; static size_t ComputeQuadrantDivisions(Scalar pixel_radius) { if (pixel_radius <= 0.0) { return 1; } int radius_index = ceil(pixel_radius); if (radius_index < kPrecomputedDivisionCount) { return kPrecomputedDivisions[radius_index]; } // For a circle with N divisions per quadrant, the maximum deviation of // the polgyon approximation from the true circle will be at the center // of the base of each triangular pie slice. We can compute that distance // by finding the midpoint of the line of the first slice and compare // its distance from the center of the circle to the radius. We will aim // to have the length of that bisector to be within |kCircleTolerance| // from the radius in pixels. // // Each vertex will appear at an angle of: // theta(i) = (kPi / 2) * (i / N) // for i in [0..N] // with each point falling at: // point(i) = r * (cos(theta), sin(theta)) // If we consider the unit circle to simplify the calculations below then // we need to scale the tolerance from its absolute quantity into a unit // circle fraction: // k = tolerance / radius // Using this scaled tolerance below to avoid multiplying by the radius // throughout all of the math, we have: // first point = (1, 0) // theta(0) == 0 // theta = kPi / 2 / N // theta(1) // second point = (cos(theta), sin(theta)) = (c, s) // midpoint = (first + second) * 0.5 = ((1 + c)/2, s/2) // |midpoint| = sqrt((1 + c)*(1 + c)/4 + s*s/4) // = sqrt((1 + c + c + c*c + s*s) / 4) // = sqrt((1 + 2c + 1) / 4) // = sqrt((2 + 2c) / 4) // = sqrt((1 + c) / 2) // = cos(theta / 2) // using half-angle cosine formula // error = 1 - |midpoint| = 1 - cos(theta / 2) // cos(theta/2) = 1 - error // theta/2 = acos(1 - error) // kPi / 2 / N / 2 = acos(1 - error) // kPi / 4 / acos(1 - error) = N // Since we need error <= k, we want divisions >= N, so we use: // N = ceil(kPi / 4 / acos(1 - k)) // // Math is confirmed in https://math.stackexchange.com/a/4132095 // (keeping in mind that we are computing quarter circle divisions here) // which also points out a performance optimization that is accurate // to within an over-estimation of 1 division would be: // N = ceil(kPi / 4 / sqrt(2 * k)) // Since we have precomputed the divisions for radii up to 1024, we can // afford to be more accurate using the acos formula here for larger radii. double k = Tessellator::kCircleTolerance / pixel_radius; return ceil(kPiOver4 / std::acos(1 - k)); } void Tessellator::Trigs::init(size_t divisions) { if (!trigs_.empty()) { return; } // Either not cached yet, or we are using the temp storage... trigs_.reserve(divisions + 1); double angle_scale = kPiOver2 / divisions; trigs_.emplace_back(1.0, 0.0); for (size_t i = 1; i < divisions; i++) { trigs_.emplace_back(Radians(i * angle_scale)); } trigs_.emplace_back(0.0, 1.0); } Tessellator::Trigs Tessellator::GetTrigsForDivisions(size_t divisions) { return divisions < Tessellator::kCachedTrigCount ? Trigs(precomputed_trigs_[divisions], divisions) : Trigs(divisions); } using TessellatedVertexProc = Tessellator::TessellatedVertexProc; using EllipticalVertexGenerator = Tessellator::EllipticalVertexGenerator; EllipticalVertexGenerator::EllipticalVertexGenerator( EllipticalVertexGenerator::GeneratorProc& generator, Trigs&& trigs, PrimitiveType triangle_type, size_t vertices_per_trig, Data&& data) : impl_(generator), trigs_(std::move(trigs)), data_(data), vertices_per_trig_(vertices_per_trig) {} EllipticalVertexGenerator Tessellator::FilledCircle( const Matrix& view_transform, const Point& center, Scalar radius) { auto divisions = ComputeQuadrantDivisions(view_transform.GetMaxBasisLength() * radius); return EllipticalVertexGenerator(Tessellator::GenerateFilledCircle, GetTrigsForDivisions(divisions), PrimitiveType::kTriangleStrip, 4, { .reference_centers = {center, center}, .radii = {radius, radius}, .half_width = -1.0f, }); } EllipticalVertexGenerator Tessellator::StrokedCircle( const Matrix& view_transform, const Point& center, Scalar radius, Scalar half_width) { if (half_width > 0) { auto divisions = ComputeQuadrantDivisions( view_transform.GetMaxBasisLength() * radius + half_width); return EllipticalVertexGenerator(Tessellator::GenerateStrokedCircle, GetTrigsForDivisions(divisions), PrimitiveType::kTriangleStrip, 8, { .reference_centers = {center, center}, .radii = {radius, radius}, .half_width = half_width, }); } else { return FilledCircle(view_transform, center, radius); } } EllipticalVertexGenerator Tessellator::RoundCapLine( const Matrix& view_transform, const Point& p0, const Point& p1, Scalar radius) { auto along = p1 - p0; auto length = along.GetLength(); if (length > kEhCloseEnough) { auto divisions = ComputeQuadrantDivisions(view_transform.GetMaxBasisLength() * radius); return EllipticalVertexGenerator(Tessellator::GenerateRoundCapLine, GetTrigsForDivisions(divisions), PrimitiveType::kTriangleStrip, 4, { .reference_centers = {p0, p1}, .radii = {radius, radius}, .half_width = -1.0f, }); } else { return FilledCircle(view_transform, p0, radius); } } EllipticalVertexGenerator Tessellator::FilledEllipse( const Matrix& view_transform, const Rect& bounds) { if (bounds.IsSquare()) { return FilledCircle(view_transform, bounds.GetCenter(), bounds.GetWidth() * 0.5f); } auto max_radius = bounds.GetSize().MaxDimension(); auto divisions = ComputeQuadrantDivisions(view_transform.GetMaxBasisLength() * max_radius); auto center = bounds.GetCenter(); return EllipticalVertexGenerator(Tessellator::GenerateFilledEllipse, GetTrigsForDivisions(divisions), PrimitiveType::kTriangleStrip, 4, { .reference_centers = {center, center}, .radii = bounds.GetSize() * 0.5f, .half_width = -1.0f, }); } EllipticalVertexGenerator Tessellator::FilledRoundRect( const Matrix& view_transform, const Rect& bounds, const Size& radii) { if (radii.width * 2 < bounds.GetWidth() || radii.height * 2 < bounds.GetHeight()) { auto max_radius = radii.MaxDimension(); auto divisions = ComputeQuadrantDivisions( view_transform.GetMaxBasisLength() * max_radius); auto upper_left = bounds.GetLeftTop() + radii; auto lower_right = bounds.GetRightBottom() - radii; return EllipticalVertexGenerator(Tessellator::GenerateFilledRoundRect, GetTrigsForDivisions(divisions), PrimitiveType::kTriangleStrip, 4, { .reference_centers = { upper_left, lower_right, }, .radii = radii, .half_width = -1.0f, }); } else { return FilledEllipse(view_transform, bounds); } } void Tessellator::GenerateFilledCircle( const Trigs& trigs, const EllipticalVertexGenerator::Data& data, const TessellatedVertexProc& proc) { auto center = data.reference_centers[0]; auto radius = data.radii.width; FML_DCHECK(center == data.reference_centers[1]); FML_DCHECK(radius == data.radii.height); FML_DCHECK(data.half_width < 0); // Quadrant 1 connecting with Quadrant 4: for (auto& trig : trigs) { auto offset = trig * radius; proc({center.x - offset.x, center.y + offset.y}); proc({center.x - offset.x, center.y - offset.y}); } // The second half of the circle should be iterated in reverse, but // we can instead iterate forward and swap the x/y values of the // offset as the angles should be symmetric and thus should generate // symmetrically reversed trig vectors. // Quadrant 2 connecting with Quadrant 2: for (auto& trig : trigs) { auto offset = trig * radius; proc({center.x + offset.y, center.y + offset.x}); proc({center.x + offset.y, center.y - offset.x}); } } void Tessellator::GenerateStrokedCircle( const Trigs& trigs, const EllipticalVertexGenerator::Data& data, const TessellatedVertexProc& proc) { auto center = data.reference_centers[0]; FML_DCHECK(center == data.reference_centers[1]); FML_DCHECK(data.radii.IsSquare()); FML_DCHECK(data.half_width > 0 && data.half_width < data.radii.width); auto outer_radius = data.radii.width + data.half_width; auto inner_radius = data.radii.width - data.half_width; // Zig-zag back and forth between points on the outer circle and the // inner circle. Both circles are evaluated at the same number of // quadrant divisions so the points for a given division should match // 1 for 1 other than their applied radius. // Quadrant 1: for (auto& trig : trigs) { auto outer = trig * outer_radius; auto inner = trig * inner_radius; proc({center.x - outer.x, center.y - outer.y}); proc({center.x - inner.x, center.y - inner.y}); } // The even quadrants of the circle should be iterated in reverse, but // we can instead iterate forward and swap the x/y values of the // offset as the angles should be symmetric and thus should generate // symmetrically reversed trig vectors. // Quadrant 2: for (auto& trig : trigs) { auto outer = trig * outer_radius; auto inner = trig * inner_radius; proc({center.x + outer.y, center.y - outer.x}); proc({center.x + inner.y, center.y - inner.x}); } // Quadrant 3: for (auto& trig : trigs) { auto outer = trig * outer_radius; auto inner = trig * inner_radius; proc({center.x + outer.x, center.y + outer.y}); proc({center.x + inner.x, center.y + inner.y}); } // Quadrant 4: for (auto& trig : trigs) { auto outer = trig * outer_radius; auto inner = trig * inner_radius; proc({center.x - outer.y, center.y + outer.x}); proc({center.x - inner.y, center.y + inner.x}); } } void Tessellator::GenerateRoundCapLine( const Trigs& trigs, const EllipticalVertexGenerator::Data& data, const TessellatedVertexProc& proc) { auto p0 = data.reference_centers[0]; auto p1 = data.reference_centers[1]; auto radius = data.radii.width; FML_DCHECK(radius == data.radii.height); FML_DCHECK(data.half_width < 0); auto along = p1 - p0; along *= radius / along.GetLength(); auto across = Point(-along.y, along.x); for (auto& trig : trigs) { auto relative_along = along * trig.cos; auto relative_across = across * trig.sin; proc(p0 - relative_along + relative_across); proc(p0 - relative_along - relative_across); } // The second half of the round caps should be iterated in reverse, but // we can instead iterate forward and swap the sin/cos values as they // should be symmetric. for (auto& trig : trigs) { auto relative_along = along * trig.sin; auto relative_across = across * trig.cos; proc(p1 + relative_along + relative_across); proc(p1 + relative_along - relative_across); } } void Tessellator::GenerateFilledEllipse( const Trigs& trigs, const EllipticalVertexGenerator::Data& data, const TessellatedVertexProc& proc) { auto center = data.reference_centers[0]; auto radii = data.radii; FML_DCHECK(center == data.reference_centers[1]); FML_DCHECK(data.half_width < 0); // Quadrant 1 connecting with Quadrant 4: for (auto& trig : trigs) { auto offset = trig * radii; proc({center.x - offset.x, center.y + offset.y}); proc({center.x - offset.x, center.y - offset.y}); } // The second half of the circle should be iterated in reverse, but // we can instead iterate forward and swap the x/y values of the // offset as the angles should be symmetric and thus should generate // symmetrically reversed trig vectors. // Quadrant 2 connecting with Quadrant 2: for (auto& trig : trigs) { auto offset = Point(trig.sin * radii.width, trig.cos * radii.height); proc({center.x + offset.x, center.y + offset.y}); proc({center.x + offset.x, center.y - offset.y}); } } void Tessellator::GenerateFilledRoundRect( const Trigs& trigs, const EllipticalVertexGenerator::Data& data, const TessellatedVertexProc& proc) { Scalar left = data.reference_centers[0].x; Scalar top = data.reference_centers[0].y; Scalar right = data.reference_centers[1].x; Scalar bottom = data.reference_centers[1].y; auto radii = data.radii; FML_DCHECK(data.half_width < 0); // Quadrant 1 connecting with Quadrant 4: for (auto& trig : trigs) { auto offset = trig * radii; proc({left - offset.x, bottom + offset.y}); proc({left - offset.x, top - offset.y}); } // The second half of the round rect should be iterated in reverse, but // we can instead iterate forward and swap the x/y values of the // offset as the angles should be symmetric and thus should generate // symmetrically reversed trig vectors. // Quadrant 2 connecting with Quadrant 2: for (auto& trig : trigs) { auto offset = Point(trig.sin * radii.width, trig.cos * radii.height); proc({right + offset.x, bottom + offset.y}); proc({right + offset.x, top - offset.y}); } } } // namespace impeller
engine/impeller/tessellator/tessellator.cc/0
{ "file_path": "engine/impeller/tessellator/tessellator.cc", "repo_id": "engine", "token_count": 12247 }
370
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_TOOLKIT_ANDROID_SURFACE_TRANSACTION_H_ #define FLUTTER_IMPELLER_TOOLKIT_ANDROID_SURFACE_TRANSACTION_H_ #include <functional> #include <map> #include "flutter/fml/unique_object.h" #include "impeller/geometry/color.h" #include "impeller/toolkit/android/proc_table.h" namespace impeller::android { class SurfaceControl; class HardwareBuffer; //------------------------------------------------------------------------------ /// @brief A wrapper for ASurfaceTransaction. /// https://developer.android.com/ndk/reference/group/native-activity#asurfacetransaction /// /// A surface transaction is a collection of updates to the /// hierarchy of surfaces (represented by `ASurfaceControl` /// instances) that are applied atomically in the compositor. /// /// This wrapper is only available on Android API 29 and above. /// /// @note Transactions should be short lived objects (create, apply, /// collect). But, if these are used on multiple threads, they must /// be externally synchronized. /// class SurfaceTransaction { public: //---------------------------------------------------------------------------- /// @return `true` if any surface transactions can be created on this /// platform. /// static bool IsAvailableOnPlatform(); SurfaceTransaction(); ~SurfaceTransaction(); SurfaceTransaction(const SurfaceTransaction&) = delete; SurfaceTransaction& operator=(const SurfaceTransaction&) = delete; bool IsValid() const; //---------------------------------------------------------------------------- /// @brief Encodes that the updated contents of a surface control are /// specified by the given hardware buffer. The update will not be /// committed till the call to `Apply` however. /// /// @see `SurfaceTransaction::Apply`. /// /// @param[in] control The control /// @param[in] buffer The hardware buffer /// /// @return If the update was encoded in the transaction. /// [[nodiscard]] bool SetContents(const SurfaceControl* control, const HardwareBuffer* buffer); //---------------------------------------------------------------------------- /// @brief Encodes the updated background color of the surface control. /// The update will not be committed till the call to `Apply` /// however. /// /// @see `SurfaceTransaction::Apply`. /// /// @param[in] control The control /// @param[in] color The color /// /// @return `true` if the background control will be set when transaction /// is applied. /// [[nodiscard]] bool SetBackgroundColor(const SurfaceControl& control, const Color& color); using OnCompleteCallback = std::function<void(void)>; //---------------------------------------------------------------------------- /// @brief Applies the updated encoded in the transaction and invokes the /// callback when the updated are complete. /// /// @warning The callback will be invoked on a system managed thread. /// /// @note It is fine to immediately destroy the transaction after the /// call to apply. It is not necessary to wait for transaction /// completion to collect the transaction handle. /// /// @param[in] callback The callback /// /// @return `true` if the surface transaction was applied. `true` does not /// indicate the application was completed however. Only the /// invocation of the callback denotes transaction completion. /// [[nodiscard]] bool Apply(OnCompleteCallback callback = nullptr); //---------------------------------------------------------------------------- /// @brief Set the new parent control of the given control. If the new /// parent is null, it is removed from the control hierarchy. /// /// @param[in] control The control /// @param[in] new_parent The new parent /// /// @return `true` if the control will be re-parented when the transaction /// is applied. /// [[nodiscard]] bool SetParent(const SurfaceControl& control, const SurfaceControl* new_parent = nullptr); private: struct UniqueASurfaceTransactionTraits { static ASurfaceTransaction* InvalidValue() { return nullptr; } static bool IsValid(ASurfaceTransaction* value) { return value != InvalidValue(); } static void Free(ASurfaceTransaction* value) { GetProcTable().ASurfaceTransaction_delete(value); } }; fml::UniqueObject<ASurfaceTransaction*, UniqueASurfaceTransactionTraits> transaction_; }; } // namespace impeller::android #endif // FLUTTER_IMPELLER_TOOLKIT_ANDROID_SURFACE_TRANSACTION_H_
engine/impeller/toolkit/android/surface_transaction.h/0
{ "file_path": "engine/impeller/toolkit/android/surface_transaction.h", "repo_id": "engine", "token_count": 1648 }
371
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/typographer/backends/skia/text_frame_skia.h" #include <vector> #include "flutter/fml/logging.h" #include "impeller/typographer/backends/skia/typeface_skia.h" #include "include/core/SkRect.h" #include "third_party/skia/include/core/SkFont.h" #include "third_party/skia/include/core/SkFontMetrics.h" #include "third_party/skia/src/core/SkStrikeSpec.h" // nogncheck #include "third_party/skia/src/core/SkTextBlobPriv.h" // nogncheck namespace impeller { static Font ToFont(const SkTextBlobRunIterator& run) { auto& font = run.font(); auto typeface = std::make_shared<TypefaceSkia>(font.refTypeface()); SkFontMetrics sk_metrics; font.getMetrics(&sk_metrics); Font::Metrics metrics; metrics.point_size = font.getSize(); metrics.embolden = font.isEmbolden(); metrics.skewX = font.getSkewX(); metrics.scaleX = font.getScaleX(); return Font{std::move(typeface), metrics}; } static Rect ToRect(const SkRect& rect) { return Rect::MakeLTRB(rect.fLeft, rect.fTop, rect.fRight, rect.fBottom); } static constexpr Scalar kScaleSize = 100000.0f; std::shared_ptr<TextFrame> MakeTextFrameFromTextBlobSkia( const sk_sp<SkTextBlob>& blob) { bool has_color = false; std::vector<TextRun> runs; for (SkTextBlobRunIterator run(blob.get()); !run.done(); run.next()) { // TODO(jonahwilliams): ask Skia for a public API to look this up. // https://github.com/flutter/flutter/issues/112005 SkStrikeSpec strikeSpec = SkStrikeSpec::MakeWithNoDevice(run.font()); SkBulkGlyphMetricsAndPaths paths{strikeSpec}; const auto glyph_count = run.glyphCount(); const auto* glyphs = run.glyphs(); switch (run.positioning()) { case SkTextBlobRunIterator::kFull_Positioning: { std::vector<SkRect> glyph_bounds; glyph_bounds.resize(glyph_count); SkFont font = run.font(); auto font_size = font.getSize(); // For some platforms (including Android), `SkFont::getBounds()` snaps // the computed bounds to integers. And so we scale up the font size // prior to fetching the bounds to ensure that the returned bounds are // always precise enough. font.setSize(kScaleSize); font.getBounds(glyphs, glyph_count, glyph_bounds.data(), nullptr); std::vector<TextRun::GlyphPosition> positions; positions.reserve(glyph_count); for (auto i = 0u; i < glyph_count; i++) { // kFull_Positioning has two scalars per glyph. const SkPoint* glyph_points = run.points(); const auto* point = glyph_points + i; Glyph::Type type = paths.glyph(glyphs[i])->isColor() ? Glyph::Type::kBitmap : Glyph::Type::kPath; has_color |= type == Glyph::Type::kBitmap; positions.emplace_back(TextRun::GlyphPosition{ Glyph{glyphs[i], type, ToRect(glyph_bounds[i]).Scale(font_size / kScaleSize)}, Point{point->x(), point->y()}}); } TextRun text_run(ToFont(run), positions); runs.emplace_back(text_run); break; } default: FML_DLOG(ERROR) << "Unimplemented."; continue; } } return std::make_shared<TextFrame>(runs, ToRect(blob->bounds()), has_color); } } // namespace impeller
engine/impeller/typographer/backends/skia/text_frame_skia.cc/0
{ "file_path": "engine/impeller/typographer/backends/skia/text_frame_skia.cc", "repo_id": "engine", "token_count": 1444 }
372
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_TYPOGRAPHER_FONT_H_ #define FLUTTER_IMPELLER_TYPOGRAPHER_FONT_H_ #include <memory> #include <optional> #include "flutter/fml/macros.h" #include "impeller/base/comparable.h" #include "impeller/typographer/glyph.h" #include "impeller/typographer/typeface.h" namespace impeller { //------------------------------------------------------------------------------ /// @brief Describes a typeface along with any modifications to its /// intrinsic properties. /// class Font : public Comparable<Font> { public: //---------------------------------------------------------------------------- /// @brief Describes the modifications made to the intrinsic properties /// of a typeface. /// /// The coordinate system of a font has its origin at (0, 0) on /// the baseline with an upper-left-origin coordinate system. /// struct Metrics { //-------------------------------------------------------------------------- /// The point size of the font. /// Scalar point_size = 12.0f; bool embolden = false; Scalar skewX = 0.0f; Scalar scaleX = 1.0f; constexpr bool operator==(const Metrics& o) const { return point_size == o.point_size && embolden == o.embolden && skewX == o.skewX && scaleX == o.scaleX; } }; Font(std::shared_ptr<Typeface> typeface, Metrics metrics); ~Font(); bool IsValid() const; //---------------------------------------------------------------------------- /// @brief The typeface whose intrinsic properties this font modifies. /// /// @return The typeface. /// const std::shared_ptr<Typeface>& GetTypeface() const; const Metrics& GetMetrics() const; // |Comparable<Font>| std::size_t GetHash() const override; // |Comparable<Font>| bool IsEqual(const Font& other) const override; private: std::shared_ptr<Typeface> typeface_; Metrics metrics_ = {}; bool is_valid_ = false; }; } // namespace impeller template <> struct std::hash<impeller::Font::Metrics> { constexpr std::size_t operator()(const impeller::Font::Metrics& m) const { return fml::HashCombine(m.point_size, m.skewX, m.scaleX); } }; #endif // FLUTTER_IMPELLER_TYPOGRAPHER_FONT_H_
engine/impeller/typographer/font.h/0
{ "file_path": "engine/impeller/typographer/font.h", "repo_id": "engine", "token_count": 818 }
373
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_TYPOGRAPHER_TYPEFACE_H_ #define FLUTTER_IMPELLER_TYPOGRAPHER_TYPEFACE_H_ #include "flutter/fml/macros.h" #include "impeller/base/comparable.h" #include "impeller/geometry/rect.h" namespace impeller { //------------------------------------------------------------------------------ /// @brief A typeface, usually obtained from a font-file, on disk describes /// the intrinsic properties of the font. Typefaces are rarely used /// directly. Instead, font refer to typefaces along with any /// modifications applied to its intrinsic properties. /// class Typeface : public Comparable<Typeface> { public: Typeface(); virtual ~Typeface(); virtual bool IsValid() const = 0; private: Typeface(const Typeface&) = delete; Typeface& operator=(const Typeface&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_TYPOGRAPHER_TYPEFACE_H_
engine/impeller/typographer/typeface.h/0
{ "file_path": "engine/impeller/typographer/typeface.h", "repo_id": "engine", "token_count": 353 }
374
// Copyright 2013 The Flutter Authors. 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/formats.h" namespace flutter { namespace gpu { // } // namespace gpu } // namespace flutter
engine/lib/gpu/formats.cc/0
{ "file_path": "engine/lib/gpu/formats.cc", "repo_id": "engine", "token_count": 89 }
375
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/lib/gpu/render_pass.h" #include "flutter/lib/gpu/formats.h" #include "flutter/lib/gpu/render_pipeline.h" #include "flutter/lib/gpu/shader.h" #include "fml/memory/ref_ptr.h" #include "impeller/core/buffer_view.h" #include "impeller/core/formats.h" #include "impeller/core/sampler_descriptor.h" #include "impeller/core/shader_types.h" #include "impeller/core/vertex_buffer.h" #include "impeller/geometry/color.h" #include "impeller/renderer/pipeline_library.h" #include "tonic/converter/dart_converter.h" namespace flutter { namespace gpu { IMPLEMENT_WRAPPERTYPEINFO(flutter_gpu, RenderPass); RenderPass::RenderPass() : vertex_buffer_( impeller::VertexBuffer{.index_type = impeller::IndexType::kNone}){}; RenderPass::~RenderPass() = default; const std::shared_ptr<const impeller::Context>& RenderPass::GetContext() const { return render_pass_->GetContext(); } impeller::Command& RenderPass::GetCommand() { return command_; } const impeller::Command& RenderPass::GetCommand() const { return command_; } impeller::RenderTarget& RenderPass::GetRenderTarget() { return render_target_; } const impeller::RenderTarget& RenderPass::GetRenderTarget() const { return render_target_; } impeller::ColorAttachmentDescriptor& RenderPass::GetColorAttachmentDescriptor( size_t color_attachment_index) { auto color = color_descriptors_.find(color_attachment_index); if (color == color_descriptors_.end()) { return color_descriptors_[color_attachment_index] = {}; } return color->second; } impeller::DepthAttachmentDescriptor& RenderPass::GetDepthAttachmentDescriptor() { return depth_desc_; } impeller::VertexBuffer& RenderPass::GetVertexBuffer() { return vertex_buffer_; } bool RenderPass::Begin(flutter::gpu::CommandBuffer& command_buffer) { render_pass_ = command_buffer.GetCommandBuffer()->CreateRenderPass(render_target_); if (!render_pass_) { return false; } command_buffer.AddRenderPass(render_pass_); return true; } void RenderPass::SetPipeline(fml::RefPtr<RenderPipeline> pipeline) { render_pipeline_ = std::move(pipeline); } std::shared_ptr<impeller::Pipeline<impeller::PipelineDescriptor>> RenderPass::GetOrCreatePipeline() { // Infer the pipeline layout based on the shape of the RenderTarget. auto pipeline_desc = pipeline_descriptor_; for (const auto& it : render_target_.GetColorAttachments()) { auto& color = GetColorAttachmentDescriptor(it.first); color.format = render_target_.GetRenderTargetPixelFormat(); } pipeline_desc.SetColorAttachmentDescriptors(color_descriptors_); { auto stencil = render_target_.GetStencilAttachment(); if (stencil && impeller::IsStencilWritable( stencil->texture->GetTextureDescriptor().format)) { pipeline_desc.SetStencilPixelFormat( stencil->texture->GetTextureDescriptor().format); pipeline_desc.SetStencilAttachmentDescriptors(stencil_front_desc_, stencil_back_desc_); } else { pipeline_desc.ClearStencilAttachments(); } } { auto depth = render_target_.GetDepthAttachment(); if (depth && impeller::IsDepthWritable( depth->texture->GetTextureDescriptor().format)) { pipeline_desc.SetDepthPixelFormat( depth->texture->GetTextureDescriptor().format); pipeline_desc.SetDepthStencilAttachmentDescriptor(depth_desc_); } else { pipeline_desc.ClearDepthAttachment(); } } auto& context = *GetContext(); render_pipeline_->BindToPipelineDescriptor(*context.GetShaderLibrary(), pipeline_desc); auto pipeline = context.GetPipelineLibrary()->GetPipeline(pipeline_desc).Get(); FML_DCHECK(pipeline) << "Couldn't resolve render pipeline"; return pipeline; } impeller::Command RenderPass::ProvisionRasterCommand() { impeller::Command result = command_; result.pipeline = GetOrCreatePipeline(); result.BindVertices(vertex_buffer_); return result; } bool RenderPass::Draw() { impeller::Command result = ProvisionRasterCommand(); #ifdef IMPELLER_DEBUG render_pass_->SetCommandLabel(result.label); #endif // IMPELLER_DEBUG render_pass_->SetPipeline(result.pipeline); render_pass_->SetStencilReference(result.stencil_reference); render_pass_->SetBaseVertex(result.base_vertex); if (result.viewport.has_value()) { render_pass_->SetViewport(result.viewport.value()); } if (result.scissor.has_value()) { render_pass_->SetScissor(result.scissor.value()); } render_pass_->SetVertexBuffer(result.vertex_buffer); for (const auto& buffer : result.vertex_bindings.buffers) { render_pass_->BindResource(impeller::ShaderStage::kVertex, impeller::DescriptorType::kUniformBuffer, buffer.slot, *buffer.view.GetMetadata(), buffer.view.resource); } for (const auto& texture : result.vertex_bindings.sampled_images) { render_pass_->BindResource(impeller::ShaderStage::kVertex, impeller::DescriptorType::kSampledImage, texture.slot, *texture.texture.GetMetadata(), texture.texture.resource, texture.sampler); } for (const auto& buffer : result.fragment_bindings.buffers) { render_pass_->BindResource(impeller::ShaderStage::kFragment, impeller::DescriptorType::kUniformBuffer, buffer.slot, *buffer.view.GetMetadata(), buffer.view.resource); } for (const auto& texture : result.fragment_bindings.sampled_images) { render_pass_->BindResource(impeller::ShaderStage::kFragment, impeller::DescriptorType::kSampledImage, texture.slot, *texture.texture.GetMetadata(), texture.texture.resource, texture.sampler); } return render_pass_->Draw().ok(); } } // namespace gpu } // namespace flutter static impeller::Color ToImpellerColor(uint32_t argb) { return impeller::Color::MakeRGBA8((argb >> 16) & 0xFF, // R (argb >> 8) & 0xFF, // G argb & 0xFF, // B argb >> 24); // A } //---------------------------------------------------------------------------- /// Exports /// void InternalFlutterGpu_RenderPass_Initialize(Dart_Handle wrapper) { auto res = fml::MakeRefCounted<flutter::gpu::RenderPass>(); res->AssociateWithDartWrapper(wrapper); } Dart_Handle InternalFlutterGpu_RenderPass_SetColorAttachment( flutter::gpu::RenderPass* wrapper, int color_attachment_index, int load_action, int store_action, int clear_color, flutter::gpu::Texture* texture, Dart_Handle resolve_texture_wrapper) { impeller::ColorAttachment desc; desc.load_action = flutter::gpu::ToImpellerLoadAction(load_action); desc.store_action = flutter::gpu::ToImpellerStoreAction(store_action); desc.clear_color = ToImpellerColor(static_cast<uint32_t>(clear_color)); desc.texture = texture->GetTexture(); if (!Dart_IsNull(resolve_texture_wrapper)) { flutter::gpu::Texture* resolve_texture = tonic::DartConverter<flutter::gpu::Texture*>::FromDart( resolve_texture_wrapper); desc.resolve_texture = resolve_texture->GetTexture(); } wrapper->GetRenderTarget().SetColorAttachment(desc, color_attachment_index); return Dart_Null(); } Dart_Handle InternalFlutterGpu_RenderPass_SetDepthStencilAttachment( flutter::gpu::RenderPass* wrapper, int depth_load_action, int depth_store_action, float depth_clear_value, int stencil_load_action, int stencil_store_action, int stencil_clear_value, flutter::gpu::Texture* texture) { { impeller::DepthAttachment desc; desc.load_action = flutter::gpu::ToImpellerLoadAction(depth_load_action); desc.store_action = flutter::gpu::ToImpellerStoreAction(depth_store_action); desc.clear_depth = depth_clear_value; desc.texture = texture->GetTexture(); wrapper->GetRenderTarget().SetDepthAttachment(desc); } { impeller::StencilAttachment desc; desc.load_action = flutter::gpu::ToImpellerLoadAction(stencil_load_action); desc.store_action = flutter::gpu::ToImpellerStoreAction(stencil_store_action); desc.clear_stencil = stencil_clear_value; desc.texture = texture->GetTexture(); wrapper->GetRenderTarget().SetStencilAttachment(desc); } return Dart_Null(); } Dart_Handle InternalFlutterGpu_RenderPass_Begin( flutter::gpu::RenderPass* wrapper, flutter::gpu::CommandBuffer* command_buffer) { if (!wrapper->Begin(*command_buffer)) { return tonic::ToDart("Failed to begin RenderPass"); } return Dart_Null(); } void InternalFlutterGpu_RenderPass_BindPipeline( flutter::gpu::RenderPass* wrapper, flutter::gpu::RenderPipeline* pipeline) { auto ref = fml::RefPtr<flutter::gpu::RenderPipeline>(pipeline); wrapper->SetPipeline(std::move(ref)); } template <typename TBuffer> static void BindVertexBuffer(flutter::gpu::RenderPass* wrapper, TBuffer buffer, int offset_in_bytes, int length_in_bytes, int vertex_count) { auto& vertex_buffer = wrapper->GetVertexBuffer(); vertex_buffer.vertex_buffer = impeller::BufferView{ .buffer = buffer, .range = impeller::Range(offset_in_bytes, length_in_bytes), }; // If the index type is set, then the `vertex_count` becomes the index // count... So don't overwrite the count if it's already been set when binding // the index buffer. // TODO(bdero): Consider just doing a more traditional API with // draw(vertexCount) and drawIndexed(indexCount). This is fine, // but overall it would be a bit more explicit and we wouldn't // have to document this behavior where the presence of the index // buffer always takes precedent. if (vertex_buffer.index_type == impeller::IndexType::kNone) { vertex_buffer.vertex_count = vertex_count; } } void InternalFlutterGpu_RenderPass_BindVertexBufferDevice( flutter::gpu::RenderPass* wrapper, flutter::gpu::DeviceBuffer* device_buffer, int offset_in_bytes, int length_in_bytes, int vertex_count) { BindVertexBuffer(wrapper, device_buffer->GetBuffer(), offset_in_bytes, length_in_bytes, vertex_count); } void InternalFlutterGpu_RenderPass_BindVertexBufferHost( flutter::gpu::RenderPass* wrapper, flutter::gpu::HostBuffer* host_buffer, int offset_in_bytes, int length_in_bytes, int vertex_count) { std::optional<impeller::BufferView> view = host_buffer->GetBufferViewForOffset(offset_in_bytes); if (!view.has_value()) { FML_LOG(ERROR) << "Failed to bind vertex buffer due to invalid HostBuffer offset: " << offset_in_bytes; return; } BindVertexBuffer(wrapper, view->buffer, view->range.offset, view->range.length, vertex_count); } template <typename TBuffer> static void BindIndexBuffer(flutter::gpu::RenderPass* wrapper, TBuffer buffer, int offset_in_bytes, int length_in_bytes, int index_type, int index_count) { auto& vertex_buffer = wrapper->GetVertexBuffer(); vertex_buffer.index_buffer = impeller::BufferView{ .buffer = buffer, .range = impeller::Range(offset_in_bytes, length_in_bytes), }; vertex_buffer.index_type = flutter::gpu::ToImpellerIndexType(index_type); vertex_buffer.vertex_count = index_count; } void InternalFlutterGpu_RenderPass_BindIndexBufferDevice( flutter::gpu::RenderPass* wrapper, flutter::gpu::DeviceBuffer* device_buffer, int offset_in_bytes, int length_in_bytes, int index_type, int index_count) { BindIndexBuffer(wrapper, device_buffer->GetBuffer(), offset_in_bytes, length_in_bytes, index_type, index_count); } void InternalFlutterGpu_RenderPass_BindIndexBufferHost( flutter::gpu::RenderPass* wrapper, flutter::gpu::HostBuffer* host_buffer, int offset_in_bytes, int length_in_bytes, int index_type, int index_count) { auto view = host_buffer->GetBufferViewForOffset(offset_in_bytes); if (!view.has_value()) { FML_LOG(ERROR) << "Failed to bind index buffer due to invalid HostBuffer offset: " << offset_in_bytes; return; } BindIndexBuffer(wrapper, view->buffer, view->range.offset, view->range.length, index_type, index_count); } template <typename TBuffer> static bool BindUniform(flutter::gpu::RenderPass* wrapper, flutter::gpu::Shader* shader, Dart_Handle uniform_name_handle, TBuffer buffer, int offset_in_bytes, int length_in_bytes) { auto& command = wrapper->GetCommand(); auto uniform_name = tonic::StdStringFromDart(uniform_name_handle); const flutter::gpu::Shader::UniformBinding* uniform_struct = shader->GetUniformStruct(uniform_name); // TODO(bdero): Return an error string stating that no uniform struct with // this name exists and throw an exception. if (!uniform_struct) { return false; } return command.BindResource( shader->GetShaderStage(), impeller::DescriptorType::kUniformBuffer, uniform_struct->slot, uniform_struct->metadata, impeller::BufferView{ .buffer = buffer, .range = impeller::Range(offset_in_bytes, length_in_bytes), }); } bool InternalFlutterGpu_RenderPass_BindUniformDevice( flutter::gpu::RenderPass* wrapper, flutter::gpu::Shader* shader, Dart_Handle uniform_name_handle, flutter::gpu::DeviceBuffer* device_buffer, int offset_in_bytes, int length_in_bytes) { return BindUniform(wrapper, shader, uniform_name_handle, device_buffer->GetBuffer(), offset_in_bytes, length_in_bytes); } bool InternalFlutterGpu_RenderPass_BindUniformHost( flutter::gpu::RenderPass* wrapper, flutter::gpu::Shader* shader, Dart_Handle uniform_name_handle, flutter::gpu::HostBuffer* host_buffer, int offset_in_bytes, int length_in_bytes) { auto view = host_buffer->GetBufferViewForOffset(offset_in_bytes); if (!view.has_value()) { FML_LOG(ERROR) << "Failed to bind index buffer due to invalid HostBuffer offset: " << offset_in_bytes; return false; } return BindUniform(wrapper, shader, uniform_name_handle, view->buffer, view->range.offset, view->range.length); } bool InternalFlutterGpu_RenderPass_BindTexture( flutter::gpu::RenderPass* wrapper, flutter::gpu::Shader* shader, Dart_Handle uniform_name_handle, flutter::gpu::Texture* texture, int min_filter, int mag_filter, int mip_filter, int width_address_mode, int height_address_mode) { auto& command = wrapper->GetCommand(); auto uniform_name = tonic::StdStringFromDart(uniform_name_handle); const impeller::SampledImageSlot* image_slot = shader->GetUniformTexture(uniform_name); // TODO(bdero): Return an error string stating that no uniform texture with // this name exists and throw an exception. if (!image_slot) { return false; } impeller::SamplerDescriptor sampler_desc; sampler_desc.min_filter = flutter::gpu::ToImpellerMinMagFilter(min_filter); sampler_desc.mag_filter = flutter::gpu::ToImpellerMinMagFilter(mag_filter); sampler_desc.mip_filter = flutter::gpu::ToImpellerMipFilter(mip_filter); sampler_desc.width_address_mode = flutter::gpu::ToImpellerSamplerAddressMode(width_address_mode); sampler_desc.height_address_mode = flutter::gpu::ToImpellerSamplerAddressMode(height_address_mode); const std::unique_ptr<const impeller::Sampler>& sampler = wrapper->GetContext()->GetSamplerLibrary()->GetSampler(sampler_desc); return command.BindResource( shader->GetShaderStage(), impeller::DescriptorType::kSampledImage, *image_slot, impeller::ShaderMetadata{}, texture->GetTexture(), sampler); } void InternalFlutterGpu_RenderPass_ClearBindings( flutter::gpu::RenderPass* wrapper) { auto& command = wrapper->GetCommand(); command.vertex_buffer = {}; command.vertex_bindings = {}; command.fragment_bindings = {}; } void InternalFlutterGpu_RenderPass_SetColorBlendEnable( flutter::gpu::RenderPass* wrapper, int color_attachment_index, bool enable) { auto& color = wrapper->GetColorAttachmentDescriptor(color_attachment_index); color.blending_enabled = enable; } void InternalFlutterGpu_RenderPass_SetColorBlendEquation( flutter::gpu::RenderPass* wrapper, int color_attachment_index, int color_blend_operation, int source_color_blend_factor, int destination_color_blend_factor, int alpha_blend_operation, int source_alpha_blend_factor, int destination_alpha_blend_factor) { auto& color = wrapper->GetColorAttachmentDescriptor(color_attachment_index); color.color_blend_op = flutter::gpu::ToImpellerBlendOperation(color_blend_operation); color.src_color_blend_factor = flutter::gpu::ToImpellerBlendFactor(source_color_blend_factor); color.dst_color_blend_factor = flutter::gpu::ToImpellerBlendFactor(destination_color_blend_factor); color.alpha_blend_op = flutter::gpu::ToImpellerBlendOperation(alpha_blend_operation); color.src_alpha_blend_factor = flutter::gpu::ToImpellerBlendFactor(source_alpha_blend_factor); color.dst_alpha_blend_factor = flutter::gpu::ToImpellerBlendFactor(destination_alpha_blend_factor); } void InternalFlutterGpu_RenderPass_SetDepthWriteEnable( flutter::gpu::RenderPass* wrapper, bool enable) { auto& depth = wrapper->GetDepthAttachmentDescriptor(); depth.depth_write_enabled = true; } void InternalFlutterGpu_RenderPass_SetDepthCompareOperation( flutter::gpu::RenderPass* wrapper, int compare_operation) { auto& depth = wrapper->GetDepthAttachmentDescriptor(); depth.depth_compare = flutter::gpu::ToImpellerCompareFunction(compare_operation); } bool InternalFlutterGpu_RenderPass_Draw(flutter::gpu::RenderPass* wrapper) { return wrapper->Draw(); }
engine/lib/gpu/render_pass.cc/0
{ "file_path": "engine/lib/gpu/render_pass.cc", "repo_id": "engine", "token_count": 7355 }
376
{ "comment:0": "NOTE: THIS FILE IS GENERATED. DO NOT EDIT.", "comment:1": "Instead modify 'flutter/lib/snapshot/libraries.yaml' and follow the instructions therein.", "flutter": { "include": [ { "path": "../../../third_party/dart/sdk/lib/libraries.json", "target": "vm_common" } ], "libraries": { "ui": { "uri": "../../lib/ui/ui.dart" } } } }
engine/lib/snapshot/libraries.json/0
{ "file_path": "engine/lib/snapshot/libraries.json", "repo_id": "engine", "token_count": 194 }
377
// Copyright 2013 The Flutter Authors. All 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_DART_RUNTIME_HOOKS_H_ #define FLUTTER_LIB_UI_DART_RUNTIME_HOOKS_H_ #include "flutter/fml/macros.h" #include "third_party/dart/runtime/include/dart_api.h" #include "third_party/tonic/dart_library_natives.h" namespace flutter { class DartRuntimeHooks { public: static void Install(bool is_ui_isolate, const std::string& script_uri); static void Logger_PrintDebugString(const std::string& message); static void Logger_PrintString(const std::string& message); static void ScheduleMicrotask(Dart_Handle closure); static Dart_Handle GetCallbackHandle(Dart_Handle func); static Dart_Handle GetCallbackFromHandle(int64_t handle); private: FML_DISALLOW_IMPLICIT_CONSTRUCTORS(DartRuntimeHooks); }; void DartPluginRegistrant_EnsureInitialized(); } // namespace flutter #endif // FLUTTER_LIB_UI_DART_RUNTIME_HOOKS_H_
engine/lib/ui/dart_runtime_hooks.h/0
{ "file_path": "engine/lib/ui/dart_runtime_hooks.h", "repo_id": "engine", "token_count": 348 }
378
[{"family":"Roboto","fonts":[{"asset":"Roboto-Medium.ttf"}]}]
engine/lib/ui/fixtures/FontManifest.json/0
{ "file_path": "engine/lib/ui/fixtures/FontManifest.json", "repo_id": "engine", "token_count": 23 }
379
#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; // clamp(x, a, b) is equivalent to min(max(x, a), b) void main() { fragColor = vec4(0.0, clamp(10.0, 0.0, a), 0.0, clamp(-1.0, a, 10.0)); }
engine/lib/ui/fixtures/shaders/supported_glsl_op_shaders/43_fclamp.frag/0
{ "file_path": "engine/lib/ui/fixtures/shaders/supported_glsl_op_shaders/43_fclamp.frag", "repo_id": "engine", "token_count": 152 }
380
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. part of dart.ui; // Examples can assume: // // ignore_for_file: deprecated_member_use // int foo = 0; // int bar = 0; // List<int> quux = <int>[]; // List<int>? thud; // int baz = 0; class _HashEnd { const _HashEnd(); } const _HashEnd _hashEnd = _HashEnd(); // ignore: avoid_classes_with_only_static_members /// Jenkins hash function, optimized for small integers. // // Borrowed from the dart sdk: sdk/lib/math/jenkins_smi_hash.dart. class _Jenkins { static int combine(int hash, Object? o) { assert(o is! Iterable); hash = 0x1fffffff & (hash + o.hashCode); hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10)); return hash ^ (hash >> 6); } static int finish(int hash) { hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3)); hash = hash ^ (hash >> 11); return 0x1fffffff & (hash + ((0x00003fff & hash) << 15)); } } /// Combine up to twenty objects' hash codes into one value. /// /// If you only need to handle one object's hash code, then just refer to its /// [Object.hashCode] getter directly. /// /// If you need to combine an arbitrary number of objects from a [List] or other /// [Iterable], use [hashList]. The output of [hashList] can be used as one of /// the arguments to this function. /// /// For example: /// /// ```dart /// int get hashCode => hashValues(foo, bar, hashList(quux), baz); /// ``` /// /// ## Deprecation /// /// This function has been replaced by [Object.hash], so that it can be used /// outside of Flutter as well. The new function is a drop-in replacement. /// /// The [hashList] function has also been replaced, [Object.hashAll] is the new /// function. The example above therefore is better written as: /// /// ```dart /// int get hashCode => Object.hash(foo, bar, Object.hashAll(quux), baz); /// ``` /// /// If a parameter is nullable, then it needs special handling, /// because [Object.hashAll]'s argument is not nullable: /// /// ```dart /// int get hashCode => Object.hash(foo, bar, thud == null ? null : Object.hashAll(thud!), baz); /// ``` @Deprecated( 'Use Object.hash() instead. ' 'This feature was deprecated in v3.1.0-0.0.pre.897' ) int hashValues( Object? arg01, Object? arg02, [ Object? arg03 = _hashEnd, Object? arg04 = _hashEnd, Object? arg05 = _hashEnd, Object? arg06 = _hashEnd, Object? arg07 = _hashEnd, Object? arg08 = _hashEnd, Object? arg09 = _hashEnd, Object? arg10 = _hashEnd, Object? arg11 = _hashEnd, Object? arg12 = _hashEnd, Object? arg13 = _hashEnd, Object? arg14 = _hashEnd, Object? arg15 = _hashEnd, Object? arg16 = _hashEnd, Object? arg17 = _hashEnd, Object? arg18 = _hashEnd, Object? arg19 = _hashEnd, Object? arg20 = _hashEnd ]) { int result = 0; result = _Jenkins.combine(result, arg01); result = _Jenkins.combine(result, arg02); if (!identical(arg03, _hashEnd)) { result = _Jenkins.combine(result, arg03); if (!identical(arg04, _hashEnd)) { result = _Jenkins.combine(result, arg04); if (!identical(arg05, _hashEnd)) { result = _Jenkins.combine(result, arg05); if (!identical(arg06, _hashEnd)) { result = _Jenkins.combine(result, arg06); if (!identical(arg07, _hashEnd)) { result = _Jenkins.combine(result, arg07); if (!identical(arg08, _hashEnd)) { result = _Jenkins.combine(result, arg08); if (!identical(arg09, _hashEnd)) { result = _Jenkins.combine(result, arg09); if (!identical(arg10, _hashEnd)) { result = _Jenkins.combine(result, arg10); if (!identical(arg11, _hashEnd)) { result = _Jenkins.combine(result, arg11); if (!identical(arg12, _hashEnd)) { result = _Jenkins.combine(result, arg12); if (!identical(arg13, _hashEnd)) { result = _Jenkins.combine(result, arg13); if (!identical(arg14, _hashEnd)) { result = _Jenkins.combine(result, arg14); if (!identical(arg15, _hashEnd)) { result = _Jenkins.combine(result, arg15); if (!identical(arg16, _hashEnd)) { result = _Jenkins.combine(result, arg16); if (!identical(arg17, _hashEnd)) { result = _Jenkins.combine(result, arg17); if (!identical(arg18, _hashEnd)) { result = _Jenkins.combine(result, arg18); if (!identical(arg19, _hashEnd)) { result = _Jenkins.combine(result, arg19); if (!identical(arg20, _hashEnd)) { result = _Jenkins.combine(result, arg20); // I can see my house from here! } } } } } } } } } } } } } } } } } } return _Jenkins.finish(result); } /// Combine the [Object.hashCode] values of an arbitrary number of objects from /// an [Iterable] into one value. This function will return the same value if /// given null as if given an empty list. /// /// ## Deprecation /// /// This function has been replaced by [Object.hashAll], so that it can be used /// outside of Flutter as well. The new function is a drop-in replacement, except /// that the argument must not be null. /// /// There is also a new function, [Object.hashAllUnordered], which is similar /// but returns the same hash code regardless of the order of the elements in /// the provided iterable. @Deprecated( 'Use Object.hashAll() or Object.hashAllUnordered() instead. ' 'This feature was deprecated in v3.1.0-0.0.pre.897' ) int hashList(Iterable<Object?>? arguments) { int result = 0; if (arguments != null) { for (final Object? argument in arguments) { result = _Jenkins.combine(result, argument); } } return _Jenkins.finish(result); }
engine/lib/ui/hash_codes.dart/0
{ "file_path": "engine/lib/ui/hash_codes.dart", "repo_id": "engine", "token_count": 2930 }
381
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_LIB_UI_PAINTING_CANVAS_H_ #define FLUTTER_LIB_UI_PAINTING_CANVAS_H_ #include "flutter/display_list/dl_blend_mode.h" #include "flutter/display_list/dl_op_flags.h" #include "flutter/lib/ui/dart_wrapper.h" #include "flutter/lib/ui/painting/path.h" #include "flutter/lib/ui/painting/picture.h" #include "flutter/lib/ui/painting/picture_recorder.h" #include "flutter/lib/ui/painting/rrect.h" #include "flutter/lib/ui/painting/vertices.h" #include "third_party/tonic/typed_data/typed_list.h" namespace flutter { class CanvasImage; class Canvas : public RefCountedDartWrappable<Canvas>, DisplayListOpFlags { DEFINE_WRAPPERTYPEINFO(); FML_FRIEND_MAKE_REF_COUNTED(Canvas); public: static void Create(Dart_Handle wrapper, PictureRecorder* recorder, double left, double top, double right, double bottom); ~Canvas() override; void save(); void saveLayerWithoutBounds(Dart_Handle paint_objects, Dart_Handle paint_data); void saveLayer(double left, double top, double right, double bottom, Dart_Handle paint_objects, Dart_Handle paint_data); void restore(); int getSaveCount(); void restoreToCount(int count); void translate(double dx, double dy); void scale(double sx, double sy); void rotate(double radians); void skew(double sx, double sy); void transform(const tonic::Float64List& matrix4); void getTransform(Dart_Handle matrix4_handle); void clipRect(double left, double top, double right, double bottom, DlCanvas::ClipOp clipOp, bool doAntiAlias = true); void clipRRect(const RRect& rrect, bool doAntiAlias = true); void clipPath(const CanvasPath* path, bool doAntiAlias = true); void getDestinationClipBounds(Dart_Handle rect_handle); void getLocalClipBounds(Dart_Handle rect_handle); void drawColor(SkColor color, DlBlendMode blend_mode); void drawLine(double x1, double y1, double x2, double y2, Dart_Handle paint_objects, Dart_Handle paint_data); void drawPaint(Dart_Handle paint_objects, Dart_Handle paint_data); void drawRect(double left, double top, double right, double bottom, Dart_Handle paint_objects, Dart_Handle paint_data); void drawRRect(const RRect& rrect, Dart_Handle paint_objects, Dart_Handle paint_data); void drawDRRect(const RRect& outer, const RRect& inner, Dart_Handle paint_objects, Dart_Handle paint_data); void drawOval(double left, double top, double right, double bottom, Dart_Handle paint_objects, Dart_Handle paint_data); void drawCircle(double x, double y, double radius, Dart_Handle paint_objects, Dart_Handle paint_data); void drawArc(double left, double top, double right, double bottom, double startAngle, double sweepAngle, bool useCenter, Dart_Handle paint_objects, Dart_Handle paint_data); void drawPath(const CanvasPath* path, Dart_Handle paint_objects, Dart_Handle paint_data); Dart_Handle drawImage(const CanvasImage* image, double x, double y, Dart_Handle paint_objects, Dart_Handle paint_data, int filterQualityIndex); Dart_Handle drawImageRect(const CanvasImage* image, double src_left, double src_top, double src_right, double src_bottom, double dst_left, double dst_top, double dst_right, double dst_bottom, Dart_Handle paint_objects, Dart_Handle paint_data, int filterQualityIndex); Dart_Handle drawImageNine(const CanvasImage* image, double center_left, double center_top, double center_right, double center_bottom, double dst_left, double dst_top, double dst_right, double dst_bottom, Dart_Handle paint_objects, Dart_Handle paint_data, int bitmapSamplingIndex); void drawPicture(Picture* picture); // The paint argument is first for the following functions because Paint // unwraps a number of C++ objects. Once we create a view unto a // Float32List, we cannot re-enter the VM to unwrap objects. That means we // either need to process the paint argument first. void drawPoints(Dart_Handle paint_objects, Dart_Handle paint_data, DlCanvas::PointMode point_mode, const tonic::Float32List& points); void drawVertices(const Vertices* vertices, DlBlendMode blend_mode, Dart_Handle paint_objects, Dart_Handle paint_data); Dart_Handle drawAtlas(Dart_Handle paint_objects, Dart_Handle paint_data, int filterQualityIndex, CanvasImage* atlas, Dart_Handle transforms_handle, Dart_Handle rects_handle, Dart_Handle colors_handle, DlBlendMode blend_mode, Dart_Handle cull_rect_handle); void drawShadow(const CanvasPath* path, SkColor color, double elevation, bool transparentOccluder); void Invalidate(); DisplayListBuilder* builder() { return display_list_builder_.get(); } private: explicit Canvas(sk_sp<DisplayListBuilder> builder); sk_sp<DisplayListBuilder> display_list_builder_; }; } // namespace flutter #endif // FLUTTER_LIB_UI_PAINTING_CANVAS_H_
engine/lib/ui/painting/canvas.h/0
{ "file_path": "engine/lib/ui/painting/canvas.h", "repo_id": "engine", "token_count": 3443 }
382
// Copyright 2013 The Flutter Authors. All 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_FRAGMENT_SHADER_H_ #define FLUTTER_LIB_UI_PAINTING_FRAGMENT_SHADER_H_ #include "flutter/lib/ui/dart_wrapper.h" #include "flutter/lib/ui/painting/fragment_program.h" #include "flutter/lib/ui/painting/image.h" #include "flutter/lib/ui/painting/image_shader.h" #include "flutter/lib/ui/painting/shader.h" #include "third_party/skia/include/core/SkShader.h" #include "third_party/skia/include/effects/SkRuntimeEffect.h" #include "third_party/tonic/dart_library_natives.h" #include "third_party/tonic/typed_data/typed_list.h" #include <string> #include <vector> namespace flutter { class FragmentProgram; class ReusableFragmentShader : public Shader { DEFINE_WRAPPERTYPEINFO(); FML_FRIEND_MAKE_REF_COUNTED(ReusableFragmentShader); public: ~ReusableFragmentShader() override; static Dart_Handle Create(Dart_Handle wrapper, Dart_Handle program, Dart_Handle float_count, Dart_Handle sampler_count); void SetImageSampler(Dart_Handle index, Dart_Handle image); bool ValidateSamplers(); void Dispose(); // |Shader| std::shared_ptr<DlColorSource> shader(DlImageSampling) override; private: ReusableFragmentShader(fml::RefPtr<FragmentProgram> program, uint64_t float_count, uint64_t sampler_count); fml::RefPtr<FragmentProgram> program_; sk_sp<SkData> uniform_data_; std::vector<std::shared_ptr<DlColorSource>> samplers_; size_t float_count_; }; } // namespace flutter #endif // FLUTTER_LIB_UI_PAINTING_FRAGMENT_SHADER_H_
engine/lib/ui/painting/fragment_shader.h/0
{ "file_path": "engine/lib/ui/painting/fragment_shader.h", "repo_id": "engine", "token_count": 741 }
383
// Copyright 2013 The Flutter 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/common/task_runners.h" #include "flutter/fml/synchronization/count_down_latch.h" #include "flutter/fml/synchronization/waitable_event.h" #include "flutter/lib/ui/painting/canvas.h" #include "flutter/lib/ui/painting/image.h" #include "flutter/lib/ui/painting/picture.h" #include "flutter/lib/ui/painting/picture_recorder.h" #include "flutter/runtime/dart_vm.h" #include "flutter/shell/common/shell_test.h" #include "flutter/shell/common/thread_host.h" #include "flutter/testing/testing.h" namespace flutter { namespace testing { class ImageDisposeTest : public ShellTest { public: template <class T> T* GetNativePeer(Dart_Handle handle) { intptr_t peer = 0; auto native_handle = Dart_GetNativeInstanceField( handle, tonic::DartWrappable::kPeerIndex, &peer); EXPECT_FALSE(Dart_IsError(native_handle)) << Dart_GetError(native_handle); return reinterpret_cast<T*>(peer); } // Used to wait on Dart callbacks or Shell task runner flushing fml::AutoResetWaitableEvent message_latch_; sk_sp<DisplayList> current_display_list_; sk_sp<DlImage> current_image_; }; TEST_F(ImageDisposeTest, ImageReleasedAfterFrameAndDisposePictureAndLayer) { auto native_capture_image_and_picture = [&](Dart_NativeArguments args) { auto image_handle = Dart_GetNativeArgument(args, 0); auto native_image_handle = Dart_GetField(image_handle, Dart_NewStringFromCString("_image")); ASSERT_FALSE(Dart_IsError(native_image_handle)) << Dart_GetError(native_image_handle); ASSERT_FALSE(Dart_IsNull(native_image_handle)); CanvasImage* image = GetNativePeer<CanvasImage>(native_image_handle); Picture* picture = GetNativePeer<Picture>(Dart_GetNativeArgument(args, 1)); ASSERT_FALSE(image->image()->unique()); ASSERT_FALSE(picture->display_list()->unique()); current_display_list_ = picture->display_list(); current_image_ = image->image(); }; auto native_finish = [&](Dart_NativeArguments args) { message_latch_.Signal(); }; Settings settings = CreateSettingsForFixture(); fml::CountDownLatch frame_latch{2}; settings.frame_rasterized_callback = [&frame_latch](const FrameTiming& t) { frame_latch.CountDown(); }; auto task_runner = CreateNewThread(); TaskRunners task_runners("test", // label GetCurrentTaskRunner(), // platform task_runner, // raster task_runner, // ui task_runner // io ); AddNativeCallback("CaptureImageAndPicture", CREATE_NATIVE_ENTRY(native_capture_image_and_picture)); AddNativeCallback("Finish", CREATE_NATIVE_ENTRY(native_finish)); std::unique_ptr<Shell> shell = CreateShell(settings, task_runners); ASSERT_TRUE(shell->IsSetup()); SetViewportMetrics(shell.get(), 800, 600); shell->GetPlatformView()->NotifyCreated(); auto configuration = RunConfiguration::InferFromSettings(settings); configuration.SetEntrypoint("pumpImage"); shell->RunEngine(std::move(configuration), [&](auto result) { ASSERT_EQ(result, Engine::RunStatus::Success); }); message_latch_.Wait(); ASSERT_TRUE(current_display_list_); ASSERT_TRUE(current_image_); // Wait for 2 frames to be rasterized. The 2nd frame releases resources of the // 1st frame. frame_latch.Wait(); // Force a drain the SkiaUnrefQueue. The engine does this normally as frames // pump, but we force it here to make the test more deterministic. message_latch_.Reset(); task_runner->PostTask([&, io_manager = shell->GetIOManager()]() { io_manager->GetSkiaUnrefQueue()->Drain(); message_latch_.Signal(); }); message_latch_.Wait(); if (current_display_list_) { EXPECT_TRUE(current_display_list_->unique()); current_display_list_.reset(); } EXPECT_TRUE(current_image_->unique()); current_image_.reset(); shell->GetPlatformView()->NotifyDestroyed(); DestroyShell(std::move(shell), task_runners); } } // namespace testing } // namespace flutter
engine/lib/ui/painting/image_dispose_unittests.cc/0
{ "file_path": "engine/lib/ui/painting/image_dispose_unittests.cc", "repo_id": "engine", "token_count": 1594 }
384
// Copyright 2013 The Flutter Authors. All 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_GENERATOR_REGISTRY_H_ #define FLUTTER_LIB_UI_PAINTING_IMAGE_GENERATOR_REGISTRY_H_ #include <functional> #include <set> #include "flutter/fml/mapping.h" #include "flutter/fml/memory/weak_ptr.h" #include "flutter/lib/ui/painting/image_generator.h" namespace flutter { /// @brief `ImageGeneratorFactory` is the top level primitive for specifying an /// image decoder in Flutter. When called, it should return an /// `ImageGenerator` that typically compatible with the given input /// data. using ImageGeneratorFactory = std::function<std::shared_ptr<ImageGenerator>(sk_sp<SkData> buffer)>; /// @brief Keeps a priority-ordered registry of image generator builders to be /// used when decoding images. This object must be created, accessed, and /// collected on the UI thread (typically the engine or its runtime /// controller). class ImageGeneratorRegistry { public: ImageGeneratorRegistry(); ~ImageGeneratorRegistry(); /// @brief Install a new factory for image generators /// @param[in] factory Callback that produces `ImageGenerator`s for /// compatible input data. /// @param[in] priority The priority used to determine the order in which /// factories are tried. Higher values mean higher /// priority. The built-in Skia decoders are installed /// at priority 0, and so a priority > 0 takes precedent /// over the builtin decoders. When multiple decoders /// are added with the same priority, those which are /// added earlier take precedent. /// @see `CreateCompatibleGenerator` void AddFactory(ImageGeneratorFactory factory, int32_t priority); /// @brief Walks the list of image generator builders in descending /// priority order until a compatible `ImageGenerator` is able to /// be built. This method is safe to perform on the UI thread, as /// checking for `ImageGenerator` compatibility is expected to be /// a lightweight operation. The returned `ImageGenerator` can /// then be used to fully decode the image on e.g. the IO thread. /// @param[in] buffer The raw encoded image data. /// @return An `ImageGenerator` that is compatible with the input buffer. /// If no compatible `ImageGenerator` type was found, then /// `std::shared_ptr<ImageGenerator>(nullptr)` is returned. /// @see `ImageGenerator` std::shared_ptr<ImageGenerator> CreateCompatibleGenerator( const sk_sp<SkData>& buffer); fml::WeakPtr<ImageGeneratorRegistry> GetWeakPtr() const; private: struct PrioritizedFactory { ImageGeneratorFactory callback; int32_t priority = 0; // Used as a fallback priority comparison when equal. size_t ascending_nonce = 0; }; struct Compare { constexpr bool operator()(const PrioritizedFactory& lhs, const PrioritizedFactory& rhs) const { // When priorities are equal, factories registered earlier take // precedent. if (lhs.priority == rhs.priority) { return lhs.ascending_nonce < rhs.ascending_nonce; } // Order by descending priority. return lhs.priority > rhs.priority; } }; using FactorySet = std::set<PrioritizedFactory, Compare>; FactorySet image_generator_factories_; size_t nonce_; fml::WeakPtrFactory<ImageGeneratorRegistry> weak_factory_; }; } // namespace flutter #endif // FLUTTER_LIB_UI_PAINTING_IMAGE_GENERATOR_REGISTRY_H_
engine/lib/ui/painting/image_generator_registry.h/0
{ "file_path": "engine/lib/ui/painting/image_generator_registry.h", "repo_id": "engine", "token_count": 1409 }
385
// Copyright 2013 The Flutter Authors. All 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_PATH_MEASURE_H_ #define FLUTTER_LIB_UI_PAINTING_PATH_MEASURE_H_ #include <vector> #include "flutter/lib/ui/dart_wrapper.h" #include "flutter/lib/ui/painting/path.h" #include "third_party/skia/include/core/SkContourMeasure.h" #include "third_party/skia/include/core/SkPath.h" #include "third_party/tonic/typed_data/typed_list.h" // Be sure that the client doesn't modify a path on us before Skia finishes // See AOSP's reasoning in PathMeasure.cpp namespace flutter { class CanvasPathMeasure : public RefCountedDartWrappable<CanvasPathMeasure> { DEFINE_WRAPPERTYPEINFO(); FML_FRIEND_MAKE_REF_COUNTED(CanvasPathMeasure); public: ~CanvasPathMeasure() override; static void Create(Dart_Handle wrapper, const CanvasPath* path, bool forceClosed); void setPath(const CanvasPath* path, bool isClosed); double getLength(int contour_index); tonic::Float32List getPosTan(int contour_index, double distance); void getSegment(Dart_Handle path_handle, int contour_index, double start_d, double stop_d, bool start_with_move_to); bool isClosed(int contour_index); bool nextContour(); const SkContourMeasureIter& pathMeasure() const { return *path_measure_; } private: CanvasPathMeasure(); std::unique_ptr<SkContourMeasureIter> path_measure_; std::vector<sk_sp<SkContourMeasure>> measures_; }; } // namespace flutter #endif // FLUTTER_LIB_UI_PAINTING_PATH_MEASURE_H_
engine/lib/ui/painting/path_measure.h/0
{ "file_path": "engine/lib/ui/painting/path_measure.h", "repo_id": "engine", "token_count": 663 }
386
// Copyright 2013 The Flutter Authors. 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/single_frame_codec.h" #include <memory> #include "flutter/common/task_runners.h" #include "flutter/fml/synchronization/waitable_event.h" #include "flutter/runtime/dart_vm.h" #include "flutter/shell/common/shell_test.h" #include "flutter/shell/common/thread_host.h" #include "flutter/testing/testing.h" namespace flutter { namespace testing { TEST_F(ShellTest, SingleFrameCodecAccuratelyReportsSize) { auto message_latch = std::make_shared<fml::AutoResetWaitableEvent>(); auto validate_codec = [](Dart_NativeArguments args) { auto handle = Dart_GetNativeArgument(args, 0); intptr_t peer = 0; Dart_Handle result = Dart_GetNativeInstanceField( handle, tonic::DartWrappable::kPeerIndex, &peer); ASSERT_FALSE(Dart_IsError(result)); }; auto finish = [message_latch](Dart_NativeArguments args) { message_latch->Signal(); }; Settings settings = CreateSettingsForFixture(); TaskRunners task_runners("test", // label GetCurrentTaskRunner(), // platform CreateNewThread(), // raster CreateNewThread(), // ui CreateNewThread() // io ); AddNativeCallback("ValidateCodec", CREATE_NATIVE_ENTRY(validate_codec)); AddNativeCallback("Finish", CREATE_NATIVE_ENTRY(finish)); std::unique_ptr<Shell> shell = CreateShell(settings, task_runners); ASSERT_TRUE(shell->IsSetup()); auto configuration = RunConfiguration::InferFromSettings(settings); configuration.SetEntrypoint("createSingleFrameCodec"); shell->RunEngine(std::move(configuration), [](auto result) { ASSERT_EQ(result, Engine::RunStatus::Success); }); message_latch->Wait(); DestroyShell(std::move(shell), task_runners); } } // namespace testing } // namespace flutter
engine/lib/ui/painting/single_frame_codec_unittests.cc/0
{ "file_path": "engine/lib/ui/painting/single_frame_codec_unittests.cc", "repo_id": "engine", "token_count": 766 }
387
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/lib/ui/semantics/semantics_update_builder.h" #include <utility> #include "flutter/lib/ui/floating_point.h" #include "flutter/lib/ui/ui_dart_state.h" #include "third_party/skia/include/core/SkScalar.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 { void pushStringAttributes( StringAttributes& destination, const std::vector<NativeStringAttribute*>& native_attributes) { for (const auto& native_attribute : native_attributes) { destination.push_back(native_attribute->GetAttribute()); } } IMPLEMENT_WRAPPERTYPEINFO(ui, SemanticsUpdateBuilder); SemanticsUpdateBuilder::SemanticsUpdateBuilder() = default; SemanticsUpdateBuilder::~SemanticsUpdateBuilder() = default; void SemanticsUpdateBuilder::updateNode( int id, int flags, int actions, int maxValueLength, int currentValueLength, int textSelectionBase, int textSelectionExtent, int platformViewId, int scrollChildren, int scrollIndex, double scrollPosition, double scrollExtentMax, double scrollExtentMin, double left, double top, double right, double bottom, double elevation, double thickness, std::string identifier, std::string label, const std::vector<NativeStringAttribute*>& labelAttributes, std::string value, const std::vector<NativeStringAttribute*>& valueAttributes, std::string increasedValue, const std::vector<NativeStringAttribute*>& increasedValueAttributes, std::string decreasedValue, const std::vector<NativeStringAttribute*>& decreasedValueAttributes, std::string hint, const std::vector<NativeStringAttribute*>& hintAttributes, std::string tooltip, int textDirection, const tonic::Float64List& transform, const tonic::Int32List& childrenInTraversalOrder, const tonic::Int32List& childrenInHitTestOrder, const tonic::Int32List& localContextActions) { FML_CHECK(scrollChildren == 0 || (scrollChildren > 0 && childrenInHitTestOrder.data())) << "Semantics update contained scrollChildren but did not have " "childrenInHitTestOrder"; SemanticsNode node; node.id = id; node.flags = flags; node.actions = actions; node.maxValueLength = maxValueLength; node.currentValueLength = currentValueLength; node.textSelectionBase = textSelectionBase; node.textSelectionExtent = textSelectionExtent; node.platformViewId = platformViewId; node.scrollChildren = scrollChildren; node.scrollIndex = scrollIndex; node.scrollPosition = scrollPosition; node.scrollExtentMax = scrollExtentMax; node.scrollExtentMin = scrollExtentMin; node.rect = SkRect::MakeLTRB(SafeNarrow(left), SafeNarrow(top), SafeNarrow(right), SafeNarrow(bottom)); node.elevation = elevation; node.thickness = thickness; node.identifier = std::move(identifier); node.label = std::move(label); pushStringAttributes(node.labelAttributes, labelAttributes); node.value = std::move(value); pushStringAttributes(node.valueAttributes, valueAttributes); node.increasedValue = std::move(increasedValue); pushStringAttributes(node.increasedValueAttributes, increasedValueAttributes); node.decreasedValue = std::move(decreasedValue); pushStringAttributes(node.decreasedValueAttributes, decreasedValueAttributes); node.hint = std::move(hint); pushStringAttributes(node.hintAttributes, hintAttributes); node.tooltip = std::move(tooltip); node.textDirection = textDirection; SkScalar scalarTransform[16]; for (int i = 0; i < 16; ++i) { scalarTransform[i] = SafeNarrow(transform.data()[i]); } node.transform = SkM44::ColMajor(scalarTransform); node.childrenInTraversalOrder = std::vector<int32_t>(childrenInTraversalOrder.data(), childrenInTraversalOrder.data() + childrenInTraversalOrder.num_elements()); node.childrenInHitTestOrder = std::vector<int32_t>( childrenInHitTestOrder.data(), childrenInHitTestOrder.data() + childrenInHitTestOrder.num_elements()); node.customAccessibilityActions = std::vector<int32_t>( localContextActions.data(), localContextActions.data() + localContextActions.num_elements()); nodes_[id] = node; } void SemanticsUpdateBuilder::updateCustomAction(int id, std::string label, std::string hint, int overrideId) { CustomAccessibilityAction action; action.id = id; action.overrideId = overrideId; action.label = std::move(label); action.hint = std::move(hint); actions_[id] = action; } void SemanticsUpdateBuilder::build(Dart_Handle semantics_update_handle) { SemanticsUpdate::create(semantics_update_handle, std::move(nodes_), std::move(actions_)); ClearDartWrapper(); } } // namespace flutter
engine/lib/ui/semantics/semantics_update_builder.cc/0
{ "file_path": "engine/lib/ui/semantics/semantics_update_builder.cc", "repo_id": "engine", "token_count": 1907 }
388
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// Built-in types and core primitives for a Flutter application. /// /// To use, import `dart:ui`. /// /// This library exposes the lowest-level services that Flutter frameworks use /// to bootstrap applications, such as classes for driving the input, graphics /// text, layout, and rendering subsystems. library dart.ui; import 'dart:async'; import 'dart:collection' as collection; import 'dart:convert'; import 'dart:developer' as developer; import 'dart:ffi'; import 'dart:io'; import 'dart:isolate' show Isolate, IsolateSpawnException, RawReceivePort, RemoteError, SendPort; import 'dart:math' as math; import 'dart:nativewrappers'; import 'dart:typed_data'; part 'annotations.dart'; part 'channel_buffers.dart'; part 'compositing.dart'; part 'geometry.dart'; part 'hash_codes.dart'; part 'hooks.dart'; part 'isolate_name_server.dart'; part 'key.dart'; part 'lerp.dart'; part 'math.dart'; part 'natives.dart'; part 'painting.dart'; part 'platform_dispatcher.dart'; part 'platform_isolate.dart'; part 'plugins.dart'; part 'pointer.dart'; part 'semantics.dart'; part 'setup_hooks.dart'; part 'text.dart'; part 'window.dart';
engine/lib/ui/ui.dart/0
{ "file_path": "engine/lib/ui/ui.dart", "repo_id": "engine", "token_count": 476 }
389
// Copyright 2013 The Flutter Authors. 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_packet_converter.h" #include <cstring> #include "gtest/gtest.h" namespace flutter { namespace testing { void CreateSimulatedPointerData(PointerData& data, // NOLINT PointerData::Change change, int64_t device, double dx, double dy, int64_t buttons) { data.time_stamp = 0; data.change = change; data.kind = PointerData::DeviceKind::kTouch; data.signal_kind = PointerData::SignalKind::kNone; data.device = device; data.pointer_identifier = 0; data.physical_x = dx; data.physical_y = dy; data.physical_delta_x = 0.0; data.physical_delta_y = 0.0; data.buttons = buttons; data.obscured = 0; data.synthesized = 0; data.pressure = 0.0; data.pressure_min = 0.0; data.pressure_max = 0.0; data.distance = 0.0; data.distance_max = 0.0; data.size = 0.0; data.radius_major = 0.0; data.radius_minor = 0.0; data.radius_min = 0.0; data.radius_max = 0.0; data.orientation = 0.0; data.tilt = 0.0; data.platformData = 0; data.scroll_delta_x = 0.0; data.scroll_delta_y = 0.0; data.view_id = 0; } void CreateSimulatedMousePointerData(PointerData& data, // NOLINT PointerData::Change change, PointerData::SignalKind signal_kind, int64_t device, double dx, double dy, double scroll_delta_x, double scroll_delta_y, int64_t buttons) { data.time_stamp = 0; data.change = change; data.kind = PointerData::DeviceKind::kMouse; data.signal_kind = signal_kind; data.device = device; data.pointer_identifier = 0; data.physical_x = dx; data.physical_y = dy; data.physical_delta_x = 0.0; data.physical_delta_y = 0.0; data.buttons = buttons; data.obscured = 0; data.synthesized = 0; data.pressure = 0.0; data.pressure_min = 0.0; data.pressure_max = 0.0; data.distance = 0.0; data.distance_max = 0.0; data.size = 0.0; data.radius_major = 0.0; data.radius_minor = 0.0; data.radius_min = 0.0; data.radius_max = 0.0; data.orientation = 0.0; data.tilt = 0.0; data.platformData = 0; data.scroll_delta_x = scroll_delta_x; data.scroll_delta_y = scroll_delta_y; data.view_id = 0; } void CreateSimulatedTrackpadGestureData(PointerData& data, // NOLINT PointerData::Change change, int64_t device, double dx, double dy, double pan_x, double pan_y, double scale, double rotation) { data.time_stamp = 0; data.change = change; data.kind = PointerData::DeviceKind::kMouse; data.signal_kind = PointerData::SignalKind::kNone; data.device = device; data.pointer_identifier = 0; data.physical_x = dx; data.physical_y = dy; data.physical_delta_x = 0.0; data.physical_delta_y = 0.0; data.buttons = 0; data.obscured = 0; data.synthesized = 0; data.pressure = 0.0; data.pressure_min = 0.0; data.pressure_max = 0.0; data.distance = 0.0; data.distance_max = 0.0; data.size = 0.0; data.radius_major = 0.0; data.radius_minor = 0.0; data.radius_min = 0.0; data.radius_max = 0.0; data.orientation = 0.0; data.tilt = 0.0; data.platformData = 0; data.scroll_delta_x = 0.0; data.scroll_delta_y = 0.0; data.pan_x = pan_x; data.pan_y = pan_y; data.pan_delta_x = 0.0; data.pan_delta_y = 0.0; data.scale = scale; data.rotation = rotation; data.view_id = 0; } void UnpackPointerPacket(std::vector<PointerData>& output, // NOLINT std::unique_ptr<PointerDataPacket> packet) { for (size_t i = 0; i < packet->GetLength(); i++) { PointerData pointer_data = packet->GetPointerData(i); output.push_back(pointer_data); } packet.reset(); } TEST(PointerDataPacketConverterTest, CanConvertPointerDataPacket) { PointerDataPacketConverter converter; auto packet = std::make_unique<PointerDataPacket>(6); PointerData data; CreateSimulatedPointerData(data, PointerData::Change::kAdd, 0, 0.0, 0.0, 0); packet->SetPointerData(0, data); CreateSimulatedPointerData(data, PointerData::Change::kHover, 0, 3.0, 0.0, 0); packet->SetPointerData(1, data); CreateSimulatedPointerData(data, PointerData::Change::kDown, 0, 3.0, 0.0, 1); packet->SetPointerData(2, data); CreateSimulatedPointerData(data, PointerData::Change::kMove, 0, 3.0, 4.0, 1); packet->SetPointerData(3, data); CreateSimulatedPointerData(data, PointerData::Change::kUp, 0, 3.0, 4.0, 0); packet->SetPointerData(4, data); CreateSimulatedPointerData(data, PointerData::Change::kRemove, 0, 3.0, 4.0, 0); packet->SetPointerData(5, data); auto converted_packet = converter.Convert(std::move(packet)); std::vector<PointerData> result; UnpackPointerPacket(result, std::move(converted_packet)); ASSERT_EQ(result.size(), (size_t)6); ASSERT_EQ(result[0].change, PointerData::Change::kAdd); ASSERT_EQ(result[0].synthesized, 0); ASSERT_EQ(result[1].change, PointerData::Change::kHover); ASSERT_EQ(result[1].synthesized, 0); ASSERT_EQ(result[1].physical_delta_x, 3.0); ASSERT_EQ(result[1].physical_delta_y, 0.0); ASSERT_EQ(result[2].change, PointerData::Change::kDown); ASSERT_EQ(result[2].pointer_identifier, 1); ASSERT_EQ(result[2].synthesized, 0); ASSERT_EQ(result[3].change, PointerData::Change::kMove); ASSERT_EQ(result[3].pointer_identifier, 1); ASSERT_EQ(result[3].synthesized, 0); ASSERT_EQ(result[3].physical_delta_x, 0.0); ASSERT_EQ(result[3].physical_delta_y, 4.0); ASSERT_EQ(result[4].change, PointerData::Change::kUp); ASSERT_EQ(result[4].pointer_identifier, 1); ASSERT_EQ(result[4].synthesized, 0); ASSERT_EQ(result[5].change, PointerData::Change::kRemove); ASSERT_EQ(result[5].synthesized, 0); } TEST(PointerDataPacketConverterTest, CanSynthesizeDownAndUp) { PointerDataPacketConverter converter; auto packet = std::make_unique<PointerDataPacket>(4); PointerData data; CreateSimulatedPointerData(data, PointerData::Change::kAdd, 0, 0.0, 0.0, 0); packet->SetPointerData(0, data); CreateSimulatedPointerData(data, PointerData::Change::kDown, 0, 3.0, 0.0, 1); packet->SetPointerData(1, data); CreateSimulatedPointerData(data, PointerData::Change::kUp, 0, 3.0, 4.0, 0); packet->SetPointerData(2, data); CreateSimulatedPointerData(data, PointerData::Change::kRemove, 0, 3.0, 4.0, 0); packet->SetPointerData(3, data); auto converted_packet = converter.Convert(std::move(packet)); std::vector<PointerData> result; UnpackPointerPacket(result, std::move(converted_packet)); ASSERT_EQ(result.size(), (size_t)6); ASSERT_EQ(result[0].change, PointerData::Change::kAdd); ASSERT_EQ(result[0].synthesized, 0); // A hover should be synthesized. ASSERT_EQ(result[1].change, PointerData::Change::kHover); ASSERT_EQ(result[1].synthesized, 1); ASSERT_EQ(result[1].physical_delta_x, 3.0); ASSERT_EQ(result[1].physical_delta_y, 0.0); ASSERT_EQ(result[1].buttons, 0); ASSERT_EQ(result[2].change, PointerData::Change::kDown); ASSERT_EQ(result[2].pointer_identifier, 1); ASSERT_EQ(result[2].synthesized, 0); ASSERT_EQ(result[2].buttons, 1); // A move should be synthesized. ASSERT_EQ(result[3].change, PointerData::Change::kMove); ASSERT_EQ(result[3].pointer_identifier, 1); ASSERT_EQ(result[3].synthesized, 1); ASSERT_EQ(result[3].physical_delta_x, 0.0); ASSERT_EQ(result[3].physical_delta_y, 4.0); ASSERT_EQ(result[3].buttons, 1); ASSERT_EQ(result[4].change, PointerData::Change::kUp); ASSERT_EQ(result[4].pointer_identifier, 1); ASSERT_EQ(result[4].synthesized, 0); ASSERT_EQ(result[4].buttons, 0); ASSERT_EQ(result[5].change, PointerData::Change::kRemove); ASSERT_EQ(result[5].synthesized, 0); } TEST(PointerDataPacketConverterTest, CanUpdatePointerIdentifier) { PointerDataPacketConverter converter; auto packet = std::make_unique<PointerDataPacket>(7); PointerData data; CreateSimulatedPointerData(data, PointerData::Change::kAdd, 0, 0.0, 0.0, 0); packet->SetPointerData(0, data); CreateSimulatedPointerData(data, PointerData::Change::kDown, 0, 0.0, 0.0, 1); packet->SetPointerData(1, data); CreateSimulatedPointerData(data, PointerData::Change::kUp, 0, 0.0, 0.0, 0); packet->SetPointerData(2, data); CreateSimulatedPointerData(data, PointerData::Change::kDown, 0, 0.0, 0.0, 1); packet->SetPointerData(3, data); CreateSimulatedPointerData(data, PointerData::Change::kMove, 0, 3.0, 0.0, 1); packet->SetPointerData(4, data); CreateSimulatedPointerData(data, PointerData::Change::kUp, 0, 3.0, 0.0, 0); packet->SetPointerData(5, data); CreateSimulatedPointerData(data, PointerData::Change::kRemove, 0, 3.0, 0.0, 0); packet->SetPointerData(6, data); auto converted_packet = converter.Convert(std::move(packet)); std::vector<PointerData> result; UnpackPointerPacket(result, std::move(converted_packet)); ASSERT_EQ(result.size(), (size_t)7); ASSERT_EQ(result[0].change, PointerData::Change::kAdd); ASSERT_EQ(result[0].synthesized, 0); ASSERT_EQ(result[1].change, PointerData::Change::kDown); ASSERT_EQ(result[1].pointer_identifier, 1); ASSERT_EQ(result[1].synthesized, 0); ASSERT_EQ(result[2].change, PointerData::Change::kUp); ASSERT_EQ(result[2].pointer_identifier, 1); ASSERT_EQ(result[2].synthesized, 0); // Pointer count increase to 2. ASSERT_EQ(result[3].change, PointerData::Change::kDown); ASSERT_EQ(result[3].pointer_identifier, 2); ASSERT_EQ(result[3].synthesized, 0); ASSERT_EQ(result[4].change, PointerData::Change::kMove); ASSERT_EQ(result[4].pointer_identifier, 2); ASSERT_EQ(result[4].synthesized, 0); ASSERT_EQ(result[4].physical_delta_x, 3.0); ASSERT_EQ(result[4].physical_delta_y, 0.0); ASSERT_EQ(result[5].change, PointerData::Change::kUp); ASSERT_EQ(result[5].pointer_identifier, 2); ASSERT_EQ(result[5].synthesized, 0); ASSERT_EQ(result[6].change, PointerData::Change::kRemove); ASSERT_EQ(result[6].synthesized, 0); } TEST(PointerDataPacketConverterTest, AlwaysForwardMoveEvent) { PointerDataPacketConverter converter; auto packet = std::make_unique<PointerDataPacket>(4); PointerData data; CreateSimulatedPointerData(data, PointerData::Change::kAdd, 0, 0.0, 0.0, 0); packet->SetPointerData(0, data); CreateSimulatedPointerData(data, PointerData::Change::kDown, 0, 0.0, 0.0, 1); packet->SetPointerData(1, data); // Creates a move event without a location change. CreateSimulatedPointerData(data, PointerData::Change::kMove, 0, 0.0, 0.0, 1); packet->SetPointerData(2, data); CreateSimulatedPointerData(data, PointerData::Change::kUp, 0, 0.0, 0.0, 0); packet->SetPointerData(3, data); auto converted_packet = converter.Convert(std::move(packet)); std::vector<PointerData> result; UnpackPointerPacket(result, std::move(converted_packet)); ASSERT_EQ(result.size(), (size_t)4); ASSERT_EQ(result[0].change, PointerData::Change::kAdd); ASSERT_EQ(result[0].synthesized, 0); ASSERT_EQ(result[1].change, PointerData::Change::kDown); ASSERT_EQ(result[1].pointer_identifier, 1); ASSERT_EQ(result[1].synthesized, 0); // Does not filter out the move event. ASSERT_EQ(result[2].change, PointerData::Change::kMove); ASSERT_EQ(result[2].pointer_identifier, 1); ASSERT_EQ(result[2].synthesized, 0); ASSERT_EQ(result[3].change, PointerData::Change::kUp); ASSERT_EQ(result[3].pointer_identifier, 1); ASSERT_EQ(result[3].synthesized, 0); } TEST(PointerDataPacketConverterTest, CanWorkWithDifferentDevices) { PointerDataPacketConverter converter; auto packet = std::make_unique<PointerDataPacket>(12); PointerData data; CreateSimulatedPointerData(data, PointerData::Change::kAdd, 0, 0.0, 0.0, 0); packet->SetPointerData(0, data); CreateSimulatedPointerData(data, PointerData::Change::kDown, 0, 0.0, 0.0, 1); packet->SetPointerData(1, data); CreateSimulatedPointerData(data, PointerData::Change::kAdd, 1, 0.0, 0.0, 0); packet->SetPointerData(2, data); CreateSimulatedPointerData(data, PointerData::Change::kDown, 1, 0.0, 0.0, 1); packet->SetPointerData(3, data); CreateSimulatedPointerData(data, PointerData::Change::kUp, 0, 0.0, 0.0, 0); packet->SetPointerData(4, data); CreateSimulatedPointerData(data, PointerData::Change::kDown, 0, 0.0, 0.0, 1); packet->SetPointerData(5, data); CreateSimulatedPointerData(data, PointerData::Change::kMove, 1, 0.0, 4.0, 1); packet->SetPointerData(6, data); CreateSimulatedPointerData(data, PointerData::Change::kMove, 0, 3.0, 0.0, 1); packet->SetPointerData(7, data); CreateSimulatedPointerData(data, PointerData::Change::kUp, 1, 0.0, 4.0, 0); packet->SetPointerData(8, data); CreateSimulatedPointerData(data, PointerData::Change::kUp, 0, 3.0, 0.0, 0); packet->SetPointerData(9, data); CreateSimulatedPointerData(data, PointerData::Change::kRemove, 0, 3.0, 0.0, 0); packet->SetPointerData(10, data); CreateSimulatedPointerData(data, PointerData::Change::kRemove, 1, 0.0, 4.0, 0); packet->SetPointerData(11, data); auto converted_packet = converter.Convert(std::move(packet)); std::vector<PointerData> result; UnpackPointerPacket(result, std::move(converted_packet)); ASSERT_EQ(result.size(), (size_t)12); ASSERT_EQ(result[0].change, PointerData::Change::kAdd); ASSERT_EQ(result[0].device, 0); ASSERT_EQ(result[0].synthesized, 0); ASSERT_EQ(result[1].change, PointerData::Change::kDown); ASSERT_EQ(result[1].device, 0); ASSERT_EQ(result[1].pointer_identifier, 1); ASSERT_EQ(result[1].synthesized, 0); ASSERT_EQ(result[2].change, PointerData::Change::kAdd); ASSERT_EQ(result[2].device, 1); ASSERT_EQ(result[2].synthesized, 0); ASSERT_EQ(result[3].change, PointerData::Change::kDown); ASSERT_EQ(result[3].device, 1); ASSERT_EQ(result[3].pointer_identifier, 2); ASSERT_EQ(result[3].synthesized, 0); ASSERT_EQ(result[4].change, PointerData::Change::kUp); ASSERT_EQ(result[4].device, 0); ASSERT_EQ(result[4].pointer_identifier, 1); ASSERT_EQ(result[4].synthesized, 0); ASSERT_EQ(result[5].change, PointerData::Change::kDown); ASSERT_EQ(result[5].device, 0); ASSERT_EQ(result[5].pointer_identifier, 3); ASSERT_EQ(result[5].synthesized, 0); ASSERT_EQ(result[6].change, PointerData::Change::kMove); ASSERT_EQ(result[6].device, 1); ASSERT_EQ(result[6].pointer_identifier, 2); ASSERT_EQ(result[6].synthesized, 0); ASSERT_EQ(result[6].physical_delta_x, 0.0); ASSERT_EQ(result[6].physical_delta_y, 4.0); ASSERT_EQ(result[7].change, PointerData::Change::kMove); ASSERT_EQ(result[7].device, 0); ASSERT_EQ(result[7].pointer_identifier, 3); ASSERT_EQ(result[7].synthesized, 0); ASSERT_EQ(result[7].physical_delta_x, 3.0); ASSERT_EQ(result[7].physical_delta_y, 0.0); ASSERT_EQ(result[8].change, PointerData::Change::kUp); ASSERT_EQ(result[8].device, 1); ASSERT_EQ(result[8].pointer_identifier, 2); ASSERT_EQ(result[8].synthesized, 0); ASSERT_EQ(result[9].change, PointerData::Change::kUp); ASSERT_EQ(result[9].device, 0); ASSERT_EQ(result[9].pointer_identifier, 3); ASSERT_EQ(result[9].synthesized, 0); ASSERT_EQ(result[10].change, PointerData::Change::kRemove); ASSERT_EQ(result[10].device, 0); ASSERT_EQ(result[10].synthesized, 0); ASSERT_EQ(result[11].change, PointerData::Change::kRemove); ASSERT_EQ(result[11].device, 1); ASSERT_EQ(result[11].synthesized, 0); } TEST(PointerDataPacketConverterTest, CanSynthesizeAdd) { PointerDataPacketConverter converter; auto packet = std::make_unique<PointerDataPacket>(2); PointerData data; CreateSimulatedPointerData(data, PointerData::Change::kDown, 0, 330.0, 450.0, 1); packet->SetPointerData(0, data); CreateSimulatedPointerData(data, PointerData::Change::kUp, 0, 0.0, 0.0, 0); packet->SetPointerData(1, data); auto converted_packet = converter.Convert(std::move(packet)); std::vector<PointerData> result; UnpackPointerPacket(result, std::move(converted_packet)); ASSERT_EQ(result.size(), (size_t)4); // A add should be synthesized. ASSERT_EQ(result[0].change, PointerData::Change::kAdd); ASSERT_EQ(result[0].physical_x, 330.0); ASSERT_EQ(result[0].physical_y, 450.0); ASSERT_EQ(result[0].synthesized, 1); ASSERT_EQ(result[0].buttons, 0); ASSERT_EQ(result[1].change, PointerData::Change::kDown); ASSERT_EQ(result[1].physical_x, 330.0); ASSERT_EQ(result[1].physical_y, 450.0); ASSERT_EQ(result[1].synthesized, 0); ASSERT_EQ(result[1].buttons, 1); // A move should be synthesized. ASSERT_EQ(result[2].change, PointerData::Change::kMove); ASSERT_EQ(result[2].physical_delta_x, -330.0); ASSERT_EQ(result[2].physical_delta_y, -450.0); ASSERT_EQ(result[2].physical_x, 0.0); ASSERT_EQ(result[2].physical_y, 0.0); ASSERT_EQ(result[2].synthesized, 1); ASSERT_EQ(result[2].buttons, 1); ASSERT_EQ(result[3].change, PointerData::Change::kUp); ASSERT_EQ(result[3].physical_x, 0.0); ASSERT_EQ(result[3].physical_y, 0.0); ASSERT_EQ(result[3].synthesized, 0); ASSERT_EQ(result[3].buttons, 0); } TEST(PointerDataPacketConverterTest, CanHandleThreeFingerGesture) { // Regression test https://github.com/flutter/flutter/issues/20517. PointerDataPacketConverter converter; PointerData data; std::vector<PointerData> result; // First finger down. auto packet = std::make_unique<PointerDataPacket>(1); CreateSimulatedPointerData(data, PointerData::Change::kDown, 0, 0.0, 0.0, 1); packet->SetPointerData(0, data); auto converted_packet = converter.Convert(std::move(packet)); UnpackPointerPacket(result, std::move(converted_packet)); // Second finger down. packet = std::make_unique<PointerDataPacket>(1); CreateSimulatedPointerData(data, PointerData::Change::kDown, 1, 33.0, 44.0, 1); packet->SetPointerData(0, data); converted_packet = converter.Convert(std::move(packet)); UnpackPointerPacket(result, std::move(converted_packet)); // Triggers three cancels. packet = std::make_unique<PointerDataPacket>(3); CreateSimulatedPointerData(data, PointerData::Change::kCancel, 1, 33.0, 44.0, 0); packet->SetPointerData(0, data); CreateSimulatedPointerData(data, PointerData::Change::kCancel, 0, 0.0, 0.0, 0); packet->SetPointerData(1, data); CreateSimulatedPointerData(data, PointerData::Change::kCancel, 2, 40.0, 50.0, 0); packet->SetPointerData(2, data); converted_packet = converter.Convert(std::move(packet)); UnpackPointerPacket(result, std::move(converted_packet)); ASSERT_EQ(result.size(), (size_t)6); ASSERT_EQ(result[0].change, PointerData::Change::kAdd); ASSERT_EQ(result[0].device, 0); ASSERT_EQ(result[0].physical_x, 0.0); ASSERT_EQ(result[0].physical_y, 0.0); ASSERT_EQ(result[0].synthesized, 1); ASSERT_EQ(result[0].buttons, 0); ASSERT_EQ(result[1].change, PointerData::Change::kDown); ASSERT_EQ(result[1].device, 0); ASSERT_EQ(result[1].physical_x, 0.0); ASSERT_EQ(result[1].physical_y, 0.0); ASSERT_EQ(result[1].synthesized, 0); ASSERT_EQ(result[1].buttons, 1); ASSERT_EQ(result[2].change, PointerData::Change::kAdd); ASSERT_EQ(result[2].device, 1); ASSERT_EQ(result[2].physical_x, 33.0); ASSERT_EQ(result[2].physical_y, 44.0); ASSERT_EQ(result[2].synthesized, 1); ASSERT_EQ(result[2].buttons, 0); ASSERT_EQ(result[3].change, PointerData::Change::kDown); ASSERT_EQ(result[3].device, 1); ASSERT_EQ(result[3].physical_x, 33.0); ASSERT_EQ(result[3].physical_y, 44.0); ASSERT_EQ(result[3].synthesized, 0); ASSERT_EQ(result[3].buttons, 1); ASSERT_EQ(result[4].change, PointerData::Change::kCancel); ASSERT_EQ(result[4].device, 1); ASSERT_EQ(result[4].physical_x, 33.0); ASSERT_EQ(result[4].physical_y, 44.0); ASSERT_EQ(result[4].synthesized, 0); ASSERT_EQ(result[5].change, PointerData::Change::kCancel); ASSERT_EQ(result[5].device, 0); ASSERT_EQ(result[5].physical_x, 0.0); ASSERT_EQ(result[5].physical_y, 0.0); ASSERT_EQ(result[5].synthesized, 0); // Third cancel should be dropped } TEST(PointerDataPacketConverterTest, CanConvertPointerSignals) { PointerData::SignalKind signal_kinds[] = { PointerData::SignalKind::kScroll, PointerData::SignalKind::kScrollInertiaCancel, PointerData::SignalKind::kScale, }; for (const PointerData::SignalKind& kind : signal_kinds) { PointerDataPacketConverter converter; auto packet = std::make_unique<PointerDataPacket>(6); PointerData data; CreateSimulatedMousePointerData(data, PointerData::Change::kAdd, PointerData::SignalKind::kNone, 0, 0.0, 0.0, 0.0, 0.0, 0); packet->SetPointerData(0, data); CreateSimulatedMousePointerData(data, PointerData::Change::kAdd, PointerData::SignalKind::kNone, 1, 0.0, 0.0, 0.0, 0.0, 0); packet->SetPointerData(1, data); CreateSimulatedMousePointerData(data, PointerData::Change::kDown, PointerData::SignalKind::kNone, 1, 0.0, 0.0, 0.0, 0.0, 1); packet->SetPointerData(2, data); CreateSimulatedMousePointerData(data, PointerData::Change::kHover, kind, 0, 34.0, 34.0, 30.0, 0.0, 0); packet->SetPointerData(3, data); CreateSimulatedMousePointerData(data, PointerData::Change::kHover, kind, 1, 49.0, 49.0, 50.0, 0.0, 0); packet->SetPointerData(4, data); CreateSimulatedMousePointerData(data, PointerData::Change::kHover, kind, 2, 10.0, 20.0, 30.0, 40.0, 0); packet->SetPointerData(5, data); auto converted_packet = converter.Convert(std::move(packet)); std::vector<PointerData> result; UnpackPointerPacket(result, std::move(converted_packet)); ASSERT_EQ(result.size(), (size_t)9); ASSERT_EQ(result[0].change, PointerData::Change::kAdd); ASSERT_EQ(result[0].signal_kind, PointerData::SignalKind::kNone); ASSERT_EQ(result[0].device, 0); ASSERT_EQ(result[0].physical_x, 0.0); ASSERT_EQ(result[0].physical_y, 0.0); ASSERT_EQ(result[0].synthesized, 0); ASSERT_EQ(result[1].change, PointerData::Change::kAdd); ASSERT_EQ(result[1].signal_kind, PointerData::SignalKind::kNone); ASSERT_EQ(result[1].device, 1); ASSERT_EQ(result[1].physical_x, 0.0); ASSERT_EQ(result[1].physical_y, 0.0); ASSERT_EQ(result[1].synthesized, 0); ASSERT_EQ(result[2].change, PointerData::Change::kDown); ASSERT_EQ(result[2].signal_kind, PointerData::SignalKind::kNone); ASSERT_EQ(result[2].device, 1); ASSERT_EQ(result[2].physical_x, 0.0); ASSERT_EQ(result[2].physical_y, 0.0); ASSERT_EQ(result[2].synthesized, 0); // Converter will synthesize a hover to position for device 0. ASSERT_EQ(result[3].change, PointerData::Change::kHover); ASSERT_EQ(result[3].signal_kind, PointerData::SignalKind::kNone); ASSERT_EQ(result[3].device, 0); ASSERT_EQ(result[3].physical_x, 34.0); ASSERT_EQ(result[3].physical_y, 34.0); ASSERT_EQ(result[3].physical_delta_x, 34.0); ASSERT_EQ(result[3].physical_delta_y, 34.0); ASSERT_EQ(result[3].buttons, 0); ASSERT_EQ(result[3].synthesized, 1); ASSERT_EQ(result[4].change, PointerData::Change::kHover); ASSERT_EQ(result[4].signal_kind, kind); ASSERT_EQ(result[4].device, 0); ASSERT_EQ(result[4].physical_x, 34.0); ASSERT_EQ(result[4].physical_y, 34.0); ASSERT_EQ(result[4].scroll_delta_x, 30.0); ASSERT_EQ(result[4].scroll_delta_y, 0.0); // Converter will synthesize a move to position for device 1. ASSERT_EQ(result[5].change, PointerData::Change::kMove); ASSERT_EQ(result[5].signal_kind, PointerData::SignalKind::kNone); ASSERT_EQ(result[5].device, 1); ASSERT_EQ(result[5].physical_x, 49.0); ASSERT_EQ(result[5].physical_y, 49.0); ASSERT_EQ(result[5].physical_delta_x, 49.0); ASSERT_EQ(result[5].physical_delta_y, 49.0); ASSERT_EQ(result[5].buttons, 1); ASSERT_EQ(result[5].synthesized, 1); ASSERT_EQ(result[6].change, PointerData::Change::kHover); ASSERT_EQ(result[6].signal_kind, kind); ASSERT_EQ(result[6].device, 1); ASSERT_EQ(result[6].physical_x, 49.0); ASSERT_EQ(result[6].physical_y, 49.0); ASSERT_EQ(result[6].scroll_delta_x, 50.0); ASSERT_EQ(result[6].scroll_delta_y, 0.0); // Converter will synthesize an add for device 2. ASSERT_EQ(result[7].change, PointerData::Change::kAdd); ASSERT_EQ(result[7].signal_kind, PointerData::SignalKind::kNone); ASSERT_EQ(result[7].device, 2); ASSERT_EQ(result[7].physical_x, 10.0); ASSERT_EQ(result[7].physical_y, 20.0); ASSERT_EQ(result[7].synthesized, 1); ASSERT_EQ(result[8].change, PointerData::Change::kHover); ASSERT_EQ(result[8].signal_kind, kind); ASSERT_EQ(result[8].device, 2); ASSERT_EQ(result[8].physical_x, 10.0); ASSERT_EQ(result[8].physical_y, 20.0); ASSERT_EQ(result[8].scroll_delta_x, 30.0); ASSERT_EQ(result[8].scroll_delta_y, 40.0); } } TEST(PointerDataPacketConverterTest, CanConvertTrackpadGesture) { PointerDataPacketConverter converter; auto packet = std::make_unique<PointerDataPacket>(3); PointerData data; CreateSimulatedTrackpadGestureData(data, PointerData::Change::kPanZoomStart, 0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); packet->SetPointerData(0, data); CreateSimulatedTrackpadGestureData(data, PointerData::Change::kPanZoomUpdate, 0, 0.0, 0.0, 3.0, 4.0, 1.0, 0.0); packet->SetPointerData(1, data); CreateSimulatedTrackpadGestureData(data, PointerData::Change::kPanZoomEnd, 0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); packet->SetPointerData(2, data); auto converted_packet = converter.Convert(std::move(packet)); std::vector<PointerData> result; UnpackPointerPacket(result, std::move(converted_packet)); ASSERT_EQ(result.size(), (size_t)4); ASSERT_EQ(result[0].change, PointerData::Change::kAdd); ASSERT_EQ(result[0].device, 0); ASSERT_EQ(result[0].synthesized, 1); ASSERT_EQ(result[1].change, PointerData::Change::kPanZoomStart); ASSERT_EQ(result[1].signal_kind, PointerData::SignalKind::kNone); ASSERT_EQ(result[1].device, 0); ASSERT_EQ(result[1].physical_x, 0.0); ASSERT_EQ(result[1].physical_y, 0.0); ASSERT_EQ(result[1].synthesized, 0); ASSERT_EQ(result[2].change, PointerData::Change::kPanZoomUpdate); ASSERT_EQ(result[2].signal_kind, PointerData::SignalKind::kNone); ASSERT_EQ(result[2].device, 0); ASSERT_EQ(result[2].physical_x, 0.0); ASSERT_EQ(result[2].physical_y, 0.0); ASSERT_EQ(result[2].pan_x, 3.0); ASSERT_EQ(result[2].pan_y, 4.0); ASSERT_EQ(result[2].pan_delta_x, 3.0); ASSERT_EQ(result[2].pan_delta_y, 4.0); ASSERT_EQ(result[2].scale, 1.0); ASSERT_EQ(result[2].rotation, 0.0); ASSERT_EQ(result[2].synthesized, 0); ASSERT_EQ(result[3].change, PointerData::Change::kPanZoomEnd); ASSERT_EQ(result[3].signal_kind, PointerData::SignalKind::kNone); ASSERT_EQ(result[3].device, 0); ASSERT_EQ(result[3].physical_x, 0.0); ASSERT_EQ(result[3].physical_y, 0.0); ASSERT_EQ(result[3].synthesized, 0); } TEST(PointerDataPacketConverterTest, CanConvertViewId) { PointerDataPacketConverter converter; auto packet = std::make_unique<PointerDataPacket>(2); PointerData data; CreateSimulatedPointerData(data, PointerData::Change::kAdd, 0, 0.0, 0.0, 0); data.view_id = 100; packet->SetPointerData(0, data); CreateSimulatedPointerData(data, PointerData::Change::kHover, 0, 1.0, 0.0, 0); data.view_id = 200; packet->SetPointerData(1, data); auto converted_packet = converter.Convert(std::move(packet)); std::vector<PointerData> result; UnpackPointerPacket(result, std::move(converted_packet)); ASSERT_EQ(result.size(), (size_t)2); ASSERT_EQ(result[0].view_id, 100); ASSERT_EQ(result[1].view_id, 200); } } // namespace testing } // namespace flutter
engine/lib/ui/window/pointer_data_packet_converter_unittests.cc/0
{ "file_path": "engine/lib/ui/window/pointer_data_packet_converter_unittests.cc", "repo_id": "engine", "token_count": 12914 }
390
// Copyright 2013 The Flutter 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:convert'; import 'dart:io'; import 'dart:math' as math; import 'package:image/image.dart'; import 'package:path/path.dart' as path; import 'package:test_api/backend.dart'; import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart' as wip; import 'browser.dart'; import 'browser_process.dart'; import 'chrome_installer.dart'; import 'common.dart'; import 'environment.dart'; import 'package_lock.dart'; /// Provides an environment for desktop Chrome. class ChromeEnvironment implements BrowserEnvironment { ChromeEnvironment({ required bool useDwarf, }) : _useDwarf = useDwarf; late final BrowserInstallation _installation; final bool _useDwarf; @override Future<Browser> launchBrowserInstance( Uri url, { bool debug = false, }) async { return Chrome( url, _installation, debug: debug, useDwarf: _useDwarf ); } @override Runtime get packageTestRuntime => Runtime.chrome; @override Future<void> prepare() async { final String version = packageLock.chromeLock.version; _installation = await getOrInstallChrome( version, infoLog: isCi ? stdout : DevNull(), ); } @override Future<void> cleanup() async {} @override String get packageTestConfigurationYamlFile => 'dart_test_chrome.yaml'; @override final String name = 'Chrome'; } /// Runs desktop Chrome. /// /// Most of the communication with the browser is expected to happen via HTTP, /// so this exposes a bare-bones API. The browser starts as soon as the class is /// constructed, and is killed when [close] is called. /// /// Any errors starting or running the process are reported through [onExit]. class Chrome extends Browser { /// Starts a new instance of Chrome open to the given [url], which may be a /// [Uri] or a [String]. factory Chrome( Uri url, BrowserInstallation installation, { required bool debug, required bool useDwarf, }) { final Completer<Uri> remoteDebuggerCompleter = Completer<Uri>.sync(); return Chrome._(BrowserProcess(() async { // A good source of various Chrome CLI options: // https://peter.sh/experiments/chromium-command-line-switches/ // // Things to try: // --font-render-hinting // --enable-font-antialiasing // --gpu-rasterization-msaa-sample-count // --disable-gpu // --disallow-non-exact-resource-reuse // --disable-font-subpixel-positioning final bool isChromeNoSandbox = Platform.environment['CHROME_NO_SANDBOX'] == 'true'; final String dir = await generateUserDirectory(installation, useDwarf); final List<String> args = <String>[ '--user-data-dir=$dir', url.toString(), if (!debug) '--headless', if (isChromeNoSandbox) '--no-sandbox', // When headless, this is the actual size of the viewport. if (!debug) '--window-size=$kMaxScreenshotWidth,$kMaxScreenshotHeight', // When debugging, run in maximized mode so there's enough room for DevTools. if (debug) '--start-maximized', if (debug) '--auto-open-devtools-for-tabs', if (useDwarf) '--devtools-flags=enabledExperiments=wasmDWARFDebugging', // Always run unit tests at a 1x scale factor '--force-device-scale-factor=1', if (!useDwarf) // DWARF debugging requires a Chrome extension. '--disable-extensions', '--disable-popup-blocking', // Indicates that the browser is in "browse without sign-in" (Guest session) mode. '--bwsi', '--no-first-run', '--no-default-browser-check', '--disable-default-apps', '--disable-translate', '--remote-debugging-port=$kDevtoolsPort', // SwiftShader support on ARM macs is disabled until they upgrade to a newer // version of LLVM, see https://issuetracker.google.com/issues/165000222. In // headless Chrome, the default is to use SwiftShader as a software renderer // for WebGL contexts. In order to work around this limitation, we can force // GPU rendering with this flag. if (environment.isMacosArm) '--use-angle=metal', ]; final Process process = await _spawnChromiumProcess(installation.executable, args); remoteDebuggerCompleter.complete( getRemoteDebuggerUrl(Uri.parse('http://localhost:$kDevtoolsPort'))); unawaited(process.exitCode .then((_) => Directory(dir).deleteSync(recursive: true))); return process; }), remoteDebuggerCompleter.future); } Chrome._(this._process, this.remoteDebuggerUrl); static Future<String> generateUserDirectory( BrowserInstallation installation, bool useDwarf ) async { final String userDirectoryPath = environment .webUiDartToolDir .createTempSync('test_chrome_user_data_') .resolveSymbolicLinksSync(); if (!useDwarf) { return userDirectoryPath; } // Using DWARF debugging info requires installation of a Chrome extension. // We can prompt for this, but in order to avoid prompting on every single // browser launch, we cache the user directory after it has been installed. final Directory baselineUserDirectory = Directory(path.join( environment.webUiDartToolDir.path, 'chrome_user_data_base', )); final Directory dwarfExtensionInstallDirectory = Directory(path.join( baselineUserDirectory.path, 'Default', 'Extensions', // This is the ID of the dwarf debugging extension. 'pdcpmagijalfljmkmjngeonclgbbannb', )); if (!baselineUserDirectory.existsSync()) { baselineUserDirectory.createSync(recursive: true); } if (!dwarfExtensionInstallDirectory.existsSync()) { print('DWARF debugging requested. Launching Chrome. Please install the ' 'extension and then exit Chrome when the installation is complete...'); final Process addExtension = await Process.start( installation.executable, <String>[ '--user-data-dir=${baselineUserDirectory.path}', 'https://goo.gle/wasm-debugging-extension', '--bwsi', '--no-first-run', '--no-default-browser-check', '--disable-default-apps', '--disable-translate', ] ); await addExtension.exitCode; } for (final FileSystemEntity input in baselineUserDirectory.listSync(recursive: true)) { final String relative = path.relative(input.path, from: baselineUserDirectory.path); final String outputPath = path.join(userDirectoryPath, relative); if (input is Directory) { await Directory(outputPath).create(recursive: true); } else if (input is File) { await input.copy(outputPath); } } return userDirectoryPath; } final BrowserProcess _process; @override final Future<Uri> remoteDebuggerUrl; @override Future<void> get onExit => _process.onExit; @override Future<void> close() => _process.close(); // Always compare screenshots when running tests locally. On CI only compare // on Linux. @override bool get supportsScreenshots => Platform.isLinux || !isLuci; /// Capture a screenshot of the web content. /// /// Uses Webkit Inspection Protocol server's `captureScreenshot` API. /// /// [region] is used to decide which part of the web content will be used in /// test image. It includes starting coordinate x,y as well as height and /// width of the area to capture. /// /// This method can be used for both macOS and Linux. // TODO(yjbanov): extends tests to Window, https://github.com/flutter/flutter/issues/65673 @override Future<Image> captureScreenshot(math.Rectangle<num>? region) async { final wip.ChromeConnection chromeConnection = wip.ChromeConnection('localhost', kDevtoolsPort); final wip.ChromeTab? chromeTab = await chromeConnection.getTab( (wip.ChromeTab chromeTab) => chromeTab.url.contains('localhost')); if (chromeTab == null) { throw StateError( 'Failed locate Chrome tab with the test page', ); } final wip.WipConnection wipConnection = await chromeTab.connect(); Map<String, dynamic>? captureScreenshotParameters; if (region != null) { captureScreenshotParameters = <String, dynamic>{ 'format': 'png', 'clip': <String, dynamic>{ 'x': region.left, 'y': region.top, 'width': region.width, 'height': region.height, 'scale': // This is NOT the DPI of the page, instead it's the "zoom level". 1, }, }; } // Setting hardware-independent screen parameters: // https://chromedevtools.github.io/devtools-protocol/tot/Emulation await wipConnection .sendCommand('Emulation.setDeviceMetricsOverride', <String, dynamic>{ 'width': kMaxScreenshotWidth, 'height': kMaxScreenshotHeight, 'deviceScaleFactor': 1, 'mobile': false, }); final wip.WipResponse response = await wipConnection.sendCommand( 'Page.captureScreenshot', captureScreenshotParameters); final Image screenshot = decodePng(base64.decode(response.result!['data'] as String))!; return screenshot; } } /// Used by [Chrome] to detect a glibc bug and retry launching the /// browser. /// /// Once every few thousands of launches we hit this glibc bug: /// /// https://sourceware.org/bugzilla/show_bug.cgi?id=19329. /// /// When this happens Chrome spits out something like the following then exits with code 127: /// /// Inconsistency detected by ld.so: ../elf/dl-tls.c: 493: _dl_allocate_tls_init: Assertion `listp->slotinfo[cnt].gen <= GL(dl_tls_generation)' failed! const String _kGlibcError = 'Inconsistency detected by ld.so'; Future<Process> _spawnChromiumProcess(String executable, List<String> args, { String? workingDirectory }) async { // Keep attempting to launch the browser until one of: // - Chrome launched successfully, in which case we just return from the loop. // - The tool detected an unretriable Chrome error, in which case we throw ToolExit. while (true) { final Process process = await Process.start(executable, args, workingDirectory: workingDirectory); process.stdout .transform(utf8.decoder) .transform(const LineSplitter()) .listen((String line) { print('[CHROME STDOUT]: $line'); }); // Wait until the DevTools are listening before trying to connect. This is // only required for flutter_test --platform=chrome and not flutter run. bool hitGlibcBug = false; await process.stderr .transform(utf8.decoder) .transform(const LineSplitter()) .map((String line) { print('[CHROME STDERR]:$line'); if (line.contains(_kGlibcError)) { hitGlibcBug = true; } return line; }) .firstWhere((String line) => line.startsWith('DevTools listening'), orElse: () { if (hitGlibcBug) { const String message = 'Encountered glibc bug ' 'https://sourceware.org/bugzilla/show_bug.cgi?id=19329. ' 'Will try launching browser again.'; print(message); return message; } print('Failed to launch browser. Command used to launch it: ${args.join(' ')}'); throw Exception( 'Failed to launch browser. Make sure you are using an up-to-date ' 'Chrome or Edge. Otherwise, consider using -d web-server instead ' 'and filing an issue at https://github.com/flutter/flutter/issues.', ); }); if (!hitGlibcBug) { return process; } // A precaution that avoids accumulating browser processes, in case the // glibc bug doesn't cause the browser to quit and we keep looping and // launching more processes. // It's OK to not await the future here, as this is a best-effort process // clean-up only. If we're executing this line, this means things are off // the rails already due to the glibc bug, and we're just scrambling to keep // the system stable. // ignore: unawaited_futures process.exitCode.timeout(const Duration(seconds: 1), onTimeout: () { process.kill(); return -1; }); } } /// Returns the full URL of the Chrome remote debugger for the main page. /// /// This takes the [base] remote debugger URL (which points to a browser-wide /// page) and uses its JSON API to find the resolved URL for debugging the host /// page. Future<Uri> getRemoteDebuggerUrl(Uri base) async { try { final HttpClient client = HttpClient(); final HttpClientRequest request = await client.getUrl(base.resolve('/json/list')); final HttpClientResponse response = await request.close(); final List<dynamic>? jsonObject = await json.fuse(utf8).decoder.bind(response).single as List<dynamic>?; return base.resolve((jsonObject!.first as Map<dynamic, dynamic>)['devtoolsFrontendUrl'] as String); } catch (_) { // If we fail to talk to the remote debugger protocol, give up and return // the raw URL rather than crashing. return base; } }
engine/lib/web_ui/dev/chrome.dart/0
{ "file_path": "engine/lib/web_ui/dev/chrome.dart", "repo_id": "engine", "token_count": 4887 }
391
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; import 'package:args/command_runner.dart'; import 'package:path/path.dart' as path; import 'environment.dart'; class LicensesCommand extends Command<bool> { @override final String name = 'check-licenses'; @override final String description = 'Check license headers.'; @override bool run() { _checkLicenseHeaders(); return true; } void _checkLicenseHeaders() { final List<io.File> allSourceFiles = _flatListSourceFiles(environment.webUiRootDir); _expect(allSourceFiles.isNotEmpty, 'Dart source listing of ${environment.webUiRootDir.path} must not be empty.'); final List<String> allDartPaths = allSourceFiles.map((io.File f) => f.path).toList(); for (final String expectedDirectory in const <String>[ 'lib', 'test', 'dev', ]) { final String expectedAbsoluteDirectory = path.join(environment.webUiRootDir.path, expectedDirectory); _expect( allDartPaths .where((String p) => p.startsWith(expectedAbsoluteDirectory)) .isNotEmpty, 'Must include the $expectedDirectory/ directory', ); } allSourceFiles.forEach(_expectLicenseHeader); print('License headers OK!'); } final RegExp _copyRegex = RegExp(r'// Copyright 2013 The Flutter Authors\. All rights reserved\.'); void _expectLicenseHeader(io.File file) { final List<String> head = file.readAsStringSync().split('\n').take(3).toList(); _expect(head.length >= 3, 'File too short: ${file.path}'); _expect( _copyRegex.firstMatch(head[0]) != null, 'Invalid first line of license header in file ${file.path}', ); _expect( head[1] == '// Use of this source code is governed by a BSD-style license that can be', 'Invalid second line of license header in file ${file.path}', ); _expect( head[2] == '// found in the LICENSE file.', 'Invalid third line of license header in file ${file.path}', ); } void _expect(bool value, String requirement) { if (!value) { throw Exception('Test failed: $requirement'); } } List<io.File> _flatListSourceFiles(io.Directory directory) { // This is the old path that tests used to be built into. Ignore anything // within this path. final String legacyBuildPath = path.join(environment.webUiRootDir.path, 'build'); return directory.listSync(recursive: true).whereType<io.File>().where((io.File f) { if (!f.path.endsWith('.dart') && !f.path.endsWith('.js')) { // Not a source file we're checking. return false; } if (path.isWithin(environment.webUiBuildDir.path, f.path) || path.isWithin(environment.webUiDartToolDir.path, f.path) || path.isWithin(legacyBuildPath, f.path)) { // Generated files. return false; } return true; }).toList(); } }
engine/lib/web_ui/dev/licenses.dart/0
{ "file_path": "engine/lib/web_ui/dev/licenses.dart", "repo_id": "engine", "token_count": 1177 }
392
# Copyright 2019 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import("//flutter/build/esbuild/esbuild.gni") import("//flutter/shell/version/version.gni") import("sources.gni") group("flutter_js") { public_deps = [ ":flutter_js_bundle", ":flutter_js_sources", ] } copy("flutter_js_sources") { sources = flutter_js_source_list outputs = [ "$root_out_dir/flutter_web_sdk/flutter_js/{{source_target_relative}}" ] } esbuild("flutter_js_bundle") { entry_point = "$root_out_dir/flutter_web_sdk/flutter_js/src/flutter.js" output_bundle = "$root_out_dir/flutter_web_sdk/flutter_js" bundle = true minify = true sourcemap = true public_deps = [ ":flutter_js_sources" ] }
engine/lib/web_ui/flutter_js/BUILD.gn/0
{ "file_path": "engine/lib/web_ui/flutter_js/BUILD.gn", "repo_id": "engine", "token_count": 315 }
393
// Copyright 2013 The Flutter 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 Scene { Future<Image> toImage(int width, int height); Image toImageSync(int width, int height); void dispose(); } abstract class TransformEngineLayer implements EngineLayer {} abstract class OffsetEngineLayer implements EngineLayer {} abstract class ClipRectEngineLayer implements EngineLayer {} abstract class ClipRRectEngineLayer implements EngineLayer {} abstract class ClipPathEngineLayer implements EngineLayer {} abstract class OpacityEngineLayer implements EngineLayer {} abstract class ColorFilterEngineLayer implements EngineLayer {} abstract class ImageFilterEngineLayer implements EngineLayer {} abstract class BackdropFilterEngineLayer implements EngineLayer {} abstract class ShaderMaskEngineLayer implements EngineLayer {} abstract class SceneBuilder { factory SceneBuilder() => engine.renderer.createSceneBuilder(); OffsetEngineLayer pushOffset( double dx, double dy, { OffsetEngineLayer? oldLayer, }); TransformEngineLayer pushTransform( Float64List matrix4, { TransformEngineLayer? oldLayer, }); ClipRectEngineLayer pushClipRect( Rect rect, { Clip clipBehavior = Clip.antiAlias, ClipRectEngineLayer? oldLayer, }); ClipRRectEngineLayer pushClipRRect( RRect rrect, { required Clip clipBehavior, ClipRRectEngineLayer? oldLayer, }); ClipPathEngineLayer pushClipPath( Path path, { Clip clipBehavior = Clip.antiAlias, ClipPathEngineLayer? oldLayer, }); OpacityEngineLayer pushOpacity( int alpha, { Offset offset = Offset.zero, OpacityEngineLayer? oldLayer, }); ColorFilterEngineLayer pushColorFilter( ColorFilter filter, { ColorFilterEngineLayer? oldLayer, }); ImageFilterEngineLayer pushImageFilter( ImageFilter filter, { Offset offset = Offset.zero, ImageFilterEngineLayer? oldLayer, }); BackdropFilterEngineLayer pushBackdropFilter( ImageFilter filter, { BlendMode blendMode = BlendMode.srcOver, BackdropFilterEngineLayer? oldLayer, }); ShaderMaskEngineLayer pushShaderMask( Shader shader, Rect maskRect, BlendMode blendMode, { ShaderMaskEngineLayer? oldLayer, FilterQuality filterQuality = FilterQuality.low, }); void addRetained(EngineLayer retainedLayer); void pop(); void addPerformanceOverlay(int enabledOptions, Rect bounds); void addPicture( Offset offset, Picture picture, { bool isComplexHint = false, bool willChangeHint = false, }); void addTexture( int textureId, { Offset offset = Offset.zero, double width = 0.0, double height = 0.0, bool freeze = false, FilterQuality filterQuality = FilterQuality.low, }); void addPlatformView( int viewId, { Offset offset = Offset.zero, double width = 0.0, double height = 0.0, }); void setRasterizerTracingThreshold(int frameInterval); void setCheckerboardRasterCacheImages(bool checkerboard); void setCheckerboardOffscreenLayers(bool checkerboard); Scene build(); void setProperties( double width, double height, double insetTop, double insetRight, double insetBottom, double insetLeft, bool focusable, ); } class EngineLayer { void dispose() {} }
engine/lib/web_ui/lib/compositing.dart/0
{ "file_path": "engine/lib/web_ui/lib/compositing.dart", "repo_id": "engine", "token_count": 1066 }
394
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:ui/ui.dart' as ui; /// A function that returns current system time. typedef TimestampFunction = DateTime Function(); /// Notifies the [callback] at the given [datetime]. /// /// Allows changing [datetime] in either direction before the alarm goes off. /// /// The implementation uses [Timer]s and therefore does not guarantee that it /// will go off precisely at the specified time. For more details see: /// /// https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Notes class AlarmClock { /// Initializes Alarmclock with a closure that gets called with a timestamp. AlarmClock(TimestampFunction timestampFunction) : _timestampFunction = timestampFunction; /// The function used to get current time. final TimestampFunction _timestampFunction; /// The underlying timer used to schedule the callback. Timer? _timer; /// Current target time the [callback] is scheduled for. DateTime? _datetime; /// The callback called when the alarm goes off. /// /// If this is null, the alarm goes off without calling the callback. Set the /// callback to null if the callback is a closure holding onto expensive /// resources. ui.VoidCallback? callback; /// The time when the alarm clock will go off. /// /// If the time is in the past or is `null` the alarm clock will not go off. /// /// If the value is updated before an already scheduled timer goes off, the /// previous time will not call the [callback]. Think of the updating this /// value as "changing your mind" about when you want the next timer to fire. DateTime? get datetime => _datetime; set datetime(DateTime? value) { if (value == _datetime) { return; } if (value == null) { _cancelTimer(); _datetime = null; return; } final DateTime now = _timestampFunction(); // We use the "not before" logic instead of "is after" because zero-duration // timers are valid. final bool isInTheFuture = !value.isBefore(now); if (!isInTheFuture) { _cancelTimer(); _datetime = value; return; } // At this point we have a non-null value that's in the future, and it is // different from the current _datetime. We need to decide whether we need // to create a new timer, or keep the existing one. if (_timer == null) { // We didn't have an existing timer, so create a new one. _timer = Timer(value.difference(now), _timerDidFire); } else { assert(_datetime != null, 'We can only have a timer if there is a non-null datetime'); if (_datetime!.isAfter(value)) { // This is the case when the value moves the target time to an earlier // point. Because there is no way to reconfigure an existing timer, we // must cancel the old timer and schedule a new one. _cancelTimer(); _timer = Timer(value.difference(now), _timerDidFire); } // We don't need to do anything in the "else" branch. If the new value // is in the future relative to the current datetime, the _timerDidFire // will reschedule. } _datetime = value; } void _cancelTimer() { _timer?.cancel(); _timer = null; } void _timerDidFire() { assert(_datetime != null, 'If _datetime is null, the timer would have been cancelled'); final DateTime now = _timestampFunction(); // We use the "not before" logic instead of "is after" because we may have // zero difference between now and _datetime. if (!now.isBefore(_datetime!)) { _timer = null; callback?.call(); } else { // The timer fired before the target date. We need to reschedule. _timer = Timer(_datetime!.difference(now), _timerDidFire); } } }
engine/lib/web_ui/lib/src/engine/alarm_clock.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/alarm_clock.dart", "repo_id": "engine", "token_count": 1283 }
395
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:typed_data'; import 'package:ui/ui.dart' as ui; import '../vector_math.dart'; import 'layer.dart'; import 'layer_tree.dart'; import 'path.dart'; import 'picture.dart'; class LayerScene implements ui.Scene { LayerScene(RootLayer rootLayer) : layerTree = LayerTree(rootLayer); final LayerTree layerTree; @override void dispose() {} @override Future<ui.Image> toImage(int width, int height) { final ui.Picture picture = layerTree.flatten(ui.Size( width.toDouble(), height.toDouble(), )); return picture.toImage(width, height); } @override ui.Image toImageSync(int width, int height) { final ui.Picture picture = layerTree.flatten(ui.Size( width.toDouble(), height.toDouble(), )); return picture.toImageSync(width, height); } } class LayerSceneBuilder implements ui.SceneBuilder { LayerSceneBuilder() : rootLayer = RootLayer() { currentLayer = rootLayer; } final RootLayer rootLayer; late ContainerLayer currentLayer; @override void addPerformanceOverlay(int enabledOptions, ui.Rect bounds) { // We don't plan to implement this on the web. throw UnimplementedError(); } @override void addPicture( ui.Offset offset, ui.Picture picture, { bool isComplexHint = false, bool willChangeHint = false, }) { currentLayer.add(PictureLayer( picture as CkPicture, offset, isComplexHint, willChangeHint)); } @override void addRetained(ui.EngineLayer retainedLayer) { currentLayer.add(retainedLayer as Layer); } @override void addTexture( int textureId, { ui.Offset offset = ui.Offset.zero, double width = 0.0, double height = 0.0, bool freeze = false, ui.FilterQuality filterQuality = ui.FilterQuality.low, }) { // TODO(hterkelsen): implement addTexture, b/128315641 } @override void addPlatformView( int viewId, { ui.Offset offset = ui.Offset.zero, double width = 0.0, double height = 0.0, }) { currentLayer.add(PlatformViewLayer(viewId, offset, width, height)); } @override LayerScene build() { return LayerScene(rootLayer); } @override void pop() { if (currentLayer == rootLayer) { // Don't pop the root layer. It must always be there. return; } currentLayer = currentLayer.parent!; } @override BackdropFilterEngineLayer pushBackdropFilter( ui.ImageFilter filter, { ui.BlendMode blendMode = ui.BlendMode.srcOver, ui.EngineLayer? oldLayer, }) { return pushLayer<BackdropFilterEngineLayer>(BackdropFilterEngineLayer( filter, blendMode, )); } @override ClipPathEngineLayer pushClipPath( ui.Path path, { ui.Clip clipBehavior = ui.Clip.antiAlias, ui.EngineLayer? oldLayer, }) { return pushLayer<ClipPathEngineLayer>( ClipPathEngineLayer(path as CkPath, clipBehavior)); } @override ClipRRectEngineLayer pushClipRRect( ui.RRect rrect, { ui.Clip? clipBehavior, ui.EngineLayer? oldLayer, }) { return pushLayer<ClipRRectEngineLayer>( ClipRRectEngineLayer(rrect, clipBehavior)); } @override ClipRectEngineLayer pushClipRect( ui.Rect rect, { ui.Clip clipBehavior = ui.Clip.antiAlias, ui.EngineLayer? oldLayer, }) { return pushLayer<ClipRectEngineLayer>( ClipRectEngineLayer(rect, clipBehavior)); } @override ColorFilterEngineLayer pushColorFilter( ui.ColorFilter filter, { ui.ColorFilterEngineLayer? oldLayer, }) { return pushLayer<ColorFilterEngineLayer>(ColorFilterEngineLayer(filter)); } @override ImageFilterEngineLayer pushImageFilter( ui.ImageFilter filter, { ui.ImageFilterEngineLayer? oldLayer, ui.Offset offset = ui.Offset.zero, }) { return pushLayer<ImageFilterEngineLayer>(ImageFilterEngineLayer(filter, offset)); } @override OffsetEngineLayer pushOffset( double dx, double dy, { ui.EngineLayer? oldLayer, }) { return pushLayer<OffsetEngineLayer>(OffsetEngineLayer(dx, dy)); } @override OpacityEngineLayer pushOpacity( int alpha, { ui.EngineLayer? oldLayer, ui.Offset offset = ui.Offset.zero, }) { return pushLayer<OpacityEngineLayer>(OpacityEngineLayer(alpha, offset)); } @override ShaderMaskEngineLayer pushShaderMask( ui.Shader shader, ui.Rect maskRect, ui.BlendMode blendMode, { ui.EngineLayer? oldLayer, ui.FilterQuality filterQuality = ui.FilterQuality.low, }) { return pushLayer<ShaderMaskEngineLayer>( ShaderMaskEngineLayer(shader, maskRect, blendMode, filterQuality)); } @override TransformEngineLayer pushTransform( Float64List matrix4, { ui.EngineLayer? oldLayer, }) { final Matrix4 matrix = Matrix4.fromFloat32List(toMatrix32(matrix4)); return pushLayer<TransformEngineLayer>(TransformEngineLayer(matrix)); } @override void setCheckerboardOffscreenLayers(bool checkerboard) { // TODO(hterkelsen): implement setCheckerboardOffscreenLayers } @override void setCheckerboardRasterCacheImages(bool checkerboard) { // TODO(hterkelsen): implement setCheckerboardRasterCacheImages } @override void setRasterizerTracingThreshold(int frameInterval) { // TODO(hterkelsen): implement setRasterizerTracingThreshold } T pushLayer<T extends ContainerLayer>(T layer) { currentLayer.add(layer); currentLayer = layer; return layer; } @override void setProperties( double width, double height, double insetTop, double insetRight, double insetBottom, double insetLeft, bool focusable, ) { throw UnimplementedError(); } }
engine/lib/web_ui/lib/src/engine/canvaskit/layer_scene_builder.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/canvaskit/layer_scene_builder.dart", "repo_id": "engine", "token_count": 2132 }
396
// Copyright 2013 The Flutter 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:js_interop'; import 'package:ui/ui.dart' as ui; import '../display.dart'; import '../dom.dart'; import 'rasterizer.dart'; /// A visible (on-screen) canvas that can display bitmaps produced by CanvasKit /// in the (off-screen) SkSurface which is backed by an OffscreenCanvas. /// /// In a typical frame, the content will be rendered via CanvasKit in an /// OffscreenCanvas, and then the contents will be transferred to the /// RenderCanvas via `transferFromImageBitmap()`. /// /// If we need more RenderCanvases, for example in the case where there are /// platform views and we need overlays to render the frame correctly, then /// we will create multiple RenderCanvases, but crucially still only have /// one OffscreenCanvas which transfers bitmaps to all of the RenderCanvases. /// /// To render into the OffscreenCanvas with CanvasKit we need to create a /// WebGL context, which is not only expensive, but the browser has a limit /// on the maximum amount of WebGL contexts which can be live at once. Using /// a single OffscreenCanvas and multiple RenderCanvases allows us to only /// create a single WebGL context. class RenderCanvas extends DisplayCanvas { RenderCanvas() { canvasElement.setAttribute('aria-hidden', 'true'); canvasElement.style.position = 'absolute'; _updateLogicalHtmlCanvasSize(); hostElement.append(canvasElement); } /// The root HTML element for this canvas. /// /// This element contains the canvas used to draw the UI. Unlike the canvas, /// this element is permanent. It is never replaced or deleted, until this /// canvas is disposed of via [dispose]. /// /// Conversely, the canvas that lives inside this element can be swapped, for /// example, when the screen size changes, or when the WebGL context is lost /// due to the browser tab becoming dormant. @override final DomElement hostElement = createDomElement('flt-canvas-container'); /// The underlying `<canvas>` element used to display the pixels. final DomCanvasElement canvasElement = createDomCanvasElement(); int _pixelWidth = 0; int _pixelHeight = 0; late final DomCanvasRenderingContextBitmapRenderer renderContext = canvasElement.contextBitmapRenderer; late final DomCanvasRenderingContext2D renderContext2d = canvasElement.context2D; double _currentDevicePixelRatio = -1; /// Sets the CSS size of the canvas so that canvas pixels are 1:1 with device /// pixels. /// /// The logical size of the canvas is not based on the size of the window /// but on the size of the canvas, which, due to `ceil()` above, may not be /// the same as the window. We do not round/floor/ceil the logical size as /// CSS pixels can contain more than one physical pixel and therefore to /// match the size of the window precisely we use the most precise floating /// point value we can get. void _updateLogicalHtmlCanvasSize() { final double devicePixelRatio = EngineFlutterDisplay.instance.devicePixelRatio; final double logicalWidth = _pixelWidth / devicePixelRatio; final double logicalHeight = _pixelHeight / devicePixelRatio; final DomCSSStyleDeclaration style = canvasElement.style; style.width = '${logicalWidth}px'; style.height = '${logicalHeight}px'; _currentDevicePixelRatio = devicePixelRatio; } /// Render the given [bitmap] with this [RenderCanvas]. /// /// The canvas will be resized to accomodate the bitmap immediately before /// rendering it. void render(DomImageBitmap bitmap) { _ensureSize(ui.Size(bitmap.width.toDartDouble, bitmap.height.toDartDouble)); renderContext.transferFromImageBitmap(bitmap); } void renderWithNoBitmapSupport( DomCanvasImageSource imageSource, int sourceHeight, ui.Size size, ) { _ensureSize(size); renderContext2d.drawImage( imageSource, 0, sourceHeight - size.height, size.width, size.height, 0, 0, size.width, size.height, ); } /// Ensures that this canvas can draw a frame of the given [size]. void _ensureSize(ui.Size size) { // Check if the frame is the same size as before, and if so, we don't need // to resize the canvas. if (size.width.ceil() == _pixelWidth && size.height.ceil() == _pixelHeight) { // The existing canvas doesn't need to be resized (unless the device pixel // ratio changed). if (EngineFlutterDisplay.instance.devicePixelRatio != _currentDevicePixelRatio) { _updateLogicalHtmlCanvasSize(); } return; } // If the canvas is too large or too small, resize it to the exact size of // the frame. We cannot allow the canvas to be larger than the screen // because then when we call `transferFromImageBitmap()` the bitmap will // be scaled to cover the entire canvas. _pixelWidth = size.width.ceil(); _pixelHeight = size.height.ceil(); canvasElement.width = _pixelWidth.toDouble(); canvasElement.height = _pixelHeight.toDouble(); _updateLogicalHtmlCanvasSize(); } @override bool get isConnected => canvasElement.isConnected!; @override void initialize() { // No extra initialization needed. } @override void dispose() { hostElement.remove(); } }
engine/lib/web_ui/lib/src/engine/canvaskit/render_canvas.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/canvaskit/render_canvas.dart", "repo_id": "engine", "token_count": 1685 }
397
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:ui/src/engine.dart'; abstract class FallbackFontRegistry { List<int> getMissingCodePoints(List<int> codePoints, List<String> fontFamilies); Future<void> loadFallbackFont(String familyName, String string); void updateFallbackFontFamilies(List<String> families); } /// Global static font fallback data. class FontFallbackManager { factory FontFallbackManager(FallbackFontRegistry registry) => FontFallbackManager._( registry, getFallbackFontList(configuration.useColorEmoji) ); FontFallbackManager._(this.registry, this.fallbackFonts) : _notoSansSC = fallbackFonts.singleWhere((NotoFont font) => font.name == 'Noto Sans SC'), _notoSansTC = fallbackFonts.singleWhere((NotoFont font) => font.name == 'Noto Sans TC'), _notoSansHK = fallbackFonts.singleWhere((NotoFont font) => font.name == 'Noto Sans HK'), _notoSansJP = fallbackFonts.singleWhere((NotoFont font) => font.name == 'Noto Sans JP'), _notoSansKR = fallbackFonts.singleWhere((NotoFont font) => font.name == 'Noto Sans KR'), _notoSymbols = fallbackFonts.singleWhere((NotoFont font) => font.name == 'Noto Sans Symbols') { downloadQueue = FallbackFontDownloadQueue(this); } final FallbackFontRegistry registry; late final FallbackFontDownloadQueue downloadQueue; /// Code points that no known font has a glyph for. final Set<int> codePointsWithNoKnownFont = <int>{}; /// Code points which are known to be covered by at least one fallback font. final Set<int> knownCoveredCodePoints = <int>{}; final List<NotoFont> fallbackFonts; final NotoFont _notoSansSC; final NotoFont _notoSansTC; final NotoFont _notoSansHK; final NotoFont _notoSansJP; final NotoFont _notoSansKR; final NotoFont _notoSymbols; Future<void> _idleFuture = Future<void>.value(); final List<String> globalFontFallbacks = <String>['Roboto']; /// A list of code points to check against the global fallback fonts. final Set<int> _codePointsToCheckAgainstFallbackFonts = <int>{}; /// This is [true] if we have scheduled a check for missing code points. /// /// We only do this once a frame, since checking if a font supports certain /// code points is very expensive. bool _scheduledCodePointCheck = false; Future<void> debugWhenIdle() { Future<void>? result; assert(() { result = _idleFuture; return true; }()); if (result != null) { return result!; } throw UnimplementedError(); } /// Determines if the given [text] contains any code points which are not /// supported by the current set of fonts. void ensureFontsSupportText(String text, List<String> fontFamilies) { // TODO(hterkelsen): Make this faster for the common case where the text // is supported by the given fonts. if (debugDisableFontFallbacks) { return; } // We have a cache of code points which are known to be covered by at least // one of our fallback fonts, and a cache of code points which are known not // to be covered by any fallback font. From the given text, construct a set // of code points which need to be checked. final Set<int> runesToCheck = <int>{}; for (final int rune in text.runes) { // Filter out code points that don't need checking. if (!(rune < 160 || // ASCII and Unicode control points. knownCoveredCodePoints.contains(rune) || // Points we've already covered codePointsWithNoKnownFont.contains(rune)) // Points that don't have a fallback font ) { runesToCheck.add(rune); } } if (runesToCheck.isEmpty) { return; } final List<int> codePoints = runesToCheck.toList(); final List<int> missingCodePoints = registry.getMissingCodePoints(codePoints, fontFamilies); if (missingCodePoints.isNotEmpty) { addMissingCodePoints(codePoints); } } void addMissingCodePoints(List<int> codePoints) { _codePointsToCheckAgainstFallbackFonts.addAll(codePoints); if (!_scheduledCodePointCheck) { _scheduledCodePointCheck = true; _idleFuture = Future<void>.delayed(Duration.zero, () async { _ensureFallbackFonts(); _scheduledCodePointCheck = false; await downloadQueue.waitForIdle(); }); } } /// Checks the missing code points against the current set of fallback fonts /// and starts downloading new fallback fonts if the current set can't cover /// the code points. void _ensureFallbackFonts() { _scheduledCodePointCheck = false; // We don't know if the remaining code points are covered by our fallback // fonts. Check them and update the cache. if (_codePointsToCheckAgainstFallbackFonts.isEmpty) { return; } final List<int> codePoints = _codePointsToCheckAgainstFallbackFonts.toList(); _codePointsToCheckAgainstFallbackFonts.clear(); findFontsForMissingCodePoints(codePoints); } void registerFallbackFont(String family) { // Insert emoji font before all other fallback fonts so we use the emoji // whenever it's available. if (family == 'Noto Color Emoji' || family == 'Noto Emoji') { if (globalFontFallbacks.first == 'Roboto') { globalFontFallbacks.insert(1, family); } else { globalFontFallbacks.insert(0, family); } } else { globalFontFallbacks.add(family); } } /// Finds the minimum set of fonts which covers all of the [codePoints]. /// /// Since set cover is NP-complete, we approximate using a greedy algorithm /// which finds the font which covers the most code points. If multiple CJK /// fonts match the same number of code points, we choose one based on the /// user's locale. /// /// If a code point is not covered by any font, it is added to /// [codePointsWithNoKnownFont] so it can be omitted next time to avoid /// searching for fonts unnecessarily. void findFontsForMissingCodePoints(List<int> codePoints) { final List<int> missingCodePoints = <int>[]; final List<FallbackFontComponent> requiredComponents = <FallbackFontComponent>[]; final List<NotoFont> candidateFonts = <NotoFont>[]; // Collect the components that cover the code points. for (final int codePoint in codePoints) { final FallbackFontComponent component = codePointToComponents.lookup(codePoint); if (component.fonts.isEmpty) { missingCodePoints.add(codePoint); } else { // A zero cover count means we have not yet seen this component. if (component.coverCount == 0) { requiredComponents.add(component); } component.coverCount++; } } // Aggregate the component cover counts to the fonts that use the component. for (final FallbackFontComponent component in requiredComponents) { for (final NotoFont font in component.fonts) { // A zero cover cover count means we have not yet seen this font. if (font.coverCount == 0) { candidateFonts.add(font); } font.coverCount += component.coverCount; font.coverComponents.add(component); } } final List<NotoFont> selectedFonts = <NotoFont>[]; while (candidateFonts.isNotEmpty) { final NotoFont selectedFont = _selectFont(candidateFonts); selectedFonts.add(selectedFont); // All the code points in the selected font are now covered. Zero out each // component that is used by the font and adjust the counts of other fonts // that use the same components. for (final FallbackFontComponent component in <FallbackFontComponent>[ ...selectedFont.coverComponents ]) { for (final NotoFont font in component.fonts) { font.coverCount -= component.coverCount; font.coverComponents.remove(component); } component.coverCount = 0; } assert(selectedFont.coverCount == 0); assert(selectedFont.coverComponents.isEmpty); // The selected font will have a zero cover count, but other fonts may // too. Remove these from further consideration. candidateFonts.removeWhere((NotoFont font) => font.coverCount == 0); } selectedFonts.forEach(downloadQueue.add); // Report code points not covered by any fallback font and ensure we don't // process those code points again. if (missingCodePoints.isNotEmpty) { if (!downloadQueue.isPending) { printWarning( 'Could not find a set of Noto fonts to display all missing ' 'characters. Please add a font asset for the missing characters.' ' See: https://flutter.dev/docs/cookbook/design/fonts'); codePointsWithNoKnownFont.addAll(missingCodePoints); } } } NotoFont _selectFont(List<NotoFont> fonts) { int maxCodePointsCovered = -1; final List<NotoFont> bestFonts = <NotoFont>[]; NotoFont? bestFont; for (final NotoFont font in fonts) { if (font.coverCount > maxCodePointsCovered) { bestFonts.clear(); bestFonts.add(font); bestFont = font; maxCodePointsCovered = font.coverCount; } else if (font.coverCount == maxCodePointsCovered) { bestFonts.add(font); // Tie-break with the lowest index which corresponds to a font name // being earlier in the list of fonts in the font fallback data // generator. if (font.index < bestFont!.index) { bestFont = font; } } } // If the list of best fonts are all CJK fonts, choose the best one based // on locale. Otherwise just choose the first font. if (bestFonts.length > 1) { if (bestFonts.every((NotoFont font) => font == _notoSansSC || font == _notoSansTC || font == _notoSansHK || font == _notoSansJP || font == _notoSansKR)) { final String language = domWindow.navigator.language; if (language == 'zh-Hans' || language == 'zh-CN' || language == 'zh-SG' || language == 'zh-MY') { if (bestFonts.contains(_notoSansSC)) { bestFont = _notoSansSC; } } else if (language == 'zh-Hant' || language == 'zh-TW' || language == 'zh-MO') { if (bestFonts.contains(_notoSansTC)) { bestFont = _notoSansTC; } } else if (language == 'zh-HK') { if (bestFonts.contains(_notoSansHK)) { bestFont = _notoSansHK; } } else if (language == 'ja') { if (bestFonts.contains(_notoSansJP)) { bestFont = _notoSansJP; } } else if (language == 'ko') { if (bestFonts.contains(_notoSansKR)) { bestFont = _notoSansKR; } } else if (bestFonts.contains(_notoSansSC)) { bestFont = _notoSansSC; } } else { // To be predictable, if there is a tie for best font, choose a font // from this list first, then just choose the first font. if (bestFonts.contains(_notoSymbols)) { bestFont = _notoSymbols; } else if (bestFonts.contains(_notoSansSC)) { bestFont = _notoSansSC; } } } return bestFont!; } late final List<FallbackFontComponent> fontComponents = _decodeFontComponents(encodedFontSets); late final _UnicodePropertyLookup<FallbackFontComponent> codePointToComponents = _UnicodePropertyLookup<FallbackFontComponent>.fromPackedData( encodedFontSetRanges, fontComponents); List<FallbackFontComponent> _decodeFontComponents(String data) { return <FallbackFontComponent>[ for (final String componentData in data.split(',')) FallbackFontComponent(_decodeFontSet(componentData)) ]; } List<NotoFont> _decodeFontSet(String data) { final List<NotoFont> result = <NotoFont>[]; int previousIndex = -1; int prefix = 0; for (int i = 0; i < data.length; i++) { final int code = data.codeUnitAt(i); if (kFontIndexDigit0 <= code && code < kFontIndexDigit0 + kFontIndexRadix) { final int delta = prefix * kFontIndexRadix + (code - kFontIndexDigit0); final int index = previousIndex + delta + 1; result.add(fallbackFonts[index]); previousIndex = index; prefix = 0; } else if (kPrefixDigit0 <= code && code < kPrefixDigit0 + kPrefixRadix) { prefix = prefix * kPrefixRadix + (code - kPrefixDigit0); } else { throw StateError('Unreachable'); } } return result; } } /// A lookup structure from code point to a property type [P]. class _UnicodePropertyLookup<P> { _UnicodePropertyLookup._(this._boundaries, this._values); factory _UnicodePropertyLookup.fromPackedData( String packedData, List<P> propertyEnumValues, ) { final List<int> boundaries = <int>[]; final List<P> values = <P>[]; int start = 0; int prefix = 0; int size = 1; for (int i = 0; i < packedData.length; i++) { final int code = packedData.codeUnitAt(i); if (kRangeValueDigit0 <= code && code < kRangeValueDigit0 + kRangeValueRadix) { final int index = prefix * kRangeValueRadix + (code - kRangeValueDigit0); final P value = propertyEnumValues[index]; start += size; boundaries.add(start); values.add(value); prefix = 0; size = 1; } else if (kRangeSizeDigit0 <= code && code < kRangeSizeDigit0 + kRangeSizeRadix) { size = prefix * kRangeSizeRadix + (code - kRangeSizeDigit0) + 2; prefix = 0; } else if (kPrefixDigit0 <= code && code < kPrefixDigit0 + kPrefixRadix) { prefix = prefix * kPrefixRadix + (code - kPrefixDigit0); } else { throw StateError('Unreachable'); } } if (start != kMaxCodePoint + 1) { throw StateError('Bad map size: $start'); } return _UnicodePropertyLookup<P>._(boundaries, values); } /// There are two parallel lists - one of boundaries between adjacent unicode /// ranges and second of the values for the ranges. /// /// `_boundaries[i]` is the open-interval end of the `i`th range and the start /// of the `i+1`th range. The implicit start of the 0th range is zero. /// /// `_values[i]` is the value for the range [`_boundaries[i-1]`, `_boundaries[i]`). /// Default values are stored as explicit ranges. /// /// Example: the unicode range properies `[10-50]=>A`, `[100]=>B`, with /// default value `X` would be represented as: /// /// boundaries: [10, 51, 100, 101, 1114112] /// values: [ X, A, X, B, X] /// final List<int> _boundaries; final List<P> _values; int get length => _boundaries.length; P lookup(int value) { assert(0 <= value && value <= kMaxCodePoint); assert(_boundaries.last == kMaxCodePoint + 1); int start = 0, end = _boundaries.length; while (true) { if (start == end) { return _values[start]; } final int mid = start + (end - start) ~/ 2; if (value >= _boundaries[mid]) { start = mid + 1; } else { end = mid; } } } /// Iterate over the ranges, calling [action] with the start and end /// (inclusive) code points and value. void forEachRange(void Function(int start, int end, P value) action) { int start = 0; for (int i = 0; i < _boundaries.length; i++) { final int end = _boundaries[i]; final P value = _values[i]; action(start, end - 1, value); start = end; } } } class FallbackFontDownloadQueue { FallbackFontDownloadQueue(this.fallbackManager); final FontFallbackManager fallbackManager; static const String _defaultFallbackFontsUrlPrefix = 'https://fonts.gstatic.com/s/'; String? fallbackFontUrlPrefixOverride; String get fallbackFontUrlPrefix => fallbackFontUrlPrefixOverride ?? _defaultFallbackFontsUrlPrefix; final Set<NotoFont> downloadedFonts = <NotoFont>{}; final Map<String, NotoFont> pendingFonts = <String, NotoFont>{}; bool get isPending => pendingFonts.isNotEmpty; void Function(String family)? debugOnLoadFontFamily; Completer<void>? _idleCompleter; Future<void> waitForIdle() { if (_idleCompleter == null) { // We're already idle return Future<void>.value(); } else { return _idleCompleter!.future; } } void add(NotoFont font) { if (downloadedFonts.contains(font) || pendingFonts.containsKey(font.url)) { return; } final bool firstInBatch = pendingFonts.isEmpty; pendingFonts[font.url] = font; _idleCompleter ??= Completer<void>(); if (firstInBatch) { Timer.run(startDownloads); } } Future<void> startDownloads() async { final Map<String, Future<void>> downloads = <String, Future<void>>{}; final List<String> downloadedFontFamilies = <String>[]; for (final NotoFont font in pendingFonts.values) { downloads[font.url] = Future<void>(() async { try { final String url = '$fallbackFontUrlPrefix${font.url}'; debugOnLoadFontFamily?.call(font.name); await fallbackManager.registry.loadFallbackFont(font.name, url); downloadedFontFamilies.add(font.url); } catch (e) { pendingFonts.remove(font.url); printWarning('Failed to load font ${font.name} at ${font.url}'); printWarning(e.toString()); return; } downloadedFonts.add(font); }); } await Future.wait<void>(downloads.values); // Register fallback fonts in a predictable order. Otherwise, the fonts // change their precedence depending on the download order causing // visual differences between app reloads. downloadedFontFamilies.sort(); for (final String url in downloadedFontFamilies) { final NotoFont font = pendingFonts.remove(url)!; fallbackManager.registerFallbackFont(font.name); } if (pendingFonts.isEmpty) { fallbackManager.registry .updateFallbackFontFamilies(fallbackManager.globalFontFallbacks); sendFontChangeMessage(); final Completer<void> idleCompleter = _idleCompleter!; _idleCompleter = null; idleCompleter.complete(); } else { await startDownloads(); } } }
engine/lib/web_ui/lib/src/engine/font_fallbacks.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/font_fallbacks.dart", "repo_id": "engine", "token_count": 7050 }
398
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math' as math; import 'dart:typed_data'; import 'path_utils.dart'; /// Chops cubic at Y extrema points and writes result to [dest]. /// /// [points] and [dest] are allowed to share underlying storage as long. int chopCubicAtYExtrema(Float32List points, Float32List dest) { final double y0 = points[1]; final double y1 = points[3]; final double y2 = points[5]; final double y3 = points[7]; final QuadRoots quadRoots = _findCubicExtrema(y0, y1, y2, y3); final List<double> roots = quadRoots.roots; if (roots.isEmpty) { // No roots, just use input cubic. return 0; } _chopCubicAt(roots, points, dest); final int rootCount = roots.length; if (rootCount > 0) { // Cleanup to ensure Y extrema are flat. dest[5] = dest[9] = dest[7]; if (rootCount == 2) { dest[11] = dest[15] = dest[13]; } } return rootCount; } QuadRoots _findCubicExtrema(double a, double b, double c, double d) { // A,B,C scaled by 1/3 to simplify final double A = d - a + 3 * (b - c); final double B = 2 * (a - b - b + c); final double C = b - a; return QuadRoots()..findRoots(A, B, C); } /// Subdivides cubic curve for a list of t values. void _chopCubicAt( List<double> tValues, Float32List points, Float32List outPts) { assert(() { for (int i = 0; i < tValues.length - 1; i++) { final double tValue = tValues[i]; assert(tValue > 0 && tValue < 1, 'Not expecting to chop curve at start, end points'); } for (int i = 0; i < tValues.length - 1; i++) { final double tValue = tValues[i]; final double nextTValue = tValues[i + 1]; assert( nextTValue > tValue, 'Expecting t value to monotonically increase'); } return true; }()); final int rootCount = tValues.length; if (0 == rootCount) { for (int i = 0; i < 8; i++) { outPts[i] = points[i]; } } else { // Chop curve at t value and loop through right side of curve // while normalizing t value based on prior t. double? t = tValues[0]; int bufferPos = 0; for (int i = 0; i < rootCount; i++) { _chopCubicAtT(points, bufferPos, outPts, bufferPos, t!); if (i == rootCount - 1) { break; } bufferPos += 6; // watch out in case the renormalized t isn't in range if ((t = validUnitDivide( tValues[i + 1] - tValues[i], 1.0 - tValues[i])) == null) { // Can't renormalize last point, just create a degenerate cubic. outPts[bufferPos + 4] = outPts[bufferPos + 5] = outPts[bufferPos + 6] = points[bufferPos + 3]; break; } } } } /// Subdivides cubic curve at [t] and writes to [outPts] at position [outIndex]. /// /// The cubic points are read from [points] at [bufferPos] offset. void _chopCubicAtT(Float32List points, int bufferPos, Float32List outPts, int outIndex, double t) { assert(t > 0 && t < 1); final double p3y = points[bufferPos + 7]; final double p0x = points[bufferPos + 0]; final double p0y = points[bufferPos + 1]; final double p1x = points[bufferPos + 2]; final double p1y = points[bufferPos + 3]; final double p2x = points[bufferPos + 4]; final double p2y = points[bufferPos + 5]; final double p3x = points[bufferPos + 6]; // If startT == 0 chop at end point and return curve. final double ab1x = interpolate(p0x, p1x, t); final double ab1y = interpolate(p0y, p1y, t); final double bc1x = interpolate(p1x, p2x, t); final double bc1y = interpolate(p1y, p2y, t); final double cd1x = interpolate(p2x, p3x, t); final double cd1y = interpolate(p2y, p3y, t); final double abc1x = interpolate(ab1x, bc1x, t); final double abc1y = interpolate(ab1y, bc1y, t); final double bcd1x = interpolate(bc1x, cd1x, t); final double bcd1y = interpolate(bc1y, cd1y, t); final double abcd1x = interpolate(abc1x, bcd1x, t); final double abcd1y = interpolate(abc1y, bcd1y, t); // Return left side of curve. outPts[outIndex++] = p0x; outPts[outIndex++] = p0y; outPts[outIndex++] = ab1x; outPts[outIndex++] = ab1y; outPts[outIndex++] = abc1x; outPts[outIndex++] = abc1y; outPts[outIndex++] = abcd1x; outPts[outIndex++] = abcd1y; // Return right side of curve. outPts[outIndex++] = bcd1x; outPts[outIndex++] = bcd1y; outPts[outIndex++] = cd1x; outPts[outIndex++] = cd1y; outPts[outIndex++] = p3x; outPts[outIndex++] = p3y; } // Returns t at Y for cubic curve. null if y is out of range. // // Options are Newton Raphson (quadratic convergence with typically // 3 iterations or bisection with 16 iterations. double? chopMonoAtY(Float32List buffer, int bufferStartPos, double y) { // Translate curve points relative to y. final double ycrv0 = buffer[1 + bufferStartPos] - y; final double ycrv1 = buffer[3 + bufferStartPos] - y; final double ycrv2 = buffer[5 + bufferStartPos] - y; final double ycrv3 = buffer[7 + bufferStartPos] - y; // Positive and negative function parameters. double tNeg, tPos; // Set initial t points to converge from. if (ycrv0 < 0) { if (ycrv3 < 0) { // Start and end points out of range. return null; } tNeg = 0; tPos = 1.0; } else if (ycrv0 > 0) { tNeg = 1.0; tPos = 0; } else { // Start is at y. return 0.0; } // Bisection / linear convergance. const double tolerance = 1.0 / 65536; do { final double tMid = (tPos + tNeg) / 2.0; final double y01 = ycrv0 + (ycrv1 - ycrv0) * tMid; final double y12 = ycrv1 + (ycrv2 - ycrv1) * tMid; final double y23 = ycrv2 + (ycrv3 - ycrv2) * tMid; final double y012 = y01 + (y12 - y01) * tMid; final double y123 = y12 + (y23 - y12) * tMid; final double y0123 = y012 + (y123 - y012) * tMid; if (y0123 == 0) { return tMid; } if (y0123 < 0) { tNeg = tMid; } else { tPos = tMid; } } while ((tPos - tNeg).abs() > tolerance); return (tNeg + tPos) / 2; } double evalCubicPts(double c0, double c1, double c2, double c3, double t) { final double A = c3 + 3 * (c1 - c2) - c0; final double B = 3 * (c2 - c1 - c1 + c0); final double C = 3 * (c1 - c0); final double D = c0; return polyEval4(A, B, C, D, t); } // Reusable class to compute bounds without object allocation. class CubicBounds { double minX = 0.0; double maxX = 0.0; double minY = 0.0; double maxY = 0.0; /// Sets resulting bounds as [minX], [minY], [maxX], [maxY]. /// /// The cubic is defined by 4 points (8 floats) in [points]. void calculateBounds(Float32List points, int pointIndex) { final double startX = points[pointIndex++]; final double startY = points[pointIndex++]; final double cpX1 = points[pointIndex++]; final double cpY1 = points[pointIndex++]; final double cpX2 = points[pointIndex++]; final double cpY2 = points[pointIndex++]; final double endX = points[pointIndex++]; final double endY = points[pointIndex++]; // Bounding box is defined by all points on the curve where // monotonicity changes. minX = math.min(startX, endX); minY = math.min(startY, endY); maxX = math.max(startX, endX); maxY = math.max(startY, endY); double extremaX; double extremaY; double a, b, c; // Check for simple case of strong ordering before calculating // extrema if (!(((startX < cpX1) && (cpX1 < cpX2) && (cpX2 < endX)) || ((startX > cpX1) && (cpX1 > cpX2) && (cpX2 > endX)))) { // The extrema point is dx/dt B(t) = 0 // The derivative of B(t) for cubic bezier is a quadratic equation // with multiple roots // B'(t) = a*t*t + b*t + c*t a = -startX + (3 * (cpX1 - cpX2)) + endX; b = 2 * (startX - (2 * cpX1) + cpX2); c = -startX + cpX1; // Now find roots for quadratic equation with known coefficients // a,b,c // The roots are (-b+-sqrt(b*b-4*a*c)) / 2a num s = (b * b) - (4 * a * c); // If s is negative, we have no real roots if ((s >= 0.0) && (a.abs() > SPath.scalarNearlyZero)) { if (s == 0.0) { // we have only 1 root final double t = -b / (2 * a); final double tprime = 1.0 - t; if ((t >= 0.0) && (t <= 1.0)) { extremaX = ((tprime * tprime * tprime) * startX) + ((3 * tprime * tprime * t) * cpX1) + ((3 * tprime * t * t) * cpX2) + (t * t * t * endX); minX = math.min(extremaX, minX); maxX = math.max(extremaX, maxX); } } else { // we have 2 roots s = math.sqrt(s); double t = (-b - s) / (2 * a); double tprime = 1.0 - t; if ((t >= 0.0) && (t <= 1.0)) { extremaX = ((tprime * tprime * tprime) * startX) + ((3 * tprime * tprime * t) * cpX1) + ((3 * tprime * t * t) * cpX2) + (t * t * t * endX); minX = math.min(extremaX, minX); maxX = math.max(extremaX, maxX); } // check 2nd root t = (-b + s) / (2 * a); tprime = 1.0 - t; if ((t >= 0.0) && (t <= 1.0)) { extremaX = ((tprime * tprime * tprime) * startX) + ((3 * tprime * tprime * t) * cpX1) + ((3 * tprime * t * t) * cpX2) + (t * t * t * endX); minX = math.min(extremaX, minX); maxX = math.max(extremaX, maxX); } } } } // Now calc extremes for dy/dt = 0 just like above if (!(((startY < cpY1) && (cpY1 < cpY2) && (cpY2 < endY)) || ((startY > cpY1) && (cpY1 > cpY2) && (cpY2 > endY)))) { // The extrema point is dy/dt B(t) = 0 // The derivative of B(t) for cubic bezier is a quadratic equation // with multiple roots // B'(t) = a*t*t + b*t + c*t a = -startY + (3 * (cpY1 - cpY2)) + endY; b = 2 * (startY - (2 * cpY1) + cpY2); c = -startY + cpY1; // Now find roots for quadratic equation with known coefficients // a,b,c // The roots are (-b+-sqrt(b*b-4*a*c)) / 2a double s = (b * b) - (4 * a * c); // If s is negative, we have no real roots if ((s >= 0.0) && (a.abs() > SPath.scalarNearlyZero)) { if (s == 0.0) { // we have only 1 root final double t = -b / (2 * a); final double tprime = 1.0 - t; if ((t >= 0.0) && (t <= 1.0)) { extremaY = ((tprime * tprime * tprime) * startY) + ((3 * tprime * tprime * t) * cpY1) + ((3 * tprime * t * t) * cpY2) + (t * t * t * endY); minY = math.min(extremaY, minY); maxY = math.max(extremaY, maxY); } } else { // we have 2 roots s = math.sqrt(s); final double t = (-b - s) / (2 * a); final double tprime = 1.0 - t; if ((t >= 0.0) && (t <= 1.0)) { extremaY = ((tprime * tprime * tprime) * startY) + ((3 * tprime * tprime * t) * cpY1) + ((3 * tprime * t * t) * cpY2) + (t * t * t * endY); minY = math.min(extremaY, minY); maxY = math.max(extremaY, maxY); } // check 2nd root final double t2 = (-b + s) / (2 * a); final double tprime2 = 1.0 - t2; if ((t2 >= 0.0) && (t2 <= 1.0)) { extremaY = ((tprime2 * tprime2 * tprime2) * startY) + ((3 * tprime2 * tprime2 * t2) * cpY1) + ((3 * tprime2 * t2 * t2) * cpY2) + (t2 * t2 * t2 * endY); minY = math.min(extremaY, minY); maxY = math.max(extremaY, maxY); } } } } } } /// Chops cubic spline at startT and stopT, writes result to buffer. void chopCubicBetweenT( List<double> points, double startT, double stopT, Float32List buffer) { assert(startT != 0 || stopT != 0); final double p3y = points[7]; final double p0x = points[0]; final double p0y = points[1]; final double p1x = points[2]; final double p1y = points[3]; final double p2x = points[4]; final double p2y = points[5]; final double p3x = points[6]; // If startT == 0 chop at end point and return curve. final bool chopStart = startT != 0; final double t = chopStart ? startT : stopT; final double ab1x = interpolate(p0x, p1x, t); final double ab1y = interpolate(p0y, p1y, t); final double bc1x = interpolate(p1x, p2x, t); final double bc1y = interpolate(p1y, p2y, t); final double cd1x = interpolate(p2x, p3x, t); final double cd1y = interpolate(p2y, p3y, t); final double abc1x = interpolate(ab1x, bc1x, t); final double abc1y = interpolate(ab1y, bc1y, t); final double bcd1x = interpolate(bc1x, cd1x, t); final double bcd1y = interpolate(bc1y, cd1y, t); final double abcd1x = interpolate(abc1x, bcd1x, t); final double abcd1y = interpolate(abc1y, bcd1y, t); if (!chopStart) { // Return left side of curve. buffer[0] = p0x; buffer[1] = p0y; buffer[2] = ab1x; buffer[3] = ab1y; buffer[4] = abc1x; buffer[5] = abc1y; buffer[6] = abcd1x; buffer[7] = abcd1y; return; } if (stopT == 1) { // Return right side of curve. buffer[0] = abcd1x; buffer[1] = abcd1y; buffer[2] = bcd1x; buffer[3] = bcd1y; buffer[4] = cd1x; buffer[5] = cd1y; buffer[6] = p3x; buffer[7] = p3y; return; } // We chopped at startT, now the right hand side of curve is at // abcd1, bcd1, cd1, p3x, p3y. Chop this part using endT; final double endT = (stopT - startT) / (1 - startT); final double ab2x = interpolate(abcd1x, bcd1x, endT); final double ab2y = interpolate(abcd1y, bcd1y, endT); final double bc2x = interpolate(bcd1x, cd1x, endT); final double bc2y = interpolate(bcd1y, cd1y, endT); final double cd2x = interpolate(cd1x, p3x, endT); final double cd2y = interpolate(cd1y, p3y, endT); final double abc2x = interpolate(ab2x, bc2x, endT); final double abc2y = interpolate(ab2y, bc2y, endT); final double bcd2x = interpolate(bc2x, cd2x, endT); final double bcd2y = interpolate(bc2y, cd2y, endT); final double abcd2x = interpolate(abc2x, bcd2x, endT); final double abcd2y = interpolate(abc2y, bcd2y, endT); buffer[0] = abcd1x; buffer[1] = abcd1y; buffer[2] = ab2x; buffer[3] = ab2y; buffer[4] = abc2x; buffer[5] = abc2y; buffer[6] = abcd2x; buffer[7] = abcd2y; }
engine/lib/web_ui/lib/src/engine/html/path/cubic.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/html/path/cubic.dart", "repo_id": "engine", "token_count": 6728 }
399