Implement texture mapping.

This commit is contained in:
Chinmay Garde
2021-11-16 15:21:25 -08:00
committed by Dan Field
parent 96fda8f7be
commit 6dc7ec06f9
23 changed files with 434 additions and 39 deletions

View File

@@ -31,10 +31,15 @@ impeller_component("aiks") {
impeller_component("aiks_unittests") {
testonly = true
sources = [ "aiks_unittests.cc" ]
sources = [
"aiks_playground.cc",
"aiks_playground.h",
"aiks_unittests.cc",
]
deps = [
":aiks",
"../geometry:geometry_unittests",
"../playground",
"//flutter/testing",
]
}

View File

@@ -0,0 +1,27 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/aiks/aiks_playground.h"
#include "impeller/aiks/picture_renderer.h"
namespace impeller {
AiksPlayground::AiksPlayground() = default;
AiksPlayground::~AiksPlayground() = default;
bool AiksPlayground::OpenPlaygroundHere(const Picture& picture) {
auto renderer = std::make_shared<PictureRenderer>(GetContext());
if (!renderer) {
return false;
}
return Playground::OpenPlaygroundHere(
[renderer, &picture](const Surface& surface, RenderPass& pass) -> bool {
return renderer->Render(surface, pass, picture);
});
}
} // namespace impeller

View File

@@ -0,0 +1,25 @@
// Copyright 2013 The Flutter 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/aiks/picture.h"
#include "impeller/playground/playground.h"
namespace impeller {
class AiksPlayground : public Playground {
public:
AiksPlayground();
~AiksPlayground();
bool OpenPlaygroundHere(const Picture& picture);
private:
FML_DISALLOW_COPY_AND_ASSIGN(AiksPlayground);
};
} // namespace impeller

View File

@@ -3,13 +3,18 @@
// found in the LICENSE file.
#include "flutter/testing/testing.h"
#include "impeller/aiks/aiks_playground.h"
#include "impeller/aiks/canvas.h"
#include "impeller/aiks/image.h"
#include "impeller/geometry/geometry_unittests.h"
#include "impeller/geometry/path_builder.h"
namespace impeller {
namespace testing {
TEST(AiksTest, CanvasCTMCanBeUpdated) {
using AiksTest = AiksPlayground;
TEST_F(AiksTest, CanvasCTMCanBeUpdated) {
Canvas canvas;
Matrix identity;
ASSERT_MATRIX_NEAR(canvas.GetCurrentTransformation(), identity);
@@ -18,7 +23,7 @@ TEST(AiksTest, CanvasCTMCanBeUpdated) {
Matrix::MakeTranslation({100.0, 100.0, 0.0}));
}
TEST(AiksTest, CanvasCanPushPopCTM) {
TEST_F(AiksTest, CanvasCanPushPopCTM) {
Canvas canvas;
ASSERT_EQ(canvas.GetSaveCount(), 1u);
ASSERT_EQ(canvas.Restore(), false);
@@ -34,5 +39,42 @@ TEST(AiksTest, CanvasCanPushPopCTM) {
Matrix::MakeTranslation({100.0, 100.0, 0.0}));
}
TEST_F(AiksTest, CanRenderColoredRect) {
Canvas canvas;
Paint paint;
paint.color = Color::Red();
canvas.DrawPath(PathBuilder{}
.AddRect(Rect::MakeXYWH(100.0, 100.0, 100.0, 100.0))
.CreatePath(),
paint);
// ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_F(AiksTest, CanRenderImage) {
Canvas canvas;
Paint paint;
auto image = std::make_shared<Image>(CreateTextureForFixture("kalimba.jpg"));
paint.color = Color::Red();
canvas.DrawImage(image, Point::MakeXY(100.0, 100.0), paint);
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_F(AiksTest, CanRenderImageRect) {
Canvas canvas;
Paint paint;
auto image = std::make_shared<Image>(CreateTextureForFixture("kalimba.jpg"));
auto source_rect = IRect::MakeSize(image->GetSize());
// Render the bottom right quarter of the source image in a stretched rect.
source_rect.size.width /= 2;
source_rect.size.height /= 2;
source_rect.origin.x += source_rect.size.width;
source_rect.origin.y += source_rect.size.height;
canvas.DrawImageRect(image, source_rect, Rect::MakeXYWH(100, 100, 600, 600),
paint);
// ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
} // namespace testing
} // namespace impeller

View File

@@ -7,6 +7,7 @@
#include <algorithm>
#include "flutter/fml/logging.h"
#include "impeller/geometry/path_builder.h"
namespace impeller {
@@ -98,6 +99,45 @@ void Canvas::DrawPicture(const Picture& picture) {
}
}
void Canvas::DrawImage(std::shared_ptr<Image> image,
Point offset,
Paint paint) {
if (!image) {
return;
}
const auto source = IRect::MakeSize(image->GetSize());
const auto dest =
Rect::MakeXYWH(offset.x, offset.y, source.size.width, source.size.height);
DrawImageRect(image, source, dest, std::move(paint));
}
void Canvas::DrawImageRect(std::shared_ptr<Image> image,
IRect source,
Rect dest,
Paint paint) {
if (!image || source.size.IsEmpty() || dest.size.IsEmpty()) {
return;
}
auto size = image->GetSize();
if (size.IsEmpty()) {
return;
}
auto contents = std::make_shared<TextureContents>();
contents->SetTexture(image->GetTexture());
contents->SetSourceRect(source);
Entity entity;
entity.SetPath(PathBuilder{}.AddRect(dest).CreatePath());
entity.SetContents(contents);
entity.SetTransformation(GetCurrentTransformation());
GetCurrentPass().PushEntity(std::move(entity));
}
Picture Canvas::EndRecordingAsPicture() {
Picture picture;
picture.passes = std::move(passes_);

View File

@@ -11,10 +11,12 @@
#include "flutter/fml/macros.h"
#include "impeller/aiks/canvas_pass.h"
#include "impeller/aiks/image.h"
#include "impeller/aiks/paint.h"
#include "impeller/aiks/picture.h"
#include "impeller/geometry/matrix.h"
#include "impeller/geometry/path.h"
#include "impeller/geometry/point.h"
#include "impeller/geometry/vector.h"
namespace impeller {
@@ -49,6 +51,13 @@ class Canvas {
void DrawPath(Path path, Paint paint);
void DrawImage(std::shared_ptr<Image> image, Point offset, Paint paint);
void DrawImageRect(std::shared_ptr<Image> image,
IRect source,
Rect dest,
Paint paint);
void ClipPath(Path path);
void DrawShadow(Path path, Color color, Scalar elevation);

View File

@@ -6,8 +6,16 @@
namespace impeller {
Image::Image() = default;
Image::Image(std::shared_ptr<Texture> texture) : texture_(std::move(texture)) {}
Image::~Image() = default;
ISize Image::GetSize() const {
return texture_ ? texture_->GetSize() : ISize{};
}
std::shared_ptr<Texture> Image::GetTexture() const {
return texture_;
}
} // namespace impeller

View File

@@ -4,17 +4,26 @@
#pragma once
#include <memory>
#include "flutter/fml/macros.h"
#include "impeller/renderer/texture.h"
namespace impeller {
class Image {
public:
Image();
Image(std::shared_ptr<Texture> texture);
~Image();
ISize GetSize() const;
std::shared_ptr<Texture> GetTexture() const;
private:
const std::shared_ptr<Texture> texture_;
FML_DISALLOW_COPY_AND_ASSIGN(Image);
};

View File

@@ -12,6 +12,8 @@ impeller_shaders("entity_shaders") {
"shaders/gradient_fill.vert",
"shaders/solid_fill.frag",
"shaders/solid_fill.vert",
"shaders/texture_fill.frag",
"shaders/texture_fill.vert",
]
}

View File

@@ -14,6 +14,7 @@ ContentRenderer::ContentRenderer(std::shared_ptr<Context> context)
gradient_fill_pipeline_ = std::make_unique<GradientFillPipeline>(*context_);
solid_fill_pipeline_ = std::make_unique<SolidFillPipeline>(*context_);
texture_pipeline_ = std::make_unique<TexturePipeline>(*context_);
is_valid_ = true;
}
@@ -43,4 +44,12 @@ std::shared_ptr<Pipeline> ContentRenderer::GetSolidFillPipeline() const {
return solid_fill_pipeline_->WaitAndGet();
}
std::shared_ptr<Pipeline> ContentRenderer::GetTexturePipeline() const {
if (!IsValid()) {
return nullptr;
}
return texture_pipeline_->WaitAndGet();
}
} // namespace impeller

View File

@@ -11,6 +11,8 @@
#include "flutter/impeller/entity/gradient_fill.vert.h"
#include "flutter/impeller/entity/solid_fill.frag.h"
#include "flutter/impeller/entity/solid_fill.vert.h"
#include "flutter/impeller/entity/texture_fill.frag.h"
#include "flutter/impeller/entity/texture_fill.vert.h"
#include "impeller/renderer/pipeline.h"
namespace impeller {
@@ -19,6 +21,8 @@ using GradientFillPipeline =
PipelineT<GradientFillVertexShader, GradientFillFragmentShader>;
using SolidFillPipeline =
PipelineT<SolidFillVertexShader, SolidFillFragmentShader>;
using TexturePipeline =
PipelineT<TextureFillVertexShader, TextureFillFragmentShader>;
class ContentRenderer {
public:
@@ -32,12 +36,15 @@ class ContentRenderer {
std::shared_ptr<Pipeline> GetSolidFillPipeline() const;
std::shared_ptr<Pipeline> GetTexturePipeline() const;
std::shared_ptr<Context> GetContext() const;
private:
std::shared_ptr<Context> context_;
std::unique_ptr<GradientFillPipeline> gradient_fill_pipeline_;
std::unique_ptr<SolidFillPipeline> solid_fill_pipeline_;
std::unique_ptr<TexturePipeline> texture_pipeline_;
bool is_valid_ = false;
FML_DISALLOW_COPY_AND_ASSIGN(ContentRenderer);

View File

@@ -9,7 +9,9 @@
#include "flutter/fml/logging.h"
#include "impeller/entity/content_renderer.h"
#include "impeller/entity/entity.h"
#include "impeller/geometry/path_builder.h"
#include "impeller/renderer/render_pass.h"
#include "impeller/renderer/sampler_library.h"
#include "impeller/renderer/surface.h"
#include "impeller/renderer/tessellator.h"
#include "impeller/renderer/vertex_buffer_builder.h"
@@ -135,6 +137,10 @@ bool SolidColorContents::Render(const ContentRenderer& renderer,
}
}
if (!vtx_builder.HasVertices()) {
return true;
}
cmd.BindVertices(vtx_builder.CreateVertexBuffer(
*renderer.GetContext()->GetPermanentsAllocator()));
@@ -171,4 +177,94 @@ const Color& SolidStrokeContents::GetColor() const {
return color_;
}
/*******************************************************************************
******* TextureContents
******************************************************************************/
TextureContents::TextureContents() = default;
TextureContents::~TextureContents() = default;
void TextureContents::SetTexture(std::shared_ptr<Texture> texture) {
texture_ = std::move(texture);
}
std::shared_ptr<Texture> TextureContents::GetTexture() const {
return texture_;
}
bool TextureContents::Render(const ContentRenderer& renderer,
const Entity& entity,
const Surface& surface,
RenderPass& pass) const {
if (texture_ == nullptr) {
return true;
}
using VS = TextureFillVertexShader;
using FS = TextureFillFragmentShader;
const auto coverage_rect = entity.GetPath().GetBoundingBox();
if (coverage_rect.size.IsEmpty()) {
return true;
}
const auto texture_size = texture_->GetSize();
if (texture_size.IsEmpty()) {
return true;
}
if (source_rect_.IsEmpty()) {
return true;
}
VertexBufferBuilder<VS::PerVertexData> vertex_builder;
{
const auto tess_result = Tessellator{}.Tessellate(
entity.GetPath().CreatePolyline(),
[&vertex_builder, &coverage_rect](Point vtx) {
VS::PerVertexData data;
data.vertices = vtx;
data.texture_coords =
((vtx - coverage_rect.origin) / coverage_rect.size);
vertex_builder.AppendVertex(data);
});
if (!tess_result) {
return false;
}
}
if (!vertex_builder.HasVertices()) {
return true;
}
auto& host_buffer = pass.GetTransientsBuffer();
VS::FrameInfo frame_info;
frame_info.mvp =
Matrix::MakeOrthographic(surface.GetSize()) * entity.GetTransformation();
auto frame_info_view = host_buffer.EmplaceUniform(frame_info);
Command cmd;
cmd.label = "TextureFill";
cmd.pipeline = renderer.GetTexturePipeline();
cmd.BindVertices(vertex_builder.CreateVertexBuffer(host_buffer));
VS::BindFrameInfo(cmd, frame_info_view);
FS::BindTextureSampler(
cmd, texture_,
renderer.GetContext()->GetSamplerLibrary()->GetSampler({}));
pass.AddCommand(std::move(cmd));
return true;
}
void TextureContents::SetSourceRect(const IRect& source_rect) {
source_rect_ = source_rect;
}
const IRect& TextureContents::GetSourceRect() const {
return source_rect_;
}
} // namespace impeller

View File

@@ -4,11 +4,14 @@
#pragma once
#include <memory>
#include <vector>
#include "flutter/fml/macros.h"
#include "impeller/geometry/color.h"
#include "impeller/geometry/point.h"
#include "impeller/geometry/rect.h"
#include "impeller/renderer/texture.h"
namespace impeller {
@@ -82,6 +85,33 @@ class SolidColorContents final : public Contents {
FML_DISALLOW_COPY_AND_ASSIGN(SolidColorContents);
};
class TextureContents final : public Contents {
public:
TextureContents();
~TextureContents() override;
void SetTexture(std::shared_ptr<Texture> texture);
std::shared_ptr<Texture> GetTexture() const;
void SetSourceRect(const IRect& source_rect);
const IRect& GetSourceRect() const;
// |Contents|
bool Render(const ContentRenderer& renderer,
const Entity& entity,
const Surface& surface,
RenderPass& pass) const override;
public:
std::shared_ptr<Texture> texture_;
IRect source_rect_;
FML_DISALLOW_COPY_AND_ASSIGN(TextureContents);
};
class SolidStrokeContents final : public Contents {
public:
SolidStrokeContents();

View File

@@ -22,7 +22,7 @@ TEST_F(EntityTest, CanDrawRect) {
Entity entity;
entity.SetPath(PathBuilder{}.AddRect({100, 100, 100, 100}).CreatePath());
entity.SetContents(SolidColorContents::Make(Color::Red()));
ASSERT_TRUE(OpenPlaygroundHere(entity));
// ASSERT_TRUE(OpenPlaygroundHere(entity));
}
} // namespace testing

View File

@@ -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.
uniform sampler2D texture_sampler;
in vec2 v_texture_coords;
out vec4 frag_color;
void main() {
frag_color = texture(texture_sampler, v_texture_coords);
}

View File

@@ -0,0 +1,17 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
uniform FrameInfo {
mat4 mvp;
} frame_info;
in vec2 vertices;
in vec2 texture_coords;
out vec2 v_texture_coords;
void main() {
gl_Position = frame_info.mvp * vec4(vertices, 0.0, 1.0);
v_texture_coords = texture_coords;
}

View File

@@ -2,7 +2,9 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "path.h"
#include "impeller/geometry/path.h"
#include <optional>
namespace impeller {
@@ -172,21 +174,44 @@ std::vector<Point> Path::CreatePolyline(
}
Rect Path::GetBoundingBox() const {
Rect box;
if (linears_.empty() && quads_.empty() && cubics_.empty()) {
return {};
}
std::optional<Point> min, max;
auto clamp = [&min, &max](const std::vector<Point>& extrema) {
for (const auto& extremum : extrema) {
if (!min.has_value()) {
min = extremum;
}
if (!max.has_value()) {
max = extremum;
}
min->x = std::min(min->x, extremum.x);
min->y = std::min(min->y, extremum.y);
max->x = std::max(max->x, extremum.x);
max->y = std::max(max->y, extremum.y);
}
};
for (const auto& linear : linears_) {
box = box.WithPoints(linear.Extrema());
clamp(linear.Extrema());
}
for (const auto& quad : quads_) {
box = box.WithPoints(quad.Extrema());
clamp(quad.Extrema());
}
for (const auto& cubic : cubics_) {
box = box.WithPoints(cubic.Extrema());
clamp(cubic.Extrema());
}
return box;
const auto difference = *max - *min;
return {min->x, min->y, difference.x, difference.y};
}
} // namespace impeller

View File

@@ -27,6 +27,8 @@ struct TPoint {
constexpr TPoint(Type x, Type y) : x(x), y(y) {}
static constexpr TPoint<Type> MakeXY(Type x, Type y) { return {x, y}; }
constexpr bool operator==(const TPoint& p) const {
return p.x == x && p.y == y;
}

View File

@@ -19,7 +19,7 @@ struct TRect {
TPoint<Type> origin;
TSize<Type> size;
constexpr TRect() : origin({0.0, 0.0}), size({0.0, 0.0}) {}
constexpr TRect() : origin({0, 0}), size({0, 0}) {}
constexpr TRect(TSize<Type> size) : origin({0.0, 0.0}), size(size) {}
@@ -40,6 +40,14 @@ struct TRect {
return TRect(left, top, right - left, bottom - top);
}
constexpr static TRect MakeXYWH(Type x, Type y, Type width, Type height) {
return TRect(x, y, width, height);
}
constexpr static TRect MakeSize(const TSize<Type>& size) {
return TRect(0.0, 0.0, size.width, size.height);
}
template <class U>
constexpr explicit TRect(const TRect<U>& other)
: origin(static_cast<TPoint<Type>>(other.origin)),
@@ -76,6 +84,8 @@ struct TRect {
constexpr bool IsZero() const { return size.IsZero(); }
constexpr bool IsEmpty() const { return size.IsEmpty(); }
constexpr TRect WithPoint(const TPoint<Type>& p) const {
TRect copy = *this;
if (p.x < origin.x) {

View File

@@ -73,7 +73,7 @@ struct TSize {
constexpr bool IsPositive() const { return width * height > 0.0; }
constexpr bool IsEmpty() { return !IsPositive(); }
constexpr bool IsEmpty() const { return !IsPositive(); }
constexpr size_t MipCount() const {
if (!IsPositive()) {

View File

@@ -43,8 +43,6 @@ bool Command::BindResource(ShaderStage stage,
}
if (!slot.HasTexture()) {
FML_DLOG(WARNING) << "Texture named " << slot.name
<< " is not actually used in the shader.";
return true;
}
@@ -70,8 +68,6 @@ bool Command::BindResource(ShaderStage stage,
}
if (!slot.HasSampler()) {
FML_DLOG(WARNING) << "Sampler named " << slot.name
<< " is not actually used in the shader.";
return true;
}

View File

@@ -28,15 +28,44 @@ class HostBuffer final : public std::enable_shared_from_this<HostBuffer>,
void SetLabel(std::string label);
template <class T, class = std::enable_if_t<std::is_standard_layout_v<T>>>
[[nodiscard]] BufferView EmplaceUniform(const T& t) {
return Emplace(reinterpret_cast<const void*>(&t), sizeof(T),
std::max(alignof(T), DefaultUniformAlignment()));
//----------------------------------------------------------------------------
/// @brief Emplace uniform data onto the host buffer. Ensure that backend
/// specific uniform alignment requirements are respected.
///
/// @param[in] uniform The uniform struct to emplace onto the buffer.
///
/// @tparam UniformType The type of the uniform struct.
///
/// @return The buffer view.
///
template <class UniformType,
class = std::enable_if_t<std::is_standard_layout_v<UniformType>>>
[[nodiscard]] BufferView EmplaceUniform(const UniformType& uniform) {
const auto alignment =
std::max(alignof(UniformType), DefaultUniformAlignment());
return Emplace(reinterpret_cast<const void*>(&uniform), // buffer
sizeof(UniformType), // size
alignment // alignment
);
}
template <class T, class = std::enable_if_t<std::is_standard_layout_v<T>>>
[[nodiscard]] BufferView Emplace(const T& t) {
return Emplace(reinterpret_cast<const void*>(&t), sizeof(T), alignof(T));
//----------------------------------------------------------------------------
/// @brief Emplace non-uniform data (like contiguous vertices) onto the
/// host buffer.
///
/// @param[in] buffer The buffer data.
///
/// @tparam BufferType The type of the buffer data.
///
/// @return The buffer view.
///
template <class BufferType,
class = std::enable_if_t<std::is_standard_layout_v<BufferType>>>
[[nodiscard]] BufferView Emplace(const BufferType& buffer) {
return Emplace(reinterpret_cast<const void*>(&buffer), // buffer
sizeof(BufferType), // size
alignof(BufferType) // alignment
);
}
[[nodiscard]] BufferView Emplace(const void* buffer,

View File

@@ -33,6 +33,8 @@ class VertexBufferBuilder {
void Reserve(size_t count) { return vertices_.reserve(count); }
bool HasVertices() const { return !vertices_.empty(); }
VertexBufferBuilder& AppendVertex(VertexType_ vertex) {
vertices_.emplace_back(std::move(vertex));
return *this;
@@ -71,13 +73,9 @@ class VertexBufferBuilder {
std::string label_;
BufferView CreateVertexBufferView(HostBuffer& buffer) const {
auto view =
buffer.Emplace(vertices_.data(), vertices_.size() * sizeof(VertexType),
alignof(VertexType));
if (!label_.empty()) {
view.SetLabel(SPrintF("%s Vertices"), label_.c_str());
}
return view;
return buffer.Emplace(vertices_.data(),
vertices_.size() * sizeof(VertexType),
alignof(VertexType));
}
BufferView CreateVertexBufferView(Allocator& allocator) const {
@@ -105,13 +103,9 @@ class VertexBufferBuilder {
BufferView CreateIndexBufferView(HostBuffer& buffer) const {
const auto index_buffer = CreateIndexBuffer();
auto view = buffer.Emplace(index_buffer.data(),
index_buffer.size() * sizeof(IndexType),
alignof(IndexType));
if (!label_.empty()) {
view.SetLabel(SPrintF("%s Indices"), label_);
}
return view;
return buffer.Emplace(index_buffer.data(),
index_buffer.size() * sizeof(IndexType),
alignof(IndexType));
}
BufferView CreateIndexBufferView(Allocator& allocator) const {