[Xiao Mu learns Unity3d] 3ds Max surface reduction tool: Simplyon (Unity3d, Python)

1 Introduction

Simplygon comes with a Unity plugin that exposes optimization features such as reduction, aggregation, remeshing, impostors (SingleView, BillboardCloud/Vegetation), occlusion meshes, and material baking with support for the following built-in shaders:

  • Standard shader
  • Universal Rendering Pipeline (URP) pre-built shaders
  • High Definition Rendering Pipeline (HDRP) pre-built shaders

Insert image description here
Insert image description here
Insert image description here

2. Download and install

https://www.simplygon.com/downloads
Import the Simlygon plug-in into Unity.

2.1 Install Simlygon plug-in

Once Simplygon is installed, follow the guidance provided in the Unity documentation section to install the package from a tarball file, then browse to find the tarball (for example). C:\Program Files\Simplygon<MajorVersion>\Unity\bin<UnityVersion>Simplygon.Unity2022Plugin.tgz
Insert image description here
The Simplygon Unity plugin should now load automatically every time you start Unity. Go to Window -> Simplygon to display the Simplygon UI if it is not already there. Simplygon UI can be docked to most docking areas in Unity; just click and hold the Simplygon tab and place it where you like.

  • (1) Find the dll file of Simplygon and copy it to the Assets folder:
    Insert image description here
  • (2) After importing Simplygon:
    Insert image description here

2.2 Install USD plug-in

Each Unity project requires manual installation of the Simplygon Unity plug-in. Since the plug-in relies on Pixar's USD (Universal Scene Description) file format, the USD package provided by Unity will also be installed. See the instructions below for information on how to install the Simplygon Unity plugin.

Simplygon Unity plug-in utilizes the USD file format as an intermediate format between Unity and Simplygon. USD support is not built into Unity, so the support Unity package is installed with the Simplygon plug-in.

  • (1) Open the package manager Window→Package Manager, switch Packages to Packages: Unity Registry, and search for USD:
    Insert image description here
  • (2) If you can find the USD package, click Install. If the current Unity version does not integrate USD package resources, choose to add it from the Git repository (URL address: com.unity.formats.usd):
    Insert image description here
    Then click Add to add and wait for the USD package installation to complete.
    Insert image description here
    Start installing the USD package:
    Insert image description here

3. Use test

  • (1) Select Window→Simplygon to open the Simplygon panel:
    Insert image description here

  • (2) Click Add LOD Component, then click Template > Basic > Reduction with material baking.
    There are two modes here: Advanced and Basic. According to the official introduction, Basic mode is a mode for novices. It blocks most of the options in optimizing parameter settings. If you are a novice or you want simple and fast operation, you can choose Basic. The Advanced mode provides settings for all optimization configuration items. If you want to selectively optimize the model, you can use the Advanced option.
    Insert image description here
    ①Reduction: Reduce the patches
    ②Reduction with material baking: Reduce the number of patches and merge materials and maps (if the object has multiple materials).
    ③Remeshing with material baking: The official explanation is to replace the original Mesh with a more original lightweight Mesh mesh and merge materials and maps. I have never used this, so you can experience it yourself.
    ④Aggregation: Merge meshes (if there are multiple Mesh or sub-objects containing Mesh, they will eventually be merged into one).
    ⑤Aggregation with material baking: merge meshes and merge materials and maps.

  • (3) After setting the parameters, click the big yellow logo to perform optimization.
    Insert image description here
    Run Mode selects Rum In This Process. You can see that you can set the target triangle ratio under ReductionSettings (if you can't see the following numbers, just enlarge the window), the default is 0.5, that is, the number of generated model faces is 0.5 times the original; you can set the map size under MappingImageSettings, the default is 1024x1024.

  • (4) Simplified result comparison: the left side is the original asset and the right side is the optimized asset:
    Insert image description here
    Insert image description here
    Insert image description here

4. Python testing

https://documentation.simplygon.com/SimplygonSDK_10.2.10100.0/api/examples/reduction/reduction.html

  • (1) First install the Python library of Simplyon SDK in the installation package, as follows:
    Insert image description here
    Insert image description here
  • (2) Write Python code files for testing:
  • test.py
# Copyright (c) Microsoft Corporation. 
# Licensed under the MIT License. 

import math
import os
import sys
import glob
import gc
import threading

from pathlib import Path
from simplygon10 import simplygon_loader
from simplygon10 import Simplygon


def LoadScene(sg: Simplygon.ISimplygon, path: str):
    # Create scene importer 
    sgSceneImporter = sg.CreateSceneImporter()
    sgSceneImporter.SetImportFilePath(path)
    
    # Run scene importer. 
    importResult = sgSceneImporter.Run()
    if Simplygon.Failed(importResult):
        raise Exception('Failed to load scene.')
    sgScene = sgSceneImporter.GetScene()
    return sgScene

def SaveScene(sg: Simplygon.ISimplygon, sgScene: Simplygon.spScene, path: str):
    # Create scene exporter. 
    sgSceneExporter = sg.CreateSceneExporter()
    outputScenePath = ''.join(['output\\', 'Reduction', '_', path])
    sgSceneExporter.SetExportFilePath(outputScenePath)
    sgSceneExporter.SetScene(sgScene)
    
    # Run scene exporter. 
    exportResult = sgSceneExporter.Run()
    if Simplygon.Failed(exportResult):
        raise Exception('Failed to save scene.')

def CheckLog(sg: Simplygon.ISimplygon):
    # Check if any errors occurred. 
    hasErrors = sg.ErrorOccurred()
    if hasErrors:
        errors = sg.CreateStringArray()
        sg.GetErrorMessages(errors)
        errorCount = errors.GetItemCount()
        if errorCount > 0:
            print('CheckLog: Errors:')
            for errorIndex in range(errorCount):
                errorString = errors.GetItem(errorIndex)
                print(errorString)
            sg.ClearErrorMessages()
    else:
        print('CheckLog: No errors.')
    
    # Check if any warnings occurred. 
    hasWarnings = sg.WarningOccurred()
    if hasWarnings:
        warnings = sg.CreateStringArray()
        sg.GetWarningMessages(warnings)
        warningCount = warnings.GetItemCount()
        if warningCount > 0:
            print('CheckLog: Warnings:')
            for warningIndex in range(warningCount):
                warningString = warnings.GetItem(warningIndex)
                print(warningString)
            sg.ClearWarningMessages()
    else:
        print('CheckLog: No warnings.')
    
    # Error out if Simplygon has errors. 
    if hasErrors:
        raise Exception('Processing failed with an error')

def RunReduction(sg: Simplygon.ISimplygon):
    # Load scene to process.     
    print("Load scene to process.")
    sgScene = LoadScene(sg, 'airplane/11805_airplane_v2_L2.obj')
    
    # Create the reduction processor. 
    sgReductionProcessor = sg.CreateReductionProcessor()
    sgReductionProcessor.SetScene( sgScene )
    sgReductionSettings = sgReductionProcessor.GetReductionSettings()
    
    # Set reduction target to triangle ratio with a ratio of 50%. 
    sgReductionSettings.SetReductionTargets( Simplygon.EStopCondition_All, True, False, False, False )
    sgReductionSettings.SetReductionTargetTriangleRatio( 0.5 )
    
    # Start the reduction process.     
    print("Start the reduction process.")
    sgReductionProcessor.RunProcessing()
    
    # Save processed scene.     
    print("Save processed scene.")
    SaveScene(sg, sgScene, 'Output.fbx')
    
    # Check log for any warnings or errors.     
    print("Check log for any warnings or errors.")
    CheckLog(sg)

if __name__ == '__main__':
        sg = simplygon_loader.init_simplygon()
        if sg is None:
            exit(Simplygon.GetLastInitializationError())

        RunReduction(sg)

        sg = None
        gc.collect()

The running results are as follows:
Insert image description here
The output simplified model is as follows:
Insert image description here

Conclusion

如果您觉得该方法或代码有一点点用处,可以给作者点个赞,或打赏杯咖啡;╮( ̄▽ ̄)╭
如果您感觉方法或代码不咋地//(ㄒoㄒ)// ,就在评论处留言,作者继续改进;o_O???
如果您需要相关功能的代码定制化开发,可以留言私信作者;(✿◡‿◡)
感谢各位大佬童鞋们的支持!( ´ ▽´ )ノ ( ´ ▽´)! ! !

Guess you like

Origin blog.csdn.net/hhy321/article/details/135119653