aboutsummaryrefslogtreecommitdiff
path: root/tools/ApexImporter/src/Main.cpp
blob: 414d6f95996191299f56aeb4c559fe350d7bff91 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
// This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2016-2020 NVIDIA Corporation. All rights reserved.


#if NV_VC
#pragma warning(push)
#pragma warning(disable: 4996) // 'fopen' unsafe warning, from NxFileBuffer.h
#endif

#include "PxPhysicsAPI.h"
#include "NvBlastExtApexImportTool.h"
#include "Log.h"
#include <string>
#include <iostream>
#include <fstream>
#include "tclap/CmdLine.h"
#include "ApexDestructibleObjExporter.h"
#include "NvBlastTkFramework.h"
#include "NvBlastGlobals.h"
#include "NvBlastExtPxAsset.h"
#include "NvBlastExtPxManager.h"
#include "BlastDataExporter.h"
#include "windows.h"
#include <NvBlastTkAsset.h>
#include "NvBlastExtLlSerialization.h"
#include "NvBlastExtTkSerialization.h"
#include "NvBlastExtPxSerialization.h"
#include "NvBlastExtExporterJsonCollision.h"
#include <nvparameterized\NvSerializer.h>
#include <PsFileBuffer.h>
#define DEFAULT_INPUT_FILE "../../../tools/ApexImporter/resources/assets/table.apb"
#define DEFAULT_OUTPUT_DIR "C:/TestFracturer/"
#define DEFAULT_ASSET_NAME "table"

using namespace Nv::Blast;
using namespace Nv::Blast::ApexImporter;

void loggingCallback(int type, const char* msg, const char* file, int line)
{
	if (type == NvBlastMessage::Info)
		lout() << Log::TYPE_INFO << msg << " FILE:" << file << " Line: " << line << "\n";
	else
		lout() << Log::TYPE_ERROR << msg << " FILE:" << file << " Line: " << line << "\n";
}

bool isDirectoryExist(std::string path)
{
	DWORD attributes = GetFileAttributesA(path.c_str());
	if ((attributes != INVALID_FILE_ATTRIBUTES) && (attributes & FILE_ATTRIBUTE_DIRECTORY))
	{
		return true;
	}
	return false;
}

bool mkDirRecursively(std::string path)
{
	if (isDirectoryExist(path))
	{
		return true;
	}
	auto indx = path.find_first_of("\\/");
	while (indx != std::string::npos)
	{
		std::string subfolder = path.substr(0, indx);
		CreateDirectory(subfolder.c_str(), NULL);
		indx = path.find_first_of("\\/", indx + 1);
	}
	return isDirectoryExist(path);
}

// Create an Asset from the APEX destructible asset
void run(const std::string& inFilepath, const std::string& outDir, const std::string& assetName, uint32_t mode, bool llFlag, bool tkFlag, bool extPxFlag,
		 bool obj, bool fbx, bool fbxascii, bool fbxCollision, bool jsonCollision, bool nonSkinned)
{
	std::string inputDir = inFilepath.substr(0, inFilepath.find_last_of("/\\"));

	// load APEX
	ApexImportTool blast;

	lout() << Log::TYPE_INFO << "ApexImportTool initialization" << std::endl;
	if (!blast.isValid())
	{
		lout() << Log::TYPE_ERROR << "Failed to create BlastSDK" << std::endl;
		return;
	}


	// load asset
	lout() << Log::TYPE_INFO << "Loading asset: " << inFilepath << std::endl;
	physx::PxFileBuf* apexAssetStream = PX_NEW(physx::general_PxIOStream::PsFileBuffer)(inFilepath.c_str(), physx::PxFileBuf::OPEN_READ_ONLY);

	NvParameterized::Serializer::DeserializedData data;
	blast.loadAssetFromFile(apexAssetStream, data);
	if (data.size() == 0)
	{
		return;
	}  
	apexAssetStream->release();

	ApexImporterConfig config;
	config.infSearchMode = static_cast<ApexImporterConfig::InterfaceSearchMode>(mode);

	std::vector<uint32_t> chunkReorderInvMap;
	TkFramework* framework = NvBlastTkFrameworkCreate();
	if (framework == nullptr)
	{
		lout() << Log::TYPE_ERROR << "Failed to create TkFramework" << std::endl;
		return;
	}

	std::vector<NvBlastChunkDesc>	chunkDesc;
	std::vector<NvBlastBondDesc>	bondDescs;
	std::vector<uint32_t>			flags;

	std::vector<ExtPxAssetDesc::ChunkDesc> physicsChunks;
	std::vector<ExtPxAssetDesc::SubchunkDesc> physicsSubchunks;

	bool result = blast.importApexAsset(chunkReorderInvMap, data[0], chunkDesc, bondDescs, flags, config);
	if (!result)
	{
		lout() << Log::TYPE_ERROR << "Failed to build Blast asset data" << std::endl;
		return;
	};
	std::vector<std::vector<CollisionHull*>> hulls;
	result = blast.getCollisionGeometry(data[0], static_cast<uint32_t>(chunkDesc.size()), chunkReorderInvMap, flags, physicsChunks, physicsSubchunks, hulls);
	if (!result)
	{
		lout() << Log::TYPE_ERROR << "Failed to build physics data" << std::endl;
		return;
	};


	// save asset
	lout() << Log::TYPE_INFO << "Saving blast asset: " << outDir << std::endl;
	BlastDataExporter blExpr(framework, blast.getPxSdk(), blast.getCooking());
	NvBlastAsset* llAsset = blExpr.createLlBlastAsset(bondDescs, chunkDesc);

	std::cout <<"Chunk count: " << NvBlastAssetGetChunkCount(llAsset, NULL) << std::endl;

	if (llAsset == nullptr && (llFlag || fbx))
	{
		lout() << Log::TYPE_ERROR << "Failed to build low-level asset" << std::endl;
		return;
	}

	if (llFlag)
	{
		blExpr.saveBlastObject(outDir, assetName, llAsset, LlObjectTypeID::Asset);
	}
	if (tkFlag)
	{
		TkAsset* tkAsset = blExpr.createTkBlastAsset(bondDescs, chunkDesc);
		blExpr.saveBlastObject(outDir, assetName, tkAsset, TkObjectTypeID::Asset);
		tkAsset->release();
	}
	if (extPxFlag)
	{
		ExtPxAsset* pxAsset = blExpr.createExtBlastAsset(bondDescs, chunkDesc, physicsChunks);
		blExpr.saveBlastObject(outDir, assetName, pxAsset, ExtPxObjectTypeID::Asset);
		pxAsset->release();
	}	
	
	lout() << Log::TYPE_INFO << "Saving model file: " << outDir << std::endl;
	ApexDestructibleGeometryExporter objSaver(inputDir, outDir);
	if (fbxCollision)
	{
		objSaver.exportToFile(llAsset, data[0], blast, assetName, chunkReorderInvMap, fbx, obj, fbxascii, nonSkinned, hulls);
	}
	else
	{
		objSaver.exportToFile(llAsset, data[0], blast, assetName, chunkReorderInvMap, fbx, obj, fbxascii, nonSkinned);
	}

	if (jsonCollision)
	{
		std::vector<CollisionHull*> flattenedHulls;
		std::vector<uint32_t> hullOffsets;
		for (std::vector<CollisionHull*>& chunkHulls : hulls)
		{
			hullOffsets.push_back(static_cast<uint32_t>(flattenedHulls.size()));
			for (CollisionHull* hull : chunkHulls)
			{
				flattenedHulls.push_back(hull);
			}
		}
		hullOffsets.push_back(static_cast<uint32_t>(flattenedHulls.size()));
		const std::string fullJsonFilename = outDir + ((outDir.back() == '/' || outDir.back() == '\\') ? "" : "/") + assetName + ".json";
		IJsonCollisionExporter* collisionExporter = NvBlastExtExporterCreateJsonCollisionExporter();
		if (collisionExporter != nullptr)
		{
			if (collisionExporter->writeCollision(fullJsonFilename.c_str(), static_cast<uint32_t>(hulls.size()), hullOffsets.data(), flattenedHulls.data()))
			{
				std::cout << "Exported collision geometry: " << fullJsonFilename << std::endl;
			}
			else
			{
				std::cerr << "Can't write collision geometry to json file." << std::endl;
			}
			collisionExporter->release();
		}
	}

	for (auto& hv : hulls)
	{
		for (auto h : hv)
		{
			blast.getCollisionBuilder()->releaseCollisionHull(h);
		}
	}

	NVBLAST_FREE(llAsset);
}


int main(int argc, const char* const* argv)
{
	try 
	{
		// setup cmd line
		TCLAP::CmdLine cmd("Blast SDK: APEX Importer", ' ', "0.1");

		TCLAP::ValueArg<std::string> infileArg("f", "file", "File to load", true, DEFAULT_INPUT_FILE, "infile");
		cmd.add(infileArg);

		TCLAP::ValueArg<std::string> outDirArg("o", "outputDir", "Output directory", false, DEFAULT_OUTPUT_DIR, "output directory");
		cmd.add(outDirArg);

		TCLAP::ValueArg<std::string> outAssetName("n", "outAssetName", "Output asset name", true, DEFAULT_ASSET_NAME, "output asset name");
		cmd.add(outAssetName);


		TCLAP::ValueArg<uint32_t> interfaceSearchMode("m", "mode", "Interface search mode", false, 0, "0 - EXACT, 1 - FORCED, for detailed description see docs.");
		cmd.add(interfaceSearchMode);

		TCLAP::SwitchArg debugSwitch("d", "debug", "Print debug output", cmd, false);

		TCLAP::SwitchArg pxOutputArg("", "px", "Output ExtPxAsset to the output directory", false);
		cmd.add(pxOutputArg);

		TCLAP::SwitchArg tkOutputArg("", "tk", "Output TkAsset to the output directory", false);
		cmd.add(tkOutputArg);

		TCLAP::SwitchArg llOutputArg("", "ll", "Output LL Blast asset to the output directory", false);
		cmd.add(llOutputArg);

		TCLAP::SwitchArg fbxAsciiArg("", "fbxascii", "Output FBX as an ascii file (defaults to binary output)", false);
		cmd.add(fbxAsciiArg);

		TCLAP::SwitchArg objOutputArg("", "obj", "Output a OBJ mesh to the output directory", false);
		cmd.add(objOutputArg);

		TCLAP::SwitchArg fbxOutputArg("", "fbx", "Output a FBX mesh to the output directory", false);
		cmd.add(fbxOutputArg);

		TCLAP::SwitchArg jsonCollision("", "jsoncollision", "Save collision geometry to a json file", false);
		cmd.add(jsonCollision);

		TCLAP::SwitchArg fbxcollision("", "fbxcollision", "Append collision geometry to FBX file", false);
		cmd.add(fbxcollision);

		TCLAP::SwitchArg nonSkinnedFBX("", "nonskinned", "Output a non-skinned FBX file", false);
		cmd.add(nonSkinnedFBX);

		// parse cmd input
		cmd.parse(argc, argv);

		bool bOutputPX = pxOutputArg.getValue();
		bool bOutputTK = tkOutputArg.getValue();
		bool bOutputLL = llOutputArg.getValue();

		bool bOutputFBXAscii = fbxAsciiArg.isSet();

		bool bOutputObjFile = objOutputArg.isSet();
		bool bOutputFbxFile = fbxOutputArg.isSet();

		bool bFbxCollision = fbxcollision.isSet();
		bool bJsonCollision = jsonCollision.isSet();

		bool bNonSkinned = nonSkinnedFBX.isSet();

		// Did we specify no output formats?
		if (!pxOutputArg.isSet() && !tkOutputArg.isSet() && !llOutputArg.isSet())
		{
			std::cout << "Didn't specify an output format on the command line, so defaulting to outputting an ExtPxAsset" << std::endl;
			bOutputPX = true;
		}
		// Did we specify no geometry output formats?
		if (!bOutputObjFile && !bOutputFbxFile)
		{
			std::cout << "Didn't specify an output geometry format on the command line, so defaulting to outputting .OBJ" << std::endl;
			bOutputObjFile = true;
		}

		// get cmd parse results
		std::string infile = infileArg.getValue();
		std::string outDir;
		std::string assetName = outAssetName.getValue();
		
		/**
			Set output dir, make sure that it exist.
		*/
		if (outDirArg.isSet())
		{
			outDir = outDirArg.getValue();
			std::string temp = outDir + '/';
			if (!isDirectoryExist(outDir.data()))
			{
				std::cout << "Output directory doesn't exist. It will be created." << std::endl;
				if (!mkDirRecursively(temp.data()))
				{
					std::cout << "Directory creation failed!" << std::endl;
					return -1;
				}
			}
		}
		else
		{
			auto idx = infile.find_last_of("/\\");
			if (idx == 0 || idx == std::string::npos)
			{
				outDir = ".";
			}
			else
			{
				outDir = infile.substr(0, idx);
			}
		}

		bool debug = debugSwitch.getValue();
		int mode = interfaceSearchMode.getValue();
		// do stuff
		if (debug)
			lout().setMinVerbosity(Log::MOST_VERBOSE);

		run(infile, outDir, assetName, mode, bOutputLL, bOutputTK, bOutputPX, bOutputObjFile, bOutputFbxFile, bOutputFBXAscii, bFbxCollision, bJsonCollision, bNonSkinned);
	}
	catch (TCLAP::ArgException &e)  // catch any exceptions
	{
		lout() << Log::TYPE_ERROR << "error: " << e.error() << " for arg " << e.argId() << std::endl;
	}

	return 0;
}