Simplygon functions
The Simplygon Max plug-in exports a number of global MaxScript / Python functions. The following sections lists general Simplygon functions and examples, Simplygon Pipeline functions and Simplygon Shading Network functions are listed separately.
General script functions
Function | Parameter(s) | Description |
---|---|---|
sgsdk_RunPipelineOnSelection | int pipelineHandle | Optimizes the selected asset(s) based on the pipeline object. |
sgsdk_RunPipelineOnSelection | string pipelineFilePath | Optimizes the selected asset(s) based on the pipeline file. |
sgsdk_RunPipelineOnFile | int pipelineHandle string inputFilePath string outputFilePath | Optimizes the asset(s) in the specified input file and stores the result in the output file. The output file will get indexed if the Pipeline specifies a LOD chain, use sgsdk_GetProcessedOutputPaths to get the correct paths. |
sgsdk_RunPipelineOnFile | string pipelineFilePath string inputFilePath string outputFilePath | Optimizes the asset(s) in the specified input file and stores the result in the output file. The output file will get indexed if the Pipeline specifies a LOD chain, use sgsdk_GetProcessedOutputPaths to get the correct paths. |
sgsdk_SelectProcessedGeometries | <none> | Selects all processed geometries that were generated by sgsdk_RunPipeline* . |
sgsdk_Reset | <none> | Resets all settings in the Max plug-in (not Pipeline-settings). |
sgsdk_SetShowProgress | bool showProgress | Sets the ShowProgress flag. If set, the process runs in its own thread with a progress bar. |
sgsdk_SetLockSelectedVertices | bool lockSelectedVertices | If lockSelectedVertices is true then the vertex sets will be applied to the mesh(es) as vertex locks, locked vertices which will not be modified during reduction. This setting is compatible with Editable Mesh and Reduction. |
sgsdk_EnableEdgeSets | bool enableEdgeSets | If enableEdgeSets is true then the edge sets will be applied to the mesh(es) before being sent to Simplygon. If the name of the edge set is equal to "ForceCollapseAlongEdge", all edges will get collapsed (get a negative weight) during reduction. This setting is compatible with Editable Mesh and Reduction. |
sgsdk_MaterialColor | string materialName string channelName float r float g float b float a | Overrides or creates a color on the specified channel for the specified material. |
sgsdk_MaterialTexture | string materialName string channelName string texturePath bool isSRGB | Overrides the texture for the specified material. |
sgsdk_MaterialTextureMapChannel | string materialName string channelName int mapChannel | Overrides the mapping channel/UV channel for the specified material. |
sgsdk_SetIsVertexColorChannel | int mapChannel bool isVertexColor | Overrides channels > 2 in Max to be used as vertex colors instead of UV coordinates. |
sgsdk_UseNonConflictingTextureNames | bool useNonConflictingNames | Override generation of unique texture names per object when a MaterialLOD is created. By default the value is set to true. |
sgsdk_GetTexturePathForCustomChannel | string materialName | Gets texture path for specified material channel, if exists. |
sgsdk_GetMaterialsWithCustomChannels | Gets a list of materials that has custom channels. | |
sgsdk_GetCustomChannelsForMaterial | string materialName | Gets a list of custom channels for the specified material. |
sgsdk_GetProcessedMeshes | <none> | Returns a list of processed mesh names from last run. |
sgsdk_GetProcessedOutputPaths | <none> | Returns a list of processed file paths from last run. |
sgsdk_GetMaterialForMesh | string meshName | Return material name for the specified mesh. |
sgsdk_GetMaterialsForMesh | string meshName | Return material names for the specified mesh. |
sgsdk_GetMeshReusesMaterial | string meshName | Returns material name of the reused material, otherwise empty string. |
sgsdk_GetMeshReusesMaterials | string meshName | Returns material names of reused materials, otherwise empty list. |
sgsdk_GetChannelsForMaterial | string materialName | Returns a list of material channel names for the specified material. |
sgsdk_GetTexturePathForChannel | string materialName string channelName | Returns the texture path for the specified material channel. |
sgsdk_GetMappingChannelForChannel | string materialName string channelName | Returns the mapping channel for the specified material channel. |
sgsdk_GetMaterials | <none> | Returns a list of material names from the last run. |
sgsdk_GetSubMaterials | string materialName | Return a list of sub-material names for the specified material. |
sgsdk_GetMaterialReusesSubMaterial | string materialName string subMaterialName | Returns reused material name id reused, otherwise empty string. |
sgsdk_GetSubMaterialIndex | string materialName string subMaterialName | Returns sub-material index. |
sgsdk_SetGenerateMaterial | bool generateMaterial | Specifies whether the plug-in should generate a standard material for baked LODs. |
sgsdk_SetUseTangentSpaceNormals | int materialName bool isTangentSpace | Sets the the material to handle normal maps as tangent space normals. |
sgsdk_SetMeshNameFormat | string formatString | Specifies the format string that will be used when importing meshes. {MeshName} and {LODIndex} are reserved keywords and will be replaced with the corresponding values during import. Use sgsdk_SetInitialLODIndex to manually adjust the value of LODIndex. |
sgsdk_SetInitialLODIndex | int lodIndex | Sets the lodIndex to start with for the next import. |
sgsdk_ClearGlobalMapping | <none> | Clears global mapping stored by previous exports. |
sgsdk_ImportFromFile | string filePath | Imports a Simplygon scene from file. |
sgsdk_ImportFromFile | string filePath bool copyTextures | Imports a Simplygon scene from file. If copyTextures is true the textures will be imported to Max bitmap directory. |
sgsdk_ImportFromFile | string filePath bool copyTextures bool linkMeshes | Imports a Simplygon scene from file. If copyTextures is true the textures will be imported to Max bitmap directory. If linkMeshes is true the imported meshes will try to access data from scene (bones, hierarchy). |
sgsdk_ImportFromFile | string filePath bool copyTextures bool linkMeshes bool linkMaterials | Imports a Simplygon scene from file. If copyTextures is true the textures will be imported to Max bitmap directory. If linkMeshes is true the imported meshes will try to access data from scene (bones, hierarchy). If linkMaterials is set the imported meshes will try to reuse existing materials. |
sgsdk_ExportToFile | string filePath | Exports selected Max objects to a Simplygon scene file. |
sgsdk_ExportToFile | string filePath bool copyTextures | Exports selected Max objects to a Simplygon scene file. If copyTextures is true the original textures will be exported to a sub-directory of the target path. |
sgsdk_SetQuadMode | bool isEnabled | Enables Quad export / import (required for QuadReductionPipeline). |
Examples
This section contains various examples written in MaxScript and Python. We've left out some parts of the scripts to keep things as simple as possible.
from pymxs import runtime as rt
must be declared at the top of each Python script.reductionPipeline
settings-path must be declared for both MaxScript and Python scripts where it makes sense.- a scene-selection is made before each
sgsdk_RunPipelineOnSelection
.
Run Simplygon
To run Simplygon, simply execute the sgsdk_RunPipelineOnSelection
along with a Pipeline
settings-path or Pipeline
settings-object. A Pipeline
contains the settings that Simplygon will use during optimization, much like SPL (8.x) and INI (7.x). The optimized result will be returned to Max as soon as the processing has completed.
Execute Simplygon using a Pipeline file-path
-- reset states
sgsdk_Reset()
-- execute Simplygon with the given pipeline (settings-file)
sgsdk_RunPipelineOnSelection "D:/Pipelines/reductionPipeline.json"
-- clear all pipelines
sgsdk_ClearPipelines()
from pymxs import runtime as rt
# execute Simplygon with the given pipeline (settings-file)
rt.sgsdk_RunPipelineOnSelection('D:/Pipelines/reductionPipeline.json')
Execute Simplygon using a Pipeline-object
-- create a reduction pipeline-object
reductionPipeline = sgsdk_CreatePipeline("ReductionPipeline")
...
-- execute Simplygon with the given pipeline-object
sgsdk_RunPipelineOnSelection(reductionPipeline)
-- clear all pipelines
sgsdk_ClearPipelines()
from pymxs import runtime as rt
# create a reduction pipeline-object
reductionPipeline = rt.sgsdk_CreatePipeline('ReductionPipeline')
...
# execute Simplygon with the given pipeline-object
rt.sgsdk_RunPipelineOnSelection(reductionPipeline)
# clear all pipelines
rt.sgsdk_ClearPipelines()
Mapping data for Import and Export
Some data is incompatible with Simplygon's scene format, such as animation (key frames). To tackle this during manual export and import we are storing some mapping data that makes it possible to preserve this information, this data will reside in memory until manually cleared. Clearing global mapping before an import will result in meshes and materials getting imported solely based on the data in the file. Clear the global mapping manually, preferably before each export.
Clear global mapping data:
-- clear global mapping
sgsdk_ClearGlobalMapping()
from pymxs import runtime as rt
# clear global mapping
rt.sgsdk_ClearGlobalMapping()
Take the example below where we first export a scene to file, then import it back into Max. During export we store mapping data for meshes and materials (guid mapped). At import we do a lookup in the mapping data and if we find a match we can copy rendering properties and link bones more accurately.
-- export the selected Max assets to file
bResult = sgsdk_ExportToFile "D:/Exports/scene.sb"
-- import the specified Simplygon scene into Max
bResult = sgsdk_ImportFromFile "D:/Exports/scene.sb"
from pymxs import runtime as rt
# export the selected Max assets to file
bResult = rt.sgsdk_ExportToFile('D:/Exports/scene.sb')
# import the specified Simplygon scene into Max
bResult = rt.sgsdk_ImportFromFile('D:/Exports/scene.sb')
To gain more control of Import we have exposed two flags, LinkMaterials and LinkMeshes. If LinkMaterials is true we will try to do a lookup in the global mapping, if any, if there is no hit we will do a name based search. If a match is found we will link the existing material(s) to the imported mesh(es). If LinkMaterials is false then new materials will be generated and applied to the mesh(es).
Allow (re)use of original materials:
-- import the specified Simplygon scene into Max, try to reuse existing materials
-- sgsdk_ImportFromFile filePath CopyTextures LinkMeshes LinkMaterials
bResult = sgsdk_ImportFromFile "D:/Exports/scene.sb" false false true
from pymxs import runtime as rt
# import the specified Simplygon scene into Max, try to reuse existing materials
# rt.sgsdk_ImportFromFile (filePath, copyTextures, linkMeshes, linkMaterials)
bResult = rt.sgsdk_ImportFromFile('D:/Exports/scene.sb', False, False, True)
If LinkMeshes is true we will try to do a global lookup, and if that is not working then we will do a named based search. Non-existing mapping may result in loss of data, for example rendering properties and skinning / key frames. If LinkMeshes is false the imported meshes will be considered new meshes, Reductions will not be able to map back to the original hierarchy as an example.
Allow Import to access data on original mesh(es):
-- import the specified Simplygon scene into Max, try to access existing mesh data
-- sgsdk_ImportFromFile filePath copyTextures linkMeshes
-- sgsdk_ImportFromFile filePath copyTextures linkMeshes linkMaterials
bResult = sgsdk_ImportFromFile "D:/Exports/scene.sb" false true false
from pymxs import runtime as rt
# import the specified Simplygon scene into Max, try to access existing mesh data
# rt.sgsdk_ImportFromFile (filePath, copyTextures, linkMeshes)
# rt.sgsdk_ImportFromFile (filePath, copyTextures, linkMeshes, linkMaterials)
bResult = rt.sgsdk_ImportFromFile('D:/Exports/scene.sb', False, True, False)
Export selected Max assets to file
To export selected Max assets to file, use sgsdk_ExportToFile
followed by the output file path. Export is compatible with flags that modifies the output scene in any manner, such as example shading networks and material overrides. The exported file will be saved as Simplygon's proprietary file format.
-- export the selected Max assets to file
bResult = sgsdk_ExportToFile "D:/Exports/scene.sb"
from pymxs import runtime as rt
# export the selected Max scene to file
bResult = rt.sgsdk_ExportToFile('D:/Exports/scene.sb')
Export selected Max assets along with its textures to file using the CopyTextures flag. Textures will be exported to a sub-directory named "Textures" located in the same directory as the output scene file, in this specific case "D:/Exports/Textures".
-- export the selected Max assets to file (bundle textures)
-- sgsdk_ExportToFile filePath copyTextures
bResult = sgsdk_ExportToFile "D:/Exports/scene.sb" true
from pymxs import runtime as rt
# export the selected Max assets to file (bundle textures)
# rt.sgsdk_ExportToFile(filePath, copyTextures)
bResult = rt.sgsdk_ExportToFile('D:/Exports/scene.sb', True)
Import saved scene into Max
To import a previously saved file into Max, use sgsdk_ImportFromFile
followed by the file path.
Note: The importer is part of the standard Simplygon pipeline (export -> process -> import) and can not create complex materials. New materials will get imported as Blinn / Phong with one (the first) texture available for the given material channel. For complex (node-based) material import we recommend a manual approach.
-- import the specified Simplygon scene into Max
bResult = sgsdk_ImportFromFile "D:/Exports/scene.sb"
from pymxs import runtime as rt
# import the specified Simplygon scene into Max
bResult = rt.sgsdk_ImportFromFile('D:/Exports/scene.sb')
To specify wether the textures should be copied to a local directory, use the CopyTextures flag. Keep in mind that LinkMaterials may override this setting, if the imported asset is reusing existing scene materials it will also use the original textures. If CopyTextures is set the textures will get imported from it's source destination to Max's texture directory. If CopyTextures is not set the imported (generated) material's texture paths will point to the imported scene's destination textures.
-- export the selected Max assets to file (copy textures into Max's texture directory)
-- sgsdk_ImportFromFile filePath copyTextures
bResult = sgsdk_ImportFromFile "D:/Exports/scene.sb" true
from pymxs import runtime as rt
# export the selected Max assets to file (copy textures into Max's texture directory)
# rt.sgsdk_ImportFromFile(filePath, copyTextures)
bResult = rt.sgsdk_ImportFromFile('D:/Exports/scene.sb', True)
Specify name of processed / imported meshes
Renaming of processed / imported meshes can now be done by using sgsdk_SetMeshNameFormat
. {MeshName} and {LODIndex} will be replaced internally if present. If meshes with the given name already exists they will get assigned a new indexed name, usually the original name appended by a unique number.
As scenes can be exported and imported in an unordered manner we've also added sgsdk_SetInitialLODIndex
which specifies the starting index for LODIndex. So if you want to import a scene from disk and want to use LODIndex = 5 for all meshes found in the scene, that is now possible.
sgsdk_SetInitialLODIndex 1
sgsdk_SetMeshNameFormat "{MeshName}_LOD{LODIndex}"
bResult = sgsdk_ImportFromFile "D:/Exports/scene.sb"
from pymxs import runtime as rt
rt.sgsdk_SetInitialLODIndex(1)
rt.sgsdk_SetMeshNameFormat('{MeshName}_LOD{LODIndex}')
bResult = rt.sgsdk_ImportFromFile('D:/Exports/scene.sb')
Process scene from file
We've added the function sgsdk_RunPipelineOnFile
to allow users to be able to process scenes from file. The InputSceneFile flag specifies which file to optimize while OutputSceneFile specifies the target file path of the optimized scene.
If the pipeline is cascaded the output scene names will be appended with "_LOD" prefix and then indexed from 1 to *, where the index increments for each cascaded level. The output texture folder for each cascaded scene will be "Textures/LOD1" for LOD1, "Textures/LOD2" for LOD2 and so on. The output file names can be fetched with sgsdk_GetProcessedOutputPaths
which can then be used at import.
-- process input file and save optimized result to output file.
bResult = sgsdk_RunPipelineOnFile pipeline "D:/Exports/scene.sb" "D:/Exports/scene_processed.sb"
-- get processed output file paths
processedOutputFiles = sgsdk_GetProcessedOutputPaths()
-- set import format string
sgsdk_SetMeshNameFormat "{MeshName}_LOD{LODIndex}"
lodIndex = 1
for path in processedOutputFiles do
(
-- update lodIndex
sgsdk_SetInitialLODIndex lodIndex
-- import Simplygon scene from file
bResult = sgsdk_ImportFromFile path
lodIndex += 1
)
from pymxs import runtime as rt
# process input file and save optimized result to output file.
bResult = rt.sgsdk_RunPipelineOnFile(pipeline, 'D:/Exports/scene.sb','D:/Exports/scene_processed.sb')
# get processed output file paths
processedOutputFiles = rt.sgsdk_GetProcessedOutputPaths()
# set import format string
rt.sgsdk_SetMeshNameFormat('{MeshName}_LOD{LODIndex}')
# import scene(s)
lodIndex = 1
for path in processedOutputFiles:
# update lodIndex
rt.sgsdk_SetInitialLODIndex(lodIndex)
# import Simplygon scene from file
bResult = sgsdk_ImportFromFile(path)
lodIndex += 1
Calculate switch-distance from custom attributes
Simplygon writes down custom attributes for each mesh transform that can be used to calculate the recommended LOD-Switch distance. The attributes are MaxDeviation which indicates the pixel deviation compared to the original asset, and SceneRadius which is the total radius of the scene that was sent for processing. All meshes processed at the same time will have the same attribute values, thus also switch distance. MaxDeviation is currently available for Reduction and Remeshing. Aggregation do not have a switch distance as all it does is to merges geometry (and possibly materials), in this example the MaxDeviation gets set to 0 where the attribute does not exists.
Attributes:
To calculate the switch distance you also need to take a few other parameters into account, such as resolution and field-of-view (FOV). See the formula below (there is a more detailed description in the API documentation).
import MaxPlus
from pymxs import runtime as rt
# Object is the mesh transform
def calculateLODSwitchDistance(object):
# Reads the .SceneRadius attribute
radius = SimplygonWrapper.getSceneRadius(object)
# Reads the MaxDeviation attribute
deviation = SimplygonWrapper.getMaxDeviation(object)
# Calculates the pixel size (OnScreenSize)
pixelsize = (radius*2)/deviation
# Screen resolution and FOV
curView = MaxPlus.ViewportManager.GetActiveViewport()
size = rt.getViewSize()
screenheight = size[1]
screenwidth = size[2]
fov_y = rt.curView.GetFOV()
# Calculates screen ratio
screen_ratio = float(pixelsize) / float(screenheight)
normalized_distance = 1.0 / (math.tan(fov_y / 2))
# The view-angle of the bounding sphere rendered on-screen.
bsphere_angle = math.atan(screen_ratio / normalized_distance)
# The distance in real world units from the camera to the center of the
# bounding sphere. Not to be confused with normalized distance.
distance = radius / math.sin(bsphere_angle)
return distance
Material color override
To override a color of a material channel, enter the material name, the name of the channel and the RGBA values for a specific color. In the example below we choose to set the diffuse channel of "MyMaterial" to blue. If the material channel does not exist it will be created.
sgsdk_MaterialColor "MyMaterial" "DiffuseColor" 0.0 0.0 1.0 1.0
from pymxs import runtime as rt
rt.sgsdk_MaterialColor('MyMaterial', 'DiffuseColor', 0.0, 0.0, 1.0, 1.0)
Material texture override
To override a texture of a material channel, enter the name of the material, the name of the channel and at last the path to the target texture. In the example below we choose to set a diffuse texture to the diffuse channel of the material. The last flag specifies if the texture should be handled as in sRGB color space or not. If the material channel does not exist it will be created.
sgsdk_MaterialTexture "MyMaterial" "DiffuseColor" "D:/Textures/MyTexture.png" false
from pymxs import runtime as rt
rt.sgsdk_MaterialTexture('MyMaterial', 'DiffuseColor', 'D:/Textures/MyTexture.png', False)
Selection sets
Object selection sets are exported from Max's selection sets automatically. There is no need to script the creation of selection sets but it is still required to assign which selection set to use for features such as Bone Lock and Clipping Geometry.
Please see the Pipeline documentation for more information on how to set specific settings parameters.