forked from ac-minetest/basic_robot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.lua
1999 lines (1644 loc) · 64.2 KB
/
init.lua
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
-- basic_robot by rnd, 2016-2022
basic_robot = {};
basic_robot.version = "2022/02/02b";
dofile(minetest.get_modpath("basic_robot").."/settings.lua") -- read configuration SETTINGS
-- structures for storing robot data
basic_robot.gui = {}; local robogui = basic_robot.gui -- gui management
basic_robot.data = {}; -- stores all robot related data
--[[
[name] = { sandbox= .., bytecode = ..., ram = ..., obj = robot object, spawnpos= ..., authlevel = ... , t = code execution time}
robot object = object of entity, used to manipulate movements and more
--]]
basic_robot.ids = {}; -- stores maxid for each player
--[name] = {id = .., maxid = .. }, current id for robot controller, how many robot ids player can use
basic_robot.virtual_players = {}; -- this way robot can interact with the world as "player" TODO
basic_robot.data.listening = {}; -- which robots listen to chat
basic_robot.data.punchareas = {}; -- where robots listen punch events, [hashes of 32 sized chunk] = robot name
dofile(minetest.get_modpath("basic_robot").."/robogui.lua") -- gui stuff
dofile(minetest.get_modpath("basic_robot").."/commands.lua")
local check_code, preprocess_code,is_inside_string;
-- SANDBOX for running lua code isolated and safely
function getSandboxEnv (name)
local authlevel = basic_robot.data[name].authlevel or 0;
local commands = basic_robot.commands;
local directions = {left = 1, right = 2, forward = 3, backward = 4, up = 5, down = 6,
left_down = 7, right_down = 8, forward_down = 9, backward_down = 10,
left_up = 11, right_up = 12, forward_up = 13, backward_up = 14
}
local pname = string.sub(name,1,-2)
if not basic_robot.data[pname] then basic_robot.data[pname] = {} end
-- all robots by player share same rom now
if not basic_robot.data[pname].rom then basic_robot.data[pname].rom = {} end -- create rom if not yet existing
local env =
{
_Gerror = error,
pcall=pcall,
robot_version = function() return basic_robot.version end,
boost = function(v)
if math.abs(v)>2 then v = 0 end; local obj = basic_robot.data[name].obj;
if v == 0 then
local pos = obj:get_pos(); pos.x = math.floor(pos.x+0.5);pos.y = math.floor(pos.y+0.5); pos.z = math.floor(pos.z+0.5);
obj:setpos(pos); obj:set_velocity({x=0,y=0,z=0});
return
end
local yaw = obj:get_yaw();
obj:set_velocity({x=-v*math.sin(yaw),y=0,z=v*math.cos(yaw)});
end,
turn = {
left = function() commands.turn(name,math.pi/2) end,
right = function() commands.turn(name,-math.pi/2) end,
angle = function(angle) commands.turn(name,angle*math.pi/180) end,
},
pickup = function(r) -- pick up items around robot
return commands.pickup(r, name);
end,
craft = function(item, idx,mode, amount)
return commands.craft(item, mode, idx, amount, name)
end,
pause = function(amount) -- pause coroutine
if not basic_robot.data[name].cor then error("you must start program with '--coroutine' to use pause()") return end
if not amount or basic_robot.data[name].operations<amount then
coroutine.yield()
end
end,
self = {
pos = function() return basic_robot.data[name].obj:get_pos() end,
spawnpos = function() local pos = basic_robot.data[name].spawnpos; return {x=pos.x,y=pos.y,z=pos.z} end,
name = function() return name end,
operations = function() return basic_robot.data[name].operations end,
viewdir = function() local yaw = basic_robot.data[name].obj:getyaw(); return {x=-math.sin(yaw), y = 0, z=math.cos(yaw)} end,
set_properties = function(properties)
if not properties then return end; local obj = basic_robot.data[name].obj;
obj:set_properties(properties);
end,
set_animation = function(anim_start,anim_end,anim_speed,anim_stand_start)
local obj = basic_robot.data[name].obj;
obj:set_animation({x=anim_start,y=anim_end}, anim_speed, anim_stand_start)
end,
listen = function (mode) -- will robot listen to chat?
if mode == 1 then
basic_robot.data.listening[name] = true
else
basic_robot.data.listening[name] = nil
end
end,
listen_punch = function(pos, is_remove) -- robot will listen to punch events in 32 sized chunk containing pos
local round = math.floor;
local r = basic_robot.radius; local ry = 2*r; -- note: this is skyblock adjusted
if not pos then return end
local ppos = {x=round(pos.x/r+0.5)*r,y=round(pos.y/ry+0.5)*ry+1,z=round(pos.z/r+0.5)*r}; -- just on top of basic_protect:protector!
local hppos = minetest.hash_node_position(ppos)
local rname = basic_robot.data.punchareas[hppos];
if is_remove then -- remove listener
basic_robot.data.punchareas[hppos] = nil
return
end
if rname then -- area already registered for listening
return rname
end
basic_robot.data.punchareas[hppos] = name; -- register robot name
end,
listen_msg = function()
local msg = basic_robot.data[name].listen_msg;
local speaker = basic_robot.data[name].listen_speaker;
basic_robot.data[name].listen_msg = nil;
basic_robot.data[name].listen_speaker = nil;
return speaker,msg
end,
read_mail = function()
local mail = basic_robot.data[name].listen_mail;
local sender = basic_robot.data[name].listen_sender;
basic_robot.data[name].listen_mail = nil;
basic_robot.data[name].listen_sender = nil;
return sender,mail
end,
send_mail = function(target,mail)
if not basic_robot.data[target] then return false end
basic_robot.data[target].listen_mail = mail;
basic_robot.data[target].listen_sender = name;
end,
remove = function()
error("abort")
basic_robot.data[name].obj:remove();
basic_robot.data[name].obj=nil;
end,
reset = function()
local pos = basic_robot.data[name].spawnpos;
local obj = basic_robot.data[name].obj;
obj:set_pos({x=pos.x,y=pos.y+1,z=pos.z}); obj:set_yaw(0);
end,
set_libpos = function(pos)
local pos = basic_robot.data[name].spawnpos; local meta = minetest.get_meta(pos);
meta:set_string("libpos",pos.x .. " " .. pos.y .. " " .. pos.z)
end,
spam = function (mode) -- allow more than one msg per "say"
if mode == 1 then
basic_robot.data[name].allow_spam = true
else
basic_robot.data[name].allow_spam = nil
end
end,
fire = function(speed, pitch,gravity, texture, is_entity) -- experimental: fires an projectile
local obj = basic_robot.data[name].obj;
local pos = obj:get_pos();
local yaw = obj:getyaw()+ math.pi/2;
pitch = pitch*math.pi/180
local velocity = {x=speed*math.cos(yaw)*math.cos(pitch), y=speed*math.sin(pitch),z=speed*math.sin(yaw)*math.cos(pitch)};
-- fire particle
if not is_entity then
minetest.add_particle(
{
pos = pos,
expirationtime = 10,
velocity = {x=speed*math.cos(yaw)*math.cos(pitch), y=speed*math.sin(pitch),z=speed*math.sin(yaw)*math.cos(pitch)},
size = 5,
texture = texture or "default_apple.png",
acceleration = {x=0,y=-gravity,z=0},
collisiondetection = true,
collision_removal = true,
}
);
return
end
local obj = minetest.add_entity(pos, "basic_robot:projectile");
if not obj then return end
obj:setvelocity(velocity);
obj:set_properties({textures = {texture or "default_furnace_fire_fg.png"}})
obj:setacceleration({x=0,y=-gravity,z=0});
local luaent = obj:get_luaentity();
luaent.name = name;
luaent.spawnpos = pos;
end,
fire_pos = function()
local fire_pos = basic_robot.data[name].fire_pos;
basic_robot.data[name].fire_pos = nil;
return fire_pos
end,
label = function(text)
local obj = basic_robot.data[name].obj;
obj:set_properties({nametag = text or ""}); -- "[" .. name .. "] " ..
end,
display_text = function(text,linesize,size)
local obj = basic_robot.data[name].obj;
return commands.display_text(obj,text,linesize,size)
end,
find_path = function(pos) -- compute path
return commands.find_path(name,pos)
end,
walk_path = function() -- walk to next node of path
return commands.walk_path(name)
end,
},
machine = {-- adds technic like functionality to robots: power generation, smelting, grinding, compressing
energy = function() return basic_robot.data[name].menergy or 0 end,
generate_power = function(input,amount) return commands.machine.generate_power(name,input, amount) end,
smelt = function(input,amount) return commands.machine.smelt(name,input, amount) end,
grind = function(input) return commands.machine.grind(name,input) end,
compress = function(input) return commands.machine.compress(name,input) end,
transfer_power = function(amount,target) return commands.machine.transfer_power(name,amount,target) end,
},
crypto = {-- basic cryptography - encryption, scramble, mod hash
encrypt = commands.crypto.encrypt,
decrypt = commands.crypto.decrypt,
scramble = commands.crypto.scramble,
basic_hash = commands.crypto.basic_hash,
};
keyboard = {
get = function() return commands.keyboard.get(name) end,
set = function(pos,type) return commands.keyboard.set(basic_robot.data[name],pos,type) end,
read = function(pos) return minetest.get_node(pos).name end,
},
find_nodes =
function(nodename,r)
if r>8 then return false end
local q = minetest.find_node_near(basic_robot.data[name].obj:get_pos(), r, nodename);
if q==nil then return false end
local p = basic_robot.data[name].obj:get_pos()
return math.sqrt((p.x-q.x)^2+(p.y-q.y)^2+(p.z-q.z)^2)
end, -- in radius around position
find_player =
function(r,pos)
pos = pos or basic_robot.data[name].obj:get_pos();
if r<0 or r>10 then return false end
local objects = minetest.get_objects_inside_radius(pos, r);
local plist = {};
for _,obj in pairs(objects) do
if obj:is_player() then
plist[#plist+1]=obj:get_player_name();
end
end
if not plist[1] then return nil end
return plist
end, -- in radius around position
player = {
getpos = function(name)
local player = minetest.get_player_by_name(name);
if player then return player:get_pos() else return nil end
end,
getview = function(name)
local player = minetest.get_player_by_name(name);
if player then return player:get_look_dir() else return nil end
end,
connected = function()
local players = minetest.get_connected_players();
local plist = {}
for _,player in pairs(players) do
plist[#plist+1]=player:get_player_name()
end
if not plist[1] then return nil else return plist end
end
},
attack = function(target) return basic_robot.commands.attack(name,target) end, -- attack player if nearby
grab = function(target) return basic_robot.commands.grab(name,target) end,
say = function(text, pname)
if not basic_robot.data[name].quiet_mode and not pname then
minetest.chat_send_all("<robot ".. name .. "> " .. text)
if not basic_robot.data[name].allow_spam then
basic_robot.data[name].quiet_mode=true
end
else
if not pname then pname = basic_robot.data[name].owner end
minetest.chat_send_player(pname,"<robot ".. name .. "> " .. text) -- send chat only to player pname
end
end,
book = {
read = function(i)
if i<=0 or i > 32 then return nil end
local pos = basic_robot.data[name].spawnpos; local meta = minetest.get_meta(pos);
local libposstring = meta:get_string("libpos");
local words = {}; for word in string.gmatch(libposstring,"%S+") do words[#words+1]=word end
local libpos = {x=tonumber(words[1] or pos.x),y=tonumber(words[2] or pos.y),z=tonumber(words[3] or pos.z)};
local inv = minetest.get_meta(libpos):get_inventory();local itemstack = inv:get_stack("library", i);
if itemstack then
return commands.read_book(itemstack);
else
return nil
end
end,
write = function(i,title,text)
if i<=0 or i > 32 then return nil end
local inv = minetest.get_meta(basic_robot.data[name].spawnpos):get_inventory();
local stackname = inv:get_stack("library",i):get_name();
if basic_robot.data[name].authlevel<3 and (stackname ~= "default:book_written" and stackname~= "default:book") then return nil end
local stack = basic_robot.commands.write_book(basic_robot.data[name].owner,title,text);
if stack then inv:set_stack("library", i, stack) end
end
},
code = {
set = function(text) -- replace bytecode in sandbox with this
local err = commands.setCode( name, text ); -- compile code
if err then
minetest.chat_send_player(name,"#ROBOT CODE COMPILATION ERROR : " .. err)
local obj = basic_robot.data[name].obj;
obj:remove();
basic_robot.data[name].obj = nil;
return
end
end,
},
rom = basic_robot.data[pname].rom,
string = {
byte = string.byte, char = string.char,
find = string.find,
gsub = string.gsub,
gmatch = string.gmatch,
len = string.len, lower = string.lower,
upper = string.upper, rep = string.rep,
reverse = string.reverse, sub = string.sub,
format = function(...)
local out = string.format(...)
if string.len(out) > 1024 then
error("result string longer than 1024")
return
end
return out
end,
concat = function(strings, sep)
local length = 0;
for i = 1,#strings do
length = length + string.len(strings[i])
if length > 1024 then
error("result string longer than 1024")
return
end
end
return table.concat(strings,sep or "")
end,
},
math = {
abs = math.abs, acos = math.acos,
asin = math.asin, atan = math.atan,
atan2 = math.atan2, ceil = math.ceil,
cos = math.cos, cosh = math.cosh,
deg = math.deg, exp = math.exp,
floor = math.floor, fmod = math.fmod,
frexp = math.frexp, huge = math.huge,
ldexp = math.ldexp, log = math.log,
log10 = math.log10, max = math.max,
min = math.min, modf = math.modf,
pi = math.pi, pow = math.pow,
rad = math.rad, random = math.random,
sin = math.sin, sinh = math.sinh,
sqrt = math.sqrt, tan = math.tan,
tanh = math.tanh,
},
os = {
clock = os.clock,
difftime = os.difftime,
time = os.time,
date = os.date,
},
colorize = core.colorize,
serialize = minetest.serialize,
deserialize = minetest.deserialize,
tonumber = tonumber, pairs = pairs,
ipairs = ipairs, error = error, type=type,
};
-- ROBOT FUNCTIONS: move,dig, place,insert,take,check_inventory,activate,read_node,read_text,write_text
env.move = {}; -- changes position of robot
for dir, dir_id in pairs(directions) do
env.move[dir] = function() return commands.move(name,dir_id) end
end
env.dig = {};
for dir, dir_id in pairs(directions) do
env.dig[dir] = function() return commands.dig(name,dir_id) end
end
env.place = {};
for dir, dir_id in pairs(directions) do
env.place[dir] = function(nodename, param2) return commands.place(name,nodename, param2, dir_id) end
end
env.insert = {}; -- insert item from robot inventory into another inventory
for dir, dir_id in pairs(directions) do
env.insert[dir] = function(item, inventory) return commands.insert_item(name,item, inventory,dir_id) end
end
env.take = {}; -- takes item from inventory and puts it in robot inventory
for dir, dir_id in pairs(directions) do
env.take[dir] = function(item, inventory) return commands.take_item(name,item, inventory,dir_id) end
end
env.check_inventory = {};
for dir, dir_id in pairs(directions) do
env.check_inventory[dir] = function(itemname, inventory,i) return commands.check_inventory(name,itemname, inventory,i,dir_id) end
end
env.check_inventory.self = function(itemname, inventory,i) return commands.check_inventory(name,itemname, inventory,i,0) end;
env.activate = {};
for dir, dir_id in pairs(directions) do
env.activate[dir] = function(mode) return commands.activate(name,mode, dir_id) end
end
env.read_node = {};
for dir, dir_id in pairs(directions) do
env.read_node[dir] = function() return commands.read_node(name,dir_id) end
end
env.read_text = {} -- returns text
for dir, dir_id in pairs(directions) do
env.read_text[dir] = function(stringname,mode) return commands.read_text(name,mode,dir_id,stringname) end
end
env.write_text = {} -- returns text
for dir, dir_id in pairs(directions) do
env.write_text[dir] = function(text) return commands.write_text(name, dir_id,text) end
end
--farming specials
env.machine.place_seed = {}; local env_machine_place_seed = env.machine.place_seed
env.machine.dig_seed = {}; local env_machine_dig_seed = env.machine.dig_seed;
for dir, dir_id in pairs(directions) do
env_machine_place_seed[dir] = function(seedbookname) return commands.machine.place_seed(name,dir_id,seedbookname) end
env_machine_dig_seed[dir] = function(dir) return commands.machine.dig_seed(name,dir_id) end
end
if authlevel>=1 then -- robot privs
env.self.sound = minetest.sound_play
env.self.sound_stop = minetest.sound_stop
env.table = {
concat = table.concat,
insert = table.insert,
maxn = table.maxn,
remove = table.remove,
sort = table.sort,
}
env.code.run = function(script)
if basic_robot.data[name].authlevel < 3 then
local err = check_code(script);
script = preprocess_code(script, basic_robot.call_limit[basic_robot.data[name].authlevel+1]);
if err then
minetest.chat_send_player(name,"#ROBOT CODE CHECK ERROR : " .. err)
return
end
end
local ScriptFunc, CompileError = loadstring( script )
if CompileError then
minetest.chat_send_player(name, "#code.run: compile error " .. CompileError )
return false
end
setfenv( ScriptFunc, basic_robot.data[name].sandbox )
local _, RuntimeError = pcall( ScriptFunc );
if RuntimeError then
minetest.chat_send_player(name, "#code.run: run error " .. RuntimeError )
return false
end
return true
end
env.self.read_form = function()
local fields = basic_robot.data[name].read_form;
local sender = basic_robot.data[name].form_sender;
basic_robot.data[name].read_form = nil;
basic_robot.data[name].form_sender = nil;
return sender,fields
end
env.self.show_form = function(playername, form)
commands.show_form(name, playername, form)
end
end
-- set up sandbox for puzzle
if authlevel>=2 then -- puzzle privs
basic_robot.data[name].puzzle = {};
local data = basic_robot.data[name];
local pdata = data.puzzle;
pdata.triggerdata = {};
pdata.gamedata = {};
pdata.block_ids = {}
pdata.triggers = {};
env.puzzle = { -- puzzle functionality
set_node = function(pos,node) commands.puzzle.set_node(data,pos,node) end,
get_node = function(pos) return minetest.get_node(pos) end,
activate = function(mode,pos) commands.puzzle.activate(data,mode,pos) end,
get_meta = function(pos) return commands.puzzle.get_meta(data,pos) end,
get_gametime = function() return minetest.get_gametime() end,
get_node_inv = function(pos) return commands.puzzle.get_node_inv(data,pos) end,
get_player = function(pname) return commands.puzzle.get_player(data,pname) end,
chat_send_player = function(pname, text) minetest.chat_send_player(pname or "", text) end,
get_player_inv = function(pname) return commands.puzzle.get_player_inv(data,pname) end,
set_triggers = function(triggers) commands.puzzle.set_triggers(pdata,triggers) end, -- FIX THIS!
check_triggers = function(pname)
local player = minetest.get_player_by_name(pname); if not player then return end
commands.puzzle.checkpos(pdata,player:get_pos(),pname)
end,
add_particle = function(def) minetest.add_particle(def) end,
count_objects = function(pos,radius) return #minetest.get_objects_inside_radius(pos, math.min(radius,5)) end,
pdata = pdata,
ItemStack = ItemStack,
}
end
--special sandbox for admin
if authlevel<3 then -- is admin?
env._G = env;
else
env.minetest = minetest;
env._G=_G;
debug = debug;
end
return env
end
-- code checker
-- bugfixes:
-- player Midskip found problem with code checking, fixed
check_code = function(code)
--"while ", "for ", "do ","goto ",
local bad_code = {"repeat", "until", "_G", "while%(", "while{", "pcall","[^%.]%.%.[^%.]","\\\"","\\\'","%[=*%["}
for _, v in pairs(bad_code) do
if string.find(code, v) then
return v .. " is not allowed!";
end
end
end
identify_strings = function(code) -- returns list of positions {start,end} of literal strings in lua code
local i = 0; local j; local _; local length = string.len(code);
local mode = 0; -- 0: not in string, 1: in '...' string, 2: in "..." string, 3. in [==[ ... ]==] string
local modes = {
{"'","'"}, -- inside ' '
{"\"","\""}, -- inside " "
{"%[=*%[","%]=*%]"}, -- inside [=[ ]=]
}
local ret = {}
while i < length do
i=i+1
local jmin = length+1;
if mode == 0 then -- not yet inside string
for k=1,#modes do
j = string.find(code,modes[k][1],i);
if j and j<jmin then -- pick closest one
if string.sub(code,j-1,j-1) ~="\\" then
jmin = j
mode = k
else
j=j+1;
end
end
end
if mode ~= 0 then -- found something
j=jmin
ret[#ret+1] = {jmin}
end
if not j then break end -- found nothing
else
_,j = string.find(code,modes[mode][2],i); -- search for closing pair
if not j then break end
local pchar = string.sub(code,j-1,j-1)
if (mode~=2 or (pchar ~= "\\") or string.sub(code,j-2,j-1) == "\\\\") then -- not (" and not \" - but "\\" is allowed)
ret[#ret][2] = j
mode = 0
end
if pchar == "\\" then j=j+1 end
end
i=j -- move to next position
end
if mode~= 0 then ret[#ret][2] = length end
return ret
end
is_inside_string = function(strings,pos) -- is position inside one of the strings?
local low = 1; local high = #strings;
if high == 0 then return false end
local mid = high;
while high>low+1 do
mid = math.floor((low+high)/2)
if pos<strings[mid][1] then high = mid else low = mid end
end
if pos>strings[low][2] then mid = high else mid = low end
return strings[mid][1]<=pos and pos<=strings[mid][2]
end
local find_outside_string = function(script, pattern, pos, strings)
local length = string.len(script)
local found = true;
local i1 = pos;
while found do
found = false
local i2 = string.find(script,pattern,i1);
if i2 then
if not is_inside_string(strings,i2) then return i2 end
found = true;
i1 = i2+1;
end
end
return nil
end
-- COMPILATION
preprocess_code = function(script, call_limit) -- version 07/24/2018
--[[ idea: in each local a = function (args) ... end insert counter like:
local a = function (args) counter_check_code ... end
when counter exceeds limit exit with error
--]]
--script = script:gsub("%-%-%[%[.*%-%-%]%]",""):gsub("%-%-[^\n]*\n","\n") -- strip comments
script = string.gsub(script,"%-%-[^\n]+\n","\n") -- strip single line comments, multiline not allowed
-- process script to insert call counter in every function
local _increase_ccounter = " _Gc = _Gc + 1; if _Gc > " .. call_limit ..
" then _Gerror(\"Execution count \".. _Gc .. \" exceeded ".. call_limit .. "\") end; "
local i1=0; local i2 = 0;
local found = true;
local strings = identify_strings(script);
local inserts = {};
local constructs = {
{"while%s", "%sdo%s", 2, 6}, -- numbers: insertion pos = i2+2, after skip to i1 = i12+6
{"function", ")", 0, 8},
{"for%s", "%sdo%s", 2, 4},
{"goto%s", nil , -1, 5},
}
for i = 1,#constructs do
i1 = 0; found = true
while (found) do -- PROCESS SCRIPT AND INSERT COUNTER AT PROBLEMATIC SPOTS
found = false;
i2=find_outside_string(script, constructs[i][1], i1, strings) -- first part of construct
if i2 then
local i21 = i2;
if constructs[i][2] then
i2 = find_outside_string(script, constructs[i][2], i2, strings); -- second part of construct ( if any )
if i2 then
inserts[#inserts+1]= i2+constructs[i][3]; -- move to last position of construct[i][2]
found = true;
end
else
inserts[#inserts+1]= i2+constructs[i][3]
found = true -- 1 part construct
end
if found then
i1=i21+constructs[i][4]; -- skip to after constructs[i][1]
end
end
end
end
table.sort(inserts)
-- add inserts
local ret = {}; i1=1;
for i = 1, #inserts do
i2 = inserts[i];
ret[#ret+1] = string.sub(script,i1,i2);
i1 = i2+1;
end
ret[#ret+1] = string.sub(script,i1);
script = table.concat(ret,_increase_ccounter)
-- must reset ccounter when paused, but user should not be able to force reset by modifying pause!
-- (suggestion about 'pause' by Kimapr, 09/26/2019)
return "_Gc = 0 local _Gpause = pause pause = function(amount) _Gc = 0; _Gpause(amount) end " .. script;
--return script:gsub("pause%(%)", "_c_ = 0; pause()") -- reset ccounter at pause
end
local function CompileCode ( script )
local ScriptFunc, CompileError = loadstring( script )
if CompileError then
return nil, CompileError
end
return ScriptFunc, nil
end
local function initSandbox (name)
basic_robot.data[name].sandbox = getSandboxEnv (name);
end
local function setCode( name, script ) -- to run script: 1. initSandbox 2. setCode 3. runSandbox
local err;
local cor = false;
if string.find(string.sub(script,1,32), "coroutine") then cor = true end
local authlevel = basic_robot.data[name].authlevel;
if authlevel<3 then -- not admin
err = check_code(script);
script = preprocess_code(script,basic_robot.call_limit[authlevel+1]);
elseif cor then
script = preprocess_code(script, basic_robot.call_limit[authlevel+1]); -- coroutines need ccounter reset or 'infinite loops' fail after limit
end
if err then return err end
local bytecode, err = CompileCode ( script );
if err then return err end
basic_robot.data[name].bytecode = bytecode;
if cor then -- create coroutine if requested
basic_robot.data[name].cor = coroutine.create(bytecode)
else
basic_robot.data[name].cor = nil
end
return nil
end
basic_robot.commands.setCode=setCode; -- so we can use it
local function runSandbox( name)
local data = basic_robot.data[name]
local ScriptFunc = data.bytecode;
if not ScriptFunc then
return "Bytecode missing."
end
data.operations = basic_robot.maxoperations;
data.t = os.clock() -- timing
setfenv( ScriptFunc, data.sandbox )
local cor = data.cor;
if cor then -- coroutine!
local err,ret
ret,err = coroutine.resume(cor)
data.t = os.clock()-data.t
if err then return err end
return nil
end
local Result, RuntimeError = pcall( ScriptFunc )
data.t = os.clock()-data.t
if RuntimeError then
return RuntimeError
end
return nil
end
-- note: to see memory used by lua in kbytes: collectgarbage("count")
local get_authlevel = function(name) -- given player name return auth level
local privs = minetest.get_player_privs(name);
local authlevel = 0;
if privs.privs then -- set auth level depending on privs
authlevel = 3
elseif privs.puzzle then
authlevel = 2
elseif privs.robot then
authlevel = 1
else
authlevel = 0
end
return authlevel
end
local function setupid(owner)
local privs = minetest.get_player_privs(owner); if not privs then return end
local maxid = basic_robot.count[get_authlevel(owner)+1] or 2;
basic_robot.ids[owner] = {id = 1, maxid = maxid}; --active id for remove control
end
local robot_spawner_update_form = function (pos, mode)
if not pos then return end
local meta = minetest.get_meta(pos);
if not meta then return end
local code = minetest.formspec_escape(meta:get_string("code"));
local form;
local id = meta:get_int("id");
if mode ~= 1 then -- when placed
form =
"size[9.5,8]" .. -- width, height
"style_type[textarea;font_size=12;font=mono;bgcolor=#000000;textcolor=#00FF00;border=false]"..
"style_type[button;font_size=14;font=mono;bgcolor=#000000;border=false]"..
"style_type[button_exit;font_size=14;font=mono;bgcolor=#000000;border=false]"..
"textarea[1.25,-0.25;8.8,10.25;code;;".. code.."]"..
"button[-0.15,7.5;1.25,1;EDIT;EDIT]"..
"button[-0.15,-0.25;1.25,1;OK;"..minetest.colorize("yellow","SAVE").."]"..
"button_exit[-0.15, 0.75;1.25,1;spawn;"..minetest.colorize("green","START").."]"..
"button[-0.15, 1.75;1.25,1;despawn;"..minetest.colorize("red","STOP").."]"..
"field[0.15,3.;1.2,1;id;id;"..id.."]"..
"button[-0.15, 3.6;1.25,1;inventory;STORAGE]"..
"button[-0.15, 4.6;1.25,1;library;LIBRARY]"..
"button[-0.15, 5.6;1.25,1;help;HELP]";
else -- when robot clicked
form =
"size[9.5,8]" .. -- width, height
"textarea[1.25,-0.25;8.75,10.25;code;;".. code.."]"..
"button_exit[-0.15,-0.25;1.25,1;OK;SAVE]"..
"button[-0.15, 1.75;1.25,1;despawn;STOP]"..
"button[-0.15, 3.6;1.25,1;inventory;storage]"..
"button[-0.15, 4.6;1.25,1;library;library]"..
"button[-0.15, 5.6;1.25,1;help;help]";
end
if mode == 1 then return form end
meta:set_string("formspec",form)
end
basic_robot.editor = {};
editor_get_lines = function(text,name)
local data = basic_robot.editor[name];
if not data then
basic_robot.editor[name] = {};
basic_robot.editor[name].lines = {};
basic_robot.editor[name].selection = 1;
data = basic_robot.editor[name];
else
data.lines = {};
end
local lines = data.lines;
for line in string.gmatch(text,"[^\r\n]+") do lines[#lines+1] = line end
end
code_edit_form = function(pos,name)
local lines = basic_robot.editor[name].lines;
local input = minetest.formspec_escape(basic_robot.editor[name].input or "");
local selection = basic_robot.editor[name].selection or 1;
local list = "";
for _,line in pairs(lines) do list = list .. minetest.formspec_escape(line) .. "," end
local form = "size[12,9.25]" .. "textlist[0,0;12,8;listname;" .. list .. ";"..selection..";false]" ..
"button[10,8;2.25,1;INSERT;INSERT LINE]" ..
"button[10,8.75;2.25,1;DELETE;DELETE LINE]" ..
"button_exit[2.25,8.75;2.25,1;SAVE;SAVE CODE]" ..
"button[0,8.75;2.25,1;UPDATE;UPDATE LINE] label[4.25,9; LINE " .. selection .."]"..
"textarea[0.25,8;10,1;input;;".. input .. "]"
return form
end
local function init_robot(obj, resetSandbox)
local self = obj:get_luaentity();
local name = self.name; -- robot name
basic_robot.data[name].obj = obj; --register object
--init settings
basic_robot.data.listening[name] = nil -- dont listen at beginning
basic_robot.data[name].quiet_mode = false; -- can chat globally
-- check if admin robot
basic_robot.data[name].authlevel = self.authlevel or 0
--robot appearance,armor...
obj:set_properties({infotext = "robot " .. name});
obj:set_properties({nametag = "[" .. name.."]",nametag_color = "LawnGreen"});
obj:set_armor_groups({fleshy=0})
if resetSandbox then initSandbox ( name ) end
end
minetest.register_entity("basic_robot:robot",{
operations = basic_robot.maxoperations,
owner = "",
name = "",
hp_max = 100,
itemstring = "robot",
code = "",
timer = 0,
timestep = 1, -- run every 1 second
spawnpos = nil,
--visual="mesh",
--mesh = "char.obj", --this is good: aligned and rotated in blender - but how to move nametag up? now is stuck in head
--textures={"character.png"},
visual="cube",
textures={"topface.png","legs.png","left-hand.png","right-hand.png","face.png","face-back.png"},
visual_size={x=1,y=1},
running = 0, -- does it run code or is it idle?
collisionbox = {-0.5,-0.5,-0.5, 0.5,0.5,0.5},
physical=true,
on_activate = function(self, staticdata)
-- reactivate robot
if staticdata~="" then
self.name = staticdata; -- remember its name
local data = basic_robot.data[self.name];
if not data then
--minetest.chat_send_all("#ROBOT INIT: error. spawn robot again.")
self.object:remove();
return;
end
if data.object and data.object~=self.object then -- is there another one already?
self.object:remove();
return;
end
self.owner = data.owner;
self.authlevel = data.authlevel;
self.spawnpos = {x=data.spawnpos.x,y=data.spawnpos.y,z=data.spawnpos.z};
init_robot(self.object, false); -- do not reset sandbox to keep all variables, just wake up
self.running = 1;
local meta = minetest.get_meta(data.spawnpos);
if meta then self.code = meta:get_string("code") end -- remember code
if not self.code or self.code == "" then
minetest.chat_send_player(self.owner, "#ROBOT INIT: no code found")
self.object:remove();
end