文件
dayu-color/大鱼调色/Plugin/DYDiagnostics.mm
T

433 行
56 KiB
Plaintext

#import "DYDiagnostics.h"
#import "DYModel.h"
#import "DYRenderer.h"
#import "DYAutoGrade.h"
#import "DYLUTLibrary.h"
#import "DYInspector.h"
#include "DYSpiderState.h"
#include <string>
#import <CoreVideo/CoreVideo.h>
#import <IOSurface/IOSurface.h>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
#include "DYToolTrackingProbe.inc.h"
// Fake host objects implement the real selectors used by the model and renderer.
// They never connect to a host document or enter the FxPrincipal service loop.
@interface DYDiagnosticManager : NSObject<PROAPIAccessing> {
@public
NSMutableDictionary *_values,*_custom;
BOOL _duplicate;
@public
int _undoStarts,_undoEnds;BOOL _undoActive;
}
@end
@interface DYInspector (DiagnosticActions)
- (void)refresh;
- (void)resetAll:(id)sender;
@end
@protocol DYSpiderProbe
@property(nonatomic,copy) NSData *meshData;
@property(nonatomic,retain) NSMutableIndexSet *selection,*pinned;
@property(nonatomic,copy) void(^changed)(DYGrade,NSData*);
@property(nonatomic,copy) void(^gesture)(BOOL);
@property(nonatomic,readonly) NSInteger hueCount,saturationCount;
- (void)changeHueCount:(int)hues saturationCount:(int)saturation;
- (void)resetMesh;
- (NSPoint)point:(NSInteger)index;
- (void)selectRing;
- (void)selectSpoke;
- (void)resetSelected;
@end
@implementation DYDiagnosticManager
- (instancetype)init {if((self=[super init])){_values=[NSMutableDictionary new];_custom=[NSMutableDictionary new];}return self;}
- (void)dealloc {[_values release];[_custom release];[super dealloc];}
- (id)apiForProtocol:(Protocol *)protocol {
NSString *name=NSStringFromProtocol(protocol);
return [@[@"FxParameterCreationAPI_v5",@"FxParameterRetrievalAPI_v6",@"FxParameterSettingAPI_v6",@"FxCustomParameterActionAPI_v4",@"FxUndoAPI"]containsObject:name]?self:nil;
}
- (BOOL)startUndoGroup:(NSString *)title{_undoStarts++;_undoActive=YES;return YES;}
- (BOOL)endUndoGroup{_undoEnds++;_undoActive=NO;return YES;}
- (void)startAction:(id)sender{}
- (void)endAction:(id)sender{}
- (CMTime)currentTime{return kCMTimeZero;}
- (BOOL)addFloatSliderWithName:(NSString *)name parameterID:(UInt32)pid defaultValue:(double)value parameterMin:(double)minimum parameterMax:(double)maximum sliderMin:(double)sliderMinimum sliderMax:(double)sliderMaximum delta:(double)delta parameterFlags:(FxParameterFlags)flags {
if(_values[@(pid)]||_custom[@(pid)]){_duplicate=YES;return NO;}_values[@(pid)]=@(value);return YES;
}
- (BOOL)addStringParameterWithName:(NSString*)name parameterID:(UInt32)pid defaultValue:(NSString*)value parameterFlags:(FxParameterFlags)flags{if(_values[@(pid)]||_custom[@(pid)]){_duplicate=YES;return NO;}_custom[@(pid)]=value;return YES;}
- (BOOL)addCustomParameterWithName:(NSString *)name parameterID:(UInt32)pid defaultValue:(NSObject<NSSecureCoding,NSCopying> *)value parameterFlags:(FxParameterFlags)flags {
if(_values[@(pid)]||_custom[@(pid)]){_duplicate=YES;return NO;}_custom[@(pid)]=value;return YES;
}
- (BOOL)getStringParameterValue:(NSString**)value fromParameter:(UInt32)pid{id string=_custom[@(pid)];if(![string isKindOfClass:NSString.class])return NO;if(value)*value=string;return YES;}
- (BOOL)setStringParameterValue:(NSString*)value toParameter:(UInt32)pid{if(![_custom[@(pid)]isKindOfClass:NSString.class])return NO;_custom[@(pid)]=value;return YES;}
- (BOOL)getFloatValue:(double *)value fromParameter:(UInt32)pid atTime:(CMTime)time {
NSNumber *stored=_values[@(pid)];if(!stored)return NO;if(value)*value=stored.doubleValue;return YES;
}
- (BOOL)setFloatValue:(double)value toParameter:(UInt32)pid atTime:(CMTime)time {
if(!_values[@(pid)])return NO;_values[@(pid)]=@(value);return YES;
}
- (BOOL)getCustomParameterValue:(NSObject<NSSecureCoding,NSCopying> **)value fromParameter:(UInt32)pid atTime:(CMTime)time {
id stored=_custom[@(pid)];if(!stored)return NO;if(value)*value=stored;return YES;
}
- (BOOL)setCustomParameterValue:(NSObject<NSSecureCoding,NSCopying> *)value toParameter:(UInt32)pid atTime:(CMTime)time {
if(!_custom[@(pid)]||!value)return NO;_custom[@(pid)]=[[value copy]autorelease];return YES;
}
@end
@interface DYDiagnosticTile : FxImageTile {
id<MTLTexture> _texture;
IOSurfaceRef _surface;
FxRect _bounds;
uint64_t _registry;
FxImageOrigin _diagnosticOrigin;
}
- (instancetype)initWithDevice:(id<MTLDevice>)device width:(NSUInteger)width height:(NSUInteger)height;
- (void)setDiagnosticImageOrigin:(FxImageOrigin)origin;
@end
@implementation DYDiagnosticTile
- (instancetype)initWithDevice:(id<MTLDevice>)device width:(NSUInteger)width height:(NSUInteger)height {
if((self=[super init])) {
NSDictionary *properties=@{(id)kIOSurfaceWidth:@(width),(id)kIOSurfaceHeight:@(height),
(id)kIOSurfaceBytesPerElement:@8,(id)kIOSurfaceBytesPerRow:@(width*8),
(id)kIOSurfacePixelFormat:@(kCVPixelFormatType_64RGBAHalf)};
_surface=IOSurfaceCreate((CFDictionaryRef)properties);
MTLTextureDescriptor *d=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA16Float width:width height:height mipmapped:NO];
d.storageMode=MTLStorageModeShared;d.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite|MTLTextureUsageRenderTarget;
if(_surface)_texture=[device newTextureWithDescriptor:d iosurface:_surface plane:0];
_bounds=(FxRect){0,0,(SInt32)width,(SInt32)height};_registry=device.registryID;_diagnosticOrigin=kFxImageOrigin_TOP_LEFT;
if(!_surface||!_texture){[self release];return nil;}
}return self;
}
- (void)dealloc {[_texture release];if(_surface)CFRelease(_surface);[super dealloc];}
- (id<MTLTexture>)metalTextureForDevice:(id<MTLDevice>)device {return device.registryID==_registry?_texture:nil;}
- (IOSurface *)ioSurface {return (IOSurface *)_surface;}
- (FxRect)tilePixelBounds {return _bounds;}
- (FxRect)imagePixelBounds {return _bounds;}
- (uint64_t)deviceRegistryID {return _registry;}
- (FxImageOrigin)imageOrigin {return _diagnosticOrigin;}
- (double)pixelAspect{return 1;}
- (void)setDiagnosticImageOrigin:(FxImageOrigin)origin {_diagnosticOrigin=origin;}
@end
namespace {
using Pixels=std::vector<__fp16>;
struct Run {
NSMutableArray *rows=[NSMutableArray array];
bool passed=true;
void record(NSString *name,bool ok,NSDictionary *details=nil) {
NSMutableDictionary *row=[NSMutableDictionary dictionaryWithDictionary:details?:@{}];
row[@"name"]=name;row[@"pass"]=@(ok);[rows addObject:row];if(!ok)passed=false;
}
void need(NSString *name,bool ok,NSDictionary *details=nil) {
record(name,ok,details);if(!ok)@throw [NSException exceptionWithName:@"DYDiagnosticStop" reason:name userInfo:nil];
}
};
static NSString *reason(NSError *error) {return error.localizedDescription?:@"未提供错误信息";}
static Pixels read(DYDiagnosticTile *tile,id<MTLDevice> gpu) {
id<MTLTexture> texture=[tile metalTextureForDevice:gpu];Pixels output(texture.width*texture.height*4);
[texture getBytes:output.data() bytesPerRow:texture.width*8 fromRegion:MTLRegionMake2D(0,0,texture.width,texture.height) mipmapLevel:0];return output;
}
struct Difference {double maximum=0;size_t different=0,nonfinite=0,nonzero=0;};
static Difference difference(const Pixels& a,const Pixels& b) {
Difference found;if(a.size()!=b.size()){found.nonfinite=1;return found;}
for(size_t i=0;i<a.size();i++){double x=a[i],y=b[i];if(!std::isfinite(x)||!std::isfinite(y)){found.nonfinite++;continue;}double error=std::fabs(x-y);found.maximum=std::max(found.maximum,error);if(error>1e-5)found.different++;if(y!=0)found.nonzero++;}return found;
}
static NSDictionary *measure(Difference d) {return @{@"maxAbsoluteError":@(d.maximum),@"changedComponents":@(d.different),@"nonfiniteComponents":@(d.nonfinite),@"nonzeroComponents":@(d.nonzero)};}
static Pixels render(Run& run,DYRenderer *renderer,DYDiagnosticTile *source,DYDiagnosticTile *destination,id<MTLDevice> gpu,DYUniforms uniforms,NSDictionary *paths,NSString *name) {
NSError *error=nil;BOOL ok=[renderer renderSource:source destination:destination uniforms:uniforms paths:paths error:&error];
run.need(name,ok,@{@"error":ok?@"":reason(error)});return read(destination,gpu);
}
static Pixels referenceFrame(id<MTLDevice> gpu,id<MTLLibrary> library,const Pixels &premult,NSUInteger width,NSUInteger height,DayuRenderParams params,NSError **error){
MTLTextureDescriptor *td=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA16Float width:width height:height mipmapped:NO];td.storageMode=MTLStorageModeShared;td.usage=MTLTextureUsageShaderRead;
id<MTLTexture>source=[gpu newTextureWithDescriptor:td];td.pixelFormat=MTLPixelFormatRGBA32Float;td.usage=MTLTextureUsageRenderTarget;id<MTLTexture>dest=[gpu newTextureWithDescriptor:td];
Pixels encoded(premult.size());for(NSUInteger i=0;i<width*height;i++){float alpha=premult[i*4+3];for(int c=0;c<3;c++){float v=alpha>0?(float)(__fp16)((float)premult[i*4+c]/alpha):0;encoded[i*4+c]=v<=.0031308f?v*12.92f:1.055f*powf(v,1/2.4f)-.055f;}encoded[i*4+3]=alpha;}
[source replaceRegion:MTLRegionMake2D(0,0,width,height) mipmapLevel:0 withBytes:encoded.data() bytesPerRow:width*8];
MTLRenderPipelineDescriptor *pd=[MTLRenderPipelineDescriptor new];pd.vertexFunction=[library newFunctionWithName:@"vertexShader"];pd.fragmentFunction=[library newFunctionWithName:@"fragmentShader"];pd.colorAttachments[0].pixelFormat=MTLPixelFormatRGBA32Float;
id<MTLRenderPipelineState>pipeline=[gpu newRenderPipelineStateWithDescriptor:pd error:error];[pd.vertexFunction release];[pd.fragmentFunction release];[pd release];
Pixels result;if(pipeline){id<MTLCommandQueue>q=[gpu newCommandQueue];id<MTLCommandBuffer>cb=[q commandBuffer];MTLRenderPassDescriptor *rp=[MTLRenderPassDescriptor renderPassDescriptor];rp.colorAttachments[0].texture=dest;rp.colorAttachments[0].loadAction=MTLLoadActionDontCare;rp.colorAttachments[0].storeAction=MTLStoreActionStore;id<MTLRenderCommandEncoder>e=[cb renderCommandEncoderWithDescriptor:rp];
float w=width,h=height;DYVertex2D vertices[]={{{w/2,-h/2},{1,1}},{{-w/2,-h/2},{0,1}},{{w/2,h/2},{1,0}},{{-w/2,h/2},{0,0}}};vector_uint2 vp={(unsigned)width,(unsigned)height};id<MTLBuffer>hist=[gpu newBufferWithLength:800 options:MTLResourceStorageModeShared];
[e setRenderPipelineState:pipeline];[e setVertexBytes:vertices length:sizeof(vertices) atIndex:0];[e setVertexBytes:&vp length:sizeof(vp) atIndex:1];[e setFragmentTexture:source atIndex:0];[e setFragmentTexture:source atIndex:1];[e setFragmentBytes:&params length:sizeof(params) atIndex:0];[e setFragmentBuffer:hist offset:0 atIndex:1];[e drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4];[e endEncoding];[cb commit];[cb waitUntilCompleted];
if(cb.status==MTLCommandBufferStatusCompleted){std::vector<float>pixels(width*height*4);[dest getBytes:pixels.data() bytesPerRow:width*16 fromRegion:MTLRegionMake2D(0,0,width,height) mipmapLevel:0];result.resize(premult.size());for(NSUInteger i=0;i<width*height;i++){float a=premult[i*4+3];for(int c=0;c<3;c++){float v=pixels[i*4+c];float linear=v<=.04045f?v/12.92f:powf((v+.055f)/1.055f,2.4f);result[i*4+c]=a>0?(__fp16)((float)(__fp16)linear*a):0;}result[i*4+3]=a;}}
[hist release];[q release];
}
[pipeline release];[source release];[dest release];return result;
}
static float *field(DYUniforms *u,NSDictionary *row){return (float *)((uint8_t *)u+[row[@"offset"]unsignedIntegerValue]);}
}
extern "C" int DYRunDiagnostics(void) { @autoreleasepool {
Run run;NSString *runtime=nil;NSString *gpuName=@"unavailable";
@try {
NSError *error=nil;
runtime=[@"/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/verification-runtime" stringByAppendingPathComponent:NSUUID.UUID.UUIDString];
run.need(@"runtime-directory",[[NSFileManager defaultManager]createDirectoryAtPath:runtime withIntermediateDirectories:YES attributes:nil error:&error],@{@"path":runtime,@"error":reason(error)});
NSArray *descriptors=DYDescriptors(),*sections=DYSections();NSMutableSet *pids=[NSMutableSet set],*offsets=[NSMutableSet set],*keys=[NSMutableSet set];bool schema=true;
for(NSDictionary *row in descriptors){NSInteger offset=[row[@"offset"]integerValue];NSNumber *pid=row[@"pid"];bool metadata=offset==-1&&pid.unsignedIntValue==8800&&[row[@"key"]isEqual:@"copyAutoGrade"];schema&=(metadata||(offset>=0&&offset%4==0&&offset+4<=sizeof(DYUniforms)&&pid.unsignedIntValue==2000+offset/4&&![offsets containsObject:row[@"offset"]]))&&![pids containsObject:pid]&&![keys containsObject:row[@"key"]];[pids addObject:pid];if(offset>=0)[offsets addObject:row[@"offset"]];[keys addObject:row[@"key"]];}
run.need(@"descriptor-unique-id-offset-key",schema,@{@"descriptors":@(descriptors.count),@"sections":@(sections.count),@"uniformBytes":@(sizeof(DYUniforms))});
DYUniforms defaults;DYDefaultUniforms(&defaults);bool finite=true,matches=true;
// SIMD float3 has a fourth ABI lane that is padding, not a semantic
// value. Check every represented control and every matrix component.
for(NSDictionary *row in descriptors)if([row[@"offset"]integerValue]>=0){float value=*field(&defaults,row);finite&=std::isfinite(value);matches&=value==[row[@"default"]floatValue];}
for(int c=0;c<3;c++)finite&=std::isfinite(defaults.primariesM0[c])&&std::isfinite(defaults.primariesM1[c])&&std::isfinite(defaults.primariesM2[c]);
run.need(@"finite-real-model-defaults",finite&&matches);
run.record(@"new-input-default-sony-slog3-sgamut3-cine",defaults.cm.inputTransfer==28&&defaults.cm.inputGamut==27&&defaults.cm.outputTransfer==1002&&defaults.cm.outputGamut==22);
bool initialGroups=true;
for(NSDictionary *section in sections){BOOL base=YES;for(NSDictionary *row in descriptors)if([row[@"pid"]isEqual:section[@"enabled"]])initialGroups&=([row[@"default"]doubleValue]>=.5)==base;}
run.record(@"all-module-eyes-enabled-by-default",initialGroups);
DYDiagnosticManager *manager=[[[DYDiagnosticManager alloc]init]autorelease];error=nil;
run.need(@"native-parameter-creation",DYCreateParameters(manager,&error)&&!manager->_duplicate&&manager->_values.count==descriptors.count&&manager->_custom.count==4,@{@"error":reason(error)});
id<FxParameterSettingAPI_v6> setter=[manager apiForProtocol:@protocol(FxParameterSettingAPI_v6)];id<FxParameterRetrievalAPI_v6> getter=[manager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)];
[setter setFloatValue:.75 toParameter:2000 atTime:kCMTimeZero];double value=0;[getter getFloatValue:&value fromParameter:2000 atTime:kCMTimeZero];DYUniforms restored;DYReadUniforms(manager,kCMTimeZero,&restored);
run.record(@"native-get-set-model-roundtrip",value==.75&&restored.exposure==.75f);
[setter setFloatValue:999 toParameter:2000 atTime:kCMTimeZero];DYReadUniforms(manager,kCMTimeZero,&restored);run.record(@"model-clamps-host-out-of-range",restored.exposure==5);
[setter setFloatValue:NAN toParameter:2000 atTime:kCMTimeZero];DYReadUniforms(manager,kCMTimeZero,&restored);run.record(@"model-rejects-host-nonfinite",restored.exposure==defaults.exposure);
DYAssetState *assets=[[[DYAssetState alloc]init]autorelease];assets.paths=@{@"input":[runtime stringByAppendingPathComponent:@"input.cube"],@"look0":[runtime stringByAppendingPathComponent:@"look.cube"]};
error=nil;NSData *archive=[NSKeyedArchiver archivedDataWithRootObject:assets requiringSecureCoding:YES error:&error];DYAssetState *decoded=archive?[NSKeyedUnarchiver unarchivedObjectOfClass:DYAssetState.class fromData:archive error:&error]:nil;
run.record(@"secure-asset-archive-roundtrip",decoded&&[assets isEqual:decoded],@{@"archiveBytes":@(archive.length),@"error":reason(error)});
BOOL wrote=DYWriteAssets(manager,assets,kCMTimeZero);DYAssetState *readBack=DYReadAssets(manager,kCMTimeZero);run.record(@"native-custom-asset-get-set",wrote&&[readBack isEqual:assets]);
DYAssetState *copy=[[assets copy]autorelease];copy.paths=@{};run.record(@"asset-copy-is-independent",assets.paths.count==2&&copy.paths.count==0);
// Exercise the real AppKit actions against a separate, in-memory host.
[NSApplication sharedApplication];
DYDiagnosticManager *uiHost=[[[DYDiagnosticManager alloc]init]autorelease];DYCreateParameters(uiHost,nil);
DYInspector *inspector=[[[DYInspector alloc]initWithAPIManager:uiHost]autorelease];[inspector refresh];
NSArray *cards=[inspector valueForKey:@"cards"];BOOL initialUI=YES;
for(NSDictionary *card in cards)initialUI&=([card[@"collapsed"]boolValue]!=[@[@"primary",@"spider",@"base"]containsObject:card[@"section"][@"key"]])&&[(NSButton*)card[@"enabled"]state]==NSControlStateValueOn;
run.record(@"default-primary-spider-base-expanded-all-eyes-on",initialUI,@{@"modules":@(cards.count)});
DYUniforms uiBefore,uiAfter;DYReadUniforms(uiHost,kCMTimeZero,&uiBefore);BOOL foldingIndependent=YES;
for(NSDictionary *card in cards){NSButton *header=card[@"header"];BOOL was=[card[@"collapsed"]boolValue];[header performClick:nil];[inspector refresh];DYReadUniforms(uiHost,kCMTimeZero,&uiAfter);foldingIndependent&=[card[@"collapsed"]boolValue]!=was&&memcmp(&uiBefore,&uiAfter,sizeof(uiBefore))==0;[header performClick:nil];[inspector refresh];}
run.record(@"all-disclosure-actions-preserve-every-render-parameter",foldingIndependent);
NSDictionary *first=cards[0];if(![first[@"collapsed"]boolValue]){[(NSButton*)first[@"header"]performClick:nil];[inspector refresh];}BOOL wasFolded=[first[@"collapsed"]boolValue];[(NSButton*)first[@"enabled"]performClick:nil];[inspector refresh];DYReadUniforms(uiHost,kCMTimeZero,&uiAfter);
run.record(@"eye-only-toggles-enable-retains-disclosure",[first[@"collapsed"]boolValue]==wasFolded&&uiAfter.inputSectionEnabled==0);
[(NSButton*)first[@"header"]performClick:nil];[inspector refresh];DYReadUniforms(uiHost,kCMTimeZero,&uiAfter);
run.record(@"expanding-disabled-module-keeps-it-disabled",uiAfter.inputSectionEnabled==0&&![first[@"collapsed"]boolValue]);
DYInspector *reopened=[[[DYInspector alloc]initWithAPIManager:uiHost]autorelease];[reopened refresh];NSArray *reopenedCards=[reopened valueForKey:@"cards"];
run.record(@"inspector-recreation-restores-independent-disclosure",![reopenedCards[0][@"collapsed"]boolValue]&&[(NSButton*)reopenedCards[0][@"enabled"]state]==NSControlStateValueOff);
DYInspectorToken *uiToken=uiHost->_custom[@(DYInspectorParameterID)];error=nil;NSData *foldArchive=[NSKeyedArchiver archivedDataWithRootObject:uiToken requiringSecureCoding:YES error:&error];DYInspectorToken *foldDecoded=[NSKeyedUnarchiver unarchivedObjectOfClass:DYInspectorToken.class fromData:foldArchive error:&error];
run.record(@"secure-disclosure-archive-roundtrip",[foldDecoded isEqual:uiToken],@{@"error":reason(error)});
DYInspectorToken *old=[[[DYInspectorToken alloc]init]autorelease];old.schema=1;uiHost->_custom[@(DYInspectorParameterID)]=old;DYReadUniforms(uiHost,kCMTimeZero,&uiAfter);
run.record(@"legacy-inspector-retains-input-and-blackwhite-behavior",uiAfter.cm.configured==-1&&uiAfter.cm.blackWhiteMix==1);
DayuRenderParams cp=DYCMRender(defaults.cm);run.record(@"working-space-shared-by-primary-and-output",cp.input.outputTransfer==cp.output.inputTransfer&&cp.input.outputGamut==cp.output.inputGamut&&cp.basis.colorspace==10);
DYCMSettings converted=defaults.cm;converted.exposure=1.25;converted.contrast=.4;converted.balanceStrength=.3;converted.midtones=.6;converted.shadows=-.4;converted.black=.2;converted.shadowContrast=.3;converted.hiContrast=-.2;DayuRenderParams mapped=DYCMRender(converted);
run.record(@"basis-raw-controls-use-reference-conversion",fabs(mapped.basis.exposure-exp2f(1.25))<1e-6&&fabs(mapped.basis.contrast-exp2f(.4))<1e-6&&fabs(mapped.basis.balanceStrength-.36)<1e-6&&fabs(mapped.basis.midtones-.1998)<1e-5&&fabs(mapped.basis.shadows+.6)<1e-6&&fabs(mapped.basis.trimLow-.9)<1e-6&&fabs(mapped.basis.shadowContrast+.39)<1e-6&&fabs(mapped.basis.hiContrast+.4)<1e-6);
converted.workingTransfer=30;mapped=DYCMRender(converted);run.record(@"unsupported-basis-curve-adapts-through-intermediate",(mapped.reserved&8)&&mapped.basis.colorspace==10&&mapped.basisInput.inputTransfer==30&&mapped.basisOutput.outputTransfer==30);
[inspector resetAll:nil];[inspector refresh];
NSWindow *interactionWindow=[[[NSWindow alloc]initWithContentRect:NSMakeRect(0,0,400,780) styleMask:NSWindowStyleMaskBorderless backing:NSBackingStoreBuffered defer:NO]autorelease];interactionWindow.contentView=inspector;[inspector layoutSubtreeIfNeeded];
NSArray *graphics=[inspector valueForKey:@"graphics"];NSView *wheel=nil;for(NSView *graphic in graphics)if([NSStringFromClass(graphic.class)isEqual:@"DYPrimaryBalanceWheel"])wheel=graphic;
run.need(@"primary-balance-wheel-restored-and-palette-loaded",wheel&&[wheel valueForKey:@"wheel"]!=nil);
BOOL merged=cards.count==12&&[cards[0][@"section"][@"key"]isEqual:@"primary"]&&[cards[1][@"section"][@"key"]isEqual:@"spider"];for(NSDictionary *card in cards)merged&=![@[@"input",@"output"]containsObject:card[@"section"][@"key"]];
NSDictionary *controls=[inspector valueForKey:@"controls"];for(NSDictionary *record in controls.allValues)merged&=![[record[@"descriptor"]objectForKey:@"key"]hasPrefix:@"cmbypass"];
run.record(@"single-primary-card-no-bypass-checkboxes",merged);
auto mouseFor=[&](NSView *view,NSEventType type,NSPoint point,NSEventModifierFlags flags=0,NSInteger clicks=1){return [NSEvent mouseEventWithType:type location:[view convertPoint:point toView:nil] modifierFlags:flags timestamp:0 windowNumber:interactionWindow.windowNumber context:nil eventNumber:0 clickCount:clicks pressure:type==NSEventTypeLeftMouseUp?0:1];};
[wheel setFrameSize:NSMakeSize(310,232)];NSPoint wheelCenter=NSMakePoint(155,126);int starts=uiHost->_undoStarts,ends=uiHost->_undoEnds;
[wheel mouseDown:mouseFor(wheel,NSEventTypeLeftMouseDown,wheelCenter)];[wheel mouseDragged:mouseFor(wheel,NSEventTypeLeftMouseDragged,NSMakePoint(wheelCenter.x+25,wheelCenter.y+10))];[wheel mouseUp:mouseFor(wheel,NSEventTypeLeftMouseUp,NSMakePoint(wheelCenter.x+50,wheelCenter.y+20))];DYReadUniforms(uiHost,kCMTimeZero,&uiAfter);
float expectedStrength=hypotf(10,4)/90.f,expectedAngle=fmodf(atan2f(4,10)*180/M_PI+360-104,360);
run.record(@"balance-wheel-reference-orientation-and-fine-drag",fabs(uiAfter.cm.balanceStrength-expectedStrength)<1e-5&&fabs(uiAfter.cm.balanceAngle-expectedAngle)<1e-4&&uiAfter.cm.balanceAngle>1,@{@"angleDegrees":@(uiAfter.cm.balanceAngle),@"strength":@(uiAfter.cm.balanceStrength)});
run.record(@"balance-drag-one-host-undo-group",uiHost->_undoStarts==starts+1&&uiHost->_undoEnds==ends+1&&!uiHost->_undoActive);
NSButton *balanceReset=[wheel valueForKey:@"reset"];run.need(@"balance-visible-reset-button",[balanceReset.title isEqual:@"复位"]&&[balanceReset.accessibilityLabel isEqual:@"复位一级白平衡"]);
DYUniforms beforeReset=uiAfter;starts=uiHost->_undoStarts;ends=uiHost->_undoEnds;[balanceReset performClick:nil];DYReadUniforms(uiHost,kCMTimeZero,&uiAfter);
DYUniforms resetExpected=beforeReset;resetExpected.cm.balanceAngle=0;resetExpected.cm.balanceStrength=0;
run.record(@"balance-button-resets-only-wheel-one-undo",memcmp(&resetExpected,&uiAfter,sizeof(uiAfter))==0&&uiHost->_undoStarts==starts+1&&uiHost->_undoEnds==ends+1);
[wheel mouseDown:mouseFor(wheel,NSEventTypeLeftMouseDown,wheelCenter,0,2)];DYReadUniforms(uiHost,kCMTimeZero,&uiAfter);run.record(@"balance-double-click-neutral",uiAfter.cm.balanceStrength==0&&uiAfter.cm.balanceAngle==0);
NSView *spiderPanel=[inspector valueForKey:@"spiderPanel"];NSView<DYSpiderProbe> *disc=(id)[spiderPanel valueForKey:@"disc"];[disc setFrameSize:NSMakeSize(310,300)];auto initialMesh=DYSpiderMesh(disc.meshData);
run.record(@"spider-default-six-by-six-31-nodes",initialMesh.hues==6&&initialMesh.rings==5&&dy::meshCount(initialMesh)==31);
auto selectNode=[&](int index,NSEventModifierFlags flags){NSPoint pt=[disc point:index];[disc mouseDown:mouseFor(disc,NSEventTypeLeftMouseDown,pt,flags)];[disc mouseUp:mouseFor(disc,NSEventTypeLeftMouseUp,pt,flags)];};
auto dragNode=[&](int index,float dx,float dy){NSPoint pt=[disc point:index];[disc mouseDown:mouseFor(disc,NSEventTypeLeftMouseDown,pt)];[disc mouseDragged:mouseFor(disc,NSEventTypeLeftMouseDragged,NSMakePoint(pt.x+dx*.5,pt.y+dy*.5))];[disc mouseDragged:mouseFor(disc,NSEventTypeLeftMouseDragged,NSMakePoint(pt.x+dx,pt.y+dy))];[disc mouseUp:mouseFor(disc,NSEventTypeLeftMouseUp,NSMakePoint(pt.x+dx,pt.y+dy))];};
starts=uiHost->_undoStarts;ends=uiHost->_undoEnds;dragNode(2,18,8);DYAssetState *spiderSaved=DYReadAssets(uiHost,kCMTimeZero);auto dragged=DYSpiderMesh(spiderSaved.spiderMesh);
run.record(@"spider-single-drag-spoke-following-and-pin",dragged.x[0]>initialMesh.x[0]&&dragged.x[1]>initialMesh.x[1]&&dragged.x[3]>initialMesh.x[3]&&dragged.x[4]==initialMesh.x[4]&&dragged.x[5]==initialMesh.x[5]&&dragged.pins[2]);
run.record(@"spider-drag-one-host-undo-group",uiHost->_undoStarts==starts+1&&uiHost->_undoEnds==ends+1&&!uiHost->_undoActive);
error=nil;NSData *spiderArchive=[NSKeyedArchiver archivedDataWithRootObject:spiderSaved requiringSecureCoding:YES error:&error];DYAssetState *decodedSpider=[NSKeyedUnarchiver unarchivedObjectOfClass:DYAssetState.class fromData:spiderArchive error:&error];run.record(@"spider-archive-retains-mesh-pins-and-lut-paths",decodedSpider&&[decodedSpider isEqual:spiderSaved],@{@"error":reason(error)});
NSDictionary *snapshot=[inspector performSelector:@selector(presetSnapshot)];NSData *presetJSON=[NSJSONSerialization dataWithJSONObject:snapshot options:0 error:&error];NSDictionary *decodedPreset=[NSJSONSerialization JSONObjectWithData:presetJSON options:0 error:&error];run.record(@"complete-version-four-preset-includes-mesh",[decodedPreset[@"version"]isEqual:@4]&&[DYSpiderFromJSON(decodedPreset[@"spider"])isEqual:spiderSaved.spiderMesh]);
NSDictionary *portable=DYSpiderJSON(spiderSaved.spiderMesh,spiderSaved.spiderLinked);NSData *decodedPortable=DYSpiderFromJSON(portable);run.record(@"spider-json-preset-exact-roundtrip",[decodedPortable isEqual:spiderSaved.spiderMesh]);
NSMutableDictionary *badJSON=[[portable mutableCopy]autorelease];badJSON[@"hues"]=@7;run.record(@"spider-json-rejects-unsupported-topology",!DYSpiderFromJSON(badJSON));auto corrupt=dragged;corrupt.x[0]=NAN;run.record(@"spider-archive-rejects-nonfinite-coordinates",!DYSpiderMeshIsValid([NSData dataWithBytes:&corrupt length:sizeof(corrupt)]));
[disc changeHueCount:12 saturationCount:8];spiderSaved=DYReadAssets(uiHost,kCMTimeZero);auto dense=DYSpiderMesh(spiderSaved.spiderMesh);run.record(@"spider-independent-resolution-and-resample",dense.hues==12&&dense.rings==7&&fabs(dy::meshDelta(dense,0,.6).x)>0);
[disc resetMesh];auto resetDense=DYSpiderMesh(DYReadAssets(uiHost,kCMTimeZero).spiderMesh);run.record(@"spider-reset-preserves-density",resetDense.hues==12&&resetDense.rings==7&&dy::meshSamples(resetDense)[4]==0);
[disc changeHueCount:6 saturationCount:6];selectNode(1,0);selectNode(2,NSEventModifierFlagCommand);run.record(@"spider-command-multiselect",disc.selection.count==2);[disc selectRing];run.record(@"spider-ring-selection",disc.selection.count==12);[disc.selection removeAllIndexes];selectNode(0,0);[disc selectSpoke];run.record(@"spider-spoke-selection",disc.selection.count==5);
selectNode(3,NSEventModifierFlagShift);run.record(@"spider-shift-pin",[disc.pinned containsIndex:3]);float pinnedX=DYSpiderMesh(disc.meshData).x[3];dragNode(3,8,0);run.record(@"spider-pinned-anchor-still-draggable",DYSpiderMesh(disc.meshData).x[3]>pinnedX);
NSPoint resetPoint=[disc point:3];[disc rightMouseDown:mouseFor(disc,NSEventTypeRightMouseDown,resetPoint)];run.record(@"spider-right-click-reset-unpins",!DYSpiderMesh(disc.meshData).pins[3]);
[disc resetMesh];NSData *beforeCancel=[[disc.meshData copy]autorelease];NSPoint anchor=[disc point:2];[disc mouseDown:mouseFor(disc,NSEventTypeLeftMouseDown,anchor)];[disc mouseDragged:mouseFor(disc,NSEventTypeLeftMouseDragged,NSMakePoint(anchor.x+10,anchor.y+5))];[disc keyDown:[NSEvent keyEventWithType:NSEventTypeKeyDown location:NSZeroPoint modifierFlags:0 timestamp:0 windowNumber:interactionWindow.windowNumber context:nil characters:@"\x1b" charactersIgnoringModifiers:@"\x1b" isARepeat:NO keyCode:53]];run.record(@"spider-escape-restores-coordinates-and-pins",[beforeCancel isEqual:disc.meshData]);
run.record(@"native-interaction-window-never-visible",!interactionWindow.visible);[inspector resetAll:nil];[inspector refresh];
id<MTLDevice> gpu=MTLCreateSystemDefaultDevice();run.need(@"metal-device",gpu!=nil);gpuName=gpu.name;
const NSUInteger width=64,height=48;DYDiagnosticTile *source=[[[DYDiagnosticTile alloc]initWithDevice:gpu width:width height:height]autorelease],*destination=[[[DYDiagnosticTile alloc]initWithDevice:gpu width:width height:height]autorelease];
run.need(@"real-iosurface-image-tiles",source&&destination&&source.ioSurface&&destination.ioSurface);
Pixels input(width*height*4);for(NSUInteger y=0;y<height;y++)for(NSUInteger x=0;x<width;x++){size_t p=(y*width+x)*4;float alpha=float((x+y)%5)/4.f;input[p]=(__fp16)((.08f+.75f*float(x)/(width-1))*alpha);input[p+1]=(__fp16)((.05f+.8f*float(y)/(height-1))*alpha);input[p+2]=(__fp16)((.1f+.65f*float((x*7+y*3)%64)/63.f)*alpha);input[p+3]=(__fp16)alpha;}
[[source metalTextureForDevice:gpu]replaceRegion:MTLRegionMake2D(0,0,width,height) mipmapLevel:0 withBytes:input.data() bytesPerRow:width*8];
// Color-tool parity fixtures deliberately use a display-space identity
// input; the user's new Sony camera default is checked independently above.
defaults.cm.inputTransfer=1002;defaults.cm.inputGamut=22;
DYRenderer *renderer=[[[DYRenderer alloc]init]autorelease];Pixels neutral=render(run,renderer,source,destination,gpu,defaults,@{},@"renderer-default-pass");Difference neutralDifference=difference(input,neutral);
run.record(@"transparent-premultiplied-neutral",neutralDifference.nonfinite==0&&neutralDifference.maximum<=.001,measure(neutralDifference));
NSString *cstReference=NSProcessInfo.processInfo.environment[@"DY_DIAGNOSTIC_CST_REFERENCE"];
if(cstReference.length){
error=nil;id<MTLLibrary>oracle=[gpu newLibraryWithURL:[NSURL fileURLWithPath:cstReference] error:&error];run.need(@"independent-installed-cst-reference-loaded",oracle!=nil,@{@"path":cstReference,@"error":reason(error)});
const int cases[][3]={{28,27,10},{2,23,10},{4,4,10},{5,5,10},{6,6,10},{8,7,10},{9,7,10},{11,10,10},{12,28,10},{15,23,10},{16,17,10},{21,23,10},{22,21,10},{25,24,10},{27,25,10},{30,23,10},{29,23,10},{28,27,1},{28,27,20},{28,27,30},{28,27,1002}};
for(unsigned index=0;index<sizeof(cases)/sizeof(cases[0]);index++){@autoreleasepool{
DYUniforms candidate=defaults;candidate.cm.configured=1;candidate.cm.inputTransfer=cases[index][0];candidate.cm.inputGamut=cases[index][1];candidate.cm.workingTransfer=cases[index][2];candidate.cm.toneMapping=1;candidate.cm.exposure=.35;candidate.cm.contrast=.15;candidate.cm.saturation=1.1;candidate.cm.balanceAngle=(index%4)*90+.12;candidate.cm.balanceStrength=.03;
DayuRenderParams p=DYCMRender(candidate.cm);Pixels expected=referenceFrame(gpu,oracle,input,width,height,p,&error);Pixels actual=render(run,renderer,source,destination,gpu,candidate,@{},[NSString stringWithFormat:@"cst-case-%02u-render",index]);
BOOL same=expected.size()==actual.size();double worst=0;float refValue=0,gotValue=0;NSUInteger nonfinite=0;for(NSUInteger i=0;i<expected.size()&&same;i++){float a=expected[i],b=actual[i];if(!std::isfinite(a)||!std::isfinite(b)){nonfinite++;same=NO;break;}double delta=fabs(a-b);worst=fmax(worst,delta);same&=delta<=.004+.003*fabs(a);if(!same){refValue=a;gotValue=b;}}
run.record([NSString stringWithFormat:@"cst-case-%02u-independent-pixels",index],same,@{@"inputCurve":@(p.input.inputTransfer),@"inputGamut":@(p.input.inputGamut),@"workingCurve":@(p.input.outputTransfer),@"maximumError":@(worst),@"referenceValue":@(refValue),@"actualValue":@(gotValue),@"nonfinite":@(nonfinite),@"components":@(actual.size())});
}}[oracle release];
}
DYUniforms monochrome=defaults;monochrome.cm.blackWhiteMix=1;Pixels mono=render(run,renderer,source,destination,gpu,monochrome,@{},@"blackwhite-full-render");
Difference monoDiff=difference(neutral,mono);run.record(@"blackwhite-mix-100-affects-frame",monoDiff.different>100&&monoDiff.nonfinite==0,measure(monoDiff));
monochrome.cm.blackWhiteMix=.5;Pixels halfMono=render(run,renderer,source,destination,gpu,monochrome,@{},@"blackwhite-half-render");BOOL smooth=YES;for(NSUInteger i=0;i<mono.size();i++)smooth&=fabs((float)halfMono[i]-.5f*((float)mono[i]+(float)neutral[i]))<.001;
run.record(@"blackwhite-half-mix-is-continuous",smooth);
monochrome.blackWhiteSectionEnabled=0;Pixels monoOff=render(run,renderer,source,destination,gpu,monochrome,@{},@"blackwhite-eye-off-render");run.record(@"blackwhite-eye-bypasses-retained-mix",difference(neutral,monoOff).maximum==0);
for(int hues:{6,12,24})for(int saturation:{6,8,24}){@autoreleasepool{
auto mesh=dy::neutralMesh(hues,saturation);std::bitset<dy::SpiderMeshCapacity>selected;selected[2]=1;mesh=dy::moveMesh(mesh,selected,-.035f,.04f);NSData *data=[NSData dataWithBytes:&mesh length:sizeof(mesh)];DYUniforms warped=defaults;
error=nil;BOOL ok=[renderer renderSource:source destination:destination uniforms:warped paths:@{} spider:data error:&error];Pixels frame=read(destination,gpu);auto samples=dy::meshSamples(mesh);BOOL parity=ok;double maximum=0;NSUInteger affected=0;
for(NSUInteger i=0;i<width*height;i++){float alpha=input[i*4+3];float3 rgb={0,0,0};if(alpha>0)for(int c=0;c<3;c++)rgb[c]=(__fp16)((float)input[i*4+c]/alpha);float3 expected=dyLimit(dyVariableSpider(rgb,hues,saturation-1,samples.data()));for(int c=0;c<3;c++){float value=alpha>0?(__fp16)((float)(__fp16)expected[c]*alpha):0;double delta=fabs(value-(float)frame[i*4+c]);maximum=fmax(maximum,delta);parity&=std::isfinite(frame[i*4+c])&&delta<.003;affected+=fabs((float)frame[i*4+c]-(float)neutral[i*4+c])>.001;}}
run.record([NSString stringWithFormat:@"spider-production-cpu-parity-%d-%d",hues,saturation],parity&&affected>0,@{@"maximumError":@(maximum),@"affectedComponents":@(affected),@"error":reason(error)});
warped.spiderSectionEnabled=0;[renderer renderSource:source destination:destination uniforms:warped paths:@{} spider:data error:&error];run.record([NSString stringWithFormat:@"spider-eye-retains-but-bypasses-%d-%d",hues,saturation],difference(neutral,read(destination,gpu)).maximum==0);
}}
DYUniforms masterProbe=defaults;masterProbe.cm.configured=1;masterProbe.cm.exposure=.7;Pixels masterOn=render(run,renderer,source,destination,gpu,masterProbe,@{},@"primary-master-active-render");masterProbe.primarySectionEnabled=0;Pixels masterOff=render(run,renderer,source,destination,gpu,masterProbe,@{},@"primary-master-inactive-render");run.record(@"primary-master-controls-complete-cst-pipeline",difference(neutral,masterOn).different>100&&difference(neutral,masterOff).maximum==0);
auto checkFoldedGroup=[&](DYUniforms active,NSUInteger offset,NSDictionary *paths,NSString *name){
*(float *)((uint8_t *)&active+offset)=0;
Pixels folded=render(run,renderer,source,destination,gpu,active,paths,[name stringByAppendingString:@"-render"]);
Difference delta=difference(neutral,folded);run.record(name,delta.nonfinite==0&&delta.maximum==0,measure(delta));
};
size_t transparentBad=0;for(size_t i=0;i<input.size();i+=4){if(input[i+3]==0)for(int c=0;c<4;c++)if(neutral[i+c]!=0)transparentBad++;if(neutral[i+3]!=input[i+3])transparentBad++;}
run.record(@"renderer-alpha-contract",transparentBad==0,@{@"invalidComponents":@(transparentBad)});
NSData *preview=[renderer preview];bool previewFinite=preview.length==320*180*16;if(previewFinite){const float *data=(const float *)preview.bytes;for(NSUInteger i=0;i<preview.length/4;i++)previewFinite&=std::isfinite(data[i]);}
run.record(@"renderer-analysis-320x180",previewFinite,@{@"bytes":@(preview.length)});
NSDictionary *autoGrade=DYAutoGrade(preview);run.record(@"renderer-auto-grade-integration",autoGrade.count==10,autoGrade?:@{});
// Vertical red/blue markers establish actual Metal texture row order.
// Browser bitmaps need top-first rows; the auto-analysis bytes must not
// be changed even when FxPlug supplies a bottom-left source texture.
Pixels marker(width*height*4),bottomFirst(marker.size());
for(NSUInteger y=0;y<height;y++)for(NSUInteger x=0;x<width;x++){
size_t p=(y*width+x)*4;marker[p]=y<height/2?.8f:.03f;marker[p+1]=.04f+.1f*float(x)/(width-1);marker[p+2]=y<height/2?.02f:.7f;marker[p+3]=1;
}
for(NSUInteger y=0;y<height;y++)memcpy(bottomFirst.data()+y*width*4,marker.data()+(height-1-y)*width*4,width*8);
DYRenderer *orientationRenderer=[[[DYRenderer alloc]init]autorelease];
[[source metalTextureForDevice:gpu]replaceRegion:MTLRegionMake2D(0,0,width,height) mipmapLevel:0 withBytes:marker.data() bytesPerRow:width*8];
error=nil;BOOL topRendered=[orientationRenderer renderSource:source destination:destination uniforms:defaults paths:@{} error:&error];
NSData *topAnalysis=[orientationRenderer preview],*topLook=[orientationRenderer lookLUTPreview];
bool topOrientation=topRendered&&topLook.length==320*180*16&&[topLook isEqualToData:topAnalysis];
if(topOrientation){const float*p=(const float*)topLook.bytes;topOrientation=p[0]>p[2]&&p[(179*320)*4+2]>p[(179*320)*4];}
run.record(@"look-preview-top-left-is-original-analysis",topOrientation,@{@"error":topRendered?@"":reason(error),@"bytes":@(topLook.length)});
[orientationRenderer invalidatePreview];[source setDiagnosticImageOrigin:kFxImageOrigin_BOTTOM_LEFT];
[[source metalTextureForDevice:gpu]replaceRegion:MTLRegionMake2D(0,0,width,height) mipmapLevel:0 withBytes:bottomFirst.data() bytesPerRow:width*8];
error=nil;BOOL bottomRendered=[orientationRenderer renderSource:source destination:destination uniforms:defaults paths:@{} error:&error];
NSData *bottomAnalysis=[orientationRenderer preview],*bottomLook=[orientationRenderer lookLUTPreview];
bool bottomOrientation=bottomRendered&&bottomAnalysis.length==320*180*16&&bottomLook.length==bottomAnalysis.length;
if(bottomOrientation){
const float*a=(const float*)bottomAnalysis.bytes,*b=(const float*)bottomLook.bytes;
bottomOrientation=a[2]>a[0]&&a[(179*320)*4]>a[(179*320)*4+2]&&b[0]>b[2]&&b[(179*320)*4+2]>b[(179*320)*4];
for(NSUInteger y=0;y<180&&bottomOrientation;y++)bottomOrientation=memcmp((const uint8_t*)bottomLook.bytes+y*320*16,(const uint8_t*)bottomAnalysis.bytes+(179-y)*320*16,320*16)==0;
}
run.record(@"look-preview-bottom-left-flips-only-browser-rows",bottomOrientation,@{@"error":bottomRendered?@"":reason(error),@"analysisKeepsPhysicalRowOrder":@(bottomOrientation),@"all180RowsCompared":@(bottomOrientation)});
[orientationRenderer invalidatePreview];run.record(@"preview-invalidation-clears-analysis-and-browser",![orientationRenderer preview]&&![orientationRenderer lookLUTPreview]);
[source setDiagnosticImageOrigin:kFxImageOrigin_TOP_LEFT];
[[source metalTextureForDevice:gpu]replaceRegion:MTLRegionMake2D(0,0,width,height) mipmapLevel:0 withBytes:input.data() bytesPerRow:width*8];
DYUniforms cstExport=defaults;cstExport.cm.configured=1;cstExport.cm.exposure=.7f;
NSURL *cstCube=[NSURL fileURLWithPath:[runtime stringByAppendingPathComponent:@"cst-export.cube"]];error=nil;BOOL cstExported=[renderer exportLUT:cstCube uniforms:cstExport paths:@{} error:&error];
NSString *cubeText=cstExported?[NSString stringWithContentsOfURL:cstCube encoding:NSUTF8StringEncoding error:&error]:nil;std::vector<float>cubeValues;
for(NSString *line in [cubeText componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]){float r,g,b;if(sscanf(line.UTF8String,"%f %f %f",&r,&g,&b)==3){cubeValues.push_back(r);cubeValues.push_back(g);cubeValues.push_back(b);}}
Pixels gray(input.size());float grayLinear=powf((.5f+.055f)/1.055f,2.4f);for(NSUInteger i=0;i<width*height;i++){for(int c=0;c<3;c++)gray[i*4+c]=grayLinear;gray[i*4+3]=1;}
[[source metalTextureForDevice:gpu]replaceRegion:MTLRegionMake2D(0,0,width,height) mipmapLevel:0 withBytes:gray.data() bytesPerRow:width*8];Pixels grayRendered=render(run,renderer,source,destination,gpu,cstExport,@{},@"cst-export-production-sample");
BOOL cstCubeMatches=cstExported&&cubeValues.size()==33*33*33*3;for(int c=0;c<3&&cstCubeMatches;c++){float code=cubeValues[((16*33+16)*33+16)*3+c];float linear=code<=.04045f?code/12.92f:powf((code+.055f)/1.055f,2.4f);cstCubeMatches&=fabs(linear-(float)grayRendered[c])<.002&&fabs(code-.5f)>.01;}
run.record(@"cube-export-includes-cst-primary-and-matches-production",cstCubeMatches,@{@"error":reason(error),@"triples":@(cubeValues.size()/3)});
[[source metalTextureForDevice:gpu]replaceRegion:MTLRegionMake2D(0,0,width,height) mipmapLevel:0 withBytes:input.data() bytesPerRow:width*8];
auto exportMesh=dy::neutralMesh();for(int i=0;i<dy::meshCount(exportMesh);i++){exportMesh.x[i]+=.02f;exportMesh.y[i]-=.01f;}NSData *exportMeshData=[NSData dataWithBytes:&exportMesh length:sizeof(exportMesh)];
NSURL *meshCube=[NSURL fileURLWithPath:[runtime stringByAppendingPathComponent:@"spider-export.cube"]];BOOL meshExported=[renderer exportLUT:meshCube uniforms:defaults paths:@{} spider:exportMeshData error:&error];NSString *meshText=meshExported?[NSString stringWithContentsOfURL:meshCube encoding:NSUTF8StringEncoding error:&error]:nil;std::vector<float>meshValues;
for(NSString *line in [meshText componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]){float r,g,b;if(sscanf(line.UTF8String,"%f %f %f",&r,&g,&b)==3){meshValues.push_back(r);meshValues.push_back(g);meshValues.push_back(b);}}
auto meshSamples=dy::meshSamples(exportMesh);float3 exportInput={0,0,0};float codes[3]={.5f,.25f,.75f};for(int c=0;c<3;c++)exportInput[c]=(__fp16)powf((codes[c]+.055f)/1.055f,2.4f);float3 exportExpected=dyLimit(dyVariableSpider(exportInput,6,5,meshSamples.data()));BOOL meshCubeMatches=meshValues.size()==33*33*33*3;
for(int c=0;c<3&&meshCubeMatches;c++){float code=meshValues[((24*33+8)*33+16)*3+c],linear=code<=.04045f?code/12.92f:powf((code+.055f)/1.055f,2.4f);meshCubeMatches&=fabs(linear-exportExpected[c])<.002;}
run.record(@"cube-export-includes-spider-warp",meshCubeMatches,@{@"triples":@(meshValues.size()/3),@"error":reason(error)});
DYUniforms u=defaults;u.exposure=.8f;Pixels exposed=render(run,renderer,source,destination,gpu,u,@{},@"renderer-exposure-pass");Difference exposureDifference=difference(neutral,exposed);run.record(@"exposure-affects-actual-frame",exposureDifference.nonfinite==0&&exposureDifference.different>100,measure(exposureDifference));
u.baseSectionEnabled=0;Pixels bypass=render(run,renderer,source,destination,gpu,u,@{},@"renderer-base-bypass-pass");Difference bypassDifference=difference(neutral,bypass);run.record(@"base-group-bypass",bypassDifference.nonfinite==0&&bypassDifference.maximum==0,measure(bypassDifference));
u=defaults;u.temperature=35;u.tint=-20;Pixels wb=render(run,renderer,source,destination,gpu,u,@{},@"renderer-white-balance-pass");Difference wbDifference=difference(neutral,wb);run.record(@"white-balance-real-table-frame",wbDifference.nonfinite==0&&wbDifference.different>100,measure(wbDifference));
u.colorSectionEnabled=0;bypass=render(run,renderer,source,destination,gpu,u,@{},@"renderer-color-bypass-pass");bypassDifference=difference(neutral,bypass);run.record(@"color-group-bypass",bypassDifference.nonfinite==0&&bypassDifference.maximum==0,measure(bypassDifference));
u=defaults;u.hslSectionEnabled=1;u.hslHueA.x=28;u.hslSatA.y=45;u.hslLumB.z=-18;Pixels hsl=render(run,renderer,source,destination,gpu,u,@{},@"renderer-hsl-pass");Difference hslDifference=difference(neutral,hsl);run.record(@"hsl-real-table-frame",hslDifference.nonfinite==0&&hslDifference.different>100,measure(hslDifference));
checkFoldedGroup(u,offsetof(DYUniforms,hslSectionEnabled),@{},@"disabled-hsl-bypasses-retained-adjustments");
u=defaults;u.colorGradingSectionEnabled=1;u.colorGradingHueSatA.x=210;u.colorGradingHueSatA.y=42;u.colorGradingLuma.x=18;Pixels grading=render(run,renderer,source,destination,gpu,u,@{},@"renderer-grading-pass");Difference gradingDifference=difference(neutral,grading);run.record(@"grading-real-table-frame",gradingDifference.nonfinite==0&&gradingDifference.different>100,measure(gradingDifference));
checkFoldedGroup(u,offsetof(DYUniforms,colorGradingSectionEnabled),@{},@"disabled-grading-bypasses-retained-adjustments");
for(int profile=1;profile<=17;profile++){@autoreleasepool{u=defaults;u.inputSectionEnabled=1;u.inputProfile=profile;Pixels transformed=render(run,renderer,source,destination,gpu,u,@{},[NSString stringWithFormat:@"input-profile-%02d-load-render",profile]);Difference delta=difference(neutral,transformed);run.record([NSString stringWithFormat:@"input-profile-%02d-finite-nonzero",profile],delta.nonfinite==0&&delta.nonzero>100,measure(delta));}}
checkFoldedGroup(u,offsetof(DYUniforms,inputSectionEnabled),@{},@"disabled-input-bypasses-retained-profile");
DYRenderer *analysisRenderer=[[[DYRenderer alloc]init]autorelease];u=defaults;u.inputSectionEnabled=1;u.inputProfile=1;render(run,analysisRenderer,source,destination,gpu,u,@{},@"renderer-input-analysis-pass");
NSData *inputPreview=[analysisRenderer preview];bool analysisDifferent=inputPreview.length==preview.length&&preview.length==320*180*16;double analysisMaximum=0;size_t analysisChanges=0;
if(analysisDifferent){const float *a=(const float *)preview.bytes,*b=(const float *)inputPreview.bytes;for(NSUInteger i=0;i<preview.length/4;i++){if(!std::isfinite(a[i])||!std::isfinite(b[i])){analysisDifferent=false;break;}if(i%4!=3){double delta=std::fabs(double(a[i])-b[i]);analysisMaximum=std::max(analysisMaximum,delta);if(delta>1e-5)analysisChanges++;}}}
run.record(@"analysis-applies-selected-input-LUT",analysisDifferent&&analysisChanges>100,@{@"changedComponents":@(analysisChanges),@"maxAbsoluteError":@(analysisMaximum)});
NSString *lookFile=[runtime stringByAppendingPathComponent:@"diagnostic-look.cube"];NSMutableString *cube=[NSMutableString stringWithString:@"TITLE \"Self test look\"\nLUT_3D_SIZE 2\nDOMAIN_MIN 0 0 0\nDOMAIN_MAX 1 1 1\n"];
for(int b=0;b<2;b++)for(int g=0;g<2;g++)for(int r=0;r<2;r++)[cube appendFormat:@"%.8f %.8f %.8f\n",.7f*r+.1f,.8f*g+.05f,.85f*b+.02f];error=nil;run.need(@"temporary-look-file",[cube writeToFile:lookFile atomically:YES encoding:NSUTF8StringEncoding error:&error],@{@"error":reason(error)});
NSDictionary *paths=@{@"look0":lookFile,@"look1":lookFile,@"look2":lookFile,@"look3":lookFile,@"look4":lookFile};u=defaults;u.lookSectionEnabled=1;u.postLUTStrength=.35f;u.extraPostLUTStrengths=(DYFloat4){.4f,.5f,.6f,.7f};Pixels looks=render(run,renderer,source,destination,gpu,u,paths,@"renderer-five-look-pass");Difference looksDifference=difference(neutral,looks);run.record(@"five-look-mixes-affect-frame",looksDifference.nonfinite==0&&looksDifference.different>100,measure(looksDifference));
checkFoldedGroup(u,offsetof(DYUniforms,lookSectionEnabled),paths,@"disabled-look-bypasses-retained-LUTs");
NSURL *exportURL=[NSURL fileURLWithPath:[runtime stringByAppendingPathComponent:@"diagnostic-export.cube"]];error=nil;run.need(@"renderer-export-33cube",[renderer exportLUT:exportURL uniforms:u paths:paths error:&error],@{@"error":reason(error),@"path":exportURL.path});
NSString *exported=[NSString stringWithContentsOfURL:exportURL encoding:NSUTF8StringEncoding error:&error];NSUInteger triples=0,nonzero=0;bool exportFinite=true;for(NSString *line in [exported componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]){float r,g,b;if(sscanf(line.UTF8String,"%f %f %f",&r,&g,&b)==3){triples++;exportFinite&=std::isfinite(r)&&std::isfinite(g)&&std::isfinite(b);if(r!=0||g!=0||b!=0)nonzero++;}}
run.record(@"export-33cube-data-contract",[exported containsString:@"LUT_3D_SIZE 33"]&&triples==33*33*33&&exportFinite&&nonzero>0,@{@"rows":@(triples),@"nonzeroRows":@(nonzero),@"bytes":@([[[NSFileManager defaultManager]attributesOfItemAtPath:exportURL.path error:nil][NSFileSize]unsignedLongLongValue])});
// A selected external table must outlive preview-cache churn and must
// not consult the file system again on the frame-render path.
NSString *external=[runtime stringByAppendingPathComponent:@"external-65.cube"];
std::string externalCube="TITLE \"External activation fixture\"\nLUT_3D_SIZE 65\n";char row[128];
for(int z=0;z<65;z++)for(int y=0;y<65;y++)for(int x=0;x<65;x++){snprintf(row,sizeof(row),"%.8f %.8f %.8f\n",x/64.f*.82f,y/64.f,z/64.f*1.12f);externalCube+=row;}
run.need(@"external-large-cube-written",[[NSData dataWithBytes:externalCube.data() length:externalCube.size()]writeToFile:external options:NSDataWritingAtomic error:&error]);
DYRenderer *externalRenderer=[[[DYRenderer alloc]init]autorelease];
__block BOOL prepared=NO;__block NSError *preparationError=nil;__block NSUInteger beats=0;__block double last=NSProcessInfo.processInfo.systemUptime,maxGap=0;
NSTimer *heartbeat=[NSTimer scheduledTimerWithTimeInterval:.005 repeats:YES block:^(NSTimer *timer){double now=NSProcessInfo.processInfo.systemUptime;maxGap=std::max(maxGap,now-last);last=now;beats++;}];
[externalRenderer prepareLUTPath:external completion:^(NSError *failure){preparationError=[failure retain];prepared=YES;}];
double deadline=NSProcessInfo.processInfo.systemUptime+30;
while(!prepared&&NSProcessInfo.processInfo.systemUptime<deadline)[[NSRunLoop mainRunLoop]runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:.01]];
double activationEnd=NSProcessInfo.processInfo.systemUptime;maxGap=std::max(maxGap,activationEnd-last);
[heartbeat invalidate];
run.need(@"external-decode-and-gpu-upload-complete",prepared&&!preparationError,@{@"error":reason(preparationError)});[preparationError release];
run.record(@"external-activation-main-loop-responsive",maxGap<.15,@{@"heartbeats":@(beats),@"maximumGapMS":@(maxGap*1000)});
DYUniforms externalUniforms=defaults;externalUniforms.lookSectionEnabled=1;externalUniforms.postLUTStrength=1;
NSDictionary *externalPaths=@{@"look0":external};
Pixels externalFrame=render(run,externalRenderer,source,destination,gpu,externalUniforms,externalPaths,@"external-first-frame-after-preparation");
run.record(@"external-lut-affects-frame",difference(neutral,externalFrame).different>100);
run.need(@"external-source-removed-for-no-io-check",[[NSFileManager defaultManager]removeItemAtPath:external error:&error]);
BOOL churnOK=YES;
for(int i=0;i<14;i++){@autoreleasepool{
NSString *other=[runtime stringByAppendingPathComponent:[NSString stringWithFormat:@"eviction-%02d.cube",i]];
NSString *text=@"LUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n";
churnOK&=[text writeToFile:other atomically:YES encoding:NSUTF8StringEncoding error:&error];
__block BOOL ready=NO;__block BOOL success=NO;
[externalRenderer prepareLUTPath:other completion:^(NSError *failure){success=failure==nil;ready=YES;}];
double until=NSProcessInfo.processInfo.systemUptime+10;
while(!ready&&NSProcessInfo.processInfo.systemUptime<until)[[NSRunLoop mainRunLoop]runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:.01]];
churnOK&=ready&&success;
}}
run.need(@"external-preview-and-gpu-cache-churn",churnOK);
Pixels retainedFrame=render(run,externalRenderer,source,destination,gpu,externalUniforms,externalPaths,@"external-render-with-source-unavailable-after-cache-churn");
Difference retainedDifference=difference(externalFrame,retainedFrame);
run.record(@"external-snapshot-is-independent-of-file-and-preview-cache",retainedDifference.maximum==0&&retainedDifference.nonfinite==0,measure(retainedDifference));
__block BOOL cancelledDone=NO;__block BOOL cancellationReported=NO;
NSProgress *cancelled=[externalRenderer prepareLUTPath:[runtime stringByAppendingPathComponent:@"eviction-00.cube"] completion:^(NSError *failure){cancellationReported=failure.code==NSUserCancelledError;cancelledDone=YES;}];[cancelled cancel];
deadline=NSProcessInfo.processInfo.systemUptime+10;
while(!cancelledDone&&NSProcessInfo.processInfo.systemUptime<deadline)[[NSRunLoop mainRunLoop]runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:.01]];
run.record(@"external-preparation-cancellation",cancelledDone&&cancellationReported);
NSString *userFolder=NSProcessInfo.processInfo.environment[@"DY_DIAGNOSTIC_LUT_FOLDER"];
if(userFolder.length){
NSUInteger userCount=0;BOOL allUserFrames=YES;
NSURL *folder=[NSURL fileURLWithPath:userFolder];
for(NSURL *file in [NSFileManager.defaultManager enumeratorAtURL:folder includingPropertiesForKeys:@[NSURLIsRegularFileKey] options:NSDirectoryEnumerationSkipsHiddenFiles errorHandler:nil]){@autoreleasepool{
NSNumber *regular=nil;[file getResourceValue:&regular forKey:NSURLIsRegularFileKey error:nil];
if(!regular.boolValue||![file.pathExtension.lowercaseString isEqual:@"cube"])continue;
__block BOOL ready=NO;__block NSError *failure=nil;
[externalRenderer prepareLUTPath:file.path completion:^(NSError *result){failure=[result retain];ready=YES;}];
double until=NSProcessInfo.processInfo.systemUptime+30;
while(!ready&&NSProcessInfo.processInfo.systemUptime<until)[[NSRunLoop mainRunLoop]runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:.01]];
run.need([@"user-lut-preparation:" stringByAppendingString:file.lastPathComponent],ready&&!failure,@{@"error":reason(failure)});[failure release];
Pixels frame=render(run,externalRenderer,source,destination,gpu,externalUniforms,@{@"look0":file.path},[@"user-lut-render:" stringByAppendingString:file.lastPathComponent]);
Difference delta=difference(neutral,frame);BOOL good=delta.nonfinite==0;allUserFrames&=good;userCount++;
run.record([@"user-lut-finite-frame:" stringByAppendingString:file.lastPathComponent],good,measure(delta));
}}
run.record(@"user-folder-all-luts-prepared-and-rendered",userCount>0&&allUserFrames,@{@"files":@(userCount),@"sourceFolder":userFolder,@"sourceFilesModified":@NO});
}
#include "DYToolDiagnostics.inc.h"
#include "DYToolTrackingDiagnostics.inc.h"
#include "DYToolCanvasDiagnostics.inc.h"
[gpu release];
} @catch(NSException *exception) {
run.record(@"diagnostic-exception",false,@{@"exception":exception.name?:@"unknown",@"message":exception.reason?:@"unknown"});
}
NSDictionary *report=@{@"pass":@(run.passed),@"checks":@(run.rows.count),@"gpu":gpuName,@"bundlePath":[NSBundle bundleForClass:DYRenderer.class].bundlePath?:@"",
@"runtimePath":runtime?:@"",@"results":run.rows,@"scope":@"Native model and renderer integration with real Metal/IOSurface textures and fake FxPlug host selectors; no GUI or live host document.",
@"limitations":@[@"Finite states and a 64x48 frame; live FCP discovery, inspector interaction, timeline persistence and real host export require separate acceptance.",@"Input profiles checked for load/render/finite output; independent color accuracy is covered by separate LUT/kernel evidence."]};
NSError *error=nil;NSData *json=[NSJSONSerialization dataWithJSONObject:report options:NSJSONWritingPrettyPrinted|NSJSONWritingSortedKeys error:&error];
if(json){fwrite(json.bytes,1,json.length,stdout);fputc('\n',stdout);}else{fputs("{\"pass\":false,\"error\":\"Unable to encode diagnostics JSON\"}\n",stdout);run.passed=false;}fflush(stdout);return run.passed?0:1;
} }