Skip to content

extract_render_local

NukeRenderLocal

Bases: Extractor, ColormanagedPyblishPluginMixin

Render the current Nuke composition locally.

Extract the result of savers by starting a comp render This will run the local render of Nuke.

Allows to use last published frames and overwrite only specific ones (set in instance.data.get("frames_to_fix"))

Source code in client/ayon_nuke/plugins/publish/extract_render_local.py
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
class NukeRenderLocal(publish.Extractor,
                      publish.ColormanagedPyblishPluginMixin):
    """Render the current Nuke composition locally.

    Extract the result of savers by starting a comp render
    This will run the local render of Nuke.

    Allows to use last published frames and overwrite only specific ones
    (set in instance.data.get("frames_to_fix"))
    """

    order = pyblish.api.ExtractorOrder
    label = "Render Local"
    hosts = ["nuke"]
    families = ["render.local", "prerender.local", "image.local"]

    settings_category = "nuke"

    def process(self, instance):
        child_nodes = (
            instance.data.get("transientData", {}).get("childNodes")
            or instance
        )

        node = None
        for x in child_nodes:
            if x.Class() == "Write":
                node = x

        self.log.debug("instance collected: {}".format(instance.data))

        node_product_name = instance.data.get("name", None)

        first_frame = instance.data.get("frameStartHandle", None)
        last_frame = instance.data.get("frameEndHandle", None)

        filenames = []
        node_file = node["file"]
        # Collect expected filepaths for each frame
        # - for cases that output is still image is first created set of
        #   paths which is then sorted and converted to list
        expected_paths = list(sorted({
            node_file.evaluate(frame)
            for frame in range(first_frame, last_frame + 1)
        }))
        # Extract only filenames for representation
        filenames.extend([
            os.path.basename(filepath)
            for filepath in expected_paths
        ])

        # Ensure output directory exists.
        out_dir = os.path.dirname(expected_paths[0])
        if not os.path.exists(out_dir):
            os.makedirs(out_dir)

        frames_to_render = [(first_frame, last_frame)]

        frames_to_fix = instance.data.get("frames_to_fix")
        if instance.data.get("last_version_published_files") and frames_to_fix:
            frames_to_render = self._get_frames_to_render(frames_to_fix)
            anatomy = instance.context.data["anatomy"]
            self._copy_last_published(anatomy, instance, out_dir,
                                      filenames)

        for render_first_frame, render_last_frame in frames_to_render:

            self.log.info("Starting render")
            self.log.info("Start frame: {}".format(render_first_frame))
            self.log.info("End frame: {}".format(render_last_frame))

            # Render frames
            nuke.execute(
                str(node_product_name),
                int(render_first_frame),
                int(render_last_frame)
            )

        # Determine defined file type
        path = node["file"].value()
        ext = os.path.splitext(path)[1].lstrip(".")

        colorspace = napi.get_colorspace_from_node(node)

        if "representations" not in instance.data:
            instance.data["representations"] = []

        if len(filenames) == 1:
            repre = {
                'name': ext,
                'ext': ext,
                'files': filenames[0],
                "stagingDir": out_dir
            }
        else:
            repre = {
                'name': ext,
                'ext': ext,
                'frameStart': (
                    "{{:0>{}}}"
                    .format(len(str(last_frame)))
                    .format(first_frame)
                ),
                'files': filenames,
                "stagingDir": out_dir
            }

        # inject colorspace data
        self.set_representation_colorspace(
            repre, instance.context,
            colorspace=colorspace
        )

        instance.data["representations"].append(repre)

        self.log.debug("Extracted instance '{0}' to: {1}".format(
            instance.name,
            out_dir
        ))

        families = instance.data["families"]
        anatomy_data = instance.data["anatomyData"]
        # redefinition of families
        if "render.local" in families:
            instance.data["family"] = "render"
            instance.data["productType"] = "render"
            families.remove("render.local")
            families.insert(0, "render2d")
            anatomy_data["family"] = "render"
            anatomy_data["product"]["type"] = "render"
        elif "prerender.local" in families:
            instance.data["family"] = "prerender"
            instance.data["productType"] = "prerender"
            families.remove("prerender.local")
            families.insert(0, "prerender")
            anatomy_data["family"] = "prerender"
            anatomy_data["product"]["type"] = "prerender"
        elif "image.local" in families:
            instance.data["family"] = "image"
            instance.data["productType"] = "image"
            families.remove("image.local")
            anatomy_data["family"] = "image"
            anatomy_data["product"]["type"] = "image"
        instance.data["families"] = families

        collections, remainder = clique.assemble(filenames)
        self.log.debug('collections: {}'.format(str(collections)))

        if collections:
            collection = collections[0]
            instance.data['collection'] = collection

        self.log.info('Finished render')

        self.log.debug("_ instance.data: {}".format(instance.data))

    def _copy_last_published(self, anatomy, instance, out_dir,
                             expected_filenames):
        """Copies last published files to temporary out_dir.

        These are base of files which will be extended/fixed for specific
        frames.
        Renames published file to expected file name based on frame, eg.
        test_project_test_asset_product_v005.1001.exr > new_render.1001.exr
        """
        last_published = instance.data["last_version_published_files"]
        last_published_and_frames = collect_frames(last_published)

        expected_and_frames = collect_frames(expected_filenames)
        frames_and_expected = {v: k for k, v in expected_and_frames.items()}
        for file_path, frame in last_published_and_frames.items():
            file_path = anatomy.fill_root(file_path)
            if not os.path.exists(file_path):
                continue
            target_file_name = frames_and_expected.get(frame)
            if not target_file_name:
                continue

            out_path = os.path.join(out_dir, target_file_name)
            self.log.debug("Copying '{}' -> '{}'".format(file_path, out_path))
            shutil.copy(file_path, out_path)

            # TODO shouldn't this be uncommented
            # instance.context.data["cleanupFullPaths"].append(out_path)

    def _get_frames_to_render(self, frames_to_fix):
        """Return list of frame range tuples to render

        Args:
            frames_to_fix (str): specific or range of frames to be rerendered
             (1005, 1009-1010)
        Returns:
            (list): [(1005, 1005), (1009-1010)]
        """
        frames_to_render = []

        for frame_range in frames_to_fix.split(","):
            if frame_range.isdigit():
                render_first_frame = frame_range
                render_last_frame = frame_range
            elif '-' in frame_range:
                frames = frame_range.split('-')
                render_first_frame = int(frames[0])
                render_last_frame = int(frames[1])
            else:
                raise ValueError("Wrong format of frames to fix {}"
                                 .format(frames_to_fix))
            frames_to_render.append((render_first_frame,
                                     render_last_frame))
        return frames_to_render