Improve paths handling on remaining occurrences.
[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
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         # Remove spaces and parentheses
458         lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
459
460         generate_1d_LUT_from_CTL(
461             os.path.join(lut_directory, lut),
462             ctls,
463             lut_resolution_1d,
464             'float',
465             input_scale,
466             1.0,
467             {},
468             cleanup,
469             aces_CTL_directory,
470             min_value,
471             max_value)
472
473         cs.to_reference_transforms = []
474         cs.to_reference_transforms.append({
475             'type': 'lutFile',
476             'path': lut,
477             'interpolation': 'linear',
478             'direction': 'forward'
479         })
480
481         # AP1 primaries to AP0 primaries
482         cs.to_reference_transforms.append({
483             'type': 'matrix',
484             'matrix': mat44_from_mat33(ACES_AP1_to_AP0),
485             'direction': 'forward'
486         })
487
488         cs.from_reference_transforms = []
489         return cs
490
491     ACEScc = create_ACEScc()
492     config_data['colorSpaces'].append(ACEScc)
493
494     #
495     # ACESproxy
496     #
497     def create_ACESproxy(name='ACESproxy'):
498         cs = ColorSpace(name)
499         cs.description = 'The %s color space' % name
500         cs.equality_group = ''
501         cs.family = 'ACES'
502         cs.is_data = False
503
504         ctls = [
505             os.path.join(aces_CTL_directory,
506                          'ACESproxy',
507                          'ACEScsc.ACESproxy10i_to_ACES.a1.0.0.ctl'),
508             # This transform gets back to the AP1 primaries
509             # Useful as the 1d LUT is only covering the transfer function
510             # The primaries switch is covered by the matrix below
511             os.path.join(aces_CTL_directory,
512                          'ACEScg',
513                          'ACEScsc.ACES_to_ACEScg.a1.0.0.ctl')]
514         lut = '%s_to_aces.spi1d' % name
515
516         # Remove spaces and parentheses
517         lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
518
519         generate_1d_LUT_from_CTL(
520             os.path.join(lut_directory, lut),
521             ctls,
522             lut_resolution_1d,
523             'uint16',
524             64.0,
525             1.0,
526             {},
527             cleanup,
528             aces_CTL_directory)
529
530         cs.to_reference_transforms = []
531         cs.to_reference_transforms.append({
532             'type': 'lutFile',
533             'path': lut,
534             'interpolation': 'linear',
535             'direction': 'forward'
536         })
537
538         # AP1 primaries to AP0 primaries
539         cs.to_reference_transforms.append({
540             'type': 'matrix',
541             'matrix': mat44_from_mat33(ACES_AP1_to_AP0),
542             'direction': 'forward'
543         })
544
545         cs.from_reference_transforms = []
546         return cs
547
548     ACESproxy = create_ACESproxy()
549     config_data['colorSpaces'].append(ACESproxy)
550
551     #
552     # ACEScg
553     #
554     def create_ACEScg(name='ACEScg'):
555         cs = ColorSpace(name)
556         cs.description = 'The %s color space' % name
557         cs.equality_group = ''
558         cs.family = 'ACES'
559         cs.is_data = False
560
561         cs.to_reference_transforms = []
562
563         # AP1 primaries to AP0 primaries
564         cs.to_reference_transforms.append({
565             'type': 'matrix',
566             'matrix': mat44_from_mat33(ACES_AP1_to_AP0),
567             'direction': 'forward'
568         })
569
570         cs.from_reference_transforms = []
571         return cs
572
573     ACEScg = create_ACEScg()
574     config_data['colorSpaces'].append(ACEScg)
575
576     #
577     # ADX
578     #
579     def create_ADX(bit_depth=10, name='ADX'):
580         name = '%s%s' % (name, bit_depth)
581         cs = ColorSpace(name)
582         cs.description = '%s color space - used for film scans' % name
583         cs.equality_group = ''
584         cs.family = 'ADX'
585         cs.is_data = False
586
587         if bit_depth == 10:
588             cs.bit_depth = bit_depth = ocio.Constants.BIT_DEPTH_UINT10
589             adx_to_cdd = [1023.0 / 500.0, 0.0, 0.0, 0.0,
590                           0.0, 1023.0 / 500.0, 0.0, 0.0,
591                           0.0, 0.0, 1023.0 / 500.0, 0.0,
592                           0.0, 0.0, 0.0, 1.0]
593             offset = [-95.0 / 500.0, -95.0 / 500.0, -95.0 / 500.0, 0.0]
594         elif bit_depth == 16:
595             cs.bit_depth = bit_depth = ocio.Constants.BIT_DEPTH_UINT16
596             adx_to_cdd = [65535.0 / 8000.0, 0.0, 0.0, 0.0,
597                           0.0, 65535.0 / 8000.0, 0.0, 0.0,
598                           0.0, 0.0, 65535.0 / 8000.0, 0.0,
599                           0.0, 0.0, 0.0, 1.0]
600             offset = [-1520.0 / 8000.0, -1520.0 / 8000.0, -1520.0 / 8000.0,
601                       0.0]
602
603         cs.to_reference_transforms = []
604
605         # Convert from ADX to Channel-Dependent Density
606         cs.to_reference_transforms.append({
607             'type': 'matrix',
608             'matrix': adx_to_cdd,
609             'offset': offset,
610             'direction': 'forward'
611         })
612
613         # Convert from Channel-Dependent Density to Channel-Independent Density
614         cs.to_reference_transforms.append({
615             'type': 'matrix',
616             'matrix': [0.75573, 0.22197, 0.02230, 0,
617                        0.05901, 0.96928, -0.02829, 0,
618                        0.16134, 0.07406, 0.76460, 0,
619                        0.0, 0.0, 0.0, 1.0],
620             'direction': 'forward'
621         })
622
623         # Copied from Alex Fry's adx_cid_to_rle.py
624         def create_CID_to_RLE_LUT():
625             def interpolate_1D(x, xp, fp):
626                 return numpy.interp(x, xp, fp)
627
628             LUT_1D_xp = [-0.190000000000000,
629                          0.010000000000000,
630                          0.028000000000000,
631                          0.054000000000000,
632                          0.095000000000000,
633                          0.145000000000000,
634                          0.220000000000000,
635                          0.300000000000000,
636                          0.400000000000000,
637                          0.500000000000000,
638                          0.600000000000000]
639
640             LUT_1D_fp = [-6.000000000000000,
641                          -2.721718645000000,
642                          -2.521718645000000,
643                          -2.321718645000000,
644                          -2.121718645000000,
645                          -1.921718645000000,
646                          -1.721718645000000,
647                          -1.521718645000000,
648                          -1.321718645000000,
649                          -1.121718645000000,
650                          -0.926545676714876]
651
652             REF_PT = ((7120.0 - 1520.0) / 8000.0 * (100.0 / 55.0) -
653                       math.log(0.18, 10.0))
654
655             def cid_to_rle(x):
656                 if x <= 0.6:
657                     return interpolate_1D(x, LUT_1D_xp, LUT_1D_fp)
658                 return (100.0 / 55.0) * x - REF_PT
659
660             def fit(value, from_min, from_max, to_min, to_max):
661                 if from_min == from_max:
662                     raise ValueError('from_min == from_max')
663                 return (value - from_min) / (from_max - from_min) * (
664                     to_max - to_min) + to_min
665
666             NUM_SAMPLES = 2 ** 12
667             RANGE = (-0.19, 3.0)
668             data = []
669             for i in xrange(NUM_SAMPLES):
670                 x = i / (NUM_SAMPLES - 1.0)
671                 x = fit(x, 0.0, 1.0, RANGE[0], RANGE[1])
672                 data.append(cid_to_rle(x))
673
674             lut = 'ADX_CID_to_RLE.spi1d'
675             write_SPI_1d(os.path.join(lut_directory, lut),
676                          RANGE[0],
677                          RANGE[1],
678                          data,
679                          NUM_SAMPLES, 1)
680
681             return lut
682
683         # Convert Channel Independent Density values to Relative Log Exposure
684         # values.
685         lut = create_CID_to_RLE_LUT()
686         cs.to_reference_transforms.append({
687             'type': 'lutFile',
688             'path': lut,
689             'interpolation': 'linear',
690             'direction': 'forward'
691         })
692
693         # Convert Relative Log Exposure values to Relative Exposure values
694         cs.to_reference_transforms.append({
695             'type': 'log',
696             'base': 10,
697             'direction': 'inverse'
698         })
699
700         # Convert Relative Exposure values to ACES values
701         cs.to_reference_transforms.append({
702             'type': 'matrix',
703             'matrix': [0.72286, 0.12630, 0.15084, 0,
704                        0.11923, 0.76418, 0.11659, 0,
705                        0.01427, 0.08213, 0.90359, 0,
706                        0.0, 0.0, 0.0, 1.0],
707             'direction': 'forward'
708         })
709
710         cs.from_reference_transforms = []
711         return cs
712
713     ADX10 = create_ADX(bit_depth=10)
714     config_data['colorSpaces'].append(ADX10)
715
716     ADX16 = create_ADX(bit_depth=16)
717     config_data['colorSpaces'].append(ADX16)
718
719     #
720     # Camera Input Transforms
721     #
722
723     # RED color spaces to ACES
724     red_colorspaces = red.create_colorspaces(lut_directory, lut_resolution_1d)
725     for cs in red_colorspaces:
726         config_data['colorSpaces'].append(cs)
727
728     # Canon-Log to ACES
729     canon_colorspaces = canon.create_colorspaces(lut_directory,
730                                                  lut_resolution_1d)
731     for cs in canon_colorspaces:
732         config_data['colorSpaces'].append(cs)
733
734     # S-Log to ACES
735     sony_colorSpaces = sony.create_colorspaces(lut_directory,
736                                                lut_resolution_1d)
737     for cs in sony_colorSpaces:
738         config_data['colorSpaces'].append(cs)
739
740     # Log-C to ACES
741     arri_colorSpaces = arri.create_colorspaces(lut_directory,
742                                                lut_resolution_1d)
743     for cs in arri_colorSpaces:
744         config_data['colorSpaces'].append(cs)
745
746     #
747     # Generic log transform
748     #
749     def create_generic_log(name='log',
750                            min_value=0.0,
751                            max_value=1.0,
752                            input_scale=1.0,
753                            middle_grey=0.18,
754                            min_exposure=-6.0,
755                            max_exposure=6.5,
756                            lut_resolution_1d=lut_resolution_1d):
757         cs = ColorSpace(name)
758         cs.description = 'The %s color space' % name
759         cs.equality_group = name
760         cs.family = 'Utility'
761         cs.is_data = False
762
763         ctls = [
764             os.path.join(aces_CTL_directory,
765                          'utilities',
766                          'ACESlib.OCIO_shaper_log2_to_lin_param.a1.0.0.ctl')]
767         lut = '%s_to_aces.spi1d' % name
768
769         # Remove spaces and parentheses
770         lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
771
772         generate_1d_LUT_from_CTL(
773             os.path.join(lut_directory, lut),
774             ctls,
775             lut_resolution_1d,
776             'float',
777             input_scale,
778             1.0,
779             {
780                 'middleGrey': middle_grey,
781                 'minExposure': min_exposure,
782                 'maxExposure': max_exposure
783             },
784             cleanup,
785             aces_CTL_directory,
786             min_value,
787             max_value)
788
789         cs.to_reference_transforms = []
790         cs.to_reference_transforms.append({
791             'type': 'lutFile',
792             'path': lut,
793             'interpolation': 'linear',
794             'direction': 'forward'
795         })
796
797         cs.from_reference_transforms = []
798         return cs
799
800     #
801     # ACES LMTs
802     #
803     def create_ACES_LMT(lmt_name,
804                         lmt_values,
805                         shaper_info,
806                         lut_resolution_1d=1024,
807                         lut_resolution_3d=64,
808                         cleanup=True):
809         cs = ColorSpace('%s' % lmt_name)
810         cs.description = 'The ACES Look Transform: %s' % lmt_name
811         cs.equality_group = ''
812         cs.family = 'Look'
813         cs.is_data = False
814
815         pprint.pprint(lmt_values)
816
817         #
818         # Generate the shaper transform
819         #
820         (shaper_name,
821          shaper_to_ACES_CTL,
822          shaper_from_ACES_CTL,
823          shaper_input_scale,
824          shaper_params) = shaper_info
825
826         shaper_lut = '%s_to_aces.spi1d' % shaper_name
827         if (not os.path.exists(os.path.join(lut_directory, shaper_lut))):
828             ctls = [shaper_to_ACES_CTL % aces_CTL_directory]
829
830             # Remove spaces and parentheses
831             shaper_lut = shaper_lut.replace(
832                 ' ', '_').replace(')', '_').replace('(', '_')
833
834             generate_1d_LUT_from_CTL(
835                 os.path.join(lut_directory, shaper_lut),
836                 ctls,
837                 lut_resolution_1d,
838                 'float',
839                 1.0 / shaper_input_scale,
840                 1.0,
841                 shaper_params,
842                 cleanup,
843                 aces_CTL_directory)
844
845         shaper_OCIO_transform = {
846             'type': 'lutFile',
847             'path': shaper_lut,
848             'interpolation': 'linear',
849             'direction': 'inverse'
850         }
851
852         #
853         # Generate the forward transform
854         #
855         cs.from_reference_transforms = []
856
857         if 'transformCTL' in lmt_values:
858             ctls = [
859                 shaper_to_ACES_CTL % aces_CTL_directory,
860                 os.path.join(aces_CTL_directory, lmt_values['transformCTL'])]
861             lut = '%s.%s.spi3d' % (shaper_name, lmt_name)
862
863             # Remove spaces and parentheses
864             lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
865
866             generate_3d_LUT_from_CTL(
867                 os.path.join(lut_directory, lut),
868                 ctls,
869                 lut_resolution_3d,
870                 'float',
871                 1.0 / shaper_input_scale,
872                 1.0,
873                 shaper_params,
874                 cleanup,
875                 aces_CTL_directory)
876
877             cs.from_reference_transforms.append(shaper_OCIO_transform)
878             cs.from_reference_transforms.append({
879                 'type': 'lutFile',
880                 'path': lut,
881                 'interpolation': 'tetrahedral',
882                 'direction': 'forward'
883             })
884
885         #
886         # Generate the inverse transform
887         #
888         cs.to_reference_transforms = []
889
890         if 'transformCTLInverse' in lmt_values:
891             ctls = [
892                 os.path.join(aces_CTL_directory,
893                              odt_values['transformCTLInverse']),
894                 shaper_from_ACES_CTL % aces_CTL_directory
895             ]
896             lut = 'Inverse.%s.%s.spi3d' % (odt_name, shaper_name)
897
898             # Remove spaces and parentheses
899             lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
900
901             generate_3d_LUT_from_CTL(
902                 os.path.join(lut_directory, lut),
903                 ctls,
904                 lut_resolution_3d,
905                 'half',
906                 1.0,
907                 shaper_input_scale,
908                 shaper_params,
909                 cleanup,
910                 aces_CTL_directory)
911
912             cs.to_reference_transforms.append({
913                 'type': 'lutFile',
914                 'path': lut,
915                 'interpolation': 'tetrahedral',
916                 'direction': 'forward'
917             })
918
919             shaper_inverse = shaper_OCIO_transform.copy()
920             shaper_inverse['direction'] = 'forward'
921             cs.to_reference_transforms.append(shaper_inverse)
922
923         return cs
924
925     #
926     # LMT Shaper
927     #
928
929     lmt_lut_resolution_1d = max(4096, lut_resolution_1d)
930     lmt_lut_resolution_3d = max(65, lut_resolution_3d)
931
932     # Log 2 shaper
933     lmt_shaper_name = 'LMT Shaper'
934     lmt_params = {
935         'middleGrey': 0.18,
936         'minExposure': -10.0,
937         'maxExposure': 6.5
938     }
939     lmt_shaper = create_generic_log(name=lmt_shaper_name,
940                                     middle_grey=lmt_params['middleGrey'],
941                                     min_exposure=lmt_params['minExposure'],
942                                     max_exposure=lmt_params['maxExposure'],
943                                     lut_resolution_1d=lmt_lut_resolution_1d)
944     config_data['colorSpaces'].append(lmt_shaper)
945
946     shaper_input_scale_generic_log2 = 1.0
947
948     # Log 2 shaper name and CTL transforms bundled up
949     lmt_shaper_data = [
950         lmt_shaper_name,
951         os.path.join('%s',
952                      'utilities',
953                      'ACESlib.OCIO_shaper_log2_to_lin_param.a1.0.0.ctl'),
954         os.path.join('%s',
955                      'utilities',
956                      'ACESlib.OCIO_shaper_lin_to_log2_param.a1.0.0.ctl'),
957         shaper_input_scale_generic_log2,
958         lmt_params]
959
960     sorted_LMTs = sorted(lmt_info.iteritems(), key=lambda x: x[1])
961     print(sorted_LMTs)
962     for lmt in sorted_LMTs:
963         (lmt_name, lmt_values) = lmt
964         cs = create_ACES_LMT(
965             lmt_values['transformUserName'],
966             lmt_values,
967             lmt_shaper_data,
968             lmt_lut_resolution_1d,
969             lmt_lut_resolution_3d,
970             cleanup)
971         config_data['colorSpaces'].append(cs)
972
973     #
974     # ACES RRT with the supplied ODT
975     #
976     def create_ACES_RRT_plus_ODT(odt_name,
977                                  odt_values,
978                                  shaper_info,
979                                  lut_resolution_1d=1024,
980                                  lut_resolution_3d=64,
981                                  cleanup=True):
982         cs = ColorSpace('%s' % odt_name)
983         cs.description = '%s - %s Output Transform' % (
984             odt_values['transformUserNamePrefix'], odt_name)
985         cs.equality_group = ''
986         cs.family = 'Output'
987         cs.is_data = False
988
989         pprint.pprint(odt_values)
990
991         #
992         # Generate the shaper transform
993         #
994         # if 'shaperCTL' in odtValues:
995         (shaper_name,
996          shaper_to_ACES_CTL,
997          shaper_from_ACES_CTL,
998          shaper_input_scale,
999          shaper_params) = shaper_info
1000
1001         if 'legalRange' in odt_values:
1002             shaper_params['legalRange'] = odt_values['legalRange']
1003         else:
1004             shaper_params['legalRange'] = 0
1005
1006         shaper_lut = '%s_to_aces.spi1d' % shaper_name
1007         if (not os.path.exists(os.path.join(lut_directory, shaper_lut))):
1008             ctls = [shaper_to_ACES_CTL % aces_CTL_directory]
1009
1010             # Remove spaces and parentheses
1011             shaper_lut = shaper_lut.replace(
1012                 ' ', '_').replace(')', '_').replace('(', '_')
1013
1014             generate_1d_LUT_from_CTL(
1015                 os.path.join(lut_directory, shaper_lut),
1016                 ctls,
1017                 lut_resolution_1d,
1018                 'float',
1019                 1.0 / shaper_input_scale,
1020                 1.0,
1021                 shaper_params,
1022                 cleanup,
1023                 aces_CTL_directory)
1024
1025         shaper_OCIO_transform = {
1026             'type': 'lutFile',
1027             'path': shaper_lut,
1028             'interpolation': 'linear',
1029             'direction': 'inverse'
1030         }
1031
1032         #
1033         # Generate the forward transform
1034         #
1035         cs.from_reference_transforms = []
1036
1037         if 'transformLUT' in odt_values:
1038             # Copy into the lut dir
1039             transform_LUT_file_name = os.path.basename(
1040                 odt_values['transformLUT'])
1041             lut = os.path.join(lut_directory, transform_LUT_file_name)
1042             shutil.copy(odt_values['transformLUT'], lut)
1043
1044             cs.from_reference_transforms.append(shaper_OCIO_transform)
1045             cs.from_reference_transforms.append({
1046                 'type': 'lutFile',
1047                 'path': transform_LUT_file_name,
1048                 'interpolation': 'tetrahedral',
1049                 'direction': 'forward'
1050             })
1051         elif 'transformCTL' in odt_values:
1052             # shaperLut
1053
1054             ctls = [
1055                 shaper_to_ACES_CTL % aces_CTL_directory,
1056                 os.path.join(aces_CTL_directory,
1057                              'rrt',
1058                              'RRT.a1.0.0.ctl'),
1059                 os.path.join(aces_CTL_directory,
1060                              'odt',
1061                              odt_values['transformCTL'])]
1062             lut = '%s.RRT.a1.0.0.%s.spi3d' % (shaper_name, odt_name)
1063
1064             # Remove spaces and parentheses
1065             lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
1066
1067             generate_3d_LUT_from_CTL(
1068                 os.path.join(lut_directory, lut),
1069                 # shaperLUT,
1070                 ctls,
1071                 lut_resolution_3d,
1072                 'float',
1073                 1.0 / shaper_input_scale,
1074                 1.0,
1075                 shaper_params,
1076                 cleanup,
1077                 aces_CTL_directory)
1078
1079             cs.from_reference_transforms.append(shaper_OCIO_transform)
1080             cs.from_reference_transforms.append({
1081                 'type': 'lutFile',
1082                 'path': lut,
1083                 'interpolation': 'tetrahedral',
1084                 'direction': 'forward'
1085             })
1086
1087         #
1088         # Generate the inverse transform
1089         #
1090         cs.to_reference_transforms = []
1091
1092         if 'transformLUTInverse' in odt_values:
1093             # Copy into the lut dir
1094             transform_LUT_inverse_file_name = os.path.basename(
1095                 odt_values['transformLUTInverse'])
1096             lut = os.path.join(lut_directory, transform_LUT_inverse_file_name)
1097             shutil.copy(odt_values['transformLUTInverse'], lut)
1098
1099             cs.to_reference_transforms.append({
1100                 'type': 'lutFile',
1101                 'path': transform_LUT_inverse_file_name,
1102                 'interpolation': 'tetrahedral',
1103                 'direction': 'forward'
1104             })
1105
1106             shaper_inverse = shaper_OCIO_transform.copy()
1107             shaper_inverse['direction'] = 'forward'
1108             cs.to_reference_transforms.append(shaper_inverse)
1109         elif 'transformCTLInverse' in odt_values:
1110             ctls = [
1111                 os.path.join(aces_CTL_directory,
1112                              'odt',
1113                              odt_values['transformCTLInverse']),
1114                 os.path.join(aces_CTL_directory,
1115                              'rrt',
1116                              'InvRRT.a1.0.0.ctl'),
1117                 shaper_from_ACES_CTL % aces_CTL_directory
1118             ]
1119             lut = 'InvRRT.a1.0.0.%s.%s.spi3d' % (odt_name, shaper_name)
1120
1121             # Remove spaces and parentheses
1122             lut = lut.replace(' ', '_').replace(')', '_').replace('(', '_')
1123
1124             generate_3d_LUT_from_CTL(
1125                 os.path.join(lut_directory, lut),
1126                 # None,
1127                 ctls,
1128                 lut_resolution_3d,
1129                 'half',
1130                 1.0,
1131                 shaper_input_scale,
1132                 shaper_params,
1133                 cleanup,
1134                 aces_CTL_directory)
1135
1136             cs.to_reference_transforms.append({
1137                 'type': 'lutFile',
1138                 'path': lut,
1139                 'interpolation': 'tetrahedral',
1140                 'direction': 'forward'
1141             })
1142
1143             shaper_inverse = shaper_OCIO_transform.copy()
1144             shaper_inverse['direction'] = 'forward'
1145             cs.to_reference_transforms.append(shaper_inverse)
1146
1147         return cs
1148
1149     #
1150     # RRT/ODT shaper options
1151     #
1152     shaper_data = {}
1153
1154     # Log 2 shaper
1155     log2_shaper_name = shaper_name
1156     log2_params = {
1157         'middleGrey': 0.18,
1158         'minExposure': -6.0,
1159         'maxExposure': 6.5
1160     }
1161     log2_shaper = create_generic_log(
1162         name=log2_shaper_name,
1163         middle_grey=log2_params['middleGrey'],
1164         min_exposure=log2_params['minExposure'],
1165         max_exposure=log2_params['maxExposure'])
1166     config_data['colorSpaces'].append(log2_shaper)
1167
1168     shaper_input_scale_generic_log2 = 1.0
1169
1170     # Log 2 shaper name and CTL transforms bundled up
1171     log2_shaper_data = [
1172         log2_shaper_name,
1173         os.path.join('%s',
1174                      'utilities',
1175                      'ACESlib.OCIO_shaper_log2_to_lin_param.a1.0.0.ctl'),
1176         os.path.join('%s',
1177                      'utilities',
1178                      'ACESlib.OCIO_shaper_lin_to_log2_param.a1.0.0.ctl'),
1179         shaper_input_scale_generic_log2,
1180         log2_params]
1181
1182     shaper_data[log2_shaper_name] = log2_shaper_data
1183
1184     #
1185     # Shaper that also includes the AP1 primaries
1186     # - Needed for some LUT baking steps
1187     #
1188     log2_shaper_AP1 = create_generic_log(
1189         name=log2_shaper_name,
1190         middle_grey=log2_params['middleGrey'],
1191         min_exposure=log2_params['minExposure'],
1192         max_exposure=log2_params['maxExposure'])
1193     log2_shaper_AP1.name = '%s - AP1' % log2_shaper_AP1.name
1194     # AP1 primaries to AP0 primaries
1195     log2_shaper_AP1.to_reference_transforms.append({
1196         'type': 'matrix',
1197         'matrix': mat44_from_mat33(ACES_AP1_to_AP0),
1198         'direction': 'forward'
1199     })
1200     config_data['colorSpaces'].append(log2_shaper_AP1)
1201
1202     #
1203     # Choose your shaper
1204     #
1205     rrt_shaper_name = log2_shaper_name
1206     rrt_shaper = log2_shaper_data
1207
1208     #
1209     # RRT + ODT Combinations
1210     #
1211     sorted_odts = sorted(odt_info.iteritems(), key=lambda x: x[1])
1212     print(sorted_odts)
1213     for odt in sorted_odts:
1214         (odt_name, odt_values) = odt
1215
1216         # Have to handle ODTs that can generate either legal or full output
1217         if odt_name in ['Academy.Rec2020_100nits_dim.a1.0.0',
1218                         'Academy.Rec709_100nits_dim.a1.0.0',
1219                         'Academy.Rec709_D60sim_100nits_dim.a1.0.0']:
1220             odt_name_legal = '%s - Legal' % odt_values['transformUserName']
1221         else:
1222             odt_name_legal = odt_values['transformUserName']
1223
1224         odt_legal = odt_values.copy()
1225         odt_legal['legalRange'] = 1
1226
1227         cs = create_ACES_RRT_plus_ODT(
1228             odt_name_legal,
1229             odt_legal,
1230             rrt_shaper,
1231             lut_resolution_1d,
1232             lut_resolution_3d,
1233             cleanup)
1234         config_data['colorSpaces'].append(cs)
1235
1236         # Create a display entry using this color space
1237         config_data['displays'][odt_name_legal] = {
1238             'Linear': ACES,
1239             'Log': ACEScc,
1240             'Output Transform': cs}
1241
1242         if odt_name in ['Academy.Rec2020_100nits_dim.a1.0.0',
1243                         'Academy.Rec709_100nits_dim.a1.0.0',
1244                         'Academy.Rec709_D60sim_100nits_dim.a1.0.0']:
1245             print('Generating full range ODT for %s' % odt_name)
1246
1247             odt_name_full = '%s - Full' % odt_values['transformUserName']
1248             odt_full = odt_values.copy()
1249             odt_full['legalRange'] = 0
1250
1251             cs_full = create_ACES_RRT_plus_ODT(
1252                 odt_name_full,
1253                 odt_full,
1254                 rrt_shaper,
1255                 lut_resolution_1d,
1256                 lut_resolution_3d,
1257                 cleanup)
1258             config_data['colorSpaces'].append(cs_full)
1259
1260             # Create a display entry using this color space
1261             config_data['displays'][odt_name_full] = {
1262                 'Linear': ACES,
1263                 'Log': ACEScc,
1264                 'Output Transform': cs_full}
1265
1266     #
1267     # Generic Matrix transform
1268     #
1269     def create_generic_matrix(name='matrix',
1270                               from_reference_values=[],
1271                               to_reference_values=[]):
1272         cs = ColorSpace(name)
1273         cs.description = 'The %s color space' % name
1274         cs.equality_group = name
1275         cs.family = 'Utility'
1276         cs.is_data = False
1277
1278         cs.to_reference_transforms = []
1279         if to_reference_values != []:
1280             for matrix in to_reference_values:
1281                 cs.to_reference_transforms.append({
1282                     'type': 'matrix',
1283                     'matrix': mat44_from_mat33(matrix),
1284                     'direction': 'forward'
1285                 })
1286
1287         cs.from_reference_transforms = []
1288         if from_reference_values != []:
1289             for matrix in from_reference_values:
1290                 cs.from_reference_transforms.append({
1291                     'type': 'matrix',
1292                     'matrix': mat44_from_mat33(matrix),
1293                     'direction': 'forward'
1294                 })
1295
1296         return cs
1297
1298     cs = create_generic_matrix('XYZ', from_reference_values=[ACES_AP0_to_XYZ])
1299     config_data['colorSpaces'].append(cs)
1300
1301     cs = create_generic_matrix(
1302         'Linear - AP1', to_reference_values=[ACES_AP1_to_AP0])
1303     config_data['colorSpaces'].append(cs)
1304
1305     # ACES to Linear, P3D60 primaries
1306     XYZ_to_P3D60 = [2.4027414142, -0.8974841639, -0.3880533700,
1307                     -0.8325796487, 1.7692317536, 0.0237127115,
1308                     0.0388233815, -0.0824996856, 1.0363685997]
1309
1310     cs = create_generic_matrix(
1311         'Linear - P3-D60',
1312         from_reference_values=[ACES_AP0_to_XYZ, XYZ_to_P3D60])
1313     config_data['colorSpaces'].append(cs)
1314
1315     # ACES to Linear, P3D60 primaries
1316     XYZ_to_P3DCI = [2.7253940305, -1.0180030062, -0.4401631952,
1317                     -0.7951680258, 1.6897320548, 0.0226471906,
1318                     0.0412418914, -0.0876390192, 1.1009293786]
1319
1320     cs = create_generic_matrix(
1321         'Linear - P3-DCI',
1322         from_reference_values=[ACES_AP0_to_XYZ, XYZ_to_P3DCI])
1323     config_data['colorSpaces'].append(cs)
1324
1325     # ACES to Linear, Rec 709 primaries
1326     XYZ_to_Rec709 = [3.2409699419, -1.5373831776, -0.4986107603,
1327                      -0.9692436363, 1.8759675015, 0.0415550574,
1328                      0.0556300797, -0.2039769589, 1.0569715142]
1329
1330     cs = create_generic_matrix(
1331         'Linear - Rec.709',
1332         from_reference_values=[ACES_AP0_to_XYZ, XYZ_to_Rec709])
1333     config_data['colorSpaces'].append(cs)
1334
1335     # ACES to Linear, Rec 2020 primaries
1336     XYZ_to_Rec2020 = [1.7166511880, -0.3556707838, -0.2533662814,
1337                       -0.6666843518, 1.6164812366, 0.0157685458,
1338                       0.0176398574, -0.0427706133, 0.9421031212]
1339
1340     cs = create_generic_matrix(
1341         'Linear - Rec.2020',
1342         from_reference_values=[ACES_AP0_to_XYZ, XYZ_to_Rec2020])
1343     config_data['colorSpaces'].append(cs)
1344
1345     print('generateLUTs - end')
1346     return config_data
1347
1348
1349 def generate_baked_LUTs(odt_info,
1350                         shaper_name,
1351                         baked_directory,
1352                         config_path,
1353                         lut_resolution_1d,
1354                         lut_resolution_3d,
1355                         lut_resolution_shaper=1024):
1356     """
1357     Object description.
1358
1359     Parameters
1360     ----------
1361     parameter : type
1362         Parameter description.
1363
1364     Returns
1365     -------
1366     type
1367          Return value description.
1368     """
1369
1370     # Add the legal and full variations into this list
1371     odt_info_C = dict(odt_info)
1372     for odt_CTL_name, odt_values in odt_info.iteritems():
1373         if odt_CTL_name in ['Academy.Rec2020_100nits_dim.a1.0.0',
1374                             'Academy.Rec709_100nits_dim.a1.0.0',
1375                             'Academy.Rec709_D60sim_100nits_dim.a1.0.0']:
1376             odt_name = odt_values['transformUserName']
1377
1378             odt_values_legal = dict(odt_values)
1379             odt_values_legal['transformUserName'] = '%s - Legal' % odt_name
1380             odt_info_C['%s - Legal' % odt_CTL_name] = odt_values_legal
1381
1382             odt_values_full = dict(odt_values)
1383             odt_values_full['transformUserName'] = '%s - Full' % odt_name
1384             odt_info_C['%s - Full' % odt_CTL_name] = odt_values_full
1385
1386             del (odt_info_C[odt_CTL_name])
1387
1388     for odt_CTL_name, odt_values in odt_info_C.iteritems():
1389         odt_prefix = odt_values['transformUserNamePrefix']
1390         odt_name = odt_values['transformUserName']
1391
1392         # For Photoshop
1393         for input_space in ['ACEScc', 'ACESproxy']:
1394             args = ['--iconfig', config_path,
1395                     '-v',
1396                     '--inputspace', input_space]
1397             args += ['--outputspace', '%s' % odt_name]
1398             args += ['--description',
1399                      '%s - %s for %s data' % (odt_prefix,
1400                                               odt_name,
1401                                               input_space)]
1402             args += ['--shaperspace', shaper_name,
1403                      '--shapersize', str(lut_resolution_shaper)]
1404             args += ['--cubesize', str(lut_resolution_3d)]
1405             args += ['--format',
1406                      'icc',
1407                      os.path.join(baked_directory,
1408                                   'photoshop',
1409                                   '%s for %s.icc' % (odt_name, input_space))]
1410
1411             bake_LUT = Process(description='bake a LUT',
1412                                cmd='ociobakelut',
1413                                args=args)
1414             bake_LUT.execute()
1415
1416         # For Flame, Lustre
1417         for input_space in ['ACEScc', 'ACESproxy']:
1418             args = ['--iconfig', config_path,
1419                     '-v',
1420                     '--inputspace', input_space]
1421             args += ['--outputspace', '%s' % odt_name]
1422             args += ['--description',
1423                      '%s - %s for %s data' % (
1424                          odt_prefix, odt_name, input_space)]
1425             args += ['--shaperspace', shaper_name,
1426                      '--shapersize', str(lut_resolution_shaper)]
1427             args += ['--cubesize', str(lut_resolution_3d)]
1428
1429             fargs = ['--format',
1430                      'flame',
1431                      os.path.join(
1432                          baked_directory,
1433                          'flame',
1434                          '%s for %s Flame.3dl' % (odt_name, input_space))]
1435             bake_LUT = Process(description='bake a LUT',
1436                                cmd='ociobakelut',
1437                                args=(args + fargs))
1438             bake_LUT.execute()
1439
1440             largs = ['--format',
1441                      'lustre',
1442                      os.path.join(
1443                          baked_directory,
1444                          'lustre',
1445                          '%s for %s Lustre.3dl' % (odt_name, input_space))]
1446             bake_LUT = Process(description='bake a LUT',
1447                                cmd='ociobakelut',
1448                                args=(args + largs))
1449             bake_LUT.execute()
1450
1451         # For Maya, Houdini
1452         for input_space in ['ACEScg', 'ACES2065-1']:
1453             args = ['--iconfig', config_path,
1454                     '-v',
1455                     '--inputspace', input_space]
1456             args += ['--outputspace', '%s' % odt_name]
1457             args += ['--description',
1458                      '%s - %s for %s data' % (
1459                          odt_prefix, odt_name, input_space)]
1460             if input_space == 'ACEScg':
1461                 lin_shaper_name = '%s - AP1' % shaper_name
1462             else:
1463                 lin_shaper_name = shaper_name
1464             args += ['--shaperspace', lin_shaper_name,
1465                      '--shapersize', str(lut_resolution_shaper)]
1466
1467             args += ['--cubesize', str(lut_resolution_3d)]
1468
1469             margs = ['--format',
1470                      'cinespace',
1471                      os.path.join(
1472                          baked_directory,
1473                          'maya',
1474                          '%s for %s Maya.csp' % (odt_name, input_space))]
1475             bake_LUT = Process(description='bake a LUT',
1476                                cmd='ociobakelut',
1477                                args=(args + margs))
1478             bake_LUT.execute()
1479
1480             hargs = ['--format',
1481                      'houdini',
1482                      os.path.join(
1483                          baked_directory,
1484                          'houdini',
1485                          '%s for %s Houdini.lut' % (odt_name, input_space))]
1486             bake_LUT = Process(description='bake a LUT',
1487                                cmd='ociobakelut',
1488                                args=(args + hargs))
1489             bake_LUT.execute()
1490
1491
1492 def create_config_dir(config_directory, bake_secondary_LUTs):
1493     """
1494     Object description.
1495
1496     Parameters
1497     ----------
1498     parameter : type
1499         Parameter description.
1500
1501     Returns
1502     -------
1503     type
1504          Return value description.
1505     """
1506
1507     dirs = [config_directory, os.path.join(config_directory, 'luts')]
1508     if bake_secondary_LUTs:
1509         dirs.extend([os.path.join(config_directory, 'baked'),
1510                      os.path.join(config_directory, 'baked', 'flame'),
1511                      os.path.join(config_directory, 'baked', 'photoshop'),
1512                      os.path.join(config_directory, 'baked', 'houdini'),
1513                      os.path.join(config_directory, 'baked', 'lustre'),
1514                      os.path.join(config_directory, 'baked', 'maya')])
1515
1516     for d in dirs:
1517         not os.path.exists(d) and os.mkdir(d)
1518
1519
1520 def get_transform_info(ctl_transform):
1521     """
1522     Object description.
1523
1524     Parameters
1525     ----------
1526     parameter : type
1527         Parameter description.
1528
1529     Returns
1530     -------
1531     type
1532          Return value description.
1533     """
1534
1535     # TODO: Use *with* statement.
1536     fp = open(ctl_transform, 'rb')
1537
1538     # Read lines
1539     lines = fp.readlines()
1540
1541     # Grab transform ID and User Name
1542     transform_ID = lines[1][3:].split('<')[1].split('>')[1].strip()
1543     # print(transformID)
1544     transform_user_name = '-'.join(
1545         lines[2][3:].split('<')[1].split('>')[1].split('-')[1:]).strip()
1546     transform_user_name_prefix = (
1547         lines[2][3:].split('<')[1].split('>')[1].split('-')[0].strip())
1548     # print(transformUserName)
1549     fp.close()
1550
1551     return transform_ID, transform_user_name, transform_user_name_prefix
1552
1553
1554 def get_ODT_info(aces_CTL_directory):
1555     """
1556     Object description.
1557
1558     For versions after WGR9.
1559
1560     Parameters
1561     ----------
1562     parameter : type
1563         Parameter description.
1564
1565     Returns
1566     -------
1567     type
1568          Return value description.
1569     """
1570
1571     # TODO: Investigate usage of *files_walker* definition here.
1572     # Credit to Alex Fry for the original approach here
1573     odt_dir = os.path.join(aces_CTL_directory, 'odt')
1574     all_odt = []
1575     for dir_name, subdir_list, file_list in os.walk(odt_dir):
1576         for fname in file_list:
1577             all_odt.append((os.path.join(dir_name, fname)))
1578
1579     odt_CTLs = [x for x in all_odt if
1580                 ('InvODT' not in x) and (os.path.split(x)[-1][0] != '.')]
1581
1582     # print odtCTLs
1583
1584     odts = {}
1585
1586     for odt_CTL in odt_CTLs:
1587         odt_tokens = os.path.split(odt_CTL)
1588         # print(odtTokens)
1589
1590         # Handle nested directories
1591         odt_path_tokens = os.path.split(odt_tokens[-2])
1592         odt_dir = odt_path_tokens[-1]
1593         while odt_path_tokens[-2][-3:] != 'odt':
1594             odt_path_tokens = os.path.split(odt_path_tokens[-2])
1595             odt_dir = os.path.join(odt_path_tokens[-1], odt_dir)
1596
1597         # Build full name
1598         # print('odtDir : %s' % odtDir)
1599         transform_CTL = odt_tokens[-1]
1600         # print(transformCTL)
1601         odt_name = string.join(transform_CTL.split('.')[1:-1], '.')
1602         # print(odtName)
1603
1604         # Find id, user name and user name prefix
1605         (transform_ID,
1606          transform_user_name,
1607          transform_user_name_prefix) = get_transform_info(
1608             os.path.join(aces_CTL_directory, 'odt', odt_dir, transform_CTL))
1609
1610         # Find inverse
1611         transform_CTL_inverse = 'InvODT.%s.ctl' % odt_name
1612         if not os.path.exists(
1613                 os.path.join(odt_tokens[-2], transform_CTL_inverse)):
1614             transform_CTL_inverse = None
1615         # print(transformCTLInverse)
1616
1617         # Add to list of ODTs
1618         odts[odt_name] = {}
1619         odts[odt_name]['transformCTL'] = os.path.join(odt_dir, transform_CTL)
1620         if transform_CTL_inverse != None:
1621             odts[odt_name]['transformCTLInverse'] = os.path.join(
1622                 odt_dir, transform_CTL_inverse)
1623
1624         odts[odt_name]['transformID'] = transform_ID
1625         odts[odt_name]['transformUserNamePrefix'] = transform_user_name_prefix
1626         odts[odt_name]['transformUserName'] = transform_user_name
1627
1628         print('ODT : %s' % odt_name)
1629         print('\tTransform ID               : %s' % transform_ID)
1630         print('\tTransform User Name Prefix : %s' % transform_user_name_prefix)
1631         print('\tTransform User Name        : %s' % transform_user_name)
1632         print('\tForward ctl                : %s' % (
1633             odts[odt_name]['transformCTL']))
1634         if 'transformCTLInverse' in odts[odt_name]:
1635             print('\tInverse ctl                : %s' % (
1636                 odts[odt_name]['transformCTLInverse']))
1637         else:
1638             print('\tInverse ctl                : %s' % 'None')
1639
1640     print('\n')
1641
1642     return odts
1643
1644
1645 def get_LMT_info(aces_CTL_directory):
1646     """
1647     Object description.
1648
1649     For versions after WGR9.
1650
1651     Parameters
1652     ----------
1653     parameter : type
1654         Parameter description.
1655
1656     Returns
1657     -------
1658     type
1659          Return value description.
1660     """
1661
1662     # TODO: Investigate refactoring with previous definition.
1663
1664     # Credit to Alex Fry for the original approach here
1665     lmt_dir = os.path.join(aces_CTL_directory, 'lmt')
1666     all_lmt = []
1667     for dir_name, subdir_list, file_list in os.walk(lmt_dir):
1668         for fname in file_list:
1669             all_lmt.append((os.path.join(dir_name, fname)))
1670
1671     lmt_CTLs = [x for x in all_lmt if
1672                 ('InvLMT' not in x) and ('README' not in x) and (
1673                     os.path.split(x)[-1][0] != '.')]
1674
1675     # print lmtCTLs
1676
1677     lmts = {}
1678
1679     for lmt_CTL in lmt_CTLs:
1680         lmt_tokens = os.path.split(lmt_CTL)
1681         # print(lmtTokens)
1682
1683         # Handle nested directories
1684         lmt_path_tokens = os.path.split(lmt_tokens[-2])
1685         lmt_dir = lmt_path_tokens[-1]
1686         while lmt_path_tokens[-2][-3:] != 'ctl':
1687             lmt_path_tokens = os.path.split(lmt_path_tokens[-2])
1688             lmt_dir = os.path.join(lmt_path_tokens[-1], lmt_dir)
1689
1690         # Build full name
1691         # print('lmtDir : %s' % lmtDir)
1692         transform_CTL = lmt_tokens[-1]
1693         # print(transformCTL)
1694         lmt_name = string.join(transform_CTL.split('.')[1:-1], '.')
1695         # print(lmtName)
1696
1697         # Find id, user name and user name prefix
1698         (transform_ID,
1699          transform_user_name,
1700          transform_user_name_prefix) = get_transform_info(
1701             os.path.join(aces_CTL_directory, lmt_dir, transform_CTL))
1702
1703         # Find inverse
1704         transform_CTL_inverse = 'InvLMT.%s.ctl' % lmt_name
1705         if not os.path.exists(
1706                 os.path.join(lmt_tokens[-2], transform_CTL_inverse)):
1707             transform_CTL_inverse = None
1708         # print(transformCTLInverse)
1709
1710         # Add to list of LMTs
1711         lmts[lmt_name] = {}
1712         lmts[lmt_name]['transformCTL'] = os.path.join(lmt_dir, transform_CTL)
1713         if transform_CTL_inverse != None:
1714             # TODO: Check unresolved *odt_name* referemce.
1715             lmts[odt_name]['transformCTLInverse'] = os.path.join(
1716                 lmt_dir, transform_CTL_inverse)
1717
1718         lmts[lmt_name]['transformID'] = transform_ID
1719         lmts[lmt_name]['transformUserNamePrefix'] = transform_user_name_prefix
1720         lmts[lmt_name]['transformUserName'] = transform_user_name
1721
1722         print('LMT : %s' % lmt_name)
1723         print('\tTransform ID               : %s' % transform_ID)
1724         print('\tTransform User Name Prefix : %s' % transform_user_name_prefix)
1725         print('\tTransform User Name        : %s' % transform_user_name)
1726         print('\t Forward ctl : %s' % lmts[lmt_name]['transformCTL'])
1727         if 'transformCTLInverse' in lmts[lmt_name]:
1728             print('\t Inverse ctl : %s' % (
1729                 lmts[lmt_name]['transformCTLInverse']))
1730         else:
1731             print('\t Inverse ctl : %s' % 'None')
1732
1733     print('\n')
1734
1735     return lmts
1736
1737
1738 def create_ACES_config(aces_CTL_directory,
1739                        config_directory,
1740                        lut_resolution_1d=4096,
1741                        lut_resolution_3d=64,
1742                        bake_secondary_LUTs=True,
1743                        cleanup=True):
1744     """
1745     Creates the ACES configuration.
1746
1747     Parameters
1748     ----------
1749     parameter : type
1750         Parameter description.
1751
1752     Returns
1753     -------
1754     type
1755          Return value description.
1756     """
1757
1758     # Get ODT names and CTL paths
1759     odt_info = get_ODT_info(aces_CTL_directory)
1760
1761     # Get ODT names and CTL paths
1762     lmt_info = get_LMT_info(aces_CTL_directory)
1763
1764     # Create config dir
1765     create_config_dir(config_directory, bake_secondary_LUTs)
1766
1767     # Generate config data and LUTs for different transforms
1768     lut_directory = os.path.join(config_directory, 'luts')
1769     shaper_name = 'Output Shaper'
1770     config_data = generate_LUTs(odt_info,
1771                                 lmt_info,
1772                                 shaper_name,
1773                                 aces_CTL_directory,
1774                                 lut_directory,
1775                                 lut_resolution_1d,
1776                                 lut_resolution_3d,
1777                                 cleanup)
1778
1779     # Create the config using the generated LUTs
1780     print('Creating generic config')
1781     config = create_config(config_data)
1782     print('\n\n\n')
1783
1784     # Write the config to disk
1785     write_config(config,
1786                  os.path.join(config_directory, 'config.ocio'))
1787
1788     # Create a config that will work well with Nuke using the previously
1789     # generated LUTs.
1790     print('Creating Nuke-specific config')
1791     nuke_config = create_config(config_data, nuke=True)
1792     print('\n\n\n')
1793
1794     # Write the config to disk
1795     write_config(nuke_config,
1796                  os.path.join(config_directory, 'nuke_config.ocio'))
1797
1798     # Bake secondary LUTs using the config
1799     if bake_secondary_LUTs:
1800         generate_baked_LUTs(odt_info,
1801                             shaper_name,
1802                             os.path.join(config_directory, 'baked'),
1803                             os.path.join(config_directory, 'config.ocio'),
1804                             lut_resolution_1d,
1805                             lut_resolution_3d,
1806                             lut_resolution_1d)
1807
1808     return True
1809
1810
1811 def main():
1812     """
1813     Object description.
1814
1815     Parameters
1816     ----------
1817     parameter : type
1818         Parameter description.
1819
1820     Returns
1821     -------
1822     type
1823          Return value description.
1824     """
1825
1826     import optparse
1827
1828     p = optparse.OptionParser(description='An OCIO config generation script',
1829                               prog='createACESConfig',
1830                               version='createACESConfig 0.1',
1831                               usage='%prog [options]')
1832     p.add_option('--acesCTLDir', '-a', default=os.environ.get(
1833         'ACES_OCIO_CTL_DIRECTORY', None))
1834     p.add_option('--configDir', '-c', default=os.environ.get(
1835         'ACES_OCIO_CONFIGURATION_DIRECTORY', None))
1836     p.add_option('--lutResolution1d', default=4096)
1837     p.add_option('--lutResolution3d', default=64)
1838     p.add_option('--dontBakeSecondaryLUTs', action='store_true')
1839     p.add_option('--keepTempImages', action='store_true')
1840
1841     options, arguments = p.parse_args()
1842
1843     #
1844     # Get options
1845     #
1846     aces_CTL_directory = options.acesCTLDir
1847     config_directory = options.configDir
1848     lut_resolution_1d = int(options.lutResolution1d)
1849     lut_resolution_3d = int(options.lutResolution3d)
1850     bake_secondary_LUTs = not (options.dontBakeSecondaryLUTs)
1851     cleanup_temp_images = not (options.keepTempImages)
1852
1853     try:
1854         args_start = sys.argv.index('--') + 1
1855         args = sys.argv[args_start:]
1856     except:
1857         args_start = len(sys.argv) + 1
1858         args = []
1859
1860     print('command line : \n%s\n' % ' '.join(sys.argv))
1861
1862     # TODO: Use assertion and mention environment variables.
1863     if not aces_CTL_directory:
1864         print('process: No ACES CTL directory specified')
1865         return
1866     if not config_directory:
1867         print('process: No configuration directory specified')
1868         return
1869     #
1870     # Generate the configuration
1871     #
1872     return create_ACES_config(aces_CTL_directory,
1873                               config_directory,
1874                               lut_resolution_1d,
1875                               lut_resolution_3d,
1876                               bake_secondary_LUTs,
1877                               cleanup_temp_images)
1878
1879
1880 if __name__ == '__main__':
1881     main()