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

69 行
8.8 KiB
C

// All work uses the renderer instance's lock and frozen state. No vendor code
// or vendor runtime is loaded by the product.
- (BOOL)renderFilmTool:(NSString*)type source:(FxImageTile*)source destination:(FxImageTile*)destination uniforms:(DYUniforms)u masks:(NSArray*)masks entry:(NSMutableDictionary*)entry error:(NSError**)error {
BOOL mixer=[type isEqual:@"mixer"],active=mixer?DYChannelMixerActive(u):DYFilmToolActive(u);
if(!active)return [self copyTile:source to:destination entry:entry error:error];
id<MTLDevice>d=entry[@"device"];id<MTLTexture>before=[source metalTextureForDevice:d];
if(!before)return fail(error,@"胶片输入纹理不可用");
// At most two working, two auxiliary half-float textures and two float32
// bloom prefilters. Allocate lazily; reuse between all five stages.
uint64_t bytes=uint64_t(before.width)*before.height*(mixer?16:DYFilmBloomActive(u.film)?64:32);
uint64_t budget=MIN(uint64_t(2)*1024*1024*1024,MAX(uint64_t(512)*1024*1024,d.recommendedMaxWorkingSetSize/3));
if(bytes>budget)return fail(error,@"当前画面超过胶片处理内存预算,请降低工程分辨率后重试。");
NSMutableArray *textures=[NSMutableArray array];id<MTLTexture>slots[6]={nil,nil,nil,nil,nil,nil};
auto texture=[&](int slot)->id<MTLTexture>{if(!slots[slot]){MTLTextureDescriptor *desc=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:slot>=4?MTLPixelFormatRGBA32Float:MTLPixelFormatRGBA16Float width:before.width height:before.height mipmapped:NO];desc.storageMode=MTLStorageModePrivate;desc.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite|MTLTextureUsageRenderTarget;id<MTLTexture>t=[d newTextureWithDescriptor:desc];if(t){[textures addObject:t];slots[slot]=t;[t release];}}return slots[slot];};
CIContext *context=entry[@"filmCIContext"];if(!context){context=[CIContext contextWithMTLDevice:d options:@{kCIContextWorkingColorSpace:NSNull.null,kCIContextOutputColorSpace:NSNull.null,kCIContextCacheIntermediates:@NO}];if(!context)return fail(error,@"胶片空间处理器不可用");entry[@"filmCIContext"]=context;}
CGRect bounds=CGRectMake(0,0,before.width,before.height);id<MTLCommandBuffer>commands=[entry[@"queue"]commandBuffer];
auto image=[&](id<MTLTexture>t){return [CIImage imageWithMTLTexture:t options:@{kCIImageColorSpace:NSNull.null}];};
auto blur=[&](id<MTLTexture>input,id<MTLTexture>output,float radius,BOOL clamp){
CIImage *ci=image(input);if(!ci)return NO;if(clamp)ci=[ci imageByClampingToExtent];
ci=[[ci imageByApplyingFilter:@"CIGaussianBlur" withInputParameters:@{kCIInputRadiusKey:@(radius)}]imageByCroppingToRect:bounds];
[context render:ci toMTLTexture:output commandBuffer:commands bounds:bounds colorSpace:nil];return YES;
};
auto encode=[&](NSString *name,id<MTLTexture>a,id<MTLTexture>b,id<MTLTexture>out,const void *data,NSUInteger length){
id<MTLComputeCommandEncoder>ce=[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];
};
id<MTLTexture>current=before;
auto point=[&](int operation,id<MTLTexture>aux){id<MTLTexture>out=texture(current==slots[0]?1:0);if(!out)return NO;struct {int operation;float radius;unsigned frameKey,reserved;}pass={operation,0,u.filmFrameKey,0};id<MTLComputeCommandEncoder>ce=[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 {
if(DYFilmSubActive(u.film)&&!point(1,nil))return fail(error,@"无法分配减色缓冲区");
if(DYFilmHaloActive(u.film)){id<MTLTexture>aux=texture(2);if(!aux||!blur(current,aux,u.film.scatter,YES)||!point(2,aux))return fail(error,@"晕光空间处理失败");}
if(DYFilmBloomActive(u.film)){
id<MTLTexture>a=texture(4),b=texture(5),edges=texture(2),spread=texture(3);if(!a||!b||!edges||!spread)return fail(error,@"无法分配辉光缓冲区");
int direction=0;encode(@"dyFilmSparseBlur",current,nil,a,&direction,sizeof(direction));direction=1;encode(@"dyFilmSparseBlur",a,nil,b,&direction,sizeof(direction));
encode(@"dyFilmBloomEdges",b,current,edges,&u.film,sizeof(u.film));if(!blur(edges,spread,u.film.diffusion,NO)||!point(3,spread))return fail(error,@"辉光空间处理失败");
}
if(DYFilmGrainActive(u.film)){
id<MTLTexture>noise=texture(2);if(!noise)return fail(error,@"无法分配颗粒缓冲区");
id<MTLComputeCommandEncoder>ce=[commands computeCommandEncoder];[ce setComputePipelineState:entry[@"dyFilmNoise"]];[ce setTexture:noise atIndex:0];[ce setBytes:&u.filmFrameKey length:4 atIndex:0];unsigned bottom=source.imageOrigin==kFxImageOrigin_BOTTOM_LEFT;[ce setBytes:&bottom length:4 atIndex:1];[ce dispatchThreads:MTLSizeMake(noise.width,noise.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];
if(u.film.grainSize>1){id<MTLTexture>smooth=texture(3);if(!smooth)return fail(error,@"无法分配颗粒扩散缓冲区");
// Reference radius=2. Recover the same sigma search without frame state.
double sigma=1,step=1;for(int iteration=0;iteration<20000;iteration++){double density=exp(-4/(sigma*sigma))/(sigma*sigma*6.283185307179586);if(.02/5<density){if(step<=.02)break;sigma-=step;step*=.1;}sigma+=step;if(sigma>1000){sigma=1;break;}}
MPSImageGaussianBlur *gaussian=[[[MPSImageGaussianBlur alloc]initWithDevice:d sigma:float(sigma*u.film.grainSize/5)]autorelease];gaussian.edgeMode=MPSImageEdgeModeClamp;[gaussian encodeToCommandBuffer:commands sourceTexture:noise destinationTexture:smooth];noise=smooth;
}
if(!point(4,noise))return fail(error,@"颗粒处理失败");
}
if(DYFilmVignetteActive(u.film)){
id<MTLTexture>aux=texture(2);if(!aux)return fail(error,@"无法分配暗角缓冲区");CIImage *ci=image(current);if(!ci)return fail(error,@"暗角输入不可用");
ci=[ci imageByApplyingFilter:@"CIVignetteEffect" withInputParameters:@{kCIInputCenterKey:[CIVector vectorWithX:before.width*.5 Y:before.height*.5],kCIInputIntensityKey:@(u.film.vignetteIntensity),kCIInputRadiusKey:@(u.film.vignetteRadius/100.f*MAX(before.width,before.height)),@"inputFalloff":@(u.film.vignetteFalloff)}];[context render:ci toMTLTexture:aux commandBuffer:commands bounds:bounds colorSpace:nil];if(!point(5,aux))return fail(error,@"暗角处理失败");
}
if(DYFilmPrintActive(u)){
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)u.filmPrint.x] ofType:@"dylut" inDirectory:@"PrintLooks"];
if(!path)return fail(error,@"印片外观资源缺失,请重新安装正式版。");id<MTLTexture>cube=[self lut:path entry:entry error:error];if(!cube)return NO;
if(cube.width!=65||cube.height!=65||cube.depth!=65)return fail(error,@"印片外观尺寸不正确,请重新安装正式版。");
id<MTLTexture>out=texture(current==slots[0]?1:0);if(!out)return fail(error,@"无法分配印片缓冲区");
encode(@"dyFilmPrint",current,cube,out,&u,sizeof(u));current=out;
}
if(u.film.mix<1){id<MTLTexture>out=texture(current==slots[0]?1:0);if(!out)return fail(error,@"无法分配胶片混合缓冲区");encode(@"dyFilmMix",before,current,out,&u.film.mix,4);current=out;}
}
// Finish the effect before the module's existing mask blend. Source and
// result retain identical alpha, and an empty mask group means full coverage.
if(masks.count){id<MTLTexture>out=texture(current==slots[0]?1:0);if(!out)return fail(error,@"无法分配胶片蒙版缓冲区");DYToolMaskHeader header{};header.section=(int)[DYToolTypes()indexOfObject:type];id<MTLBuffer>buffer=[self maskBuffer:@{type:masks} tile:source device:d header:&header];[self encodeBlend:before after:current output:out masks:buffer header:header entry:entry commands:commands];current=out;}
[commands commit];[commands waitUntilCompleted];if(commands.status!=MTLCommandBufferStatusCompleted)return fail(error,commands.error.localizedDescription);
DYExportTile *result=[[[DYExportTile alloc]initWithTexture:current registry:d.registryID]autorelease];[result setBounds:source.tilePixelBounds origin:source.imageOrigin];[result setPixelAspect:source.pixelAspect];return [self copyTile:result to:destination entry:entry error:error];
}@catch(NSException *exception){return fail(error,[@"胶片处理失败:" stringByAppendingString:exception.reason?:@""]);}
}