Implement stencil-only clips.

This commit is contained in:
Chinmay Garde
2021-11-20 14:39:55 -08:00
committed by Dan Field
parent 6223a79f95
commit 2eb6372d9d
18 changed files with 163 additions and 92 deletions

View File

@@ -70,10 +70,9 @@ TEST_F(AiksTest, DISABLED_CanRenderImageRect) {
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()));
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
TEST_F(AiksTest, CanRenderStrokes) {
@@ -102,9 +101,9 @@ TEST_F(AiksTest, CanRenderClips) {
Paint paint;
paint.color = Color::Fuchsia();
canvas.ClipPath(
PathBuilder{}.AddRect(Rect::MakeXYWH(0, 0, 100, 100)).CreatePath());
canvas.DrawPath(PathBuilder{}.AddCircle({100, 100}, 50).CreatePath(), paint);
// ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
PathBuilder{}.AddRect(Rect::MakeXYWH(0, 0, 500, 500)).CreatePath());
canvas.DrawPath(PathBuilder{}.AddCircle({500, 500}, 250).CreatePath(), paint);
ASSERT_TRUE(OpenPlaygroundHere(canvas.EndRecordingAsPicture()));
}
} // namespace testing

View File

@@ -33,11 +33,12 @@ bool Canvas::Restore() {
}
void Canvas::Concat(const Matrix& xformation) {
xformation_stack_.top() = xformation * xformation_stack_.top();
const auto current_xformation = xformation_stack_.top().xformation;
xformation_stack_.top().xformation = xformation * current_xformation;
}
const Matrix& Canvas::GetCurrentTransformation() const {
return xformation_stack_.top();
return xformation_stack_.top().xformation;
}
void Canvas::Translate(const Vector3& offset) {
@@ -68,6 +69,7 @@ void Canvas::DrawPath(Path path, Paint paint) {
Entity entity;
entity.SetTransformation(GetCurrentTransformation());
entity.SetPath(std::move(path));
entity.SetStencilDepth(GetStencilDepth());
entity.SetContents(paint.CreateContentsForEntity());
GetCurrentPass().PushEntity(std::move(entity));
}
@@ -77,10 +79,13 @@ void Canvas::SaveLayer(const Paint& paint, std::optional<Rect> bounds) {
}
void Canvas::ClipPath(Path path) {
IncrementStencilDepth();
Entity entity;
entity.SetTransformation(GetCurrentTransformation());
entity.SetPath(std::move(path));
entity.SetContents(std::make_shared<ClipContents>());
entity.SetStencilDepth(GetStencilDepth());
GetCurrentPass().PushEntity(std::move(entity));
}
@@ -149,4 +154,12 @@ CanvasPass& Canvas::GetCurrentPass() {
return passes_.back();
}
void Canvas::IncrementStencilDepth() {
++xformation_stack_.top().stencil_depth;
}
size_t Canvas::GetStencilDepth() const {
return xformation_stack_.top().stencil_depth;
}
} // namespace impeller

View File

@@ -23,6 +23,11 @@ namespace impeller {
class Entity;
struct CanvasStackEntry {
Matrix xformation;
size_t stencil_depth = 0u;
};
class Canvas {
public:
Canvas();
@@ -67,11 +72,15 @@ class Canvas {
Picture EndRecordingAsPicture();
private:
std::stack<Matrix> xformation_stack_;
std::stack<CanvasStackEntry> xformation_stack_;
std::vector<CanvasPass> passes_;
CanvasPass& GetCurrentPass();
void IncrementStencilDepth();
size_t GetStencilDepth() const;
FML_DISALLOW_COPY_AND_ASSIGN(Canvas);
};

View File

@@ -526,17 +526,19 @@ std::vector<StructMember> Reflector::ReadStructMembers(
}
}
const auto struct_length = current_byte_offset;
{
const auto excess = struct_length % max_member_alignment;
if (excess != 0) {
const auto padding = max_member_alignment - excess;
result.emplace_back(StructMember{
.type = TypeNameWithPaddingOfSize(padding),
.name = "_PADDING_",
.offset = current_byte_offset,
.byte_length = padding,
});
if (max_member_alignment > 0u) {
const auto struct_length = current_byte_offset;
{
const auto excess = struct_length % max_member_alignment;
if (excess != 0) {
const auto padding = max_member_alignment - excess;
result.emplace_back(StructMember{
.type = TypeNameWithPaddingOfSize(padding),
.name = "_PADDING_",
.offset = current_byte_offset,
.byte_length = padding,
});
}
}
}

View File

@@ -12,11 +12,35 @@ ContentRenderer::ContentRenderer(std::shared_ptr<Context> context)
return;
}
// Pipelines whose default descriptors work fine for the entity framework.
gradient_fill_pipeline_ = std::make_unique<GradientFillPipeline>(*context_);
solid_fill_pipeline_ = std::make_unique<SolidFillPipeline>(*context_);
texture_pipeline_ = std::make_unique<TexturePipeline>(*context_);
solid_stroke_pipeline_ = std::make_unique<SolidStrokePipeline>(*context_);
// Pipelines that are variants of the base pipelines with custom descriptors.
if (auto solid_fill_pipeline = solid_fill_pipeline_->WaitAndGet()) {
auto clip_pipeline_descriptor = solid_fill_pipeline->GetDescriptor();
// Write to the stencil buffer.
StencilAttachmentDescriptor stencil0;
stencil0.stencil_compare = CompareFunction::kGreaterEqual;
stencil0.depth_stencil_pass = StencilOperation::kSetToReferenceValue;
clip_pipeline_descriptor.SetStencilAttachmentDescriptors(stencil0);
// Disable write to all color attachments.
auto color_attachments =
clip_pipeline_descriptor.GetColorAttachmentDescriptors();
for (auto& color_attachment : color_attachments) {
color_attachment.second.write_mask =
static_cast<uint64_t>(ColorWriteMask::kNone);
}
clip_pipeline_descriptor.SetColorAttachmentDescriptors(
std::move(color_attachments));
clip_pipeline_ = std::make_unique<ClipPipeline>(
*context_, std::move(clip_pipeline_descriptor));
} else {
return;
}
is_valid_ = true;
}
@@ -61,4 +85,12 @@ std::shared_ptr<Pipeline> ContentRenderer::GetSolidStrokePipeline() const {
return solid_stroke_pipeline_->WaitAndGet();
}
std::shared_ptr<Pipeline> ContentRenderer::GetClipPipeline() const {
if (!IsValid()) {
return nullptr;
}
return clip_pipeline_->WaitAndGet();
}
} // namespace impeller

View File

@@ -27,6 +27,9 @@ using TexturePipeline =
PipelineT<TextureFillVertexShader, TextureFillFragmentShader>;
using SolidStrokePipeline =
PipelineT<SolidStrokeVertexShader, SolidStrokeFragmentShader>;
// 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<SolidFillVertexShader, SolidFillFragmentShader>;
class ContentRenderer {
public:
@@ -44,6 +47,8 @@ class ContentRenderer {
std::shared_ptr<Pipeline> GetSolidStrokePipeline() const;
std::shared_ptr<Pipeline> GetClipPipeline() const;
std::shared_ptr<Context> GetContext() const;
private:
@@ -52,6 +57,7 @@ class ContentRenderer {
std::unique_ptr<SolidFillPipeline> solid_fill_pipeline_;
std::unique_ptr<TexturePipeline> texture_pipeline_;
std::unique_ptr<SolidStrokePipeline> solid_stroke_pipeline_;
std::unique_ptr<ClipPipeline> clip_pipeline_;
bool is_valid_ = false;
FML_DISALLOW_COPY_AND_ASSIGN(ContentRenderer);

View File

@@ -87,6 +87,7 @@ bool LinearGradientContents::Render(const ContentRenderer& renderer,
Command cmd;
cmd.label = "LinearGradientFill";
cmd.pipeline = renderer.GetGradientFillPipeline();
cmd.stencil_reference = entity.GetStencilDepth();
cmd.BindVertices(vertices_builder.CreateVertexBuffer(
*renderer.GetContext()->GetPermanentsAllocator()));
cmd.primitive_type = PrimitiveType::kTriangle;
@@ -112,6 +113,25 @@ const Color& SolidColorContents::GetColor() const {
return color_;
}
static VertexBuffer CreateSolidFillVertices(const Path& path,
HostBuffer& buffer) {
using VS = SolidFillPipeline::VertexShader;
VertexBufferBuilder<VS::PerVertexData> vtx_builder;
auto tesselation_result = Tessellator{}.Tessellate(
path.CreatePolyline(), [&vtx_builder](auto point) {
VS::PerVertexData vtx;
vtx.vertices = point;
vtx_builder.AppendVertex(vtx);
});
if (!tesselation_result) {
return {};
}
return vtx_builder.CreateVertexBuffer(buffer);
}
bool SolidColorContents::Render(const ContentRenderer& renderer,
const Entity& entity,
const Surface& surface,
@@ -125,29 +145,9 @@ bool SolidColorContents::Render(const ContentRenderer& renderer,
Command cmd;
cmd.label = "SolidFill";
cmd.pipeline = renderer.GetSolidFillPipeline();
if (cmd.pipeline == nullptr) {
return false;
}
VertexBufferBuilder<VS::PerVertexData> vtx_builder;
{
auto tesselation_result = Tessellator{}.Tessellate(
entity.GetPath().CreatePolyline(), [&vtx_builder](auto point) {
VS::PerVertexData vtx;
vtx.vertices = point;
vtx_builder.AppendVertex(vtx);
});
if (!tesselation_result) {
return false;
}
}
if (!vtx_builder.HasVertices()) {
return true;
}
cmd.BindVertices(vtx_builder.CreateVertexBuffer(
*renderer.GetContext()->GetPermanentsAllocator()));
cmd.stencil_reference = entity.GetStencilDepth();
cmd.BindVertices(
CreateSolidFillVertices(entity.GetPath(), pass.GetTransientsBuffer()));
VS::FrameInfo frame_info;
frame_info.mvp =
@@ -240,6 +240,7 @@ bool TextureContents::Render(const ContentRenderer& renderer,
Command cmd;
cmd.label = "TextureFill";
cmd.pipeline = renderer.GetTexturePipeline();
cmd.stencil_reference = entity.GetStencilDepth();
cmd.BindVertices(vertex_builder.CreateVertexBuffer(host_buffer));
VS::BindFrameInfo(cmd, host_buffer.EmplaceUniform(frame_info));
FS::BindTextureSampler(
@@ -335,6 +336,7 @@ bool SolidStrokeContents::Render(const ContentRenderer& renderer,
cmd.primitive_type = PrimitiveType::kTriangleStrip;
cmd.label = "SolidStroke";
cmd.pipeline = renderer.GetSolidStrokePipeline();
cmd.stencil_reference = entity.GetStencilDepth();
cmd.BindVertices(
CreateSolidStrokeVertices(entity.GetPath(), pass.GetTransientsBuffer()));
VS::BindFrameInfo(cmd, pass.GetTransientsBuffer().EmplaceUniform(frame_info));
@@ -366,6 +368,23 @@ bool ClipContents::Render(const ContentRenderer& renderer,
const Entity& entity,
const Surface& surface,
RenderPass& pass) const {
using VS = ClipPipeline::VertexShader;
Command cmd;
cmd.label = "Clip";
cmd.pipeline = renderer.GetClipPipeline();
cmd.stencil_reference = entity.GetStencilDepth() + 1u;
cmd.BindVertices(
CreateSolidFillVertices(entity.GetPath(), pass.GetTransientsBuffer()));
VS::FrameInfo info;
// The color really doesn't matter.
info.color = Color::SkyBlue();
info.mvp = Matrix::MakeOrthographic(surface.GetSize());
VS::BindFrameInfo(cmd, pass.GetTransientsBuffer().EmplaceUniform(info));
pass.AddCommand(std::move(cmd));
return true;
}

View File

@@ -34,4 +34,12 @@ const std::shared_ptr<Contents>& Entity::GetContents() const {
return contents_;
}
void Entity::SetStencilDepth(uint32_t depth) {
stencil_depth_ = depth;
}
uint32_t Entity::GetStencilDepth() const {
return stencil_depth_;
}
} // namespace impeller

View File

@@ -31,10 +31,15 @@ class Entity {
const std::shared_ptr<Contents>& GetContents() const;
void SetStencilDepth(uint32_t stencil_depth);
uint32_t GetStencilDepth() const;
private:
Matrix transformation_;
std::shared_ptr<Contents> contents_;
Path path_;
uint32_t stencil_depth_ = 0u;
};
} // namespace impeller

View File

@@ -172,7 +172,7 @@ bool Playground::OpenPlaygroundHere(Renderer::RenderCallback render_callback) {
stencil0.texture = stencil_texture;
stencil0.clear_stencil = 0;
stencil0.load_action = LoadAction::kClear;
stencil0.store_action = StoreAction::kStore;
stencil0.store_action = StoreAction::kDontCare;
RenderTarget desc;
desc.SetColorAttachment(color0, 0u);

View File

@@ -156,7 +156,7 @@ constexpr MTLStencilOperation ToMTLStencilOperation(StencilOperation op) {
return MTLStencilOperationKeep;
case StencilOperation::kZero:
return MTLStencilOperationZero;
case StencilOperation::kSetToReferneceValue:
case StencilOperation::kSetToReferenceValue:
return MTLStencilOperationReplace;
case StencilOperation::kIncrementClamp:
return MTLStencilOperationIncrementClamp;

View File

@@ -371,6 +371,7 @@ bool RenderPassMTL::EncodeCommands(Allocator& allocator,
? MTLWindingClockwise
: MTLWindingCounterClockwise];
[pass setCullMode:MTLCullModeNone];
[pass setStencilReferenceValue:command.stencil_reference];
if (!bind_stage_resources(command.vertex_bindings, ShaderStage::kVertex)) {
return false;
}

View File

@@ -67,6 +67,7 @@ struct Command {
std::string label;
PrimitiveType primitive_type = PrimitiveType::kTriangle;
WindingOrder winding = WindingOrder::kClockwise;
uint32_t stencil_reference = 0u;
bool BindVertices(const VertexBuffer& buffer);

View File

@@ -241,7 +241,7 @@ enum class StencilOperation {
/// Reset the stencil value to zero.
kZero,
/// Reset the stencil value to the reference value.
kSetToReferneceValue,
kSetToReferenceValue,
/// Increment the current stencil value by 1. Clamp it to the maximum.
kIncrementClamp,
/// Decrement the current stencil value by 1. Clamp it to zero.

View File

@@ -107,7 +107,7 @@ struct PipelineBuilder {
// Setup default stencil buffer descriptions.
{
StencilAttachmentDescriptor stencil0;
stencil0.depth_stencil_pass = StencilOperation::kIncrementClamp;
stencil0.stencil_compare = CompareFunction::kLessEqual;
desc.SetStencilAttachmentDescriptors(stencil0);
desc.SetStencilPixelFormat(PixelFormat::kD32FloatS8UNormInt);
}

View File

@@ -94,6 +94,12 @@ PipelineDescriptor& PipelineDescriptor::SetColorAttachmentDescriptor(
return *this;
}
PipelineDescriptor& PipelineDescriptor::SetColorAttachmentDescriptors(
std::map<size_t /* index */, ColorAttachmentDescriptor> descriptors) {
color_attachment_descriptors_ = std::move(descriptors);
return *this;
}
const ColorAttachmentDescriptor*
PipelineDescriptor::GetColorAttachmentDescriptor(size_t index) const {
auto found = color_attachment_descriptors_.find(index);
@@ -153,7 +159,7 @@ PipelineDescriptor::GetDepthStencilAttachmentDescriptor() const {
return depth_attachment_descriptor_;
}
const std::map<size_t /* index */, ColorAttachmentDescriptor>
const std::map<size_t /* index */, ColorAttachmentDescriptor>&
PipelineDescriptor::GetColorAttachmentDescriptors() const {
return color_attachment_descriptors_;
}

View File

@@ -51,10 +51,13 @@ class PipelineDescriptor final : public Comparable<PipelineDescriptor> {
size_t index,
ColorAttachmentDescriptor desc);
PipelineDescriptor& SetColorAttachmentDescriptors(
std::map<size_t /* index */, ColorAttachmentDescriptor> descriptors);
const ColorAttachmentDescriptor* GetColorAttachmentDescriptor(
size_t index) const;
const std::map<size_t /* index */, ColorAttachmentDescriptor>
const std::map<size_t /* index */, ColorAttachmentDescriptor>&
GetColorAttachmentDescriptors() const;
PipelineDescriptor& SetDepthStencilAttachmentDescriptor(

View File

@@ -172,6 +172,7 @@ TEST_F(RendererTest, CanRenderToTexture) {
using BoxPipelineBuilder = PipelineBuilder<VS, FS>;
auto pipeline_desc =
BoxPipelineBuilder::MakeDefaultPipelineDescriptor(*context);
ASSERT_TRUE(pipeline_desc.has_value());
auto box_pipeline = context->GetPipelineLibrary()
->GetRenderPipeline(std::move(pipeline_desc))
.get();
@@ -220,8 +221,18 @@ TEST_F(RendererTest, CanRenderToTexture) {
color0.texture->SetLabel("r2t_target");
StencilAttachment stencil0;
stencil0.load_action = LoadAction::kClear;
stencil0.store_action = StoreAction::kDontCare;
TextureDescriptor stencil_texture_desc;
stencil_texture_desc.size = texture_descriptor.size;
stencil_texture_desc.format = PixelFormat::kD32FloatS8UNormInt;
stencil0.texture = context->GetPermanentsAllocator()->CreateTexture(
StorageMode::kDeviceTransient, stencil_texture_desc);
RenderTarget r2t_desc;
r2t_desc.SetColorAttachment(color0, 0u);
r2t_desc.SetStencilAttachment(stencil0);
auto cmd_buffer = context->CreateRenderCommandBuffer();
r2t_pass = cmd_buffer->CreateRenderPass(r2t_desc);
ASSERT_TRUE(r2t_pass && r2t_pass->IsValid());
@@ -325,49 +336,5 @@ TEST_F(RendererTest, CanRenderPath) {
// OpenPlaygroundHere(callback);
}
TEST_F(RendererTest, CanPerformStencilOperations) {
using VS = TestTextureVertexShader;
using FS = TestTextureFragmentShader;
using TestTextureCommand = CommandT<VS, FS>;
auto pipeline = std::make_unique<TestTextureCommand::Pipeline>(*GetContext());
auto buffer = HostBuffer::Create();
auto circle_vtx_builder = TestTextureCommand::CreateVertexBuilder();
Tessellator{}.Tessellate(
PathBuilder{}.AddCircle({500, 500}, 250).CreatePath().CreatePolyline(),
[&circle_vtx_builder](Point vtx) {
VS::PerVertexData data;
data.vtx = vtx;
circle_vtx_builder.AppendVertex(data);
});
auto cicle_vertices = circle_vtx_builder.CreateVertexBuffer(*buffer);
auto square_vtx_builder = TestTextureCommand::CreateVertexBuilder();
Tessellator{}.Tessellate(
PathBuilder{}.AddRect({0, 0, 250, 250}).CreatePath().CreatePolyline(),
[&square_vtx_builder](Point vtx) {
VS::PerVertexData data;
data.vtx = vtx;
square_vtx_builder.AppendVertex(data);
});
auto square_vertices = square_vtx_builder.CreateVertexBuffer(*buffer);
OpenPlaygroundHere([&](const Surface& surface, RenderPass& pass) -> bool {
TestTextureCommand command(*pipeline.get());
command.BindVerticesDynamic(cicle_vertices);
VS::FrameInfo info;
info.mvp = Matrix::MakeOrthographic(surface.GetSize());
VS::BindFrameInfo(command, pass.GetTransientsBuffer().EmplaceUniform(info));
pass.AddCommand(command);
return true;
});
}
} // namespace testing
} // namespace impeller