Ejemplo n.º 1
0
    def _tx_convert(self,
                    product_desc,
                    version_note,
                    tif_product_repr,
                    queue,
                    queue_name=None):

        now = datetime.datetime.now()

        tx_product_repr = self._create_product(product_desc, version_note,
                                               'tx')

        tx_dir = tx_product_repr.directory
        tif_dir = tif_product_repr.directory

        if not os.path.exists(tif_dir):
            raise EntityError("TIF files must exist prior to TX conversion.")

        try:
            tif_files = [f for f in os.listdir(tif_dir) if f.endswith('.tif')]
            self.session.mari.app.startProcessing(
                'Converting existing .tif to .tx',
                len(tif_files) + 1, True)
            self.session.mari.app.setProgress(0)

            for (count, tif_file) in enumerate(tif_files):
                self.session.mari.app.setProgress(count)
                (file_base, tif_ext) = os.path.splitext(tif_file)
                tx_file = file_base + '.tx'

                tif_file = os.path.join(tif_dir, tif_file)
                tx_file = os.path.join(tx_dir, tx_file)

                maketx = self.session.require_executable('maketx')
                txcmd = '{maketx} -v -u -oiio {tif} -o {tx}'.format(
                    maketx=maketx, tif=tif_file, tx=tx_file)

                if queue:
                    queue_submit_cmd(txcmd,
                                     queue_name,
                                     output_file=tx_file,
                                     id_extra=file_base.replace(".", "_"),
                                     dt=now)
                else:
                    os.system(txcmd)

            self.session.mari.app.stopProcessing()

        except Exception as e:
            import traceback
            traceback.print_exc()
            self.session.mari.app.stopProcessing()
            self.session.mari.utils.message(
                "Error with conversion. "
                "Please make sure folders are chmodded correctly/files exist.")

        tx_product_repr.area.set_permissions(0660)

        return [tx_product_repr]
Ejemplo n.º 2
0
    def get_export_channels(cls, session):
        try:
            geo = session.mari.geo.current()
        except:
            raise EntityError("No project open; please open one.")
        else:
            if geo is None:
                raise EntityError("Please select an object to export a "
                                  "channel from for this entity.")

            export_channels = geo.channelList()

            if not export_channels:
                raise EntityError("There are no channels to export for "
                                  "this entity.")

            return export_channels
Ejemplo n.º 3
0
    def import_product_representation(cls, session, representation, *args,
                                      **kwargs):

        if representation.type == 'fbx':
            cls._fbx_import(session, representation, *args, **kwargs)
        elif representation.type == 'abc':
            cls._abc_import(session, representation, *args, **kwargs)
        else:
            raise EntityError("Unknown type for {cat} import: {typ}".format(
                cat=cls.category, typ=representation.type))
Ejemplo n.º 4
0
    def _get_export_set(self):

        # make sure the name exists.
        set_names = self.__class__.get_export_sets(self.session)
        matches = [s for s in set_names if s.endswith(self.display_name)]

        if not matches and len(matches) != 1:
            raise EntityError("Unable to identify export set for entity!")

        return matches[0]
Ejemplo n.º 5
0
    def import_product_representation(cls, session, representation, *args,
        **kwargs):

        if representation.type == 'ma':
            super(CameraEntity, cls).import_product_representation(
                session, representation, *args, **kwargs)    
        else:
            if representation.type != 'fbx':
                raise EntityError(
                    "Unknown type for {cat} import: {typ}".format(
                        cls=cls.category, typ=representation.type))

            cls._fbx_import(session, representation, *args, **kwargs)
Ejemplo n.º 6
0
    def get(cls, name, session, instance=None):
        """Retrieve an entity instance from the supplied session."""

        # make sure the name exists.
        channels = cls.get_export_channels(session)
        matches = [s for s in channels if s.endswith(name)]

        if not matches and len(matches) != 1:
            raise EntityError(
                "Could not find unique channel {name} instance in session.".\
                    format(cat=cls.category, name=name)
            )

        return cls(name, session, instance)
Ejemplo n.º 7
0
    def get(cls, name, session, instance=None):
        """Retrieve an entity instance from the supplied session."""

        # make sure the name exists.
        set_names = cls.get_export_sets(session)

        fullname = name
        if instance:
            fullname += "_" + str(instance)

        matches = [s for s in set_names if s.endswith(fullname)]

        if not matches and len(matches) != 1:
            raise EntityError(
                "Could not find unique {cat} {name} instance in session.".\
                    format(cat=cls.category, name=fullname)
            )

        return cls(name, session, instance)
Ejemplo n.º 8
0
 def export(self, *args, **kwargs):
     raise EntityError("Maya maps export not implemented.")
Ejemplo n.º 9
0
    def ptexImport(cls, session, representation, kwargs):
        """Import maps into the session."""

        session.require_plugin('RenderMan_for_Maya')

        product_version = representation.product_version
        product = product_version.product

        product_name_parts = product.name.split("_")
        maps_type = product_name_parts.pop()
        obj_name = "_".join(product_name_parts)

        # ---- file read node

        file_node_name = "ptex_{pn}".format(pn=product.name)
        file_node = session.cmds.shadingNode('PxrPtexture',
                                             asTexture=True,
                                             name=file_node_name)

        # set UDIM/ATLAS support to mari
        current_file = session.cmds.file(q=True, sceneName=True)
        import_base = cls.get_import_file_common_base(session,
                                                      product.name,
                                                      product.category,
                                                      representation,
                                                      relative_to=current_file)
        map_path = import_base + '.' + representation.type
        session.cmds.setAttr(file_node + '.filename', map_path, type="string")
        #session.cmds.setAttr(file_node + '.filterType', 0)
        #session.cmds.setAttr(file_node + '.colorProfile', 0)

        # add renderman attributes
        add_attr = 'rmanAddAttr {fn} {attr} "";'
        session.mel.eval(add_attr.format(fn=file_node,
                                         attr='rman__tx2dFilter'))
        session.mel.eval(add_attr.format(fn=file_node,
                                         attr='rman__tx2dSwidth'))
        session.mel.eval(add_attr.format(fn=file_node,
                                         attr='rman__tx2dTwidth'))
        session.mel.eval(add_attr.format(fn=file_node, attr='rman__tx2dLerp'))
        session.mel.eval(add_attr.format(fn=file_node, attr='rman__applysRGB'))
        session.mel.eval(add_attr.format(fn=file_node, attr='rman__udim'))
        session.mel.eval(
            add_attr.format(fn=file_node, attr='rman__unpremultiply'))

        # set udim lookup to 'mari'
        session.cmds.setAttr(file_node + '.rman__udim', 'mari', type='string')

        # ---- config options

        # linearize?
        session.cmds.setAttr(file_node + '.rman__applysRGB',
                             kwargs.get('linearize', False))

        # disable file load
        #session.cmds.setAttr(file_node + '.disableFileLoad',
        #    kwargs.get('disable_file_load', False))

        # ---- create surface shader if it doesn't exist
        shader_type = 'PxrSurface'
        shader_name = "shaderPxr_{on}".format(on=obj_name)

        if not session.cmds.ls(shader_name):
            session.cmds.shadingNode(shader_type,
                                     asShader=True,
                                     name=shader_name)

        # ---- type specific attributes and connections

        connect = kwargs.get('connect', True)

        # DIFFUSE
        if maps_type in [
                'diff', 'diffuse', 'diffMap', 'diffuseMap', 'ptex_diffuse'
        ]:

            if connect:
                session.cmds.connectAttr(file_node + '.resultRGB',
                                         shader_name + '.diffuseColor')

        # SPECULAR
        elif maps_type in ['spec', 'specular', 'specMap', 'specularMap']:

            if connect:
                session.cmds.connectAttr(file_node + '.resultRGB',
                                         shader_name + '.specularFaceColor')
                session.cmds.connectAttr(file_node + '.resultRGB',
                                         shader_name + '.specularEdgeColor')

        # BUMP
        elif maps_type in ['bump', 'bumpMap']:

            session.cmds.setAttr(file_node + '.alphaIsLuminance', 1)

            session.mel.eval('rmanSetAttr {sn} {attr} 0'.format(
                sn=shader_name, attr='enableDisplacement'))

            session.cmds.setAttr(shader_name + '.bumpAmount', 1.0)

            if connect:
                session.cmds.connectAttr(file_node + '.outColor.outColorR',
                                         shader_name + '.bumpScalar')

        # TRANSPARENCY
        elif maps_type in [
                'trans', 'transparency', 'transMap', 'transparencyMap'
        ]:

            session.cmds.setAttr(file_node + '.alphaIsLuminance', 1)

            if connect:
                session.cmds.connectAttr(file_node + '.outColor',
                                         shader_name + '.transparency')

        # DISPLACEMENT
        elif maps_type in [
                'disp', 'displacement', 'dispMap', 'displacementMap'
        ]:

            add_attr = 'rmanAddAttr {sn} {attr} "";'
            session.mel.eval(
                add_attr.format(sn=shader_name,
                                attr='rman__riattr__displacementbound_sphere'))

            session.mel.eval(
                add_attr.format(
                    sn=shader_name,
                    attr='rman__riattr__displacementbound_coordinatesystem'))

            session.mel.eval(
                add_attr.format(sn=shader_name,
                                attr='rman__riattr__trace_displacements'))

            if connect:
                session.cmds.connectAttr(file_node + '.outColor.outColorR',
                                         shader_name + '.displacementScalar')

            session.cmds.setAttr(shader_name + '.displacementAmount', 1.0)

            session.cmds.setAttr(
                shader_name + ".rman__riattr__displacementbound_sphere", 1.0)

            session.mel.eval('rmanSetAttr {sn} {val} 0;'.format(
                sn=shader_name, val='enableDisplacement'))

        # UNKNOWN
        else:
            raise EntityError("Don't know how to process map type: " +
                              maps_type)
Ejemplo n.º 10
0
    def import_product_representation(cls, session, representation, *args,
                                      **kwargs):

        product = representation.product_version.product

        if representation.type != "ma":
            raise EntityError(
                "Don't know how to import {cat} of type {typ}".format(
                    cat=cls.category, type=representation.type))

        repr_path = cls.get_import_file(session, product.name,
                                        product.category, representation)

        name = product.name
        instances = kwargs.get('instances', 1)
        instance_start = kwargs.get('instance_start', 0)
        exportable = kwargs.get('exportable', True)
        group_reference = kwargs.get('group_reference', False)

        entities_to_create = []

        if instances == 1 and instance_start == 0:
            session.cmds.file(repr_path,
                              reference=True,
                              groupReference=group_reference,
                              groupName=name,
                              mergeNamespacesOnClash=True,
                              namespace=":")
            if exportable:
                if group_reference:
                    entities_to_create.append((name, name, None))
                else:
                    ref_node = session.cmds.file(repr_path,
                                                 referenceNode=True,
                                                 query=True)
                    if not ref_node:
                        Logger.get().warning("No reference node found for " +
                                             repr_path)
                    else:
                        entities_to_create.append(
                            (cls._get_top_level_ref_objs(session, ref_node),
                             name, None))
        else:
            for inst in range(instance_start, instance_start + instances):
                inst_name = name + "_" + str(inst)
                session.cmds.file(repr_path,
                                  reference=True,
                                  groupReference=group_reference,
                                  groupName=inst_name,
                                  mergeNamespacesOnClash=True,
                                  namespace=":")
                if exportable:
                    if group_reference:
                        entities_to_create.append((inst_name, name, inst))
                    else:
                        ref_node = session.cmds.file(repr_path,
                                                     referenceNode=True,
                                                     query=True)
                        if not ref_node:
                            Logger.get().warning(
                                "No reference node found for " + repr_path)
                        else:
                            entities_to_create.append(
                                (cls._get_top_level_ref_objs(
                                    session, ref_node), name, inst))

        entities = []

        if exportable:
            for (obj_name, name, inst) in entities_to_create:
                set_name = cls.get_set_name(name, inst)
                session.cmds.sets(obj_name, name=set_name)

                entities.append(cls.get(name, session, instance=inst))

        return entities
Ejemplo n.º 11
0
    def import_product_representation(cls, session, representation, *args,
                                      **kwargs):

        if session.mari.projects.current():
            raise EntityError("Cannot have a project open when importing.")

        channel_config = session.ptask_area.config(cls.CHANNEL_CONFIG,
                                                   composite_ancestors=True)

        force_ptex = kwargs.get('force_ptex', False)

        if not channel_config or not hasattr(channel_config, 'channels'):
            raise EntityError(
                "Unable to find channel config for {cat} import.".format(
                    cat=cls.category))

        product_name = representation.product_version.product.name

        channels = []

        # create the channels
        for (channel_name,
             channel_options) in channel_config.channels.iteritems():

            # prepend the product name to the channel
            channel_name = product_name + '_' + channel_name

            # retrieve the channel options
            color_values = channel_options.get('color', [0.5, 0.5, 0.5, 1.0])
            color = session.mari.Color(*color_values[0:3])
            use_alpha = channel_options.get('alpha', True)
            depth = channel_options.get('depth', 16)

            channel = session.mari.ChannelInfo(channel_name,
                                               use_alpha=use_alpha,
                                               fill_color=color)
            channel.setDepth(depth)

            channels.append(channel)

        mari_dir = session.ptask_area.dir(dir_name='mari')

        # get a path to the geom product via the import directory
        geom_file = cls.get_import_file(session, product_name, cls.category,
                                        representation)

        # create the project
        if force_ptex:
            #session.mari.utils.message("Using Ptex!")
            EmptyChannels = []
            project_meta_options = dict()
            project_meta_options[
                "MappingScheme"] = session.mari.projects.FORCE_PTEX
            project_meta_options[
                "MultipleGeometries"] = session.mari.projects.MERGE_GEOMETRIES
            project_meta_options[
                "PtexFaceSizeScheme"] = session.mari.projects.PTEX_WORLD_SPACE_DENSITY_SIZE
            project_meta_options["PtexFaceSize"] = 16
            project_meta_options[
                "PtexImageFormat"] = session.mari.projects.PTEXFORMAT_BYTE
            project_meta_options["PtexFaceColor"] = session.mari.Color(
                0.5, 0.5, 0.5, 1)
            project_meta_options[
                "MergeType"] = session.mari.geo.MERGETYPE_SINGLE_MESH
            project_meta_options[
                "CreateSelectionSets"] = session.mari.geo.SELECTION_GROUPS_CREATE_FROM_FACE_GROUPS
            session.mari.projects.create(product_name, geom_file,
                                         EmptyChannels, EmptyChannels,
                                         project_meta_options)
        else:
            session.mari.projects.create(product_name, geom_file, channels)

            # now account for adjustment layers, etc.
            for (channel_name,
                 channel_options) in channel_config.channels.iteritems():

                # prepend the product name to the channel
                channel_name = product_name + '_' + channel_name

                # layers
                if 'layers' in channel_options:

                    for (layer_type, layer_options) in \
                        channel_options.layers.iteritems():

                        # adjustment layer
                        if layer_type == 'adjustment':
                            for (layer_name, adjustment_key) in \
                                layer_options.iteritems():

                                geo = session.mari.geo.current()
                                geo_channel = geo.channel(channel_name)
                                adjustment_layer = \
                                    geo_channel.createAdjustmentLayer(
                                        layer_name, adjustment_key)
                                adjustment_layer.setVisibility(False)

                        # other layer types...

        # close and archive the new project
        project = session.mari.projects.current()
        uuid = project.uuid()
        project.save(force_save=True)
        project.close(confirm_if_modified=False)

        # archive
        mari_file = os.path.join(mari_dir, product_name + '.mra')
        session.mari.projects.archive(uuid, mari_file)
        os.chmod(mari_file, 0770)
        session.mari.projects.open(uuid)
Ejemplo n.º 12
0
    def export(self, *args, **kwargs):
        """Export this entity to a product."""

        raise EntityError("Mari geom export not supported.")
Ejemplo n.º 13
0
    def import_product_representation(cls, session, representation, *args,
                                      **kwargs):

        if session.mari.projects.current():
            raise EntityError("Cannot have a project open when importing.")

        channel_config = session.ptask_area.config(cls.CHANNEL_CONFIG,
                                                   composite_ancestors=True)

        if not channel_config or not hasattr(channel_config, 'channels'):
            raise EntityError(
                "Unable to find channel config for {cat} import.".format(
                    cat=cls.category))

        product_name = representation.product_version.product.name

        channels = []

        # create the channels
        for (channel_name,
             channel_options) in channel_config.channels.iteritems():

            # prepend the product name to the channel
            channel_name = product_name + '_' + channel_name

            # retrieve the channel options
            color_values = channel_options.get('color', [0.5, 0.5, 0.5, 1.0])
            color = session.mari.Color(*color_values[0:3])
            use_alpha = channel_options.get('alpha', True)
            depth = channel_options.get('depth', 16)

            channel = session.mari.ChannelInfo(channel_name,
                                               use_alpha=use_alpha,
                                               fill_color=color)
            channel.setDepth(depth)

            channels.append(channel)

        mari_dir = session.ptask_area.dir(dir_name='mari')

        # get a path to the geom product via the import directory
        geom_file = cls.get_import_file(session, product_name, cls.category,
                                        representation)

        # create the project
        session.mari.projects.create(product_name, geom_file, channels)

        # now account for adjustment layers, etc.
        for (channel_name,
             channel_options) in channel_config.channels.iteritems():

            # prepend the product name to the channel
            channel_name = product_name + '_' + channel_name

            # layers
            if 'layers' in channel_options:

                for (layer_type, layer_options) in \
                    channel_options.layers.iteritems():

                    # adjustment layer
                    if layer_type == 'adjustment':
                        for (layer_name, adjustment_key) in \
                            layer_options.iteritems():

                            geo = session.mari.geo.current()
                            geo_channel = geo.channel(channel_name)
                            adjustment_layer = \
                                geo_channel.createAdjustmentLayer(
                                    layer_name, adjustment_key)
                            adjustment_layer.setVisibility(False)

                    # other layer types...

        # close and archive the new project
        project = session.mari.projects.current()
        uuid = project.uuid()
        project.save(force_save=True)
        project.close(confirm_if_modified=False)

        # archive
        mari_file = os.path.join(mari_dir, product_name + '.mra')
        session.mari.projects.archive(uuid, mari_file)
        os.chmod(mari_file, 0770)
        session.mari.projects.open(uuid)