-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbellatui.cpp
More file actions
1764 lines (1588 loc) · 70.4 KB
/
bellatui.cpp
File metadata and controls
1764 lines (1588 loc) · 70.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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* BellaTUI - A Client-Server Rendering Application
*
* This application provides a command-line interface for a rendering system called Bella.
* It consists of two main parts:
* 1. A server component that handles rendering operations
* 2. A client component that sends commands and files to the server
*
* The application uses ZeroMQ (ZMQ) for secure network communication between client and server.
* Key features:
* - Secure communication using CURVE encryption
* - File transfer capabilities (.bsz files)
* - Real-time rendering status updates
* - Heartbeat monitoring to check connection status
*/
#include <iostream>
#include <fstream>
#include <thread>
#include <zmq.hpp>
#include <vector>
#include <chrono>
#include <filesystem>
#include <cstdio> // For sprintf
#include <string>
#include <sstream> // For string streams
#include <atomic>
#include <mutex> // Add this line for std::mutex and std::lock_guard
#include <map> // Add this line for std::map
#include <cstdlib> // For std::system
#include <stdexcept> // For std::runtime_error
#ifdef _WIN32
#include <windows.h> // For ShellExecuteW
#include <shellapi.h> // For ShellExecuteW
#include <codecvt> // For wstring_convert
#elif defined(__APPLE__) || defined(__linux__)
#include <unistd.h> // For fork, exec
#include <sys/wait.h> // For waitpid
#endif
#include <efsw/FileSystem.hpp> // For file watching
#include <efsw/System.hpp> // For file watching
#include <efsw/efsw.hpp> // For file watching
#include <iostream>
#include <signal.h>
#include "../bella_engine_sdk/src/bella_sdk/bella_engine.h" // For rendering
#include "../bella_engine_sdk/src/dl_core/dl_fs.h" // For rendering
using namespace dl;
using namespace dl::bella_sdk;
//#include "../oom/oom_bella_long.h"
//#include "../oom/oom_bella_scene.h"
//#include "../oom/oom_misc.h" // common misc code
#include "../oom/oom_license.h" // common license
//#include "../oom/oom_voxel_vmax.h" // common vmax voxel code and structures
//#include "../oom/oom_voxel_ogt.h" // common opengametools voxel conversion wrappers
//Forward declarations
std::string bellaSliderPreviewsHTML();
//dl::Mat4 oomer_orbit(dl::Mat4 beginCamXform, int currentFrame, int totalFrames);
/// A class that manages a queue of files to render with both FIFO order and fast lookups
class RenderQueue {
public:
// Default constructor
RenderQueue() = default;
// Move constructor
RenderQueue(RenderQueue&& other) noexcept {
std::lock_guard<std::mutex> lock(other.mutex);
pathVector = std::move(other.pathVector);
pathMap = std::move(other.pathMap);
}
// Move assignment operator
RenderQueue& operator=(RenderQueue&& other) noexcept {
if (this != &other) {
std::lock_guard<std::mutex> lock1(mutex);
std::lock_guard<std::mutex> lock2(other.mutex);
pathVector = std::move(other.pathVector);
pathMap = std::move(other.pathMap);
}
return *this;
}
// Delete copy operations since mutexes can't be copied
RenderQueue(const RenderQueue&) = delete;
RenderQueue& operator=(const RenderQueue&) = delete;
// Add a file to the queue if it's not already there
bool push(const dl::String& path) {
std::lock_guard<std::mutex> lock(mutex);
if (pathMap.find(path) == pathMap.end()) {
pathVector.push_back(path);
pathMap[path] = true;
return true;
}
return false;
}
// Get the next file to render (FIFO order)
bool pop(dl::String& outPath) {
std::lock_guard<std::mutex> lock(mutex);
if (!pathVector.empty()) {
outPath = pathVector.front();
pathVector.erase(pathVector.begin());
pathMap.erase(outPath);
return true;
}
return false;
}
// Remove a specific file by name
bool remove(const dl::String& path) {
std::lock_guard<std::mutex> lock(mutex);
if (pathMap.find(path) != pathMap.end()) {
// Remove from vector using erase-remove idiom
pathVector.erase(
std::remove(pathVector.begin(), pathVector.end(), path),
pathVector.end()
);
// Remove from map
pathMap.erase(path);
return true;
}
return false;
}
// Check if a file exists in the queue
bool contains(const dl::String& path) const {
std::lock_guard<std::mutex> lock(mutex);
return pathMap.find(path) != pathMap.end();
}
// Get the number of files in the queue
size_t size() const {
std::lock_guard<std::mutex> lock(mutex);
return pathVector.size();
}
// Check if the queue is empty
bool empty() const {
std::lock_guard<std::mutex> lock(mutex);
return pathVector.empty();
}
// Clear all files from the queue
void clear() {
std::lock_guard<std::mutex> lock(mutex);
pathVector.clear();
pathMap.clear();
}
private:
std::vector<dl::String> pathVector; // Maintains FIFO order
std::map<dl::String, bool> pathMap; // Enables fast lookups
mutable std::mutex mutex; // Thread safety
};
std::atomic<bool> active_render(false);
//bool active_render(false);
//RenderQueue renderQueue; // Replace the old vector and map with our new class
//std::mutex renderQueueMutex; // Add mutex for thread safety
//std::vector<dl::String> renderDelete; // This is the efsw queue for when we delete a file
//std::mutex renderDeleteMutex; // Add mutex for thread safety
dl::String currentRender;
std::mutex currentRenderMutex; // Add mutex for thread safety
// Queues for incoming files from the efsw watcher
RenderQueue incomingDeleteQueue;
RenderQueue incomingRenderQueue;
std::mutex incomingDeleteQueueMutex; // Add mutex for thread safety
std::mutex incomingRenderQueueMutex; // Add mutex for thread safety
/// Processes a file action libefsw
class UpdateListener : public efsw::FileWatchListener {
public:
UpdateListener() : should_stop_(false) {}
void stop() {
should_stop_ = true;
}
std::string getActionName( efsw::Action action ) {
switch ( action ) {
case efsw::Actions::Add:
return "Add";
case efsw::Actions::Modified:
return "Modified";
case efsw::Actions::Delete:
return "Delete";
case efsw::Actions::Moved:
return "Moved";
default:
return "Bad Action";
}
}
void handleFileAction( efsw::WatchID watchid, const std::string& dir,
const std::string& filename, efsw::Action action,
std::string oldFilename = "" ) override {
if (should_stop_) return; // Early exit if we're stopping
std::string actionName = getActionName( action );
/*std::cout << "Watch ID " << watchid << " DIR ("
<< dir + ") FILE (" +
( oldFilename.empty() ? "" : "from file " + oldFilename + " to " ) +
filename + ") has event "
<< actionName << std::endl;*/
if (actionName == "Delete") {
dl::String belPath = (dir + filename).c_str();
if (belPath.endsWith(".bsz") || belPath.endsWith(".zip")) {
{
std::lock_guard<std::mutex> lock(incomingDeleteQueueMutex);
if (!incomingDeleteQueue.contains(belPath)) {
incomingDeleteQueue.push(belPath);
std::cout << "\n==" << "STOP RENDER: " << belPath.buf() << "\n==" << std::endl;
}
}
}
}
if (actionName == "Add" || actionName == "Modified") {
dl::String belPath = (dir + filename).c_str();
dl::String parentPath = dir.c_str();
//std::cout << "parentPath: " << parentPath.buf() << std::endl;
if (should_stop_) return; // Check again before starting render
if (parentPath.endsWith("download")) {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
return;
}
if (belPath.endsWith(".bsz") || belPath.endsWith(".zip") && !parentPath.endsWith("download/")) {
{
std::lock_guard<std::mutex> lock(incomingRenderQueueMutex);
if (!incomingRenderQueue.contains(belPath)) {
incomingRenderQueue.push(belPath);
std::cout << "\n==" << "RENDER QUEUED: " << belPath.buf() << "\n==" << std::endl;
}
}
}
}
}
private:
std::atomic<bool> should_stop_; // ctrl-c was not working, so we use this to stop the thread
};
// Global state variables
//std::string initializeGlobalLicense(); // Function to return license text
//std::string initializeGlobalThirdPartyLicences(); // Function to return third-party licenses
std::atomic<bool> connection_state (false); // Tracks if client/server are connected
std::atomic<bool> abort_state (false); // Used to signal program termination
std::atomic<bool> server (true); // Indicates if running in server mode
UpdateListener* global_ul = nullptr; // Global pointer to UpdateListener
// Function declarations
std::string get_pubkey_from_srv(std::string server_address, uint16_t publickey_port); // Gets server's public key for encryption
bool STOP = false;
void sigend( int ) {
std::cout << std::endl << "Bye bye" << std::endl;
STOP = true;
if (global_ul) { // Use the global pointer
global_ul->stop();
}
// Give a short time for cleanup
std::this_thread::sleep_for(std::chrono::milliseconds(100));
exit(0); // Force exit after cleanup
}
efsw::WatchID handleWatchID( efsw::WatchID watchid ) {
switch ( watchid ) {
case efsw::Errors::FileNotFound:
case efsw::Errors::FileRepeated:
case efsw::Errors::FileOutOfScope:
case efsw::Errors::FileRemote:
case efsw::Errors::WatcherFailed:
case efsw::Errors::Unspecified: {
std::cout << efsw::Errors::Log::getLastErrorLog().c_str() << std::endl;
break;
}
default: {
std::cout << "Added WatchID: " << watchid << std::endl;
}
}
return watchid;
}
static int s_logCtx = 0;
static void log(void* /*ctx*/, LogType type, const char* msg)
{
switch (type)
{
case LogType_Info:
DL_PRINT("[INFO] %s\n", msg);
break;
case LogType_Warning:
DL_PRINT("[WARN] %s\n", msg);
break;
case LogType_Error:
DL_PRINT("[ERROR] %s\n", msg);
break;
case LogType_Custom:
DL_PRINT("%s\n", msg);
break;
}
}
// Main client communication thread
void client_thread( std::string server_pkey,
std::string client_pkey,
std::string client_skey,
std::string server_address,
uint16_t command_port);
// Utility function to open files with system default program
void openFileWithDefaultProgram(const std::string& filePath);
// Helper function to check file extensions
bool ends_with_suffix(const std::string& str, const std::string& suffix);
// Server function to handle initial key exchange
void pkey_server(const std::string& pub_key, uint16_t publickey_port);
/*
* MyEngineObserver Class
* This class receives callbacks from the Bella rendering engine to track rendering progress.
* It implements the EngineObserver interface and provides methods to:
* - Handle render start/stop events
* - Track rendering progress
* - Handle error conditions
* - Store and retrieve the current progress state
*/
struct MyEngineObserver : public EngineObserver
{
public:
// Called when a rendering pass starts
void onStarted(String pass) override
{
std::cout << "Started pass " << pass.buf() << std::endl;
logInfo("Started pass %s", pass.buf());
}
// Called to update the current status of rendering
//void onStatus(String pass, String status) override
//{
// logInfo("%s [%s]", status.buf(), pass.buf());
//}
// Called to update rendering progress (percentage, time remaining, etc)
void onProgress(String pass, Progress progress) override
{
std::cout << progress.toString().buf() << std::endl;
setString(new std::string(progress.toString().buf()));
logInfo("%s [%s]", progress.toString().buf(), pass.buf());
}
//void onImage(String pass, Image image) override
//{
// logInfo("We got an image %d x %d.", (int)image.width(), (int)image.height());
//}
// Called when an error occurs during rendering
void onError(String pass, String msg) override
{
logError("%s [%s]", msg.buf(), pass.buf());
}
// Called when a rendering pass completes
void onStopped(String pass) override
{
logInfo("Stopped %s", pass.buf());
active_render = false;
}
// Returns the current progress as a string
std::string getProgress() const {
std::string* currentProgress = progressPtr.load();
if (currentProgress) {
return *currentProgress;
} else {
return "";
}
}
// Cleanup resources in destructor
~MyEngineObserver() {
setString(nullptr);
}
private:
// Thread-safe pointer to current progress string
std::atomic<std::string*> progressPtr{nullptr};
// Helper function to safely update the progress string
void setString(std::string* newStatus) {
std::string* oldStatus = progressPtr.exchange(newStatus);
delete oldStatus; // Clean up old string if it exists
}
};
// Main server thread that handles client requests
void server_thread( std::string server_skey,
uint16_t command_port,
bool test_render,
Engine engine,
MyEngineObserver& engineObserver);
void render_thread( Engine engine,
MyEngineObserver& engineObserver);
/*
* Heartbeat Monitoring System
*
* This function implements a heartbeat mechanism to monitor the connection between client and server.
* It runs in a separate thread and:
* - For server: listens for periodic messages from client
* - For client: sends periodic messages to server
* If either side stops receiving messages, it marks the connection as dead.
*
* Parameters:
* - server_pkey: Server's public key (used by client)
* - server_skey: Server's secret key (used by server)
* - client_pkey: Client's public key (used by client)
* - client_skey: Client's secret key (used by client)
* - is_server: Boolean indicating if running in server mode
* - server_address: Address of the server (used by client)
* - heartbeat_port: Port number for heartbeat communication
*/
void heartbeat_thread( std::string server_pkey,
std::string server_skey,
std::string client_pkey,
std::string client_skey,
bool is_server,
std::string server_address,
uint16_t heartbeat_port ) {
zmq::context_t ctx; // Create ZMQ context
zmq::socket_t heartbeat_sock; // Socket for heartbeat messages
if(is_server) {
// Server mode: Listen for client heartbeats
heartbeat_sock = zmq::socket_t(ctx, zmq::socket_type::rep);
heartbeat_sock.set(zmq::sockopt::curve_server, true);
heartbeat_sock.set(zmq::sockopt::curve_secretkey, server_skey);
std::string url = "tcp://*:" + std::to_string(heartbeat_port);
heartbeat_sock.bind(url);
while(true) {
// Only check heartbeats when client is connected
if (connection_state == true) {
// Wait up to 5 seconds for client heartbeat
zmq::pollitem_t response_item = { heartbeat_sock, 0, ZMQ_POLLIN, 0 };
zmq::poll(&response_item, 1, 5000);
if (response_item.revents & ZMQ_POLLIN) {
// Received heartbeat from client
zmq::message_t message;
heartbeat_sock.recv(message, zmq::recv_flags::none);
heartbeat_sock.send(zmq::message_t("ACK"), zmq::send_flags::dontwait);
} else {
// No heartbeat received - mark connection as dead
std::cout << "Bella Client Lost" << std::endl;
connection_state = false;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
} else {
// Client mode: Send heartbeats to server
zmq::socket_t heartbeat_sock (ctx, zmq::socket_type::req);
// Set up encryption keys
heartbeat_sock.set(zmq::sockopt::curve_serverkey, server_pkey);
heartbeat_sock.set(zmq::sockopt::curve_publickey, client_pkey);
heartbeat_sock.set(zmq::sockopt::curve_secretkey, client_skey);
heartbeat_sock.set(zmq::sockopt::linger, 1);
std::string url = "tcp://" + server_address + ":" + std::to_string(heartbeat_port);
heartbeat_sock.connect(url);
while (true) {
// Check if we should stop
if(abort_state.load()==true) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
if(connection_state == true) {
// Send heartbeat to server
heartbeat_sock.send(zmq::message_t("ACK"), zmq::send_flags::none);
// Wait for server response
zmq::pollitem_t response_item = { heartbeat_sock, 0, ZMQ_POLLIN, 0 };
zmq::poll(&response_item, 1, 5000);
if (response_item.revents & ZMQ_POLLIN) {
// Got response from server
zmq::message_t msg_response;
heartbeat_sock.recv(msg_response, zmq::recv_flags::none);
} else {
// No response - mark connection as dead
std::cout << "Bella Server is unavailable" << std::endl;
connection_state = false;
break;
}
}
}
}
// Clean up resources
heartbeat_sock.close();
ctx.close();
}
void file_watcher_thread(const std::string& watch_path = "") {
bool commonTest = true;
bool useGeneric = false;
global_ul = new UpdateListener();
efsw::FileWatcher fileWatcher(useGeneric);
fileWatcher.followSymlinks(false);
fileWatcher.allowOutOfScopeLinks(false);
if (!watch_path.empty() && dl::fs::exists(watch_path.data())) {
commonTest = false;
if (fileWatcher.addWatch(watch_path, global_ul, true) > 0) {
fileWatcher.watch();
std::cout << "Watching directory: " << watch_path << std::endl;
} else {
std::cout << "Error trying to watch directory: " << watch_path << std::endl;
std::cout << efsw::Errors::Log::getLastErrorLog().c_str() << std::endl;
return;
}
} else if (commonTest) {
std::string CurPath(efsw::System::getProcessPath());
std::cout << "CurPath: " << CurPath.c_str() << std::endl;
fileWatcher.watch();
handleWatchID(fileWatcher.addWatch(CurPath + "test", global_ul, true));
}
while(STOP == false) {
efsw::System::sleep(500);
}
delete global_ul;
global_ul = nullptr;
}
/*
* Main Program Entry Point
*
* This function initializes the application and handles command-line arguments.
* It can run in either server or client mode:
* - Server mode: Starts rendering engine and waits for client connections
* - Client mode: Connects to server and sends commands
*
* Command-line arguments:
* --server : Run in server mode
* --serverAddress : IP address of server (for client mode)
* --commandPort : Port for main command communication
* --heartbeatPort : Port for connection monitoring
* --publickeyPort : Port for initial key exchange
* --testRender : Use small resolution for testing
* --thirdparty : Show third-party licenses
* --licenseinfo : Show license information
*/
#include "dl_core/dl_main.inl"
#include "dl_core/dl_args.h"
int DL_main(Args& args)
{
// Default configuration values
const size_t chunk_size = 65536;
std::string server_address = "localhost";
uint16_t command_port = 5797;
uint16_t heartbeat_port = 5798;
uint16_t publickey_port = 5799;
bool test_render = false;
Engine engine;
engine.scene().loadDefs();
MyEngineObserver engineObserver;
engine.subscribe(&engineObserver);
// Very early on, we will subscribe to the global bella logging callback, and ask to flush
// any messages that may have accumulated prior to this point.
//
subscribeLog(&s_logCtx, log);
flushStartupMessages();
// Register command-line arguments
args.add("sa", "serverAddress", "", "Bella render server ip address");
args.add("cp", "commandPort", "", "tcp port for zmq server socket for commands");
args.add("hp", "heartbeatPort", "", "tcp port for zmq server socket for heartbeats");
args.add("pp", "publickeyPort", "", "tcp port for zmq server socket for server pubkey");
args.add("c", "client", "", "turn on client mode");
args.add("tr", "testRender", "", "force res to 100x100");
args.add("tp", "thirdparty", "", "prints third party licenses");
args.add("li", "licenseinfo", "", "prints license info");
args.add("ef", "efsw", "", "mode efsw");
args.add("wd", "watchdir", "", "mode file warch");
// Handle special command-line options
if (args.versionReqested())
{
printf("%s", bellaSdkVersion().toString().buf());
return 0;
}
if (args.helpRequested())
{
printf("%s", args.help("SDK Test", fs::exePath(), bellaSdkVersion().toString()).buf());
return 0;
}
std::string path=".";
if (args.have("--watchdir")) {
path = args.value("--watchdir").buf();
}
//EFSW mode alwys on
// Create the file watcher thread
std::thread watcher_thread(file_watcher_thread, path);
// Don't wait for the thread to finish here, let it run in background
watcher_thread.detach();
// Show license information if requested
if (args.have("--licenseinfo"))
{
std::cout << "bellatui Copyright (c) Harvey Fong 2025" << std::endl;
std::cout << oom::license::printLicense() << std::endl;
return 0;
}
// Show third-party licenses if requested
if (args.have("--thirdparty"))
{
std::cout << oom::license::printBellaSDK() << "\n====\n" << std::endl;
std::cout << oom::license::printLibSodium() << "\n====\n" << std::endl;
std::cout << oom::license::printLibZMQ() << "\n====\n" << std::endl;
std::cout << oom::license::printCppZMQ() << "\n====\n" << std::endl;
std::cout << oom::license::printEFSW() << "\n====\n" << std::endl;
return 0;
}
// Check if running in server mode
// Check if running in server mode
if (args.have("--client"))
{
server=false;
}
// Enable test rendering if requested
if (args.have("--testRender"))
{
test_render=true;
}
// Parse server address (for client mode)
if (args.have("--serverAddress"))
{
server_address = args.value("--serverAddress").buf();
server=false;
}
// Parse port numbers if provided
if (args.have("--heartbeatPort"))
{
String argString = args.value("--heartbeatPort");
uint16_t u16;
if (argString.parse(u16)) {
heartbeat_port = u16;
} else {
std::cerr << "invalid --heartbeatPort" << argString << std::endl;
}
}
if (args.have("--commandPort"))
{
String argString = args.value("--commandPort");
uint16_t u16;
if (argString.parse(u16)) {
command_port = u16;
} else {
std::cerr << "invalid --commandPort" << argString << std::endl;
}
}
if (args.have("--publickeyPort"))
{
String argString = args.value("--publickeyPort");
uint16_t u16;
if (argString.parse(u16)) {
publickey_port = u16;
} else {
std::cerr << "invalid --commandPort" << argString << std::endl;
}
}
// Generate brand new keypair on launch
// [TODO] Add client side public key fingerprinting for added security
if(server.load()) {
std::cout << "BellaTUI server started ..." << std::endl;
char server_skey[41] = { 0 };
char server_pkey[41] = { 0 };
if ( zmq_curve_keypair(&server_pkey[0], &server_skey[0])) {
// 1 is fail
std::cout << "\ncurve keypair gen failed.";
exit(EXIT_FAILURE);
}
std::thread server_t(server_thread, server_skey, command_port, test_render, engine, std::ref(engineObserver));
std::thread render_t(render_thread, engine, std::ref(engineObserver));
std::thread heartbeat_t(heartbeat_thread, //function
"", //NA Public server key
server_skey, //Secret servery key
"", //NA Public client key
"", //NA Secret client key
true, //is server
"", //FQDN or ip address of server
heartbeat_port); //bind port
//
while(true) { // awaiting new client loop
std::cout << "Awaiting new client ..." << std::endl;
pkey_server(server_pkey, publickey_port); // blocking wait client to get public key
std::cout << "Client connected" << std::endl;
connection_state = true;
while(true) { // inner loop
if (connection_state.load()==false) {
std::cout << "Client connection dead" << std::endl;
break; // Go back to awaiting client
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
//abort_state==true;
server_t.join();
heartbeat_t.join();
return 0;
} else { //Client
char client_skey[41] = { 0 };
char client_pkey[41] = { 0 };
if ( zmq_curve_keypair(&client_pkey[0], &client_skey[0])) {
// 1 is fail
std::cout << "\ncurve keypair gen failed.";
exit(EXIT_FAILURE);
}
std::string server_pkey = get_pubkey_from_srv(server_address, publickey_port);
std::string client_pkey_str(client_pkey);
std::string client_skey_str(client_skey);
// Multithreaded
std::thread command_t( client_thread,
server_pkey,
client_pkey_str,
client_skey_str,
server_address,
command_port);
//std::thread heartbeat_t(heartbeat_thread, server_pkey, client_pkey_str, client_skey_str);
std::thread heartbeat_t(heartbeat_thread, //function
server_pkey, //Public server key
"", //NA Secret server key
client_pkey_str, //Public client key
client_skey_str, //Secret client key
false, //is server
server_address, //Server FQDN or ip address
heartbeat_port); //connect port
while (true) {
/*if (!heartbeat_state.load()) {
std::cout << "Dead" << std::endl;
abort_state==true;
break;
}*/
if (connection_state.load() == false) {
std::cout << "Dead2" << std::endl;
abort_state==true;
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
}
}
std::string get_pubkey_from_srv(std::string server_address, uint16_t publickey_port) {
// No authentication is used, server will give out pubkey to anybody
// Could use a unique message but since socket is unencrypted this provides
// no protection. In main loop we establish an encrypted connection with the server
// now that we have the pubkey and in combo with the client_secret_key we can
// be secure. 0MQ uses PFS perfect forward security, because this initial
// back and forth is extended with behind the scenes new keypairs taken care of by
// 0MQ after we establish our intitial encrypted socket
zmq::context_t ctx;
zmq::socket_t pubkey_sock(ctx, zmq::socket_type::req);
std::string url = "tcp://" + server_address + ":" + std::to_string(publickey_port);
pubkey_sock.connect(url);
zmq::message_t z_out(std::string("Bellarender123"));
try {
zmq::send_result_t send_result = pubkey_sock.send(z_out, zmq::send_flags::none);
} catch (const zmq::error_t& e) {
std::cout << "ERROR" << std::endl;
}
std::cout << "\nbellatui connecting to " << server_address << " ..." << std::endl;
zmq::message_t z_in;
pubkey_sock.recv(z_in);
std::string pub_key = z_in.to_string();
pubkey_sock.close();
ctx.close();
std::cout << "Connection to " << server_address << " successful" << std::endl;
connection_state = true;
return pub_key;
}
void client_thread( std::string server_pkey,
std::string client_pkey,
std::string client_skey,
std::string server_address,
uint16_t command_port ) {
//std::cout << "client thread: " << server_address << " " << command_port << std::endl;
const size_t chunk_size = 65536;
zmq::context_t ctx;
zmq::socket_t command_sock (ctx, zmq::socket_type::req);
//command_sock.set(zmq::sockopt::sndtimeo, 10000);
//command_sock.set(zmq::sockopt::rcvtimeo, 10000);
command_sock.set(zmq::sockopt::curve_serverkey, server_pkey);
command_sock.set(zmq::sockopt::curve_publickey, client_pkey);
command_sock.set(zmq::sockopt::curve_secretkey, client_skey);
command_sock.set(zmq::sockopt::linger, 1); // Close immediately on disconnect
//std::string url = "tcp://" + server_address+ ":" + std::to_string(command_port);
std::string url = "tcp://" + server_address + ":" + std::to_string(command_port);
//std::cout << "client thread " << url << std::endl;
command_sock.connect(url);
std::string input;
while (true) {
if(abort_state.load()==true) {
break;
}
std::getline(std::cin, input);
std::stringstream ss(input);
std::string arg;
std::vector<std::string> args;
while (ss >> arg) {
args.push_back(arg);
}
// Sanity checks on input before sending to server
int num_args = args.size();
std::string command;
if (num_args > 0) {
command = args[0];
if ( command == "send") {
if(num_args == 1) {
std::cout << "Please provide a .bsz file" << std::endl;
continue;
}
if(!ends_with_suffix(args[1],".bsz")) {
std::cout << "Only .bsz files can be sent" << std::endl;
continue;
}
if(!dl::fs::exists(args[1].data())) {
std::cout << args[1] << " cannot be found" << std::endl;
continue;
}
std::cout << "Sending:" << args[1] << std::endl;
} else if (command == "get") {
if(num_args == 1) {
std::cout << "Please provide image filename" << std::endl;
continue;
}
} else if (command == "exit") {
;
} else if (command == "render") {
std::string compoundArg;
if(num_args > 1) {
for (size_t i = 1; i < args.size(); ++i) {
compoundArg += args[i];
if (i < args.size() - 1) {
compoundArg += " "; // Add spaces between arguments
}
}
std::cout << compoundArg << std::endl;
}
} else if (command == "hello") {
;
} else if (command == "stat") {
;
} else if (command == "help") {
std::cout << "\033[32msend file.bsz\033[0m upload bella scene to server\n";
std::cout << "\033[32mrender\033[0m start render on server\n";
std::cout << "\033[32mget file.png\033[0m download png from server\n";
std::cout << "\033[32mstop\033[0m stop render on server\n";
std::cout << "\033[32mstat\033[0m display progress\n";
continue;
} else if (command == "stop") {
;
} else {
std::cout << "unknown" << std::endl;
continue;
}
}
// Sanity check input complete
// Push to server over encrypted socket
zmq::message_t server_response;
zmq::message_t msg_command(command);
//>>>ZOUT
command_sock.send(msg_command, zmq::send_flags::none); //SEND
//std::cout << "Sent: " << input.data() << std::endl;
//ZIN<<<
command_sock.recv(server_response, zmq::recv_flags::none); //RECV
std::string response_str(static_cast<char*>(server_response.data()), server_response.size()-1);
std::string response_str2(static_cast<char*>(server_response.data()), server_response.size());
if(response_str=="RDY") { // Server acknowledges readiness for multi message commands
std::cout << "Server Readiness: " << response_str << std::endl;
if(command == "exit") {
exit(0);
// RENDER
} else if(command == "render") {
std::string compoundArg;
if(num_args > 1) {
for (size_t i = 1; i < args.size(); ++i) {
compoundArg += args[i];
if (i < args.size() - 1) {
compoundArg += " "; // Add spaces between arguments
}
}
std::cout << compoundArg << std::endl;
}
//>>>ZOUT
command_sock.send(zmq::message_t("render"), zmq::send_flags::none);
//ZIN<<<
command_sock.recv(server_response, zmq::recv_flags::none);
} else if(command == "stat") {
//>>>ZOUT
command_sock.send(zmq::message_t("stat"), zmq::send_flags::none);
//ZIN<<<
command_sock.recv(server_response, zmq::recv_flags::none);
// GET
} else if(command == "get") {
std::ofstream output_file(args[1], std::ios::binary); // Open file in binary mode
if (!output_file.is_open()) {
std::cerr << "Error opening file for writing" << std::endl;
std::cout << "ERR" << std::endl;
continue; // Don't bother server
} else {
while (true) {
//>>>ZOUT
command_sock.send(zmq::message_t("GO"), zmq::send_flags::none);
zmq::message_t recv_data;
//ZIN<<<
command_sock.recv(recv_data, zmq::recv_flags::none); // data transfer
// inline messaging with data, breaks to exit loop
if (recv_data.size() < 8) {
std::string recv_string(static_cast<const char*>(recv_data.data()), recv_data.size()-1);
//std::string recv_string = recv_data.to_string();
if (recv_string == "EOF") {
std::cout << "EOF" << std::endl;
break; // End of file
} else if(recv_string == "ERR") { //LIKELY ERR\0 from client, can't find file
std::cout << "ERR client read ACK" << std::endl;
break; // Err
} else {
std::cout << "HUH" << recv_string << std::endl;
break;
}
}
// by reaching this point we assume binary data ( even 8 bytes will reach here )
std::cout << "\033[32m.\033[0m";
output_file.write(static_cast<char*>(recv_data.data()), recv_data.size());
}
output_file.close();
try {
openFileWithDefaultProgram(args[1]); // Replace with your file path