From 1c21164f3093633cd6252588c3591a8684588019 Mon Sep 17 00:00:00 2001 From: Chinmay Garde Date: Fri, 25 Feb 2022 14:50:32 -0800 Subject: [PATCH] Add `//impeller/typographer`. (flutter/engine#36) Renders shaped text frames. Has the ability to plug into to different text shapers and render glyphs using different techniques. For now, the Aiks layer expects a prepared glyph atlas. But this will be changed so that render pass will be responsible for preparing these and setting these on the content renderer after pass consolidation. --- engine/src/flutter/impeller/BUILD.gn | 2 + .../flutter/impeller/aiks/aiks_unittests.cc | 112 ++++++++ engine/src/flutter/impeller/aiks/canvas.cc | 21 ++ engine/src/flutter/impeller/aiks/canvas.h | 5 + engine/src/flutter/impeller/aiks/paint.cc | 4 + engine/src/flutter/impeller/aiks/paint.h | 1 + engine/src/flutter/impeller/base/BUILD.gn | 1 + .../src/flutter/impeller/base/allocation.cc | 2 +- engine/src/flutter/impeller/base/allocation.h | 2 + .../backend/metal => base}/backend_cast.h | 0 .../display_list/display_list_dispatcher.cc | 60 ++++- engine/src/flutter/impeller/entity/BUILD.gn | 3 + .../impeller/entity/content_context.cc | 1 + .../flutter/impeller/entity/content_context.h | 9 + .../src/flutter/impeller/entity/contents.cc | 117 ++++++++ engine/src/flutter/impeller/entity/contents.h | 26 ++ .../impeller/entity/shaders/glyph_atlas.frag | 22 ++ .../impeller/entity/shaders/glyph_atlas.vert | 40 +++ engine/src/flutter/impeller/fixtures/BUILD.gn | 3 + engine/src/flutter/impeller/geometry/color.h | 11 + engine/src/flutter/impeller/geometry/rect.h | 16 ++ engine/src/flutter/impeller/geometry/size.h | 4 + .../flutter/impeller/playground/playground.mm | 3 +- engine/src/flutter/impeller/renderer/BUILD.gn | 1 - .../renderer/backend/metal/context_mtl.h | 5 +- .../renderer/backend/metal/context_mtl.mm | 9 +- .../backend/metal/device_buffer_mtl.h | 2 +- .../renderer/backend/metal/formats_mtl.h | 4 + .../renderer/backend/metal/pipeline_mtl.h | 2 +- .../renderer/backend/metal/render_pass_mtl.mm | 1 + .../backend/metal/sampler_library_mtl.h | 2 +- .../backend/metal/sampler_library_mtl.mm | 5 + .../renderer/backend/metal/sampler_mtl.h | 2 +- .../backend/metal/shader_function_mtl.h | 2 +- .../renderer/backend/metal/surface_mtl.mm | 2 +- .../renderer/backend/metal/texture_mtl.h | 2 +- .../backend/metal/vertex_descriptor_mtl.h | 2 +- .../src/flutter/impeller/renderer/formats.h | 2 + .../impeller/renderer/sampler_descriptor.h | 2 + .../src/flutter/impeller/typographer/BUILD.gn | 50 ++++ .../backends/skia/text_frame_skia.cc | 69 +++++ .../backends/skia/text_frame_skia.h | 15 ++ .../backends/skia/text_render_context_skia.cc | 252 ++++++++++++++++++ .../backends/skia/text_render_context_skia.h | 26 ++ .../backends/skia/typeface_skia.cc | 46 ++++ .../typographer/backends/skia/typeface_skia.h | 42 +++ .../src/flutter/impeller/typographer/font.cc | 48 ++++ .../src/flutter/impeller/typographer/font.h | 96 +++++++ .../impeller/typographer/font_glyph_pair.cc | 11 + .../impeller/typographer/font_glyph_pair.h | 44 +++ .../src/flutter/impeller/typographer/glyph.cc | 11 + .../src/flutter/impeller/typographer/glyph.h | 38 +++ .../impeller/typographer/glyph_atlas.cc | 59 ++++ .../impeller/typographer/glyph_atlas.h | 99 +++++++ .../impeller/typographer/text_frame.cc | 29 ++ .../flutter/impeller/typographer/text_frame.h | 51 ++++ .../typographer/text_render_context.cc | 27 ++ .../typographer/text_render_context.h | 63 +++++ .../flutter/impeller/typographer/text_run.cc | 39 +++ .../flutter/impeller/typographer/text_run.h | 77 ++++++ .../flutter/impeller/typographer/typeface.cc | 13 + .../flutter/impeller/typographer/typeface.h | 40 +++ .../typographer/typographer_unittests.cc | 46 ++++ 63 files changed, 1778 insertions(+), 23 deletions(-) rename engine/src/flutter/impeller/{renderer/backend/metal => base}/backend_cast.h (100%) create mode 100644 engine/src/flutter/impeller/entity/shaders/glyph_atlas.frag create mode 100644 engine/src/flutter/impeller/entity/shaders/glyph_atlas.vert create mode 100644 engine/src/flutter/impeller/typographer/BUILD.gn create mode 100644 engine/src/flutter/impeller/typographer/backends/skia/text_frame_skia.cc create mode 100644 engine/src/flutter/impeller/typographer/backends/skia/text_frame_skia.h create mode 100644 engine/src/flutter/impeller/typographer/backends/skia/text_render_context_skia.cc create mode 100644 engine/src/flutter/impeller/typographer/backends/skia/text_render_context_skia.h create mode 100644 engine/src/flutter/impeller/typographer/backends/skia/typeface_skia.cc create mode 100644 engine/src/flutter/impeller/typographer/backends/skia/typeface_skia.h create mode 100644 engine/src/flutter/impeller/typographer/font.cc create mode 100644 engine/src/flutter/impeller/typographer/font.h create mode 100644 engine/src/flutter/impeller/typographer/font_glyph_pair.cc create mode 100644 engine/src/flutter/impeller/typographer/font_glyph_pair.h create mode 100644 engine/src/flutter/impeller/typographer/glyph.cc create mode 100644 engine/src/flutter/impeller/typographer/glyph.h create mode 100644 engine/src/flutter/impeller/typographer/glyph_atlas.cc create mode 100644 engine/src/flutter/impeller/typographer/glyph_atlas.h create mode 100644 engine/src/flutter/impeller/typographer/text_frame.cc create mode 100644 engine/src/flutter/impeller/typographer/text_frame.h create mode 100644 engine/src/flutter/impeller/typographer/text_render_context.cc create mode 100644 engine/src/flutter/impeller/typographer/text_render_context.h create mode 100644 engine/src/flutter/impeller/typographer/text_run.cc create mode 100644 engine/src/flutter/impeller/typographer/text_run.h create mode 100644 engine/src/flutter/impeller/typographer/typeface.cc create mode 100644 engine/src/flutter/impeller/typographer/typeface.h create mode 100644 engine/src/flutter/impeller/typographer/typographer_unittests.cc diff --git a/engine/src/flutter/impeller/BUILD.gn b/engine/src/flutter/impeller/BUILD.gn index f46067dd58..d3b6bb6de7 100644 --- a/engine/src/flutter/impeller/BUILD.gn +++ b/engine/src/flutter/impeller/BUILD.gn @@ -21,6 +21,7 @@ group("impeller") { "geometry", "image", "renderer", + "typographer", ] if (is_host) { @@ -43,5 +44,6 @@ executable("impeller_unittests") { "image:image_unittests", "playground", "renderer:renderer_unittests", + "typographer:typographer_unittests", ] } diff --git a/engine/src/flutter/impeller/aiks/aiks_unittests.cc b/engine/src/flutter/impeller/aiks/aiks_unittests.cc index ca96b494c4..5531beee47 100644 --- a/engine/src/flutter/impeller/aiks/aiks_unittests.cc +++ b/engine/src/flutter/impeller/aiks/aiks_unittests.cc @@ -8,6 +8,9 @@ #include "impeller/aiks/image.h" #include "impeller/geometry/geometry_unittests.h" #include "impeller/geometry/path_builder.h" +#include "impeller/typographer/backends/skia/text_frame_skia.h" +#include "impeller/typographer/backends/skia/text_render_context_skia.h" +#include "third_party/skia/include/core/SkData.h" namespace impeller { namespace testing { @@ -283,5 +286,114 @@ TEST_F(AiksTest, CanRenderDifferencePaths) { ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture())); } +static sk_sp OpenFixtureAsSkData(const char* fixture_name) { + auto mapping = flutter::testing::OpenFixtureAsMapping(fixture_name); + if (!mapping) { + return nullptr; + } + return SkData::MakeWithProc( + mapping->GetMapping(), mapping->GetSize(), + [](const void* ptr, void* context) { + delete reinterpret_cast(context); + }, + mapping.release()); +} + +TEST_F(AiksTest, CanRenderTextFrame) { + Canvas canvas; + + Scalar baseline = 200.0; + Point text_position = {100, baseline}; + + // Draw the baseline. + canvas.DrawRect({50, baseline, 900, 10}, + Paint{.color = Color::Aqua().WithAlpha(0.25)}); + + // Mark the point at which the text is drawn. + canvas.DrawCircle(text_position, 5.0, + Paint{.color = Color::Red().WithAlpha(0.25)}); + + // Construct the text blob. + auto mapping = OpenFixtureAsSkData("Roboto-Regular.ttf"); + ASSERT_TRUE(mapping); + SkFont sk_font(SkTypeface::MakeFromData(mapping), 50.0); + auto blob = SkTextBlob::MakeFromString( + "the quick brown fox jumped over the lazy dog!.?", sk_font); + ASSERT_TRUE(blob); + + // Create the Impeller text frame and draw it at the designated baseline. + auto frame = TextFrameFromTextBlob(blob); + TextRenderContextSkia text_context(GetContext()); + ASSERT_TRUE(text_context.IsValid()); + auto atlas = text_context.CreateGlyphAtlas(frame); + ASSERT_NE(atlas, nullptr); + canvas.DrawTextFrame(std::move(frame), std::move(atlas), text_position); + ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture())); +} + +TEST_F(AiksTest, CanRenderItalicizedText) { + Canvas canvas; + + Scalar baseline = 200.0; + Point text_position = {100, baseline}; + + // Draw the baseline. + canvas.DrawRect({50, baseline, 900, 10}, + Paint{.color = Color::Aqua().WithAlpha(0.25)}); + + // Mark the point at which the text is drawn. + canvas.DrawCircle(text_position, 5.0, + Paint{.color = Color::Red().WithAlpha(0.25)}); + + // Construct the text blob. + auto mapping = OpenFixtureAsSkData("HomemadeApple.ttf"); + ASSERT_TRUE(mapping); + SkFont sk_font(SkTypeface::MakeFromData(mapping), 50.0); + auto blob = SkTextBlob::MakeFromString( + "the quick brown fox jumped over the lazy dog!.?", sk_font); + ASSERT_TRUE(blob); + + // Create the Impeller text frame and draw it at the designated baseline. + auto frame = TextFrameFromTextBlob(blob); + TextRenderContextSkia text_context(GetContext()); + ASSERT_TRUE(text_context.IsValid()); + auto atlas = text_context.CreateGlyphAtlas(frame); + ASSERT_NE(atlas, nullptr); + canvas.DrawTextFrame(std::move(frame), std::move(atlas), text_position); + ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture())); +} + +TEST_F(AiksTest, CanRenderEmojiTextFrame) { + Canvas canvas; + + Scalar baseline = 200.0; + Point text_position = {100, baseline}; + + // Draw the baseline. + canvas.DrawRect({50, baseline, 900, 10}, + Paint{.color = Color::Aqua().WithAlpha(0.25)}); + + // Mark the point at which the text is drawn. + canvas.DrawCircle(text_position, 5.0, + Paint{.color = Color::Red().WithAlpha(0.25)}); + + // Construct the text blob. + auto mapping = OpenFixtureAsSkData("NotoColorEmoji.ttf"); + ASSERT_TRUE(mapping); + SkFont sk_font(SkTypeface::MakeFromData(mapping), 50.0); + auto blob = SkTextBlob::MakeFromString( + "πŸ˜€ πŸ˜ƒ πŸ˜„ 😁 πŸ˜† πŸ˜… πŸ˜‚ 🀣 πŸ₯² ☺️ 😊", sk_font); + ASSERT_TRUE(blob); + + // Create the Impeller text frame and draw it at the designated baseline. + auto frame = TextFrameFromTextBlob(blob); + TextRenderContextSkia text_context(GetContext()); + ASSERT_TRUE(text_context.IsValid()); + auto atlas = text_context.CreateGlyphAtlas(frame); + ASSERT_NE(atlas, nullptr); + canvas.DrawTextFrame(std::move(frame), std::move(atlas), text_position); + ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture())); +} + } // namespace testing } // namespace impeller diff --git a/engine/src/flutter/impeller/aiks/canvas.cc b/engine/src/flutter/impeller/aiks/canvas.cc index 0825d5c2ba..0a6e214de9 100644 --- a/engine/src/flutter/impeller/aiks/canvas.cc +++ b/engine/src/flutter/impeller/aiks/canvas.cc @@ -252,4 +252,25 @@ void Canvas::Save(bool create_subpass) { xformation_stack_.emplace_back(std::move(entry)); } +void Canvas::DrawTextFrame(TextFrame text_frame, + std::shared_ptr atlas, + Point position) { + if (!atlas || !atlas->IsValid()) { + return; + } + + auto text_contents = std::make_shared(); + text_contents->SetTextFrame(std::move(text_frame)); + text_contents->SetGlyphAtlas(std::move(atlas)); + + Entity entity; + entity.SetTransformation(GetCurrentTransformation() * + Matrix::MakeTranslation(position)); + entity.SetPath({}); + entity.SetStencilDepth(GetStencilDepth()); + entity.SetContents(std::move(text_contents)); + + GetCurrentPass().AddEntity(std::move(entity)); +} + } // namespace impeller diff --git a/engine/src/flutter/impeller/aiks/canvas.h b/engine/src/flutter/impeller/aiks/canvas.h index 367669eccb..88db60911e 100644 --- a/engine/src/flutter/impeller/aiks/canvas.h +++ b/engine/src/flutter/impeller/aiks/canvas.h @@ -18,6 +18,7 @@ #include "impeller/geometry/path.h" #include "impeller/geometry/point.h" #include "impeller/geometry/vector.h" +#include "impeller/typographer/text_frame.h" namespace impeller { @@ -74,6 +75,10 @@ class Canvas { void DrawPicture(Picture picture); + void DrawTextFrame(TextFrame text_frame, + std::shared_ptr atlas, + Point position); + Picture EndRecordingAsPicture(); private: diff --git a/engine/src/flutter/impeller/aiks/paint.cc b/engine/src/flutter/impeller/aiks/paint.cc index ca1f6169f2..6f2eea50cc 100644 --- a/engine/src/flutter/impeller/aiks/paint.cc +++ b/engine/src/flutter/impeller/aiks/paint.cc @@ -7,6 +7,10 @@ namespace impeller { std::shared_ptr Paint::CreateContentsForEntity() const { + if (contents) { + return contents; + } + switch (style) { case Style::kFill: { auto solid_color = std::make_shared(); diff --git a/engine/src/flutter/impeller/aiks/paint.h b/engine/src/flutter/impeller/aiks/paint.h index 6334e42471..7a941474a7 100644 --- a/engine/src/flutter/impeller/aiks/paint.h +++ b/engine/src/flutter/impeller/aiks/paint.h @@ -21,6 +21,7 @@ struct Paint { Color color = Color::Black(); Scalar stroke_width = 0.0; Style style = Style::kFill; + std::shared_ptr contents; std::shared_ptr CreateContentsForEntity() const; }; diff --git a/engine/src/flutter/impeller/base/BUILD.gn b/engine/src/flutter/impeller/base/BUILD.gn index ab988b1adc..0a4ba5fcec 100644 --- a/engine/src/flutter/impeller/base/BUILD.gn +++ b/engine/src/flutter/impeller/base/BUILD.gn @@ -8,6 +8,7 @@ impeller_component("base") { sources = [ "allocation.cc", "allocation.h", + "backend_cast.h", "base.h", "config.h", "promise.cc", diff --git a/engine/src/flutter/impeller/base/allocation.cc b/engine/src/flutter/impeller/base/allocation.cc index d3c8602e10..0a66a24e74 100644 --- a/engine/src/flutter/impeller/base/allocation.cc +++ b/engine/src/flutter/impeller/base/allocation.cc @@ -38,7 +38,7 @@ bool Allocation::Truncate(size_t length, bool npot) { return true; } -static uint32_t NextPowerOfTwoSize(uint32_t x) { +uint32_t Allocation::NextPowerOfTwoSize(uint32_t x) { if (x == 0) { return 1; } diff --git a/engine/src/flutter/impeller/base/allocation.h b/engine/src/flutter/impeller/base/allocation.h index f707e08929..ffb202562a 100644 --- a/engine/src/flutter/impeller/base/allocation.h +++ b/engine/src/flutter/impeller/base/allocation.h @@ -25,6 +25,8 @@ class Allocation { [[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; diff --git a/engine/src/flutter/impeller/renderer/backend/metal/backend_cast.h b/engine/src/flutter/impeller/base/backend_cast.h similarity index 100% rename from engine/src/flutter/impeller/renderer/backend/metal/backend_cast.h rename to engine/src/flutter/impeller/base/backend_cast.h diff --git a/engine/src/flutter/impeller/display_list/display_list_dispatcher.cc b/engine/src/flutter/impeller/display_list/display_list_dispatcher.cc index 9fdf58b4ba..ddeabcffa3 100644 --- a/engine/src/flutter/impeller/display_list/display_list_dispatcher.cc +++ b/engine/src/flutter/impeller/display_list/display_list_dispatcher.cc @@ -6,6 +6,9 @@ #include "flutter/fml/trace_event.h" #include "impeller/geometry/path_builder.h" +#include "impeller/typographer/backends/skia/text_frame_skia.h" +#include "third_party/skia/include/core/SkColor.h" +#include "third_party/skia/include/core/SkShader.h" namespace impeller { @@ -72,8 +75,56 @@ void DisplayListDispatcher::setStrokeJoin(SkPaint::Join join) { UNIMPLEMENTED; } +static Point ToPoint(const SkPoint& point) { + return Point::MakeXY(point.fX, point.fY); +} + +static Color ToColor(const SkColor& color) { + return { + static_cast(SkColorGetR(color) / 255.0), // + static_cast(SkColorGetG(color) / 255.0), // + static_cast(SkColorGetB(color) / 255.0), // + static_cast(SkColorGetA(color) / 255.0) // + }; +} + // |flutter::Dispatcher| void DisplayListDispatcher::setShader(sk_sp shader) { + if (!shader) { + return; + } + + { + SkShader::GradientInfo info = {}; + constexpr auto kColorsArrayCount = 2u; + info.fColorCount = kColorsArrayCount; + SkColor sk_colors[kColorsArrayCount]; + info.fColors = sk_colors; + auto gradient_type = shader->asAGradient(&info); + switch (gradient_type) { + case SkShader::kLinear_GradientType: { + auto contents = std::make_shared(); + contents->SetEndPoints(ToPoint(info.fPoint[0]), + ToPoint(info.fPoint[1])); + std::vector colors; + for (auto i = 0; i < info.fColorCount; i++) { + colors.emplace_back(ToColor(sk_colors[i])); + } + contents->SetColors(std::move(colors)); + paint_.contents = std::move(contents); + return; + } break; + case SkShader::kNone_GradientType: + case SkShader::kColor_GradientType: + case SkShader::kRadial_GradientType: + case SkShader::kSweep_GradientType: + case SkShader::kConical_GradientType: + default: + UNIMPLEMENTED; + break; + } + } + // Needs https://github.com/flutter/flutter/issues/95434 UNIMPLEMENTED; } @@ -154,9 +205,8 @@ static std::optional ToRect(const SkRect* rect) { // |flutter::Dispatcher| void DisplayListDispatcher::saveLayer(const SkRect* bounds, const flutter::SaveLayerOptions options) { - canvas_.SaveLayer( - options.renders_with_attributes() ? paint_ : Paint{}, - ToRect(bounds)); + canvas_.SaveLayer(options.renders_with_attributes() ? paint_ : Paint{}, + ToRect(bounds)); } // |flutter::Dispatcher| @@ -242,10 +292,6 @@ void DisplayListDispatcher::clipRect(const SkRect& rect, canvas_.ClipPath(std::move(path)); } -static Point ToPoint(const SkVector& vector) { - return {vector.fX, vector.fY}; -} - static PathBuilder::RoundingRadii ToRoundingRadii(const SkRRect& rrect) { using Corner = SkRRect::Corner; PathBuilder::RoundingRadii radii; diff --git a/engine/src/flutter/impeller/entity/BUILD.gn b/engine/src/flutter/impeller/entity/BUILD.gn index 7badc02495..6a01accfba 100644 --- a/engine/src/flutter/impeller/entity/BUILD.gn +++ b/engine/src/flutter/impeller/entity/BUILD.gn @@ -16,6 +16,8 @@ impeller_shaders("entity_shaders") { "shaders/solid_stroke.vert", "shaders/texture_fill.frag", "shaders/texture_fill.vert", + "shaders/glyph_atlas.frag", + "shaders/glyph_atlas.vert", ] } @@ -38,6 +40,7 @@ impeller_component("entity") { "../archivist", "../image", "../renderer", + "../typographer", ] } diff --git a/engine/src/flutter/impeller/entity/content_context.cc b/engine/src/flutter/impeller/entity/content_context.cc index 53fd91745f..0d4b23de76 100644 --- a/engine/src/flutter/impeller/entity/content_context.cc +++ b/engine/src/flutter/impeller/entity/content_context.cc @@ -21,6 +21,7 @@ ContentContext::ContentContext(std::shared_ptr context) texture_pipelines_[{}] = std::make_unique(*context_); solid_stroke_pipelines_[{}] = std::make_unique(*context_); + glyph_atlas_pipelines_[{}] = std::make_unique(*context_); // Pipelines that are variants of the base pipelines with custom descriptors. // TODO(98684): Rework this API to allow fetching the descriptor without diff --git a/engine/src/flutter/impeller/entity/content_context.h b/engine/src/flutter/impeller/entity/content_context.h index 78d21e5c63..a3b0ec270e 100644 --- a/engine/src/flutter/impeller/entity/content_context.h +++ b/engine/src/flutter/impeller/entity/content_context.h @@ -9,6 +9,8 @@ #include "flutter/fml/hash_combine.h" #include "flutter/fml/macros.h" +#include "flutter/impeller/entity/glyph_atlas.frag.h" +#include "flutter/impeller/entity/glyph_atlas.vert.h" #include "flutter/impeller/entity/gradient_fill.frag.h" #include "flutter/impeller/entity/gradient_fill.vert.h" #include "flutter/impeller/entity/solid_fill.frag.h" @@ -29,6 +31,8 @@ using TexturePipeline = PipelineT; using SolidStrokePipeline = PipelineT; +using GlyphAtlasPipeline = + PipelineT; // Instead of requiring new shaders for clips, the solid fill stages are used // to redirect writing to the stencil instead of color attachments. using ClipPipeline = PipelineT; @@ -81,6 +85,10 @@ class ContentContext { return GetPipeline(clip_restoration_pipelines_, opts); } + std::shared_ptr GetGlyphAtlasPipeline(Options opts) const { + return GetPipeline(glyph_atlas_pipelines_, opts); + } + std::shared_ptr GetContext() const; private: @@ -99,6 +107,7 @@ class ContentContext { mutable Variants solid_stroke_pipelines_; mutable Variants clip_pipelines_; mutable Variants clip_restoration_pipelines_; + mutable Variants glyph_atlas_pipelines_; static void ApplyOptionsToDescriptor(PipelineDescriptor& desc, const Options& options) { diff --git a/engine/src/flutter/impeller/entity/contents.cc b/engine/src/flutter/impeller/entity/contents.cc index 8f2ad02878..6288d3b3c1 100644 --- a/engine/src/flutter/impeller/entity/contents.cc +++ b/engine/src/flutter/impeller/entity/contents.cc @@ -551,4 +551,121 @@ bool ClipRestoreContents::Render(const ContentContext& renderer, return true; } +/******************************************************************************* + ******* TextContents + ******************************************************************************/ + +TextContents::TextContents() = default; + +TextContents::~TextContents() = default; + +void TextContents::SetTextFrame(TextFrame frame) { + frame_ = std::move(frame); +} + +void TextContents::SetGlyphAtlas(std::shared_ptr atlas) { + atlas_ = std::move(atlas); +} + +bool TextContents::Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + if (!atlas_ || !atlas_->IsValid()) { + VALIDATION_LOG << "Cannot render glyphs without prepared atlas."; + return false; + } + + using VS = GlyphAtlasPipeline::VertexShader; + using FS = GlyphAtlasPipeline::FragmentShader; + + // Information shared by all glyph draw calls. + Command cmd; + cmd.label = "Glyph"; + cmd.primitive_type = PrimitiveType::kTriangle; + cmd.pipeline = renderer.GetGlyphAtlasPipeline(OptionsFromPass(pass)); + cmd.stencil_reference = entity.GetStencilDepth(); + + // Common vertex uniforms for all glyphs. + VS::FrameInfo frame_info; + frame_info.mvp = Matrix::MakeOrthographic(pass.GetRenderTargetSize()) * + entity.GetTransformation(); + frame_info.atlas_size = + Point{static_cast(atlas_->GetTexture()->GetSize().width), + static_cast(atlas_->GetTexture()->GetSize().height)}; + VS::BindFrameInfo(cmd, pass.GetTransientsBuffer().EmplaceUniform(frame_info)); + + // Common fragment uniforms for all glyphs. + FS::BindGlyphAtlasSampler( + cmd, // command + atlas_->GetTexture(), // texture + renderer.GetContext()->GetSamplerLibrary()->GetSampler({}) // sampler + ); + + // Common vertex information for all glyphs. + // Currently, glyphs are being drawn individually. This can be batched later. + // But we don't want to give each glyph unique vertex information. So all + // glyphs are given the same vertex information in the form of a unit-sized + // quad. The size of the glyph is specified in uniform data and the vertex + // shader uses this to size the glyph correctly. The interpolated vertex + // information is also used in the fragment shader to sample from the glyph + // atlas. + { + VertexBufferBuilder vertex_builder; + if (!Tessellator{FillType::kPositive}.Tessellate( + PathBuilder{} + .AddRect(Rect::MakeXYWH(0.0, 0.0, 1.0, 1.0)) + .TakePath() + .CreatePolyline(), + [&vertex_builder](Point point) { + VS::PerVertexData vtx; + vtx.unit_vertex = point; + vertex_builder.AppendVertex(std::move(vtx)); + })) { + return false; + } + auto dummy = vertex_builder.CreateVertexBuffer(pass.GetTransientsBuffer()); + auto vertex_buffer = dummy; + if (!vertex_buffer) { + return false; + } + cmd.BindVertices(std::move(vertex_buffer)); + } + + // Iterate through all the runs in the blob. + for (const auto& run : frame_.GetRuns()) { + auto font = run.GetFont(); + auto glyph_size = font.GetGlyphSize(); + if (!glyph_size.has_value()) { + VALIDATION_LOG << "Glyph has no size."; + return false; + } + // Draw each glyph individually. This should probably be batched. + for (const auto& glyph_position : run.GetGlyphPositions()) { + FontGlyphPair font_glyph_pair{font, glyph_position.glyph}; + auto atlas_glyph_pos = atlas_->FindFontGlyphPosition(font_glyph_pair); + if (!atlas_glyph_pos.has_value()) { + VALIDATION_LOG << "Could not find glyph position in the atlas."; + return false; + } + + VS::GlyphInfo glyph_info; + glyph_info.position = glyph_position.position.Translate( + {0.0, font.GetMetrics().ascent, 0.0}); + glyph_info.glyph_size = {static_cast(glyph_size->width), + static_cast(glyph_size->height)}; + glyph_info.atlas_position = atlas_glyph_pos->origin; + glyph_info.atlas_glyph_size = {atlas_glyph_pos->size.width, + atlas_glyph_pos->size.height}; + VS::BindGlyphInfo(cmd, + pass.GetTransientsBuffer().EmplaceUniform(glyph_info)); + + if (!pass.AddCommand(cmd)) { + return false; + } + } + } + + return true; +} + } // namespace impeller diff --git a/engine/src/flutter/impeller/entity/contents.h b/engine/src/flutter/impeller/entity/contents.h index dbdffb231d..5488f6d3a8 100644 --- a/engine/src/flutter/impeller/entity/contents.h +++ b/engine/src/flutter/impeller/entity/contents.h @@ -12,6 +12,8 @@ #include "impeller/geometry/point.h" #include "impeller/geometry/rect.h" #include "impeller/renderer/texture.h" +#include "impeller/typographer/glyph_atlas.h" +#include "impeller/typographer/text_frame.h" namespace impeller { @@ -187,6 +189,8 @@ class ClipRestoreContents final : public Contents { ~ClipRestoreContents(); + void SetGlyphAtlas(std::shared_ptr atlas); + // |Contents| bool Render(const ContentContext& renderer, const Entity& entity, @@ -196,4 +200,26 @@ class ClipRestoreContents final : public Contents { FML_DISALLOW_COPY_AND_ASSIGN(ClipRestoreContents); }; +class TextContents final : public Contents { + public: + TextContents(); + + ~TextContents(); + + void SetTextFrame(TextFrame frame); + + void SetGlyphAtlas(std::shared_ptr atlas); + + // |Contents| + bool Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + private: + TextFrame frame_; + std::shared_ptr atlas_; + + FML_DISALLOW_COPY_AND_ASSIGN(TextContents); +}; + } // namespace impeller diff --git a/engine/src/flutter/impeller/entity/shaders/glyph_atlas.frag b/engine/src/flutter/impeller/entity/shaders/glyph_atlas.frag new file mode 100644 index 0000000000..0fedba1c14 --- /dev/null +++ b/engine/src/flutter/impeller/entity/shaders/glyph_atlas.frag @@ -0,0 +1,22 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +uniform sampler2D glyph_atlas_sampler; + +in vec2 v_unit_vertex; +in vec2 v_atlas_position; +in vec2 v_atlas_glyph_size; +in vec2 v_atlas_size; + +out vec4 frag_color; + +void main() { + vec2 scale_perspective = v_atlas_glyph_size / v_atlas_size; + vec2 offset = v_atlas_position / v_atlas_size; + + frag_color = texture( + glyph_atlas_sampler, + v_unit_vertex * scale_perspective + offset + ); +} diff --git a/engine/src/flutter/impeller/entity/shaders/glyph_atlas.vert b/engine/src/flutter/impeller/entity/shaders/glyph_atlas.vert new file mode 100644 index 0000000000..7cff4886b7 --- /dev/null +++ b/engine/src/flutter/impeller/entity/shaders/glyph_atlas.vert @@ -0,0 +1,40 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +uniform FrameInfo { + mat4 mvp; + vec2 atlas_size; +} frame_info; + +uniform GlyphInfo { + mat4 position; + vec2 glyph_size; + vec2 atlas_position; + vec2 atlas_glyph_size; +} glyph_info; + +in vec2 unit_vertex; + +out vec2 v_unit_vertex; +out vec2 v_atlas_position; +out vec2 v_atlas_glyph_size; +out vec2 v_atlas_size; + +void main() { + mat4 scale = mat4( + glyph_info.glyph_size.x, 0.0, 0.0, 0.0, + 0.0, glyph_info.glyph_size.y, 0.0, 0.0, + 0.0, 0.0, 1.0 , 0.0, + 0.0, 0.0, 0.0 , 1.0 + ); + gl_Position = frame_info.mvp + * glyph_info.position + * scale + * vec4(unit_vertex, 0.0, 1.0); + + v_unit_vertex = unit_vertex; + v_atlas_position = glyph_info.atlas_position; + v_atlas_glyph_size = glyph_info.atlas_glyph_size; + v_atlas_size = frame_info.atlas_size; +} diff --git a/engine/src/flutter/impeller/fixtures/BUILD.gn b/engine/src/flutter/impeller/fixtures/BUILD.gn index 11640f79c3..db56ad66fb 100644 --- a/engine/src/flutter/impeller/fixtures/BUILD.gn +++ b/engine/src/flutter/impeller/fixtures/BUILD.gn @@ -26,6 +26,9 @@ test_fixtures("file_fixtures") { "boston.jpg", "embarcadero.jpg", "kalimba.jpg", + "//flutter/third_party/txt/third_party/fonts/Roboto-Regular.ttf", + "//flutter/third_party/txt/third_party/fonts/NotoColorEmoji.ttf", + "//flutter/third_party/txt/third_party/fonts/HomemadeApple.ttf", ] } diff --git a/engine/src/flutter/impeller/geometry/color.h b/engine/src/flutter/impeller/geometry/color.h index 86d40f6abb..8f5a83885e 100644 --- a/engine/src/flutter/impeller/geometry/color.h +++ b/engine/src/flutter/impeller/geometry/color.h @@ -5,6 +5,7 @@ #pragma once #include +#include #include "impeller/geometry/scalar.h" @@ -683,3 +684,13 @@ struct ColorHSB { static_assert(sizeof(Color) == 4 * sizeof(Scalar)); } // namespace impeller + +namespace std { + +inline std::ostream& operator<<(std::ostream& out, const impeller::Color& c) { + out << "(" << c.red << ", " << c.green << ", " << c.blue << ", " << c.alpha + << ")"; + return out; +} + +} // namespace std diff --git a/engine/src/flutter/impeller/geometry/rect.h b/engine/src/flutter/impeller/geometry/rect.h index 96fc41fd8f..bb39b4bcd4 100644 --- a/engine/src/flutter/impeller/geometry/rect.h +++ b/engine/src/flutter/impeller/geometry/rect.h @@ -92,6 +92,22 @@ struct TRect { constexpr bool IsEmpty() const { return size.IsEmpty(); } + constexpr auto GetLeft() const { + return std::min(origin.x, origin.x + size.width); + } + + constexpr auto GetTop() const { + return std::min(origin.y, origin.y + size.height); + } + + constexpr auto GetRight() const { + return std::max(origin.x, origin.x + size.width); + } + + constexpr auto GetBottom() const { + return std::max(origin.y, origin.y + size.height); + } + constexpr std::array GetLTRB() const { const auto left = std::min(origin.x, origin.x + size.width); const auto top = std::min(origin.y, origin.y + size.height); diff --git a/engine/src/flutter/impeller/geometry/size.h b/engine/src/flutter/impeller/geometry/size.h index 2415d314a5..9a58f32f68 100644 --- a/engine/src/flutter/impeller/geometry/size.h +++ b/engine/src/flutter/impeller/geometry/size.h @@ -29,6 +29,10 @@ struct TSize { : TSize(static_cast(other.width), static_cast(other.height)) { } + static constexpr TSize MakeWH(Type width, Type height) { + return TSize{width, height}; + } + static constexpr TSize Infinite() { return TSize{std::numeric_limits::max(), std::numeric_limits::max()}; diff --git a/engine/src/flutter/impeller/playground/playground.mm b/engine/src/flutter/impeller/playground/playground.mm index 183f91aaa4..52b2c11599 100644 --- a/engine/src/flutter/impeller/playground/playground.mm +++ b/engine/src/flutter/impeller/playground/playground.mm @@ -49,7 +49,8 @@ ShaderLibraryMappingsForPlayground() { } Playground::Playground() - : renderer_(ContextMTL::Create(ShaderLibraryMappingsForPlayground())) {} + : renderer_(ContextMTL::Create(ShaderLibraryMappingsForPlayground(), + "Playground Library")) {} Playground::~Playground() = default; diff --git a/engine/src/flutter/impeller/renderer/BUILD.gn b/engine/src/flutter/impeller/renderer/BUILD.gn index 5bd501217d..8e208638f2 100644 --- a/engine/src/flutter/impeller/renderer/BUILD.gn +++ b/engine/src/flutter/impeller/renderer/BUILD.gn @@ -8,7 +8,6 @@ impeller_component("renderer") { metal_backend_sources = [ "backend/metal/allocator_mtl.h", "backend/metal/allocator_mtl.mm", - "backend/metal/backend_cast.h", "backend/metal/command_buffer_mtl.h", "backend/metal/command_buffer_mtl.mm", "backend/metal/context_mtl.h", diff --git a/engine/src/flutter/impeller/renderer/backend/metal/context_mtl.h b/engine/src/flutter/impeller/renderer/backend/metal/context_mtl.h index b7f7080e80..705978601b 100644 --- a/engine/src/flutter/impeller/renderer/backend/metal/context_mtl.h +++ b/engine/src/flutter/impeller/renderer/backend/metal/context_mtl.h @@ -10,8 +10,8 @@ #include #include "flutter/fml/macros.h" +#include "impeller/base/backend_cast.h" #include "impeller/renderer/backend/metal/allocator_mtl.h" -#include "impeller/renderer/backend/metal/backend_cast.h" #include "impeller/renderer/backend/metal/command_buffer_mtl.h" #include "impeller/renderer/backend/metal/pipeline_library_mtl.h" #include "impeller/renderer/backend/metal/shader_library_mtl.h" @@ -27,7 +27,8 @@ class ContextMTL final : public Context, const std::vector& shader_library_paths); static std::shared_ptr Create( - const std::vector>& shader_libraries_data); + const std::vector>& shader_libraries_data, + const std::string& label); // |Context| ~ContextMTL() override; diff --git a/engine/src/flutter/impeller/renderer/backend/metal/context_mtl.mm b/engine/src/flutter/impeller/renderer/backend/metal/context_mtl.mm index 0b464e6851..af3ec0de76 100644 --- a/engine/src/flutter/impeller/renderer/backend/metal/context_mtl.mm +++ b/engine/src/flutter/impeller/renderer/backend/metal/context_mtl.mm @@ -105,7 +105,8 @@ static NSArray>* MTLShaderLibraryFromFilePaths( static NSArray>* MTLShaderLibraryFromFileData( id device, - const std::vector>& libraries_data) { + const std::vector>& libraries_data, + const std::string& label) { NSMutableArray>* found_libraries = [NSMutableArray array]; for (const auto& library_data : libraries_data) { if (library_data == nullptr) { @@ -159,10 +160,12 @@ std::shared_ptr ContextMTL::Create( } std::shared_ptr ContextMTL::Create( - const std::vector>& shader_libraries_data) { + const std::vector>& shader_libraries_data, + const std::string& label) { auto device = CreateMetalDevice(); auto context = std::shared_ptr(new ContextMTL( - device, MTLShaderLibraryFromFileData(device, shader_libraries_data))); + device, + MTLShaderLibraryFromFileData(device, shader_libraries_data, label))); if (!context->IsValid()) { FML_LOG(ERROR) << "Could not create Metal context."; return nullptr; diff --git a/engine/src/flutter/impeller/renderer/backend/metal/device_buffer_mtl.h b/engine/src/flutter/impeller/renderer/backend/metal/device_buffer_mtl.h index 7523cc4cac..c930626c24 100644 --- a/engine/src/flutter/impeller/renderer/backend/metal/device_buffer_mtl.h +++ b/engine/src/flutter/impeller/renderer/backend/metal/device_buffer_mtl.h @@ -7,7 +7,7 @@ #include #include "flutter/fml/macros.h" -#include "impeller/renderer/backend/metal/backend_cast.h" +#include "impeller/base/backend_cast.h" #include "impeller/renderer/device_buffer.h" namespace impeller { diff --git a/engine/src/flutter/impeller/renderer/backend/metal/formats_mtl.h b/engine/src/flutter/impeller/renderer/backend/metal/formats_mtl.h index 9cdb319f1b..dd91136924 100644 --- a/engine/src/flutter/impeller/renderer/backend/metal/formats_mtl.h +++ b/engine/src/flutter/impeller/renderer/backend/metal/formats_mtl.h @@ -21,6 +21,8 @@ constexpr PixelFormat FromMTLPixelFormat(MTLPixelFormat format) { switch (format) { case MTLPixelFormatInvalid: return PixelFormat::kUnknown; + case MTLPixelFormatR8Unorm: + return PixelFormat::kR8UNormInt; case MTLPixelFormatBGRA8Unorm: return PixelFormat::kB8G8R8A8UNormInt; case MTLPixelFormatBGRA8Unorm_sRGB: @@ -41,6 +43,8 @@ constexpr MTLPixelFormat ToMTLPixelFormat(PixelFormat format) { switch (format) { case PixelFormat::kUnknown: return MTLPixelFormatInvalid; + case PixelFormat::kR8UNormInt: + return MTLPixelFormatR8Unorm; case PixelFormat::kB8G8R8A8UNormInt: return MTLPixelFormatBGRA8Unorm; case PixelFormat::kB8G8R8A8UNormIntSRGB: diff --git a/engine/src/flutter/impeller/renderer/backend/metal/pipeline_mtl.h b/engine/src/flutter/impeller/renderer/backend/metal/pipeline_mtl.h index 6756747121..238fae7944 100644 --- a/engine/src/flutter/impeller/renderer/backend/metal/pipeline_mtl.h +++ b/engine/src/flutter/impeller/renderer/backend/metal/pipeline_mtl.h @@ -7,7 +7,7 @@ #include #include "flutter/fml/macros.h" -#include "impeller/renderer/backend/metal/backend_cast.h" +#include "impeller/base/backend_cast.h" #include "impeller/renderer/pipeline.h" namespace impeller { diff --git a/engine/src/flutter/impeller/renderer/backend/metal/render_pass_mtl.mm b/engine/src/flutter/impeller/renderer/backend/metal/render_pass_mtl.mm index 8335b36233..068dd67ba1 100644 --- a/engine/src/flutter/impeller/renderer/backend/metal/render_pass_mtl.mm +++ b/engine/src/flutter/impeller/renderer/backend/metal/render_pass_mtl.mm @@ -136,6 +136,7 @@ RenderPassMTL::RenderPassMTL(id buffer, RenderTarget target) if (!buffer_ || !desc_ || !render_target_.IsValid()) { return; } + SetLabel("RenderPass"); is_valid_ = true; } diff --git a/engine/src/flutter/impeller/renderer/backend/metal/sampler_library_mtl.h b/engine/src/flutter/impeller/renderer/backend/metal/sampler_library_mtl.h index 71b8acb563..c8195320e8 100644 --- a/engine/src/flutter/impeller/renderer/backend/metal/sampler_library_mtl.h +++ b/engine/src/flutter/impeller/renderer/backend/metal/sampler_library_mtl.h @@ -10,7 +10,7 @@ #include #include "flutter/fml/macros.h" -#include "impeller/renderer/backend/metal/backend_cast.h" +#include "impeller/base/backend_cast.h" #include "impeller/renderer/comparable.h" #include "impeller/renderer/sampler_descriptor.h" #include "impeller/renderer/sampler_library.h" diff --git a/engine/src/flutter/impeller/renderer/backend/metal/sampler_library_mtl.mm b/engine/src/flutter/impeller/renderer/backend/metal/sampler_library_mtl.mm index 313e670971..fd8f6d6ed9 100644 --- a/engine/src/flutter/impeller/renderer/backend/metal/sampler_library_mtl.mm +++ b/engine/src/flutter/impeller/renderer/backend/metal/sampler_library_mtl.mm @@ -28,6 +28,11 @@ std::shared_ptr SamplerLibraryMTL::GetSampler( desc.sAddressMode = MTLSamplerAddressMode(descriptor.width_address_mode); desc.rAddressMode = MTLSamplerAddressMode(descriptor.depth_address_mode); desc.tAddressMode = MTLSamplerAddressMode(descriptor.height_address_mode); + + if (!descriptor.label.empty()) { + desc.label = @(descriptor.label.c_str()); + } + auto mtl_sampler = [device_ newSamplerStateWithDescriptor:desc]; if (!mtl_sampler) { return nullptr; diff --git a/engine/src/flutter/impeller/renderer/backend/metal/sampler_mtl.h b/engine/src/flutter/impeller/renderer/backend/metal/sampler_mtl.h index de80442942..001b943da1 100644 --- a/engine/src/flutter/impeller/renderer/backend/metal/sampler_mtl.h +++ b/engine/src/flutter/impeller/renderer/backend/metal/sampler_mtl.h @@ -7,7 +7,7 @@ #include #include "flutter/fml/macros.h" -#include "impeller/renderer/backend/metal/backend_cast.h" +#include "impeller/base/backend_cast.h" #include "impeller/renderer/sampler.h" namespace impeller { diff --git a/engine/src/flutter/impeller/renderer/backend/metal/shader_function_mtl.h b/engine/src/flutter/impeller/renderer/backend/metal/shader_function_mtl.h index 6dc35b248e..e7f43c886b 100644 --- a/engine/src/flutter/impeller/renderer/backend/metal/shader_function_mtl.h +++ b/engine/src/flutter/impeller/renderer/backend/metal/shader_function_mtl.h @@ -7,7 +7,7 @@ #include #include "flutter/fml/macros.h" -#include "impeller/renderer/backend/metal/backend_cast.h" +#include "impeller/base/backend_cast.h" #include "impeller/renderer/shader_function.h" namespace impeller { diff --git a/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.mm b/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.mm index 8b0c6e26ca..3dbd602ab0 100644 --- a/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.mm +++ b/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.mm @@ -52,7 +52,7 @@ std::unique_ptr SurfaceMTL::WrapCurrentMetalLayerDrawable( return nullptr; } - msaa_tex->SetLabel("ImpellerOnscreenColor4xMSAA"); + msaa_tex->SetLabel("ImpellerOnscreenColorMSAA"); TextureDescriptor color0_resolve_tex_desc; color0_resolve_tex_desc.format = color_format; diff --git a/engine/src/flutter/impeller/renderer/backend/metal/texture_mtl.h b/engine/src/flutter/impeller/renderer/backend/metal/texture_mtl.h index 8f254672e2..02e9cbb4d3 100644 --- a/engine/src/flutter/impeller/renderer/backend/metal/texture_mtl.h +++ b/engine/src/flutter/impeller/renderer/backend/metal/texture_mtl.h @@ -7,7 +7,7 @@ #include #include "flutter/fml/macros.h" -#include "impeller/renderer/backend/metal/backend_cast.h" +#include "impeller/base/backend_cast.h" #include "impeller/renderer/texture.h" namespace impeller { diff --git a/engine/src/flutter/impeller/renderer/backend/metal/vertex_descriptor_mtl.h b/engine/src/flutter/impeller/renderer/backend/metal/vertex_descriptor_mtl.h index 82dcceb4da..0fe392b214 100644 --- a/engine/src/flutter/impeller/renderer/backend/metal/vertex_descriptor_mtl.h +++ b/engine/src/flutter/impeller/renderer/backend/metal/vertex_descriptor_mtl.h @@ -7,7 +7,7 @@ #include #include "flutter/fml/macros.h" -#include "impeller/renderer/backend/metal/backend_cast.h" +#include "impeller/base/backend_cast.h" #include "impeller/renderer/vertex_descriptor.h" namespace impeller { diff --git a/engine/src/flutter/impeller/renderer/formats.h b/engine/src/flutter/impeller/renderer/formats.h index 092d86283f..dedc080a80 100644 --- a/engine/src/flutter/impeller/renderer/formats.h +++ b/engine/src/flutter/impeller/renderer/formats.h @@ -48,6 +48,7 @@ class Texture; /// enum class PixelFormat { kUnknown, + kR8UNormInt, kR8G8B8A8UNormInt, kR8G8B8A8UNormIntSRGB, kB8G8R8A8UNormInt, @@ -193,6 +194,7 @@ constexpr size_t BytesPerPixelForPixelFormat(PixelFormat format) { switch (format) { case PixelFormat::kUnknown: return 0u; + case PixelFormat::kR8UNormInt: case PixelFormat::kS8UInt: return 1u; case PixelFormat::kR8G8B8A8UNormInt: diff --git a/engine/src/flutter/impeller/renderer/sampler_descriptor.h b/engine/src/flutter/impeller/renderer/sampler_descriptor.h index 6b0eb69c58..bb2fffc61f 100644 --- a/engine/src/flutter/impeller/renderer/sampler_descriptor.h +++ b/engine/src/flutter/impeller/renderer/sampler_descriptor.h @@ -21,6 +21,8 @@ struct SamplerDescriptor final : public Comparable { SamplerAddressMode height_address_mode = SamplerAddressMode::kClampToEdge; SamplerAddressMode depth_address_mode = SamplerAddressMode::kClampToEdge; + std::string label = "NN Clamp Sampler"; + // Comparable std::size_t GetHash() const override { return fml::HashCombine(min_filter, mag_filter, width_address_mode, diff --git a/engine/src/flutter/impeller/typographer/BUILD.gn b/engine/src/flutter/impeller/typographer/BUILD.gn new file mode 100644 index 0000000000..3e06926491 --- /dev/null +++ b/engine/src/flutter/impeller/typographer/BUILD.gn @@ -0,0 +1,50 @@ +# Copyright 2013 The Flutter 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("typographer") { + sources = [ + "backends/skia/text_frame_skia.cc", + "backends/skia/text_frame_skia.h", + "backends/skia/text_render_context_skia.cc", + "backends/skia/text_render_context_skia.h", + "backends/skia/typeface_skia.cc", + "backends/skia/typeface_skia.h", + "font.cc", + "font.h", + "font_glyph_pair.cc", + "font_glyph_pair.h", + "glyph.cc", + "glyph.h", + "glyph_atlas.cc", + "glyph_atlas.h", + "text_frame.cc", + "text_frame.h", + "text_render_context.cc", + "text_render_context.h", + "text_run.cc", + "text_run.h", + "typeface.cc", + "typeface.h", + ] + + public_deps = [ + "../base", + "../geometry", + "../renderer", + "//third_party/skia", + ] +} + +impeller_component("typographer_unittests") { + testonly = true + + sources = [ "typographer_unittests.cc" ] + + deps = [ + ":typographer", + "../playground", + ] +} diff --git a/engine/src/flutter/impeller/typographer/backends/skia/text_frame_skia.cc b/engine/src/flutter/impeller/typographer/backends/skia/text_frame_skia.cc new file mode 100644 index 0000000000..979d6fcda7 --- /dev/null +++ b/engine/src/flutter/impeller/typographer/backends/skia/text_frame_skia.cc @@ -0,0 +1,69 @@ +// Copyright 2013 The Flutter 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 "flutter/fml/logging.h" +#include "impeller/typographer/backends/skia/typeface_skia.h" +#include "third_party/skia/include/core/SkFont.h" +#include "third_party/skia/include/core/SkFontMetrics.h" +#include "third_party/skia/src/core/SkTextBlobPriv.h" // nogncheck + +namespace impeller { + +static Font ToFont(const SkFont& font) { + auto typeface = std::make_shared(font.refTypefaceOrDefault()); + + SkFontMetrics sk_metrics; + font.getMetrics(&sk_metrics); + + Font::Metrics metrics; + metrics.point_size = font.getSize(); + metrics.ascent = sk_metrics.fAscent; + metrics.descent = sk_metrics.fDescent; + + return Font{std::move(typeface), std::move(metrics)}; +} + +TextFrame TextFrameFromTextBlob(sk_sp blob) { + if (!blob) { + return {}; + } + + TextFrame frame; + + for (SkTextBlobRunIterator run(blob.get()); !run.done(); run.next()) { + TextRun text_run(ToFont(run.font())); + const auto glyph_count = run.glyphCount(); + const auto* glyphs = run.glyphs(); + switch (run.positioning()) { + case SkTextBlobRunIterator::kDefault_Positioning: + FML_DLOG(ERROR) << "Unimplemented."; + break; + case SkTextBlobRunIterator::kHorizontal_Positioning: + FML_DLOG(ERROR) << "Unimplemented."; + break; + case SkTextBlobRunIterator::kFull_Positioning: + 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; + text_run.AddGlyph(glyphs[i], + Matrix::MakeTranslation({point->x(), point->y()})); + } + break; + case SkTextBlobRunIterator::kRSXform_Positioning: + FML_DLOG(ERROR) << "Unimplemented."; + break; + default: + FML_DLOG(ERROR) << "Unimplemented."; + continue; + } + frame.AddTextRun(std::move(text_run)); + } + + return frame; +} + +} // namespace impeller diff --git a/engine/src/flutter/impeller/typographer/backends/skia/text_frame_skia.h b/engine/src/flutter/impeller/typographer/backends/skia/text_frame_skia.h new file mode 100644 index 0000000000..ca15f01881 --- /dev/null +++ b/engine/src/flutter/impeller/typographer/backends/skia/text_frame_skia.h @@ -0,0 +1,15 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#pragma once + +#include "flutter/fml/macros.h" +#include "impeller/typographer/text_frame.h" +#include "third_party/skia/include/core/SkTextBlob.h" + +namespace impeller { + +TextFrame TextFrameFromTextBlob(sk_sp blob); + +} // namespace impeller diff --git a/engine/src/flutter/impeller/typographer/backends/skia/text_render_context_skia.cc b/engine/src/flutter/impeller/typographer/backends/skia/text_render_context_skia.cc new file mode 100644 index 0000000000..84beacfca7 --- /dev/null +++ b/engine/src/flutter/impeller/typographer/backends/skia/text_render_context_skia.cc @@ -0,0 +1,252 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/typographer/backends/skia/text_render_context_skia.h" + +#include "flutter/fml/trace_event.h" +#include "impeller/base/allocation.h" +#include "impeller/renderer/allocator.h" +#include "impeller/typographer/backends/skia/typeface_skia.h" +#include "third_party/skia/include/core/SkBitmap.h" +#include "third_party/skia/include/core/SkCanvas.h" +#include "third_party/skia/include/core/SkFont.h" +#include "third_party/skia/include/core/SkFontMetrics.h" +#include "third_party/skia/include/core/SkRSXform.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/src/core/SkIPoint16.h" //nogncheck +#include "third_party/skia/src/gpu/GrRectanizer.h" //nogncheck + +namespace impeller { + +TextRenderContextSkia::TextRenderContextSkia(std::shared_ptr context) + : TextRenderContext(std::move(context)) {} + +TextRenderContextSkia::~TextRenderContextSkia() = default; + +static FontGlyphPair::Set CollectUniqueFontGlyphPairsSet( + const std::vector& runs) { + FontGlyphPair::Set set; + for (const auto& run : runs) { + auto font = run.GetFont(); + for (const auto& glyph_position : run.GetGlyphPositions()) { + set.insert({font, glyph_position.glyph}); + } + } + return set; +} + +static FontGlyphPair::Vector CollectUniqueFontGlyphPairs( + const std::vector& runs) { + TRACE_EVENT0("impeller", __FUNCTION__); + FontGlyphPair::Vector vector; + auto set = CollectUniqueFontGlyphPairsSet(runs); + vector.reserve(set.size()); + for (const auto& item : set) { + vector.emplace_back(std::move(item)); + } + return vector; +} + +static bool PairsFitInAtlasOfSize(const FontGlyphPair::Vector& pairs, + size_t atlas_size, + std::vector& glyph_positions) { + if (atlas_size == 0u) { + return false; + } + + auto rect_packer = std::unique_ptr( + GrRectanizer::Factory(atlas_size, atlas_size)); + + glyph_positions.clear(); + glyph_positions.reserve(pairs.size()); + + for (const auto& pair : pairs) { + auto glyph_size = pair.font.GetGlyphSize(); + if (!glyph_size.has_value()) { + continue; + } + SkIPoint16 location_in_atlas; + if (!rect_packer->addRect(glyph_size->width, // + glyph_size->height, // + &location_in_atlas // + )) { + return false; + } + glyph_positions.emplace_back(Rect::MakeXYWH(location_in_atlas.x(), // + location_in_atlas.y(), // + glyph_size->width, // + glyph_size->height // + )); + } + + return true; +} + +static size_t OptimumAtlasSizeForFontGlyphPairs( + const FontGlyphPair::Vector& pairs, + std::vector& glyph_positions) { + static constexpr auto kMinAtlasSize = 8u; + static constexpr auto kMaxAtlasSize = 4096u; + + TRACE_EVENT0("impeller", __FUNCTION__); + + size_t current_size = kMinAtlasSize; + do { + if (PairsFitInAtlasOfSize(pairs, current_size, glyph_positions)) { + return current_size; + } + current_size = Allocation::NextPowerOfTwoSize(current_size + 1); + } while (current_size <= kMaxAtlasSize); + return 0u; +} + +static std::optional CreateAtlasBitmap(const GlyphAtlas& atlas, + size_t atlas_size) { + TRACE_EVENT0("impeller", __FUNCTION__); + SkBitmap bitmap; + auto image_info = SkImageInfo::MakeN32Premul(atlas_size, atlas_size); + if (!bitmap.tryAllocPixels(image_info)) { + return std::nullopt; + } + auto surface = SkSurface::MakeRasterDirect(bitmap.pixmap()); + if (!surface) { + return std::nullopt; + } + auto canvas = surface->getCanvas(); + if (!canvas) { + return std::nullopt; + } + + atlas.IterateGlyphs([canvas](const FontGlyphPair& font_glyph, + const Rect& location) -> bool { + const auto position = SkPoint::Make(location.origin.x, location.origin.y); + SkGlyphID glyph_id = font_glyph.glyph.index; + SkFont font( + TypefaceSkia::Cast(*font_glyph.font.GetTypeface()).GetSkiaTypeface(), + font_glyph.font.GetMetrics().point_size); + + SkFontMetrics metrics; + font.getMetrics(&metrics); + + SkPaint glyph_paint; + glyph_paint.setColor(SK_ColorWHITE); + canvas->drawGlyphs(1u, // count + &glyph_id, // glyphs + &position, // positions + SkPoint::Make(0.0, + -metrics.fAscent), // origin + font, // font + glyph_paint // paint + ); + return true; + }); + + return bitmap; +} + +static std::shared_ptr UploadGlyphTextureAtlas( + std::shared_ptr allocator, + const SkBitmap& bitmap, + size_t atlas_size) { + TRACE_EVENT0("impeller", __FUNCTION__); + if (!allocator) { + return nullptr; + } + + const auto& pixmap = bitmap.pixmap(); + + TextureDescriptor texture_descriptor; + texture_descriptor.format = PixelFormat::kR8G8B8A8UNormInt; + texture_descriptor.size = ISize::MakeWH(atlas_size, atlas_size); + + if (pixmap.rowBytes() * pixmap.height() != + texture_descriptor.GetSizeOfBaseMipLevel()) { + return nullptr; + } + + auto texture = + allocator->CreateTexture(StorageMode::kHostVisible, texture_descriptor); + if (!texture || !texture->IsValid()) { + return nullptr; + } + texture->SetLabel("GlyphAtlas"); + + if (!texture->SetContents(static_cast(pixmap.addr()), + pixmap.rowBytes() * pixmap.height())) { + return nullptr; + } + return texture; +} + +std::shared_ptr TextRenderContextSkia::CreateGlyphAtlas( + const TextFrame& frame) const { + TRACE_EVENT0("impeller", __FUNCTION__); + if (!IsValid()) { + return nullptr; + } + + auto glyph_atlas = std::make_shared(); + + // --------------------------------------------------------------------------- + // Step 1: Collect unique font-glyph pairs in the frame. + // --------------------------------------------------------------------------- + auto font_glyph_pairs = CollectUniqueFontGlyphPairs(frame.GetRuns()); + if (font_glyph_pairs.empty()) { + return glyph_atlas; + } + + // --------------------------------------------------------------------------- + // Step 2: Get the optimum size of the texture atlas. + // --------------------------------------------------------------------------- + std::vector glyph_positions; + const auto atlas_size = + OptimumAtlasSizeForFontGlyphPairs(font_glyph_pairs, glyph_positions); + if (atlas_size == 0u) { + return nullptr; + } + + // --------------------------------------------------------------------------- + // Step 3: Find location of font-glyph pairs in the atlas. We have this from + // the last step. So no need to do create another rect packer. But just do a + // sanity check of counts. This could also be just an assertion as only a + // construction issue would cause such a failure. + // --------------------------------------------------------------------------- + if (glyph_positions.size() != font_glyph_pairs.size()) { + return nullptr; + } + + // --------------------------------------------------------------------------- + // Step 4: Record the positions in the glyph atlas. + // --------------------------------------------------------------------------- + for (size_t i = 0, count = glyph_positions.size(); i < count; i++) { + glyph_atlas->AddTypefaceGlyphPosition(font_glyph_pairs[i], + glyph_positions[i]); + } + + // --------------------------------------------------------------------------- + // Step 5: Draw font-glyph pairs in the correct spot in the atlas. + // --------------------------------------------------------------------------- + auto bitmap = CreateAtlasBitmap(*glyph_atlas, atlas_size); + if (!bitmap.has_value()) { + return nullptr; + } + + // --------------------------------------------------------------------------- + // Step 6: Upload the atlas as a texture. + // --------------------------------------------------------------------------- + auto texture = UploadGlyphTextureAtlas(GetContext()->GetTransientsAllocator(), + bitmap.value(), atlas_size); + if (!texture) { + return nullptr; + } + + // --------------------------------------------------------------------------- + // Step 7: Record the texture in the glyph atlas. + // --------------------------------------------------------------------------- + glyph_atlas->SetTexture(std::move(texture)); + + return glyph_atlas; +} + +} // namespace impeller diff --git a/engine/src/flutter/impeller/typographer/backends/skia/text_render_context_skia.h b/engine/src/flutter/impeller/typographer/backends/skia/text_render_context_skia.h new file mode 100644 index 0000000000..936b64bfde --- /dev/null +++ b/engine/src/flutter/impeller/typographer/backends/skia/text_render_context_skia.h @@ -0,0 +1,26 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#pragma once + +#include "flutter/fml/macros.h" +#include "impeller/typographer/text_render_context.h" + +namespace impeller { + +class TextRenderContextSkia : public TextRenderContext { + public: + TextRenderContextSkia(std::shared_ptr context); + + ~TextRenderContextSkia() override; + + // |TextRenderContext| + std::shared_ptr CreateGlyphAtlas( + const TextFrame& frame) const override; + + private: + FML_DISALLOW_COPY_AND_ASSIGN(TextRenderContextSkia); +}; + +} // namespace impeller diff --git a/engine/src/flutter/impeller/typographer/backends/skia/typeface_skia.cc b/engine/src/flutter/impeller/typographer/backends/skia/typeface_skia.cc new file mode 100644 index 0000000000..552e159f1f --- /dev/null +++ b/engine/src/flutter/impeller/typographer/backends/skia/typeface_skia.cc @@ -0,0 +1,46 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/typographer/backends/skia/typeface_skia.h" + +namespace impeller { + +TypefaceSkia::TypefaceSkia(sk_sp typeface) + : typeface_(std::move(typeface)) {} + +TypefaceSkia::~TypefaceSkia() = default; + +bool TypefaceSkia::IsValid() const { + return !!typeface_; +} + +std::size_t TypefaceSkia::GetHash() const { + if (!IsValid()) { + return 0u; + } + + return reinterpret_cast(typeface_.get()); +} + +bool TypefaceSkia::IsEqual(const Typeface& other) const { + auto sk_other = reinterpret_cast(&other); + return sk_other->typeface_ == typeface_; +} + +Rect TypefaceSkia::GetBoundingBox() const { + if (!IsValid()) { + return {}; + } + + const auto bounds = typeface_->getBounds(); + + return Rect::MakeLTRB(bounds.left(), bounds.top(), bounds.right(), + bounds.bottom()); +} + +const sk_sp& TypefaceSkia::GetSkiaTypeface() const { + return typeface_; +} + +} // namespace impeller diff --git a/engine/src/flutter/impeller/typographer/backends/skia/typeface_skia.h b/engine/src/flutter/impeller/typographer/backends/skia/typeface_skia.h new file mode 100644 index 0000000000..6ac52c4776 --- /dev/null +++ b/engine/src/flutter/impeller/typographer/backends/skia/typeface_skia.h @@ -0,0 +1,42 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#pragma once + +#include "flutter/fml/macros.h" +#include "impeller/base/backend_cast.h" +#include "impeller/typographer/typeface.h" +#include "third_party/skia/include/core/SkRefCnt.h" +#include "third_party/skia/include/core/SkTypeface.h" + +namespace impeller { + +class TypefaceSkia final : public Typeface, + public BackendCast { + public: + TypefaceSkia(sk_sp typeface); + + ~TypefaceSkia() override; + + // |Typeface| + bool IsValid() const override; + + // |Comparable| + std::size_t GetHash() const override; + + // |Comparable| + bool IsEqual(const Typeface& other) const override; + + // |Typeface| + Rect GetBoundingBox() const override; + + const sk_sp& GetSkiaTypeface() const; + + private: + sk_sp typeface_; + + FML_DISALLOW_COPY_AND_ASSIGN(TypefaceSkia); +}; + +} // namespace impeller diff --git a/engine/src/flutter/impeller/typographer/font.cc b/engine/src/flutter/impeller/typographer/font.cc new file mode 100644 index 0000000000..e675b0431e --- /dev/null +++ b/engine/src/flutter/impeller/typographer/font.cc @@ -0,0 +1,48 @@ +// Copyright 2013 The Flutter 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/font.h" + +namespace impeller { + +Font::Font(std::shared_ptr typeface, Metrics metrics) + : typeface_(std::move(typeface)), metrics_(std::move(metrics)) { + if (!typeface_) { + return; + } + is_valid_ = true; +} + +Font::~Font() = default; + +bool Font::IsValid() const { + return is_valid_; +} + +const std::shared_ptr& Font::GetTypeface() const { + return typeface_; +} + +std::size_t Font::GetHash() const { + return fml::HashCombine(is_valid_, typeface_ ? typeface_->GetHash() : 0u, + metrics_); +} + +bool Font::IsEqual(const Font& other) const { + return DeepComparePointer(typeface_, other.typeface_) && + is_valid_ == other.is_valid_ && metrics_ == other.metrics_; +} + +std::optional Font::GetGlyphSize() const { + if (!IsValid()) { + return std::nullopt; + } + return ISize::Ceil(typeface_->GetBoundingBox().size * metrics_.point_size); +} + +const Font::Metrics& Font::GetMetrics() const { + return metrics_; +} + +} // namespace impeller diff --git a/engine/src/flutter/impeller/typographer/font.h b/engine/src/flutter/impeller/typographer/font.h new file mode 100644 index 0000000000..2b4af8f86f --- /dev/null +++ b/engine/src/flutter/impeller/typographer/font.h @@ -0,0 +1,96 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#pragma once + +#include +#include + +#include "flutter/fml/macros.h" +#include "impeller/renderer/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 { + 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; + //-------------------------------------------------------------------------- + /// The font ascent relative to the baseline. This is usually negative as + /// moving upwards (ascending) in an upper-left-origin coordinate system + /// yields smaller numbers. + /// + Scalar ascent = 0.0f; + //-------------------------------------------------------------------------- + /// The font descent relative to the baseline. This is usually positive as + /// moving downwards (descending) in an upper-left-origin coordinate system + /// yields larger numbers. + /// + Scalar descent = 0.0f; + + constexpr bool operator==(const Metrics& o) const { + return point_size == o.point_size && ascent == o.ascent && + descent == o.descent; + } + }; + + Font(std::shared_ptr typeface, Metrics metrics); + + ~Font(); + + bool IsValid() const; + + //---------------------------------------------------------------------------- + /// @brief The typeface whose intrinsic properties this font modifies. + /// + /// @return The typeface. + /// + const std::shared_ptr& GetTypeface() const; + + //---------------------------------------------------------------------------- + /// @brief A conservatively large scaled bounding box of all glyphs in + /// this font. + /// + /// @return The scaled glyph size. + /// + std::optional GetGlyphSize() const; + + const Metrics& GetMetrics() const; + + // |Comparable| + std::size_t GetHash() const override; + + // |Comparable| + bool IsEqual(const Font& other) const override; + + private: + std::shared_ptr typeface_; + Metrics metrics_ = {}; + bool is_valid_ = false; +}; + +} // namespace impeller + +template <> +struct std::hash { + constexpr std::size_t operator()(const impeller::Font::Metrics& m) const { + return fml::HashCombine(m.point_size, m.ascent, m.descent); + } +}; diff --git a/engine/src/flutter/impeller/typographer/font_glyph_pair.cc b/engine/src/flutter/impeller/typographer/font_glyph_pair.cc new file mode 100644 index 0000000000..667caadb4e --- /dev/null +++ b/engine/src/flutter/impeller/typographer/font_glyph_pair.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter 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/font_glyph_pair.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/engine/src/flutter/impeller/typographer/font_glyph_pair.h b/engine/src/flutter/impeller/typographer/font_glyph_pair.h new file mode 100644 index 0000000000..b8cb7b0af2 --- /dev/null +++ b/engine/src/flutter/impeller/typographer/font_glyph_pair.h @@ -0,0 +1,44 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#pragma once + +#include +#include +#include + +#include "flutter/fml/macros.h" +#include "impeller/geometry/size.h" +#include "impeller/typographer/font.h" +#include "impeller/typographer/glyph.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief A font along with a glyph in that font. Used in glyph atlases as +/// keys. +/// +struct FontGlyphPair { + struct Hash; + struct Equal; + + using Set = std::unordered_set; + using Vector = std::vector; + + Font font; + Glyph glyph; + + struct Hash { + std::size_t operator()(const FontGlyphPair& p) const { + return fml::HashCombine(p.font.GetHash(), p.glyph); + } + }; + struct Equal { + bool operator()(const FontGlyphPair& lhs, const FontGlyphPair& rhs) const { + return lhs.font.IsEqual(rhs.font) && lhs.glyph.index == rhs.glyph.index; + } + }; +}; + +} // namespace impeller diff --git a/engine/src/flutter/impeller/typographer/glyph.cc b/engine/src/flutter/impeller/typographer/glyph.cc new file mode 100644 index 0000000000..9182d8f1f9 --- /dev/null +++ b/engine/src/flutter/impeller/typographer/glyph.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter 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/glyph.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/engine/src/flutter/impeller/typographer/glyph.h b/engine/src/flutter/impeller/typographer/glyph.h new file mode 100644 index 0000000000..000346ba9d --- /dev/null +++ b/engine/src/flutter/impeller/typographer/glyph.h @@ -0,0 +1,38 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#pragma once + +#include +#include + +#include "flutter/fml/macros.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief The glyph index in the typeface. +/// +struct Glyph { + uint16_t index = 0; + + Glyph(uint16_t p_index) : index(p_index) {} +}; + +} // namespace impeller + +template <> +struct std::hash { + constexpr std::size_t operator()(const impeller::Glyph& g) const { + return g.index; + } +}; + +template <> +struct std::less { + constexpr bool operator()(const impeller::Glyph& lhs, + const impeller::Glyph& rhs) const { + return lhs.index < rhs.index; + } +}; diff --git a/engine/src/flutter/impeller/typographer/glyph_atlas.cc b/engine/src/flutter/impeller/typographer/glyph_atlas.cc new file mode 100644 index 0000000000..7ed4578bbd --- /dev/null +++ b/engine/src/flutter/impeller/typographer/glyph_atlas.cc @@ -0,0 +1,59 @@ +// Copyright 2013 The Flutter 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/glyph_atlas.h" + +namespace impeller { + +GlyphAtlas::GlyphAtlas() = default; + +GlyphAtlas::~GlyphAtlas() = default; + +bool GlyphAtlas::IsValid() const { + return !!texture_; +} + +const std::shared_ptr& GlyphAtlas::GetTexture() const { + return texture_; +} + +void GlyphAtlas::SetTexture(std::shared_ptr texture) { + texture_ = std::move(texture); +} + +void GlyphAtlas::AddTypefaceGlyphPosition(FontGlyphPair pair, Rect rect) { + positions_[pair] = rect; +} + +std::optional GlyphAtlas::FindFontGlyphPosition( + const FontGlyphPair& pair) const { + auto found = positions_.find(pair); + if (found == positions_.end()) { + return std::nullopt; + } + return found->second; +} + +size_t GlyphAtlas::GetGlyphCount() const { + return positions_.size(); +} + +size_t GlyphAtlas::IterateGlyphs( + std::function iterator) + const { + if (!iterator) { + return 0u; + } + + size_t count = 0u; + for (const auto& position : positions_) { + count++; + if (!iterator(position.first, position.second)) { + return count; + } + } + return count; +} + +} // namespace impeller diff --git a/engine/src/flutter/impeller/typographer/glyph_atlas.h b/engine/src/flutter/impeller/typographer/glyph_atlas.h new file mode 100644 index 0000000000..e72c3b83e1 --- /dev/null +++ b/engine/src/flutter/impeller/typographer/glyph_atlas.h @@ -0,0 +1,99 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#pragma once + +#include +#include +#include +#include + +#include "flutter/fml/macros.h" +#include "impeller/geometry/rect.h" +#include "impeller/renderer/texture.h" +#include "impeller/typographer/font_glyph_pair.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief A texture containing the bitmap representation of glyphs in +/// different fonts along with the ability to query the location of +/// specific font glyphs within the texture. +/// +class GlyphAtlas { + public: + //---------------------------------------------------------------------------- + /// @brief Create an empty glyph atlas. + /// + GlyphAtlas(); + + ~GlyphAtlas(); + + bool IsValid() const; + + //---------------------------------------------------------------------------- + /// @brief Set the texture for the glyph atlas. + /// + /// @param[in] texture The texture + /// + void SetTexture(std::shared_ptr texture); + + //---------------------------------------------------------------------------- + /// @brief Get the texture for the glyph atlas. + /// + /// @return The texture. + /// + const std::shared_ptr& GetTexture() const; + + //---------------------------------------------------------------------------- + /// @brief Record there location of a specific font-glyph pair within the + /// atlas. + /// + /// @param[in] pair The font-glyph pair + /// @param[in] rect The rectangle + /// + void AddTypefaceGlyphPosition(FontGlyphPair pair, Rect rect); + + //---------------------------------------------------------------------------- + /// @brief Get the number of unique font-glyph pairs in this atlas. + /// + /// @return The glyph count. + /// + size_t GetGlyphCount() const; + + //---------------------------------------------------------------------------- + /// @brief Iterate of all the glyphs along with their locations in the + /// atlas. + /// + /// @param[in] iterator The iterator. Return `false` from the iterator to + /// stop iterating. + /// + /// @return The number of glyphs iterated over. + /// + size_t IterateGlyphs(std::function iterator) const; + + //---------------------------------------------------------------------------- + /// @brief Find the location of a specific font-glyph pair in the atlas. + /// + /// @param[in] pair The font-glyph pair + /// + /// @return The location of the font-glyph pair in the atlas. + /// `std::nullopt` of the pair in not in the atlas. + /// + std::optional FindFontGlyphPosition(const FontGlyphPair& pair) const; + + private: + std::shared_ptr texture_; + + std::unordered_map + positions_; + + FML_DISALLOW_COPY_AND_ASSIGN(GlyphAtlas); +}; + +} // namespace impeller diff --git a/engine/src/flutter/impeller/typographer/text_frame.cc b/engine/src/flutter/impeller/typographer/text_frame.cc new file mode 100644 index 0000000000..f6681e5e46 --- /dev/null +++ b/engine/src/flutter/impeller/typographer/text_frame.cc @@ -0,0 +1,29 @@ +// Copyright 2013 The Flutter 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/text_frame.h" + +namespace impeller { + +TextFrame::TextFrame() = default; + +TextFrame::~TextFrame() = default; + +bool TextFrame::AddTextRun(TextRun run) { + if (!run.IsValid()) { + return false; + } + runs_.emplace_back(std::move(run)); + return true; +} + +size_t TextFrame::GetRunCount() const { + return runs_.size(); +} + +const std::vector& TextFrame::GetRuns() const { + return runs_; +} + +} // namespace impeller diff --git a/engine/src/flutter/impeller/typographer/text_frame.h b/engine/src/flutter/impeller/typographer/text_frame.h new file mode 100644 index 0000000000..a6d86b01d0 --- /dev/null +++ b/engine/src/flutter/impeller/typographer/text_frame.h @@ -0,0 +1,51 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#pragma once + +#include "flutter/fml/macros.h" +#include "impeller/typographer/text_run.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief Represents a collection of shaped text runs. +/// +/// This object is typically the entrypoint in the Impeller type +/// rendering subsystem. +/// +class TextFrame { + public: + TextFrame(); + + ~TextFrame(); + + //---------------------------------------------------------------------------- + /// @brief The number of runs in this text frame. + /// + /// @return The run count. + /// + size_t GetRunCount() const; + + //---------------------------------------------------------------------------- + /// @brief Adds a new text run to the text frame. + /// + /// @param[in] run The run + /// + /// @return If the text run could be added to this frame. + /// + bool AddTextRun(TextRun run); + + //---------------------------------------------------------------------------- + /// @brief Returns a reference to all the text runs in this frame. + /// + /// @return The runs in this frame. + /// + const std::vector& GetRuns() const; + + private: + std::vector runs_; +}; + +} // namespace impeller diff --git a/engine/src/flutter/impeller/typographer/text_render_context.cc b/engine/src/flutter/impeller/typographer/text_render_context.cc new file mode 100644 index 0000000000..600e213915 --- /dev/null +++ b/engine/src/flutter/impeller/typographer/text_render_context.cc @@ -0,0 +1,27 @@ +// Copyright 2019 The Fuchsia 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/text_render_context.h" + +namespace impeller { + +TextRenderContext::TextRenderContext(std::shared_ptr context) + : context_(std::move(context)) { + if (!context_ || !context_->IsValid()) { + return; + } + is_valid_ = true; +} + +TextRenderContext::~TextRenderContext() = default; + +bool TextRenderContext::IsValid() const { + return is_valid_; +} + +const std::shared_ptr& TextRenderContext::GetContext() const { + return context_; +} + +} // namespace impeller diff --git a/engine/src/flutter/impeller/typographer/text_render_context.h b/engine/src/flutter/impeller/typographer/text_render_context.h new file mode 100644 index 0000000000..8d5ac6fa13 --- /dev/null +++ b/engine/src/flutter/impeller/typographer/text_render_context.h @@ -0,0 +1,63 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#pragma once + +#include + +#include "flutter/fml/macros.h" +#include "impeller/renderer/context.h" +#include "impeller/typographer/glyph_atlas.h" +#include "impeller/typographer/text_frame.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief The graphics context necessary to render text. +/// +/// This is necessary to create and reference resources related to +/// rendering text on the GPU. +/// +/// It is caller responsibility to create as few of these and keep +/// these around for as long possible. +/// +class TextRenderContext { + public: + //---------------------------------------------------------------------------- + /// @brief Create a new context to render text that talks to an + /// underlying graphics context. + /// + /// @param[in] context The graphics context + /// + TextRenderContext(std::shared_ptr context); + + virtual ~TextRenderContext(); + + virtual bool IsValid() const; + + //---------------------------------------------------------------------------- + /// @brief Get the underlying graphics context. + /// + /// @return The context. + /// + const std::shared_ptr& GetContext() const; + + //---------------------------------------------------------------------------- + /// @brief Create a new glyph atlas for the specified text frame. + /// + /// @param[in] frame The text frame + /// + /// @return A valid glyph atlas or null. + /// + virtual std::shared_ptr CreateGlyphAtlas( + const TextFrame& frame) const = 0; + + private: + std::shared_ptr context_; + bool is_valid_ = false; + + FML_DISALLOW_COPY_AND_ASSIGN(TextRenderContext); +}; + +} // namespace impeller diff --git a/engine/src/flutter/impeller/typographer/text_run.cc b/engine/src/flutter/impeller/typographer/text_run.cc new file mode 100644 index 0000000000..dc21b3865b --- /dev/null +++ b/engine/src/flutter/impeller/typographer/text_run.cc @@ -0,0 +1,39 @@ +// Copyright 2013 The Flutter 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/text_run.h" + +namespace impeller { + +TextRun::TextRun(Font font) : font_(std::move(font)) { + if (!font.IsValid()) { + return; + } + is_valid_ = true; +} + +TextRun::~TextRun() = default; + +bool TextRun::AddGlyph(Glyph glyph, Matrix position) { + glyphs_.emplace_back(GlyphPosition{glyph, position}); + return true; +} + +bool TextRun::IsValid() const { + return is_valid_; +} + +const std::vector& TextRun::GetGlyphPositions() const { + return glyphs_; +} + +size_t TextRun::GetGlyphCount() const { + return glyphs_.size(); +} + +const Font& TextRun::GetFont() const { + return font_; +} + +} // namespace impeller diff --git a/engine/src/flutter/impeller/typographer/text_run.h b/engine/src/flutter/impeller/typographer/text_run.h new file mode 100644 index 0000000000..10c5e3ef71 --- /dev/null +++ b/engine/src/flutter/impeller/typographer/text_run.h @@ -0,0 +1,77 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#pragma once + +#include + +#include "impeller/geometry/matrix.h" +#include "impeller/typographer/font.h" +#include "impeller/typographer/glyph.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief Represents a collection of positioned glyphs from a specific +/// font. +/// +class TextRun { + public: + struct GlyphPosition { + Glyph glyph; + Matrix position; + + GlyphPosition(Glyph p_glyph, Matrix p_position) + : glyph(p_glyph), position(p_position) {} + }; + + //---------------------------------------------------------------------------- + /// @brief Create an empty text run with the specified font. + /// + /// @param[in] font The font + /// + TextRun(Font font); + + ~TextRun(); + + bool IsValid() const; + + //---------------------------------------------------------------------------- + /// @brief Add a glyph at the specified position to the run. + /// + /// @param[in] glyph The glyph + /// @param[in] position The position + /// + /// @return If the glyph could be added to the run. + /// + bool AddGlyph(Glyph glyph, Matrix position); + + //---------------------------------------------------------------------------- + /// @brief Get the number of glyphs in the run. + /// + /// @return The glyph count. + /// + size_t GetGlyphCount() const; + + //---------------------------------------------------------------------------- + /// @brief Get a reference to all the glyph positions within the run. + /// + /// @return The glyph positions. + /// + const std::vector& GetGlyphPositions() const; + + //---------------------------------------------------------------------------- + /// @brief Get the font for this run. + /// + /// @return The font. + /// + const Font& GetFont() const; + + private: + Font font_; + std::vector glyphs_; + bool is_valid_ = false; +}; + +} // namespace impeller diff --git a/engine/src/flutter/impeller/typographer/typeface.cc b/engine/src/flutter/impeller/typographer/typeface.cc new file mode 100644 index 0000000000..9c5fdd5451 --- /dev/null +++ b/engine/src/flutter/impeller/typographer/typeface.cc @@ -0,0 +1,13 @@ +// Copyright 2013 The Flutter 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/typeface.h" + +namespace impeller { + +Typeface::Typeface() = default; + +Typeface::~Typeface() = default; + +} // namespace impeller diff --git a/engine/src/flutter/impeller/typographer/typeface.h b/engine/src/flutter/impeller/typographer/typeface.h new file mode 100644 index 0000000000..5c2a8574ee --- /dev/null +++ b/engine/src/flutter/impeller/typographer/typeface.h @@ -0,0 +1,40 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#pragma once + +#include "flutter/fml/macros.h" +#include "impeller/geometry/rect.h" +#include "impeller/renderer/comparable.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 { + public: + Typeface(); + + virtual ~Typeface(); + + virtual bool IsValid() const = 0; + + //---------------------------------------------------------------------------- + /// @brief Get the union of the bounding boxes of all glyphs in the + /// typeface. This box is unit-scaled and conservatively large to + /// cover all glyphs. + /// + /// @return The conservative unit-scaled bounding box. + /// + virtual Rect GetBoundingBox() const = 0; + + private: + FML_DISALLOW_COPY_AND_ASSIGN(Typeface); +}; + +} // namespace impeller diff --git a/engine/src/flutter/impeller/typographer/typographer_unittests.cc b/engine/src/flutter/impeller/typographer/typographer_unittests.cc new file mode 100644 index 0000000000..1f59d633bc --- /dev/null +++ b/engine/src/flutter/impeller/typographer/typographer_unittests.cc @@ -0,0 +1,46 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" +#include "impeller/playground/playground.h" +#include "impeller/typographer/backends/skia/text_frame_skia.h" +#include "impeller/typographer/backends/skia/text_render_context_skia.h" +#include "third_party/skia/include/core/SkTextBlob.h" + +namespace impeller { +namespace testing { + +using TypographerTest = Playground; + +TEST_F(TypographerTest, CanConvertTextBlob) { + SkFont font; + auto blob = SkTextBlob::MakeFromString( + "the quick brown fox jumped over the lazy dog.", font); + ASSERT_TRUE(blob); + auto frame = TextFrameFromTextBlob(blob); + ASSERT_EQ(frame.GetRunCount(), 1u); + for (const auto& run : frame.GetRuns()) { + ASSERT_TRUE(run.IsValid()); + ASSERT_EQ(run.GetGlyphCount(), 45u); + } +} + +TEST_F(TypographerTest, CanCreateRenderContext) { + auto context = std::make_shared(GetContext()); + ASSERT_TRUE(context->IsValid()); +} + +TEST_F(TypographerTest, CanCreateGlyphAtlas) { + auto context = std::make_shared(GetContext()); + ASSERT_TRUE(context->IsValid()); + SkFont sk_font; + auto blob = SkTextBlob::MakeFromString("hello", sk_font); + ASSERT_TRUE(blob); + auto atlas = context->CreateGlyphAtlas(TextFrameFromTextBlob(blob)); + ASSERT_NE(atlas, nullptr); + OpenPlaygroundHere([](auto&) { return true; }); +} + +} // namespace testing +} // namespace impeller