A pipeline builder utility to create pipeline state objects from reflected shader information.

This commit is contained in:
Chinmay Garde
2021-07-03 00:57:56 -07:00
committed by Dan Field
parent d828e0b1db
commit 61dad3b194
24 changed files with 146 additions and 779 deletions

View File

@@ -13,7 +13,6 @@ group("impeller") {
"compositor",
"entity",
"geometry",
"host",
"image",
"primitives",
"shader_glue",

View File

@@ -16,9 +16,8 @@ constexpr std::string_view kReflectionHeaderTemplate =
#include "shader_types.h"
namespace impeller {
namespace shader {
struct {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Info {
struct {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Shader {
// ===========================================================================
// Stage Info ================================================================
// ===========================================================================
@@ -116,10 +115,9 @@ struct {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Info {
};
{% endif %}
}; // struct {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Info
}; // struct {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Shader
} // namespace shader
} // namespace impeller
} // namespace impeller
)~~";
constexpr std::string_view kReflectionCCTemplate =
@@ -131,22 +129,19 @@ constexpr std::string_view kReflectionCCTemplate =
#include <type_traits>
namespace impeller {
namespace shader {
using Info = {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Info;
using Shader = {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Shader;
{% for def in struct_definitions %}
// Sanity checks for {{def.name}}
static_assert(std::is_standard_layout_v<Info::{{def.name}}>);
static_assert(sizeof(Info::{{def.name}}) == {{def.byte_length}});
static_assert(std::is_standard_layout_v<Shader::{{def.name}}>);
static_assert(sizeof(Shader::{{def.name}}) == {{def.byte_length}});
{% for member in def.members %}
static_assert(offsetof(Info::{{def.name}}, {{member.name}}) == {{member.offset}});
static_assert(offsetof(Shader::{{def.name}}, {{member.name}}) == {{member.offset}});
{% endfor %}
{% endfor %}
} // namespace shader
} // namespace impeller
} // namespace impeller
)~~";
} // namespace compiler

View File

@@ -30,6 +30,8 @@ impeller_component("compositor") {
"host_buffer.mm",
"pipeline.h",
"pipeline.mm",
"pipeline_builder.h",
"pipeline_builder.mm",
"pipeline_descriptor.h",
"pipeline_descriptor.mm",
"pipeline_library.h",

View File

@@ -0,0 +1,107 @@
// 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/logging.h"
#include "flutter/fml/macros.h"
#include "impeller/compositor/context.h"
#include "impeller/compositor/pipeline_descriptor.h"
#include "impeller/compositor/shader_library.h"
#include "impeller/compositor/vertex_descriptor.h"
namespace impeller {
//------------------------------------------------------------------------------
/// @brief A utility for creating pipelines from reflected shader
/// information.
///
/// @tparam VertexShader_ The reflected vertex shader information. Found
/// in a generated header file called
/// <shader_name>.vert.h.
/// @tparam FragmentShader_ The reflected fragment shader information.
/// Found in a generated header file called
/// <shader_name>.frag.h.
///
template <class VertexShader_, class FragmentShader_>
struct PipelineBuilder {
public:
using VertexShader = VertexShader_;
using FragmentShader = FragmentShader_;
static constexpr size_t kVertexBufferIndex =
VertexDescriptor::kReservedVertexBufferIndex;
//----------------------------------------------------------------------------
/// @brief Create a default pipeline descriptor using the combination
/// reflected shader information. The descriptor can be configured
/// further before a pipline state object is created using it.
///
/// @param[in] context The context
///
/// @return If the combination of reflected shader information is
/// compatible and the requisite functions can be found in the
/// context, a pipeine descriptor.
///
static std::optional<PipelineDescriptor> MakeDefaultPipelineDescriptor(
const Context& context) {
PipelineDescriptor desc;
// Setup debug instrumentation.
desc.SetLabel(SPrintF("%s Pipeline", VertexShader::kLabel.data()));
// Resolve pipeline entrypoints.
{
auto vertex_function = context.GetShaderLibrary()->GetFunction(
VertexShader::kEntrypointName, ShaderStage::kVertex);
auto fragment_function = context.GetShaderLibrary()->GetFunction(
FragmentShader::kEntrypointName, ShaderStage::kFragment);
if (!vertex_function || !fragment_function) {
FML_LOG(ERROR) << "Could not resolve pipeline entrypoint(s).";
return std::nullopt;
}
desc.AddStageEntrypoint(std::move(vertex_function));
desc.AddStageEntrypoint(std::move(fragment_function));
}
// Setup the vertex descriptor from reflected information.
{
auto vertex_descriptor = std::make_shared<VertexDescriptor>();
if (!vertex_descriptor->SetStageInputs(
VertexShader::kAllShaderStageInputs)) {
FML_LOG(ERROR) << "Could not configure vertex descriptor.";
return std::nullopt;
}
desc.SetVertexDescriptor(std::move(vertex_descriptor));
}
// Setup fragment shader output descriptions.
{
// Configure the sole color attachments pixel format.
// TODO(csg): This can be easily reflected but we are sticking to the
// convention that the first stage output is the color output.
ColorAttachmentDescriptor color0;
color0.format = PixelFormat::kPixelFormat_B8G8R8A8_UNormInt_SRGB;
desc.SetColorAttachmentDescriptor(0u, std::move(color0));
}
// Setup depth and stencil attachment descriptions.
{
// Configure the stencil attachment.
// TODO(csg): Make this configurable if possible as the D32 component is
// wasted. This can even be moved out of the "default" descriptor
// construction as a case can be made that this is caller responsibility.
const auto combined_depth_stencil_format =
PixelFormat::kPixelFormat_D32_Float_S8_UNormInt;
desc.SetDepthPixelFormat(combined_depth_stencil_format);
desc.SetStencilPixelFormat(combined_depth_stencil_format);
}
return desc;
}
};
} // namespace impeller

View File

@@ -2,10 +2,10 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "impeller/compositor/pipeline_builder.h"
namespace impeller {
std::string GetAssetLocation(const char* asset_path);
//
} // namespace impeller
} // namespace impeller

View File

@@ -24,7 +24,7 @@ namespace impeller {
class ShaderFunction;
class VertexDescriptor;
class PipelineDescriptor : public Comparable<PipelineDescriptor> {
class PipelineDescriptor final : public Comparable<PipelineDescriptor> {
public:
PipelineDescriptor();

View File

@@ -16,6 +16,9 @@ namespace impeller {
class VertexDescriptor final : public Comparable<VertexDescriptor> {
public:
static constexpr size_t kReservedVertexBufferIndex =
30u; // The final slot available. Regular buffer indices go up from 0.
VertexDescriptor();
virtual ~VertexDescriptor();
@@ -31,8 +34,6 @@ class VertexDescriptor final : public Comparable<VertexDescriptor> {
MTLVertexDescriptor* GetMTLVertexDescriptor() const;
size_t GetVertexBufferIndex() const;
//| Comparable<VertexDescriptor>|
std::size_t GetHash() const override;

View File

@@ -188,16 +188,10 @@ bool VertexDescriptor::SetStageInputs(
return true;
}
size_t VertexDescriptor::GetVertexBufferIndex() const {
static constexpr size_t kReservedVertexBufferIndex =
30u; // The final slot available.
return kReservedVertexBufferIndex;
}
MTLVertexDescriptor* VertexDescriptor::GetMTLVertexDescriptor() const {
auto descriptor = [MTLVertexDescriptor vertexDescriptor];
const size_t vertex_buffer_index = GetVertexBufferIndex();
const size_t vertex_buffer_index = kReservedVertexBufferIndex;
size_t stride = 0u;
for (const auto& input : stage_inputs_) {

View File

@@ -24,5 +24,8 @@ impeller_component("entity_unittests") {
sources = [ "entity_unittests.mm" ]
deps = [ "../playground" ]
deps = [
":entity",
"../playground",
]
}

View File

@@ -30,7 +30,7 @@ EntityRenderer::EntityRenderer(std::string shaders_directory)
return;
}
VertexBufferBuilder<shader::BoxVertexInfo::PerVertexData> vertex_builder;
VertexBufferBuilder<BoxVertexShader::PerVertexData> vertex_builder;
vertex_builder.SetLabel("Box");
vertex_builder.AddVertices({
{{100, 100, 0.0}, {Color::Red()}, {0.0, 0.0}}, // 1
@@ -61,30 +61,23 @@ bool EntityRenderer::OnIsValid() const {
bool EntityRenderer::OnRender(const Surface& surface, RenderPass& pass) {
pass.SetLabel("EntityRenderer Render Pass");
shader::BoxVertexInfo::UniformBuffer uniforms;
BoxVertexShader::UniformBuffer uniforms;
uniforms.mvp = Matrix::MakeOrthographic(surface.GetSize());
Command cmd;
cmd.label = "Box";
cmd.pipeline = box_primitive_->GetPipeline();
cmd.vertex_bindings.buffers[box_primitive_->GetVertexBufferIndex()] =
vertex_buffer_.vertex_buffer;
cmd.vertex_bindings
.buffers[shader::BoxVertexInfo::kUniformUniformBuffer.binding] =
cmd.vertex_bindings.buffers[BoxVertexShader::kUniformUniformBuffer.binding] =
pass.GetTransientsBuffer().EmplaceUniform(uniforms);
cmd.fragment_bindings
.samplers[shader::BoxFragmentInfo::kInputContents1.binding] =
cmd.fragment_bindings.samplers[BoxFragmentShader::kInputContents1.binding] =
GetContext()->GetSamplerLibrary()->GetSampler({});
cmd.fragment_bindings
.samplers[shader::BoxFragmentInfo::kInputContents2.binding] =
cmd.fragment_bindings.samplers[BoxFragmentShader::kInputContents2.binding] =
GetContext()->GetSamplerLibrary()->GetSampler({});
cmd.fragment_bindings
.samplers[shader::BoxFragmentInfo::kInputContents3.binding] =
cmd.fragment_bindings.samplers[BoxFragmentShader::kInputContents3.binding] =
GetContext()->GetSamplerLibrary()->GetSampler({});
cmd.index_buffer = vertex_buffer_.index_buffer;
cmd.index_count = vertex_buffer_.index_count;
cmd.primitive_type = PrimitiveType::kTriange;

View File

@@ -1,53 +0,0 @@
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//flutter/impeller/tools/impeller.gni")
import("//flutter/testing/testing.gni")
metal_library("impeller_host_shaders") {
name = "impeller_host"
sources = [ "shaders.metal" ]
}
test_fixtures("impeller_host_fixtures") {
fixtures = [ "assets/ColorMap.png" ]
}
executable("host") {
cflags_objc = flutter_cflags_objc_arc
cflags_objcc = flutter_cflags_objcc_arc
cflags_objcc += [ "-Wno-auto-var-id" ]
output_name = "impeller"
sources = [
"ShaderTypes.h",
"assets_location.cc",
"assets_location.h",
"impeller_host_view_controller.h",
"impeller_host_view_controller.mm",
"impeller_renderer.h",
"impeller_renderer.mm",
"main.mm",
"shaders_location.cc",
"shaders_location.h",
]
libs = [
"AppKit.framework",
"Metal.framework",
"MetalKit.framework",
"QuartzCore.framework",
"ModelIO.framework",
]
deps = [
":impeller_host_fixtures",
":impeller_host_shaders",
"../entity",
"../primitives",
"//flutter/fml",
]
}

View File

@@ -1,39 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ShaderTypes_h
#define ShaderTypes_h
#ifdef __METAL_VERSION__
#define NS_ENUM(_type, _name) \
enum _name : _type _name; \
enum _name : _type
#define NSInteger metal::int32_t
#else
#import <Foundation/Foundation.h>
#endif
#include <simd/simd.h>
typedef NS_ENUM(NSInteger, BufferIndex) {
BufferIndexMeshPositions = 0,
BufferIndexMeshGenerics = 1,
BufferIndexUniforms = 2
};
typedef NS_ENUM(NSInteger, VertexAttribute) {
VertexAttributePosition = 0,
VertexAttributeTexcoord = 1,
};
typedef NS_ENUM(NSInteger, TextureIndex) {
TextureIndexColor = 0,
};
typedef struct {
matrix_float4x4 projectionMatrix;
matrix_float4x4 modelViewMatrix;
} Uniforms;
#endif /* ShaderTypes_h */

View File

@@ -1,50 +0,0 @@
// 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.
// File for Metal kernel and shader functions
#include <metal_stdlib>
#include <simd/simd.h>
// Including header shared between this Metal shader code and Swift/C code executing Metal API commands
#import "ShaderTypes.h"
using namespace metal;
typedef struct
{
float3 position [[attribute(VertexAttributePosition)]];
float2 texCoord [[attribute(VertexAttributeTexcoord)]];
} Vertex;
typedef struct
{
float4 position [[position]];
float2 texCoord;
} ColorInOut;
vertex ColorInOut vertexShader(Vertex in [[stage_in]],
constant Uniforms & uniforms [[ buffer(BufferIndexUniforms) ]])
{
ColorInOut out;
float4 position = float4(in.position, 1.0);
out.position = uniforms.projectionMatrix * uniforms.modelViewMatrix * position;
out.texCoord = in.texCoord;
return out;
}
fragment float4 fragmentShader(ColorInOut in [[stage_in]],
constant Uniforms & uniforms [[ buffer(BufferIndexUniforms) ]],
texture2d<half> colorMap [[ texture(TextureIndexColor) ]])
{
constexpr sampler colorSampler(mip_filter::linear,
mag_filter::linear,
min_filter::linear);
half4 colorSample = colorMap.sample(colorSampler, in.texCoord.xy);
return float4(colorSample);
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

View File

@@ -1,31 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/impeller/host/assets_location.h"
#include "flutter/fml/paths.h"
namespace flutter::testing {
//------------------------------------------------------------------------------
/// @brief Returns the directory containing the test fixture for the target
/// if this target has fixtures configured. If there are no
/// fixtures, this is a link error. If you see a linker error on
/// this symbol, the unit-test target needs to depend on a
/// `test_fixtures` target.
///
/// @return The fixtures path.
///
const char* GetFixturesPath();
} // namespace flutter::testing
namespace impeller {
std::string GetAssetLocation(const char* asset_path) {
return fml::paths::JoinPaths(
{flutter::testing::GetFixturesPath(), std::string{asset_path}});
}
} // namespace impeller

View File

@@ -1,12 +0,0 @@
// 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 <Cocoa/Cocoa.h>
#import <Metal/Metal.h>
#import <MetalKit/MetalKit.h>
#import "impeller_renderer.h"
@interface ImpellerHostViewController : NSViewController
@end

View File

@@ -1,35 +0,0 @@
// 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 "impeller_host_view_controller.h"
#import "impeller_renderer.h"
@implementation ImpellerHostViewController {
MTKView* view_;
ImpellerRenderer* renderer_;
}
- (void)loadView {
view_ = [[MTKView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600)];
view_.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
self.view = view_;
}
- (void)viewDidLoad {
[super viewDidLoad];
view_.device = MTLCreateSystemDefaultDevice();
if (!view_.device) {
NSLog(@"Metal is not supported on this device");
self.view = [[NSView alloc] initWithFrame:self.view.frame];
return;
}
renderer_ = [[ImpellerRenderer alloc] initWithMetalKitView:view_];
[renderer_ mtkView:view_ drawableSizeWillChange:view_.bounds.size];
view_.delegate = renderer_;
}
@end

View File

@@ -1,11 +0,0 @@
// 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 <MetalKit/MetalKit.h>
@interface ImpellerRenderer : NSObject <MTKViewDelegate>
- (nonnull instancetype)initWithMetalKitView:(nonnull MTKView*)view;
@end

View File

@@ -1,353 +0,0 @@
// 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 <ModelIO/ModelIO.h>
#import <simd/simd.h>
#import "ShaderTypes.h"
#include "assets_location.h"
#include "flutter/fml/logging.h"
#include "impeller/compositor/formats_metal.h"
#include "impeller/compositor/surface.h"
#include "impeller/entity/entity_renderer.h"
#include "impeller/primitives/box_primitive.h"
#include "impeller_renderer.h"
#include "shaders_location.h"
static const NSUInteger kMaxBuffersInFlight = 3;
static const size_t kAlignedUniformsSize = (sizeof(Uniforms) & ~0xFF) + 0x100;
@implementation ImpellerRenderer {
dispatch_semaphore_t _inFlightSemaphore;
id<MTLDevice> _device;
id<MTLCommandQueue> _commandQueue;
id<MTLBuffer> _dynamicUniformBuffer;
id<MTLRenderPipelineState> _pipelineState;
id<MTLDepthStencilState> _depthState;
id<MTLTexture> _colorMap;
MTLVertexDescriptor* _mtlVertexDescriptor;
uint32_t _uniformBufferOffset;
uint8_t _uniformBufferIndex;
void* _uniformBufferAddress;
matrix_float4x4 _projectionMatrix;
float _rotation;
MTKMesh* _mesh;
std::unique_ptr<impeller::Renderer> renderer_;
}
- (nonnull instancetype)initWithMetalKitView:(nonnull MTKView*)view {
self = [super init];
if (self) {
_device = view.device;
_inFlightSemaphore = dispatch_semaphore_create(kMaxBuffersInFlight);
[self _loadMetalWithView:view];
[self _loadAssets];
}
renderer_ = std::make_unique<impeller::EntityRenderer>(
impeller::ImpellerShadersDirectory());
FML_CHECK(renderer_->IsValid()) << "Impeller Renderer is not valid.";
return self;
}
- (void)_loadMetalWithView:(nonnull MTKView*)view {
/// Load Metal state objects and initialize renderer dependent view properties
view.depthStencilPixelFormat = MTLPixelFormatDepth32Float_Stencil8;
view.colorPixelFormat = MTLPixelFormatBGRA8Unorm_sRGB;
view.sampleCount = 1;
_mtlVertexDescriptor = [[MTLVertexDescriptor alloc] init];
_mtlVertexDescriptor.attributes[VertexAttributePosition].format =
MTLVertexFormatFloat3;
_mtlVertexDescriptor.attributes[VertexAttributePosition].offset = 0;
_mtlVertexDescriptor.attributes[VertexAttributePosition].bufferIndex =
BufferIndexMeshPositions;
_mtlVertexDescriptor.attributes[VertexAttributeTexcoord].format =
MTLVertexFormatFloat2;
_mtlVertexDescriptor.attributes[VertexAttributeTexcoord].offset = 0;
_mtlVertexDescriptor.attributes[VertexAttributeTexcoord].bufferIndex =
BufferIndexMeshGenerics;
_mtlVertexDescriptor.layouts[BufferIndexMeshPositions].stride = 12;
_mtlVertexDescriptor.layouts[BufferIndexMeshPositions].stepRate = 1;
_mtlVertexDescriptor.layouts[BufferIndexMeshPositions].stepFunction =
MTLVertexStepFunctionPerVertex;
_mtlVertexDescriptor.layouts[BufferIndexMeshGenerics].stride = 8;
_mtlVertexDescriptor.layouts[BufferIndexMeshGenerics].stepRate = 1;
_mtlVertexDescriptor.layouts[BufferIndexMeshGenerics].stepFunction =
MTLVertexStepFunctionPerVertex;
auto shader_library_path =
impeller::ImpellerShadersLocation("impeller_host.metallib");
FML_CHECK(shader_library_path.has_value());
NSError* shader_library_error = nil;
id<MTLLibrary> defaultLibrary =
[_device newLibraryWithFile:@(shader_library_path.value().c_str())
error:&shader_library_error];
id<MTLFunction> vertexFunction =
[defaultLibrary newFunctionWithName:@"vertexShader"];
id<MTLFunction> fragmentFunction =
[defaultLibrary newFunctionWithName:@"fragmentShader"];
MTLRenderPipelineDescriptor* pipelineStateDescriptor =
[[MTLRenderPipelineDescriptor alloc] init];
pipelineStateDescriptor.label = @"MyPipeline";
pipelineStateDescriptor.sampleCount = view.sampleCount;
pipelineStateDescriptor.vertexFunction = vertexFunction;
pipelineStateDescriptor.fragmentFunction = fragmentFunction;
pipelineStateDescriptor.vertexDescriptor = _mtlVertexDescriptor;
pipelineStateDescriptor.colorAttachments[0].pixelFormat =
view.colorPixelFormat;
pipelineStateDescriptor.depthAttachmentPixelFormat =
view.depthStencilPixelFormat;
pipelineStateDescriptor.stencilAttachmentPixelFormat =
view.depthStencilPixelFormat;
NSError* error = NULL;
_pipelineState =
[_device newRenderPipelineStateWithDescriptor:pipelineStateDescriptor
error:&error];
if (!_pipelineState) {
NSLog(@"Failed to created pipeline state, error %@", error);
}
MTLDepthStencilDescriptor* depthStateDesc =
[[MTLDepthStencilDescriptor alloc] init];
depthStateDesc.depthCompareFunction = MTLCompareFunctionLess;
depthStateDesc.depthWriteEnabled = YES;
_depthState = [_device newDepthStencilStateWithDescriptor:depthStateDesc];
NSUInteger uniformBufferSize = kAlignedUniformsSize * kMaxBuffersInFlight;
_dynamicUniformBuffer =
[_device newBufferWithLength:uniformBufferSize
options:MTLResourceStorageModeShared];
_dynamicUniformBuffer.label = @"UniformBuffer";
_commandQueue = [_device newCommandQueue];
}
- (void)_loadAssets {
/// Load assets into metal objects
NSError* error;
MTKMeshBufferAllocator* metalAllocator =
[[MTKMeshBufferAllocator alloc] initWithDevice:_device];
MDLMesh* mdlMesh = [MDLMesh newBoxWithDimensions:(vector_float3){4, 4, 4}
segments:(vector_uint3){2, 2, 2}
geometryType:MDLGeometryTypeTriangles
inwardNormals:NO
allocator:metalAllocator];
MDLVertexDescriptor* mdlVertexDescriptor =
MTKModelIOVertexDescriptorFromMetal(_mtlVertexDescriptor);
mdlVertexDescriptor.attributes[VertexAttributePosition].name =
MDLVertexAttributePosition;
mdlVertexDescriptor.attributes[VertexAttributeTexcoord].name =
MDLVertexAttributeTextureCoordinate;
mdlMesh.vertexDescriptor = mdlVertexDescriptor;
_mesh = [[MTKMesh alloc] initWithMesh:mdlMesh device:_device error:&error];
if (!_mesh || error) {
NSLog(@"Error creating MetalKit mesh %@", error.localizedDescription);
}
MTKTextureLoader* textureLoader =
[[MTKTextureLoader alloc] initWithDevice:_device];
NSDictionary* textureLoaderOptions = @{
MTKTextureLoaderOptionTextureUsage : @(MTLTextureUsageShaderRead),
MTKTextureLoaderOptionTextureStorageMode : @(MTLStorageModePrivate)
};
auto color_map_data = [NSData
dataWithContentsOfFile:@(impeller::GetAssetLocation("ColorMap.png")
.c_str())];
_colorMap = [textureLoader newTextureWithData:color_map_data
options:textureLoaderOptions
error:&error];
if (!_colorMap || error) {
NSLog(@"Error creating texture %@", error.localizedDescription);
}
}
- (void)_updateDynamicBufferState {
/// Update the state of our uniform buffers before rendering
_uniformBufferIndex = (_uniformBufferIndex + 1) % kMaxBuffersInFlight;
_uniformBufferOffset = kAlignedUniformsSize * _uniformBufferIndex;
_uniformBufferAddress =
((uint8_t*)_dynamicUniformBuffer.contents) + _uniformBufferOffset;
}
- (void)_updateGameState {
/// Update any game state before encoding renderint commands to our drawable
Uniforms* uniforms = (Uniforms*)_uniformBufferAddress;
uniforms->projectionMatrix = _projectionMatrix;
vector_float3 rotationAxis = {1, 1, 0};
matrix_float4x4 modelMatrix = matrix4x4_rotation(_rotation, rotationAxis);
matrix_float4x4 viewMatrix = matrix4x4_translation(0.0, 0.0, -8.0);
uniforms->modelViewMatrix = matrix_multiply(viewMatrix, modelMatrix);
_rotation += .01;
}
- (void)drawInMTKView:(nonnull MTKView*)view {
impeller::Surface surface(
impeller::FromMTLRenderPassDescriptor(view.currentRenderPassDescriptor),
[drawable = view.currentDrawable]() {
[drawable present];
return true;
});
if (!renderer_->Render(surface)) {
FML_LOG(ERROR) << "Could not render.";
}
return;
/// Per frame updates here
dispatch_semaphore_wait(_inFlightSemaphore, DISPATCH_TIME_FOREVER);
id<MTLCommandBuffer> commandBuffer = [_commandQueue commandBuffer];
commandBuffer.label = @"MyCommand";
__block dispatch_semaphore_t block_sema = _inFlightSemaphore;
[commandBuffer addCompletedHandler:^(id<MTLCommandBuffer> buffer) {
dispatch_semaphore_signal(block_sema);
}];
[self _updateDynamicBufferState];
[self _updateGameState];
/// Delay getting the currentRenderPassDescriptor until we absolutely need it
/// to avoid holding onto the drawable and blocking the display pipeline any
/// longer than necessary
MTLRenderPassDescriptor* renderPassDescriptor =
view.currentRenderPassDescriptor;
if (renderPassDescriptor != nil) {
/// Final pass rendering code here
id<MTLRenderCommandEncoder> renderEncoder =
[commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor];
renderEncoder.label = @"MyRenderEncoder";
[renderEncoder pushDebugGroup:@"DrawBox"];
[renderEncoder setFrontFacingWinding:MTLWindingCounterClockwise];
[renderEncoder setCullMode:MTLCullModeBack];
[renderEncoder setRenderPipelineState:_pipelineState];
[renderEncoder setDepthStencilState:_depthState];
[renderEncoder setVertexBuffer:_dynamicUniformBuffer
offset:_uniformBufferOffset
atIndex:BufferIndexUniforms];
[renderEncoder setFragmentBuffer:_dynamicUniformBuffer
offset:_uniformBufferOffset
atIndex:BufferIndexUniforms];
for (NSUInteger bufferIndex = 0; bufferIndex < _mesh.vertexBuffers.count;
bufferIndex++) {
MTKMeshBuffer* vertexBuffer = _mesh.vertexBuffers[bufferIndex];
if ((NSNull*)vertexBuffer != [NSNull null]) {
[renderEncoder setVertexBuffer:vertexBuffer.buffer
offset:vertexBuffer.offset
atIndex:bufferIndex];
}
}
[renderEncoder setFragmentTexture:_colorMap atIndex:TextureIndexColor];
for (MTKSubmesh* submesh in _mesh.submeshes) {
[renderEncoder drawIndexedPrimitives:submesh.primitiveType
indexCount:submesh.indexCount
indexType:submesh.indexType
indexBuffer:submesh.indexBuffer.buffer
indexBufferOffset:submesh.indexBuffer.offset];
}
[renderEncoder popDebugGroup];
[renderEncoder endEncoding];
[commandBuffer presentDrawable:view.currentDrawable];
}
[commandBuffer commit];
}
- (void)mtkView:(nonnull MTKView*)view drawableSizeWillChange:(CGSize)size {
float aspect = size.width / (float)size.height;
_projectionMatrix = matrix_perspective_right_hand(65.0f * (M_PI / 180.0f),
aspect, 0.1f, 100.0f);
}
#pragma mark Matrix Math Utilities
// NOLINTNEXTLINE
matrix_float4x4 matrix4x4_translation(float tx, float ty, float tz) {
return (matrix_float4x4){
{{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {tx, ty, tz, 1}}};
}
// NOLINTNEXTLINE
static matrix_float4x4 matrix4x4_rotation(float radians, vector_float3 axis) {
axis = vector_normalize(axis);
float ct = cosf(radians);
float st = sinf(radians);
float ci = 1 - ct;
float x = axis.x, y = axis.y, z = axis.z;
return (matrix_float4x4){
{{ct + x * x * ci, y * x * ci + z * st, z * x * ci - y * st, 0},
{x * y * ci - z * st, ct + y * y * ci, z * y * ci + x * st, 0},
{x * z * ci + y * st, y * z * ci - x * st, ct + z * z * ci, 0},
{0, 0, 0, 1}}};
}
// NOLINTNEXTLINE
matrix_float4x4 matrix_perspective_right_hand(float fovyRadians,
float aspect,
float nearZ,
float farZ) {
float ys = 1 / tanf(fovyRadians * 0.5);
float xs = ys / aspect;
float zs = farZ / (nearZ - farZ);
return (matrix_float4x4){
{{xs, 0, 0, 0}, {0, ys, 0, 0}, {0, 0, zs, -1}, {0, 0, nearZ * zs, 0}}};
}
@end

View File

@@ -1,62 +0,0 @@
// 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 <Cocoa/Cocoa.h>
#include "impeller_host_view_controller.h"
@interface ImpellerAppDelegate
: NSObject <NSApplicationDelegate, NSWindowDelegate> {
NSWindow* window_;
ImpellerHostViewController* view_controller_;
}
@end
@implementation ImpellerAppDelegate : NSObject
- (id)init {
if (self = [super init]) {
view_controller_ = [[ImpellerHostViewController alloc] init];
window_ = [[NSWindow alloc]
initWithContentRect:NSMakeRect(200, 200, 800, 600)
styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable
backing:NSBackingStoreBuffered
defer:NO];
window_.styleMask |= NSWindowStyleMaskResizable;
[window_ setContentViewController:view_controller_];
}
return self;
}
- (void)applicationDidFinishLaunching:(NSNotification*)notification {
[window_ setTitle:@"Impeller Host"];
[window_ makeKeyAndOrderFront:self];
}
- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication*)sender {
return YES;
}
@end
int main(int argc, const char* argv[]) {
NSApplication* app = [NSApplication sharedApplication];
[app setActivationPolicy:NSApplicationActivationPolicyRegular];
NSMenuItem* item = [[NSMenuItem alloc] init];
app.mainMenu = [[NSMenu alloc] init];
item.submenu = [[NSMenu alloc] init];
[app.mainMenu addItem:item];
[item.submenu
addItem:[[NSMenuItem alloc]
initWithTitle:[@"Quit "
stringByAppendingString:[NSProcessInfo
processInfo]
.processName]
action:@selector(terminate:)
keyEquivalent:@"q"]];
ImpellerAppDelegate* appDelegate = [[ImpellerAppDelegate alloc] init];
[app setDelegate:appDelegate];
[app run];
return 0;
}

View File

@@ -1,31 +0,0 @@
// 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 "shaders_location.h"
#include "flutter/fml/file.h"
#include "flutter/fml/paths.h"
namespace impeller {
std::string ImpellerShadersDirectory() {
auto path_result = fml::paths::GetExecutableDirectoryPath();
if (!path_result.first) {
return {};
}
return fml::paths::JoinPaths({path_result.second, "shaders"});
}
std::optional<std::string> ImpellerShadersLocation(std::string library_name) {
auto path = fml::paths::JoinPaths({ImpellerShadersDirectory(), library_name});
if (!fml::IsFile(path)) {
FML_LOG(ERROR) << "The shader library does not exist: " << path;
return std::nullopt;
}
return path;
}
} // namespace impeller

View File

@@ -1,14 +0,0 @@
// 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 <optional>
#include <string>
namespace impeller {
std::string ImpellerShadersDirectory();
std::optional<std::string> ImpellerShadersLocation(std::string library_name);
} // namespace impeller

View File

@@ -14,6 +14,7 @@ impeller_component("playground") {
]
public_deps = [
"../compositor",
"//flutter/testing",
"//third_party/glfw",
]

View File

@@ -8,6 +8,7 @@
#include "flutter/fml/logging.h"
#include "impeller/base/base.h"
#include "impeller/compositor/pipeline_builder.h"
#include "impeller/compositor/pipeline_descriptor.h"
#include "impeller/compositor/shader_library.h"
#include "impeller/compositor/vertex_descriptor.h"
@@ -16,55 +17,17 @@ namespace impeller {
BoxPrimitive::BoxPrimitive(std::shared_ptr<Context> context)
: Primitive(context) {
PipelineDescriptor desc;
desc.SetLabel(SPrintF("%s Pipeline", shader::BoxVertexInfo::kLabel.data()));
{
auto fragment_function = context->GetShaderLibrary()->GetFunction(
shader::BoxFragmentInfo::kEntrypointName, ShaderStage::kFragment);
auto vertex_function = context->GetShaderLibrary()->GetFunction(
shader::BoxVertexInfo::kEntrypointName, ShaderStage::kVertex);
desc.AddStageEntrypoint(vertex_function);
desc.AddStageEntrypoint(fragment_function);
}
{
auto vertex_descriptor = std::make_shared<VertexDescriptor>();
vertex_buffer_index_ = vertex_descriptor->GetVertexBufferIndex();
if (!vertex_descriptor->SetStageInputs(
shader::BoxVertexInfo::kAllShaderStageInputs)) {
FML_LOG(ERROR) << "Could not configure vertex descriptor.";
return;
}
desc.SetVertexDescriptor(std::move(vertex_descriptor));
}
{
// Configure the sole color attachments pixel format.
ColorAttachmentDescriptor color0;
color0.format = PixelFormat::kPixelFormat_B8G8R8A8_UNormInt_SRGB;
desc.SetColorAttachmentDescriptor(0u, std::move(color0));
}
{
// Configure the stencil attachment.
// TODO(wip): Make this configurable if possible as the D32 component is
// wasted.
const auto combined_depth_stencil_format =
PixelFormat::kPixelFormat_D32_Float_S8_UNormInt;
desc.SetDepthPixelFormat(combined_depth_stencil_format);
desc.SetStencilPixelFormat(combined_depth_stencil_format);
}
pipeline_ =
context->GetPipelineLibrary()->GetRenderPipeline(std::move(desc)).get();
if (!pipeline_) {
FML_LOG(ERROR) << "Could not create the render pipeline.";
using Builder = PipelineBuilder<BoxVertexShader, BoxFragmentShader>;
auto pipeline_descriptor = Builder::MakeDefaultPipelineDescriptor(*context);
if (!pipeline_descriptor.has_value()) {
return;
}
pipeline_ = context->GetPipelineLibrary()
->GetRenderPipeline(pipeline_descriptor.value())
.get();
if (!pipeline_) {
return;
}
is_valid_ = true;
}