文件
dayu-color/大鱼调色/Plugin/DYPrimaryRender.inc.h
T

43 行
9.7 KiB
C

// Opt-in V3. The root primary owns input/working/output; V1/V2 stay frozen.
- (BOOL)renderPrimarySource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools hostPrimaries:(NSInteger)primaries error:(NSError**)error {
if(tools[@"sharedMasks"])tools=DYResolvedToolDocument(tools);
// The main eye bypasses the whole primary/CST module. Other tools retain
// their established unmanaged host workflow rather than inheriting a Log tag.
if(u.primarySectionEnabled<.5||DYBaseToolRemoved(tools,@"primary"))return [self renderSource:src destination:dst uniforms:u paths:paths spider:spider tools:tools error:error];
NSMutableDictionary*entry=[self device:dst.deviceRegistryID error:error];if(!entry)return NO;id<MTLDevice>d=entry[@"device"];id<MTLTexture>source=[src metalTextureForDevice:d];if(!source)return fail(error,@"一级 CST 输入纹理不可用。");
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,@"当前画面超过一级 CST 内存预算。");
DYApplyRemovedBaseTools(&u,tools);BOOL root=u.primarySectionEnabled>.5;BOOL transparent=identityCM(u)&&!DYFilmPrintActive(u);int wt=lroundf(u.cm.workingTransfer),wg=lroundf(u.cm.workingGamut);
NSMutableArray*pool=[NSMutableArray array];NSMutableSet*pinned=[NSMutableSet set];id<MTLTexture>current=nil;
auto next=[&]()->id<MTLTexture>{for(id<MTLTexture>t in pool)if(t!=current&&![pinned containsObject:t])return t;MTLTextureDescriptor*td=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA32Float width:source.width height:source.height mipmapped:NO];td.storageMode=MTLStorageModePrivate;td.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite|MTLTextureUsageRenderTarget;id<MTLTexture>t=[d newTextureWithDescriptor:td];if(t){[pool addObject:t];[t release];}return t;};
auto dispatch=[&](NSString*name,const void*params,NSUInteger length,const void*extra=nullptr,NSUInteger extraLength=0){id<MTLTexture>out=next();if(!out)return fail(error,@"无法分配一级 CST 缓冲区。");BOOL ok=[self managedDispatch:name textures:@[current,out] data:params length:length extra:extra extraLength:extraLength entry:entry error:error];if(ok)current=out;return ok;};
auto transform=[&](CSTParams p){if(p.inputTransfer==p.outputTransfer&&p.inputGamut==p.outputGamut&&!p.toneMapping)return YES;return dispatch(@"dyPrimaryCST",&p,sizeof(p));};
auto tile=[&](id<MTLTexture>t){DYExportTile*v=[[[DYExportTile alloc]initWithTexture:t registry:d.registryID]autorelease];[v setBounds:src.tilePixelBounds origin:src.imageOrigin];[v setPixelAspect:src.pixelAspect];return v;};
auto blend=[&](id<MTLTexture>before,NSArray*masks,float amount,NSString*type){if(!masks.count&&amount>=1)return YES;id<MTLTexture>out=next();if(!out)return fail(error,@"无法分配一级混合缓冲区。");DYToolMaskHeader h{};id<MTLBuffer>mb=[self maskBuffer:@{type:masks?:@[]} tile:src device:d header:&h];h.section=(int)[DYToolTypes()indexOfObject:type];DYCSTMixParams p={{wg,wt,2,20,0},{2,20,wg,wt,0},amount};id<MTLComputePipelineState>pipeline=[self managedKernel:@"dyPrimaryBlend" entry:entry error:error];if(!pipeline||!mb)return NO;id<MTLCommandBuffer>cb=[entry[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>ce=[cb computeCommandEncoder];[ce setComputePipelineState:pipeline];[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 setBytes:&p length:sizeof(p) atIndex:2];[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 grade=[&](DYUniforms values,NSArray*masks,BOOL local){if(values.primarySectionEnabled<.5||values.cm.mix<=0)return YES;DYUniforms neutral=values;neutral.inputSectionEnabled=neutral.cm.outputEnabled=0;BOOL gradeNeutral=identityCM(neutral);if(!local&&gradeNeutral)return YES;if(local&&identityCM(values))return YES;
DayuRenderParams p=DYCMRender(values.cm);p.input.toneMapping=0;if((int)lroundf(values.cm.workingTransfer)==20){p.reserved|=8;p.basis.colorspace=10;p.basisInput={(int)lroundf(values.cm.workingGamut),20,(int)lroundf(values.cm.workingGamut),10,0};p.basisOutput={(int)lroundf(values.cm.workingGamut),10,(int)lroundf(values.cm.workingGamut),20,0};}CSTParams back={wg,wt,wg,wt,0};
if(local){p.stages=(values.inputSectionEnabled>.5?1:0)|(gradeNeutral?0:2)|(values.cm.outputEnabled>.5?4:0);back={values.cm.outputEnabled>.5?(int)lroundf(values.cm.outputGamut):(int)lroundf(values.cm.workingGamut),values.cm.outputEnabled>.5?(int)lroundf(values.cm.outputTransfer):(int)lroundf(values.cm.workingTransfer),wg,wt,0};}
else{p.stages=2;}
id<MTLTexture>before=current;[pinned addObject:before];BOOL ok=dispatch(@"dyPrimaryGrade",&p,sizeof(p),&back,sizeof(back));if(ok)ok=blend(before,masks,values.cm.mix,@"primary");[pinned removeObject:before];return ok;
};
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"];id<MTLTexture>cube=path?[self lut:path entry:entry error:error]:nil;if(!cube)return fail(error,@"印片资源不可用。");id<MTLTexture>before=current;[pinned addObject:before];BOOL ok=transform({wg,wt,2,1,0});float amount=values.filmPrint.y*values.film.mix;if(ok){id<MTLTexture>out=next();ok=out&&[self managedDispatch:@"dyManagedPrint" textures:@[current,cube,out] data:&amount length:4 extra:nullptr extraLength:0 entry:entry error:error];if(ok)current=out;}if(ok)ok=transform({2,1,wg,wt,0});if(ok)ok=blend(before,masks,1,@"film");[pinned removeObject:before];return ok;};
// Recover only the pre-existing explicit code-value carrier. No display
// transform or host-profile-to-709 conversion precedes the declared input.
current=source;id<MTLTexture>carrier=next();uint32_t noLUT=0;if(!carrier||![self managedDispatch:@"dyManagedCarrier" textures:@[current,carrier,entry[@"identity"]] data:&noLUT length:4 extra:nullptr extraLength:0 entry:entry error:error])return NO;current=carrier;
if(root&&u.inputSectionEnabled>.5&&!transform({(int)lroundf(u.cm.inputGamut),(int)lroundf(u.cm.inputTransfer),wg,wt,0}))return NO;
if(!grade(u,tools[@"baseMasks"][@"primary"],NO))return NO;
NSMutableDictionary*finishing=DYMutablePlist(tools);NSMutableSet*scene=[NSMutableSet set];for(NSString*ID in DYToolDisplayOrder(tools)){NSDictionary*node=DYToolWithID(tools,ID);if([node[@"type"]isEqual:@"primary"]){transparent&=identityCM(DYToolUniforms(node));if(!grade(DYToolUniforms(node),node[@"masks"],YES))return NO;[scene 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"]){transparent&=!DYFilmPrintActive(DYToolUniforms(node));if(!print(DYToolUniforms(node),node[@"masks"]))return NO;}}
for(NSString*ID in scene)DYRemoveTool(finishing,ID);for(NSMutableDictionary*node in finishing[@"layers"])if([node[@"type"]isEqual:@"film"])node[@"values"][@"filmPrintLook"]=@0;
BOOL outputEnabled=root&&u.cm.outputEnabled>.5;int ot=outputEnabled?lroundf(u.cm.outputTransfer):wt,og=outputEnabled?lroundf(u.cm.outputGamut):wg;
// Only this stage owns the main display rendering / tone mapping.
if(outputEnabled&&!transform(DYCMRender(u.cm).output))return NO;
u.primarySectionEnabled=0;u.cm.configured=-1;u.inputProfile=u.preLUTStrength=0;u.filmPrint.x=0;NSDictionary*finishPaths=DYVisibleBaseToolPaths(paths,finishing);NSArray*activeFinish=DYPrimaryActiveFinishing(u,finishPaths,spider,finishing);
BOOL display=outputEnabled&&ot>=1001&&ot<=1003;
if(!display&&activeFinish.count)return fail(error,@"当前是 Log/线性码值输出。SDR 修饰工具需要显示输出,请选择 Gamma 输出,或关闭这些工具并保存完整预设。");
if(!display&&transparent&&!activeFinish.count){current=source;[self managedPreview:current origin:src.imageOrigin entry:entry];}else if(display&&_exporting&&!activeFinish.count){if(!dispatch(@"dyPrimaryCodeOutput",nullptr,0))return NO;}else if(display){if(!transform({og,ot,22,20,0}))return NO;[self managedPreview:current origin:src.imageOrigin entry:entry];
if(activeFinish.count){id<MTLTexture>out=next();if(!out)return fail(error,@"无法分配 SDR 修饰缓冲区。");_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;}
if(_exporting){if(!transform({22,20,og,ot,0})||!dispatch(@"dyPrimaryCodeOutput",nullptr,0))return NO;}else{CGColorSpaceRef from=CGColorSpaceCreateWithName(kCGColorSpaceExtendedLinearSRGB),to=DYManagedTileSpace(dst,primaries);DYColorProfile*p=to?[[[DYColorProfile alloc]initWithSource:from target:to error:error]autorelease]:nil;CGColorSpaceRelease(from);if(to)CGColorSpaceRelease(to);if(!p)return fail(error,@"宿主未提供明确的目标颜色空间。");id<MTLTexture>out=next();if(!out||![self managedProfile:p input:current output:out entry:entry error:error])return NO;current=out;}
}else{if(!dispatch(@"dyPrimaryCodeOutput",nullptr,0))return NO;[self managedPreview:current origin:src.imageOrigin entry:entry];}
_managedFinishing=YES;@try{return [self copyTile:tile(current) to:dst entry:entry error:error];}@finally{_managedFinishing=NO;}
}