def writeDatablock(bus, pluginModule, pluginName, propGroup, overrideParams):
    o = bus['output']
    scene = bus['scene']
    camera = bus['camera']

    VRayCamera = camera.data.vray
    CameraStereoscopic = VRayCamera.CameraStereoscopic

    # XXX: Some code is broken in VRayStereoscopicSettings
    # Export it only if we are use CameraStereoscopic to calculate views
    #
    if not CameraStereoscopic.use:
        return

    cam = bpy.data.objects.get(CameraStereoscopic.LeftCam)
    if cam:
        overrideParams['left_camera'] = LibUtils.CleanString(cam.name)

    cam = bpy.data.objects.get(CameraStereoscopic.RightCam)
    if cam:
        overrideParams['right_camera'] = LibUtils.CleanString(cam.name)

    # NOTE: Shademap is currently broken
    overrideParams['sm_mode'] = 0
    overrideParams['shademap_file'] = None

    return ExportUtils.WritePluginCustom(bus, pluginModule, pluginName,
                                         propGroup, overrideParams)
Exemple #2
0
def writeCamera(bus, camera, tm):
	o = bus['output']

	camName = LibUtils.CleanString(camera.name)

	o.set('CAMERA', 'RenderView', camName)
	o.writeHeader()
	o.writeAttibute("transform", tm)
	o.writeFooter()
    def execute(self, context):
        preset_menu_class = getattr(bpy.types, self.preset_menu)
        preset_type = preset_menu_class.preset_subdir

        presetSubdir = PathUtils.CreateDirectory(os.path.join(SysUtils.GetUserConfigDir(), "presets"))
        exportPath   = PathUtils.CreateDirectory(os.path.join(presetSubdir, preset_type))

        presetName = preset_menu_class.bl_label if self.remove_active else self.name

        fileName = "%s.vrscene" % LibUtils.CleanString(bpy.path.display_name(presetName))

        outputFilepath = os.path.normpath(os.path.join(exportPath, fileName))

        if self.remove_active:
            # NOTE: Remove function is locked to user config directory,
            # so system settings are safe

            debug.PrintInfo('Removing preset file: "%s"' % outputFilepath)
            if not os.path.exists(outputFilepath):
                return {'CANCELLED'}
            try:
                os.remove(outputFilepath)
            except:
                debug.PrintError('Error removing preset file: "%s"!' % outputFilepath)

            # Set default menu name
            preset_menu_class.bl_label = bpy.path.display_name(preset_type)

        else:
            bus = {
                'output' : VRayStream.VRaySimplePluginExporter(outputFilepath),
                'scene'  : context.scene,
                'camera' : context.scene.camera,
                'preview' : False,
            }

            pluginPresetIDs = None
            if preset_type == 'global':
                pluginPresetIDs = (pID for pID in sorted(PLUGINS['SETTINGS']))
            else:
                pluginPresetIDs = PresetTypePlugins[preset_type]

            for pluginID in pluginPresetIDs:
                pluginModule = PLUGINS_ID.get(pluginID)
                if pluginModule is None:
                    continue

                if not hasattr(context.scene.vray, pluginID):
                    continue

                propGroup = getattr(context.scene.vray, pluginID)

                ExportUtils.WritePlugin(bus, pluginModule, pluginID.lower(), propGroup, {})

        return {'FINISHED'}
Exemple #4
0
    def execute(self, context):
        VRayExporter = context.scene.vray.Exporter

        selectedNodeTree = VRayExporter.ntreeListIndex
        if selectedNodeTree == -1:
            return {'CANCELLED'}

        ntree = bpy.data.node_groups[selectedNodeTree]

        outputNode = NodesExport.GetOutputNode(ntree)
        if not outputNode:
            return {'CANCELLED'}

        exportPath = BlenderUtils.GetFullFilepath(
            VRayExporter.ntreeExportDirectory)
        exportPath = PathUtils.CreateDirectory(exportPath)

        fileName = "%s.vrscene" % LibUtils.CleanString(ntree.name)

        outputFilepath = os.path.normpath(os.path.join(exportPath, fileName))

        debug.PrintInfo('Exporting "%s" to: "%s"' %
                        (ntree.name, outputFilepath))

        o = VRayStream.VRaySimplePluginExporter(outputFilepath)

        exporter = _vray_for_blender.init(
            engine=0,
            context=bpy.context.as_pointer(),
            scene=bpy.context.scene.as_pointer(),
            data=bpy.data.as_pointer(),
            mainFile=o.output,
            objectFile=o.output,
            envFile=o.output,
            geometryFile=o.output,
            lightsFile=o.output,
            materialFile=o.output,
            textureFile=o.output,
            drSharePath="",
        )

        for sock in outputNode.inputs:
            conNode = NodesExport.GetConnectedNode(ntree, sock)
            if conNode:
                _vray_for_blender.exportNode(ntree.as_pointer(),
                                             conNode.as_pointer(),
                                             sock.as_pointer())

        _vray_for_blender.exit(exporter)

        return {'FINISHED'}
Exemple #5
0
    def execute(self, context):
        VRayScene = context.scene.vray
        BatchBake = VRayScene.BatchBake
        VRayBake = VRayScene.BakeView

        # Copy selection
        selection = [ob for ob in context.selected_objects]

        formatDict = LibUtils.GetDefFormatDict()

        obList = None
        if BatchBake.work_mode == 'SELECTION':
            obList = selection
        elif BatchBake.work_mode == 'LIST':
            obList = [
                item.ob for item in BatchBake.list_items
                if item.use and item.ob
            ]

        numObjects = len(obList)

        # Backup some settings
        ValueBackup(VRayScene.SettingsOutput, 'img_dir')
        ValueBackup(VRayScene.SettingsOutput, 'img_file')
        ValueBackup(VRayScene.Exporter, 'autoclose')
        ValueBackup(VRayScene.Exporter, 'auto_save_render')

        if numObjects:
            VRayScene.Exporter.auto_save_render = True

            # We have to wait for render end
            # only if baking multiple objects
            if numObjects > 1:
                VRayScene.Exporter.wait = True
                VRayScene.Exporter.autoclose = True

            try:
                for ob in obList:
                    debug.PrintInfo("Baking: %s..." % ob.name)
                    VRayScene.Exporter.currentBakeObject = ob

                    # UV channel to use for baking
                    uv_channel = None

                    # Find UV map index
                    if BatchBake.uv_map == 'UV_DEFAULT':
                        if len(ob.data.uv_layers):
                            uv_channel = 0

                    elif BatchBake.uv_map == 'UV_VRAYBAKE':
                        uv_channel = GetUVChannelIndex(ob, "VRayBake")

                    # Add projection if need
                    elif BatchBake.uv_map.startswith('UV_NEW_'):
                        uvName = None
                        if BatchBake.uv_map == 'UV_NEW_SMART':
                            uvName = "VRayBakeSmart"
                        elif BatchBake.uv_map == 'UV_NEW_LM':
                            uvName = "VRayBakeLightmap"

                        uv_channel = GetUVChannelIndex(ob, uvName)
                        if uv_channel is None:
                            if ob.mode in {'EDIT'}:
                                bpy.ops.object.mode_set(mode='OBJECT')

                            bpy.ops.object.select_all(action='DESELECT')

                            ob.select = True
                            context.scene.objects.active = ob

                            if BatchBake.uv_map == 'UV_NEW_SMART':
                                bpy.ops.object.mode_set(mode='EDIT')
                                bpy.ops.mesh.select_all(action='SELECT')

                                layer = ob.data.uv_textures.new(name=uvName)
                                layer.active = True

                                bpy.ops.uv.smart_project(
                                    angle_limit=BatchBake.smart_uv.angle_limit,
                                    island_margin=BatchBake.smart_uv.
                                    island_margin,
                                    user_area_weight=BatchBake.smart_uv.
                                    user_area_weight,
                                )

                                bpy.ops.mesh.select_all(action='DESELECT')
                                bpy.ops.object.mode_set(mode='OBJECT')

                            elif BatchBake.uv_map == 'UV_NEW_LM':
                                bpy.ops.uv.lightmap_pack(
                                    PREF_CONTEXT='ALL_FACES',
                                    PREF_NEW_UVLAYER=True,
                                    PREF_BOX_DIV=BatchBake.lightmap_uv.
                                    PREF_BOX_DIV,
                                    PREF_MARGIN_DIV=BatchBake.lightmap_uv.
                                    PREF_MARGIN_DIV,
                                )
                                ob.data.uv_textures[-1].name = uvName

                            uv_channel = len(ob.data.uv_textures) - 1

                    if uv_channel is None:
                        debug.PrintError("UV Map is not found!")
                        continue

                    # Bake settings
                    VRayScene.BakeView.bake_node = ob.name
                    VRayScene.BakeView.uv_channel = uv_channel

                    # Setup vars
                    formatDict['$O'] = ("Object Name",
                                        LibUtils.CleanString(ob.name,
                                                             stripSigns=False))

                    # Render
                    VRayScene.SettingsOutput.img_file = LibUtils.FormatName(
                        BatchBake.output_filename, formatDict)
                    VRayScene.SettingsOutput.img_dir = LibUtils.FormatName(
                        BatchBake.output_dirpath, formatDict)

                    bpy.ops.render.render()

            except Exception as e:
                debug.PrintError("Erorr baking objects!")
                debug.ExceptionInfo(e)

        # Restore selection
        for ob in selection:
            ob.select = True

        RestoreSettings(context.scene)

        return {'FINISHED'}
Exemple #6
0
def GetNodeName(ntree, node):
    return LibUtils.CleanString("NT%sN%s" % (ntree.name, node.name))
def proxy_save_materials():

    #scene > node tools > path same than proxy export path
    GeomMeshFile = bpy.context.object.data.vray.GeomMeshFile
    outputDirpath = BlenderUtils.GetFullFilepath(GeomMeshFile.dirpath)
    bpy.context.scene.vray.Exporter.ntreeExportDirectory = PathUtils.CreateDirectory(
        outputDirpath)

    print()
    print("outputDirpath:", outputDirpath)
    print()

    o = bpy.context.object

    filenames = []
    nodenames = []
    proxyname = o.data.vray.GeomMeshFile.filename

    #change node names
    for i, mat in enumerate(o.data.materials):

        nodename = mat.vray.ntree.name
        nodenames.append(nodename)

        #get Material Output, check node type and change node name for later material slot order
        nodeindex = nodes_iterate(mat, True)
        mat.vray.ntree.nodes[nodeindex].name = SLOT + str(i)

        #print (i)
        #print (mat.name)
        #print ("nodename:", nodename)
        #mat.vray.ntree.name = proxyname + "_ProxyMat_" + mat.name + "_slot_" + str(i)

        #not sure about this
        #mat.vray.ntree.name = proxyname + SLOT + str(i)

        #print ("new nodename:",mat.vray.ntree.name)

        filenames.append(
            os.path.join(
                outputDirpath,
                LibUtils.CleanString(mat.vray.ntree.name) + '.vrscene'))

    #save nodes
    print("Saving...")
    for mat in o.data.materials:

        nodename = mat.vray.ntree.name
        print("Saving nodename:", nodename)
        i = bpy.data.node_groups.find(nodename)
        bpy.context.scene.vray.Exporter.ntreeListIndex = i
        bpy.ops.vray.export_nodetree()

    #change node names back to original
    for i, mat in enumerate(o.data.materials):
        mat.vray.ntree.name = nodenames[i]

    #print filenames

    for name in filenames:
        print("Filename:", name)

    proxy_files_join(outputDirpath, filenames, proxyname)

    print(len(o.data.materials), ": materials saved")
    def execute(self, context):
        sce = context.scene

        # Use current active object UI for initial settings
        ob = bpy.context.object
        selection = bpy.context.selected_objects
        oneObject = len(selection)

        GeomMeshFile = ob.data.vray.GeomMeshFile

        # Create output path
        outputIsRelative = BlenderUtils.IsPathRelative(GeomMeshFile.dirpath)

        outputDirpath = BlenderUtils.GetFullFilepath(GeomMeshFile.dirpath)
        outputDirpath = PathUtils.CreateDirectory(outputDirpath)

        # Create tmp export file
        vrsceneFilepath = os.path.join(tempfile.gettempdir(), "vrmesh.vrscene")
        vrsceneFile = open(vrsceneFilepath, 'w')

        # Settings
        frames = None
        frameStart = 1
        frameStep = 1
        if GeomMeshFile.animation not in {'NONE'}:
            if GeomMeshFile.animation == 'MANUAL':
                frameStart = GeomMeshFile.frame_start
                frames = (frameStart, GeomMeshFile.frame_end, 1)
            else:
                frameStart = sce.frame_start
                frameStep = sce.frame_step
                frames = (sce.frame_start, sce.frame_end, sce.frame_step)

        applyTm = GeomMeshFile.apply_transforms
        useVelocity = GeomMeshFile.add_velocity

        # Export objects meshes and generate nodes name list
        obPluginNames = []
        o = VRayStream.VRaySimplePluginExporter(outputFile=vrsceneFile)

        exporter = _vray_for_blender.init(
            engine=0,
            context=bpy.context.as_pointer(),
            scene=sce.as_pointer(),
            data=bpy.data.as_pointer(),
            mainFile=o.output,
            objectFile=o.output,
            envFile=o.output,
            geometryFile=o.output,
            lightsFile=o.output,
            materialFile=o.output,
            textureFile=o.output,
            drSharePath="",
        )

        _vray_for_blender.initAnimation(True, frameStart, 1)

        _vray_for_blender.setFrame(frameStart)

        for ob in selection:
            if ob.type in BlenderUtils.NonGeometryTypes:
                continue
            nodeName = None
            if not frames:
                nodeName = ExportMeshSample(o, ob)
            else:
                sce = bpy.context.scene
                frame_current = sce.frame_current
                for f in range(frames[0], frames[1] + frames[2], frames[2]):
                    bpy.context.scene.frame_set(f)
                    _vray_for_blender.setFrame(f)
                    nodeName = ExportMeshSample(o, ob)
                    _vray_for_blender.clearCache()
                sce.frame_set(frame_current)
            obPluginNames.append([ob, nodeName])
        o.done()
        vrsceneFile.close()

        _vray_for_blender.clearFrames()
        _vray_for_blender.exit(exporter)

        # Launch the generator tool
        err = None
        for ob, nodeName in obPluginNames:
            vrmeshName = LibUtils.CleanString(ob.name)
            if oneObject and GeomMeshFile.filename:
                vrmeshName = GeomMeshFile.filename
            vrmeshName += ".vrmesh"
            vrmeshFilepath = os.path.join(outputDirpath, vrmeshName)

            err = LaunchPly2Vrmesh(vrsceneFilepath, vrmeshFilepath, nodeName,
                                   frames, applyTm, useVelocity)
            if err is not None:
                break

            if GeomMeshFile.proxy_attach_mode != 'NONE':
                attachOb = ob

                if GeomMeshFile.proxy_attach_mode == 'NEW':
                    newName = '%s@VRayProxy' % ob.name
                    newMesh = bpy.data.meshes.new(newName)
                    attachOb = bpy.data.objects.new(newName, newMesh)

                    context.scene.objects.link(attachOb)

                BlenderUtils.SelectObject(attachOb)

                if GeomMeshFile.proxy_attach_mode == 'NEW':
                    for slot in ob.material_slots:
                        if slot and slot.material:
                            attachOb.data.materials.append(slot.material)
                            attachOb.material_slots[-1].link = 'OBJECT'
                            attachOb.material_slots[
                                -1].material = slot.material

                if GeomMeshFile.apply_transforms:
                    bpy.ops.object.transform_apply(location=True,
                                                   rotation=True,
                                                   scale=True)
                else:
                    attachOb.matrix_world = ob.matrix_world

                CreateProxyNodetree(attachOb, vrmeshFilepath, outputIsRelative)

                if GeomMeshFile.proxy_attach_mode in {'NEW', 'REPLACE'}:
                    LoadProxyPreviewMesh(attachOb, vrmeshFilepath,
                                         GeomMeshFile.anim_type,
                                         GeomMeshFile.anim_offset,
                                         GeomMeshFile.anim_speed,
                                         context.scene.frame_current - 1)

        # Remove temp export file
        os.remove(vrsceneFilepath)

        if err:
            self.report({'ERROR'},
                        "Error generating VRayProxy! Check system console!")
            debug.PrintError(err)
            return {'CANCELLED'}

        self.report({'INFO'}, "Done creating proxy!")

        return {'FINISHED'}
    def execute(self, context):
        if not self.asset_name:
            self.report({'ERROR'}, "Asset name is not set!")
            return {'CANCELLED'}

        presetsPath       = PathUtils.CreateDirectory(os.path.join(SysUtils.GetUserConfigDir(), "presets"))
        userNodeAssetPath = PathUtils.CreateDirectory(os.path.join(presetsPath, self.asset_type))

        fileName = "%s.vrscene" % LibUtils.CleanString(bpy.path.display_name(self.asset_name))

        outputFilepath = os.path.normpath(os.path.join(userNodeAssetPath, fileName))

        # Create exporter (output)
        o = VRayStream.VRaySimplePluginExporter(outputFilepath)

        exporter = _vray_for_blender.init(
            engine  = 0,
            context = bpy.context.as_pointer(),
            scene   = bpy.context.scene.as_pointer(),
            data    = bpy.data.as_pointer(),

            mainFile     = o.output,
            objectFile   = o.output,
            envFile      = o.output,
            geometryFile = o.output,
            lightsFile   = o.output,
            materialFile = o.output,
            textureFile  = o.output,

            drSharePath = "",
        )

        # Get selected nodes
        ntree        = context.space_data.edit_tree
        selectedNode = context.selected_nodes[0]

        if selectedNode.bl_idname == 'VRayNodeRenderChannels':
            pluginNames = []

            for inSock in selectedNode.inputs:
                pluginNames.append(NodesExport.WriteConnectedNode(None, ntree, inSock))

            pluginName = "List(%s)" % ",".join(pluginNames)

        else:
            if selectedNode.bl_idname == 'VRayNodeOutputMaterial':
                selectedNode = NodesExport.GetConnectedNode(ntree, selectedNode.inputs['Material'])

            pluginName = _vray_for_blender.exportNode(
                ntree.as_pointer(),
                selectedNode.as_pointer(),
                None
            )

        # Write fake Asset node
        o.set('MAIN', 'Asset', self.asset_type.capitalize())
        o.writeHeader()
        o.writeAttibute(self.asset_type, pluginName)
        o.writeFooter()
        o.done()

        _vray_for_blender.exit(exporter)

        return {'FINISHED'}