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