From bb5ede7be4869781235a1e0ea0e3c8bb428222b0 Mon Sep 17 00:00:00 2001 From: mac Date: Tue, 3 Nov 2026 12:44:08 +0800 Subject: [PATCH] WIP: integrate opt-in ACES renderer and inspector; Release compiles, regression validation pending --- 大鱼调色/Plugin/DYFilmKernels.inc.h | 2 +- 大鱼调色/Plugin/DYFilmRender.inc.h | 2 +- 大鱼调色/Plugin/DYInspector.mm | 21 +++++--- 大鱼调色/Plugin/DYManagedColor.mm | 4 +- 大鱼调色/Plugin/DYManagedColorPanel.h | 9 ++++ 大鱼调色/Plugin/DYManagedColorPanel.mm | 41 +++++++++++++++ 大鱼调色/Plugin/DYManagedKernels.inc.h | 6 ++- 大鱼调色/Plugin/DYManagedRender.inc.h | 69 +++++++++++++++++++++++++ 大鱼调色/Plugin/DYPlugIn.mm | 2 +- 大鱼调色/Plugin/DYRenderer.mm | 31 +++++++++-- 大鱼调色/Plugin/DYToolDiagnostics.inc.h | 2 +- 大鱼调色/Plugin/DYToolState.mm | 2 +- 12 files changed, 171 insertions(+), 20 deletions(-) create mode 100644 大鱼调色/Plugin/DYManagedColorPanel.h create mode 100644 大鱼调色/Plugin/DYManagedColorPanel.mm create mode 100644 大鱼调色/Plugin/DYManagedRender.inc.h diff --git a/大鱼调色/Plugin/DYFilmKernels.inc.h b/大鱼调色/Plugin/DYFilmKernels.inc.h index 670d4e4..59a9f18 100644 --- a/大鱼调色/Plugin/DYFilmKernels.inc.h +++ b/大鱼调色/Plugin/DYFilmKernels.inc.h @@ -6,7 +6,7 @@ kernel void dyFilmPoint(texture2d source [[texture(0)]],text float4 pixel=source.read(pos);if(!(pixel.a>0)){output.write(pixel,pos);return;} float3 c=pixel.rgb/pixel.a,result=c;DYFilmSettings film=uniforms.film; if(pass.operation==0)result=dyDecode(dyFilmMixer(dyEncode(c),uniforms)); - else if(pass.operation==1)result=dyDecode(dyFilmSubtractive(dyEncode(c),film)); + else if(pass.operation==1){float3 code=dyEncode(c);float3 bounded=clamp(code,0.f,1.f);result=dyDecode(dyFilmSubtractive(code,film)+(pass.reserved?code-bounded:float3(0)));} else if(pass.operation==2){float3 b=auxiliary.read(pos).rgb;float3 w=float3(film.boost,film.dyeTransmission/500.f,0);result=(c+b*w)/(1+w);} else if(pass.operation==3)result=c+auxiliary.read(pos).rgb; else if(pass.operation==4)result=dyDecode(dyFilmGrain(dyEncode(c),auxiliary.read(pos).rgb,film)); diff --git a/大鱼调色/Plugin/DYFilmRender.inc.h b/大鱼调色/Plugin/DYFilmRender.inc.h index f6aafb2..3b27ce3 100644 --- a/大鱼调色/Plugin/DYFilmRender.inc.h +++ b/大鱼调色/Plugin/DYFilmRender.inc.h @@ -24,7 +24,7 @@ idce=[commands computeCommandEncoder];[ce setComputePipelineState:entry[name]];[ce setTexture:a atIndex:0];if(b)[ce setTexture:b atIndex:1];[ce setTexture:out atIndex:b?2:1];if(data)[ce setBytes:data length:length atIndex:0];[ce dispatchThreads:MTLSizeMake(out.width,out.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding]; }; idcurrent=before; - auto point=[&](int operation,idaux){idout=texture(current==slots[0]?1:0);if(!out)return NO;struct {int operation;float radius;unsigned frameKey,reserved;}pass={operation,0,u.filmFrameKey,0};idce=[commands computeCommandEncoder];[ce setComputePipelineState:entry[@"dyFilmPoint"]];[ce setTexture:current atIndex:0];[ce setTexture:aux?:current atIndex:1];[ce setTexture:out atIndex:2];[ce setBytes:&u length:sizeof(u) atIndex:0];[ce setBytes:&pass length:sizeof(pass) atIndex:1];[ce dispatchThreads:MTLSizeMake(out.width,out.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];current=out;return YES;}; + auto point=[&](int operation,idaux){idout=texture(current==slots[0]?1:0);if(!out)return NO;struct {int operation;float radius;unsigned frameKey,reserved;}pass={operation,0,u.filmFrameKey,_managedFinishing?1u:0u};idce=[commands computeCommandEncoder];[ce setComputePipelineState:entry[@"dyFilmPoint"]];[ce setTexture:current atIndex:0];[ce setTexture:aux?:current atIndex:1];[ce setTexture:out atIndex:2];[ce setBytes:&u length:sizeof(u) atIndex:0];[ce setBytes:&pass length:sizeof(pass) atIndex:1];[ce dispatchThreads:MTLSizeMake(out.width,out.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];current=out;return YES;}; @try{ if(mixer){if(!point(0,nil))return fail(error,@"无法分配通道混合缓冲区");} else { diff --git a/大鱼调色/Plugin/DYInspector.mm b/大鱼调色/Plugin/DYInspector.mm index b3f0a27..a7ffebb 100644 --- a/大鱼调色/Plugin/DYInspector.mm +++ b/大鱼调色/Plugin/DYInspector.mm @@ -1,3 +1,5 @@ +#import "DYManagedColorPanel.h" +#import "DYManagedColor.h" #import "DYInspector.h" #import "../Shared/DYBetaDiagnostics.h" #import "DYModel.h" @@ -569,6 +571,7 @@ static NSImage *DYWheelImage(void) { NSMutableArray *body=[NSMutableArray array]; NSString *key=section[@"key"]?:@""; if([key isEqual:@"primary"]) { + if(!_embedded){DYManagedColorPanel *cms=[[[DYManagedColorPanel alloc]initWithManager:_manager renderer:_renderer assetTarget:self]autorelease];[card addSubview:cms];[body addObject:cms];} NSButton *migrate=DYButton(@"旧版输入 → 改用 CST",self,@selector(useCST:));migrate.identifier=@"legacyInput";migrate.toolTip=@"保留旧工程输入效果;点击后改用上方 CST 设置,可撤销";[card addSubview:migrate];[body addObject:migrate]; } if([key localizedCaseInsensitiveContainsString:@"look"]) { @@ -687,7 +690,8 @@ static NSImage *DYWheelImage(void) { if([row.identifier isEqual:@"toolMasks"])return [(DYToolMaskPanel*)row contentHeight]>0; NSString *key=row.identifier?:@"";NSInteger tab=[_tabs[section]integerValue]; if(!_embedded&&[section isEqual:@"base"]&&[key isEqual:@"skinEnabled"])for(NSDictionary *card in _cards)if([card[@"section"][@"key"]isEqual:@"skin"])return ![card[@"removed"]boolValue]; - if([key isEqual:@"legacyInput"])return [_tabs[@"legacyInput"]boolValue]; + if([key isEqual:@"legacyInput"])return ![_tabs[@"managedColor"]boolValue]&&[_tabs[@"legacyInput"]boolValue]; + if([section isEqual:@"primary"]&&[_tabs[@"managedColor"]boolValue]){if([@[@"heading:input",@"heading:output"]containsObject:key])return NO;if([key isEqual:@"cmmix"])return YES;for(NSDictionary*d in DYDescriptors())if([d[@"key"]isEqual:key]&&d[@"cmTab"]&&[d[@"cmTab"]integerValue]!=1)return NO;} if([section isEqual:@"curve"] && ![key isEqual:@"curveGraph"])return NO; if([section isEqual:@"hsl"]) { int axis=0,color=0;if(sscanf(key.UTF8String,"hsl%d_%d",&axis,&color)==2)return color==tab; @@ -700,7 +704,7 @@ static NSImage *DYWheelImage(void) { if([section isEqual:@"look"]){int slot=0;if(sscanf(key.UTF8String,"asset:look%d",&slot)==1)return slot<_visibleLooks;if([key isEqual:@"postLUTStrength"])return YES;int number=0;if(sscanf(key.UTF8String,"look%dStrength",&number)==1)return number-1<_visibleLooks;return NO;} return YES; } -- (CGFloat)heightForRow:(NSView *)row {if([row isKindOfClass:DYToolMaskPanel.class])return [(DYToolMaskPanel*)row contentHeight];if([row.identifier isEqual:@"spiderGraph"])return 444;if([row.identifier isEqual:@"primaryBalance"])return 232;if([row.identifier hasPrefix:@"heading:"])return 27;return [row.identifier isEqual:@"curveGraph"]?240:[row.identifier isEqual:@"gradingWheels"]?292:32;} +- (CGFloat)heightForRow:(NSView *)row {if([row isKindOfClass:DYManagedColorPanel.class])return [(DYManagedColorPanel*)row contentHeight];if([row isKindOfClass:DYToolMaskPanel.class])return [(DYToolMaskPanel*)row contentHeight];if([row.identifier isEqual:@"spiderGraph"])return 444;if([row.identifier isEqual:@"primaryBalance"])return 232;if([row.identifier hasPrefix:@"heading:"])return 27;return [row.identifier isEqual:@"curveGraph"]?240:[row.identifier isEqual:@"gradingWheels"]?292:32;} - (void)layout { [super layout]; CGFloat w=MAX(280,self.bounds.size.width),h=self.bounds.size.height; @@ -804,7 +808,7 @@ static NSImage *DYWheelImage(void) { [(DYMaskCountBadge*)card[@"maskBadge"]setCount:count];NSString *hint=count?[NSString stringWithFormat:@"已有 %lu 个蒙版;点击添加独立蒙版",(unsigned long)count]:@"添加本工具的独立蒙版"; [card[@"maskButton"]setToolTip:hint];[card[@"maskButton"]setAccessibilityHelp:hint]; } - DYAssetState *assets=DYReadAssets(_manager,t);[_spiderPanel setMesh:assets.spiderMesh linked:assets.spiderLinked]; + DYAssetState *assets=DYReadAssets(_manager,t);_tabs[@"managedColor"]=@((_embedded?DYReadAssets([(DYToolManager*)_manager host],t).colorManagement:assets.colorManagement).count>0);for(NSDictionary*card in _cards)for(NSView*row in card[@"body"])if([row isKindOfClass:DYManagedColorPanel.class]){[(DYManagedColorPanel*)row refreshWithState:assets.colorManagement context:[_renderer colorContext]];row.alphaValue=1;}[_spiderPanel setMesh:assets.spiderMesh linked:assets.spiderLinked]; double profile=0,configured=0;[get getFloatValue:&profile fromParameter:2013 atTime:t];[get getFloatValue:&configured fromParameter:2236 atTime:t]; DYInspectorToken *oldToken=nil;[get getCustomParameterValue:&oldToken fromParameter:DYInspectorParameterID atTime:t]; _tabs[@"legacyInput"]=@(configured<.5&&(configured<0||profile>.5||[assets.paths[@"input"]length]||oldToken.schema<2)); @@ -1082,15 +1086,15 @@ static NSImage *DYWheelImage(void) { } - (NSDictionary *)presetSnapshot { id action=[self actionAPI];if(!action)return nil; - NSMutableDictionary *values=[NSMutableDictionary dictionary];NSDictionary *paths=@{},*spider=nil;NSString *tools=nil; + NSMutableDictionary *values=[NSMutableDictionary dictionary];NSDictionary *paths=@{},*spider=nil,*cms=nil;NSString *tools=nil; [action startAction:self]; @try { CMTime t=action.currentTime;id 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);} DYUniforms effective;DYReadUniforms(_manager,t,&effective);values[@"cmConfigured"]=@(effective.cm.configured);values[@"blackWhiteMix"]=@(effective.cm.blackWhiteMix); - DYAssetState *state=DYReadAssets(_manager,t);paths=[[state.paths copy]autorelease]?:@{};spider=DYSpiderJSON(state.spiderMesh,state.spiderLinked);NSData *toolData=[NSPropertyListSerialization dataWithPropertyList:DYReadTools(_manager,t).document format:NSPropertyListBinaryFormat_v1_0 options:0 error:nil];tools=[toolData base64EncodedStringWithOptions:0]; + DYAssetState *state=DYReadAssets(_manager,t);paths=[[state.paths copy]autorelease]?:@{};cms=[[state.colorManagement copy]autorelease];spider=DYSpiderJSON(state.spiderMesh,state.spiderLinked);NSData *toolData=[NSPropertyListSerialization dataWithPropertyList:DYReadTools(_manager,t).document format:NSPropertyListBinaryFormat_v1_0 options:0 error:nil];tools=[toolData base64EncodedStringWithOptions:0]; } @finally {[action endAction:self];} - return @{@"format":@"com.dayu.color.preset",@"version":@6,@"values":values,@"paths":paths,@"spider":spider,@"tools":tools?:@""}; + return @{@"format":@"com.dayu.color.preset",@"version":@7,@"colorManagement":cms?:@{},@"values":values,@"paths":paths,@"spider":spider,@"tools":tools?:@""}; } - (void)savePreset:(id)sender { NSDictionary *snapshot=[self presetSnapshot];if(!snapshot)return; @@ -1105,7 +1109,8 @@ static NSImage *DYWheelImage(void) { NSError *error=nil;NSData *data=[NSData dataWithContentsOfURL:panel.URL options:0 error:&error]; if(!data||data.length>32*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"]||![@[@1,@2,@3,@4,@5,@6]containsObject:json[@"version"]]||![json[@"values"] isKindOfClass:NSDictionary.class]||![json[@"paths"] isKindOfClass:NSDictionary.class]){[self showError:@"这不是有效的大鱼调色预设。"];return;} + if(![json isKindOfClass:NSDictionary.class]||![json[@"format"] isEqual:@"com.dayu.color.preset"]||![@[@1,@2,@3,@4,@5,@6,@7]containsObject:json[@"version"]]||![json[@"values"] isKindOfClass:NSDictionary.class]||![json[@"paths"] isKindOfClass:NSDictionary.class]){[self showError:@"这不是有效的大鱼调色预设。"];return;} + NSDictionary *newCMS=[json[@"version"]integerValue]>=7?json[@"colorManagement"]:nil;if(newCMS&&(![newCMS isKindOfClass:NSDictionary.class]||([newCMS count]&&!DYManagedColorValid(newCMS,nil)))){[self showError:@"预设色彩管理设置无效,当前调色未修改。"];return;} NSDictionary *values=json[@"values"],*paths=json[@"paths"];NSData *mesh=[json[@"version"]integerValue]>=3?DYSpiderFromJSON(json[@"spider"]):nil;if([json[@"version"]integerValue]>=3&&!mesh){[self showError:@"预设包含无效蜘蛛盘,当前调色未修改。"];return;} NSDictionary *tools=[[[DYToolDocument alloc]init]autorelease].document;if([json[@"version"]integerValue]>=4){id encoded=json[@"tools"];NSData *binary=[encoded isKindOfClass:NSString.class]?[[[NSData alloc]initWithBase64EncodedString:encoded options:0]autorelease]:nil;tools=binary?[NSPropertyListSerialization propertyListWithData:binary options:NSPropertyListImmutable format:NULL error:nil]:nil;if(!DYValidToolDocument(tools)){[self showError:@"预设包含无效工具或蒙版,当前调色未修改。"];return;}} for(NSDictionary *d in DYDescriptors()) { @@ -1126,7 +1131,7 @@ static NSImage *DYWheelImage(void) { CMTime t=action.currentTime;id set=[_manager apiForProtocol:@protocol(FxParameterSettingAPI_v6)]; for(NSDictionary *d in DYDescriptors()){id value=values[d[@"key"]];if(!value&&[d[@"offset"]integerValue]>=1104)value=d[@"default"];if(value)[set setFloatValue:[value doubleValue] toParameter:[d[@"pid"]unsignedIntValue] atTime:t];} if([json[@"version"]isEqual:@1]&&!values[@"cmConfigured"]){[set setFloatValue:-1 toParameter:2236 atTime:t];[set setFloatValue:1 toParameter:2270 atTime:t];} - DYAssetState *assets=[[[DYAssetState alloc] init] autorelease];assets.paths=validPaths;assets.spiderMesh=mesh;assets.spiderLinked=mesh?[json[@"spider"][@"linked"]boolValue]:YES;DYWriteAssets(_manager,assets,t);DYWriteTools(_manager,tools,t); + DYAssetState *assets=[[[DYAssetState alloc] init] autorelease];assets.paths=validPaths;assets.colorManagement=newCMS.count?newCMS:nil;assets.spiderMesh=mesh;assets.spiderLinked=mesh?[json[@"spider"][@"linked"]boolValue]:YES;DYWriteAssets(_manager,assets,t);DYWriteTools(_manager,tools,t); } @finally {[action endAction:self];} [self postChanged]; if(missing.count)[self showError:[@"调色参数已恢复,以下 LUT 文件需要重新选择:\n" stringByAppendingString:[missing componentsJoinedByString:@"\n"]]]; diff --git a/大鱼调色/Plugin/DYManagedColor.mm b/大鱼调色/Plugin/DYManagedColor.mm index 94d6d7f..aa6d99c 100644 --- a/大鱼调色/Plugin/DYManagedColor.mm +++ b/大鱼调色/Plugin/DYManagedColor.mm @@ -3,8 +3,8 @@ #include #include NSDictionary *DYManagedColorDefaults(void){return @{@"version":@2,@"mode":@1,@"input":@109,@"output":@1,@"gamutCompression":@YES,@"engine":@"OpenColorIO-2.5.2",@"config":@"studio-config-v2.2.0_aces-v1.3_ocio-v2.4"};} -NSArray *DYManagedInputSpaces(void){NSMutableArray *a=[NSMutableArray array];for(const auto&s:dycm::spaces())[a addObject:@{@"id":@(unsigned(s.id)),@"name":@(s.label)}];return a;} -NSArray *DYManagedOutputSpaces(void){NSMutableArray *a=[NSMutableArray array];for(const auto&s:dycm::outputs())[a addObject:@{@"id":@(unsigned(s.id)),@"name":@(s.label)}];return a;} +NSArray *DYManagedInputSpaces(void){NSMutableArray *a=[NSMutableArray array];for(const auto&s:dycm::spaces())[a addObject:@{@"id":@(unsigned(s.id)),@"name":@(s.label)}];return a;} +NSArray *DYManagedOutputSpaces(void){NSMutableArray *a=[NSMutableArray array];for(const auto&s:dycm::outputs())[a addObject:@{@"id":@(unsigned(s.id)),@"name":@(s.label)}];return a;} BOOL DYManagedColorValid(id state,NSError **error){ BOOL valid=[state isKindOfClass:NSDictionary.class]&&[state count]<=8&&[state[@"version"]isEqual:@2]&&[state[@"engine"]isEqual:@"OpenColorIO-2.5.2"]&&[state[@"config"]isEqual:@"studio-config-v2.2.0_aces-v1.3_ocio-v2.4"]; for(NSString *key in @[@"mode",@"input",@"output",@"gamutCompression"]){id v=[state isKindOfClass:NSDictionary.class]?state[key]:nil;double n=[v isKindOfClass:NSNumber.class]?[v doubleValue]:NAN;valid&=std::isfinite(n)&&n==floor(n);} diff --git a/大鱼调色/Plugin/DYManagedColorPanel.h b/大鱼调色/Plugin/DYManagedColorPanel.h new file mode 100644 index 0000000..bcca670 --- /dev/null +++ b/大鱼调色/Plugin/DYManagedColorPanel.h @@ -0,0 +1,9 @@ +#pragma once +#import +#import +@class DYRenderer; +@interface DYManagedColorPanel : NSView +- (instancetype)initWithManager:(id)manager renderer:(DYRenderer*)renderer assetTarget:(id)target; +- (void)refreshWithState:(NSDictionary*)state context:(NSDictionary*)context; +- (CGFloat)contentHeight; +@end diff --git a/大鱼调色/Plugin/DYManagedColorPanel.mm b/大鱼调色/Plugin/DYManagedColorPanel.mm new file mode 100644 index 0000000..41bda7e --- /dev/null +++ b/大鱼调色/Plugin/DYManagedColorPanel.mm @@ -0,0 +1,41 @@ +#import "DYManagedColorPanel.h" +#import "DYManagedColor.h" +#import "DYModel.h" +#import "DYRenderer.h" +#import "DYTheme.h" +@implementation DYManagedColorPanel { + id _manager;id _assetTarget;DYRenderer *_renderer; + NSPopUpButton *_mode,*_input,*_output;NSButton *_gamut,*_lut;NSTextField *_inputLabel,*_outputLabel,*_help,*_context; + NSDictionary *_state;BOOL _refreshing; +} +- (BOOL)isFlipped{return YES;} +- (CGFloat)contentHeight{return 268;} +static NSTextField *cmsLabel(NSString*s){NSTextField*l=[NSTextField wrappingLabelWithString:s];l.font=[NSFont systemFontOfSize:11];l.textColor=DYThemeColor(@"text");return l;} +- (instancetype)initWithManager:(id)m renderer:(DYRenderer*)r assetTarget:(id)target { + if((self=[super initWithFrame:NSZeroRect])){_manager=m;_renderer=[r retain];_assetTarget=target;self.identifier=@"managedColor"; + _mode=[[NSPopUpButton alloc]initWithFrame:NSZeroRect];[_mode addItemsWithTitles:@[@"旧版兼容",@"跟随 FCP 色彩管理",@"相机编码 → ACES",@"输入 LUT → ACES"]];_mode.target=self;_mode.action=@selector(modeChanged:);_mode.accessibilityLabel=@"色彩管理方式"; + _inputLabel=[cmsLabel(@"输入空间")retain];_outputLabel=[cmsLabel(@"输出目标")retain]; + _input=[[NSPopUpButton alloc]initWithFrame:NSZeroRect];for(NSDictionary*s in DYManagedInputSpaces()){[_input addItemWithTitle:s[@"name"]];_input.lastItem.representedObject=s[@"id"];} _input.target=self;_input.action=@selector(settingsChanged:);_input.accessibilityLabel=@"新版输入空间"; + _output=[[NSPopUpButton alloc]initWithFrame:NSZeroRect];for(NSDictionary*s in DYManagedOutputSpaces()){[_output addItemWithTitle:s[@"name"]];_output.lastItem.representedObject=s[@"id"];} _output.target=self;_output.action=@selector(settingsChanged:);_output.accessibilityLabel=@"新版输出目标"; + _gamut=[[NSButton checkboxWithTitle:@"ACES 参考色域压缩" target:self action:@selector(settingsChanged:)]retain];_gamut.font=[NSFont systemFontOfSize:11]; + _lut=[[NSButton buttonWithTitle:@"选择输入 LUT…" target:self action:@selector(chooseLUT:)]retain];_lut.bezelStyle=NSBezelStyleRounded; + _help=[cmsLabel(@"")retain];_help.textColor=DYThemeColor(@"secondary");_context=[cmsLabel(@"宿主颜色信息将在渲染后显示。")retain];_context.textColor=DYThemeColor(@"secondary");_context.accessibilityLabel=@"当前颜色链路"; + for(NSView*v in @[_mode,_inputLabel,_input,_outputLabel,_output,_gamut,_lut,_help,_context])[self addSubview:v];[self refreshWithState:nil context:nil]; + }return self; +} +- (void)dealloc{[_renderer release];[_state release];for(id v in @[_mode,_input,_output,_gamut,_lut,_inputLabel,_outputLabel,_help,_context])[v release];[super dealloc];} +- (void)layout{[super layout];CGFloat w=self.bounds.size.width;_mode.frame=NSMakeRect(0,3,w,26);_inputLabel.frame=NSMakeRect(2,36,70,22);_input.frame=NSMakeRect(72,32,w-72,26);_outputLabel.frame=NSMakeRect(2,67,70,22);_output.frame=NSMakeRect(72,63,w-72,26);_gamut.frame=NSMakeRect(0,94,w,22);_lut.frame=NSMakeRect(0,120,w,25);_help.frame=NSMakeRect(2,152,w-4,65);_context.frame=NSMakeRect(2,220,w-4,45);} +- (void)refreshWithState:(NSDictionary*)s context:(NSDictionary*)context { + _refreshing=YES;[_state release];_state=[s copy];NSInteger mode=s.count?[s[@"mode"]integerValue]:0;[_mode selectItemAtIndex:mode]; + NSDictionary *values=s.count?s:DYManagedColorDefaults();for(NSMenuItem*i in _input.itemArray)if([i.representedObject isEqual:values[@"input"]])[_input selectItem:i];for(NSMenuItem*i in _output.itemArray)if([i.representedObject isEqual:values[@"output"]])[_output selectItem:i]; + _input.enabled=mode==2||mode==3;_output.enabled=mode==2||mode==3;_gamut.enabled=mode==2||mode==3;_gamut.state=[values[@"gamutCompression"]boolValue];_lut.hidden=mode!=3;_inputLabel.stringValue=mode==3?@"LUT 输出":@"输入空间";_outputLabel.stringValue=mode==1?@"跟随宿主":@"输出目标"; + _help.stringValue=mode==0?@"保留当前工程的原有颜色。选择新版后,一级层在 ACEScct 中调色,印片位于输出之前;可撤销或切回兼容方式。":mode==1?@"使用宿主实际颜色空间,不再次还原相机或执行显示映射。内部 ACEScct;旧式风格工具在明确的 Rec.709 修饰域运行。":mode==2?@"按所选相机编码解释兼容码值。请确认上游未还原、未自动符合;选择准确输入与输出目标。":@"使用输入 LUT,并按“LUT 输出”解释其结果;再进入 ACEScct 和所选输出变换。"; + _context.stringValue=context.count?[NSString stringWithFormat:@"%@ → ACEScct → %@",context[@"source"]?:@"未知",context[@"destination"]?:@"未知"]:@"宿主颜色信息将在渲染后显示。";_refreshing=NO;[self setNeedsLayout:YES]; +} +- (void)writeState:(NSDictionary*)state { + if(state&&!DYManagedColorValid(state,nil))return;ida=[_manager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;[a startAction:self];@try{idundo=[_manager apiForProtocol:@protocol(FxUndoAPI)];[undo startUndoGroup:@"更改色彩管理方式"];DYAssetState*assets=[[DYReadAssets(_manager,a.currentTime)copy]autorelease];assets.colorManagement=state;DYWriteAssets(_manager,assets,a.currentTime);[undo endUndoGroup];}@finally{[a endAction:self];}[_renderer invalidatePreview];[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:_manager]; +} +- (void)modeChanged:(id)sender {if(_refreshing)return;NSInteger mode=_mode.indexOfSelectedItem;if(!mode){[self writeState:nil];return;}NSMutableDictionary *s=[[_state?:DYManagedColorDefaults() mutableCopy]autorelease];s[@"mode"]=@(mode);[self writeState:s];} +- (void)settingsChanged:(id)sender {if(_refreshing||!_state)return;NSMutableDictionary*s=[[_state mutableCopy]autorelease];s[@"input"]=_input.selectedItem.representedObject;s[@"output"]=_output.selectedItem.representedObject;s[@"gamutCompression"]=@(_gamut.state==NSControlStateValueOn);[self writeState:s];} +- (void)chooseLUT:(id)sender {[_assetTarget performSelector:@selector(chooseFileForKey:) withObject:@"input"];} +@end diff --git a/大鱼调色/Plugin/DYManagedKernels.inc.h b/大鱼调色/Plugin/DYManagedKernels.inc.h index 611e7a7..9bdc166 100644 --- a/大鱼调色/Plugin/DYManagedKernels.inc.h +++ b/大鱼调色/Plugin/DYManagedKernels.inc.h @@ -12,7 +12,7 @@ kernel void dyManagedPrint(texture2d a [[texture(0)]],textur b.write(float4(dyManagedEncode(mix(dyManagedDecode(raw),dyManagedDecode(result),amount))*c.a,c.a),p); } kernel void dyManagedBlend(texture2d before [[texture(0)]],texture2d after [[texture(1)]],texture2d output [[texture(2)]],device const DYToolMaskEntry* masks [[buffer(0)]],constant DYToolMaskHeader& h [[buffer(1)]],uint2 p [[thread_position_in_grid]]){ - if(any(p>=uint2(output.get_width(),output.get_height())))return;float4 a=before.read(p),b=after.read(p);if(!(a.a>0)){output.write(a,p);return;} + if(any(p>=uint2(output.get_width(),output.get_height())))return;float4 a=before.read(p),b=after.read(p);if(!(a.a>0)||!(b.a>0)){output.write(a,p);return;} float3 ac=dyManagedDecode(a.rgb/a.a),bc=dyManagedDecode(b.rgb/b.a);float2 uv=(float2(p)+.5f)/float2(output.get_width(),output.get_height()); float w=dyToolCoverage(uv,dyToolEncode(dyPrintFromAP1(ac)),masks,h,h.section);if(w<=0){output.write(a,p);return;}if(w>=1){output.write(b,p);return;} output.write(float4(dyManagedEncode(mix(ac,bc,w))*a.a,a.a),p); @@ -22,3 +22,7 @@ kernel void dyManagedBlend(texture2d before [[texture(0)]],t kernel void dyManagedCarrier(texture2d a [[texture(0)]],texture2d b [[texture(1)]],texture3d cube [[texture(2)]],constant uint& useLUT [[buffer(0)]],uint2 p [[thread_position_in_grid]]){ if(any(p>=uint2(b.get_width(),b.get_height())))return;float4 c=a.read(p);if(c.a>0){float3 v=dyEncode(c.rgb/c.a);if(useLUT){constexpr sampler s(coord::normalized,address::clamp_to_edge,filter::linear);float n=cube.get_width();v=cube.sample(s,clamp(v,0.f,1.f)*((n-1)/n)+.5f/n).rgb;}c.rgb=v*c.a;}b.write(c,p); } + +fragment float4 dyManagedCopyFragment(DYRaster in [[stage_in]],texture2d source [[texture(0)]]){constexpr sampler f(coord::normalized,address::clamp_to_edge,filter::linear);return source.sample(f,in.uv);} + +kernel void dyManagedPreview(texture2d a [[texture(0)]],device float4* out [[buffer(0)]],uint2 p [[thread_position_in_grid]]){if(any(p>=uint2(320,180)))return;constexpr sampler s(coord::normalized,address::clamp_to_edge,filter::linear);float4 c=a.sample(s,(float2(p)+.5f)/float2(320,180));out[p.y*320+p.x]=float4(c.a>0?dyEncode(c.rgb/c.a):float3(0),c.a);} diff --git a/大鱼调色/Plugin/DYManagedRender.inc.h b/大鱼调色/Plugin/DYManagedRender.inc.h new file mode 100644 index 0000000..8f4fa85 --- /dev/null +++ b/大鱼调色/Plugin/DYManagedRender.inc.h @@ -0,0 +1,69 @@ +- (void)managedPreview:(id)texture origin:(FxImageOrigin)origin entry:(NSMutableDictionary*)entry { + @synchronized(_previewLock){if(_exporting||CACurrentMediaTime()-_lastPreview<=.5)return;} + idp=[self managedKernel:@"dyManagedPreview" entry:entry error:nil];if(!p)return; + idb=[entry[@"device"]newBufferWithLength:320*180*16 options:MTLResourceStorageModeShared];if(!b)return; + idcb=[entry[@"queue"]commandBuffer];idce=[cb computeCommandEncoder];[ce setComputePipelineState:p];[ce setTexture:texture atIndex:0];[ce setBuffer:b offset:0 atIndex:0];[ce dispatchThreads:MTLSizeMake(320,180,1) threadsPerThreadgroup:MTLSizeMake(8,8,1)];[ce endEncoding];[cb commit];[cb waitUntilCompleted]; + if(cb.status==MTLCommandBufferStatusCompleted){@synchronized(_previewLock){[_preview release];_preview=[[NSData alloc]initWithBytes:b.contents length:b.length];[_lookLUTPreview release];if(origin==kFxImageOrigin_BOTTOM_LEFT){NSMutableData *flipped=[NSMutableData dataWithLength:b.length];for(NSUInteger y=0;y<180;y++)memcpy((uint8_t*)flipped.mutableBytes+y*320*16,(uint8_t*)b.contents+(179-y)*320*16,320*16);_lookLUTPreview=[flipped copy];}else _lookLUTPreview=[_preview retain];_lastPreview=CACurrentMediaTime();}dispatch_async(dispatch_get_main_queue(),^{[NSNotificationCenter.defaultCenter postNotificationName:@"DYPreviewDidChange" object:self];});}[b release]; +} +// Included in DYRenderer. V1 callers and their ABI remain on renderSource:...tools:error:. +- (NSDictionary*)colorContext {@synchronized(_previewLock){return [[_colorContext copy]autorelease];}} +- (id)managedKernel:(NSString*)name entry:(NSMutableDictionary*)entry error:(NSError**)error { + NSMutableDictionary *cache=entry[@"managedKernels"];if(!cache){cache=[NSMutableDictionary dictionary];entry[@"managedKernels"]=cache;} + idpipeline=cache[name];if(!pipeline){idf=[entry[@"library"]newFunctionWithName:name];if(!f){fail(error,[@"色彩管理内核缺失:" stringByAppendingString:name]);return nil;}pipeline=[entry[@"device"]newComputePipelineStateWithFunction:f error:error];[f release];if(!pipeline)return nil;cache[name]=pipeline;[pipeline release];}return pipeline; +} +- (BOOL)managedDispatch:(NSString*)name textures:(NSArray*)textures data:(const void*)data length:(NSUInteger)length extra:(const void*)extra extraLength:(NSUInteger)extraLength entry:(NSMutableDictionary*)entry error:(NSError**)error { + idpipeline=[self managedKernel:name entry:entry error:error];if(!pipeline)return NO; + idcb=[entry[@"queue"]commandBuffer];idce=[cb computeCommandEncoder];[ce setComputePipelineState:pipeline];for(NSUInteger i=0;it=textures[0];[ce dispatchThreads:MTLSizeMake(t.width,t.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];[cb commit];[cb waitUntilCompleted];return cb.status==MTLCommandBufferStatusCompleted?YES:fail(error,cb.error.localizedDescription); +} +- (BOOL)managedConvert:(dycm::Space)from to:(dycm::Space)to display:(NSInteger)display gamut:(BOOL)gamut input:(id)input output:(id)output entry:(NSMutableDictionary*)entry error:(NSError**)error { + static std::mutex guard;static std::mapplans; + std::string key=std::to_string(unsigned(from))+":"+std::to_string(unsigned(to))+":"+std::to_string(display)+":"+std::to_string(gamut); + dycm::Transform transform=[&]{std::lock_guardlock(guard);auto i=plans.find(key);if(i!=plans.end())return i->second;auto t=display?dycm::Transform::display(from,dycm::Output(display),gamut):dycm::Transform::convert(from,to);if(plans.size()>=48)plans.clear();plans.emplace(key,t);return t;}(); + DYColorManagementGPU*p=[[DYColorManagementGPUCache sharedCache]pipelineWithDevice:entry[@"device"] transform:transform resourceBudget:128*1024*1024 error:error];if(!p)return NO;idcb=[entry[@"queue"]commandBuffer];if(![p encodeInput:input output:output alpha:dycm::Alpha::Premultiplied commandBuffer:cb workspaceBudget:2ull*1024*1024*1024 error:error])return NO;[cb commit];[cb waitUntilCompleted];return cb.status==MTLCommandBufferStatusCompleted?YES:fail(error,cb.error.localizedDescription); +} +- (BOOL)managedProfile:(DYColorProfile*)profile input:(id)input output:(id)output entry:(NSMutableDictionary*)entry error:(NSError**)error { + if(!profile)return NO;NSMutableDictionary*cache=entry[@"managedProfiles"];if(!cache){cache=[NSMutableDictionary dictionary];entry[@"managedProfiles"]=cache;}DYColorProfileGPU*p=cache[profile.key];if(!p){p=[[[DYColorProfileGPU alloc]initWithDevice:entry[@"device"] profile:profile error:error]autorelease];if(!p)return NO;if(cache.count>=16)[cache removeAllObjects];cache[profile.key]=p;}return [p renderInput:input output:output alpha:dycm::Alpha::Premultiplied workspaceBudget:2ull*1024*1024*1024 cancelled:nullptr error:error]; +} +- (BOOL)renderSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools colorManagement:(NSDictionary*)state hostPrimaries:(NSInteger)primaries error:(NSError**)error {@synchronized(self){@autoreleasepool{ + NSDictionary*context=DYHostColorContext(src,dst,primaries);@synchronized(_previewLock){[_colorContext release];_colorContext=[context copy];} + if(!state.count)return [self renderSource:src destination:dst uniforms:u paths:paths spider:spider tools:tools error:error]; + if(!DYManagedColorValid(state,error))return NO;if(!tools)tools=@{@"schema":@2,@"layers":@[],@"baseMasks":@{}};if(!DYValidToolDocument(tools))return fail(error,@"调色层或蒙版数据无效。"); + NSMutableDictionary*entry=[self device:dst.deviceRegistryID error:error];if(!entry)return NO;idd=entry[@"device"];idsource=[src metalTextureForDevice:d];if(!source)return fail(error,@"色彩管理输入纹理不可用。"); + uint64_t pixels=uint64_t(source.width)*source.height;if(!pixels||pixels>64ull*1024*1024||pixels*16*8>MAX(768ull*1024*1024,MIN(2ull*1024*1024*1024,d.recommendedMaxWorkingSetSize/2)))return fail(error,@"当前画面超过色彩管理内存预算。"); + CGColorSpaceRef srcSpace=DYManagedTileSpace(src,primaries),dstSpace=DYManagedTileSpace(dst,primaries),aces=CGColorSpaceCreateWithName(kCGColorSpaceACESCGLinear),linear709=CGColorSpaceCreateWithName(kCGColorSpaceExtendedLinearSRGB); + NSMutableArray*pool=[NSMutableArray array];idcurrent=nil; + auto next=[&](idexclude=nil)->id{for(idt in pool)if(t!=current&&t!=exclude)return t;MTLTextureDescriptor*td=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA32Float width:source.width height:source.height mipmapped:NO];td.storageMode=MTLStorageModePrivate;td.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite|MTLTextureUsageRenderTarget;idt=[d newTextureWithDescriptor:td];if(t){[pool addObject:t];[t release];}return t;}; + auto copy=[&](idinput,idoutput){return input&&output&&[self managedDispatch:@"dyManagedCopy" textures:@[input,output] data:nullptr length:0 extra:nullptr extraLength:0 entry:entry error:error];}; + auto convert=[&](dycm::Space a,dycm::Space b,NSInteger display=0,BOOL gamut=NO){idout=next();if(!out)return fail(error,@"无法分配色彩管理缓冲区。");BOOL ok=[self managedConvert:a to:b display:display gamut:gamut input:current output:out entry:entry error:error];if(ok)current=out;return ok;}; + auto profile=[&](DYColorProfile*p){idout=next();if(!out)return fail(error,@"无法分配颜色配置缓冲区。");BOOL ok=[self managedProfile:p input:current output:out entry:entry error:error];if(ok)current=out;return ok;}; + auto tile=[&](idtexture){DYExportTile*t=[[[DYExportTile alloc]initWithTexture:texture registry:d.registryID]autorelease];[t setBounds:src.tilePixelBounds origin:src.imageOrigin];[t setPixelAspect:src.pixelAspect];return t;}; + auto blend=[&](idbefore,NSArray*masks,NSString*type){if(!masks.count)return YES;idout=next(before);if(!out)return fail(error,@"无法分配工作空间蒙版缓冲区。");DYToolMaskHeader h{};idmb=[self maskBuffer:@{type:masks} tile:src device:d header:&h];h.section=(int)[DYToolTypes()indexOfObject:type];idp=[self managedKernel:@"dyManagedBlend" entry:entry error:error];if(!mb||!p)return NO;idcb=[entry[@"queue"]commandBuffer];idce=[cb computeCommandEncoder];[ce setComputePipelineState:p];[ce setTexture:before atIndex:0];[ce setTexture:current atIndex:1];[ce setTexture:out atIndex:2];[ce setBuffer:mb offset:0 atIndex:0];[ce setBytes:&h length:sizeof(h) atIndex:1];[ce dispatchThreads:MTLSizeMake(source.width,source.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];[cb commit];[cb waitUntilCompleted];if(cb.status!=MTLCommandBufferStatusCompleted)return fail(error,cb.error.localizedDescription);current=out;return YES;}; + auto basis=[&](DYUniforms values,NSArray*masks){values.cm.inputTransfer=values.cm.workingTransfer=values.cm.outputTransfer=1;values.cm.inputGamut=values.cm.workingGamut=values.cm.outputGamut=2;values.cm.toneMapping=0;values.inputSectionEnabled=values.cm.outputEnabled=0;if(values.primarySectionEnabled<.5||values.cm.basisEnabled<.5||identityCM(values)||values.cm.mix<=0)return YES;idbefore=current,out=next();BasisParams p=DYCMRender(values.cm).basis;float amount=values.cm.mix;if(!out||![self managedDispatch:@"dyManagedBasis" textures:@[current,out] data:&p length:sizeof(p) extra:&amount extraLength:4 entry:entry error:error])return NO;current=out;return blend(before,masks,@"primary");}; + auto print=[&](DYUniforms values,NSArray*masks){if(!DYFilmPrintActive(values))return YES;NSArray*names=@[@"",@"kodak_2383",@"kodak_2393",@"kodak_2302_bw",@"fuji_3510",@"fuji_3513",@"fuji_3519",@"fuji_3521",@"agfa_cp30"];NSString*path=[[NSBundle bundleForClass:self.class]pathForResource:names[(int)values.filmPrint.x] ofType:@"dylut" inDirectory:@"PrintLooks"];idcube=path?[self lut:path entry:entry error:error]:nil;if(!cube)return fail(error,@"印片资源不可用。");idbefore=current,out=next();float amount=values.filmPrint.y*values.film.mix;if(!out||![self managedDispatch:@"dyManagedPrint" textures:@[current,cube,out] data:&amount length:4 extra:nullptr extraLength:0 entry:entry error:error])return NO;current=out;return blend(before,masks,@"film");}; + @try{try{ + if(!dstSpace||(!srcSpace&&[state[@"mode"]integerValue]==1))return fail(error,@"宿主未提供明确颜色空间,无法使用新版管理。可切回旧版兼容。"); + idfirst=next();if(!copy(source,first))return NO;current=first; + NSInteger mode=[state[@"mode"]integerValue],output=[state[@"output"]integerValue]; + if(mode==1){DYColorProfile*p=[[[DYColorProfile alloc]initWithSource:srcSpace target:aces error:error]autorelease];if(!profile(p)||!convert(dycm::Space::ACEScg,dycm::Space::ACEScct))return NO;} + else {idout=next(),cube=entry[@"identity"];uint32_t useLUT=mode==3;if(useLUT){if(![paths[@"input"]length])return fail(error,@"请选择输入 LUT,并指定 LUT 输出空间。");cube=[self lut:paths[@"input"] entry:entry error:error];if(!cube)return NO;}if(!out||![self managedDispatch:@"dyManagedCarrier" textures:@[current,out,cube] data:&useLUT length:4 extra:nullptr extraLength:0 entry:entry error:error])return NO;current=out;if(!convert(dycm::Space([state[@"input"]unsignedIntValue]),dycm::Space::ACEScct))return NO;} + DYApplyRemovedBaseTools(&u,tools);if(!basis(u,tools[@"baseMasks"][@"primary"]))return NO; + NSMutableDictionary*finishing=DYMutablePlist(tools);NSMutableSet*sceneLayers=[NSMutableSet set]; + for(NSString*ID in DYToolDisplayOrder(tools)){NSDictionary*node=DYToolWithID(tools,ID);if([node[@"type"]isEqual:@"primary"]){if(!basis(DYToolUniforms(node),node[@"masks"]))return NO;[sceneLayers addObject:ID];}} + if(!print(u,tools[@"baseMasks"][@"film"]))return NO;for(NSString*ID in DYToolDisplayOrder(tools)){NSDictionary*node=DYToolWithID(tools,ID);if([node[@"type"]isEqual:@"film"]&&!print(DYToolUniforms(node),node[@"masks"]))return NO;} + for(NSString*ID in sceneLayers)DYRemoveTool(finishing,ID);for(NSMutableDictionary*node in finishing[@"layers"])if([node[@"type"]isEqual:@"film"])node[@"values"][@"filmPrintLook"]=@0; + u.primarySectionEnabled=0;u.cm.configured=-1;u.inputProfile=u.preLUTStrength=0;u.filmPrint.x=0; + if(mode==1){if(!convert(dycm::Space::ACEScct,dycm::Space::Linear709))return NO;} + else {if(!convert(dycm::Space::ACEScct,dycm::Space::ACEScct,output,[state[@"gamutCompression"]boolValue]))return NO;DYColorProfile*p=[[[DYColorProfile alloc]initWithDisplayOutput:dycm::Output(output) target:linear709 error:error]autorelease];if(!profile(p))return NO;} + // Bounded display tools are an explicit SDR finishing branch. HDR delivery + // uses the float32 primary / print / single-ODT core until these tools have + // measured HDR implementations; never silently clip them through old LUTs. + NSDictionary *finishPaths=DYVisibleBaseToolPaths(paths,finishing); + NSArray *activeFinish=DYManagedActiveFinishing(u,finishPaths,spider,finishing); + if(mode!=1&&(output==6||output==7)&&activeFinish.count)return fail(error,@"HDR 输出目前支持一级调色与印片。请关闭基础、曲线、风格、胶片空间等 SDR 修饰工具,或选择 SDR 输出。"); + [self managedPreview:current origin:src.imageOrigin entry:entry]; + if(activeFinish.count){idout=next();if(!out)return fail(error,@"无法分配显示域修饰缓冲区。");_managedFinishing=YES;BOOL ok=NO;@try{ok=[self renderSource:tile(current) destination:tile(out) uniforms:u paths:finishPaths spider:spider tools:finishing error:error];}@finally{_managedFinishing=NO;}if(!ok)return NO;current=out;} + DYColorProfile*returnProfile=[[[DYColorProfile alloc]initWithSource:linear709 target:dstSpace error:error]autorelease];if(!profile(returnProfile))return NO; + _managedFinishing=YES;@try{return [self copyTile:tile(current) to:dst entry:entry error:error];}@finally{_managedFinishing=NO;} + }catch(const std::exception&e){return fail(error,@(e.what()));}}@finally{if(srcSpace)CGColorSpaceRelease(srcSpace);if(dstSpace)CGColorSpaceRelease(dstSpace);if(aces)CGColorSpaceRelease(aces);if(linear709)CGColorSpaceRelease(linear709);} +}}} +- (BOOL)exportLUT:(NSURL*)url uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools colorManagement:(NSDictionary*)state error:(NSError**)error {@synchronized(self){if(state.count&&!DYManagedColorValid(state,error))return NO;if(state.count&&[state[@"mode"]integerValue]!=1&&[@[@6,@7]containsObject:state[@"output"]])return fail(error,@"PQ/HLG 交付需要明确的亮度与范围,请保存完整预设;当前静态 Cube 输出为 sRGB。");_exportManagedState=state.count?state:nil;@try{return [self exportLUT:url uniforms:u paths:paths spider:spider tools:tools error:error];}@finally{_exportManagedState=nil;}}} diff --git a/大鱼调色/Plugin/DYPlugIn.mm b/大鱼调色/Plugin/DYPlugIn.mm index 50afee7..2760ac7 100644 --- a/大鱼调色/Plugin/DYPlugIn.mm +++ b/大鱼调色/Plugin/DYPlugIn.mm @@ -38,7 +38,7 @@ } - (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;ida=[_apiManager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];[a startAction:self];DYUniforms u;DYReadUniforms(_apiManager,a.currentTime,&u);DYAssetState *assets=DYReadAssets(_apiManager,a.currentTime);NSDictionary*paths=[assets.paths copy];NSData *mesh=[assets.spiderMesh copy];NSDictionary *tools=[DYReadTools(_apiManager,a.currentTime).document copy];[a endAction:self];NSError*e=nil;BOOL ok=[_renderer exportLUT:url uniforms:u paths:paths spider:mesh tools:tools error:&e];[tools release];[mesh release];[paths release];if(!ok)[self alert:e.localizedDescription]; + NSURL*url=n.userInfo[@"url"];if(![url isKindOfClass:NSURL.class])return;ida=[_apiManager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];[a startAction:self];DYUniforms u;DYReadUniforms(_apiManager,a.currentTime,&u);DYAssetState *assets=DYReadAssets(_apiManager,a.currentTime);NSDictionary*paths=[assets.paths copy];NSDictionary *cms=[assets.colorManagement copy];NSData *mesh=[assets.spiderMesh copy];NSDictionary *tools=[DYReadTools(_apiManager,a.currentTime).document copy];[a endAction:self];NSError*e=nil;BOOL ok=[_renderer exportLUT:url uniforms:u paths:paths spider:mesh tools:tools colorManagement:cms error:&e];[cms release];[tools release];[mesh release];[paths release];if(!ok)[self alert:e.localizedDescription]; } - (void)applyValues:(NSDictionary*)values{if(!values){[self alert:@"尚未拿到当前片段画面,请移动播放头后重试。"];return;}ida=[_apiManager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];[a startAction:self];@try{ids=[_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)];} diff --git a/大鱼调色/Plugin/DYRenderer.mm b/大鱼调色/Plugin/DYRenderer.mm index 50c3ae4..ffc7d33 100644 --- a/大鱼调色/Plugin/DYRenderer.mm +++ b/大鱼调色/Plugin/DYRenderer.mm @@ -1,3 +1,8 @@ +#import "DYManagedColor.h" +#import "../../ColorManagement/Sources/DYColorManagementGPU.h" +#import "../../ColorManagement/Sources/DYColorProfile.h" +#include +#include #import "DYRenderer.h" #import "../Shared/DYBetaDiagnostics.h" #import "DYModel.h" @@ -26,6 +31,7 @@ static id texture3D(idd,const float*values,NSUInteger n){ - (void)dealloc{[_tex release];[super dealloc];} - (id)metalTextureForDevice:(id)d{return d.registryID==_registry?_tex:nil;} - (void)setBounds:(FxRect)bounds origin:(FxImageOrigin)origin{_bounds=bounds;_origin=origin;} +- (CGColorSpaceRef)colorSpace{static CGColorSpaceRef s;static dispatch_once_t once;dispatch_once(&once,^{s=CGColorSpaceCreateWithName(kCGColorSpaceExtendedLinearSRGB);});return s;} - (FxRect)tilePixelBounds{return _bounds;} - (FxRect)imagePixelBounds{return self.tilePixelBounds;} - (uint64_t)deviceRegistryID{return _registry;} @@ -56,6 +62,20 @@ static void bypassIdleSkin(DYUniforms *u){ for(int i=0;i<13;i++){BOOL group=(i>=6&&i<=9)?u->colorSectionEnabled>.5:u->baseSectionEnabled>.5;if(group&&enabled[i]>.5&&values[i]!=0)return;} u->skinProtection.x=0; } +// Admission and identity bypass for the explicitly bounded finishing domain. +static NSArray *DYManagedActiveFinishing(DYUniforms u,NSDictionary *paths,NSData *spider,NSDictionary *tools){ + bypassNeutralTools(&u);bypassIdleSkin(&u);if(u.cm.blackWhiteMix<=0)u.blackWhiteSectionEnabled=0; + NSMutableArray *active=[NSMutableArray array]; + for(NSString *type in DYToolTypes()){ + if([type isEqual:@"primary"])continue; + NSMutableDictionary *values=[NSMutableDictionary dictionary],*localPaths=[NSMutableDictionary dictionary]; + for(NSDictionary *d in DYBaseToolDescriptors(type))if([d[@"offset"]integerValue]>=0)values[d[@"key"]]=@(*(float*)((uint8_t*)&u+[d[@"offset"]unsignedIntegerValue])); + if([type isEqual:@"look"]&&u.lookSectionEnabled>.5)for(NSString *key in paths)if([key hasPrefix:@"look"])localPaths[key]=paths[key]; + NSMutableDictionary *node=[NSMutableDictionary dictionaryWithDictionary:@{@"type":type,@"values":values,@"paths":localPaths}];if([type isEqual:@"spider"]&&spider)node[@"spider"]=spider; + if(!DYToolIsNeutral(node))[active addObject:type]; + } + for(NSDictionary *node in tools[@"layers"])if(!DYToolIsNeutral(node))[active addObject:node[@"type"]];return active; +} @interface DYRenderer(){ NSMutableDictionary *_devices,*_luts,*_preparedLUTs; NSSet *_activeLUTPaths; @@ -65,14 +85,16 @@ static void bypassIdleSkin(DYUniforms *u){ NSData *_preview,*_lookLUTPreview; CFTimeInterval _lastPreview; BOOL _exporting; - NSDictionary *_toolDocument; + NSDictionary *_toolDocument,*_colorContext,*_exportManagedState; + BOOL _managedFinishing; } @end @implementation DYRenderer #include "DYFilmRender.inc.h" +#include "DYManagedRender.inc.h" #include "DYToolRender.inc.h" - (instancetype)init{if((self=[super init])){_previewLock=[NSObject new];_devices=[NSMutableDictionary new];_luts=[NSMutableDictionary new];_preparedLUTs=[NSMutableDictionary new];_activeLUTPaths=[NSSet new];_lutPreparationQueue=dispatch_queue_create("com.dayu.color.lut-upload",DISPATCH_QUEUE_SERIAL);dispatch_set_target_queue(_lutPreparationQueue,dispatch_get_global_queue(QOS_CLASS_USER_INITIATED,0));_tables=[DYColorTables new];}return self;} -- (void)dealloc{[_devices release];[_luts release];[_preparedLUTs release];[_activeLUTPaths release];dispatch_release(_lutPreparationQueue);[_tables release];[_preview release];[_lookLUTPreview release];[_previewLock release];[super dealloc];} +- (void)dealloc{[_devices release];[_luts release];[_preparedLUTs release];[_activeLUTPaths release];dispatch_release(_lutPreparationQueue);[_tables release];[_preview release];[_lookLUTPreview release];[_colorContext release];[_previewLock release];[super dealloc];} - (void)trimPreparedLUTsKeeping:(NSString *)path { if(_preparedLUTs.count<=12)return; for(NSString *key in _preparedLUTs.allKeys)if(![_activeLUTPaths containsObject:key]&&![key isEqualToString:path])[_preparedLUTs removeObjectForKey:key]; @@ -198,17 +220,18 @@ static void bypassIdleSkin(DYUniforms *u){ - (BOOL)exportLUT:(NSURL*)url uniforms:(DYUniforms)u paths:(NSDictionary*)paths error:(NSError**)err{return [self exportLUT:url uniforms:u paths:paths spider:nil error:err];} - (BOOL)exportLUT:(NSURL*)url uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider error:(NSError**)err{@synchronized(self){ if(DYFilmToolActive(u)&&DYFilmSpatialActive(u.film))return fail(err,@"胶片空间和颗粒处理不能保存到静态 Cube,请保存完整预设。"); - NSMutableDictionary *e=[self device:0 error:err];if(!e)return NO;idd=e[@"device"];const NSUInteger n=33,count=n*n*n,width=n*n,height=n; + NSMutableDictionary *e=[self device:0 error:err];if(!e)return NO;idd=e[@"device"];const NSUInteger n=_exportManagedState?65:33,count=n*n*n,width=n*n,height=n; MTLTextureDescriptor *desc=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA16Float width:width height:height mipmapped:NO];desc.storageMode=MTLStorageModeShared;desc.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite|MTLTextureUsageRenderTarget; idinput=[d newTextureWithDescriptor:desc],output=[d newTextureWithDescriptor:desc];if(!input||!output){[input release];[output release];return fail(err,@"无法分配 LUT 色格");} std::vector<__fp16>values(count*4);for(NSUInteger i=0;i=0)*(float*)((uint8_t*)&u+[d[@"offset"]unsignedIntegerValue])=v.floatValue;}return u;} BOOL DYToolIsNeutral(NSDictionary *node){NSString *type=node[@"type"];DYUniforms u=DYToolUniforms(node);NSDictionary *section=DYToolSection(type);BOOL enabled=YES;if([type isEqual:@"primary"])enabled=u.primarySectionEnabled>.5;else if([type isEqual:@"base"])enabled=u.baseSectionEnabled>.5||u.colorSectionEnabled>.5;else for(NSDictionary *d in DYDescriptors())if([d[@"pid"]isEqual:section[@"enabled"]])enabled=*(float*)((uint8_t*)&u+[d[@"offset"]unsignedIntegerValue])>.5;if(!enabled)return YES;if([type isEqual:@"primary"]&&u.cm.toneMapping>.5)return NO;if([type isEqual:@"mixer"])return !DYChannelMixerActive(u);if([type isEqual:@"film"])return !DYFilmToolActive(u);if([type isEqual:@"skin"])return u.skinProtection.y==0;if([node[@"type"]isEqual:@"spider"]&&[node[@"spider"]length]){auto mesh=DYSpiderMesh(node[@"spider"]);for(float v:dy::meshSamples(mesh))if(v!=0)return NO;}if([node[@"paths"]count])return NO;for(NSDictionary *d in DYDescriptors()){NSNumber *v=node[@"values"][d[@"key"]];if(v&&v.floatValue!=[d[@"default"]floatValue])return NO;}return YES;}