static void RunReductionWithTextureCasting(ISimplygonSDK sdk, string readFrom, string writeTo) { // Load input geometry from file spWavefrontImporter objReader = sdk.CreateWavefrontImporter(); objReader.SetExtractGroups(false); //This makes the .obj reader import into a single geometry object instead of multiple objReader.SetImportFilePath(readFrom); if (!objReader.RunImport()) { Console.WriteLine("Failed to read: " + readFrom); return; } // Get geometry and materials from importer spGeometryData originalGeom = objReader.GetFirstGeometry(); //Only contains a single geom, so "first" is fine spMaterialTable originalMaterialTable = objReader.GetMaterials(); // Create a copy of the original geometry on which we will run the reduction spGeometryData lodGeometry = originalGeom.NewCopy(true); // Create the reduction-processor, and set the geometry to reduce spReductionProcessor reductionProcessor = sdk.CreateReductionProcessor(); reductionProcessor.SetGeometry(lodGeometry); /////////////////////////////////////////////////////////////////////////////////////////////// // 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.SetReductionHeuristics((uint)ReductionHeuristics.SG_REDUCTIONHEURISTICS_FAST); //Choose between "fast" and "consistent" processing. // The actual reduction triangle target are controlled by these three settings reductionSettings.SetStopCondition((uint)StopCondition.SG_STOPCONDITION_EITHER_IS_REACHED); //The reduction stops when either of the targets is reached reductionSettings.SetReductionRatio(0.5f); //Stops at 50% of the original triangle count reductionSettings.SetMaxDeviation(SimplygonSDK.REAL_MAX); //Stops when an error of the specified size has been reached. As set here it never happens. // The normal calculation settings deal with the normal-specific reduction settings spNormalCalculationSettings normalSettings = reductionProcessor.GetNormalCalculationSettings(); normalSettings.SetReplaceNormals(true); //If true, this will turn off normal handling in the reducer and recalculate them all afterwards instead. normalSettings.SetHardEdgeAngle(70.0f); //If the normals are recalculated, this sets the hard-edge angle. // The Image Mapping Settings, specifically needed for the texture baking we are doing later spMappingImageSettings mappingSettings = reductionProcessor.GetMappingImageSettings(); mappingSettings.SetGenerateMappingImage(true); //Without this we cannot fetch data from the original geometry, and thus not generate diffuse and normal-maps later on. mappingSettings.SetGenerateTexCoords(true); //Set to generate new texture coordinates. mappingSettings.SetMaxStretch(0.4f); //The higher the number, the fewer texture-borders. mappingSettings.SetGutterSpace(2); //Buffer space for when texture is mip-mapped, so color values don't blend over. Greatly influences packing efficiency mappingSettings.SetTexCoordLevel(0); //Sets the output texcoord level. For this asset, this will overwrite the original coords mappingSettings.SetWidth(1024); mappingSettings.SetHeight(1024); mappingSettings.SetMultisamplingLevel(2); //END SETTINGS /////////////////////////////////////////////////////////////////////////////////////////////// // Run the actual processing. After this, the set geometry will have been reduced according to the settings reductionProcessor.RunProcessing(); /////////////////////////////////////////////////////////////////////////////////////////////// // CASTING // Now, we need to retrieve the generated mapping image and use it to cast the old materials into a new one, for each channel. spMappingImage mappingImage = reductionProcessor.GetMappingImage(); // Now, for each channel, we want to cast the 9 input materials into a single output material, with one texture per channel. // First, create a new material table. spMaterialTable lodMaterialTable = sdk.CreateMaterialTable(); // Create new material for the table. spMaterial lodMaterial = sdk.CreateMaterial(); lodMaterial.SetName("SimplygonBakedMaterial"); lodMaterialTable.AddMaterial(lodMaterial); // Cast diffuse and specular texture data with a color caster { // Set the material properties lodMaterial.SetColor(SimplygonSDK.SG_MATERIAL_CHANNEL_AMBIENT, 0, 0, 0, 0); lodMaterial.SetColor(SimplygonSDK.SG_MATERIAL_CHANNEL_DIFFUSE, 1, 1, 1, 1); lodMaterial.SetColor(SimplygonSDK.SG_MATERIAL_CHANNEL_SPECULAR, 1, 1, 1, 128); //Note the 128 on the specular channels alpha. Simplygon bakes shininess //to the alpha channel of the specular map if the caster is set to 4 channel //output, and it is scaled between 0 and 1 internally. To get the correct //scale on the output, it should be multiplied by 128. // Cast the data using a color caster spColorCaster colorCaster = sdk.CreateColorCaster(); colorCaster.SetSourceMaterials(originalMaterialTable); colorCaster.SetDestMaterial(lodMaterial); //This modulates the cast color with the base colors set for the dest material above. //It means the internal shininess is multiplied by 128 before baking to texture. colorCaster.SetMappingImage(mappingImage); //The mapping image we got from the reduction process. colorCaster.SetOutputChannelBitDepth(8); //8 bits per channel. So in this case we will have 24bit colors RGB. colorCaster.SetDilation(10); //To avoid mip-map artifacts, the empty pixels on the map needs to be filled to a degree as well. colorCaster.SetColorType(SimplygonSDK.SG_MATERIAL_CHANNEL_DIFFUSE); colorCaster.SetOutputChannels(3); //RGB, 3 channels! (1 would be for grey scale, and 4 would be for RGBA.) colorCaster.SetOutputFilePath("combinedDiffuseMap.png"); //Where the texture map will be saved to file. colorCaster.CastMaterials(); //Do the actual casting and write to texture. colorCaster.SetColorType(SimplygonSDK.SG_MATERIAL_CHANNEL_SPECULAR); colorCaster.SetOutputChannels(4); //RGBA, 4 channels! Stores spec power in A colorCaster.SetOutputFilePath("combinedSpecularMap.png"); //Where the texture map will be saved to file. colorCaster.CastMaterials(); //Do the actual casting and write to texture. lodMaterial.SetTexture(SimplygonSDK.SG_MATERIAL_CHANNEL_DIFFUSE, "combinedDiffuseMap.png"); //Set material to point to the texture we cast to above lodMaterial.SetTexture(SimplygonSDK.SG_MATERIAL_CHANNEL_SPECULAR, "combinedSpecularMap.png"); //Set material to point to the texture we cast to above } // Cast normal map texture data with the normal caster. This also compensates for any geometric errors that have appeared in the reduction process. { // cast the data using a normal caster spNormalCaster normalCaster = sdk.CreateNormalCaster(); normalCaster.SetSourceMaterials(originalMaterialTable); normalCaster.SetMappingImage(mappingImage); normalCaster.SetOutputChannels(3); // RGB, 3 channels! (But really the x, y and z values for the normal) normalCaster.SetOutputChannelBitDepth(8); normalCaster.SetDilation(10); normalCaster.SetOutputFilePath("combinedNormalMap.png"); normalCaster.SetFlipBackfacingNormals(false); normalCaster.SetGenerateTangentSpaceNormals(true); normalCaster.CastMaterials(); // Set normal map of the created material to point to the combined normal map lodMaterial.SetTexture(SimplygonSDK.SG_MATERIAL_CHANNEL_NORMALS, "combinedNormalMap.png"); } // END CASTING /////////////////////////////////////////////////////////////////////////////////////////////// //Create an .obj exporter to save our result spWavefrontExporter objExporter = sdk.CreateWavefrontExporter(); // Generate the output filenames // Do the actual exporting objExporter.SetExportFilePath(writeTo + ".obj"); objExporter.SetSingleGeometry(lodGeometry); //This is the geometry we set as the processing geom of the reducer objExporter.SetMaterials(lodMaterialTable); //Our new cast material if (!objExporter.RunExport()) { Console.WriteLine("Failed to write target file"); } //Done! LOD and material created. }
static bool run_remeshing_for_lod(ISimplygonSDK sdk, int lod_index, uint merge_distance) { string userProfileDirectory = System.Environment.GetEnvironmentVariable("USERPROFILE"); string assetRoot = userProfileDirectory + @"/Documents/SimplygonSDK/SourceCode/Assets/"; string tempRoot = @"../../../../../temp/"; string output_filename = string.Format(tempRoot + "wall_lod{0}_merge{1}.obj", lod_index + 1, merge_distance); string output_material_filename = string.Format(tempRoot + "wall_lod{0}_merge{1}.mtl", lod_index + 1, merge_distance); string output_diffuse_filename = string.Format(tempRoot + "wall_lod{0}_merge{1}_diffuse.png", lod_index + 1, merge_distance); string output_normals_filename = string.Format(tempRoot + "wall_lod{0}_merge{1}_normals.png", lod_index + 1, merge_distance); // Import source geometry spGeometryData geom; spMaterialTable materials; Console.WriteLine("Importing wavefront .obj file...\n"); { // Run import spWavefrontImporter importer = sdk.CreateWavefrontImporter(); importer.SetExtractGroups(false); // We only want one large geometry, no need to extract groups importer.SetImportFilePath(assetRoot + "wall.obj"); if (!importer.RunImport()) { Console.WriteLine("Could not open input test file"); return(false); } // Get the only geometry and the materials geom = importer.GetFirstGeometry(); materials = importer.GetMaterials(); } // Make a copy of the geometry, we need the original for texture casting later. // The remesher will replace the data of the geometry after it has processed it. spGeometryData red_geom = geom.NewCopy(true); // Create a Scene-object and a SceneMesh-object. // Place the red_geom into the SceneMesh, and then the SceneMesh as a child to the RootNode. spScene scene = sdk.CreateScene(); spSceneMesh mesh = sdk.CreateSceneMesh(); mesh.SetGeometry(red_geom); mesh.SetName(red_geom.GetName().GetText()); scene.GetRootNode().AddChild(mesh); spMappingImage mapping_image; // Remesh it Console.WriteLine("Running remesher...\n"); { spRemeshingProcessor remesher = sdk.CreateRemeshingProcessor(); // Set target on-screen size in pixels remesher.GetRemeshingSettings().SetOnScreenSize(lod_sizes[lod_index]); // Set the on-screen merge distance in pixels. Holes smaller than this will be sealed // and geometries closer to each other than this will be merged. remesher.GetRemeshingSettings().SetMergeDistance(merge_distance); // Disable the cutting plane remesher.GetRemeshingSettings().SetUseGroundPlane(false); // Set to generate mapping image for texture casting. remesher.GetMappingImageSettings().SetGenerateMappingImage(true); remesher.SetSceneRoot(scene.GetRootNode()); remesher.RemeshGeometry(); // Mapping image is needed later on for texture casting. mapping_image = remesher.GetMappingImage(); } spSceneMesh topmesh = Utils.SimplygonCast <spSceneMesh>(scene.GetRootNode().GetChild(0), false); // Cast diffuse texture and normal map data into a new material // Create new material table. spMaterialTable output_materials = sdk.CreateMaterialTable(); // Create new material for the table. spMaterial output_material = sdk.CreateMaterial(); output_materials.AddMaterial(output_material); // Cast diffuse texture data { // Cast the data using a color caster spColorCaster cast = sdk.CreateColorCaster(); cast.SetColorType(SimplygonSDK.SG_MATERIAL_CHANNEL_DIFFUSE); cast.SetSourceMaterials(materials); cast.SetMappingImage(mapping_image); // The mapping image we got from the remeshing process. cast.SetOutputChannels(3); // RGB, 3 channels! (1 would be for grey scale, and 4 would be for RGBA.) cast.SetOutputChannelBitDepth(8); // 8 bits per channel. So in this case we will have 24bit colors RGB. cast.SetDilation(10); // To avoid mip-map artifacts, the empty pixels on the map needs to be filled to a degree aswell. cast.SetOutputFilePath(output_diffuse_filename); // Where the texture map will be saved to file. cast.CastMaterials(); // Fetch! // set the material properties // Set the diffuse multiplier for the texture. 1 means it will not differ from original texture, // For example: 0 would ignore a specified color and 2 would make a color twice as pronounced as the others. output_material.SetDiffuseRed(1); output_material.SetDiffuseGreen(1); output_material.SetDiffuseBlue(1); // Set material to point to created texture filename. output_material.SetTexture(SimplygonSDK.SG_MATERIAL_CHANNEL_DIFFUSE, output_diffuse_filename); } // cast normal map texture data { // cast the data using a color caster spNormalCaster cast = sdk.CreateNormalCaster(); cast.SetSourceMaterials(materials); cast.SetMappingImage(mapping_image); cast.SetOutputChannels(3); // RGB, 3 channels! (But really the x, y and z values for the normal) cast.SetOutputChannelBitDepth(8); cast.SetDilation(10); cast.SetOutputFilePath(output_normals_filename); cast.CastMaterials(); // Set material to point to created texture filename. output_material.SetTexture(SimplygonSDK.SG_MATERIAL_CHANNEL_NORMALS, output_normals_filename); } // export the remeshed geometry to an OBJ file Console.WriteLine("Exporting wavefront .obj file...\n"); { spWavefrontExporter exporter = sdk.CreateWavefrontExporter(); exporter.SetExportFilePath(output_filename); exporter.SetSingleGeometry(topmesh.GetGeometry()); exporter.SetMaterials(output_materials); if (!exporter.RunExport()) { Console.WriteLine("Failed to write result"); return(false); } } return(true); }