forked from ac-minetest/basic_robot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit.lua
2011 lines (1652 loc) · 65.8 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
local function file_exists(name)
local file = io.open(name,"r")
if file ~= nil then
io.close(file)
return true
end
return false
end
local modName = minetest.get_current_modname()
basic_robot = {};
local defaultSettingsFilename = minetest.get_modpath(modName).."/settings.default.lua";
dofile(defaultSettingsFilename)
local customSettingsFilename = minetest.get_modpath(modName).."/settings.lua"
if file_exists(customSettingsFilename) then
minetest.log("info", "Loading custom settings ...")
dofile(customSettingsFilename)
else
minetest.log("warning", "WARNING! No custom settings found in "..customSettingsFilename..". Using defaults from "..defaultSettingsFilename.."!")
end
basic_robot.http_api = minetest.request_http_api();
basic_robot.version = "2017/12/18a";
basic_robot.data = {}; -- stores all robot related data
--[[
[name] = { sandbox= .., bytecode = ..., ram = ..., obj = robot object, spawnpos= ..., authlevel = ...}
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.data.listening = {}; -- which robots listen to chat
dofile(minetest.get_modpath(modName).."/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 env =
{
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:getpos(); 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.cos(yaw),y=0,z=v*math.sin(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)
return commands.craft(item, mode, idx, name)
end,
self = {
pos = function() return basic_robot.data[name].obj:getpos() 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,
viewdir = function() local yaw = basic_robot.data[name].obj:getyaw(); return {x=math.cos(yaw), y = 0, z=math.sin(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)
if mode == 1 then
basic_robot.data.listening[name] = true
else
basic_robot.data.listening[name] = nil
end
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:setpos({x=pos.x,y=pos.y+1,z=pos.z}); obj:setyaw(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:getpos();
local yaw = obj:getyaw();
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: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}); -- "[" .. name .. "] " ..
end,
display_text = function(text,linesize,size)
local obj = basic_robot.data[name].obj;
return commands.display_text(obj,text,linesize,size)
end,
sound = function(sample,volume, pos)
if pos then
return minetest.sound_play( sample,
{
pos = pos,
gain = volume or 1,
max_hear_distance = 32, -- default, uses an euclidean metric
})
end
local obj = basic_robot.data[name].obj;
return minetest.sound_play( sample,
{
object = obj,
gain = volume or 1,
max_hear_distance = 32, -- default, uses an euclidean metric
})
end,
sound_stop = function(handle)
minetest.sound_stop(handle)
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:getpos(), r, nodename);
if q==nil then return false end
local p = basic_robot.data[name].obj:getpos()
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:getpos();
if 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:getpos() 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, owneronly)
if not basic_robot.data[name].quiet_mode and not owneronly 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
minetest.chat_send_player(basic_robot.data[name].owner,"<robot ".. name .. "> " .. text)
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 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,
run = function(script)
if basic_robot.data[name].authlevel < 3 then
local err = check_code(script);
script = preprocess_code(script);
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 Result, RuntimeError = pcall( ScriptFunc );
if RuntimeError then
minetest.chat_send_player(name, "#code.run: run error " .. RuntimeError )
return false
end
return true
end
},
rom = basic_robot.data[name].rom,
string = {
byte = string.byte, char = string.char,
find = string.find,
format = string.format, gsub = string.gsub,
gmatch = string.gmatch,
len = string.len, lower = string.lower,
upper = string.upper, rep = string.rep,
reverse = string.reverse, sub = string.sub,
},
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,
},
table = {
concat = table.concat,
insert = table.insert,
maxn = table.maxn,
remove = table.remove,
sort = table.sort,
},
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,
--_ccounter = basic_robot.data[name].ccounter, -- counts how many executions of critical spots in script
increase_ccounter =
function()
local _ccounter = basic_robot.data[name].ccounter;
if _ccounter > basic_robot.call_limit then
error("Execution limit " .. basic_robot.call_limit .. " exceeded");
end
basic_robot.data[name].ccounter = _ccounter + 1;
end,
};
-- 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
if authlevel>=1 then -- robot privs
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:getpos(),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
check_code = function(code)
--"while ", "for ", "do ","goto ",
local bad_code = {"repeat", "until", "_ccounter", "_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
is_inside_string = function(pos,script)
local i1=string.find (script, "\"", 1);
if not i1 then
return false
end
local i2=0;
local par = 1;
if pos<i1 then
return false
end
while i1 do
i2=string.find(script,"\"",i1+1);
if i2 then
par = 1 - par;
else
return false
end
if par == 0 then
if i1<pos and pos<i2 then
return true
end
end
i1=i2;
end
return false;
end
-- COMPILATION
preprocess_code = function(script)
--[[ idea: in each local a = function (args) ... end insert counter like:
local a = function (args) counter() ... end
when counter exceeds limit exit with error
--]]
script="_ccounter = 0; " .. script;
local i1 -- process script to insert call counter in every function
local _increase_ccounter = " if _ccounter > " .. basic_robot.call_limit ..
" then error(\"Execution count \".. _ccounter .. \" exceeded ".. basic_robot.call_limit .. "\") end _ccounter = _ccounter + 1; "
local i1=0; local i2 = 0;
local found = true;
while (found) do -- PROCESS SCRIPT AND INSERT COUNTER AT PROBLEMATIC SPOTS
found = false;
i2 = nil;
-- i1 = where its looking
i2=string.find (script, "while ", i1) -- fix while OK
if i2 then
if not is_inside_string(i2,script) then
local i21 = i2;
i2=string.find(script, "do", i2);
if i2 then
script = script.sub(script,1, i2+1) .. _increase_ccounter .. script.sub(script, i2+2);
i1=i21+6; -- after while
found = true;
end
end
end
i2=string.find (script, "function", i1) -- fix functions
if i2 then
--minetest.chat_send_all("func0")
if not is_inside_string(i2,script) then
i2=string.find(script, ")", i2);
if i2 then
script = script.sub(script,1, i2) .. _increase_ccounter .. script.sub(script, i2+1);
i1=i2+string.len(_increase_ccounter);
found = true;
end
end
end
i2=string.find (script, "for ", i1) -- fix for OK
if i2 then
if not is_inside_string(i2,script) then
i2=string.find(script, "do", i2);
if i2 then
script = script.sub(script,1, i2+1) .. _increase_ccounter .. script.sub(script, i2+2);
i1=i2+string.len(_increase_ccounter);
found = true;
end
end
end
i2=string.find (script, "goto ", i1) -- fix goto OK
if i2 then
if not is_inside_string(i2,script) then
script = script.sub(script,1, i2-1) .. _increase_ccounter .. script.sub(script, i2);
i1=i2+string.len(_increase_ccounter)+5; -- insert + skip goto
found = true;
end
end
--minetest.chat_send_all("code rem " .. string.sub(script,i1))
end
return script
end
local function CompileCode ( script )
--minetest.chat_send_all(script)
--if true then return nil, "" end
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;
if basic_robot.data[name].authlevel<3 then -- not admin
err = check_code(script);
script = preprocess_code(script);
end
if err then return err end
local bytecode, err = CompileCode ( script );
if err then return err end
basic_robot.data[name].bytecode = bytecode;
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.ccounter = 0;
data.operations = basic_robot.maxoperations;
setfenv( ScriptFunc, data.sandbox )
local Result, RuntimeError = pcall( ScriptFunc )
if RuntimeError then
return RuntimeError
end
return nil
end
-- note: to see memory used by lua in kbytes: collectgarbage("count")
local function setupid(owner)
local privs = minetest.get_player_privs(owner); if not privs then return end
local maxid = basic_robot.entry_count;
if privs.robot then maxid = basic_robot.advanced_count end -- max id's per user
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
"textarea[1.25,-0.25;8.75,9.8;code;;".. code.."]"..
"button[-0.25,7.5;1.25,1;EDIT;EDIT]"..
"button_exit[-0.25,-0.25;1.25,1;OK;SAVE]"..
"button_exit[-0.25, 0.75;1.25,1;spawn;START]"..
"button[-0.25, 1.75;1.25,1;despawn;STOP]"..
"field[0.25,3.5;1.0,1;id;ID;"..id.."]"..
"button[-0.25, 4.1;1.25,1;inventory;INV]"..
"button[-0.25, 5.1;1.25,1;library;LIB]"..
"button[-0.25, 6.1;1.25,1;help;?]"
else -- when robot clicked
form =
"size[9.5,8]" .. -- width, height
"textarea[1.25,-0.25;8.75,9.8;code;;".. code.."]"..
"button_exit[-0.25,-0.25;1.25,1;OK;SAVE]"..
"button_exit[-0.25, 1.75;1.25,1;despawn;STOP]"..
"button[-0.25, 4.1;1.25,1;inventory;INV]"..
"button[-0.25, 5.1;1.25,1;library;LIB]"..
"button[-0.25, 6.1;1.25,1;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,1;INSERT;INS LINE]" ..
"button[10,8.75;2,1;DELETE;DEL LINE]" ..
"button_exit[2,8.75;2,1;SAVE;SAVE]" ..
"button[0,8.75;2,1;UPDATE;UPD LINE]"..
"textarea[0.25,8;10,1;input;;".. input .. "]"
return form
end
local function init_robot(obj)
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})
initSandbox ( name )
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={"arrow.png","basic_machine_side.png","face.png","basic_machine_side.png","basic_machine_side.png","basic_machine_side.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
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);
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
return
end
-- lost robots
--if not self.spawnpos then self.object:remove() return end
end,
get_staticdata = function(self)
return self.name;
end,
on_punch = function (self, puncher, time_from_last_punch, tool_capabilities, dir)
end,
on_step = function(self, dtime)
self.timer=self.timer+dtime
if self.timer>self.timestep and self.running == 1 then
self.timer = 0;
local err = runSandbox(self.name);
if err and type(err) == "string" then
local i = string.find(err,":");
if i then err = string.sub(err,i+1) end
if string.sub(err,-5)~="abort" then
minetest.chat_send_player(self.owner,"#ROBOT ERROR : " .. err)
end
self.running = 0; -- stop execution
if string.find(err,"stack overflow") then -- remove stupid player privs and spawner, ban player ip
local name = self.name;
local pos = basic_robot.data[name].spawnpos;
minetest.set_node(pos, {name = "air"});
local privs = core.get_player_privs(self.owner);privs.interact = false;
core.set_player_privs(self.owner, privs); minetest.auth_reload()
minetest.ban_player(self.owner)
end
local name = self.name;
local pos = basic_robot.data[name].spawnpos;
if not basic_robot.data[name] then return end
if basic_robot.data[name].obj then
basic_robot.data[name].obj = nil;
end
self.object:remove();
end
return
end
return
end,
on_rightclick = function(self, clicker)
local owner = basic_robot.data[self.name].owner
if owner == clicker:get_player_name() then
local text = minetest.formspec_escape(self.code)
local form = robot_spawner_update_form(self.spawnpos, 1)
minetest.show_formspec(clicker:get_player_name(), "robot_worker_" .. self.name, form);
else
minetest.chat_send_player(clicker, "This robot is not yours. You can not access its menu!")
end
end,
})
local spawn_robot = function(pos,node,ttl)
if type(ttl) ~= "number" then ttl = 0 end
if ttl<0 then return end
local meta = minetest.get_meta(pos);
--temperature based spam activate protect
local t0 = meta:get_int("t");
local t1 = minetest.get_gametime();
local T = meta:get_int("T"); -- temperature
if t0>t1-2 then -- activated before natural time
T=T+1;
else
if T>0 then
T=T-1
if t1-t0>5 then T = 0 end
end
end
meta:set_int("T",T);
meta:set_int("t",t1); -- update last activation time
if T > 2 then -- overheat
minetest.sound_play("default_cool_lava",{pos = pos, max_hear_distance = 16, gain = 0.25})
meta:set_string("infotext","overheat: temperature ".. T)
return
end
-- spawn robot on top
pos.y=pos.y+1;
local owner = meta:get_string("owner")
local id = meta:get_int("id");
local name = owner..id;
if id <= 0 then -- just compile code and run it, no robot spawn
local codechange = false;
if meta:get_int("codechange") == 1 then
meta:set_int("codechange",0);
codechange = true;
end
-- compile code & run it