Implement "aces_ocio.utilities.sanitize_path" definition.
[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 Defines objects creating the *ACES* configuration.
6 """
7
8 import math
9 import numpy
10 import os
11 import pprint
12 import shutil
13 import string
14 import sys
15
16 # TODO: This restores the capability of running the script without having
17 # added the package to PYTHONPATH, this is ugly and should ideally replaced by
18 # dedicated executable in a /bin directory.
19 sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
20
21 import PyOpenColorIO as ocio
22
23 import aces_ocio.create_arri_colorspaces as arri
24 import aces_ocio.create_canon_colorspaces as canon
25 import aces_ocio.create_red_colorspaces as red
26 import aces_ocio.create_sony_colorspaces as sony
27 from aces_ocio.generate_lut import (
28     generate_1d_LUT_from_CTL,
29     generate_3d_LUT_from_CTL,
30     write_SPI_1d)
31 from aces_ocio.process import Process
32 from aces_ocio.utilities import ColorSpace, mat44_from_mat33, sanitize_path
33
34 __author__ = 'ACES Developers'
35 __copyright__ = 'Copyright (C) 2014 - 2015 - ACES Developers'
36 __license__ = ''
37 __maintainer__ = 'ACES Developers'
38 __email__ = 'aces@oscars.org'
39 __status__ = 'Production'
40
41 __all__ = ['ACES_OCIO_CTL_DIRECTORY_ENVIRON',
42            'ACES_OCIO_CONFIGURATION_DIRECTORY_ENVIRON',
43            'set_config_default_roles',
44            'write_config',
45            'generate_OCIO_transform',
46            'create_config',
47            'generate_LUTs',
48            'generate_baked_LUTs',
49            'create_config_dir',
50            'get_transform_info',
51            'get_ODT_info',
52            'get_LMT_info',
53            'create_ACES_config',
54            'main']
55
56 ACES_OCIO_CTL_DIRECTORY_ENVIRON = 'ACES_OCIO_CTL_DIRECTORY'
57 ACES_OCIO_CONFIGURATION_DIRECTORY_ENVIRON = 'ACES_OCIO_CONFIGURATION_DIRECTORY'
58
59
60 def set_config_default_roles(config,
61                              color_picking='',
62                              color_timing='',
63                              compositing_log='',
64                              data='',
65                              default='',
66                              matte_paint='',
67                              reference='',
68                              scene_linear='',
69                              texture_paint=''):
70     """
71     Sets given *OCIO* configuration default roles.
72
73     Parameters
74     ----------
75     config : config
76         *OCIO* configuration.
77     color_picking : str or unicode
78         Color picking role title.
79     color_timing : str or unicode
80         Color timing role title.
81     compositing_log : str or unicode
82         Compositing log role title.
83     data : str or unicode
84         Data role title.
85     default : str or unicode
86         Default role title.
87     matte_paint : str or unicode
88         Matte painting role title.
89     reference : str or unicode
90         Reference role title.
91     scene_linear : str or unicode
92         Scene linear role title.
93     texture_paint : str or unicode
94         Texture painting role title.
95
96     Returns
97     -------
98     bool
99          Definition success.
100     """
101
102     if color_picking:
103         config.setRole(ocio.Constants.ROLE_COLOR_PICKING, color_picking)
104     if color_timing:
105         config.setRole(ocio.Constants.ROLE_COLOR_TIMING, color_timing)
106     if compositing_log:
107         config.setRole(ocio.Constants.ROLE_COMPOSITING_LOG, compositing_log)
108     if data:
109         config.setRole(ocio.Constants.ROLE_DATA, data)
110     if default:
111         config.setRole(ocio.Constants.ROLE_DEFAULT, default)
112     if matte_paint:
113         config.setRole(ocio.Constants.ROLE_MATTE_PAINT, matte_paint)
114     if reference:
115         config.setRole(ocio.Constants.ROLE_REFERENCE, reference)
116     if scene_linear:
117         config.setRole(ocio.Constants.ROLE_SCENE_LINEAR, scene_linear)
118     if texture_paint:
119         config.setRole(ocio.Constants.ROLE_TEXTURE_PAINT, texture_paint)
120
121     return True
122
123
124 def write_config(config, config_path, sanity_check=True):
125     """
126     Writes the configuration to given path.
127
128     Parameters
129     ----------
130     parameter : type
131         Parameter description.
132
133     Returns
134     -------
135     type
136          Return value description.
137     """
138
139     if sanity_check:
140         try:
141             config.sanityCheck()
142         except Exception, e:
143             print e
144             print 'Configuration was not written due to a failed Sanity Check'
145             return
146             # sys.exit()
147
148     file_handle = open(config_path, mode='w')
149     file_handle.write(config.serialize())
150     file_handle.close()
151
152
153 def generate_OCIO_transform(transforms):
154     """
155     Object description.
156
157     Parameters
158     ----------
159     parameter : type
160         Parameter description.
161
162     Returns
163     -------
164     type
165          Return value description.
166     """
167
168     # print('Generating transforms')
169
170     interpolation_options = {
171         'linear': ocio.Constants.INTERP_LINEAR,
172         'nearest': ocio.Constants.INTERP_NEAREST,
173         'tetrahedral': ocio.Constants.INTERP_TETRAHEDRAL
174     }
175     direction_options = {
176         'forward': ocio.Constants.TRANSFORM_DIR_FORWARD,
177         'inverse': ocio.Constants.TRANSFORM_DIR_INVERSE
178     }
179
180     ocio_transforms = []
181
182     for transform in transforms:
183         if transform['type'] == 'lutFile':
184             ocio_transform = ocio.FileTransform(
185                 src=transform['path'],
186                 interpolation=interpolation_options[
187                     transform['interpolation']],
188                 direction=direction_options[transform['direction']])
189             ocio_transforms.append(ocio_transform)
190         elif transform['type'] == 'matrix':
191             ocio_transform = ocio.MatrixTransform()
192             # MatrixTransform member variables can't be initialized directly.
193             # Each must be set individually.
194             ocio_transform.setMatrix(transform['matrix'])
195
196             if 'offset' in transform:
197                 ocio_transform.setOffset(transform['offset'])
198
199             if 'direction' in transform:
200                 ocio_transform.setDirection(
201                     direction_options[transform['direction']])
202
203             ocio_transforms.append(ocio_transform)
204         elif transform['type'] == 'exponent':
205             ocio_transform = ocio.ExponentTransform()
206             ocio_transform.setValue(transform['value'])
207             ocio_transforms.append(ocio_transform)
208         elif transform['type'] == 'log':
209             ocio_transform = ocio.LogTransform(
210                 base=transform['base'],
211                 direction=direction_options[transform['direction']])
212
213             ocio_transforms.append(ocio_transform)
214         else:
215             print('Ignoring unknown transform type : %s' % transform['type'])
216
217     # Build a group transform if necessary
218     if len(ocio_transforms) > 1:
219         transform_G = ocio.GroupTransform()
220         for transform in ocio_transforms:
221             transform_G.push_back(transform)
222         transform = transform_G
223
224     # Or take the first transform from the list
225     else:
226         transform = ocio_transforms[0]
227
228     return transform
229
230
231 def create_config(config_data, nuke=False):
232     """
233     Object description.
234
235     Parameters
236     ----------
237     parameter : type
238         Parameter description.
239
240     Returns
241     -------
242     type
243          Return value description.
244     """
245
246     # Create the config
247     config = ocio.Config()
248
249     #
250     # Set config wide values
251     #
252     config.setDescription('An ACES config generated from python')
253     config.setSearchPath('luts')
254
255     #
256     # Define the reference color space
257     #
258     reference_data = config_data['referenceColorSpace']
259     print('Adding the reference color space : %s' % reference_data.name)
260
261     # Create a color space
262     reference = ocio.ColorSpace(
263         name=reference_data.name,
264         bitDepth=reference_data.bit_depth,
265         description=reference_data.description,
266         equalityGroup=reference_data.equality_group,
267         family=reference_data.family,
268         isData=reference_data.is_data,
269         allocation=reference_data.allocation_type,
270         allocationVars=reference_data.allocation_vars)
271
272     # Add to config
273     config.addColorSpace(reference)
274
275     #
276     # Create the rest of the color spaces
277     #
278     for colorspace in sorted(config_data['colorSpaces']):
279         print('Creating new color space : %s' % colorspace.name)
280
281         ocio_colorspace = ocio.ColorSpace(
282             name=colorspace.name,
283             bitDepth=colorspace.bit_depth,
284             description=colorspace.description,
285             equalityGroup=colorspace.equality_group,
286             family=colorspace.family,
287             isData=colorspace.is_data,
288             allocation=colorspace.allocation_type,
289             allocationVars=colorspace.allocation_vars)
290
291         if colorspace.to_reference_transforms != []:
292             print('Generating To-Reference transforms')
293             ocio_transform = generate_OCIO_transform(
294                 colorspace.to_reference_transforms)
295             ocio_colorspace.setTransform(
296                 ocio_transform,
297                 ocio.Constants.COLORSPACE_DIR_TO_REFERENCE)
298
299         if colorspace.from_reference_transforms != []:
300             print('Generating From-Reference transforms')
301             ocio_transform = generate_OCIO_transform(
302                 colorspace.from_reference_transforms)
303             ocio_colorspace.setTransform(
304                 ocio_transform,
305                 ocio.Constants.COLORSPACE_DIR_FROM_REFERENCE)
306
307         config.addColorSpace(ocio_colorspace)
308
309         print('')
310
311     #
312     # Define the views and displays
313     #
314     displays = []
315     views = []
316
317     # Generic display and view setup
318     if not nuke:
319         for display, view_list in config_data['displays'].iteritems():
320             for view_name, colorspace in view_list.iteritems():
321                 config.addDisplay(display, view_name, colorspace.name)
322                 if not (view_name in views):
323                     views.append(view_name)
324             displays.append(display)
325     # A Nuke specific set of views and displays
326     #
327     # XXX
328     # A few names: Output Transform, ACES, ACEScc, are hard-coded here.
329     # Would be better to automate.
330     #
331     else:
332         for display, view_list in config_data['displays'].iteritems():
333             for view_name, colorspace in view_list.iteritems():
334                 if (view_name == 'Output Transform'):
335                     view_name = 'View'
336                     config.addDisplay(display, view_name, colorspace.name)
337                     if not (view_name in views):
338                         views.append(view_name)
339             displays.append(display)
340
341         config.addDisplay('linear', 'View', 'ACES2065-1')
342         displays.append('linear')
343         config.addDisplay('log', 'View', 'ACEScc')
344         displays.append('log')
345
346     # Set active displays and views
347     config.setActiveDisplays(','.join(sorted(displays)))
348     config.setActiveViews(','.join(views))
349
350     #
351     # Need to generalize this at some point
352     #
353
354     # Add Default Roles
355     set_config_default_roles(
356         config,
357         color_picking=reference.getName(),
358         color_timing=reference.getName(),
359         compositing_log=reference.getName(),
360         data=reference.getName(),
361         default=reference.getName(),
362         matte_paint=reference.getName(),
363         reference=reference.getName(),
364         scene_linear=reference.getName(),
365         texture_paint=reference.getName())
366
367     # Check to make sure we didn't screw something up
368     config.sanityCheck()
369
370     return config
371
372
373 def generate_LUTs(odt_info,
374                   lmt_info,
375                   shaper_name,
376                   aces_CTL_directory,
377                   lut_directory,
378                   lut_resolution_1d=4096,
379                   lut_resolution_3d=64,
380                   cleanup=True):
381     """
382     Object description.
383
384     Parameters
385     ----------
386     parameter : type
387         Parameter description.
388
389     Returns
390     -------
391     dict
392          Colorspaces and transforms converting between those colorspaces and
393          the reference colorspace, *ACES*.
394     """
395
396     print('generateLUTs - begin')
397     config_data = {}
398
399     #
400     # Define the reference color space
401     #
402     ACES = ColorSpace('ACES2065-1')
403     ACES.description = (
404         'The Academy Color Encoding System reference color space')
405     ACES.equality_group = ''
406     ACES.family = 'ACES'
407     ACES.is_data = False
408     ACES.allocation_type = ocio.Constants.ALLOCATION_LG2
409     ACES.allocation_vars = [-15, 6]
410
411     config_data['referenceColorSpace'] = ACES
412
413     #
414     # Define the displays
415     #
416     config_data['displays'] = {}
417
418     #
419     # Define the other color spaces
420     #
421     config_data['colorSpaces'] = []
422
423     # Matrix converting ACES AP1 primaries to AP0
424     ACES_AP1_to_AP0 = [0.6954522414, 0.1406786965, 0.1638690622,
425                        0.0447945634, 0.8596711185, 0.0955343182,
426                        -0.0055258826, 0.0040252103, 1.0015006723]
427
428     # Matrix converting ACES AP0 primaries to XYZ
429     ACES_AP0_to_XYZ = [0.9525523959, 0.0000000000, 0.0000936786,
430                        0.3439664498, 0.7281660966, -0.0721325464,
431                        0.0000000000, 0.0000000000, 1.0088251844]
432
433     #
434     # ACEScc
435     #
436     def create_ACEScc(name='ACEScc',
437                       min_value=0.0,
438                       max_value=1.0,
439                       input_scale=1.0):
440         cs = ColorSpace(name)
441         cs.description = 'The %s color space' % name
442         cs.equality_group = ''
443         cs.family = 'ACES'
444         cs.is_data = False
445
446         ctls = [os.path.join(aces_CTL_directory,
447                              'ACEScc',
448                              'ACEScsc.ACEScc_to_ACES.a1.0.0.ctl'),
449                 # This transform gets back to the AP1 primaries
450                 # Useful as the 1d LUT is only covering the transfer function
451                 # The primaries switch is covered by the matrix below
452                 os.path.join(aces_CTL_directory,
453                              'ACEScg',
454                              'ACEScsc.ACES_to_ACEScg.a1.0.0.ctl')]
455         lut = '%s_to_ACES.spi1d' % name
456
457         lut = sanitize_path(lut)
458
459         generate_1d_LUT_from_CTL(
460             os.path.join(lut_directory, lut),
461             ctls,
462             lut_resolution_1d,
463             'float',
464             input_scale,
465             1.0,
466             {},
467             cleanup,
468             aces_CTL_directory,
469             min_value,
470             max_value)
471
472         cs.to_reference_transforms = []
473         cs.to_reference_transforms.append({
474             'type': 'lutFile',
475             'path': lut,
476             'interpolation': 'linear',
477             'direction': 'forward'
478         })
479
480         # AP1 primaries to AP0 primaries
481         cs.to_reference_transforms.append({
482             'type': 'matrix',
483             'matrix': mat44_from_mat33(ACES_AP1_to_AP0),
484             'direction': 'forward'
485         })
486
487         cs.from_reference_transforms = []
488         return cs
489
490     ACEScc = create_ACEScc()
491     config_data['colorSpaces'].append(ACEScc)
492
493     #
494     # ACESproxy
495     #
496     def create_ACESproxy(name='ACESproxy'):
497         cs = ColorSpace(name)
498         cs.description = 'The %s color space' % name
499         cs.equality_group = ''
500         cs.family = 'ACES'
501         cs.is_data = False
502
503         ctls = [
504             os.path.join(aces_CTL_directory,
505                          'ACESproxy',
506                          'ACEScsc.ACESproxy10i_to_ACES.a1.0.0.ctl'),
507             # This transform gets back to the AP1 primaries
508             # Useful as the 1d LUT is only covering the transfer function
509             # The primaries switch is covered by the matrix below
510             os.path.join(aces_CTL_directory,
511                          'ACEScg',
512                          'ACEScsc.ACES_to_ACEScg.a1.0.0.ctl')]
513         lut = '%s_to_aces.spi1d' % name
514
515         lut = sanitize_path(lut)
516
517         generate_1d_LUT_from_CTL(
518             os.path.join(lut_directory, lut),
519             ctls,
520             lut_resolution_1d,
521             'uint16',
522             64.0,
523             1.0,
524             {},
525             cleanup,
526             aces_CTL_directory)
527
528         cs.to_reference_transforms = []
529         cs.to_reference_transforms.append({
530             'type': 'lutFile',
531             'path': lut,
532             'interpolation': 'linear',
533             'direction': 'forward'
534         })
535
536         # AP1 primaries to AP0 primaries
537         cs.to_reference_transforms.append({
538             'type': 'matrix',
539             'matrix': mat44_from_mat33(ACES_AP1_to_AP0),
540             'direction': 'forward'
541         })
542
543         cs.from_reference_transforms = []
544         return cs
545
546     ACESproxy = create_ACESproxy()
547     config_data['colorSpaces'].append(ACESproxy)
548
549     #
550     # ACEScg
551     #
552     def create_ACEScg(name='ACEScg'):
553         cs = ColorSpace(name)
554         cs.description = 'The %s color space' % name
555         cs.equality_group = ''
556         cs.family = 'ACES'
557         cs.is_data = False
558
559         cs.to_reference_transforms = []
560
561         # AP1 primaries to AP0 primaries
562         cs.to_reference_transforms.append({
563             'type': 'matrix',
564             'matrix': mat44_from_mat33(ACES_AP1_to_AP0),
565             'direction': 'forward'
566         })
567
568         cs.from_reference_transforms = []
569         return cs
570
571     ACEScg = create_ACEScg()
572     config_data['colorSpaces'].append(ACEScg)
573
574     #
575     # ADX
576     #
577     def create_ADX(bit_depth=10, name='ADX'):
578         name = '%s%s' % (name, bit_depth)
579         cs = ColorSpace(name)
580         cs.description = '%s color space - used for film scans' % name
581         cs.equality_group = ''
582         cs.family = 'ADX'
583         cs.is_data = False
584
585         if bit_depth == 10:
586             cs.bit_depth = bit_depth = ocio.Constants.BIT_DEPTH_UINT10
587             adx_to_cdd = [1023.0 / 500.0, 0.0, 0.0, 0.0,
588                           0.0, 1023.0 / 500.0, 0.0, 0.0,
589                           0.0, 0.0, 1023.0 / 500.0, 0.0,
590                           0.0, 0.0, 0.0, 1.0]
591             offset = [-95.0 / 500.0, -95.0 / 500.0, -95.0 / 500.0, 0.0]
592         elif bit_depth == 16:
593             cs.bit_depth = bit_depth = ocio.Constants.BIT_DEPTH_UINT16
594             adx_to_cdd = [65535.0 / 8000.0, 0.0, 0.0, 0.0,
595                           0.0, 65535.0 / 8000.0, 0.0, 0.0,
596                           0.0, 0.0, 65535.0 / 8000.0, 0.0,
597                           0.0, 0.0, 0.0, 1.0]
598             offset = [-1520.0 / 8000.0, -1520.0 / 8000.0, -1520.0 / 8000.0,
599                       0.0]
600
601         cs.to_reference_transforms = []
602
603         # Convert from ADX to Channel-Dependent Density
604         cs.to_reference_transforms.append({
605             'type': 'matrix',
606             'matrix': adx_to_cdd,
607             'offset': offset,
608             'direction': 'forward'
609         })
610
611         # Convert from Channel-Dependent Density to Channel-Independent Density
612         cs.to_reference_transforms.append({
613             'type': 'matrix',
614             'matrix': [0.75573, 0.22197, 0.02230, 0,
615                        0.05901, 0.96928, -0.02829, 0,
616                        0.16134, 0.07406, 0.76460, 0,
617                        0.0, 0.0, 0.0, 1.0],
618             'direction': 'forward'
619         })
620
621         # Copied from Alex Fry's adx_cid_to_rle.py
622         def create_CID_to_RLE_LUT():
623             def interpolate_1D(x, xp, fp):
624                 return numpy.interp(x, xp, fp)
625
626             LUT_1D_xp = [-0.190000000000000,
627                          0.010000000000000,
628                          0.028000000000000,
629                          0.054000000000000,
630                          0.095000000000000,
631                          0.145000000000000,
632                          0.220000000000000,
633                          0.300000000000000,
634                          0.400000000000000,
635                          0.500000000000000,
636                          0.600000000000000]
637
638             LUT_1D_fp = [-6.000000000000000,
639                          -2.721718645000000,
640                          -2.521718645000000,
641                          -2.321718645000000,
642                          -2.121718645000000,
643                          -1.921718645000000,
644                          -1.721718645000000,
645                          -1.521718645000000,
646                          -1.321718645000000,
647                          -1.121718645000000,
648                          -0.926545676714876]
649
650             REF_PT = ((7120.0 - 1520.0) / 8000.0 * (100.0 / 55.0) -
651                       math.log(0.18, 10.0))
652
653             def cid_to_rle(x):
654                 if x <= 0.6:
655                     return interpolate_1D(x, LUT_1D_xp, LUT_1D_fp)
656                 return (100.0 / 55.0) * x - REF_PT
657
658             def fit(value, from_min, from_max, to_min, to_max):
659                 if from_min == from_max:
660                     raise ValueError('from_min == from_max')
661                 return (value - from_min) / (from_max - from_min) * (
662                     to_max - to_min) + to_min
663
664             NUM_SAMPLES = 2 ** 12
665             RANGE = (-0.19, 3.0)
666             data = []
667             for i in xrange(NUM_SAMPLES):
668                 x = i / (NUM_SAMPLES - 1.0)
669                 x = fit(x, 0.0, 1.0, RANGE[0], RANGE[1])
670                 data.append(cid_to_rle(x))
671
672             lut = 'ADX_CID_to_RLE.spi1d'
673             write_SPI_1d(os.path.join(lut_directory, lut),
674                          RANGE[0],
675                          RANGE[1],
676                          data,
677                          NUM_SAMPLES, 1)
678
679             return lut
680
681         # Convert Channel Independent Density values to Relative Log Exposure
682         # values.
683         lut = create_CID_to_RLE_LUT()
684         cs.to_reference_transforms.append({
685             'type': 'lutFile',
686             'path': lut,
687             'interpolation': 'linear',
688             'direction': 'forward'
689         })
690
691         # Convert Relative Log Exposure values to Relative Exposure values
692         cs.to_reference_transforms.append({
693             'type': 'log',
694             'base': 10,
695             'direction': 'inverse'
696         })
697
698         # Convert Relative Exposure values to ACES values
699         cs.to_reference_transforms.append({
700             'type': 'matrix',
701             'matrix': [0.72286, 0.12630, 0.15084, 0,
702                        0.11923, 0.76418, 0.11659, 0,
703                        0.01427, 0.08213, 0.90359, 0,
704                        0.0, 0.0, 0.0, 1.0],
705             'direction': 'forward'
706         })
707
708         cs.from_reference_transforms = []
709         return cs
710
711     ADX10 = create_ADX(bit_depth=10)
712     config_data['colorSpaces'].append(ADX10)
713
714     ADX16 = create_ADX(bit_depth=16)
715     config_data['colorSpaces'].append(ADX16)
716
717     #
718     # Camera Input Transforms
719     #
720
721     # RED color spaces to ACES
722     red_colorspaces = red.create_colorspaces(lut_directory, lut_resolution_1d)
723     for cs in red_colorspaces:
724         config_data['colorSpaces'].append(cs)
725
726     # Canon-Log to ACES
727     canon_colorspaces = canon.create_colorspaces(lut_directory,
728                                                  lut_resolution_1d)
729     for cs in canon_colorspaces:
730         config_data['colorSpaces'].append(cs)
731
732     # S-Log to ACES
733     sony_colorSpaces = sony.create_colorspaces(lut_directory,
734                                                lut_resolution_1d)
735     for cs in sony_colorSpaces:
736         config_data['colorSpaces'].append(cs)
737
738     # Log-C to ACES
739     arri_colorSpaces = arri.create_colorspaces(lut_directory,
740                                                lut_resolution_1d)
741     for cs in arri_colorSpaces:
742         config_data['colorSpaces'].append(cs)
743
744     #
745     # Generic log transform
746     #
747     def create_generic_log(name='log',
748                            min_value=0.0,
749                            max_value=1.0,
750                            input_scale=1.0,
751                            middle_grey=0.18,
752                            min_exposure=-6.0,
753                            max_exposure=6.5,
754                            lut_resolution_1d=lut_resolution_1d):
755         cs = ColorSpace(name)
756         cs.description = 'The %s color space' % name
757         cs.equality_group = name
758         cs.family = 'Utility'
759         cs.is_data = False
760
761         ctls = [
762             os.path.join(aces_CTL_directory,
763                          'utilities',
764                          'ACESlib.OCIO_shaper_log2_to_lin_param.a1.0.0.ctl')]
765         lut = '%s_to_aces.spi1d' % name
766
767         lut = sanitize_path(lut)
768
769         generate_1d_LUT_from_CTL(
770             os.path.join(lut_directory, lut),
771             ctls,
772             lut_resolution_1d,
773             'float',
774             input_scale,
775             1.0,
776             {
777                 'middleGrey': middle_grey,
778                 'minExposure': min_exposure,
779                 'maxExposure': max_exposure
780             },
781             cleanup,
782             aces_CTL_directory,
783             min_value,
784             max_value)
785
786         cs.to_reference_transforms = []
787         cs.to_reference_transforms.append({
788             'type': 'lutFile',
789             'path': lut,
790             'interpolation': 'linear',
791             'direction': 'forward'
792         })
793
794         cs.from_reference_transforms = []
795         return cs
796
797     #
798     # ACES LMTs
799     #
800     def create_ACES_LMT(lmt_name,
801                         lmt_values,
802                         shaper_info,
803                         lut_resolution_1d=1024,
804                         lut_resolution_3d=64,
805                         cleanup=True):
806         cs = ColorSpace('%s' % lmt_name)
807         cs.description = 'The ACES Look Transform: %s' % lmt_name
808         cs.equality_group = ''
809         cs.family = 'Look'
810         cs.is_data = False
811
812         pprint.pprint(lmt_values)
813
814         #
815         # Generate the shaper transform
816         #
817         (shaper_name,
818          shaper_to_ACES_CTL,
819          shaper_from_ACES_CTL,
820          shaper_input_scale,
821          shaper_params) = shaper_info
822
823         shaper_lut = '%s_to_aces.spi1d' % shaper_name
824         if (not os.path.exists(os.path.join(lut_directory, shaper_lut))):
825             ctls = [shaper_to_ACES_CTL % aces_CTL_directory]
826
827             # Remove spaces and parentheses
828             shaper_lut = shaper_lut.replace(
829                 ' ', '_').replace(')', '_').replace('(', '_')
830
831             generate_1d_LUT_from_CTL(
832                 os.path.join(lut_directory, shaper_lut),
833                 ctls,
834                 lut_resolution_1d,
835                 'float',
836                 1.0 / shaper_input_scale,
837                 1.0,
838                 shaper_params,
839                 cleanup,
840                 aces_CTL_directory)
841
842         shaper_OCIO_transform = {
843             'type': 'lutFile',
844             'path': shaper_lut,
845             'interpolation': 'linear',
846             'direction': 'inverse'
847         }
848
849         #
850         # Generate the forward transform
851         #
852         cs.from_reference_transforms = []
853
854         if 'transformCTL' in lmt_values:
855             ctls = [
856                 shaper_to_ACES_CTL % aces_CTL_directory,
857                 os.path.join(aces_CTL_directory, lmt_values['transformCTL'])]
858             lut = '%s.%s.spi3d' % (shaper_name, lmt_name)
859
860             lut = sanitize_path(lut)
861
862             generate_3d_LUT_from_CTL(
863                 os.path.join(lut_directory, lut),
864                 ctls,
865                 lut_resolution_3d,
866                 'float',
867                 1.0 / shaper_input_scale,
868                 1.0,
869                 shaper_params,
870                 cleanup,
871                 aces_CTL_directory)
872
873             cs.from_reference_transforms.append(shaper_OCIO_transform)
874             cs.from_reference_transforms.append({
875                 'type': 'lutFile',
876                 'path': lut,
877                 'interpolation': 'tetrahedral',
878                 'direction': 'forward'
879             })
880
881         #
882         # Generate the inverse transform
883         #
884         cs.to_reference_transforms = []
885
886         if 'transformCTLInverse' in lmt_values:
887             ctls = [
888                 os.path.join(aces_CTL_directory,
889                              odt_values['transformCTLInverse']),
890                 shaper_from_ACES_CTL % aces_CTL_directory
891             ]
892             lut = 'Inverse.%s.%s.spi3d' % (odt_name, shaper_name)
893
894             lut = sanitize_path(lut)
895
896             generate_3d_LUT_from_CTL(
897                 os.path.join(lut_directory, lut),
898                 ctls,
899                 lut_resolution_3d,
900                 'half',
901                 1.0,
902                 shaper_input_scale,
903                 shaper_params,
904                 cleanup,
905                 aces_CTL_directory)
906
907             cs.to_reference_transforms.append({
908                 'type': 'lutFile',
909                 'path': lut,
910                 'interpolation': 'tetrahedral',
911                 'direction': 'forward'
912             })
913
914             shaper_inverse = shaper_OCIO_transform.copy()
915             shaper_inverse['direction'] = 'forward'
916             cs.to_reference_transforms.append(shaper_inverse)
917
918         return cs
919
920     #
921     # LMT Shaper
922     #
923
924     lmt_lut_resolution_1d = max(4096, lut_resolution_1d)
925     lmt_lut_resolution_3d = max(65, lut_resolution_3d)
926
927     # Log 2 shaper
928     lmt_shaper_name = 'LMT Shaper'
929     lmt_params = {
930         'middleGrey': 0.18,
931         'minExposure': -10.0,
932         'maxExposure': 6.5
933     }
934     lmt_shaper = create_generic_log(name=lmt_shaper_name,
935                                     middle_grey=lmt_params['middleGrey'],
936                                     min_exposure=lmt_params['minExposure'],
937                                     max_exposure=lmt_params['maxExposure'],
938                                     lut_resolution_1d=lmt_lut_resolution_1d)
939     config_data['colorSpaces'].append(lmt_shaper)
940
941     shaper_input_scale_generic_log2 = 1.0
942
943     # Log 2 shaper name and CTL transforms bundled up
944     lmt_shaper_data = [
945         lmt_shaper_name,
946         os.path.join('%s',
947                      'utilities',
948                      'ACESlib.OCIO_shaper_log2_to_lin_param.a1.0.0.ctl'),
949         os.path.join('%s',
950                      'utilities',
951                      'ACESlib.OCIO_shaper_lin_to_log2_param.a1.0.0.ctl'),
952         shaper_input_scale_generic_log2,
953         lmt_params]
954
955     sorted_LMTs = sorted(lmt_info.iteritems(), key=lambda x: x[1])
956     print(sorted_LMTs)
957     for lmt in sorted_LMTs:
958         (lmt_name, lmt_values) = lmt
959         cs = create_ACES_LMT(
960             lmt_values['transformUserName'],
961             lmt_values,
962             lmt_shaper_data,
963             lmt_lut_resolution_1d,
964             lmt_lut_resolution_3d,
965             cleanup)
966         config_data['colorSpaces'].append(cs)
967
968     #
969     # ACES RRT with the supplied ODT
970     #
971     def create_ACES_RRT_plus_ODT(odt_name,
972                                  odt_values,
973                                  shaper_info,
974                                  lut_resolution_1d=1024,
975                                  lut_resolution_3d=64,
976                                  cleanup=True):
977         cs = ColorSpace('%s' % odt_name)
978         cs.description = '%s - %s Output Transform' % (
979             odt_values['transformUserNamePrefix'], odt_name)
980         cs.equality_group = ''
981         cs.family = 'Output'
982         cs.is_data = False
983
984         pprint.pprint(odt_values)
985
986         #
987         # Generate the shaper transform
988         #
989         # if 'shaperCTL' in odtValues:
990         (shaper_name,
991          shaper_to_ACES_CTL,
992          shaper_from_ACES_CTL,
993          shaper_input_scale,
994          shaper_params) = shaper_info
995
996         if 'legalRange' in odt_values:
997             shaper_params['legalRange'] = odt_values['legalRange']
998         else:
999             shaper_params['legalRange'] = 0
1000
1001         shaper_lut = '%s_to_aces.spi1d' % shaper_name
1002         if (not os.path.exists(os.path.join(lut_directory, shaper_lut))):
1003             ctls = [shaper_to_ACES_CTL % aces_CTL_directory]
1004
1005             # Remove spaces and parentheses
1006             shaper_lut = shaper_lut.replace(
1007                 ' ', '_').replace(')', '_').replace('(', '_')
1008
1009             generate_1d_LUT_from_CTL(
1010                 os.path.join(lut_directory, shaper_lut),
1011                 ctls,
1012                 lut_resolution_1d,
1013                 'float',
1014                 1.0 / shaper_input_scale,
1015                 1.0,
1016                 shaper_params,
1017                 cleanup,
1018                 aces_CTL_directory)
1019
1020         shaper_OCIO_transform = {
1021             'type': 'lutFile',
1022             'path': shaper_lut,
1023             'interpolation': 'linear',
1024             'direction': 'inverse'
1025         }
1026
1027         #
1028         # Generate the forward transform
1029         #
1030         cs.from_reference_transforms = []
1031
1032         if 'transformLUT' in odt_values:
1033             # Copy into the lut dir
1034             transform_LUT_file_name = os.path.basename(
1035                 odt_values['transformLUT'])
1036             lut = os.path.join(lut_directory, transform_LUT_file_name)
1037             shutil.copy(odt_values['transformLUT'], lut)
1038
1039             cs.from_reference_transforms.append(shaper_OCIO_transform)
1040             cs.from_reference_transforms.append({
1041                 'type': 'lutFile',
1042                 'path': transform_LUT_file_name,
1043                 'interpolation': 'tetrahedral',
1044                 'direction': 'forward'
1045             })
1046         elif 'transformCTL' in odt_values:
1047             # shaperLut
1048
1049             ctls = [
1050                 shaper_to_ACES_CTL % aces_CTL_directory,
1051                 os.path.join(aces_CTL_directory,
1052                              'rrt',
1053                              'RRT.a1.0.0.ctl'),
1054                 os.path.join(aces_CTL_directory,
1055                              'odt',
1056                              odt_values['transformCTL'])]
1057             lut = '%s.RRT.a1.0.0.%s.spi3d' % (shaper_name, odt_name)
1058
1059             lut = sanitize_path(lut)
1060
1061             generate_3d_LUT_from_CTL(
1062                 os.path.join(lut_directory, lut),
1063                 # shaperLUT,
1064                 ctls,
1065                 lut_resolution_3d,
1066                 'float',
1067                 1.0 / shaper_input_scale,
1068                 1.0,
1069                 shaper_params,
1070                 cleanup,
1071                 aces_CTL_directory)
1072
1073             cs.from_reference_transforms.append(shaper_OCIO_transform)
1074             cs.from_reference_transforms.append({
1075                 'type': 'lutFile',
1076                 'path': lut,
1077                 'interpolation': 'tetrahedral',
1078                 'direction': 'forward'
1079             })
1080
1081         #
1082         # Generate the inverse transform
1083         #
1084         cs.to_reference_transforms = []
1085
1086         if 'transformLUTInverse' in odt_values:
1087             # Copy into the lut dir
1088             transform_LUT_inverse_file_name = os.path.basename(
1089                 odt_values['transformLUTInverse'])
1090             lut = os.path.join(lut_directory, transform_LUT_inverse_file_name)
1091             shutil.copy(odt_values['transformLUTInverse'], lut)
1092
1093             cs.to_reference_transforms.append({
1094                 'type': 'lutFile',
1095                 'path': transform_LUT_inverse_file_name,
1096                 'interpolation': 'tetrahedral',
1097                 'direction': 'forward'
1098             })
1099
1100             shaper_inverse = shaper_OCIO_transform.copy()
1101             shaper_inverse['direction'] = 'forward'
1102             cs.to_reference_transforms.append(shaper_inverse)
1103         elif 'transformCTLInverse' in odt_values:
1104             ctls = [
1105                 os.path.join(aces_CTL_directory,
1106                              'odt',
1107                              odt_values['transformCTLInverse']),
1108                 os.path.join(aces_CTL_directory,
1109                              'rrt',
1110                              'InvRRT.a1.0.0.ctl'),
1111                 shaper_from_ACES_CTL % aces_CTL_directory
1112             ]
1113             lut = 'InvRRT.a1.0.0.%s.%s.spi3d' % (odt_name, shaper_name)
1114
1115             lut = sanitize_path(lut)
1116
1117             generate_3d_LUT_from_CTL(
1118                 os.path.join(lut_directory, lut),
1119                 # None,
1120                 ctls,
1121                 lut_resolution_3d,
1122                 'half',
1123                 1.0,
1124                 shaper_input_scale,
1125                 shaper_params,
1126                 cleanup,
1127                 aces_CTL_directory)
1128
1129             cs.to_reference_transforms.append({
1130                 'type': 'lutFile',
1131                 'path': lut,
1132                 'interpolation': 'tetrahedral',
1133                 'direction': 'forward'
1134             })
1135
1136             shaper_inverse = shaper_OCIO_transform.copy()
1137             shaper_inverse['direction'] = 'forward'
1138             cs.to_reference_transforms.append(shaper_inverse)
1139
1140         return cs
1141
1142     #
1143     # RRT/ODT shaper options
1144     #
1145     shaper_data = {}
1146
1147     # Log 2 shaper
1148     log2_shaper_name = shaper_name
1149     log2_params = {
1150         'middleGrey': 0.18,
1151         'minExposure': -6.0,
1152         'maxExposure': 6.5
1153     }
1154     log2_shaper = create_generic_log(
1155         name=log2_shaper_name,
1156         middle_grey=log2_params['middleGrey'],
1157         min_exposure=log2_params['minExposure'],
1158         max_exposure=log2_params['maxExposure'])
1159     config_data['colorSpaces'].append(log2_shaper)
1160
1161     shaper_input_scale_generic_log2 = 1.0
1162
1163     # Log 2 shaper name and CTL transforms bundled up
1164     log2_shaper_data = [
1165         log2_shaper_name,
1166         os.path.join('%s',
1167                      'utilities',
1168                      'ACESlib.OCIO_shaper_log2_to_lin_param.a1.0.0.ctl'),
1169         os.path.join('%s',
1170                      'utilities',
1171                      'ACESlib.OCIO_shaper_lin_to_log2_param.a1.0.0.ctl'),
1172         shaper_input_scale_generic_log2,
1173         log2_params]
1174
1175     shaper_data[log2_shaper_name] = log2_shaper_data
1176
1177     #
1178     # Shaper that also includes the AP1 primaries
1179     # - Needed for some LUT baking steps
1180     #
1181     log2_shaper_AP1 = create_generic_log(
1182         name=log2_shaper_name,
1183         middle_grey=log2_params['middleGrey'],
1184         min_exposure=log2_params['minExposure'],
1185         max_exposure=log2_params['maxExposure'])
1186     log2_shaper_AP1.name = '%s - AP1' % log2_shaper_AP1.name
1187     # AP1 primaries to AP0 primaries
1188     log2_shaper_AP1.to_reference_transforms.append({
1189         'type': 'matrix',
1190         'matrix': mat44_from_mat33(ACES_AP1_to_AP0),
1191         'direction': 'forward'
1192     })
1193     config_data['colorSpaces'].append(log2_shaper_AP1)
1194
1195     #
1196     # Choose your shaper
1197     #
1198     rrt_shaper_name = log2_shaper_name
1199     rrt_shaper = log2_shaper_data
1200
1201     #
1202     # RRT + ODT Combinations
1203     #
1204     sorted_odts = sorted(odt_info.iteritems(), key=lambda x: x[1])
1205     print(sorted_odts)
1206     for odt in sorted_odts:
1207         (odt_name, odt_values) = odt
1208
1209         # Have to handle ODTs that can generate either legal or full output
1210         if odt_name in ['Academy.Rec2020_100nits_dim.a1.0.0',
1211                         'Academy.Rec709_100nits_dim.a1.0.0',
1212                         'Academy.Rec709_D60sim_100nits_dim.a1.0.0']:
1213             odt_name_legal = '%s - Legal' % odt_values['transformUserName']
1214         else:
1215             odt_name_legal = odt_values['transformUserName']
1216
1217         odt_legal = odt_values.copy()
1218         odt_legal['legalRange'] = 1
1219
1220         cs = create_ACES_RRT_plus_ODT(
1221             odt_name_legal,
1222             odt_legal,
1223             rrt_shaper,
1224             lut_resolution_1d,
1225             lut_resolution_3d,
1226             cleanup)
1227         config_data['colorSpaces'].append(cs)
1228
1229         # Create a display entry using this color space
1230         config_data['displays'][odt_name_legal] = {
1231             'Linear': ACES,
1232             'Log': ACEScc,
1233             'Output Transform': cs}
1234
1235         if odt_name in ['Academy.Rec2020_100nits_dim.a1.0.0',
1236                         'Academy.Rec709_100nits_dim.a1.0.0',
1237                         'Academy.Rec709_D60sim_100nits_dim.a1.0.0']:
1238             print('Generating full range ODT for %s' % odt_name)
1239
1240             odt_name_full = '%s - Full' % odt_values['transformUserName']
1241             odt_full = odt_values.copy()
1242             odt_full['legalRange'] = 0
1243
1244             cs_full = create_ACES_RRT_plus_ODT(
1245                 odt_name_full,
1246                 odt_full,
1247                 rrt_shaper,
1248                 lut_resolution_1d,
1249                 lut_resolution_3d,
1250                 cleanup)
1251             config_data['colorSpaces'].append(cs_full)
1252
1253             # Create a display entry using this color space
1254             config_data['displays'][odt_name_full] = {
1255                 'Linear': ACES,
1256                 'Log': ACEScc,
1257                 'Output Transform': cs_full}
1258
1259     #
1260     # Generic Matrix transform
1261     #
1262     def create_generic_matrix(name='matrix',
1263                               from_reference_values=[],
1264                               to_reference_values=[]):
1265         cs = ColorSpace(name)
1266         cs.description = 'The %s color space' % name
1267         cs.equality_group = name
1268         cs.family = 'Utility'
1269         cs.is_data = False
1270
1271         cs.to_reference_transforms = []
1272         if to_reference_values != []:
1273             for matrix in to_reference_values:
1274                 cs.to_reference_transforms.append({
1275                     'type': 'matrix',
1276                     'matrix': mat44_from_mat33(matrix),
1277                     'direction': 'forward'
1278                 })
1279
1280         cs.from_reference_transforms = []
1281         if from_reference_values != []:
1282             for matrix in from_reference_values:
1283                 cs.from_reference_transforms.append({
1284                     'type': 'matrix',
1285                     'matrix': mat44_from_mat33(matrix),
1286                     'direction': 'forward'
1287                 })
1288
1289         return cs
1290
1291     cs = create_generic_matrix('XYZ', from_reference_values=[ACES_AP0_to_XYZ])
1292     config_data['colorSpaces'].append(cs)
1293
1294     cs = create_generic_matrix(
1295         'Linear - AP1', to_reference_values=[ACES_AP1_to_AP0])
1296     config_data['colorSpaces'].append(cs)
1297
1298     # ACES to Linear, P3D60 primaries
1299     XYZ_to_P3D60 = [2.4027414142, -0.8974841639, -0.3880533700,
1300                     -0.8325796487, 1.7692317536, 0.0237127115,
1301                     0.0388233815, -0.0824996856, 1.0363685997]
1302
1303     cs = create_generic_matrix(
1304         'Linear - P3-D60',
1305         from_reference_values=[ACES_AP0_to_XYZ, XYZ_to_P3D60])
1306     config_data['colorSpaces'].append(cs)
1307
1308     # ACES to Linear, P3D60 primaries
1309     XYZ_to_P3DCI = [2.7253940305, -1.0180030062, -0.4401631952,
1310                     -0.7951680258, 1.6897320548, 0.0226471906,
1311                     0.0412418914, -0.0876390192, 1.1009293786]
1312
1313     cs = create_generic_matrix(
1314         'Linear - P3-DCI',
1315         from_reference_values=[ACES_AP0_to_XYZ, XYZ_to_P3DCI])
1316     config_data['colorSpaces'].append(cs)
1317
1318     # ACES to Linear, Rec 709 primaries
1319     XYZ_to_Rec709 = [3.2409699419, -1.5373831776, -0.4986107603,
1320                      -0.9692436363, 1.8759675015, 0.0415550574,
1321                      0.0556300797, -0.2039769589, 1.0569715142]
1322
1323     cs = create_generic_matrix(
1324         'Linear - Rec.709',
1325         from_reference_values=[ACES_AP0_to_XYZ, XYZ_to_Rec709])
1326     config_data['colorSpaces'].append(cs)
1327
1328     # ACES to Linear, Rec 2020 primaries
1329     XYZ_to_Rec2020 = [1.7166511880, -0.3556707838, -0.2533662814,
1330                       -0.6666843518, 1.6164812366, 0.0157685458,
1331                       0.0176398574, -0.0427706133, 0.9421031212]
1332
1333     cs = create_generic_matrix(
1334         'Linear - Rec.2020',
1335         from_reference_values=[ACES_AP0_to_XYZ, XYZ_to_Rec2020])
1336     config_data['colorSpaces'].append(cs)
1337
1338     print('generateLUTs - end')
1339     return config_data
1340
1341
1342 def generate_baked_LUTs(odt_info,
1343                         shaper_name,
1344                         baked_directory,
1345                         config_path,
1346                         lut_resolution_1d,
1347                         lut_resolution_3d,
1348                         lut_resolution_shaper=1024):
1349     """
1350     Object description.
1351
1352     Parameters
1353     ----------
1354     parameter : type
1355         Parameter description.
1356
1357     Returns
1358     -------
1359     type
1360          Return value description.
1361     """
1362
1363     # Add the legal and full variations into this list
1364     odt_info_C = dict(odt_info)
1365     for odt_CTL_name, odt_values in odt_info.iteritems():
1366         if odt_CTL_name in ['Academy.Rec2020_100nits_dim.a1.0.0',
1367                             'Academy.Rec709_100nits_dim.a1.0.0',
1368                             'Academy.Rec709_D60sim_100nits_dim.a1.0.0']:
1369             odt_name = odt_values['transformUserName']
1370
1371             odt_values_legal = dict(odt_values)
1372             odt_values_legal['transformUserName'] = '%s - Legal' % odt_name
1373             odt_info_C['%s - Legal' % odt_CTL_name] = odt_values_legal
1374
1375             odt_values_full = dict(odt_values)
1376             odt_values_full['transformUserName'] = '%s - Full' % odt_name
1377             odt_info_C['%s - Full' % odt_CTL_name] = odt_values_full
1378
1379             del (odt_info_C[odt_CTL_name])
1380
1381     for odt_CTL_name, odt_values in odt_info_C.iteritems():
1382         odt_prefix = odt_values['transformUserNamePrefix']
1383         odt_name = odt_values['transformUserName']
1384
1385         # For Photoshop
1386         for input_space in ['ACEScc', 'ACESproxy']:
1387             args = ['--iconfig', config_path,
1388                     '-v',
1389                     '--inputspace', input_space]
1390             args += ['--outputspace', '%s' % odt_name]
1391             args += ['--description',
1392                      '%s - %s for %s data' % (odt_prefix,
1393                                               odt_name,
1394                                               input_space)]
1395             args += ['--shaperspace', shaper_name,
1396                      '--shapersize', str(lut_resolution_shaper)]
1397             args += ['--cubesize', str(lut_resolution_3d)]
1398             args += ['--format',
1399                      'icc',
1400                      os.path.join(baked_directory,
1401                                   'photoshop',
1402                                   '%s for %s.icc' % (odt_name, input_space))]
1403
1404             bake_LUT = Process(description='bake a LUT',
1405                                cmd='ociobakelut',
1406                                args=args)
1407             bake_LUT.execute()
1408
1409         # For Flame, Lustre
1410         for input_space in ['ACEScc', 'ACESproxy']:
1411             args = ['--iconfig', config_path,
1412                     '-v',
1413                     '--inputspace', input_space]
1414             args += ['--outputspace', '%s' % odt_name]
1415             args += ['--description',
1416                      '%s - %s for %s data' % (
1417                          odt_prefix, odt_name, input_space)]
1418             args += ['--shaperspace', shaper_name,
1419                      '--shapersize', str(lut_resolution_shaper)]
1420             args += ['--cubesize', str(lut_resolution_3d)]
1421
1422             fargs = ['--format',
1423                      'flame',
1424                      os.path.join(
1425                          baked_directory,
1426                          'flame',
1427                          '%s for %s Flame.3dl' % (odt_name, input_space))]
1428             bake_LUT = Process(description='bake a LUT',
1429                                cmd='ociobakelut',
1430                                args=(args + fargs))
1431             bake_LUT.execute()
1432
1433             largs = ['--format',
1434                      'lustre',
1435                      os.path.join(
1436                          baked_directory,
1437                          'lustre',
1438                          '%s for %s Lustre.3dl' % (odt_name, input_space))]
1439             bake_LUT = Process(description='bake a LUT',
1440                                cmd='ociobakelut',
1441                                args=(args + largs))
1442             bake_LUT.execute()
1443
1444         # For Maya, Houdini
1445         for input_space in ['ACEScg', 'ACES2065-1']:
1446             args = ['--iconfig', config_path,
1447                     '-v',
1448                     '--inputspace', input_space]
1449             args += ['--outputspace', '%s' % odt_name]
1450             args += ['--description',
1451                      '%s - %s for %s data' % (
1452                          odt_prefix, odt_name, input_space)]
1453             if input_space == 'ACEScg':
1454                 lin_shaper_name = '%s - AP1' % shaper_name
1455             else:
1456                 lin_shaper_name = shaper_name
1457             args += ['--shaperspace', lin_shaper_name,
1458                      '--shapersize', str(lut_resolution_shaper)]
1459
1460             args += ['--cubesize', str(lut_resolution_3d)]
1461
1462             margs = ['--format',
1463                      'cinespace',
1464                      os.path.join(
1465                          baked_directory,
1466                          'maya',
1467                          '%s for %s Maya.csp' % (odt_name, input_space))]
1468             bake_LUT = Process(description='bake a LUT',
1469                                cmd='ociobakelut',
1470                                args=(args + margs))
1471             bake_LUT.execute()
1472
1473             hargs = ['--format',
1474                      'houdini',
1475                      os.path.join(
1476                          baked_directory,
1477                          'houdini',
1478                          '%s for %s Houdini.lut' % (odt_name, input_space))]
1479             bake_LUT = Process(description='bake a LUT',
1480                                cmd='ociobakelut',
1481                                args=(args + hargs))
1482             bake_LUT.execute()
1483
1484
1485 def create_config_dir(config_directory, bake_secondary_LUTs):
1486     """
1487     Object description.
1488
1489     Parameters
1490     ----------
1491     parameter : type
1492         Parameter description.
1493
1494     Returns
1495     -------
1496     type
1497          Return value description.
1498     """
1499
1500     dirs = [config_directory, os.path.join(config_directory, 'luts')]
1501     if bake_secondary_LUTs:
1502         dirs.extend([os.path.join(config_directory, 'baked'),
1503                      os.path.join(config_directory, 'baked', 'flame'),
1504                      os.path.join(config_directory, 'baked', 'photoshop'),
1505                      os.path.join(config_directory, 'baked', 'houdini'),
1506                      os.path.join(config_directory, 'baked', 'lustre'),
1507                      os.path.join(config_directory, 'baked', 'maya')])
1508
1509     for d in dirs:
1510         not os.path.exists(d) and os.mkdir(d)
1511
1512
1513 def get_transform_info(ctl_transform):
1514     """
1515     Object description.
1516
1517     Parameters
1518     ----------
1519     parameter : type
1520         Parameter description.
1521
1522     Returns
1523     -------
1524     type
1525          Return value description.
1526     """
1527
1528     # TODO: Use *with* statement.
1529     fp = open(ctl_transform, 'rb')
1530
1531     # Read lines
1532     lines = fp.readlines()
1533
1534     # Grab transform ID and User Name
1535     transform_ID = lines[1][3:].split('<')[1].split('>')[1].strip()
1536     # print(transformID)
1537     transform_user_name = '-'.join(
1538         lines[2][3:].split('<')[1].split('>')[1].split('-')[1:]).strip()
1539     transform_user_name_prefix = (
1540         lines[2][3:].split('<')[1].split('>')[1].split('-')[0].strip())
1541     # print(transformUserName)
1542     fp.close()
1543
1544     return transform_ID, transform_user_name, transform_user_name_prefix
1545
1546
1547 def get_ODT_info(aces_CTL_directory):
1548     """
1549     Object description.
1550
1551     For versions after WGR9.
1552
1553     Parameters
1554     ----------
1555     parameter : type
1556         Parameter description.
1557
1558     Returns
1559     -------
1560     type
1561          Return value description.
1562     """
1563
1564     # TODO: Investigate usage of *files_walker* definition here.
1565     # Credit to Alex Fry for the original approach here
1566     odt_dir = os.path.join(aces_CTL_directory, 'odt')
1567     all_odt = []
1568     for dir_name, subdir_list, file_list in os.walk(odt_dir):
1569         for fname in file_list:
1570             all_odt.append((os.path.join(dir_name, fname)))
1571
1572     odt_CTLs = [x for x in all_odt if
1573                 ('InvODT' not in x) and (os.path.split(x)[-1][0] != '.')]
1574
1575     # print odtCTLs
1576
1577     odts = {}
1578
1579     for odt_CTL in odt_CTLs:
1580         odt_tokens = os.path.split(odt_CTL)
1581         # print(odtTokens)
1582
1583         # Handle nested directories
1584         odt_path_tokens = os.path.split(odt_tokens[-2])
1585         odt_dir = odt_path_tokens[-1]
1586         while odt_path_tokens[-2][-3:] != 'odt':
1587             odt_path_tokens = os.path.split(odt_path_tokens[-2])
1588             odt_dir = os.path.join(odt_path_tokens[-1], odt_dir)
1589
1590         # Build full name
1591         # print('odtDir : %s' % odtDir)
1592         transform_CTL = odt_tokens[-1]
1593         # print(transformCTL)
1594         odt_name = string.join(transform_CTL.split('.')[1:-1], '.')
1595         # print(odtName)
1596
1597         # Find id, user name and user name prefix
1598         (transform_ID,
1599          transform_user_name,
1600          transform_user_name_prefix) = get_transform_info(
1601             os.path.join(aces_CTL_directory, 'odt', odt_dir, transform_CTL))
1602
1603         # Find inverse
1604         transform_CTL_inverse = 'InvODT.%s.ctl' % odt_name
1605         if not os.path.exists(
1606                 os.path.join(odt_tokens[-2], transform_CTL_inverse)):
1607             transform_CTL_inverse = None
1608         # print(transformCTLInverse)
1609
1610         # Add to list of ODTs
1611         odts[odt_name] = {}
1612         odts[odt_name]['transformCTL'] = os.path.join(odt_dir, transform_CTL)
1613         if transform_CTL_inverse != None:
1614             odts[odt_name]['transformCTLInverse'] = os.path.join(
1615                 odt_dir, transform_CTL_inverse)
1616
1617         odts[odt_name]['transformID'] = transform_ID
1618         odts[odt_name]['transformUserNamePrefix'] = transform_user_name_prefix
1619         odts[odt_name]['transformUserName'] = transform_user_name
1620
1621         print('ODT : %s' % odt_name)
1622         print('\tTransform ID               : %s' % transform_ID)
1623         print('\tTransform User Name Prefix : %s' % transform_user_name_prefix)
1624         print('\tTransform User Name        : %s' % transform_user_name)
1625         print('\tForward ctl                : %s' % (
1626             odts[odt_name]['transformCTL']))
1627         if 'transformCTLInverse' in odts[odt_name]:
1628             print('\tInverse ctl                : %s' % (
1629                 odts[odt_name]['transformCTLInverse']))
1630         else:
1631             print('\tInverse ctl                : %s' % 'None')
1632
1633     print('\n')
1634
1635     return odts
1636
1637
1638 def get_LMT_info(aces_CTL_directory):
1639     """
1640     Object description.
1641
1642     For versions after WGR9.
1643
1644     Parameters
1645     ----------
1646     parameter : type
1647         Parameter description.
1648
1649     Returns
1650     -------
1651     type
1652          Return value description.
1653     """
1654
1655     # TODO: Investigate refactoring with previous definition.
1656
1657     # Credit to Alex Fry for the original approach here
1658     lmt_dir = os.path.join(aces_CTL_directory, 'lmt')
1659     all_lmt = []
1660     for dir_name, subdir_list, file_list in os.walk(lmt_dir):
1661         for fname in file_list:
1662             all_lmt.append((os.path.join(dir_name, fname)))
1663
1664     lmt_CTLs = [x for x in all_lmt if
1665                 ('InvLMT' not in x) and ('README' not in x) and (
1666                     os.path.split(x)[-1][0] != '.')]
1667
1668     # print lmtCTLs
1669
1670     lmts = {}
1671
1672     for lmt_CTL in lmt_CTLs:
1673         lmt_tokens = os.path.split(lmt_CTL)
1674         # print(lmtTokens)
1675
1676         # Handle nested directories
1677         lmt_path_tokens = os.path.split(lmt_tokens[-2])
1678         lmt_dir = lmt_path_tokens[-1]
1679         while lmt_path_tokens[-2][-3:] != 'ctl':
1680             lmt_path_tokens = os.path.split(lmt_path_tokens[-2])
1681             lmt_dir = os.path.join(lmt_path_tokens[-1], lmt_dir)
1682
1683         # Build full name
1684         # print('lmtDir : %s' % lmtDir)
1685         transform_CTL = lmt_tokens[-1]
1686         # print(transformCTL)
1687         lmt_name = string.join(transform_CTL.split('.')[1:-1], '.')
1688         # print(lmtName)
1689
1690         # Find id, user name and user name prefix
1691         (transform_ID,
1692          transform_user_name,
1693          transform_user_name_prefix) = get_transform_info(
1694             os.path.join(aces_CTL_directory, lmt_dir, transform_CTL))
1695
1696         # Find inverse
1697         transform_CTL_inverse = 'InvLMT.%s.ctl' % lmt_name
1698         if not os.path.exists(
1699                 os.path.join(lmt_tokens[-2], transform_CTL_inverse)):
1700             transform_CTL_inverse = None
1701         # print(transformCTLInverse)
1702
1703         # Add to list of LMTs
1704         lmts[lmt_name] = {}
1705         lmts[lmt_name]['transformCTL'] = os.path.join(lmt_dir, transform_CTL)
1706         if transform_CTL_inverse != None:
1707             # TODO: Check unresolved *odt_name* referemce.
1708             lmts[odt_name]['transformCTLInverse'] = os.path.join(
1709                 lmt_dir, transform_CTL_inverse)
1710
1711         lmts[lmt_name]['transformID'] = transform_ID
1712         lmts[lmt_name]['transformUserNamePrefix'] = transform_user_name_prefix
1713         lmts[lmt_name]['transformUserName'] = transform_user_name
1714
1715         print('LMT : %s' % lmt_name)
1716         print('\tTransform ID               : %s' % transform_ID)
1717         print('\tTransform User Name Prefix : %s' % transform_user_name_prefix)
1718         print('\tTransform User Name        : %s' % transform_user_name)
1719         print('\t Forward ctl : %s' % lmts[lmt_name]['transformCTL'])
1720         if 'transformCTLInverse' in lmts[lmt_name]:
1721             print('\t Inverse ctl : %s' % (
1722                 lmts[lmt_name]['transformCTLInverse']))
1723         else:
1724             print('\t Inverse ctl : %s' % 'None')
1725
1726     print('\n')
1727
1728     return lmts
1729
1730
1731 def create_ACES_config(aces_CTL_directory,
1732                        config_directory,
1733                        lut_resolution_1d=4096,
1734                        lut_resolution_3d=64,
1735                        bake_secondary_LUTs=True,
1736                        cleanup=True):
1737     """
1738     Creates the ACES configuration.
1739
1740     Parameters
1741     ----------
1742     parameter : type
1743         Parameter description.
1744
1745     Returns
1746     -------
1747     type
1748          Return value description.
1749     """
1750
1751     # Get ODT names and CTL paths
1752     odt_info = get_ODT_info(aces_CTL_directory)
1753
1754     # Get ODT names and CTL paths
1755     lmt_info = get_LMT_info(aces_CTL_directory)
1756
1757     # Create config dir
1758     create_config_dir(config_directory, bake_secondary_LUTs)
1759
1760     # Generate config data and LUTs for different transforms
1761     lut_directory = os.path.join(config_directory, 'luts')
1762     shaper_name = 'Output Shaper'
1763     config_data = generate_LUTs(odt_info,
1764                                 lmt_info,
1765                                 shaper_name,
1766                                 aces_CTL_directory,
1767                                 lut_directory,
1768                                 lut_resolution_1d,
1769                                 lut_resolution_3d,
1770                                 cleanup)
1771
1772     # Create the config using the generated LUTs
1773     print('Creating generic config')
1774     config = create_config(config_data)
1775     print('\n\n\n')
1776
1777     # Write the config to disk
1778     write_config(config,
1779                  os.path.join(config_directory, 'config.ocio'))
1780
1781     # Create a config that will work well with Nuke using the previously
1782     # generated LUTs.
1783     print('Creating Nuke-specific config')
1784     nuke_config = create_config(config_data, nuke=True)
1785     print('\n\n\n')
1786
1787     # Write the config to disk
1788     write_config(nuke_config,
1789                  os.path.join(config_directory, 'nuke_config.ocio'))
1790
1791     # Bake secondary LUTs using the config
1792     if bake_secondary_LUTs:
1793         generate_baked_LUTs(odt_info,
1794                             shaper_name,
1795                             os.path.join(config_directory, 'baked'),
1796                             os.path.join(config_directory, 'config.ocio'),
1797                             lut_resolution_1d,
1798                             lut_resolution_3d,
1799                             lut_resolution_1d)
1800
1801     return True
1802
1803
1804 def main():
1805     """
1806     Object description.
1807
1808     Parameters
1809     ----------
1810     parameter : type
1811         Parameter description.
1812
1813     Returns
1814     -------
1815     type
1816          Return value description.
1817     """
1818
1819     import optparse
1820
1821     p = optparse.OptionParser(description='An OCIO config generation script',
1822                               prog='createACESConfig',
1823                               version='createACESConfig 0.1',
1824                               usage='%prog [options]')
1825     p.add_option('--acesCTLDir', '-a', default=os.environ.get(
1826         'ACES_OCIO_CTL_DIRECTORY', None))
1827     p.add_option('--configDir', '-c', default=os.environ.get(
1828         'ACES_OCIO_CONFIGURATION_DIRECTORY', None))
1829     p.add_option('--lutResolution1d', default=4096)
1830     p.add_option('--lutResolution3d', default=64)
1831     p.add_option('--dontBakeSecondaryLUTs', action='store_true')
1832     p.add_option('--keepTempImages', action='store_true')
1833
1834     options, arguments = p.parse_args()
1835
1836     #
1837     # Get options
1838     #
1839     aces_CTL_directory = options.acesCTLDir
1840     config_directory = options.configDir
1841     lut_resolution_1d = int(options.lutResolution1d)
1842     lut_resolution_3d = int(options.lutResolution3d)
1843     bake_secondary_LUTs = not (options.dontBakeSecondaryLUTs)
1844     cleanup_temp_images = not (options.keepTempImages)
1845
1846     try:
1847         args_start = sys.argv.index('--') + 1
1848         args = sys.argv[args_start:]
1849     except:
1850         args_start = len(sys.argv) + 1
1851         args = []
1852
1853     print('command line : \n%s\n' % ' '.join(sys.argv))
1854
1855     # TODO: Use assertion and mention environment variables.
1856     if not aces_CTL_directory:
1857         print('process: No ACES CTL directory specified')
1858         return
1859     if not config_directory:
1860         print('process: No configuration directory specified')
1861         return
1862     #
1863     # Generate the configuration
1864     #
1865     return create_ACES_config(aces_CTL_directory,
1866                               config_directory,
1867                               lut_resolution_1d,
1868                               lut_resolution_3d,
1869                               bake_secondary_LUTs,
1870                               cleanup_temp_images)
1871
1872
1873 if __name__ == '__main__':
1874     main()