-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathobj2hmap.cpp
More file actions
520 lines (444 loc) · 15.3 KB
/
obj2hmap.cpp
File metadata and controls
520 lines (444 loc) · 15.3 KB
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
/**
* @file obj2hmap.cpp
* @brief Convert Wavefront's OBJ to heightmap/displacement file.
* @internal
*
* Copyright(c) 2017 by ryobg@users.noreply.github.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @endinternal
*
* @details
* Add detailed description of file
*/
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <vector>
#include <limits>
#include <array>
#include <algorithm>
#include <numeric>
#include <exception>
#include <utility>
/**
* Application of converting Wavefront's OBJ file into binary 2d heightfield file.
*
* This class can parse command line arguments, validate them, and report a help message if needed.
*/
class obj2hmap
{
public:
/// 32-bit integer based 3d vector
typedef std::array<std::uint32_t, 3> uvec3;
/// Single float based 3d vector
typedef std::array<float, 3> vec3;
/// Double float based 3d vector (prioritize precision for bin->obj->bin iterations)
typedef std::array<double, 3> dvec3;
/// Another special - boolean 3d vector
typedef std::array<bool, 3> bvec3;
/// Describes the application parameters
struct param_type
{
std::string obj; ///< Input *.obj file to read from
std::string hmap; ///< Output *.* binary file to write to
uvec3 hmap_size; ///< Says how big is the integer grid for the heightmap
bvec3 height_coord; ///< Toggles which one of the 3 coords is the displacement axis
double objmin; ///< Optional, real OBJ lowest displacement coordinate value
double objmax; ///< Optional, real OBJ highest displacement coordinate value
enum file_type ///< Talks about what kind of heightmap values we should output
{
u8, u16, u32, f32, ///< Binary 8/16/32 unsigned and 32 bit float
tu8, tu16, tu32, tf32 ///< Same, but in text variant
}
ftype; ///< The selected heightmap file
};
//
static param_type parse_cli (std::vector<std::string> const& args);
//
static std::string validate_params (param_type const& params);
/// Just inits the app parameters.
obj2hmap (param_type const& p) : params (p) {};
/// Empty dtor
~ obj2hmap () {};
//
void read_obj ();
/// Peek at the read up point cloud data
auto const& obj_vertices () const {
return xyz;
}
/// Report the axis aligned bounding box of the point cloud data
auto obj_aabb () const {
return std::make_pair (blo, bhi);
}
//
void make_grid ();
//
void dump_heightmap ();
private:
param_type params; ///< The input to the app
dvec3 blo; ///< Lowest corner of the obj bounding box
dvec3 bhi; ///< Highest corner of the obj bounding box
std::vector<dvec3> xyz; ///< The point cloud data coming from the obj file
std::vector<dvec3::value_type> grid; ///< The integer XY grid of height values
/// Detects which is height/displacement axis
std::size_t find_disp_axis () const
{
return std::find (params.height_coord.cbegin (), params.height_coord.cend (), true)
- params.height_coord.cbegin ();
}
/// Report vertices size on all non-height dimensions.
std::size_t accumulate_nondisp_size () const
{
size_t acc = 1;
for (size_t n = params.hmap_size.size (), i = 0; i < n; ++i)
if (!params.height_coord[i])
acc *= params.hmap_size[i];
return acc;
}
};
//--------------------------------------------------------------------------------------------------
/**
* Create application parameters out of the C++ main() arguments
*
* The arguments are expected to be (in any order):
* * obj and then heightmap file
* * heightmap dimensions in hex/dec X Y Z format.
* * One of X Y or Z which shows the actual height of the displacement (e.g. height of terrain)
* * Optionally, one of the obj2hmap#param_type#file_type members in text format
* * --help or so - this makes this func to throw with the message
*
* @param args as reported by main() (e.g. the first one is the exe name path)
*/
obj2hmap::param_type obj2hmap::parse_cli (std::vector<std::string> const& args)
{
using namespace std;
param_type p;
p.objmin = numeric_limits<decltype(p.objmin)>::quiet_NaN ();
p.objmax = numeric_limits<decltype(p.objmax)>::quiet_NaN ();
p.hmap_size.fill (0);
p.height_coord.fill (false);
for (auto& arg: args)
{
if (arg == "x" || arg == "X")
{
p.height_coord[0] = true;
continue;
}
if (arg == "y" || arg == "Y")
{
p.height_coord[1] = true;
continue;
}
if (arg == "z" || arg == "Z")
{
p.height_coord[2] = true;
continue;
}
if (arg == "u8") {
p.ftype = param_type::u8;
continue;
}
if (arg == "u16") {
p.ftype = param_type::u16;
continue;
}
if (arg == "u32") {
p.ftype = param_type::u32;
continue;
}
if (arg == "f32") {
p.ftype = param_type::f32;
continue;
}
if (arg == "tu8") {
p.ftype = param_type::tu8;
continue;
}
if (arg == "tu16") {
p.ftype = param_type::tu16;
continue;
}
if (arg == "tu32") {
p.ftype = param_type::tu32;
continue;
}
if (arg == "tf32") {
p.ftype = param_type::tf32;
continue;
}
try
{
bool succ = false;
int n = stoi (arg, nullptr, 0);
if (n > 0)
for (auto& d: p.hmap_size) if (!d)
{
d = static_cast<unsigned> (n);
succ = true;
break;
}
if (succ) continue;
}
catch (exception&)
{}
try
{
auto n = stod (arg);
if (isnan (p.objmin))
{
p.objmin = n;
continue;
}
if (isnan (p.objmax))
{
p.objmax = n;
continue;
}
}
catch (exception&)
{}
if (p.obj.empty ())
{
p.obj = arg;
continue;
}
if (p.hmap.empty ())
{
p.hmap = arg;
continue;
}
}
return p;
}
//--------------------------------------------------------------------------------------------------
/**
* Validation of the paramaters (the object does not assumes such).
*
* @param p to check
* @return an human-readable error message if any issue was found
*/
std::string obj2hmap::validate_params (param_type const& p)
{
using namespace std;
if ([&p] () -> bool {
ifstream f;
f.open (p.obj);
return !f.is_open ();
} ())
return "An input Wavefront *.obj file was not opened!";
if ([&p] () -> bool {
ofstream f;
f.open (p.hmap, ios_base::app);
return !f.is_open ();
} ())
return "An output heightmap file was not opened!";
for (auto n: p.hmap_size)
if (n < 1)
return "The heightmap size parameter is invalid!";
if (1 != accumulate (p.height_coord.cbegin (), p.height_coord.cend (),
0, [] (int r, bool x) { return r += int (x); }))
return "The heightmap displacement axis parameter is invalid!";
if (isnan (p.objmin) ^ isnan (p.objmax))
return "Either none, or both OBJ real min/max values should be set!";
return "";
}
//--------------------------------------------------------------------------------------------------
/**
* Parse and extract up the *.obj file vertices.
*
* A terrain mesh of 8k can reach up like 1GiB of file size. So this can take few minutes, depending
* on the system.
*
* This function should be safe to be called multiple times, though it does not make sense for the
* current application. Note that used RAM can increase a lot - a 8k by 8k map is like 768MiB.
*
* After the call to this function, the @ref xyz and @ref blo / @ref bhi members will have actual
* values.
*/
void obj2hmap::read_obj ()
{
using namespace std;
ifstream obj (params.obj);
blo.fill (numeric_limits<decltype(blo)::value_type>::max ());
bhi.fill (numeric_limits<decltype(bhi)::value_type>::min ());
// Good guess is that the requested hmap is 1:1 with the supplied OBJ vertices
xyz.clear ();
xyz.reserve (accumulate_nondisp_size ());
// As getline, but w/o the memory store - useless optimization.
auto skipline = [] (ifstream& is) {
for (char c; is.get (c) && c != '\n'; );
};
for (; obj; skipline (obj))
{
char t[2] = { 0, 0 };
obj.read (t, 2);
if (t[0] != 'v' || t[1] != ' ') // Wavefront's vertex type text line
continue;
dvec3 v;
for (size_t i = 0; i < v.size (); ++i)
{
obj >> v[i];
blo[i] = min (blo[i], v[i]);
bhi[i] = max (bhi[i], v[i]);
}
xyz.push_back (v);
}
xyz.shrink_to_fit ();
}
//--------------------------------------------------------------------------------------------------
/**
* Fit the point cloud into integer grid (i.e. plane or heightmap)
*
* It is expected that the point cloud is already created with #read_obj(). The non-height
* dimensions are fit into integer grid by rounding. The height dimension is just carried over.
*
* At the end of this state we will have the #grid object populated in 2d.
*/
void obj2hmap::make_grid ()
{
using namespace std;
grid.clear ();
grid.resize (accumulate_nondisp_size (), 0);
dvec3 gridsz;
for (size_t n = gridsz.size (), i = 0; i < n; ++i)
{
gridsz[i] = (params.hmap_size[i] - 1) / (bhi[i] - blo[i]);
gridsz[i] *= !params.height_coord[i];
}
size_t haxis = find_disp_axis ();
for (size_t end = xyz.size (), beg = 0; beg < end; ++beg)
{
size_t ndx = 0, ndxmul = 1;
for (size_t n = gridsz.size (), i = 0; i < n; ++i)
{
auto p = round ((xyz[beg][i] - blo[i]) * gridsz[i]);
ndx += static_cast<size_t> (p) * ndxmul;
ndxmul = ndxmul * !params.height_coord[i] * params.hmap_size[i]
+ ndxmul * params.height_coord[i];
}
grid.at (ndx) = xyz[beg][haxis];
}
}
//--------------------------------------------------------------------------------------------------
/// Utility to allow basic_ostream to write unformatted objects (apart of char_type pointers).
template<class CV, class V, class S>
static inline void bstream_write (S& os, V val)
{
CV v = static_cast<CV> (std::is_integral<CV>::value ? std::lround (val) : val);
os.write (reinterpret_cast<typename S::char_type*> (&v), sizeof v);
}
/**
* Dump the grid plane onto a binary file of proper format.
*
* At this point of time, the #grid should be already available and using the other parameters we
* can write a file. Size of each file unit (8 bit, 16 bit or 32 bit) is decided by looking at the
* size of the height axis.
*/
void obj2hmap::dump_heightmap ()
{
using namespace std;
ofstream file (params.hmap, ios_base::binary);
size_t haxis = find_disp_axis ();
double objmin = blo[haxis];
double objmax = bhi[haxis];
if (!isnan (params.objmin) && !isnan (params.objmax))
{
objmin = min (objmin, params.objmin);
objmax = max (objmax, params.objmax);
}
auto height = params.hmap_size.at (haxis) / (objmax - objmin);
for (auto h: grid)
{
auto val = (h - objmin) * height;
switch (params.ftype) {
case param_type::u8 : bstream_write<uint8_t > (file, val); break;
default :
case param_type::u16 : bstream_write<uint16_t> (file, val); break;
case param_type::u32 : bstream_write<uint32_t> (file, val); break;
case param_type::f32 : bstream_write<float > (file, val); break;
case param_type::tu8 : file << static_cast<uint8_t > (val) << '\n'; break;
case param_type::tu16: file << static_cast<uint16_t> (val) << '\n'; break;
case param_type::tu32: file << static_cast<uint32_t> (val) << '\n'; break;
case param_type::tf32: file << static_cast<float > (val) << '\n'; break;
};
}
}
//--------------------------------------------------------------------------------------------------
/**
* The venerable C++ main() function.
*/
int main (int argc, const char* argv[])
{
using namespace std;
const char* info =
"obj2hmap - An Wavefront *.obj file convertor to binary heightmap file\n"
"\n"
"obj2hmap OBJ HMAP SIZE_X SIZE_Y SIZE_Z x|y|z [OBJ_HEIGHT] [[t]u|f<8|16|32>]\n"
"OBJ - is the input obj file\n"
"HMAP - is the output binary heightmap file\n"
"SIZE_XYZ - the three integer dimensions of the heightmap into which to put the obj\n"
"x y z - one of the axes showing the displacement value of the heightmap\n"
"OBJ_HEIGHT - if given, try to fit the obj height into these instead of the full SIZE_Y\n"
"[t]u|f[n] - an optional type of heightmap values, binary or text 't'. Default u16.\n"
"\n"
"Example:\n"
"obj2hmap terrain.obj terrain.r16 4096 0xFFFF 4096 y 0.0 0.02\n"
;
try
{
// CLI
vector<string> args (argv + 1, argv + argc);
for (auto& str: args)
if (str == "--help")
{
cout << info << endl;
return 0;
}
auto p = obj2hmap::parse_cli (args);
auto err = obj2hmap::validate_params (p);
if (err.size ())
{
cerr << err << endl;
return 1;
}
obj2hmap tool (move (p));
// Parse *.obj
cout << "Read obj file..." << endl;
tool.read_obj ();
cout << "Parsed vertices: " << tool.obj_vertices ().size () << '\n'
<< "Bounding box :";
auto aabb = tool.obj_aabb ();
for (auto i: aabb.first) cout << ' ' << i;
cout << ';';
for (auto i: aabb.second) cout << ' ' << i;
cout << endl;
// Create integer grid
cout << "Fit into grid..." << endl;
tool.make_grid ();
// Dump data
cout << "Dump heights..." << endl;
tool.dump_heightmap ();
cout << "Done." << endl;
}
catch (exception& ex)
{
cerr << ex.what () << endl;
return 1;
}
return 0;
}
//--------------------------------------------------------------------------------------------------