This repository has been archived by the owner on May 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathmain.c
1590 lines (1321 loc) · 47.2 KB
/
main.c
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
/* See Copyright Notice in LICENSE.txt */
#define _BSD_SOURCE
#define _GNU_SOURCE
#include <strings.h>
#include <unistd.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <signal.h>
#include <assert.h>
#include <errno.h>
#include <time.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/inotify.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <GL/glew.h>
#include <GL/gl.h>
#include <GL/glext.h>
#include <GLFW/glfw3.h>
#include <IL/il.h>
#include <IL/ilu.h>
#include <libavformat/avformat.h>
#include <event.h>
#include <event2/dns.h>
#include <lualib.h>
#include <lauxlib.h>
#include "uthash.h"
#include "utlist.h"
#include "misc.h"
#include "image.h"
#include "video.h"
#include "font.h"
#include "shader.h"
#include "vnc.h"
#include "framebuffer.h"
#include "struct.h"
#include "kernel.h"
#include "userlib.h"
#include "module_json.h"
#if USE_LUAJIT
#include <luajit.h>
#define VERSION_STRING "Info Beamer " VERSION "+" LUA_VERSION "+" LUAJIT_VERSION
#else
#define VERSION_STRING "Info Beamer " VERSION "+" LUA_VERSION
#endif
#define INFO_URL "http://info-beamer.org/"
#define NODE_CODE_FILE "node.lua"
#define ENVIRONMENT_PREFIX "INFOBEAMER_ENV_"
#define ENVIRONMENT_PREFIX_SIZE (sizeof(ENVIRONMENT_PREFIX)-1)
#define MAX_MEM 2000000 // KB
#define MAX_GL_PUSH 20 // glPushMatrix depth
#define MAX_CHILD_RENDERS 20 // maximum childs rendered per node
#define MAX_SNAPSHOTS 5 // maximum number of snapshots per render
// Default host/port (both udp & tcp)
#define LISTEN_ADDR "0.0.0.0"
#define DEFAULT_PORT 4444
#ifdef DEBUG
#define MAX_RUNAWAY_TIME 10 // sec
#define MAX_PCALL_TIME 5000000 // usec
#else
#define MAX_RUNAWAY_TIME 1 // sec
#define MAX_PCALL_TIME 500000 // usec
#endif
#define NO_GL_PUSHPOP -1
#define NODE_INACTIVITY 2.0 // node considered idle after x seconds
#define NODE_CPU_BLACKLIST 60.0 // seconds a node is blacklisted if it exceeds cpu usage
static int win_w, win_h;
typedef enum { PROFILE_BOOT, PROFILE_UPDATE, PROFILE_EVENT } profiling_bins;
typedef struct node_s {
int wd; // inotify watch descriptor
char *name; // local node name
char *path; // full path (including node name)
char *alias; // alias path
lua_State *L;
UT_hash_handle by_wd; // global handle for search by watch descriptor
UT_hash_handle by_name; // childs by name
UT_hash_handle by_path; // node by path
UT_hash_handle by_alias; // node by alias
struct node_s *parent;
struct node_s *childs;
int width;
int height;
int gl_matrix_depth;
struct client_s *clients;
int child_render_quota;
int snapshot_quota;
double profiling[3];
double last_profile;
int num_frames;
int num_resource_inits;
int num_allocs;
double last_activity;
double blacklisted;
} node_t;
static node_t *nodes_by_wd = NULL;
static node_t *nodes_by_path = NULL;
static node_t *nodes_by_alias = NULL;
static node_t root = {0};
typedef struct client_s {
int fd;
node_t *node;
struct bufferevent *buf_ev;
struct client_s *next;
struct client_s *prev;
} client_t;
static int inotify_fd;
static double now;
static int running = 1;
static int listen_port;
GLuint default_tex; // white default texture
struct event_base *event_base;
struct evdns_base *dns_base;
/*=== Forward declarations =====*/
static void client_write(client_t *client, const char *data, size_t data_size);
static void client_close(client_t *client);
static void node_printf(node_t *node, const char *fmt, ...);
static void node_blacklist(node_t *node, double time);
static void node_remove_alias(node_t *node);
static void node_reset_quota(node_t *node);
static int node_render_to_image(lua_State *L, node_t *node);
static void node_init(node_t *node, node_t *parent, const char *path, const char *name);
static void node_free(node_t *node);
/*======= Lua Sandboxing =======*/
#ifndef USE_LUAJIT
static void *lua_alloc(void *ud, void *ptr, size_t osize, size_t nsize) {
node_t *node = ud;
node->num_allocs++;
(void)osize; /* not used */
if (nsize == 0) {
free(ptr);
return NULL;
} else {
return realloc(ptr, nsize);
}
}
#endif
/* execution time limiting for pcalls */
static node_t *global_node = NULL;
static int timers_expired = 0;
static void deadline_stop(lua_State *L, lua_Debug *ar) {
lua_sethook(L, NULL, 0, 0);
lua_pushliteral(L, "alarm");
lua_gettable(L, LUA_REGISTRYINDEX);
lua_call(L, 0, 0);
}
static void deadline_signal(int i) {
if (!global_node)
die("urg. timer expired and no global_node");
fprintf(stderr, RED("[%s]") " timeout\n", global_node->path);
if (timers_expired == 0) {
// timer expired once? Try to solve it inside of
// lua: set a hook that will execute deadline_stop.
lua_sethook(global_node->L, deadline_stop,
LUA_MASKCALL | LUA_MASKRET | LUA_MASKLINE | LUA_MASKCOUNT, 1);
node_blacklist(global_node, NODE_CPU_BLACKLIST);
} else {
// timer expired again without lua being stopped?
die("unstoppable runaway code in %s", global_node->path);
}
timers_expired++;
}
static int lua_timed_pcall(node_t *node, int in, int out,
int error_handler_pos)
{
node_t *old_global_node = global_node;
struct itimerval old_timer;
struct itimerval deadline;
deadline.it_interval.tv_sec = MAX_RUNAWAY_TIME;
deadline.it_interval.tv_usec = 0;
deadline.it_value.tv_sec = MAX_PCALL_TIME / 1000000;
deadline.it_value.tv_usec = MAX_PCALL_TIME % 1000000;
setitimer(ITIMER_VIRTUAL, &deadline, &old_timer);
global_node = node;
timers_expired = 0;
int ret = lua_pcall(node->L, in, out, error_handler_pos);
setitimer(ITIMER_VIRTUAL, &old_timer, NULL);
global_node = old_global_node;
return ret;
}
static int lua_panic(lua_State *L) {
die("node panic!");
return 0;
}
static const char *lua_safe_dedup_error_message(lua_State *L) {
const char *message = lua_tostring(L, -1);
if (!message)
die("<null> error message");
lua_pushliteral(L, "last_error");
lua_rawget(L, LUA_REGISTRYINDEX);
int same_as_last_time = lua_equal(L, -1, -2);
lua_pop(L, 1); // remove value of last_error
if (same_as_last_time) {
message = NULL;
} else {
lua_pushliteral(L, "last_error");
lua_pushvalue(L, -2);
lua_rawset(L, LUA_REGISTRYINDEX);
}
return message;
}
static void lua_node_enter(node_t *node, int args, profiling_bins bin) {
node_reset_quota(node);
lua_State *L = node->L;
lua_pushliteral(L, "execute"); // [args] "execute"
lua_rawget(L, LUA_REGISTRYINDEX); // [args] execute
lua_insert(L, -1 - args); // execute [args]
lua_pushliteral(L, "traceback"); // execute [args] "traceback"
lua_rawget(L, LUA_REGISTRYINDEX); // execute [args] traceback
const int error_handler_pos = lua_gettop(L) - 1 - args;
lua_insert(L, error_handler_pos); // traceback execute [args]
struct timeval before, after;
gettimeofday(&before, NULL);
int status = lua_timed_pcall(node, args, 0, error_handler_pos);
if (status == 0) {
// success // traceback
lua_remove(L, error_handler_pos); //
} else {
// error // traceback "error"
char *err = status == LUA_ERRRUN ? "runtime error" :
status == LUA_ERRMEM ? "memory error" :
status == LUA_ERRERR ? "error handling error" : NULL;
assert(err);
const char *message = lua_safe_dedup_error_message(L);
if (message)
node_printf(node, "%s: %s\n", err, message);
lua_pop(L, 2); //
}
gettimeofday(&after, NULL);
lua_gc(node->L, LUA_GCSTEP, 5);
node->profiling[bin] += time_delta(&before, &after);
node->last_activity = now;
}
/*======= Lua entry points =======*/
// reinit sandbox, load usercode and user code
static void node_boot(node_t *node) {
lua_pushliteral(node->L, "boot");
lua_node_enter(node, 1, PROFILE_BOOT);
}
// notify of child update
static void node_child_update(node_t *node, const char *name, int added) {
lua_pushliteral(node->L, "child_update");
lua_pushstring(node->L, name);
lua_pushboolean(node->L, added);
lua_node_enter(node, 3, PROFILE_UPDATE);
}
// notify of content update
static void node_content_update(node_t *node, const char *name, int added) {
fprintf(stderr, YELLOW("[%s]")" update %c%s\n", node->path, added ? '+' : '-', name);
lua_pushliteral(node->L, "content_update");
lua_pushstring(node->L, name);
lua_pushboolean(node->L, added);
if (!strcmp(name, NODE_CODE_FILE)) {
// reset blacklisted flag
node->blacklisted = 0;
// reset node dimensions
node->width = 0;
node->height = 0;
// remove existing node alias
node_remove_alias(node);
}
lua_node_enter(node, 3, PROFILE_UPDATE);
}
// event.<event_name>(args...)
static void node_event(node_t *node, const char *name, int args) {
lua_pushliteral(node->L, "event"); // [args] "event_name"
lua_pushstring(node->L, name); // [args] "event_name" name
lua_insert(node->L, -2 - args); // name [args] "event_name"
lua_insert(node->L, -2 - args); // "event_name" name [args]
lua_node_enter(node, 2 + args, PROFILE_EVENT);
}
// render node
static void node_render_self(node_t *node, int width, int height) {
lua_pushliteral(node->L, "render_self");
lua_pushnumber(node->L, width);
lua_pushnumber(node->L, height);
lua_node_enter(node, 3, PROFILE_EVENT);
}
/*===== node macros =======*/
#define node_setup_completed(node) ((node)->width != 0)
#define node_is_idle(node) (now > (node)->last_activity + NODE_INACTIVITY)
#define node_is_blacklisted(node) (now < (node)->blacklisted)
#define node_is_rendering(node) ((node)->gl_matrix_depth != NO_GL_PUSHPOP)
/*===== Lua bindings ======*/
static node_t *get_rendering_node(lua_State *L) {
node_t *node = lua_touserdata(L, lua_upvalueindex(1));
if (!node_is_rendering(node))
luaL_error(L, "only callable in node.render");
return node;
}
static int luaResetError(lua_State *L) {
lua_pushliteral(L, "last_error");
lua_pushnil(L);
lua_rawset(L, LUA_REGISTRYINDEX);
return 0;
}
static int luaRenderSelf(lua_State *L) {
node_t *node = lua_touserdata(L, lua_upvalueindex(1));
return node_render_to_image(L, node);
}
static int luaRenderChild(lua_State *L) {
node_t *node = get_rendering_node(L);
if (node->child_render_quota-- <= 0)
return luaL_error(L, "too many childs rendered");
const char *name = luaL_checkstring(L, 1);
node_t *child;
HASH_FIND(by_name, node->childs, name, strlen(name), child);
if (!child)
return luaL_error(L, "child %s not found", name);
return node_render_to_image(L, child);
}
static int luaSetup(lua_State *L) {
node_t *node = lua_touserdata(L, lua_upvalueindex(1));
if (node_is_rendering(node))
return luaL_error(L, "cannot change width or height while rendering");
int width = (int)luaL_checknumber(L, 1);
int height = (int)luaL_checknumber(L, 2);
if (width < 32 || width > 4096)
luaL_argerror(L, 1, "invalid width. must be within [32,4096]");
if (height < 32 || height > 4096)
luaL_argerror(L, 2, "invalid height. must be within [32,4096]");
node->width = width;
node->height = height;
return 0;
}
static int luaGlOrtho(lua_State *L) {
node_t *node = get_rendering_node(L);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, node->width,
node->height, 0,
-1000, 1000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
node->gl_matrix_depth = 0;
return 0;
}
static int luaGlPerspective(lua_State *L) {
node_t *node = get_rendering_node(L);
double fov = luaL_checknumber(L, 1);
double eye_x = luaL_checknumber(L, 2);
double eye_y = luaL_checknumber(L, 3);
double eye_z = luaL_checknumber(L, 4);
double center_x = luaL_checknumber(L, 5);
double center_y = luaL_checknumber(L, 6);
double center_z = luaL_checknumber(L, 7);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(fov, (float)node->width / (float)node->height, 0.1, 10000);
gluLookAt(eye_x, eye_y, eye_z,
center_x, center_y, center_z,
0, -1, 0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
node->gl_matrix_depth = 0;
return 0;
}
static int luaSetAlias(lua_State *L) {
node_t *node = lua_touserdata(L, lua_upvalueindex(1));
const char *alias = luaL_checkstring(L, 1);
// already exists?
node_t *existing_node;
HASH_FIND(by_alias, nodes_by_alias, alias, strlen(alias), existing_node);
if (existing_node) {
if (existing_node == node) {
return 0;
} else {
return luaL_error(L, "alias already taken by %s", existing_node->path);
}
}
// remove old alias
if (node->alias) {
HASH_DELETE(by_alias, nodes_by_alias, node);
free(node->alias);
}
// set new alias
node->alias = strdup(alias);
HASH_ADD_KEYPTR(by_alias, nodes_by_alias, node->alias, strlen(node->alias), node);
return 0;
}
static int luaLoadImage(lua_State *L) {
node_t *node = lua_touserdata(L, lua_upvalueindex(1));
const char *name = luaL_checkstring(L, 1);
if (index(name, '/'))
luaL_argerror(L, 1, "invalid resource name");
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", node->path, name);
node->num_resource_inits++;
return image_load(L, path, name);
}
static int luaLoadVideo(lua_State *L) {
node_t *node = lua_touserdata(L, lua_upvalueindex(1));
const char *name = luaL_checkstring(L, 1);
if (index(name, '/'))
luaL_argerror(L, 1, "invalid resource name");
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", node->path, name);
node->num_resource_inits++;
return video_load(L, path, name);
}
static int luaLoadFont(lua_State *L) {
node_t *node = lua_touserdata(L, lua_upvalueindex(1));
const char *name = luaL_checkstring(L, 1);
if (index(name, '/'))
luaL_argerror(L, 1, "invalid resource name");
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", node->path, name);
node->num_resource_inits++;
return font_new(L, path, name);
}
static int luaLoadFile(lua_State *L) {
node_t *node = lua_touserdata(L, lua_upvalueindex(1));
const char *name = luaL_checkstring(L, 1);
if (index(name, '/'))
luaL_argerror(L, 1, "invalid resource name");
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", node->path, name);
int fd = open(path, O_RDONLY);
if (fd == -1)
return luaL_error(L, "cannot open file '%s'", path);
luaL_Buffer b;
luaL_buffinit(L, &b);
while (1) {
char *data = luaL_prepbuffer(&b);
ssize_t data_size = read(fd, data, LUAL_BUFFERSIZE);
if (data_size < 0)
return luaL_error(L, "cannot read %s: %s", name, strerror(errno));
if (data_size == 0)
break;
luaL_addsize(&b, data_size);
}
close(fd);
luaL_pushresult(&b);
node->num_resource_inits++;
return 1;
}
static int luaCreateColoredTexture(lua_State *L) {
node_t *node = lua_touserdata(L, lua_upvalueindex(1));
GLfloat r = luaL_checknumber(L, 1);
GLfloat g = luaL_checknumber(L, 2);
GLfloat b = luaL_checknumber(L, 3);
GLfloat a = luaL_optnumber(L, 4, 1.0);
node->num_resource_inits++;
return image_from_color(L,
CLAMP(r, 0, 1),
CLAMP(g, 0, 1),
CLAMP(b, 0, 1),
CLAMP(a, 0, 1)
);
}
static int luaCreateSnapshot(lua_State *L) {
node_t *node = get_rendering_node(L);
if (node->snapshot_quota-- <= 0)
return luaL_error(L, "too many snapshots");
node->num_resource_inits++;
int mipmap = 0;
int x = 0;
int y = 0;
int width = node->width;
int height = node->height;
if (lua_gettop(L) <= 1) {
mipmap = lua_toboolean(L, 1);
} else if (lua_gettop(L) == 4) {
x = luaL_checknumber(L, 1);
y = luaL_checknumber(L, 2);
width = luaL_checknumber(L, 3);
height = luaL_checknumber(L, 4);
if (x < 0 || y < 0 || width < 0 || height < 0 ||
x + width > node->width || y + height > node->height) {
return luaL_error(L, "snapshot out of bounds");
}
} else {
return luaL_error(L, "invalid number of arguments");
}
return image_from_current_framebuffer(
L, x, node->height - y - height, width, height, mipmap
);
}
static int luaCreateShader(lua_State *L) {
node_t *node = lua_touserdata(L, lua_upvalueindex(1));
const char *vertex = luaL_checkstring(L, 1);
const char *fragment = luaL_checkstring(L, 2);
node->num_resource_inits++;
return shader_new(L, vertex, fragment);
}
static int luaCreateVnc(lua_State *L) {
node_t *node = lua_touserdata(L, lua_upvalueindex(1));
const char *host = luaL_checkstring(L, 1);
int port = luaL_optnumber(L, 2, 5900);
node->num_resource_inits++;
return vnc_create(L, host, port);
}
static int luaPushFormattedArgs(lua_State *L) {
luaL_Buffer b;
luaL_buffinit(L, &b);
int n = lua_gettop(L);
lua_getglobal(L, "tostring");
for (int i = 1; i <= n; i++) {
lua_pushvalue(L, n + 1);
lua_pushvalue(L, i);
lua_call(L, 1, 1);
if (!lua_isstring(L, -1))
return luaL_error(L, "tostring must return a string to print");
if (i > 1)
luaL_addchar(&b, '\t');
luaL_addvalue(&b);
}
luaL_addchar(&b, '\n');
luaL_pushresult(&b);
return 1;
}
static int luaPrint(lua_State *L) {
node_t *node = lua_touserdata(L, lua_upvalueindex(1));
luaPushFormattedArgs(L);
node_printf(node, "%s", lua_tostring(L, -1));
return 0;
}
static int luaGetScreenInfo(lua_State *L) {
lua_pushnumber(L, win_w);
lua_pushnumber(L, win_h);
return 2;
}
static int luaClientWrite(lua_State *L) {
node_t *node = lua_touserdata(L, lua_upvalueindex(1));
client_t *client = lua_touserdata(L, 1);
lua_remove(L, 1);
luaPushFormattedArgs(L);
size_t string_len;
const char *string = lua_tolstring(L, -1, &string_len);
client_t *current_client;
DL_FOREACH(node->clients, current_client) {
if (current_client == client) {
client_write(current_client, string, string_len);
}
}
return 0;
}
static int luaGlClear(lua_State *L) {
get_rendering_node(L);
GLdouble r = luaL_checknumber(L, 1);
GLdouble g = luaL_checknumber(L, 2);
GLdouble b = luaL_checknumber(L, 3);
GLdouble a = luaL_checknumber(L, 4);
glClearColor(r, g, b, a);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(0);
return 0;
}
static int luaGlPushMatrix(lua_State *L) {
node_t *node = get_rendering_node(L);
if (node->gl_matrix_depth > MAX_GL_PUSH)
return luaL_error(L, "Too may pushes");
glPushMatrix();
node->gl_matrix_depth++;
return 0;
}
static int luaGlPopMatrix(lua_State *L) {
node_t *node = get_rendering_node(L);
if (node->gl_matrix_depth == 0)
return luaL_error(L, "Nothing to pop");
glPopMatrix();
node->gl_matrix_depth--;
return 0;
}
static int luaGlRotate(lua_State *L) {
get_rendering_node(L);
double angle = luaL_checknumber(L, 1);
double x = luaL_checknumber(L, 2);
double y = luaL_checknumber(L, 3);
double z = luaL_checknumber(L, 4);
glRotated(angle, x, y, z);
return 0;
}
static int luaGlTranslate(lua_State *L) {
get_rendering_node(L);
double x = luaL_checknumber(L, 1);
double y = luaL_checknumber(L, 2);
double z = luaL_optnumber(L, 3, 0.0);
glTranslated(x, y, z);
return 0;
}
static int luaGlScale(lua_State *L) {
get_rendering_node(L);
double x = luaL_checknumber(L, 1);
double y = luaL_checknumber(L, 2);
double z = luaL_optnumber(L, 3, 1.0);
glScaled(x, y, z);
return 0;
}
static int luaNow(lua_State *L) {
lua_pushnumber(L, now);
return 1;
}
/*==== Node functions =====*/
static int node_render_to_image(lua_State *L, node_t *node) {
// save current gl state
int prev_fbo, prev_prog;
GLdouble prev_projection[16];
GLdouble prev_modelview[16];
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &prev_fbo);
glGetIntegerv(GL_CURRENT_PROGRAM, &prev_prog);
glGetDoublev(GL_PROJECTION_MATRIX, prev_projection);
glGetDoublev(GL_MODELVIEW_MATRIX, prev_modelview);
glPushAttrib(GL_ALL_ATTRIB_BITS);
int width = 1, height = 1;
if (node_setup_completed(node))
width = node->width, height = node->height;
// get new framebuffer and associated texture from recycler
unsigned int fbo, tex;
make_framebuffer(width, height, &tex, &fbo);
// initialize gl state
glUseProgram(0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, width, height);
glOrtho(0, width,
height, 0,
-1000, 1000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
if (!node_setup_completed(node)) {
node_printf(node, "node not initialized with gl.setup()\n");
glClearColor(0.5, 0.5, 0.5, 1);
glClear(GL_COLOR_BUFFER_BIT);
} else if (node_is_blacklisted(node)) {
node_printf(node, "node is blacklisted\n");
glClearColor(0.5, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
} else {
// clear with transparent color
glClearColor(1, 1, 1, 0);
glClear(GL_COLOR_BUFFER_BIT);
// render node
node->gl_matrix_depth = 0;
node->num_frames++;
node_event(node, "render", 0);
while (node->gl_matrix_depth-- > 0)
glPopMatrix();
node->gl_matrix_depth = NO_GL_PUSHPOP;
}
// rebind to framebuffer texture
glBindTexture(GL_TEXTURE_2D, tex);
glGenerateMipmap(GL_TEXTURE_2D);
// restore previous state
glPopAttrib();
glMatrixMode(GL_PROJECTION);
glLoadMatrixd(prev_projection);
glMatrixMode(GL_MODELVIEW);
glLoadMatrixd(prev_modelview);
glUseProgram(prev_prog);
glBindFramebuffer(GL_FRAMEBUFFER, prev_fbo);
return image_create(L, tex, fbo, width, height, 1);
}
static void node_printf(node_t *node, const char *fmt, ...) {
char buffer[16384];
va_list ap;
va_start(ap, fmt);
vsnprintf(buffer, sizeof(buffer), fmt, ap);
va_end(ap);
fprintf(stderr, GREEN("[%s]")" %s", node->path, buffer);
}
static void node_blacklist(node_t *node, double time) {
node->blacklisted = now + time;
node_printf(node, "blacklisted for %.0f seconds\n", time);
}
static void node_remove_alias(node_t *node) {
if (node->alias) {
HASH_DELETE(by_alias, nodes_by_alias, node);
free(node->alias);
node->alias = NULL;
}
}
static void node_tree_gc(node_t *node) {
if (!node_is_idle(node))
lua_gc(node->L, LUA_GCSTEP, 30);
node_t *child, *tmp;
HASH_ITER(by_name, node->childs, child, tmp) {
node_tree_gc(child);
};
}
static node_t *node_add_child(node_t* node, const char *path, const char *name) {
fprintf(stderr, YELLOW("[%s]")" adding new child node %s\n", node->name, name);
node_t *child = xmalloc(sizeof(node_t));
node_init(child, node, path, name);
HASH_ADD_KEYPTR(by_name, node->childs, child->name, strlen(child->name), child);
return child;
}
static void node_remove_child(node_t* node, node_t* child) {
fprintf(stderr, YELLOW("[%s]")" removing child node %s\n", node->name, child->name);
node_child_update(node, child->name, 0);
HASH_DELETE(by_name, node->childs, child);
node_free(child);
free(child);
}
static void node_remove_child_by_name(node_t* node, const char *name) {
node_t *child;
HASH_FIND(by_name, node->childs, name, strlen(name), child);
if (!child)
die("child not found: %s", name);
node_remove_child(node, child);
}
static void node_reset_quota(node_t *node) {
node->child_render_quota = MAX_CHILD_RENDERS;
node->snapshot_quota = MAX_SNAPSHOTS;
}
static void node_reset_profiler(node_t *node) {
node->last_profile = now;
node->profiling[PROFILE_BOOT] = 0.0;
node->profiling[PROFILE_UPDATE] = 0.0;
node->profiling[PROFILE_EVENT] = 0.0;
node->num_frames = 0;
node->num_resource_inits = 0;
node->num_allocs = 0;
}
#define lua_register_node_func(node,name,func) \
(lua_pushliteral((node)->L, name), \
lua_pushlightuserdata((node)->L, node), \
lua_pushcclosure((node)->L, func, 1), \
lua_settable((node)->L, LUA_GLOBALSINDEX))
static void node_init(node_t *node, node_t *parent, const char *path, const char *name) {
// add directory watcher
node->wd = inotify_add_watch(inotify_fd, path,
IN_CLOSE_WRITE|IN_CREATE|IN_DELETE|IN_DELETE_SELF|
IN_MOVE);
if (node->wd == -1)
die("cannot start watching directory %s: %s", path, strerror(errno));
node->parent = parent;
node->path = strdup(path);
node->name = strdup(name);
node->alias = NULL;
node->width = 0;
node->height = 0;
node_reset_profiler(node);
node->last_activity = now;
node->gl_matrix_depth = NO_GL_PUSHPOP;
// link by watch descriptor & path
HASH_ADD(by_wd, nodes_by_wd, wd, sizeof(int), node);
HASH_ADD_KEYPTR(by_path, nodes_by_path, node->path, strlen(node->path), node);
// create lua state
#ifdef USE_LUAJIT
node->L = luaL_newstate();
#else
node->L = lua_newstate(lua_alloc, node);
#endif
if (!node->L)
die("cannot create lua");
lua_atpanic(node->L, lua_panic);
luaL_openlibs(node->L);
image_register(node->L);
video_register(node->L);
font_register(node->L);
shader_register(node->L);
vnc_register(node->L);
luaopen_struct(node->L);
lua_register_node_func(node, "reset_error", luaResetError);
lua_register_node_func(node, "setup", luaSetup);
lua_register_node_func(node, "print", luaPrint);
lua_register_node_func(node, "set_alias", luaSetAlias);
lua_register_node_func(node, "client_write", luaClientWrite);
lua_register_node_func(node, "get_screen_info", luaGetScreenInfo);
lua_register_node_func(node, "render_self", luaRenderSelf);
lua_register_node_func(node, "render_child", luaRenderChild);
lua_register_node_func(node, "load_image", luaLoadImage);
lua_register_node_func(node, "load_video", luaLoadVideo);
lua_register_node_func(node, "load_font", luaLoadFont);
lua_register_node_func(node, "load_file", luaLoadFile);
lua_register_node_func(node, "create_colored_texture", luaCreateColoredTexture);
lua_register_node_func(node, "create_snapshot", luaCreateSnapshot);
lua_register_node_func(node, "create_shader", luaCreateShader);
lua_register_node_func(node, "create_vnc", luaCreateVnc);
lua_register_node_func(node, "glClear", luaGlClear);
lua_register_node_func(node, "glPushMatrix", luaGlPushMatrix);
lua_register_node_func(node, "glPopMatrix", luaGlPopMatrix);
lua_register_node_func(node, "glRotate", luaGlRotate);
lua_register_node_func(node, "glTranslate", luaGlTranslate);
lua_register_node_func(node, "glScale", luaGlScale);
lua_register_node_func(node, "glOrtho", luaGlOrtho);
lua_register_node_func(node, "glPerspective", luaGlPerspective);
lua_register(node->L, "now", luaNow);
lua_pushliteral(node->L, VERSION);
lua_setglobal(node->L, "VERSION");
lua_pushstring(node->L, path);
lua_setglobal(node->L, "PATH");
lua_pushstring(node->L, name);
lua_setglobal(node->L, "NAME");
lua_pushlstring(node->L, userlib, userlib_size);
lua_setglobal(node->L, "USERLIB");
lua_pushlstring(node->L, module_json, module_json_size);
lua_setglobal(node->L, "MODULE_JSON");
lua_pushliteral(node->L, NODE_CODE_FILE);
lua_setglobal(node->L, "NODE_CODE_FILE");
// get variables from environment
lua_newtable(node->L);
for (const char **cur = (const char**)environ; *cur; cur++) {
if (strstr(*cur, ENVIRONMENT_PREFIX) != *cur)
continue;
const char *equals = strstr(*cur + ENVIRONMENT_PREFIX_SIZE, "=");
if (!equals)
continue;
const char *name = *cur + ENVIRONMENT_PREFIX_SIZE;
int name_len = equals - name;
const char *value = equals+1;
// printf("%d %.*s %s\n", name_len, name_len, name, value);
lua_pushlstring(node->L, name, name_len);
lua_pushstring(node->L, value);
lua_rawset(node->L, -3);
}
lua_setglobal(node->L, "NODE_ENVIRON");
if (luaL_loadbuffer(node->L, kernel, kernel_size, "=kernel.lua") != 0) {
const char *error = lua_tostring(node->L, -1);
// If kernel.lua was procompiled with an incompatible lua
// version, loading the embedded code fail here. Try to
// detect this...
die("cannot load kernel.lua: %s%s", error,
strstr(error, "bad header") ? " (See 'kernel load error' in the docs)" : ""
);
}
if (lua_pcall(node->L, 0, 0, 0) != 0)
die("kernel run %s", lua_tostring(node->L, -1));
}
static void node_free(node_t *node) {
node_t *child, *tmp;
HASH_ITER(by_name, node->childs, child, tmp) {
node_remove_child(node, child);
}
HASH_DELETE(by_wd, nodes_by_wd, node);
HASH_DELETE(by_path, nodes_by_path, node);
free(node->path);
free(node->name);
node_remove_alias(node);
client_t *client, *tmp_client;
DL_FOREACH_SAFE(node->clients, client, tmp_client) {
client_close(client);
}
assert(node->clients == NULL);
lua_close(node->L);
}
static void node_search_and_boot(node_t *node) {
DIR *dp = opendir(node->path);