WIP: reconstruct color kernels, camera tables and native inspector; integration checks pending

这个提交包含在:
mac 于 2026-10-31 01:16:08 +08:00 提交
1 父节点 10987dd6bc
当前提交 2f11e8bd0f
52 个文件已更改
+11421 -835

没有与搜索条件相匹配的文件

+26
查看文件
@@ -0,0 +1,26 @@
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
#import "DYUniforms.h"
NS_ASSUME_NONNULL_BEGIN
/// Camera Raw tables are the MIT-licensed Compositor dataset, not application code.
/// Nil means a resource/GPU failure; inactive controls return an identity texture.
@interface DYColorTables : NSObject
@property (nonatomic, readonly, nullable) NSString *lastError;
- (nullable id<MTLTexture>)whiteBalanceForDevice:(id<MTLDevice>)device uniforms:(const DYUniforms *)uniforms;
- (nullable id<MTLTexture>)hslForDevice:(id<MTLDevice>)device uniforms:(const DYUniforms *)uniforms;
- (nullable id<MTLTexture>)gradingForDevice:(id<MTLDevice>)device uniforms:(const DYUniforms *)uniforms;
+ (void)fillPrimaries:(DYUniforms *)uniforms;
+ (BOOL)neutralizeColor:(vector_float3)color temperature:(float *)temperature tint:(float *)tint;
@end
#ifdef DY_COLOR_TABLES_TESTING
FOUNDATION_EXPORT NSData * _Nullable DYDecodeColorTables(NSData *file, NSError **error);
FOUNDATION_EXPORT vector_float3 DYSampleColorTable(NSData *tables, NSInteger table, vector_float3 color);
FOUNDATION_EXPORT NSData *DYComposeWhiteBalance(NSData *tables, float temperature, float tint);
FOUNDATION_EXPORT NSData *DYComposeHSL(NSData *tables, const float *hue, const float *saturation, const float *luminance);
FOUNDATION_EXPORT NSData *DYComposeGrading(NSData *tables, const float *parameters);
#endif
NS_ASSUME_NONNULL_END
+321
查看文件
@@ -0,0 +1,321 @@
// Camera Raw table decoding and composition adapted from Compositor (MIT).
// Upstream: https://github.com/robbietilton/Compositor
// Commit: 92f5225afe7e921dbfa4c563462980e45db345fc
// Table SHA-256: e67ff4dbcce35cb7765752acff4405be5c934d913ef1396b2ca3fc6dc8a85190
// Float composition order checked against LumiGrade 3.0 build 56, arm64.
#define DY_COLOR_TABLES_TESTING 1
#import "DYColorTables.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <vector>
namespace {
constexpr size_t kTableCells = 17 * 17 * 17;
constexpr size_t kTableBytes = kTableCells * 3;
constexpr size_t kTableCount = 763;
constexpr size_t kGrid = 33;
constexpr size_t kGridBytes = kGrid * kGrid * kGrid * sizeof(vector_float4);
constexpr float kEpsilon = 1e-6f;
using Color = vector_float3;
struct Part { NSInteger table; float weight; }; // table -1 means identity.
struct Stage : std::vector<Part> {
using std::vector<Part>::vector;
bool interpolatesPair=false;
};
using Stages = std::vector<Stage>;
inline float safe(float value, float low, float high) { return std::isfinite(value) ? std::clamp(value,low,high) : std::clamp(0.f,low,high); }
inline Color bounded(Color c) { return simd_clamp(c,(Color){0,0,0},(Color){1,1,1}); }
std::pair<int,float> between(float value,float low,float step,int count) {
float p=safe((value-low)/step,0.f,float(count-1));
int index=std::min(count-2,int(p));
return {index,p-float(index)};
}
Stage twoTables(NSInteger start,float value) {
auto [index,up]=between(value,-100.f,50.f,5);
return {{start+index,1.f-up},{start+index+1,up}};
}
Stage whiteBalanceStage(float temperature,float tint) {
auto [row,down]=between(temperature,-100.f,25.f,9);
auto [column,across]=between(tint,-100.f,25.f,9);
NSInteger base=row*9+column;
return {{base,(1.f-down)*(1.f-across)},{base+1,(1.f-down)*across},
{base+9,down*(1.f-across)},{base+10,down*across}};
}
Stages mixerStages(const float hue[8],const float saturation[8],const float luminance[8]) {
Stages stages;
const float *values[3]={luminance,saturation,hue};
for(int kind=0;kind<3;kind++)for(int color=0;color<8;color++) {
float v=safe(values[kind][color],-100.f,100.f);
if(std::fabs(v)>kEpsilon) {
Stage stage=twoTables(285+(kind*8+color)*5,v);
stage.interpolatesPair=true;
stages.push_back(std::move(stage));
}
}
return stages;
}
Stages gradingStages(const float parameters[14]) {
// Input order: midtones, shadows, highlights, global (H,S,L), blending,balance.
struct Wheel {float hue,saturation,luminance;};
Wheel wheels[4]={{parameters[3],parameters[4],parameters[5]},
{parameters[0],parameters[1],parameters[2]},
{parameters[6],parameters[7],parameters[8]},
{parameters[9],parameters[10],parameters[11]}};
Stages stages;
for(int i=0;i<4;i++)if(std::fabs(wheels[i].luminance)>kEpsilon)
stages.push_back(twoTables(743+i*5,safe(wheels[i].luminance,-100,100)));
float balance=safe(parameters[13],-100,100)/100.f;
float highlightShare=std::max(0.f,balance<0?1.f+1.4f*balance:1.f+2.f*balance);
float shadowShare=std::max(0.f,balance<0?1.f-1.2f*balance:1.f-1.4f*balance);
auto [blendLow,blendUp]=between(parameters[12],0.f,50.f,3);
const int order[4]={3,1,2,0};
for(int index:order) {
// Source table wheel numbering is shadows=0, highlights=1, midtones=2, global=3.
int wheel=index==1?2:index==2?1:index;
const Wheel &color=wheels[index];
float share=index==0?shadowShare:index==2?highlightShare:1.f;
float saturation=safe(color.saturation,0.f,100.f)*share;
if(saturation<=kEpsilon)continue;
float position=std::fmod(std::isfinite(color.hue)?color.hue:0.f,360.f)/30.f;
if(position<0)position+=12.f;
int first=int(position)%12,second=(first+1)%12;
float around=position-float(int(position));
float levelPosition=saturation<=25?saturation/25.f:saturation<=50?1.f+(saturation-25.f)/25.f:2.f+(saturation-50.f)/50.f;
levelPosition=safe(levelPosition,0.f,3.f);
int level=std::min(2,int(levelPosition));
float up=levelPosition-float(level);
bool blends=index==0||index==2;
std::vector<std::pair<int,float>> blendings=blends?
std::vector<std::pair<int,float>>{{blendLow,1.f-blendUp},{blendLow+1,blendUp}}:
std::vector<std::pair<int,float>>{{1,1.f}};
Stage stage;
for(auto [blendIndex,blendWeight]:blendings) {
int base=455+(blendIndex==0?0:blendIndex==1?72:216)+wheel*36;
for(auto [hue,hueWeight]:std::array<std::pair<int,float>,2>{{{first,1.f-around},{second,around}}})
for(auto [sat,satWeight]:std::array<std::pair<int,float>,2>{{{level,1.f-up},{level+1,up}}})
stage.push_back({sat==0?-1:base+hue*3+sat-1,blendWeight*hueWeight*satWeight});
}
stages.push_back(std::move(stage));
}
return stages;
}
Color sample(const uint8_t *tables,NSInteger table,Color color) {
if(table<0)return color;
if(table>=NSInteger(kTableCount))return (Color){0,0,0};
Color p=bounded(color)*16.f;
vector_int3 cell={(int)p.x,(int)p.y,(int)p.z};
cell=simd_min(cell,(vector_int3){15,15,15});
Color f=p-__builtin_convertvector(cell,Color);
Color out={0,0,0};
for(int corner=0;corner<8;corner++) {
int dr=corner>>2,dg=(corner>>1)&1,db=corner&1;
float weight=(db?f.z:1.f-f.z)*(dr?f.x:1.f-f.x)*(dg?f.y:1.f-f.y);
if(weight<=0)continue;
size_t at=table*kTableBytes+(((cell.x+dr)*17+(cell.y+dg))*17+cell.z+db)*3;
// Retain the reference's multiply-then-divide float operation order.
out.x+=float(tables[at])*weight/255.f;
out.y+=float(tables[at+1])*weight/255.f;
out.z+=float(tables[at+2])*weight/255.f;
}
return out;
}
Color apply(const uint8_t *tables,const Stages &stages,Color color) {
for(const Stage &stage:stages) {
if(stage.interpolatesPair&&stage.size()==2) {
Color low=sample(tables,stage[0].table,color);
Color high=sample(tables,stage[1].table,color);
color=bounded(low+(high-low)*stage[1].weight);
continue;
}
Color out={0,0,0};
for(const Part &p:stage)if(p.weight>0)out+=sample(tables,p.table,color)*p.weight;
color=bounded(out);
}
return color;
}
NSData *compose(NSData *tables,const Stages &stages) {
NSMutableData *data=[NSMutableData dataWithLength:kGridBytes];
vector_float4 *out=(vector_float4 *)data.mutableBytes;
const uint8_t *bytes=(const uint8_t *)tables.bytes;
// A Metal 3D texture is R-fastest; the source 17³ tables are B-fastest.
dispatch_apply(kGrid,dispatch_get_global_queue(QOS_CLASS_USER_INITIATED,0),^(size_t b){
for(size_t g=0;g<kGrid;g++)for(size_t r=0;r<kGrid;r++) {
Color c={(float)r/32.f,(float)g/32.f,(float)b/32.f};
c=apply(bytes,stages,c);
out[(b*kGrid+g)*kGrid+r]=(vector_float4){c.x,c.y,c.z,1.f};
}
});
return data;
}
NSError *resourceError(NSString *message) {
return [NSError errorWithDomain:@"com.dayu.color.tables" code:1 userInfo:@{NSLocalizedDescriptionKey:message}];
}
NSData *sourceTables(NSString **diagnostic) {
static NSData *tables=nil;
static NSString *failure=nil;
static dispatch_once_t once;
dispatch_once(&once,^{
NSBundle *bundle=[NSBundle bundleForClass:DYColorTables.class];
NSURL *url=[bundle URLForResource:@"DayuColorTables" withExtension:@"bin"];
if(!url)url=[bundle URLForResource:@"DayuColorTables" withExtension:@"bin" subdirectory:@"Resources"];
NSError *error=nil;
NSData *file=url?[NSData dataWithContentsOfURL:url options:0 error:&error]:nil;
if(file)tables=[DYDecodeColorTables(file,&error) retain];
if(!tables)failure=[(error.localizedDescription?:@"缺少 DayuColorTables.bin 调色数据") copy];
});
if(diagnostic)*diagnostic=failure;
return tables;
}
Color rotatePrimary(Color primary,float shift) {
const Color n={.5773502588272095f,.5773502588272095f,.5773502588272095f};
const Color a={.7071067690849304f,-.7071067690849304f,0};
const Color b={-.40824827551841736f,-.40824827551841736f,.8164965510368347f};
float angle=shift/100.f*.5235987305641174f;
float x=simd_dot(primary,a),y=simd_dot(primary,b),gray=simd_dot(primary,n);
float sine=std::sin(angle),cosine=std::cos(angle);
return n*gray+a*(cosine*x+sine*y)+b*(cosine*y-sine*x);
}
matrix_float3x3 satAxis(Color primary,float amount) {
Color v=primary-(Color){1.f/3.f,1.f/3.f,1.f/3.f};
float scale=amount/std::max(1e-8f,simd_dot(v,v));
matrix_float3x3 result=matrix_identity_float3x3;
for(int column=0;column<3;column++)result.columns[column]+=v*(scale*v[column]);
return result;
}
} // namespace
// Kept callable by the focused CPU verification tool; production loads one immutable dataset.
NSData *DYDecodeColorTables(NSData *file,NSError **error) {
if(error)*error=nil;
if(file.length<=10||memcmp(file.bytes,"CRT3",4)!=0) {if(error)*error=resourceError(@"调色数据头无效");return nil;}
const uint8_t *header=(const uint8_t *)file.bytes;
auto word=[&](int at){return int(header[at])|(int(header[at+1])<<8);};
int step=word(8);
if(word(4)!=17||word(6)!=763||step<=0) {if(error)*error=resourceError(@"调色数据尺寸不兼容");return nil;}
NSData *planes=[[file subdataWithRange:NSMakeRange(10,file.length-10)]decompressedDataUsingAlgorithm:NSDataCompressionAlgorithmLZMA error:error];
if(planes.length!=kTableCount*kTableBytes) {if(error&&!*error)*error=resourceError(@"调色数据解压长度错误");return nil;}
NSMutableData *result=[NSMutableData dataWithLength:planes.length];
const uint8_t *bytes=(const uint8_t *)planes.bytes;
uint8_t *out=(uint8_t *)result.mutableBytes;
int levels[17];for(int i=0;i<17;i++)levels[i]=(int)std::round(double(i)*255.0/16.0);
for(size_t table=0;table<kTableCount;table++)for(size_t channel=0;channel<3;channel++) {
uint8_t running=0;
size_t base=(table*3+channel)*kTableCells;
for(size_t cell=0;cell<kTableCells;cell++) {
running=uint8_t(running+bytes[base+cell]);
size_t axis=channel==0?cell/(17*17):channel==1?(cell/17)%17:cell%17;
int value=levels[axis]+int((int8_t)running)*step;
out[table*kTableBytes+cell*3+channel]=(uint8_t)std::clamp(value,0,255);
}
}
return result;
}
Color DYSampleColorTable(NSData *tables,NSInteger table,Color color) {return sample((const uint8_t *)tables.bytes,table,color);}
NSData *DYComposeWhiteBalance(NSData *tables,float temperature,float tint) {return compose(tables,{whiteBalanceStage(temperature,tint)});}
NSData *DYComposeHSL(NSData *tables,const float hue[8],const float saturation[8],const float luminance[8]) {return compose(tables,mixerStages(hue,saturation,luminance));}
NSData *DYComposeGrading(NSData *tables,const float parameters[14]) {return compose(tables,gradingStages(parameters));}
@implementation DYColorTables {
NSLock *_lock;
NSMutableDictionary *_textures;
NSMutableArray *_order;
NSString *_lastError;
}
- (instancetype)init {if((self=[super init])){_lock=[NSLock new];_textures=[NSMutableDictionary new];_order=[NSMutableArray new];}return self;}
- (void)dealloc {[_lock release];[_textures release];[_order release];[_lastError release];[super dealloc];}
- (NSString *)lastError {[_lock lock];NSString *value=[[_lastError retain]autorelease];[_lock unlock];return value;}
- (id<MTLTexture>)textureForDevice:(id<MTLDevice>)device kind:(NSString *)kind key:(NSData *)parameters stages:(const Stages &)stages {
[_lock lock];
@try {
NSArray *key=@[@(device.registryID),kind,parameters];
id<MTLTexture> cached=_textures[key];
if(cached){[_order removeObject:key];[_order addObject:key];return [[cached retain]autorelease];}
NSString *diagnostic=nil;
NSData *tables=sourceTables(&diagnostic);
if(!tables){[_lastError release];_lastError=[diagnostic copy];return nil;}
NSData *data=compose(tables,stages);
MTLTextureDescriptor *descriptor=[[[MTLTextureDescriptor alloc]init]autorelease];
descriptor.textureType=MTLTextureType3D;descriptor.pixelFormat=MTLPixelFormatRGBA32Float;
descriptor.width=kGrid;descriptor.height=kGrid;descriptor.depth=kGrid;
descriptor.mipmapLevelCount=1;descriptor.storageMode=MTLStorageModeShared;descriptor.usage=MTLTextureUsageShaderRead;
id<MTLTexture> texture=[device newTextureWithDescriptor:descriptor];
if(!texture){[_lastError release];_lastError=[@"无法创建调色 LUT 纹理" copy];return nil;}
texture.label=[@"大鱼调色 " stringByAppendingString:kind];
[texture replaceRegion:MTLRegionMake3D(0,0,0,kGrid,kGrid,kGrid) mipmapLevel:0 slice:0 withBytes:data.bytes bytesPerRow:kGrid*sizeof(vector_float4) bytesPerImage:kGrid*kGrid*sizeof(vector_float4)];
_textures[key]=texture;[_order addObject:key];
while(_order.count>12){id oldest=[[_order[0]retain]autorelease];[_textures removeObjectForKey:oldest];[_order removeObjectAtIndex:0];}
[_lastError release];_lastError=nil;
return [texture autorelease];
} @finally {[_lock unlock];}
}
- (id<MTLTexture>)whiteBalanceForDevice:(id<MTLDevice>)device uniforms:(const DYUniforms *)u {
float p[2]={u->temperatureEnabled>.5f?safe(u->temperature,-100,100):0,u->tintEnabled>.5f?safe(u->tint,-100,100):0};
Stages stages;if(std::fabs(p[0])+std::fabs(p[1])>kEpsilon)stages.push_back(whiteBalanceStage(p[0],p[1]));
return [self textureForDevice:device kind:@"WhiteBalance" key:[NSData dataWithBytes:p length:sizeof(p)] stages:stages];
}
- (id<MTLTexture>)hslForDevice:(id<MTLDevice>)device uniforms:(const DYUniforms *)u {
float p[24]={0};
if(u->hslSectionEnabled>.5f)for(int i=0;i<8;i++) {
p[i]=i<4?u->hslHueA[i]:u->hslHueB[i-4];
p[8+i]=i<4?u->hslSatA[i]:u->hslSatB[i-4];
p[16+i]=i<4?u->hslLumA[i]:u->hslLumB[i-4];
}
return [self textureForDevice:device kind:@"HSL" key:[NSData dataWithBytes:p length:sizeof(p)] stages:mixerStages(p,p+8,p+16)];
}
- (id<MTLTexture>)gradingForDevice:(id<MTLDevice>)device uniforms:(const DYUniforms *)u {
float p[14]={0};
if(u->colorGradingSectionEnabled>.5f) {
p[0]=u->colorGradingHueSatA.x;p[1]=u->colorGradingHueSatA.y;p[2]=u->colorGradingLuma.x;
p[3]=u->colorGradingHueSatA.z;p[4]=u->colorGradingHueSatA.w;p[5]=u->colorGradingLuma.y;
p[6]=u->colorGradingHueSatB.x;p[7]=u->colorGradingHueSatB.y;p[8]=u->colorGradingLuma.z;
p[9]=u->colorGradingGlobal.x;p[10]=u->colorGradingGlobal.y;p[11]=u->colorGradingGlobal.z;
p[12]=u->colorGradingBlending;p[13]=u->colorGradingBalance;
}
return [self textureForDevice:device kind:@"ColorGrading" key:[NSData dataWithBytes:p length:sizeof(p)] stages:gradingStages(p)];
}
+ (void)fillPrimaries:(DYUniforms *)u {
matrix_float3x3 result=matrix_identity_float3x3;
float total=std::fabs(u->redPrimaryHue)+std::fabs(u->greenPrimaryHue)+std::fabs(u->bluePrimaryHue)+std::fabs(u->redPrimarySaturation)+std::fabs(u->greenPrimarySaturation)+std::fabs(u->bluePrimarySaturation);
if(total>=kEpsilon) {
const matrix_float3x3 xyz=(matrix_float3x3){(Color){.4124564f,.2126729f,.0193339f},(Color){.3575761f,.7151522f,.119192f},(Color){.1804375f,.072175f,.9503041f}};
matrix_float3x3 shifted=(matrix_float3x3){simd_mul(xyz,rotatePrimary((Color){1,0,0},u->redPrimaryHue)),simd_mul(xyz,rotatePrimary((Color){0,1,0},u->greenPrimaryHue)),simd_mul(xyz,rotatePrimary((Color){0,0,1},u->bluePrimaryHue))};
if(std::fabs(simd_determinant(shifted))>1e-10f) {
Color scale=simd_mul(simd_inverse(shifted),(Color){.95047003f,1.0000001f,1.08883f});
if(simd_all(scale>(Color){.01f,.01f,.01f})) {
for(int c=0;c<3;c++)shifted.columns[c]*=scale[c];
result=simd_mul(simd_inverse(xyz),shifted);
float amounts[3]={u->redPrimarySaturation/100.f*.55f,u->greenPrimarySaturation/100.f*.55f,u->bluePrimarySaturation/100.f*.55f};
if(std::fabs(amounts[0])>kEpsilon||std::fabs(amounts[1])>kEpsilon||std::fabs(amounts[2])>kEpsilon)
result=simd_mul(simd_mul(simd_mul(result,satAxis((Color){1,0,0},amounts[0])),satAxis((Color){0,1,0},amounts[1])),satAxis((Color){0,0,1},amounts[2]));
float maxDeviation=0;
for(int c=0;c<3;c++)for(int r=0;r<3;r++)maxDeviation=std::max(maxDeviation,std::fabs(result.columns[c][r]-(c==r?1.f:0.f)));
if(maxDeviation>.6f) {
float blend=safe((maxDeviation-.6f)/.4f,0.f,1.f);
for(int c=0;c<3;c++)result.columns[c]=matrix_identity_float3x3.columns[c]*blend+result.columns[c]*(1.f-blend);
}
}
}
}
u->primariesM0=result.columns[0];u->primariesM1=result.columns[1];u->primariesM2=result.columns[2];
}
+ (BOOL)neutralizeColor:(Color)color temperature:(float *)temperature tint:(float *)tint {
NSData *tables=sourceTables(nullptr);
if(!tables||!simd_all(color>(Color){1e-4f,1e-4f,1e-4f})||!std::isfinite(color.x+color.y+color.z))return NO;
const uint8_t *bytes=(const uint8_t *)tables.bytes;
auto cast=[&](float t,float g){Color c=apply(bytes,{whiteBalanceStage(t,g)},color);return simd_reduce_max(c)-simd_reduce_min(c);};
float bestTemperature=0,bestTint=0,bestCast=cast(0,0);
const float steps[3]={10,2,.5f},reaches[3]={100,10,2};
for(int pass=0;pass<3;pass++) {
float centerT=bestTemperature,centerG=bestTint;
for(float t=centerT-reaches[pass];t<=centerT+reaches[pass];t+=steps[pass])
for(float g=centerG-reaches[pass];g<=centerG+reaches[pass];g+=steps[pass]) {
if(std::fabs(t)>100||std::fabs(g)>100)continue;
float found=cast(t,g);
if(found<bestCast){bestTemperature=t;bestTint=g;bestCast=found;}
}
}
if(temperature)*temperature=bestTemperature;if(tint)*tint=bestTint;return YES;
}
@end
+80
查看文件
@@ -0,0 +1,80 @@
#include <metal_stdlib>
#include "DYUniforms.h"
using namespace metal;
// The linked, versioned AIR helper owns color arithmetic only. Its source is in
// tools/kernels; production builds never read the reference application.
extern "C" half4 dy_grade(half4 sample, float2 uv, texture2d<half> source,
texture3d<float> preLUT, texture3d<float> look1, texture3d<float> look2,
texture3d<float> look3, texture3d<float> look4, texture3d<float> look5,
texture3d<float> hslMixer, texture3d<float> whiteBalance,
texture3d<float> colorGrading, constant DYUniforms& uniforms,
constant float& sceneLevel);
struct DYRaster {
float4 position [[position]];
float2 uv;
};
vertex DYRaster dyVertex(uint vertexID [[vertex_id]],
constant DYVertex2D* vertices [[buffer(0)]],
constant uint2& viewportSize [[buffer(1)]]) {
DYRaster result;
result.position = float4(vertices[vertexID].position / (float2(viewportSize) * 0.5f), 0.0f, 1.0f);
result.uv = vertices[vertexID].textureCoordinate;
return result;
}
fragment half4 dyFragment(DYRaster in [[stage_in]],
texture2d<half> source [[texture(0)]],
texture3d<float> preLUT [[texture(1)]],
texture3d<float> look1 [[texture(2)]],
texture3d<float> look2 [[texture(3)]],
texture3d<float> look3 [[texture(4)]],
texture3d<float> look4 [[texture(5)]],
texture3d<float> look5 [[texture(6)]],
texture3d<float> hslMixer [[texture(7)]],
texture3d<float> whiteBalance [[texture(8)]],
texture3d<float> colorGrading [[texture(9)]],
constant DYUniforms& uniforms [[buffer(0)]],
constant float& sceneLevel [[buffer(1)]],
constant DYRenderOptions& options [[buffer(2)]]) {
constexpr sampler sampleFilter(coord::normalized, address::clamp_to_edge, filter::linear);
half4 sample = source.sample(sampleFilter, in.uv);
if (!(sample.a > half(0.0))) return half4(0.0h);
half4 result = dy_grade(sample, in.uv, source, preLUT, look1, look2, look3,
look4, look5, hslMixer, whiteBalance, colorGrading, uniforms, sceneLevel);
result.a = sample.a;
if (options.outputPremultiplied) result.rgb *= result.a;
return result;
}
// Optional boundary conversion. Use this before both statistics and grading
// when the host supplies premultiplied RGB; all neighborhood samples then see
// the same straight RGB representation. Source and destination must differ.
kernel void dyUnpremultiply(texture2d<float, access::read> source [[texture(0)]],
texture2d<half, access::write> destination [[texture(1)]],
uint2 pixel [[thread_position_in_grid]]) {
if (pixel.x >= destination.get_width() || pixel.y >= destination.get_height()) return;
float4 sample = source.read(pixel);
if (!(sample.a > 0.0f) || !all(isfinite(sample))) {
destination.write(half4(0.0h), pixel);
return;
}
destination.write(half4(half3(sample.rgb / sample.a), half(sample.a)), pixel);
}
// Per-instance CPU analysis thumbnail. Host dispatches exactly 64x64 threads;
// RGB is sRGB encoded, alpha is unchanged. HDR and negative values are retained
// by the standard piecewise transfer rather than silently clipping the sample.
kernel void dyPreview(texture2d<half> source [[texture(0)]],
device float4* outRGBA [[buffer(0)]],
uint2 pixel [[thread_position_in_grid]]) {
if (pixel.x >= 64 || pixel.y >= 64) return;
constexpr sampler sampleFilter(coord::normalized, address::clamp_to_edge, filter::linear);
half4 sample = source.sample(sampleFilter, (float2(pixel) + 0.5f) / 64.0f);
float3 linear = float3(sample.rgb);
float3 power = 1.055f * pow(max(linear, float3(0.0f)), float3(1.0f / 2.4f)) - 0.055f;
float3 encoded = select(power, linear * 12.92f, linear <= 0.0031308f);
outRGBA[pixel.y * 64 + pixel.x] = float4(encoded, float(sample.a));
}
+8
查看文件
@@ -0,0 +1,8 @@
#import <Cocoa/Cocoa.h>
#import <FxPlug/FxPlugSDK.h>
/// Per-instance custom inspector. All host reads and edits are bracketed actions.
@interface DYInspector : NSView
- (instancetype)initWithAPIManager:(id<PROAPIAccessing>)manager;
- (void)refresh;
@end
+684
查看文件
@@ -0,0 +1,684 @@
#import "DYInspector.h"
#import "DYModel.h"
#import <QuartzCore/QuartzCore.h>
#include <cmath>
#include <vector>
#include <algorithm>
static NSColor *DYAccent(void) { return [NSColor colorWithSRGBRed:.26 green:.73 blue:.98 alpha:1]; }
static NSColor *DYInk(void) { return [NSColor colorWithSRGBRed:.83 green:.91 blue:.97 alpha:1]; }
static NSTextField *DYLabel(NSString *text, CGFloat size) {
NSTextField *v=[NSTextField labelWithString:text?:@""];
v.font=[NSFont systemFontOfSize:size]; v.textColor=DYInk();
v.lineBreakMode=NSLineBreakByTruncatingTail;
return v;
}
static NSButton *DYButton(NSString *title,id target,SEL action) {
NSButton *b=[NSButton buttonWithTitle:title target:target action:action];
b.bezelStyle=NSBezelStyleRounded; b.font=[NSFont systemFontOfSize:11];
b.contentTintColor=DYAccent(); return b;
}
static NSString *DYNumber(double value,NSDictionary *d) {
double step=[d[@"step"] doubleValue];
return [NSString stringWithFormat:step>0&&step<.1?@"%.2f":step>0&&step<1?@"%.1f":@"%.0f",value];
}
@interface DYBlueSliderCell : NSSliderCell @end
@implementation DYBlueSliderCell
- (void)drawBarInside:(NSRect)rect flipped:(BOOL)flipped {
NSRect track=NSMakeRect(rect.origin.x,NSMidY(rect)-2,rect.size.width,4);
[[NSColor colorWithSRGBRed:.19 green:.30 blue:.37 alpha:1] setFill];[[NSBezierPath bezierPathWithRoundedRect:track xRadius:2 yRadius:2] fill];
double fraction=(self.doubleValue-self.minValue)/fmax(.000001,self.maxValue-self.minValue);
NSRect active=track;active.size.width*=fmax(0,fmin(1,fraction));[DYAccent() setFill];[[NSBezierPath bezierPathWithRoundedRect:active xRadius:2 yRadius:2] fill];
}
- (void)drawKnob:(NSRect)knobRect {
NSRect circle=NSInsetRect(knobRect,1,1);
[[NSColor colorWithSRGBRed:.69 green:.88 blue:1 alpha:1] setFill];[[NSBezierPath bezierPathWithOvalInRect:circle] fill];
[DYAccent() setStroke];NSBezierPath *ring=[NSBezierPath bezierPathWithOvalInRect:circle];ring.lineWidth=.7;[ring stroke];
}
@end
@interface DYFlippedView : NSView @end
@implementation DYFlippedView
- (BOOL)isFlipped { return YES; }
@end
@interface DYCard : DYFlippedView @end
@implementation DYCard
- (void)drawRect:(NSRect)rect {
[[NSColor colorWithSRGBRed:.045 green:.135 blue:.20 alpha:1] setFill];
NSBezierPath *path=[NSBezierPath bezierPathWithRoundedRect:NSInsetRect(self.bounds,.5,.5) xRadius:11 yRadius:11];
[path fill]; [[NSColor colorWithSRGBRed:.16 green:.34 blue:.45 alpha:1] setStroke];
path.lineWidth=1; [path stroke];
}
@end
@interface DYHeader : NSButton
@property SEL doubleClickAction;
@end
@implementation DYHeader
- (void)mouseDown:(NSEvent *)event {
if(event.clickCount==2) [NSApp sendAction:self.doubleClickAction to:self.target from:self];
else [super mouseDown:event];
}
@end
@protocol DYGraphicDelegate <NSObject>
- (void)writeGraphicValues:(NSDictionary *)values;
@end
/// The graph uses the same sorted monotone Hermite tangent limiter as the GPU.
@interface DYCurvePanel : DYFlippedView {
NSDictionary *_values;
NSSegmentedControl *_channels;
NSInteger _channel;
NSString *_dragXKey,*_dragYKey;
}
@property(nonatomic,assign) id<DYGraphicDelegate> delegate;
- (void)setValues:(NSDictionary *)values;
@end
@implementation DYCurvePanel
- (instancetype)initWithFrame:(NSRect)frame {
if((self=[super initWithFrame:frame])) {
_values=[@{} copy];
_channels=[[NSSegmentedControl segmentedControlWithLabels:@[@"RGB",@"红",@"绿",@"蓝"] trackingMode:NSSegmentSwitchTrackingSelectOne target:self action:@selector(channelChanged:)] retain];
_channels.selectedSegment=0; _channels.controlSize=NSControlSizeSmall; [self addSubview:_channels];
self.accessibilityLabel=@"曲线点编辑器";self.toolTip=@"点击添加点;拖动调整;双击、右键或按住 Option 点击已有点可删除";
}
return self;
}
- (void)dealloc { [_values release];[_channels release];[_dragXKey release];[_dragYKey release];[super dealloc]; }
- (BOOL)acceptsFirstResponder { return YES; }
- (void)setValues:(NSDictionary *)values { [_values release];_values=[values copy];[self setNeedsDisplay:YES]; }
- (void)layout { [super layout];_channels.frame=NSMakeRect(12,4,self.bounds.size.width-24,24); }
- (void)channelChanged:(NSSegmentedControl *)sender { _channel=sender.selectedSegment;[self setNeedsDisplay:YES]; }
- (NSRect)plotRect { return NSMakeRect(16,37,MAX(50,self.bounds.size.width-32),MAX(50,self.bounds.size.height-56)); }
- (NSArray *)slots {
NSMutableArray *result=[NSMutableArray array];
NSInteger n=_channel==0?4:2;
for(NSInteger i=0;i<n;i++) {
NSString *x=_channel==0?[NSString stringWithFormat:@"masterX%ld",(long)i]:[NSString stringWithFormat:@"channel%ldX%ld",(long)(_channel-1),(long)i];
NSString *y=[NSString stringWithFormat:@"curveY%ld",(long)(_channel==0?i:4+(_channel-1)*2+i)];
[result addObject:@{@"xKey":x,@"yKey":y}];
}
for(NSInteger i=0;i<4;i++) [result addObject:@{@"xKey":[NSString stringWithFormat:@"curve%ldExtraX%ld",(long)_channel,(long)i],@"yKey":[NSString stringWithFormat:@"curve%ldExtra%ld",(long)_channel,(long)i]}];
return result;
}
- (NSArray *)activePoints {
NSMutableArray *points=[NSMutableArray array];
for(NSDictionary *slot in [self slots]) {
NSNumber *xValue=_values[slot[@"xKey"]];double x=xValue?xValue.doubleValue:-1;
if(x<0)continue;
double y=fmax(0,fmin(1,x+[_values[slot[@"yKey"]] doubleValue]*.01));
[points addObject:@{@"xKey":slot[@"xKey"],@"yKey":slot[@"yKey"],@"x":@(x),@"y":@(y)}];
}
[points sortUsingComparator:^NSComparisonResult(NSDictionary *a,NSDictionary *b) {return [a[@"x"] compare:b[@"x"]];}];
return points;
}
- (NSPoint)positionOfPoint:(NSDictionary *)point {
NSRect r=[self plotRect];return NSMakePoint(r.origin.x+[point[@"x"] doubleValue]*r.size.width,r.origin.y+(1-[point[@"y"] doubleValue])*r.size.height);
}
- (NSDictionary *)pointNear:(NSPoint)p {
NSDictionary *closest=nil;double distance=13;
for(NSDictionary *point in [self activePoints]) {NSPoint q=[self positionOfPoint:point];double d=hypot(q.x-p.x,q.y-p.y);if(d<distance){distance=d;closest=point;}}
return closest;
}
- (void)drawRect:(NSRect)dirtyRect {
NSRect r=[self plotRect];
[[NSColor colorWithSRGBRed:.025 green:.085 blue:.13 alpha:1] setFill];[[NSBezierPath bezierPathWithRoundedRect:r xRadius:4 yRadius:4] fill];
[[NSColor colorWithWhite:1 alpha:.1] setStroke];NSBezierPath *grid=[NSBezierPath bezierPath];grid.lineWidth=.5;
for(int i=0;i<5;i++){CGFloat x=r.origin.x+r.size.width*i/4,y=r.origin.y+r.size.height*i/4;[grid moveToPoint:NSMakePoint(x,NSMinY(r))];[grid lineToPoint:NSMakePoint(x,NSMaxY(r))];[grid moveToPoint:NSMakePoint(NSMinX(r),y)];[grid lineToPoint:NSMakePoint(NSMaxX(r),y)];}[grid stroke];
std::vector<NSPoint> p; p.push_back(NSMakePoint(0,0));
NSArray *points=[self activePoints];for(NSDictionary *point in points)p.push_back(NSMakePoint([point[@"x"] doubleValue],[point[@"y"] doubleValue]));p.push_back(NSMakePoint(1,1));
for(size_t i=1;i<p.size();i++)p[i].x=fmax(p[i].x,p[i-1].x+.0001);p.back().x=1;
std::vector<double> slopes(p.size()-1),m(p.size());
for(size_t i=0;i<slopes.size();i++)slopes[i]=(p[i+1].y-p[i].y)/fmax(.0001,p[i+1].x-p[i].x);
m.front()=slopes.front();m.back()=slopes.back();
for(size_t i=1;i+1<p.size();i++)m[i]=slopes[i-1]*slopes[i]>0?(slopes[i-1]+slopes[i])*.5:0;
for(size_t i=0;i<slopes.size();i++) {
if(fabs(slopes[i])<.00001)m[i]=m[i+1]=0;
else {double a=m[i]/slopes[i],b=m[i+1]/slopes[i],v=hypot(a,b);if(v>3){m[i]=3*slopes[i]*a/v;m[i+1]=3*slopes[i]*b/v;}}
}
NSBezierPath *curve=[NSBezierPath bezierPath];curve.lineWidth=1.8;
size_t segment=0;
for(int sample=0;sample<=256;sample++) {
double x=sample/256.;while(segment+2<p.size()&&x>p[segment+1].x)segment++;
double width=fmax(.0001,p[segment+1].x-p[segment].x),t=fmax(0,fmin(1,(x-p[segment].x)/width));
double t2=t*t,t3=t2*t;
double y=(2*t3-3*t2+1)*p[segment].y+(t3-2*t2+t)*width*m[segment]+(-2*t3+3*t2)*p[segment+1].y+(t3-t2)*width*m[segment+1];
NSPoint q=NSMakePoint(r.origin.x+x*r.size.width,r.origin.y+(1-fmax(0,fmin(1,y)))*r.size.height);
if(sample==0)[curve moveToPoint:q];else[curve lineToPoint:q];
}
NSColor *color=_channel==0?DYAccent():_channel==1?[NSColor systemRedColor]:_channel==2?[NSColor systemGreenColor]:[NSColor systemBlueColor];[color setStroke];[curve stroke];
for(NSDictionary *point in points) {NSPoint q=[self positionOfPoint:point];[color setFill];[[NSBezierPath bezierPathWithOvalInRect:NSMakeRect(q.x-4,q.y-4,8,8)] fill];[DYInk() setStroke];[[NSBezierPath bezierPathWithOvalInRect:NSMakeRect(q.x-4,q.y-4,8,8)] stroke];}
[@"点击添加 · 拖动调整 · 双击删除" drawAtPoint:NSMakePoint(16,self.bounds.size.height-16) withAttributes:@{NSFontAttributeName:[NSFont systemFontOfSize:9],NSForegroundColorAttributeName:[NSColor colorWithWhite:.7 alpha:1]}];
}
- (void)sendValues:(NSDictionary *)values {
NSMutableDictionary *merged=[[_values mutableCopy] autorelease];[merged addEntriesFromDictionary:values];[self setValues:merged];
[self.delegate writeGraphicValues:values];
}
- (void)removePoint:(NSDictionary *)point { if(point)[self sendValues:@{point[@"xKey"]:@(-1),point[@"yKey"]:@0}]; }
- (void)mouseDown:(NSEvent *)event {
NSPoint p=[self convertPoint:event.locationInWindow fromView:nil];if(!NSPointInRect(p,[self plotRect]))return;
[self.window makeFirstResponder:self];NSDictionary *point=[self pointNear:p];
if(point&&(event.clickCount==2||(event.modifierFlags&NSEventModifierFlagOption))) {[self removePoint:point];return;}
if(!point) {
NSDictionary *freeSlot=nil;for(NSDictionary *slot in [self slots]) {NSNumber *v=_values[slot[@"xKey"]];if(!v||v.doubleValue<0){freeSlot=slot;break;}}
if(!freeSlot){NSBeep();return;}
[_dragXKey release];_dragXKey=[freeSlot[@"xKey"] copy];[_dragYKey release];_dragYKey=[freeSlot[@"yKey"] copy];
[self updateDragAt:p];return;
}
[_dragXKey release];_dragXKey=[point[@"xKey"] copy];[_dragYKey release];_dragYKey=[point[@"yKey"] copy];
}
- (void)updateDragAt:(NSPoint)p {
if(!_dragXKey)return;NSRect r=[self plotRect];double x=fmax(.001,fmin(.999,(p.x-r.origin.x)/r.size.width)),y=fmax(0,fmin(1,1-(p.y-r.origin.y)/r.size.height));
for(NSDictionary *point in [self activePoints])if(![point[@"xKey"] isEqual:_dragXKey]) {double other=[point[@"x"] doubleValue];if(fabs(x-other)<.001)x=x<other?other-.001:other+.001;}
x=fmax(.001,fmin(.999,x));[self sendValues:@{_dragXKey:@(x),_dragYKey:@((y-x)*100)}];
}
- (void)mouseDragged:(NSEvent *)event { [self updateDragAt:[self convertPoint:event.locationInWindow fromView:nil]]; }
- (void)mouseUp:(NSEvent *)event { if(_dragXKey)[self updateDragAt:[self convertPoint:event.locationInWindow fromView:nil]];[_dragXKey release];_dragXKey=nil;[_dragYKey release];_dragYKey=nil; }
- (void)rightMouseDown:(NSEvent *)event { [self removePoint:[self pointNear:[self convertPoint:event.locationInWindow fromView:nil]]]; }
- (void)keyDown:(NSEvent *)event { if(event.keyCode==51&&_dragXKey)[self sendValues:@{_dragXKey:@(-1),_dragYKey:@0}];else[super keyDown:event]; }
@end
static NSImage *DYWheelImage(void) {
static NSImage *image;static dispatch_once_t once;
dispatch_once(&once,^{
const NSInteger size=192;
NSBitmapImageRep *rep=[[[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL pixelsWide:size pixelsHigh:size bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO colorSpaceName:NSCalibratedRGBColorSpace bytesPerRow:size*4 bitsPerPixel:32] autorelease];
unsigned char *bytes=rep.bitmapData;
for(NSInteger y=0;y<size;y++)for(NSInteger x=0;x<size;x++) {
double dx=(x+.5-size*.5)/(size*.5-1),dy=(size*.5-y-.5)/(size*.5-1),sat=hypot(dx,dy),hue=atan2(dy,dx)/(2*M_PI);if(hue<0)hue+=1;
double h=hue*6,c=fmin(1,sat),v=1-c,t=c*(1-fabs(fmod(h,2)-1)),r=0,g=0,b=0;
if(h<1){r=c;g=t;}else if(h<2){r=t;g=c;}else if(h<3){g=c;b=t;}else if(h<4){g=t;b=c;}else if(h<5){r=t;b=c;}else{r=c;b=t;}
NSInteger i=(y*size+x)*4;bytes[i]=(unsigned char)lrint((r+v)*255);bytes[i+1]=(unsigned char)lrint((g+v)*255);bytes[i+2]=(unsigned char)lrint((b+v)*255);bytes[i+3]=sat<=1?255:0;
}
image=[[NSImage alloc]initWithSize:NSMakeSize(size,size)];[image addRepresentation:rep];
});return image;
}
@interface DYColorWheel : DYFlippedView {
NSInteger _index;
double _hue,_sat;
BOOL _dragging;
}
@property(nonatomic,assign) id<DYGraphicDelegate> delegate;
- (instancetype)initWithIndex:(NSInteger)index;
- (void)setHue:(double)hue saturation:(double)sat;
@end
@implementation DYColorWheel
- (instancetype)initWithIndex:(NSInteger)index { if((self=[super initWithFrame:NSZeroRect])) {_index=index;self.accessibilityLabel=[@[@"阴影",@"中间调",@"高光",@"全局"][index] stringByAppendingString:@"色轮"];self.toolTip=@"拖动调整色相和饱和度;双击还原";}return self; }
- (BOOL)acceptsFirstResponder { return YES; }
- (NSRect)wheelRect {CGFloat diameter=MIN(self.bounds.size.width-12,self.bounds.size.height-26);return NSMakeRect((self.bounds.size.width-diameter)/2,22,diameter,diameter);}
- (void)setHue:(double)hue saturation:(double)sat {_hue=hue;_sat=sat;[self setNeedsDisplay:YES];}
- (void)drawRect:(NSRect)rect {
NSString *title=@[@"阴影",@"中间调",@"高光",@"全局"][_index];
NSDictionary *attrs=@{NSFontAttributeName:[NSFont systemFontOfSize:10],NSForegroundColorAttributeName:DYInk()};
NSSize titleSize=[title sizeWithAttributes:attrs];[title drawAtPoint:NSMakePoint((self.bounds.size.width-titleSize.width)/2,3) withAttributes:attrs];
NSRect r=[self wheelRect];[DYWheelImage() drawInRect:r fromRect:NSZeroRect operation:NSCompositingOperationSourceOver fraction:.85 respectFlipped:YES hints:nil];
[[NSColor colorWithWhite:0 alpha:.35] setStroke];[[NSBezierPath bezierPathWithOvalInRect:r] stroke];
double angle=_hue*M_PI/180,rad=r.size.width*.5*_sat/100;NSPoint p=NSMakePoint(NSMidX(r)+cos(angle)*rad,NSMidY(r)-sin(angle)*rad);
[[NSColor colorWithWhite:0 alpha:.7] setFill];[[NSBezierPath bezierPathWithOvalInRect:NSMakeRect(p.x-5,p.y-5,10,10)] fill];
[[NSColor whiteColor] setStroke];NSBezierPath *knob=[NSBezierPath bezierPathWithOvalInRect:NSMakeRect(p.x-4,p.y-4,8,8)];knob.lineWidth=1.6;[knob stroke];
[[NSColor colorWithWhite:1 alpha:.45] setStroke];NSBezierPath *cross=[NSBezierPath bezierPath];[cross moveToPoint:NSMakePoint(NSMidX(r)-3,NSMidY(r))];[cross lineToPoint:NSMakePoint(NSMidX(r)+3,NSMidY(r))];[cross moveToPoint:NSMakePoint(NSMidX(r),NSMidY(r)-3)];[cross lineToPoint:NSMakePoint(NSMidX(r),NSMidY(r)+3)];cross.lineWidth=.5;[cross stroke];
}
- (void)sendHue:(double)hue saturation:(double)sat {
[self setHue:hue saturation:sat];[self.delegate writeGraphicValues:@{[NSString stringWithFormat:@"grade%ld_0",(long)_index]:@(hue),[NSString stringWithFormat:@"grade%ld_1",(long)_index]:@(sat)}];
}
- (void)mouseDown:(NSEvent *)event {
_dragging=NO;
NSPoint p=[self convertPoint:event.locationInWindow fromView:nil];NSRect r=[self wheelRect];
if(hypot(p.x-NSMidX(r),p.y-NSMidY(r))>r.size.width*.5)return;
if(event.clickCount==2){[self sendHue:0 saturation:0];return;}
_dragging=YES;[self updateAt:p];
}
- (void)updateAt:(NSPoint)p {
NSRect r=[self wheelRect];double dx=p.x-NSMidX(r),dy=NSMidY(r)-p.y,h=atan2(dy,dx)*180/M_PI;if(h<0)h+=360;
[self sendHue:h saturation:fmin(100,hypot(dx,dy)/(r.size.width*.5)*100)];
}
- (void)mouseDragged:(NSEvent *)event {if(_dragging)[self updateAt:[self convertPoint:event.locationInWindow fromView:nil]];}
- (void)mouseUp:(NSEvent *)event {if(_dragging)[self updateAt:[self convertPoint:event.locationInWindow fromView:nil]];_dragging=NO;}
@end
@interface DYWheelPanel : DYFlippedView {
NSArray *_wheels;
}
@property(nonatomic,assign) id<DYGraphicDelegate> delegate;
- (void)setValues:(NSDictionary *)values;
@end
@implementation DYWheelPanel
- (instancetype)initWithFrame:(NSRect)frame {if((self=[super initWithFrame:frame])){NSMutableArray *w=[NSMutableArray array];for(NSInteger i=0;i<4;i++){DYColorWheel *wheel=[[[DYColorWheel alloc]initWithIndex:i]autorelease];[self addSubview:wheel];[w addObject:wheel];}_wheels=[w copy];}return self;}
- (void)dealloc {[_wheels release];[super dealloc];}
- (void)setDelegate:(id<DYGraphicDelegate>)delegate {_delegate=delegate;for(DYColorWheel *wheel in _wheels)wheel.delegate=delegate;}
- (void)setValues:(NSDictionary *)values {for(NSInteger i=0;i<4;i++)[_wheels[i] setHue:[values[[NSString stringWithFormat:@"grade%ld_0",(long)i]] doubleValue] saturation:[values[[NSString stringWithFormat:@"grade%ld_1",(long)i]] doubleValue]];}
- (void)layout {[super layout];CGFloat w=self.bounds.size.width/2,h=self.bounds.size.height/2;for(NSInteger i=0;i<4;i++)[_wheels[i] setFrame:NSMakeRect((i%2)*w,(i/2)*h,w,h)];}
@end
@interface DYInspector () <DYGraphicDelegate> {
id<PROAPIAccessing> _manager;
NSScrollView *_scroll;
DYFlippedView *_document;
NSTextField *_brand;
NSTextField *_subtitle;
NSButton *_resetAll, *_save, *_load, *_export;
NSArray *_sections;
NSMutableArray *_cards;
NSMutableDictionary *_controls;
NSMutableDictionary *_assetButtons;
NSMutableArray *_graphics;
NSColorSampler *_sampler;
BOOL _refreshing;
}
@end
@implementation DYInspector
- (instancetype)initWithAPIManager:(id<PROAPIAccessing>)manager {
if((self=[super initWithFrame:NSMakeRect(0,0,360,780)])) {
_manager=manager; _sections=[DYSections() copy];
_cards=[[NSMutableArray alloc] init]; _controls=[[NSMutableDictionary alloc] init];
_assetButtons=[[NSMutableDictionary alloc] init]; _graphics=[[NSMutableArray alloc] init];
self.autoresizingMask=NSViewWidthSizable;
self.wantsLayer=YES; self.layer.backgroundColor=[[NSColor colorWithSRGBRed:.018 green:.074 blue:.12 alpha:1] CGColor];
_brand=[DYLabel(@"大鱼调色",20) retain]; _brand.font=[NSFont boldSystemFontOfSize:20];
_subtitle=[DYLabel(@"颜色 · 光影 · 风格",10) retain]; _subtitle.textColor=DYAccent();
_resetAll=[DYButton(@"全部还原",self,@selector(resetAll:)) retain]; _resetAll.toolTip=@"恢复全部调色参数与 LUT";
_save=[DYButton(@"保存预设",self,@selector(savePreset:)) retain];
_load=[DYButton(@"载入预设",self,@selector(loadPreset:)) retain];
_export=[DYButton(@"导出 LUT",self,@selector(exportLUT:)) retain];
for(NSView *v in @[_brand,_subtitle,_resetAll,_save,_load,_export]) [self addSubview:v];
_scroll=[[NSScrollView alloc] initWithFrame:NSZeroRect];
_scroll.hasVerticalScroller=YES; _scroll.hasHorizontalScroller=NO; _scroll.drawsBackground=NO;
_scroll.autohidesScrollers=YES; _scroll.borderType=NSNoBorder;
_document=[[DYFlippedView alloc] initWithFrame:NSMakeRect(0,0,360,1000)];
_scroll.documentView=_document; [self addSubview:_scroll];
[self buildCards];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(modelChanged:) name:@"DYModelChanged" object:_manager];
[self setAccessibilityLabel:@"大鱼调色检查器"];
[self setNeedsLayout:YES];
}
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[_brand release]; [_subtitle release]; [_resetAll release]; [_save release]; [_load release]; [_export release];
[_scroll release]; [_document release]; [_sections release]; [_cards release]; [_controls release]; [_assetButtons release]; [_graphics release]; [_sampler release];
[super dealloc];
}
- (BOOL)isFlipped { return YES; }
- (NSSize)intrinsicContentSize { return NSMakeSize(360,780); }
- (void)viewDidMoveToWindow { [super viewDidMoveToWindow]; if(self.window) [self refresh]; }
- (void)modelChanged:(NSNotification *)n {
if([NSThread isMainThread]) [self refresh];
else dispatch_async(dispatch_get_main_queue(),^{ [self refresh]; });
}
- (void)buildCards {
NSInteger index=0;
for(NSDictionary *section in _sections) {
DYCard *card=[[[DYCard alloc] initWithFrame:NSZeroRect] autorelease];
[_document addSubview:card];
DYHeader *header=[[[DYHeader alloc] initWithFrame:NSZeroRect] autorelease];
header.title=[@"▾ " stringByAppendingString:section[@"title"]?:@""];
header.bordered=NO; header.alignment=NSTextAlignmentLeft; header.font=[NSFont boldSystemFontOfSize:12];
header.contentTintColor=DYInk(); header.target=self; header.action=@selector(toggleSection:); header.tag=index;
header.doubleClickAction=@selector(resetSection:); header.toolTip=@"点击折叠;双击还原本组";
[card addSubview:header];
NSButton *enabled=[NSButton checkboxWithTitle:@"" target:self action:@selector(groupEnabled:)];
enabled.tag=index; enabled.contentTintColor=DYAccent(); enabled.toolTip=@"启用或旁路本组";
enabled.accessibilityLabel=[section[@"title"] stringByAppendingString:@"启用"];
[card addSubview:enabled]; enabled.hidden=section[@"enabled"]==nil;
NSButton *reset=DYButton(@"↺",self,@selector(resetSection:)); reset.tag=index;
reset.toolTip=@"还原本组"; reset.accessibilityLabel=[section[@"title"] stringByAppendingString:@"还原"];
[card addSubview:reset];
NSMutableArray *body=[NSMutableArray array];
NSString *key=section[@"key"]?:@"";
if([key localizedCaseInsensitiveContainsString:@"input"]) {
[body addObject:[self assetRowForKey:@"input" title:@"输入 LUT" inCard:card]];
}
if([key localizedCaseInsensitiveContainsString:@"look"]) {
for(NSInteger i=0;i<5;i++) {
NSString *slot=[NSString stringWithFormat:@"look%ld",(long)i];
[body addObject:[self assetRowForKey:slot title:[NSString stringWithFormat:@"风格 LUT %ld",(long)(i+1)] inCard:card]];
}
}
if([key isEqual:@"base"]) {
DYFlippedView *actions=[[[DYFlippedView alloc]initWithFrame:NSZeroRect]autorelease];actions.identifier=@"autoControls";
[actions addSubview:DYButton(@"自动调色",self,@selector(autoGrade:))];
[actions addSubview:DYButton(@"自动白平衡",self,@selector(autoWhiteBalance:))];
NSButton *picker=DYButton(@"白平衡吸管",self,@selector(sampleWhiteBalance:));picker.toolTip=@"在画面上吸取中性白色或灰色";[actions addSubview:picker];
[card addSubview:actions];[body addObject:actions];
}
if([key isEqual:@"hsl"]) {
DYFlippedView *actions=[[[DYFlippedView alloc]initWithFrame:NSZeroRect]autorelease];actions.identifier=@"sampleControls";
NSButton *picker=DYButton(@"吸取自定义 HSL 颜色",self,@selector(sampleCustomColor:));[actions addSubview:picker];[card addSubview:actions];[body addObject:actions];
}
if([key isEqual:@"curve"]) {
DYCurvePanel *graph=[[[DYCurvePanel alloc]initWithFrame:NSZeroRect]autorelease];graph.delegate=self;graph.identifier=@"curveGraph";[card addSubview:graph];[body addObject:graph];[_graphics addObject:graph];
}
if([key isEqual:@"grading"]) {
DYWheelPanel *wheels=[[[DYWheelPanel alloc]initWithFrame:NSZeroRect]autorelease];wheels.delegate=self;wheels.identifier=@"gradingWheels";[card addSubview:wheels];[body addObject:wheels];[_graphics addObject:wheels];
}
for(NSDictionary *d in section[@"rows"]) {
DYFlippedView *row=[[[DYFlippedView alloc] initWithFrame:NSZeroRect] autorelease];
[card addSubview:row]; [body addObject:row];
NSNumber *pid=d[@"pid"]; if(!pid)continue;
NSTextField *label=DYLabel(d[@"title"]?:d[@"key"],11); label.toolTip=d[@"title"];
[row addSubview:label];
NSMutableDictionary *record=[NSMutableDictionary dictionaryWithDictionary:@{@"descriptor":d,@"row":row,@"label":label}];
if(d[@"enabled"]) {
NSButton *eye=DYButton(@"",self,@selector(itemEnabled:));eye.bordered=NO;[eye setButtonType:NSButtonTypePushOnPushOff];eye.image=[NSImage imageWithSystemSymbolName:@"eye" accessibilityDescription:@"启用"];eye.tag=[pid integerValue];eye.contentTintColor=DYAccent();eye.accessibilityLabel=[d[@"title"] stringByAppendingString:@"启用"];eye.toolTip=@"启用或旁路此项";[row addSubview:eye];record[@"itemEnabled"]=eye;
}
NSString *kind=d[@"kind"]?:@"float";
if([kind isEqualToString:@"bool"]) {
NSButton *toggle=[NSButton checkboxWithTitle:@"" target:self action:@selector(scalarChanged:)];
toggle.tag=[pid integerValue]; toggle.contentTintColor=DYAccent(); toggle.accessibilityLabel=d[@"title"];
[row addSubview:toggle]; record[@"toggle"]=toggle;
} else if([kind isEqualToString:@"popup"]) {
NSPopUpButton *popup=[[[NSPopUpButton alloc] initWithFrame:NSZeroRect pullsDown:NO] autorelease];
[popup addItemsWithTitles:d[@"options"]?:@[]]; popup.font=[NSFont systemFontOfSize:11];
popup.target=self; popup.action=@selector(scalarChanged:); popup.tag=[pid integerValue];
popup.accessibilityLabel=d[@"title"]; [row addSubview:popup]; record[@"popup"]=popup;
} else {
NSSlider *slider=[[[NSSlider alloc]initWithFrame:NSZeroRect]autorelease];
DYBlueSliderCell *sliderCell=[[[DYBlueSliderCell alloc]init]autorelease];slider.cell=sliderCell;
slider.minValue=[d[@"min"]doubleValue];slider.maxValue=[d[@"max"]doubleValue];slider.doubleValue=[d[@"default"]doubleValue];slider.target=self;slider.action=@selector(scalarChanged:);
slider.tag=[pid integerValue]; slider.continuous=YES; slider.controlSize=NSControlSizeSmall;
slider.accessibilityLabel=d[@"title"]; [row addSubview:slider]; record[@"slider"]=slider;
NSTextField *field=[[[NSTextField alloc] initWithFrame:NSZeroRect] autorelease];
field.font=[NSFont monospacedDigitSystemFontOfSize:11 weight:NSFontWeightMedium];
field.textColor=DYInk(); field.backgroundColor=[NSColor colorWithSRGBRed:.08 green:.20 blue:.28 alpha:1];
field.bezeled=YES; field.bezelStyle=NSTextFieldRoundedBezel;
field.alignment=NSTextAlignmentRight; field.target=self; field.action=@selector(scalarChanged:);
field.tag=[pid integerValue]; field.accessibilityLabel=[d[@"title"] stringByAppendingString:@"数值"];
[row addSubview:field]; record[@"field"]=field;
}
NSButton *itemReset=DYButton(@"↺",self,@selector(resetScalar:));
itemReset.tag=[pid integerValue]; itemReset.toolTip=@"还原此项";
itemReset.accessibilityLabel=[d[@"title"] stringByAppendingString:@"还原"];
[row addSubview:itemReset]; record[@"reset"]=itemReset;
_controls[pid]=record;
}
[_cards addObject:[NSMutableDictionary dictionaryWithDictionary:@{@"section":section,@"view":card,@"header":header,@"enabled":enabled,@"reset":reset,@"body":body,@"collapsed":@NO}]];
index++;
}
}
- (NSView *)assetRowForKey:(NSString *)key title:(NSString *)title inCard:(NSView *)card {
DYFlippedView *row=[[[DYFlippedView alloc] initWithFrame:NSZeroRect] autorelease]; [card addSubview:row];
NSTextField *label=DYLabel(title,11); [row addSubview:label];
NSButton *choose=DYButton(@"无 · 点击选择…",self,@selector(chooseAsset:)); choose.identifier=key;
choose.alignment=NSTextAlignmentLeft; choose.accessibilityLabel=title; [row addSubview:choose];
NSButton *remove=DYButton(@"×",self,@selector(removeAsset:)); remove.identifier=key;
remove.toolTip=@"移除此 LUT"; remove.accessibilityLabel=[title stringByAppendingString:@"移除"]; [row addSubview:remove];
_assetButtons[key]=@{@"row":row,@"label":label,@"choose":choose,@"remove":remove};
return row;
}
- (void)layout {
[super layout];
CGFloat w=MAX(240,self.bounds.size.width),h=self.bounds.size.height;
_brand.frame=NSMakeRect(16,13,w-124,28); _subtitle.frame=NSMakeRect(17,43,w-124,16);
_resetAll.frame=NSMakeRect(w-101,23,86,28);
CGFloat gap=6,bw=(w-32-gap*2)/3;
_save.frame=NSMakeRect(16,66,bw,27); _load.frame=NSMakeRect(16+bw+gap,66,bw,27); _export.frame=NSMakeRect(16+(bw+gap)*2,66,bw,27);
_scroll.frame=NSMakeRect(0,104,w,MAX(80,h-104));
CGFloat cw=MAX(220,_scroll.contentSize.width-24),y=7;
for(NSMutableDictionary *c in _cards) {
DYCard *card=c[@"view"]; BOOL collapsed=[c[@"collapsed"] boolValue];
NSArray *body=c[@"body"];CGFloat contentHeight=0;
for(NSView *row in body)contentHeight+=[row.identifier isEqual:@"curveGraph"]?240:[row.identifier isEqual:@"gradingWheels"]?292:35;
CGFloat bh=collapsed?0:contentHeight+9;
card.frame=NSMakeRect(12,y,cw,43+bh); y+=card.frame.size.height+12;
[c[@"enabled"] setFrame:NSMakeRect(12,12,20,20)];
[c[@"header"] setFrame:NSMakeRect(36,8,cw-82,28)];
[c[@"reset"] setFrame:NSMakeRect(cw-39,10,27,24)];
CGFloat rowY=43;
for(NSView *row in body) {
CGFloat rh=[row.identifier isEqual:@"curveGraph"]?240:[row.identifier isEqual:@"gradingWheels"]?292:35;row.hidden=collapsed;row.frame=NSMakeRect(10,rowY,cw-20,rh-2);rowY+=rh;
if([row.identifier isEqual:@"autoControls"]||[row.identifier isEqual:@"sampleControls"]) {
CGFloat buttonWidth=(row.bounds.size.width-8-4*(row.subviews.count-1))/MAX((NSUInteger)1,row.subviews.count);NSInteger buttonIndex=0;
for(NSView *button in row.subviews)[button setFrame:NSMakeRect(4+(buttonWidth+4)*buttonIndex++,4,buttonWidth,26)];
}
}
}
for(NSDictionary *record in _controls.allValues) {
CGFloat rw=[record[@"row"] bounds].size.width;
CGFloat lw=MIN(111,MAX(76,rw*.34));
CGFloat eyeWidth=record[@"itemEnabled"]?20:0;
[record[@"itemEnabled"] setFrame:NSMakeRect(0,6,20,20)];
[record[@"label"] setFrame:NSMakeRect(5+eyeWidth,8,lw-eyeWidth,18)];
[record[@"reset"] setFrame:NSMakeRect(rw-27,5,25,24)];
if(record[@"toggle"]) [record[@"toggle"] setFrame:NSMakeRect(lw+12,6,45,22)];
if(record[@"popup"]) [record[@"popup"] setFrame:NSMakeRect(lw+8,5,rw-lw-41,25)];
if(record[@"slider"]) {
[record[@"slider"] setFrame:NSMakeRect(lw+8,8,MAX(25,rw-lw-103),18)];
[record[@"field"] setFrame:NSMakeRect(rw-88,5,57,24)];
}
}
for(NSDictionary *record in _assetButtons.allValues) {
CGFloat rw=[record[@"row"] bounds].size.width;
[record[@"label"] setFrame:NSMakeRect(5,8,88,18)];
[record[@"choose"] setFrame:NSMakeRect(95,4,MAX(80,rw-127),26)];
[record[@"remove"] setFrame:NSMakeRect(rw-27,5,25,24)];
}
[_document setFrameSize:NSMakeSize(_scroll.contentSize.width,MAX(y,_scroll.contentSize.height))];
}
- (id<FxCustomParameterActionAPI_v4>)actionAPI { return [_manager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)]; }
- (void)refresh {
if(_refreshing||!_manager)return;
id<FxCustomParameterActionAPI_v4> action=[self actionAPI]; if(!action)return;
_refreshing=YES;
[action startAction:self];
@try {
CMTime t=action.currentTime;
id<FxParameterRetrievalAPI_v6> get=[_manager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)];
NSMutableDictionary *graphicValues=[NSMutableDictionary dictionary];
for(NSNumber *pid in _controls) {
NSDictionary *r=_controls[pid],*d=r[@"descriptor"]; double v=[d[@"default"] doubleValue];
[get getFloatValue:&v fromParameter:pid.unsignedIntValue atTime:t];
if(!std::isfinite(v))v=[d[@"default"] doubleValue];
graphicValues[d[@"key"]]=@(v);
if(d[@"enabled"]) {double enabled=1;[get getFloatValue:&enabled fromParameter:[d[@"enabled"] unsignedIntValue] atTime:t];[r[@"itemEnabled"] setState:enabled>=.5?NSControlStateValueOn:NSControlStateValueOff];[r[@"itemEnabled"] setImage:[NSImage imageWithSystemSymbolName:enabled>=.5?@"eye":@"eye.slash" accessibilityDescription:enabled>=.5?@"启用":@"旁路"]];for(NSString *control in @[@"slider",@"field",@"popup"]) [r[control] setAlphaValue:enabled>=.5?1:.45];}
[r[@"slider"] setDoubleValue:v]; [r[@"field"] setStringValue:DYNumber(v,d)];
[r[@"toggle"] setState:v>=.5?NSControlStateValueOn:NSControlStateValueOff];
NSPopUpButton *popup=r[@"popup"]; if(popup.numberOfItems>0) [popup selectItemAtIndex:MAX(0,MIN((NSInteger)llround(v),popup.numberOfItems-1))];
}
for(id graphic in _graphics)[graphic setValues:graphicValues];
for(NSDictionary *c in _cards) {
NSNumber *pid=c[@"section"][@"enabled"];
double v=1;if(pid)[get getFloatValue:&v fromParameter:pid.unsignedIntValue atTime:t];
[c[@"enabled"] setState:v>=.5?NSControlStateValueOn:NSControlStateValueOff];
for(NSView *row in c[@"body"])row.alphaValue=v>=.5?1:.45;
}
DYAssetState *assets=DYReadAssets(_manager,t);
for(NSString *key in _assetButtons) {
NSString *path=assets.paths[key]; NSButton *button=_assetButtons[key][@"choose"];
button.title=path.length?path.lastPathComponent:@"无 · 点击选择…"; button.toolTip=path.length?path:@"选择 .cube 立体 LUT";
[_assetButtons[key][@"remove"] setEnabled:path.length>0];
}
} @finally { [action endAction:self]; _refreshing=NO; }
}
- (void)postChanged { [[NSNotificationCenter defaultCenter] postNotificationName:@"DYModelChanged" object:_manager]; }
- (void)scalarChanged:(NSControl *)sender {
if(_refreshing)return;
NSNumber *pid=@(sender.tag); NSDictionary *r=_controls[pid],*d=r[@"descriptor"]; if(!d)return;
double v;
if([sender isKindOfClass:[NSPopUpButton class]])v=[(NSPopUpButton *)sender indexOfSelectedItem];
else if([sender isKindOfClass:[NSButton class]])v=[(NSButton *)sender state]==NSControlStateValueOn?1:0;
else {
if([sender isKindOfClass:[NSTextField class]]) {
NSScanner *scanner=[NSScanner scannerWithString:sender.stringValue];
if(![scanner scanDouble:&v]||!scanner.isAtEnd||!std::isfinite(v)){NSBeep();[self refresh];return;}
} else v=sender.doubleValue;
}
v=fmax([d[@"min"] doubleValue],fmin([d[@"max"] doubleValue],v));
id<FxCustomParameterActionAPI_v4> action=[self actionAPI];if(!action)return;
[action startAction:self];
@try { id<FxParameterSettingAPI_v6> set=[_manager apiForProtocol:@protocol(FxParameterSettingAPI_v6)]; [set setFloatValue:v toParameter:pid.unsignedIntValue atTime:action.currentTime]; }
@finally { [action endAction:self]; }
[self postChanged];
}
- (void)resetScalar:(NSControl *)sender {
NSDictionary *r=_controls[@(sender.tag)],*d=r[@"descriptor"];if(!d)return;
id<FxCustomParameterActionAPI_v4> action=[self actionAPI];if(!action)return;
[action startAction:self];
@try {id<FxParameterSettingAPI_v6> set=[_manager apiForProtocol:@protocol(FxParameterSettingAPI_v6)];[set setFloatValue:[d[@"default"] doubleValue] toParameter:(UInt32)sender.tag atTime:action.currentTime];}
@finally {[action endAction:self];}
[self postChanged];
}
- (void)itemEnabled:(NSButton *)sender {
NSDictionary *d=_controls[@(sender.tag)][@"descriptor"];NSNumber *pid=d[@"enabled"];if(!pid)return;
id<FxCustomParameterActionAPI_v4> action=[self actionAPI];if(!action)return;
[action startAction:self];
@try {id<FxParameterSettingAPI_v6> set=[_manager apiForProtocol:@protocol(FxParameterSettingAPI_v6)];[set setFloatValue:sender.state==NSControlStateValueOn?1:0 toParameter:pid.unsignedIntValue atTime:action.currentTime];}
@finally {[action endAction:self];}
[self postChanged];
}
- (void)writeGraphicValues:(NSDictionary *)values {
NSMutableDictionary *byKey=[NSMutableDictionary dictionary];for(NSDictionary *d in DYDescriptors())byKey[d[@"key"]]=d;
id<FxCustomParameterActionAPI_v4> action=[self actionAPI];if(!action)return;
[action startAction:self];
@try {
CMTime t=action.currentTime;id<FxParameterSettingAPI_v6> set=[_manager apiForProtocol:@protocol(FxParameterSettingAPI_v6)];
for(NSString *key in values) {NSDictionary *d=byKey[key];double v=[values[key] doubleValue];if(!d||!std::isfinite(v))continue;v=fmax([d[@"min"]doubleValue],fmin([d[@"max"]doubleValue],v));[set setFloatValue:v toParameter:[d[@"pid"]unsignedIntValue] atTime:t];}
} @finally {[action endAction:self];}
[self postChanged];
}
- (void)groupEnabled:(NSButton *)sender {
if(sender.tag>=_cards.count)return;
NSNumber *pid=_cards[sender.tag][@"section"][@"enabled"];if(!pid)return;
id<FxCustomParameterActionAPI_v4> action=[self actionAPI];if(!action)return;
[action startAction:self];
@try {id<FxParameterSettingAPI_v6> set=[_manager apiForProtocol:@protocol(FxParameterSettingAPI_v6)];[set setFloatValue:sender.state==NSControlStateValueOn?1:0 toParameter:pid.unsignedIntValue atTime:action.currentTime];}
@finally {[action endAction:self];}
[self postChanged];
}
- (void)toggleSection:(NSButton *)sender {
if(sender.tag>=_cards.count)return;
NSMutableDictionary *card=_cards[sender.tag];BOOL collapsed=![card[@"collapsed"] boolValue];card[@"collapsed"]=@(collapsed);
sender.title=[(collapsed?@"▸ ":@"▾ ") stringByAppendingString:card[@"section"][@"title"]?:@""];
[self setNeedsLayout:YES];
}
- (void)resetSection:(NSButton *)sender {
if(sender.tag>=_cards.count)return;
NSDictionary *section=_cards[sender.tag][@"section"];
id<FxCustomParameterActionAPI_v4> action=[self actionAPI];if(!action)return;
[action startAction:self];
@try {
CMTime t=action.currentTime;id<FxParameterSettingAPI_v6> set=[_manager apiForProtocol:@protocol(FxParameterSettingAPI_v6)];
for(NSDictionary *d in section[@"rows"]) {[set setFloatValue:[d[@"default"] doubleValue] toParameter:[d[@"pid"] unsignedIntValue] atTime:t];if(d[@"enabled"])[set setFloatValue:1 toParameter:[d[@"enabled"] unsignedIntValue] atTime:t];}
NSNumber *enabled=section[@"enabled"];if(enabled)[set setFloatValue:1 toParameter:enabled.unsignedIntValue atTime:t];
NSString *key=section[@"key"]?:@"";
if([key localizedCaseInsensitiveContainsString:@"input"]||[key localizedCaseInsensitiveContainsString:@"look"]) {
DYAssetState *assets=[[DYReadAssets(_manager,t) copy] autorelease];
if(!assets)assets=[[[DYAssetState alloc] init] autorelease];
NSMutableDictionary *paths=[[assets.paths mutableCopy] autorelease];
if(!paths)paths=[NSMutableDictionary dictionary];
if([key localizedCaseInsensitiveContainsString:@"input"]) [paths removeObjectForKey:@"input"];
if([key localizedCaseInsensitiveContainsString:@"look"])for(NSInteger i=0;i<5;i++)[paths removeObjectForKey:[NSString stringWithFormat:@"look%ld",(long)i]];
assets.paths=paths;DYWriteAssets(_manager,assets,t);
}
} @finally {[action endAction:self];}
[self postChanged];
}
- (void)resetAll:(id)sender {
id<FxCustomParameterActionAPI_v4> action=[self actionAPI];if(!action)return;
[action startAction:self];
@try {
CMTime t=action.currentTime;id<FxParameterSettingAPI_v6> set=[_manager apiForProtocol:@protocol(FxParameterSettingAPI_v6)];
for(NSDictionary *d in DYDescriptors())[set setFloatValue:[d[@"default"] doubleValue] toParameter:[d[@"pid"] unsignedIntValue] atTime:t];
DYAssetState *assets=[[[DYAssetState alloc] init] autorelease];assets.paths=@{};DYWriteAssets(_manager,assets,t);
} @finally {[action endAction:self];}
[self postChanged];
}
- (void)chooseAsset:(NSButton *)sender {
NSOpenPanel *panel=[NSOpenPanel openPanel];panel.allowedFileTypes=@[@"cube"];panel.allowsMultipleSelection=NO;
panel.canChooseDirectories=NO;panel.message=@"选择 .cube 立体 LUT";
if([panel runModal]!=NSModalResponseOK)return;
[self setAssetPath:panel.URL.path forKey:sender.identifier];
}
- (void)removeAsset:(NSButton *)sender { [self setAssetPath:nil forKey:sender.identifier]; }
- (void)setAssetPath:(NSString *)path forKey:(NSString *)key {
id<FxCustomParameterActionAPI_v4> action=[self actionAPI];if(!action)return;
[action startAction:self];
@try {
CMTime t=action.currentTime;DYAssetState *assets=[[DYReadAssets(_manager,t) copy] autorelease];
if(!assets)assets=[[[DYAssetState alloc] init] autorelease];
NSMutableDictionary *paths=[[assets.paths mutableCopy] autorelease];if(!paths)paths=[NSMutableDictionary dictionary];
if(path.length)paths[key]=path;else [paths removeObjectForKey:key];
assets.paths=paths;DYWriteAssets(_manager,assets,t);
} @finally {[action endAction:self];}
[self postChanged];
}
- (void)showError:(NSString *)message {
NSAlert *a=[[[NSAlert alloc] init] autorelease];a.messageText=@"大鱼调色";a.informativeText=message?:@"操作未完成";[a addButtonWithTitle:@"好"];[a runModal];
}
- (NSDictionary *)presetSnapshot {
id<FxCustomParameterActionAPI_v4> action=[self actionAPI];if(!action)return nil;
NSMutableDictionary *values=[NSMutableDictionary dictionary];NSDictionary *paths=@{};
[action startAction:self];
@try {
CMTime t=action.currentTime;id<FxParameterRetrievalAPI_v6> get=[_manager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)];
for(NSDictionary *d in DYDescriptors()) {double v=[d[@"default"] doubleValue];[get getFloatValue:&v fromParameter:[d[@"pid"] unsignedIntValue] atTime:t];if(std::isfinite(v))values[d[@"key"]]=@(v);}
paths=[[DYReadAssets(_manager,t).paths copy] autorelease]?:@{};
} @finally {[action endAction:self];}
return @{@"format":@"com.dayu.color.preset",@"version":@1,@"values":values,@"paths":paths};
}
- (void)savePreset:(id)sender {
NSDictionary *snapshot=[self presetSnapshot];if(!snapshot)return;
NSSavePanel *panel=[NSSavePanel savePanel];panel.nameFieldStringValue=@"大鱼调色预设.json";panel.allowedFileTypes=@[@"json"];
if([panel runModal]!=NSModalResponseOK)return;
NSError *error=nil;NSData *data=[NSJSONSerialization dataWithJSONObject:snapshot options:NSJSONWritingPrettyPrinted error:&error];
if(!data||![data writeToURL:panel.URL options:NSDataWritingAtomic error:&error])[self showError:error.localizedDescription];
}
- (void)loadPreset:(id)sender {
NSOpenPanel *panel=[NSOpenPanel openPanel];panel.allowedFileTypes=@[@"json"];panel.allowsMultipleSelection=NO;panel.canChooseDirectories=NO;
if([panel runModal]!=NSModalResponseOK)return;
NSError *error=nil;NSData *data=[NSData dataWithContentsOfURL:panel.URL options:0 error:&error];
if(!data||data.length>2*1024*1024){[self showError:error.localizedDescription?:@"预设文件过大"];return;}
id json=[NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if(![json isKindOfClass:NSDictionary.class]||![json[@"format"] isEqual:@"com.dayu.color.preset"]||![json[@"version"] isEqual:@1]||![json[@"values"] isKindOfClass:NSDictionary.class]||![json[@"paths"] isKindOfClass:NSDictionary.class]){[self showError:@"这不是有效的大鱼调色预设。"];return;}
NSDictionary *values=json[@"values"],*paths=json[@"paths"];
for(NSDictionary *d in DYDescriptors()) {
id v=values[d[@"key"]];if(!v)continue;
if(![v isKindOfClass:NSNumber.class]||!std::isfinite([v doubleValue])||[v doubleValue]<[d[@"min"] doubleValue]||[v doubleValue]>[d[@"max"] doubleValue]){[self showError:@"预设包含无效参数,尚未修改当前调色。"];return;}
}
NSMutableDictionary *validPaths=[NSMutableDictionary dictionary];NSMutableArray *missing=[NSMutableArray array];
for(NSString *key in @[@"input",@"look0",@"look1",@"look2",@"look3",@"look4"]) {
id path=paths[key];if(!path)continue;
if(![path isKindOfClass:NSString.class]||![path isAbsolutePath]||![[path pathExtension].lowercaseString isEqual:@"cube"]){[self showError:@"预设包含无效 LUT 路径,尚未修改当前调色。"];return;}
if([[NSFileManager defaultManager] isReadableFileAtPath:path])validPaths[key]=path;else [missing addObject:[path lastPathComponent]];
}
id<FxCustomParameterActionAPI_v4> action=[self actionAPI];if(!action)return;
[action startAction:self];
@try {
CMTime t=action.currentTime;id<FxParameterSettingAPI_v6> set=[_manager apiForProtocol:@protocol(FxParameterSettingAPI_v6)];
for(NSDictionary *d in DYDescriptors())if(values[d[@"key"]])[set setFloatValue:[values[d[@"key"]] doubleValue] toParameter:[d[@"pid"] unsignedIntValue] atTime:t];
DYAssetState *assets=[[[DYAssetState alloc] init] autorelease];assets.paths=validPaths;DYWriteAssets(_manager,assets,t);
} @finally {[action endAction:self];}
[self postChanged];
if(missing.count)[self showError:[@"调色参数已恢复,以下 LUT 文件需要重新选择:\n" stringByAppendingString:[missing componentsJoinedByString:@"\n"]]];
}
- (void)autoGrade:(id)sender { [[NSNotificationCenter defaultCenter]postNotificationName:@"DYAutoGrade" object:_manager]; }
- (void)autoWhiteBalance:(id)sender { [[NSNotificationCenter defaultCenter]postNotificationName:@"DYAutoWhiteBalance" object:_manager]; }
- (void)sampleWhiteBalance:(id)sender { [self sampleColorForWhiteBalance:YES]; }
- (void)sampleCustomColor:(id)sender { [self sampleColorForWhiteBalance:NO]; }
- (void)sampleColorForWhiteBalance:(BOOL)whiteBalance {
if(_sampler)return;
_sampler=[[NSColorSampler alloc]init];
[_sampler showSamplerWithSelectionHandler:^(NSColor *selectedColor) {
NSColor *color=[selectedColor colorUsingColorSpace:NSColorSpace.sRGBColorSpace];
if(color) {
if(whiteBalance)[[NSNotificationCenter defaultCenter]postNotificationName:@"DYWhiteBalanceColor" object:_manager userInfo:@{@"color":color}];
else [self writeGraphicValues:@{@"sample0":@(color.redComponent),@"sample1":@(color.greenComponent),@"sample2":@(color.blueComponent)}];
}
[_sampler release];_sampler=nil;
}];
}
- (void)exportLUT:(id)sender {
NSSavePanel *panel=[NSSavePanel savePanel];panel.allowedFileTypes=@[@"cube"];panel.nameFieldStringValue=@"大鱼调色.cube";
panel.message=@"导出仅包含逐像素调色。纹理、清晰度和画面分析无法保存到 .cube LUT。";
if([panel runModal]!=NSModalResponseOK)return;
[[NSNotificationCenter defaultCenter] postNotificationName:@"DYExportLUT" object:_manager userInfo:@{@"url":panel.URL}];
}
@end
+19
查看文件
@@ -0,0 +1,19 @@
#import <AppKit/AppKit.h>
#import <FxPlug/FxPlugSDK.h>
#import "DYUniforms.h"
enum { DYInspectorParameterID=9000, DYAssetsParameterID=9001 };
FOUNDATION_EXPORT NSString *const DYModelChanged;
FOUNDATION_EXPORT NSArray<NSDictionary*> *DYSections(void);
FOUNDATION_EXPORT NSArray<NSDictionary*> *DYDescriptors(void);
FOUNDATION_EXPORT void DYDefaultUniforms(DYUniforms *u);
FOUNDATION_EXPORT BOOL DYCreateParameters(id<PROAPIAccessing> manager,NSError **error);
FOUNDATION_EXPORT void DYReadUniforms(id<PROAPIAccessing> manager,CMTime time,DYUniforms *u);
@interface DYAssetState : NSObject<NSSecureCoding,NSCopying,FxCustomParameterInterpolation_v2>
@property(copy) NSDictionary *paths;
@end
@interface DYInspectorToken : NSObject<NSSecureCoding,NSCopying,FxCustomParameterInterpolation_v2>
@end
FOUNDATION_EXPORT DYAssetState *DYReadAssets(id<PROAPIAccessing> manager,CMTime time);
FOUNDATION_EXPORT BOOL DYWriteAssets(id<PROAPIAccessing> manager,DYAssetState *assets,CMTime time);
+82
查看文件
@@ -0,0 +1,82 @@
#import "DYModel.h"
#include <cmath>
NSString *const DYModelChanged=@"DYModelChanged";
static NSMutableArray *sections,*descriptors;
static UInt32 PID(NSUInteger offset){return 2000+(UInt32)offset/4;}
static NSDictionary *row(NSString*k,NSString*t,NSUInteger o,double lo,double hi,double d,NSString*kind){
NSMutableDictionary*r=[@{@"key":k,@"title":t,@"pid":@(PID(o)),@"offset":@(o),@"min":@(lo),@"max":@(hi),@"default":@(d),@"step":@(hi-lo>10?1:.01),@"kind":kind?:@"float"}mutableCopy];
[descriptors addObject:r];return [r autorelease];
}
static void section(NSString*k,NSString*t,NSUInteger offset,NSArray*rows,double def=1){
NSDictionary*e=row([k stringByAppendingString:@"Enabled"],t,offset,0,1,def,@"bool");
[sections addObject:@{@"key":k,@"title":t,@"enabled":e[@"pid"],@"rows":rows}];
}
static NSDictionary *scalar(NSString*k,NSString*t,NSUInteger o,double lo=-100,double hi=100,double def=0){return row(k,t,o,lo,hi,def,@"float");}
static void initialize(){static dispatch_once_t once;dispatch_once(&once,^{
sections=[[NSMutableArray alloc]init];descriptors=[[NSMutableArray alloc]init];
NSMutableDictionary*profile=[[scalar(@"inputProfile",@"相机输入",52,0,17)mutableCopy]autorelease];profile[@"kind"]=@"popup";profile[@"options"]=@[@"无",@"Apple Log",@"ARRI LogC3",@"ARRI LogC4",@"Blackmagic Film Gen5",@"Canon C-Log",@"Canon C-Log2",@"Canon C-Log3",@"DJI D-Log",@"DJI D-Log M",@"Fujifilm F-Log",@"Fujifilm F-Log2",@"Nikon N-Log",@"Panasonic V-Log",@"RED Log3G10",@"Sony S-Log2",@"Sony S-Log3",@"Sony HLG"];
[descriptors replaceObjectAtIndex:0 withObject:profile];
section(@"input",@"输入 / LUT",132,@[profile,scalar(@"preLUTStrength",@"输入强度",56,0,1,1)]);
NSMutableArray*base=[NSMutableArray array];
NSArray*names=@[@"曝光",@"对比度",@"高光",@"阴影",@"白色色阶",@"黑色色阶",@"色温",@"色调",@"饱和度",@"鲜艳度",@"纹理",@"清晰度",@"去朦胧"];
NSArray*keys=@[@"exposure",@"contrast",@"highlights",@"shadows",@"whites",@"blacks",@"temperature",@"tint",@"saturation",@"vibrance",@"texture",@"clarity",@"dehaze"];
for(NSUInteger i=0;i<keys.count;i++){
NSMutableDictionary*r=[[scalar(keys[i],names[i],i*4,i==0?-5:-100,i==0?5:100)mutableCopy]autorelease];
NSDictionary*e=row([keys[i]stringByAppendingString:@"Enabled"],[names[i]stringByAppendingString:@" 启用"],80+i*4,0,1,1,@"bool");r[@"enabled"]=e[@"pid"];
[descriptors replaceObjectAtIndex:[descriptors indexOfObjectPassingTest:^BOOL(id obj,NSUInteger idx,BOOL*stop){return [obj[@"key"]isEqual:keys[i]];}] withObject:r];[base addObject:r];
}
section(@"base",@"基础调色",136,[base subarrayWithRange:NSMakeRange(0,8)]);
section(@"color",@"颜色",140,@[base[9],base[8],base[10],base[11],base[12],row(@"skinProtection",@"肤色保护",464,0,1,0,@"bool"),scalar(@"skinHueRange",@"肤色色相范围",468,5,100,40),scalar(@"skinChromaRange",@"肤色饱和度范围",472,5,100,40)]);
NSMutableArray*look=[NSMutableArray arrayWithObject:scalar(@"postLUTStrength",@"风格 1 强度",60,0,1,1)];
for(int i=0;i<4;i++){[look addObject:row([NSString stringWithFormat:@"look%dEnabled",i+2],[NSString stringWithFormat:@"风格 %d 启用",i+2],160+i*4,0,1,1,@"bool")];[look addObject:scalar([NSString stringWithFormat:@"look%dStrength",i+2],[NSString stringWithFormat:@"风格 %d 强度",i+2],64+i*4,0,1,1)];}
section(@"look",@"风格 LUT",144,look);
NSMutableArray*curves=[NSMutableArray array];
NSArray*cn=@[@"主曲线 阴影",@"主曲线 暗部",@"主曲线 亮部",@"主曲线 高光",@"红曲线 阴影",@"红曲线 高光",@"绿曲线 阴影",@"绿曲线 高光",@"蓝曲线 阴影",@"蓝曲线 高光"];
for(int i=0;i<10;i++)[curves addObject:scalar([NSString stringWithFormat:@"curveY%d",i],cn[i],184+i*4)];
for(int i=0;i<4;i++)[curves addObject:scalar([NSString stringWithFormat:@"masterX%d",i],[NSString stringWithFormat:@"主曲线 点%d X",i+1],224+i*4,-1,1,-1)];
for(int c=0;c<3;c++)for(int i=0;i<2;i++)[curves addObject:scalar([NSString stringWithFormat:@"channel%dX%d",c,i],[NSString stringWithFormat:@"%@曲线 点%d X",@[@"红",@"绿",@"蓝"][c],i+1],240+c*8+i*4,-1,1,-1)];
for(int c=0;c<4;c++)for(int i=0;i<4;i++){NSUInteger off=816+c*32;[curves addObject:scalar([NSString stringWithFormat:@"curve%dExtra%d",c,i],[NSString stringWithFormat:@"%@ 扩展点%d 偏移",@[@"主",@"红",@"绿",@"蓝"][c],i+1],off+i*4)];[curves addObject:scalar([NSString stringWithFormat:@"curve%dExtraX%d",c,i],[NSString stringWithFormat:@"%@ 扩展点%d X",@[@"主",@"红",@"绿",@"蓝"][c],i+1],off+16+i*4,-1,1,-1)];}
section(@"curve",@"曲线",176,curves);
NSMutableArray*hsl=[NSMutableArray array];NSArray*colors=@[@"红",@"橙",@"黄",@"绿",@"青",@"蓝",@"紫",@"洋红"];
for(int a=0;a<3;a++)for(int c=0;c<8;c++)[hsl addObject:scalar([NSString stringWithFormat:@"hsl%d_%d",a,c],[NSString stringWithFormat:@"%@ %@",colors[c],@[@"色相",@"饱和度",@"明亮度"][a]],272+a*32+c*4)];
for(int i=0;i<3;i++){[hsl addObject:scalar([NSString stringWithFormat:@"sample%d",i],[NSString stringWithFormat:@"自定义色 %@",@[@"R",@"G",@"B"][i]],368+i*4,0,1,i==0?1:i==1?.1:.58)];[hsl addObject:scalar([NSString stringWithFormat:@"custom%d",i],[NSString stringWithFormat:@"自定义 %@",@[@"色相",@"饱和度",@"明亮度"][i]],384+i*4)];[hsl addObject:scalar([NSString stringWithFormat:@"range%d",i],[NSString stringWithFormat:@"自定义 %@范围",@[@"色相",@"饱和度",@"明亮度"][i]],560+i*4,5,i==0?180:100,i==0?30:40)];}
[hsl addObject:row(@"hslVisualize",@"显示自定义色选区",576,0,1,0,@"bool")];section(@"hsl",@"HSL 混色",180,hsl);
NSMutableArray*grade=[NSMutableArray array];
for(int c=0;c<4;c++){NSString*n=@[@"阴影",@"中间调",@"高光",@"全局"][c];int pair=c==0?424:c==1?416:c==2?432:592;int lum=c==0?452:c==1?448:c==2?456:600;
for(int a=0;a<3;a++)[grade addObject:scalar([NSString stringWithFormat:@"grade%d_%d",c,a],[NSString stringWithFormat:@"%@ %@",n,@[@"色相",@"饱和度",@"明亮度"][a]],a==2?lum:pair+a*4,a==2?-100:0,a==0?360:100)];}
[grade addObject:scalar(@"gradingBlending",@"混合",404,0,100,50)];[grade addObject:scalar(@"gradingBalance",@"平衡",408)];section(@"grading",@"颜色分级",400,grade);
NSMutableArray*prim=[NSMutableArray array];for(int c=0;c<3;c++)for(int a=0;a<2;a++)[prim addObject:scalar([NSString stringWithFormat:@"primary%d_%d",c,a],[NSString stringWithFormat:@"%@原色 %@",@[@"红",@"绿",@"蓝"][c],a?@"饱和度":@"色相"],484+c*8+a*4)];section(@"primaries",@"三原色",480,prim);
NSMutableArray*levels=[NSMutableArray array];for(int c=0;c<4;c++)for(int a=0;a<5;a++)[levels addObject:scalar([NSString stringWithFormat:@"level%d_%d",c,a],[NSString stringWithFormat:@"%@ %@",@[@"RGB",@"红",@"绿",@"蓝"][c],@[@"输入黑",@"伽马",@"输入白",@"输出黑",@"输出白"][a]],624+a*16+c*4,a==1?.1:0,a==1?10:255,a==1?1:(a==2||a==4)?255:0)];section(@"levels",@"色阶",608,levels);
NSMutableArray*bw=[NSMutableArray array];for(int c=0;c<6;c++)[bw addObject:scalar([NSString stringWithFormat:@"bw%d",c],[NSString stringWithFormat:@"黑白 %@",@[@"红",@"黄",@"绿",@"青",@"蓝",@"洋红"][c]],c<4?720+c*4:736+(c-4)*4,0,200,100)];[bw addObject:scalar(@"bwHue",@"着色色相",744,0,360)];[bw addObject:scalar(@"bwSat",@"着色饱和度",748,0,100)];section(@"blackwhite",@"黑白混色",704,bw,0);
NSMutableArray*balance=[NSMutableArray arrayWithObject:row(@"preserveLuma",@"保持明度",756,0,1,1,@"bool")];for(int c=0;c<3;c++)for(int a=0;a<3;a++)[balance addObject:scalar([NSString stringWithFormat:@"balance%d_%d",c,a],[NSString stringWithFormat:@"%@ %@",@[@"阴影",@"中间调",@"高光"][c],@[@"青 ↔ 红",@"洋红 ↔ 绿",@"黄 ↔ 蓝"][a]],768+c*16+a*4)];section(@"balance",@"色彩平衡",752,balance);
});}
NSArray *DYSections(){initialize();return sections;} NSArray *DYDescriptors(){initialize();return descriptors;}
void DYDefaultUniforms(DYUniforms*u){memset(u,0,sizeof(*u));for(NSDictionary*r in DYDescriptors())*(float*)((uint8_t*)u+[r[@"offset"]unsignedIntegerValue])=[r[@"default"]floatValue];u->primariesM0=(DYFloat3){1,0,0};u->primariesM1=(DYFloat3){0,1,0};u->primariesM2=(DYFloat3){0,0,1};}
void DYReadUniforms(id<PROAPIAccessing>m,CMTime t,DYUniforms*u){DYDefaultUniforms(u);id<FxParameterRetrievalAPI_v6>g=[m apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)];for(NSDictionary*r in DYDescriptors()){double v=[r[@"default"]doubleValue];if([g getFloatValue:&v fromParameter:[r[@"pid"]unsignedIntValue] atTime:t]&&std::isfinite(v))*(float*)((uint8_t*)u+[r[@"offset"]unsignedIntegerValue])=fmin([r[@"max"]doubleValue],fmax([r[@"min"]doubleValue],v));}}
BOOL DYCreateParameters(id<PROAPIAccessing>m,NSError**error){id<FxParameterCreationAPI_v5>a=[m apiForProtocol:@protocol(FxParameterCreationAPI_v5)];BOOL ok=a!=nil;
ok=[a addCustomParameterWithName:@"大鱼调色" parameterID:DYInspectorParameterID defaultValue:[[[DYInspectorToken alloc]init]autorelease] parameterFlags:kFxParameterFlag_CUSTOM_UI|kFxParameterFlag_USE_FULL_VIEW_WIDTH|kFxParameterFlag_DONT_DISPLAY_IN_DASHBOARD|kFxParameterFlag_NOT_ANIMATABLE]&&ok;
for(NSDictionary*r in DYDescriptors())ok=[a addFloatSliderWithName:r[@"title"] parameterID:[r[@"pid"]unsignedIntValue] defaultValue:[r[@"default"]doubleValue] parameterMin:[r[@"min"]doubleValue] parameterMax:[r[@"max"]doubleValue] sliderMin:[r[@"min"]doubleValue] sliderMax:[r[@"max"]doubleValue] delta:[r[@"step"]doubleValue] parameterFlags:kFxParameterFlag_HIDDEN]&&ok;
ok=[a addCustomParameterWithName:@"LUT 文件" parameterID:DYAssetsParameterID defaultValue:[[[DYAssetState alloc]init]autorelease] parameterFlags:kFxParameterFlag_HIDDEN|kFxParameterFlag_NOT_ANIMATABLE]&&ok;
if(!ok&&error)*error=[NSError errorWithDomain:FxPlugErrorDomain code:kFxError_InvalidParameter userInfo:@{NSLocalizedDescriptionKey:@"无法创建大鱼调色参数"}];return ok;}
@implementation DYAssetState
+ (BOOL)supportsSecureCoding{return YES;}
- (instancetype)init{if((self=[super init]))_paths=[@{}copy];return self;}
- (void)dealloc{[_paths release];[super dealloc];}
- (void)encodeWithCoder:(NSCoder*)c{[c encodeObject:_paths forKey:@"paths"];}
- (instancetype)initWithCoder:(NSCoder*)c{if((self=[self init])){NSSet*s=[NSSet setWithObjects:NSDictionary.class,NSString.class,nil];NSDictionary*d=[c decodeObjectOfClasses:s forKey:@"paths"];if(d)self.paths=d;}return self;}
- (id)copyWithZone:(NSZone*)z{DYAssetState*v=[[[self class]allocWithZone:z]init];v.paths=_paths;return v;}
- (id)interpolateBetween:(id)r withWeight:(float)w{return w<.5?[[self copy]autorelease]:[[r copy]autorelease];}
- (BOOL)isEqual:(id)o{return [o isKindOfClass:self.class]&&[_paths isEqual:[o paths]];}
- (NSUInteger)hash{return _paths.hash;}
@end
@implementation DYInspectorToken
+ (BOOL)supportsSecureCoding{return YES;}
- (void)encodeWithCoder:(NSCoder*)c{[c encodeInt:1 forKey:@"schema"];}
- (instancetype)initWithCoder:(NSCoder*)c{return [self init];}
- (id)copyWithZone:(NSZone*)z{return [[[self class]allocWithZone:z]init];}
- (id)interpolateBetween:(id)r withWeight:(float)w{return [[self copy]autorelease];}
- (BOOL)isEqual:(id)o{return [o isKindOfClass:self.class];}
- (NSUInteger)hash{return 1;}
@end
DYAssetState*DYReadAssets(id<PROAPIAccessing>m,CMTime t){DYAssetState*v=nil;id<FxParameterRetrievalAPI_v6>g=[m apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)];[g getCustomParameterValue:&v fromParameter:DYAssetsParameterID atTime:t];return [v isKindOfClass:DYAssetState.class]?v:[[[DYAssetState alloc]init]autorelease];}
BOOL DYWriteAssets(id<PROAPIAccessing>m,DYAssetState*v,CMTime t){id<FxParameterSettingAPI_v6>s=[m apiForProtocol:@protocol(FxParameterSettingAPI_v6)];return [s setCustomParameterValue:v toParameter:DYAssetsParameterID atTime:t];}
+4
查看文件
@@ -0,0 +1,4 @@
#import <FxPlug/FxPlugSDK.h>
@interface DYPlugIn : NSObject<FxTileableEffect,FxCustomParameterViewHost_v2>
@property(assign) id<PROAPIAccessing> apiManager;
@end
+32
查看文件
@@ -0,0 +1,32 @@
#import "DYPlugIn.h"
#import "DYModel.h"
#import "DYRenderer.h"
#import "DYInspector.h"
#import "DYColorTables.h"
#import "DYAutoGrade.h"
@implementation DYPlugIn {
DYRenderer *_renderer;
}
- (instancetype)initWithAPIManager:(id<PROAPIAccessing>)manager{if((self=[super init])){_apiManager=manager;_renderer=[DYRenderer new];NSNotificationCenter*n=NSNotificationCenter.defaultCenter;[n addObserver:self selector:@selector(exportRequested:) name:@"DYExportLUT" object:manager];[n addObserver:self selector:@selector(autoRequested:) name:@"DYAutoGrade" object:manager];[n addObserver:self selector:@selector(autoRequested:) name:@"DYAutoWhiteBalance" object:manager];[n addObserver:self selector:@selector(whiteBalanceRequested:) name:@"DYWhiteBalanceColor" object:manager];}return self;}
- (void)dealloc{[NSNotificationCenter.defaultCenter removeObserver:self];[_renderer release];[super dealloc];}
- (BOOL)properties:(NSDictionary**)p error:(NSError**)e{*p=@{kFxPropertyKey_MayRemapTime:@NO,kFxPropertyKey_PixelTransformSupport:@(kFxPixelTransform_ScaleTranslate),kFxPropertyKey_VariesWhenParamsAreStatic:@NO,kFxPropertyKey_DesiredProcessingColorInfo:@(kFxImageColorInfo_RGB_LINEAR),kFxPropertyKey_NeedsFullBuffer:@YES};return YES;}
- (BOOL)addParametersWithError:(NSError**)e{return DYCreateParameters(_apiManager,e);}
- (NSSet<Class>*)classesForCustomParameterID:(UInt32)pid{return pid==DYAssetsParameterID?[NSSet setWithObjects:DYAssetState.class,NSDictionary.class,NSString.class,nil]:[NSSet setWithObject:DYInspectorToken.class];}
- (NSView*)createViewForParameterID:(UInt32)pid{return pid==DYInspectorParameterID?[[DYInspector alloc]initWithAPIManager:_apiManager]:[[NSView alloc]initWithFrame:NSZeroRect];}
- (BOOL)parameterChanged:(UInt32)pid atTime:(CMTime)t error:(NSError**)e{dispatch_async(dispatch_get_main_queue(),^{[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:self.apiManager];});return YES;}
- (BOOL)pluginState:(NSData**)state atTime:(CMTime)t quality:(FxQuality)q error:(NSError**)e{
DYUniforms u;DYReadUniforms(_apiManager,t,&u);DYAssetState*a=DYReadAssets(_apiManager,t);NSDictionary*s=@{@"schema":@1,@"uniforms":[NSData dataWithBytes:&u length:sizeof(u)],@"paths":a.paths?:@{}};*state=[NSPropertyListSerialization dataWithPropertyList:s format:NSPropertyListBinaryFormat_v1_0 options:0 error:e];return *state!=nil;
}
- (BOOL)destinationImageRect:(FxRect*)rect sourceImages:(NSArray<FxImageTile*>*)src destinationImage:(FxImageTile*)dst pluginState:(NSData*)s atTime:(CMTime)t error:(NSError**)e{if(!src.count)return NO;*rect=src[0].imagePixelBounds;return YES;}
- (BOOL)sourceTileRect:(FxRect*)rect sourceImageIndex:(NSUInteger)i sourceImages:(NSArray<FxImageTile*>*)src destinationTileRect:(FxRect)dstRect destinationImage:(FxImageTile*)dst pluginState:(NSData*)s atTime:(CMTime)t error:(NSError**)e{if(i>=src.count)return NO;*rect=src[i].imagePixelBounds;return YES;}
- (BOOL)renderDestinationImage:(FxImageTile*)dst sourceImages:(NSArray<FxImageTile*>*)src pluginState:(NSData*)s atTime:(CMTime)t error:(NSError**)e{
if(!src.count||!src[0].ioSurface||!dst.ioSurface||!s.length)return NO;NSDictionary*p=[NSPropertyListSerialization propertyListWithData:s options:NSPropertyListImmutable format:NULL error:e];NSData*b=p[@"uniforms"];if(![p isKindOfClass:NSDictionary.class]||![p[@"schema"]isEqual:@1]||![b isKindOfClass:NSData.class]||b.length!=sizeof(DYUniforms)||![p[@"paths"]isKindOfClass:NSDictionary.class])return NO;DYUniforms u;[b getBytes:&u length:sizeof(u)];return [_renderer renderSource:src[0] destination:dst uniforms:u paths:p[@"paths"] error:e];
}
- (void)alert:(NSString*)message{dispatch_async(dispatch_get_main_queue(),^{NSAlert*a=[NSAlert new];a.messageText=@"大鱼调色";a.informativeText=message?:@"操作未完成";[a runModal];[a release];});}
- (void)exportRequested:(NSNotification*)n{
NSURL*url=n.userInfo[@"url"];if(![url isKindOfClass:NSURL.class])return;id<FxCustomParameterActionAPI_v4>a=[_apiManager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];[a startAction:self];DYUniforms u;DYReadUniforms(_apiManager,a.currentTime,&u);NSDictionary*paths=[DYReadAssets(_apiManager,a.currentTime).paths copy];[a endAction:self];NSError*e=nil;BOOL ok=[_renderer exportLUT:url uniforms:u paths:paths error:&e];[paths release];if(!ok)[self alert:e.localizedDescription];
}
- (void)applyValues:(NSDictionary*)values{if(!values){[self alert:@"尚未拿到当前片段画面,请移动播放头后重试。"];return;}id<FxCustomParameterActionAPI_v4>a=[_apiManager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];[a startAction:self];@try{id<FxParameterSettingAPI_v6>s=[_apiManager apiForProtocol:@protocol(FxParameterSettingAPI_v6)];for(NSDictionary*r in DYDescriptors()){NSNumber*v=values[r[@"key"]];if(v)[s setFloatValue:v.doubleValue toParameter:[r[@"pid"]unsignedIntValue] atTime:a.currentTime];}}@finally{[a endAction:self];}[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:_apiManager];}
- (void)autoRequested:(NSNotification*)n{NSData*frame=[_renderer preview];[self applyValues:[n.name isEqual:@"DYAutoGrade"]?DYAutoGrade(frame):DYAutoWhiteBalance(frame)];}
- (void)whiteBalanceRequested:(NSNotification*)n{NSColor*c=[n.userInfo[@"color"]colorUsingColorSpace:NSColorSpace.sRGBColorSpace];if(!c)return;float temp=0,tint=0;if([DYColorTables neutralizeColor:(vector_float3){(float)c.redComponent,(float)c.greenComponent,(float)c.blueComponent} temperature:&temp tint:&tint])[self applyValues:@{@"temperature":@(temp),@"tint":@(tint)}];else [self alert:@"所选颜色过暗,请选择白色或中性灰区域。"];}
@end
+9
查看文件
@@ -0,0 +1,9 @@
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
#import <FxPlug/FxPlugSDK.h>
#import "DYUniforms.h"
@interface DYRenderer : NSObject
- (BOOL)renderSource:(FxImageTile*)source destination:(FxImageTile*)destination uniforms:(DYUniforms)uniforms paths:(NSDictionary*)paths error:(NSError**)error;
- (BOOL)exportLUT:(NSURL*)url uniforms:(DYUniforms)uniforms paths:(NSDictionary*)paths error:(NSError**)error;
- (NSData*)preview;
@end
+89
查看文件
@@ -0,0 +1,89 @@
#import "DYRenderer.h"
#import "DYColorTables.h"
#import <QuartzCore/QuartzCore.h>
#include <zlib.h>
#include <vector>
#include <cmath>
static BOOL fail(NSError**e,NSString*m){if(e)*e=[NSError errorWithDomain:@"com.dayu.color" code:1 userInfo:@{NSLocalizedDescriptionKey:m?:@"Metal 调色失败"}];return NO;}
static NSArray *inputFiles(){return @[@"",@"apple_log_to_rec709",@"arri_logc3_to_rec709",@"arri_logc4_to_rec709",@"blackmagic_film_gen5_to_rec709",@"canon_clog_bt709_to_rec709",@"canon_clog2_cinema_gamut_to_rec709",@"canon_clog3_cinema_gamut_to_rec709",@"dji_dlog_to_rec709",@"dji_dlog_m_to_rec709",@"fujifilm_flog_to_rec709",@"fujifilm_flog2_to_rec709",@"nikon_nlog_to_rec709",@"panasonic_vlog_vgamut_to_rec709",@"red_log3g10_rwg_to_rec709",@"sony_slog2_sgamut_to_rec709",@"sony_slog3_sgamut3cine_to_rec709",@"sony_hlg_bt2020_to_rec709"];}
static id<MTLTexture> texture3D(id<MTLDevice>d,const float*values,NSUInteger n){MTLTextureDescriptor*t=[MTLTextureDescriptor new];t.textureType=MTLTextureType3D;t.pixelFormat=MTLPixelFormatRGBA32Float;t.width=n;t.height=n;t.depth=n;t.storageMode=MTLStorageModeShared;t.usage=MTLTextureUsageShaderRead;id<MTLTexture>x=[d newTextureWithDescriptor:t];[t release];if(x)[x replaceRegion:MTLRegionMake3D(0,0,0,n,n,n) mipmapLevel:0 slice:0 withBytes:values bytesPerRow:n*16 bytesPerImage:n*n*16];return [x autorelease];}
static BOOL loadCube(NSString*path,std::vector<float>&data,NSUInteger&size,NSError**err){
NSData*b=[NSData dataWithContentsOfFile:path options:NSDataReadingMappedIfSafe error:err];if(!b)return NO;
if([path.pathExtension.lowercaseString isEqual:@"dylut"]){
if(b.length<36||memcmp(b.bytes,"DYLT",4))return fail(err,@"输入 LUT 格式损坏");uint32_t n=0,bytes=0;memcpy(&n,(uint8_t*)b.bytes+4,4);memcpy(&bytes,(uint8_t*)b.bytes+8,4);if(n<2||n>128||bytes!=n*n*n*16)return fail(err,@"输入 LUT 尺寸无效");data.resize(bytes/4);uLongf len=bytes;if(uncompress((Bytef*)data.data(),&len,(Bytef*)b.bytes+36,b.length-36)!=Z_OK||len!=bytes)return fail(err,@"输入 LUT 解压失败");size=n;return YES;
}
NSString*s=[[[NSString alloc]initWithData:b encoding:NSUTF8StringEncoding]autorelease];if(!s)return fail(err,@"LUT 必须是 UTF-8 文本");
size=0;float domainMin[3]={0,0,0},domainMax[3]={1,1,1};
for(NSString*line in [s componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]){
NSString*clean=[[[line componentsSeparatedByString:@"#"]firstObject]stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];if(!clean.length)continue;
const char*c=clean.UTF8String;int n=0;float r,g,bl;
if(sscanf(c,"LUT_3D_SIZE %d",&n)==1){if(n<2||n>128)return fail(err,@"LUT 尺寸应为 2–128");size=n;}
else if(sscanf(c,"DOMAIN_MIN %f %f %f",&r,&g,&bl)==3){domainMin[0]=r;domainMin[1]=g;domainMin[2]=bl;}
else if(sscanf(c,"DOMAIN_MAX %f %f %f",&r,&g,&bl)==3){domainMax[0]=r;domainMax[1]=g;domainMax[2]=bl;}
else if(sscanf(c,"%f %f %f",&r,&g,&bl)==3){if(!std::isfinite(r)||!std::isfinite(g)||!std::isfinite(bl))return fail(err,@"LUT 含无效数字");data.insert(data.end(),{r,g,bl,1});if(data.size()>128*128*128*4)return fail(err,@"LUT 数据过多");}
else if([clean hasPrefix:@"LUT_1D_SIZE"])return fail(err,@"请选择三维 .cube LUT");
}
if(size<2||data.size()!=size*size*size*4)return fail(err,@"LUT 数据数量与尺寸不符");
bool resample=false;for(int c=0;c<3;c++){if(!std::isfinite(domainMin[c])||!std::isfinite(domainMax[c])||domainMax[c]<=domainMin[c])return fail(err,@"LUT DOMAIN 范围无效");resample|=domainMin[c]!=0||domainMax[c]!=1;}
if(resample){std::vector<float>src=data;for(NSUInteger z=0;z<size;z++)for(NSUInteger y=0;y<size;y++)for(NSUInteger x=0;x<size;x++){float v[3];NSUInteger i[3];NSUInteger pos[3]={x,y,z};for(int c=0;c<3;c++){v[c]=fminf(1,fmaxf(0,(float(pos[c])/(size-1)-domainMin[c])/(domainMax[c]-domainMin[c])))*(size-1);i[c]=fmin(size-2,(NSUInteger)v[c]);v[c]-=i[c];}size_t dest=((z*size+y)*size+x)*4;for(int c=0;c<3;c++){float sum=0;for(int k=0;k<8;k++){int a=k&1,b=(k>>1)&1,d=(k>>2)&1;sum+=src[(((i[2]+d)*size+i[1]+b)*size+i[0]+a)*4+c]*(a?v[0]:1-v[0])*(b?v[1]:1-v[1])*(d?v[2]:1-v[2]);}data[dest+c]=sum;}}}
return YES;
}
@interface DYRenderer(){
NSMutableDictionary *_devices,*_luts;
DYColorTables *_tables;
NSData *_preview;
CFTimeInterval _lastPreview;
}
@end
@implementation DYRenderer
- (instancetype)init{if((self=[super init])){_devices=[NSMutableDictionary new];_luts=[NSMutableDictionary new];_tables=[DYColorTables new];}return self;}
- (void)dealloc{[_devices release];[_luts release];[_tables release];[_preview release];[super dealloc];}
- (NSData*)preview{@synchronized(self){return [[_preview retain]autorelease];}}
- (NSMutableDictionary*)device:(uint64_t)registry error:(NSError**)err{
NSNumber*k=@(registry);NSMutableDictionary*entry=_devices[k];if(entry)return entry;
id<MTLDevice>d=nil;NSArray*all=MTLCopyAllDevices();for(id<MTLDevice>candidate in all)if(candidate.registryID==registry||!registry){d=[candidate retain];break;}[all release];if(!d){fail(err,@"宿主的 Metal 设备不可用");return nil;}
NSURL*url=[[NSBundle bundleForClass:self.class]URLForResource:@"default" withExtension:@"metallib"];
id<MTLLibrary>lib=[d newLibraryWithURL:url error:err];if(!lib){[d release];return nil;}
id<MTLCommandQueue>q=[d newCommandQueue];entry=[NSMutableDictionary dictionaryWithDictionary:@{@"device":d,@"library":lib,@"queue":q,@"pipelines":[NSMutableDictionary dictionary]}];
for(NSString*fn in @[@"dyUnpremultiply",@"dyWhitesSceneStatistics",@"dyLUTExportKernel",@"dyPreview"]){id<MTLFunction>f=[lib newFunctionWithName:fn];if(!f){fail(err,[fn stringByAppendingString:@" 缺失"]);[lib release];[q release];[d release];return nil;}id<MTLComputePipelineState>p=[d newComputePipelineStateWithFunction:f error:err];[f release];if(!p){[lib release];[q release];[d release];return nil;}entry[fn]=p;[p release];}
float identity[32];for(int z=0;z<2;z++)for(int y=0;y<2;y++)for(int x=0;x<2;x++){int i=((z*2+y)*2+x)*4;identity[i]=x;identity[i+1]=y;identity[i+2]=z;identity[i+3]=1;}id<MTLTexture>neutral=texture3D(d,identity,2);if(!neutral){fail(err,@"无法分配中性 LUT");return nil;}entry[@"identity"]=neutral;
_devices[k]=entry;[d release];[lib release];[q release];return entry;
}
- (id<MTLTexture>)lut:(NSString*)path entry:(NSDictionary*)e error:(NSError**)err{
if(!path.length)return e[@"identity"];
NSDictionary*attrs=[[NSFileManager defaultManager]attributesOfItemAtPath:path error:err];if(!attrs)return nil;
NSString*key=[NSString stringWithFormat:@"%llu|%@|%@|%@",[e[@"device"]registryID],path,attrs[NSFileModificationDate],attrs[NSFileSize]];id<MTLTexture>t=_luts[key];if(t)return t;
std::vector<float>v;NSUInteger n=0;if(!loadCube(path,v,n,err))return nil;t=texture3D(e[@"device"],v.data(),n);if(!t){fail(err,@"LUT 纹理分配失败");return nil;}if(_luts.count>=12)[_luts removeAllObjects];_luts[key]=t;return t;
}
- (NSArray*)textures:(NSDictionary*)paths uniforms:(DYUniforms*)u entry:(NSDictionary*)e error:(NSError**)err{
NSString*input=paths[@"input"];int profile=(int)roundf(u->inputProfile);
if(!input.length&&profile>0&&profile<(int)inputFiles().count)input=[[NSBundle bundleForClass:self.class]pathForResource:inputFiles()[profile] ofType:@"dylut" inDirectory:@"InputLUTs"];
if(profile>0&&!input.length){fail(err,@"相机输入转换资源缺失");return nil;}
NSMutableArray*ts=[NSMutableArray array];id<MTLTexture>t=[self lut:input entry:e error:err];if(!t)return nil;[ts addObject:t];if(!input.length)u->preLUTStrength=0;
for(int i=0;i<5;i++){NSString*p=paths[[NSString stringWithFormat:@"look%d",i]];t=[self lut:p entry:e error:err];if(!t)return nil;[ts addObject:t];if(!p.length){if(i==0)u->postLUTStrength=0;else u->extraPostLUTStrengths[i-1]=0;}}
[DYColorTables fillPrimaries:u];id<MTLDevice>d=e[@"device"];
id<MTLTexture>h=[_tables hslForDevice:d uniforms:u],w=[_tables whiteBalanceForDevice:d uniforms:u],g=[_tables gradingForDevice:d uniforms:u];if(!h||!w||!g){fail(err,@"颜色查表构建失败");return nil;}[ts addObjectsFromArray:@[h,w,g]];return ts;
}
- (BOOL)renderSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths error:(NSError**)err{@synchronized(self){@autoreleasepool{
NSMutableDictionary*e=[self device:dst.deviceRegistryID error:err];if(!e)return NO;id<MTLDevice>d=e[@"device"];id<MTLTexture>input=[src metalTextureForDevice:d],output=[dst metalTextureForDevice:d];if(!input||!output)return fail(err,@"宿主图像纹理不可用");
NSArray*ts=[self textures:paths uniforms:&u entry:e error:err];if(!ts)return NO;
NSMutableDictionary*ps=e[@"pipelines"];NSNumber*format=@(output.pixelFormat);id<MTLRenderPipelineState>pipeline=ps[format];if(!pipeline){MTLRenderPipelineDescriptor*p=[MTLRenderPipelineDescriptor new];p.vertexFunction=[e[@"library"]newFunctionWithName:@"dyVertex"];p.fragmentFunction=[e[@"library"]newFunctionWithName:@"dyFragment"];p.colorAttachments[0].pixelFormat=output.pixelFormat;pipeline=[d newRenderPipelineStateWithDescriptor:p error:err];[p.vertexFunction release];[p.fragmentFunction release];[p release];if(!pipeline)return NO;ps[format]=pipeline;[pipeline release];}
MTLTextureDescriptor*td=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA16Float width:input.width height:input.height mipmapped:NO];td.storageMode=MTLStorageModePrivate;td.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite;id<MTLTexture>straight=[d newTextureWithDescriptor:td];if(!straight)return fail(err,@"无法分配调色缓冲区");
id<MTLCommandBuffer>cb=[e[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyUnpremultiply"]];[ce setTexture:input atIndex:0];[ce setTexture:straight atIndex:1];[ce dispatchThreads:MTLSizeMake(input.width,input.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];
float level=.5;id<MTLBuffer>scene=[d newBufferWithBytes:&level length:4 options:MTLResourceStorageModeShared];
if(u.whites>0&&u.whitesEnabled>.5&&u.baseSectionEnabled>.5){ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyWhitesSceneStatistics"]];[ce setTexture:straight atIndex:0];[ce setTexture:ts[7] atIndex:1];[ce setBytes:&u length:sizeof(u) atIndex:0];[ce setBuffer:scene offset:0 atIndex:1];[ce dispatchThreadgroups:MTLSizeMake(1,1,1) threadsPerThreadgroup:MTLSizeMake(256,1,1)];[ce endEncoding];}
BOOL preview=CACurrentMediaTime()-_lastPreview>.5;id<MTLBuffer>pb=nil;if(preview){pb=[d newBufferWithLength:64*64*16 options:MTLResourceStorageModeShared];ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyPreview"]];[ce setTexture:straight atIndex:0];[ce setBuffer:pb offset:0 atIndex:0];[ce dispatchThreads:MTLSizeMake(64,64,1) threadsPerThreadgroup:MTLSizeMake(8,8,1)];[ce endEncoding];}
MTLRenderPassDescriptor*rp=[MTLRenderPassDescriptor renderPassDescriptor];rp.colorAttachments[0].texture=output;rp.colorAttachments[0].loadAction=MTLLoadActionDontCare;rp.colorAttachments[0].storeAction=MTLStoreActionStore;id<MTLRenderCommandEncoder>re=[cb renderCommandEncoderWithDescriptor:rp];[re setRenderPipelineState:pipeline];
float w=output.width,h=output.height;FxRect s=src.tilePixelBounds,t=dst.tilePixelBounds;float sw=s.right-s.left,sh=s.top-s.bottom;float l=(t.left-s.left)/sw,r=(t.right-s.left)/sw,top=(s.top-t.top)/sh,bottom=(s.top-t.bottom)/sh;
if(src.imageOrigin==kFxImageOrigin_BOTTOM_LEFT){top=1-top;bottom=1-bottom;}
DYVertex2D vs[]={{{w/2,-h/2},{r,bottom}},{{-w/2,-h/2},{l,bottom}},{{w/2,h/2},{r,top}},{{-w/2,h/2},{l,top}}};
if(dst.imageOrigin==kFxImageOrigin_BOTTOM_LEFT)for(int i=0;i<4;i++)vs[i].position.y=-vs[i].position.y;
vector_uint2 vp={(unsigned)output.width,(unsigned)output.height};[re setVertexBytes:vs length:sizeof(vs) atIndex:0];[re setVertexBytes:&vp length:sizeof(vp) atIndex:1];[re setViewport:(MTLViewport){0,0,w,h,0,1}];[re setFragmentTexture:straight atIndex:0];for(NSUInteger i=0;i<ts.count;i++)[re setFragmentTexture:ts[i] atIndex:i+1];[re setFragmentBytes:&u length:sizeof(u) atIndex:0];[re setFragmentBuffer:scene offset:0 atIndex:1];DYRenderOptions options={1,0,0,0};[re setFragmentBytes:&options length:sizeof(options) atIndex:2];[re drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4];[re endEncoding];[cb commit];[cb waitUntilCompleted];BOOL ok=cb.status==MTLCommandBufferStatusCompleted;
if(ok&&pb){[_preview release];_preview=[[NSData alloc]initWithBytes:pb.contents length:64*64*16];_lastPreview=CACurrentMediaTime();}
if(!ok)fail(err,cb.error.localizedDescription);[pb release];[straight release];[scene release];return ok;
}}}
- (BOOL)exportLUT:(NSURL*)url uniforms:(DYUniforms)u paths:(NSDictionary*)paths error:(NSError**)err{@synchronized(self){
NSMutableDictionary*e=[self device:0 error:err];if(!e)return NO;NSArray*ts=[self textures:paths uniforms:&u entry:e error:err];if(!ts)return NO;id<MTLDevice>d=e[@"device"];uint32_t n=33;NSUInteger count=n*n*n;id<MTLBuffer>out=[d newBufferWithLength:count*3*4 options:MTLResourceStorageModeShared];if(!out)return fail(err,@"无法分配 LUT 输出");id<MTLCommandBuffer>cb=[e[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyLUTExportKernel"]];for(NSUInteger i=0;i<ts.count;i++)[ce setTexture:ts[i] atIndex:i];[ce setBytes:&u length:sizeof(u) atIndex:0];[ce setBuffer:out offset:0 atIndex:1];[ce setBytes:&n length:4 atIndex:2];[ce dispatchThreads:MTLSizeMake(count,1,1) threadsPerThreadgroup:MTLSizeMake(64,1,1)];[ce endEncoding];[cb commit];[cb waitUntilCompleted];if(cb.status!=MTLCommandBufferStatusCompleted){[out release];return fail(err,cb.error.localizedDescription);}
NSMutableString*s=[NSMutableString stringWithString:@"TITLE \"大鱼调色\"\n# 仅包含逐像素颜色;纹理、清晰度和画面分析不写入 LUT。\nLUT_3D_SIZE 33\nDOMAIN_MIN 0 0 0\nDOMAIN_MAX 1 1 1\n"];float*v=(float*)out.contents;for(NSUInteger i=0;i<count;i++){if(!std::isfinite(v[i*3])||!std::isfinite(v[i*3+1])||!std::isfinite(v[i*3+2])){[out release];return fail(err,@"LUT GPU 输出含无效值");}[s appendFormat:@"%.8f %.8f %.8f\n",v[i*3],v[i*3+1],v[i*3+2]];}[out release];return [s writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:err];
}}
@end
+240
查看文件
@@ -0,0 +1,240 @@
// Stable CPU/Metal ABI, reconstructed from shipped reflection. See tools/kernels/PROVENANCE.json.
#pragma once
#ifdef __METAL_VERSION__
#include <metal_stdlib>
typedef metal::float2 DYFloat2;
typedef metal::float3 DYFloat3;
typedef metal::float4 DYFloat4;
typedef metal::uint DYUInt;
#else
#include <simd/simd.h>
#include <stddef.h>
#include <stdint.h>
typedef vector_float2 DYFloat2;
typedef vector_float3 DYFloat3;
typedef vector_float4 DYFloat4;
typedef uint32_t DYUInt;
#endif
typedef struct DYUniforms {
float exposure; // offset 0
float contrast; // offset 4
float highlights; // offset 8
float shadows; // offset 12
float whites; // offset 16
float blacks; // offset 20
float temperature; // offset 24
float tint; // offset 28
float saturation; // offset 32
float vibrance; // offset 36
float texture; // offset 40
float clarity; // offset 44
float dehaze; // offset 48
float inputProfile; // offset 52
float preLUTStrength; // offset 56
float postLUTStrength; // offset 60
DYFloat4 extraPostLUTStrengths; // offset 64
float exposureEnabled; // offset 80
float contrastEnabled; // offset 84
float highlightsEnabled; // offset 88
float shadowsEnabled; // offset 92
float whitesEnabled; // offset 96
float blacksEnabled; // offset 100
float temperatureEnabled; // offset 104
float tintEnabled; // offset 108
float saturationEnabled; // offset 112
float vibranceEnabled; // offset 116
float textureEnabled; // offset 120
float clarityEnabled; // offset 124
float dehazeEnabled; // offset 128
float inputSectionEnabled; // offset 132
float baseSectionEnabled; // offset 136
float colorSectionEnabled; // offset 140
float lookSectionEnabled; // offset 144
DYFloat4 extraLookSectionEnableds; // offset 160
float curveSectionEnabled; // offset 176
float hslSectionEnabled; // offset 180
float curveShadows; // offset 184
float curveDarks; // offset 188
float curveLights; // offset 192
float curveHighlights; // offset 196
float redCurveShadows; // offset 200
float redCurveHighlights; // offset 204
float greenCurveShadows; // offset 208
float greenCurveHighlights; // offset 212
float blueCurveShadows; // offset 216
float blueCurveHighlights; // offset 220
DYFloat4 curveX; // offset 224
DYFloat2 redCurveX; // offset 240
DYFloat2 greenCurveX; // offset 248
DYFloat2 blueCurveX; // offset 256
DYFloat4 hslHueA; // offset 272
DYFloat4 hslHueB; // offset 288
DYFloat4 hslSatA; // offset 304
DYFloat4 hslSatB; // offset 320
DYFloat4 hslLumA; // offset 336
DYFloat4 hslLumB; // offset 352
DYFloat3 hslCustomSample; // offset 368
DYFloat3 hslCustomAdjust; // offset 384
float colorGradingSectionEnabled; // offset 400
float colorGradingBlending; // offset 404
float colorGradingBalance; // offset 408
DYFloat4 colorGradingHueSatA; // offset 416
DYFloat4 colorGradingHueSatB; // offset 432
DYFloat3 colorGradingLuma; // offset 448
DYFloat3 skinProtection; // offset 464
float primariesSectionEnabled; // offset 480
float redPrimaryHue; // offset 484
float redPrimarySaturation; // offset 488
float greenPrimaryHue; // offset 492
float greenPrimarySaturation; // offset 496
float bluePrimaryHue; // offset 500
float bluePrimarySaturation; // offset 504
DYFloat3 primariesM0; // offset 512
DYFloat3 primariesM1; // offset 528
DYFloat3 primariesM2; // offset 544
DYFloat3 hslCustomRange; // offset 560
float hslCustomVisualize; // offset 576
DYFloat3 colorGradingGlobal; // offset 592
float levelsSectionEnabled; // offset 608
DYFloat4 levelsInputBlack; // offset 624
DYFloat4 levelsGamma; // offset 640
DYFloat4 levelsInputWhite; // offset 656
DYFloat4 levelsOutputBlack; // offset 672
DYFloat4 levelsOutputWhite; // offset 688
float blackWhiteSectionEnabled; // offset 704
DYFloat4 blackWhiteMixA; // offset 720
DYFloat2 blackWhiteMixB; // offset 736
DYFloat2 blackWhiteTint; // offset 744
float colorBalanceSectionEnabled; // offset 752
float colorBalancePreserveLuminosity; // offset 756
DYFloat3 colorBalanceShadows; // offset 768
DYFloat3 colorBalanceMidtones; // offset 784
DYFloat3 colorBalanceHighlights; // offset 800
DYFloat4 curveExtra; // offset 816
DYFloat4 curveExtraX; // offset 832
DYFloat4 redCurveExtra; // offset 848
DYFloat4 redCurveExtraX; // offset 864
DYFloat4 greenCurveExtra; // offset 880
DYFloat4 greenCurveExtraX; // offset 896
DYFloat4 blueCurveExtra; // offset 912
DYFloat4 blueCurveExtraX; // offset 928
} DYUniforms;
typedef struct DYVertex2D { DYFloat2 position; DYFloat2 textureCoordinate; } DYVertex2D;
typedef struct DYRenderOptions {
DYUInt outputPremultiplied;
DYUInt reserved[3];
} DYRenderOptions;
#ifndef __METAL_VERSION__
#if defined(__cplusplus)
#define DY_ABI_ASSERT static_assert
#else
#define DY_ABI_ASSERT _Static_assert
#endif
DY_ABI_ASSERT(sizeof(DYUniforms) == 944, "DYUniforms must match recovered GPU ABI");
DY_ABI_ASSERT(offsetof(DYUniforms, exposure) == 0, "exposure offset");
DY_ABI_ASSERT(offsetof(DYUniforms, contrast) == 4, "contrast offset");
DY_ABI_ASSERT(offsetof(DYUniforms, highlights) == 8, "highlights offset");
DY_ABI_ASSERT(offsetof(DYUniforms, shadows) == 12, "shadows offset");
DY_ABI_ASSERT(offsetof(DYUniforms, whites) == 16, "whites offset");
DY_ABI_ASSERT(offsetof(DYUniforms, blacks) == 20, "blacks offset");
DY_ABI_ASSERT(offsetof(DYUniforms, temperature) == 24, "temperature offset");
DY_ABI_ASSERT(offsetof(DYUniforms, tint) == 28, "tint offset");
DY_ABI_ASSERT(offsetof(DYUniforms, saturation) == 32, "saturation offset");
DY_ABI_ASSERT(offsetof(DYUniforms, vibrance) == 36, "vibrance offset");
DY_ABI_ASSERT(offsetof(DYUniforms, texture) == 40, "texture offset");
DY_ABI_ASSERT(offsetof(DYUniforms, clarity) == 44, "clarity offset");
DY_ABI_ASSERT(offsetof(DYUniforms, dehaze) == 48, "dehaze offset");
DY_ABI_ASSERT(offsetof(DYUniforms, inputProfile) == 52, "inputProfile offset");
DY_ABI_ASSERT(offsetof(DYUniforms, preLUTStrength) == 56, "preLUTStrength offset");
DY_ABI_ASSERT(offsetof(DYUniforms, postLUTStrength) == 60, "postLUTStrength offset");
DY_ABI_ASSERT(offsetof(DYUniforms, extraPostLUTStrengths) == 64, "extraPostLUTStrengths offset");
DY_ABI_ASSERT(offsetof(DYUniforms, exposureEnabled) == 80, "exposureEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, contrastEnabled) == 84, "contrastEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, highlightsEnabled) == 88, "highlightsEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, shadowsEnabled) == 92, "shadowsEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, whitesEnabled) == 96, "whitesEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, blacksEnabled) == 100, "blacksEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, temperatureEnabled) == 104, "temperatureEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, tintEnabled) == 108, "tintEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, saturationEnabled) == 112, "saturationEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, vibranceEnabled) == 116, "vibranceEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, textureEnabled) == 120, "textureEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, clarityEnabled) == 124, "clarityEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, dehazeEnabled) == 128, "dehazeEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, inputSectionEnabled) == 132, "inputSectionEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, baseSectionEnabled) == 136, "baseSectionEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, colorSectionEnabled) == 140, "colorSectionEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, lookSectionEnabled) == 144, "lookSectionEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, extraLookSectionEnableds) == 160, "extraLookSectionEnableds offset");
DY_ABI_ASSERT(offsetof(DYUniforms, curveSectionEnabled) == 176, "curveSectionEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, hslSectionEnabled) == 180, "hslSectionEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, curveShadows) == 184, "curveShadows offset");
DY_ABI_ASSERT(offsetof(DYUniforms, curveDarks) == 188, "curveDarks offset");
DY_ABI_ASSERT(offsetof(DYUniforms, curveLights) == 192, "curveLights offset");
DY_ABI_ASSERT(offsetof(DYUniforms, curveHighlights) == 196, "curveHighlights offset");
DY_ABI_ASSERT(offsetof(DYUniforms, redCurveShadows) == 200, "redCurveShadows offset");
DY_ABI_ASSERT(offsetof(DYUniforms, redCurveHighlights) == 204, "redCurveHighlights offset");
DY_ABI_ASSERT(offsetof(DYUniforms, greenCurveShadows) == 208, "greenCurveShadows offset");
DY_ABI_ASSERT(offsetof(DYUniforms, greenCurveHighlights) == 212, "greenCurveHighlights offset");
DY_ABI_ASSERT(offsetof(DYUniforms, blueCurveShadows) == 216, "blueCurveShadows offset");
DY_ABI_ASSERT(offsetof(DYUniforms, blueCurveHighlights) == 220, "blueCurveHighlights offset");
DY_ABI_ASSERT(offsetof(DYUniforms, curveX) == 224, "curveX offset");
DY_ABI_ASSERT(offsetof(DYUniforms, redCurveX) == 240, "redCurveX offset");
DY_ABI_ASSERT(offsetof(DYUniforms, greenCurveX) == 248, "greenCurveX offset");
DY_ABI_ASSERT(offsetof(DYUniforms, blueCurveX) == 256, "blueCurveX offset");
DY_ABI_ASSERT(offsetof(DYUniforms, hslHueA) == 272, "hslHueA offset");
DY_ABI_ASSERT(offsetof(DYUniforms, hslHueB) == 288, "hslHueB offset");
DY_ABI_ASSERT(offsetof(DYUniforms, hslSatA) == 304, "hslSatA offset");
DY_ABI_ASSERT(offsetof(DYUniforms, hslSatB) == 320, "hslSatB offset");
DY_ABI_ASSERT(offsetof(DYUniforms, hslLumA) == 336, "hslLumA offset");
DY_ABI_ASSERT(offsetof(DYUniforms, hslLumB) == 352, "hslLumB offset");
DY_ABI_ASSERT(offsetof(DYUniforms, hslCustomSample) == 368, "hslCustomSample offset");
DY_ABI_ASSERT(offsetof(DYUniforms, hslCustomAdjust) == 384, "hslCustomAdjust offset");
DY_ABI_ASSERT(offsetof(DYUniforms, colorGradingSectionEnabled) == 400, "colorGradingSectionEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, colorGradingBlending) == 404, "colorGradingBlending offset");
DY_ABI_ASSERT(offsetof(DYUniforms, colorGradingBalance) == 408, "colorGradingBalance offset");
DY_ABI_ASSERT(offsetof(DYUniforms, colorGradingHueSatA) == 416, "colorGradingHueSatA offset");
DY_ABI_ASSERT(offsetof(DYUniforms, colorGradingHueSatB) == 432, "colorGradingHueSatB offset");
DY_ABI_ASSERT(offsetof(DYUniforms, colorGradingLuma) == 448, "colorGradingLuma offset");
DY_ABI_ASSERT(offsetof(DYUniforms, skinProtection) == 464, "skinProtection offset");
DY_ABI_ASSERT(offsetof(DYUniforms, primariesSectionEnabled) == 480, "primariesSectionEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, redPrimaryHue) == 484, "redPrimaryHue offset");
DY_ABI_ASSERT(offsetof(DYUniforms, redPrimarySaturation) == 488, "redPrimarySaturation offset");
DY_ABI_ASSERT(offsetof(DYUniforms, greenPrimaryHue) == 492, "greenPrimaryHue offset");
DY_ABI_ASSERT(offsetof(DYUniforms, greenPrimarySaturation) == 496, "greenPrimarySaturation offset");
DY_ABI_ASSERT(offsetof(DYUniforms, bluePrimaryHue) == 500, "bluePrimaryHue offset");
DY_ABI_ASSERT(offsetof(DYUniforms, bluePrimarySaturation) == 504, "bluePrimarySaturation offset");
DY_ABI_ASSERT(offsetof(DYUniforms, primariesM0) == 512, "primariesM0 offset");
DY_ABI_ASSERT(offsetof(DYUniforms, primariesM1) == 528, "primariesM1 offset");
DY_ABI_ASSERT(offsetof(DYUniforms, primariesM2) == 544, "primariesM2 offset");
DY_ABI_ASSERT(offsetof(DYUniforms, hslCustomRange) == 560, "hslCustomRange offset");
DY_ABI_ASSERT(offsetof(DYUniforms, hslCustomVisualize) == 576, "hslCustomVisualize offset");
DY_ABI_ASSERT(offsetof(DYUniforms, colorGradingGlobal) == 592, "colorGradingGlobal offset");
DY_ABI_ASSERT(offsetof(DYUniforms, levelsSectionEnabled) == 608, "levelsSectionEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, levelsInputBlack) == 624, "levelsInputBlack offset");
DY_ABI_ASSERT(offsetof(DYUniforms, levelsGamma) == 640, "levelsGamma offset");
DY_ABI_ASSERT(offsetof(DYUniforms, levelsInputWhite) == 656, "levelsInputWhite offset");
DY_ABI_ASSERT(offsetof(DYUniforms, levelsOutputBlack) == 672, "levelsOutputBlack offset");
DY_ABI_ASSERT(offsetof(DYUniforms, levelsOutputWhite) == 688, "levelsOutputWhite offset");
DY_ABI_ASSERT(offsetof(DYUniforms, blackWhiteSectionEnabled) == 704, "blackWhiteSectionEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, blackWhiteMixA) == 720, "blackWhiteMixA offset");
DY_ABI_ASSERT(offsetof(DYUniforms, blackWhiteMixB) == 736, "blackWhiteMixB offset");
DY_ABI_ASSERT(offsetof(DYUniforms, blackWhiteTint) == 744, "blackWhiteTint offset");
DY_ABI_ASSERT(offsetof(DYUniforms, colorBalanceSectionEnabled) == 752, "colorBalanceSectionEnabled offset");
DY_ABI_ASSERT(offsetof(DYUniforms, colorBalancePreserveLuminosity) == 756, "colorBalancePreserveLuminosity offset");
DY_ABI_ASSERT(offsetof(DYUniforms, colorBalanceShadows) == 768, "colorBalanceShadows offset");
DY_ABI_ASSERT(offsetof(DYUniforms, colorBalanceMidtones) == 784, "colorBalanceMidtones offset");
DY_ABI_ASSERT(offsetof(DYUniforms, colorBalanceHighlights) == 800, "colorBalanceHighlights offset");
DY_ABI_ASSERT(offsetof(DYUniforms, curveExtra) == 816, "curveExtra offset");
DY_ABI_ASSERT(offsetof(DYUniforms, curveExtraX) == 832, "curveExtraX offset");
DY_ABI_ASSERT(offsetof(DYUniforms, redCurveExtra) == 848, "redCurveExtra offset");
DY_ABI_ASSERT(offsetof(DYUniforms, redCurveExtraX) == 864, "redCurveExtraX offset");
DY_ABI_ASSERT(offsetof(DYUniforms, greenCurveExtra) == 880, "greenCurveExtra offset");
DY_ABI_ASSERT(offsetof(DYUniforms, greenCurveExtraX) == 896, "greenCurveExtraX offset");
DY_ABI_ASSERT(offsetof(DYUniforms, blueCurveExtra) == 912, "blueCurveExtra offset");
DY_ABI_ASSERT(offsetof(DYUniforms, blueCurveExtraX) == 928, "blueCurveExtraX offset");
#undef DY_ABI_ASSERT
#endif
+6 -6
查看文件
@@ -5,7 +5,7 @@
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>____XPCService</string>
<string>大鱼调色</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
@@ -17,7 +17,7 @@
<key>CFBundlePackageType</key>
<string>XPC!</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<string>1.0.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>NSHumanReadableCopyright</key>
@@ -48,7 +48,7 @@
<array>
<dict>
<key>groupName</key>
<string>大鱼调色 Group</string>
<string>大鱼调色</string>
<key>uuid</key>
<string>19E2727A-6BCD-4656-B270-7E2BF482A692</string>
</dict>
@@ -57,13 +57,13 @@
<array>
<dict>
<key>className</key>
<string>____PlugIn</string>
<string>DYPlugIn</string>
<key>displayName</key>
<string>____::FxPlug Name</string>
<string>大鱼调色</string>
<key>group</key>
<string>19E2727A-6BCD-4656-B270-7E2BF482A692</string>
<key>infoString</key>
<string>____::FxPlug Description</string>
<string>输入转换、光影、曲线、HSL 与风格调色</string>
<key>protocolNames</key>
<array>
<string>FxFilter</string>
-28
查看文件
@@ -1,28 +0,0 @@
//
// MetalDeviceCache.h
// 大鱼调色
//
// Created by mac on 2026/10/31.
//
#import <Metal/Metal.h>
#import <FxPlug/FxPlugSDK.h>
@class MetalDeviceCacheItem;
@interface MetalDeviceCache : NSObject
{
NSMutableArray<MetalDeviceCacheItem*>* deviceCaches;
}
+ (MetalDeviceCache*)deviceCache;
+ (MTLPixelFormat)MTLPixelFormatForImageTile:(FxImageTile*)imageTile;
- (id<MTLDevice>)deviceWithRegistryID:(uint64_t)registryID;
- (id<MTLRenderPipelineState>)pipelineStateWithRegistryID:(uint64_t)registryID
pixelFormat:(MTLPixelFormat)pixFormat;
- (id<MTLCommandQueue>)commandQueueWithRegistryID:(uint64_t)registryID
pixelFormat:(MTLPixelFormat)pixFormat;
- (void)returnCommandQueueToCache:(id<MTLCommandQueue>)commandQueue;
@end
-339
查看文件
@@ -1,339 +0,0 @@
//
// MetalDeviceCache.m
// 大鱼调色
//
// Created by mac on 2026/10/31.
//
#import "MetalDeviceCache.h"
const NSUInteger kMaxCommandQueues = 5;
static NSString* kKey_InUse = @"InUse";
static NSString* kKey_CommandQueue = @"CommandQueue";
static MetalDeviceCache* gDeviceCache = nil;
@interface MetalDeviceCacheItem : NSObject
@property (readonly) id<MTLDevice> gpuDevice;
@property (readonly) id<MTLRenderPipelineState> pipelineState;
@property (retain) NSMutableArray<NSMutableDictionary*>* commandQueueCache;
@property (readonly) NSLock* commandQueueCacheLock;
@property (readonly) MTLPixelFormat pixelFormat;
- (instancetype)initWithDevice:(id<MTLDevice>)device
pixelFormat:(MTLPixelFormat)pixFormat;
- (id<MTLCommandQueue>)getNextFreeCommandQueue;
- (void)returnCommandQueue:(id<MTLCommandQueue>)commandQueue;
- (BOOL)containsCommandQueue:(id<MTLCommandQueue>)commandQueue;
@end
@implementation MetalDeviceCacheItem
- (instancetype)initWithDevice:(id<MTLDevice>)device
pixelFormat:(MTLPixelFormat)pixFormat;
{
self = [super init];
if (self != nil)
{
_gpuDevice = [device retain];
_commandQueueCache = [[NSMutableArray alloc] initWithCapacity:kMaxCommandQueues];
for (NSUInteger i = 0; (_commandQueueCache != nil) && (i < kMaxCommandQueues); i++)
{
NSMutableDictionary* commandDict = [NSMutableDictionary dictionary];
[commandDict setObject:[NSNumber numberWithBool:NO]
forKey:kKey_InUse];
id<MTLCommandQueue> commandQueue = [_gpuDevice newCommandQueue];
[commandDict setObject:commandQueue
forKey:kKey_CommandQueue];
[_commandQueueCache addObject:commandDict];
}
// Load all the shader files with a .metal file extension in the project
id<MTLLibrary> defaultLibrary = [[_gpuDevice newDefaultLibrary] autorelease];
// Load the vertex function from the library
id<MTLFunction> vertexFunction = [[defaultLibrary newFunctionWithName:@"vertexShader"] autorelease];
// Load the fragment function from the library
id<MTLFunction> fragmentFunction = [[defaultLibrary newFunctionWithName:@"fragmentShader"] autorelease];
// Configure a pipeline descriptor that is used to create a pipeline state
MTLRenderPipelineDescriptor *pipelineStateDescriptor = [[[MTLRenderPipelineDescriptor alloc] init] autorelease];
pipelineStateDescriptor.label = @"Simple Pipeline";
pipelineStateDescriptor.vertexFunction = vertexFunction;
pipelineStateDescriptor.fragmentFunction = fragmentFunction;
pipelineStateDescriptor.colorAttachments[0].pixelFormat = pixFormat;
_pixelFormat = pixFormat;
NSError* error = nil;
_pipelineState = [_gpuDevice newRenderPipelineStateWithDescriptor:pipelineStateDescriptor
error:&error];
if (error != nil)
{
NSLog (@"Error generating brightness pipeline state: %@", error);
}
if (_commandQueueCache != nil)
{
_commandQueueCacheLock = [[NSLock alloc] init];
}
if ((_gpuDevice == nil) || (_commandQueueCache == nil) || (_commandQueueCacheLock == nil) ||
(_pipelineState == nil))
{
[self release];
self = nil;
}
}
return self;
}
- (void)dealloc
{
[_gpuDevice release];
[_commandQueueCache release];
[_commandQueueCacheLock release];
[_pipelineState release];
[super dealloc];
}
- (id<MTLCommandQueue>)getNextFreeCommandQueue
{
id<MTLCommandQueue> result = nil;
[_commandQueueCacheLock lock];
NSUInteger index = 0;
while ((result == nil) && (index < kMaxCommandQueues))
{
NSMutableDictionary* nextCommandQueue = [_commandQueueCache objectAtIndex:index];
NSNumber* inUse = [nextCommandQueue objectForKey:kKey_InUse];
if (![inUse boolValue])
{
[nextCommandQueue setObject:[NSNumber numberWithBool:YES]
forKey:kKey_InUse];
result = [nextCommandQueue objectForKey:kKey_CommandQueue];
}
index++;
}
[_commandQueueCacheLock unlock];
return result;
}
- (void)returnCommandQueue:(id<MTLCommandQueue>)commandQueue
{
[_commandQueueCacheLock lock];
BOOL found = false;
NSUInteger index = 0;
while ((!found) && (index < kMaxCommandQueues))
{
NSMutableDictionary* nextCommandQueuDict = [_commandQueueCache objectAtIndex:index];
id<MTLCommandQueue> nextCommandQueue = [nextCommandQueuDict objectForKey:kKey_CommandQueue];
if (nextCommandQueue == commandQueue)
{
found = YES;
[nextCommandQueuDict setObject:[NSNumber numberWithBool:NO]
forKey:kKey_InUse];
}
index++;
}
[_commandQueueCacheLock unlock];
}
- (BOOL)containsCommandQueue:(id<MTLCommandQueue>)commandQueue
{
BOOL found = NO;
NSUInteger index = 0;
while ((!found) && (index < kMaxCommandQueues))
{
NSMutableDictionary* nextCommandQueuDict = [_commandQueueCache objectAtIndex:index];
id<MTLCommandQueue> nextCommandQueue = [nextCommandQueuDict objectForKey:kKey_CommandQueue];
if (nextCommandQueue == commandQueue)
{
found = YES;
}
index++;
}
return found;
}
@end
@implementation MetalDeviceCache
+ (MTLPixelFormat)MTLPixelFormatForImageTile:(FxImageTile*)imageTile
{
MTLPixelFormat result = MTLPixelFormatRGBA16Float;
switch (imageTile.ioSurface.pixelFormat)
{
case kCVPixelFormatType_128RGBAFloat:
result = MTLPixelFormatRGBA32Float;
break;
case kCVPixelFormatType_32BGRA:
result = MTLPixelFormatBGRA8Unorm;
break;
default:
break;
}
return result;
}
+ (MetalDeviceCache*)deviceCache;
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
gDeviceCache = [[MetalDeviceCache alloc] init];
});
return gDeviceCache;
}
- (instancetype)init
{
self = [super init];
if (self != nil)
{
NSArray<id<MTLDevice>>* devices = MTLCopyAllDevices();
deviceCaches = [[NSMutableArray alloc] initWithCapacity:devices.count];
for (id<MTLDevice> nextDevice in devices)
{
MetalDeviceCacheItem* newCacheItem = [[[MetalDeviceCacheItem alloc] initWithDevice:nextDevice
pixelFormat:MTLPixelFormatRGBA16Float]
autorelease];
[deviceCaches addObject:newCacheItem];
}
[devices release];
}
return self;
}
- (void)dealloc
{
[deviceCaches release];
[super dealloc];
}
- (id<MTLDevice>)deviceWithRegistryID:(uint64_t)registryID
{
for (MetalDeviceCacheItem* nextCacheItem in deviceCaches)
{
if (nextCacheItem.gpuDevice.registryID == registryID)
{
return nextCacheItem.gpuDevice;
}
}
return nil;
}
- (id<MTLRenderPipelineState>)pipelineStateWithRegistryID:(uint64_t)registryID
pixelFormat:(MTLPixelFormat)pixFormat
{
for (MetalDeviceCacheItem* nextCacheItem in deviceCaches)
{
if ((nextCacheItem.gpuDevice.registryID == registryID) &&
(nextCacheItem.pixelFormat == pixFormat))
{
return nextCacheItem.pipelineState;
}
}
// Didn't find one, so create one with the right settings
NSArray<id<MTLDevice>>* devices = MTLCopyAllDevices();
id<MTLDevice> device = nil;
for (id<MTLDevice> nextDevice in devices)
{
if (nextDevice.registryID == registryID)
{
device = nextDevice;
}
}
id<MTLRenderPipelineState> result = nil;
if (device != nil)
{
MetalDeviceCacheItem* newCacheItem = [[[MetalDeviceCacheItem alloc] initWithDevice:device
pixelFormat:pixFormat]
autorelease];
if (newCacheItem != nil)
{
[deviceCaches addObject:newCacheItem];
result = newCacheItem.pipelineState;
}
}
[devices release];
return result;
}
- (id<MTLCommandQueue>)commandQueueWithRegistryID:(uint64_t)registryID
pixelFormat:(MTLPixelFormat)pixFormat;
{
for (MetalDeviceCacheItem* nextCacheItem in deviceCaches)
{
if ((nextCacheItem.gpuDevice.registryID == registryID) &&
(nextCacheItem.pixelFormat == pixFormat))
{
return [nextCacheItem getNextFreeCommandQueue];
}
}
// Didn't find one, so create one with the right settings
NSArray<id<MTLDevice>>* devices = MTLCopyAllDevices();
id<MTLDevice> device = nil;
for (id<MTLDevice> nextDevice in devices)
{
if (nextDevice.registryID == registryID)
{
device = nextDevice;
}
}
id<MTLCommandQueue> result = nil;
if (device != nil)
{
MetalDeviceCacheItem* newCacheItem = [[[MetalDeviceCacheItem alloc] initWithDevice:device
pixelFormat:pixFormat]
autorelease];
if (newCacheItem != nil)
{
[deviceCaches addObject:newCacheItem];
result = [newCacheItem getNextFreeCommandQueue];
}
}
[devices release];
return result;
}
- (void)returnCommandQueueToCache:(id<MTLCommandQueue>)commandQueue;
{
for (MetalDeviceCacheItem* nextCacheItem in deviceCaches)
{
if ([nextCacheItem containsCommandQueue:commandQueue])
{
[nextCacheItem returnCommandQueue:commandQueue];
break;
}
}
}
@end
二进制文件未显示。
二进制文件未显示。
二进制文件未显示。
二进制文件未显示。
二进制文件未显示。
二进制文件未显示。
@@ -0,0 +1,121 @@
[
{
"file": "apple_log_to_rec709.dylut",
"dimension": 65,
"source": "apple_log_to_rec709.cube",
"sourceSHA256": "a2080a4e4be9505bf95ebda07e5a911beed03dff359a235bab30457213be21e0",
"sha256": "d98f0a02cbe440bcbaff3d5b0c524a4720d3e0915553953ff00d331d25b8413d"
},
{
"file": "arri_logc3_to_rec709.dylut",
"dimension": 33,
"source": "arri_logc3_to_rec709.cube",
"sourceSHA256": "241aff344709aa90b468f8658144888db38f29f9aa1b3c0d917cf327ca3b354e",
"sha256": "e5b3c99c692e5ca903b5f2df8fa4a54faad5640f36d00a3fd9f9ad09a337bac8"
},
{
"file": "arri_logc4_to_rec709.dylut",
"dimension": 33,
"source": "arri_logc4_to_rec709.cube",
"sourceSHA256": "ab9618bc72dc3fab3e1d23a0c25ffd9cfb0491ed715448a629e44939cbd3f4b4",
"sha256": "2bae85e04d87dd79cc24b69a6e4897fa04dee16c62f1da413dd63ca9ecb36866"
},
{
"file": "blackmagic_film_gen5_to_rec709.dylut",
"dimension": 33,
"source": "blackmagic_film_gen5_to_rec709.cube",
"sourceSHA256": "c1424b30899da95708ef346e1e386496b28fe742b6d29f704f43dfea8f616c5f",
"sha256": "b5ccc9537f3de78ea48414a03ac2e64492510ac35ecc678ef5689902129805cc"
},
{
"file": "canon_clog2_cinema_gamut_to_rec709.dylut",
"dimension": 33,
"source": "canon_clog2_cinema_gamut_to_rec709.cube",
"sourceSHA256": "522fd5d8f3c853954224b7742c609c920b6bd3f9cdae6fbdf26ac9c643278c48",
"sha256": "fe4ec3e6a83e25530fba5cf14ea1d4c8c01df3f3b8507418697b33ad5dc125e9"
},
{
"file": "canon_clog3_cinema_gamut_to_rec709.dylut",
"dimension": 33,
"source": "canon_clog3_cinema_gamut_to_rec709.cube",
"sourceSHA256": "7ec33910d4aa1910021d8276b467a3ef0ff4a52a75e648deb93e5f908c1f21e4",
"sha256": "68326395ab1358fe1c568a3bf5fcb950e7e5fd07a468e812fdc6f770a20f6d0b"
},
{
"file": "canon_clog_bt709_to_rec709.dylut",
"dimension": 33,
"source": "canon_clog_bt709_to_rec709.cube",
"sourceSHA256": "7c9c4162a3f00b60ba8f6a95aa24502b7c04471306dc7ae7b5996f542dcf4060",
"sha256": "7c6a6a2fd2f78c0013ebf01205e615238f16bef07e0b8b72bcfd9e970fa43e22"
},
{
"file": "dji_dlog_m_to_rec709.dylut",
"dimension": 33,
"source": "dji_dlog_m_to_rec709.cube",
"sourceSHA256": "ac3e114ba6467d27f97295bf91532428bddc05fb61922635d9271d57ecbc9d48",
"sha256": "cb37af7934b5658e814ad36e4a042cbe82d4da3b96150f2aa7969e71a8291f0e"
},
{
"file": "dji_dlog_to_rec709.dylut",
"dimension": 33,
"source": "dji_dlog_to_rec709.cube",
"sourceSHA256": "ca8bc7d3bf382512ed9501137c8b88d1829ae9b22a84965d7d2e1339f615de72",
"sha256": "997b3e6d106eaee13702bd218271a0c2e467000273fb4522ff66676ce05bb6f5"
},
{
"file": "fujifilm_flog2_to_rec709.dylut",
"dimension": 33,
"source": "fujifilm_flog2_to_rec709.cube",
"sourceSHA256": "6c0e327c2ba055e6ca539717c85b509aca91a14a6aa86b092474ed567d3873cf",
"sha256": "08afea18a6bb2e746f845f96d5389db016bde0d46ee6e0ff75af1bee0c7c8523"
},
{
"file": "fujifilm_flog_to_rec709.dylut",
"dimension": 33,
"source": "fujifilm_flog_to_rec709.cube",
"sourceSHA256": "6c0e327c2ba055e6ca539717c85b509aca91a14a6aa86b092474ed567d3873cf",
"sha256": "08afea18a6bb2e746f845f96d5389db016bde0d46ee6e0ff75af1bee0c7c8523"
},
{
"file": "nikon_nlog_to_rec709.dylut",
"dimension": 33,
"source": "nikon_nlog_to_rec709.cube",
"sourceSHA256": "e898acc5c7d00b145ff64d28ada99fec3aa9c3e321fc9cbfcc1dfdc83de356d5",
"sha256": "d5a102958b48da213520029d2dab9831af47d6a64b9cc84966b55baf372ac614"
},
{
"file": "panasonic_vlog_vgamut_to_rec709.dylut",
"dimension": 33,
"source": "panasonic_vlog_vgamut_to_rec709.cube",
"sourceSHA256": "f99223675b29933952da2153bdb3137dd749d12964d0753db85e47576ca4578d",
"sha256": "bf65022ae5021189afb14cede57a98a5fcf6469574e97ffce1a3cf5b2c08b428"
},
{
"file": "red_log3g10_rwg_to_rec709.dylut",
"dimension": 33,
"source": "red_log3g10_rwg_to_rec709.cube",
"sourceSHA256": "15014c07170c770d626fb49424a3995a1f23b64cc9ec00dc01de4e317fa1057c",
"sha256": "2ef8f2b1b70ceedcff66e00b5dfb49184846c9b0c667f347714fa3e68f4251b5"
},
{
"file": "sony_hlg_bt2020_to_rec709.dylut",
"dimension": 33,
"source": "sony_hlg_bt2020_to_rec709.cube",
"sourceSHA256": "f4f75e99e2a81a9288166486920ad27a5894f97661976f00f81ebe4e1a425964",
"sha256": "49b9526785f94d288fd9538358379d509720f3ea3b5685430a125117aa6aeee3"
},
{
"file": "sony_slog2_sgamut_to_rec709.dylut",
"dimension": 65,
"source": "sony_slog2_sgamut_to_rec709.cube",
"sourceSHA256": "315b6a01d16b44f0449cb5450c1ccda8fcd54f7efaa5470bcd92f2844d60ae9f",
"sha256": "62230c479abd04d53c104a9016d53255441f58f7ff6a6f1b6139529bf6d08ad8"
},
{
"file": "sony_slog3_sgamut3cine_to_rec709.dylut",
"dimension": 65,
"source": "sony_slog3_sgamut3cine_to_rec709.cube",
"sourceSHA256": "286d5eaa3e4f5f46ccc9119c2594c59c7b0502cb140941dd6c01aeb08474ec94",
"sha256": "4e60f55f717635293249e0c6f17be5f0864bf42aadebf3addcd6dd56fe9af265"
}
]
二进制文件未显示。
@@ -0,0 +1,27 @@
Dayu Color uses Camera Raw lookup-table data and composition behavior adapted from Compositor.
https://github.com/robbietilton/Compositor
Upstream commit: 92f5225afe7e921dbfa4c563462980e45db345fc
DayuColorTables.bin is byte-identical to upstream CameraRawTables.bin.
SHA-256: e67ff4dbcce35cb7765752acff4405be5c934d913ef1396b2ca3fc6dc8a85190
MIT License
Copyright (c) 2026 Wonder Assembly LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -1,83 +0,0 @@
//
// TileableRemoteBrightness.metal
// 大鱼调色
//
// Created by mac on 2026/10/31.
//
#include <metal_stdlib>
#include <simd/simd.h>
using namespace metal;
#include "TileableRemoteBrightnessShaderTypes.h"
typedef struct
{
// The [[position]] attribute of this member indicates that this value is the clip space
// position of the vertex when this structure is returned from the vertex function
float4 clipSpacePosition [[position]];
// Since this member does not have a special attribute, the rasterizer interpolates
// its value with the values of the other triangle vertices and then passes
// the interpolated value to the fragment shader for each fragment in the triangle
float2 textureCoordinate;
} RasterizerData;
vertex RasterizerData
vertexShader(uint vertexID [[vertex_id]],
constant Vertex2D *vertexArray [[buffer(BVI_Vertices)]],
constant vector_uint2 *viewportSizePointer [[buffer(BVI_ViewportSize)]])
{
RasterizerData out;
// Index into our array of positions to get the current vertex
// Our positions are specified in pixel dimensions (i.e. a value of 100 is 100 pixels from
// the origin)
float2 pixelSpacePosition = vertexArray[vertexID].position.xy;
// Get the size of the drawable so that we can convert to normalized device coordinates,
float2 viewportSize = float2(*viewportSizePointer);
// The output position of every vertex shader is in clip space (also known as normalized device
// coordinate space, or NDC). A value of (-1.0, -1.0) in clip-space represents the
// lower-left corner of the viewport whereas (1.0, 1.0) represents the upper-right corner of
// the viewport.
// In order to convert from positions in pixel space to positions in clip space we divide the
// pixel coordinates by half the size of the viewport.
out.clipSpacePosition.xy = pixelSpacePosition / (viewportSize / 2.0);
// Set the z component of our clip space position 0 (since we're only rendering in
// 2-Dimensions for this sample)
out.clipSpacePosition.z = 0.0;
// Set the w component to 1.0 since we don't need a perspective divide, which is also not
// necessary when rendering in 2-Dimensions
out.clipSpacePosition.w = 1.0;
// Pass our input textureCoordinate straight to our output RasterizerData. This value will be
// interpolated with the other textureCoordinate values in the vertices that make up the
// triangle.
out.textureCoordinate = vertexArray[vertexID].textureCoordinate;
return out;
}
// Fragment function
fragment float4 fragmentShader(RasterizerData in [[stage_in]],
texture2d<half> colorTexture [[ texture(BTI_InputImage) ]],
constant float* brightness [[ buffer(BFI_Brightness) ]])
{
constexpr sampler textureSampler (mag_filter::linear,
min_filter::linear);
// Sample the texture to obtain a color
half4 colorSample = colorTexture.sample(textureSampler, in.textureCoordinate);
const half hBrightness = static_cast<half>(*brightness);
colorSample.rgb = colorSample.rgb * hBrightness;
// We return the color of the texture
return float4(colorSample);
}
@@ -1,32 +0,0 @@
//
// TileableRemoteBrightnessShaderTypes.h
// 大鱼调色
//
// Created by mac on 2026/10/31.
//
#ifndef TileableRemoteBrightnessShaderTypes_h
#define TileableRemoteBrightnessShaderTypes_h
#import <simd/simd.h>
typedef enum BrightnessVertexInputIndex {
BVI_Vertices = 0,
BVI_ViewportSize = 1
} BrightnessVertexInputIndex;
typedef enum BrightnessTextureIndex {
BTI_InputImage = 0
} BrightnessTextureIndex;
typedef enum BrightnessFragmentIndex {
BFI_Brightness = 0
} BrightnessFragmentIndex;
typedef struct Vertex2D {
vector_float2 position;
vector_float2 textureCoordinate;
} Vertex2D;
#endif /* TileableRemoteBrightnessShaderTypes_h */
-8
查看文件
@@ -1,8 +0,0 @@
//___FILEHEADER___
#import <Foundation/Foundation.h>
#import <FxPlug/FxPlugSDK.h>
@interface ___PACKAGENAMEASIDENTIFIER___PlugIn : NSObject <FxTileableEffect>
@property (assign) id<PROAPIAccessing> apiManager;
@end
-315
查看文件
@@ -1,315 +0,0 @@
//___FILEHEADER___
#import "___PACKAGENAMEASIDENTIFIER___PlugIn.h"
#import <IOSurface/IOSurfaceObjC.h>
#import "TileableRemoteBrightnessShaderTypes.h"
#import "MetalDeviceCache.h"
@implementation ___PACKAGENAMEASIDENTIFIER___PlugIn
//---------------------------------------------------------
// initWithAPIManager:
//
// This method is called when a plug-in is first loaded, and
// is a good point to conduct any checks for anti-piracy or
// system compatibility. Returning NULL means that a plug-in
// chooses not to be accessible for some reason.
//---------------------------------------------------------
- (nullable instancetype)initWithAPIManager:(id<PROAPIAccessing>)newApiManager;
{
self = [super init];
if (self != nil)
{
_apiManager = newApiManager;
}
return self;
}
//---------------------------------------------------------
// properties
//
// This method should return an NSDictionary defining the
// properties of the effect.
//---------------------------------------------------------
- (BOOL)properties:(NSDictionary * _Nonnull *)properties
error:(NSError * _Nullable *)error
{
*properties = @{
kFxPropertyKey_MayRemapTime : [NSNumber numberWithBool:NO],
kFxPropertyKey_PixelTransformSupport : [NSNumber numberWithInt:kFxPixelTransform_ScaleTranslate],
kFxPropertyKey_VariesWhenParamsAreStatic : [NSNumber numberWithBool:NO]
};
return YES;
}
//---------------------------------------------------------
// addParametersWithError
//
// This method is where a plug-in defines its list of parameters.
//---------------------------------------------------------
- (BOOL)addParametersWithError:(NSError**)error
{
id<FxParameterCreationAPI_v5> paramAPI = [_apiManager apiForProtocol:@protocol(FxParameterCreationAPI_v5)];
if (paramAPI == nil)
{
NSDictionary* userInfo = @{
NSLocalizedDescriptionKey : @"Unable to obtain an FxPlug API Object"
};
if (error != NULL)
*error = [NSError errorWithDomain:FxPlugErrorDomain
code:kFxError_APIUnavailable
userInfo:userInfo];
return NO;
}
if (![paramAPI addFloatSliderWithName:@"Brightness"
parameterID:1
defaultValue:1.0
parameterMin:0.0
parameterMax:100.0
sliderMin:0.0
sliderMax:10.0
delta:0.1
parameterFlags:kFxParameterFlag_DEFAULT])
{
NSDictionary* userInfo = @{
NSLocalizedDescriptionKey : @"Unable to add brightness slider"
};
if (error != NULL)
*error = [NSError errorWithDomain:FxPlugErrorDomain
code:kFxError_InvalidParameter
userInfo:userInfo];
return NO;
}
return YES;
}
//---------------------------------------------------------
// pluginState:atTime:quality:error
//
// Your plug-in should get its parameter values, do any calculations it needs to
// from those values, and package up the result to be used later with rendering.
// The host application will call this method before rendering. The
// FxParameterRetrievalAPI* is valid during this call. Use it to get the values of
// your plug-in's parameters, then put those values or the results of any calculations
// you need to do with those parameters to render into an NSData that you return
// to the host application. The host will pass it back to you during subsequent calls.
// Do not re-use the NSData; always create a new one as this method may be called
// on multiple threads at the same time.
//---------------------------------------------------------
- (BOOL)pluginState:(NSData**)pluginState
atTime:(CMTime)renderTime
quality:(FxQuality)qualityLevel
error:(NSError**)error
{
BOOL succeeded = NO;
id<FxParameterRetrievalAPI_v6> paramGetAPI = [_apiManager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)];
if (paramGetAPI != nil)
{
double brightness = 1.0;
[paramGetAPI getFloatValue:&brightness
fromParameter:1
atTime:renderTime];
*pluginState = [NSData dataWithBytes:&brightness
length:sizeof(brightness)];
if (*pluginState != nil)
{
succeeded = YES;
}
}
else
{
if (error != NULL)
*error = [NSError errorWithDomain:FxPlugErrorDomain
code:kFxError_ThirdPartyDeveloperStart + 20
userInfo:@{
NSLocalizedDescriptionKey :
@"Unable to retrieve FxParameterRetrievalAPI_v6 in \
[-pluginStateAtTime:]" }];
}
return succeeded;
}
//---------------------------------------------------------
// destinationImageRect:sourceImages:destinationImage:pluginState:atTime:error
//
// This method will calculate the rectangular bounds of the output
// image given the various inputs and plug-in state
// at the given render time.
// It will pass in an array of images, the plug-in state
// returned from your plug-in's -pluginStateAtTime:error: method,
// and the render time.
//---------------------------------------------------------
- (BOOL)destinationImageRect:(FxRect *)destinationImageRect
sourceImages:(NSArray<FxImageTile *> *)sourceImages
destinationImage:(nonnull FxImageTile *)destinationImage
pluginState:(NSData *)pluginState
atTime:(CMTime)renderTime
error:(NSError * _Nullable *)outError
{
if (sourceImages.count < 1)
{
NSLog (@"No inputImages list");
return NO;
}
// In the case of a filter that only changed RGB values,
// the output rect is the same as the input rect.
*destinationImageRect = sourceImages [ 0 ].imagePixelBounds;
return YES;
}
//---------------------------------------------------------
// sourceTileRect:sourceImageIndex:sourceImages:destinationTileRect:destinationImage:pluginState:atTime:error
//
// Calculate tile of the source image we need
// to render the given output tile.
//---------------------------------------------------------
- (BOOL)sourceTileRect:(FxRect *)sourceTileRect
sourceImageIndex:(NSUInteger)sourceImageIndex
sourceImages:(NSArray<FxImageTile *> *)sourceImages
destinationTileRect:(FxRect)destinationTileRect
destinationImage:(FxImageTile *)destinationImage
pluginState:(NSData *)pluginState
atTime:(CMTime)renderTime
error:(NSError * _Nullable *)outError
{
// Since this is a color-only filter, the input tile will be the same size as the output tile
*sourceTileRect = destinationTileRect;
return YES;
}
//---------------------------------------------------------
// renderDestinationImage:sourceImages:pluginState:atTime:error:
//
// The host will call this method when it wants your plug-in to render an image
// tile of the output image. It will pass in each of the input tiles needed as well
// as the plug-in state needed for the calculations. Your plug-in should do all its
// rendering in this method. It should not attempt to use the FxParameterRetrievalAPI*
// object as it is invalid at this time. Note that this method will be called on
// multiple threads at the same time.
//---------------------------------------------------------
- (BOOL)renderDestinationImage:(FxImageTile *)destinationImage
sourceImages:(NSArray<FxImageTile *> *)sourceImages
pluginState:(NSData *)pluginState
atTime:(CMTime)renderTime
error:(NSError * _Nullable *)outError
{
if ((pluginState == nil) || (sourceImages [ 0 ].ioSurface == nil) || (destinationImage.ioSurface == nil))
{
NSDictionary* userInfo = @{
NSLocalizedDescriptionKey : @"Invalid plugin state received from host"
};
if (outError != NULL)
*outError = [NSError errorWithDomain:FxPlugErrorDomain
code:kFxError_InvalidParameter
userInfo:userInfo];
return NO;
}
// This is where you would access parameter values and other info about the source tile
// from the pluginState.
double brightness = 0.0;
[pluginState getBytes:&brightness
length:sizeof(brightness)];
// Set up the renderer, in this case we are using Metal.
MetalDeviceCache* deviceCache = [MetalDeviceCache deviceCache];
MTLPixelFormat pixelFormat = [MetalDeviceCache MTLPixelFormatForImageTile:destinationImage];
id<MTLCommandQueue> commandQueue = [deviceCache commandQueueWithRegistryID:sourceImages[0].deviceRegistryID
pixelFormat:pixelFormat];
if (commandQueue == nil)
{
return NO;
}
id<MTLCommandBuffer> commandBuffer = [commandQueue commandBuffer];
commandBuffer.label = @"DynamicRegXPC Command Buffer";
[commandBuffer enqueue];
id<MTLTexture> inputTexture = [sourceImages[0] metalTextureForDevice:[deviceCache deviceWithRegistryID:sourceImages[0].deviceRegistryID]];
id<MTLTexture> outputTexture = [destinationImage metalTextureForDevice:[deviceCache deviceWithRegistryID:destinationImage.deviceRegistryID]];
MTLRenderPassColorAttachmentDescriptor* colorAttachmentDescriptor = [[MTLRenderPassColorAttachmentDescriptor alloc] init];
colorAttachmentDescriptor.texture = outputTexture;
colorAttachmentDescriptor.clearColor = MTLClearColorMake(1.0, 0.5, 0.0, 1.0);
colorAttachmentDescriptor.loadAction = MTLLoadActionClear;
MTLRenderPassDescriptor* renderPassDescriptor = [MTLRenderPassDescriptor renderPassDescriptor];
renderPassDescriptor.colorAttachments [ 0 ] = colorAttachmentDescriptor;
id<MTLRenderCommandEncoder> commandEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor];
// Rendering
float outputWidth = (float)(destinationImage.tilePixelBounds.right - destinationImage.tilePixelBounds.left);
float outputHeight = (float)(destinationImage.tilePixelBounds.top - destinationImage.tilePixelBounds.bottom);
Vertex2D vertices[] = {
{ { outputWidth / 2.0, -outputHeight / 2.0 }, { 1.0, 1.0 } },
{ { -outputWidth / 2.0, -outputHeight / 2.0 }, { 0.0, 1.0 } },
{ { outputWidth / 2.0, outputHeight / 2.0 }, { 1.0, 0.0 } },
{ { -outputWidth / 2.0, outputHeight / 2.0 }, { 0.0, 0.0 } }
};
MTLViewport viewport = {
0, 0, outputWidth, outputHeight, -1.0, 1.0
};
[commandEncoder setViewport:viewport];
id<MTLRenderPipelineState> pipelineState = [deviceCache pipelineStateWithRegistryID:sourceImages[0].deviceRegistryID
pixelFormat:pixelFormat];
[commandEncoder setRenderPipelineState:pipelineState];
[commandEncoder setVertexBytes:vertices
length:sizeof(vertices)
atIndex:BVI_Vertices];
simd_uint2 viewportSize = {
(unsigned int)(outputWidth),
(unsigned int)(outputHeight)
};
[commandEncoder setVertexBytes:&viewportSize
length:sizeof(viewportSize)
atIndex:BVI_ViewportSize];
[commandEncoder setFragmentTexture:inputTexture
atIndex:BTI_InputImage];
float fragmentBrightness = (float)brightness;
[commandEncoder setFragmentBytes:&fragmentBrightness
length:sizeof(fragmentBrightness)
atIndex:BFI_Brightness];
[commandEncoder drawPrimitives:MTLPrimitiveTypeTriangleStrip
vertexStart:0
vertexCount:4];
[commandEncoder endEncoding];
[commandBuffer commit];
[commandBuffer waitUntilCompleted];
[colorAttachmentDescriptor release];
[deviceCache returnCommandQueueToCache:commandQueue];
return YES;
}
@end