Reorder imports.
[OpenColorIO-Configs.git] / aces_1.0.0 / python / aces_ocio / create_aces_config.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 '''
5 usage from python
6
7 import sys
8 sys.path.append( "/path/to/script" )
9 import create_aces_config as cac
10 acesReleaseCTLDir = "/path/to/github/checkout/releases/v0.7.1/transforms/ctl"
11 configDir = "/path/to/config/dir"
12 cac.createACESConfig(acesReleaseCTLDir, configDir, 1024, 33, True)
13
14 usage from command line, from the directory with 'create_aces_config.py'
15 python create_aces_config.py -a "/path/to/github/checkout/releases/v0.7.1/transforms/ctl" -c "/path/to/config/dir" --lutResolution1d 1024 --lutResolution3d 33 --keepTempImages
16
17
18
19 build instructions for osx for needed packages.
20
21 #opencolorio
22 brew install -vd opencolorio --with-python
23
24 #openimageio
25 brew tap homebrew/science
26
27 # optional installs
28 brew install -vd libRaw
29 brew install -vd OpenCV
30
31 brew install -vd openimageio --with-python
32
33 #ctl
34 brew install -vd CTL
35
36 #opencolorio - again.
37 # this time, 'ociolutimage' will build because openimageio is installed
38 brew uninstall -vd opencolorio
39 brew install -vd opencolorio --with-python
40 '''
41
42
43 import math
44 import numpy
45 import os
46 import shutil
47 import string
48 import sys
49
50 # TODO: This restores the capability of running the script without having
51 # added the package to PYTHONPATH, this is ugly and should ideally replaced by
52 # dedicated executable in a /bin directory.
53 sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
54
55 import PyOpenColorIO as OCIO
56
57 import aces_ocio.createARRIColorSpaces as arri
58 import aces_ocio.createCanonColorSpaces as canon
59 import aces_ocio.createREDColorSpaces as red
60 import aces_ocio.createSonyColorSpaces as sony
61 import aces_ocio.generateLUT as genlut
62 from aces_ocio.process import Process
63 from aces_ocio.util import ColorSpace, mat44FromMat33
64
65 ACES_OCIO_CTL_DIRECTORY_ENVIRON = 'ACES_OCIO_CTL_DIRECTORY'
66 ACES_OCIO_CONFIGURATION_DIRECTORY_ENVIRON = 'ACES_OCIO_CONFIGURATION_DIRECTORY'
67
68 #
69 # Utility functions
70 #
71 def setConfigDefaultRoles(config,
72                           color_picking="",
73                           color_timing="",
74                           compositing_log="",
75                           data="",
76                           default="",
77                           matte_paint="",
78                           reference="",
79                           scene_linear="",
80                           texture_paint=""):
81     # Add Roles
82     if color_picking: config.setRole(OCIO.Constants.ROLE_COLOR_PICKING,
83                                      color_picking)
84     if color_timing: config.setRole(OCIO.Constants.ROLE_COLOR_TIMING,
85                                     color_timing)
86     if compositing_log: config.setRole(OCIO.Constants.ROLE_COMPOSITING_LOG,
87                                        compositing_log)
88     if data: config.setRole(OCIO.Constants.ROLE_DATA, data)
89     if default: config.setRole(OCIO.Constants.ROLE_DEFAULT, default)
90     if matte_paint: config.setRole(OCIO.Constants.ROLE_MATTE_PAINT,
91                                    matte_paint)
92     if reference: config.setRole(OCIO.Constants.ROLE_REFERENCE, reference)
93     if scene_linear: config.setRole(OCIO.Constants.ROLE_SCENE_LINEAR,
94                                     scene_linear)
95     if texture_paint: config.setRole(OCIO.Constants.ROLE_TEXTURE_PAINT,
96                                      texture_paint)
97
98
99 # Write config to disk
100 def writeConfig(config, configPath, sanityCheck=True):
101     if sanityCheck:
102         try:
103             config.sanityCheck()
104         except Exception, e:
105             print e
106             print "Configuration was not written due to a failed Sanity Check"
107             return
108             # sys.exit()
109
110     fileHandle = open(configPath, mode='w')
111     fileHandle.write(config.serialize())
112     fileHandle.close()
113
114
115 def generateOCIOTransform(transforms):
116     # print( "Generating transforms")
117
118     interpolationOptions = {
119         'linear': OCIO.Constants.INTERP_LINEAR,
120         'nearest': OCIO.Constants.INTERP_NEAREST,
121         'tetrahedral': OCIO.Constants.INTERP_TETRAHEDRAL
122     }
123     directionOptions = {
124         'forward': OCIO.Constants.TRANSFORM_DIR_FORWARD,
125         'inverse': OCIO.Constants.TRANSFORM_DIR_INVERSE
126     }
127
128     ocioTransforms = []
129
130     for transform in transforms:
131         if transform['type'] == 'lutFile':
132
133             ocioTransform = OCIO.FileTransform(src=transform['path'],
134                                                interpolation=
135                                                interpolationOptions[
136                                                    transform['interpolation']],
137                                                direction=directionOptions[
138                                                    transform['direction']])
139
140             ocioTransforms.append(ocioTransform)
141         elif transform['type'] == 'matrix':
142             ocioTransform = OCIO.MatrixTransform()
143             # MatrixTransform member variables can't be initialized directly. Each must be set individually
144             ocioTransform.setMatrix(transform['matrix'])
145
146             if 'offset' in transform:
147                 ocioTransform.setOffset(transform['offset'])
148             if 'direction' in transform:
149                 ocioTransform.setDirection(
150                     directionOptions[transform['direction']])
151
152             ocioTransforms.append(ocioTransform)
153         elif transform['type'] == 'exponent':
154             ocioTransform = OCIO.ExponentTransform()
155             ocioTransform.setValue(transform['value'])
156
157             ocioTransforms.append(ocioTransform)
158         elif transform['type'] == 'log':
159             ocioTransform = OCIO.LogTransform(base=transform['base'],
160                                               direction=directionOptions[
161                                                   transform['direction']])
162
163             ocioTransforms.append(ocioTransform)
164         else:
165             print( "Ignoring unknown transform type : %s" % transform['type'] )
166
167     # Build a group transform if necessary
168     if len(ocioTransforms) > 1:
169         transformG = OCIO.GroupTransform()
170         for transform in ocioTransforms:
171             transformG.push_back(transform)
172         transform = transformG
173
174     # Or take the first transform from the list
175     else:
176         transform = ocioTransforms[0]
177
178     return transform
179
180
181 def createConfig(configData, nuke=False):
182     # Create the config
183     config = OCIO.Config()
184
185     #
186     # Set config wide values
187     #
188     config.setDescription("An ACES config generated from python")
189     config.setSearchPath("luts")
190
191     #
192     # Define the reference color space
193     #
194     referenceData = configData['referenceColorSpace']
195     print( "Adding the reference color space : %s" % referenceData.name)
196
197     # Create a color space
198     reference = OCIO.ColorSpace(name=referenceData.name,
199                                 bitDepth=referenceData.bitDepth,
200                                 description=referenceData.description,
201                                 equalityGroup=referenceData.equalityGroup,
202                                 family=referenceData.family,
203                                 isData=referenceData.isData,
204                                 allocation=referenceData.allocationType,
205                                 allocationVars=referenceData.allocationVars)
206
207     # Add to config
208     config.addColorSpace(reference)
209
210     #
211     # Create the rest of the color spaces
212     #
213     for colorspace in sorted(configData['colorSpaces']):
214         print( "Creating new color space : %s" % colorspace.name)
215
216         ocioColorspace = OCIO.ColorSpace(name=colorspace.name,
217                                          bitDepth=colorspace.bitDepth,
218                                          description=colorspace.description,
219                                          equalityGroup=colorspace.equalityGroup,
220                                          family=colorspace.family,
221                                          isData=colorspace.isData,
222                                          allocation=colorspace.allocationType,
223                                          allocationVars=colorspace.allocationVars)
224
225         if colorspace.toReferenceTransforms != []:
226             print( "Generating To-Reference transforms")
227             ocioTransform = generateOCIOTransform(
228                 colorspace.toReferenceTransforms)
229             ocioColorspace.setTransform(ocioTransform,
230                                         OCIO.Constants.COLORSPACE_DIR_TO_REFERENCE)
231
232         if colorspace.fromReferenceTransforms != []:
233             print( "Generating From-Reference transforms")
234             ocioTransform = generateOCIOTransform(
235                 colorspace.fromReferenceTransforms)
236             ocioColorspace.setTransform(ocioTransform,
237                                         OCIO.Constants.COLORSPACE_DIR_FROM_REFERENCE)
238
239         config.addColorSpace(ocioColorspace)
240
241         print( "" )
242
243     #
244     # Define the views and displays
245     #
246     displays = []
247     views = []
248
249     # Generic display and view setup
250     if not nuke:
251         for display, viewList in configData['displays'].iteritems():
252             for viewName, colorspace in viewList.iteritems():
253                 config.addDisplay(display, viewName, colorspace.name)
254                 if not (viewName in views):
255                     views.append(viewName)
256             displays.append(display)
257     # A Nuke specific set of views and displays
258     #
259     # XXX
260     # A few names: Output Transform, ACES, ACEScc, are hard-coded here. Would be better to automate
261     #
262     else:
263         for display, viewList in configData['displays'].iteritems():
264             for viewName, colorspace in viewList.iteritems():
265                 if ( viewName == 'Output Transform'):
266                     viewName = 'View'
267                     config.addDisplay(display, viewName, colorspace.name)
268                     if not (viewName in views):
269                         views.append(viewName)
270             displays.append(display)
271
272         config.addDisplay('linear', 'View', 'ACES2065-1')
273         displays.append('linear')
274         config.addDisplay('log', 'View', 'ACEScc')
275         displays.append('log')
276
277     # Set active displays and views
278     config.setActiveDisplays(','.join(sorted(displays)))
279     config.setActiveViews(','.join(views))
280
281     #
282     # Need to generalize this at some point
283     #
284
285     # Add Default Roles
286     setConfigDefaultRoles(config,
287                           color_picking=reference.getName(),
288                           color_timing=reference.getName(),
289                           compositing_log=reference.getName(),
290                           data=reference.getName(),
291                           default=reference.getName(),
292                           matte_paint=reference.getName(),
293                           reference=reference.getName(),
294                           scene_linear=reference.getName(),
295                           texture_paint=reference.getName())
296
297     # Check to make sure we didn't screw something up
298     config.sanityCheck()
299
300     return config
301
302
303 #
304 # Functions to generate color space definitions and LUTs for transforms for a specific ACES release
305 #
306
307 # Output is a list of colorspaces and transforms that convert between those
308 # colorspaces and reference color space, ACES
309 def generateLUTs(odtInfo, lmtInfo, shaperName, acesCTLReleaseDir, lutDir,
310                  lutResolution1d=4096, lutResolution3d=64, cleanup=True):
311     print( "generateLUTs - begin" )
312     configData = {}
313
314     #
315     # Define the reference color space
316     #
317     ACES = ColorSpace('ACES2065-1')
318     ACES.description = "The Academy Color Encoding System reference color space"
319     ACES.equalityGroup = ''
320     ACES.family = 'ACES'
321     ACES.isData = False
322     ACES.allocationType = OCIO.Constants.ALLOCATION_LG2
323     ACES.allocationVars = [-15, 6]
324
325     configData['referenceColorSpace'] = ACES
326
327     #
328     # Define the displays
329     #
330     configData['displays'] = {}
331
332     #
333     # Define the other color spaces
334     #
335     configData['colorSpaces'] = []
336
337     # Matrix converting ACES AP1 primaries to AP0
338     acesAP1toAP0 = [0.6954522414, 0.1406786965, 0.1638690622,
339                     0.0447945634, 0.8596711185, 0.0955343182,
340                     -0.0055258826, 0.0040252103, 1.0015006723]
341
342     # Matrix converting ACES AP0 primaries to XYZ
343     acesAP0toXYZ = [0.9525523959, 0.0000000000, 0.0000936786,
344                     0.3439664498, 0.7281660966, -0.0721325464,
345                     0.0000000000, 0.0000000000, 1.0088251844]
346
347     #
348     # ACEScc
349     #
350     def createACEScc(name='ACEScc', minValue=0.0, maxValue=1.0,
351                      inputScale=1.0):
352         cs = ColorSpace(name)
353         cs.description = "The %s color space" % name
354         cs.equalityGroup = ''
355         cs.family = 'ACES'
356         cs.isData = False
357
358         ctls = [
359             '%s/ACEScc/ACEScsc.ACEScc_to_ACES.a1.0.0.ctl' % acesCTLReleaseDir,
360             # This transform gets back to the AP1 primaries
361             # Useful as the 1d LUT is only covering the transfer function
362             # The primaries switch is covered by the matrix below
363             '%s/ACEScg/ACEScsc.ACES_to_ACEScg.a1.0.0.ctl' % acesCTLReleaseDir
364         ]
365         lut = "%s_to_ACES.spi1d" % name
366
367         # Remove spaces and parentheses
368         lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
369
370         genlut.generate1dLUTFromCTL(lutDir + "/" + lut,
371                                     ctls,
372                                     lutResolution1d,
373                                     'float',
374                                     inputScale,
375                                     1.0,
376             {},
377                                     cleanup,
378                                     acesCTLReleaseDir,
379                                     minValue,
380                                     maxValue)
381
382         cs.toReferenceTransforms = []
383         cs.toReferenceTransforms.append({
384             'type': 'lutFile',
385             'path': lut,
386             'interpolation': 'linear',
387             'direction': 'forward'
388         })
389
390         # AP1 primaries to AP0 primaries
391         cs.toReferenceTransforms.append({
392             'type': 'matrix',
393             'matrix': mat44FromMat33(acesAP1toAP0),
394             'direction': 'forward'
395         })
396
397         cs.fromReferenceTransforms = []
398         return cs
399
400     ACEScc = createACEScc()
401     configData['colorSpaces'].append(ACEScc)
402
403     #
404     # ACESproxy
405     #
406     def createACESProxy(name='ACESproxy'):
407         cs = ColorSpace(name)
408         cs.description = "The %s color space" % name
409         cs.equalityGroup = ''
410         cs.family = 'ACES'
411         cs.isData = False
412
413         ctls = [
414             '%s/ACESproxy/ACEScsc.ACESproxy10i_to_ACES.a1.0.0.ctl' % acesCTLReleaseDir,
415             # This transform gets back to the AP1 primaries
416             # Useful as the 1d LUT is only covering the transfer function
417             # The primaries switch is covered by the matrix below
418             '%s/ACEScg/ACEScsc.ACES_to_ACEScg.a1.0.0.ctl' % acesCTLReleaseDir
419         ]
420         lut = "%s_to_aces.spi1d" % name
421
422         # Remove spaces and parentheses
423         lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
424
425         genlut.generate1dLUTFromCTL(lutDir + "/" + lut,
426                                     ctls,
427                                     lutResolution1d,
428                                     'uint16',
429                                     64.0,
430                                     1.0,
431             {},
432                                     cleanup,
433                                     acesCTLReleaseDir)
434
435         cs.toReferenceTransforms = []
436         cs.toReferenceTransforms.append({
437             'type': 'lutFile',
438             'path': lut,
439             'interpolation': 'linear',
440             'direction': 'forward'
441         })
442
443         # AP1 primaries to AP0 primaries
444         cs.toReferenceTransforms.append({
445             'type': 'matrix',
446             'matrix': mat44FromMat33(acesAP1toAP0),
447             'direction': 'forward'
448         })
449
450         cs.fromReferenceTransforms = []
451         return cs
452
453     ACESproxy = createACESProxy()
454     configData['colorSpaces'].append(ACESproxy)
455
456     #
457     # ACEScg
458     #
459     def createACEScg(name='ACEScg'):
460         cs = ColorSpace(name)
461         cs.description = "The %s color space" % name
462         cs.equalityGroup = ''
463         cs.family = 'ACES'
464         cs.isData = False
465
466         cs.toReferenceTransforms = []
467
468         # AP1 primaries to AP0 primaries
469         cs.toReferenceTransforms.append({
470             'type': 'matrix',
471             'matrix': mat44FromMat33(acesAP1toAP0),
472             'direction': 'forward'
473         })
474
475         cs.fromReferenceTransforms = []
476         return cs
477
478     ACEScg = createACEScg()
479     configData['colorSpaces'].append(ACEScg)
480
481     #
482     # ADX
483     #
484     def createADX(bitdepth=10, name='ADX'):
485         name = "%s%s" % (name, bitdepth)
486         cs = ColorSpace(name)
487         cs.description = "%s color space - used for film scans" % name
488         cs.equalityGroup = ''
489         cs.family = 'ADX'
490         cs.isData = False
491
492         if bitdepth == 10:
493             cs.bitDepth = bitDepth = OCIO.Constants.BIT_DEPTH_UINT10
494             adx_to_cdd = [1023.0 / 500.0, 0.0, 0.0, 0.0,
495                           0.0, 1023.0 / 500.0, 0.0, 0.0,
496                           0.0, 0.0, 1023.0 / 500.0, 0.0,
497                           0.0, 0.0, 0.0, 1.0]
498             offset = [-95.0 / 500.0, -95.0 / 500.0, -95.0 / 500.0, 0.0]
499         elif bitdepth == 16:
500             cs.bitDepth = bitDepth = OCIO.Constants.BIT_DEPTH_UINT16
501             adx_to_cdd = [65535.0 / 8000.0, 0.0, 0.0, 0.0,
502                           0.0, 65535.0 / 8000.0, 0.0, 0.0,
503                           0.0, 0.0, 65535.0 / 8000.0, 0.0,
504                           0.0, 0.0, 0.0, 1.0]
505             offset = [-1520.0 / 8000.0, -1520.0 / 8000.0, -1520.0 / 8000.0,
506                       0.0]
507
508         cs.toReferenceTransforms = []
509
510         # Convert from ADX to Channel-Dependent Density
511         cs.toReferenceTransforms.append({
512             'type': 'matrix',
513             'matrix': adx_to_cdd,
514             'offset': offset,
515             'direction': 'forward'
516         })
517
518         # Convert from Channel-Dependent Density to Channel-Independent Density
519         cs.toReferenceTransforms.append({
520             'type': 'matrix',
521             'matrix': [0.75573, 0.22197, 0.02230, 0,
522                        0.05901, 0.96928, -0.02829, 0,
523                        0.16134, 0.07406, 0.76460, 0,
524                        0.0, 0.0, 0.0, 1.0],
525             'direction': 'forward'
526         })
527
528         # Copied from Alex Fry's adx_cid_to_rle.py
529         def createCIDtoRLELUT():
530             def interpolate1D(x, xp, fp):
531                 return numpy.interp(x, xp, fp)
532
533             LUT_1D_xp = [-0.190000000000000,
534                          0.010000000000000,
535                          0.028000000000000,
536                          0.054000000000000,
537                          0.095000000000000,
538                          0.145000000000000,
539                          0.220000000000000,
540                          0.300000000000000,
541                          0.400000000000000,
542                          0.500000000000000,
543                          0.600000000000000]
544
545             LUT_1D_fp = [-6.000000000000000,
546                          -2.721718645000000,
547                          -2.521718645000000,
548                          -2.321718645000000,
549                          -2.121718645000000,
550                          -1.921718645000000,
551                          -1.721718645000000,
552                          -1.521718645000000,
553                          -1.321718645000000,
554                          -1.121718645000000,
555                          -0.926545676714876]
556
557             REF_PT = (7120.0 - 1520.0) / 8000.0 * (100.0 / 55.0) - math.log(
558                 0.18, 10.0)
559
560             def cid_to_rle(x):
561                 if x <= 0.6:
562                     return interpolate1D(x, LUT_1D_xp, LUT_1D_fp)
563                 return (100.0 / 55.0) * x - REF_PT
564
565             def Fit(value, fromMin, fromMax, toMin, toMax):
566                 if fromMin == fromMax:
567                     raise ValueError("fromMin == fromMax")
568                 return (value - fromMin) / (fromMax - fromMin) * (
569                     toMax - toMin) + toMin
570
571             NUM_SAMPLES = 2 ** 12
572             RANGE = (-0.19, 3.0)
573             data = []
574             for i in xrange(NUM_SAMPLES):
575                 x = i / (NUM_SAMPLES - 1.0)
576                 x = Fit(x, 0.0, 1.0, RANGE[0], RANGE[1])
577                 data.append(cid_to_rle(x))
578
579             lut = 'ADX_CID_to_RLE.spi1d'
580             genlut.writeSPI1D(lutDir + "/" + lut, RANGE[0], RANGE[1], data,
581                               NUM_SAMPLES, 1)
582
583             return lut
584
585         # Convert Channel Independent Density values to Relative Log Exposure values
586         lut = createCIDtoRLELUT()
587         cs.toReferenceTransforms.append({
588             'type': 'lutFile',
589             'path': lut,
590             'interpolation': 'linear',
591             'direction': 'forward'
592         })
593
594         # Convert Relative Log Exposure values to Relative Exposure values
595         cs.toReferenceTransforms.append({
596             'type': 'log',
597             'base': 10,
598             'direction': 'inverse'
599         })
600
601         # Convert Relative Exposure values to ACES values
602         cs.toReferenceTransforms.append({
603             'type': 'matrix',
604             'matrix': [0.72286, 0.12630, 0.15084, 0,
605                        0.11923, 0.76418, 0.11659, 0,
606                        0.01427, 0.08213, 0.90359, 0,
607                        0.0, 0.0, 0.0, 1.0],
608             'direction': 'forward'
609         })
610
611         cs.fromReferenceTransforms = []
612         return cs
613
614     ADX10 = createADX(bitdepth=10)
615     configData['colorSpaces'].append(ADX10)
616
617     ADX16 = createADX(bitdepth=16)
618     configData['colorSpaces'].append(ADX16)
619
620     #
621     # Camera Input Transforms
622     #
623
624     # RED color spaces to ACES
625     redColorSpaces = red.createColorSpaces(lutDir, lutResolution1d)
626     for cs in redColorSpaces:
627         configData['colorSpaces'].append(cs)
628
629     # Canon-Log to ACES
630     canonColorSpaces = canon.createColorSpaces(lutDir, lutResolution1d)
631     for cs in canonColorSpaces:
632         configData['colorSpaces'].append(cs)
633
634     # SLog to ACES
635     sonyColorSpaces = sony.createColorSpaces(lutDir, lutResolution1d)
636     for cs in sonyColorSpaces:
637         configData['colorSpaces'].append(cs)
638
639     # LogC to ACES
640     arriColorSpaces = arri.createColorSpaces(lutDir, lutResolution1d)
641     for cs in arriColorSpaces:
642         configData['colorSpaces'].append(cs)
643
644     #
645     # Generic log transform
646     #
647     def createGenericLog(name='log',
648                          minValue=0.0,
649                          maxValue=1.0,
650                          inputScale=1.0,
651                          middleGrey=0.18,
652                          minExposure=-6.0,
653                          maxExposure=6.5,
654                          lutResolution1d=lutResolution1d):
655         cs = ColorSpace(name)
656         cs.description = "The %s color space" % name
657         cs.equalityGroup = name
658         cs.family = 'Utility'
659         cs.isData = False
660
661         ctls = [
662             '%s/utilities/ACESlib.OCIO_shaper_log2_to_lin_param.a1.0.0.ctl' % acesCTLReleaseDir
663         ]
664         lut = "%s_to_aces.spi1d" % name
665
666         # Remove spaces and parentheses
667         lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
668
669         genlut.generate1dLUTFromCTL(lutDir + "/" + lut,
670                                     ctls,
671                                     lutResolution1d,
672                                     'float',
673                                     inputScale,
674                                     1.0,
675                                     {
676                                         'middleGrey': middleGrey,
677                                         'minExposure': minExposure,
678                                         'maxExposure': maxExposure
679                                     },
680                                     cleanup,
681                                     acesCTLReleaseDir,
682                                     minValue,
683                                     maxValue)
684
685         cs.toReferenceTransforms = []
686         cs.toReferenceTransforms.append({
687             'type': 'lutFile',
688             'path': lut,
689             'interpolation': 'linear',
690             'direction': 'forward'
691         })
692
693         cs.fromReferenceTransforms = []
694         return cs
695
696     #
697     # ACES LMTs
698     #
699     def createACESLMT(lmtName,
700                       lmtValues,
701                       shaperInfo,
702                       lutResolution1d=1024,
703                       lutResolution3d=64,
704                       cleanup=True):
705         cs = ColorSpace("%s" % lmtName)
706         cs.description = "The ACES Look Transform: %s" % lmtName
707         cs.equalityGroup = ''
708         cs.family = 'Look'
709         cs.isData = False
710
711         import pprint
712
713         pprint.pprint(lmtValues)
714
715         #
716         # Generate the shaper transform
717         #
718         (shaperName, shaperToACESCTL, shaperFromACESCTL, shaperInputScale,
719          shaperParams) = shaperInfo
720
721         shaperLut = "%s_to_aces.spi1d" % shaperName
722         if ( not os.path.exists(lutDir + "/" + shaperLut) ):
723             ctls = [
724                 shaperToACESCTL % acesCTLReleaseDir
725             ]
726
727             # Remove spaces and parentheses
728             shaperLut = shaperLut.replace(' ', '_').replace(')', '_').replace(
729                 '(', '_')
730
731             genlut.generate1dLUTFromCTL(lutDir + "/" + shaperLut,
732                                         ctls,
733                                         lutResolution1d,
734                                         'float',
735                                         1.0 / shaperInputScale,
736                                         1.0,
737                                         shaperParams,
738                                         cleanup,
739                                         acesCTLReleaseDir)
740
741         shaperOCIOTransform = {
742             'type': 'lutFile',
743             'path': shaperLut,
744             'interpolation': 'linear',
745             'direction': 'inverse'
746         }
747
748         #
749         # Generate the forward transform
750         #
751         cs.fromReferenceTransforms = []
752
753         if 'transformCTL' in lmtValues:
754             ctls = [
755                 shaperToACESCTL % acesCTLReleaseDir,
756                 '%s/%s' % (acesCTLReleaseDir, lmtValues['transformCTL'])
757             ]
758             lut = "%s.%s.spi3d" % (shaperName, lmtName)
759
760             # Remove spaces and parentheses
761             lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
762
763             genlut.generate3dLUTFromCTL(lutDir + "/" + lut,
764                                         ctls,
765                                         lutResolution3d,
766                                         'float',
767                                         1.0 / shaperInputScale,
768                                         1.0,
769                                         shaperParams,
770                                         cleanup,
771                                         acesCTLReleaseDir)
772
773             cs.fromReferenceTransforms.append(shaperOCIOTransform)
774             cs.fromReferenceTransforms.append({
775                 'type': 'lutFile',
776                 'path': lut,
777                 'interpolation': 'tetrahedral',
778                 'direction': 'forward'
779             })
780
781         #
782         # Generate the inverse transform
783         #
784         cs.toReferenceTransforms = []
785
786         if 'transformCTLInverse' in lmtValues:
787             ctls = [
788                 '%s/%s' % (
789                     acesCTLReleaseDir, odtValues['transformCTLInverse']),
790                 shaperFromACESCTL % acesCTLReleaseDir
791             ]
792             lut = "Inverse.%s.%s.spi3d" % (odtName, shaperName)
793
794             # Remove spaces and parentheses
795             lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
796
797             genlut.generate3dLUTFromCTL(lutDir + "/" + lut,
798                                         ctls,
799                                         lutResolution3d,
800                                         'half',
801                                         1.0,
802                                         shaperInputScale,
803                                         shaperParams,
804                                         cleanup,
805                                         acesCTLReleaseDir)
806
807             cs.toReferenceTransforms.append({
808                 'type': 'lutFile',
809                 'path': lut,
810                 'interpolation': 'tetrahedral',
811                 'direction': 'forward'
812             })
813
814             shaperInverse = shaperOCIOTransform.copy()
815             shaperInverse['direction'] = 'forward'
816             cs.toReferenceTransforms.append(shaperInverse)
817
818         return cs
819
820     #
821     # LMT Shaper
822     #
823
824     lmtLutResolution1d = max(4096, lutResolution1d)
825     lmtLutResolution3d = max(65, lutResolution3d)
826
827     # Log 2 shaper
828     lmtShaperName = 'LMT Shaper'
829     lmtParams = {
830         'middleGrey': 0.18,
831         'minExposure': -10.0,
832         'maxExposure': 6.5
833     }
834     lmtShaper = createGenericLog(name=lmtShaperName,
835                                  middleGrey=lmtParams['middleGrey'],
836                                  minExposure=lmtParams['minExposure'],
837                                  maxExposure=lmtParams['maxExposure'],
838                                  lutResolution1d=lmtLutResolution1d)
839     configData['colorSpaces'].append(lmtShaper)
840
841     shaperInputScale_genericLog2 = 1.0
842
843     # Log 2 shaper name and CTL transforms bundled up
844     lmtShaperData = [
845         lmtShaperName,
846         '%s/utilities/ACESlib.OCIO_shaper_log2_to_lin_param.a1.0.0.ctl',
847         '%s/utilities/ACESlib.OCIO_shaper_lin_to_log2_param.a1.0.0.ctl',
848         shaperInputScale_genericLog2,
849         lmtParams
850     ]
851
852     sortedLMTs = sorted(lmtInfo.iteritems(), key=lambda x: x[1])
853     print( sortedLMTs )
854     for lmt in sortedLMTs:
855         (lmtName, lmtValues) = lmt
856         cs = createACESLMT(
857             lmtValues['transformUserName'],
858             lmtValues,
859             lmtShaperData,
860             lmtLutResolution1d,
861             lmtLutResolution3d,
862             cleanup)
863         configData['colorSpaces'].append(cs)
864
865     #
866     # ACES RRT with the supplied ODT
867     #
868     def createACESRRTplusODT(odtName,
869                              odtValues,
870                              shaperInfo,
871                              lutResolution1d=1024,
872                              lutResolution3d=64,
873                              cleanup=True):
874         cs = ColorSpace("%s" % odtName)
875         cs.description = "%s - %s Output Transform" % (
876             odtValues['transformUserNamePrefix'], odtName)
877         cs.equalityGroup = ''
878         cs.family = 'Output'
879         cs.isData = False
880
881         import pprint
882
883         pprint.pprint(odtValues)
884
885         #
886         # Generate the shaper transform
887         #
888         # if 'shaperCTL' in odtValues:
889         (shaperName, shaperToACESCTL, shaperFromACESCTL, shaperInputScale,
890          shaperParams) = shaperInfo
891
892         if 'legalRange' in odtValues:
893             shaperParams['legalRange'] = odtValues['legalRange']
894         else:
895             shaperParams['legalRange'] = 0
896
897         shaperLut = "%s_to_aces.spi1d" % shaperName
898         if ( not os.path.exists(lutDir + "/" + shaperLut) ):
899             ctls = [
900                 shaperToACESCTL % acesCTLReleaseDir
901             ]
902
903             # Remove spaces and parentheses
904             shaperLut = shaperLut.replace(' ', '_').replace(')', '_').replace(
905                 '(', '_')
906
907             genlut.generate1dLUTFromCTL(lutDir + "/" + shaperLut,
908                                         ctls,
909                                         lutResolution1d,
910                                         'float',
911                                         1.0 / shaperInputScale,
912                                         1.0,
913                                         shaperParams,
914                                         cleanup,
915                                         acesCTLReleaseDir)
916
917         shaperOCIOTransform = {
918             'type': 'lutFile',
919             'path': shaperLut,
920             'interpolation': 'linear',
921             'direction': 'inverse'
922         }
923
924         #
925         # Generate the forward transform
926         #
927         cs.fromReferenceTransforms = []
928
929         if 'transformLUT' in odtValues:
930             # Copy into the lut dir
931             transformLUTFileName = os.path.basename(odtValues['transformLUT'])
932             lut = lutDir + "/" + transformLUTFileName
933             shutil.copy(odtValues['transformLUT'], lut)
934
935             cs.fromReferenceTransforms.append(shaperOCIOTransform)
936             cs.fromReferenceTransforms.append({
937                 'type': 'lutFile',
938                 'path': transformLUTFileName,
939                 'interpolation': 'tetrahedral',
940                 'direction': 'forward'
941             })
942         elif 'transformCTL' in odtValues:
943             # shaperLut
944
945             ctls = [
946                 shaperToACESCTL % acesCTLReleaseDir,
947                 '%s/rrt/RRT.a1.0.0.ctl' % acesCTLReleaseDir,
948                 '%s/odt/%s' % (acesCTLReleaseDir, odtValues['transformCTL'])
949             ]
950             lut = "%s.RRT.a1.0.0.%s.spi3d" % (shaperName, odtName)
951
952             # Remove spaces and parentheses
953             lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
954
955             genlut.generate3dLUTFromCTL(lutDir + "/" + lut,
956                                         # shaperLUT,
957                                         ctls,
958                                         lutResolution3d,
959                                         'float',
960                                         1.0 / shaperInputScale,
961                                         1.0,
962                                         shaperParams,
963                                         cleanup,
964                                         acesCTLReleaseDir)
965
966             cs.fromReferenceTransforms.append(shaperOCIOTransform)
967             cs.fromReferenceTransforms.append({
968                 'type': 'lutFile',
969                 'path': lut,
970                 'interpolation': 'tetrahedral',
971                 'direction': 'forward'
972             })
973
974         #
975         # Generate the inverse transform
976         #
977         cs.toReferenceTransforms = []
978
979         if 'transformLUTInverse' in odtValues:
980             # Copy into the lut dir
981             transformLUTInverseFileName = os.path.basename(
982                 odtValues['transformLUTInverse'])
983             lut = lutDir + "/" + transformLUTInverseFileName
984             shutil.copy(odtValues['transformLUTInverse'], lut)
985
986             cs.toReferenceTransforms.append({
987                 'type': 'lutFile',
988                 'path': transformLUTInverseFileName,
989                 'interpolation': 'tetrahedral',
990                 'direction': 'forward'
991             })
992
993             shaperInverse = shaperOCIOTransform.copy()
994             shaperInverse['direction'] = 'forward'
995             cs.toReferenceTransforms.append(shaperInverse)
996         elif 'transformCTLInverse' in odtValues:
997             ctls = [
998                 '%s/odt/%s' % (
999                     acesCTLReleaseDir, odtValues['transformCTLInverse']),
1000                 '%s/rrt/InvRRT.a1.0.0.ctl' % acesCTLReleaseDir,
1001                 shaperFromACESCTL % acesCTLReleaseDir
1002             ]
1003             lut = "InvRRT.a1.0.0.%s.%s.spi3d" % (odtName, shaperName)
1004
1005             # Remove spaces and parentheses
1006             lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
1007
1008             genlut.generate3dLUTFromCTL(lutDir + "/" + lut,
1009                                         # None,
1010                                         ctls,
1011                                         lutResolution3d,
1012                                         'half',
1013                                         1.0,
1014                                         shaperInputScale,
1015                                         shaperParams,
1016                                         cleanup,
1017                                         acesCTLReleaseDir)
1018
1019             cs.toReferenceTransforms.append({
1020                 'type': 'lutFile',
1021                 'path': lut,
1022                 'interpolation': 'tetrahedral',
1023                 'direction': 'forward'
1024             })
1025
1026             shaperInverse = shaperOCIOTransform.copy()
1027             shaperInverse['direction'] = 'forward'
1028             cs.toReferenceTransforms.append(shaperInverse)
1029
1030         return cs
1031
1032     #
1033     # RRT/ODT shaper options
1034     #
1035     shaperData = {}
1036
1037     # Log 2 shaper
1038     log2ShaperName = shaperName
1039     log2Params = {
1040         'middleGrey': 0.18,
1041         'minExposure': -6.0,
1042         'maxExposure': 6.5
1043     }
1044     log2Shaper = createGenericLog(name=log2ShaperName,
1045                                   middleGrey=log2Params['middleGrey'],
1046                                   minExposure=log2Params['minExposure'],
1047                                   maxExposure=log2Params['maxExposure'])
1048     configData['colorSpaces'].append(log2Shaper)
1049
1050     shaperInputScale_genericLog2 = 1.0
1051
1052     # Log 2 shaper name and CTL transforms bundled up
1053     log2ShaperData = [
1054         log2ShaperName,
1055         '%s/utilities/ACESlib.OCIO_shaper_log2_to_lin_param.a1.0.0.ctl',
1056         '%s/utilities/ACESlib.OCIO_shaper_lin_to_log2_param.a1.0.0.ctl',
1057         shaperInputScale_genericLog2,
1058         log2Params
1059     ]
1060
1061     shaperData[log2ShaperName] = log2ShaperData
1062
1063     #
1064     # Shaper that also includes the AP1 primaries
1065     # - Needed for some LUT baking steps
1066     #
1067     log2ShaperAP1 = createGenericLog(name=log2ShaperName,
1068                                      middleGrey=log2Params['middleGrey'],
1069                                      minExposure=log2Params['minExposure'],
1070                                      maxExposure=log2Params['maxExposure'])
1071     log2ShaperAP1.name = "%s - AP1" % log2ShaperAP1.name
1072     # AP1 primaries to AP0 primaries
1073     log2ShaperAP1.toReferenceTransforms.append({
1074         'type': 'matrix',
1075         'matrix': mat44FromMat33(acesAP1toAP0),
1076         'direction': 'forward'
1077     })
1078     configData['colorSpaces'].append(log2ShaperAP1)
1079
1080     #
1081     # Choose your shaper
1082     #
1083     rrtShaperName = log2ShaperName
1084     rrtShaper = log2ShaperData
1085
1086     #
1087     # RRT + ODT Combinations
1088     #
1089     sortedOdts = sorted(odtInfo.iteritems(), key=lambda x: x[1])
1090     print( sortedOdts )
1091     for odt in sortedOdts:
1092         (odtName, odtValues) = odt
1093
1094         # Have to handle ODTs that can generate either legal or full output
1095         if odtName in ['Academy.Rec2020_100nits_dim.a1.0.0',
1096                        'Academy.Rec709_100nits_dim.a1.0.0',
1097                        'Academy.Rec709_D60sim_100nits_dim.a1.0.0']:
1098             odtNameLegal = '%s - Legal' % odtValues['transformUserName']
1099         else:
1100             odtNameLegal = odtValues['transformUserName']
1101
1102         odtLegal = odtValues.copy()
1103         odtLegal['legalRange'] = 1
1104
1105         cs = createACESRRTplusODT(
1106             odtNameLegal,
1107             odtLegal,
1108             rrtShaper,
1109             lutResolution1d,
1110             lutResolution3d,
1111             cleanup)
1112         configData['colorSpaces'].append(cs)
1113
1114         # Create a display entry using this color space
1115         configData['displays'][odtNameLegal] = {
1116             'Linear': ACES,
1117             'Log': ACEScc,
1118             'Output Transform': cs}
1119
1120         if odtName in ['Academy.Rec2020_100nits_dim.a1.0.0',
1121                        'Academy.Rec709_100nits_dim.a1.0.0',
1122                        'Academy.Rec709_D60sim_100nits_dim.a1.0.0']:
1123             print( "Generating full range ODT for %s" % odtName)
1124
1125             odtNameFull = "%s - Full" % odtValues['transformUserName']
1126             odtFull = odtValues.copy()
1127             odtFull['legalRange'] = 0
1128
1129             csFull = createACESRRTplusODT(
1130                 odtNameFull,
1131                 odtFull,
1132                 rrtShaper,
1133                 lutResolution1d,
1134                 lutResolution3d,
1135                 cleanup)
1136             configData['colorSpaces'].append(csFull)
1137
1138             # Create a display entry using this color space
1139             configData['displays'][odtNameFull] = {
1140                 'Linear': ACES,
1141                 'Log': ACEScc,
1142                 'Output Transform': csFull}
1143
1144     #
1145     # Generic Matrix transform
1146     #
1147     def createGenericMatrix(name='matrix',
1148                             fromReferenceValues=[],
1149                             toReferenceValues=[]):
1150         cs = ColorSpace(name)
1151         cs.description = "The %s color space" % name
1152         cs.equalityGroup = name
1153         cs.family = 'Utility'
1154         cs.isData = False
1155
1156         cs.toReferenceTransforms = []
1157         if toReferenceValues != []:
1158             for matrix in toReferenceValues:
1159                 cs.toReferenceTransforms.append({
1160                     'type': 'matrix',
1161                     'matrix': mat44FromMat33(matrix),
1162                     'direction': 'forward'
1163                 })
1164
1165         cs.fromReferenceTransforms = []
1166         if fromReferenceValues != []:
1167             for matrix in fromReferenceValues:
1168                 cs.fromReferenceTransforms.append({
1169                     'type': 'matrix',
1170                     'matrix': mat44FromMat33(matrix),
1171                     'direction': 'forward'
1172                 })
1173
1174         return cs
1175
1176     cs = createGenericMatrix('XYZ', fromReferenceValues=[acesAP0toXYZ])
1177     configData['colorSpaces'].append(cs)
1178
1179     cs = createGenericMatrix('Linear - AP1', toReferenceValues=[acesAP1toAP0])
1180     configData['colorSpaces'].append(cs)
1181
1182     # ACES to Linear, P3D60 primaries
1183     xyzToP3D60 = [2.4027414142, -0.8974841639, -0.3880533700,
1184                   -0.8325796487, 1.7692317536, 0.0237127115,
1185                   0.0388233815, -0.0824996856, 1.0363685997]
1186
1187     cs = createGenericMatrix('Linear - P3-D60',
1188                              fromReferenceValues=[acesAP0toXYZ, xyzToP3D60])
1189     configData['colorSpaces'].append(cs)
1190
1191     # ACES to Linear, P3D60 primaries
1192     xyzToP3DCI = [2.7253940305, -1.0180030062, -0.4401631952,
1193                   -0.7951680258, 1.6897320548, 0.0226471906,
1194                   0.0412418914, -0.0876390192, 1.1009293786]
1195
1196     cs = createGenericMatrix('Linear - P3-DCI',
1197                              fromReferenceValues=[acesAP0toXYZ, xyzToP3DCI])
1198     configData['colorSpaces'].append(cs)
1199
1200     # ACES to Linear, Rec 709 primaries
1201     xyzToRec709 = [3.2409699419, -1.5373831776, -0.4986107603,
1202                    -0.9692436363, 1.8759675015, 0.0415550574,
1203                    0.0556300797, -0.2039769589, 1.0569715142]
1204
1205     cs = createGenericMatrix('Linear - Rec.709',
1206                              fromReferenceValues=[acesAP0toXYZ, xyzToRec709])
1207     configData['colorSpaces'].append(cs)
1208
1209     # ACES to Linear, Rec 2020 primaries
1210     xyzToRec2020 = [1.7166511880, -0.3556707838, -0.2533662814,
1211                     -0.6666843518, 1.6164812366, 0.0157685458,
1212                     0.0176398574, -0.0427706133, 0.9421031212]
1213
1214     cs = createGenericMatrix('Linear - Rec.2020',
1215                              fromReferenceValues=[acesAP0toXYZ, xyzToRec2020])
1216     configData['colorSpaces'].append(cs)
1217
1218     print( "generateLUTs - end" )
1219     return configData
1220
1221
1222 def generateBakedLUTs(odtInfo, shaperName, bakedDir, configPath,
1223                       lutResolution1d, lutResolution3d,
1224                       lutResolutionShaper=1024):
1225     # Add the legal and full variations into this list
1226     odtInfoC = dict(odtInfo)
1227     for odtCTLName, odtValues in odtInfo.iteritems():
1228         if odtCTLName in ['Academy.Rec2020_100nits_dim.a1.0.0',
1229                           'Academy.Rec709_100nits_dim.a1.0.0',
1230                           'Academy.Rec709_D60sim_100nits_dim.a1.0.0']:
1231             odtName = odtValues["transformUserName"]
1232
1233             odtValuesLegal = dict(odtValues)
1234             odtValuesLegal["transformUserName"] = "%s - Legal" % odtName
1235             odtInfoC["%s - Legal" % odtCTLName] = odtValuesLegal
1236
1237             odtValuesFull = dict(odtValues)
1238             odtValuesFull["transformUserName"] = "%s - Full" % odtName
1239             odtInfoC["%s - Full" % odtCTLName] = odtValuesFull
1240
1241             del ( odtInfoC[odtCTLName] )
1242
1243     for odtCTLName, odtValues in odtInfoC.iteritems():
1244         odtPrefix = odtValues["transformUserNamePrefix"]
1245         odtName = odtValues["transformUserName"]
1246
1247         # For Photoshop
1248         for inputspace in ["ACEScc", "ACESproxy"]:
1249             args = ["--iconfig", configPath, "-v", "--inputspace", inputspace]
1250             args += ["--outputspace", "%s" % odtName]
1251             args += ["--description",
1252                      "%s - %s for %s data" % (odtPrefix, odtName, inputspace)]
1253             args += ["--shaperspace", shaperName, "--shapersize",
1254                      str(lutResolutionShaper)]
1255             args += ["--cubesize", str(lutResolution3d)]
1256             args += ["--format", "icc", "%s/photoshop/%s for %s.icc" % (
1257                 bakedDir, odtName, inputspace)]
1258
1259             bakeLUT = Process(description="bake a LUT", cmd="ociobakelut",
1260                               args=args)
1261             bakeLUT.execute()
1262
1263             # For Flame, Lustre
1264         for inputspace in ["ACEScc", "ACESproxy"]:
1265             args = ["--iconfig", configPath, "-v", "--inputspace", inputspace]
1266             args += ["--outputspace", "%s" % odtName]
1267             args += ["--description",
1268                      "%s - %s for %s data" % (odtPrefix, odtName, inputspace)]
1269             args += ["--shaperspace", shaperName, "--shapersize",
1270                      str(lutResolutionShaper)]
1271             args += ["--cubesize", str(lutResolution3d)]
1272
1273             fargs = ["--format", "flame", "%s/flame/%s for %s Flame.3dl" % (
1274                 bakedDir, odtName, inputspace)]
1275             bakeLUT = Process(description="bake a LUT", cmd="ociobakelut",
1276                               args=(args + fargs))
1277             bakeLUT.execute()
1278
1279             largs = ["--format", "lustre", "%s/lustre/%s for %s Lustre.3dl" % (
1280                 bakedDir, odtName, inputspace)]
1281             bakeLUT = Process(description="bake a LUT", cmd="ociobakelut",
1282                               args=(args + largs))
1283             bakeLUT.execute()
1284
1285         # For Maya, Houdini
1286         for inputspace in ["ACEScg", "ACES2065-1"]:
1287             args = ["--iconfig", configPath, "-v", "--inputspace", inputspace]
1288             args += ["--outputspace", "%s" % odtName]
1289             args += ["--description",
1290                      "%s - %s for %s data" % (odtPrefix, odtName, inputspace)]
1291             if inputspace == 'ACEScg':
1292                 linShaperName = "%s - AP1" % shaperName
1293             else:
1294                 linShaperName = shaperName
1295             args += ["--shaperspace", linShaperName, "--shapersize",
1296                      str(lutResolutionShaper)]
1297
1298             args += ["--cubesize", str(lutResolution3d)]
1299
1300             margs = ["--format", "cinespace", "%s/maya/%s for %s Maya.csp" % (
1301                 bakedDir, odtName, inputspace)]
1302             bakeLUT = Process(description="bake a LUT", cmd="ociobakelut",
1303                               args=(args + margs))
1304             bakeLUT.execute()
1305
1306             hargs = ["--format", "houdini",
1307                      "%s/houdini/%s for %s Houdini.lut" % (
1308                          bakedDir, odtName, inputspace)]
1309             bakeLUT = Process(description="bake a LUT", cmd="ociobakelut",
1310                               args=(args + hargs))
1311             bakeLUT.execute()
1312
1313
1314 def createConfigDir(configDir, bakeSecondaryLUTs):
1315     dirs = [configDir, "%s/luts" % configDir]
1316     if bakeSecondaryLUTs:
1317         dirs.extend(["%s/baked" % configDir,
1318                      "%s/baked/flame" % configDir,
1319                      "%s/baked/photoshop" % configDir,
1320                      "%s/baked/houdini" % configDir,
1321                      "%s/baked/lustre" % configDir,
1322                      "%s/baked/maya" % configDir])
1323
1324     for d in dirs:
1325         if not os.path.exists(d):
1326             os.mkdir(d)
1327
1328
1329 def getTransformInfo(ctlTransform):
1330     fp = open(ctlTransform, 'rb')
1331
1332     # Read lines
1333     lines = fp.readlines()
1334
1335     # Grab transform ID and User Name
1336     transformID = lines[1][3:].split('<')[1].split('>')[1].lstrip().rstrip()
1337     # print( transformID )
1338     transformUserName = '-'.join(
1339         lines[2][3:].split('<')[1].split('>')[1].split('-')[
1340         1:]).lstrip().rstrip()
1341     transformUserNamePrefix = \
1342         lines[2][3:].split('<')[1].split('>')[1].split('-')[
1343             0].lstrip().rstrip()
1344     # print( transformUserName )
1345     fp.close()
1346
1347     return (transformID, transformUserName, transformUserNamePrefix)
1348
1349
1350 # For versions after WGR9
1351 def getODTInfo(acesCTLReleaseDir):
1352     # Credit to Alex Fry for the original approach here
1353     odtDir = os.path.join(acesCTLReleaseDir, "odt")
1354     allodt = []
1355     for dirName, subdirList, fileList in os.walk(odtDir):
1356         for fname in fileList:
1357             allodt.append((os.path.join(dirName, fname)))
1358
1359     odtCTLs = [x for x in allodt if
1360                ("InvODT" not in x) and (os.path.split(x)[-1][0] != '.')]
1361
1362     # print odtCTLs
1363
1364     odts = {}
1365
1366     for odtCTL in odtCTLs:
1367         odtTokens = os.path.split(odtCTL)
1368         # print( odtTokens )
1369
1370         # Handle nested directories
1371         odtPathTokens = os.path.split(odtTokens[-2])
1372         odtDir = odtPathTokens[-1]
1373         while odtPathTokens[-2][-3:] != 'odt':
1374             odtPathTokens = os.path.split(odtPathTokens[-2])
1375             odtDir = os.path.join(odtPathTokens[-1], odtDir)
1376
1377         # Build full name
1378         # print( "odtDir : %s" % odtDir )
1379         transformCTL = odtTokens[-1]
1380         # print( transformCTL )
1381         odtName = string.join(transformCTL.split('.')[1:-1], '.')
1382         # print( odtName )
1383
1384         # Find id, user name and user name prefix
1385         (transformID, transformUserName,
1386          transformUserNamePrefix) = getTransformInfo(
1387             "%s/odt/%s/%s" % (acesCTLReleaseDir, odtDir, transformCTL))
1388
1389         # Find inverse
1390         transformCTLInverse = "InvODT.%s.ctl" % odtName
1391         if not os.path.exists(
1392                 os.path.join(odtTokens[-2], transformCTLInverse)):
1393             transformCTLInverse = None
1394         #print( transformCTLInverse )
1395
1396         # Add to list of ODTs
1397         odts[odtName] = {}
1398         odts[odtName]['transformCTL'] = os.path.join(odtDir, transformCTL)
1399         if transformCTLInverse != None:
1400             odts[odtName]['transformCTLInverse'] = os.path.join(odtDir,
1401                                                                 transformCTLInverse)
1402
1403         odts[odtName]['transformID'] = transformID
1404         odts[odtName]['transformUserNamePrefix'] = transformUserNamePrefix
1405         odts[odtName]['transformUserName'] = transformUserName
1406
1407         print( "ODT : %s" % odtName )
1408         print( "\tTransform ID               : %s" % transformID )
1409         print( "\tTransform User Name Prefix : %s" % transformUserNamePrefix )
1410         print( "\tTransform User Name        : %s" % transformUserName )
1411         print(
1412             "\tForward ctl                : %s" % odts[odtName][
1413                 'transformCTL'])
1414         if 'transformCTLInverse' in odts[odtName]:
1415             print("\tInverse ctl                : %s" % odts[odtName][
1416                 'transformCTLInverse'])
1417         else:
1418             print( "\tInverse ctl                : %s" % "None" )
1419
1420     print( "\n" )
1421
1422     return odts
1423
1424
1425 # For versions after WGR9
1426 def getLMTInfo(acesCTLReleaseDir):
1427     # Credit to Alex Fry for the original approach here
1428     lmtDir = os.path.join(acesCTLReleaseDir, "lmt")
1429     alllmt = []
1430     for dirName, subdirList, fileList in os.walk(lmtDir):
1431         for fname in fileList:
1432             alllmt.append((os.path.join(dirName, fname)))
1433
1434     lmtCTLs = [x for x in alllmt if
1435                ("InvLMT" not in x) and ("README" not in x) and (
1436                    os.path.split(x)[-1][0] != '.')]
1437
1438     # print lmtCTLs
1439
1440     lmts = {}
1441
1442     for lmtCTL in lmtCTLs:
1443         lmtTokens = os.path.split(lmtCTL)
1444         # print( lmtTokens )
1445
1446         # Handle nested directories
1447         lmtPathTokens = os.path.split(lmtTokens[-2])
1448         lmtDir = lmtPathTokens[-1]
1449         while lmtPathTokens[-2][-3:] != 'ctl':
1450             lmtPathTokens = os.path.split(lmtPathTokens[-2])
1451             lmtDir = os.path.join(lmtPathTokens[-1], lmtDir)
1452
1453         # Build full name
1454         # print( "lmtDir : %s" % lmtDir )
1455         transformCTL = lmtTokens[-1]
1456         # print( transformCTL )
1457         lmtName = string.join(transformCTL.split('.')[1:-1], '.')
1458         # print( lmtName )
1459
1460         # Find id, user name and user name prefix
1461         (transformID, transformUserName,
1462          transformUserNamePrefix) = getTransformInfo(
1463             "%s/%s/%s" % (acesCTLReleaseDir, lmtDir, transformCTL))
1464
1465         # Find inverse
1466         transformCTLInverse = "InvLMT.%s.ctl" % lmtName
1467         if not os.path.exists(
1468                 os.path.join(lmtTokens[-2], transformCTLInverse)):
1469             transformCTLInverse = None
1470         #print( transformCTLInverse )
1471
1472         # Add to list of LMTs
1473         lmts[lmtName] = {}
1474         lmts[lmtName]['transformCTL'] = os.path.join(lmtDir, transformCTL)
1475         if transformCTLInverse != None:
1476             # TODO: Check unresolved *odtName* referemce.
1477             lmts[odtName]['transformCTLInverse'] = os.path.join(lmtDir,
1478                                                                 transformCTLInverse)
1479
1480         lmts[lmtName]['transformID'] = transformID
1481         lmts[lmtName]['transformUserNamePrefix'] = transformUserNamePrefix
1482         lmts[lmtName]['transformUserName'] = transformUserName
1483
1484         print( "LMT : %s" % lmtName )
1485         print( "\tTransform ID               : %s" % transformID )
1486         print( "\tTransform User Name Prefix : %s" % transformUserNamePrefix )
1487         print( "\tTransform User Name        : %s" % transformUserName )
1488         print( "\t Forward ctl : %s" % lmts[lmtName]['transformCTL'])
1489         if 'transformCTLInverse' in lmts[lmtName]:
1490             print(
1491                 "\t Inverse ctl : %s" % lmts[lmtName]['transformCTLInverse'])
1492         else:
1493             print( "\t Inverse ctl : %s" % "None" )
1494
1495     print( "\n" )
1496
1497     return lmts
1498
1499
1500 #
1501 # Create the ACES config
1502 #
1503 def createACESConfig(acesCTLReleaseDir,
1504                      configDir,
1505                      lutResolution1d=4096,
1506                      lutResolution3d=64,
1507                      bakeSecondaryLUTs=True,
1508                      cleanup=True):
1509     # Get ODT names and CTL paths
1510     odtInfo = getODTInfo(acesCTLReleaseDir)
1511
1512     # Get ODT names and CTL paths
1513     lmtInfo = getLMTInfo(acesCTLReleaseDir)
1514
1515     # Create config dir
1516     createConfigDir(configDir, bakeSecondaryLUTs)
1517
1518     # Generate config data and LUTs for different transforms
1519     lutDir = "%s/luts" % configDir
1520     shaperName = 'Output Shaper'
1521     configData = generateLUTs(odtInfo, lmtInfo, shaperName, acesCTLReleaseDir,
1522                               lutDir, lutResolution1d, lutResolution3d,
1523                               cleanup)
1524
1525     # Create the config using the generated LUTs
1526     print( "Creating generic config")
1527     config = createConfig(configData)
1528     print( "\n\n\n" )
1529
1530     # Write the config to disk
1531     writeConfig(config, "%s/config.ocio" % configDir)
1532
1533     # Create a config that will work well with Nuke using the previously generated LUTs
1534     print( "Creating Nuke-specific config")
1535     nuke_config = createConfig(configData, nuke=True)
1536     print( "\n\n\n" )
1537
1538     # Write the config to disk
1539     writeConfig(nuke_config, "%s/nuke_config.ocio" % configDir)
1540
1541     # Bake secondary LUTs using the config
1542     if bakeSecondaryLUTs:
1543         generateBakedLUTs(odtInfo, shaperName, "%s/baked" % configDir,
1544                           "%s/config.ocio" % configDir, lutResolution1d,
1545                           lutResolution3d, lutResolution1d)
1546
1547     return True
1548
1549
1550 #
1551 # Main
1552 #
1553 def main():
1554     import optparse
1555
1556     p = optparse.OptionParser(description='An OCIO config generation script',
1557                               prog='createACESConfig',
1558                               version='createACESConfig 0.1',
1559                               usage='%prog [options]')
1560     p.add_option('--acesCTLDir', '-a', default=os.environ.get(
1561         'ACES_OCIO_CTL_DIRECTORY', None))
1562     p.add_option('--configDir', '-c', default=os.environ.get(
1563         'ACES_OCIO_CONFIGURATION_DIRECTORY', None))
1564     p.add_option('--lutResolution1d', default=4096)
1565     p.add_option('--lutResolution3d', default=64)
1566     p.add_option('--dontBakeSecondaryLUTs', action="store_true")
1567     p.add_option('--keepTempImages', action="store_true")
1568
1569     options, arguments = p.parse_args()
1570
1571     #
1572     # Get options
1573     # 
1574     acesCTLDir = options.acesCTLDir
1575     configDir = options.configDir
1576     lutResolution1d = int(options.lutResolution1d)
1577     lutResolution3d = int(options.lutResolution3d)
1578     bakeSecondaryLUTs = not (options.dontBakeSecondaryLUTs)
1579     cleanupTempImages = not (options.keepTempImages)
1580
1581     try:
1582         argsStart = sys.argv.index('--') + 1
1583         args = sys.argv[argsStart:]
1584     except:
1585         argsStart = len(sys.argv) + 1
1586         args = []
1587
1588     print( "command line : \n%s\n" % " ".join(sys.argv) )
1589
1590     # TODO: Use assertion and mention environment variables.
1591     if not acesCTLDir:
1592         print( "process: No ACES CTL directory specified" )
1593         return
1594     if not configDir:
1595         print( "process: No configuration directory specified" )
1596         return
1597     #
1598     # Generate the configuration
1599     #
1600     createACESConfig(acesCTLDir, configDir, lutResolution1d, lutResolution3d,
1601                      bakeSecondaryLUTs, cleanupTempImages)
1602
1603 # main
1604
1605 if __name__ == '__main__':
1606     main()