forked from alejandrojapkin/CocoaLUT
/
LUTHelper.m
329 lines (269 loc) · 11.9 KB
/
LUTHelper.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
//
// LUTHelper.m
// Pods
//
// Created by Wil Gieseler on 12/16/13.
//
//
#import "LUTHelper.h"
double contrastStretch(double value, double currentMin, double currentMax, double finalMin, double finalMax){
return (value - currentMin)*((finalMax-finalMin)/(currentMax-currentMin)) + finalMin;
}
double clamp(double value, double min, double max){
return (value > max) ? max : ((value < min) ? min : value);
}
double clamp01(double value) {
return clamp(value, 0, 1);
}
double clampLowerBound(double value, double lowerBound){
if(value < lowerBound) return lowerBound;
else return value;
}
double clampUpperBound(double value, double upperBound){
if(value > upperBound) return upperBound;
else return value;
}
double nsremapint01(NSInteger value, NSInteger maxValue) {
return (double)value / (double)maxValue;
}
double remapint01(int value, int maxValue) {
return nsremapint01(value, maxValue);
}
double remap(double value, double inputLow, double inputHigh, double outputLow, double outputHigh){
if(value < inputLow || value > inputHigh){
@throw [NSException exceptionWithName:@"RemapValueOutOfBounds"
reason:[NSString stringWithFormat:@"Tried to remap out-of-bounds value (%f) with input constraints low:%f high:%f", value, inputLow, inputHigh]
userInfo:nil];
}
if(inputLow > inputHigh){
@throw [NSException exceptionWithName:@"RemapInputsError"
reason:[NSString stringWithFormat:@"Inputs low:%f high:%f. low must be less than or equal to high", inputLow, inputHigh]
userInfo:nil];
}
if(outputLow > outputHigh){
@throw [NSException exceptionWithName:@"RemapOutputsError"
reason:[NSString stringWithFormat:@"Outputs low:%f high:%f. low must be less than or equal to high", outputLow, outputHigh]
userInfo:nil];
}
return outputLow + ((value - inputLow)*(outputHigh - outputLow))/(inputHigh - inputLow);
}
double remapNoError(double value, double inputLow, double inputHigh, double outputLow, double outputHigh){
return outputLow + ((value - inputLow)*(outputHigh - outputLow))/(inputHigh - inputLow);
}
BOOL outOfBounds(double value, double min, double max, BOOL inclusive){
if(inclusive){
return value < min || value > max;
}
else{
return value <= min || value >= max;
}
}
double lerp1d(double beginning, double end, double value01) {
if (value01 < 0 || value01 > 1){
@throw [NSException exceptionWithName:@"Invalid Lerp" reason:@"Value out of bounds" userInfo:nil];
}
float range = end - beginning;
return beginning + range * value01;
}
double smootherstep(double beginning, double end, double percentage)
{
if(percentage < 0 || percentage > 1){
@throw [NSException exceptionWithName:@"Invalid Smoothstep" reason:@"Percentage out of bounds [0-1]" userInfo:nil];
}
percentage = remap(percentage, 0, 1, beginning, end);
return percentage*percentage*percentage*(percentage*(percentage*6.0 - 15.0) + 10.0);
}
double smoothstep(double beginning, double end, double percentage){
if(percentage < 0 || percentage > 1){
@throw [NSException exceptionWithName:@"Invalid Smoothstep" reason:@"Percentage out of bounds [0-1]" userInfo:nil];
}
percentage = remap(percentage, 0, 1, beginning, end);
// Evaluate polynomial
return percentage*percentage*(3 - 2*percentage);
}
float distancecalc(float x1, float y1, float z1, float x2, float y2, float z2) {
float dx = x2 - x1;
float dy = y2 - y1;
float dz = z2 - z1;
return sqrt((float)(dx * dx + dy * dy + dz * dz));
}
NSArray* indicesDoubleArray(double startValue, double endValue, int numIndices){
NSMutableArray *indices = [NSMutableArray array];
double ratio = remap(1, 0, numIndices - 1, startValue, endValue);
for (int i = 0; i < numIndices; i++) {
[indices addObject:@(clampUpperBound((double)i * ratio, endValue))];
}
return indices;
}
NSArray* indicesIntegerArray(int startValue, int endValue, int numIndices){
NSMutableArray *indices = [NSMutableArray array];
double ratio = remap(1, 0, numIndices - 1, startValue, endValue);
for (int i = 0; i < numIndices; i++) {
[indices addObject:@((long)round((double)i * ratio))];
}
return indices;
}
void timer(NSString* name, void (^block)()) {
NSLog(@"Starting %@", name);
NSDate *startTime = [NSDate date];
block();
NSLog(@"%@ finished in %fs", name, -[startTime timeIntervalSinceNow]);
}
BOOL isLUT3D(LUT* lut){
return [lut isKindOfClass:[LUT3D class]];
}
BOOL isLUT1D(LUT* lut){
return [lut isKindOfClass:[LUT1D class]];
}
LUT3D* LUTAsLUT3D(LUT* lut, NSUInteger size){
if (isLUT1D(lut)){
return [(LUT1D *)lut LUT3DOfSize:size];
}
else{
return [(LUT3D *)lut LUTByResizingToSize:size];
}
}
LUT1D* LUTAsLUT1D(LUT* lut, NSUInteger size){
if (isLUT3D(lut)){
return [[(LUT3D *)lut LUT1D] LUTByResizingToSize:size];
}
else{
return [(LUT1D *)lut LUTByResizingToSize:size];
}
}
BOOL stringIsNumeric(NSString* str){
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSNumber *number = [formatter numberFromString:str];
return !!number; // If the string is not numeric, number will be nil
}
void LUTConcurrentRectLoop(NSUInteger width, NSUInteger height, void (^block)(NSUInteger x, NSUInteger y)) {
dispatch_apply(width, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0) , ^(size_t x){
for (int y = 0; y < height; y++) {
block(x, y);
}
});
}
CGSize CGSizeProportionallyScaled(CGSize currentSize, CGSize targetSize) {
if ( CGSizeEqualToSize(currentSize, targetSize) == NO ) {
float widthFactor = targetSize.width / currentSize.width;
float heightFactor = targetSize.height / currentSize.height;
float scaleFactor = 0.0;
if ( widthFactor < heightFactor )
scaleFactor = widthFactor;
else
scaleFactor = heightFactor;
float scaledWidth = currentSize.width * scaleFactor;
float scaledHeight = currentSize.height * scaleFactor;
return CGSizeMake(scaledWidth, scaledHeight);
}
return currentSize;
}
M13OrderedDictionary* M13OrderedDictionaryFromOrderedArrayWithDictionaries(NSArray *array){
NSMutableArray *keys = [[NSMutableArray alloc] init];
NSMutableArray *values = [[NSMutableArray alloc] init];
for (NSDictionary *item in array){
if([[item allKeys] count] == 1 && [[item allValues] count] == 1){
[keys addObject:[item allKeys][0]];
[values addObject:[item allValues][0]];
}
else{
@throw [NSException exceptionWithName:@"M13OrderedDictionary generator failed." reason:@"A dictionary in the array was not of count 1" userInfo:nil];
}
}
return [[M13OrderedDictionary alloc] initWithObjects:values pairedWithKeys:keys];
}
NSNumberFormatter* sharedNumberFormatter(){
static NSNumberFormatter *numberFormatter = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
numberFormatter = [NSNumberFormatter new];
});
return numberFormatter;
}
BOOL stringIsValidNumber(NSString *string){
return [sharedNumberFormatter() numberFromString:string] != nil;
}
NSUInteger findFirstLUTLineInLines(NSArray *lines, NSString *seperator, int numValues, int startLine){
NSNumberFormatter *formatter = [NSNumberFormatter new];
for (int i = startLine; i < lines.count; i++){
NSArray *splitLine = [lines[i] componentsSeparatedByString:seperator];
splitLine = arrayWithEmptyElementsRemoved(splitLine);
if(splitLine.count == numValues){
BOOL isLine = YES;
for (int j = 0; j < numValues; j++){
if([formatter numberFromString:splitLine[j]] == nil){
isLine = NO;
}
}
if(isLine){
return i;
}
}
}
return -1;
}
NSArray* arrayWithEmptyElementsRemoved(NSArray *array){
return [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF != ''"]];
}
NSArray* arrayWithComponentsSeperatedByNewlineAndWhitespaceWithEmptyElementsRemoved(NSString *string){
return arrayWithEmptyElementsRemoved([string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]);
}
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
#elif TARGET_OS_MAC
void LUTNSImageLog(NSImage *image) {
for (NSImageRep *rep in image.representations) {
NSLog(@"Color Space: %@", rep.colorSpaceName);
NSLog(@"Bits Per Sample: %ld", (long)rep.bitsPerSample);
if ([rep isKindOfClass:[NSBitmapImageRep class]]) {
NSLog(@"Bits Per Pixel: %ld", (long)((NSBitmapImageRep *)rep).bitsPerPixel);
}
}
}
NSString* FirstRegexMatch(NSString *text, NSString *pattern) {
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:NULL];
NSTextCheckingResult *match = [regex firstMatchInString:text options:0 range:NSMakeRange(0, [text length])];
return [text substringWithRange:[match rangeAtIndex:1]];
}
NSImage* LUTNSImageFromCIImage(CIImage *ciImage, BOOL useSoftwareRenderer) {
[NSGraphicsContext saveGraphicsState];
int width = [ciImage extent].size.width;
int rows = [ciImage extent].size.height;
int rowBytes = (width * 8);
NSBitmapImageRep* rep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:nil
pixelsWide:width
pixelsHigh:rows
bitsPerSample:16
samplesPerPixel:4
hasAlpha:YES
isPlanar:NO
colorSpaceName:NSDeviceRGBColorSpace
bitmapFormat:0
bytesPerRow:rowBytes
bitsPerPixel:0];
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate([rep bitmapData],
width,
rows,
16,
rowBytes,
colorSpace,
(CGBitmapInfo)kCGImageAlphaPremultipliedLast);
NSDictionary *contextOptions = @{
kCIContextWorkingColorSpace: (__bridge id)colorSpace,
kCIContextOutputColorSpace: (__bridge id)colorSpace,
kCIContextUseSoftwareRenderer: @(useSoftwareRenderer)
};
CIContext* ciContext = [CIContext contextWithCGContext:context options:contextOptions];
[ciContext drawImage:ciImage
inRect:CGRectMake(0, 0, ciImage.extent.size.width, ciImage.extent.size.height)
fromRect:ciImage.extent];
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
[NSGraphicsContext restoreGraphicsState];
NSImage *nsImage = [[NSImage alloc] initWithSize:rep.size];
[nsImage addRepresentation:rep];
return nsImage;
}
#endif
@implementation LUTHelper
@end