forked from admtrv/objcurses
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
614 lines (530 loc) · 17.4 KB
/
Copy pathmain.cpp
File metadata and controls
614 lines (530 loc) · 17.4 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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
/*
* main.cpp
*/
#ifdef _WIN32
// for msys2 on windows platform use
#include <ncurses/ncurses.h>
// but sounds like it does not support it, if I have
// time I will change it all.
#elif
#include <ncurses.h>
#endif
#include <algorithm>
#include <cmath>
#include <filesystem>
#include <iostream>
#include <optional>
#include <string>
#include <vector>
#include <chrono>
#include <thread>
#include "entities/geometry/object.h"
#include "entities/rendering/buffer.h"
#include "entities/rendering/renderer.h"
#include "utils/tools.h"
#include "config.h"
#include "version.h"
#ifdef ASAN_OPTIONS
extern "C" const char *__asan_default_options() {
return ASAN_OPTIONS;
}
#endif
using SteadyClock = std::chrono::steady_clock;
const auto t0 = SteadyClock::now();
// ncurses
enum class Theme {
Dark = 1,
Light = 2,
Transparent = 3
};
static int g_hud_pair = 0; // hud color pair
void init_ncurses()
{
initscr(); // start ncurses mode
noecho(); // disable echoing of typed characters
curs_set(0); // hide the cursor
keypad(stdscr, true); // enable special keys (arrows, etc.)
timeout(1); // make getch() non-blocking
}
void init_colors(const std::vector<Material> &materials, Theme theme)
{
//OK, this is the way that Linux use ncurses to show color
//but for Windows, I think I should change it all by using
//ANSI things
//Maybe some platform isn't Linux but the things are still
//available for them, so I use _WIN32 to use for Windows
#ifdef _WIN32
if (!has_colors())
return;
start_color();
const short BG_DEFAULT = -1;
short bg = COLOR_BLACK;
short hud = COLOR_WHITE;
switch (theme)
{
case Theme::Dark: bg = COLOR_BLACK; hud = COLOR_WHITE; break;
case Theme::Light: bg = COLOR_WHITE; hud = COLOR_BLACK; break;
case Theme::Transparent: bg = BG_DEFAULT; hud = COLOR_WHITE; break;
}
if (bg == BG_DEFAULT)
use_default_colors();
const size_t max_pairs = static_cast<size_t>(COLOR_PAIRS > 2 ? COLOR_PAIRS - 2 : 0);
size_t limit = std::min(materials.size(), max_pairs);
// 最近邻 8 色映射(更稳健,避免白被判成黄)
auto map_to_basic_color = [](float r, float g, float b) -> short {
r = std::clamp(r, 0.0f, 1.0f);
g = std::clamp(g, 0.0f, 1.0f);
b = std::clamp(b, 0.0f, 1.0f);
// 如果想用伽马校正以更贴近视觉感知,可以启用下面两行
// auto gamma = [](float v){ return std::pow(v, 2.2f); };
// r = gamma(r); g = gamma(g); b = gamma(b);
const std::array<std::pair<short, std::array<float,3>>,8> centers = {{
{COLOR_BLACK, {0.0f, 0.0f, 0.0f}},
{COLOR_RED, {1.0f, 0.0f, 0.0f}},
{COLOR_GREEN, {0.0f, 1.0f, 0.0f}},
{COLOR_YELLOW, {1.0f, 1.0f, 0.0f}},
{COLOR_BLUE, {0.0f, 0.0f, 1.0f}},
{COLOR_MAGENTA,{1.0f, 0.0f, 1.0f}},
{COLOR_CYAN, {0.0f, 1.0f, 1.0f}},
{COLOR_WHITE, {1.0f, 1.0f, 1.0f}}
}};
short best = COLOR_WHITE;
float best_dist = std::numeric_limits<float>::infinity();
std::array<float,3> src{r,g,b};
for (const auto &c : centers) {
const auto ¢ = c.second;
float dr = src[0] - cent[0];
float dg = src[1] - cent[1];
float db = src[2] - cent[2];
float d2 = dr*dr + dg*dg + db*db;
if (d2 < best_dist) { best_dist = d2; best = c.first; }
}
return best;
};
// RGB -> xterm-256 index (choose between color cube and gray)
auto rgb_to_xterm256 = [](float r, float g, float b) -> int {
r = std::clamp(r, 0.0f, 1.0f);
g = std::clamp(g, 0.0f, 1.0f);
b = std::clamp(b, 0.0f, 1.0f);
int ri = static_cast<int>(std::round(r * 5.0f));
int gi = static_cast<int>(std::round(g * 5.0f));
int bi = static_cast<int>(std::round(b * 5.0f));
ri = std::clamp(ri, 0, 5);
gi = std::clamp(gi, 0, 5);
bi = std::clamp(bi, 0, 5);
int cube_index = 16 + 36 * ri + 6 * gi + bi;
float lum = 0.2126f * r + 0.7152f * g + 0.0722f * b;
int gray_level = static_cast<int>(std::round(lum * 23.0f));
gray_level = std::clamp(gray_level, 0, 23);
int gray_index = 232 + gray_level;
auto cube_center = [&](int r6, int g6, int b6){
return std::array<float,3>{ r6 / 5.0f, g6 / 5.0f, b6 / 5.0f };
};
auto gray_center = [&](int gray){
float v = gray / 23.0f;
return std::array<float,3>{ v, v, v };
};
auto dist2 = [](const std::array<float,3>& a, const std::array<float,3>& b){
float dr = a[0]-b[0], dg = a[1]-b[1], db = a[2]-b[2];
return dr*dr + dg*dg + db*db;
};
auto ccenter = cube_center(ri, gi, bi);
auto gcenter = gray_center(gray_level);
std::array<float,3> orig{r,g,b};
float d_cube = dist2(orig, ccenter);
float d_gray = dist2(orig, gcenter);
return (d_gray < d_cube) ? gray_index : cube_index;
};
const bool can_change = can_change_color() != 0;
const int n_colors = COLORS;
const bool has_256 = (n_colors >= 256);
for (size_t i = 0; i < limit; ++i)
{
int pair = static_cast<int>(i) + 1;
const auto &d = materials[i].diffuse; // x,y,z in 0..1
if (has_256)
{
int mapped = rgb_to_xterm256(d.x, d.y, d.z);
if (mapped >= n_colors) mapped = mapped % n_colors;
init_pair(pair, mapped, bg);
}
else if (can_change)
{
int color_index = pair;
if (color_index < n_colors)
{
init_color(color_index,
static_cast<short>(std::clamp(d.x, 0.0f, 1.0f) * 1000.0f),
static_cast<short>(std::clamp(d.y, 0.0f, 1.0f) * 1000.0f),
static_cast<short>(std::clamp(d.z, 0.0f, 1.0f) * 1000.0f));
init_pair(pair, color_index, bg);
}
else
{
short mapped = map_to_basic_color(d.x, d.y, d.z);
init_pair(pair, mapped, bg);
}
}
else
{
short mapped = map_to_basic_color(d.x, d.y, d.z);
init_pair(pair, mapped, bg);
}
}
g_hud_pair = static_cast<int>(limit) + 1;
if (g_hud_pair < COLOR_PAIRS)
init_pair(g_hud_pair, hud, bg);
bkgd(' ' | COLOR_PAIR(g_hud_pair));
#elif
if (!has_colors() || !can_change_color())
return;
start_color();
const short BG_DEFAULT = -1;
short bg;
short hud;
switch (theme)
{
case Theme::Dark:
bg = COLOR_BLACK;
hud = COLOR_WHITE;
break;
case Theme::Light:
bg = COLOR_WHITE;
hud = COLOR_BLACK;
break;
case Theme::Transparent:
bg = BG_DEFAULT;
hud = COLOR_WHITE;
break;
}
if (bg == BG_DEFAULT)
use_default_colors();
size_t limit = std::min(materials.size(), static_cast<size_t>(COLOR_PAIRS - 2));
for (size_t i = 0; i < limit; i++)
{
int pair = static_cast<int>(i) + 1;
const auto &d = materials[i].diffuse; // 0–1
if (can_change_color())
init_color(pair,
static_cast<short>(std::clamp(d.x, 0.0f, 1.0f) * 1000.0f),
static_cast<short>(std::clamp(d.y, 0.0f, 1.0f) * 1000.0f),
static_cast<short>(std::clamp(d.z, 0.0f, 1.0f) * 1000.0f));
init_pair(pair, pair, bg);
}
g_hud_pair = static_cast<int>(limit) + 1;
if (g_hud_pair < COLOR_PAIRS)
init_pair(g_hud_pair, hud, bg);
bkgd(' ' | COLOR_PAIR(g_hud_pair));
#endif
}
// cli
static void print_help()
{
std::cout <<
"Usage: " << APP_NAME << " [OPTIONS] <file.obj>\n"
"\n"
"Options:\n"
" -c, --color <theme> Enable colors support, optional theme {dark|light|transparent}\n"
" -l, --light Disable light rotation\n"
" -a, --animate <deg> Start with animated object, optional speed [default: " << std::fixed << std::setprecision(1) << ANIMATION_STEP << std::defaultfloat << " deg/s]\n"
" -z, --zoom <x> Provide initial zoom [default: " << std::fixed << std::setprecision(1) << ZOOM_START << std::defaultfloat << " x]\n"
" --flip Flip faces winding order\n"
" --invert-x Flip geometry along X axis\n"
" --invert-y Flip geometry along Y axis\n"
" --invert-z Flip geometry along Z axis\n"
" -h, --help Print help\n"
" -v, --version Print version\n"
"\n"
"Controls:\n"
" ←, h, a Rotate left\n"
" →, l, d Rotate right\n"
" ↑, k, w Rotate up\n"
" ↓, j, s Rotate down\n"
" +, i Zoom in\n"
" -, o Zoom out\n"
" Tab Toggle HUD\n"
" q Quit\n";
}
static void print_version()
{
std::cout << APP_NAME << " " << APP_VERSION << '\n';
}
struct Args {
std::filesystem::path input_file;
bool color_support = false; // -c / --color
Theme theme = Theme::Dark;
bool static_light = false; // -l / --light
bool flip_faces = false; // -f / --flip
bool invert_x = false; // -x / --invert-x
bool invert_y = false; // -y / --invert-y
bool invert_z = false; // -z / --invert-z
bool animate = false; // -a / --animate
float speed = ANIMATION_STEP; // deg/s
float zoom = ZOOM_START; // -z / --zoom
};
static Args parse_args(int argc, char **argv)
{
Args a;
for (int i = 1; i < argc; ++i)
{
const std::string_view arg{argv[i]};
// help
if (arg == "-h" || arg == "--help")
{
print_help();
std::exit(0);
}
// version
if (arg == "-v" || arg == "--version")
{
print_version();
std::exit(0);
}
// flags
if (arg == "-c" || arg == "--color")
{
a.color_support = true;
if (i + 1 < argc && argv[i + 1][0] != '-')
{
std::string_view next{argv[i + 1]};
if (next == "dark")
{
a.theme = Theme::Dark;
++i;
}
else if (next == "light")
{
a.theme = Theme::Light;
++i;
}
else if (next == "transparent")
{
a.theme = Theme::Transparent;
++i;
}
// else next - file name
}
}
else if (arg == "-l" || arg == "--light")
{
a.static_light = true;
}
else if (arg == "-a" || arg == "--animate")
{
a.animate = true;
if (i + 1 < argc && argv[i + 1][0] != '-')
{
if (auto val = safe_stof(argv[i + 1]); val)
{
a.speed = val.value();
++i;
}
// else - file name
}
}
else if (arg == "-z" || arg == "--zoom")
{
if (++i == argc)
{
std::cerr << "error: zoom needs value\n";
std::exit(1);
}
auto val = safe_stof(argv[i]);
if (!val)
{
std::cerr << "error: invalid zoom value\n";
std::exit(1);
}
a.zoom = val.value();
}
else if (arg == "--flip")
{
a.flip_faces = true;
}
else if (arg == "--invert-x")
{
a.invert_x = true;
}
else if (arg == "--invert-y")
{
a.invert_y = true;
}
else if (arg == "--invert-z")
{
a.invert_z = true;
}
else if (arg[0] != '-')
{
if (!a.input_file.empty())
{
std::cerr << "error: more arguments than expected\n";
std::exit(1);
}
a.input_file = arg;
}
// unknown
else
{
std::cerr << "unknown option: " << arg << '\n';
std::cerr << "type '--help' for usage\n";
std::exit(1);
}
}
if (a.input_file.empty())
{
std::cerr << "error: no input file\n";
std::cerr << "type '--help' for usage\n";
std::exit(1);
}
return a;
}
// helpers
void render_hud(const Camera &cam, const float fps)
{
if (g_hud_pair)
attron(COLOR_PAIR(g_hud_pair));
mvprintw(0, 0, "framerate %6d fps", static_cast<int>(std::round(fps)));
mvprintw(1, 0, "zoom %6.1f x", cam.zoom);
mvprintw(2, 0, "azimuth %6.1f deg", clamp0(rad2deg(cam.azimuth)));
mvprintw(3, 0, "altitude %6.1f deg", clamp0(rad2deg(cam.altitude)));
if (g_hud_pair)
attroff(COLOR_PAIR(g_hud_pair));
}
void handle_control(const int ch, Camera &cam)
{
switch (ch)
{
// keys / vim / wasd
case KEY_LEFT: case 'h': case 'H': case 'a' : case 'A': // left rotation
cam.rotate_left();
break;
case KEY_RIGHT: case 'l': case 'L': case 'd': case 'D': // right rotation
cam.rotate_right();
break;
case KEY_UP: case 'k': case 'K': case 'w': case 'W': // up rotation
cam.rotate_up();
break;
case KEY_DOWN: case 'j': case 'J': case 's': case 'S': // down rotation
cam.rotate_down();
break;
// +- / io
case '+': case '=': case 'i': case 'I': // zoom in
cam.zoom_in();
break;
case '-': case 'o': case 'O': // zoom out
cam.zoom_out();
break;
default:
break;
}
}
// main
int main(int argc, char **argv)
{
const Args args = parse_args(argc, argv);
// load object
Object obj;
if (!obj.load(args.input_file.string(), args.color_support))
{
return 1;
}
// normalize to unit cube
obj.normalize();
// resize to make model >= 0.5 screen size
obj.scale(3.0f);
// flip faces winding order
if (args.flip_faces)
obj.flip_faces();
// invert along axes
if (args.invert_x)
obj.invert_x();
if (args.invert_y)
obj.invert_y();
if (args.invert_z)
obj.invert_z();
// init curses
init_ncurses();
// init colors
if (args.color_support)
init_colors(obj.materials, args.theme);
// buffer
int rows;
int cols;
getmaxyx(stdscr, rows, cols);
const float logical_y = 2.0f;
const float logical_x = logical_y * static_cast<float>(cols) / (static_cast<float>(rows) * CHAR_ASPECT_RATIO);
Buffer buf(static_cast<unsigned int>(cols), static_cast<unsigned int>(rows), logical_x, logical_y);
// view
Camera cam(args.zoom); // constructor with zoom
Light light; // default
bool hud = false;
// animation
bool rotate = args.animate;
auto last = SteadyClock::now();
// optimizing drawing
bool needs_redraw = true;
// main render loop
while (true)
{
auto now = SteadyClock::now();
float dt = std::chrono::duration<float>(now - last).count(); // seconds since previous frame
last = now;
float fps = dt > 0.f ? 1.f / dt : 0.f;
if (rotate) {
cam.rotate_left(args.speed * dt);
needs_redraw = true;
}
// handle key
int ch = getch();
if (ch == KEY_RESIZE)
{
getmaxyx(stdscr, rows, cols);
const float lx = logical_y * static_cast<float>(cols) / (static_cast<float>(rows) * CHAR_ASPECT_RATIO);
buf = Buffer(static_cast<unsigned int>(cols), static_cast<unsigned int>(rows), lx, logical_y);
needs_redraw = true;
}
else if (ch == 'q' || ch == 'Q') // exit
{
break;
}
else if (ch == '\t') // toggle hud
{
hud = !hud;
needs_redraw = true;
}
else if (ch != ERR)
{
rotate = false; // stop animation on first movement
handle_control(ch, cam); // handle camera control
needs_redraw = true;
}
// redrawing
if (needs_redraw)
{
// clear buffer
buf.clear();
// render model
Renderer::render(buf, obj, cam, light, args.static_light, args.color_support);
move(0, 0);
buf.printw();
// render hud
if (hud)
{
render_hud(cam, fps);
}
// draw buffer
refresh();
needs_redraw = false;
}
else if (hud) // update only hud
{
render_hud(cam, fps);
refresh();
}
// limiting fps
auto frame_deadline = now + std::chrono::duration<float>(FRAME_DURATION);
std::this_thread::sleep_until(frame_deadline);
}
endwin();
return 0;
}