exportar módulo
Este módulo expõe funções para exportar ativos (texturas e malhas) de um projeto em vários formatos. É o equivalente a scripts das janelas “Exportar texturas” e “Exportar malha”.
Para as texturas de exportação, a configuração de exportação é definida com um arquivo JSON, mas também pode usar predefinições de exportação existentes.
classe substance_painter.export.ExportStatus(valor) substance_painter.export.ExportStatus
Código de status do processo de exportação.
Membros:
SuccessCancelledWarningErrorExportar texturas
substance_painter.export.list_project_textura(json_config: dict) -> Dict[Tupla[str, str], Lista[str]] substance_painter.export.list_project_textures
Obtém a lista de texturas que seriam exportadas de acordo com a configuração JSON fornecida.
Parâmetros:
json_config (dict) - objeto JSON que representa a configuração de exportação a ser usada. Consulte configuração de JSON.
Retorna:
Lista de arquivos de textura que serão exportados, agrupados por pilha (nome do Conjunto de Texturas, nome da pilha).
Tipo de retorno: Dito[Tupla[ str, str], Lista[ str]]
Aumentos:
- ProjectError - Se nenhum projeto estiver aberto.
- ValueError - Se
json_configestiver mal formado ou for inválido no contexto do projeto atual. Contém uma mensagem legível.
export_project_textures().class substance_painter.export.TextureExportResult(status: ExportStatus, mensagem: str, textura: Dict[Tupla[str, str], Lista[str]]) substance_painter.export.TextureExportResult
Resultado do processo de exportação de texturas
Parâmetros:
- status (ExportStatus) - Código de status.
- mensagem (str) - Mensagem de status legível.
- textura (Dict [ Tupla [str**, str*] ,* Lista*[ str ]]*) - Lista de arquivos de textura gravados no disco, agrupados por pilha (nome do Conjunto de Texturas, nome da pilha).
substance_painter.export.export_project_textura(json_config: dict) -> TextureExportResult substance_painter.export.export_project_textures
Exportar texturas de documento de acordo com a configuração JSON fornecida. O valor de retorno contém a lista de arquivos de textura gravados no disco.
O status do valor de retorno nunca pode ser Erro. Qualquer erro que faça com que a exportação falhe levantará uma exceção. No entanto, se a exportação falhar, o evento associado ExportTextureEnded receberá, de fato, Erro como status. Se a exportação for cancelada pelo usuário, o valor de retorno da função terá o status Cancelado e conterá a lista de arquivos de textura gravados no disco antes do cancelamento da exportação.
Parâmetros:
json_config (dict) -
Objeto JSON que representa a configuração de exportação a ser usada. Consulte configuração de JSON.
Retorna: Resultado do processo de exportação.
Tipo de retorno: TextureExportResult
Aumentos:
- ProjectError - Se nenhum projeto estiver aberto.
- ValueError - Se
json_configestiver mal formado ou for inválido no contexto do projeto atual. Contém uma mensagem legível detalhando o problema.
Exemplo:
import substance_painter.export
# Open a project we want to export from (see substance_painter.project
# for details). This step is not necessary if there is already a project
# opened in Substance 3D Painter.
import substance_painter.project
substance_painter.project.open("C:/projects/MeetMat.spp")
# Choose an export preset to use (see substance_painter.resource). This
# step is not mandatory as you can alternatively describe the export
# preset entirely in JSON (see the full example at the bottom of the
# page).
# Note: in this example the preset file format and bit depth are
# overridden below for '03_Base', but otherwise follow the export preset
# configuration.
import substance_painter.resource
export_preset = substance_painter.resource.ResourceID(
context="starter_assets", name="Arnold (AiStandard)")
# Set the details of the export (a comprehensive example of all the
# configuration options is presented at the bottom of the page):
export_config = {
"exportShaderParams": False,
"exportPath": "C:/export",
"defaultExportPreset" : export_preset.url(),
"exportList": [
{
"rootPath": "01_Head"
},
{
"rootPath": "02_Body"
},
{
"rootPath": "03_Base"
}],
"exportParameters": [
# No filters: those parameters apply to all exported maps
{
"parameters": {
"dithering": True,
"paddingAlgorithm": "infinite"
}
},
# Force file format and bitDepth for all maps in '03_Base'
{
"filter": {"dataPaths": ["03_Base"]},
"parameters": {
"fileFormat" : "png",
"bitDepth" : "8"
}
},
# Force 2K size for all maps in '01_Head'
{
"filter": {"dataPaths": ["01_Head"]},
"parameters": {
"sizeLog2": 11
}
}]
}
# Display the list of textures that should be exported, according to the
# configuration:
export_list = substance_painter.export.list_project_textures(export_config)
for k,v in export_list.items():
print("Stack {0}:".format(k))
for to_export in v:
print(to_export)
# Actual export operation:
export_result = substance_painter.export.export_project_textures(export_config)
# In case of error, display a human readable message:
if export_result.status != substance_painter.export.ExportStatus.Success:
print(export_result.message)
# Display the details of what was exported:
for k,v in export_result.textures.items():
print("Stack {0}:".format(k))
for exported in v:
print(exported)
substance_painter.export.get_default_export_path() -> str substance_painter.export.get_default_export_path
Obtenha o caminho de exportação padrão do aplicativo usado para exportar texturas. Esse caminho não depende do projeto e é o valor padrão usado ao criar um novo projeto.
Retorna: o caminho de exportação padrão do aplicativo.
Tipo de retorno: str
class substance_painter.export.PredefinedExportPreset(nome: str, url: str) substance_painter.export.PredefinedExportPreset
Uma predefinição de exportação (modelo de saída) controla o comportamento do processo de exportação. Uma predefinição tem uma lista dinâmica de mapas exportados dependendo do projeto e pode ter processos de pré/pós que geram dados personalizados (por exemplo, glTF). Esse tipo de predefinição de exportação é incorporado no aplicativo e não pode ser editado.
Exemplo:
import substance_painter.export
import substance_painter.project
import substance_painter.textureset
# A project needs to be opened to introspect the output maps of a predefined export preset
substance_painter.project.open("C:/projects/MeetMat.spp")
# Retrieve all predefined export presets
predefined_presets = substance_painter.export.list_predefined_export_presets()
# Retrieve data of the first preset
predefined_preset = predefined_presets[0]
print("Name: " + predefined_preset.name + ", url: " + predefined_preset.url)
stack = substance_painter.textureset.get_active_stack()
print(predefined_preset.list_output_maps(stack))
Parâmetros:
- nome (str) - O nome da predefinição.
- url (str) - A URL da predefinição.
list_output_maps(stack: Stack) -> list substance_painter.export.PredefinedExportPreset.list_output_maps
Obtenha a lista de mapas de saída com base nos canais disponíveis na pilha fornecida. Os mapas de saída têm o mesmo formato que a lista maps na configuração JSON.
Parâmetros: pilha (substance_painter.textureset.Stack) - A pilha da qual obter os mapas de saída.
Retorna:
A lista de mapas de saída nos canais disponíveis na pilha fornecida. Os mapas de saída têm o mesmo formato que a lista maps na configuração JSON. Consulte configuração de JSON.
Tipo de retorno: dict
Aumentos:
- ProjectError - Se nenhum projeto estiver aberto.
- ValueError - Se a pilha fornecida for inválida.
substance_painter.texturesetsubstance_painter.export.list_predefined_export_presets() -> List[PredefinedExportPreset] substance_painter.export.list_predefined_export_presets
Obtenha a lista de predefinições de exportação predefinidas (modelos de saída).
Retorna: a lista de predefinições de exportação predefinidas.
Tipo de retorno: Lista[PredefiniçãoExportarPredefinição]
PredefinedExportPresetclass substance_painter.export.ResourceExportPreset(resource_id: ResourceID) substance_painter.export.ResourceExportPreset
Uma predefinição de exportação (modelo de saída) controla o comportamento do processo de exportação. Uma predefinição de exportação de prateleira é um recurso com Export substance_painter.resource.Type. Ele pode ser modificado pelo usuário por meio da interface do usuário.
Exemplo:
import substance_painter.export
import substance_painter.project
substance_painter.project.open("C:/projects/MeetMat.spp")
# Retrieve all resource export presets
resource_presets = substance_painter.export.list_resource_export_presets()
# Retrieve PBR Metalllic Roughness export preset
preset = ""
match = "PBR Metallic Roughness"
for resource_preset in resource_presets :
if resource_preset.resource_id.name == "PBR Metallic Roughness":
print("Name: {}, url: {}".format(
resource_preset.resource_id.name,
resource_preset.resource_id.url()))
preset = resource_preset
break
maps = preset.list_output_maps()
# Add new output map 2D View
maps.append({
'channels': [{
'destChannel': 'R',
'srcChannel': 'R',
'srcMapName': 'View_2D',
'srcMapType': 'virtualMap',
'srcPath': ''
}, {
'destChannel': 'G',
'srcChannel': 'G',
'srcMapName': 'View_2D',
'srcMapType': 'virtualMap',
'srcPath': ''
}, {
'destChannel': 'B',
'srcChannel': 'B',
'srcMapName': 'View_2D',
'srcMapType': 'virtualMap',
'srcPath': ''
}, {
'destChannel': 'A',
'srcChannel': 'A',
'srcMapName': 'View_2D',
'srcMapType': 'virtualMap',
'srcPath': ''
}],
'fileName':
'$mesh_$textureSet_2D_View',
'parameters': {
'bitDepth': '8',
'dithering': False,
'fileFormat': 'png'
}
})
# Create a new preset
newPresetName = "PBR Metallic Roughness 2D View"
newPreset = {
"name": newPresetName,
"maps": maps
}
# Use the preset in the export configuration
export_config = {
"exportShaderParams": False,
"exportPath": "C:/export",
"defaultExportPreset" : newPresetName,
"exportPresets": [newPreset],
"exportList": [
{
"rootPath": "01_Head"
},
{
"rootPath": "02_Body"
},
{
"rootPath": "03_Base"
}],
"exportParameters": [
{
"parameters": {
"dithering": True,
"paddingAlgorithm": "infinite"
}
}]
}
substance_painter.export.export_project_textures(export_config)
Parâmetros: resource_id (ResourceID) - A ID de recurso da predefinição de exportação.
substance_painter.resource, Criar predefinições de exportação.list_output_maps() -> list substance_painter.export.ResourceExportPreset.list_output_maps
Obtém a lista de mapas de saída para a predefinição especificada. Os mapas de saída têm o mesmo formato que a lista maps na configuração JSON.
Retorna:
A lista de mapas de saída para a predefinição especificada. Os mapas de saída têm o mesmo formato que a lista maps na configuração JSON. Consulte configuração de JSON.
Tipo de retorno: dict
Gerações: ValueError - Se a predefinição fornecida for inválida.
substance_painter.export.list_resource_export_presets() -> List[ResourceExportPreset] substance_painter.export.list_resource_export_presets
Obtenha a lista de predefinições de exportação (modelos de saída). Essa lista contém todas as predefinições de exportação disponíveis nas prateleiras (predefinições fornecidas por padrão e personalizadas, se houver).
Retorna: a lista de predefinições de exportação.
Tipo de retorno: Lista[ResourceExportPreset]
ResourceExportPresetPossibilidades completas de dict json_config
{
// Path to the root folder where texture files will be exported.
"exportPath": "C:/export",
// Whether to export shader instances to a JSON file.
"exportShaderParams": true,
// (optional) Export preset to be used when no export preset is provided in
// "exportList.exportPreset".
// The value can be the name of a preset defined in the "exportPresets" part
// of the configuration JSON:
"defaultExportPreset": "preset1",
// Alternatively the value can be a URL to an existing preset file (see
// substance_painter.resource) listed in the export dialog:
// "defaultExportPreset" : substance_painter.resource.ResourceID(
// context="starter_assets",
// name="PBR Metallic Roughness").url(),
// (optional) List of export presets definitions.
"exportPresets": [
{
// Defines the name of the export preset. This name can be referenced in
// "defaultExportPreset" and/or "exportList.exportPreset".
"name": "preset1",
// List of maps making up this export preset.
"maps": [
{
// Filename of the texture file written to disk; may contain wildcards
// resolved at export time.
// (e.g. "$project_$mesh_$textureSet_$udim_$sceneMaterial_BaseColor")
//
// $colorSpace: Current color space.
// $mesh: Filename of the imported mesh.
// $project: Project name.
// $sceneMaterial: Current material name, as found in the imported
// mesh.
// $textureSet: Current Texture Set.
// $udim: Current UV Tile (e.g. 1001).
// $uvTileName: Current UV Tile name.
"fileName": "$textureSet_color",
// List of source/destination defining which channels will make up the
// texture file.
"channels": [
{
// Channel to write to.
// L (Luminance), R (Red), G (Green), B (Blue), A (Alpha)
//
// In addition to alpha channel, either R+G+B must be specified, or
// either L only.
"destChannel": "R",
// Channel to read from.
// L, R, G, B, A
//
// When the source map is color, L will generate a mix of R+G+B.
"srcChannel": "R",
// The type of map to read from:
// documentMap: Maps present in the document (e.g. "baseColor").
// meshMap: Baked mesh maps (e.g. "normal").
// virtualMap: Generated map (e.g. "f0").
// defaultMap: Constant color (e.g. "black").
"srcMapType": "documentMap",
// Name of the map of type scrMapType.
//
// For type documentMap:
// basecolor, height, specular, opacity, emissive, displacement,
// glossiness, roughness, anisotropylevel, anisotropyangle,
// transmissive, scattering, reflection, ior, metallic, normal,
// ambientOcclusion, diffuse, specularlevel, blendingmask, user0,
// user1, user2, user3, user4, user5, user6, user7.
//
// For type meshMap:
// ambient_occlusion, id, curvature, normal_base,
// world_space_normals, position, thickness.
//
// For type virtualMap:
// Normal_OpenGL, Normal_DirectX, AO_Mixed, Diffuse, Specular,
// Glossiness, Unity4Diff, Unity4Gloss, reflection, 1/ior,
// Glossiness2, f0, View_2D.
//
// For type defaultMap:
// black, white.
"srcMapName": "baseColor"
}
],
// (optional) Export parameters to be used for this export preset map.
//
// When "parameters" is not provided, the existing parameters are used.
// When "parameters" is provided, it overrides the existing parameters.
//
// Each individual parameter is optional and, when defined, overrides
// previously defined parameters. See in exportList.parameters how the
// rules are applied.
//
// It is important to understand that even though this section is
// optional, if after evaluating all the rules some parameters remain
// undefined, the configuration is invalid.
"parameters": {
// (optional) File format (and file extension) of the generated
// texture file.
"fileFormat": "png",
// (optional) Bit depth.
//
// The bit depth must be supported by the file format.
"bitDepth": "16",
// (optional) Whether to use dithering.
"dithering": False,
// (optional) Size of the texture file in log2.
// (i.e. 10 means 2^10 = 1024)
//
// When "sizeLog2" is not provided, the texture size from the project
// is used.
//
// It can either be a single integer, or an array of two integers.
//
// If it's a single integer, it represents the biggest of width and
// height, and will maintain the aspect ratio.
// (i.e. 10 means a 2048x4086 map will be exported as 512x1024)
//
// If it's an array of two integers, the original aspect ratio will be
// ignored.
// (i.e. [10, 12] means a 2048x4086 map will be exported as 1024x4096)
"sizeLog2": 10,
// (optional) Padding algorithm used to fill holes in rendered
// texture.
//
// The possible values are:
// passthrough, color, transparent, diffusion, infinite.
"paddingAlgorithm": "diffusion",
// (optional) When padding algorithm needs it, distance in pixels used
// by the padding algorithm.
//
// Dilation distance is needed for transparent, color and diffusion
// padding algorithms.
"dilationDistance": 16
}
}
]
}
],
// List of subparts of the document to export.
"exportList": [
{
// Root path of the document structure this subpart applies to.
//
// For Texture Sets without stacks, this is a Texture Set name.
// (e.g. "O1_Head")
// For Texture Sets with stacks, this is Texture Set name + stack name
// separated by /
"rootPath": "02_Body/Mask",
// (optional) In the selected rootPath, which maps to export.
//
// When "filter" is not provided, export everything.
"filter": {
// Which maps to export, as an array of map names.
//
// The map names are to be used as defined in
// exportPresets.maps.fileName, including wildcards.
// (e.g. ["$textureSet_color", "$textureSet_normal"])
"outputMaps": [
"$textureSet_color"
],
// Which UV Tiles to export, as an array of tile coordinates.
// A tile coordinate is a 2 dimensional array of U and V coordinates.
// (e.g. [[1, 1], [1, 2]] to export tiles U=1, V=1 and U=1, V=2)
"uvTiles": [
[
1,
1
]
]
},
// (optional) Export preset to use. If undefined, fall back to
// "defaultExportPreset" value.
// The value can be the name of a preset defined in "exportPresets":
"exportPreset": "preset1"
// Alternatively the value can be a URL to an existing preset file (see
// substance_painter.resource) listed in the export dialog:
// "defaultExportPreset" : substance_painter.resource.ResourceID(
// context="starter_assets",
// name="PBR Metallic Roughness").url(),
}
],
// List of rules used to override export parameters of texture files.
//
// For each exported texture file, the export process will go through this
// list, in the order they are provided, to override export parameters.
// Available export parameters are:
// fileFormat, bitDepth, dithering, sizeLog2, paddingAlgorithm and
// dilationDistance.
// (see exportPresets.map.parameters)
//
// For each possible export parameter of each texture file:
// First, the parameter is initialized with the value provided by the
// exportPreset.maps.parameters, if any.
// Then, the export process iterates the rules of exportParameters and tries
// to match the texture file with the filter.
// If the filter matches, the parameter is overridden by this rule, else it
// stays untouched.
//
// At the end of the process, every parameter of every texture file must be
// defined for the export process to be able to continue.
// To achieve this, a good practice may be to define a default value for all
// the parameters:
// - For each preset map
// - With a global exportParameters rule using a filter that always matches
"exportParameters": [
{
// (optional) Select which texture files match the current rule.
// (i.e. for which texture files this rule will override parameters)
//
// When "filter" is not provided, select everything.
//
// Examples:
// Filter that matches all:
// "filter" : {}
//
// Filter that matches some Texture Sets:
// "filter" : {"dataPaths": ["01_Head", "02_Body"]}
//
// Filter that matches some outputMaps:
// "filter" : {"outputMaps": ["$textureSet_color"]}
//
// Filter that matches nothing:
// "filter" : {"dataPaths": []}
//
// Use of a combined filter to match a Texture Set for some
// outputMaps:
// "filter" : {"dataPaths": ["01_Head"],
// "outputMaps" : ["$textureSet_color"]}
"filter": {
// List of rootPaths to match.
//
// This can be a mix of:
// - Texture Set names only, even for Texture Sets with stacks
// - Stack names, when stacks are used
"dataPaths": [
"01_Head",
"02_Body/Mask"
],
// List of map names to match.
//
// The map names are to be used as defined in "exportPresets.maps.fileName",
// including wildcards.
"outputMaps": [
"$textureSet_color"
],
// List of UV Tiles to match, as an array of tile coordinates.
// A tile coordinate is a 2 dimensional array of U and V coordinates.
// (e.g. [[1, 1], [1, 2]] to export tiles U=1, V=1 and U=1, V=2)
"uvTiles": [
[
1,
1
]
]
},
// (optional) Parameters to apply to the matched texture files as per the
// current rule.
//
// When "parameters" is not provided, the existing parameters are used.
// When "parameters" is provided, it overrides the existing parameters.
//
// Each individual parameter is optional and, when defined, overrides
// previously defined parameters (coming from the selected preset).
//
// It is important to understand that even though this section is
// optional, if after evaluating all the rules some parameters remain
// undefined, the configuration is invalid.
//
// In this example, we're setting a different texture size for the color
// map of both 01_Head and 02_Body/Mask, leaving settings on maps and
// other data paths, and leaving the other parameters untouched.
"parameters": {
"sizeLog2": 11
}
}
]
}
Eventos
Exportar texturas, seja iniciado por meio da API Python ou na interface do usuário, pode acionar os seguintes eventos. Consulte substance_painter.event para obter mais detalhes.
class substance_painter.event.ExportTexturesAboutToStart(textura: Dict[Tupla[str, str], Lista[str]])
Evento acionado logo antes de uma exportação do textura.
Parâmetros:
textura (Dict [ Tupla [str**, str*] ,* Lista*[ str ]]*) - Lista de arquivos de textura a serem gravados no disco, agrupados por pilha (nome do Conjunto de Texturas, nome da pilha).
class substance_painter.event.ExportTexturesEnded(status: ExportStatus, mensagem: str, textura: Dict[Tupla[str, str], Lista[str]])
Evento disparado após a conclusão da exportação para textura.
Parâmetros:
- status (ExportStatus) - Código de status.
- mensagem (str) - Mensagem de status legível.
- textura (Dict [ Tupla [str**, str*] ,* Lista*[ str ]]*) - Lista de arquivos de textura gravados no disco, agrupados por pilha (nome do Conjunto de Texturas, nome da pilha).
Exportar malha
substance_painter.export.scene_is_triangulated() -> bool substance_painter.export.scene_is_triangulated
Verifique se a cena tem apenas triângulos (polígonos com apenas 3 lados).
Retorna: True se a cena atual tiver apenas triângulos; caso contrário, retorna False.
Tipo de retorno: bool
Gerações: ProjectError - Se nenhum projeto estiver aberto.
substance_painter.export.scene_has_tessellation() -> bool substance_painter.export.scene_has_tessellation
Verifique se a cena tem deslocamento/mosaico ativado.
Retorna: True se a cena atual tiver deslocamento/mosaico; caso contrário, retorna False.
Tipo de retorno: bool
Gerações: ProjectError - Se nenhum projeto estiver aberto.
class substance_painter.export.MeshExportOption(value) substance_painter.export.MeshExportOption
Opções disponíveis para a exportação em malha.
Membros:
BaseMeshTriangulatedMeshTessellationNormalsBaseMeshTessellationRecomputeNormalsclasse substance_painter.export.MeshExportResult(status: ExportStatus, mensagem: str) substance_painter.export.MeshExportResult
Resultado do processo de malha de exportação
Parâmetros:
- status (ExportStatus) - Código de status.
- mensagem (str) - Mensagem de status legível.
substance_painter.export.export_mesh(file_path: str, opção: MeshExportOption) -> MeshExportResult substance_painter.export.export_mesh
Exporta a malha atual para o caminho de arquivo indicado.
Parâmetros:
- arquivo_caminho (cadeia) - O caminho de arquivo completo para onde exportar a malha. O formato do arquivo é deduzido da extensão. As extensões com suporte são:
.usd,.obj,.fbx,.dae,.ply,.gltf. - opção (MeshExportOption) - A opção de exportação a ser usada.
Retorna: Resultado do processo de exportação.
Tipo de retorno: MeshExportResult
Aumentos:
- ProjectError - Se nenhum projeto estiver aberto.
- ValueError - Se
file_pathouoptionforem inválidos no contexto do projeto atual. Contém uma mensagem legível detalhando o problema.
Exemplo:
import substance_painter.export
# Open a project we want to export from (see substance_painter.project
# for details). This step is not necessary if there is already a project
# opened in Substance 3D Painter.
import substance_painter.project
substance_painter.project.open("C:/projects/MeetMat.spp")
# Choose an export option to use
export_option = substance_painter.export.MeshExportOption.BaseMesh
if not substance_painter.export.scene_is_triangulated():
export_option = substance_painter.export.MeshExportOption.TriangulatedMesh
if substance_painter.export.scene_has_tessellation():
export_option = substance_painter.export.MeshExportOption.TessellationNormalsBaseMesh
# Actual export mesh operation:
filename = "C:/projects/MeetMat.obj"
export_result = substance_painter.export.export_mesh(filename, export_option)
# In case of error, display a human readable message:
if export_result.status != substance_painter.export.ExportStatus.Success:
print(export_result.message)
substance_painter.project, Exportar documentação.