Как оптимизировать модель fbx с Simplygon SDK - PullRequest
0 голосов
/ 15 февраля 2020

Пожалуйста, извините моего бедного Энгли sh.


Я создаю инструмент, который оптимизирует модели fbx, хранящиеся в данном каталоге.

Я видел эту страницу .

Я могу оптимизировать obj-модели таким способом, но не могу оптимизировать fbx-модели.

Программа не выдает никаких ошибок или сообщений, она экспортирует 1-килобайтный поврежденный fbx-файл.

Это мой код.

#include "SimplygonSDK.h"
#include "SimplygonSDKLoader.cpp"
#include <iostream>
#include <Windows.h>
#include <vector>
#include <string>
#include <stdexcept>
using namespace SimplygonSDK;
using namespace std;

class ProgressObserver : public robserver
{
public:
    virtual void Execute(
        IObject * subject,
        rid EventId,
        void * EventParameterBlock,
        unsigned int EventParameterBlockSize)
    {
        // only care for progress events
        if (EventId == SG_EVENT_PROGRESS)
        {
            // get the progress in percent
            int val = *((int *)EventParameterBlock);
            // tell the process to continue
            // this is required by the progress event
            *((int *)EventParameterBlock) = 1;
            // output the progress update
            cout << val << "\n";
        }
    }
} progressObserver;


void RunHighQualityReduction(const std::string& readFrom, const std::string& writeTo);

ISimplygonSDK* sg = 0;
int main() {
    string license = "", licensePath = "C:\\ProgramData\\Microsoft\\SimplygonSDK\\Simplygon_8_license.dat";
    if (!ReadLicense(licensePath, license)) {
        cout << "Failed to Read License\n";
        cin.get();
        return -1;
    }
    cout << "Read License Complete\n";

    if (!LoadLicense(license)) {
        cout << "Failed to Load License\n";
        cin.get();
        return -1;
    }
    cout << "Load License Complete\n";

    string sdkPath = "C:\\Users\\{myname}\\AppData\\Local\\Simplygon\\Grid\\Agent\\SimplygonLibs\\SimplygonLib_8.3.35000.0\\SimplygonSDKRuntimeReleasex64.dll";

    if (!LoadDynamicLibrary(sdkPath)) {
        cout << "Failed to Find SDK\n";
        cin.get();
        return -1;
    }
    cout << "Load SDK Complete\n";

    int retval = Initialize(&sg, sdkPath.c_str(), license.c_str());

    if (retval == SimplygonSDK::SG_ERROR_NOERROR) {
        sg->SetGlobalSetting("DefaultTBNType", SG_TANGENTSPACEMETHOD_ORTHONORMAL);

        RunHighQualityReduction("C:\\Users\\{myname}\\Documents\\Assets\\Models\\model.FBX", "E:\\Simplygon_Export\\temp.fbx");
        cout << "Initialized\n";
    }

    Deinitialize();
    cin.get();
    return 0;
}



void RunHighQualityReduction(const std::string& readFrom, const std::string& writeTo)
{
    // Load input geometry from file
    auto objReader = sg->CreateWavefrontImporter();
    //objReader->SetExtractGroups(false); //This makes the .obj reader import into a single geometry object instead of multiple
    objReader->SetImportFilePath(readFrom.c_str());

    cout << readFrom.c_str() << "\n";
    if (!objReader->RunImport())
        throw std::exception("Failed to load input file!");

    // Get geometry and materials from importer
    spScene originalScene = objReader->GetScene();
    //Create a copy of the original scene on which we will run the reduction
    spScene lodScene = originalScene->NewCopy();

    // Create the reduction-processor, and set which scene to reduce
    spReductionProcessor reductionProcessor = sg->CreateReductionProcessor();

    reductionProcessor->SetScene(lodScene);

    ///////////////////////////////////////////////////////////////////////////////////////////////
    // SETTINGS - Most of these are set to the same value by default, but are set anyway for clarity

    // The reduction settings object contains settings pertaining to the actual decimation
    spReductionSettings reductionSettings = reductionProcessor->GetReductionSettings();
    reductionSettings->SetKeepSymmetry(true); //Try, when possible to reduce symmetrically
    reductionSettings->SetUseAutomaticSymmetryDetection(true); //Auto-detect the symmetry plane, if one exists. Can, if required, be set manually instead.
    reductionSettings->SetUseHighQualityNormalCalculation(true); //Drastically increases the quality of the LODs normals, at the cost of extra processing time.
    reductionSettings->SetReductionHeuristics(SG_REDUCTIONHEURISTICS_CONSISTENT); //Choose between "fast" and "consistent" processing. Fast will look as good, but may cause inconsistent 
    //triangle counts when comparing MaxDeviation targets to the corresponding percentage targets.

    // The reducer uses importance weights for all features to decide where and how to reduce.
    // These are advanced settings and should only be changed if you have some specific reduction requirement
    /*reductionSettings->SetShadingImportance(2.f); //This would make the shading twice as important to the reducer as the other features.*/

    // The actual reduction triangle target are controlled by these settings
    reductionSettings->SetStopCondition(SG_STOPCONDITION_ANY);//The reduction stops when any of the targets below is reached
    reductionSettings->SetReductionTargets(SG_REDUCTIONTARGET_ALL);//Selects which targets should be considered when reducing
    reductionSettings->SetTriangleRatio(0.5); //Targets at 50% of the original triangle count
    //reductionSettings->SetTriangleCount(10); //Targets when only 10 triangle remains
    //reductionSettings->SetMaxDeviation(REAL_MAX); //Targets when an error of the specified size has been reached. As set here it never happens.
    //reductionSettings->SetOnScreenSize(50); //Targets when the LOD is optimized for the selected on screen pixel size

    // The repair settings object contains settings to fix the geometries
    spRepairSettings repairSettings = reductionProcessor->GetRepairSettings();
    repairSettings->SetTjuncDist(0.0f); //Removes t-junctions with distance 0.0f
    repairSettings->SetWeldDist(0.0f); //Welds overlapping vertices

    // The normal calculation settings deal with the normal-specific reduction settings
    spNormalCalculationSettings normalSettings = reductionProcessor->GetNormalCalculationSettings();
    normalSettings->SetReplaceNormals(false); //If true, this will turn off normal handling in the reducer and recalculate them all afterwards instead.
    //If false, the reducer will try to preserve the original normals as well as possible
    /*normalSettings->SetHardEdgeAngleInRadians( 3.14159f*60.0f/180.0f ); //If the normals are recalculated, this sets the hard-edge angle.*/

    //END SETTINGS 
    ///////////////////////////////////////////////////////////////////////////////////////////////

    reductionProcessor->AddObserver(&progressObserver, SG_EVENT_PROGRESS);

    // Run the actual processing. After this, the set geometry will have been reduced according to the settings
    reductionProcessor->RunProcessing();

    // For this reduction, the LOD will use the same material set as the original, and hence no further processing is required

    //Create an .obj exporter to save our result
    spWavefrontExporter objExporter = sg->CreateWavefrontExporter();

    // Generate the output filenames
    std::string outputGeomFilename = writeTo;

    // Do the actual exporting
    objExporter->SetExportFilePath(outputGeomFilename.c_str());
    objExporter->SetScene(lodScene); //This is the geometry we set as the processing geom of the reducer, retaining the materials in the original scene
    if (objExporter->RunExport()) {
        cout << "Export success\n";
    }
    else {
        cout << "Export failed\n";
    }

    //Done! LOD created.
}

Я также пытался ReductionPipeline .

Но это не сработало и выдало сообщение об ошибке

"An error occured in a call to IReductionPipeline::RunSceneFromFile:
Error text: This is not a raven stream, or the stream is corrupt"


Моя среда
Windows10 Home 64bit,
Simplygon Lib 8.3.35000.

Я могу оптимизировать модели fbx с Просто пользовательский интерфейс. Поэтому я думаю, что SDK не сломан.

...