Initial Commit

This commit is contained in:
Chinmay Garde
2021-04-20 13:02:44 -07:00
committed by Dan Field
parent 723ea3e81d
commit 072ea4baf3
14 changed files with 632 additions and 0 deletions

View File

@@ -0,0 +1,8 @@
# Defines the Chromium style for automatic reformatting.
# http://clang.llvm.org/docs/ClangFormatStyleOptions.html
BasedOnStyle: Chromium
# This defaults to 'Auto'. Explicitly set it for a while, so that
# 'vector<vector<int> >' in existing files gets formatted to
# 'vector<vector<int>>'. ('Auto' means that clang-format will only use
# 'int>>' if the file already contains at least one such instance.)
Standard: Cpp11

26
engine/src/flutter/impeller/.gitignore vendored Normal file
View File

@@ -0,0 +1,26 @@
# commonly generated files
*.pyc
*~
.*.sw?
.ccls-cache
.checkstyle
.clangd
.classpath
.cproject
.DS_Store
.gdb_history
.gdbinit
.idea
.ignore
.landmines
.packages
.project
.pub
.pydevproject
.vscode
compile_commands.json
cscope.*
Session.vim
tags
Thumbs.db

View File

@@ -0,0 +1,10 @@
# 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.
group("impeller") {
deps = [
"host",
"impeller",
]
}

View File

@@ -0,0 +1,12 @@
```
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
----------------- ___ _ _ --------------------
----------------- |_ _|_ __ ___ _ __ ___| | | ___ _ __ --------------------
----------------- | || '_ ` _ \| '_ \ / _ \ | |/ _ \ '__| --------------------
----------------- | || | | | | | |_) | __/ | | __/ | --------------------
----------------- |___|_| |_| |_| .__/ \___|_|_|\___|_| --------------------
----------------- |_| --------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
```

View File

@@ -0,0 +1,28 @@
# 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/common/config.gni")
executable("host") {
cflags_objc = flutter_cflags_objc_arc
cflags_objcc = flutter_cflags_objcc_arc
output_name = "impeller"
sources = [
"Renderer.h",
"Renderer.m",
"ShaderTypes.h",
"impeller_host_view_controller.h",
"impeller_host_view_controller.m",
"main.m",
]
libs = [
"AppKit.framework",
"Metal.framework",
"MetalKit.framework",
"ModelIO.framework",
]
}

View File

@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIconFile</key>
<string></string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>NSMainStoryboardFile</key>
<string>Main</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
</dict>
</plist>

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.
#import <MetalKit/MetalKit.h>
// Our platform independent renderer class. Implements the MTKViewDelegate protocol which
// allows it to accept per-frame update and drawable resize callbacks.
@interface Renderer : NSObject <MTKViewDelegate>
- (nonnull instancetype)initWithMetalKitView:(nonnull MTKView*)view;
@end

View File

@@ -0,0 +1,299 @@
// 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 "Renderer.h"
// Include header shared between C code here, which executes Metal API commands, and .metal files
#import "ShaderTypes.h"
static const NSUInteger kMaxBuffersInFlight = 3;
static const size_t kAlignedUniformsSize = (sizeof(Uniforms) & ~0xFF) + 0x100;
@implementation Renderer {
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;
}
- (nonnull instancetype)initWithMetalKitView:(nonnull MTKView*)view {
self = [super init];
if (self) {
_device = view.device;
_inFlightSemaphore = dispatch_semaphore_create(kMaxBuffersInFlight);
[self _loadMetalWithView:view];
[self _loadAssets];
}
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;
id<MTLLibrary> defaultLibrary = [_device newDefaultLibrary];
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)
};
_colorMap = [textureLoader newTextureWithName:@"ColorMap"
scaleFactor:1.0
bundle:nil
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 {
/// 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 {
/// Respond to drawable size or orientation changes here
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
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}}};
}
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}}};
}
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

@@ -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.
#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

@@ -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.
// 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);
}

View File

@@ -0,0 +1,12 @@
// 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 "Renderer.h"
@interface ImpellerHostViewController : NSViewController
@end

View File

@@ -0,0 +1,37 @@
// 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 "Renderer.h"
@implementation ImpellerHostViewController {
MTKView* view_;
Renderer* renderer_;
}
- (void)loadView {
view_ = [[MTKView alloc] init];
view_.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
[self setView: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_ = [[Renderer alloc] initWithMetalKitView:view_];
[renderer_ mtkView:view_ drawableSizeWillChange:view_.bounds.size];
view_.delegate = renderer_;
}
@end

View File

@@ -0,0 +1,58 @@
// 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(0, 0, 800, 600)
styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable
backing:NSBackingStoreBuffered
defer:NO];
[window_ setContentViewController:view_controller_];
}
return self;
}
- (void)applicationWillFinishLaunching:(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];
NSApp.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

@@ -0,0 +1,10 @@
# 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/common/config.gni")
source_set("impeller") {
cflags_objc = flutter_cflags_objc_arc
cflags_objcc = flutter_cflags_objcc_arc
}