content
stringlengths
5
1.05M
#!/usr/bin/env lua local gl = require("moongl") local glfw = require("moonglfw") local SCR_WIDTH, SCR_HEIGHT = 800, 600 local vertex_shader_source = [[ #version 330 core layout (location = 0) in vec3 aPos; void main() { gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0); } ]] local fragment_shader1_source = [[ #version 330 core out vec4 FragColor; void main() { FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f); // orange } ]] local fragment_shader2_source = [[ #version 330 core out vec4 FragColor; void main() { FragColor = vec4(1.0f, 1.0f, 0.0f, 1.0f); // yellow } ]] -- glfw inits and window creation --------------------------------------------- glfw.version_hint(3, 3, 'core') local window = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL") glfw.make_context_current(window) gl.init() -- this loads all OpenGL function pointers glfw.set_framebuffer_size_callback(window, function (window, width, height) gl.viewport(0, 0, width, height) end) -- build and compile our shader programs --------------------------------------- -- vertex shader local vsh = gl.create_shader('vertex') gl.shader_source(vsh, vertex_shader_source) gl.compile_shader(vsh) if not gl.get_shader(vsh, 'compile status') then error(gl.get_shader_info_log(vsh)) end -- fragment shader 1 local fsh1 = gl.create_shader('fragment') gl.shader_source(fsh1, fragment_shader1_source) gl.compile_shader(fsh1) if not gl.get_shader(fsh1, 'compile status') then error(gl.get_shader_info_log(fsh1)) end -- fragment shader 2 local fsh2 = gl.create_shader('fragment') gl.shader_source(fsh2, fragment_shader2_source) gl.compile_shader(fsh2) if not gl.get_shader(fsh2, 'compile status') then error(gl.get_shader_info_log(fsh2)) end -- program 1 local prog1 = gl.create_program() gl.attach_shader(prog1, vsh) gl.attach_shader(prog1, fsh1) gl.link_program(prog1) if not gl.get_program(prog1, 'link status') then error(gl.get_program_info_log(prog1)) end -- program 2 local prog2 = gl.create_program() -- The second program object uses a different fragment shader, but same vertex shader. -- This is perfectly allowed since the inputs and outputs of both the vertex and -- fragment shaders are equally matched. gl.attach_shader(prog2, vsh) gl.attach_shader(prog2, fsh2) gl.link_program(prog2) if not gl.get_program(prog2, 'link status') then error(gl.get_program_info_log(prog2)) end gl.delete_shader(vsh) gl.delete_shader(fsh1) gl.delete_shader(fsh2) -- set up vertex data (and buffer(s)) and configure vertex attributes --------- local first_triangle = { -0.9, -0.5, 0.0, -- left 0.0, -0.5, 0.0, -- right -0.45, 0.5, 0.0, -- top } local second_triangle = { 0.0, -0.5, 0.0, -- left 0.9, -0.5, 0.0, -- right 0.45, 0.5, 0.0 -- top } local vao = {gl.gen_vertex_arrays(2)} local vbo = {gl.gen_buffers(2)} -- first triangle setup gl.bind_vertex_array(vao[1]) gl.bind_buffer('array', vbo[1]) gl.buffer_data('array', gl.pack('float', first_triangle), 'static draw') gl.vertex_attrib_pointer(0, 3, 'float', false, 3*gl.sizeof('float'), 0) gl.enable_vertex_attrib_array(0) gl.unbind_buffer('array') -- gl.unbind_vertex_array() unneeded since we bind to vao[2] just after: -- second triangle setup gl.bind_vertex_array(vao[2]) gl.bind_buffer('array', vbo[2]) gl.buffer_data('array', gl.pack('float', second_triangle), 'static draw') gl.vertex_attrib_pointer(0, 3, 'float', false, 3*gl.sizeof('float'), 0) gl.enable_vertex_attrib_array(0) gl.unbind_buffer('array') gl.unbind_vertex_array() -- To draw in wireframe polygons, run the script with the '-w' option as firts arg: if arg[1]=='-w' then gl.polygon_mode('front and back', 'line') end -- render loop while not glfw.window_should_close(window) do -- process input if glfw.get_key(window, 'escape') == 'press' then glfw.set_window_should_close(window, true) end -- render gl.clear_color(0.2, 0.3, 0.3, 1.0) gl.clear('color') -- draw first triangle using the data from the first VAO gl.use_program(prog1) gl.bind_vertex_array(vao[1]) gl.draw_arrays('triangles', 0, 3) -- then we draw the second triangle using the data from the second VAO -- and a different shader program gl.use_program(prog2) gl.bind_vertex_array(vao[2]) gl.draw_arrays('triangles', 0, 3) gl.unbind_vertex_array() -- swap buffers and poll IO events glfw.swap_buffers(window) glfw.poll_events() end -- optional: de-allocate all resources once they've outlived their purpose: gl.delete_vertex_arrays(vao[1], vao[2]) gl.delete_buffers(vbo[1], vbo[2]) gl.delete_program(prog1) gl.delete_program(prog2)
CorelliaCoronetScreenPlay = CityScreenPlay:new { numberOfActs = 1, screenplayName = "CorelliaCoronetScreenPlay", planet = "corellia", gcwMobs = { {"stormtrooper_sniper", "rebel_master_sergeant", -501.3, 28, -4644.5, -2, 0, "", ""}, {"stormtrooper_squad_leader", "rebel_surface_marshall", -502.1, 28, -4701.1, 185.005, 0, "", ""}, {"command_security_guard", "rebel_specforce_pathfinder", -175.887, 28, -4765.95, 86.2823, 0, "npc_imperial", "conversation"}, {"dark_trooper", "specforce_heavy_weapons_specialist", -574.2, 28, -4247, 333.01, 0, "", ""}, {"dark_trooper", "specforce_heavy_weapons_specialist", -303.8, 28, -4144.4, 304.009, 0, "", ""}, {"dark_trooper", "specforce_heavy_weapons_specialist", 111.5, 28, -4464.9, 26.0008, 0, "", ""}, {"dark_trooper", "specforce_heavy_weapons_specialist", 141.3, 28, -4540.1, 138, 0, "npc_imperial", "neutral"}, {"dark_trooper", "specforce_heavy_weapons_specialist", -76.6, 28.5179, -4625.3, 215.006, 0, "", ""}, {"dark_trooper", "specforce_heavy_weapons_specialist", -124.2, 28, -4798.7, 116, 0, "", ""}, {"elite_sand_trooper", "specforce_infiltrator", -2.3, 28, -4512.6, 91, 0, "npc_imperial", "neutral"}, {"dark_trooper", "specforce_heavy_weapons_specialist", -458, 28, -4590.8, 262.008, 0, "", ""}, {"dark_trooper", "specforce_heavy_weapons_specialist", -175.3, 28, -4837.9, -179, 0, "npc_imperial", "neutral"}, {"imperial_army_captain", "specforce_major", -157.7, 28, -4832.6, -130, 0, "npc_imperial", "neutral"}, {"imperial_army_captain", "specforce_major", -177.7, 28, -4766.5, 86, 0, "npc_imperial", "neutral"}, {"imperial_colonel", "rebel_general", 158.9, 28, -4707.2, 137.004, 0, "", ""}, {"imperial_corporal", "specforce_marine", -289.2, 28, -4416.3, -94, 0, "", ""}, {"imperial_first_lieutenant", "specforce_lieutenant", -336.602, 28, -4791.97, 283.938, 0, "npc_imperial", "neutral"}, {"imperial_first_lieutenant", "specforce_lieutenant", -206.6, 28, -4063.8, 0, 0, "npc_imperial", "neutral"}, {"imperial_medic", "rebel_medic", -439.1, 28, -4144.4, 335.01, 0, "npc_imperial", "neutral"}, {"imperial_medic", "rebel_medic", -561.9, 28, -4234.3, -54, 0, "npc_imperial", "neutral"}, {"imperial_warrant_officer_ii", "specforce_master_sergeant", -404.7, 28, -4430.7, -45, 0, "", ""}, {"imperial_warrant_officer_ii", "specforce_master_sergeant", -541.2, 28, -4628.5, 176, 0, "npc_imperial", "neutral"}, {"scout_trooper", "specforce_marine", -593.7, 28, -4322, -98, 0, "", ""}, {"scout_trooper", "specforce_marine", -547.3, 28, -4668.3, 151, 0, "", ""}, {"scout_trooper", "specforce_marine", 141, 28, -4692.8, 76, 0, "", ""}, {"scout_trooper", "specforce_marine", 100.5, 28, -4668.1, -127, 0, "", ""}, {"scout_trooper", "specforce_marine", -192.6, 28, -4833.5, 134, 0, "", ""}, {"scout_trooper", "specforce_marine", -201.2, 28.6, -4122, 20.0006, 0, "", ""}, {"specialist_noncom", "specforce_technician", -171.8, 28, -4418, -88, 0, "", ""}, {"storm_commando", "specforce_heavy_weapons_specialist", 48.8, 28, -4569.3, 34, 0, "", ""}, {"stormtrooper", "specforce_marine", -557.5, 28, -4230.3, 266.008, 0, "", ""}, {"stormtrooper", "specforce_marine", -517.9, 28, -4213.9, 303.009, 0, "", ""}, {"stormtrooper", "specforce_marine", 19.3, 28, -4366.5, -176, 0, "", ""}, {"stormtrooper", "specforce_marine", -64, 28, -4255.2, 55, 0, "", ""}, {"stormtrooper", "specforce_marine", 96.6, 28, -4394.9, 91.0027, 0, "", ""}, {"stormtrooper", "specforce_marine", 168.1, 28, -4698.4, 145.004, 0, "", ""}, {"stormtrooper", "specforce_marine", -306.7, 28, -4785.9, 187.006, 0, "", ""}, {"stormtrooper", "specforce_marine", -446.5, 28, -4744, 226.007, 0, "", ""}, {"stormtrooper", "specforce_marine", -526.1, 28, -4675.8, 252.007, 0, "", ""}, {"stormtrooper", "specforce_marine", -593.7, 28, -4502.9, 272.008, 0, "", ""}, {"stormtrooper", "specforce_marine", -462.4, 28, -4569.3, 178, 0, "", ""}, {"stormtrooper", "specforce_marine", -42.2, 28, -4500.6, 44.0013, 0, "", ""}, {"stormtrooper", "specforce_marine", -35.4, 28.5179, -4573.8, 49.0014, 0, "", ""}, {"stormtrooper", "specforce_marine", -249.8, 28, -4412.7, 96, 0, "", ""}, {"stormtrooper", "specforce_marine", -215.7, 29.185, -4509.8, 1.00017, 0, "", ""}, {"stormtrooper", "specforce_marine", -204.7, 29.185, -4509.8, 1.00017, 0, "", ""}, {"stormtrooper", "specforce_marine", -569.2, 28, -4242.5, -43, 0, "npc_imperial", "neutral"}, {"stormtrooper", "specforce_marine", -276.7, 28, -4535.2, 230.415, 0, "", ""}, {"stormtrooper", "specforce_marine", -148.6, 28, -4660.7, 202.006, 0, "", ""}, {"stormtrooper", "specforce_marine", -159.2, 28, -4660.7, 161.005, 0, "", ""}, {"stormtrooper", "specforce_marine", -216.9, 28.6, -4121.1, 339.01, 0, "", ""}, {"stormtrooper", "specforce_marine", 110.8, 28, -4496.5, 99, 0, "npc_imperial", "neutral"}, {"stormtrooper", "specforce_marine", 25.8, 28, -4239.9, -6, 0, "npc_imperial", "neutral"}, {"stormtrooper", "specforce_marine", -221.1, 28, -4798.1, 237.007, 0, "", ""}, {"stormtrooper", "specforce_marine", -531.8, 28, -4628.7, -165, 0, "", ""}, {"stormtrooper_bombardier", "specforce_procurement_specialist", -547.026, 28, -4669.14, 331.925, 0, "npc_imperial", "neutral"}, {"stormtrooper_captain", "specforce_major", 19.7, 28, -4282.5, -4, 0, "", ""}, {"stormtrooper_captain", "specforce_major", -338.2, 28, -4791.5, 110, 0, "npc_imperial", "neutral"}, {"stormtrooper_rifleman", "rebel_specforce_urban_guerrilla", -118.7, 28, -4204.6, 16.0005, 0, "", ""}, {"stormtrooper_rifleman", "rebel_specforce_urban_guerrilla", -526.1, 28, -4670.1, 290.009, 0, "", ""}, {"stormtrooper_rifleman", "rebel_specforce_urban_guerrilla", -193.7, 28, -4401.6, -90, 0, "", ""}, {"stormtrooper_rifleman", "rebel_specforce_urban_guerrilla", -316.4, 28.6, -4635.8, 172, 0, "", ""}, {"stormtrooper_rifleman", "rebel_specforce_urban_guerrilla", -223.2, 28, -4078, 9.00022, 0, "", ""}, {"stormtrooper_rifleman", "rebel_specforce_urban_guerrilla", -188.9, 28, -4076.8, 336.01, 0, "", ""}, {"stormtrooper_sniper", "specforce_infiltrator", 96.6, 28, -4407.1, 91.0027, 0, "", ""}, {"stormtrooper_sniper", "specforce_infiltrator", -295.9, 28, -4786.4, 194.006, 0, "", ""}, {"stormtrooper_sniper", "specforce_infiltrator", -593.7, 28, -4483.1, 270.008, 0, "", ""}, {"stormtrooper_sniper", "specforce_infiltrator", -59.1, 28, -4260.1, 47.0014, 0, "", ""}, {"stormtrooper_sniper", "specforce_infiltrator", -275.4, 28, -4614.6, 256.27, 0, "", ""}, {"stormtrooper_sniper", "specforce_infiltrator", -533.523, 28, -4632.07, 270.284, 0, "npc_imperial", "neutral"}, {"stormtrooper_squad_leader", "specforce_wilderness_operative", -226.3, 28, -4378.4, 90, 0, "", ""}, {"stormtrooper_squad_leader", "specforce_wilderness_operative", -12.4, 28.6, -4404.7, 181.005, 0, "", ""}, {"stormtrooper_squad_leader", "specforce_wilderness_operative", -175.938, 28, -4767.14, 86.307, 0, "npc_imperial", "conversation"}, {"corsec_agent", "corsec_agent", -671.712,6.15933,-4169.03,37.6923,0, "", ""}, {"corsec_detective", "corsec_detective", -526.1,28,-4702,-41,0, "", ""}, {"corsec_master_sergeant", "corsec_master_sergeant", -172.8,28,-4167.1,0,0, "", ""}, {"corsec_trooper", "corsec_trooper", -662.805,9.26289,-4182.05,196.426,0, "", ""}, {"corsec_detective", "corsec_detective", -672.123,5.60327,-4164.83,340.354,0, "", ""}, {"corsec_agent", "corsec_agent", -240.2,28,-4450.9,94,0, "", ""}, {"corsec_cadet", "corsec_cadet", -172.8,28.0929,-4165.5,179,0, "", ""}, {"corsec_captain", "corsec_captain", -528.144,28,-4699.89,132.784,0, "", ""}, {"corsec_chief", "corsec_chief", 0.3,28,-4464.5,-87,0, "", ""}, {"corsec_trooper", "corsec_trooper", -1.67932,28,-4464.42,93.3597,0, "", ""}, {"corsec_trooper", "corsec_trooper", -60,28.5,-4597.2,-96,0, "", ""}, {"corsec_trooper", "corsec_trooper", -344.9,28,-4444.3,-48,0, "", ""}, {"corsec_trooper", "corsec_trooper", -347.5,28,-4442.6,123,0, "", ""}, }, } registerScreenPlay("CorelliaCoronetScreenPlay", true) function CorelliaCoronetScreenPlay:start() if (isZoneEnabled(self.planet)) then self:spawnMobiles() self:spawnSceneObjects() self:spawnGcwMobiles() end end function CorelliaCoronetScreenPlay:spawnSceneObjects() --outside starport spawnSceneObject(self.planet, "object/tangible/crafting/station/public_space_station.iff", -178.575, 28, -4689.35, 0, math.rad(180) ) end function CorelliaCoronetScreenPlay:spawnMobiles() --Starport local pNpc = spawnMobile(self.planet, "info_broker",60,8.5,0.6,74.4,-77,1855672) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "noble",60,56.669,-0.521137,33.7689,180.017,1855678) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "contractor",300,37.163,0.639417,40.7061,180.01,1855678) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "mercenary",60,-4.61669,0.639424,67.8263,180.012,1855675) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "bounty_hunter",300,8.65132,0.639421,75.5483,256.69,1855672) self:setMoodString(pNpc, "calm") pNpc = spawnMobile(self.planet, "businessman",60,37.163,0.639417,39.6061,0,1855678) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "scientist",60,56.669,-0.521137,32.6689,360.011,1855678) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "shadowy_figure",60,-4.61669,0.639424,66.7263,0,1855675) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "farmer",60,-62.7673,2.63942,40.6604,360.011,1855683) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "mercenary",300,-62.7673,2.63942,41.7604,179.995,1855683) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "trainer_shipwright",60,-0.1,0.6,67.1,-179,1855675) self:setMoodString(pNpc, "neutral") --Guild Hall -275 -4700 pNpc = spawnMobile(self.planet, "sullustan_male",300,-9.42234,1.75,-18.7259,180.005,1855484) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "chiss_male",300,-10.5223,1.75,-18.7259,134.999,1855484) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "farmer",60,-9.42234,1.75,-19.8259,0,1855484) self:setMoodString(pNpc, "conversation") spawnMobile(self.planet, "farmer",60,11.9421,1.75,-18.7404,129.059,1855484) pNpc = spawnMobile(self.planet, "noble",60,11.9421,1.75,-19.8404,0,1855484) self:setMoodString(pNpc, "conversation") spawnMobile(self.planet, "rikkh",60,0.180826,1.75,-21.4842,28.861,1855484) spawnMobile(self.planet, "rhea",60,1.70956,1.75,-14.1406,4.76848,1855483) pNpc = spawnMobile(self.planet, "brawler",60,16.2045,2.25,19.3968,135.003,1855477) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "chiss_female",300,17.3045,2.25,19.3968,180.006,1855477) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "commoner_naboo",60,17.3045,2.25,18.2968,360.011,1855477) self:setMoodString(pNpc, "conversation") --Hotel pNpc = spawnMobile(self.planet, "corellia_times_investigator",60,7.44572,1.00001,-8.00652,0,1855548) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "agriculturalist",300,7.44572,1.00001,-6.90652,179.997,1855548) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "artisan",60,17.2826,1.28309,-11.8404,179.994,1855549) self:setMoodString(pNpc, "nervous") pNpc = spawnMobile(self.planet, "farmer_rancher",300,24.3471,1.28309,10.0336,180.007,1855549) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "entertainer",300,24.3471,1.28309,8.93357,360.011,1855549) self:setMoodString(pNpc, "conversation") --Cantina spawnMobile(self.planet, "bartender",60,7.60649,-0.894992,1.42464,324.005,8105496) pNpc = spawnMobile(self.planet, "bounty_hunter",300,3.61201,-0.894992,-8.73417,135.006,8105496) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "info_broker",300,2.80432,-0.894991,10.6543,180.012,8105496) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "businessman",60,-7.91375,-0.894992,-4.88587,179.995,8105496) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "corellia_times_reporter",300,-7.91375,-0.894992,-5.88587,0,8105496) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "ithorian_male",300,4.71201,-0.894992,-8.73417,180.01,8105496) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "entertainer",60,2.80432,-0.894991,9.55434,360.011,8105496) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "farmer_rancher",60,4.71201,-0.894992,-9.83418,360.011,8105496) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "mercenary",60,-5.02826,-0.894991,-21.3375,60.6357,8105501) self:setMoodString(pNpc, "calm") spawnMobile(self.planet, "businessman",60,0.978477,-0.894992,21.4841,311.517,8105500) spawnMobile(self.planet, "rebel_recruiter",60,-28.3633,-0.894984,0.335875,171.796,8105504) --Guild Hall -243 -4389 spawnMobile(self.planet, "trainer_brawler",0,-11,1.13306,-14,0,1855508) spawnMobile(self.planet, "trainer_marksman",0,0,1.13306,-14,0,1855507) spawnMobile(self.planet, "trainer_scout",0,-12,1.13306,5.5,180,1855505) spawnMobile(self.planet, "junk_dealer", 0, -14.5, 1.1, 3.0, 98, 1855505) --Guild Hall -177 -4390 spawnMobile(self.planet, "trainer_artisan",0,0,1.13306,-14,0,1855517) --Med Center spawnMobile(self.planet, "surgical_droid_21b",60,-25.52,0.26,-3.48,357.849,1855535) spawnMobile(self.planet, "trainer_combatmedic",0,26.676,0.26,5.41823,85,1855531) spawnMobile(self.planet, "trainer_doctor",0,-25.2731,0.26,-5,13,1855535) spawnMobile(self.planet, "trainer_medic",0,-17.7359,0.26,-0.58142,137,1855535) spawnMobile(self.planet, "trainer_medic",0,14.2688,0.26,4.66124,159,1855531) --3rd floor pNpc = spawnMobile(self.planet, "corellia_times_investigator",60,21.5803,14.26,-8.84205,360.011,1855541) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "artisan",60,21.5803,14.26,-7.84205,180.006,1855541) self:setMoodString(pNpc, "conversation") --Guild Hall 24 -4400 spawnMobile(self.planet, "trainer_architect",0,11,1.13306,-14,0,1855526) spawnMobile(self.planet, "trainer_armorsmith",0,-12,1.1,5,180,1855525) spawnMobile(self.planet, "trainer_droidengineer",0,-11,1.13306,-14,0,1855528) spawnMobile(self.planet, "trainer_merchant",0,12.1,1.1,5.8,177,1855524) spawnMobile(self.planet, "trainer_weaponsmith",0,-2.5,1.13306,-8.4,91,1855527) --Capitol pNpc = spawnMobile(self.planet, "noble",60,5.22842,0.3,2.91677,0,1855463) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "info_broker",60,5.22842,0.3,4.01677,180.005,1855463) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "corellia_times_reporter",60,5.43518,2.27819,-27.0615,344.925,1855463) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "brawler",60,16.2045,2.25,19.3968,135.003,1855477) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "brawler",60,-1.72746,7.9,-32.175,0,1855463) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "comm_operator",300,-0.332123,0.3,-2.90219,134.998,1855463) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "entertainer",60,0.767877,0.3,-2.90219,180.005,1855463) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "farmer",60,-18.6014,1.30259,-11.3146,360.011,1855463) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "farmer",60,0.767877,0.3,-4.00219,0,1855463) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "medic",60,-0.332123,0.3,-4.00219,45.0054,1855463) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "medic",60,5.18395,2.27819,-26.1292,164.924,1855463) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "noble",60,4.12842,0.3,4.01677,134.998,1855463) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "scientist",60,-1.72746,7.9,-31.075,180.005,1855463) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "mercenary",60,-18.6014,1.30292,-10.2146,180.006,1855463) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "commoner_technician",300,-20.2743,3.22324,22.781,180.005,1855468) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "farmer",60,-20.2743,3.22324,21.681,0,1855468) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "info_broker",60,21.8079,3.22324,26.617,180.006,1855469) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "artisan",300,21.8079,3.22324,25.517,360.011,1855469) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "farmer",60,37.1168,1.29422,-4.41488,0,1855470) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "businessman",60,37.1168,1.29422,-3.41488,180.005,1855470) self:setMoodString(pNpc, "conversation") --Guild Hall/Theater -207 -4133 pNpc = spawnMobile(self.planet, "commoner_old",300,3.66172,0.6,-2.64185,180.005,2365392) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "commoner",60,2.56172,0.6,-2.64185,135,2365392) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "farmer",60,1.5,2.6,1.7,-90,2365397) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "businessman",60,-6.12488,2.6,13.0431,0,2365397) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "corellia_times_investigator",300,0.3,2.6,1.8,90,2365397) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "commoner_naboo",60,-6.12488,2.6,14.1431,180.005,2365397) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "farmer",60,-25.0,0.6,9.3,-6,2365393) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "info_broker",60,-24.5,0.6,10.4,-79,2365393) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "scientist",60,-7.22488,2.6,14.1431,135.008,2365397) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "twilek_slave",60,-25.4,0.6,10.6,130,2365393) self:setMoodString(pNpc, "conversation") spawnMobile(self.planet, "noble",60,28.93,2.12878,58.19,222.007,2365398) spawnMobile(self.planet, "noble",60,19.26,2.12847,56.13,266.008,2365399) pNpc = spawnMobile(self.planet, "twilek_slave",60,26.5189,2.12846,71.9319,0,2365399) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile(self.planet, "contractor",60,26.5189,2.12858,73.0319,180.005,2365399) self:setMoodString(pNpc, "conversation") spawnMobile(self.planet, "trainer_dancer",0,18.5885,2.12869,53.9366,0,2365399) spawnMobile(self.planet, "trainer_musician",0,21.7,2.1,75.9,180,2365399) spawnMobile(self.planet, "theater_manager",0,21.8947,2.12814,63.5,0,2365399) pNpc = spawnMobile(self.planet, "farmer_rancher",60,-20.3488,2.12878,65.9854,180.006,2365400) self:setMoodString(pNpc, "conversation") spawnMobile(self.planet, "trainer_imagedesigner",0,-21.4483,2.12878,74.4461,185,2365400) --Outside Misc spawnMobile(self.planet, "businessman",60,-306.34,28,-4620.82,67.4368,0) spawnMobile(self.planet, "businessman",60,-312.404,28,-4646.51,242.881,0) spawnMobile(self.planet, "businessman",60,-135.995,28,-4745.63,251.824,0) spawnMobile(self.planet, "commoner",60,-306.539,28,-4546.52,95.6639,0) spawnMobile(self.planet, "commoner",60,-306.061,28,-4600.68,146.312,0) spawnMobile(self.planet, "commoner",60,-258.479,28,-4620,198.098,0) spawnMobile(self.planet, "commoner",60,-350.892,28,-4219.92,244.079,0) spawnMobile(self.planet, "commoner",60,-357.932,28,-4267.81,39.6745,0) spawnMobile(self.planet, "commoner",60,-350.452,28,-4287.73,88.2402,0) spawnMobile(self.planet, "commoner",60,-350.998,28,-4250.76,129.539,0) spawnMobile(self.planet, "commoner",60,-302.182,28,-4300.76,29.3627,0) spawnMobile(self.planet, "commoner",60,-282.189,28,-4343.57,319.557,0) spawnMobile(self.planet, "commoner",60,-239.932,28,-4522.15,78.2005,0) spawnMobile(self.planet, "commoner",60,-163.792,28,-4606.3,8.06951,0) spawnMobile(self.planet, "commoner",60,-163.751,28,-4552.14,55.4278,0) spawnMobile(self.planet, "commoner",60,-168.38,28,-4515.61,103.857,0) spawnMobile(self.planet, "commoner",60,-158.666,28,-4526.31,289.183,0) spawnMobile(self.planet, "commoner",60,-106.79,28,-4528.6,277.086,0) spawnMobile(self.planet, "commoner",60,-26.0533,28,-4558.43,310.059,0) spawnMobile(self.planet, "commoner",60,-54.9984,28,-4530.84,320.833,0) spawnMobile(self.planet, "commoner",60,-37.2537,28,-4476.76,289.212,0) spawnMobile(self.planet, "commoner",60,-92.217,28,-4471.14,34.4098,0) spawnMobile(self.planet, "commoner",60,-14.9281,28,-4451.64,343.833,0) spawnMobile(self.planet, "commoner",60,40.5453,28,-4416.63,80.7447,0) spawnMobile(self.planet, "commoner",60,14.4606,28,-4407.11,38.4825,0) spawnMobile(self.planet, "commoner",60,-15.4515,28,-4415.25,54.8457,0) spawnMobile(self.planet, "commoner",60,-64.8198,28,-4398.56,247.888,0) spawnMobile(self.planet, "commoner",60,-78.7157,28,-4286.4,22.2156,0) spawnMobile(self.planet, "commoner",60,-71.0095,28,-4325.21,60.8559,0) spawnMobile(self.planet, "commoner",60,-87.6481,28,-4302.16,97.3912,0) spawnMobile(self.planet, "commoner",60,-112.646,28,-4310.7,151.383,0) spawnMobile(self.planet, "commoner",60,-118.993,28,-4285.29,181.854,0) spawnMobile(self.planet, "commoner",60,-54.3716,28,-4304.72,97.2405,0) spawnMobile(self.planet, "commoner",60,-56.7639,28,-4229.33,47.6277,0) spawnMobile(self.planet, "commoner",60,-103.047,28,-4182.61,84.8143,0) spawnMobile(self.planet, "commoner",60,-163.872,28,-4181.48,294.873,0) spawnMobile(self.planet, "commoner",60,-122.156,28,-4392.8,270.52,0) spawnMobile(self.planet, "commoner",60,-195.909,28,-4451.7,186.379,0) spawnMobile(self.planet, "commoner",60,-181.008,28,-4505.08,109.502,0) spawnMobile(self.planet, "commoner",60,71.9271,28,-4568.97,267.444,0) spawnMobile(self.planet, "commoner",60,10.3286,28,-4633.8,159.984,0) spawnMobile(self.planet, "commoner",60,88.4953,28,-4727.94,340.398,0) spawnMobile(self.planet, "commoner",60,55.6269,28,-4782.24,123.611,0) spawnMobile(self.planet, "commoner",60,101.283,28,-4554.86,358.797,0) pNpc = spawnMobile(self.planet, "commoner", 60, -51.7918, 28, -4662.65, 360.011, 0) self:setMoodString(pNpc, "calm") self:setCustomName(pNpc, "Hunter Javeezo") --More Misc spawnMobile(self.planet, "gadget_specialist",60,19.7425,28,-4775.49,27.4957,0) spawnMobile(self.planet, "informant_npc_lvl_1",0,-33,28,-4825,45,0) spawnMobile(self.planet, "informant_npc_lvl_1",0,-86,28,-4829,0,0) spawnMobile(self.planet, "informant_npc_lvl_1",0,-172,28,-4442,270,0) spawnMobile(self.planet, "informant_npc_lvl_1",0,-172,28,-4410,225,0) spawnMobile(self.planet, "informant_npc_lvl_1",0,-212,28,-4465,0,0) spawnMobile(self.planet, "informant_npc_lvl_1",0,-250,28,-4430,90,0) spawnMobile(self.planet, "informant_npc_lvl_1",0,-428,28,-4751,225,0) spawnMobile(self.planet, "informant_npc_lvl_1",0,-477,28,-4553,180,0) spawnMobile(self.planet, "informant_npc_lvl_1",0,-566,28,-4361,90,0) spawnMobile(self.planet, "informant_npc_lvl_1",0,-508,28,-4367,45,0) spawnMobile(self.planet, "informant_npc_lvl_1",0,-359,28,-4210,270,0) spawnMobile(self.planet, "informant_npc_lvl_1",0,-293,28,-4251,315,0) spawnMobile(self.planet, "informant_npc_lvl_1",0,-184,28,-4342,90,0) spawnMobile(self.planet, "io_tsomcren",60,-140.701,28,-4719.16,44.0418,0) spawnMobile(self.planet, "junk_dealer", 0, -118.06, 28, -4791.91, -120, 0) pNpc = spawnMobile(self.planet, "junk_dealer", 0, -189.62, 28, -4371.06, 0, 0) if pNpc ~= nil then AiAgent(pNpc):setConvoTemplate("junkDealerFineryConvoTemplate") end pNpc = spawnMobile(self.planet, "junk_dealer", 0, -28.7, -0.9, 20.8, 95, 8105505) if pNpc ~= nil then AiAgent(pNpc):setConvoTemplate("junkDealerArmsConvoTemplate") end --Meatlump's outside spawnMobile(self.planet, "meatlump_buffoon",300,-145,28.9,-4959.8,63,0) spawnMobile(self.planet, "meatlump_buffoon",300,-54.3,28.2,-4963.4,-90,0) spawnMobile(self.planet, "meatlump_buffoon",300,-20.1,28,-4922.2,109,0) spawnMobile(self.planet, "meatlump_buffoon",300,266.9,28.5,-4656.5,-109,0) spawnMobile(self.planet, "meatlump_buffoon",300,284.5,29,-4541.7,-175,0) spawnMobile(self.planet, "meatlump_buffoon",300,258.2,28,-4424.1,-5,0) spawnMobile(self.planet, "meatlump_buffoon",300,-365.3,28,-4658.5,26,0) spawnMobile(self.planet, "meatlump_buffoon",300,-270.1,28,-4923,-97,0) spawnMobile(self.planet, "meatlump_clod",300,-130.2,31.1,-4993.8,72,0) spawnMobile(self.planet, "meatlump_clod",300,-11.4,28,-4920.5,63,0) spawnMobile(self.planet, "meatlump_clod",300,93.4,27.1,-4865,60,0) spawnMobile(self.planet, "meatlump_cretin",300,-89.4,30.3,-4985.2,33,0) spawnMobile(self.planet, "meatlump_cretin",300,188.1,27.1,-4770.2,-99,0) spawnMobile(self.planet, "meatlump_cretin",300,287.1,29.3,-4558,-95,0) spawnMobile(self.planet, "meatlump_cretin",300,-236.2,28.4,-4947.9,-16,0) spawnMobile(self.planet, "meatlump_fool",300,172.6,27.9,-4773,-87,0) spawnMobile(self.planet, "meatlump_fool",300,277.9,28.6,-4545.9,-99,0) spawnMobile(self.planet, "meatlump_fool",300,266.6,28,-4408.9,68,0) spawnMobile(self.planet, "meatlump_fool",300,-361.8,28,-4655,164,0) spawnMobile(self.planet, "meatlump_fool",300,-297.3,28,-4918.8,-86,0) spawnMobile(self.planet, "meatlump_fool",300,-257,30,-4968.4,24,0) spawnMobile(self.planet, "meatlump_loon",300,-163,28.2,-49493,102,0) spawnMobile(self.planet, "meatlump_loon",300,176,27.3,-4763.6,-7,0) spawnMobile(self.planet, "meatlump_oaf",300,-136,28.8,-4958.5,83,0) spawnMobile(self.planet, "meatlump_oaf",300,-72,28,-4973.1,-77,0) spawnMobile(self.planet, "meatlump_oaf",300,97.6,26.6,-4867.1,101,0) spawnMobile(self.planet, "meatlump_oaf",300,255,28.3,-4666.8,-51,0) spawnMobile(self.planet, "meatlump_oaf",300,249.6,28,-4418.9,92,0) spawnMobile(self.planet, "meatlump_oaf",300,-366,28,-4655,148,0) spawnMobile(self.planet, "meatlump_oaf",300,-308,28,-4897.9,64,0) spawnMobile(self.planet, "meatlump_stooge",300,-133.5,28.2,-4946,72,0) spawnMobile(self.planet, "meatlump_stooge",300,-12.6,27.9,-4931.6,-19,0) spawnMobile(self.planet, "meatlump_stooge",300,90.7,26.6,-4872.1,73,0) spawnMobile(self.planet, "meatlump_stooge",300,252.9,28.3,-4657.7,-3,0) spawnMobile(self.planet, "meatlump_stooge",300,293.9,29.7,-4552.4,-93,0) --Misc pNpc = spawnMobile(self.planet, "r3",60,-149.754,28,-4785.34,297.928,0) self:setMoodString(pNpc, "calm") pNpc = spawnMobile(self.planet, "r3",60,-182.479,28,-4731.42,293.019,0) self:setMoodString(pNpc, "calm") --Ragtag's outside spawnMobile(self.planet, "ragtag_kook",300,-217.315,28,-4927.23,40.3799,0) spawnMobile(self.planet, "ragtag_kook",300,-213.219,28,-4926.08,204.867,0) spawnMobile(self.planet, "ragtag_kook",300,-225.238,28,-4931.01,254.658,0) spawnMobile(self.planet, "ragtag_kook",300,-212.993,28,-4922.77,38.0909,0) spawnMobile(self.planet, "ragtag_kook",300,-712.063,5.13106,-4304.96,315.72,0) spawnMobile(self.planet, "ragtag_kook",300,-719.18,4.19027,-4309.55,164.033,0) spawnMobile(self.planet, "ragtag_kook",300,-703.067,2.97988,-4657.98,93.9451,0) spawnMobile(self.planet, "ragtag_kook",300,-711.002,2.29761,-4657.71,82.4599,0) spawnMobile(self.planet, "ragtag_loon",300,-396.754,28,-4869.82,8.29735,0) spawnMobile(self.planet, "ragtag_loon",300,-397.655,28,-4875.17,8.04579,0) spawnMobile(self.planet, "ragtag_loon",300,227.709,28,-4494.78,296.837,0) spawnMobile(self.planet, "ragtag_loon",300,229.296,28,-4484.62,54.5993,0) spawnMobile(self.planet, "ragtag_loon",300,234.249,28,-4490.03,258.204,0) spawnMobile(self.planet, "ragtag_loon",300,227.363,28,-4490.61,140.577,0) spawnMobile(self.planet, "ragtag_loon",300,177.412,28,-4413.68,227.101,0) spawnMobile(self.planet, "ragtag_loon",300,177.412,28,-4411.68,159.855,0) spawnMobile(self.planet, "ragtag_loon",300,-205.027,28.3091,-3998.32,80.3182,0) spawnMobile(self.planet, "ragtag_loon",300,-208.5,29.2,-3999.9,191.197,0) spawnMobile(self.planet, "ragtag_loon",300,-205.027,29.2182,-4001.32,192.016,0) spawnMobile(self.planet, "ragtag_loon",300,-201.8,28.6,-4000.2,-122,0) spawnMobile(self.planet, "ragtag_loon",300,-525.124,5.82557,-4079.84,207.519,0) spawnMobile(self.planet, "ragtag_loon",300,-534.124,6.67109,-4078.84,149.496,0) spawnMobile(self.planet, "ragtag_maniac",300,-691.483,7.08209,-4227.75,29.5129,0) spawnMobile(self.planet, "ral_mundi",60,-138.975,28,-4718.86,10.0036,0) spawnMobile(self.planet, "tarth_jaxx",60,-137.464,28,-4718.83,342.825,0) --Trainers Outside spawnMobile(self.planet, "trainer_architect",0,-161,28,-4698,-95,0) spawnMobile(self.planet, "trainer_artisan",0,-187,28,-4700,92,0) spawnMobile(self.planet, "trainer_bioengineer",0,-424.092,28,-4651.85,94,0) spawnMobile(self.planet, "trainer_brawler",0,-164,28,-4754,88,0) spawnMobile(self.planet, "trainer_combatmedic",0,-33.9759,28,-4435.08,95,0) spawnMobile(self.planet, "trainer_creaturehandler",0,-55,28,-4566,0,0) spawnMobile(self.planet, "trainer_entertainer",0,-173,28,-4739,0,0) spawnMobile(self.planet, "trainer_entertainer",0,-228,28.6,-4118,0,0) spawnMobile(self.planet, "trainer_marksman",0,-165,28,-4746,92,0) spawnMobile(self.planet, "trainer_marksman",0,-35,28,-4372,269,0) spawnMobile(self.planet, "trainer_medic",0,-33,28,-4422,72,0) spawnMobile(self.planet, "trainer_medic",0,-172,28,-4691,0,0) spawnMobile(self.planet, "trainer_merchant",0,-369,28,-4533,92,0) spawnMobile(self.planet, "trainer_politician",0,-218,28,-4500,0,0) spawnMobile(self.planet, "trainer_ranger",0,-505,28,-4633,180,0) spawnMobile(self.planet, "trainer_scout",0,-169.45,28,-4712.58,134,0) spawnMobile(self.planet, "trainer_spy",0,-133.999,28,-4716.53,270,0) spawnMobile(self.planet, "trainer_meleebountyhunter",0,-133.812,28,-4715.22,276,0) -- Chassis dealer. spawnMobile(self.planet, "chassis_dealer", 0, 0.1, 0.6, 72.9, -4, 1855672) -- Fallen Players spawnMobile(self.planet, "geistvater_ghost", 0, -159.986, 28, -4724.06, 90, 0) spawnMobile(self.planet, "rizz_ghost", 0, -159.986, 28, -4727.92, 90, 0) spawnMobile(self.planet, "heat_ghost", 0, -159.986, 28, -4719.8, 90, 0) spawnMobile(self.planet, "thornes", 1, -159.902, 28, -4715.79, 73, 0) end
----------------------------------- -- Ability: Retaliation -- Allows you to counterattack but reduces movement speed. -- Obtained: Warrior Level 60 -- Recast Time: 00:03:00 -- Duration: 00:03:00 ----------------------------------- require("scripts/globals/status") ----------------------------------- function onAbilityCheck(player,target,ability) return 0,0 end function onUseAbility(player, target, ability) player:addStatusEffect(tpz.effect.RETALIATION, 1, 0, 180) end
--Generated By protoc-gen-lua Do not Edit local protobuf = require "protobuf.protobuf" module('Protol.common_pb') HEADER = protobuf.Descriptor(); HEADER_CMD_FIELD = protobuf.FieldDescriptor(); HEADER_SEQ_FIELD = protobuf.FieldDescriptor(); HEADER_CMD_FIELD.name = "cmd" HEADER_CMD_FIELD.full_name = ".Header.cmd" HEADER_CMD_FIELD.number = 1 HEADER_CMD_FIELD.index = 0 HEADER_CMD_FIELD.label = 2 HEADER_CMD_FIELD.has_default_value = false HEADER_CMD_FIELD.default_value = 0 HEADER_CMD_FIELD.type = 3 HEADER_CMD_FIELD.cpp_type = 2 HEADER_SEQ_FIELD.name = "seq" HEADER_SEQ_FIELD.full_name = ".Header.seq" HEADER_SEQ_FIELD.number = 2 HEADER_SEQ_FIELD.index = 1 HEADER_SEQ_FIELD.label = 2 HEADER_SEQ_FIELD.has_default_value = false HEADER_SEQ_FIELD.default_value = 0 HEADER_SEQ_FIELD.type = 5 HEADER_SEQ_FIELD.cpp_type = 1 HEADER.name = "Header" HEADER.full_name = ".Header" HEADER.nested_types = {} HEADER.enum_types = {} HEADER.fields = {HEADER_CMD_FIELD, HEADER_SEQ_FIELD} HEADER.is_extendable = false HEADER.extensions = {} Header = protobuf.Message(HEADER)
object_static_worldbuilding_terminal_floor_travel_01 = object_static_worldbuilding_terminal_shared_floor_travel_01:new { } ObjectTemplates:addTemplate(object_static_worldbuilding_terminal_floor_travel_01, "object/static/worldbuilding/terminal/floor_travel_01.iff")
function onSpeak(player, type, message) local playerAccountType = player:getAccountType() if player:getLevel() == 1 and playerAccountType < ACCOUNT_TYPE_GAMEMASTER then player:sendCancelMessage("You may not speak into channels as long as you are on level 1.") return false end if type == TALKTYPE_CHANNEL_Y then if playerAccountType >= ACCOUNT_TYPE_GAMEMASTER then type = TALKTYPE_CHANNEL_O end elseif type == TALKTYPE_CHANNEL_O then if playerAccountType < ACCOUNT_TYPE_GAMEMASTER then type = TALKTYPE_CHANNEL_Y end elseif type == TALKTYPE_CHANNEL_R1 then if playerAccountType < ACCOUNT_TYPE_GAMEMASTER and not player:hasFlag(PlayerFlag_CanTalkRedChannel) then type = TALKTYPE_CHANNEL_Y end end return type end
-- NetHack 3.7 Wizard.des $NHDT-Date: 1432512783 2015/05/25 00:13:03 $ $NHDT-Branch: master $:$NHDT-Revision: 1.11 $ -- Copyright (c) 1992 by David Cohrs -- NetHack may be freely redistributed. See license for details. -- des.level_init({ style = "solidfill", fg = " " }); des.level_flags("mazelevel"); des.map([[ ------------- ------------- |...........| |...........| -------|...........-------------------...........| |......S...........|..|..|..|..|..|..|...........| |......|...........|..|..|..|..|..|..|...........| |......|...........-F+-F+-F+-F+-F+-F+-...........| --S----|...........S.................+...........| |......|...........-F+-F+-F+-F+-F+-F+-...........| |......|...........|..|..|..|..|..|..|...........| |......|...........|..|..|..|..|..|..|...........| -------|...........-------------------...........| |...........| |...........| ------------- ------------- ]]); -- Dungeon Description des.region({ region={13,10,18,12}, lit=0, type="temple", filled=2 }) des.region(selection.area(13,06,18,08), "lit") des.region(selection.area(20,04,30,14), "unlit") des.region(selection.area(32,06,33,07), "unlit") des.region(selection.area(35,06,36,07), "unlit") des.region(selection.area(38,06,39,07), "unlit") des.region(selection.area(41,06,42,07), "unlit") des.region(selection.area(44,06,45,07), "unlit") des.region(selection.area(47,06,48,07), "unlit") des.region(selection.area(32,09,48,09), "unlit") des.region(selection.area(32,11,33,12), "unlit") des.region(selection.area(35,11,36,12), "unlit") des.region(selection.area(38,11,39,12), "unlit") des.region(selection.area(41,11,42,12), "unlit") des.region(selection.area(44,11,45,12), "unlit") des.region(selection.area(47,11,48,12), "unlit") des.region(selection.area(50,04,60,14), "lit") -- Doors des.door("locked",19,06) des.door("locked",14,09) des.door("locked",31,09) des.door("locked",33,08) des.door("locked",36,08) des.door("locked",39,08) des.door("locked",42,08) des.door("locked",45,08) des.door("locked",48,08) des.door("locked",33,10) des.door("locked",36,10) des.door("locked",39,10) des.door("locked",42,10) des.door("locked",45,10) des.door("locked",48,10) des.door("locked",49,09) -- Stairs des.stair("up", 55,05) -- Non diggable walls des.non_diggable(selection.area(00,00,75,19)) -- The altar. This is not a shrine. des.altar({ coord={16,11}, aligned="noncoaligned", type="altar" }) -- Objects des.object({ id = "amulet of ESP", x=16, y=11, buc="blessed", spe=0, name="The Eye of the Aethiopica" }) des.object() des.object() des.object() des.object() des.object() des.object() des.object() des.object() des.object() des.object() des.object() des.object() des.object() des.object() -- Random traps des.trap() des.trap() des.trap() des.trap() des.trap() des.trap() -- Random monsters. des.monster("Dark One", 16, 11) des.monster({ class = "B",random, peaceful = 0 }) des.monster({ class = "B",random, peaceful = 0 }) des.monster({ class = "B",random, peaceful = 0 }) des.monster({ class = "B",random, peaceful = 0 }) des.monster({ class = "B",random, peaceful = 0 }) des.monster({ class = "B",random, peaceful = 0 }) des.monster({ class = "B",random, peaceful = 0 }) des.monster({ class = "B",random, peaceful = 0 }) des.monster({ class = "B",random, peaceful = 0 }) des.monster({ class = "B",random, peaceful = 0 }) des.monster({ class = "B",random, peaceful = 0 }) des.monster({ class = "i",random, peaceful = 0 }) des.monster({ class = "i",random, peaceful = 0 }) des.monster({ class = "i",random, peaceful = 0 }) des.monster({ class = "i",random, peaceful = 0 }) des.monster({ class = "i",random, peaceful = 0 }) des.monster({ class = "i",random, peaceful = 0 }) des.monster({ class = "i",random, peaceful = 0 }) des.monster("vampire bat") des.monster("vampire bat") des.monster("vampire bat") des.monster("vampire bat") des.monster("vampire bat") des.monster("vampire bat") des.monster("vampire bat") des.monster("vampire bat") des.monster({ class = "i",random, peaceful = 0 }) -- Captive Monsters in the dungeon des.monster({ id = "rogue", x=35, y=06, peaceful=1, name="Pug" }) des.monster({ id = "owlbear", x=47, y=06, peaceful=1, asleep=1 }) des.monster({ id = "wizard", x=32, y=11, peaceful=1, asleep=1, name="Newt" }) des.monster({ id = "Grey-elf", x=44, y=11, peaceful=1 }) des.monster({ id = "hill giant", x=47, y=11, peaceful=1, asleep=1 }) des.monster({ id = "gnomish wizard", x=38, y=06, peaceful=1 }) des.monster({ id = "prisoner", x=35, y=11, peaceful=1 }) des.monster({ id = "prisoner", x=41, y=11, peaceful=1, asleep=1 })
function table.removeByValue(t, value) for i,v in pairs(t) do if v == value then table.remove(t, i) end end end function table.swap(array, index1, index2) array[index1], array[index2] = array[index2], array[index1] end function table.shuffle(array) local counter = #array while counter > 1 do local index = RandomInt(1, counter) table.swap(array, index, counter) counter = counter - 1 end end function table.includes(table, element) if table then for _, value in pairs(table) do if value == element then return true end end end return false end function table.allEqual(table, value) for _,v in pairs(table) do if v ~= value then return false end end return true end function table.iterate(inputTable) local toutput = {} for _,v in pairs(inputTable) do table.insert(toutput, v) end return toutput end function table.iterateKeys(inputTable) local toutput = {} for k,_ in pairs(inputTable) do table.insert(toutput, k) end return toutput end function table.count(inputTable) local counter = 0 for _,_ in pairs(inputTable) do counter = counter + 1 end return counter end function table.merge(input1, input2) for i,v in pairs(input2) do input1[i] = v end return input1 end function table.highest(t) if #t < 1 then return end table.sort(t) return(t[#t]) end function table.add(input1, input2) for _,v in ipairs(input2) do table.insert(input1, v) end end function table.nearest(table, number) local smallestSoFar, smallestIndex for i, y in ipairs(table) do if not smallestSoFar or (math.abs(number-y) < smallestSoFar) then smallestSoFar = math.abs(number-y) smallestIndex = i end end return table[smallestIndex], smallestIndex end function table.nearestOrLowerKey(t, key) if not t then return end local selectedKey for k,v in pairs(t) do if k <= key and (not selectedKey or math.abs(k - key) < math.abs(selectedKey - key)) then selectedKey = k end end return t[selectedKey] end function table.deepmerge(t1, t2) for k,v in pairs(t2) do if type(v) == "table" then if type(t1[k] or false) == "table" then table.deepmerge(t1[k] or {}, t2[k] or {}) else t1[k] = v end else t1[k] = v end end return t1 end function table.deepcopy(obj, seen) if type(obj) ~= 'table' then return obj end if seen and seen[obj] then return seen[obj] end local s = seen or {} local res = setmetatable({}, getmetatable(obj)) s[obj] = res for k, v in pairs(obj) do res[table.deepcopy(k, s)] = table.deepcopy(v, s) end return res end function pairsByKeys(t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 local iter = function() i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end function shuffledPairs(t) local a = {} for n in pairs(t) do table.insert(a, n) end table.shuffle(a) local i = 0 local iter = function() i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end function table.average(t) if #t == 0 then return 0 end local sum = 0 for _,v in pairs(t) do sum = sum + v end return sum/#t end function table.filter(t, predicate) local new = {} for k, v in pairs(t) do if predicate(v, k) then table.insert(new, v) end end return new end function table.filterValues(t, predicate) local new = {} for k, v in pairs(t) do if predicate(v, k) then new[k] = v end end return new end
-- imported modules local color = require 'engine.color' -- module local logger = {} function logger.logItems(items, itemCount) local messages = {} if 1 == itemCount then messages = { { 1, 1, 1, 1 }, 'There is ', color.crimson, items[next(items)].desc.blueprint.name, { 1, 1, 1, 1 }, ' lying there' } else table.insert(messages, color.white) table.insert(messages, 'There are multiple items lying here: ') local skipFirst = true for k, item in pairs(items) do if not skipFirst then table.insert(messages, color.white) table.insert(messages, ', ') end table.insert(messages, color.crimson) table.insert(messages, item.desc.blueprint.name) skipFirst = false end end return messages end return logger
------------------------------------------------------------------------------- -- Mob Framework Mod by Sapier -- -- You may copy, use, modify or do nearly anything except removing this -- copyright notice. -- And of course you are NOT allow to pretend you have written it. -- --! @file init.lua --! @brief animalmaterials --! @copyright Sapier --! @author Sapier --! @date 2013-01-27 -- -- Contact sapier a t gmx net ------------------------------------------------------------------------------- -- Boilerplate to support localized strings if intllib mod is installed. local S if (minetest.get_modpath("intllib")) then dofile(minetest.get_modpath("intllib").."/intllib.lua") S = intllib.Getter(minetest.get_current_modname()) else S = function ( s ) return s end end core.log("action","MOD: animalmaterials loading ...") local version = "0.1.3" animalmaterialsdata = {} --+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ --+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -- Node definitions --+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ --+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ --+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ --+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -- Item definitions --+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ --+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- deamondeath sword -- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- minetest.register_tool("animalmaterials:sword_deamondeath", { description = S("Sword (Deamondeath)"), inventory_image = "default_tool_steelsword.png", tool_capabilities = { full_punch_interval = 0.50, max_drop_level=1, groupcaps={ fleshy={times={[1]=2.00, [2]=0.80, [3]=0.40}, uses=10, maxlevel=1}, snappy={times={[2]=0.70, [3]=0.30}, uses=40, maxlevel=1}, choppy={times={[3]=0.70}, uses=40, maxlevel=0}, deamon={times={[1]=0.25, [2]=0.10, [3]=0.05}, uses=20, maxlevel=3}, } } }) ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- scissors -- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- minetest.register_tool("animalmaterials:scissors", { description = S("Scissors"), inventory_image = "animalmaterials_scissors.png", tool_capabilities = { max_drop_level=0, groupcaps={ wool = {uses=40,maxlevel=1} } }, }) ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- lasso -- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- minetest.register_craftitem("animalmaterials:lasso", { description = S("Lasso"), image = "animalmaterials_lasso.png", stack_max=10, }) ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- net -- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- minetest.register_craftitem("animalmaterials:net", { description = S("Net"), image = "animalmaterials_net.png", stack_max=10, }) ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- saddle -- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- minetest.register_craftitem("animalmaterials:saddle", { description = S("Saddle"), image = "animalmaterials_saddle.png", stack_max=1 }) ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- contract -- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- minetest.register_craftitem("animalmaterials:contract", { description = S("Contract"), image = "animalmaterials_contract.png", stack_max=10, }) ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- meat -- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- minetest.register_craftitem("animalmaterials:meat_raw", { description = S("Raw meat"), image = "animalmaterials_meat_raw.png", on_use = minetest.item_eat(1), groups = { meat=1, eatable=1 }, stack_max=25 }) minetest.register_craftitem("animalmaterials:meat_pork", { description = S("Pork (raw)"), image = "animalmaterials_meat_raw.png", on_use = minetest.item_eat(1), groups = { meat=1, eatable=1 }, stack_max=25 }) minetest.register_craftitem("animalmaterials:meat_beef", { description = S("Beef (raw)"), image = "animalmaterials_meat_raw.png", on_use = minetest.item_eat(1), groups = { meat=1, eatable=1 }, stack_max=25 }) minetest.register_craftitem("animalmaterials:meat_chicken", { description = S("Chicken (raw)"), image = "animalmaterials_meat_raw.png", on_use = minetest.item_eat(1), groups = { meat=1, eatable=1 }, stack_max=25 }) minetest.register_craftitem("animalmaterials:meat_lamb", { description = S("Lamb (raw)"), image = "animalmaterials_meat_raw.png", on_use = minetest.item_eat(1), groups = { meat=1, eatable=1 }, stack_max=25 }) minetest.register_craftitem("animalmaterials:meat_venison", { description = S("Venison (raw)"), image = "animalmaterials_meat_raw.png", on_use = minetest.item_eat(1), groups = { meat=1, eatable=1 }, stack_max=25 }) minetest.register_craftitem("animalmaterials:meat_undead", { description = S("Meat (not quite dead)"), image = "animalmaterials_meat_undead_raw.png", on_use = minetest.item_eat(-2), groups = { meat=1, eatable=1 }, stack_max=5 }) minetest.register_craftitem("animalmaterials:meat_toxic", { description = S("Toxic Meat"), image = "animalmaterials_meat_toxic_raw.png", on_use = minetest.item_eat(-5), groups = { meat=1, eatable=1 }, stack_max=5 }) minetest.register_craftitem("animalmaterials:meat_ostrich", { description = S("Ostrich Meat"), image = "animalmaterials_meat_raw.png", on_use = minetest.item_eat(3), groups = { meat=1, eatable=1 }, stack_max=5 }) minetest.register_craftitem("animalmaterials:pork_raw", { description = S("Pork"), image = "animalmaterials_pork_raw.png", on_use = minetest.item_eat(4), groups = { meat=1, eatable=1 }, stack_max=5 }) minetest.register_craftitem("animalmaterials:fish_bluewhite", { description = S("Fish (bluewhite)"), image = "animalmaterials_meat_raw.png", on_use = minetest.item_eat(1), groups = { meat=1, eatable=1 }, stack_max=25 }) minetest.register_craftitem("animalmaterials:fish_clownfish", { description = S("Fish (clownfish)"), image = "animalmaterials_meat_raw.png", on_use = minetest.item_eat(1), groups = { meat=1, eatable=1 }, stack_max=25 }) ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- feather -- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- minetest.register_craftitem("animalmaterials:feather", { description = S("Feather"), image = "animalmaterials_feather.png", stack_max=25 }) ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- milk -- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- minetest.register_craftitem("animalmaterials:milk", { description = S("Milk"), image = "animalmaterials_milk.png", on_use = minetest.item_eat(1), groups = { eatable=1 }, stack_max=10 }) ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- egg -- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- minetest.register_craftitem("animalmaterials:egg", { description = S("Egg"), image = "animalmaterials_egg.png", stack_max=10 }) minetest.register_craftitem("animalmaterials:egg_big", { description = S("Egg (big)"), image = "animalmaterials_egg_big.png", stack_max=5 }) animalmaterialsdata["animalmaterials_egg"] = { graphics_3d = { visual = "mesh", mesh = "animalmaterials_egg_ent.b3d", textures = { "animalmaterials_egg_ent_mesh.png" }, collisionbox = { -0.12,-0.125,-0.12,0.12,0.125,0.12 }, visual_size = {x=1,y=1,z=1}, } } animalmaterialsdata["animalmaterials_egg_big"] = { graphics_3d = { visual = "mesh", mesh = "animalmaterials_egg_ent.b3d", textures = { "animalmaterials_egg_ent_mesh.png" }, collisionbox = { -0.24,-0.25,-0.24,0.24,0.25,0.24 }, visual_size = {x=2,y=2,z=2}, } } ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- bone -- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- minetest.register_craftitem("animalmaterials:bone", { description = S("Bone"), image = "animalmaterials_bone.png", stack_max=25 }) ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- furs -- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- minetest.register_craftitem("animalmaterials:fur", { description = S("Fur"), image = "animalmaterials_fur.png", stack_max=25 }) minetest.register_craftitem("animalmaterials:fur_deer", { description = S("Deer fur"), image = "animalmaterials_deer_fur.png", stack_max=10 }) minetest.register_craftitem("animalmaterials:coat_cattle", { description = S("Cattle coat"), image = "animalmaterials_cattle_coat.png", stack_max=10 }) ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- horns -- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- minetest.register_craftitem("animalmaterials:deer_horns", { description = S("Deer horns"), image = "animalmaterials_deer_horns.png", stack_max=20 }) minetest.register_craftitem("animalmaterials:ivory", { description = S("Ivory"), image = "animalmaterials_ivory.png", stack_max=20 }) ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- scale -- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- minetest.register_craftitem("animalmaterials:scale_golden", { description = S("Scale (golden)"), image = "animalmaterials_scale_golden.png", stack_max=25 }) minetest.register_craftitem("animalmaterials:scale_white", { description = S("Scale (white)"), image = "animalmaterials_scale_white.png", stack_max=25 }) minetest.register_craftitem("animalmaterials:scale_grey", { description = S("Scale (grey)"), image = "animalmaterials_scale_grey.png", stack_max=25 }) minetest.register_craftitem("animalmaterials:scale_blue", { description = S("Scale (blue)"), image = "animalmaterials_scale_blue.png", stack_max=25 }) ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- recipes -- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- minetest.register_craft({ output = "wool:white", recipe = { {"animalmaterials:feather","animalmaterials:feather","animalmaterials:feather"}, {"animalmaterials:feather", "animalmaterials:feather","animalmaterials:feather"}, {"animalmaterials:feather","animalmaterials:feather","animalmaterials:feather"}, } }) minetest.register_craft({ output = "animalmaterials:contract", recipe = { {"default:paper"}, {"default:paper"}, } }) core.log("action","MOD: animalmaterials mod version " .. version .. " loaded")
require('teeswift') local nw = "(((((COLLI:0.10374812919279975676,CAPCA:0.07285820959258730578)72:0.01687633680392261470,((CHAPE:0.09436074887800374733,CALAN:0.20253965688958708302)81:0.02742615135783911876,(PICPU:0.21751383294136364399,(OPHHO:0.09675872794281610567,((MELUN:0.08887850140662424681,NESNO:0.05874177300058070622)100:0.06995967804137828705,(ACACH:0.11286773318738121952,((CORBR:0.03358217852721183394,(GEOFO:0.05523736608468161891,TAEGU:0.03530042644379066674)100:0.05363464311987679867)100:0.10566225761538157457,MANVI:0.07521604544639204359)94:0.02739670354302274277)87:0.01766137251847924028)63:0.00544202821240259618)51:0.00316666983787007930)27:0.00274070754266861902)16:0.00000196869490312238)54:0.00977444841055891828,(EURHE:0.10159343709480662954,((PHACA:0.08584793545984133190,(FULGL:0.05354739058566788945,(APTFO:0.00913129287756810938,PYGAD:0.02297643158428801236)100:0.06845647756872645651)61:0.01037777695888693341)5:0.00000196869490312238,((GAVST:0.06175530757699851381,(TAUER:0.08240929784069504771,PHALE:0.06519004947996714927)26:0.00429286290202376616)22:0.00273303677117812385,((EGRGA:0.03383695486236295430,PELCR:0.03399545656749024258)59:0.00152968866382312621,NIPNI:0.05645231821438039671)74:0.01263761265503960882)3:0.00000196869490312238)29:0.00209062282265232982)79:0.00983723114729546586)89:0.02411800220691390911,(((CHLUN:0.09586641091813387361,BALRE:0.06468407628202049731)36:0.00698054372731473499,(CHAVO:0.08867093965953791457,((MESUN:0.09741720084819313619,((PODCR:0.06283968350294601157,PHORU:0.04937783489016153021)54:0.00625245935973366574,CUCCA:0.11506218702666083653)29:0.00446978217566842799)28:0.00619130356480267728,((CATAU:0.07130541874086816778,(((COLST:0.20112645217282462684,FALPE:0.08546516798573794427)51:0.00961300428540062465,CARCR:0.02574304172267912610)26:0.00350533885725209026,(((BUCRH:0.08749980421698314026,(LEPDI:0.11251088435859424308,APAVI:0.11214943798148015175)25:0.00112902455354903317)34:0.00424804398952821453,((HALLE:0.00000196869490312238,HALAL:0.00000196869490312238)100:0.08990167493577440327,MERNU:0.08314516926356781135)14:0.00000196869490312238)26:0.00861349530233438895,TYTAL:0.10298062541052484253)23:0.00087686834626606253)12:0.00370507739587786497)16:0.00364511139986219927,PTEGU:0.11563697309606628394)14:0.00542440930924274322)33:0.00521450426208774909)14:0.00000196869490312238)93:0.04396199247384282444,(ANAPL:0.19285063663720022897,(GALGA:0.02283234311805707253,MELGA:0.06200609429258526623)55:0.00228419673746398360)100:0.09283249756683750742)56:0.00010680300439297902)86:0.01534176395895781725,(STRCA:0.14961763263528296553,TINMA:0.15817124355863812490)86:0.01534176395895781725);" -- local nw = "((1,2)a,(3,4)b)r;" local t = read_tree_newick(nw) -- print(t:newick()) -- print(t:copy():newick()) local pprint = require('pprint') t:suppress_unifurcations() for n in t:extract_subtree(t.root[1][1]):traverse_leaves() do -- print(n:is_root()) print(n:newick()) -- pprint(n) -- break -- print(n:newick()) end -- print(read_tree_newick(t:newick()):newick())
-- This table is indexed by coroutine and simply contains the time at which the coroutine -- should be woken up. local WAITING_ON_TIME = {} local WAITING_ON_MOVE = {} -- Keep track of how long the game has been running. local CURRENT_TIME = 0 local savedStates = {} local function wait(ms, id) if id and savedStates[id] == true then return end -- Grab a reference to the current running coroutine. local co = coroutine.running() -- If co is nil, that means we're on the main process, which isn't a coroutine and can't yield assert(co ~= nil, "The main thread cannot wait!") -- Store the coroutine and its wakeup time in the WAITING_ON_TIME table local wakeupTime = CURRENT_TIME + ms WAITING_ON_TIME[co] = wakeupTime -- And suspend the process return coroutine.yield(co) end local function moveToPosition(obj, id, x, y, z, running) if running == nil then running = true end local co = coroutine.running() if WAITING_ON_MOVE[id] == nil then WAITING_ON_MOVE[id] = {} end WAITING_ON_MOVE[id][obj] = co CharacterMoveToPosition(obj, x, y, z, running, id) return coroutine.yield(co) end Ext.RegisterOsirisListener("StoryEvent", 2, "after", function(obj, event) local waiting = WAITING_ON_MOVE[event] if waiting then local obj = StringHelpers.GetUUID(obj) local co = waiting[obj] if co then waiting[obj] = nil coroutine.resume(co) end local length = Common.TableLength(waiting, true) if length == 0 then WAITING_ON_MOVE[event] = nil end end end) local function wakeUpWaitingThreads(dt) -- This function should be called once per game logic update with the amount of time -- that has passed since it was last called CURRENT_TIME = CURRENT_TIME + dt -- First, grab a list of the threads that need to be woken up. They'll need to be removed -- from the WAITING_ON_TIME table which we don't want to try and do while we're iterating -- through that table, hence the list. local threadsToWake = {} for co, wakeupTime in pairs(WAITING_ON_TIME) do if wakeupTime < CURRENT_TIME then table.insert(threadsToWake, co) end end -- Now wake them all up. for _, co in ipairs(threadsToWake) do WAITING_ON_TIME[co] = nil -- Setting a field to nil removes it from the table coroutine.resume(co) end end local function runProcess(func) -- This function is just a quick wrapper to start a coroutine. local co = coroutine.create(func) return coroutine.resume(co) end Timer.RegisterListener("LeaderLib_CoroutineLoop", function() wakeUpWaitingThreads(250) StartTimer("LeaderLib_CoroutineLoop", 250) end) Ext.RegisterConsoleCommand("coroutinetest", function(cmd) StartTimer("LeaderLib_CoroutineLoop", 250) runProcess(function () local startTime = Ext.MonotonicTime() PrintDebug("Hello world. I will now astound you by waiting for 2 seconds.", Ext.MonotonicTime()) wait(2000) PrintDebug("Haha! I did it!", Ext.MonotonicTime() - startTime) local host = StringHelpers.GetUUID(CharacterGetHostCharacter()) local x,y,z = table.unpack(GameHelpers.Math.GetForwardPosition(host, 3.0)) PrintDebug("Moving", x, y, z) moveToPosition(host, "LeaderLib_CoroutineMove", x, y, z, true) PrintDebug("Move done!", GetPosition(host)) CancelTimer("LeaderLib_CoroutineLoop") end) end)
local httpd = require "maoj.http.httpd" local ls = require "maoj.http.socket" local task = require "maoj.thread" local urllib = require "maoj.http.url" local serv = {} function serv.on_exit(obj,exit_cb) obj._exit_cb = exit_cb end function serv.exit(obj) obj._exit = true end function serv.location(obj,l) local lcts = {} for k,v in pairs(l) do assert(type(k) == "string" and type(v) == "function","unknow location") table.insert(lcts,{rule = k,handler = v}) end table.sort(lcts,function(a,b) return #a.rule > #b.rule end) obj._location = lcts end local _serv_meta = { __index = serv} local function response(sock,...) httpd.write_response(ls.writefunc(sock),...) end local function _log(info) print(os.date("[%Y-%m-%d %H:%M:%S]"),info) end local function req_worke(self,sock) sock:start() local code,url,method,heads,body = httpd.read_request(ls.readfunc(sock)) local log = '' if code then if code ~= 200 then response(sock,code) else local path,query = urllib.parse(url) local arg = urllib.parse_query(query) local handler = nil for _,v in ipairs(self._location) do local h,e = string.find(path,v.rule) if h then handler = v.handler break end end if not handler then response(sock,404) log = log .. " "..method.." "..url.." 404" else local ok,rcode,rbody,rhead = pcall(handler,{args = arg,path = path,url = url,heades = heads,method = method,body = body}) if ok then log = log .. " "..method.." "..url.." "..rcode response(sock,rcode,rbody,rhead) else log = log .. " "..method.." "..url.." 500" response(sock,500) end end end else log = log.." unkown" end sock:close() _log(log) end local function create(ip,port) local self = setmetatable({},_serv_meta) self._handler = {} local sock,err = ls.listen(ip,port,function(s,c,err) if c then task.fork(req_worke,self,c) else local f = self._exit_cb if f then f() end end end) assert(sock,err) _log('start http://'..ip..':'..port) return self end return { create = create }
-- Copyright 2022 SmartThings -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. local test = require "integration_test" local capabilities = require "st.capabilities" local zw = require "st.zwave" --- @type st.zwave.CommandClass.DoorLock local DoorLock = (require "st.zwave.CommandClass.DoorLock")({ version = 1 }) local Battery = (require "st.zwave.CommandClass.Battery")({ version = 1 }) local DANALOCK_MANUFACTURER_ID = 0x010E local DANALOCK_PRODUCT_TYPE = 0x0008 local DANALOCK_PRODUCT_ID = 0x0002 local zwave_lock_profile = { components = { main = { capabilities = { [capabilities.lock.ID] = { id = capabilities.lock.ID }, [capabilities.battery.ID] = { id = capabilities.battery.ID } }, id = "main" } } } -- supported comand classes local zwave_lock_endpoints = { { command_classes = { { value = zw.BATTERY }, { value = DoorLock } } } } local mock_device = test.mock_device.build_test_zwave_device( { profile = zwave_lock_profile, zwave_endpoints = zwave_lock_endpoints, zwave_manufacturer_id = DANALOCK_MANUFACTURER_ID, zwave_product_type = DANALOCK_PRODUCT_TYPE, zwave_product_id = DANALOCK_PRODUCT_ID } ) local function test_init() test.mock_device.add_test_device(mock_device) end test.set_test_init_function(test_init) test.register_coroutine_test( "Door Lock Operation Reports should be handled", function() test.socket.zwave:__queue_receive({ mock_device.id, DoorLock:OperationReport({ door_lock_mode = DoorLock.door_lock_mode.DOOR_UNSECURED }) }) test.socket.capability:__expect_send(mock_device:generate_test_message("main", capabilities.lock.lock.unlocked())) end ) test.register_message_test( "Battery percentage report should be handled", { { channel = "zwave", direction = "receive", message = { mock_device.id, Battery:Report({ battery_level = 0x32 }) } }, { channel = "capability", direction = "send", message = mock_device:generate_test_message("main", capabilities.battery.battery(50)) } } ) test.register_message_test( "Battery percentage 0xFF report should be handled as 1%", { { channel = "zwave", direction = "receive", message = { mock_device.id, Battery:Report({ battery_level = 0xFF }) } }, { channel = "capability", direction = "send", message = mock_device:generate_test_message("main", capabilities.battery.battery(1)) } } ) test.register_coroutine_test( "Sending the lock command should be handled", function() test.timer.__create_and_queue_test_time_advance_timer(4.2, "oneshot") test.socket.capability:__queue_receive({ mock_device.id, { capability = "lock", component = "main", command = "lock", args = {} } }) test.socket.zwave:__expect_send(DoorLock:OperationSet({ door_lock_mode = DoorLock.door_lock_mode.DOOR_SECURED }):build_test_tx(mock_device.id)) test.wait_for_events() test.mock_time.advance_time(4.2) test.socket.zwave:__expect_send(DoorLock:OperationGet({}):build_test_tx(mock_device.id)) end ) test.run_registered_tests()
#!/usr/bin/env lua config = require("config") json = require("cjson") require("utils") posts = json.decode(readFile(config.posts_path)) addPost{ title = getInput("title"), content = getInput("content"), author = {1} } syncPostsRefs()
-- This script template has each of the script entry point functions. -- They are described in detail in VR-Forces Configuration Guide. -- Some basic VRF Utilities defined in a common module. require "vrfutil" -- Global Variables -- -- Global variables get saved when a scenario gets checkpointed in one of the folowing way: -- 1) If the checkpoint mode is AllGlobals all global variables defined will be saved as part of the save stat -- 2) In setting CheckpointStateOnly, this means that the script will *only* save variables that are part of the checkpointState table. If you remove this value, it will then -- default to the behavior of sabing all globals -- -- If you wish to change the mode, call setCheckpointMode(AllGlobals) to save all globals or setCheckpointMode(CheckpointStateOnly) -- to save only those variables in the checkpointState table -- They get re-initialized when a checkpointed scenario is loaded. vrf:setCheckpointMode(CheckpointStateOnly) -- Task Parameters Available in Script local currentlyJammingList = {} theJamStartTime = 0 -- Seconds of no new trackers before the jammer is turned off. local THE_JAM_RECYCLYE_PERIOD = 600 -- Called when reactive task is enabled or changes to the enabled state. function checkInit() -- Set the tick period for this script while checking. vrf:setTickPeriod(1.0) end -- Called each tick period for this script while enabled but not in the active state. function check() -- Check if entity AI is enabled. If not, a reactive task should generally not -- run, as this means the entity is making a decision for itself about how to -- behave as the result of events within the scenario. local aiEnabled = this:getStateProperty(AIEnabledStateProperty) if (aiEnabled ~= nil and not aiEnabled) then return false end local trackingEmitters = this:getStateProperty("tracking-emitters") if (trackingEmitters ~= nil and #trackingEmitters > 0) then return true; end -- Returning true will cause the reactive task to become active and will call init() -- and tick() until the task completes. return false end -- Called when the task first starts. Never called again. function init() -- turn on the jammer vrf:executeSetData("Jammer_Enabled", {enabled=1}) theJamStartTime = vrf:getExerciseTime() -- Set the tick period for this script. vrf:setTickPeriod(1.0) end -- Called each tick while this task is active. function tick() local trackingEmitters = this:getStateProperty("tracking-emitters") if (trackingEmitters ~= nil and #trackingEmitters > 0) then for i, uuid in ipairs(trackingEmitters) do local obj = vrf:getSimObjectByUUID(uuid) if (obj ~= nil) then if (not onJammingList(obj)) then startJamming(obj) end end end end if (vrf:getExerciseTime() > theJamStartTime + THE_JAM_RECYCLYE_PERIOD) then stopAllJamming() vrf:endTask(true) end end function onJammingList(object) for i, o in ipairs(currentlyJammingList) do if (o == object) then return true end end return false end function stopAllJamming() for i, o in ipairs(currentlyJammingList) do vrf:executeSetData("Remove_Jamming_Target", {target=o}) end currentlyJammingList={} vrf:executeSetData("Jammer_Enabled", {enabled=2}) end function startJamming(obj) table.insert(currentlyJammingList, obj) vrf:executeSetData("Add_Jamming_Target", {target=obj}) end -- Called when this task is being suspended, likely by a reaction activating. function suspend() -- By default, halt all subtasks and other entity tasks started by this task when suspending. vrf:stopAllSubtasks() vrf:stopAllTasks() end -- Called when this task is being resumed after being suspended. function resume() -- By default, simply call init() to start the task over. init() end -- Called immediately before a scenario checkpoint is saved when -- this task is active. -- It is typically not necessary to add code to this function. function saveState() end -- Called immediately after a scenario checkpoint is loaded in which -- this task is active. -- It is typically not necessary to add code to this function. function loadState() end -- Called when this task is ending, for any reason. -- It is typically not necessary to add code to this function. function shutdown() end -- Called whenever the entity receives a text report message while -- this task is active. -- message is the message text string. -- sender is the SimObject which sent the message. function receiveTextMessage(message, sender) end -- Called when a reactive task is disabled (check will no longer called) -- It is typically not necessary to add code to this function. function disable() end
log = require('lib/log') -- copied from lua-csv submodule csv = require('lib/csv') log.info("LOADING ELEVATION") local f = csv.open("./data/elevation.csv") ElevationTable = {} for fields in f:lines() do data = {} data['elevation'] = fields[2] data['lng'] = fields[3] data['lat'] = fields[4] ElevationTable[fields[1]] = data end log.info("FINISHED LOADING ELEVATION") return ElevationTable
local landmines = {} local landmineUtils = require("utils/LandmineUtils") local technologyUtils = require("utils/TechnologyUtils") local recipeUtils = require("utils/RecipeUtils") local makeRecipe = recipeUtils.makeRecipe local addEffectToTech = technologyUtils.addEffectToTech local makeLandmine = landmineUtils.makeLandmine function landmines.enable() local nuclearLandmine = makeLandmine( { name = "nuclear", icon = "__RampantArsenal__/graphics/icons/nuclear-landmine.png", tint = {r=0.70,g=0.9,b=0.70,a=1}, triggerRadius = 7, stackSize = 100, order="f[land-mine]-c[nuclear]" }, { type = "direct", action_delivery = { type = "instant", source_effects = { { repeat_count = 100, type = "create-trivial-smoke", smoke_name = "nuclear-smoke", offset_deviation = {{-1, -1}, {1, 1}}, slow_down_factor = 1, starting_frame = 3, starting_frame_deviation = 5, starting_frame_speed = 0, starting_frame_speed_deviation = 5, speed_from_center = 0.5, speed_deviation = 0.2 }, { type = "create-entity", entity_name = "small-scorchmark", check_buildability = true }, { type = "nested-result", action = { type = "area", target_entities = false, repeat_count = 2000, radius = 35, action_delivery = { type = "projectile", projectile = "atomic-bomb-wave", starting_speed = 0.5 } } }, { type = "create-entity", entity_name = "explosion" }, { type = "damage", damage = { amount = 1000, type = "explosion"} } } } } ) local incendiaryLandmine = makeLandmine( { name = "incendiary", icon = "__RampantArsenal__/graphics/icons/incendiary-landmine.png", tint = {r=0.9,g=0.70,b=0.70,a=1}, triggerRadius = 2.5, stackSize = 100, resistances = { { type = "fire", percent = 100 } }, order="f[land-mine]-b[incendiary]" }, { type = "direct", action_delivery = { type = "instant", source_effects = { { type = "create-entity", entity_name = "big-explosion" }, { type = "damage", damage = { amount = 500, type = "explosion"} }, { type = "damage", damage = { amount = 750, type = "fire"} }, { type = "nested-result", affects_target = true, action = { { type = "area", radius = 6, force = "not-same", action_delivery = { type = "instant", target_effects = { { type = "create-sticker", sticker = "small-fire-sticker-rampant-arsenal" }, { type = "damage", damage = { amount = 500, type = "fire" }, apply_damage_to_trees = false }, { type = "create-fire", entity_name = "fire-flame", initial_ground_flame_count = 7, check_buildability = true } } } }, { type = "cluster", cluster_count = 22, distance = 4, distance_deviation = 3, action_delivery = { type = "instant", target_effects = { { type = "create-fire", entity_name = "fire-flame", initial_ground_flame_count = 7, check_buildability = true, show_in_tooltip = true } } } }} } } } } ) local bioLandmine = makeLandmine( { name = "bio", icon = "__RampantArsenal__/graphics/icons/bio-landmine.png", tint = {r=0.9,g=0.60,b=0.9,a=1}, triggerRadius = 2.5, stackSize = 100, order="f[land-mine]-c[bio]" }, { type = "direct", action_delivery = { type = "instant", source_effects = { { type = "create-entity", entity_name = "big-explosion" }, { type = "damage", damage = { amount = 500, type = "explosion"} }, { type = "damage", damage = { amount = 750, type = "poison"} }, { type = "create-entity", entity_name = "toxic-cloud-rampant-arsenal", show_in_tooltip = true }, { type = "nested-result", affects_target = true, action = { { type = "area", radius = 6, force = "not-same", action_delivery = { type = "instant", target_effects = { { type = "damage", damage = { amount = 450, type = "poison" } } } } } } } } } } ) local heLandmine = makeLandmine( { name = "he", icon = "__RampantArsenal__/graphics/icons/he-landmine.png", tint = {r=0.70,g=0.70,b=0.9,a=1}, triggerRadius = 2.5, stackSize = 100, order="f[land-mine]-c[bio]" }, { type = "direct", action_delivery = { type = "instant", source_effects = { { type = "create-entity", entity_name = "big-artillery-explosion" }, { type = "damage", damage = { amount = 4500, type = "explosion"} }, { type = "nested-result", affects_target = true, action = { { type = "area", radius = 6, force = "not-same", action_delivery = { type = "instant", target_effects = { { type = "push-back", distance = 2.5 }, { type = "damage", damage = { amount = 2000, type = "explosion" } } } } } } } } } } ) makeRecipe({ name = nuclearLandmine, icon = "__RampantArsenal__/graphics/icons/nuclear-landmine.png", enabled = false, ingredients = { {"land-mine", 1}, {"atomic-bomb", 1} }, result = nuclearLandmine }) makeRecipe({ name = incendiaryLandmine, icon = "__RampantArsenal__/graphics/icons/incendiary-landmine.png", enabled = false, category = "chemistry", ingredients = { {"land-mine", 1}, {"steel-plate", 1}, {type="fluid", name="light-oil", amount=40} }, result = incendiaryLandmine }) makeRecipe({ name = heLandmine, icon = "__RampantArsenal__/graphics/icons/he-landmine.png", enabled = false, category = "chemistry", ingredients = { {"land-mine", 1}, {"steel-plate", 1}, {"explosives", 4} }, result = heLandmine }) makeRecipe({ name = bioLandmine, icon = "__RampantArsenal__/graphics/icons/bio-landmine.png", enabled = false, category = "chemistry", ingredients = { {"land-mine", 1}, {"steel-plate", 1}, {"poison-capsule", 2} }, result = bioLandmine }) local landmine = data.raw["land-mine"]["land-mine"] landmine.action = { type = "direct", action_delivery = { type = "instant", source_effects = { { type = "nested-result", affects_target = true, action = { type = "area", radius = 6, force = "not-same", action_delivery = { type = "instant", target_effects = { { type = "damage", damage = { amount = 250, type = "explosion"} }, { type = "create-sticker", sticker = "lite-slow-sticker-rampant-arsenal" } } } } }, { type = "create-entity", entity_name = "explosion" }, { type = "damage", damage = { amount = 1000, type = "explosion"} } } } } landmine = table.deepcopy(data.raw["land-mine"]["land-mine"]) -- local landmineRecipe = table.deepcopy(data.raw["recipe"]["land-mine"]) local landmineItem = table.deepcopy(data.raw["item"]["land-mine"]) landmineItem.hidden = true landmineItem.name = "landmine-ghostless-rampant-arsenal" landmineItem.place_result = "landmine-ghostless-rampant-arsenal" landmine.name = "landmine-ghostless-rampant-arsenal" landmine.create_ghost_on_death = false landmine.flags[#landmine.flags+1] = "hidden" data:extend({ landmine, landmineItem }) addEffectToTech("uranium-ammo", { type = "unlock-recipe", recipe = nuclearLandmine, }) addEffectToTech("incendiary-landmine", { type = "unlock-recipe", recipe = incendiaryLandmine, }) addEffectToTech("he-landmine", { type = "unlock-recipe", recipe = heLandmine, }) addEffectToTech("bio-landmine", { type = "unlock-recipe", recipe = bioLandmine, }) end return landmines
local ntype ntype = require("moonscript.types").ntype local Transformer do local _class_0 local _base_0 = { transform_once = function(self, scope, node, ...) if self.seen_nodes[node] then return node end self.seen_nodes[node] = true local transformer = self.transformers[ntype(node)] if transformer then return transformer(scope, node, ...) or node else return node end end, transform = function(self, scope, node, ...) if self.seen_nodes[node] then return node end self.seen_nodes[node] = true while true do local transformer = self.transformers[ntype(node)] local res if transformer then res = transformer(scope, node, ...) or node else res = node end if res == node then return node end node = res end return node end, bind = function(self, scope) return function(...) return self:transform(scope, ...) end end, __call = function(self, ...) return self:transform(...) end, can_transform = function(self, node) return self.transformers[ntype(node)] ~= nil end } _base_0.__index = _base_0 _class_0 = setmetatable({ __init = function(self, transformers) self.transformers = transformers self.seen_nodes = setmetatable({ }, { __mode = "k" }) end, __base = _base_0, __name = "Transformer" }, { __index = _base_0, __call = function(cls, ...) local _self_0 = setmetatable({}, _base_0) cls.__init(_self_0, ...) return _self_0 end }) _base_0.__class = _class_0 Transformer = _class_0 end return { Transformer = Transformer }
---@class IsoBrokenGlass : zombie.iso.objects.IsoBrokenGlass IsoBrokenGlass = {} ---@public ---@return void function IsoBrokenGlass:addToWorld() end ---@public ---@return String function IsoBrokenGlass:getObjectName() end ---@public ---@param arg0 ByteBuffer ---@param arg1 boolean ---@return void function IsoBrokenGlass:save(arg0, arg1) end ---@public ---@param arg0 ByteBuffer ---@param arg1 int ---@param arg2 boolean ---@return void function IsoBrokenGlass:load(arg0, arg1, arg2) end ---@public ---@return void function IsoBrokenGlass:removeFromWorld() end ---@public ---@param arg0 float ---@param arg1 float ---@param arg2 float ---@param arg3 ColorInfo ---@return void function IsoBrokenGlass:renderObjectPicker(arg0, arg1, arg2, arg3) end ---@public ---@param arg0 float ---@param arg1 float ---@param arg2 float ---@param arg3 ColorInfo ---@param arg4 boolean ---@param arg5 boolean ---@param arg6 Shader ---@return void function IsoBrokenGlass:render(arg0, arg1, arg2, arg3, arg4, arg5, arg6) end
local BOSS = {} BOSS.Num = 2 //Boss ID number. 1,2,3,etc if making a new boss make sure it increments in order! BOSS.PName = "Terrorist" //Boss name BOSS.Music = { } //Put music in BOSS.Music for it to play during fight. 'pvb_enablebossmusic' in console controls if its playing (client side) function BOSS:Init() local ply = table.Random(player.GetAll()) ply:SetTeam(TEAM_BOSS) ply.BossPlayerModel = "models/player/guerilla.mdl" //Bosses Model end //Include weapons/ammo/armor/etc in BOSS:Loadout function BOSS:Loadout(ply) ply:SetHealth(#team.GetPlayers(TEAM_PLAYERS)*3800) //Health multiplier so health scales depending on player count ply:Give("bulletstorm") //ply:GiveAmmo(99999999,"Pistol", true) end PVB.RegisterBossClass(BOSS)
--[[ MFF: Prevent trees from destroying existing blocks This is the list of "safe" blocks in which a tree can grow They were moved outside the local safety function for speed (I hope) --]] local c_air = minetest.get_content_id("air") local c_ignore = minetest.get_content_id("ignore") -- MFF: The local function to do safety checks local function safely_set_block(t, k, v) if t[k] == c_air or t[k] == c_ignore then t[k] = v end end function watershed_appletree(x, y, z, area, data) local c_tree = minetest.get_content_id("default:tree") local c_apple = minetest.get_content_id("default:apple") local c_wsappleaf = minetest.get_content_id("watershed:appleleaf") -- MFF: Higher default tree with a bit of randomness local tree_top = 5 + math.random(0, 1) local leaves_height = tree_top - 1 local branches_height = leaves_height - 1 for j = 0, tree_top do -- MFF: Higher tree, same design if j >= leaves_height then for i = -2, 2 do for k = -2, 2 do local vil = area:index(x + i, y + j, z + k) if math.random(64) == 2 then -- MFF: Prevent trees from destroying existing blocks safely_set_block(data, vil, c_apple) elseif math.random(5) ~= 2 then -- MFF: Prevent trees from destroying existing blocks safely_set_block(data, vil, c_wsappleaf) end end end elseif j == branches_height then for i = -1, 1 do for k = -1, 1 do if math.abs(i) + math.abs(k) == 2 then local vit = area:index(x + i, y + j, z + k) -- MFF: Prevent trees from destroying existing blocks safely_set_block(data, vit, c_tree) end end end else local vit = area:index(x, y + j, z) -- MFF: Prevent trees from destroying existing blocks if j == 0 then -- MFF: the position of the sapling itself, replace it without checking. data[vit] = c_tree else safely_set_block(data, vit, c_tree) end end end end function watershed_pinetree(x, y, z, area, data) local c_wspitree = minetest.get_content_id("watershed:pinetree") local c_wsneedles = minetest.get_content_id("watershed:needles") local c_snowblock = minetest.get_content_id("default:snowblock") for j = 0, 14 do if j == 3 or j == 6 or j == 9 or j == 12 then for i = -2, 2 do for k = -2, 2 do if math.abs(i) == 2 or math.abs(k) == 2 then if math.random(7) ~= 2 then -- MFF: Prevent trees from destroying existing blocks local vil = area:index(x + i, y + j, z + k) safely_set_block(data, vil, c_wsneedles) local vila = area:index(x + i, y + j + 1, z + k) safely_set_block(data, vila, c_snowblock) end end end end elseif j == 4 or j == 7 or j == 10 then for i = -1, 1 do for k = -1, 1 do if not (i == 0 and j == 0) then if math.random(11) ~= 2 then -- MFF: Prevent trees from destroying existing blocks local vil = area:index(x + i, y + j, z + k) safely_set_block(data, vil, c_wsneedles) local vila = area:index(x + i, y + j + 1, z + k) safely_set_block(data, vila, c_snowblock) end end end end elseif j == 13 then for i = -1, 1 do for k = -1, 1 do if not (i == 0 and j == 0) then -- MFF: Prevent trees from destroying existing blocks local vil = area:index(x + i, y + j, z + k) safely_set_block(data, vil,c_wsneedles) local vila = area:index(x + i, y + j + 1, z + k) safely_set_block(data, vila, c_wsneedles) local vilaa = area:index(x + i, y + j + 2, z + k) safely_set_block(data, vilaa, c_snowblock) end end end end -- MFF: Prevent trees from destroying existing blocks local vit = area:index(x, y + j, z) if j == 0 then data[vit] = c_wspitree -- No safety check for the sapling itself else safely_set_block(data, vit, c_wspitree) end end local vil = area:index(x, y + 15, z) local vila = area:index(x, y + 16, z) local vilaa = area:index(x, y + 17, z) -- MFF: Prevent trees from destroying existing blocks safely_set_block(data, vil, c_wsneedles) safely_set_block(data, vila, c_wsneedles) safely_set_block(data, vilaa, c_snowblock) end function watershed_jungletree(x, y, z, area, data) local c_juntree = minetest.get_content_id("default:jungletree") local c_wsjunleaf = minetest.get_content_id("watershed:jungleleaf") local top = math.random(17,23) local branch = math.floor(top * 0.6) for j = 0, top do if j == top or j == top - 1 or j == branch + 1 or j == branch + 2 then for i = -2, 2 do -- leaves for k = -2, 2 do local vi = area:index(x + i, y + j, z + k) if math.random(5) ~= 2 then -- MFF: Prevent trees from destroying existing blocks safely_set_block(data, vi, c_wsjunleaf) end end end elseif j == top - 2 or j == branch then -- branches for i = -1, 1 do for k = -1, 1 do if math.abs(i) + math.abs(k) == 2 then local vi = area:index(x + i, y + j, z + k) -- MFF: Prevent trees from destroying existing blocks safely_set_block(data, vi, c_juntree) end end end end if j <= top - 3 then -- trunk local vi = area:index(x, y + j, z) -- MFF: Prevent trees from destroying existing blocks if j == 0 then data[vi] = c_juntree -- No safety check for the sapling itself else safely_set_block(data, vi, c_juntree) end end end end function watershed_acaciatree(x, y, z, area, data) local c_sapling = minetest.get_content_id("moretrees:acacia_sapling_ongen") local vi = area:index(x, y, z) data[vi] = c_sapling end function watershed_flower(data, vi, noise) local c_danwhi = minetest.get_content_id("flowers:dandelion_white") local c_danyel = minetest.get_content_id("flowers:dandelion_yellow") local c_rose = minetest.get_content_id("flowers:rose") local c_tulip = minetest.get_content_id("flowers:tulip") local c_geranium = minetest.get_content_id("flowers:geranium") local c_viola = minetest.get_content_id("flowers:viola") if noise > 0.8 then data[vi] = c_danwhi elseif noise > 0.4 then data[vi] = c_rose elseif noise > 0 then data[vi] = c_tulip elseif noise > -0.4 then data[vi] = c_danyel elseif noise > -0.8 then data[vi] = c_geranium else data[vi] = c_viola end end function watershed_cactus(x, y, z, area, data) local c_wscactus = minetest.get_content_id("watershed:cactus") for j = 0, 4 do for i = -2, 2 do if i == 0 or j == 2 or (j == 3 and math.abs(i) == 2) then local vic = area:index(x + i, y + j, z) data[vic] = c_wscactus end end end end function watershed_papyrus(x, y, z, area, data) local c_papyrus = minetest.get_content_id("default:papyrus") local ph = math.random(1, 4) for j = 0, ph do local vip = area:index(x, y + j, z) data[vip] = c_papyrus end end -- Singlenode option local SINGLENODE = true if SINGLENODE then -- Set mapgen parameters minetest.set_mapgen_params({mgname="singlenode", flags="nolight"}) -- Spawn player function is useless in minetestforfun end -- Appletree sapling function default.grow_tree(pos) local x = pos.x local y = pos.y local z = pos.z local vm = minetest.get_voxel_manip() local pos1 = {x = x - 2, y = y - 2, z = z - 2} local pos2 = {x = x + 2, y = y + 4, z = z + 2} local emin, emax = vm:read_from_map(pos1, pos2) local area = VoxelArea:new({MinEdge = emin, MaxEdge = emax}) local data = vm:get_data() watershed_appletree(x, y, z, area, data) vm:set_data(data) vm:write_to_map() vm:update_map() end -- Pine sapling function default.grow_pine_tree(pos) local x = pos.x local y = pos.y local z = pos.z local vm = minetest.get_voxel_manip() local pos1 = {x = x - 2, y = y - 4, z = z - 2} local pos2 = {x = x + 2, y = y + 17, z = z + 2} local emin, emax = vm:read_from_map(pos1, pos2) local area = VoxelArea:new({MinEdge=emin, MaxEdge=emax}) local data = vm:get_data() watershed_pinetree(x, y, z, area, data) vm:set_data(data) vm:write_to_map() vm:update_map() end -- Acacia sapling is already defined in Moretrees -- Jungletree sapling function default.grow_jungle_tree(pos) local x = pos.x local y = pos.y local z = pos.z local vm = minetest.get_voxel_manip() local pos1 = {x = x - 2, y = y - 5, z = z - 2} local pos2 = {x = x + 2, y = y + 23, z = z + 2} local emin, emax = vm:read_from_map(pos1, pos2) local area = VoxelArea:new({MinEdge = emin, MaxEdge = emax}) local data = vm:get_data() watershed_jungletree(x, y, z, area, data) vm:set_data(data) vm:write_to_map() vm:update_map() end default.grow_new_apple_tree = default.grow_tree default.grow_new_jungle_tree = default.grow_jungle_tree default.grow_new_pine_tree = default.grow_pine_tree
------------------- ABOUT ---------------------- -- -- In this cold planet hero seeks for a part of the -- antigravity device. He has to capture Thanta who -- knows where the device is hidden. Hero will be -- able to use only the ice gun for this mission. HedgewarsScriptLoad("/Scripts/Locale.lua") HedgewarsScriptLoad("/Scripts/Animate.lua") HedgewarsScriptLoad("/Missions/Campaign/A_Space_Adventure/global_functions.lua") ----------------- VARIABLES -------------------- -- globals local missionName = loc("A frozen adventure") local heroAtAntiFlyArea = false local heroVisitedAntiFlyArea = false local heroAtFinalStep = false local iceGunTaken = false local checkPointReached = 1 -- 1 is normal spawn local heroDamageAtCurrentTurn = 0 -- dialogs local dialog01 = {} local dialog02 = {} -- mission objectives local goals = { [dialog01] = {missionName, loc("Getting ready"), loc("Collect the icegun and get the device part from Thanta"), 1, 4500}, [dialog02] = {missionName, loc("Win"), loc("Congratulations, you collected the device part!"), 1, 3500}, } -- crates local icegunY = 1950 local icegunX = 260 -- hogs local hero = {} local ally = {} local bandit1 = {} local bandit2 = {} local bandit3 = {} local bandit4 = {} local bandit5 = {} -- teams local teamA = {} local teamB = {} local teamC = {} -- hedgehogs values hero.name = loc("Hog Solo") hero.x = 340 hero.y = 1840 hero.dead = false ally.name = loc("Paul McHoggy") ally.x = 300 ally.y = 1840 bandit1.name = loc("Thanta") bandit1.x = 3240 bandit1.y = 1280 bandit1.dead = false bandit1.frozen = false bandit1.roundsToUnfreeze = 0 bandit2.name = loc("Billy Frost") bandit2.x = 1480 bandit2.y = 1990 bandit3.name = loc("Ice Jake") bandit3.x = 1860 bandit3.y = 1150 bandit4.name = loc("John Snow") bandit4.x = 3200 bandit4.y = 970 bandit4.frozen = false bandit4.roundsToUnfreeze = 0 bandit5.name = loc("White Tee") bandit5.x = 3280 bandit5.y = 600 bandit5.frozen = false bandit5.roundsToUnfreeze = 0 teamA.name = loc("Allies") teamA.color = tonumber("FF0000",16) -- red teamB.name = loc("Frozen Bandits") teamB.color = tonumber("0033FF",16) -- blues teamC.name = loc("Hog Solo") teamC.color = tonumber("38D61C",16) -- green -------------- LuaAPI EVENT HANDLERS ------------------ function onGameInit() Seed = 1 TurnTime = 25000 CaseFreq = 0 MinesNum = 0 MinesTime = 1 Explosives = 0 Delay = 3 Map = "ice01_map" Theme = "Snow" -- get the check point checkPointReached = initCheckpoint("ice01") -- get hero health local heroHealth = 100 if tonumber(GetCampaignVar("HeroHealth")) then heroHealth = tonumber(GetCampaignVar("HeroHealth")) end if heroHealth ~= 100 then heroHealth = heroHealth + 5 if heroHealth > 100 then heroHealth = 100 end SaveCampaignVar("HeroHealth", heroHealth) end -- Hog Solo AddTeam(teamC.name, teamC.color, "Bone", "Island", "HillBilly", "cm_birdy") hero.gear = AddHog(hero.name, 0, heroHealth, "war_desertgrenadier1") AnimSetGearPosition(hero.gear, hero.x, hero.y) HogTurnLeft(hero.gear, true) -- Ally AddTeam(teamA.name, teamA.color, "Bone", "Island", "HillBilly", "cm_birdy") ally.gear = AddHog(ally.name, 0, 100, "war_airwarden02") AnimSetGearPosition(ally.gear, ally.x, ally.y) -- Frozen Bandits AddTeam(teamB.name, teamB.color, "Bone", "Island", "HillBilly", "cm_birdy") bandit1.gear = AddHog(bandit1.name, 1, 120, "Santa") AnimSetGearPosition(bandit1.gear, bandit1.x, bandit1.y) HogTurnLeft(bandit1.gear, true) bandit2.gear = AddHog(bandit2.name, 1, 100, "ushanka") AnimSetGearPosition(bandit2.gear, bandit2.x, bandit2.y) bandit3.gear = AddHog(bandit3.name, 1, 100, "thug") AnimSetGearPosition(bandit3.gear, bandit3.x, bandit3.y) bandit4.gear = AddHog(bandit4.name, 1, 40, "tophats") AnimSetGearPosition(bandit4.gear, bandit4.x, bandit4.y) HogTurnLeft(bandit4.gear, true) bandit5.gear = AddHog(bandit5.name, 1, 40, "Sniper") AnimSetGearPosition(bandit5.gear, bandit5.x, bandit5.y) HogTurnLeft(bandit5.gear, true) if checkPointReached == 1 then -- Start of the game elseif checkPointReached == 2 then iceGunTaken = true AnimSetGearPosition(hero.gear, 840, 1650) elseif checkPointReached == 3 then iceGunTaken = true heroAtFinalStep = true heroVisitedAntiFlyArea = true AnimSetGearPosition(hero.gear, 1450, 910) end AnimInit() AnimationSetup() end function onGameStart() AnimWait(hero.gear, 3000) FollowGear(hero.gear) -- Add mines AddGear(1612, 940, gtMine, 0, 0, 0, 0) AddGear(1622, 945, gtMine, 0, 0, 0, 0) AddGear(1645, 950, gtMine, 0, 0, 0, 0) AddGear(1655, 960, gtMine, 0, 0, 0, 0) AddGear(1665, 965, gtMine, 0, 0, 0, 0) AddGear(1800, 1000, gtMine, 0, 0, 0, 0) AddGear(1810, 1005, gtMine, 0, 0, 0, 0) AddGear(1820, 1010, gtMine, 0, 0, 0, 0) AddGear(1830, 1015, gtMine, 0, 0, 0, 0) AddGear(1840, 1020, gtMine, 0, 0, 0, 0) AddGear(1900, 1020, gtMine, 0, 0, 0, 0) AddGear(1910, 1020, gtMine, 0, 0, 0, 0) AddGear(1920, 1020, gtMine, 0, 0, 0, 0) AddGear(1930, 1030, gtMine, 0, 0, 0, 0) AddGear(1940, 1040, gtMine, 0, 0, 0, 0) AddGear(2130, 1110, gtMine, 0, 0, 0, 0) AddGear(2140, 1120, gtMine, 0, 0, 0, 0) AddGear(2180, 1120, gtMine, 0, 0, 0, 0) AddGear(2200, 1130, gtMine, 0, 0, 0, 0) AddGear(2210, 1130, gtMine, 0, 0, 0, 0) local x=2300 local step=0 while x<3100 do AddGear(x, 1150, gtMine, 0, 0, 0, 0) step = step + 1 if step == 5 then step = 0 x = x + GetRandom(201)+100 else x = x + GetRandom(21)+10 end end AddEvent(onHeroDeath, {hero.gear}, heroDeath, {hero.gear}, 0) AddEvent(onHeroFinalStep, {hero.gear}, heroFinalStep, {hero.gear}, 0) AddEvent(onAntiFlyArea, {hero.gear}, antiFlyArea, {hero.gear}, 1) AddEvent(onAntiFlyAreaVelocity, {hero.gear}, antiFlyAreaVelocity, {hero.gear}, 1) AddEvent(onNonAntiFlyArea, {hero.gear}, nonAntiFlyArea, {hero.gear}, 1) AddEvent(onThantaDeath, {bandit1.gear}, thantaDeath, {bandit1.gear}, 0) AddEvent(onHeroWin, {hero.gear}, heroWin, {hero.gear}, 0) AddAmmo(hero.gear, amJetpack, 99) AddAmmo(bandit1.gear, amBazooka, 5) AddAmmo(bandit2.gear, amBazooka, 4) AddAmmo(bandit3.gear, amMine, 2) AddAmmo(bandit3.gear, amGrenade, 3) AddAmmo(bandit4.gear, amBazooka, 5) AddAmmo(bandit5.gear, amBazooka, 5) goToThantaString = loc("Go to Thanta and get the device part!") if checkPointReached == 1 then AddAmmo(hero.gear, amBazooka, 1) SpawnAmmoCrate(icegunX, icegunY, amIceGun) AddEvent(onColumnCheckPoint, {hero.gear}, columnCheckPoint, {hero.gear}, 0) AddEvent(onHeroAtIceGun, {hero.gear}, heroAtIceGun, {hero.gear}, 0) AddAnim(dialog01) elseif checkPointReached == 2 then AddAmmo(hero.gear, amIceGun, 8) AnimCaption(hero.gear, goToThantaString, 5000) elseif checkPointReached == 3 then AddAmmo(hero.gear, amIceGun, 6) AnimCaption(hero.gear, goToThantaString, 5000) end SendHealthStatsOff() end function onNewTurn() heroDamageAtCurrentTurn = 0 -- round has to start if hero goes near the column if not heroVisitedAntiFlyArea and CurrentHedgehog ~= hero.gear then TurnTimeLeft = 0 elseif not heroVisitedAntiFlyArea and CurrentHedgehog == hero.gear then TurnTimeLeft = -1 elseif not heroAtFinalStep and (CurrentHedgehog == bandit1.gear or CurrentHedgehog == bandit4.gear or CurrentHedgehog == bandit5.gear) then AnimSwitchHog(hero.gear) TurnTimeLeft = 0 elseif heroAtFinalStep and (CurrentHedgehog == bandit2.gear or CurrentHedgehog == bandit3.gear) then if (GetHealth(bandit1.gear) and GetEffect(bandit1.gear,heFrozen) > 256) and ((GetHealth(bandit4.gear) and GetEffect(bandit4.gear,heFrozen) > 256) or not GetHealth(bandit4.gear)) and ((GetHealth(bandit5.gear) and GetEffect(bandit5.gear,heFrozen) > 256) or not GetHealth(bandit5.gear)) then TurnTimeLeft = 0 else AnimSwitchHog(hero.gear) TurnTimeLeft = 0 end elseif CurrentHedgehog == ally.gear then TurnTimeLeft = 0 end -- frozen hogs accounting if CurrentHedgehog == hero.gear and heroAtFinalStep and TurnTimeLeft > 0 then if bandit1.frozen then if bandit1.roundsToUnfreeze == 0 then SetEffect(bandit1.gear, heFrozen, 255) bandit1.frozen = false else bandit1.roundsToUnfreeze = bandit1.roundsToUnfreeze - 1 end end if bandit4.frozen then if bandit4.roundsToUnfreeze == 0 then SetEffect(bandit4.gear, heFrozen, 255) bandit4.frozen = false else bandit4.roundsToUnfreeze = bandit4.roundsToUnfreeze - 1 end end if bandit5.frozen then if bandit5.roundsToUnfreeze == 0 then SetEffect(bandit5.gear, heFrozen, 255) bandit5.frozen = false else bandit5.roundsToUnfreeze = bandit5.roundsToUnfreeze - 1 end end else if bandit1.frozen then SetEffect(bandit1.gear, heFrozen, 9999999999) end if bandit4.frozen then SetEffect(bandit4.gear, heFrozen, 9999999999) end if bandit5.frozen then SetEffect(bandit5.gear, heFrozen, 9999999999) end end end function onGameTick() AnimUnWait() if ShowAnimation() == false then return end ExecuteAfterAnimations() CheckEvents() if GetEffect(bandit1.gear, heFrozen) > 256 and not bandit1.frozen then bandit1.frozen = true SetEffect(bandit1.gear, heFrozen, 9999999999) bandit1.roundsToUnfreeze = 1 end if GetEffect(bandit4.gear, heFrozen) > 256 and not bandit4.frozen then bandit4.frozen = true SetEffect(bandit4.gear, heFrozen, 9999999999) bandit4.roundsToUnfreeze = 2 end if GetEffect(bandit5.gear, heFrozen) > 256 and not bandit5.frozen then bandit5.frozen = true SetEffect(bandit5.gear, heFrozen, 9999999999) bandit5.roundsToUnfreeze = 2 end end function onAmmoStoreInit() SetAmmo(amIceGun, 0, 0, 0, 8) end function onGearDelete(gear) if gear == hero.gear then hero.dead = true elseif gear == bandit1.gear then bandit1.dead = true end end function onPrecise() if GameTime > 3000 then SetAnimSkip(true) end end function onGearDamage(gear, damage) if gear == hero.gear then heroDamageAtCurrentTurn = heroDamageAtCurrentTurn + damage end end -------------- EVENTS ------------------ function onAntiFlyArea(gear) if not hero.dead and (GetX(gear) > 860 or GetY(gear) < 1400) and not heroAtAntiFlyArea then return true end return false end function onAntiFlyAreaVelocity(gear) if not hero.dead and GetY(gear) < 1300 and GetX(gear) < 1190 then return true end return false end function onNonAntiFlyArea(gear) if not hero.dead and (GetX(gear) < 860 and GetY(gear) > 1400) and heroAtAntiFlyArea then return true end return false end function onHeroDeath(gear) if hero.dead then return true end return false end function onHeroFinalStep(gear) if not hero.dead and GetY(gear) < 960 and GetX(gear) > 1400 then return true end return false end function onColumnCheckPoint(gear) if not hero.dead and iceGunTaken and GetX(gear) < 870 and GetX(gear) > 850 and GetY(gear) > 1500 and StoppedGear(gear) then return true end return false end function onHeroAtIceGun(gear) if not hero.dead and GetX(gear) < icegunX+15 and GetX(gear) > icegunX-15 and GetY(gear) > icegunY-15 and GetY(gear) < icegunY+15 then return true end return false end function onThantaDeath(gear) if bandit1.dead then return true end return false end function onHeroWin(gear) if (not hero.dead and not bandit1.dead) and heroDamageAtCurrentTurn == 0 and (GetX(hero.gear)>=GetX(bandit1.gear)-80 and GetX(hero.gear)<=GetX(bandit1.gear)+80) and (GetY(hero.gear)>=GetY(bandit1.gear)-30 and GetY(hero.gear)<=GetY(bandit1.gear)+30) then return true end return false end -------------- ACTIONS ------------------ function antiFlyArea(gear) heroAtAntiFlyArea = true if not heroVisitedAntiFlyArea then TurnTimeLeft = 0 FollowGear(hero.gear) AnimSwitchHog(bandit1.gear) FollowGear(hero.gear) TurnTimeLeft = 0 end AddAmmo(hero.gear, amJetpack, 0) heroVisitedAntiFlyArea = true end function antiFlyAreaVelocity(gear) dx, dy = GetGearVelocity(hero.gear) SetGearVelocity(hero.gear, dx, math.max(dy, 0)) end function nonAntiFlyArea(gear) heroAtAntiFlyArea = false AddAmmo(hero.gear, amJetpack, 99) end function heroDeath(gear) SendStat(siGameResult, loc("Hog Solo lost, try again!")) SendStat(siCustomAchievement, loc("To win the game you have to go next to Thanta")) SendStat(siCustomAchievement, loc("Most of the time you'll be able to use only the icegun")) SendStat(siCustomAchievement, loc("Use the bazooka and the flying saucer to get the icegun")) SendStat(siPlayerKills,'1',teamB.name) SendStat(siPlayerKills,'0',teamC.name) EndGame() end function heroFinalStep(gear) heroAtFinalStep = true saveCheckpoint("3") SaveCampaignVar("HeroHealth", GetHealth(hero.gear)) end function columnCheckPoint(gear) saveCheckpoint("2") SaveCampaignVar("HeroHealth", GetHealth(hero.gear)) AnimCaption(hero.gear, loc("Checkpoint reached!"), 5000) end function heroAtIceGun(gear) iceGunTaken=true end function thantaDeath(gear) SendStat(siGameResult, loc("Hog Solo lost, try again!")) SendStat(siCustomAchievement, loc("Noooo, Thanta has to stay alive!")) SendStat(siCustomAchievement, loc("To win the game you have to go next to Thanta")) SendStat(siCustomAchievement, loc("Most of the time you'll be able to use only the icegun")) SendStat(siCustomAchievement, loc("Use the bazooka and the flying saucer to get the icegun")) SendStat(siPlayerKills,'1',teamB.name) SendStat(siPlayerKills,'0',teamC.name) EndGame() end function heroWin(gear) TurnTimeLeft=0 if GetX(hero.gear) < GetX(bandit1.gear) then HogTurnLeft(bandit1.gear, true) else HogTurnLeft(bandit1.gear, false) end AddAnim(dialog02) end -------------- ANIMATIONS ------------------ function Skipanim(anim) if goals[anim] ~= nil then ShowMission(unpack(goals[anim])) end if anim == dialog02 then actionsOnWin() else AnimSwitchHog(hero.gear) end end function AnimationSetup() -- DIALOG 01 - Start, welcome to moon AddSkipFunction(dialog01, Skipanim, {dialog01}) table.insert(dialog01, {func = AnimWait, args = {hero.gear, 3000}}) table.insert(dialog01, {func = AnimCaption, args = {hero.gear, loc("On the Ice Planet, where ice rules..."), 5000}}) table.insert(dialog01, {func = AnimSay, args = {ally.gear, loc("Finally you are here..."), SAY_SAY, 2000}}) table.insert(dialog01, {func = AnimWait, args = {hero.gear, 2000}}) table.insert(dialog01, {func = AnimSay, args = {hero.gear, loc("Hi! Nice to meet you"), SAY_SAY, 3000}}) table.insert(dialog01, {func = AnimWait, args = {ally.gear, 2000}}) table.insert(dialog01, {func = AnimSay, args = {ally.gear, loc("Listen carefully! The bandit leader, Thanta, has recently found a very strange device"), SAY_SAY, 4000}}) table.insert(dialog01, {func = AnimSay, args = {ally.gear, loc("He doesn't know it but this device is a part of the anti-gravity device"), SAY_SAY, 2500}}) table.insert(dialog01, {func = AnimWait, args = {hero.gear, 8000}}) table.insert(dialog01, {func = AnimSay, args = {hero.gear, loc("Nice, then I should get the part as soon as possible!"), SAY_SAY, 4000}}) table.insert(dialog01, {func = AnimWait, args = {ally.gear, 4000}}) table.insert(dialog01, {func = AnimSay, args = {ally.gear, loc("Be careful, your gadgets won't work in the bandit area. You should get an ice gun"), SAY_SAY, 7000}}) table.insert(dialog01, {func = AnimSay, args = {ally.gear, loc("There is one below us!"), SAY_SAY, 4000}}) table.insert(dialog01, {func = AnimWait, args = {hero.gear, 500}}) table.insert(dialog01, {func = AnimSwitchHog, args = {hero.gear}}) -- DIALOG 02 - Hero got to Thant2 AddSkipFunction(dialog02, Skipanim, {dialog02}) table.insert(dialog02, {func = AnimWait, args = {hero.gear, 3000}}) table.insert(dialog02, {func = AnimCaption, args = {hero.gear, loc("Congratulations, now you can take Thanta's device part..."), 5000}}) table.insert(dialog02, {func = AnimSay, args = {bandit1.gear, loc("Oh! Please spare me. You can take all my treasures!"), SAY_SAY, 3000}}) table.insert(dialog02, {func = AnimWait, args = {hero.gear, 5000}}) table.insert(dialog02, {func = AnimSay, args = {hero.gear, loc("I just want the strange device you found!"), SAY_SAY, 3000}}) table.insert(dialog02, {func = AnimWait, args = {bandit1.gear, 4000}}) table.insert(dialog02, {func = AnimSay, args = {bandit1.gear, loc("Here! Take it..."), SAY_SAY, 3000}}) table.insert(dialog02, {func = actionsOnWin, args = {}}) end -------------- Other Functions ------------------- function actionsOnWin() saveCompletedStatus(4) SendStat(siGameResult, loc("Congratulations, you acquired the device part!")) SendStat(siCustomAchievement, loc("At the end of the game your health was ")..GetHealth(hero.gear)) -- maybe add number of tries for each part? SendStat(siPlayerKills,'1',teamC.name) SendStat(siPlayerKills,'0',teamB.name) EndGame() end
-- file: snake.lua Snake = Object.extend(Object) --- Constructor of Snake Class ---@param segments table ---@param isAlive boolean function Snake:new(segments, isAlive) self.segments = segments self.alive = isAlive self.directionQueue = { 'right' } end --- Execute event by transitions into frames ---@param dt number function Snake:update(dt) Timer = Timer + dt if self.alive then if (Timer >= 0.15) then Timer = 0 if #self.directionQueue > 1 then table.remove(self.directionQueue, 1) end local nextXPosition = self.segments[1].x local nextYPosition = self.segments[1].y if self.directionQueue[1] == 'right' then nextXPosition = nextXPosition + 1 if nextXPosition > GridXCount then nextXPosition = 1 end elseif self.directionQueue[1] == 'left' then nextXPosition = nextXPosition - 1 if nextXPosition < 1 then nextXPosition = GridXCount end elseif self.directionQueue[1] == 'down' then nextYPosition = nextYPosition + 1 if nextYPosition > GridYCount then nextYPosition = 1 end elseif self.directionQueue[1] == 'up' then nextYPosition = nextYPosition - 1 if nextYPosition < 1 then nextYPosition = GridYCount end end local canMove = true for segmentIndex, segment in ipairs(self.segments) do if segmentIndex ~= #self.segments and nextXPosition == segment.x and nextYPosition == segment.y then canMove = false end end if canMove then table.insert(self.segments, 1, { x = nextXPosition, y = nextYPosition }) if self.segments[1].x == FoodObj.position.x and self.segments[1].y == FoodObj.position.y then EatEffectSong:play() MoveFood() else table.remove(self.segments) end else self.alive = false end end elseif Timer >=2 then Reset() end end --- draw elements relationed a snake function Snake:draw() local cellSize = 15 love.graphics.setColor(.28, .28, .28) love.graphics.rectangle("fill", 0, 0, GridXCount * cellSize, GridYCount * cellSize) for _, segment in ipairs(self.segments) do love.graphics.setColor(.6, 1, .32) love.graphics.rectangle( "fill", (segment.x - 1) * cellSize, (segment.y - 1) * cellSize, cellSize - 1, cellSize - 1 ) end love.graphics.setColor(1, .3, .3) love.graphics.rectangle( 'fill', (FoodObj.position.x - 1) * cellSize, (FoodObj.position.y - 1) * cellSize, cellSize - 1, cellSize - 1 ) for _, segment in ipairs(self.segments) do if self.alive then love.graphics.setColor(.6, 1, .32) else love.graphics.setColor(.5, .5, .5) end DrawCell(segment.x, segment.y, cellSize) end love.graphics.setColor(1, .3, .3) DrawCell(FoodObj.position.x, FoodObj.position.y, cellSize) end --- Bind an event when whatever key is pressed ---@param key string function Snake:keypressed(key) if key == 'right' and self.directionQueue[#self.directionQueue] ~= 'right' and self.directionQueue[#self.directionQueue] ~= 'left' then table.insert(self.directionQueue, 'right') elseif key == 'left' and self.directionQueue[#self.directionQueue] ~= 'left' and self.directionQueue[#self.directionQueue] ~= 'right' then table.insert(self.directionQueue, 'left') elseif key == 'down' and self.directionQueue[#self.directionQueue] ~= 'down' and self.directionQueue[#self.directionQueue] ~= 'up' then table.insert(self.directionQueue, 'down') elseif key == 'up' and self.directionQueue[#self.directionQueue] ~= 'up' and self.directionQueue[#self.directionQueue] ~= 'down' then table.insert(self.directionQueue, 'up') end end
local L = require "lpeg" local u = {} function u.inherit(meta) local MT = meta or {} local M = setmetatable({}, MT) M.__index = M local m = setmetatable({}, M) m.__index = m return M, m end function u.export(mod, constructor) mod.__call = constructor return setmetatable({}, mod) end local s = require "status:status" () local epeg = require "orb:util/epeg" local Csp = epeg.Csp local Node = require "espalier/node" local m = require "orb:Orbit/morphemes" local Link = require "orb:Orbit/link" local Richtext = require "orb:Orbit/richtext" local Grammar = require "espalier/grammar" local Pr, pr = u.inherit(Node) Pr.id = "prose" s.chatty = false local function equal_strings(s, i, a, b) -- Returns true if a and b are equal. -- s and i are not used, provided because expected by Cb. return a == b end local function bookends(sigil) local Cg, C, P, Cmt, Cb = L.Cg, L.C, L.P, L.Cmt, L.Cb -- Returns a pair of patterns, _open and _close, -- which will match a brace of sigil. -- sigil must be a string. local _open = Cg(C(P(sigil)^1), sigil .. "_init") local _close = Cmt(C(P(sigil)^1) * Cb(sigil .. "_init"), equal_strings) return _open, _close end local bold_open, bold_close = bookends("*") local italic_open, italic_close = bookends("/") local under_open, under_close = bookends("_") local strike_open, strike_close = bookends("-") local lit_open, lit_close = bookends("=") local inter_open, inter_close = bookends("`") function Pr.toMarkdown(prose) local phrase = "" for _, node in ipairs(prose) do if node.toMarkdown then phrase = phrase .. node:toMarkdown() elseif node.id == "raw" then phrase = phrase .. node:toValue() end end return phrase end local punct = m.punctuation local function prose_gm(_ENV) START "prose" SUPPRESS ("anchorboxed", "urlboxed", "richtext", "literalwrap", "boldwrap", "italicwrap", "interpolwrap") prose = (V"link" + (V"prespace" * V"richtext") + V"raw")^1 link = m.sel * m.WS * V"anchorboxed" * (m._ + m.NL)^0 * V"urlboxed" * m.ser anchorboxed = m.sel * m.WS * V"anchortext" * m.ser urlboxed = m.sel * m.WS * V"url" * m.WS * m.ser anchortext = m.anchor_text url = m.url richtext = (V"literalwrap" + V"boldwrap" + V"italicwrap" + V"interpolwrap") * #(m.WS + m.punctuation) literalwrap = lit_open * V"literal" * lit_close literal = (P(1) - lit_close)^1 -- These are not even close to correct boldwrap = bold_open * V"bold" * bold_close bold = (P(1) - bold_close)^1 italicwrap = italic_open * V"italic" * italic_close italic = (P(1) - italic_close)^1 interpolwrap = inter_open * V"interpolated" * inter_close interpolated = (P(1) - inter_close)^1 -- This may even be true -- This is the catch bucket. raw = (P(1) - (V"link" + (V"prespace" * V"richtext")))^1 -- This is another one. prespace = m._ + m.NL end local function proseBuild(prose, str) return setmetatable(prose, {__index = Pr}) end local proseMetas = { prose = proseBuild, -- prespace = proseBuild, link = Link } for k, v in pairs(Richtext) do proseMetas[k] = v end local parse = Grammar(prose_gm, proseMetas) local function new(Prose, block) local phrase = "\n" for _,l in ipairs(block.lines) do phrase = phrase .. l .. "\n" end local prose = parse(phrase) return prose end return u.export(pr, new)
-- Called OnSpellStart function ElectromagneticPulse(keys) local caster = keys.caster local ability = keys.ability local ability_level = ability:GetLevel() - 1 local mana_to_burn_percent = ability:GetLevelSpecialValueFor("mana_burned", ability_level) local delay = ability:GetLevelSpecialValueFor("delay", ability_level) local radius = ability:GetLevelSpecialValueFor("radius", ability_level) local damage_per_burned_mana_percent = ability:GetLevelSpecialValueFor("damage_per_mana_burned", ability_level) local mana_gained_percent = ability:GetLevelSpecialValueFor("mana_gained_per_mana_burned", ability_level) -- Sounds caster:EmitSound("Hero_Invoker.EMP.Cast") caster:EmitSound("Hero_Invoker.EMP.Charge") -- Particles local emp_effect = ParticleManager:CreateParticle("particles/units/heroes/hero_invoker/invoker_emp.vpcf", PATTACH_ABSORIGIN_FOLLOW, caster) -- Explode the EMP after the delay has passed. Timers:CreateTimer({ endTime = delay, callback = function() ParticleManager:DestroyParticle(emp_effect, false) ParticleManager:ReleaseParticleIndex(emp_effect) local emp_explosion_effect = ParticleManager:CreateParticle("particles/units/heroes/hero_invoker/invoker_emp_explode.vpcf", PATTACH_ABSORIGIN, caster) ParticleManager:ReleaseParticleIndex(emp_explosion_effect) caster:EmitSound("Hero_Invoker.EMP.Discharge") local target_type = bit.bor(DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_HERO) local nearby_enemy_units = FindUnitsInRadius(caster:GetTeamNumber(), caster:GetAbsOrigin(), nil, radius, DOTA_UNIT_TARGET_TEAM_ENEMY, target_type, DOTA_UNIT_TARGET_FLAG_MANA_ONLY, FIND_ANY_ORDER, false) for _, unit in pairs(nearby_enemy_units) do if unit:IsIllusion() then unit:Kill(ability, caster) -- This gives the kill credit to the caster else -- Calculating mana burn value local unit_current_mana = unit:GetMana() local unit_max_mana = unit:GetMaxMana() local mana_to_burn_on_unit = unit_max_mana*mana_to_burn_percent*0.01 if mana_to_burn_on_unit > unit_current_mana then mana_to_burn_on_unit = unit_current_mana end -- Burning Mana (Reducing mana) of the unit unit:ReduceMana(mana_to_burn_on_unit) -- Calculating damage and applying damage to the unit local damage_on_unit = damage_per_burned_mana_percent*mana_to_burn_on_unit ApplyDamage({victim = unit, attacker = caster, ability = ability, damage = damage_on_unit, damage_type = DAMAGE_TYPE_PURE}) -- Restore some of the burnt mana to the caster local mana_gained_from_unit = mana_gained_percent*mana_to_burn_on_unit*0.01 caster:GiveMana(mana_gained_from_unit) end end end }) end
local base_arrow = { visual = "sprite", visual_size = {x = 0.5, y = 0.5}, velocity = 8, textures = {}, tail = 1, -- enable tail tail_texture = "dmobs_ice.png", hit_player = function(self, player) player:punch(self.object, 1.0, { full_punch_interval = 1.0, damage_groups = {fleshy = 8}, }, nil) end, hit_mob = function(self, player) player:punch(self.object, 1.0, { full_punch_interval = 1.0, damage_groups = {fleshy = 8}, }, nil) end, hit_node = function(self, pos, node) self.object:remove() end, } for _,arrowtype in pairs({"ice","lightning","poison"}) do base_arrow.textures = {"dmobs_" .. arrowtype .. ".png"} mobs:register_arrow("dmobs:" .. arrowtype, dmobs.deepclone(base_arrow)) end
if Config.Debug then --- Set fuel in chat -- /fuel <0.100> RegisterCommand('fuel', function(_, args, _) local level = args[1] local vehicle = GetPlayersLastVehicle() if vehicle then SetVehicleFuelLevel(vehicle, level / 1.0) -- needs to be float end end) --- Spawns teslax for testing -- Requires wtf_teslax resource to be installed and started RegisterCommand('teslax', function() local modelHash = GetHashKey('teslax') RequestModel(modelHash) Citizen.CreateThread(function() local t = 0 while not HasModelLoaded(modelHash) do Citizen.Wait(100) t = t + 100 if t > 5000 then SetNotificationTextEntry("STRING") AddTextComponentSubstringPlayerName("/teslax failed. The resource must be installed and started.") DrawNotification(false, false) break end end local ped = GetPlayerPed(-1) local vehicle = CreateVehicle(modelHash, GetEntityCoords(ped), GetEntityHeading(ped), 1, 0) SetVehicleOnGroundProperly(vehicle) SetPedIntoVehicle(ped, vehicle, -1) SetModelAsNoLongerNeeded(modelHash) end) end) end
-- SemVer parser by hugeblank https://github.com/hugeblank -- Parses strings that meet SemVer 2.0.0 specs as documented here: https://semver.org/spec/v2.0.0.html -- Feel free to use/redistribute/modify this file. Should you do so keep the above 3 lines as they are. -- Any strings that don't meet SemVer specs the parse will return false, and the rule number violated -- If successful, parser will return a table that can be compared with other SemVer tables. local this, meta = {}, {} meta.__eq = function(in1, in2) local recurse_tag = function(ver1, ver2) if #ver1 ~= #ver2 then return false, 1 else for i = 1, #ver1 do if ver1[i] ~= ver2[i] then return false, 2 end end end if ver1.tag and ver2.tag then return recurse_tag(ver1.tag, ver2.tag) elseif (ver1.tag and not ver2.tag) or (ver2.tag and not ver1.tag) then return false, 3 else return true, 4 end end return recurse_tag(in1, in2) end meta.__lt = function(in1, in2) local recurse_tag = function(ver1, ver2) if #ver1 < #ver2 then return true end for i = 1, #ver1 do if ver1[i] ~= ver2[i] then if ver1[i] < ver2[i] then return true else return false end end end if ver1.tag and ver2.tag then return recurse_tag(ver1, ver2) elseif ver1.tag and not ver2.tag then return true elseif (ver2.tag and not ver1.tag) then return false else return false end end return recurse_tag(in1, in2) end meta.__le = function(in1, in2) if meta.__eq(in1, in2) then return true else return meta.__lt(in1, in2) end end meta.__tostring = function(in1) local out = table.concat(in1, ".") if in1.tag then out = out.."-"..table.concat(in1.tag, ".") end if in1.meta then out = out.."+"..table.concat(in1.meta, ".") end return out end this.parse = function(str) local out = {} local param = "" local mode = "release" for char in str:gmatch(".") do if mode == "release" then if char:find("%d") then param = param..char elseif char == "." then if #param == 0 or not tostring(tonumber(param)) == param then return false, 2 end out[#out+1] = tonumber(param) param = "" elseif char == "-" and not out.meta then if #param > 0 then out[#out+1] = tonumber(param) param = "" end if not out.tag then mode = "patch" out.tag = {} end elseif char == "+" then if #param > 0 then out[#out+1] = tonumber(param) param = "" end if not out.meta then mode = "meta" out.meta = {} end else return false, 2 end elseif mode == "patch" then if char:find("%w") then param = param..char elseif char == "." then if #param == 0 then return false, 9 end out.tag[#out.tag+1] = param param = "" elseif char == "+" then if #param > 0 then out.tag[#out.tag+1] = param param = "" end if not out.meta then mode = "meta" out.meta = {} end else return false, 9 end elseif mode == "meta" then if char == "." then if #param == 0 then return false, 10 end out.meta[#out.meta+1] = param param = "" end if char:find("%w") then param = param..char end else error("Invalid Semver syntax (Column "..str:find(char)..")", 2) end end if #param > 0 then if mode == "release" then out[#out+1] = tonumber(param) elseif mode == "patch" then out.tag[#out.tag+1] = param elseif mode == "meta" then out.meta[#out.meta+1] = param end end if #out < 3 then return false, 2 elseif out.tag and #out.tag == 0 then return false, 9 elseif out.meta and #out.meta == 0 then return false, 10 end return setmetatable(out, meta) end return this
-- idk who might need it, but: -- incredible-gmod.ru if not (debug.getmetatable(hook) and debug.getmetatable(hook).__call) then return end setmetatable(hook, {__call = function(self, v) return { Add = function(self, name, func) hook.Add(v, name, func) return self end } end}) --[[ EXAPLE: hook("HUDPaint") :Add("Text", function() draw.SimpleText("Hello world", "Default", ScrW() * 0.5, 32, color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER) end) :Add("Box", function() surface.SetDrawColor(0, 0, 0, 200) surface.DrawRect(ScrW() * 0.5 - 64, 16, 128, 32) end) ]]--
local osmose = require 'osmose' local et = osmose.Model 'Chimney' ---------- -- User parameters ---------- et.inputs = { -- Exhaust gas coming from the engine T_TC_OUT_M = {default=350, unit='C'}, T_TC_OUT_L = {default=400, unit='C'}, LOAD_SHIFT_LM = {default = 0.51, unit = '-'}, -- The shift load between the low load and high medium operations T_EG_OUT_MIN = {default=150, unit='C'}, -- Environment COOL_TIN = {default=25, unit='°C'}, -- Environmental temperature COOL_TOUT = {default=25, unit='°C'}, -- Same as above COOL_QMAX = {default=200000, unit='kW'}, -- Very high value, the environment can basically absorb as much heat as possible -- Heat recovery boiler, if present QMAX = {default=0, unit='kW'} } ----------- -- Calculated parameters ----------- et.outputs = { } ------------ -- Equations ------------ --Add equations et:addEquations { eq_112 = { statement = string.format("subject to %s {p in Periods, t in TimesOfPeriod[p]}: \n\t Units_Use_t[%s,p,t] + Units_Use_t[%s,p,t] <= 1;",'ChimneyMultiUnit_neq','ChimneyL','ChimneyM'), param = {}, addToProblem=1, type ='ampl' }, } ----------- -- Layers ----------- et:addLayers {ExhaustGas = {type= 'ResourceBalance', unit = 'kW'} } ----------- -- Units ----------- -- The main scope of the unit "chimney" is basically to convert the mass flow to a qt et:addUnit('ChimneyM',{type='Utility', Fmin = 0, Fmax = 'LOAD_SHIFT_LM', Cost1=0, Cost2=0, Cinv1=0, Cinv2=0, Power1=0, Power2=0, Impact1=0,Impact2=0}) et['ChimneyM']:addStreams{ -- Exhaust gas exhaust_gas = rs({'ExhaustGas','in','COOL_QMAX'}), -- Heat qt = qt({tin = 'T_TC_OUT_M', hin = 'COOL_QMAX', tout='T_EG_OUT_MIN', hout=0, dtmin=0}) } et:addUnit('ChimneyL',{type='Utility', Fmin = 'LOAD_SHIFT_LM', Fmax = 1, Cost1=0, Cost2=0, Cinv1=0, Cinv2=0, Power1=0, Power2=0, Impact1=0,Impact2=0}) et['ChimneyL']:addStreams{ -- Exhaust gas exhaust_gas = rs({'ExhaustGas','in','COOL_QMAX'}), -- Heat qt = qt({tin = 'T_TC_OUT_L', hin = 'COOL_QMAX', tout='T_EG_OUT_MIN', hout=0, dtmin=0}) } et:addUnit('Environment',{type='Utility', Fmin = 0, Fmax = 1, Cost1=0, Cost2=0, Cinv1=0, Cinv2=0, Power1=0, Power2=0, Impact1=0,Impact2=0}) et['Environment']:addStreams{ -- Heat qt = qt({tin = 'COOL_TIN', hin = 0, tout='COOL_TOUT', hout='COOL_QMAX', dtmin=0}) } return et
local Object = require 'libs.classic' local Piece = Object:extend() function Piece:new(shape, rotation, position, block_offsets, gravity, lock_delay, skin, colour, big) self.shape = shape self.rotation = rotation self.position = position self.block_offsets = block_offsets self.gravity = gravity self.lock_delay = lock_delay self.skin = skin self.colour = colour self.ghost = false self.locked = false self.big = big end -- Functions that return a new piece to test in rotation systems. function Piece:withOffset(offset) return Piece( self.shape, self.rotation, {x = self.position.x + offset.x, y = self.position.y + offset.y}, self.block_offsets, self.gravity, self.lock_delay, self.skin, self.colour, self.big ) end function Piece:withRelativeRotation(rot) local new_rot = self.rotation + rot while new_rot < 0 do new_rot = new_rot + 4 end while new_rot >= 4 do new_rot = new_rot - 4 end return Piece( self.shape, new_rot, self.position, self.block_offsets, self.gravity, self.lock_delay, self.skin, self.colour, self.big ) end -- Functions that return predicates relative to a grid. function Piece:getBlockOffsets() return self.block_offsets[self.shape][self.rotation + 1] end function Piece:occupiesSquare(x, y) local offsets = self:getBlockOffsets() for index, offset in pairs(offsets) do local new_offset = {x = self.position.x + offset.x, y = self.position.y + offset.y} if new_offset.x == x and new_offset.y == y then return true end end return false end function Piece:isMoveBlocked(grid, offset) local moved_piece = self:withOffset(offset) return not grid:canPlacePiece(moved_piece) end function Piece:isDropBlocked(grid) return self:isMoveBlocked(grid, { x=0, y=1 }) end -- Procedures to actually do stuff to pieces. function Piece:setOffset(offset) self.position.x = self.position.x + offset.x self.position.y = self.position.y + offset.y return self end function Piece:setRelativeRotation(rot) new_rot = self.rotation + rot while new_rot < 0 do new_rot = new_rot + 4 end while new_rot >= 4 do new_rot = new_rot - 4 end self.rotation = new_rot return self end function Piece:moveInGrid(step, squares, grid, instant) local moved = false for x = 1, squares do if grid:canPlacePiece(self:withOffset(step)) then moved = true self:setOffset(step) if instant then self:dropToBottom(grid) end else break end end if moved and step.y == 0 then playSE("move") end return self end function Piece:dropSquares(dropped_squares, grid) self:moveInGrid({ x = 0, y = 1 }, dropped_squares, grid) end function Piece:dropToBottom(grid) local piece_y = self.position.y self:dropSquares(math.huge, grid) self.gravity = 0 if self.position.y > piece_y then if self.ghost == false then playSE("bottom") end -- self.lock_delay = 0 end return self end function Piece:lockIfBottomed(grid) if self:isDropBlocked(grid) then self.locked = true end return self end function Piece:addGravity(gravity, grid, classic_lock) gravity = gravity / (self.big and 2 or 1) local new_gravity = self.gravity + gravity if self:isDropBlocked(grid) then if classic_lock then self.gravity = new_gravity else self.gravity = 0 self.lock_delay = self.lock_delay + 1 end elseif not ( self:isMoveBlocked(grid, { x=0, y=-1 }) and gravity < 0 ) then local dropped_squares = math.floor(math.abs(new_gravity)) if gravity >= 0 then local new_frac_gravity = new_gravity - dropped_squares self.gravity = new_frac_gravity self:dropSquares(dropped_squares, grid) if self:isDropBlocked(grid) then playSE("bottom") end else local new_frac_gravity = new_gravity + dropped_squares self.gravity = new_frac_gravity self:moveInGrid({ x=0, y=-1 }, dropped_squares, grid) if self:isMoveBlocked(grid, { x=0, y=-1 }) then playSE("bottom") end end else self.gravity = 0 end return self end -- Procedures for drawing. function Piece:draw(opacity, brightness, grid, partial_das) if opacity == nil then opacity = 1 end if brightness == nil then brightness = 1 end love.graphics.setColor(brightness, brightness, brightness, opacity) local offsets = self:getBlockOffsets() local gravity_offset = 0 if config.gamesettings.smooth_movement == 1 and grid ~= nil and not self:isDropBlocked(grid) then gravity_offset = self.gravity * 16 end if partial_das == nil then partial_das = 0 end for index, offset in pairs(offsets) do local x = self.position.x + offset.x local y = self.position.y + offset.y if self.big then love.graphics.draw( blocks[self.skin][self.colour], 64+x*32+partial_das*2, 16+y*32+gravity_offset*2, 0, 2, 2 ) else love.graphics.draw( blocks[self.skin][self.colour], 64+x*16+partial_das, 16+y*16+gravity_offset ) end end return false end return Piece
-- pwd -- print(shell.pwd())
---@class Cursor C_Cursor = {} function C_Cursor.DropCursorCommunitiesStream() end ---@return string, string clubId, streamId function C_Cursor.GetCursorCommunitiesStream() end ---@return table item function C_Cursor.GetCursorItem() end ---@param clubId string ---@param streamId string function C_Cursor.SetCursorCommunitiesStream(clubId, streamId) end ---@class UICursorType local UICursorType = {} UICursorType.Default = 0 UICursorType.Item = 1 UICursorType.Money = 2 UICursorType.Spell = 3 UICursorType.PetAction = 4 UICursorType.Merchant = 5 UICursorType.ActionBar = 6 UICursorType.Macro = 7 UICursorType.AmmoObsolete = 9 UICursorType.Pet = 10 UICursorType.GuildBank = 11 UICursorType.GuildBankMoney = 12 UICursorType.EquipmentSet = 13 UICursorType.Currency = 14 UICursorType.Flyout = 15 UICursorType.VoidItem = 16 UICursorType.BattlePet = 17 UICursorType.Mount = 18 UICursorType.Toy = 19 UICursorType.CommunitiesStream = 20 UICursorType.ConduitCollectionItem = 21
local ffi = require 'ffi' ffi.cdef[[ struct sd_html_renderopt { struct { int header_count; int current_level; int level_offset; } toc_data; unsigned int flags; /* extra callbacks */ void (*link_attributes)(struct sd_buf *ob, const struct sd_buf *url, void *self); }; typedef enum { HTML_SKIP_HTML = (1 << 0), HTML_SKIP_STYLE = (1 << 1), HTML_SKIP_IMAGES = (1 << 2), HTML_SKIP_LINKS = (1 << 3), HTML_EXPAND_TABS = (1 << 4), HTML_SAFELINK = (1 << 5), HTML_TOC = (1 << 6), HTML_HARD_WRAP = (1 << 7), HTML_USE_XHTML = (1 << 8), HTML_ESCAPE = (1 << 9), } sd_html_render_mode; typedef enum { HTML_TAG_NONE = 0, HTML_TAG_OPEN, HTML_TAG_CLOSE, } sd_html_tag; int sd_html_is_tag(const uint8_t *tag_data, size_t tag_size, const char *tagname); void sd_html_renderer(struct sd_callbacks *callbacks, struct sd_html_renderopt *options_ptr, unsigned int render_flags); void sd_html_toc_renderer(struct sd_callbacks *callbacks, struct sd_html_renderopt *options_ptr); void sd_html_smartypants(struct sd_buf *ob, const uint8_t *text, size_t size); ]]
-- N-body benchmark from benchmarks game -- https://benchmarksgame-team.pages.debian.net/benchmarksgame/description/nbody.html -- -- Original code by Mike Pall and Geoff Leyland, with modifications by Hugo -- Gualandi for correctness, clarity, and compatibility with Pallene. -- * Fix implementation of advance() to use two outer loops. -- * Use #xs instead of passing "n" as a parameter to all the functions -- * Use math.math.sqrt instead of caching math.sqrt in a local variable -- * Use 0.0 instead of 0 where appropriate. -- * Don't use multiple assignments. -- -- Expected output (N = 1000): -- -0.169075164 -- -0.169087605 -- -- Expected output (N = 50000000): -- -0.169075164 -- -0.169059907 local function new_body(x, y, z, vx, vy, vz, mass) return { x = x, y = y, z = z, vx = vx, vy = vy, vz = vz, mass = mass, } end local function offset_momentum(bodies) local n = #bodies local px = 0.0 local py = 0.0 local pz = 0.0 for i= 1, n do local bi = bodies[i] local bim = bi.mass px = px + (bi.vx * bim) py = py + (bi.vy * bim) pz = pz + (bi.vz * bim) end local sun = bodies[1] local solar_mass = sun.mass sun.vx = sun.vx - px / solar_mass sun.vy = sun.vy - py / solar_mass sun.vz = sun.vz - pz / solar_mass end local function advance(bodies, dt) local n = #bodies for i = 1, n do local bi = bodies[i] for j=i+1,n do local bj = bodies[j] local dx = bi.x - bj.x local dy = bi.y - bj.y local dz = bi.z - bj.z local dist = math.sqrt(dx*dx + dy*dy + dz*dz) local mag = dt / (dist * dist * dist) local bjm = bj.mass * mag bi.vx = bi.vx - (dx * bjm) bi.vy = bi.vy - (dy * bjm) bi.vz = bi.vz - (dz * bjm) local bim = bi.mass * mag bj.vx = bj.vx + (dx * bim) bj.vy = bj.vy + (dy * bim) bj.vz = bj.vz + (dz * bim) end end for i = 1, n do local bi = bodies[i] bi.x = bi.x + dt * bi.vx bi.y = bi.y + dt * bi.vy bi.z = bi.z + dt * bi.vz end end local function advance_multiple_steps(nsteps, bodies, dt) for _ = 1, nsteps do advance(bodies, dt) end end local function energy(bodies) local n = #bodies local e = 0.0 for i = 1, n do local bi = bodies[i] local vx = bi.vx local vy = bi.vy local vz = bi.vz e = e + (0.5 * bi.mass * (vx*vx + vy*vy + vz*vz)) for j = i+1, n do local bj = bodies[j] local dx = bi.x-bj.x local dy = bi.y-bj.y local dz = bi.z-bj.z local distance = math.sqrt(dx*dx + dy*dy + dz*dz) e = e - ((bi.mass * bj.mass) / distance) end end return e end local PI = 3.141592653589793 local SOLAR_MASS = 4 * PI * PI local DAYS_PER_YEAR = 365.24 local bodies = { -- Sun new_body( 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, SOLAR_MASS), -- Jupiter new_body( 4.84143144246472090e+00, -1.16032004402742839e+00, -1.03622044471123109e-01, 1.66007664274403694e-03 * DAYS_PER_YEAR, 7.69901118419740425e-03 * DAYS_PER_YEAR, -6.90460016972063023e-05 * DAYS_PER_YEAR, 9.54791938424326609e-04 * SOLAR_MASS ), -- Saturn new_body( 8.34336671824457987e+00, 4.12479856412430479e+00, -4.03523417114321381e-01, -2.76742510726862411e-03 * DAYS_PER_YEAR, 4.99852801234917238e-03 * DAYS_PER_YEAR, 2.30417297573763929e-05 * DAYS_PER_YEAR, 2.85885980666130812e-04 * SOLAR_MASS ), -- Uranus new_body( 1.28943695621391310e+01, -1.51111514016986312e+01, -2.23307578892655734e-01, 2.96460137564761618e-03 * DAYS_PER_YEAR, 2.37847173959480950e-03 * DAYS_PER_YEAR, -2.96589568540237556e-05 * DAYS_PER_YEAR, 4.36624404335156298e-05 * SOLAR_MASS ), -- Neptune new_body( 1.53796971148509165e+01, -2.59193146099879641e+01, 1.79258772950371181e-01, 2.68067772490389322e-03 * DAYS_PER_YEAR, 1.62824170038242295e-03 * DAYS_PER_YEAR, -9.51592254519715870e-05 * DAYS_PER_YEAR, 5.15138902046611451e-05 * SOLAR_MASS ), } return function (N) N = N or 50000000 offset_momentum(bodies) print(string.format("%0.9f", energy(bodies))) advance_multiple_steps(N, bodies, 0.01) print(string.format("%0.9f", energy(bodies))) end
-------------------------------------------------------------------------------- ------------------------------ ##### ## ------------------------------ ------------------------------ ## ## # ## ------------------------------ ------------------------------ ## ## ## ## ------------------------------ ------------------------------ ## ## # ## ------------------------------ ------------------------------ ##### ### ###### ------------------------------ -------------------------------- -------------------------------- ----------------------- An Object Request Broker in Lua ------------------------ -------------------------------------------------------------------------------- -- Project: OiL - ORB in Lua -- -- Release: 0.5 -- -- Title : Client-side CORBA GIOP Protocol specific to IIOP -- -- Authors: Renato Maia <maia@inf.puc-rio.br> -- -------------------------------------------------------------------------------- -- channels:Facet -- channel:object retieve(configs:table) -- channel:object select(channel|configs...) -- configs:table default(configs:table) -- -- sockets:Receptacle -- socket:object tcp() -- input:table, output:table select([input:table], [output:table], [timeout:number]) -------------------------------------------------------------------------------- local getmetatable = getmetatable local pairs = pairs local tonumber = tonumber local tostring = tostring local rawget = rawget local rawset = rawset local table = require "loop.table" local StringStream = require "loop.serial.StringStream" local oo = require "oil.oo" local Codec = require "oil.ludo.Codec" --[[VERBOSE]] local verbose = require "oil.verbose" module "oil.ludo.CodecByRef" oo.class(_M, Codec) -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- TODO:[maia] copied from loop.serial.Serializer. Make it a member function local function getidfor(value) local meta = getmetatable(value) local backup if meta then backup = rawget(meta, "__tostring") if backup ~= nil then rawset(meta, "__tostring", nil) end end local id = tostring(value):match("%l+: (%w+)") if meta then if backup ~= nil then rawset(meta, "__tostring", backup) end end return tonumber(id, 16) or id end local function serialproxy(self, value, id) --[[VERBOSE]] verbose:marshal("marshalling proxy for value ",value) self[value] = self.namespace..":value("..id..")" self:write(self.namespace,":value(",id,",'table',") self:write("proxies:resolve(") local reference = self.servants:register(value).__reference StringStream.table(self, reference, getidfor(reference)) self:write("))") end local function serialtable(self, value, id) --[[VERBOSE]] verbose:marshal(true, "marshalling of table ",value) local reference = rawget(value, "__reference") if reference then --[[VERBOSE]] verbose:marshal "table is a proxy" self[value] = self.namespace..":value("..id..")" self:write(self.namespace,":value(",id,",'table',") self:write("proxies:resolve(") StringStream.table(self, reference, getidfor(reference)) self:write("))") else local meta = getmetatable(value) if meta and meta.__marshalcopy then --[[VERBOSE]] verbose:marshal "table by copy" StringStream.table(self, value, id) else --[[VERBOSE]] verbose:marshal "table by reference" serialproxy(self, value, id) end --[[VERBOSE]] verbose:marshal(false) end end local LuDOStream = oo.class({ table = serialtable, thread = serialproxy, userdata = serialproxy, ["function"] = serialproxy, }, StringStream) function encoder(self) return LuDOStream(table.copy(self.names, {servants = self.servants})) end function decoder(self, stream) return StringStream{ environment = table.copy(self.values, {proxies = self.proxies}), data = stream, } end
----------------------------------- -- Area: Apollyon NE -- Mob: Goobbue Harvester ----------------------------------- require("scripts/globals/limbus") require("scripts/globals/pathfind") local ID = require("scripts/zones/Apollyon/IDs") local flags = tpz.path.flag.NONE local path = { {424.271, 0.000, 22.975}, {496.692, 0.000, 22.934} } function onMobRoam(mob) local pause = mob:getLocalVar("pause") if pause < os.time() then local point = (mob:getLocalVar("point") % 2)+1 mob:setLocalVar("point", point) mob:pathTo(path[point][1], path[point][2], path[point][3], flags) mob:setLocalVar("pause", os.time()+40) end end function onMobDeath(mob, player, isKiller, noKiller) if isKiller or noKiller then local battlefield = mob:getBattlefield() local randomF1 = battlefield:getLocalVar("randomF1") if randomF1 == 2 or randomF1 == 4 then local mobX = mob:getXPos() local mobY = mob:getYPos() local mobZ = mob:getZPos() GetNPCByID(ID.npc.APOLLYON_NE_CRATE[1][1]):setPos(mobX, mobY, mobZ) GetNPCByID(ID.npc.APOLLYON_NE_CRATE[1][1]):setStatus(tpz.status.NORMAL) elseif randomF1 == 1 or randomF1 == 3 then battlefield:setLocalVar("randomF2", ID.mob.APOLLYON_NE_MOB[2]+math.random(0,2)) tpz.limbus.handleDoors(battlefield, true, ID.npc.APOLLYON_NE_PORTAL[1]) end end end
Matrix = Matrix or {} Matrix.__index = Matrix function Matrix.new(row, col) local self = {} self.row = row self.col = col for i = 0, self.row - 1 do self[i] = {} for j = 0, self.col - 1 do self[i][j] = 0 end end setmetatable(self, Matrix) return self end function Matrix.__mul(a, b) local type_a = type(a) local type_b = type(b) if type_a == type_b then return a:mul(b) elseif type_a == "number" then return b:mulNum(a) elseif type_b == "number" then return a:mulNum(b) end end function Matrix:mulNum(num) local new_mat = Matrix.new(self.row, self.col) for i = 0, self.row - 1 do for j = 0, self.col - 1 do new_mat[i][j] = self[i][j] * num end end return new_mat end function Matrix:mul(matrix) if self.col ~= matrix.row then return end local new_mat = Matrix.new(self.row, matrix.col) for i = 0, self.row - 1 do new_mat[i] = {} for j = 0, matrix.col - 1 do new_mat[i][j] = 0 for k = 0, self.col - 1 do new_mat[i][j] = new_mat[i][j] + self[i][k] * matrix[k][j] end end end return new_mat end -- 转置矩阵 function Matrix:transpose() local new_mat = Matrix.new(self.col, self.row) for i = 0, self.col - 1 do for j = 0, self.row - 1 do new_mat[i][j] = self[j][i] end end return new_mat end -- 逆矩阵 function Matrix:inverse() local det = self:determinant() if det == nil or det == 0 then return nil end local new_mat = Matrix.new(self.row, self.col) for i = 0, self.row - 1 do for j = 0, self.col - 1 do new_mat[i][j] = self:cofactor(j, i) end end return (1 / det) * new_mat end -- 行列式 function Matrix:determinant() if self.row ~= self.col then return end local det = 0 if self.row == 2 then det = self[0][0] * self[1][1] - self[0][1] * self[1][0] else local row = 0 for i = 0, self.col - 1 do det = det + self[row][i] * self:cofactor(row, i) end end return det end -- 余子式 function Matrix:cofactor(i, j) local sign = (i + j) % 2 == 0 and 1 or -1 local mat = Matrix.new(self.row - 1, self.col - 1) local index = 0 for r = 0, self.row - 1 do for c = 0, self.col - 1 do if r ~= i and c ~= j then local x = math.floor(index / (self.row - 1)) local y = index % (self.col - 1) mat[x][y] = self[r][c] index = index + 1 end end end return sign * mat:determinant() end function Matrix.__tostring(matrix) local str = "[ \n" for i = 0, matrix.row - 1 do local row = "" for j = 0, matrix.col - 1 do row = row .. matrix[i][j] .. (j == matrix.col - 1 and "" or ",") end str = str .. row .. "\n" end return str .. " ]" end local mat1 = Matrix.new(4, 4) mat1[0] = {[0] = 1, [1] = 0, [2] = 0, [3] = 1} mat1[1] = {[0] = 0, [1] = 1, [2] = 0, [3] = 1} mat1[2] = {[0] = 0, [1] = 0, [2] = 1, [3] = 1} mat1[3] = {[0] = 0, [1] = 0, [2] = 0, [3] = 1} local mat2 = Matrix.new(3, 3) mat2[0] = {[0] = 0, [1] = 1, [2] = 2} mat2[1] = {[0] = 3, [1] = 4, [2] = 5} mat2[2] = {[0] = 6, [1] = 7, [2] = 8} local mat3 = Matrix.new(3, 3) mat3[0] = {[0] = 1, [1] = 1, [2] = 2} mat3[1] = {[0] = 1, [1] = 3, [2] = 4} mat3[2] = {[0] = 0, [1] = 2, [2] = 5} print(mat3:inverse())
local isreadable = require "isreadable" local t = require "testhelper" io.open( "isreadable.txt", "wb" ):close() t( isreadable( "isreadable.txt" ), true ) os.remove( "isreadable.txt" ) t( isreadable( "isreadable.txt" ), false ) t.test_embedded_example() t()
package.cpath = "./cservice/?.so;./luaclib/?.so" package.path = "lualib/?.lua" local socket = require "clientsocket" local cjson = require "cjson" --local skynet = require "skynet" local i = 50 local fd = assert(socket.connect("127.0.0.1",9999)) print(".....fd is :",fd) --local sampleJson = [[{"age":"23","testArray":{"array":"12"},"Himi":"himigame.com"}]] local jsontable = {} local array = {} array["age"] = 100 array["firstname"] = "tang" jsontable["name"] = "tkx" jsontable["array"] = array local jsonstr = cjson.encode(jsontable) local package = string.pack(">s2", jsonstr) socket.send(fd, package) print('ok') --socket.write(fd,net) --print(socket.recv(fd))
local parser = require("moocscript.parser") local compile = require("moocscript.compile") describe("test success #repeat", function() local mnstr=[[ a = 1 repeat { a += 2; if a >= 10 { break } } until {} and fn(){}; return a ]] local ret, ast = parser.parse(mnstr) it("should get ast", function() assert.is_true(ret) assert.is_true(type(ast) == "table") end) local ret, content = compile.compile({}, ast) it("should get compiled lua", function() assert.is_true(ret) assert.is_true(type(content) == "string") end) local f = load(content, "test", "t") it("should get function", function() assert(type(f) == "function") local a = f() assert.is_equal(a, 3) end) end) describe("test failed #repeat", function() local mnstr=[[ repeat { } until c ]] local ret, ast = parser.parse(mnstr) it("should get ast", function() assert.is_true(ret) assert.is_true(type(ast) == "table") end) it("has error", function() local ret, content = compile.compile({}, ast) assert.is_false(ret) assert.is_equal(content, "_:2: } until c <undefined variable 'c'>") end) end)
local pairs = pairs; local tostring = tostring; local tonumber = tonumber; local tinsert = table.insert; local twipe = table.wipe; local VUHDO_ACTIVE_TRACE_SPELLS = { -- [<unit GUID>] = { -- ["latest"] = <latest trace spell ID>, -- ["spells"] = { -- [<spell ID>] = { -- ["icon"] = <spell icon>, -- ["startTime"] = <epoch time event received>, -- }, -- }, -- }, }; local VUHDO_TRAIL_OF_LIGHT_SPELL_ID = 200128; local VUHDO_SPELL_TRACE_TRAIL_OF_LIGHT = { }; local sIsPlayerKnowsTrailOfLight = false; local sCurrentPlayerTrailOfLight = nil; local sTrailOfLightIcon = nil; -- local VUHDO_PLAYER_GUID = -1; local VUHDO_RAID_GUIDS = { }; local VUHDO_INTERNAL_TOGGLES = { }; local sShowSpellTrace = nil; local sShowTrailOfLight = nil; local sSpellTraceStoredSettings = nil; local sSpellTraceDefaultDuration = nil; function VUHDO_spellTraceInitLocalOverrides() VUHDO_PLAYER_GUID = UnitGUID("player"); VUHDO_RAID_GUIDS = _G["VUHDO_RAID_GUIDS"]; VUHDO_INTERNAL_TOGGLES = _G["VUHDO_INTERNAL_TOGGLES"]; sShowSpellTrace = VUHDO_CONFIG["SHOW_SPELL_TRACE"]; sSpellTraceStoredSettings = VUHDO_CONFIG["SPELL_TRACE"]["STORED_SETTINGS"]; sSpellTraceDefaultDuration = VUHDO_CONFIG["SPELL_TRACE"]["duration"]; sShowTrailOfLight = VUHDO_CONFIG["SPELL_TRACE"]["showTrailOfLight"]; VUHDO_setKnowsTrailOfLight(VUHDO_isTalentKnown(VUHDO_SPELL_ID.TRAIL_OF_LIGHT)); end -- function VUHDO_setKnowsTrailOfLight(aKnowsTrailOfLight) sIsPlayerKnowsTrailOfLight = aKnowsTrailOfLight; if aKnowsTrailOfLight then _, _, sTrailOfLightIcon = GetSpellInfo(VUHDO_TRAIL_OF_LIGHT_SPELL_ID); else twipe(VUHDO_SPELL_TRACE_TRAIL_OF_LIGHT); local tPreviousPlayerTrailOfLight = sCurrentPlayerTrailOfLight; sCurrentPlayerTrailOfLight = nil; if tPreviousPlayerTrailOfLight and VUHDO_RAID_GUIDS[tPreviousPlayerTrailOfLight] then VUHDO_updateBouquetsForEvent( VUHDO_RAID_GUIDS[tPreviousPlayerTrailOfLight], VUHDO_UPDATE_SPELL_TRACE ); end VUHDO_updateBouquetsForEvent("target", VUHDO_UPDATE_SPELL_TRACE); VUHDO_updateBouquetsForEvent("focus", VUHDO_UPDATE_SPELL_TRACE); end end -- function VUHDO_parseCombatLogSpellTrace(aMessage, aSrcGuid, aDstGuid, aSpellName, aSpellId, anAmount) -- ensure table keys are always strings local tSpellId = tostring(aSpellId); if not VUHDO_INTERNAL_TOGGLES[37] or not sShowSpellTrace or (aMessage ~= "SPELL_HEAL" and aMessage ~= "SPELL_PERIODIC_HEAL") then return; end -- special tracking for Holy Priest "Trail of Light" if sShowTrailOfLight and sIsPlayerKnowsTrailOfLight and aSrcGuid == VUHDO_PLAYER_GUID and aSpellName == VUHDO_SPELL_ID.FLASH_HEAL then if not VUHDO_SPELL_TRACE_TRAIL_OF_LIGHT[1] or (VUHDO_SPELL_TRACE_TRAIL_OF_LIGHT[1] and VUHDO_SPELL_TRACE_TRAIL_OF_LIGHT[1][2] ~= aDstGuid) then tinsert( VUHDO_SPELL_TRACE_TRAIL_OF_LIGHT, { anAmount, aDstGuid } ); end local flashHeal1 = VUHDO_SPELL_TRACE_TRAIL_OF_LIGHT[1]; local flashHeal2 = VUHDO_SPELL_TRACE_TRAIL_OF_LIGHT[2]; if flashHeal1 and flashHeal2 then local tPreviousPlayerTrailOfLight = sCurrentPlayerTrailOfLight; sCurrentPlayerTrailOfLight = flashHeal1[2]; tremove(VUHDO_SPELL_TRACE_TRAIL_OF_LIGHT, 2); VUHDO_SPELL_TRACE_TRAIL_OF_LIGHT[1] = flashHeal2; if VUHDO_RAID_GUIDS[sCurrentPlayerTrailOfLight] then VUHDO_updateBouquetsForEvent( VUHDO_RAID_GUIDS[sCurrentPlayerTrailOfLight], VUHDO_UPDATE_SPELL_TRACE ); end if tPreviousPlayerTrailOfLight and tPreviousPlayerTrailOfLight ~= sCurrentPlayerTrailOfLight and VUHDO_RAID_GUIDS[tPreviousPlayerTrailOfLight] then VUHDO_updateBouquetsForEvent( VUHDO_RAID_GUIDS[tPreviousPlayerTrailOfLight], VUHDO_UPDATE_SPELL_TRACE ); end VUHDO_updateBouquetsForEvent("target", VUHDO_UPDATE_SPELL_TRACE); VUHDO_updateBouquetsForEvent("focus", VUHDO_UPDATE_SPELL_TRACE); end end -- spells can be traced by name or spell ID if not sSpellTraceStoredSettings[tSpellId] then tSpellId = aSpellName; if not sSpellTraceStoredSettings[tSpellId] then return; end end if not VUHDO_RAID_GUIDS[aDstGuid] or (aSrcGuid ~= VUHDO_PLAYER_GUID and not sSpellTraceStoredSettings[tSpellId]["isOthers"]) or (aSrcGuid == VUHDO_PLAYER_GUID and not sSpellTraceStoredSettings[tSpellId]["isMine"]) then return; end if not VUHDO_ACTIVE_TRACE_SPELLS[aDstGuid] or not VUHDO_ACTIVE_TRACE_SPELLS[aDstGuid]["spells"] or not VUHDO_ACTIVE_TRACE_SPELLS[aDstGuid]["spells"][tSpellId] then local tName, _, tIcon = GetSpellInfo(aSpellId); if not tName then return; end if not VUHDO_ACTIVE_TRACE_SPELLS[aDstGuid] then VUHDO_ACTIVE_TRACE_SPELLS[aDstGuid] = { ["spells"] = { }, }; end VUHDO_ACTIVE_TRACE_SPELLS[aDstGuid]["spells"][tSpellId] = { ["icon"] = tIcon, }; end VUHDO_ACTIVE_TRACE_SPELLS[aDstGuid]["spells"][tSpellId]["startTime"] = GetTime(); VUHDO_ACTIVE_TRACE_SPELLS[aDstGuid]["latest"] = tSpellId; VUHDO_updateBouquetsForEvent(VUHDO_RAID_GUIDS[aDstGuid], VUHDO_UPDATE_SPELL_TRACE); end -- function VUHDO_updateSpellTrace() for tUnitGuid, tActiveTrace in pairs(VUHDO_ACTIVE_TRACE_SPELLS) do local i = 0; local tActiveTraceSpells = tActiveTrace["spells"]; local tCurrentTime = GetTime(); for tSpellId, tActiveTraceSpell in pairs(tActiveTraceSpells) do if tActiveTraceSpell then local tDuration = tonumber(sSpellTraceStoredSettings[tSpellId]["duration"] or sSpellTraceDefaultDuration) or sSpellTraceDefaultDuration; local tRemaining = tDuration - (tCurrentTime - tActiveTraceSpell["startTime"]); if tRemaining <= 0 then VUHDO_ACTIVE_TRACE_SPELLS[tUnitGuid]["spells"][tSpellId] = nil; if tActiveTrace["latest"] == tSpellId then VUHDO_ACTIVE_TRACE_SPELLS[tUnitGuid]["latest"] = nil; end local tUnit = VUHDO_RAID_GUIDS[tUnitGuid]; if tUnit then VUHDO_updateBouquetsForEvent(tUnit, VUHDO_UPDATE_SPELL_TRACE); end end i = i + 1; end end if i == 0 then VUHDO_ACTIVE_TRACE_SPELLS[tUnitGuid] = nil; end end end -- function VUHDO_getSpellTraceForUnit(aUnit) if not VUHDO_INTERNAL_TOGGLES[37] or not sShowSpellTrace or not aUnit then return; end local tUnitGuid = UnitGUID(aUnit); if not tUnitGuid or not VUHDO_ACTIVE_TRACE_SPELLS[tUnitGuid] then return; end local tLatestTraceSpellId = VUHDO_ACTIVE_TRACE_SPELLS[tUnitGuid]["latest"]; if tLatestTraceSpellId then return VUHDO_ACTIVE_TRACE_SPELLS[tUnitGuid]["spells"][tLatestTraceSpellId]; end end -- function VUHDO_getActiveSpellTraceSpells() return VUHDO_ACTIVE_TRACE_SPELLS; end -- function VUHDO_getSpellTraceTrailOfLight() return VUHDO_SPELL_TRACE_TRAIL_OF_LIGHT; end -- function VUHDO_getSpellTraceTrailOfLightForUnit(aUnit) if not VUHDO_INTERNAL_TOGGLES[37] or not sShowSpellTrace or not sShowTrailOfLight or not sIsPlayerKnowsTrailOfLight or not aUnit then return; end local tUnitGuid = UnitGUID(aUnit); if not tUnitGuid or tUnitGuid ~= sCurrentPlayerTrailOfLight then return; end return { ["icon"] = sTrailOfLightIcon, }; end
----------------------------------- -- Area: Wajaom Woodlands -- ZNM: Vulpangue ----------------------------------- mixins = {require("scripts/mixins/rage")} require("scripts/globals/status") require("scripts/globals/weather") ----------------------------------- function onMobInitialize(mob) mob:setMobMod(tpz.mobMod.IDLE_DESPAWN, 300) end function onMobSpawn(mob) mob:setLocalVar("[rage]timer", 3600) -- 60 minutes mod:addMod((tpz.mod.FIRE_ABSORB + VanadielDayElement()), 100) mob:addMod(tpz.mod.WIND_ABSORB, 100) mob:setLocalVar("HPP", 90) end function onMobFight(mob, target) local defUpHPP = mob:getLocalVar("HPP") if mob:getHPP() <= defUpHPP then if mob:getHPP() > 10 then mob:addMod(tpz.mod.ACC, 10) mob:addMod(tpz.mod.ATT, 10) mob:setLocalVar("HPP", mob:getHPP() - 10) end end end function onMobDeath(mob, killer) end
-- Copyright (c) 2021 Johnathan P. Irvin -- -- Permission is hereby granted, free of charge, to any person obtaining -- a copy of this software and associated documentation files (the -- "Software"), to deal in the Software without restriction, including -- without limitation the rights to use, copy, modify, merge, publish, -- distribute, sublicense, and/or sell copies of the Software, and to -- permit persons to whom the Software is furnished to do so, subject to -- the following conditions: -- -- The above copyright notice and this permission notice shall be -- included in all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -- LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -- OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. local origTurtle = { place = turtle.place, placeDown = turtle.placeDown, placeUp = turtle.placeUp } local function placementFactory(func) local function generatedFunction(text, blockName) if blockName ~= nil and turtle.selectItem(blockName) == nil then return false, blockName .. ' was not found.' end return func(text) end return generatedFunction end turtle.place = placementFactory(origTurtle.place) turtle.placeDown = placementFactory(origTurtle.placeDown) turtle.placeUp = placementFactory(origTurtle.placeUp)
ESX = nil TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) RegisterServerEvent('elec:vote') AddEventHandler('elec:vote', function(candidate) local _source = source local xPlayer = ESX.GetPlayerFromId(_source) local candidate = candidate MySQL.Async.execute('UPDATE users SET vote = @vote WHERE identifier = @identifier',{['@identifier'] = xPlayer.getIdentifier(),['@vote'] = candidate }) end)
return { number = 7, name = "Some Persistent Gems...", message = "You might need to match the same gem more than once sometimes. Destroy the selected gems to proceed.", timer = false, countDownSpeed = 15, -- only used if timer is true. Controls the speed of the timer. newColumn = function(column) probability(column, { 1/10, "normal", function(n) column[n] = gems.wild() end, 1/10, "normal", function(n) column[3] = gems.burn() end, }) return column end, boardMap = function() return [[ | F A F B F C F D F | | F F F F F F F F F | ]], { A = {"normal", {color=1, selected=true, stays=2}}, B = {"normal", {color=2, selected=true, stays=3}}, C = {"normal", {color=3, selected=true, stays=4}}, D = {"normal", {color=4, selected=true, stays=5}}, } end, music= "classic1", background= "interference", vert = 3, horz = 3, upDiag = 3, downDiag = 3, checkObjectives = function(game) return game.board.selectedCount() == 0 end }
--i figured i should start using local functions despite 1.6 using like none local undo_clear, undo_store, undo_stopstore--[[, undo_undo]] local meta_data, promptedmetadatasave local updatetilesscrollbar, updatelevelscrollbar local worldscrollbarheight, levelscrollbarheight local tilehotkeys = { ["1"] = {t=false, entity=false}, ["2"] = {t=false, entity=false}, ["3"] = {t=false, entity=false}, ["4"] = {t=false, entity=false}, ["5"] = {t=false, entity=false}, ["6"] = {t=false, entity=false}, ["7"] = {t=false, entity=false}, ["8"] = {t=false, entity=false}, ["9"] = {t=false, entity=false}, ["0"] = {t=false, entity=false}, } local tilehotkeysindex = {} local tilehotkeysentityindex = {} local trackgenerationid function editor_load(player_position) --{x, y, xscroll, yscroll} --BLOCKTOGGLE STUFF solidblockperma = {false, false, false, false} collectables = {} --[marioworld-mariolevel-mariosublevel][x-y] collectableslist = {{},{},{},{},{},{},{},{},{},{}} collectablescount = {0,0,0,0,0,0,0,0,0,0} animationnumbers = {} autosave = false subleveltest = false --assist mode if assistmode == nil then if AutoAssistMode then assistmode = true else assistmode = false end latesttiles = {{1, 1}, {2, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1}} --{type of tile, id} end backgroundtilemode = false --sublevels in level sublevelstable = {} if not (mappacklevels[marioworld]) then print("PANIC, levels not found!") for k = 0, defaultsublevels do table.insert(sublevelstable, k) end else if (not mappacklevels[marioworld][mariolevel]) then print("PANIC, sublevels not found!") mappacklevels[marioworld][mariolevel] = defaultsublevels end for k = 0, mappacklevels[marioworld][mariolevel] do table.insert(sublevelstable, k) end end brushsizetoggle = false brushsizex = 1 brushsizey = 1 quickmenuopen = false quickmenuopeny = (height*16)-24 quickmenuclosedy = (height*16) quickmenuy = quickmenuclosedy quickmenusel = false quickmenuspeed = 200 tilehotkeysindex = {} tilehotkeysentityindex = {} for i, t in pairs(tilehotkeys) do if t.entity then tilehotkeysentityindex[t.t] = i else tilehotkeysindex[t.t] = i end end levelmodified = false currentanimation = 1 tileselection = false tileselectionants = 0 tileselectionmoving = false --dragging tile selection if tilesoffset == nil then --there was a weird crash with this, idk if this fixes it tilesoffset = 0 end editmtobjects = false mtsavehighlighttime = 5 mtsavetimer = 0 mtjustsaved = false mtsavecolors = {255, 112, 112, 128} pastingtiles = false pastemode = 1 pastecenter = {0, 0} mtclipboard = {} -- fill with x, y, tile tooltipa = -1000 minimapscroll = 0 minimapx = 3 minimapy = 30 minimapheight = 15 currenttile = 1 minimapscrollspeed = 30 minimapdragging = false minimapmoving = false tilemenuy = 0 tilemenumoving = false allowdrag = true if love.mouse.isDown("l") then allowdrag = false end animationguiarea = {12, 33, 399, 212} animationlineinset = 14 rightclickmenuopen = false customrcopen = false powerlinestate = 1 selectiontoolclick = {{false, false}, {false, false}} selectiontoolselection = {} guielements["tabmain"] = guielement:new("button", 1, 1, TEXT["main"], maintab, 3) guielements["tabmain"].fillcolor = {63, 63, 63} guielements["tabtiles"] = guielement:new("button", guielements["tabmain"].x+guielements["tabmain"].width+10, 1, TEXT["tiles"], tilestab, 3) guielements["tabtiles"].fillcolor = {63, 63, 63} guielements["tabtools"] = guielement:new("button", guielements["tabtiles"].x+guielements["tabtiles"].width+10, 1, TEXT["tools"], toolstab, 3) guielements["tabtools"].fillcolor = {63, 63, 63} guielements["tabmaps"] = guielement:new("button", guielements["tabtools"].x+guielements["tabtools"].width+10, 1, TEXT["maps"], mapstab, 3) guielements["tabmaps"].fillcolor = {63, 63, 63} guielements["tabcustom"] = guielement:new("button", guielements["tabmaps"].x+guielements["tabmaps"].width+10, 1, TEXT["custom"], customtab, 3) guielements["tabcustom"].fillcolor = {63, 63, 63} guielements["tabanimations"] = guielement:new("button", guielements["tabcustom"].x+guielements["tabcustom"].width+10, 1, TEXT["animations"], animationstab, 3) guielements["tabanimations"].fillcolor = {63, 63, 63} --MAIN if android then autoscroll = false end guielements["autoscrollcheckbox"] = guielement:new("checkbox", width*16-14-utf8.len(TEXT["follow player"])*8, 20, toggleautoscroll, autoscroll, TEXT["follow player"]) for i = 1, #backgroundcolor do guielements["defaultcolor" .. i] = guielement:new("button", 17+(i-1)*12, 78, " ", defaultbackground, 0, {i}) if i == 4 then guielements["defaultcolor" .. i].fillcolor = backgroundrgb else guielements["defaultcolor" .. i].fillcolor = backgroundcolor[i] end end --guielements["backgrounddropdown"] = guielement:new("dropdown", 17, 85, 6, changebackground, background, "blue", "black", "water", "rgb") guielements["backgroundinput1"] = guielement:new("input", 65, 78, 3, changebackgroundrgb, backgroundrgb[1], 3, nil, nil, 0) guielements["backgroundinput2"] = guielement:new("input", 93, 78, 3, changebackgroundrgb, backgroundrgb[2], 3, nil, nil, 0) guielements["backgroundinput3"] = guielement:new("input", 121, 78, 3, changebackgroundrgb, backgroundrgb[3], 3, nil, nil, 0) guielements["backgroundinput1"].numdrag = {0,255} guielements["backgroundinput2"].numdrag = {0,255} guielements["backgroundinput3"].numdrag = {0,255} guielements["musicdropdown"] = guielement:new("dropdown", 17, 102, 15, changemusic, musici, unpack(editormusictable)) guielements["custommusiciinput"] = guielement:new("input", 150, 102, 2, changemusic, custommusici, 2, 1, "music", 0) guielements["spritesetdropdown"] = guielement:new("dropdown", 17, 126, 11, changespriteset, spriteset, "overworld", "underground", "castle", "underwater") guielements["timelimitdecrease"] = guielement:new("button", 17, 152, "{", decreasetimelimit, 0) guielements["timelimitincrease"] = guielement:new("button", 31 + string.len(mariotimelimit)*8, 152, "}", increasetimelimit, 0) guielements["timelimitdecrease"].autorepeat = true guielements["timelimitdecrease"].repeatwait = 0.3 guielements["timelimitdecrease"].repeatdelay = 0.08 guielements["timelimitincrease"].autorepeat = true guielements["timelimitincrease"].repeatwait = 0.3 guielements["timelimitincrease"].repeatdelay = 0.08 guielements["portalgundropdown"] = guielement:new("dropdown", 17, 175, 11, changeportalgun, portalguni, "normal", "none", "1 only", "2 only", "gel") --guielements["portalgundropdown"].dropup = true guielements["widthbutton"] = guielement:new("button", 384-(utf8.len(TEXT["change size"])*8), 200, TEXT["change size"], openchangewidth, 2) guielements["savebutton"] = guielement:new("button", 10, 200, TEXT["save"], function() savelevel(); levelmodified = false end, 2) guielements["menubutton"] = guielement:new("button", guielements["savebutton"].x+guielements["savebutton"].width+12, 200, TEXT["exit"], menu_load, 2) guielements["testbutton"] = guielement:new("button", guielements["menubutton"].x+guielements["menubutton"].width+12, 200, TEXT["test level"], test_level, 2) guielements["testbuttonplayer"] = guielement:new("button", guielements["testbutton"].x+guielements["testbutton"].width+12, 200, TEXT["quick test"], function() test_level(objects["player"][1].x, objects["player"][1].y) end, 2) guielements["savebutton"].bordercolor = {255, 0, 0} guielements["savebutton"].bordercolorhigh = {255, 127, 127} --guielements["levelpropertiesdropdown"] = guielement:new("dropdown", 200, 69, 20, function() end, 1, "level properties") guielements["levelpropertiesdropdown"] = guielement:new("button", 200, 69, TEXT["level properties ↓"], levelpropertiestoggle, 1) levelpropertiesdropdown = false local lpx = 202 local lpy = guielements["levelpropertiesdropdown"].y+14 guielements["intermissioncheckbox"] = guielement:new("checkbox", lpx, lpy+10*(1-1), toggleintermission, intermission, TEXT["intermission"]) guielements["warpzonecheckbox"] = guielement:new("checkbox", lpx, lpy+10*(2-1), togglewarpzone, haswarpzone, TEXT["warpzone text"]) guielements["underwatercheckbox"] = guielement:new("checkbox", lpx, lpy+10*(3-1), toggleunderwater, underwater, TEXT["underwater"]) guielements["bonusstagecheckbox"] = guielement:new("checkbox", lpx, lpy+10*(4-1), togglebonusstage, bonusstage, TEXT["bonus stage"]) guielements["edgewrappingcheckbox"] = guielement:new("checkbox", lpx, lpy+10*(5-1), toggleedgewrapping, edgewrapping, TEXT["wrap around"]) guielements["lightsoutcheckbox"] = guielement:new("checkbox", lpx, lpy+10*(6-1), togglelightsout, lightsout, TEXT["lights out"]) guielements["lowgravitycheckbox"] = guielement:new("checkbox", lpx, lpy+10*(7-1), togglelowgravity, lowgravity, TEXT["low gravity"]) guielements["autoscrollingcheckbox"] = guielement:new("checkbox", 200, 86, toggleautoscrolling, autoscrolling, TEXT["autoscroll"]) guielements["autoscrollingscrollbar"] = guielement:new("scrollbar", 298, 86, 93, 35, 9, reverseautoscrollingscrollbar(), "hor") guielements["autoscrollingscrollbar"].scrollstep = 0 guielements["custombackgroundcheckbox"] = guielement:new("checkbox", 200, 133, togglecustombackground, custombackground, TEXT["background"]) guielements["customforegroundcheckbox"] = guielement:new("checkbox", 200, 166, togglecustomforeground, customforeground, TEXT["foreground"]) guielements["scrollfactorxscrollbar"] = guielement:new("scrollbar", 298, 145, 93, 35, 9, reversescrollfactor(), "hor") guielements["scrollfactoryscrollbar"] = guielement:new("scrollbar", 298, 155, 93, 35, 9, reversescrollfactor(scrollfactory), "hor") guielements["scrollfactor2xscrollbar"] = guielement:new("scrollbar", 298, 177, 93, 35, 9, reversescrollfactor2(), "hor") guielements["scrollfactor2yscrollbar"] = guielement:new("scrollbar", 298, 187, 93, 35, 9, reversescrollfactor2(scrollfactor2y), "hor") guielements["scrollfactorxscrollbar"].scrollstep = 0 guielements["scrollfactoryscrollbar"].scrollstep = 0 guielements["scrollfactor2xscrollbar"].scrollstep = 0 guielements["scrollfactor2yscrollbar"].scrollstep = 0 guielements["backgrounddropdown"] = guielement:new("dropdown", 298, 133, 10, changecustombackground, 1, unpack(custombackgrounds)) guielements["foregrounddropdown"] = guielement:new("dropdown", 298, 165, 10, changecustomforeground, 1, unpack(custombackgrounds)) for i = 1, #custombackgrounds do if custombackground and type(custombackground) == "string" and custombackground == custombackgrounds[i] then guielements["backgrounddropdown"].var = i guielements["custombackgroundcheckbox"].var = true end if customforeground and type(customforeground) == "string" and customforeground == custombackgrounds[i] then guielements["foregrounddropdown"].var = i guielements["customforegroundcheckbox"].var = true end end --mapsize stuff guielements["maptopup"] = guielement:new("button", 0, 0, "↑", changenewmapsize, nil, {"top", "up"}, nil, 8, 0.02) guielements["maptopdown"] = guielement:new("button", 0, 0, "↓", changenewmapsize, nil, {"top", "down"}, nil, 8, 0.02) guielements["mapleftleft"] = guielement:new("button", 0, 0, "{", changenewmapsize, nil, {"left", "left"}, nil, 8, 0.02) guielements["mapleftright"] = guielement:new("button", 0, 0, "}", changenewmapsize, nil, {"left", "right"}, nil, 8, 0.02) guielements["maprightleft"] = guielement:new("button", 0, 0, "{", changenewmapsize, nil, {"right", "left"}, nil, 8, 0.02) guielements["maprightright"] = guielement:new("button", 0, 0, "}", changenewmapsize, nil, {"right", "right"}, nil, 8, 0.02) guielements["mapbottomup"] = guielement:new("button", 0, 0, "↑", changenewmapsize, nil, {"bottom", "up"}, nil, 8, 0.02) guielements["mapbottomdown"] = guielement:new("button", 0, 0, "↓", changenewmapsize, nil, {"bottom", "down"}, nil, 8, 0.02) guielements["mapwidthapply"] = guielement:new("button", 0, 0, TEXT["apply"], mapwidthapply, 3) guielements["mapwidthcancel"] = guielement:new("button", 0, 0, TEXT["cancel"], mapwidthcancel, 3) --TILES guielements["tilesall"] = guielement:new("button", 5, 20, TEXT["all"], tilesall, 2) guielements["tilessmb"] = guielement:new("button", guielements["tilesall"].x+guielements["tilesall"].width+8, 20, TEXT["smb"], tilessmb, 2) guielements["tilesportal"] = guielement:new("button", guielements["tilessmb"].x+guielements["tilessmb"].width+8, 20, TEXT["portal"], tilesportal, 2) guielements["tilescustom"] = guielement:new("button", guielements["tilesportal"].x+guielements["tilesportal"].width+8, 20, TEXT["custom"], tilescustom, 2) guielements["tilesanimated"] = guielement:new("button", guielements["tilescustom"].x+guielements["tilescustom"].width+8, 20, TEXT["animated"], tilesanimated, 2) guielements["tilesobjects"] = guielement:new("button", guielements["tilesanimated"].x+guielements["tilesanimated"].width+8, 20, TEXT["objects"], tilesobjects, 2) guielements["tilesentities"] = guielement:new("button", width*16-12-utf8.len(TEXT["entities"])*8, 20, TEXT["entities"], tilesentities, 2) guielements["tilesscrollbar"] = guielement:new("scrollbar", 381, 37, 167, 15, 40, 0, "ver") --TOOLS guielements["linkbutton"] = guielement:new("button", 5, 22, TEXT["link tool"], linkbutton, 2, false, 1, 120) guielements["linkbutton"].bordercolor = {0, 255, 0} guielements["linkbutton"].bordercolorhigh = {220, 255, 220} guielements["portalbutton"] = guielement:new("button", 5, 40, TEXT["portal gun"], portalbutton, 2, false, 1, 120) guielements["portalbutton"].bordercolor = {0, 0, 255} guielements["portalbutton"].bordercolorhigh = {127, 127, 255} guielements["selectionbutton"] = guielement:new("button", 5, 58, TEXT["selection tool"], selectionbutton, 2, false, 1, 120) guielements["selectionbutton"].bordercolor = {255, 106, 0} guielements["selectionbutton"].bordercolorhigh = {255, 206, 127} guielements["powerlinebutton"] = guielement:new("button", 5, 76, TEXT["power line draw"], powerlinebutton, 2, false, 1, 120) guielements["powerlinebutton"].bordercolor = {255, 216, 0} guielements["powerlinebutton"].bordercolorhigh = {255, 255, 220} currenttooldesc = 1 --what description should be displayed for the buttons guielements["livesdecrease"] = guielement:new("button", 294, 104, "{", livesdecrease, 0) guielements["livesincrease"] = guielement:new("button", 314, 104, "}", livesincrease, 0) guielements["physicsdropdown"] = guielement:new("dropdown", 294, 117, 11, changephysics, currentphysics, "mari0", "smb", "mari0-smb2j", "smb2j", "mari0-maker", "mario maker", "portal") guielements["cameradropdown"] = guielement:new("dropdown", 294, 130, 11, changecamerasetting, camerasetting, "default", "centered"--[[, "forward only"]]) guielements["dropshadowcheckbox"] = guielement:new("checkbox", 294, 143, toggledropshadow, dropshadow, TEXT["drop shadow"]) guielements["realtimecheckbox"] = guielement:new("checkbox", 294, 154, togglerealtime, realtime, TEXT["real time"]) local _, count = TEXT["real time"]:gsub("\n", '') guielements["continuemusiccheckbox"] = guielement:new("checkbox", 294, guielements["realtimecheckbox"].y+11+10*count, togglecontinuemusic, continuesublevelmusic, TEXT["cont. music"]) --MAPS guielements["savebutton2"] = guielement:new("button", 300, 196, TEXT["save level"], guielements["savebutton"].func, 0, nil, 2.4, 94, true) --guielements["autosavecheckbox"] = guielement:new("checkbox", 300, guielements["savebutton2"].y+16, function() autosave = not autosave; guielements["autosavecheckbox"].var = autosave end, autosave, TEXT["autosave"]) guielements["savebutton2"].bordercolor = {255, 0, 0} guielements["savebutton2"].bordercolorhigh = {255, 127, 127} guielements["worldscrollbar"] = guielement:new("scrollbar", 90, 20, 201, 11, 75, 0, "ver") guielements["levelscrollbar"] = guielement:new("scrollbar", 383, 20, 173, 14, 60, oldlevelscrollbar or 0, "ver") oldworldscrollbarv = 0 oldlevelscrollbarv = 0 oldlevelscrollbar = 0 levelrightclickmenu = guielement:new("rightclick", 0, 0, 6, levelrightclickmenuclick, false, "action", "copy", "paste", "delete") levelrightclickmenu.active = false --CUSTOM TAB guielements["graphicscustomtab"] = guielement:new("button", 5, 20, TEXT["graphics"], customtabtab, 2, {"graphics"}) guielements["tilescustomtab"] = guielement:new("button", guielements["graphicscustomtab"].x+guielements["graphicscustomtab"].width+8, 20, TEXT["tiles"], customtabtab, 2, {"tiles"}) guielements["backgroundscustomtab"] = guielement:new("button", guielements["tilescustomtab"].x+guielements["tilescustomtab"].width+8, 20, TEXT["backgrounds"], customtabtab, 2, {"backgrounds"}) guielements["soundscustomtab"] = guielement:new("button", guielements["backgroundscustomtab"].x+guielements["backgroundscustomtab"].width+8, 20, TEXT["sounds"], customtabtab, 2, {"sounds"}) guielements["textcustomtab"] = guielement:new("button", guielements["soundscustomtab"].x+guielements["soundscustomtab"].width+8, 20, TEXT["text"], customtabtab, 2, {"text"}) guielements["enemiescustomtab"] = guielement:new("button", guielements["textcustomtab"].x+guielements["textcustomtab"].width+8, 20, TEXT["enemies"], customtabtab, 2, {"enemies"}) customtabstate = "graphics" --custom graphics changecurrentimage(1, true) guielements["currentimagedropdown"] = guielement:new("dropdown", 184, 63, 22, changecurrentimage, currentcustomimage[1], unpack(imagestable)) guielements["currentimagedropdown"].displayentries = imagestabledisplay --guielements["currentimagedropdown"].scrollbar.scrollstep = 0.11 --how much mousewheel scrolls guielements["exportimagetemplate"] = guielement:new("button", 184, 88, TEXT["export template"], exportcustomimage, 2) guielements["openfoldercustom"] = guielement:new("button", 184, 105, TEXT["open folder"], opencustomimagefolder, 2) guielements["saveimage"] = guielement:new("button", 176, 199, TEXT["update image"], savecustomimage, 2) guielements["saveimage"].bordercolor = {255, 0, 0} guielements["saveimage"].bordercolorhigh = {255, 127, 127} guielements["resetimage"] = guielement:new("button", guielements["saveimage"].x+guielements["saveimage"].width+8, 199, TEXT["reset"], resetcustomimage, 2) --custom tiles guielements["exporttilestemplate"] = guielement:new("button", 184, 63, TEXT["export template"], exportcustomimage, 2) guielements["exportanimatedtilestemplate"] = guielement:new("button", 184, 163, TEXT["export template"], exportcustomimage, 2, {"animated"}) guielements["openfoldertilescustom"] = guielement:new("button", 184, 80, TEXT["open folder"], opencustomimagefolder, 2, {"tiles"}) guielements["openfolderanimatedtilescustom"] = guielement:new("button", 184, 180, TEXT["open folder"], opencustomimagefolder, 2, {"animated"}) --custom background changecurrentbackground(1, true) guielements["currentbackgrounddropdown"] = guielement:new("dropdown", 184, 63, 10, changecurrentbackground, 1, "background", "foreground") guielements["openfolderbackgroundscustom"] = guielement:new("button", 184, 131, TEXT["open folder"], opencustomimagefolder, 2, {"backgrounds"}) --custom sounds changecurrentsound(1, true) guielements["currentsounddropdown"] = guielement:new("dropdown", 184, 63, 16, changecurrentsound, 1, unpack(soundliststring)) --guielements["currentsounddropdown"].scrollbar.scrollstep = 0.11 --how much mousewheel scrolls guielements["openfoldersoundscustom"] = guielement:new("button", 184, 105, TEXT["open folder"], opencustomimagefolder, 2, {"sounds"}) guielements["openfoldermusiccustom"] = guielement:new("button", 184, 165, TEXT["open folder"], opencustomimagefolder, 2, {"music"}) --custom enemies changecurrentenemy(1, true) guielements["currentenemydropdown"] = guielement:new("dropdown", 184, 63, 22, changecurrentenemy, 1, unpack(customenemies)) if guielements["currentenemydropdown"].scrollbar then --guielements["currentenemydropdown"].scrollbar.scrollstep = 0.11 --how much mousewheel scrolls end guielements["openfolderenemiescustom"] = guielement:new("button", 184, 105, TEXT["open folder"], opencustomimagefolder, 2) --custom text guielements["savecustomtext"] = guielement:new("button", 10, 201, "save text", savecustomtext, 2) guielements["savecustomtext"].bordercolor = {255, 0, 0} guielements["savecustomtext"].bordercolorhigh = {255, 127, 127} guielements["hudtexttab"] = guielement:new("button", 10, 40, TEXT["hud"], texttabtab, 2, {"hud"}) guielements["endingtexttab"] = guielement:new("button", guielements["hudtexttab"].x+guielements["hudtexttab"].width+8, 40, TEXT["ending"], texttabtab, 2, {"ending"}) guielements["castletexttab"] = guielement:new("button", guielements["endingtexttab"].x+guielements["endingtexttab"].width+8, 40, TEXT["castle"], texttabtab, 2, {"castle"}) guielements["levelscreentexttab"] = guielement:new("button", guielements["castletexttab"].x+guielements["castletexttab"].width+8, 40, TEXT["levelscreen"], texttabtab, 2, {"levelscreen"}) guielements["editendingtext1"] = guielement:new("input", 10, 67, 32, nil, endingtext[1], 32) guielements["editendingtext2"] = guielement:new("input", 10, 81, 32, nil, endingtext[2], 32) guielements["editplayername"] = guielement:new("input", 10, 67, 12, nil, playername, 12) guielements["endingcolor<"] = guielement:new("button", 10, 97, "{", endingtextcolorleft, 1) guielements["endingcolor>"] = guielement:new("button", guielements["endingcolor<"].x+guielements["endingcolor<"].width+utf8.len(TEXT["color"])*8+7, 97, "}", endingtextcolorright, 1) guielements["edittoadtext1"] = guielement:new("input", 10, 67, 32, nil, toadtext[1], 32) guielements["edittoadtext2"] = guielement:new("input", 10, 81, 32, nil, toadtext[2], 32) guielements["edittoadtext3"] = guielement:new("input", 10, 95, 32, nil, toadtext[3], 32) guielements["editpeachtext1"] = guielement:new("input", 10, 121, 32, nil, peachtext[1], 32) guielements["editpeachtext2"] = guielement:new("input", 10, 135, 32, nil, peachtext[2], 32) guielements["editpeachtext3"] = guielement:new("input", 10, 149, 32, nil, peachtext[3], 32) guielements["editpeachtext4"] = guielement:new("input", 10, 163, 32, nil, peachtext[4], 32) guielements["editpeachtext5"] = guielement:new("input", 10, 177, 32, nil, peachtext[5], 32) guielements["stevecheckbox"] = guielement:new("checkbox", 10, 191, togglesteve, pressbtosteve, "steve") guielements["hudcolor<"] = guielement:new("button", 10, 83, "{", hudtextcolorleft, 1) guielements["hudcolor>"] = guielement:new("button", guielements["hudcolor<"].x+guielements["hudcolor<"].width+utf8.len(TEXT["color"])*8+7, 83, "}", hudtextcolorright, 1) guielements["hudworldlettercheckbox"] = guielement:new("checkbox", 10, 98, togglehudworldletter, hudworldletter, TEXT["use letters for worlds over 9"]) guielements["hudvisiblecheckbox"] = guielement:new("checkbox", 10, 109, togglehudvisible, hudvisible, TEXT["hud visible"]) guielements["hudoutlinecheckbox"] = guielement:new("checkbox", 10, 120, togglehudoutline, hudoutline, TEXT["hud outline"]) guielements["hudsimplecheckbox"] = guielement:new("checkbox", 10, 131, togglehudsimple, hudsimple, TEXT["simple hud"]) guielements["editlevelscreentext"] = guielement:new("input", 10, 81, 40, nil, levelscreentext[marioworld .. "-" .. mariolevel] or "", 45) textcolorl = endingtextcolorname textcolorp = hudtextcolorname textstate = "hud" --animationS guielements["animationsscrollbarver"] = guielement:new("scrollbar", animationguiarea[1]-10, animationguiarea[2], animationguiarea[4]-animationguiarea[2], 10, 40, 0, "ver", nil, nil, nil, nil, true) guielements["animationsscrollbarhor"] = guielement:new("scrollbar", animationguiarea[1], animationguiarea[4], animationguiarea[3]-animationguiarea[1], 40, 10, 0, "hor", nil, nil, nil, nil, false) guielements["animationsscrollbarhor"].scrollstep = 0 local args = {} for i, v in ipairs(animations) do table.insert(args, string.sub(v.name, 1, -6)) end guielements["animationselectdrop"] = guielement:new("dropdown", 15, 20, 15, selectanimation, 1, unpack(args)) guielements["animationnewbutton"] = guielement:new("button", 3, 20, "+", createnewanimation, nil) guielements["animationsavebutton"] = guielement:new("button", 150, 19, TEXT["save"], saveanimation, 1) guielements["animationdelbutton"] = guielement:new("button", guielements["animationsavebutton"].x+guielements["animationsavebutton"].width+8, 19, "x", removeanimation, 1) guielements["animationnameinput"] = guielement:new("input", 282, 20, 14, function() animationsaveas = guielements["animationnameinput"].value; guielements["animationnameinput"].inputting = false end, "", 20, nil, nil, 0) if animations[currentanimation] then guielements["animationnameinput"].value = string.sub(animations[currentanimation].name, 1, -6) guielements["animationnameinput"]:updatePos() end addanimationtriggerbutton = guielement:new("button", 0, 0, "+", addanimationtrigger, nil, nil, nil, 8) addanimationtriggerbutton.textcolor = {0, 200, 0} addanimationconditionbutton = guielement:new("button", 0, 0, "+", addanimationcondition, nil, nil, nil, 8) addanimationconditionbutton.textcolor = {0, 200, 0} addanimationactionbutton = guielement:new("button", 0, 0, "+", addanimationaction, nil, nil, nil, 8) addanimationactionbutton.textcolor = {0, 200, 0} --get current description and shit local mappackname = "" local mappackauthor = "" local mappackdescription = "" if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/settings.txt") then local data = love.filesystem.read(mappackfolder .. "/" .. mappack .. "/settings.txt") local split1 = data:split("\n") for i = 1, #split1 do local split2 = split1[i]:split("=") if split2[1] == "name" then mappackname = split2[2] elseif split2[1] == "author" then mappackauthor = split2[2] elseif split2[1] == "description" then mappackdescription = split2[2] end end end if love.filesystem.exists( mappackfolder .. "/" .. mappack .. "/icon.png" ) then editmappackicon = love.graphics.newImage(mappackfolder .. "/" .. mappack .. "/icon.png") else editmappackicon = nil end multitileobjects = {} multitileobjectnames = {} loadmtobjects() guielements["mtobjectrename"] = guielement:new("input", 6, 39, 30, function() multitileobjectnames[guielements["mtobjectrename"].i] = guielements["mtobjectrename"].value guielements["mtobjectrename"].active = false changemtname(guielements["mtobjectrename"].i) end, "", 30) guielements["edittitle"] = guielement:new("input", 5, 115, 17, nil, mappackname, 17) guielements["editauthor"] = guielement:new("input", 5, 140, 13, nil, mappackauthor, 13) guielements["editdescription"] = guielement:new("input", 5, 165, 17, nil, mappackdescription, 51, 3) guielements["savesettings"] = guielement:new("button", 5, 203, TEXT["save settings"], savesettings, 2) guielements["savesettings"].bordercolor = {255, 0, 0} guielements["savesettings"].bordercolorhigh = {255, 127, 127} --MISC editortilemousescroll = false editortilemousescrolltimer = 0 undo_clear() tilesall() if editorloadopen then editoropen() editorloadopen = false else editorclose() editorstate = "main" editentities = false end if player_position then --test from position objects["player"][1].x = player_position[1] objects["player"][1].y = player_position[2] camerasnap(player_position[3], player_position[4]) end trackgenerationid = 0 trackpreviews = false end function editor_update(dt) ---------- --EDITOR-- ---------- --[[level modified debug if oldlevelmodified ~= nil then if oldlevelmodified ~= levelmodified and levelmodified then notice.new("level modified",notice.white) end end oldlevelmodified = levelmodified]] if editormenuopen == false or minimapmoving then --key scroll if (not rightclickmenuopen) or customrcopen == "region" or customrcopen == "link" or customrcopen == "path" or customrcopen == "trackpath" or minimapmoving then if (love.keyboard.isDown("left") or (android and leftkey(1) and not autoscroll)) and not brushsizetoggle then autoscroll = false guielements["autoscrollcheckbox"].var = autoscroll splitxscroll[1] = splitxscroll[1] - 30*gdt if splitxscroll[1] < 0 then splitxscroll[1] = 0 end generatespritebatch() elseif (love.keyboard.isDown("right") or (android and rightkey(1) and not autoscroll)) and not brushsizetoggle then autoscroll = false guielements["autoscrollcheckbox"].var = autoscroll splitxscroll[1] = splitxscroll[1] + 30*gdt if splitxscroll[1] > mapwidth-width then splitxscroll[1] = mapwidth-width end generatespritebatch() end if mapheight ~= 15 and not brushsizetoggle then if (love.keyboard.isDown("up") or (android and upkey(1) and not autoscroll)) then autoscroll = false guielements["autoscrollcheckbox"].var = autoscroll splityscroll[1] = splityscroll[1] - 30*gdt if splityscroll[1] < 0 then splityscroll[1] = 0 end generatespritebatch() elseif (love.keyboard.isDown("down") or (android and downkey(1) and not autoscroll)) then autoscroll = false guielements["autoscrollcheckbox"].var = autoscroll splityscroll[1] = splityscroll[1] + 30*gdt if splityscroll[1] >= mapheight-height-1 then splityscroll[1] = mapheight-height-1 end generatespritebatch() end end end end if editormenuopen == false and (not minimapmoving) then if editorstate == "powerline" then local x, y = love.mouse.getPosition() if love.mouse.isDown("l") then powerlinedraw(x, y) elseif love.mouse.isDown("r") then editentities = true currenttile = 1 placetile(x, y) end elseif customrcopen == "path" and allowdrag then --draw path (this used to be so simple, but then i added clear pipes ;( ) local x, y = love.mouse.getPosition() if love.mouse.isDown("l") then local rcp = rightclickpath local ox, oy = rcp.last[1], rcp.last[2] local dir = rcp.dir local tx, ty = getMouseTile(x, y+8*screenzoom*scale) local coveredtiles = {} tx = tx-rcp.x ty = ty-rcp.y --fit into pipe path if rcp.pipe then if (dir == "right" or dir == "left") and ty < oy then ty = ty + 1 elseif (dir == "down" or dir == "up") and tx < ox then tx = tx + 1 end --allow going left too if #rcp.path == 1 and tx == ox-1 then dir = "left" end end local overlap = ((tx == ox) and (ty == oy)) --allow dragging again if (not rcp.drag) and overlap then rcp.drag = true end if not overlap then local lx, ly = rcp.last[1], rcp.last[2]--last pos for i = #rcp.path, 1, -1 do --check normal overlap local pass = true if (tx == rcp.path[i][1] and ty == rcp.path[i][2]) and not (i == #rcp.path-1) then pass = false end --check pipe overlap if rcp.pipe and not (i == #rcp.path-1) then local cx, cy = rcp.path[i][1], rcp.path[i][2]--check x, check y table.insert(coveredtiles, {cx, cy}) local dir if ly < cy then dir = "up"; table.insert(coveredtiles, {cx-1, cy}) elseif lx > cx then dir = "right"; table.insert(coveredtiles, {cx, cy-1}) elseif lx < cx then dir = "left"; table.insert(coveredtiles, {cx, cy-1}) elseif ly > cy then dir = "down"; table.insert(coveredtiles, {cx-1, cy}) end lx, ly = cx, cy if dir then if dir == "up" and ty == cy and tx == cx-1 then pass = false elseif dir == "right" and tx == cx and ty == cy-1 then pass = false elseif dir == "left" and tx == cx and ty == cy-1 then pass = false elseif dir == "down" and ty == cy and tx == cx-1 then pass = false end end end if not pass then overlap = true break end end end if (not overlap) and rcp.drag then local erase = false local place = false if tx == ox+1 and ty == oy then if dir == "left" then erase = true else --no overlapping turns local pass = true if rcp.pipe and dir == "down" and rcp.path[#rcp.path-2] and rcp.path[#rcp.path][1] ~= rcp.path[#rcp.path-2][1] then pass = false end if pass then rcp.dir = "right" place = true end end elseif tx == ox-1 and ty == oy then if dir == "right" then erase = true else --no overlapping turns local pass = true if rcp.pipe and dir == "down" and rcp.path[#rcp.path-2] and rcp.path[#rcp.path][1] ~= rcp.path[#rcp.path-2][1] then pass = false end if pass then rcp.dir = "left" place = true end end elseif tx == ox and ty == oy+1 then if dir == "up" then erase = true else --no overlapping turns local pass = true if rcp.pipe and dir == "right" and rcp.path[#rcp.path-2] and rcp.path[#rcp.path][2] ~= rcp.path[#rcp.path-2][2] then pass = false end if pass then rcp.dir = "down" place = true end end elseif tx == ox and ty == oy-1 then if dir == "down" then erase = true else --no overlapping turns local pass = true if rcp.pipe and dir == "right" and rcp.path[#rcp.path-2] and rcp.path[#rcp.path][2] ~= rcp.path[#rcp.path-2][2] then pass = false end if pass then rcp.dir = "up" place = true end end end if place then if rcp.pipe then local turn = (dir ~= rcp.dir) --add additional segment for turning pipe local pass = true for i, t in pairs(coveredtiles) do if tx == t[1] and ty == t[2] then pass = false elseif turn and rcp.dir == "up" and tx == t[1] and ty-1 == t[2] then pass = false elseif turn and rcp.dir == "left" and tx-1 == t[1] and ty == t[2] then pass = false elseif (rcp.dir == "up" or rcp.dir == "down") and tx-1 == t[1] and ty == t[2] then pass = false elseif (rcp.dir == "left" or rcp.dir == "right") and tx == t[1] and ty-1 == t[2] then pass = false end end if pass then table.insert(rcp.path, {tx, ty}) if turn then if rcp.dir == "up" then table.insert(rcp.path, {tx, ty-1}) rcp.drag = false elseif rcp.dir == "left" then table.insert(rcp.path, {tx-1, ty}) rcp.drag = false end end rcp.last = {rcp.path[#rcp.path][1], rcp.path[#rcp.path][2]} else rcp.dir = dir end else table.insert(rcp.path, {tx, ty}) rcp.last = {rcp.path[#rcp.path][1], rcp.path[#rcp.path][2]} end elseif erase and #rcp.path > 1 then table.remove(rcp.path, #rcp.path) --remove additional segment for turning pipe if rcp.pipe and (dir == "left" or dir == "up") and rcp.path[#rcp.path-1] and rcp.path[#rcp.path-2] then if not ((tx == rcp.path[#rcp.path-2][1]) or (ty == rcp.path[#rcp.path-2][2])) then tx, ty = rcp.path[#rcp.path-1][1], rcp.path[#rcp.path-1][2] table.remove(rcp.path, #rcp.path) rcp.drag = false end end rcp.last = {rcp.path[#rcp.path][1], rcp.path[#rcp.path][2]} rcp.dir = "right" if #rcp.path > 1 then local lx, ly = rcp.path[#rcp.path-1][1], rcp.path[#rcp.path-1][2] if lx > tx then rcp.dir = "left" elseif ly < ty then rcp.dir = "down" elseif ly > ty then rcp.dir = "up" end end end end end elseif customrcopen == "trackpath" and allowdrag then --draw track local x, y = love.mouse.getPosition() if love.mouse.isDown("l") then local rcp = rightclicktrack local ox, oy = rcp.last[1], rcp.last[2] local dir = rcp.dir local tx, ty = getMouseTile(x, y+8*screenzoom*scale) tx = tx-rcp.x ty = ty-rcp.y local overlap = ((tx == ox) and (ty == oy)) --allow dragging again if (not rcp.drag) and overlap then rcp.drag = true end local looped, looping = false, false if #rcp.path > 3 and rcp.path[1][3] ~= "c" and rcp.path[1][3] ~= "o" then looped = true overlap = false end if #rcp.path > 3 and rcp.path[1][1] == tx and rcp.path[1][2] == ty then looping = true end if not overlap then for i = #rcp.path, 1, -1 do --check overlap if (tx == rcp.path[i][1] and ty == rcp.path[i][2]) and i ~= #rcp.path-1 and (#rcp.path <= 3 or i ~= 1) and not (looped and i == #rcp.path) then overlap = true break end end end if (not overlap) and rcp.drag and (not (looping and looped)) then local erase = false local place = false if rcp.path[#rcp.path-1] and (tx == rcp.path[#rcp.path-1][1] and ty == rcp.path[#rcp.path-1][2]) then erase = true elseif looped and tx == rcp.path[#rcp.path][1] and ty == rcp.path[#rcp.path][2] then erase = true end if (not erase) and (not looped) then if tx == ox+1 and ty == oy then rcp.dir = "r" place = true elseif tx == ox-1 and ty == oy then rcp.dir = "l" place = true elseif tx == ox and ty == oy+1 then rcp.dir = "d" place = true elseif tx == ox-1 and ty == oy-1 then rcp.dir = "lu" place = true elseif tx == ox+1 and ty == oy-1 then rcp.dir = "ru" place = true elseif tx == ox-1 and ty == oy+1 then rcp.dir = "ld" place = true elseif tx == ox+1 and ty == oy+1 then rcp.dir = "rd" place = true elseif tx == ox and ty == oy-1 then rcp.dir = "u" place = true end end if place then if looping then --make loop rcp.path[1][3] = oppositetrackdirection(rcp.dir) rcp.path[#rcp.path][4] = rcp.dir else local openorclosed = rcp.path[#rcp.path][4] rcp.path[#rcp.path][4] = rcp.dir table.insert(rcp.path, {tx, ty, oppositetrackdirection(rcp.dir), openorclosed, "d"}) end elseif erase and #rcp.path > 1 then if looped then --remove loop rcp.path[#rcp.path][4] = "c" rcp.path[1][3] = "c" else local openorclosed = rcp.path[#rcp.path][4] table.remove(rcp.path, #rcp.path) rcp.path[#rcp.path][4] = openorclosed end end if place or erase then rcp.last = {rcp.path[#rcp.path][1], rcp.path[#rcp.path][2], rcp.path[#rcp.path][3], rcp.path[#rcp.path][4], rcp.path[#rcp.path][5]} end end end end if not android then if love.keyboard.isDown("lshift") then brushsizetoggle = true else brushsizetoggle = false end end if love.keyboard.isDown("rctrl") or love.keyboard.isDown("lctrl") or love.keyboard.isDown("rgui") or love.keyboard.isDown("lgui") then ctrlpressed = true else ctrlpressed = false end if rightclickmenuopen and customrcopen then if rightclickobjects then for i = 1, #rightclickobjects do local obj = rightclickobjects[i] obj:update(dt) end end end if editorstate == "linktool" or editorstate == "portalgun" or editorstate == "selectiontool" or editorstate == "powerline" then return end tileselectionants = (tileselectionants + 8*dt)%16 if love.mouse.isDown("l") and allowdrag and customrcopen == false and not (assistmode and quickmenuopen) then local x, y = love.mouse.getPosition() if tileselection then if not tileselection.finished then --increase tileselection local tx, ty = getMouseTile(x, y+8*screenzoom*scale) tileselection[3] = tx tileselection[4] = ty end elseif pastingtiles then --PASTE TILES for i, v in pairs(mtclipboard) do for j, w in pairs(v) do if w[1] == 1 and (not w[2]) and (not w["back"]) and pastemode == 1 then -- nothing else local tx, ty = getMouseTile(x+(i-1 + pastecenter[1])*16*scale, y+(j-1 + pastecenter[2])*16*scale+8*scale) if ismaptile(tx, ty) then local d = mtclipboard[i][j] currenttile = d[1] --[[placetile(x+(i-1 + pastecenter[1])*16*scale, y+(j-1 + pastecenter[2])*16*scale) local tile1 = d[1] if tile1 == 1 then tile1 = false --don't paste empty space end if not backgroundtilemode then if not d[3] then map[tx][ty][1] = tile1 or map[tx][ty][1] map[tx][ty][2] = d[2] or map[tx][ty][2] map[tx][ty]["back"] = d["back"] else map[tx][ty] = {tile1 or map[tx][ty][1], d[2] or map[tx][ty][2], d[3] or map[tx][ty][3], back=d["back"]} end end map[tx][ty]["gels"] = {}]] end end end end allowdrag = false elseif (brushsizex > 1 or brushsizey > 1) and not pastingtiles then for lx = 1, brushsizex do for ly = 1, brushsizey do placetile(x+((lx-1)*16*scale), y+((ly-1)*16*scale)) end end elseif not pastingtiles then placetile(x, y) end end elseif editorstate == "main" then if love.mouse.isDown("l") and not changemapwidthmenu and not minimapmoving then local mousex, mousey = love.mouse.getPosition() if mousey >= minimapy*scale and mousey < (minimapy+34)*scale then if mousex >= minimapx*scale and mousex < (minimapx+394)*scale then --HORIZONTAL if mousex < (minimapx+width)*scale then if minimapscroll > 0 then minimapscroll = minimapscroll - minimapscrollspeed*dt if minimapscroll < 0 then minimapscroll = 0 end end elseif mousex >= (minimapx+394-width)*scale then if minimapscroll < mapwidth-width-170 then minimapscroll = minimapscroll + minimapscrollspeed*dt if minimapscroll > mapwidth-width-170 then minimapscroll = mapwidth-width-170 end end end --VERTICAL if mousey < (minimapy+5)*scale then if yscroll > 0 then yscroll = yscroll - minimapscrollspeed*dt if yscroll < 0 then yscroll = 0 end splityscroll[1] = yscroll end elseif mousey >= (minimapy+minimapheight*2+4-5)*scale then if yscroll < mapheight-height then yscroll = yscroll + minimapscrollspeed*dt if yscroll > mapheight-height-1 then yscroll = mapheight-height-1 end splityscroll[1] = yscroll end end splitxscroll[1] = (mousex/scale-3-width) / 2 + minimapscroll if splitxscroll[1] < minimapscroll then splitxscroll[1] = minimapscroll end if splitxscroll[1] > 170 + minimapscroll then splitxscroll[1] = 170 + minimapscroll end if splitxscroll[1] > mapwidth-width then splitxscroll[1] = mapwidth-width end --SPRITEBATCH UPDATE if math.floor(splitxscroll[1]) ~= spritebatchX[1] or math.floor(splityscroll[1]) ~= spritebatchY[1] then generatespritebatch() spritebatchX[1] = math.floor(splitxscroll[1]) spritebatchY[1] = math.floor(splityscroll[1]) end end elseif minimapdragging and mousey >= (height-8)*16*scale then --full minimap minimapdragging = false minimapmoving = true nothingtab() end --mapwidth repeat if guirepeattimer > 0 then guirepeattimer = guirepeattimer - dt else end end updatescrollfactor() elseif editorstate == "tiles" then local x, y = love.mouse.getPosition() tilesoffset = (guielements["tilesscrollbar"].value or 0) * (tilescrollbarheight or 1) * scale if (editentities and not editenemies) and not DisableToolTips then local t, list = getentitylistpos(x, y) local tile if t and list then tile = entitiesform[list][t] end if tile ~= prevtile then if tile and (tooltipimages[tile] or type(tile) == "string") then entitytooltipobject = entitytooltip:new(tile) end end if tile and (tooltipimages[tile] or type(tile) == "string") then entitytooltipobject:update(dt) tooltipa = math.min(255, tooltipa + dt*4000) else tooltipa = math.max(-2000, tooltipa - dt*4000) end prevtile = tile end if y > tilemenuy+height*16-32 and y > tilemenuy+height*16 then tilemenumoving = true end --tile stamp selection on android if android and tilestampholdtimer then tilestampholdtimer = tilestampholdtimer + dt if tilestampholdtimer > 0.8 then if math.abs(x-tilestampholdx) < 5*scale and math.abs(y-tilestampholdy) < 5*scale then editor_mousepressed(tilestampholdx,tilestampholdy,"l") love.system.vibrate(0.1) end tilestampholdtimer = false end end elseif editorstate == "tools" then --update description for the button that is being hovered if guielements["linkbutton"]:inhighlight(love.mouse.getPosition()) then currenttooldesc = 1 elseif guielements["portalbutton"]:inhighlight(love.mouse.getPosition()) then currenttooldesc = 2 elseif guielements["selectionbutton"]:inhighlight(love.mouse.getPosition()) then currenttooldesc = 3 elseif guielements["powerlinebutton"]:inhighlight(love.mouse.getPosition()) then currenttooldesc = 4 end elseif editorstate == "maps" then --map button scroll local v = worldscrollbarheight*guielements["worldscrollbar"].value if v ~= oldworldscrollbarv then for i = 1, #mappacklevels do --world guielements["world-" .. i].y = math.floor(20+((i-1)*16)-v) end guielements["newworld"].y = math.floor(20+((#mappacklevels)*16)-v) end oldworldscrollbarv = v --level button scroll v = levelscrollbarheight*guielements["levelscrollbar"].value if v ~= oldlevelscrollbarv then for j = 1, #mappacklevels[currentworldselection] do --level for k = 0, mappacklevels[currentworldselection][j] do --sublevel local name = currentworldselection .. "-" .. j .. "_" .. k if k < 1 then guielements[name].y = math.floor(20+((j-1)*39)-v) else guielements[name].y = math.floor(41+((j-1)*39)-v) end end guielements["newsublevel-" .. currentworldselection .. "-" .. j].y = math.floor(41+((j-1)*39)-v) end guielements["newlevel-" .. currentworldselection].y = math.floor(20+((#mappacklevels[currentworldselection])*39)-v) end oldlevelscrollbarv = v oldlevelscrollbar = guielements["levelscrollbar"].value --scrollbar priority local x, y = love.mouse.getPosition() if x > 103*scale then guielements["levelscrollbar"].scrollstepdisabled = false guielements["worldscrollbar"].scrollstepdisabled = true else guielements["levelscrollbar"].scrollstepdisabled = true guielements["worldscrollbar"].scrollstepdisabled = false end elseif editorstate == "custom" then if customtabstate == "enemies" then if currentcustomenemy then local en = enemiesdata[currentcustomenemy[2]] if en then if en.animationtype == "mirror" then currentcustomenemy.timer = currentcustomenemy.timer + dt while currentcustomenemy.timer > en.animationspeed do currentcustomenemy.timer = currentcustomenemy.timer - en.animationspeed if currentcustomenemy.animationdirection == "left" then currentcustomenemy.animationdirection = "right" else currentcustomenemy.animationdirection = "left" end end elseif en.animationtype == "frames" then currentcustomenemy.timer = currentcustomenemy.timer + dt if type(en.animationspeed) == "table" then while currentcustomenemy.timer > en.animationspeed[currentcustomenemy.timerstage] do currentcustomenemy.timer = currentcustomenemy.timer - en.animationspeed[currentcustomenemy.timerstage] currentcustomenemy.quadi = currentcustomenemy.quadi + 1 if currentcustomenemy.quadi > en.animationstart + en.animationframes - 1 then currentcustomenemy.quadi = currentcustomenemy.quadi - en.animationframes end currentcustomenemy.timerstage = currentcustomenemy.timerstage + 1 if currentcustomenemy.timerstage > #en.animationspeed then currentcustomenemy.timerstage = 1 end end else while currentcustomenemy.timer > en.animationspeed do currentcustomenemy.timer = currentcustomenemy.timer - en.animationspeed currentcustomenemy.quadi = currentcustomenemy.quadi + 1 if currentcustomenemy.quadi > en.animationstart + en.animationframes - 1 then currentcustomenemy.quadi = currentcustomenemy.quadi - en.animationframes end end end end end end end end if musici == 7 and editorstate == "main" and guielements["custommusiciinput"].active == false then guielements["custommusiciinput"].active = true end if editortilemousescroll then editortilemousescrolltimer = editortilemousescrolltimer + dt if editortilemousescrolltimer > .4 then editortilemousescroll = false editortilemousescrolltimer = 0 end end if assistmode and not editormenuopen then --quick menu local x, y = love.mouse.getX()/scale, love.mouse.getY()/scale if ((x > ((width*8)-30) and y > (quickmenuy-7) and x < ((width*8)+30) and y < (quickmenuy+7)) or (x > (width*8)-((#latesttiles*24)/2) and y > (quickmenuy) and x < (width*8)+((#latesttiles*24)/2) and y < (quickmenuy)+24)) and not (quickmenuy == quickmenuclosedy and love.mouse.isDown("l")) then quickmenuy = math.max(quickmenuy-quickmenuspeed*dt, quickmenuopeny) quickmenuopen = true else quickmenuopen = false quickmenuy = math.min(quickmenuy+quickmenuspeed*dt, quickmenuclosedy) end if quickmenuopen then quickmenusel = false local checkx = (width*8)-((#latesttiles*24)/2) local val = math.ceil((x-checkx)/24) if val > 0 and val <= #latesttiles then quickmenusel = val end --[[for i = 1, #latesttiles do local checkx = (((width*8)-((#latesttiles*24)/2))+(24*(i-1))+2) if x > checkx and y > quickmenuy+2 and x < checkx+20 and y < quickmenuy+22 then quickmenusel = i break end end]] end end if animationguilines then for i, v in pairs(animationguilines) do for k, w in pairs(v) do w:update(dt) end end end end function editor_draw() love.graphics.setColor(255, 255, 255) local mousex, mousey = love.mouse.getPosition() --EDITOR if not editormenuopen then if customrcopen and customrcopen == "trackpath" then love.graphics.setColor(255, 255, 255, 200) properprintF(TEXT["erase: click previous track\nchange ends: right click\nchange grabbing: right click"], 1*scale, (height*16-3*10)*scale) elseif tileselection and tileselection.finished then love.graphics.setColor(255, 255, 255, 200) properprintF(TEXT["move:left click\ncopy:ctrl+c\npaste:ctrl+v\ncut:ctrl+x\ndelete:backspace/delete\nsave as object:ctrl+s"], 1*scale, (height*16-6*10)*scale) elseif ctrlpressed and not love.mouse.isDown("l") then love.graphics.setColor(255, 255, 255, 200) properprintF(TEXT["undo:ctrl+z\ntile selection:left click\nentity selection:ctrl+e\nselect entire map:ctrl+a"], 1*scale, (height*16-4*10)*scale) elseif backgroundtilemode or assistmode or editorstate == "linktool" or editorstate == "portalgun" or editorstate == "selectiontool" or editorstate == "powerline" then local s if backgroundtilemode then s = TEXT["background layer"] elseif assistmode then s = TEXT["assist mode"] elseif editorstate == "linktool" then s = TEXT["link tool"] elseif editorstate == "portalgun" then s = TEXT["portal gun"] elseif editorstate == "selectiontool" then s = TEXT["selection tool"] elseif editorstate == "powerline" then s = TEXT["power line draw"] end love.graphics.setColor(0, 0, 0, 120) properprintF(s, 3*scale, 211*scale) love.graphics.setColor(255, 255, 255, 180) properprintF(s, 2*scale, 210*scale) love.graphics.setColor(255, 255, 255, 255) end --links! if editorstate == "linktool" then love.graphics.setLineStyle("rough") love.graphics.setLineWidth(scale) local cox, coy = getMouseTile(mousex, mousey+8*screenzoom*scale) local table1 = {} for i, v in pairs(outputsi) do table.insert(table1, v) end for i, v in pairs(inputsi) do table.insert(table1, v) end for x = math.floor(splitxscroll[1]), math.floor(splitxscroll[1])+width+1 do for y = math.floor(splityscroll[1]), math.floor(splityscroll[1])+height+1 do for i, v in pairs(table1) do if inmap(x, y) and #map[x][y] > 1 and map[x][y][2] == v then local r = map[x][y] local drawline = false local printlabels = false if (rightclickmenuopen and x == rightclickmenucox and y == rightclickmenucoy) then love.graphics.setColor(0, 255, 0, 150) elseif (cox == x and coy == y and (not love.mouse.isDown("l"))) then love.graphics.setColor(0, 255, 0, 255) if tablecontains(r, "link") then drawline = true printlabels = true end elseif tablecontains(r, "link") then love.graphics.setColor(150, 255, 150, 100) drawline = true elseif tablecontains(outputsi, map[x][y][2]) and cox == x and coy == y and linktoolX and love.mouse.isDown("l") then love.graphics.setColor(255, 255, 0, 255) elseif tablecontains(outputsi, map[x][y][2]) then love.graphics.setColor(255, 255, 150, 150) elseif cox == x and coy == y and not love.mouse.isDown("l") then love.graphics.setColor(255, 0, 0, 255) else love.graphics.setColor(255, 150, 150, 150) end love.graphics.rectangle("fill", math.floor((x-splitxscroll[1]-1)*16*scale), ((y-splityscroll[1]-1)*16-8)*scale, 16*scale, 16*scale) if drawline then local tx, ty = x, y local x1, y1 = (tx-.5-xscroll)*16*scale, (ty-1-yscroll)*16*scale local x2, y2 local drawtable = {} for i = 1, #map[tx][ty] do if map[tx][ty][i] == "link" then if map[tx][ty][i+1] and tonumber(map[tx][ty][i+1]) and map[tx][ty][i+2] and tonumber(map[tx][ty][i+2]) then local next1, next2 = tonumber(map[tx][ty][i+1]), tonumber(map[tx][ty][i+2]) x2, y2 = math.floor((next1-xscroll-.5)*16*scale), math.floor((next2-yscroll-1)*16*scale) local t = map[tx][ty][i] if map[tx][ty][i+3] then t = map[tx][ty][i+3] end table.insert(drawtable, {x1, y1, x2, y2, t}) end end end table.sort(drawtable, function(a,b) return math.abs(a[3]-a[1])>math.abs(b[3]-b[1]) end) for i = 1, #drawtable do local x1, y1, x2, y2, t = unpack(drawtable[i]) love.graphics.setColor(127, 127, 255*(i/#drawtable), 255) love.graphics.line(x1, y1, x2, y2) if printlabels then properprintFbackground(t, math.floor(x2-string.len(t)*4*scale), y2+10*scale)--, {0, 0, 0, 255}) --why would the text be black? wtf, {0, 0, 0, 255}) end end end end end end end love.graphics.setLineStyle("smooth") end if rightclickmenuopen then if customrcopen then --custom right-click menus if customrcopen == "seesaw" then --draw seesaw local t = rightclickvalues2--seesawtype[rightclickvalues2[1]] if t[1] then local platwidth = math.floor((rightclickobjects[8].value*9+1)*2)/2 local x, y = rightclickmenucox, rightclickmenucoy love.graphics.setColor(255, 255, 255, 200) love.graphics.draw(seesawimg, seesawquad[spriteset][1], math.floor((x-1-xscroll)*16*scale), (y-1.5-yscroll)*16*scale, 0, scale, scale) love.graphics.draw(seesawimg, seesawquad[spriteset][2], math.floor((x-1+t[1]-xscroll)*16*scale), (y-1.5-yscroll)*16*scale, 0, scale, scale) for i = 1, t[1]-1 do love.graphics.draw(seesawimg, seesawquad[spriteset][4], math.floor((x-1+i-xscroll)*16*scale), (y-1.5-yscroll)*16*scale, 0, scale, scale) end for i = 1, t[2]-1 do love.graphics.draw(seesawimg, seesawquad[spriteset][3], math.floor((x-1-xscroll)*16*scale), (y+i-1.5-yscroll)*16*scale, 0, scale, scale) end for i = 1, t[3]-1 do love.graphics.draw(seesawimg, seesawquad[spriteset][3], math.floor((x+t[1]-1-xscroll)*16*scale), (y+i-1.5-yscroll)*16*scale, 0, scale, scale) end for i = 1, platwidth do local q = 2 if i == 1 then q = 1 elseif i == platwidth then q = 3 end love.graphics.draw(platformimg, platformquad[q], math.floor((x-(platwidth/2)+i-1.5-xscroll)*16*scale), math.floor((y+t[2]-yscroll-25/16)*16*scale), 0, scale, scale) love.graphics.draw(platformimg, platformquad[q], math.floor((x-(platwidth/2)+t[1]+i-1.5-xscroll)*16*scale), math.floor((y+t[3]-yscroll-25/16)*16*scale), 0, scale, scale) end if math.ceil(platwidth) ~= platwidth then love.graphics.draw(platformimg, platformquad[3], math.floor((x-(platwidth/2)+platwidth-1.5-xscroll)*16*scale), math.floor((y+t[2]-yscroll-25/16)*16*scale), 0, scale, scale) love.graphics.draw(platformimg, platformquad[3], math.floor((x-(platwidth/2)+t[1]+platwidth-1.5-xscroll)*16*scale), math.floor((y+t[3]-yscroll-25/16)*16*scale), 0, scale, scale) end end elseif customrcopen == "platformup" or customrcopen == "platformright" or customrcopen == "platform" or customrcopen == "platformfall" then local t = rightclickvalues2 if t[1] then local platwidth = math.floor((rightclickobjects[2].value*9+1)*2)/2 local dx, dy = 0, 0 if customrcopen ~= "platformfall" then dx = round(rightclickobjects[4].value*(rightclickobjects[4].rcrange[2]-rightclickobjects[4].rcrange[1])+rightclickobjects[4].rcrange[1], 4) dy = round(rightclickobjects[6].value*(rightclickobjects[6].rcrange[2]-rightclickobjects[6].rcrange[1])+rightclickobjects[6].rcrange[1], 4) end local x, y = rightclickmenucox, rightclickmenucoy local offx, offy = 0, 0 if platwidth ~= math.floor(platwidth) then --or customrcopen == "platform" then offx = -platwidth/2+0.5 end if customrcopen == "platformup" then offy = -8/16 elseif (customrcopen == "platformright" and dy ~= 0) then offy = -15/16 end for i = 1, platwidth do local q = 2 if i == 1 then q = 1 elseif i == platwidth then q = 3 end love.graphics.setColor(255,255,255,255) love.graphics.draw(platformimg, platformquad[q], math.floor((x+i-2-xscroll+offx)*16*scale), math.floor((y-yscroll-23/16+offy)*16*scale), 0, scale, scale) love.graphics.setColor(255,255,255,100) love.graphics.draw(platformimg, platformquad[q], math.floor((x+dx+i-2-xscroll+offx)*16*scale), math.floor((y+dy-yscroll-23/16+offy)*16*scale), 0, scale, scale) end if math.ceil(platwidth) ~= platwidth then love.graphics.setColor(255,255,255,255) love.graphics.draw(platformimg, platformquad[3], math.floor((x+platwidth-2-xscroll+offx)*16*scale), math.floor((y-yscroll-23/16+offy)*16*scale), 0, scale, scale) love.graphics.setColor(255,255,255,100) love.graphics.draw(platformimg, platformquad[3], math.floor((x+dx+platwidth-2-xscroll+offx)*16*scale), math.floor((y+dy-yscroll-23/16+offy)*16*scale), 0, scale, scale) end end elseif customrcopen == "belt" or customrcopen == "beltswitch" then drawbelt(rightclickmenucox, rightclickmenucoy, rightclickvalues2[2], customrcopen, rightclickvalues2[3] or false) elseif customrcopen == "redseesaw" then redseesaweditordraw(rightclickmenucox-1, rightclickmenucoy-1, tonumber(rightclickvalues2[1]) or 1) elseif customrcopen == "bowser" then local x, y = rightclickmenucox, rightclickmenucoy local ox = 4 local qi = 1 if rightclickvalues2[1] == 2 then ox = -1 qi = 2 end love.graphics.setColor(255, 255, 255, 200) love.graphics.draw(bowserimg, bowserquad[qi][1][1], math.floor((x+ox-xscroll)*16*scale), (y-2.5-yscroll+1/16)*16*scale, 0, scale, scale) elseif customrcopen == "text" then if rightclickvalues2[1] then local textx, texty = ((rightclickmenucox-1))-xscroll, (rightclickmenucoy-1-(3/16)-yscroll) local size, sizesep = 1, 8/16 if rightclickvalues2[6] and tostring(rightclickvalues2[6]) == "true" then --big size, sizesep = 2, 1 texty = texty - 4/16 end if rightclickvalues2[5] and tostring(rightclickvalues2[5]) == "true" then --centered textx = textx - ((#rightclickvalues2[1]*sizesep)/2)+.5 end if rightclickvalues2[2] then love.graphics.setColor(textcolors[rightclickobjects[4].entries[rightclickvalues2[2]]]) end if rightclickvalues2[3] and tostring(rightclickvalues2[3]) == "true" then properprintbackground(rightclickvalues2[1], textx*16*scale, texty*16*scale, nil, nil, size) end properprint(rightclickvalues2[1], textx*16*scale, texty*16*scale, size) end elseif customrcopen == "castlefireccw" or customrcopen == "castlefirecw" then local x, y = rightclickmenucox, rightclickmenucoy local length, delay, angle = rightclickvalues2[1] or 3, 0, rightclickvalues2[3] or 0 for i = 1, length do love.graphics.draw(fireballimg, fireballquad[1], math.floor((x-0.75+(((i-1)/2)*math.sin(((-angle+90)/360)*math.pi*2))-xscroll)*16*scale), math.floor((y-1.25+(((i-1)/2)*math.cos(((-angle+90)/360)*math.pi*2))-yscroll)*16*scale), 0, scale, scale) end elseif customrcopen == "tiletool" then --tile tool preview local tile local x, y = rightclickmenucox, rightclickmenucoy local mod = false local command = rightclickvalues2[1] if string.sub(command, 1, 10) == "change to " then tile = tonumber(string.sub(command, 11, -1)) elseif string.sub(command, 1, 12) == "set back to " then tile = tonumber(string.sub(command, 13, -1)) elseif string.sub(command, 1, 4) == "mod " then mod = true local s = command:split(" ") local s2 = command:find(" to ") if s2 and s[2] and tonumber(s[2]) and s[3] and tonumber(s[3]) and tonumber(command:sub(s2+4, -1)) then x = tonumber(s[2]) y = tonumber(s[3]) tile = tonumber(command:sub(s2+4, -1)) end love.graphics.setColor(255,255,255,150) local tx, ty = getMouseTile(mousex, mousey+8*screenzoom*scale) properprint(tx .. "-" .. ty, mousex, mousey) end --tile tool preview selection if tile and tilequads[tile] then love.graphics.setColor(255, 255, 255, 150) if mod then love.graphics.draw(tilequads[tile].image, tilequads[tile].quad, math.floor((x-xscroll-1)*16*scale), math.floor(((y-yscroll-2)*16+8)*scale), 0, scale, scale) else local x1, x2, y1, y2 = x, y, x, y if rightclickvalues2[2] then local v1, v2 = rightclickvalues2[4]:gsub("n", "-"), rightclickvalues2[5]:gsub("n", "-") local v3, v4 = rightclickvalues2[2]:gsub("n", "-"), rightclickvalues2[3]:gsub("n", "-") x1, y1 = x+(tonumber(v1) or 0), y+(tonumber(v2) or 0) x2, y2 = x1+(tonumber(v3) or 1)-1, y1+(tonumber(v4) or 1)-1 end for dx = x1, x2 do for dy = y1, y2 do love.graphics.draw(tilequads[tile].image, tilequads[tile].quad, math.floor((dx-xscroll-1)*16*scale), math.floor(((dy-yscroll-2)*16+8)*scale), 0, scale, scale) end end end end elseif customrcopen == "faithplateup" or customrcopen == "faithplateleft" or customrcopen == "faithplateright" then local yoffset = -8/16 local x = rightclickmenucox-.5 local y = rightclickmenucoy-.5 local pointstable = {(x-xscroll)*16*scale, ((y+yoffset)-yscroll-.5)*16*scale} local speedx, speedy speedx = (rightclickobjects[2].value*100-50) speedy = -(rightclickobjects[4].value*45+5) local step = 1/60 repeat x, y = x+speedx*step, y+speedy*step speedy = speedy + yacceleration*step table.insert(pointstable, (x-xscroll)*16*scale) table.insert(pointstable, ((y+yoffset)-yscroll-.5)*16*scale) until y+yoffset > yscroll+height+.5 love.graphics.setColor(62, 213, 244, 160) love.graphics.setLineWidth(3) love.graphics.line(pointstable) elseif customrcopen == "snakeblock" then if rightclickvalues2[2] and rightclickvalues2[3] then local q = 1 if tonumber(rightclickvalues2[3]) > snakeblockspeed then q = 3 end for i = 1, tonumber(rightclickvalues2[2]) do local x, y = rightclickmenucox-i+1, rightclickmenucoy love.graphics.draw(snakeblockimg, starquad[spriteset][q], math.floor((x-xscroll-.5)*16*scale), math.floor(((y-yscroll-1.5)*16+8)*scale), 0, scale, scale, 8, 8) end end end if customrcopen == "region" then guielements["rightclickdrag"]:draw() elseif customrcopen == "path" then local rcp = rightclickpath local lx, ly = rcp.last[1], rcp.last[2]--last pos local quadcenterx, quadcentery = 8, 8 if rcp.pipe then quadcenterx = 24 end for i = #rcp.path, 1, -1 do local offx, offy = 0, 0 --get quad (direction and start) local q = 1 local r = 0 if i == #rcp.path then if rcp.pipe then --make big (pipe) q = 4 else quadcenterx = 8 q = 2 end if rcp.dir == "right" then r = math.pi*0.5 elseif rcp.dir == "left" then r = math.pi*1.5; if rcp.pipe then offy = -16 end elseif rcp.dir == "down" then r = math.pi; if rcp.pipe then offx = -16 end end else if rcp.pipe then --make wide (pipe) quadcenterx = 24 q = 3 end local dir = "up" if lx > rcp.path[i][1] then r = math.pi*0.5; dir = "right" elseif lx < rcp.path[i][1] then r = math.pi*1.5; dir = "left"; if rcp.pipe then offy = -16 end elseif ly > rcp.path[i][2] then r = math.pi; dir = "down"; if rcp.pipe then offx = -16 end end if rcp.pipe then if (rcp.path[i-1] and rcp.path[i+1]) and not ((rcp.path[i+1][1] ~= rcp.path[i-1][1] and rcp.path[i+1][2] == rcp.path[i-1][2]) or (rcp.path[i+1][2] ~= rcp.path[i-1][2] and rcp.path[i+1][1] == rcp.path[i-1][1])) then q = 5 if dir == "left" then offx = -16 elseif dir == "up" then offy = -16 end elseif (rcp.path[i-1] and rcp.path[i-2]) and ((dir == "right" and rcp.path[i][2] ~= rcp.path[i-1][2]) or (dir == "left" and rcp.path[i][2] == rcp.path[i-1][2] and rcp.path[i][2] ~= rcp.path[i-2][2]) or (dir == "down" and rcp.path[i][1] ~= rcp.path[i-1][1]) or (dir == "up" and rcp.path[i][1] == rcp.path[i-1][1] and rcp.path[i][1] ~= rcp.path[i-2][1])) then --is the path 2 tiles ago in a different direction? q = false elseif (rcp.path[i+1] and rcp.path[i+2]) and ((dir == "left" and rcp.path[i][2] ~= rcp.path[i+1][2]) or (dir == "right" and rcp.path[i][2] == rcp.path[i+1][2] and rcp.path[i][2] ~= rcp.path[i+2][2]) or (dir == "up" and rcp.path[i][1] ~= rcp.path[i+1][1]) or (dir == "down" and rcp.path[i][1] == rcp.path[i+1][1] and rcp.path[i][1] ~= rcp.path[i+2][1])) then --is the path 2 tiles ahead in a different direction? q = false end end end if q then lx, ly = rcp.path[i][1], rcp.path[i][2] love.graphics.draw(pathmarkerimg, pathmarkerquad[q], math.floor(((rcp.x+rcp.path[i][1]-xscroll-.5)*16+offx)*scale), math.floor(((rcp.y+rcp.path[i][2]-yscroll-1.5)*16+offy+8)*scale), r, scale, scale, quadcenterx, quadcentery) end end elseif customrcopen == "trackpath" then love.graphics.setColor(255,255,255) local rcp = rightclicktrack local lx, ly = rcp.last[1], rcp.last[2]--last pos for i = 1, #rcp.path do local tx, ty = rcp.x+rcp.path[i][1], rcp.y+rcp.path[i][2] drawtrack(tx, ty, rcp.path[i][3], rcp.path[i][4]) --is object selected to be tracked? (d=default(entity),r=reverse,t=tile,tr=tile reverse) if i ~= 1 and i ~= ismaptile(tx, ty) and (map[tx][ty][2] or rcp.path[i][5] == "t" or rcp.path[i][5] == "tr" or rcp.path[i][5] == "tf" or rcp.path[i][5] == "tfr") then local trackable = rcp.path[i][5] or "d" if trackable ~= "" then local dir = rcp.path[i][4] local quadi = 1 local r = 0 if dir == "r" or dir == "ru" or dir == "rd" or dir == "u" then dir = oppositetrackdirection(dir) end if trackable == "r" or trackable == "tr" or trackable == "fr" or trackable == "tfr" then dir = oppositetrackdirection(dir) end if dir == "l" or dir == "lu" then r = 0 elseif dir == "r" or dir == "rd" then r = math.pi elseif dir == "u" or dir == "ru" then r = math.pi*.5 elseif dir == "d" or dir == "ld" then r = math.pi*1.5 end if trackable == "d" or trackable == "r" or trackable == "f" or trackable == "fr" then if #dir == 2 then --diagonal quadi = 2 else quadi = 1 end elseif trackable == "t" or trackable == "tr" or trackable == "tf" or trackable == "tfr" then if map[tx][ty][2] then love.graphics.draw(tilequads[map[tx][ty][1]].image, tilequads[map[tx][ty][1]].quad, math.floor(((tx-xscroll-1)*16)*scale), math.floor(((ty-yscroll-1.5)*16)*scale), 0, scale, scale) end if #dir == 2 then --diagonal quadi = 4 else quadi = 3 end end local cox, coy = getMouseTile(mousex, mousey+8*screenzoom*scale) if (cox == tx and coy == ty and not trackrightclickmenu.active) or (trackrightclickmenu.active and trackrightclickmenustage == i) then love.graphics.setColor(255,216,0,255) end love.graphics.draw(trackmarkerimg, trackmarkerquad[quadi], math.floor(((tx-xscroll-.5)*16)*scale), math.floor(((ty-yscroll-1)*16)*scale), r, scale, scale, 8, 8) love.graphics.setColor(255,255,255) end end end --next track love.graphics.setColor(255,216,0,150) local left, right, up, down, leftup, leftdown, rightup, rightdown = true,true,true,true,true,true,true,true for i = #rcp.path, 1, -1 do --check overlap local x, y = rcp.path[i][1], rcp.path[i][2] if x == lx-1 and y == ly then left = false elseif x == lx+1 and y == ly then right = false elseif x == lx and y == ly-1 then up = false elseif x == lx and y == ly+1 then down = false elseif x == lx-1 and y == ly-1 then leftup = false elseif x == lx-1 and y == ly+1 then leftdown = false elseif x == lx+1 and y == ly-1 then rightup = false elseif x == lx+1 and y == ly+1 then rightdown = false end end if left then drawtrack(rcp.x+lx-1, rcp.y+ly, "c", "c") end if right then drawtrack(rcp.x+lx+1, rcp.y+ly, "c", "c") end if up then drawtrack(rcp.x+lx, rcp.y+ly-1, "c", "c") end if down then drawtrack(rcp.x+lx, rcp.y+ly+1, "c", "c") end if leftup then drawtrack(rcp.x+lx-1, rcp.y+ly-1, "c", "c") end if leftdown then drawtrack(rcp.x+lx-1, rcp.y+ly+1, "c", "c") end if rightup then drawtrack(rcp.x+lx+1, rcp.y+ly-1, "c", "c") end if rightdown then drawtrack(rcp.x+lx+1, rcp.y+ly+1, "c", "c") end --right click menu if trackrightclickmenu.active then trackrightclickmenu:draw() end elseif customrcopen == "link" then local x1, y1 = math.floor((linktoolX-xscroll-.5)*16*scale), math.floor((linktoolY-yscroll-1)*16*scale) local x2, y2 = mousex, mousey --draw proper outputs for x = math.floor(splitxscroll[1]), math.floor(splitxscroll[1])+width+1 do for y = math.floor(splityscroll[1]), math.floor(splityscroll[1])+height+1 do for i, v in pairs(outputsi) do if inmap(x, y) and #map[x][y] > 1 and map[x][y][2] == v then local r = map[x][y] if tablecontains(outputsi, map[x][y][2]) then love.graphics.setColor(255, 255, 150, 150) else love.graphics.setColor(255, 150, 150, 150) end love.graphics.rectangle("fill", math.floor((x-splitxscroll[1]-1)*16*scale), ((y-splityscroll[1]-1)*16-8)*scale, 16*scale, 16*scale) end end end end love.graphics.setColor(255, 172, 47, 255) drawlinkline(x1, y1, x2, y2) love.graphics.setColor(200, 140, 30, 255) love.graphics.draw(linktoolpointerimg, x2-math.ceil(scale/2), y2, 0, scale, scale, 3, 3) properprintFbackground(linktoolt, math.floor(x2+4*scale), y2-4*scale, true) else --draw links local tx, ty = rightclickmenucox, rightclickmenucoy local x1, y1 = (rightclickmenucox-.5-xscroll)*16*scale, (rightclickmenucoy-1-yscroll)*16*scale local x2, y2 local drawtable = {} for i = 1, #map[tx][ty] do if map[tx][ty][i] == "link" and map[tx][ty][i+1] and map[tx][ty][i+2] then x2, y2 = math.floor((map[tx][ty][i+1]-xscroll-.5)*16*scale), math.floor((map[tx][ty][i+2]-yscroll-1)*16*scale) local t = map[tx][ty][i] if map[tx][ty][i+3] then t = map[tx][ty][i+3] end table.insert(drawtable, {x1, y1, x2, y2, t}) end end table.sort(drawtable, function(a,b) return math.abs(a[3]-a[1])>math.abs(b[3]-b[1]) end) for i = 1, #drawtable do local x1, y1, x2, y2, t = unpack(drawtable[i]) love.graphics.setColor(127, 127, 255*(i/#drawtable), 255) if math.fmod(i, 2) == 0 then drawlinkline2(x1, y1, x2, y2) else drawlinkline(x1, y1, x2, y2) end properprintFbackground(t, math.floor(x2-string.len(t)*4*scale), y2+10*scale, true)--, {0, 0, 0, 255}) --why would the text be black? wtf end --draw actual menu love.graphics.setColor(10, 10, 10, 190) love.graphics.rectangle("fill", rightclickobjects.x*scale, rightclickobjects.y*scale, rightclickobjects.width*scale, rightclickobjects.height*scale) --draw them bottom to top to make drop-downs work love.graphics.setColor(255, 255, 255) local ontop = {} --drop ups drawn on top for i = #rightclickobjects, 1, -1 do local obj = rightclickobjects[i] if obj.type == "dropdown" and obj.extended then table.insert(ontop, i) elseif not obj.dontdraw then obj:draw() end end --draw on top objects for i = 1, #ontop do local obj = rightclickobjects[ontop[i]] obj:draw() end end elseif rightclickmenu then rightclickmenu:draw() end elseif editorstate ~= "linktool" and editorstate ~= "portalgun" and editorstate ~= "selectiontool" and editorstate ~= "powerline" then local x, y = getMouseTile(love.mouse.getX(), love.mouse.getY()-8*screenzoom*scale) love.graphics.push() love.graphics.scale(screenzoom,screenzoom) if inmap(x, y+1) then if pastingtiles then -- draw mtclipboard for i, v in ipairs(mtclipboard) do for j, w in ipairs(v) do --w = tonumber(w) local tilei = w[1] if tilei == 1 and pastemode == 1 then love.graphics.setColor(255, 255, 255, 8) love.graphics.draw(tilequads[tilei].image, tilequads[tilei].quad, math.floor((x-splitxscroll[1]-1 + pastecenter[1])*16*scale)+(i-1)*16*scale, ((y-splityscroll[1]-1 + pastecenter[2])*16+8)*scale+((j-1)*16*scale), 0, scale, scale) else love.graphics.setColor(255, 255, 255, 72) love.graphics.draw(tilequads[tilei].image, tilequads[tilei].quad, math.floor((x-splitxscroll[1]-1 + pastecenter[1])*16*scale)+(i-1)*16*scale, ((y-splityscroll[1]-1 + pastecenter[2])*16+8)*scale+((j-1)*16*scale), 0, scale, scale) end local entityi = w[2] if entityi and type(w[2]) == "number" then love.graphics.setColor(255, 255, 255, 72) love.graphics.draw(entityquads[entityi].image, entityquads[entityi].quad, math.floor((x-splitxscroll[1]-1 + pastecenter[1])*16*scale)+(i-1)*16*scale, ((y-splityscroll[1]-1 + pastecenter[2])*16+8)*scale+((j-1)*16*scale), 0, scale, scale) end end end --end if android then love.graphics.setColor(255, 255, 255, 200) love.graphics.setLineWidth(1*scale) love.graphics.rectangle("line",math.floor((x-splitxscroll[1]-1)*16*scale), math.floor(((y-splityscroll[1]-1)*16+8)*scale), 16*scale, 16*scale) end end love.graphics.setColor(255, 255, 255, 200) if tileselection or ctrlpressed or tileselectionmoving then local x1, y1 = x, y+1 local x2, y2 = x, y+1 if tileselection then x1, y1 = math.min(tileselection[1],tileselection[3]),math.min(tileselection[2],tileselection[4]) x2, y2 = math.max(tileselection[1],tileselection[3]),math.max(tileselection[2],tileselection[4]) elseif tileselectionmoving then x1, y1 = x+pastecenter[1], y+pastecenter[2]+1 x2, y2 = x+pastecenter[1]+#mtclipboard-1, y+pastecenter[2]+#mtclipboard[1] end x1, y1 = math.max(xscroll-1, x1), math.max(yscroll-1, y1) x2, y2 = math.min(xscroll+width*screenzoom2+1, x2), math.min(yscroll+height*screenzoom2+1, y2) local sx, sy, sw, sh = x1-1, y1-1, x2-x1+1, y2-y1+1 love.graphics.setColor(0, 131, 255, 45) love.graphics.rectangle("fill", ((sx-xscroll)*16)*scale,((sy-yscroll)*16-8)*scale, sw*16*scale, sh*16*scale) love.graphics.setColor(255,255,255) love.graphics.stencil(function() love.graphics.setLineWidth(scale) love.graphics.rectangle("line", (math.floor((sx-xscroll)*16)+.5)*scale, (math.floor((sy-yscroll)*16)-8+.5)*scale, (sw*16-1)*scale, (sh*16-1)*scale) end, "increment") love.graphics.setStencilTest("greater", 0) for mx = 2, sw do love.graphics.draw(antsimg, math.floor(((sx+mx-1-xscroll)*16-math.floor(tileselectionants)))*scale, math.floor((sy-yscroll)*16-8-math.floor(tileselectionants))*scale, 0, scale, scale) love.graphics.draw(antsimg, math.floor(((sx+mx-1-xscroll)*16-math.floor(tileselectionants)))*scale, math.floor((sy+sh-1-yscroll)*16-8-math.floor(tileselectionants))*scale, 0, scale, scale) love.graphics.draw(antsimg, math.floor(((sx+mx-1-xscroll)*16-math.floor(tileselectionants)))*scale, math.floor((sy+sh-yscroll)*16-8-math.floor(tileselectionants))*scale, 0, scale, scale) end for my = 1, sh+1 do love.graphics.draw(antsimg, math.floor(((sx-xscroll)*16-math.floor(tileselectionants)))*scale, math.floor((sy+my-1-yscroll)*16-8-math.floor(tileselectionants))*scale, 0, scale, scale) love.graphics.draw(antsimg, math.floor(((sx+sw-1-xscroll)*16-math.floor(tileselectionants)))*scale, math.floor((sy+my-1-yscroll)*16-8-math.floor(tileselectionants))*scale, 0, scale, scale) love.graphics.draw(antsimg, math.floor(((sx+sw-xscroll)*16-math.floor(tileselectionants)))*scale, math.floor((sy+my-1-yscroll)*16-8-math.floor(tileselectionants))*scale, 0, scale, scale) end love.graphics.setStencilTest() elseif editentities == false and not pastingtiles then love.graphics.draw(tilequads[currenttile].image, tilequads[currenttile].quad, math.floor((x-splitxscroll[1]-1)*16*scale), math.floor(((y-splityscroll[1]-1)*16+8)*scale), 0, scale, scale) if android then love.graphics.setLineWidth(1*scale) love.graphics.rectangle("line",math.floor((x-splitxscroll[1]-1)*16*scale), math.floor(((y-splityscroll[1]-1)*16+8)*scale), 16*scale, 16*scale) end if editortilemousescroll and (brushsizex <= 1 and brushsizey <= 1) then for i = 1, 2 do love.graphics.setColor(255, 255, 255, 200-(i*70)) if currenttile - i >= 1 then if currenttile - i >= 89996 and currenttile - i < 90001 then else love.graphics.draw(tilequads[currenttile-i].image, tilequads[currenttile-i].quad, math.floor((x-splitxscroll[1]-1)*16*scale), math.floor(((y-splityscroll[1]-1)*16+8-((i*16)+i))*scale), 0, scale, scale) end end end for i = 1, 2 do love.graphics.setColor(255, 255, 255, 200-(i*70)) if (currenttile + i > smbtilecount+portaltilecount+customtilecount and currenttile + i < 90000) or (currenttile + i > animatedtilecount+90000 and currenttile + i > 89996) then else love.graphics.draw(tilequads[currenttile+i].image, tilequads[currenttile+i].quad, math.floor((x-splitxscroll[1]-1)*16*scale), math.floor(((y-splityscroll[1]-1)*16+8+((i*16)+i))*scale), 0, scale, scale) end end elseif (brushsizex > 1 or brushsizey > 1) then for xl = 1, brushsizex do for yl = 1, brushsizey do if yl == 1 and xl == 1 then else love.graphics.setColor(255, 255, 255, 200) love.graphics.draw(tilequads[currenttile].image, tilequads[currenttile].quad, math.floor((x-splitxscroll[1]-1+xl-1)*16*scale), math.floor(((y-splityscroll[1]-1+yl-1)*16+8)*scale), 0, scale, scale) end end end end --replace tiles if love.keyboard.isDown("e") and not android then local ontile = map[x][y+1][1] for x = math.floor(xscroll)+1, math.min(mapwidth, math.floor(xscroll+width)+1) do for y = math.floor(yscroll)+1, math.min(mapheight, math.floor(yscroll+height)+1) do if onscreen(x-1, y-1, 1, 1) and ontile == map[x][y][1] then love.graphics.setColor(255, 255, 255, 200) love.graphics.draw(tilequads[currenttile].image, tilequads[currenttile].quad, math.floor((x-splitxscroll[1]-1)*16*scale), math.floor(((y-splityscroll[1]-2)*16+8)*scale), 0, scale, scale) end end end elseif love.keyboard.isDown("f") and not android then local ontile = map[x][y+1][1] if backgroundtilemode then ontile = map[x][y+1]["back"] end local replacetiles = paintbucket(x, y+1, ontile, "onscreen") for i, t in pairs(replacetiles) do local x, y = t[1], t[2] --if onscreen(x-1, y-1, 1, 1) then love.graphics.setColor(255, 255, 255, 200) love.graphics.draw(tilequads[currenttile].image, tilequads[currenttile].quad, math.floor((x-splitxscroll[1]-1)*16*scale), math.floor(((y-splityscroll[1]-2)*16+8)*scale), 0, scale, scale) --end end end elseif not pastingtiles then if not tilequads[currenttile] and enemiesdata[currenttile] then --custom enemy local v = enemiesdata[currenttile] if v.showicononeditor and v.icongraphic then love.graphics.draw(v.icongraphic, math.floor((x-xscroll-1)*16*scale), math.floor(((y-yscroll-0.5)*16)*scale), 0, scale, scale) else local xoff, yoff = ((0.5-v.width/2+(v.spawnoffsetx or 0))*16 + v.offsetX - v.quadcenterX)*scale, (((v.spawnoffsety or 0)-v.height+1)*16-v.offsetY - v.quadcenterY)*scale love.graphics.draw(v.graphic, v.quad, math.floor((x-xscroll-1)*16*scale+xoff), math.floor(((y-yscroll)*16)*scale+yoff), 0, scale, scale) end else --offset enemy local offsetx = 0 if entitylist[currenttile] and entitylist[currenttile].offset then local allowoffset = true --don't clip with entity on the right if ismaptile(x+1, y+1) and map[x+1][y+1][2] and map[x+1][y+1][2] == currenttile and not map[x+1][y+1].argument then allowoffset = false elseif ismaptile(x, y+1) and map[x][y+1][2] and map[x][y+1][2] == currenttile and not map[x][y+1].argument then allowoffset = false end if allowoffset then local mx = ((love.mouse.getX()/scale)+(xscroll*16))%16 --[[if mx < 16*0 then offsetx = -.5 else]]if mx > 16*0.75 then offsetx = .5 end end end love.graphics.draw(entityquads[currenttile].image, entityquads[currenttile].quad, math.floor((x-splitxscroll[1]-1+offsetx)*16*scale), math.floor(((y-splityscroll[1]-1)*16+8)*scale), 0, scale, scale) end if android then love.graphics.setLineWidth(1*scale) love.graphics.rectangle("line",math.floor((x-splitxscroll[1]-1)*16*scale), math.floor(((y-splityscroll[1]-1)*16+8)*scale), 16*scale, 16*scale) end if editortilemousescroll and ( brushsizex <= 1 and brushsizey <= 1) then if type(editortilemousescroll) == "table" then local t = editortilemousescroll for i = 1, 2 do love.graphics.setColor(255, 255, 255, 200-(i*70)) if tonumber(t[i]) and t[i] > 0 then love.graphics.draw(entityquads[t[i]].image, entityquads[t[i]].quad, math.floor((x-splitxscroll[1]-1)*16*scale), math.floor(((y-splityscroll[1]-1)*16+8-((i*16)+i))*scale), 0, scale, scale) end end for i = 1, 2 do love.graphics.setColor(255, 255, 255, 200-(i*70)) if tonumber(t[2+i]) and t[2+i] > 0 then love.graphics.draw(entityquads[t[2+i]].image, entityquads[t[2+i]].quad, math.floor((x-splitxscroll[1]-1)*16*scale), math.floor(((y-splityscroll[1]-1)*16+8+((i*16)+i))*scale), 0, scale, scale) end end elseif type(currenttile) == "number" then for i = 1, 2 do love.graphics.setColor(255, 255, 255, 200-(i*70)) if currenttile - i > 0 then love.graphics.draw(entityquads[currenttile-i].image, entityquads[currenttile-i].quad, math.floor((x-splitxscroll[1]-1)*16*scale), math.floor(((y-splityscroll[1]-1)*16+8-((i*16)+i))*scale), 0, scale, scale) end end for i = 1, 2 do love.graphics.setColor(255, 255, 255, 200-(i*70)) if currenttile + i < #entitylist then love.graphics.draw(entityquads[currenttile+i].image, entityquads[currenttile+i].quad, math.floor((x-splitxscroll[1]-1)*16*scale), math.floor(((y-splityscroll[1]-1)*16+8+((i*16)+i))*scale), 0, scale, scale) end end end elseif (brushsizex > 1 or brushsizey > 1) then for xl = 1, brushsizex do for yl = 1, brushsizey do if yl == 1 and xl == 1 then elseif not tilequads[currenttile] and enemiesdata[currenttile] then --custom enemy local v = enemiesdata[currenttile] if v.showicononeditor and v.icongraphic then love.graphics.draw(v.icongraphic, math.floor((x-splitxscroll[1]-1+xl-1)*16*scale), math.floor(((y-splityscroll[1]-0.5+yl-1)*16)*scale), 0, scale, scale) else local xoff, yoff = ((0.5-v.width/2+(v.spawnoffsetx or 0))*16 + v.offsetX - v.quadcenterX)*scale, (((v.spawnoffsety or 0)-v.height+1)*16-v.offsetY - v.quadcenterY)*scale love.graphics.draw(v.graphic, v.quad, math.floor((x-splitxscroll[1]-1+xl-1)*16*scale+xoff), math.floor(((y-splityscroll[1]-1+yl-1)*16+16)*scale+yoff), 0, scale, scale) end else love.graphics.setColor(255, 255, 255, 200) love.graphics.draw(entityquads[currenttile].image, entityquads[currenttile].quad, math.floor((x-splitxscroll[1]-1+xl-1)*16*scale), math.floor(((y-splityscroll[1]-1+yl-1)*16+8)*scale), 0, scale, scale) end end end end end end love.graphics.pop() end if assistmode and not editormenuopen then --quickmenu love.graphics.setColor(0, 0, 0, 110) love.graphics.rectangle("fill", ((width*8)-30)*scale, (quickmenuy-7)*scale, 60*scale, 7*scale) love.graphics.setColor(255, 255, 255, 200) if quickmenuopen then love.graphics.draw(quickmenuarrowimg, ((width*8)-3)*scale, (quickmenuy-1)*scale, 0, scale, -scale) else love.graphics.draw(quickmenuarrowimg, ((width*8)-3)*scale, (quickmenuy-6)*scale, 0, scale, scale) end if quickmenuy ~= quickmenuclosedy then love.graphics.setColor(0, 0, 0, 180) love.graphics.rectangle("fill", ((width*8)-((#latesttiles*24)/2))*scale, (quickmenuy)*scale, (#latesttiles*24)*scale, 24*scale) love.graphics.setColor(0, 0, 0, 200) love.graphics.rectangle("fill", ((width*8)-((#latesttiles*24)/2)+47)*scale, (quickmenuy+2)*scale, 2*scale, 20*scale) for i = 1, #latesttiles do local t = latesttiles[i] love.graphics.setColor(255, 255, 255, 255) local x = (((width*8)-((#latesttiles*24)/2))+(24*(i-1))+4) if t[1] == 1 and tilequads[t[2]] then love.graphics.draw(tilequads[t[2]].image, tilequads[t[2]].quad, x*scale, (quickmenuy+4)*scale, 0, scale, scale) elseif t[1] == 2 and entityquads[t[2]] then if type(t[2]) == "string" then local v = enemiesdata[t[2]] love.graphics.setScissor(x*scale, (quickmenuy+4)*scale, 16*scale, 16*scale) if v.icongraphic then love.graphics.draw(v.icongraphic, x*scale, (quickmenuy+4)*scale, 0, scale, scale) elseif v.quad then love.graphics.draw(v.graphic, v.quad, x*scale, (quickmenuy+4)*scale, 0, scale, scale) else love.graphics.draw(entityquads[1].image, entityquads[1].quad, x*scale, (quickmenuy+4)*scale, 0, scale, scale) end love.graphics.setScissor() else love.graphics.draw(entityquads[t[2]].image, entityquads[t[2]].quad, x*scale, (quickmenuy+4)*scale, 0, scale, scale) end end if quickmenusel == i then love.graphics.setColor(255, 255, 255, 127) love.graphics.rectangle("fill", x*scale, (quickmenuy+4)*scale, 16*scale, 16*scale) end end end love.graphics.setColor(255, 255, 255, 255) end if editorstate == "selectiontool" then if selectiontoolclick[1][1] and selectiontoolclick[1][2] then love.graphics.setLineStyle("rough") love.graphics.setLineWidth(2*scale) love.graphics.rectangle("line", (selectiontoolclick[1][1] - xscroll*16)*scale, (selectiontoolclick[1][2] - yscroll*16)*scale, mousex-(selectiontoolclick[1][1] - xscroll*16)*scale, mousey-(selectiontoolclick[1][2] - yscroll*16)*scale) love.graphics.setLineStyle("smooth") elseif #selectiontoolselection > 0 and not rightclickmenuopen then love.graphics.setColor(255, 255, 255, 120) for i, t in pairs(selectiontoolselection) do local x, y = t[1], t[2] love.graphics.rectangle("fill", math.floor((x-splitxscroll[1]-1)*16*scale), ((y-splityscroll[1]-1)*16-8)*scale, 16*scale, 16*scale) end end end if love.keyboard.isDown("lalt") then love.graphics.setColor(255, 255, 255, 120) local tx, ty = getMouseTile(mousex, mousey+8*scale) properprint(tx .. "-" .. ty, mousex, mousey) -- .. " " .. tilemap(tx, ty) end elseif changemapwidthmenu or minimapmoving then local w = width*16-52 local h = height*16-52 local s, nmw, nmox, nmh, nmoy --newmapwidth, newmapoffsetx, newmapheight, newmapoffsety if changemapwidthmenu then s = math.min(w/newmapwidth, h/newmapheight) w = newmapwidth*s h = newmapheight*s nmw = newmapwidth nmox = newmapoffsetx nmh = newmapheight nmoy = newmapoffsety else s = math.min(w/mapwidth, h/mapheight) w = mapwidth*s h = mapheight*s nmw = mapwidth nmox = 0 nmh = mapheight nmoy = 0 end local mapx, mapy = (width*16 - w)/2, (height*16 - h)/2 love.graphics.setColor(0, 0, 0, 200) love.graphics.rectangle("fill", (mapx-2)*scale, (mapy-2)*scale, (w+4)*scale, (h+4)*scale) --minimap for x = 1, mapwidth do for y = 1, mapheight do if x > -nmox and x <= nmw-nmox and y > -nmoy and y <= nmh-nmoy then local id = map[x][y][1] if id ~= nil and (rgblist[id] or animatedrgblist[id]) and id ~= 0 and not tilequads[id].invisible then if id > 90000 then if animatedrgblist[id] and animatedrgblist[id][animatedtilesframe[id]] then love.graphics.setColor(unpack(animatedrgblist[id][animatedtilesframe[id]])) love.graphics.rectangle("fill", (mapx+(x-1+nmox)*s)*scale, (mapy+(y-1+nmoy)*s)*scale, s*scale, s*scale) end else love.graphics.setColor(unpack(rgblist[id])) love.graphics.rectangle("fill", (mapx+(x-1+nmox)*s)*scale, (mapy+(y-1+nmoy)*s)*scale, s*scale, s*scale) end end end end end love.graphics.setColor(255, 0, 0, 255) drawrectangle(mapx-1, mapy-1, w+2, h+2) --resizing stuff if changemapwidthmenu then love.graphics.setColor(255, 255, 255) properprintFbackground(TEXT["old width: "] .. mapwidth, 26*scale, (mapy-21)*scale, true) properprintFbackground(TEXT["old height: "] .. mapheight, 26*scale, (mapy-11)*scale, true) properprintFbackground(TEXT["new width: "] .. newmapwidth, 26*scale, (mapy+h+4)*scale, true) properprintFbackground(TEXT["new height: "] .. newmapheight, 26*scale, (mapy+h+14)*scale, true) --button positioning guielements["maptopup"].x, guielements["maptopup"].y = width*8-5, mapy-24 guielements["maptopdown"].x, guielements["maptopdown"].y = width*8-5, mapy-13 guielements["mapbottomup"].x, guielements["mapbottomup"].y = width*8-5, mapy+h+2 guielements["mapbottomdown"].x, guielements["mapbottomdown"].y = width*8-5, mapy+h+13 guielements["mapleftleft"].x, guielements["mapleftleft"].y = mapx-24, height*8-5 guielements["mapleftright"].x, guielements["mapleftright"].y = mapx-13, height*8-5 guielements["maprightleft"].x, guielements["maprightleft"].y = mapx+w+2, height*8-5 guielements["maprightright"].x, guielements["maprightright"].y = mapx+w+13, height*8-5 guielements["mapwidthapply"].x, guielements["mapwidthapply"].y = width*8+10, mapy+h+4 guielements["mapwidthcancel"].x, guielements["mapwidthcancel"].y = width*8+65, mapy+h+4 guielements["maptopup"]:draw() guielements["maptopdown"]:draw() guielements["mapleftleft"]:draw() guielements["mapleftright"]:draw() guielements["maprightleft"]:draw() guielements["maprightright"]:draw() guielements["mapbottomup"]:draw() guielements["mapbottomdown"]:draw() guielements["mapwidthapply"]:draw() guielements["mapwidthcancel"]:draw() else --just moving camera love.graphics.setColor(255,0,0) love.graphics.rectangle("line", (mapx+(xscroll+nmox)*s)*scale, (mapy+(yscroll+nmoy+.5)*s)*scale, width*s*scale, height*s*scale) love.graphics.setColor(255,255,255) properprintFbackground(TEXT["toggle minimap with m"], 8*scale, (height*16-16)*scale) end else if editorstate == "maps" then love.graphics.setColor(0, 0, 0, 100) else love.graphics.setColor(0, 0, 0, 230) end if not minimapdragging then love.graphics.rectangle("fill", 1*scale, 18*scale, 398*scale, (205+tilemenuy)*scale) else love.graphics.rectangle("fill", 1*scale, 18*scale, 398*scale, (18+minimapheight*2)*scale) end guielements["tabmain"]:draw() guielements["tabtiles"]:draw() guielements["tabtools"]:draw() guielements["tabmaps"]:draw() guielements["tabcustom"]:draw() guielements["tabanimations"]:draw() if editorstate == "tiles" then --TILES love.graphics.setColor(255, 255, 255) --properprint("tilelist", 3*scale, 24*scale) guielements["tilesall"]:draw() guielements["tilessmb"]:draw() guielements["tilesportal"]:draw() guielements["tilescustom"]:draw() guielements["tilesanimated"]:draw() guielements["tilesobjects"]:draw() guielements["tilesentities"]:draw() drawrectangle(4, 37, 375, 167+tilemenuy) --tilemenuy love.graphics.push() love.graphics.translate(0, tilemenuy*scale) love.graphics.setScissor(5*scale, (38)*scale, 373*scale, (165+tilemenuy)*scale) if editmtobjects then if #multitileobjects > 0 then for i = 1, #multitileobjects do if i < 10 then love.graphics.setColor(127, 127, 127, 255) love.graphics.rectangle("fill", 6*scale, math.floor(i-1)*17*scale+39*scale-tilesoffset, 14*scale, 14*scale) love.graphics.setColor(0, 0, 0, 255) love.graphics.rectangle("fill", 7*scale, math.floor(i-1)*17*scale+39*scale-tilesoffset+1*scale, 14*scale-2*scale, 14*scale-2*scale) love.graphics.setColor(255, 255, 255, 255) properprint(i .. " " .. multitileobjectnames[i], 8*scale, math.floor(i-1)*17*scale+42*scale-tilesoffset) else properprint(multitileobjectnames[i], 8*scale, math.floor(i-1)*17*scale+42*scale-tilesoffset) end end else love.graphics.setColor(255, 255, 255) properprintF(TEXT["no objects saved"], (194-utf8.len(TEXT["no objects saved"])*4)*scale, 52*scale) properprintF(TEXT["press ctrl in map to save tile selection"], (194-utf8.len(TEXT["press ctrl in map to save tile selection"])*4)*scale, 62*scale) properprintF(TEXT["as an object"], (194-utf8.len(TEXT["as an object"])*4)*scale, 72*scale) end elseif editentities == false then if animatedtilelist then for i = 1, tilelistcount+1 do love.graphics.draw(tilequads[i+tileliststart-1+90000].image, tilequads[i+tileliststart-1+90000].quad, math.fmod((i-1), 22)*17*scale+5*scale, math.floor((i-1)/22)*17*scale+38*scale-tilesoffset, 0, scale, scale) if tilehotkeysindex[i+tileliststart-1+90000] then properprintbackground(tilehotkeysindex[i+tileliststart-1+90000], math.fmod((i-1), 22)*17*scale+13*scale, math.floor((i-1)/22)*17*scale+47*scale-tilesoffset) end end else for i = 1, tilelistcount+1 do local dy = math.floor((i-1)/22)*17*scale+38*scale-tilesoffset if dy > 0 and dy < height*16*scale then love.graphics.draw(tilequads[i+tileliststart-1].image, tilequads[i+tileliststart-1].quad, math.fmod((i-1), 22)*17*scale+5*scale, dy, 0, scale, scale) if tilehotkeysindex[i+tileliststart-1] then properprintbackground(tilehotkeysindex[i+tileliststart-1], math.fmod((i-1), 22)*17*scale+13*scale, math.floor((i-1)/22)*17*scale+47*scale-tilesoffset) end end end end else --nice and organized entities for list = 1, #entitiesform do if entitiesform[list].hidden then love.graphics.setColor(127, 127, 127) properprint("+", (368)*scale, (40+entitiesform[list].y-10)*scale-tilesoffset) else love.graphics.setColor(255, 255, 255) properprint("-", (367)*scale, (40+entitiesform[list].y-10)*scale-tilesoffset) end properprintF(TEXT[entitiesform[list].name], (5)*scale, (40+entitiesform[list].y-10)*scale-tilesoffset) love.graphics.setColor(255, 255, 255) if not entitiesform[list].hidden then for i = 1, #entitiesform[list] do local t = entitiesform[list][i] local x = math.fmod((i-1), 22)*17*scale+5*scale local y = (math.floor((i-1)/22)*17*scale+(39+entitiesform[list].y)*scale) love.graphics.setColor(255, 255, 255) if tonumber(t) then love.graphics.draw(entityquads[t].image, entityquads[t].quad, x, y-tilesoffset, 0, scale, scale) else local v = enemiesdata[t] local starty = y-tilesoffset if starty < 39*scale and starty > 23*scale then love.graphics.setScissor(x, 39*scale, 16*scale, (16*scale)-((39*scale)-starty)) else love.graphics.setScissor(x, math.min(y-tilesoffset, 186*scale), 16*scale, 16*scale) end if starty > 23*scale then if v.icongraphic then love.graphics.draw(v.icongraphic, x, y-tilesoffset, 0, scale, scale) elseif v.quad then love.graphics.draw(v.graphic, v.quad, x, y-tilesoffset, 0, scale, scale) else love.graphics.draw(entityquads[1].image, entityquads[1].quad, x, y-tilesoffset, 0, scale, scale) end end love.graphics.setScissor(5*scale, 38*scale, 373*scale, 165*scale) end if tilehotkeysentityindex[t] then properprintbackground(tilehotkeysentityindex[t], x+8*scale, y-tilesoffset+9*scale) end end end end love.graphics.setColor(255, 255, 255) end local mtbutton local mousex, mousey = love.mouse.getX(), love.mouse.getY() local tile = gettilelistpos(mousex, mousey) if editentities == false and not editmtobjects then if tilestampselection then local t = tilestampselection love.graphics.setLineWidth(2*scale) love.graphics.setColor(255, 255, 255, 127) love.graphics.rectangle("line", t.mx, t.my, mousex-t.mx, mousey-t.my) local x1, y1, x2, y2 = t.x, t.y, mousex, mousey if mousex <= t.x then x1 = t.x+17*scale end if mousey <= t.y then y1 = t.y+17*scale end if x2 < x1 then x2 = x1; x1 = mousex end if y2 < y1 then y2 = y1; y1 = mousey end for tx = 1, math.ceil((x2-x1)/(17*scale)) do for ty = 1, math.ceil((y2-y1)/(17*scale)) do local tile = gettilelistpos(x1+(17*scale)*(tx-1), y1+(17*scale)*(ty-1)) if tile and tile <= tilelistcount+1 then love.graphics.setColor(255, 255, 255, 127) love.graphics.rectangle("fill", (5+math.fmod((tile-1), 22)*17)*scale, (38+math.floor((tile-1)/22)*17)*scale-tilesoffset, 16*scale, 16*scale) end end end else if tile and tile <= tilelistcount+1 then love.graphics.setColor(255, 255, 255, 127) love.graphics.rectangle("fill", (5+math.fmod((tile-1), 22)*17)*scale, (38+math.floor((tile-1)/22)*17)*scale-tilesoffset, 16*scale, 16*scale) end end elseif editmtobjects then if #multitileobjects > 0 then entry = getlistpos(mousex, mousey) mtbutton = getmtbutton(mousex) -- 0 1 2 3 = nobutton up down delete if entry and entry <= #multitileobjects-1 then love.graphics.setColor(255, 255, 255, 64) love.graphics.rectangle("fill", 5*scale, (38+math.floor((tile-1)/22)*17)*scale-tilesoffset, 373*scale, 16*scale) --buttons for i = 1, 3 do if mtbutton == i then love.graphics.setColor(255, 255, 255, 255) else love.graphics.setColor(127, 127, 127, 255) end love.graphics.rectangle("fill", (333+15*(i-1))*scale, (39+math.floor((tile-1)/22)*17)*scale-tilesoffset, 14*scale, 14*scale) love.graphics.setColor(0, 0, 0, 255) love.graphics.rectangle("fill", (333+15*(i-1)+1)*scale, (39+math.floor((tile-1)/22)*17)*scale-tilesoffset+1*scale, 14*scale-2*scale, 14*scale-2*scale) if mtbutton == i then if i == 3 then love.graphics.setColor(255, 0, 0, 255) else love.graphics.setColor(255, 255, 255, 255) end else love.graphics.setColor(127, 127, 127, 255) end if i == 1 then --up love.graphics.draw(uparrowimg, (333+15*(i-1)+3)*scale, (38+math.floor((tile-1)/22)*17)*scale-tilesoffset+3*scale, 0, scale, scale) elseif i == 2 then --down love.graphics.draw(downarrowimg, (333+15*(i-1)+3)*scale, (38+math.floor((tile-1)/22)*17)*scale-tilesoffset+3*scale, 0, scale, scale) elseif i == 3 then --delete properprint("x",(333+15*(i-1)+3)*scale, (39+math.floor((tile-1)/22)*17)*scale-tilesoffset+3*scale) end end end if guielements["mtobjectrename"].active then guielements["mtobjectrename"]:draw() end end else local tile, list = getentitylistpos(love.mouse.getX(), love.mouse.getY()) if tile then local x = (5+math.fmod((tile-1), 22)*17)*scale local y = (math.floor(((tile-1))/22)*17*scale+(39+entitiesform[list].y)*scale) love.graphics.setColor(255, 255, 255, 127) love.graphics.rectangle("fill", x, y-tilesoffset, 16*scale, 16*scale) elseif list then local x = (5)*scale local y = ((39+entitiesform[list].y-10)*scale) love.graphics.setColor(255, 255, 255, 127) love.graphics.rectangle("fill", x, y-tilesoffset, 373*scale, 9*scale) end end love.graphics.setScissor() guielements["tilesscrollbar"]:draw() if editentities then local tilei, list = getentitylistpos(love.mouse.getX(), love.mouse.getY()) if tilei then local tile = entitiesform[list][tilei] local customenemydescription = (tile and (not tonumber(tile)) and tablecontains(customenemies, tile) and enemiesdata[tile] and enemiesdata[tile].description) if tonumber(tile) or customenemydescription then local newstring = entitydescriptions[tile] if customenemydescription then newstring = enemiesdata[tile].description elseif TEXT["entitydescriptions"] and TEXT["entitydescriptions"][tile] then newstring = TEXT["entitydescriptions"][tile] end if string.len(newstring) > 49 then local chari = 49 if string.len(newstring) < 98 then --proper wrapping with spaces while string.sub(newstring, chari+1, chari+1) ~= " " do chari = chari - 1 end newstring = string.sub(newstring, 1, chari) .. "\n" .. string.sub(newstring, chari+2, 98) else newstring = string.sub(newstring, 1, chari) .. "\n" .. string.sub(newstring, chari+1, 98) end end properprintF(newstring, 3*scale, 205*scale) else properprint(tile, 3*scale, 205*scale) end end elseif editmtobjects then if mtbutton == 1 then properprintF(TEXT["move up"], 10*scale, 210*scale) elseif mtbutton == 2 then properprintF(TEXT["move down"], 10*scale, 210*scale) elseif mtbutton == 3 then properprintF(TEXT["delete"], 10*scale, 210*scale) else local entry = getlistpos(mousex, mousey) if entry and entry <= #multitileobjects-1 then if mousex < 20*scale and entry <= 9 then properprintF(TEXT["shortcut: hold ctrl and press number"], 10*scale, 210*scale) else properprintF(TEXT["right click to rename"], 10*scale, 210*scale) end end end else if tile then local actualtile = tile+tileliststart-1 if animatedtilelist then actualtile = tile+tileliststart-1+90000 end if tilequads[actualtile] then love.graphics.setColor(255, 255, 255, 255) if tilequads[actualtile].collision and tilequads[actualtile].platform then love.graphics.setColor(255, 255, 255, 255) properprint("collision : semi.", 3*scale, 205*scale) elseif tilequads[actualtile].collision then love.graphics.setColor(255, 255, 255, 255) properprint("collision : yes", 3*scale, 205*scale) else love.graphics.setColor(255, 255, 255, 127) properprint("collision : no", 3*scale, 205*scale) end if tilequads[actualtile].collision and tilequads[actualtile].portalable then love.graphics.setColor(255, 255, 255, 255) properprint("portalable: yes", 3*scale, 215*scale) else love.graphics.setColor(255, 255, 255, 127) properprint("portalable: no", 3*scale, 215*scale) end if tilequads[actualtile].collision and (tilequads[actualtile].debris and blockdebrisquads[tilequads[actualtile].debris]) then love.graphics.setColor(255, 255, 255, 255) properprint("breakable : hard", 140*scale, 205*scale) elseif tilequads[actualtile].collision and tilequads[actualtile].breakable then love.graphics.setColor(255, 255, 255, 255) properprint("breakable : yes", 140*scale, 205*scale) else love.graphics.setColor(255, 255, 255, 127) properprint("breakable : no", 140*scale, 205*scale) end if tilequads[actualtile].foreground then love.graphics.setColor(255, 255, 255, 255) properprint("foreground: yes", 140*scale, 215*scale) else love.graphics.setColor(255, 255, 255, 127) properprint("foreground: no", 140*scale, 215*scale) end love.graphics.setColor(255, 255, 255, 255) properprint("id: " .. actualtile, (396-(#("id: " .. actualtile)*8))*scale, 215*scale) end end end love.graphics.setColor(255, 255, 255) if editentities and not editenemies and editorstate == "tiles" and editormenuopen and entitytooltipobject then entitytooltipobject:draw(math.max(0, tooltipa)) end --tilemenuy love.graphics.pop() elseif editorstate == "main" then --MINIMAP love.graphics.setColor(255, 255, 255) properprintF(TEXT["minimap"], 3*scale, 21*scale) love.graphics.rectangle("fill", minimapx*scale, minimapy*scale, 394*scale, 34*scale) love.graphics.setColor(unpack(backgroundcolor[background])) love.graphics.rectangle("fill", (minimapx+2)*scale, (minimapy+2)*scale, 390*scale, 30*scale) local lmap = map love.graphics.setScissor((minimapx+2)*scale, (minimapy+2)*scale, 390*scale, 30*scale) for x = 1, mapwidth do for y = math.floor(yscroll)+1, math.min(mapheight, math.ceil(yscroll)+16) do if x-minimapscroll > 0 and x-minimapscroll < 196 then if lmap[x][y] then local id = lmap[x][y][1] if id ~= nil and id ~= 0 and not tilequads[id].invisible then if id > 90000 then if animatedrgblist[id] and animatedrgblist[id][animatedtilesframe[id]] then love.graphics.setColor(unpack(animatedrgblist[id][animatedtilesframe[id]])) love.graphics.rectangle("fill", (minimapx+x*2-minimapscroll*2)*scale, (minimapy+(y+1)*2-(math.floor(yscroll)+1)*2-math.fmod(yscroll, 1)*2)*scale, 2*scale, 2*scale) end else if rgblist[id] then love.graphics.setColor(unpack(rgblist[id])) love.graphics.rectangle("fill", (minimapx+x*2-minimapscroll*2)*scale, (minimapy+(y+1)*2-(math.floor(yscroll)+1)*2-math.fmod(yscroll, 1)*2)*scale, 2*scale, 2*scale) end end end end end end end love.graphics.setScissor() love.graphics.setColor(255, 0, 0) drawrectangle(splitxscroll[1]*2+minimapx-minimapscroll*2, minimapy, (width+2)*2, 34) drawrectangle(splitxscroll[1]*2+minimapx-minimapscroll*2+1, minimapy+1, (width+1)*2, 32) guielements["autoscrollcheckbox"]:draw() if minimapdragging == false then guielements["savebutton"]:draw() guielements["menubutton"]:draw() guielements["testbutton"]:draw() guielements["testbuttonplayer"]:draw() guielements["widthbutton"]:draw() guielements["timelimitdecrease"]:draw() properprint(mariotimelimit, 29*scale, 154*scale) guielements["timelimitincrease"]:draw() properprintF(TEXT["timelimit"], 8*scale, 142*scale) --left side properprintF(TEXT["music"], 8*scale, 93*scale) --guielements["backgrounddropdown"]:draw() properprintF(TEXT["background color"], 8*scale, 69*scale) guielements["backgroundinput1"]:draw() guielements["backgroundinput2"]:draw() guielements["backgroundinput3"]:draw() for i = 1, #backgroundcolor do guielements["defaultcolor" .. i]:draw() end if guielements["portalgundropdown"].extended then guielements["spritesetdropdown"]:draw() properprintF(TEXT["spriteset"], 8*scale, 117*scale) guielements["musicdropdown"]:draw() if musici == 7 then guielements["custommusiciinput"]:draw() end properprintF(TEXT["portal gun"], 8*scale, 166*scale) guielements["portalgundropdown"]:draw() else properprintF(TEXT["portal gun"], 8*scale, 166*scale) guielements["portalgundropdown"]:draw() guielements["spritesetdropdown"]:draw() properprintF(TEXT["spriteset"], 8*scale, 117*scale) guielements["musicdropdown"]:draw() if musici == 7 then guielements["custommusiciinput"]:draw() end end --right side guielements["autoscrollingcheckbox"]:draw() guielements["autoscrollingscrollbar"]:draw() if autoscrolling then love.graphics.setColor(255, 255, 255, 255) else love.graphics.setColor(150, 150, 150, 255) end properprint(formatscrollnumber(autoscrollingspeed), (guielements["autoscrollingscrollbar"].x+1+guielements["autoscrollingscrollbar"].xrange*guielements["autoscrollingscrollbar"].value)*scale, (guielements["autoscrollingscrollbar"].y+1)*scale) guielements["custombackgroundcheckbox"]:draw() guielements["customforegroundcheckbox"]:draw() if custombackground then love.graphics.setColor(255, 255, 255, 255) else love.graphics.setColor(150, 150, 150, 255) end properprintF(TEXT["scrollfactor"], 199*scale, 146*scale) if customforeground then love.graphics.setColor(255, 255, 255, 255) else love.graphics.setColor(150, 150, 150, 255) end properprintF(TEXT["scrollfactor"], 199*scale, 178*scale) guielements["scrollfactoryscrollbar"]:draw() guielements["scrollfactorxscrollbar"]:draw() guielements["scrollfactor2yscrollbar"]:draw() guielements["scrollfactor2xscrollbar"]:draw() if custombackground then love.graphics.setColor(255, 255, 255, 255) else love.graphics.setColor(150, 150, 150, 255) end properprint(formatscrollnumber(scrollfactor), (guielements["scrollfactorxscrollbar"].x+1+guielements["scrollfactorxscrollbar"].xrange*guielements["scrollfactorxscrollbar"].value)*scale, 146*scale) properprint(formatscrollnumber(scrollfactory), (guielements["scrollfactorxscrollbar"].x+1+guielements["scrollfactoryscrollbar"].xrange*guielements["scrollfactoryscrollbar"].value)*scale, 156*scale) if customforeground then love.graphics.setColor(255, 255, 255, 255) else love.graphics.setColor(150, 150, 150, 255) end properprint(formatscrollnumber(scrollfactor2), (guielements["scrollfactor2xscrollbar"].x+1+guielements["scrollfactor2xscrollbar"].xrange*guielements["scrollfactor2xscrollbar"].value)*scale, 178*scale) properprint(formatscrollnumber(scrollfactor2y), (guielements["scrollfactor2xscrollbar"].x+1+guielements["scrollfactor2yscrollbar"].xrange*guielements["scrollfactor2yscrollbar"].value)*scale, 188*scale) love.graphics.setColor(255, 255, 255, 255) --level properties guielements["levelpropertiesdropdown"]:draw() if guielements["foregrounddropdown"].extended then guielements["backgrounddropdown"]:draw() guielements["foregrounddropdown"]:draw() else guielements["foregrounddropdown"]:draw() guielements["backgrounddropdown"]:draw() end if levelpropertiesdropdown then local len = 9 local lpd = guielements["levelpropertiesdropdown"] local high = guielements["levelpropertiesdropdown"]:inhighlight(love.mouse.getPosition()) love.graphics.setColor(0,0,0) love.graphics.rectangle("fill", (lpd.x+1)*scale, (lpd.y+12)*scale, (lpd.width+5-2)*scale, (8*len+1-1)*scale) if high then love.graphics.setColor(255,255,255) else love.graphics.setColor(127,127,127) end drawrectangle(lpd.x, lpd.y+12, lpd.width+5, 8*len+1) guielements["intermissioncheckbox"]:draw() guielements["warpzonecheckbox"]:draw() guielements["underwatercheckbox"]:draw() guielements["bonusstagecheckbox"]:draw() guielements["edgewrappingcheckbox"]:draw() guielements["lightsoutcheckbox"]:draw() guielements["lowgravitycheckbox"]:draw() end end elseif editorstate == "maps" then love.graphics.setColor(0, 0, 0, 210) love.graphics.rectangle("fill", 2*scale, 19*scale, 100*scale, 203*scale) love.graphics.rectangle("fill", 103*scale, 195*scale, 295*scale, 27*scale) love.graphics.setColor(0, 0, 0, 50) love.graphics.rectangle("fill", 103*scale, 19*scale, 295*scale, 175*scale) guielements["worldscrollbar"]:draw() guielements["levelscrollbar"]:draw() love.graphics.setScissor(2*scale, 20*scale, 100*scale, 201*scale) for i = 1, #mappacklevels do --world if guielements["world-" .. i].y > 0 and guielements["world-" .. i].y < height*16 then guielements["world-" .. i]:draw() end end guielements["newworld"]:draw() love.graphics.setScissor() love.graphics.setScissor(104*scale, 20*scale, 278*scale, 173*scale) local i = currentworldselection for j = 1, #mappacklevels[i] do --level local y = (46+((j-1)*39)-(guielements["levelscrollbar"].value*math.max(0, (#mappacklevels[currentworldselection]*39)+17-173))) if y > 0 and y < height*16 then love.graphics.setColor(255, 255, 255) properprint("sub", 106*scale, y*scale) for k = 0, mappacklevels[i][j] do --sublevel local name = i .. "-" .. j .. "_" .. k guielements[name]:draw() end if guielements["newsublevel-" .. i .. "-" .. j].active then guielements["newsublevel-" .. i .. "-" .. j]:draw() end end end guielements["newlevel-" .. i]:draw() love.graphics.setScissor() love.graphics.setColor(255, 255, 255) properprintF(TEXT["do not forget to save\nyour current level!"], 108*scale, 200*scale) guielements["savebutton2"]:draw() --guielements["autosavecheckbox"]:draw() if levelrightclickmenu.active then levelrightclickmenu:draw() end elseif editorstate == "tools" then guielements["linkbutton"]:draw() guielements["portalbutton"]:draw() guielements["selectionbutton"]:draw() guielements["powerlinebutton"]:draw() love.graphics.setColor(51, 51, 51) love.graphics.rectangle("fill", 140*scale, 22*scale, 255*scale, 69*scale) love.graphics.rectangle("fill", 132*scale, (22+(currenttooldesc-1)*18)*scale, 8*scale, 15*scale) love.graphics.setColor(0, 0, 0) love.graphics.rectangle("fill", 141*scale, 23*scale, 253*scale, 67*scale) love.graphics.rectangle("fill", 132*scale, (23+(currenttooldesc-1)*18)*scale, 9*scale, 13*scale) love.graphics.setColor(255, 255, 255) properprintF(TEXT["tool descriptions"][currenttooldesc], 143*scale, 26*scale) properprintF(TEXT["mappack title:"], 5*scale, 106*scale) properprintF(TEXT["author:"], 5*scale, 131*scale) properprintF(TEXT["description:"], 5*scale, 156*scale) guielements["edittitle"]:draw() guielements["editauthor"]:draw() guielements["editdescription"]:draw() guielements["savesettings"]:draw() guielements["dropshadowcheckbox"]:draw() guielements["realtimecheckbox"]:draw() guielements["continuemusiccheckbox"]:draw() properprintF(TEXT["lives:"], 228*scale, 106*scale) guielements["livesincrease"]:draw() if mariolivecount == false then properprint("inf", 306*scale, 106*scale) else properprint(mariolivecount, 306*scale, 106*scale) end guielements["livesdecrease"]:draw() properprintF(TEXT["camera:"], 228*scale, 132*scale) guielements["cameradropdown"]:draw() properprintF(TEXT["physics:"], 228*scale, 119*scale) guielements["physicsdropdown"]:draw() properprintF("icon:", 150*scale, 138*scale) if mousex > 151*scale and mousey > 146*scale and mousex < 203*scale and mousey < 198*scale then love.graphics.setColor(255, 255, 255) else love.graphics.setColor(127, 127, 127) end local w = love.graphics.getLineWidth() love.graphics.setLineWidth(scale) love.graphics.rectangle("line", 151.5*scale, 146.5*scale, 51*scale, 51*scale) love.graphics.setColor(255, 255, 255) if editmappackicon ~= nil then local scale2w = scale*50 / math.max(1, editmappackicon:getWidth()) local scale2h = scale*50 / math.max(1, editmappackicon:getHeight()) love.graphics.draw(editmappackicon, 152*scale, 147*scale, 0, scale2w, scale2h) else love.graphics.draw(mappacknoicon, 152*scale, 147*scale, 0, scale, scale) end love.graphics.setLineWidth(w) elseif editorstate == "custom" then love.graphics.setColor(255, 255, 255) love.graphics.rectangle("fill", 5*scale, 37*scale, 390*scale, scale) love.graphics.rectangle("fill", 394*scale, 38*scale, scale, 180*scale) love.graphics.rectangle("fill", 5*scale, 38*scale, scale, 180*scale) love.graphics.rectangle("fill", 5*scale, 218*scale, 390*scale, scale) guielements["graphicscustomtab"]:draw() guielements["tilescustomtab"]:draw() guielements["backgroundscustomtab"]:draw() guielements["soundscustomtab"]:draw() guielements["textcustomtab"]:draw() guielements["enemiescustomtab"]:draw() if customtabstate == "graphics" then love.graphics.setColor(255, 255, 255) properprint(currentcustomimage[3], 10*scale, 41*scale) love.graphics.rectangle("fill", 10*scale, 50*scale, 164*scale, 164*scale) love.graphics.draw(customimagebackimg, 12*scale, 52*scale, 0, scale, scale) local img = _G[currentcustomimage[2]] local sx, sy = math.max(1, math.floor(160/img:getWidth())), math.max(1, math.floor(160/img:getWidth())) if img:getWidth() > 160 or img:getHeight() > 160 then if img:getHeight() > img:getWidth() then sx, sy = 160/img:getHeight(), 160/img:getHeight() else sx, sy = 160/img:getWidth(), 160/img:getWidth() end elseif img:getHeight() > img:getWidth() then sx, sy = math.max(1, math.floor(160/img:getHeight())), math.max(1, math.floor(160/img:getHeight())) end love.graphics.draw(img, 92*scale, 132*scale, 0, sx*scale, sy*scale, img:getWidth()/2, img:getHeight()/2) properprintF(TEXT["current image"], 176*scale, 54*scale) properprintF(TEXT["image template"], 176*scale, 79*scale) properprintF(TEXT["replace image"], 176*scale, 125*scale) love.graphics.setColor(127, 127, 127) properprintF(TEXT["drag an image file into\nthe square to replace it!"], 184*scale, 134*scale) properprintF(TEXT["or 'open folder' and\nchange the image there!"], 184*scale, 157*scale) love.graphics.setColor(255, 255, 255) guielements["exportimagetemplate"]:draw() guielements["openfoldercustom"]:draw() guielements["saveimage"]:draw() guielements["resetimage"]:draw() guielements["currentimagedropdown"]:draw() elseif customtabstate == "tiles" then love.graphics.setColor(255, 255, 255) properprintF(TEXT["custom tileset"], 10*scale, 41*scale) love.graphics.rectangle("fill", 10*scale, 50*scale, 164*scale, 164*scale) love.graphics.draw(customimagebackimg, 12*scale, 52*scale, 0, scale, scale) local mx, my = love.mouse.getPosition() local img --show tile properties if mx > 375*scale and mx < (375+15)*scale and my > 199*scale and my < (199+15)*scale then img = tilepropertiesimg elseif customtiles then img = customtilesimg[1] end if img then local sx, sy = math.max(1, math.floor(160/img:getWidth())), math.max(1, math.floor(160/img:getWidth())) if img:getWidth() > 160 or img:getHeight() > 160 then if img:getHeight() > img:getWidth() then sx, sy = 160/img:getHeight(), 160/img:getHeight() else sx, sy = 160/img:getWidth(), 160/img:getWidth() end elseif img:getHeight() > img:getWidth() then sx, sy = math.max(1, math.floor(160/img:getHeight())), math.max(1, math.floor(160/img:getHeight())) end love.graphics.draw(img, 92*scale, 132*scale, 0, sx*scale, sy*scale, img:getWidth()/2, img:getHeight()/2) end properprintF(TEXT["tileset template"], 176*scale, 54*scale) properprintF(TEXT["add tileset"], 176*scale, 100*scale) properprintF(TEXT["animated tiles"], 176*scale, 154*scale) love.graphics.setColor(127, 127, 127) properprintF(TEXT["drag an image file into\nthe square to replace it!"], 184*scale, 109*scale) properprintF(TEXT["or 'open folder' and\nchange the image there!"], 184*scale, 132*scale) love.graphics.setColor(255, 255, 255) guielements["exporttilestemplate"]:draw() guielements["exportanimatedtilestemplate"]:draw() guielements["openfoldertilescustom"]:draw() guielements["openfolderanimatedtilescustom"]:draw() guielements["saveimage"]:draw() love.graphics.setColor(127, 127, 127) if mx > 375*scale and mx < (375+15)*scale and my > 199*scale and my < (199+15)*scale then love.graphics.setColor(255, 255, 255) end love.graphics.rectangle("fill", 375*scale, 199*scale, 15*scale, 15*scale) love.graphics.setColor(0, 0, 0) love.graphics.rectangle("fill", (375+1)*scale, (199+1)*scale, 13*scale, 13*scale) love.graphics.setColor(255, 255, 255) love.graphics.draw(tilepropertiesimg, (375+2)*scale, (199+2)*scale, 0, (11/tilepropertiesimg:getWidth())*scale, (11/tilepropertiesimg:getHeight())*scale) elseif customtabstate == "backgrounds" then love.graphics.setColor(255, 255, 255) properprintF(TEXT["custom background"], 10*scale, 41*scale) love.graphics.rectangle("fill", 10*scale, 50*scale, 164*scale, 164*scale) love.graphics.draw(customimagebackimg, 12*scale, 52*scale, 0, scale, scale) if editorbackgroundstate == "background" then love.graphics.setColor(255, 255, 255) else love.graphics.setColor(255, 255, 255, 150) end local w, h = width*16, height*16 local sx, sy = math.max(1, math.floor(160/w)), math.max(1, math.floor(160/w)) sx, sy = 160/w, 160/w if custombackgroundimg then love.graphics.push() love.graphics.setScissor(12*scale, 52*scale, 160*scale, 160*scale) love.graphics.translate(12*scale, (132-(h*sy)/2)*scale) love.graphics.scale(sx, sy) rendercustombackground(0,0,0,0) love.graphics.pop() love.graphics.setScissor() end if editorbackgroundstate == "foreground" then love.graphics.setColor(255, 255, 255) else love.graphics.setColor(255, 255, 255, 150) end if customforegroundimg then love.graphics.push() love.graphics.setScissor(12*scale, 52*scale, 160*scale, 160*scale) love.graphics.translate(12*scale, (132-(h*sy)/2)*scale) love.graphics.scale(sx, sy) rendercustomforeground(0,0,0,0) love.graphics.pop() love.graphics.setScissor() end love.graphics.setColor(255, 255, 255) properprintF(TEXT["current"], 176*scale, 54*scale) properprintF(TEXT["add background"], 176*scale, 79*scale) love.graphics.setColor(127, 127, 127) properprintF(TEXT["drag file to add custom\nbackground or foreground!"], 184*scale, 88*scale) properprintF(TEXT["or just put a .png\nin the backgrounds folder"], 184*scale, 112*scale) properprintF(TEXT["add a .json file\nfor animated backgrounds"], 184*scale, 159*scale) love.graphics.setColor(255, 255, 255) properprintF(TEXT["animated backgrounds"], 176*scale, 150*scale) guielements["openfolderbackgroundscustom"]:draw() guielements["currentbackgrounddropdown"]:draw() guielements["saveimage"]:draw() elseif customtabstate == "sounds" then love.graphics.setColor(255, 255, 255) properprintF(TEXT["custom sounds"], 10*scale, 41*scale) love.graphics.rectangle("fill", 10*scale, 50*scale, 164*scale, 164*scale) love.graphics.draw(customimagebackimg, 12*scale, 52*scale, 0, scale, scale) love.graphics.draw(gateimg, gatequad[5], 92*scale, 132*scale, math.sin(((coinanimation-1)/5)*(math.pi*2))/6, 8*scale, 8*scale, 8, 8) properprintF(TEXT["current sound"], 176*scale, 54*scale) properprintF(TEXT["sound template"], 176*scale, 79*scale) properprintF(TEXT["replace sound"], 176*scale, 125*scale) properprintF(TEXT["add music"], 176*scale, 156*scale) love.graphics.setColor(127, 127, 127) properprintF(TEXT["open sounds folder to\nreplace sounds!"], 184*scale, 134*scale) properprintF(TEXT["put any .mp3 or .ogg\nin the music folder!"], 184*scale, 183*scale) love.graphics.setColor(255, 255, 255) guielements["exportimagetemplate"]:draw() guielements["openfoldersoundscustom"]:draw() guielements["openfoldermusiccustom"]:draw() guielements["currentsounddropdown"]:draw() elseif customtabstate == "text" then guielements["endingtexttab"]:draw() guielements["hudtexttab"]:draw() guielements["castletexttab"]:draw() guielements["levelscreentexttab"]:draw() guielements["savecustomtext"]:draw() if textstate == "ending" then properprintF(TEXT["ending text"], 11*scale, 57*scale) guielements["editendingtext1"]:draw() guielements["editendingtext2"]:draw() love.graphics.setColor(textcolors[textcolorl]) properprintF(TEXT["color"], 24*scale, 100*scale) guielements["endingcolor<"]:draw() guielements["endingcolor>"]:draw() elseif textstate == "hud" then love.graphics.setColor(255, 255, 255) properprintF(TEXT["player name"], 11*scale, 57*scale) guielements["editplayername"]:draw() love.graphics.setColor(textcolors[textcolorp]) properprintF(TEXT["color"], 23*scale, 86*scale) guielements["hudcolor<"]:draw() guielements["hudcolor>"]:draw() guielements["hudworldlettercheckbox"]:draw() guielements["hudvisiblecheckbox"]:draw() guielements["hudoutlinecheckbox"]:draw() guielements["hudsimplecheckbox"]:draw() elseif textstate == "castle" then love.graphics.setColor(255, 255, 255) properprintF(TEXT["toad"], 11*scale, 57*scale) guielements["edittoadtext1"]:draw() guielements["edittoadtext2"]:draw() guielements["edittoadtext3"]:draw() properprintF(TEXT["peach"], 11*scale, 111*scale) guielements["editpeachtext1"]:draw() guielements["editpeachtext2"]:draw() guielements["editpeachtext3"]:draw() guielements["editpeachtext4"]:draw() guielements["editpeachtext5"]:draw() guielements["stevecheckbox"]:draw() elseif textstate == "levelscreen" then love.graphics.setColor(255, 255, 255) local sublev = "" if mariosublevel ~= 0 then sublev = "-" .. mariosublevel end properprintF(TEXT["level "] .. marioworld .. "-" .. mariolevel .. sublev, 11*scale, 57*scale) properprintF(TEXT["caption"], 11*scale, 70*scale) guielements["editlevelscreentext"]:draw() love.graphics.setColor(127, 127, 127) properprintF(TEXT["add a background image\nby naming it\n'"] .. marioworld .. "-" .. mariolevel .. "levelscreen.png'", 159*scale, 110*scale) properprintF(TEXT["or drag an image file\ninto the square!"], 159*scale, 143*scale) love.graphics.setColor(255, 255, 255) love.graphics.rectangle("fill", 11*scale, 110*scale, 144*scale, 82*scale) properprintF(TEXT["preview"], 11*scale, 100*scale) -- levelscreen preview love.graphics.setScissor(12*scale, 111*scale, 142*scale, 80*scale) love.graphics.push() love.graphics.translate(12*scale, 111*scale) love.graphics.scale((80/224), (80/224)) love.graphics.setColor(0, 0, 0) love.graphics.rectangle("fill", 0, 0, 400*scale, 224*scale) love.graphics.setColor(255, 255, 255) if levelscreenimage then love.graphics.draw(levelscreenimage, 0, 0, 0, scale, scale) end local world = marioworld if hudworldletter and tonumber(world) and world > 9 and world <= 9+#alphabet then world = alphabet:sub(world-9, world-9) end properprintF(TEXT["world "] .. world .. "-" .. mariolevel, (width/2*16)*scale-40*scale, 72*scale - (players-1)*6*scale) --for i = 1, 1 do local i = 1 local x = (width/2*16)*scale-29*scale local y = (97 + (i-1)*20 - (players-1)*8)*scale local v = characters.data[mariocharacter[i]] for j = 1, #characters.data[mariocharacter[i]]["animations"] do love.graphics.setColor(unpack(mariocolors[i][j])) if playertype == "classic" or playertype == "cappy" or not portalgun then--no portal gun love.graphics.draw(v["animations"][j], v["small"]["idle"][5], x+(v.smalloffsetX)*scale, y+(11-v.smalloffsetY)*scale, 0, scale, scale, v.smallquadcenterX, v.smallquadcenterY) else love.graphics.draw(v["animations"][j], v["small"]["idle"][3], x+(v.smalloffsetX)*scale, y+(11-v.smalloffsetY)*scale, 0, scale, scale, v.smallquadcenterX, v.smallquadcenterY) end end --hat offsets = hatoffsets["idle"] if #mariohats[i] > 1 or mariohats[i][1] ~= 1 then local yadd = 0 for j = 1, #mariohats[i] do love.graphics.setColor(255, 255, 255) love.graphics.draw(hat[mariohats[i][j]].graphic, hat[mariohats[i][j]].quad[1], x+(v.smalloffsetX)*scale, y+(11-v.smalloffsetY)*scale, 0, scale, scale, v.smallquadcenterX - hat[mariohats[i][j]].x + offsets[1], v.smallquadcenterY - hat[mariohats[i][j]].y + offsets[2] + yadd) yadd = yadd + hat[mariohats[i][j]].height end elseif #mariohats[i] == 1 then love.graphics.setColor(mariocolors[i][1]) love.graphics.draw(hat[mariohats[i][1]].graphic, hat[mariohats[i][1]].quad[1], x+(v.smalloffsetX)*scale, y+(11-v.smalloffsetY)*scale, 0, scale, scale, v.smallquadcenterX - hat[mariohats[i][1]].x + offsets[1], v.smallquadcenterY - hat[mariohats[i][1]].y + offsets[2]) end love.graphics.setColor(255, 255, 255, 255) if playertype == "classic" or playertype == "cappy" or not portalgun then--no portal gun love.graphics.draw(v["animations"][0], v["small"]["idle"][5], x+(v.smalloffsetX)*scale, y+(11-v.smalloffsetY)*scale, 0, scale, scale, v.smallquadcenterX, v.smallquadcenterY) else love.graphics.draw(v["animations"][0], v["small"]["idle"][3], x+(v.smalloffsetX)*scale, y+(11-v.smalloffsetY)*scale, 0, scale, scale, v.smallquadcenterX, v.smallquadcenterY) end properprint("* 3", (width/2*16)*scale-8*scale, y+7*scale) --end local s = guielements["editlevelscreentext"].value properprint(s, (width/2*16)*scale-string.len(s)*4*scale, 200*scale) love.graphics.pop() love.graphics.setScissor() end elseif customtabstate == "enemies" then love.graphics.setColor(255, 255, 255) if currentcustomenemy[2] then properprint(currentcustomenemy[2], 10*scale, 41*scale) else properprint("custom enemies: none", 10*scale, 41*scale) end love.graphics.rectangle("fill", 10*scale, 50*scale, 164*scale, 164*scale) love.graphics.draw(customimagebackimg, 12*scale, 52*scale, 0, scale, scale) if enemiesdata[currentcustomenemy[2]] and enemiesdata[currentcustomenemy[2]].graphic then local en = currentcustomenemy[2] local img = enemiesdata[en].graphic local w, h = img:getWidth(), img:getHeight() local quad = false if enemiesdata[en].quadbase then quad = enemiesdata[en].quadbase[spriteset][currentcustomenemy.quadi] local qx, qy, qw, qh = quad:getViewport() w, h = qw, qh end local sx, sy = math.max(1, math.floor(160/w)), math.max(1, math.floor(160/w)) if w > 160 or h > 160 then if h > w then sx, sy = 160/h, 160/h else sx, sy = 160/w, 160/w end elseif h > w then sx, sy = math.max(1, math.floor(160/h)), math.max(1, math.floor(160/h)) end if currentcustomenemy.animationdirection == "right" then sx = -sx end if quad then love.graphics.draw(img, quad, 92*scale, 132*scale, 0, sx*scale, sy*scale, w/2, h/2) else love.graphics.draw(img, 92*scale, 132*scale, 0, sx*scale, sy*scale, w/2, h/2) end end properprintF(TEXT["current enemy"], 176*scale, 54*scale) properprintF(TEXT["enemy template"], 176*scale, 79*scale) properprintF(TEXT["add new enemies"], 176*scale, 125*scale) love.graphics.setColor(127, 127, 127) properprintF(TEXT["'open folder' to add\nmore enemies!"], 184*scale, 134*scale) properprintF(TEXT["making enemies is simple!\nno coding required.\nopen the .json file\nto add/change properties"], 184*scale, 158*scale) love.graphics.setColor(255, 255, 255) guielements["exportimagetemplate"]:draw() guielements["openfolderenemiescustom"]:draw() guielements["currentenemydropdown"]:draw() end elseif editorstate == "animations" then if #animations > 0 then love.graphics.setScissor(animationguiarea[1]*scale, animationguiarea[2]*scale, (animationguiarea[3]-animationguiarea[1])*scale, (animationguiarea[4]-animationguiarea[2])*scale) local completeheight = 14+#animationguilines.triggers*13+12+#animationguilines.conditions*13+12+#animationguilines.actions*13 local offy = math.max(0, guielements["animationsscrollbarver"].value/1*(completeheight-(animationguiarea[4]-animationguiarea[2]))) local completewidth = 0 for i, v in pairs(animationguilines) do for k, w in pairs(v) do local width = 32+animationlineinset for j, z in pairs(w.elements) do width = width + w.elements[j].width end if width > completewidth then completewidth = width end end end local offx = -math.max(0, guielements["animationsscrollbarhor"].value/1*(completewidth-(animationguiarea[3]-animationguiarea[1]))) love.graphics.setColor(255, 255, 255) local y = animationguiarea[2]+1-offy y = y + 2 addanimationtriggerbutton.x = animationguiarea[1]+2+offx addanimationtriggerbutton.y = y-2 addanimationtriggerbutton:draw() properprintF(TEXT["triggers:"], (animationguiarea[1]+13+offx)*scale, y*scale) y = y + 10 for i, v in pairs(animationguilines.triggers) do v:draw((animationguiarea[1]+animationlineinset+offx), y) y = y + 13 end y = y + 2 addanimationconditionbutton.x = animationguiarea[1]+2+offx addanimationconditionbutton.y = y-2 addanimationconditionbutton:draw() properprintF(TEXT["conditions:"], (animationguiarea[1]+13+offx)*scale, y*scale) y = y + 10 for i, v in pairs(animationguilines.conditions) do v:draw((animationguiarea[1]+animationlineinset+offx), y) y = y + 13 end y = y + 2 addanimationactionbutton.x = animationguiarea[1]+2+offx addanimationactionbutton.y = y-2 addanimationactionbutton:draw() properprintF(TEXT["actions:"], (animationguiarea[1]+13+offx)*scale, y*scale) y = y + 10 for i, v in pairs(animationguilines.actions) do v:draw((animationguiarea[1]+animationlineinset+offx), y) y = y + 13 end for i, v in pairs(animationguilines) do for k, w in pairs(v) do for anotherletter, fuck in pairs(w.elements) do if fuck.gui and not fuck.gui.priority then fuck.gui:draw() end end end end love.graphics.setScissor() love.graphics.setColor(90, 90, 90) drawrectangle(animationguiarea[1]-10, animationguiarea[4], 10, 10) end --GUI not priority for i, v in pairs(guielements) do if not v.priority and v.active then v:draw() end end if editorstate == "animations" and editormenuopen and not changemapwidthmenu then for i, v in pairs(animationguilines) do for k, w in pairs(v) do for anotherletter, fuck in pairs(w.elements) do if fuck.gui and fuck.gui.priority then fuck.gui:draw() end end end end end --GUI priority for i, v in pairs(guielements) do if v.priority and v.active then v:draw() end end end end end --TABS function maintab() if _G["from" .. editorstate .. "tab"] then _G["from" .. editorstate .. "tab"]() end editorstate = "main" for i, v in pairs(guielements) do v.active = false end tilemenuy = 0 tilemenumoving = false guielements["tabmain"].fillcolor = {0, 0, 0} guielements["tabtiles"].fillcolor = {63, 63, 63} guielements["tabtools"].fillcolor = {63, 63, 63} guielements["tabmaps"].fillcolor = {63, 63, 63} guielements["tabcustom"].fillcolor = {63, 63, 63} guielements["tabanimations"].fillcolor = {63, 63, 63} guielements["tabmain"].active = true guielements["tabtiles"].active = true guielements["tabtools"].active = true guielements["tabmaps"].active = true guielements["tabcustom"].active = true guielements["tabanimations"].active = true guielements["autoscrollcheckbox"].active = true --guielements["backgrounddropdown"].active = true guielements["musicdropdown"].active = true if musici == 7 then guielements["custommusiciinput"].active = true end guielements["backgroundinput1"].active = true guielements["backgroundinput2"].active = true guielements["backgroundinput3"].active = true for i = 1, #backgroundcolor do guielements["defaultcolor" .. i].active = true end guielements["spritesetdropdown"].active = true guielements["timelimitdecrease"].active = true guielements["timelimitincrease"].active = true guielements["portalgundropdown"].active = true guielements["savebutton"].active = true guielements["menubutton"].active = true guielements["testbutton"].active = true guielements["testbuttonplayer"].active = true guielements["widthbutton"].active = true guielements["levelpropertiesdropdown"].active = true levelpropertiesactive(levelpropertiesdropdown) end function levelpropertiesactive(t) guielements["intermissioncheckbox"].active = t guielements["warpzonecheckbox"].active = t guielements["underwatercheckbox"].active = t guielements["bonusstagecheckbox"].active = t guielements["edgewrappingcheckbox"].active = t guielements["lightsoutcheckbox"].active = t guielements["lowgravitycheckbox"].active = t guielements["autoscrollingcheckbox"].active = not t guielements["autoscrollingscrollbar"].active = not t guielements["custombackgroundcheckbox"].active = not t guielements["customforegroundcheckbox"].active = not t guielements["scrollfactorxscrollbar"].active = not t guielements["scrollfactoryscrollbar"].active = not t guielements["scrollfactor2xscrollbar"].active = not t guielements["scrollfactor2yscrollbar"].active = not t guielements["backgrounddropdown"].active = not t guielements["foregrounddropdown"].active = not t end function levelpropertiestoggle() levelpropertiesdropdown = not levelpropertiesdropdown if levelpropertiesdropdown then guielements["levelpropertiesdropdown"].textcolor = {127, 127, 127} else guielements["levelpropertiesdropdown"].textcolor = {255, 255, 255} end levelpropertiesactive(levelpropertiesdropdown) end function tilestab() if _G["from" .. editorstate .. "tab"] then _G["from" .. editorstate .. "tab"]() end editorstate = "tiles" for i, v in pairs(guielements) do v.active = false end tilemenuy = 0 tilemenumoving = false guielements["tabmain"].fillcolor = {63, 63, 63} guielements["tabtiles"].fillcolor = {0, 0, 0} guielements["tabtools"].fillcolor = {63, 63, 63} guielements["tabmaps"].fillcolor = {63, 63, 63} guielements["tabcustom"].fillcolor = {63, 63, 63} guielements["tabanimations"].fillcolor = {63, 63, 63} guielements["tabmain"].active = true guielements["tabtiles"].active = true guielements["tabtools"].active = true guielements["tabmaps"].active = true guielements["tabcustom"].active = true guielements["tabanimations"].active = true guielements["tilesscrollbar"].active = true guielements["tilesall"].active = true guielements["tilessmb"].active = true guielements["tilesportal"].active = true guielements["tilescustom"].active = true guielements["tilesanimated"].active = true guielements["tilesobjects"].active = true guielements["tilesentities"].active = true if animatedtileslist then tilesanimated() elseif editmtobjects then tilesobjects() elseif editentities then tilesentities() else end end function toolstab() if _G["from" .. editorstate .. "tab"] then _G["from" .. editorstate .. "tab"]() end editorstate = "tools" for i, v in pairs(guielements) do v.active = false end tilemenuy = 0 tilemenumoving = false guielements["tabmain"].fillcolor = {63, 63, 63} guielements["tabtiles"].fillcolor = {63, 63, 63} guielements["tabtools"].fillcolor = {0, 0, 0} guielements["tabmaps"].fillcolor = {63, 63, 63} guielements["tabcustom"].fillcolor = {63, 63, 63} guielements["tabanimations"].fillcolor = {63, 63, 63} guielements["tabmain"].active = true guielements["tabtiles"].active = true guielements["tabtools"].active = true guielements["tabmaps"].active = true guielements["tabcustom"].active = true guielements["tabanimations"].active = true guielements["linkbutton"].active = true guielements["portalbutton"].active = true guielements["selectionbutton"].active = true guielements["powerlinebutton"].active = true guielements["edittitle"].active = true guielements["editauthor"].active = true guielements["editdescription"].active = true guielements["savesettings"].active = true guielements["livesdecrease"].active = true guielements["livesincrease"].active = true guielements["physicsdropdown"].active = true guielements["cameradropdown"].active = true guielements["dropshadowcheckbox"].active = true guielements["realtimecheckbox"].active = true guielements["continuemusiccheckbox"].active = true end function mapstab() if _G["from" .. editorstate .. "tab"] then _G["from" .. editorstate .. "tab"]() end editorstate = "maps" for i, v in pairs(guielements) do v.active = false end tilemenuy = 0 tilemenumoving = false guielements["tabmain"].fillcolor = {63, 63, 63} guielements["tabtiles"].fillcolor = {63, 63, 63} guielements["tabtools"].fillcolor = {63, 63, 63} guielements["tabmaps"].fillcolor = {0, 0, 0} guielements["tabcustom"].fillcolor = {63, 63, 63} guielements["tabanimations"].fillcolor = {63, 63, 63} guielements["tabmain"].active = true guielements["tabtiles"].active = true guielements["tabtools"].active = true guielements["tabmaps"].active = true guielements["tabcustom"].active = true guielements["tabanimations"].active = true guielements["worldscrollbar"].active = true guielements["levelscrollbar"].active = true for i = 1, #mappacklevels do --world guielements["world-" .. i].active = true end guielements["newworld"].active = true guielements["savebutton2"].active = true --guielements["autosavecheckbox"].active = true switchworldselection(marioworld) updatelevelscrollbar() end function customtab() if _G["from" .. editorstate .. "tab"] then _G["from" .. editorstate .. "tab"]() end editorstate = "custom" for i, v in pairs(guielements) do v.active = false end tilemenuy = 0 tilemenumoving = false customtabtab(customtabstate) end --tabs in tabs function customtabtab(t) local t = t or "graphics" for i, v in pairs(guielements) do v.active = false end guielements["tabmain"].fillcolor = {63, 63, 63} guielements["tabtiles"].fillcolor = {63, 63, 63} guielements["tabtools"].fillcolor = {63, 63, 63} guielements["tabmaps"].fillcolor = {63, 63, 63} guielements["tabcustom"].fillcolor = {0, 0, 0} guielements["tabanimations"].fillcolor = {63, 63, 63} guielements["tabmain"].active = true guielements["tabtiles"].active = true guielements["tabtools"].active = true guielements["tabmaps"].active = true guielements["tabcustom"].active = true guielements["tabanimations"].active = true guielements["graphicscustomtab"].textcolor = {127, 127, 127} guielements["tilescustomtab"].textcolor = {127, 127, 127} guielements["backgroundscustomtab"].textcolor = {127, 127, 127} guielements["soundscustomtab"].textcolor = {127, 127, 127} guielements["textcustomtab"].textcolor = {127, 127, 127} guielements["enemiescustomtab"].textcolor = {127, 127, 127} guielements["graphicscustomtab"].active = true guielements["tilescustomtab"].active = true guielements["backgroundscustomtab"].active = true guielements["soundscustomtab"].active = true guielements["textcustomtab"].active = true guielements["enemiescustomtab"].active = true if t == "graphics" then guielements["graphicscustomtab"].textcolor = {255, 255, 255} guielements["currentimagedropdown"].active = true guielements["exportimagetemplate"].active = true guielements["openfoldercustom"].active = true guielements["saveimage"].active = true guielements["resetimage"].active = true elseif t == "tiles" then guielements["tilescustomtab"].textcolor = {255, 255, 255} guielements["exporttilestemplate"].active = true guielements["exportanimatedtilestemplate"].active = true guielements["openfoldertilescustom"].active = true guielements["openfolderanimatedtilescustom"].active = true guielements["saveimage"].active = true elseif t == "backgrounds" then guielements["backgroundscustomtab"].textcolor = {255, 255, 255} guielements["saveimage"].active = true guielements["openfolderbackgroundscustom"].active = true guielements["currentbackgrounddropdown"].active = true elseif t == "sounds" then guielements["currentsounddropdown"].active = true guielements["soundscustomtab"].textcolor = {255, 255, 255} guielements["exportimagetemplate"].active = true guielements["openfoldersoundscustom"].active = true guielements["openfoldermusiccustom"].active = true elseif t == "text" then texttabtab(textstate) elseif t == "enemies" then guielements["enemiescustomtab"].textcolor = {255, 255, 255} guielements["currentenemydropdown"].active = true guielements["exportimagetemplate"].active = true guielements["openfolderenemiescustom"].active = true end customtabstate = t end function texttabtab(t) local t = t or "hud" for i, v in pairs(guielements) do v.active = false end guielements["tabmain"].fillcolor = {63, 63, 63} guielements["tabtiles"].fillcolor = {63, 63, 63} guielements["tabtools"].fillcolor = {63, 63, 63} guielements["tabmaps"].fillcolor = {63, 63, 63} guielements["tabcustom"].fillcolor = {0, 0, 0} guielements["tabanimations"].fillcolor = {63, 63, 63} guielements["tabmain"].active = true guielements["tabtiles"].active = true guielements["tabtools"].active = true guielements["tabmaps"].active = true guielements["tabcustom"].active = true guielements["tabanimations"].active = true guielements["graphicscustomtab"].textcolor = {127, 127, 127} guielements["tilescustomtab"].textcolor = {127, 127, 127} guielements["backgroundscustomtab"].textcolor = {127, 127, 127} guielements["soundscustomtab"].textcolor = {127, 127, 127} guielements["textcustomtab"].textcolor = {255, 255, 255} guielements["enemiescustomtab"].textcolor = {127, 127, 127} guielements["graphicscustomtab"].active = true guielements["tilescustomtab"].active = true guielements["backgroundscustomtab"].active = true guielements["soundscustomtab"].active = true guielements["textcustomtab"].active = true guielements["enemiescustomtab"].active = true guielements["endingtexttab"].textcolor = {127, 127, 127} guielements["hudtexttab"].textcolor = {127, 127, 127} guielements["castletexttab"].textcolor = {127, 127, 127} guielements["levelscreentexttab"].textcolor = {127, 127, 127} guielements["endingtexttab"].active = true guielements["hudtexttab"].active = true guielements["castletexttab"].active = true guielements["levelscreentexttab"].active = true guielements["savecustomtext"].active = true if t == "hud" then guielements["hudtexttab"].textcolor = {255, 255, 255} guielements["editplayername"].active = true guielements["hudcolor<"].active = true guielements["hudcolor>"].active = true guielements["hudworldlettercheckbox"].active = true guielements["hudvisiblecheckbox"].active = true guielements["hudoutlinecheckbox"].active = true guielements["hudsimplecheckbox"].active = true elseif t == "ending" then guielements["endingtexttab"].textcolor = {255, 255, 255} guielements["editendingtext1"].active = true guielements["editendingtext2"].active = true guielements["endingcolor<"].active = true guielements["endingcolor>"].active = true elseif t == "castle" then guielements["castletexttab"].textcolor = {255, 255, 255} guielements["edittoadtext1"].active = true guielements["edittoadtext2"].active = true guielements["edittoadtext3"].active = true guielements["editpeachtext1"].active = true guielements["editpeachtext2"].active = true guielements["editpeachtext3"].active = true guielements["editpeachtext4"].active = true guielements["editpeachtext5"].active = true guielements["stevecheckbox"].active = true elseif t == "levelscreen" then guielements["levelscreentexttab"].textcolor = {255, 255, 255} guielements["editlevelscreentext"].active = true --levelscreenimage if levelscreenimagecheck ~= mappack .. "-" .. marioworld .. "-" .. mariolevel then if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/" .. marioworld .. "-" .. mariolevel .. "levelscreen.png") then levelscreenimage = love.graphics.newImage(mappackfolder .. "/" .. mappack .. "/" .. marioworld .. "-" .. mariolevel .. "levelscreen.png") elseif love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/" .. marioworld .. "levelscreen.png") then levelscreenimage = love.graphics.newImage(mappackfolder .. "/" .. mappack .. "/" .. marioworld .. "levelscreen.png") elseif love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/levelscreen.png") then levelscreenimage = love.graphics.newImage(mappackfolder .. "/" .. mappack .. "/levelscreen.png") else levelscreenimage = false end levelscreenimagecheck = mappack .. "-" .. marioworld .. "-" .. mariolevel end end textstate = t end function animationstab() if _G["from" .. editorstate .. "tab"] then _G["from" .. editorstate .. "tab"]() end editorstate = "animations" for i, v in pairs(guielements) do v.active = false end tilemenuy = 0 tilemenumoving = false guielements["tabmain"].fillcolor = {63, 63, 63} guielements["tabtiles"].fillcolor = {63, 63, 63} guielements["tabtools"].fillcolor = {63, 63, 63} guielements["tabmaps"].fillcolor = {63, 63, 63} guielements["tabcustom"].fillcolor = {63, 63, 63} guielements["tabanimations"].fillcolor = {0, 0, 0} guielements["tabmain"].active = true guielements["tabtiles"].active = true guielements["tabtools"].active = true guielements["tabmaps"].active = true guielements["tabcustom"].active = true guielements["tabanimations"].active = true guielements["animationsscrollbarver"].active = true guielements["animationsscrollbarhor"].active = true guielements["animationsavebutton"].active = true guielements["animationdelbutton"].active = true guielements["animationselectdrop"].active = true guielements["animationnewbutton"].active = true guielements["animationnameinput"].active = true generateanimationgui() end function fromanimationstab() saveanimation() end function nothingtab() if _G["from" .. editorstate .. "tab"] then _G["from" .. editorstate .. "tab"]() end for i, v in pairs(guielements) do v.active = false end end function endingtextcolorleft() if textcolorl == "red" then textcolorl = "white" elseif textcolorl == "blue" then textcolorl = "red" elseif textcolor1 == "yellow" then textcolorl = "blue" elseif textcolorl == "green" then textcolorl = "yellow" elseif textcolorl == "orange" then textcolorl = "green" elseif textcolorl == "pink" then textcolorl = "orange" elseif textcolorl == "purple" then textcolorl = "pink" elseif textcolorl ~= "white" then textcolorl = "blue" end end function endingtextcolorright() if textcolorl == "white" then textcolorl = "red" elseif textcolorl == "red" then textcolorl = "blue" elseif textcolor1 == "blue" then textcolorl = "yellow" elseif textcolorl == "yellow" then textcolorl = "green" elseif textcolorl == "green" then textcolorl = "orange" elseif textcolorl == "orange" then textcolorl = "pink" elseif textcolorl == "pink" then textcolorl = "purple" elseif textcolorl ~= "purple" then textcolorl = "yellow" end end function hudtextcolorleft() if textcolorp == "red" then textcolorp = "white" elseif textcolorp == "blue" then textcolorp = "red" elseif textcolor1 == "yellow" then textcolorp = "blue" elseif textcolorp == "green" then textcolorp = "yellow" elseif textcolorp == "orange" then textcolorp = "green" elseif textcolorp == "pink" then textcolorp = "orange" elseif textcolorp == "purple" then textcolorp = "pink" elseif textcolorp == "black" then textcolorp = "purple" elseif textcolorp ~= "white" then textcolorp = "blue" end if textcolorp == "black" then togglehudoutline(false) elseif textcolorp ~= "white" then togglehudoutline(true) end end function hudtextcolorright() if textcolorp == "white" then textcolorp = "red" elseif textcolorp == "red" then textcolorp = "blue" elseif textcolor1 == "blue" then textcolorp = "yellow" elseif textcolorp == "yellow" then textcolorp = "green" elseif textcolorp == "green" then textcolorp = "orange" elseif textcolorp == "orange" then textcolorp = "pink" elseif textcolorp == "pink" then textcolorp = "purple" elseif textcolorp == "purple" then textcolorp = "black" elseif textcolorp ~= "black" then textcolorp = "yellow" end if textcolorp == "black" then togglehudoutline(false) elseif textcolorp ~= "white" then togglehudoutline(true) end end function generateanimationgui() if not animations[currentanimation] then createnewanimation(nil,"dont_generate_gui") end animationguilines = {} animationguilines.triggers = {} for i, v in pairs(animations[currentanimation].triggers) do table.insert(animationguilines.triggers, animationguiline:new(v, "trigger")) end animationguilines.conditions = {} for i, v in pairs(animations[currentanimation].conditions) do table.insert(animationguilines.conditions, animationguiline:new(v, "condition")) end animationguilines.actions = {} for i, v in pairs(animations[currentanimation].actions) do table.insert(animationguilines.actions, animationguiline:new(v, "action")) end end function createnewanimation(name,dont_generate_gui) local s = {} s.triggers = {} s.conditions = {} s.actions = {} if not name then local i = 1 while love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/animations/animation" .. i .. ".json") do i = i + 1 end name = "animation" .. i end love.filesystem.createDirectory(mappackfolder .. "/" .. mappack .. "/animations/") love.filesystem.write(mappackfolder .. "/" .. mappack .. "/animations/" .. name .. ".json", JSON:encode_pretty(s)) table.insert(animations, animation:new(mappackfolder .. "/" .. mappack .. "/animations/" .. name .. ".json", name .. ".json")) currentanimation = #animations if not dont_generate_gui then generateanimationgui(currentanimation) end updateanimationdropdown() guielements["animationnameinput"].value = string.sub(animations[currentanimation].name, 1, -6) guielements["animationnameinput"]:updatePos() animationsaveas = false end function updateanimationdropdown() local args = {} for i, v in ipairs(animations) do table.insert(args, string.sub(v.name, 1, -6)) end guielements["animationselectdrop"] = guielement:new("dropdown", 15, 20, 15, selectanimation, currentanimation, unpack(args)) end function deleteanimationguiline(t, tabl) for i, v in ipairs(animationguilines[t .. "s"]) do if v == tabl then table.remove(animationguilines[t .. "s"], i) end end end function movedownanimationguiline(t, tabl) for i, v in ipairs(animationguilines[t .. "s"]) do if v == tabl then if i ~= #animationguilines[t .. "s"] then animationguilines[t .. "s"][i], animationguilines[t .. "s"][i+1] = animationguilines[t .. "s"][i+1], animationguilines[t .. "s"][i] break end end end end function moveupanimationguiline(t, tabl) for i, v in ipairs(animationguilines[t .. "s"]) do if v == tabl then if i ~= 1 then animationguilines[t .. "s"][i], animationguilines[t .. "s"][i-1] = animationguilines[t .. "s"][i-1], animationguilines[t .. "s"][i] break end end end end function selectanimation(i) guielements["animationselectdrop"].var = i saveanimation() currentanimation = i generateanimationgui() guielements["animationnameinput"].value = string.sub(animations[currentanimation].name, 1, -6) guielements["animationnameinput"]:updatePos() animationsaveas = false end function saveanimation() local out = {} local typelist = {"triggers", "conditions", "actions"} for h, w in ipairs(typelist) do out[w] = {} for i, v in ipairs(animationguilines[w]) do out[w][i] = {} for j, k in ipairs(v.elements) do if k.gui then local val = "" if k.gui.type == "dropdown" then if j == 1 then --find normal name for l, m in pairs(animationlist) do if m.nicename == k.gui.entries[k.gui.var] then val = l break end end else val = k.gui.entries[k.gui.var] end elseif k.gui.type == "input" then val = k.gui.value end table.insert(out[w][i], val) end end end end animations[currentanimation].triggers = out.triggers animations[currentanimation].conditions = out.conditions animations[currentanimation].actions = out.actions local json = JSON:encode_pretty(out) if animationsaveas then love.filesystem.write(mappackfolder .. "/" .. mappack .. "/animations/" .. animationsaveas .. ".json", json) love.filesystem.remove(animations[currentanimation].filepath) table.remove(animations, currentanimation) table.insert(animations, animation:new(mappackfolder .. "/" .. mappack .. "/animations/" .. animationsaveas .. ".json", animationsaveas .. ".json")) updateanimationdropdown() currentanimation = #animations guielements["animationselectdrop"].var = #animations animationsaveas = false else love.filesystem.write(animations[currentanimation].filepath, json) end animationsaveas = false end local areyousure = false function removeanimation() if areyousure then --areyousure = false else notice.new("Delete Animation?\nPress button again if yes.", notice.white, 2) areyousure = true return false end love.filesystem.remove(animations[i or currentanimation].filepath) table.remove(animations, currentanimation) if #animations <= 0 then createnewanimation() else notice.new("Animation Deleted", notice.red, 3) end updateanimationdropdown() currentanimation = #animations guielements["animationselectdrop"].var = #animations generateanimationgui(currentanimation) end function addanimationtrigger() table.insert(animationguilines.triggers, animationguiline:new({}, "trigger")) end function addanimationcondition() table.insert(animationguilines.conditions, animationguiline:new({}, "condition")) end function addanimationaction() table.insert(animationguilines.actions, animationguiline:new({}, "action")) end function openchangewidth() levelmodified = true for i, v in pairs(guielements) do v.active = false end guielements["maptopup"].active = true guielements["maptopdown"].active = true guielements["mapbottomup"].active = true guielements["mapbottomdown"].active = true guielements["mapleftleft"].active = true guielements["mapleftright"].active = true guielements["maprightleft"].active = true guielements["maprightright"].active = true guielements["mapwidthapply"].active = true guielements["mapwidthcancel"].active = true changemapwidthmenu = true newmapwidth = mapwidth newmapheight = mapheight newmapoffsetx = 0 newmapoffsety = 0 end function mapwidthapply() changemapwidthmenu = false objects["tile"] = {} local newmap = {} for x = 1, newmapwidth do newmap[x] = {} for y = 1, newmapheight do local oldx, oldy = x-newmapoffsetx, y-newmapoffsety if inmap(oldx, oldy) then newmap[x][y] = map[oldx][oldy] else newmap[x][y] = {1, gels={}}--, portaloverride={} end if tilequads[newmap[x][y][1]]["collision"] then objects["tile"][tilemap(x, y)] = tile:new(x-1, y-1, 1, 1, true) end end end objects["player"][1].x = objects["player"][1].x + newmapoffsetx objects["player"][1].y = objects["player"][1].y + newmapoffsety map = newmap mapwidth = newmapwidth mapheight = newmapheight xscroll = xscroll + newmapoffsetx yscroll = yscroll + newmapoffsety if xscroll < 0 then xscroll = 0 end if xscroll > mapwidth-width-1 then xscroll = math.max(0, mapwidth-width-1) hitrightside() end if yscroll < 0 then yscroll = 0 end if yscroll > mapheight-height-1 then yscroll = math.max(0, mapheight-height-1) end splitxscroll = {xscroll} splityscroll = {yscroll} --move all them links! for x = 1, mapwidth do for y = 1, mapheight do for i, v in pairs(map[x][y]) do if v == "link" then if map[x][y][i+1] and tonumber(map[x][y][i+1]) then map[x][y][i+1] = tonumber(map[x][y][i+1]) + newmapoffsetx end if map[x][y][i+2] and tonumber(map[x][y][i+2]) then map[x][y][i+2] = tonumber(map[x][y][i+2]) + newmapoffsety end end end end end objects["screenboundary"]["right"].x = mapwidth generatespritebatch() editorclose() allowdrag = false --maintab() end function mapwidthcancel() changemapwidthmenu = false editorclose() allowdrag = false --maintab() end function changenewmapsize(side, dir) if side == "top" then if dir == "up" then newmapheight = newmapheight + 1 newmapoffsety = newmapoffsety + 1 else if newmapheight > 15 then newmapheight = newmapheight - 1 newmapoffsety = newmapoffsety - 1 end end elseif side == "bottom" then if dir == "up" then if newmapheight > 15 then newmapheight = newmapheight - 1 end else newmapheight = newmapheight + 1 end elseif side == "left" then if dir == "left" then newmapwidth = newmapwidth + 1 newmapoffsetx = newmapoffsetx + 1 else if newmapwidth > 1 then newmapwidth = newmapwidth - 1 newmapoffsetx = newmapoffsetx - 1 end end elseif side == "right" then if dir == "left" then if newmapwidth > 1 then newmapwidth = newmapwidth - 1 end else newmapwidth = newmapwidth + 1 end end end function updatetilesscrollbar() guielements["tilesscrollbar"].yrange = guielements["tilesscrollbar"].yrange + guielements["tilesscrollbar"].height guielements["tilesscrollbar"].height = math.max(30, math.min(1, 165/(tilescrollbarheight+165))*167) guielements["tilesscrollbar"].yrange = guielements["tilesscrollbar"].yrange - guielements["tilesscrollbar"].height guielements["tilesscrollbar"].scrollstep = math.max(0.0001, 73/tilescrollbarheight) end function updatelevelscrollbar() local scrolllimit = 201 worldscrollbarheight = math.max(0, ((#mappacklevels+1-(1/16))*16)-scrolllimit) guielements["worldscrollbar"].yrange = guielements["worldscrollbar"].yrange + guielements["worldscrollbar"].height guielements["worldscrollbar"].height = math.max(30, math.min(1, scrolllimit/(worldscrollbarheight+scrolllimit))*scrolllimit) guielements["worldscrollbar"].yrange = guielements["worldscrollbar"].yrange - guielements["worldscrollbar"].height guielements["worldscrollbar"].scrollstep = math.max(0.0001, 73/worldscrollbarheight) if not currentworldselection then return end local scrolllimit = 173 levelscrollbarheight = math.max(0, (#mappacklevels[currentworldselection]*39)+17-scrolllimit) guielements["levelscrollbar"].yrange = guielements["levelscrollbar"].yrange + guielements["levelscrollbar"].height guielements["levelscrollbar"].height = math.max(30, math.min(1, scrolllimit/(levelscrollbarheight+scrolllimit))*scrolllimit) guielements["levelscrollbar"].yrange = guielements["levelscrollbar"].yrange - guielements["levelscrollbar"].height guielements["levelscrollbar"].scrollstep = math.max(0.0001, 73/levelscrollbarheight) end function tilesall() guielements["tilesall"].textcolor = {255, 255, 255} guielements["tilessmb"].textcolor = {127, 127, 127} guielements["tilesportal"].textcolor = {127, 127, 127} guielements["tilescustom"].textcolor = {127, 127, 127} guielements["tilesanimated"].textcolor = {127, 127, 127} guielements["tilesentities"].textcolor = {127, 127, 127} guielements["tilesobjects"].textcolor = {127, 127, 127} tileliststart = 1 tilelistcount = smbtilecount + portaltilecount + customtilecount -1 tilescrollbarheight = math.max(0, math.ceil((smbtilecount + portaltilecount + customtilecount)/22)*17 - 1 - (17*9) - 12) if (not tonumber(currenttile)) or editentities then currenttile = 1 end animatedtilelist = false editentities = false editmtobjects = false updatetilesscrollbar() end function tilessmb() guielements["tilesall"].textcolor = {127, 127, 127} guielements["tilessmb"].textcolor = {255, 255, 255} guielements["tilesportal"].textcolor = {127, 127, 127} guielements["tilescustom"].textcolor = {127, 127, 127} guielements["tilesanimated"].textcolor = {127, 127, 127} guielements["tilesentities"].textcolor = {127, 127, 127} guielements["tilesobjects"].textcolor = {127, 127, 127} tileliststart = 1 tilelistcount = smbtilecount-1 tilescrollbarheight = math.max(0, math.ceil((smbtilecount)/22)*17 - 1 - (17*9) - 12) if (not tonumber(currenttile)) or editentities then currenttile = 1 end animatedtilelist = false editentities = false editmtobjects = false updatetilesscrollbar() end function tilesportal() guielements["tilesall"].textcolor = {127, 127, 127} guielements["tilessmb"].textcolor = {127, 127, 127} guielements["tilesportal"].textcolor = {255, 255, 255} guielements["tilescustom"].textcolor = {127, 127, 127} guielements["tilesanimated"].textcolor = {127, 127, 127} guielements["tilesentities"].textcolor = {127, 127, 127} guielements["tilesobjects"].textcolor = {127, 127, 127} tileliststart = smbtilecount + 1 tilelistcount = portaltilecount - 1 tilescrollbarheight = math.max(0, math.ceil((portaltilecount)/22)*17 - 1 - (17*9) - 12) if (not tonumber(currenttile)) or editentities then currenttile = 1 end animatedtilelist = false editentities = false editmtobjects = false updatetilesscrollbar() end function tilescustom() guielements["tilesall"].textcolor = {127, 127, 127} guielements["tilessmb"].textcolor = {127, 127, 127} guielements["tilesportal"].textcolor = {127, 127, 127} guielements["tilescustom"].textcolor = {255, 255, 255} guielements["tilesanimated"].textcolor = {127, 127, 127} guielements["tilesentities"].textcolor = {127, 127, 127} guielements["tilesobjects"].textcolor = {127, 127, 127} tileliststart = smbtilecount + portaltilecount + 1 tilelistcount = customtilecount - 1 tilescrollbarheight = math.max(0, math.ceil((customtilecount)/22)*17 - 1 - (17*9) - 12) if (not tonumber(currenttile)) or editentities then currenttile = 1 end animatedtilelist = false editentities = false editmtobjects = false updatetilesscrollbar() end function tilesanimated() guielements["tilesall"].textcolor = {127, 127, 127} guielements["tilessmb"].textcolor = {127, 127, 127} guielements["tilesportal"].textcolor = {127, 127, 127} guielements["tilescustom"].textcolor = {127, 127, 127} guielements["tilesanimated"].textcolor = {255, 255, 255} guielements["tilesentities"].textcolor = {127, 127, 127} guielements["tilesobjects"].textcolor = {127, 127, 127} animatedtilelist = true tilelistcount = animatedtilecount - 1 tileliststart = 1 tilescrollbarheight = math.max(0, math.ceil((animatedtilecount)/22)*17 - 1 - (17*9) - 12) if (not tonumber(currenttile)) or editentities then currenttile = 1 end editentities = false editmtobjects = false updatetilesscrollbar() end function tilesentities() guielements["tilesall"].textcolor = {127, 127, 127} guielements["tilessmb"].textcolor = {127, 127, 127} guielements["tilesportal"].textcolor = {127, 127, 127} guielements["tilescustom"].textcolor = {127, 127, 127} guielements["tilesanimated"].textcolor = {127, 127, 127} guielements["tilesentities"].textcolor = {255, 255, 255} guielements["tilesobjects"].textcolor = {127, 127, 127} animatedtilelist = false tilescrollbarheight = math.max(0, entitiesform[#entitiesform].y+entitiesform[#entitiesform].h - 164) editentities = true editmtobjects = false if (not tonumber(currenttile)) or currenttile > entitiescount then currenttile = 1 end updatetilesscrollbar() end function tilesobjects() guielements["tilesall"].textcolor = {127, 127, 127} guielements["tilessmb"].textcolor = {127, 127, 127} guielements["tilesportal"].textcolor = {127, 127, 127} guielements["tilescustom"].textcolor = {127, 127, 127} guielements["tilesanimated"].textcolor = {127, 127, 127} guielements["tilesobjects"].textcolor = {255, 255, 255} guielements["tilesentities"].textcolor = {127, 127, 127} tilescrollbarheight = math.max(0, math.ceil((#multitileobjects))*17 - 1 - (17*9) - 12) editentities = false editmtobjects = true animatedtilelist = false if (not tonumber(currenttile)) or currenttile > #multitileobjects then currenttile = 1 end updatetilesscrollbar() end function placetile(x, y, tilei) local cox, coy = getMouseTile(x, y+8*screenzoom*scale) if inmap(cox, coy) == false then return end levelmodified = true if assistmode then --update latest tiles updatelatesttiles() end local currenttile = tilei or currenttile local argument if editentities and entitylist[currenttile] and entitylist[currenttile].offset then local allowoffset = true --don't clip with entity on the right if ismaptile(cox+1, coy) and map[cox+1][coy][2] and map[cox+1][coy][2] == currenttile and not map[cox+1][coy].argument then allowoffset = false elseif map[cox][coy][2] and map[cox][coy][2] == currenttile and not map[cox][coy].argument then allowoffset = false end if allowoffset then local mx = ((x/scale)+(xscroll*16))%16 --[[if mx < 16*0 and inmap(cox-1, coy) then cox = cox - 1 argument = "o" else]]if mx > 16*0.75 then if type(entitylist[currenttile].offset) == "number" then currenttile = entitylist[currenttile].offset else argument = "o" end end end end if backgroundtilemode then if not editentities then if map[cox][coy]["back"] ~= currenttile then if currenttile == 1 then map[cox][coy]["back"] = nil else map[cox][coy]["back"] = currenttile bmap_on = true end undo_store(cox, coy) generatespritebatch() end end elseif editentities == false then if objects["tile"][tilemap(cox, coy)] and objects["tile"][tilemap(cox, coy)].slant then for num = 1, objects["tile"][tilemap(cox, coy)].slants do objects["pixeltile"][num + tilemap(cox, coy)*100] = nil end end if tilequads[currenttile].collision == true and (tilequads[map[cox][coy][1]].collision == false or (objects["tile"][tilemap(cox, coy)] and objects["tile"][tilemap(cox, coy)].slant)) then local oldtile if tilequads[currenttile].leftslant or tilequads[currenttile].halfleftslant1 or tilequads[currenttile].halfleftslant2 or tilequads[currenttile].rightslant or tilequads[currenttile].halfrightslant1 or tilequads[currenttile].halfrightslant2 then --so many people complained about this minor oddity --guess i have to do a wack workaround oldtile = map[cox][coy][1] map[cox][coy][1] = currenttile end objects["tile"][tilemap(cox, coy)] = tile:new(cox-1, coy-1, 1, 1, true) if oldtile then map[cox][coy][1] = oldtile end elseif tilequads[currenttile].collision == false and tilequads[map[cox][coy][1]].collision == true then objects["tile"][tilemap(cox, coy)] = nil end if map[cox][coy][1] ~= currenttile then undo_store(cox, coy) map[cox][coy][1] = currenttile map[cox][coy]["gels"] = {} generatespritebatch() end if currenttile == 136 then currenttile = 137 placetile(x+16*scale, y, 137) currenttile = 138 placetile(x, y+16*scale, 138) currenttile = 139 placetile(x+16*scale, y+16*scale, 139) currenttile = 136 end else local t = map[cox][coy] --update track previews local queuetrackpreview if trackpreviews and map[cox][coy][2] and entityquads[map[cox][coy][2]] and entityquads[map[cox][coy][2]].t == "track" then queuetrackpreview = true end if entityquads[currenttile] and entityquads[currenttile].t == "remove" then --removing tile if map[cox][coy][2] and map[cox][coy][2] ~= currenttile then undo_store(cox, coy) end for i = 2, #map[cox][coy] do map[cox][coy][i] = nil end map[cox][coy]["argument"] = nil elseif entitylist[currenttile] and entitylist[currenttile].argument then --argument if map[cox][coy]["argument"] then undo_store(cox, coy) end if map[cox][coy]["argument"] and map[cox][coy]["argument"] == entitylist[currenttile].argument then --map[cox][coy]["argument"] = nil elseif map[cox][coy][2] and entitylist[map[cox][coy][2]] and entitylist[map[cox][coy][2]][entitylist[currenttile].argumentname] then map[cox][coy]["argument"] = entitylist[currenttile].argument elseif entitylist[currenttile].t == "supersize" and map[cox][coy][2] and tablecontains(customenemies, map[cox][coy][2]) and enemiesdata[map[cox][coy][2]] and enemiesdata[map[cox][coy][2]].supersize then map[cox][coy]["argument"] = entitylist[currenttile].argument end else if map[cox][coy][2] ~= currenttile then undo_store(cox, coy) end map[cox][coy][2] = currenttile --check if tile has settable option, if so default to this. if entitylist[currenttile] and rightclickvalues[entitylist[currenttile].t] then map[cox][coy][3] = rightclickvalues[entitylist[currenttile].t][2] for i = 4, #map[cox][coy] do map[cox][coy][i] = nil end elseif tablecontains(customenemies, currenttile) and enemiesdata[currenttile] and enemiesdata[currenttile].rightclickmenu then --custom enemies if enemiesdata[currenttile].rightclickmenutable then map[cox][coy][3] = 2 else local default = enemiesdata[currenttile].rightclickmenu[2] local s = tostring(default) default = s:gsub("-", "B") map[cox][coy][3] = default end for i = 4, #map[cox][coy] do map[cox][coy][i] = nil end elseif entitylist[currenttile] and rightclicktype[entitylist[currenttile].t] then map[cox][coy][3] = rightclicktype[entitylist[currenttile].t].default for i = 4, #map[cox][coy] do map[cox][coy][i] = nil end else for i = 3, #map[cox][coy] do map[cox][coy][i] = nil end end map[cox][coy]["argument"] = argument end if queuetrackpreview then generatetrackpreviews() end end editortilemousescroll = false editortilemousescrolltimer = 0 end function powerlinedraw(x, y) local cox, coy = getMouseTile(x, y+8*scale) if inmap(cox, coy) == false then return end if not allowdrag then return end --connect the power lines oh boi if powerlinestate == 1 and ((inmap(cox, coy-1) and (map[cox][coy-1][2] == 43 or map[cox][coy-1][2] == 46 or map[cox][coy-1][2] == 47)) or (inmap(cox, coy+1) and (map[cox][coy+1][2] == 43 or map[cox][coy+1][2] == 45 or map[cox][coy+1][2] == 48))) then map[cox][coy][2] = 43 elseif powerlinestate == 2 and ((inmap(cox-1, coy) and (map[cox-1][coy][2] == 44 or map[cox-1][coy][2] == 45 or map[cox-1][coy][2] == 46)) or (inmap(cox+1, coy) and (map[cox+1][coy][2] == 44 or map[cox+1][coy][2] == 47 or map[cox+1][coy][2] == 48))) then map[cox][coy][2] = 44 elseif (inmap(cox-1, coy) and map[cox-1][coy][2] == 43) or (inmap(cox+1, coy) and map[cox+1][coy][2] == 43) then map[cox][coy][2] = 44 powerlinestate = 2 if inmap(cox-1, coy) and map[cox-1][coy][2] == 43 then if inmap(cox-1, coy-1) and (map[cox-1][coy-1][2] == 43 or map[cox-1][coy-1][2] == 47 or map[cox-1][coy-1][2] == 46) then map[cox-1][coy][2] = 45 elseif inmap(cox-1, coy+1) and (map[cox-1][coy+1][2] == 43 or map[cox-1][coy+1][2] == 45 or map[cox-1][coy+1][2] == 48) then map[cox-1][coy][2] = 46 else map[cox-1][coy][2] = 44 end else if inmap(cox+1, coy-1) and (map[cox+1][coy-1][2] == 43 or map[cox+1][coy-1][2] == 46 or map[cox+1][coy-1][2] == 47) then map[cox+1][coy][2] = 48 elseif inmap(cox+1, coy+1) and (map[cox+1][coy+1][2] == 43 or map[cox+1][coy+1][2] == 45 or map[cox+1][coy+1][2] == 48) then map[cox+1][coy][2] = 47 else map[cox+1][coy][2] = 44 end end elseif (inmap(cox, coy-1) and map[cox][coy-1][2] == 44) or (inmap(cox, coy+1) and map[cox][coy+1][2] == 44) then map[cox][coy][2] = 43 powerlinestate = 1 if inmap(cox, coy-1) and map[cox][coy-1][2] == 44 then if inmap(cox-1, coy-1) and (map[cox-1][coy-1][2] == 44 or map[cox-1][coy-1][2] == 45 or map[cox-1][coy-1][2] == 46) then map[cox][coy-1][2] = 47 elseif inmap(cox+1, coy-1) and (map[cox+1][coy-1][2] == 44 or map[cox+1][coy-1][2] == 47 or map[cox+1][coy-1][2] == 48) then map[cox][coy-1][2] = 46 else map[cox][coy-1][2] = 43 end else if inmap(cox-1, coy+1) and (map[cox-1][coy+1][2] == 44 or map[cox-1][coy+1][2] == 46 or map[cox-1][coy+1][2] == 47) then map[cox][coy+1][2] = 48 elseif inmap(cox+1, coy+1) and (map[cox+1][coy+1][2] == 44 or map[cox+1][coy+1][2] == 47 or map[cox+1][coy+1][2] == 48) then map[cox][coy+1][2] = 45 else map[cox][coy+1][2] = 43 end end else if powerlinestate == 1 then map[cox][coy][2] = 43 elseif powerlinestate == 2 then map[cox][coy][2] = 44 end end for i = 3, #map[cox][coy] do map[cox][coy][i] = nil end end function updatelatesttiles() local ct1 = 1 local ct2 = currenttile if editentities then ct1 = 2 end local t = latesttiles[3] if ct2 ~= 1 then local yes = true for i = 3, #latesttiles do --check if already in quick menu if (ct1 == latesttiles[i][1] and ct2 == latesttiles[i][2]) then yes = false break end end if yes then for i = #latesttiles, 4, -1 do latesttiles[i] = {latesttiles[i-1][1], latesttiles[i-1][2]} end latesttiles[3] = {ct1, ct2} end end end function editorclose() editormenuopen = false for i, v in pairs(guielements) do v.active = false end end function editoropen() for i = 1, players do objects["player"][i]:removeportals() end if editorstate == "linktool" or editorstate == "portalgun" or editorstate == "selectiontool" or editorstate == "powerline" then editorstate = "tools" end rightclickmenuopen = false editormenuopen = true targetmapwidth = mapwidth targetmapheight = mapheight --guielements["mapwidthincrease"].x = 282 + string.len(targetmapwidth)*8 --guielements["mapheightincrease"].x = 282 + string.len(targetmapheight)*8 if mariolivecount == false then guielements["livesincrease"].x = 314 - 6 + 24 else guielements["livesincrease"].x = 314 - 6 + string.len(mariolivecount)*8 end guirepeattimer = 0 getmaps() tilestampselection = false if editorstate == "main" then maintab() elseif editorstate == "tiles" then tilestab() elseif editorstate == "tools" then toolstab() elseif editorstate == "maps" then mapstab() elseif editorstate == "custom" then customtab() elseif editorstate == "animations" then animationstab() end end function mapnumberclick(i, j, k) if editormode then if promptedmetadatasave then --save editor meta data saveeditormetadata() promptedmetadatasave = false end if levelmodified and autosave then guielements["savebutton2"].func() end marioworld = i mariolevel = j actualsublevel = k checkpointx = nil editorloadopen = true if k ~= 0 then startlevel(k) else startlevel(i .. "-" .. j) end end end function getmaps() local clickablerange = {20, 20+201} existingmaps = {} for i = 1, #mappacklevels do --world local world = i if hudworldletter and world > 9 and world <= 9+#alphabet then world = alphabet:sub(world-9, world-9) end guielements["world-" .. i] = guielement:new("button", 3, 20+((i-1)*16), TEXT["world "] .. world, switchworldselection, 0, {i}, 1.4, 83, true) guielements["world-" .. i].bordercolor = {150, 150, 150} guielements["world-" .. i].bordercolorhigh = {255, 255, 255} guielements["world-" .. i].fillcolor = {0, 0, 0} if i == marioworld then guielements["world-" .. i].fillcolor = {30, 30, 30} end guielements["world-" .. i].clickswithinyrange = clickablerange createlevelbuttons(i) end guielements["newworld"] = guielement:new("button", 3, 20+(#mappacklevels*16), TEXT["new world"], addworld, 0, nil, 1.4, 83, true) guielements["newworld"].bordercolor = {150, 150, 150} guielements["newworld"].bordercolorhigh = {255, 255, 255} guielements["newworld"].fillcolor = {0, 0, 0} end function createlevelbuttons(i) local clickablerange = {20, 192} existingmaps[i] = {} for j = 1, #mappacklevels[i] do --level existingmaps[i][j] = {} for k = 0, mappacklevels[i][j] do --sublevel local name = i .. "-" .. j .. "_" .. k if k == 0 then guielements[name] = guielement:new("button", 104, 20+((j-1)*39), TEXT["level "] .. j, mapnumberclick, 0, {i, j, k}, 1.8, 71, true) else guielements[name] = guielement:new("button", 134+((k-1)*19), 41+((j-1)*39), k, mapnumberclick, 0, {i, j, k}, 1.6, 15, true) end local s = i .. "-" .. j if k ~= 0 then s = s .. "_" .. k end s = s .. ".txt" if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/" .. s) then existingmaps[i][j][k] = true guielements[name].textcolor = {255, 255, 255} if meta_data and meta_data[i .. "~" .. j .. "~" .. k] then local d = meta_data[i .. "~" .. j .. "~" .. k] if d.img then guielements[name].image = d.img guielements[name].imagecolor = {128, 128, 128} guielements[name].imageoffsetx = 2 guielements[name].imageoffsety = 2 end --guielements[name].fillcolor = meta_data[i .. "~" .. j .. "~" .. k] end else guielements[name].textcolor = {50, 50, 50} end if i == marioworld and j == mariolevel and k == mariosublevel then if existingmaps[i][j][k] == true then guielements[name].textcolor = {0, 0, 0} else guielements[name].textcolor = {100, 100, 100} end guielements[name].bordercolorhigh = {255, 255, 255} guielements[name].fillcolor = {255, 255, 255} guielements[name].image = false end guielements[name].clickswithinyrange = clickablerange end guielements["newsublevel-" .. i .. "-" .. j] = guielement:new("button", 134+((mappacklevels[i][j])*19), 41+((j-1)*39), "+", addsublevel, 0, {j}, 1.6, 15, true) if not (mappacklevels[i][j] < maxsublevels) then guielements["newsublevel-" .. i .. "-" .. j].active = false end end guielements["newlevel-" .. i] = guielement:new("button", 104, 20+(#mappacklevels[i]*39), TEXT["new level"], addlevel, 0, nil, 1.6, 83, true) guielements["newlevel-" .. i].bordercolor = {150, 150, 150} guielements["newlevel-" .. i].bordercolorhigh = {255, 255, 255} guielements["newlevel-" .. i].fillcolor = {0, 0, 0} end function switchworldselection(w) --switch map "page" local w = w or 1 currentworldselection = w for i = 1, #mappacklevels do if i == w then guielements["world-" .. i].fillcolor = {80, 80, 80} else if i == marioworld then guielements["world-" .. i].fillcolor = {30, 30, 30} else guielements["world-" .. i].fillcolor = {0, 0, 0} end end for j = 1, #mappacklevels[i] do --level for k = 0, mappacklevels[i][j] do --sublevel local name = i .. "-" .. j .. "_" .. k guielements[name].active = (i == w) end if mappacklevels[i][j] < maxsublevels then guielements["newsublevel-" .. i .. "-" .. j].active = (i == w) end end end oldlevelscrollbarv = -1 --update scroll guielements["newlevel-" .. w].active = true --guielements["levelscrollbar"].value = 0 updatelevelscrollbar() end function addworld() if #mappacklevels < maxworlds then table.insert(mappacklevels, {defaultsublevels,defaultsublevels,defaultsublevels,defaultsublevels}) local i = #mappacklevels createlevelbuttons(i) local world = i if hudworldletter and world > 9 and world <= 9+#alphabet then world = alphabet:sub(world-9, world-9) end guielements["world-" .. i] = guielement:new("button", 3, 20+((i-1)*16), TEXT["world "] .. world, switchworldselection, 0, {i}, 1.4, 83, true) guielements["world-" .. i].bordercolor = {150, 150, 150} guielements["world-" .. i].bordercolorhigh = {255, 255, 255} guielements["world-" .. i].fillcolor = {0, 0, 0} guielements["newworld"].y = guielements["newworld"].y + 16 updatelevelscrollbar() else guielements["newworld"].fillcolor = {100, 0, 0} end end function addlevel() local w = currentworldselection if #mappacklevels[w] < maxlevels then table.insert(mappacklevels[w], defaultsublevels) createlevelbuttons(w) guielements["levelscrollbar"].value = 1 oldlevelscrollbarv = -1 --update scroll guielements["newlevel-" .. w].y = guielements["newlevel-" .. w].y + 39 updatelevelscrollbar() else guielements["newlevel-" .. w].fillcolor = {100, 0, 0} end end function addsublevel(l) local w, l = currentworldselection, l --make new sublevel button if mappacklevels[w][l] < maxsublevels then local k = mappacklevels[w][l] + 1 mappacklevels[w][l] = k createlevelbuttons(w) oldlevelscrollbarv = -1 --update scroll sublevelstable = {} for k = 0, mappacklevels[marioworld][mariolevel] do table.insert(sublevelstable, k) end --guielements["newsublevel-" .. w .. "-" .. l].x = guielements["newsublevel-" .. w .. "-" .. l].x + 19 else guielements["newsublevel-" .. w .. "-" .. l].textcolor = {100, 0, 0} end end function editor_mousepressed(x, y, button) if changemapwidthmenu or minimapmoving then return end if rightclickmenuopen then if customrcopen then if customrcopen == "trackpath" then --edit track local x, y = love.mouse.getPosition() local rcp = rightclicktrack local ox, oy = rcp.last[1], rcp.last[2] local dir = rcp.dir local tx, ty = getMouseTile(x, y+8*scale) local ttx,tty = tx, ty tx = tx-rcp.x ty = ty-rcp.y if button == "l" then if trackrightclickmenu.active then trackrightclickmenu:click(x, y, button) trackrightclickmenu.active = false rcp.drag = true return end elseif button == "r" then --right click menu for track grab options if trackrightclickmenu.active then --trackrightclickmenu:click(x, y, button) trackrightclickmenu.active = false rcp.drag = true return end --Change from open to closed local editpath = false if (tx == rcp.path[1][1] and ty == rcp.path[1][2]) then editpath = 1 elseif (tx == rcp.path[#rcp.path][1] and ty == rcp.path[#rcp.path][2]) then editpath = #rcp.path end if editpath then if rcp.path[editpath][3] == "c" or rcp.path[editpath][3] == "o" then rcp.path[editpath][3] = oppositetrackdirection(rcp.path[editpath][3]) return end if rcp.path[editpath][4] == "c" or rcp.path[editpath][4] == "o" then rcp.path[editpath][4] = oppositetrackdirection(rcp.path[editpath][4]) return end --rcp.drag = false end --Change what object is being grabbed (entity or tile) local start = #rcp.path-1 if rcp.path[#rcp.path][4] ~= "c" and rcp.path[#rcp.path][4] ~= "o" then start = #rcp.path end for i = start, 2, -1 do --check normal overlap if (tx == rcp.path[i][1] and ty == rcp.path[i][2]) and ismaptile(ttx, tty) then trackrightclickmenustage = i trackrightclickmenu.active = true trackrightclickmenu.x = x/scale trackrightclickmenu.y = y/scale trackrightclickmenu:updatePos() return --old cycle through code (i like it but there's just too many options :( ) --[[if rcp.path[i][5] == "d" then if not map[ttx][tty][2] then if tilequads[map[ttx][tty][1] ].collision then rcp.path[i][5] = "t" --tile end else rcp.path[i][5] = "r" --reverse end elseif rcp.path[i][5] == "r" then rcp.path[i][5] = "t" --tile elseif rcp.path[i][5] == "t" then rcp.path[i][5] = "tr" --tile reverse elseif rcp.path[i][5] == "tr" then rcp.path[i][5] = "d" --defaults end --break return]] end end end end --close local doreturn = false if button == "r" and rightclickobjects and rightclickobjects[1] and (x > rightclickobjects.x*scale and x < (rightclickobjects.x+rightclickobjects.width)*scale and y > rightclickobjects.y*scale and y < (rightclickobjects.y+rightclickobjects.height)*scale) and customrcopen ~= "region" and customrcopen ~= "path" and customrcopen ~= "trackpath" and customrcopen ~= "link" then --don't close doreturn = true elseif button == "r" then rightclickmenuopen = false allowdrag = false if customrcopen == "region" then rcrtsize() elseif customrcopen == "path" then setrcpath() elseif customrcopen == "trackpath" then setrctrack() elseif customrcopen == "link" then else closecustomrc(true) end customrcopen = false return end --otherwise, update objects if rightclickobjects then for i = 1, #rightclickobjects do local obj = rightclickobjects[i] if obj and obj.priority then if obj:click(x, y, button) then return end end end for i = 1, #rightclickobjects do local obj = rightclickobjects[i] if obj and not obj.priority then if obj:click(x, y, button) then return end end end end --click out of right click menu if button == "l" and rightclickobjects and rightclickobjects[1] then if not ((x > rightclickobjects.x*scale and x < (rightclickobjects.x+rightclickobjects.width)*scale and y > rightclickobjects.y*scale and y < (rightclickobjects.y+rightclickobjects.height)*scale)) then if customrcopen == "region" then elseif customrcopen == "path" then elseif customrcopen == "trackpath" then elseif customrcopen == "link" then else rightclickmenuopen = false allowdrag = false closecustomrc(true) customrcopen = false return end end end if doreturn then return end elseif rightclickmenu then rightclickmenu:click(x, y, button) rightclickmenuopen = false allowdrag = false return end end if levelrightclickmenu.active then levelrightclickmenu:click(x, y, button) levelrightclickmenu.active = false ignoregui = true return end if button == "m" or (button == "l" and eyedroppertool) then --eye dropper (pick tile) local cox, coy = getMouseTile(x, y+8*screenzoom*scale) if pastingtiles then pastingtiles = false end if eyedroppertool then eyedroppertool = false; ANDROIDSHOWTOOLS = false end if inmap(cox, coy) == false then return end if editentities and map[cox][coy][2] then currenttile = map[cox][coy][2] return false end editentities = false tilesall() if backgroundtilemode then local backgroundtile = bmapt(cox, coy, 1) if backgroundtile then currenttile = backgroundtile else currenttile = 1 end else currenttile = map[cox][coy][1] end elseif button == "l" then if editormenuopen == false then levelmodified = true if customrcopen == "link" then local tileX, tileY = getMouseTile(x, y+8*scale) setrclink(tileX, tileY) return elseif editorstate == "linktool" then local tileX, tileY = getMouseTile(x, y+8*scale) local r = map[tileX][tileY] if #r > 1 then local tile = r[2] --LIST OF NUMBERS THAT ARE ACCEPT AS OUTPUT (doors, lights) if tablecontains( inputsi, r[2] ) then --linktoolX, linktoolY = tileX, tileY --syke, just open up the right click menu openrightclickmenu(x, y, tileX, tileY) end end elseif editorstate == "selectiontool" then if not customrcopen then selectiontoolclick[1][1] = x/scale + xscroll*16 selectiontoolclick[1][2] = y/scale + yscroll*16 selectiontoolselection = {} end elseif editorstate ~= "portalgun" and customrcopen == false and not (assistmode and quickmenuopen) then undo_clear() -- left click on the selected area if tileselection and tileselection.finished and x > (tileselection[1]-xscroll-1)*16*scale and y > ((tileselection[2]-yscroll-1)*16-8)*scale and x < (tileselection[3]-xscroll)*16*scale and y < ((tileselection[4]-yscroll)*16-8)*scale then mtclipboard = getTilesSelection() emptySelection("store") pastecenter = {-(math.floor((x-(tileselection[1]-xscroll)*16*scale)/scale/16))-1, -(math.floor((y-((tileselection[2]-yscroll-1)*16-8)*scale)/scale/16))} pastingtiles = true editentities = false tilesall() resettileselection() tileselectionmoving = true allowdrag = false return end if ctrlpressed then if pastingtiles then pastingtiles = false mtclipboard = {} end resettileselection() local tx, ty = getMouseTile(x, y+8*screenzoom*scale) tileselection = {tx, ty, tx, ty} tileselection.finished = false allowdrag = true elseif pastingtiles then --PASTE TILES for i, v in pairs(mtclipboard) do for j, w in pairs(v) do if w[1] == 1 and (not w[2]) and (not w["back"]) and pastemode == 1 then -- nothing else local tx, ty = getMouseTile(x+(i-1 + pastecenter[1])*16*scale, y+(j-1 + pastecenter[2])*16*scale+8*scale) if ismaptile(tx, ty) then local d = mtclipboard[i][j] currenttile = d[1] placetile(x+(i-1 + pastecenter[1])*16*scale, y+(j-1 + pastecenter[2])*16*scale) local tile1 = d[1] if tile1 == 1 then tile1 = false --don't paste empty space end if not backgroundtilemode then if not d[3] then map[tx][ty][1] = tile1 or map[tx][ty][1] map[tx][ty][2] = d[2] or map[tx][ty][2] map[tx][ty]["back"] = d["back"] if map[tx][ty][2] then map[tx][ty]["argument"] = d["argument"] end else map[tx][ty] = {tile1 or map[tx][ty][1], d[2] or map[tx][ty][2], d[3] or map[tx][ty][3], back=d["back"],argument=d["argument"]} end end map[tx][ty]["gels"] = {} end end end end --allowdrag = false end if tileselection and pastingtiles == false then --finish tileselection elseif pastingtiles == false then if (brushsizex > 1 or brushsizey > 1) then for lx = 1, brushsizex do for ly = 1, brushsizey do placetile(x+((lx-1)*16*scale), y+((ly-1)*16*scale)) end end elseif editentities == false and ((love.keyboard.isDown("e") and not android) or (android and replacetool)) then --replace tiles local tx, ty = getMouseTile(x, y+8*screenzoom*scale) if inmap(tx, ty) then local ontile = map[tx][ty][1] if backgroundtilemode then ontile = map[tx][ty]["back"] end for sx = 1, mapwidth do for sy = 1, mapheight do local checktile if backgroundtilemode then ontile = map[sx][sy]["back"] else checktile = map[sx][sy][1] end if ontile == checktile then placetile(((sx-1-math.floor(xscroll))*16*scale), ((sy-1-math.floor(yscroll)-.5)*16*scale)) end end end end elseif editentities == false and ((love.keyboard.isDown("f") and not android) or (android and paintbuckettool)) then --fill tiles local tx, ty = getMouseTile(x, y+8*screenzoom*scale) if inmap(tx, ty) then local ontile = map[tx][ty][1] if backgroundtilemode then ontile = map[tx][ty]["back"] end local replacetiles = paintbucket(tx, ty, ontile) for i, t in pairs(replacetiles) do local sx, sy = t[1], t[2] placetile(((sx-1-math.floor(xscroll))*16*scale), ((sy-1-math.floor(yscroll)-.5)*16*scale)) end end else placetile(x, y) end end end if assistmode and quickmenuopen then if quickmenusel then currenttile = latesttiles[quickmenusel][2] editentities = (latesttiles[quickmenusel][1] == 2) end end else if editorstate == "tiles" then local tile = gettilelistpos(x, y) if editmtobjects then tile = getlistpos(x, y) local mtbutton = getmtbutton(x) if tile and not guielements["mtobjectrename"].active then if mtbutton == 0 then allowdrag = false editorclose() mtclipboard = multitileobjects[tile+1] pastecenter = {0, 0} pastingtiles = true editentities = false tilesall() resettileselection() else if mtbutton == 1 then moveline(mappackfolder .. "/" .. mappack .. "/objects.txt",tile+1,"up") loadmtobjects() elseif mtbutton == 2 then moveline(mappackfolder .. "/" .. mappack .. "/objects.txt",tile+1,"down") loadmtobjects() elseif mtbutton == 3 then deleteline(mappackfolder .. "/" .. mappack .. "/objects.txt", tile+1) loadmtobjects() end end end elseif editentities == false then if tile and tile <= tilelistcount+1 then if animatedtilelist then currenttile = tile + tileliststart-1+90000 else currenttile = tile + tileliststart-1 end if love.keyboard.isDown("lshift") or (tilestampholdtimer and tilestampholdtimer > 0.8) then local sx, sy = x, y sx = (sx - 5*scale)/scale sy = sy + tilesoffset sy = (sy - 38*scale)/scale sx = math.floor(sx/17) sy = math.floor(sy/17) tilestampselection = {x = (sx*17+5)*scale, y = (sy*17+38)*scale-tilesoffset, mx = love.mouse.getX(), my = love.mouse.getY()} else if android then --hold to do tile stamp selection tilestampholdtimer = 0 tilestampholdx = x tilestampholdy = y else editorclose() allowdrag = false end end end else local tile, list = getentitylistpos(x, y) if tile then currenttile = entitiesform[list][tile] if not android then editorclose() allowdrag = false end elseif list then if not entitiesform[list].hidden then --hide entitiesform[list].hidden = true entitiesform[list].h = 0 local namespacing = 10 local ly = 0 --listy for list = 1, #entitiesform do ly = ly + namespacing entitiesform[list].y = ly ly = ly + entitiesform[list].h end else --unhide entitiesform[list].hidden = false entitiesform[list].h = 17*(math.ceil(#entitiesform[list]/22)) local namespacing = 10 local ly = 0 --listy for list = 1, #entitiesform do ly = ly + namespacing entitiesform[list].y = ly ly = ly + entitiesform[list].h end end local v = guielements["tilesscrollbar"].value*tilescrollbarheight tilescrollbarheight = math.max(0.01, entitiesform[#entitiesform].y+entitiesform[#entitiesform].h - 164) updatetilesscrollbar() guielements["tilesscrollbar"].value = math.max(0,math.min(1,v/tilescrollbarheight)) end end elseif editorstate == "main" then if y >= minimapy*scale and y < (minimapy+34)*scale then if x >= minimapx*scale and x < (minimapx+394)*scale then minimapdragging = true toggleautoscroll(false) end end end end elseif button == "wu" then if editormenuopen then else if EditorZoom and ctrlpressed then local dy = 1 local r1, r2 = love.mouse.getX()/(width*16*scale), love.mouse.getY()/(height*16*scale) local zoom1 = screenzoom local centerx, centery = xscroll+(width*(1/screenzoom))*r1, yscroll+(height*(1/screenzoom))*r2 setscreenzoom(math.min(1,math.max(0.05, screenzoom + (screenzoom/(dy*5))))) if zoom1 ~= screenzoom then xscroll = centerx - (width*(1/screenzoom))*r1 yscroll = centery - (height*(1/screenzoom))*r2 splitxscroll[1] = xscroll splityscroll[1] = yscroll end autoscroll = false return elseif editentities then local dobreak = false for formi, form in pairs(entitiesform) do for count = 1, #form do ti = form[count] if currenttile == ti then local ti = math.max(count-1, 1) currenttile = form[ti] editortilemousescroll = {form[ti-1] or 0, form[ti-2] or 0, form[ti+1] or 0, form[ti+2] or 0} editortilemousescrolltimer = 0 dobreak = true break end end if dobreak then break end end else if tonumber(currenttile) and currenttile > 1 then if currenttile ~= 90001 then currenttile = math.floor(currenttile) - 1 editortilemousescroll = true editortilemousescrolltimer = 0 end end end end elseif button == "wd" then if editormenuopen then else if EditorZoom and ctrlpressed then local dy = -1 local r1, r2 = love.mouse.getX()/(width*16*scale), love.mouse.getY()/(height*16*scale) local zoom1 = screenzoom local centerx, centery = xscroll+(width*(1/screenzoom))*r1, yscroll+(height*(1/screenzoom))*r2 setscreenzoom(math.min(1,math.max(0.05, screenzoom + (screenzoom/(dy*5))))) if zoom1 ~= screenzoom then xscroll = centerx - (width*(1/screenzoom))*r1 yscroll = centery - (height*(1/screenzoom))*r2 splitxscroll[1] = xscroll splityscroll[1] = yscroll end autoscroll = false return elseif editentities then local dobreak = false for formi, form in pairs(entitiesform) do for count = 1, #form do local ti = form[count] if currenttile == ti then ti = math.min(count+1, #form) currenttile = form[ti] editortilemousescroll = {form[ti-1] or 0, form[ti-2] or 0, form[ti+1] or 0, form[ti+2] or 0} editortilemousescrolltimer = 0 dobreak = true break end end if dobreak then break end end elseif animatedtilelist or currenttile >= 90001 then if currenttile < animatedtilecount+90000 then currenttile = math.floor(currenttile) + 1 editortilemousescroll = true editortilemousescrolltimer = 0 end else if currenttile < smbtilecount+portaltilecount+customtilecount then currenttile = math.floor(currenttile) + 1 editortilemousescroll = true editortilemousescrolltimer = 0 end end end elseif button == "r" then if editormenuopen == false and editorstate ~= "powerline" then local tileX, tileY = getMouseTile(x, y+8*screenzoom*scale) if inmap(tileX, tileY) == false then return end if pastingtiles then pastingtiles = false --reset tileselection and stop pasting else if tileselection and tileselection.finished then --reset tileselection resettileselection() return end local r = map[tileX][tileY] if #r > 1 then openrightclickmenu(x, y, tileX, tileY) else if editorstate ~= "portalgun" and not customrcopen then local cox, coy = getMouseTile(x, y+8*screenzoom*scale) if objects["player"][1] then local p = objects["player"][1] p.x = cox-1+2/16 p.y = coy-p.height if p.animation == "vinestart" then p.animation = false p.controlsenabled = true p.active = true end --check if anything below if (not rightkey(1)) and (not leftkey(1)) and #checkrect(p.x, p.y+3/16, p.width, p.height, {"tile"}, true) == 0 then p.static = true p.speedy = 0 p.speedx = 0 p.animationstate = "idle" p.falling = false p.jumping = false p:setquad() end --[[if objects["flipblock"][1] then objects["flipblock"][1].instantdelete = true end if #checkrect(p.x, p.y+3/16, p.width, p.height, {"tile"}, true) == 0 then table.insert(objects["flipblock"], tile:new(cox-1, coy, 1, 1, true)) end]] end end end end else if editorstate == "main" then if y >= (minimapy+2)*scale and y < (minimapy+32)*scale then if x >= (minimapx+2)*scale and x < (minimapx+392)*scale then local x = math.floor((x-minimapx*scale+math.floor(minimapscroll*scale*2))/scale/2) local y = math.floor((y-minimapy*scale)/scale/2) if objects["player"][1] then objects["player"][1].x = x-1+2/16 objects["player"][1].y = y-1+2/16 end end end elseif editorstate == "tiles" then if editmtobjects then local tile = getlistpos(x, y) if tile and not guielements["mtobjectrename"].active then local obj = guielements["mtobjectrename"] obj.active = true obj.value = multitileobjectnames[tile+1] obj.i = tile+1 obj.y = 39+(17*tile)-(tilesoffset/scale) obj.cursorpos = string.len(obj.value)+1 obj.inputting = true allowdrag = false end end elseif editorstate == "maps" then for j = 1, #mappacklevels[currentworldselection] do --level for k = 0, mappacklevels[currentworldselection][j] do --sublevel local name = currentworldselection .. "-" .. j .. "_" .. k if guielements[name]:inhighlight(x, y) then levelrightclickmenu.active = true levelrightclickmenu.x = x/scale levelrightclickmenu.y = y/scale levelrightclickmenu:updatePos() levelrightclickmenu.level = {currentworldselection, j, k} levelrightclickmenu.button = guielements[name] return end end end end end end end function openrightclickmenu(x, y, tileX, tileY) local r = map[tileX][tileY] local tile = r[2] if not r[2] then return false end levelmodified = true --LIST OF TILES THAT DO SHIT if entitylist[r[2]] and rightclickvalues[entitylist[r[2]].t] then rightclickmenuX = x rightclickmenuY = y rightclickmenucox = tileX rightclickmenucoy = tileY rightclickmenuopen = true rightclickmenutile = entitylist[r[2]].t rightclickobjects = {} rightclickvalues2 = {} customrcopen = false --create button --get width and start local rcwidth = 0 local start for i = 1, #rightclickvalues[rightclickmenutile] do if string.len(rightclickvalues[rightclickmenutile][i]) > rcwidth then rcwidth = string.len(rightclickvalues[rightclickmenutile][i]) end if rightclickvalues[rightclickmenutile][i] == r[3] then start = rightclickvalues[rightclickmenutile][i] end end rightclickmenu = guielement:new("rightclick", x/scale, y/scale, rcwidth, rightclickmenuclick, start, unpack(rightclickvalues[rightclickmenutile])) if rightclickmenu.x+rightclickmenu.width*8 > width*16 then rightclickmenu.x = (width*16)-rightclickmenu.width*8 end elseif tablecontains(customenemies, r[2]) and enemiesdata[r[2]] and enemiesdata[r[2]].rightclickmenu then local v = enemiesdata[r[2]] rightclickmenuX = x rightclickmenuY = y rightclickmenucox = tileX rightclickmenucoy = tileY rightclickmenuopen = true rightclickmenutile = r[2] rightclickobjects = {} rightclickvalues2 = {} customrcopen = false --create button --get width and start local rcwidth = 0 local start = v.rightclickmenu[2] if v.rightclickmenutable then start = (tonumber(r[3]) or 2) end for i = 1, #v.rightclickmenu do --replace negative sign for saving if (not v.rightclickmenutable) then local s = tostring(v.rightclickmenu[i]) v.rightclickmenu[i] = s:gsub("-", "B") end --get longest name if v.rightclickmenudisplay then if string.len(v.rightclickmenudisplay[i]) > rcwidth then rcwidth = string.len(v.rightclickmenudisplay[i]) end else if type(v.rightclickmenu[i]) == "table" then notice.new("right click option name\nmissing for option " .. i, notice.red, 3) elseif string.len(v.rightclickmenu[i]) > rcwidth then rcwidth = string.len(v.rightclickmenu[i]) end end --is the option currently selected? if i ~= 1 and (not v.rightclickmenutable) and v.rightclickmenu[i] == tostring(r[3]) then if v.rightclickmenudisplay then start = v.rightclickmenudisplay[i] else start = v.rightclickmenu[i] end end end if v.rightclickmenudisplay then rightclickmenu = guielement:new("rightclick", x/scale, y/scale, rcwidth, rightclickmenuclick, start, unpack(v.rightclickmenudisplay)) else rightclickmenu = guielement:new("rightclick", x/scale, y/scale, rcwidth, rightclickmenuclick, start, unpack(v.rightclickmenu)) end if rightclickmenu.x+rightclickmenu.width*8 > width*16 then rightclickmenu.x = (width*16)-rightclickmenu.width*8 end if v.rightclickmenutable then rightclickmenu.trustWhatStartWasSetAs = true end elseif entitylist[r[2]] and rightclicktype[entitylist[r[2]].t] then --custom rightclick menu rightclickmenuX = x rightclickmenuY = y rightclickmenucox = tileX rightclickmenucoy = tileY rightclickmenuopen = true rightclickobjects = {width = 8, height = 6} --width 4px border | height 4px border, 2px obj separation local rx, ry = (x/scale)+4, (y/scale)+4 local rct = rightclicktype[entitylist[r[2]].t] --custom right-click table customrcopen = entitylist[r[2]].t --rct.name local usingdefaultvalues = false if ((not r[3]) or (r[3] == "link" and #r == 5)) and rct.default then table.insert(map[rightclickmenucox][rightclickmenucoy], 3, rct.default) --load default if there is no right-click value usingdefaultvalues = true end rightclickvalues2 = {map[rightclickmenucox][rightclickmenucoy][3]}--right-click values if tostring(map[rightclickmenucox][rightclickmenucoy][3]):find("|") then rightclickvalues2 = tostring(map[rightclickmenucox][rightclickmenucoy][3]):split("|")--split the values end --load in default values if there aren't enough local defaultvalues = {} if rct.default and (not rct.fixdefault) and (not usingdefaultvalues) then if tostring(rct.default):find("|") then defaultvalues = rct.default:split("|") else defaultvalues = {rct.default} end local numberofdefaultvalues = #defaultvalues for i = #rightclickvalues2+1, numberofdefaultvalues do if ((rct.ignoredefault and rct.ignoredefault[i])) then rightclickvalues2[i] = rct.ignoredefault[i] else rightclickvalues2[i] = defaultvalues[i] end end end --modify values in special ways local vt = rightclickvalues2 if rct.varfunc then local i = 1 while rightclickvalues2[i] do rightclickvalues2[i] = rct.varfunc(rightclickvalues2[i], i) i = i + 1 end end for i, t in pairs(rct.format) do local addv = 0 local width = 0 local ttype = type(t) if ttype == "string" then table.insert(rightclickobjects, guielement:new("text", rx, ry, t, {255, 255, 255})) width = 8*#t addv = 10 elseif ttype == "table" then local obj = t[1] if obj == "input" then table.insert(rightclickobjects, guielement:new("input", rx, ry, t[4], t[7], vt[t[2]] or t[3], t[5], t[6], "rightclick")) width = t[4]*8+5 addv = 16 elseif obj == "smallinput" then table.insert(rightclickobjects, guielement:new("input", rx, ry-2, t[4], t[7], vt[t[2]] or t[3], t[5], t[6], "rightclick", 1, nil, nil, 0)) width = t[4]*8+3 addv = 14 elseif obj == "dropdown" then local var = vt[t[2]] if var == nil and t.default ~= nil then var = t.default end if ((not rct.t) or t.ignorerctt) and tostring(var) then local list = t[5] for i = 1, #list do if tostring(var) == tostring(list[i]) then var = i vt[t[2]] = i break end end end local func = t[4] --function called when dropdown is clicked if not func then --if there is no function, make one local varid, objecti = t[2], #rightclickobjects+1 func = function(v) rightclickobjects[objecti].var = v rightclickvalues2[varid] = v end end local d = guielement:new("dropdown", rx, ry, t[3], func, var or 1, unpack(t[5])) if t[6] then d.displayentries = t[6] end --d.dropup = ((d.y+11+(10*#d.entries)) > (height*16)) table.insert(rightclickobjects, d) width = t[3]*8+13 addv = 15 elseif obj == "button" then if type(t[3]) == "table" then for i = 3, #t do local b = guielement:new("button", rx+width, ry, t[i][1], t[i][2], 1, t[i][3]) if t[i].textcolor then b.textcolor = t[i].textcolor end table.insert(rightclickobjects, b) width = width + #t[i][1]*8+6 end else local b = guielement:new("button", rx, ry, t[3], t[4], 1, t[5]) if t[i].textcolor then b.textcolor = t[i].textcolor end table.insert(rightclickobjects, b) width = #t[3]*8+6 end addv = 14 elseif obj == "dirbuttonset" or obj == "hordirbuttonset" or obj == "verdirbuttonset" or obj == "rotdirbuttonset" or obj == "rotbuttonset" or obj == "orientationbuttonset" or obj == "anglebuttonset" then --buttons for 4 directions local bt if obj == "dirbuttonset" then bt = {{{directionsimg, directionsquad["left"]}, "left"}, {{directionsimg, directionsquad["up"]}, "up"}, {{directionsimg, directionsquad["right"]}, "right"}, {{directionsimg, directionsquad["down"]}, "down"}} elseif obj == "hordirbuttonset" then bt = {{{directionsimg, directionsquad["left"]}, "left"}, {{directionsimg, directionsquad["right"]}, "right"}} elseif obj == "verdirbuttonset" then bt = {{{directionsimg, directionsquad["up"]}, "up"}, {{directionsimg, directionsquad["down"]}, "down"}} elseif obj == "rotdirbuttonset" then bt = {{{directionsimg, directionsquad["cw"]}, "right"}, {{directionsimg, directionsquad["ccw"]}, "left"}} elseif obj == "rotbuttonset" then bt = {{{directionsimg, directionsquad["cw"]}, "cw"}, {{directionsimg, directionsquad["ccw"]}, "ccw"}} elseif obj == "orientationbuttonset" then bt = {{{directionsimg, directionsquad["hor"]}, "hor"}, {{directionsimg, directionsquad["ver"]}, "ver"}} elseif obj == "anglebuttonset" then bt = {{{directionsimg, directionsquad["left"]}, "left"}, {{directionsimg, directionsquad["left up"]}, "left up"}, {{directionsimg, directionsquad["up"]}, "up"}, {{directionsimg, directionsquad["right up"]}, "right up"}, {{directionsimg, directionsquad["right"]}, "right"}, {{directionsimg, directionsquad["right down"]}, "right down"}, {{directionsimg, directionsquad["down"]}, "down"}, {{directionsimg, directionsquad["left down"]}, "left down"}} end local buttonsstart = #rightclickobjects+1 for i = 1, #bt do --button press function local buttonfunc = function(variablenum, dir, obj, objstart, objs) --set variable and update button color rightclickvalues2[variablenum] = dir for i = objstart, objstart+objs-1 do if i == obj then rightclickobjects[i].bordercolorhigh = {255,127,127} rightclickobjects[i].bordercolor = {255,0,0} else rightclickobjects[i].bordercolorhigh = {255,255,255} rightclickobjects[i].bordercolor = {127,127,127} end end end local b = guielement:new("button", rx+width, ry, bt[i][1], buttonfunc, 0, {t[2], bt[i][2], #rightclickobjects+1, buttonsstart, #bt}, 1, 8) if rightclickvalues2[t[2]] == bt[i][2] then--is the direction selected b.bordercolorhigh = {255, 127, 127} b.bordercolor = {255, 0, 0} end table.insert(rightclickobjects, b) width = width + 8+4 end addv = 14 elseif obj == "checkbox" then local var = vt[t[2]] if var == nil and t.default ~= nil then var = t.default end if type(var) == "string" then var = vt[t[2]] == "true" end local func = t[4] --function called when check box is ticked if not func then --if there is no function, make one local varid, objecti = t[2], #rightclickobjects+1 func = function(v) rightclickobjects[objecti].var = v rightclickvalues2[varid] = v end end local d = guielement:new("checkbox", rx, ry+2, func, var, t[3] or "") table.insert(rightclickobjects, d) width = #t[3]*8+10 addv = 13 elseif obj == "slider" then local d = guielement:new("scrollbar", rx, ry, 100, 33, 9, vt[t[2]], "hor") d.backgroundcolor = {0,0,0} d.scrollstep = 0 d.displayfunction = t[3] d.rightclickvalue = t[2] if t.range then local v = tostring(vt[t[2]] or defaultvalues[d.rightclickvalue] or 0) v = v:gsub("n", "-") v = tonumber(v) d.value = (v-t.range[1])/(t.range[2]-t.range[1]) d.rcrange = t.range --convert to value for saving d.updatefunc = function(self, v) local i = self.rightclickvalue local min, max, rnd, step = self.rcrange[1], self.rcrange[2], self.rcrange.round, self.rcrange.step local s if step then s = math.floor(((v*(max-min))+min) * (1/step)) /(1/step) else s = round((v*(max-min))+min, rnd or 2) end s = tostring(s) rightclickvalues2[i] = s:gsub("-", "n") end --what's displayed in slider d.displayfunction = function(self, v) local min, max, rnd, step = self.rcrange[1], self.rcrange[2], self.rcrange.round, self.rcrange.step local s if step then s = math.floor(((v*(max-min))+min) * (1/step)) /(1/step) else s = round((v*(max-min))+min, rnd or 2) end if math.floor(s) ~= s or string.len(s) <= math.floor(self.width/8)-2 then return formatscrollnumber(s) else return s end end d:updatefunc(d.value) end if (not d.value) and defaultvalues then d.value = ((tonumber(defaultvalues[d.rightclickvalue]) or 0)-t.range[1])/(t.range[2]-t.range[1]) end table.insert(rightclickobjects, d) width = 100 addv = 12 end end if width+8 > rightclickobjects.width then rightclickobjects.width = width+8 end ry = ry + addv rightclickobjects.height = rightclickobjects.height + addv end if rct.objfunc then rct.objfunc() end --Move if out of screen local scootx = ((x/scale)+rightclickobjects.width > width*16) local scooty = ((y/scale)+rightclickobjects.height > height*16) local shifty = ((y/scale)-rightclickobjects.height < 0) local truey = rightclickobjects[1].y if scootx or scooty then for i = 1, #rightclickobjects do local obj = rightclickobjects[i] if scootx then rightclickobjects[i].x = rightclickobjects[i].x - rightclickobjects.width end if scooty then if shifty then --neither work, just shift rightclickobjects[i].y = ((height*16)-(y/scale))-rightclickobjects.height+rightclickobjects[i].y else --just flip rightclickobjects[i].y = rightclickobjects[i].y - rightclickobjects.height end end obj:updatePos() end end rightclickobjects.x = rightclickobjects[1].x-4 rightclickobjects.y = rightclickobjects[1].y-4 end return true end function rightclickmenuclick(i) if i > 1 then local r = map[rightclickmenucox][rightclickmenucoy] if tablecontains(customenemies, r[2]) and enemiesdata[r[2]] and enemiesdata[r[2]].rightclickmenu then --custom enemy --print(i, enemiesdata[r[2]].rightclickmenu[i]) if enemiesdata[r[2]].rightclickmenutable then r[3] = i else r[3] = enemiesdata[r[2]].rightclickmenu[i] end else r[3] = rightclickvalues[rightclickmenutile][i] end if editorstate == "selectiontool" and #selectiontoolselection > 0 then for i, t in pairs(selectiontoolselection) do local x, y = t[1], t[2] if map[x][y][2] == r[2] then map[x][y][3] = r[3] end end end end end function closecustomrc(save) if rightclickobjects and inmap(rightclickmenucox,rightclickmenucoy) then --save dropdowns correctly local rct = rightclicktype[entitylist[map[rightclickmenucox][rightclickmenucoy][2]].t] --custom right-click table local vt = rightclickvalues2 if rct then for i, t in pairs(rct.format) do local ttype = type(t) if ttype == "table" then local obj = t[1] if obj == "dropdown" and ((not rct.t) or t.ignorerctt) then if vt[t[2]] then vt[t[2]] = t[5][vt[t[2]]] end end end end else notice.new("rightclick menu error", notice.red, 3) end end if rightclicktype[customrcopen].savefunc then rightclicktype[customrcopen].savefunc() end if save and rightclicktype[customrcopen].default then local s = "" for i = 1, #rightclickvalues2 do s = s .. tostring(rightclickvalues2[i]) .. "|" end s = s:sub(1, -2) map[rightclickmenucox][rightclickmenucoy][3] = s if editorstate == "selectiontool" and #selectiontoolselection > 0 then for i, t in pairs(selectiontoolselection) do local x, y = t[1], t[2] if map[x][y][2] == map[rightclickmenucox][rightclickmenucoy][2] then map[x][y][3] = map[rightclickmenucox][rightclickmenucoy][3] end end end end rightclickvalues2 = {} rightclickobjects = {} customrcopen = false end function startrcregion(var, step) local var = var or 1 if editorstate == "linktool" then editorstate = "tools" end local r = map[rightclickmenucox][rightclickmenucoy] local x, y if rightclickvalues2[var+2] and rightclickvalues2[var+3] then x, y = rightclickvalues2[var+2]:gsub("n", "-"), rightclickvalues2[var+3]:gsub("n", "-") x = rightclickmenucox-1+tonumber(x) y = rightclickmenucoy-1+tonumber(y) end guielements["rightclickdrag"] = regiondrag:new(tonumber(rightclickvalues2[var]), tonumber(rightclickvalues2[var+1]), x or rightclickmenucox-1, y or rightclickmenucoy-1) guielements["rightclickdrag"].vars = deepcopy(rightclickvalues2) guielements["rightclickdrag"].cox = rightclickmenucox-1 guielements["rightclickdrag"].coy = rightclickmenucoy-1 if step then guielements["rightclickdrag"].step = step end closecustomrc(true) rightclickobjects = {} customrcopen = "region" rightclickmenuopen = true end function rcrtsize() --right click region trigger size local w = tostring(guielements["rightclickdrag"].width):gsub("-", "n") --change - to n to make level load properly local h = tostring(guielements["rightclickdrag"].height):gsub("-", "n") local x = tostring(guielements["rightclickdrag"].x-guielements["rightclickdrag"].cox):gsub("-", "n") local y = tostring(guielements["rightclickdrag"].y-guielements["rightclickdrag"].coy):gsub("-", "n") rightclickvalues2 = deepcopy(guielements["rightclickdrag"].vars) local r = map[rightclickmenucox][rightclickmenucoy] customrcopen = entitylist[r[2]].t if rightclicktype[customrcopen].regionfunc then rightclicktype[customrcopen].regionfunc(w,h,x,y) end closecustomrc(true) guielements["rightclickdrag"] = nil end function startrcpath(var) --snake block path local var = var or 1 local t = {} if type(var) == "table" then t = var var = t[1] end if editorstate == "linktool" then editorstate = "tools" end rightclickpath = { path = {t.default or {1,0}}, last = t.default or {1,0}, --last placed dir = "right", x = rightclickmenucox,--offsetx y = rightclickmenucoy,--offsety pipe = t.pipe or false, --is it wide? vars = deepcopy(rightclickvalues2), drag = true, --able to add onto path currently? } local rcp = rightclickpath --load path if rightclickvalues2[var] then local s = rightclickvalues2[var]:gsub("n", "-") local s2 = s:split("`") local s3 local ox, oy = rcp.last[1], rcp.last[2] for i = 1, #s2 do s3 = s2[i]:split(":") local x, y = tonumber(s3[1]), tonumber(s3[2]) if x and y then rcp.last = {x, y} table.insert(rcp.path, {x, y}) if x > ox then rcp.dir = "right" elseif x < ox then rcp.dir = "left" elseif y > oy then rcp.dir = "down" elseif y < oy then rcp.dir = "up" end ox, oy = x, y else break end end end closecustomrc(true) rightclickobjects = {} customrcopen = "path" rightclickmenuopen = true end function setrcpath() rightclickvalues2 = deepcopy(rightclickpath.vars) local rcp = rightclickpath local s = "" for i = 2, #rcp.path do local x = tostring(rcp.path[i][1]) local y = tostring(rcp.path[i][2]) s = s .. x:gsub("-", "n") .. ":" .. y:gsub("-", "n") .. "`" end s = s:sub(1, -2) local r = map[rightclickmenucox][rightclickmenucoy] customrcopen = entitylist[r[2]].t if rightclicktype[customrcopen].pathfunc then rightclicktype[customrcopen].pathfunc(s) end rightclickpath = {} closecustomrc(true) allowdrag = true end function startrctrack(var) --track path local var = var or 1 local t = {} if type(var) == "table" then t = var var = t[1] end if editorstate == "linktool" then editorstate = "tools" end rightclicktrack = { --c=closed,o=open,u=up,d=down,l=left,r=right,ur=up-right,etc. --grab: d=default,r=reverse,t=tile,tr=reverse tile path = {t.default or {0,0,"c","c","d"}}, last = t.default or {0,0,"c","c","d"}, --last placed dir = "c", x = rightclickmenucox,--offsetx y = rightclickmenucoy,--offsety vars = deepcopy(rightclickvalues2), drag = true, --able to add onto path currently? } local rcp = rightclicktrack --load path if rightclickvalues2[var] then rcp.path = {} local s = rightclickvalues2[var]:gsub("n", "-") local s2 = s:split("`") local s3 local ox, oy = rcp.last[1], rcp.last[2] for i = 1, #s2 do s3 = s2[i]:split(":") local x, y = tonumber(s3[1]), tonumber(s3[2]) local start, ending, grab = s3[3], s3[4], s3[5] if x and y then rcp.last = {x, y,start,ending} table.insert(rcp.path, {x, y, start, ending, grab}) ox, oy = x, y else break end end end --grab right click menu (rightclick-ception!) trackrightclickmenustage = nil local clickfunc = function(i) local t = {"", "d", "r", "f", "fr", "t", "tr", "tf", "tfr"} rightclicktrack.path[trackrightclickmenustage][5] = t[i-1] end trackrightclickmenu = guielement:new("rightclick", 0, 0, 13, clickfunc, false, "track grabs:", "nothing", "entity {","entity }","entity fast {","entity fast }","tile {","tile }","tile { fast", "tile } fast") trackrightclickmenu.active = false closecustomrc(true) rightclickobjects = {} customrcopen = "trackpath" if android then ANDROIDRIGHTCLICK = false end rightclickmenuopen = true end function setrctrack() rightclickvalues2 = deepcopy(rightclicktrack.vars) local rcp = rightclicktrack local s = "" for i = 1, #rcp.path do --x:y:start:ending` local x = tostring(rcp.path[i][1]) local y = tostring(rcp.path[i][2]) local start = tostring(rcp.path[i][3]) local ending = tostring(rcp.path[i][4]) local grab = tostring(rcp.path[i][5]) s = s .. x:gsub("-", "n") .. ":" .. y:gsub("-", "n") .. ":" .. start .. ":" .. ending .. ":" .. grab .. "`" end s = s:sub(1, -2) local r = map[rightclickmenucox][rightclickmenucoy] customrcopen = entitylist[r[2]].t if rightclicktype[customrcopen].trackfunc then rightclicktype[customrcopen].trackfunc(s) end rightclicktrack = {} closecustomrc(true) generatetrackpreviews() end function startrclink(t, i) --name of link, link id --[[if editorstate == "linktool" then editorstate = "tools" end]] local r = map[rightclickmenucox][rightclickmenucoy] linktooli = false if #r > 1 then local tile = r[2] linktoolX, linktoolY = rightclickmenucox, rightclickmenucoy linktoolt = t or "input" linktooli = i end closecustomrc(true) rightclickobjects = {} customrcopen = "link" rightclickmenuopen = true end function setrclink(endx, endy) local x, y = rightclickmenucox, rightclickmenucoy local r = map[endx][endy] --LIST OF NUMBERS THAT ARE ACCEPTED AS INPUTS (buttons, laserdetectors) local customoutput = false if rightclicktype[entityquads[map[rightclickmenucox][rightclickmenucoy][2]].t].customoutputs and entityquads[r[2]] then customoutput = tablecontains( rightclicktype[entityquads[map[rightclickmenucox][rightclickmenucoy][2]].t].customoutputs, entityquads[r[2]].t ) end if #r > 1 and (tablecontains( outputsi, r[2] ) or customoutput) then r = map[x][y] local i = 1 while (r[i] ~= "link" or (linktooli and tostring(linktooli) ~= tostring(r[i+3]))) and i <= #r do i = i + 1 end map[x][y][i] = "link" map[x][y][i+1] = endx map[x][y][i+2] = endy if linktooli then map[x][y][i+3] = linktooli end if editorstate == "selectiontool" and #selectiontoolselection > 0 then for i, t in pairs(selectiontoolselection) do local x, y = t[1], t[2] if tablecontains(inputsi, map[x][y][2]) then local r = map[x][y] local i = 1 while (r[i] ~= "link" or (linktooli and tostring(linktooli) ~= tostring(r[i+3]))) and i <= #r do i = i + 1 end map[x][y][i] = "link" map[x][y][i+1] = endx map[x][y][i+2] = endy if linktooli then map[x][y][i+3] = linktooli end end end end end allowdrag = false customrcopen = false rightclickmenuopen = false end function resetrclink(id) --id local x, y = rightclickmenucox, rightclickmenucoy local r = map[x][y] local i = 1 while (r[i] ~= "link" or (id and tostring(id) ~= tostring(r[i+3]))) and i <= #r do i = i + 1 end table.remove(map[x][y], i) table.remove(map[x][y], i) table.remove(map[x][y], i) if id then table.remove(map[x][y], i) end if editorstate == "selectiontool" and #selectiontoolselection > 0 then for i, t in pairs(selectiontoolselection) do local x, y = t[1], t[2] if tablecontains(inputsi, map[x][y][2]) then local i = 1 while (r[i] ~= "link" or (id and tostring(id) ~= tostring(r[i+3]))) and i <= #r do i = i + 1 end table.remove(map[x][y], i) table.remove(map[x][y], i) table.remove(map[x][y], i) if id then table.remove(map[x][y], i) end end end end linktoolX, linktoolY = nil, nil end function editor_mousereleased(x, y, button) if minimapmoving then return end if button == "l" then if editormenuopen == false then tilemenumoving = false if editorstate == "linktool" then elseif editorstate == "selectiontool" then if selectiontoolclick[1][1] and selectiontoolclick[1][2] then selectiontoolclick[2][1] = x/scale + xscroll*16 selectiontoolclick[2][2] = y/scale + yscroll*16 local x1, y1, x2, y2 = selectiontoolclick[1][1], selectiontoolclick[1][2], selectiontoolclick[2][1], selectiontoolclick[2][2] if x2 < x1 then x1 = selectiontoolclick[2][1] x2 = selectiontoolclick[1][1] end if y2 < y1 then y1 = selectiontoolclick[2][2] y2 = selectiontoolclick[1][2] end x1, y1, x2, y2 = math.ceil(x1/16), math.ceil((y1+8)/16), math.ceil(x2/16), math.ceil((y2+8)/16) for x = x1, x2 do for y = y1, y2 do if ismaptile(x, y) and map[x][y][2] and tonumber(map[x][y][2]) and map[x][y][2] > 1 then table.insert(selectiontoolselection, {x, y}) end end end end selectiontoolclick = {{false, false}, {false, false}} allowdrag = true else if pastingtiles and tileselectionmoving then --PASTE TILES for i, v in pairs(mtclipboard) do for j, w in pairs(v) do if w[1] == 1 and (not w[2]) and (not w["back"]) and pastemode == 1 then -- nothing else local tx, ty = getMouseTile(x+(i-1 + pastecenter[1])*16*scale, y+(j-1 + pastecenter[2])*16*scale+8*scale) if ismaptile(tx, ty) then local d = mtclipboard[i][j] currenttile = d[1] backgroundtilemode = false placetile(x+(i-1 + pastecenter[1])*16*scale, y+(j-1 + pastecenter[2])*16*scale) map[tx][ty] = {d[1] or map[tx][ty][1], d[2] or map[tx][ty][2], d[3] or map[tx][ty][3], back=d["back"], argument=d["argument"]} map[tx][ty]["gels"] = {} --generate new tracks if track moved if d[2] and entityquads[d[2]] and entityquads[d[2]].t == "track" then generatetrackpreviews() end end end end end local tx, ty = getMouseTile(x, y+8*scale) tileselection = {tx+math.floor(pastecenter[1]), ty+math.floor(pastecenter[2]), tx+math.floor(pastecenter[1])+#mtclipboard-1, ty+math.floor(pastecenter[2])+#mtclipboard[1]-1} tileselection.finished = true pastingtiles = false tileselectionmoving = false elseif tileselection and not tileselection.finished then local sx, sy = math.min(tileselection[1],tileselection[3]), math.min(tileselection[2],tileselection[4]) local sw, sh = math.max(tileselection[1],tileselection[3]), math.max(tileselection[2],tileselection[4]) tileselection = {sx, sy, sw, sh} tileselection.finished = true end allowdrag = true end else guirepeattimer = 0 minimapdragging = false tilestampholdtimer = false if editorstate == "tiles" then allowdrag = true if editmtobjects then elseif editentities == false then if tilestampselection then local t = tilestampselection if x <= t.x then t.x = t.x+17*scale end if y <= t.y then t.y = t.y+17*scale end if x < t.x then t.x2 = t.x; t.x = x else t.x2 = x end if y < t.y then t.y2 = t.y; t.y = y else t.y2 = y end pastingtiles = true pastecenter = {0,0} mtclipboard = {} local tile = 1 for tx = 1, math.ceil((t.x2-t.x)/(17*scale)) do mtclipboard[tx] = {} for ty = 1, math.ceil((t.y2-t.y)/(17*scale)) do local tile = gettilelistpos(t.x+(17*scale)*(tx-1), t.y+(17*scale)*(ty-1)) if tile and tile <= tilelistcount+1 then if animatedtilelist then tile = tile + tileliststart-1+90000 else tile = tile + tileliststart-1 end mtclipboard[tx][ty] = {tile or 1} end end end allowdrag = false editorclose() tilestampselection = false else if android then local tile = gettilelistpos(x, y) if tile and tile <= tilelistcount+1 then editorclose() --allowdrag = false end end end else tilestampselection = false if android then local tile, list = getentitylistpos(x, y) if tile then editorclose() --allowdrag = false end end end end end end if rightclickmenuopen then if customrcopen then if rightclickobjects then for i = 1, #rightclickobjects do local obj = rightclickobjects[i] if obj then if obj:unclick(x, y, button) then return end end end end end end if animationguilines and editormenuopen and not changemapwidthmenu and not minimapmoving then for i, v in pairs(animationguilines) do for k, w in pairs(v) do w:unclick(x, y, button) end end end end function editor_keypressed(key) if (not editormenuopen) and (not customrcopen) and (not rightclickmenuopen) then if key == "=" then assistmode = not assistmode elseif (key == "-" or key == "tab") then backgroundtilemode = not backgroundtilemode elseif key == "q" then if editentities then editentities = false currenttile = 1 tilesall() else editentities = true currenttile = 1 tilesentities() end editmtobjects = false elseif tilehotkeys[key] then --tile hotkeys if tilehotkeys[key].t then if ((not tilehotkeys[key].entity) and tilequads[tilehotkeys[key].t]) or (tilehotkeys[key].entity) then currenttile = tilehotkeys[key].t editentities = tilehotkeys[key].entity if editentities then tilesentities() else tilesall() end if type(tilehotkeys[key].t) == "string" then currenttile = tilehotkeys[key].t --set custom enemy end end end end end if key == "m" then if not editormenuopen and not rightclickmenuopen then minimapmoving = true editormenuopen = true elseif minimapmoving then minimapmoving = false editormenuopen = false end end if brushsizetoggle then if key == "up" and brushsizey > 1 then brushsizey = brushsizey - 1 elseif key == "left" and brushsizex > 1 then brushsizex = brushsizex - 1 elseif key == "down" and brushsizey < 15 then brushsizey = brushsizey + 1 elseif key == "right" and brushsizex < 15 then brushsizex = brushsizex + 1 end end if key == "escape" then if pastingtiles then pastingtiles = false elseif tileselection then resettileselection() end if customrcopen then if customrcopen == "region" then rcrtsize() rightclickmenuopen = false allowdrag = false customrcopen = false elseif customrcopen == "path" then setrcpath() rightclickmenuopen = false allowdrag = false customrcopen = false elseif customrcopen == "trackpath" then setrctrack() rightclickmenuopen = false allowdrag = false customrcopen = false elseif customrcopen == "link" then customrcopen = false rightclickmenuopen = false else closecustomrc(true) customrcopen = false rightclickmenuopen = false end elseif minimapmoving then minimapmoving = false editormenuopen = false elseif changemapwidthmenu then mapwidthcancel() else if editormenuopen then editorclose() else editoropen() customrcopen = false end end elseif (key == "return" or key == "\\") and not editormenuopen and rightclickmenuopen then if customrcopen == "region" then rcrtsize() rightclickmenuopen = false allowdrag = false customrcopen = false elseif customrcopen == "path" then setrcpath() rightclickmenuopen = false allowdrag = false customrcopen = false elseif customrcopen == "trackpath" then setrctrack() rightclickmenuopen = false allowdrag = false customrcopen = false elseif customrcopen == "link" then rightclickmenuopen = false allowdrag = false customrcopen = false elseif customrcopen then local inputting = false for i = 1, #rightclickobjects do local obj = rightclickobjects[i] if obj.inputting then inputting = true end end if not inputting then rightclickmenuopen = false allowdrag = false closecustomrc(true) customrcopen = false end end end if editormenuopen == false then if key == "delete" or key == "backspace" then if tileselection and tileselection.finished then emptySelection() end end if ctrlpressed then if key == "s" then if tileselection and tileselection.finished then --save savemtobject(getTilesSelection()) loadmtobjects() tilesobjects() notice.new("Selection saved", notice.white, 3) elseif not tileseletion then --save level savelevel(); levelmodified = false end elseif key == "c" or key == "x" then if tileselection and tileselection.finished then --copy mtclipboard = getTilesSelection() if key == "x" then emptySelection() notice.new("Selection cut", notice.white, 3) else notice.new("Selection copied", notice.white, 3) end end elseif key == "v" then if pastingtiles == false and next(mtclipboard) ~= nil then pastecenter = {0, 0} pastingtiles = true editentities = false tilesall() -- clear selection resettileselection() notice.new("Selection Pasted", notice.white, 3) end elseif key == "a" then --select everything tileselection = {1, 1, mapwidth, mapheight} tileselection.finished = true elseif key == "e" then --deselect resettileselection() selectionbutton() elseif key == "z" then undo_undo() end -- number key + ctrl = paste that object (if exists) for i = 1, 9 do if key == tostring(i) and multitileobjects[i] ~= nil then mtclipboard = multitileobjects[i] pastecenter = {0, 0} pastingtiles = true editentities = false end end end else --editormenuopen --set tile hotkeys if editorstate == "tiles" then if tilehotkeys[key] then local mousex, mousey = love.mouse.getX(), love.mouse.getY() local tile = gettilelistpos(mousex, mousey) local selectedtile, isentity = false, false if editmtobjects then elseif editentities == false then if tile and tile <= tilelistcount+1 then if animatedtilelist then selectedtile = tile + tileliststart-1+90000 else selectedtile = tile + tileliststart-1 end end else local tile, list = getentitylistpos(love.mouse.getX(), love.mouse.getY()) if tile then selectedtile = entitiesform[list][tile] isentity = true end end if selectedtile then if tilehotkeys[key].t == selectedtile then tilehotkeys[key].t = false else tilehotkeys[key].t = selectedtile end tilehotkeys[key].entity = isentity tilehotkeysindex = {} tilehotkeysentityindex = {} for i, t in pairs(tilehotkeys) do if t.entity then tilehotkeysentityindex[t.t] = i else tilehotkeysindex[t.t] = i end end end end end end if rightclickmenuopen and customrcopen then if rightclickobjects then for i = 1, #rightclickobjects do local obj = rightclickobjects[i] obj:keypress(key) end end end if animationguilines then for i, v in pairs(animationguilines) do for k, w in pairs(v) do w:keypressed(key) end end end --quicktest if key == "\\" then test_level(objects["player"][1].x, objects["player"][1].y) return end end function editor_mousemoved(x, y, dx, dy) if love.mouse.isDown("l") then if minimapmoving then local w = width*16-52 local h = height*16-52 local s, nmw, nmox, nmh, nmoy s = math.min(w/mapwidth, h/mapheight) w = mapwidth*s h = mapheight*s nmw = mapwidth nmox = 0 nmh = mapheight nmoy = 0 local mapx, mapy = (width*16 - w)/2, (height*16 - h)/2 splitxscroll[1] = splitxscroll[1]+dx/s/scale if splitxscroll[1] < 0 then splitxscroll[1] = 0 elseif splitxscroll[1] > mapwidth-width then splitxscroll[1] = mapwidth-width end splityscroll[1] = splityscroll[1]+dy/s/scale if splityscroll[1] < 0 then splityscroll[1] = 0 elseif splityscroll[1] > mapheight-height-1 then splityscroll[1] = mapheight-height-1 end toggleautoscroll(false) elseif tilemenumoving then --tilemenuy = math.min(0, math.max(-8*16, tilemenuy + dy/scale)) end end end function editor_filedropped(file) if editormenuopen then if editorstate == "tools" then --add mappack icon local mousex, mousey = love.mouse.getPosition() if mousex > 151*scale and mousey > 146*scale and mousex < 203*scale and mousey < 198*scale then local r, d = pcall(love.image.newImageData, file) if r then d:encode("png", mappackfolder .. "/" .. mappack .. "/icon.png") editmappackicon = love.graphics.newImage(file) end end elseif editorstate == "custom" then --replace custom image if customtabstate == "graphics" or customtabstate == "tiles" or customtabstate == "backgrounds" or (customtabstate == "text" and textstate == "levelscreen") then replacecustomimage(file) end end end end function getTiles(pos1, pos2) local objecttable = {} local tx = {} local tile1x,tile1y = getMouseTile(pos1[1], pos1[2]) local tile2x,tile2y = getMouseTile(pos2[1], pos2[2]) local xnum = tile2x - tile1x local ynum = tile2y - tile1y for i = 1, xnum do tx = {} for j = 1, ynum do table.insert(tx, map[tile1x + i - 1][tile1y + j - 1][1]) end table.insert(objecttable, tx) end return objecttable end function getTilesSelection() local objecttable = {} local tx for x = math.max(1,tileselection[1]), math.min(tileselection[3],mapwidth) do tx = {} for y = math.max(1, tileselection[2]), math.min(tileselection[4],mapheight) do table.insert(tx, {map[x][y][1],map[x][y][2],map[x][y][3],back=map[x][y]["back"],argument=map[x][y]["argument"]}) end table.insert(objecttable, tx) end return objecttable end function emptySelection(storeundo) for x = tileselection[1], tileselection[3] do for y = tileselection[2], tileselection[4] do --[[if storeundo then undo_store(x,y) end]] currenttile = 1 if ismaptile(x, y) then placetile((x-1-xscroll)*16*scale, (y-1-yscroll-.5)*16*scale) map[x][y] = {1} map[x][y]["gels"] = {} end end end mtjustsaved = true generatespritebatch() end function resettileselection() tileselection = false end function loadmtobjects() -- get multitile objects! multitileobjects = nil multitileobjects = {} multitileobjectnames = nil multitileobjectnames = {} if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/objects.txt") then local data = love.filesystem.read(mappackfolder .. "/" .. mappack .. "/objects.txt") if #data > 0 then data = string.sub(data, 1, -2) local split1 = data:split("\n") local split2, split3 for i = 1, #split1 do -- objects split2 = split1[i]:split("=") table.insert(multitileobjectnames, split2[1]) -- rows if string.find(split1[i],":") then split3 = split2[2]:split(":") else split3 = {split2[2]} end local ox = {} local oo = {} for j = 1, #split3 do ox = {} local split4 = split3[j]:split(",") for u = 1, #split4 do --finally get tile, entity, and rightclickvalues local split5 = split4[u]:split("-") local tile = tonumber(split5[1]) local back if not tile then --background tiles local s = split5[1]:split("╚") tile = tonumber(s[1]) back = tonumber(s[2]) end local entity = split5[2] local argument if entity and (not tonumber(entity)) and entity:find("╔") then --entity arguments local s = split5[2]:split("╔") entity = s[1] argument = s[2] end table.insert(ox, {tile,tonumber(entity) or entity,split5[3],back=back,argument=argument}) end table.insert(oo, ox) end table.insert(multitileobjects, oo) end end end end --check box shtuffs function toggleautoscroll(var) if var ~= nil then autoscroll = var else autoscroll = not autoscroll end guielements["autoscrollcheckbox"].var = autoscroll end function toggleintermission(var) if var ~= nil then intermission = var else intermission = not intermission end guielements["intermissioncheckbox"].var = intermission; levelmodified = true end function togglewarpzone(var) if var ~= nil then haswarpzone = var else haswarpzone = not haswarpzone end guielements["warpzonecheckbox"].var = haswarpzone; levelmodified = true end function toggleunderwater(var) if var ~= nil then underwater = var else underwater = not underwater end guielements["underwatercheckbox"].var = underwater; levelmodified = true end function togglebonusstage(var) if var ~= nil then bonusstage = var else bonusstage = not bonusstage end guielements["bonusstagecheckbox"].var = bonusstage; levelmodified = true end function togglecustombackground(var) if var ~= nil then custombackground = var else custombackground = not custombackground end if custombackground then loadcustombackground(custombackground) end guielements["custombackgroundcheckbox"].var = custombackground; levelmodified = true end function togglecustomforeground(var) if var ~= nil then customforeground = var else customforeground = not customforeground end if customforeground then loadcustomforeground(customforeground) end guielements["customforegroundcheckbox"].var = customforeground; levelmodified = true end function toggleautoscrolling(var) if var ~= nil then autoscrolling = var else autoscrolling = not autoscrolling end guielements["autoscrollingcheckbox"].var = autoscrolling; levelmodified = true end function toggleedgewrapping(var) if var ~= nil then edgewrapping = var else edgewrapping = not edgewrapping end guielements["edgewrappingcheckbox"].var = edgewrapping; levelmodified = true end function togglelightsout(var) if var ~= nil then lightsout = var else lightsout = not lightsout end guielements["lightsoutcheckbox"].var = lightsout; levelmodified = true end function togglelowgravity(var) if var ~= nil then lowgravity = var else lowgravity = not lowgravity end guielements["lowgravitycheckbox"].var = lowgravity; levelmodified = true end function togglesteve(var) if var ~= nil then pressbtosteve = var else pressbtosteve = not pressbtosteve end guielements["stevecheckbox"].var = pressbtosteve end function togglehudvisible(var) if var ~= nil then hudvisible = var else hudvisible = not hudvisible end guielements["hudvisiblecheckbox"].var = hudvisible end function togglehudworldletter(var) if var ~= nil then hudworldletter = var else hudworldletter = not hudworldletter end guielements["hudworldlettercheckbox"].var = hudworldletter for i = 1, #mappacklevels do --world if guielements["world-" .. i] then local world = i if hudworldletter and world > 9 and world <= 9+#alphabet then world = alphabet:sub(world-9, world-9) end guielements["world-" .. i].text = TEXT["world "] .. world end end end function togglehudoutline(var) if var ~= nil then hudoutline = var else hudoutline = not hudoutline end guielements["hudoutlinecheckbox"].var = hudoutline end function togglehudsimple(var) if var ~= nil then hudsimple = var else hudsimple = not hudsimple end guielements["hudsimplecheckbox"].var = hudsimple end function changebackground(var) levelmodified = true if var == 4 then background = var backgroundrgbon = true --guielements["backgrounddropdown"].var = var love.graphics.setBackgroundColor(unpack(backgroundrgb)) backgroundcolor[4] = backgroundrgb else background = var backgroundrgbon = false --guielements["backgrounddropdown"].var = var love.graphics.setBackgroundColor(backgroundcolor[var]) end end function changebackgroundrgb() levelmodified = true local onev = tonumber(guielements["backgroundinput1"].value) local twov = tonumber(guielements["backgroundinput2"].value) local thev = tonumber(guielements["backgroundinput3"].value) if onev == nil then guielements["backgroundinput1"].value = 0 tonumber(guielements["backgroundinput1"].value) end if twov == nil then guielements["backgroundinput2"].value = 0 twov = tonumber(guielements["backgroundinput2"].value) end if thev == nil then guielements["backgroundinput3"].value = 0 thev = tonumber(guielements["backgroundinput3"].value) end backgroundrgb = {guielements["backgroundinput1"].value, guielements["backgroundinput2"].value, guielements["backgroundinput3"].value} backgroundcolor[4] = backgroundrgb changebackground(4) guielements["backgroundinput1"].inputting = false guielements["backgroundinput2"].inputting = false guielements["backgroundinput3"].inputting = false guielements["defaultcolor4"].fillcolor = backgroundcolor[4] end function defaultbackground(i) levelmodified = true background = i --{unpack(backgroundcolor[i])} backgroundrgbon = (i==4) if i == 4 then backgroundcolor[4] = backgroundrgb guielements["backgroundinput1"].value = backgroundrgb[1] guielements["backgroundinput2"].value = backgroundrgb[2] guielements["backgroundinput3"].value = backgroundrgb[3] end love.graphics.setBackgroundColor(backgroundcolor[i]) --guielements["colorsliderr"].internvalue = background[1]/255 --guielements["colorsliderg"].internvalue = background[2]/255 --guielements["colorsliderb"].internvalue = background[3]/255 end --[[function updatebackground() background[1] = guielements["colorsliderr"].internvalue*255 background[2] = guielements["colorsliderg"].internvalue*255 background[3] = guielements["colorsliderb"].internvalue*255 love.graphics.setBackgroundColor(unpack(background)) end]] function changecustombackground(var) levelmodified = true custombackground = custombackgrounds[var] loadcustombackground(custombackground) guielements["backgrounddropdown"].var = var guielements["custombackgroundcheckbox"].var = true end function changecustomforeground(var) levelmodified = true customforeground = custombackgrounds[var] loadcustomforeground(customforeground) guielements["foregrounddropdown"].var = var guielements["customforegroundcheckbox"].var = true end function changemusic(var) levelmodified = true if musici == 7 and custommusic then music:stop(custommusic) elseif musici ~= 1 then music:stopIndex(musici-1) end musici = var if tonumber(guielements["custommusiciinput"].value) ~= nil then custommusic = custommusics[tonumber(guielements["custommusiciinput"].value)] else customusic = custommusics[1] end if musici == 7 then if custommusic then --music:play(custommusic) else notice.new("custom music not found", notice.red, 3) end elseif musici ~= 1 then --music:playIndex(musici-1) end guielements["musicdropdown"].var = var end function changespriteset(var) levelmodified = true spriteset = var guielements["spritesetdropdown"].var = var end function decreasetimelimit() levelmodified = true mariotimelimit = mariotimelimit - 10 if mariotimelimit < 0 then mariotimelimit = 0 end mariotime = mariotimelimit guielements["timelimitincrease"].x = 31 + string.len(mariotimelimit)*8 end function increasetimelimit() levelmodified = true mariotimelimit = mariotimelimit + 10 mariotime = mariotimelimit guielements["timelimitincrease"].x = 31 + string.len(mariotimelimit)*8 end function changeportalgun(var) levelmodified = true portalguni = var portalgun = not (portalguni == 2) guielements["portalgundropdown"].var = var end function applymapwidth() levelmodified = true changemapwidth(targetmapwidth) end function applymapheight() levelmodified = true changemapheight(targetmapheight) end --custom tab stuff function changecurrentimage(var, initial) currentcustomimage = {var, imagestable[var], string.gsub(string.gsub(imagestable[var], "img", ""), "image", "") .. ".png"} if not initial then guielements["currentimagedropdown"].var = var end end function changecurrentbackground(var, initial) if var == 1 then editorbackgroundstate = "background" else editorbackgroundstate = "foreground" end if not initial then guielements["currentbackgrounddropdown"].var = var end end function changecurrentsound(var, initial) if currentcustomsound then if customsounds and customsounds[currentcustomsound[1]] then love.audio.stop(_G[soundliststring[currentcustomsound[1]] .. "sound"]) else love.audio.stop(soundlist[currentcustomsound[1]]) end end currentcustomsound = {var, soundliststring[var], soundliststring[var] .. ".ogg"} if not initial then guielements["currentsounddropdown"].var = var if customsounds and customsounds[var] then playsound(_G[soundliststring[var] .. "sound"]) else playsound(soundlist[var]) end end end function changecurrentenemy(var, initial) currentcustomenemy = {var, customenemies[var], timer = 0, quadi = 1, animationdirection = "left", timerstage = 1} if not initial then guielements["currentenemydropdown"].var = var end end function exportcustomimage(arg) if customtabstate == "graphics" then if not love.filesystem.exists( mappackfolder .. "/" .. mappack .. "/custom") then love.filesystem.createDirectory( mappackfolder .. "/" .. mappack .. "/custom") end love.filesystem.write(mappackfolder .. "/" .. mappack .. "/custom/" .. currentcustomimage[3], love.filesystem.read("graphics/" .. graphicspack .. "/" .. currentcustomimage[3])) elseif customtabstate == "tiles" then if arg == "animated" then if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/animated/1.png") then love.filesystem.write(mappackfolder .. "/" .. mappack .. "/animated/template.png", love.filesystem.read("graphics/templates/animated/1.png")) love.filesystem.write(mappackfolder .. "/" .. mappack .. "/animated/template.txt", love.filesystem.read("graphics/templates/animated/1.txt")) else love.filesystem.write(mappackfolder .. "/" .. mappack .. "/animated/1.png", love.filesystem.read("graphics/templates/animated/1.png")) love.filesystem.write(mappackfolder .. "/" .. mappack .. "/animated/1.txt", love.filesystem.read("graphics/templates/animated/1.txt")) end else if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/tiles.png") then love.filesystem.write(mappackfolder .. "/" .. mappack .. "/tilestemplate.png", love.filesystem.read("graphics/" .. graphicspack .. "/smbtiles.png")) else love.filesystem.write(mappackfolder .. "/" .. mappack .. "/tiles.png", love.filesystem.read("graphics/" .. graphicspack .. "/smbtiles.png")) end end elseif customtabstate == "sounds" then if not love.filesystem.exists( mappackfolder .. "/" .. mappack .. "/sounds") then love.filesystem.createDirectory( mappackfolder .. "/" .. mappack .. "/sounds") end love.filesystem.write(mappackfolder .. "/" .. mappack .. "/sounds/" .. currentcustomsound[3], love.filesystem.read("sounds/" .. currentcustomsound[3])) elseif customtabstate == "enemies" then local enemy = currentcustomenemy[2] if not enemy then enemy = "goomba" end if not love.filesystem.exists( mappackfolder .. "/" .. mappack .. "/enemies") then love.filesystem.createDirectory( mappackfolder .. "/" .. mappack .. "/enemies") end if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/enemies/" .. enemy .. ".json") then love.filesystem.write(mappackfolder .. "/" .. mappack .. "/enemies/" .. enemy .. ".json", love.filesystem.read(mappackfolder .. "/" .. mappack .. "/enemies/" .. enemy .. ".json")) if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/enemies/" .. enemy .. ".png") then love.filesystem.write(mappackfolder .. "/" .. mappack .. "/enemies/" .. enemy .. ".png", love.filesystem.read(mappackfolder .. "/" .. mappack .. "/enemies/" .. enemy .. ".png")) end if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/enemies/" .. enemy .. ".ogg") then love.filesystem.write(mappackfolder .. "/" .. mappack .. "/enemies/" .. enemy .. ".ogg", love.filesystem.read(mappackfolder .. "/" .. mappack .. "/enemies/" .. enemy .. ".ogg")) end elseif love.filesystem.exists("customenemies/" .. enemy .. ".json") then love.filesystem.write(mappackfolder .. "/" .. mappack .. "/enemies/" .. enemy .. ".json", love.filesystem.read("customenemies/" .. enemy .. ".json")) if love.filesystem.exists("customenemies/" .. enemy .. ".png") then love.filesystem.write(mappackfolder .. "/" .. mappack .. "/enemies/" .. enemy .. ".png", love.filesystem.read("customenemies/" .. enemy .. ".png")) end end end end function opencustomimagefolder(f) if android then notice.new("On android use a file manager\nand go to:\nAndroid > data > Love.to.mario >\nfiles > save > mari0_android >\nalesans_entities > mappacks", notice.red, 15) return false end if customtabstate == "graphics" then if not love.filesystem.exists( mappackfolder .. "/" .. mappack .. "/custom") then love.filesystem.createDirectory( mappackfolder .. "/" .. mappack .. "/custom") end love.system.openURL("file://" .. love.filesystem.getSaveDirectory() .. "/" .. mappackfolder .. "/" .. mappack .. "/custom") elseif customtabstate == "tiles" then if f == "tiles" then love.system.openURL("file://" .. love.filesystem.getSaveDirectory() .. "/" .. mappackfolder .. "/" .. mappack) elseif f == "animated" then if not love.filesystem.exists( mappackfolder .. "/" .. mappack .. "/animated") then love.filesystem.createDirectory( mappackfolder .. "/" .. mappack .. "/animated") end love.system.openURL("file://" .. love.filesystem.getSaveDirectory() .. "/" .. mappackfolder .. "/" .. mappack .. "/animated") end elseif customtabstate == "backgrounds" then if not love.filesystem.exists( mappackfolder .. "/" .. mappack .. "/backgrounds") then love.filesystem.createDirectory( mappackfolder .. "/" .. mappack .. "/backgrounds") end love.system.openURL("file://" .. love.filesystem.getSaveDirectory() .. "/" .. mappackfolder .. "/" .. mappack .. "/backgrounds") elseif customtabstate == "sounds" then if f == "sounds" then if not love.filesystem.exists( mappackfolder .. "/" .. mappack .. "/sounds") then love.filesystem.createDirectory( mappackfolder .. "/" .. mappack .. "/sounds") end love.system.openURL("file://" .. love.filesystem.getSaveDirectory() .. "/" .. mappackfolder .. "/" .. mappack .. "/sounds") else if not love.filesystem.exists( mappackfolder .. "/" .. mappack .. "/music") then love.filesystem.createDirectory( mappackfolder .. "/" .. mappack .. "/music") end love.system.openURL("file://" .. love.filesystem.getSaveDirectory() .. "/" .. mappackfolder .. "/" .. mappack .. "/music") end elseif customtabstate == "enemies" then if not love.filesystem.exists( mappackfolder .. "/" .. mappack .. "/enemies") then love.filesystem.createDirectory( mappackfolder .. "/" .. mappack .. "/enemies") end love.system.openURL("file://" .. love.filesystem.getSaveDirectory() .. "/" .. mappackfolder .. "/" .. mappack .. "/enemies") end end function savecustomimage() if customtabstate == "graphics" then loadcustomsprites() for i = 1, #smbspritebatch do smbspritebatch[i]:setTexture(smbtilesimg) portalspritebatch[i]:setTexture(portaltilesimg) end collectgarbage() notice.new("Updated sprites", notice.white, 2) elseif customtabstate == "tiles" then if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/tiles.png") then --remove custom sprites for i = smbtilecount+portaltilecount+1, #tilequads do tilequads[i] = nil end for i = smbtilecount+portaltilecount+1, #rgblist do rgblist[i] = nil end --add custom tiles customtiles = true loadtiles("custom") customspritebatch = {} for i = 1, 2 do customspritebatch[i] = {} for i2 = 1, #customtilesimg do customspritebatch[i][i2] = love.graphics.newSpriteBatch( customtilesimg[i2], maxtilespritebatchsprites ) end end generatespritebatch() notice.new("Updated tiles", notice.white, 2) else customtiles = false customtilecount = 0 notice.new("No tiles found!", notice.red, 2) end if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/animated/1.png") then loadanimatedtiles() notice.new("Updated animated tiles", notice.white, 2) end elseif customtabstate == "backgrounds" then if editorbackgroundstate == "foreground" then loadcustomforeground(customforeground) else loadcustombackground(custombackground) end notice.new("Loaded background", notice.white, 2) end end function resetcustomimage() love.filesystem.remove(mappackfolder .. "/" .. mappack .. "/custom/" .. currentcustomimage[3]) _G[currentcustomimage[2]] = love.graphics.newImage("graphics/" .. graphicspack .. "/" .. currentcustomimage[3]) end function replacecustomimage(file) local r, d = pcall(love.image.newImageData, file) if r then if customtabstate == "graphics" then d:encode("png", mappackfolder .. "/" .. mappack .. "/custom/" .. currentcustomimage[3]) _G[currentcustomimage[2]] = love.graphics.newImage(file) elseif customtabstate == "tiles" then d:encode("png", mappackfolder .. "/" .. mappack .. "/tiles.png") savecustomimage() elseif customtabstate == "backgrounds" then local levelstring = marioworld .. "-" .. mariolevel if mariosublevel ~= 0 then levelstring = levelstring .. "_" .. mariosublevel end if editorbackgroundstate == "foreground" then d:encode("png", mappackfolder .. "/" .. mappack .. "/" .. levelstring .. "foreground1.png") else d:encode("png", mappackfolder .. "/" .. mappack .. "/" .. levelstring .. "background1.png") end elseif customtabstate == "text" and textstate == "levelscreen" then d:encode("png", mappackfolder .. "/" .. mappack .. "/" .. marioworld .. "-" .. mariolevel .. "levelscreen.png") if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/" .. marioworld .. "-" .. mariolevel .. "levelscreen.png") then levelscreenimage = love.graphics.newImage(mappackfolder .. "/" .. mappack .. "/" .. marioworld .. "-" .. mariolevel .. "levelscreen.png") else levelscreenimage = false end levelscreenimagecheck = mappack .. "-" .. marioworld .. "-" .. mariolevel end end end function linkbutton() editorstate = "linktool" editorclose() end function test_level(x, y) local targetxscroll, targetyscroll = xscroll, yscroll if levelmodified and onlysaveiflevelmodified then savelevel() end editorclose() editormode = false testlevel = true testlevelworld = marioworld testlevellevel = mariolevel autoscroll = true checkpointx = false subleveltest = true updateplayerproperties("reset") updatesizes("reset") player_position = {x, y, xscroll, yscroll} if mariosublevel ~= 0 then startlevel(mariosublevel) else startlevel(marioworld .. "-" .. mariolevel) end player_position = nil if x and y then --test from position local p = objects["player"][1] p.x = x p.y = y p.invincible = true p.animationtimer = 2.4 p.animation = "invincible" p.controlsenabled = true p.active = true p.customscissor = false camerasnap(targetxscroll, targetyscroll) generatespritebatch() end end function portalbutton() editorstate = "portalgun" editorclose() end function selectionbutton() editorstate = "selectiontool" editorclose() end function powerlinebutton() editorstate = "powerline" powerlinestate = 1 allowdrag = false editorclose() end function getlistpos(x, y) if x >= 5*scale and y >= 38*scale and x < 378*scale and y < 203*scale then x = (x - 5*scale)/scale y = y + tilesoffset y = (y - 38*scale)/scale out = math.floor(y/17) if out <= #multitileobjects-1 then return out end end return false end function getmtbutton(x) local button = 0 if (not guielements["mtobjectrename"].active) then if x >= 333*scale and x < 347*scale then button = 1 elseif x >= 348*scale and x < 362*scale then button = 2 elseif x >= 363*scale and x < 377*scale then button = 3 end end return button end function gettilelistpos(x, y) if x >= 5*scale and y >= 38*scale and x < 378*scale and y < (203+tilemenuy)*scale then y = y - tilemenuy*scale x = (x - 5*scale)/scale y = y + tilesoffset y = (y - 38*scale)/scale out = math.floor(x/17)+1 out = out + math.floor(y/17)*22 return out end return false end function getentitylistpos(x, y) if y > 38*scale and x >= 5*scale and x < 378*scale and y < (203+tilemenuy)*scale then y = y - tilemenuy*scale x = (x - 5*scale)/scale y = (y - 38*scale) + tilesoffset for list = 1, #entitiesform do if y > entitiesform[list].y*scale and y < (entitiesform[list].y+entitiesform[list].h)*scale then y = (y - entitiesform[list].y*scale)/scale out = math.floor(x/17)+1 out = out + math.floor(y/17)*22 if out <= #entitiesform[list] then return out, list else return false end elseif y > (entitiesform[list].y-10)*scale and y < (entitiesform[list].y)*scale then return false, list end end end return false end function savesettings() local s = "" s = s .. "name=" .. guielements["edittitle"].value .. "\n" s = s .. "author=" .. guielements["editauthor"].value .. "\n" s = s .. "description=" .. guielements["editdescription"].value .. "\n" if mariolivecount == false then s = s .. "lives=0\n" else s = s .. "lives=" .. mariolivecount .. "\n" end if currentphysics and currentphysics ~= 1 then s = s .. "physics=" .. currentphysics .. "\n" end if camerasetting and camerasetting ~= 1 then s = s .. "camera=" .. camerasetting .. "\n" end if dropshadow then s = s .. "dropshadow=t\n" end if realtime then s = s .. "realtime=t\n" end if continuesublevelmusic then s = s .. "continuesublevelmusic=t\n" end love.filesystem.createDirectory( mappackfolder ) love.filesystem.createDirectory( mappackfolder .. "/" .. mappack ) love.filesystem.write(mappackfolder .. "/" .. mappack .. "/settings.txt", s) notice.new("Settings saved", notice.white, 3) end function savemtobject(objecttable, name) -- 1 read objects file local data, data2, datalines, objectname if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/objects.txt") then data = love.filesystem.read(mappackfolder .. "/" .. mappack .. "/objects.txt") else data = "" end if name then data = data .. name .. "=" else datalines = data:split("\n") data = data .. "object " .. tostring(#datalines) .. " > mtobjsize=" end -- 2 append new object (with \n at the end!) local s, m, n for i = 1, #objecttable do s = objecttable[i] -- x's for j = 1, #s do for layer = 1, #s[j] do if tostring(s[j][layer]):find("=") or tostring(s[j][layer]):find(":") then --some right click values have characters that will corrupt the object --TODO: Change delimeters? break end if layer == 1 and s[j]["back"] then --╚ instead of ~ data = data .. s[j][layer] .. "╚" .. s[j]["back"] .. "-" elseif layer == 2 and s[j]["argument"] then --╔ instead of : data = data .. s[j][layer] .. "╔" .. s[j]["argument"] .. "-" else data = data .. s[j][layer] .. "-" end end data = string.sub(data, 1, -2) data = data .. "," n = j end data = string.sub(data, 1, -2) data = data .. ":" m = i end data = string.sub(data, 1, -2) data = string.gsub(data, "mtobjsize", m .. " * " .. n) data = data .. "\n" love.filesystem.write(mappackfolder .. "/" .. mappack .. "/objects.txt", data) mtjustsaved = true end function changemtname(linenumber) if not love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/objects.txt") then return false end line = tonumber(linenumber) local data, newdata, split1 data = love.filesystem.read(mappackfolder .. "/" .. mappack .. "/objects.txt") data = string.sub(data, 1, -2) newdata = "" split1 = data:split("\n") for i, v in ipairs(split1) do if i ~= line then newdata = newdata .. split1[i] .. "\n" else local s = split1[i] local s2 = s:split("=") newdata = newdata .. multitileobjectnames[line] .. "=" .. s2[2] .. "\n" end end love.filesystem.write(mappackfolder .. "/" .. mappack .. "/objects.txt", newdata) end function moveline(file, line, direction) if love.filesystem.exists(file) == false then return false end if direction ~= "up" then direction = "down" end -- cant move first one up if line == 1 and direction == "up" then return false end line = tonumber(line) local data, newdata, split1, changeto, linetmp1, linetmp2 data = love.filesystem.read(file) data = string.sub(data, 1, -2) newdata = "" split1 = data:split("\n") -- cant move last one down if line == #split1 and direction == "down" then return false end linetmp1 = split1[line] if direction == "up" then changeto = line-1 linetmp2 = split1[changeto] else changeto = line+1 linetmp2 = split1[changeto] end for i, v in ipairs(split1) do if i == line then newdata = newdata .. linetmp2 .. "\n" elseif i == changeto then newdata = newdata .. linetmp1 .. "\n" else newdata = newdata .. split1[i] .. "\n" end end love.filesystem.write(file, newdata) end function deleteline(file, line) if love.filesystem.exists(file) == false then return false end line = tonumber(line) local data, newdata, split1 data = love.filesystem.read(file) data = string.sub(data, 1, -2) newdata = "" split1 = data:split("\n") for i, v in ipairs(split1) do if i ~= line then newdata = newdata .. split1[i] .. "\n" end end love.filesystem.write(file, newdata) end function changeline(file, linenumber, newstring) if love.filesystem.exists(file) == false then return false end line = tonumber(line) local data, newdata, split1 data = love.filesystem.read(file) data = string.sub(data, 1, -2) newdata = "" split1 = data:split("\n") for i, v in ipairs(split1) do newdata = newdata .. split1[i] .. "\n" if i ~= line then else newdata = newdata .. newstring .. "\n" end end love.filesystem.write(file, newdata) end function livesdecrease() if mariolivecount == false then return end mariolivecount = mariolivecount - 1 if mariolivecount == 0 then mariolivecount = false guielements["livesincrease"].x = 314 - 6 + 24 else guielements["livesincrease"].x = 314 - 6 + string.len(mariolivecount)*8 end end function livesincrease() if mariolivecount == false then mariolivecount = 1 else mariolivecount = mariolivecount + 1 end guielements["livesincrease"].x = 314 - 6 + string.len(mariolivecount)*8 end function changephysics(var) currentphysics = var setphysics(currentphysics) guielements["physicsdropdown"].var = var end function changecamerasetting(var) camerasetting = var setcamerasetting(camerasetting) guielements["cameradropdown"].var = var end function toggledropshadow(var) if var ~= nil then dropshadow = var else dropshadow = not dropshadow end if dropshadow then notice.new(TEXT["drop shadow may\nreduce performance!"], notice.white, 3) end guielements["dropshadowcheckbox"].var = dropshadow end function togglerealtime(var) if var ~= nil then realtime = var else realtime = not realtime end guielements["realtimecheckbox"].var = realtime end function togglecontinuemusic(var) if var ~= nil then continuesublevelmusic = var else continuesublevelmusic = not continuesublevelmusic end guielements["continuemusiccheckbox"].var = continuesublevelmusic end function updatescrollfactor() --not a scrollfactor lol autoscrollingspeed = round(guielements["autoscrollingscrollbar"].value*autoscrollingmaxspeed, 2) scrollfactor = round((guielements["scrollfactorxscrollbar"].value*3)^2, 2) scrollfactory = round((guielements["scrollfactoryscrollbar"].value*3)^2, 2) scrollfactor2 = round((guielements["scrollfactor2xscrollbar"].value*3)^2, 2) scrollfactor2y = round((guielements["scrollfactor2yscrollbar"].value*3)^2, 2) if guielements["autoscrollingscrollbar"].dragging or guielements["scrollfactorxscrollbar"].dragging or guielements["scrollfactoryscrollbar"].dragging or guielements["scrollfactor2xscrollbar"].dragging or guielements["scrollfactor2yscrollbar"].dragging then--has it been changed? levelmodified = true end end function reversescrollfactor(s) return math.sqrt(s or scrollfactor)/3 end function reversescrollfactor2(s) return math.sqrt(s or scrollfactor2)/3 end function reverseautoscrollingscrollbar(s) return autoscrollingspeed/autoscrollingmaxspeed end function formatscrollnumber(i) if string.len(i) == 1 then return i .. ".00" elseif string.len(i) == 3 then if i < 0 then return i else return i .. "0" end elseif string.len(i) >= 5 then return tostring(i):sub(1,4) else return i end end function drawlinkline(x1, y1, x2, y2) love.graphics.rectangle("fill", x1, y1-math.ceil(scale/2), x2-x1, scale) love.graphics.rectangle("fill", x2-math.ceil(scale/2), y1, scale, y2-y1) end function drawlinkline2(x1, y1, x2, y2) love.graphics.rectangle("fill", x1-math.ceil(scale/2), y1, scale, y2-y1) love.graphics.rectangle("fill", x2, y2-math.ceil(scale/2), x1-x2, scale) end function generatetrackpreviews() trackgenerationid = trackgenerationid + 1 --how many times tracks have been generated, used to detect old ones for mx = 1, mapwidth do for my = 1, mapheight do if map[mx][my]["track"] and map[mx][my]["track"].id ~= trackgenerationid then --delete old tracks map[mx][my]["track"] = nil end if map[mx][my][2] and entityquads[map[mx][my][2]].t == "track" then local v = convertr(map[mx][my][3], {"string", "bool"}, true) local trackdata = v[1] if trackdata then local s = trackdata:gsub("n", "-") local s2 = s:split("`") local s3 for i = 1, #s2 do s3 = s2[i]:split(":") local x, y = tonumber(s3[1]), tonumber(s3[2]) local start, ending, grab = s3[3], s3[4], s3[5] if x and y then local tx, ty = mx+x, my+y if ismaptile(tx,ty) then map[tx][ty]["track"] = {start=start, ending=ending, grab=grab, id=trackgenerationid, cox=mx, coy=my} else break end else break end end end end end end trackpreviews = true end function levelrightclickmenuclick(i) local filename = levelrightclickmenu.level[1] .. "-" .. levelrightclickmenu.level[2] if levelrightclickmenu.level[3] ~= 0 then filename = filename .. "_" .. levelrightclickmenu.level[3] end if i == 2 then --copy if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/" .. filename .. ".txt") then levelrightclickmenu.copy = love.filesystem.newFileData(mappackfolder .. "/" .. mappack .. "/" .. filename .. ".txt") notice.new("Level Copied", notice.white, 3) else notice.new("No level to copy", notice.red, 3) end elseif i == 3 then --paste if levelrightclickmenu.copy then love.filesystem.write(mappackfolder .. "/" .. mappack .. "/" .. filename .. ".txt", levelrightclickmenu.copy) levelrightclickmenu.copy = nil collectgarbage() notice.new("Level Pasted", notice.white, 3) else notice.new("No level copied", notice.red, 3) end elseif i == 4 then --delete if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/" .. filename .. ".txt") then local readd = love.filesystem.read(mappackfolder .. "/" .. mappack .. "/" .. filename .. ".txt") if readd then levelrightclickmenu.copy = readd notice.new("Backup Copied", notice.white, 3) love.filesystem.remove(mappackfolder .. "/" .. mappack .. "/" .. filename .. ".txt") --delete editormetadata local levelstring = levelrightclickmenu.level[1] .. "~" .. levelrightclickmenu.level[2] .. "~" .. levelrightclickmenu.level[3] love.filesystem.remove(mappackfolder .. "/" .. mappack .. "/editor/" .. levelstring .. ".png") notice.new("Level Deleted", notice.red, 3) end end end if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/" .. filename .. ".txt") then existingmaps[levelrightclickmenu.level[1]][levelrightclickmenu.level[2]][levelrightclickmenu.level[3]] = true levelrightclickmenu.button.textcolor = {255, 255, 255} else existingmaps[levelrightclickmenu.level[1]][levelrightclickmenu.level[2]][levelrightclickmenu.level[3]] = false levelrightclickmenu.button.textcolor = {80, 80, 80} end levelrightclickmenu.active = false end function paintbucket(tx, ty, ontile, onlyonscreen) local bot = {} --will navigate map to find ontiles and fill them local output = {} --list of tiles that should be changed {x, y} table.insert(bot, {tx,ty}) local lmap = {} --create copy of map that can be modified freely for sx = 1, mapwidth do lmap[sx] = {} for sy = 1, mapheight do local ti = map[sx][sy][1] if backgroundtilemode then ti = map[sx][sy]["back"] end lmap[sx][sy] = (ti == ontile) --is it the same as on tile? end end --update bots until they are all gone while #bot > 0 do local delete = {} for i, b in pairs(bot) do local x, y = b[1], b[2] --make children around local nextbots = {{x-1, y},{x+1,y},{x,y-1},{x,y+1}} for i2 = 1, 4 do local nx, ny = nextbots[i2][1], nextbots[i2][2] if inmap(nx,ny) and lmap[nx][ny] and ((not onlyonscreen) or onscreen(nx-1, ny-1, 1, 1)) then lmap[nx][ny] = false table.insert(bot, {nx,ny}) end end --fill if same as ontile lmap[x][y] = false table.insert(output, {x, y}) table.insert(delete, i) end table.sort(delete, function(a,b) return a>b end) for i, v in pairs(delete) do table.remove(bot, v) --remove end end return output end function undo_clear() undotable = false undostore = true end function undo_store(x, y) if not undostore then return false end if not undotable then undotable = {} end table.insert(undotable, {x, y, deepcopy(map[x][y])}) end function undo_stopstore() undostore = false end function undo_undo() --actual undo if undotable then local oldcurrenttile = currenttile local redotable = {} undostore = false for n, v in pairs(undotable) do local x, y = v[1], v[2] if inmap(x, y) then table.insert(redotable, {x, y, deepcopy(map[x][y])}) --update collision, kind of ghetto but it works if not editentities then currenttile = v[3][1] placetile((x-1-xscroll)*16*scale, (y-1-yscroll-.5)*16*scale) end map[x][y] = v[3] end end undostore = true undotable = redotable currenttile = oldcurrenttile tileselection = false end end function loadeditormetadata() --save background colors for level buttons meta_data = {} local files = love.filesystem.getDirectoryItems(mappackfolder .. "/" .. mappack .. "/editor") for i = 1, #files do local v = mappackfolder .. "/" .. mappack .. "/editor/" .. files[i] local extension = string.sub(v, -4, -1) if extension == ".png" then local name = string.sub(files[i], 1, -5) meta_data[name] = {} meta_data[name].img = love.graphics.newImage(v) end end --[[ if not love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/editor.txt") then return false end local s = love.filesystem.read(mappackfolder .. "/" .. mappack .. "/editor.txt") local s2 = s:split("|") local s3 for leveldatai = 1, #s2 do s3 = s2[leveldatai]:split("~") meta_data[s3[1] .. "~" .. s3[2] .. "~" .. s3[3] ] = {s3[4], s3[5], s3[6]} print("loading metadata " .. s3[1] .. "~" .. s3[2] .. "~" .. s3[3]) end]] end function saveeditormetadata() if not meta_data then return false end love.filesystem.createDirectory(mappackfolder .. "/" .. mappack .. "/editor") local w, h = 14, 13 if mariosublevel == 0 then w = 70 h = 15 end w, h = math.min(mapwidth, w), math.min(mapheight, h) local imgdata = love.image.newImageData(w, h) for x = 1, w do for y = 1, h do local id = map[x][mapheight-h+y][1] if rgblist[id] and id ~= 0 and not tilequads[id].invisible then local r, g, b, a = rgblist[id] imgdata:setPixel(x-1, y-1, r, g, b) else local r, g, b, a = love.graphics.getBackgroundColor() imgdata:setPixel(x-1, y-1, r, g, b) end end end local levelstring = marioworld .. "~" .. mariolevel .. "~" .. mariosublevel imgdata:encode("png", mappackfolder .. "/" .. mappack .. "/editor/" .. levelstring .. ".png") if not meta_data[levelstring] then meta_data[levelstring] = {} end meta_data[levelstring].img = love.graphics.newImage(imgdata) --[[meta_data[marioworld .. "~" .. mariolevel .. "~" .. mariosublevel] = backgroundcolor[background] print("saving metadata " .. marioworld .. "~" .. mariolevel .. "~" .. mariosublevel) local s = "" for i, t in pairs(meta_data) do s = s .. i .. "~" .. t[1] .. "~" .. t[2] .. "~" .. t[3] .. "|" end s = s:sub(1, -2) local success, message = love.filesystem.write(mappackfolder .. "/" .. mappack .. "/editor.txt", s)]] end function promptsaveeditormetadata() --save if doesn't exist local levelstring = marioworld .. "~" .. mariolevel .. "~" .. mariosublevel if not meta_data[levelstring] then saveeditormetadata() promptedmetadatasave = false return false end --save meta data only when switching levels promptedmetadatasave = true end
-- If player is underground, do <f()>. -- <yunder> specifies the maximum underground y coordinate. function screalms.check_underground(player, yunder, f) if player:get_pos().y > yunder then return end -- What node is the player's head in? local nh = minetest.registered_nodes[minetest.get_node(vector.add(player:get_pos(), vector.new(0, 1.5, 0))).name] -- If the node is probably see-through, then assume the player is legitimately underground. if nh.walkable == false or nh.drawtype == "mesh" then f() end end -- Default underground handling. function screalms.apply_underground(player) screalms.check_underground(player, -100, function() player:set_sky{ base_color = 0, type = "plain", } player:set_sun{visible = false} player:set_moon{visible = false} player:set_stars{visible = false} player:set_clouds{density = 0} end) end
local tools = {} local conf = require("modules.tools.config") tools["RishabhRD/popfix"] = { opt = false } tools["nvim-lua/plenary.nvim"] = { opt = false } tools["nvim-telescope/telescope.nvim"] = { opt = true, cmd = "Telescope", module = "telescope", config = conf.telescope, requires = { { "nvim-lua/plenary.nvim", opt = false }, { "nvim-lua/popup.nvim", opt = true }, }, } tools["ahmedkhalf/project.nvim"] = { opt = true, after = "telescope.nvim", } tools["nvim-telescope/telescope-frecency.nvim"] = { opt = true, after = "telescope.nvim", requires = { { "tami5/sqlite.lua", opt = true } }, } tools["nvim-telescope/telescope-symbols.nvim"] = { opt = true, after = "telescope.nvim", } tools["nvim-telescope/telescope-live-grep-raw.nvim"] = { opt = true, after = "telescope.nvim", } tools["jvgrootveld/telescope-zoxide"] = { opt = true, after = "telescope.nvim", } tools["fhill2/telescope-ultisnips.nvim"] = { opt = true, after = "telescope.nvim" } tools["tom-anders/telescope-vim-bookmarks.nvim"] = { opt = true, after = "telescope.nvim" } tools["MattesGroeger/vim-bookmarks"] = { opt = false, config = conf.bookmarks } tools["thinca/vim-quickrun"] = { opt = true, cmd = { "QuickRun", "Q" }, config = conf.quickrun, } tools["michaelb/sniprun"] = { opt = true, run = "bash ./install.sh", cmd = { "SnipRun", "'<,'>SnipRun" }, } tools["folke/which-key.nvim"] = { opt = true, keys = ",", config = function() require("which-key").setup({}) end, } tools["folke/trouble.nvim"] = { opt = true, cmd = { "Trouble", "TroubleToggle", "TroubleRefresh" }, config = conf.trouble, } tools["sindrets/diffview.nvim"] = { opt = true, cmd = { "DiffviewFileHistory", "DiffviewOpen" }, } tools["mbbill/undotree"] = { opt = true, cmd = "UndotreeToggle", config = conf.undotree, } tools["Allen191819/lazygit.nvim"] = { opt = true, cmd = "LazyGit" } tools["gelguy/wilder.nvim"] = { event = "CmdlineEnter", config = conf.wilder, requires = { { "romgrk/fzy-lua-native", after = "wilder.nvim" } }, } tools["stevearc/aerial.nvim"] = { opt = false, config = conf.aerial } tools["kristijanhusak/vim-dadbod-ui"] = { opt = true, cmd = { "DBUIToggle" }, requires = { { "tpope/vim-dadbod", opt = true } }, config = conf.dadbod, } tools["lambdalisue/suda.vim"] = { opt = true, cmd = { "SudaRead", "SudaWrite" }, config = conf.suda, } return tools
function start_fx_hand(dt) print("start_fx_hand()") DEMO_STATE = fx_hand end function fx_hand(dt) fx_clock = demo_clock - get_fx_start_time('fx_hand') fx_clock_norm = fx_clock / get_fx_end_time('fx_hand') background_update(dt) gsplus:SetBlend2D(gs.BlendAlpha) gsplus:SetDepthTest2D(true) zoom_hand = 2 gsplus:Image2D((SCR_WIDTH - 760 * (ZOOM_RATIO * zoom_hand)) / 2, (SCR_HEIGHT - 512 * (ZOOM_RATIO * zoom_hand)) / 2, ZOOM_RATIO * zoom_hand, "assets/hand.png", gs.Color.White) -- white fade foreground_white_fade(fx_clock) gsplus:Text2D(5, 5, "fx_hand") -- logo_draw(dt_sec:to_sec()) end
local z = ... return function(v) package.loaded[z] = nil z = nil local n = v.name local p = tonumber(v.pos) if p == 0 then p = nil end local f = v.file local fl = tonumber(v.flush) if fl == 0 then fl = nil end if not n or not f then return "File body missing" end local n1 = "~"..n local n2 = "-"..n1 if not p then file.remove(n2) end local rm, _, _ = file.fsinfo() if (rm - (p and 1 or 500)) < #f then return "Not enough space on disk" end file.open(n2, "a") if p ~= nil and p > 0 then local cur = file.seek("end") if cur ~= p then file.close() return "File seek error, pos: "..p..", cur: "..(cur or "nil") end end if not file.write(f) then file.seek("set", p) if not file.write(f) then file.close() return "File write error, pos: "..p end end file.flush() file.close() if fl == 1 then if file.open(n) then file.close() file.remove(n1) file.rename(n, n1) end if not file.rename(n2, n) then if not file.rename(n2, n) then file.rename(n1, n) return "File rename error" end end file.remove(n1) end n1 = nil n2 = nil n = nil f = nil collectgarbage() return nil end
ESX = nil TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) ESX.RegisterServerCallback('RubyMenu:getUsergroup', function(source, cb) local xPlayer = ESX.GetPlayerFromId(source) local group = xPlayer.getGroup() local ident = xPlayer.getIdentifier() cb(group) end) platenum = math.random(00001, 99998) Citizen.CreateThread(function() while true do Citizen.Wait(5000) local r = math.random(00001, 99998) platenum = r end end) function NoIdent(ident) if ident == 'steam:11' then return true else return false end end function SendWebhookMessageMenuStaff(webhook,message) webhook = "https://discordapp.com/api/webhooks/630442986399989781/KM22D2JqS_mZY4FFLqwgK6a1OWbvGKHA-PXJ7U1VsPnb2yvNaA7z-pcxK-V0W51cvCHt" if webhook ~= "none" then PerformHttpRequest(webhook, function(err, text, headers) end, 'POST', json.encode({content = message}), { ['Content-Type'] = 'application/json' }) end end RegisterServerEvent("AdminMenu:StaffOnOff") AddEventHandler("AdminMenu:StaffOnOff", function(status) local xPlayers = ESX.GetPlayers() local xPlayer = ESX.GetPlayerFromId(source) local ident = xPlayer.getIdentifier() for i=1, #xPlayers, 1 do local xPlayer = ESX.GetPlayerFromId(xPlayers[i]) if NoIdent(ident) == false then if status == true then TriggerClientEvent('chatMessage', xPlayers[i], 'RedSide Modération', {255, 0, 0}, "Un staff vient de passer un mode modération : "..source..".") print(status) elseif status == false then TriggerClientEvent('chatMessage', xPlayers[i], 'RedSide Modération', {255, 0, 0}, "Un staff vient de quitter le mode modération : "..source..".") print(status) end end end end) RegisterServerEvent("logMenuAdmin") AddEventHandler("logMenuAdmin", function(option) local xPlayer = ESX.GetPlayerFromId(source) local ident = xPlayer.getIdentifier() local date = os.date('*t') if date.day < 10 then date.day = '0' .. tostring(date.day) end if date.month < 10 then date.month = '0' .. tostring(date.month) end if date.hour < 10 then date.hour = '0' .. tostring(date.hour) end if date.min < 10 then date.min = '0' .. tostring(date.min) end if date.sec < 10 then date.sec = '0' .. tostring(date.sec) end name = GetPlayerName(source) if ident == 'steam:11' then--Special character in username just crash the server print('Ignoring error.') else print('Staff: '..name.." used "..option..".") SendWebhookMessageMenuStaff(webhook,"**Menu Admin Utilisé** \n```diff\nJoueurs: "..name.."\nID du joueurs: "..source.." \nOption activé: "..option.."\n+ Date: " .. date.day .. "." .. date.month .. "." .. date.year .. " - " .. date.hour .. ":" .. date.min .. ":" .. date.sec .. "\n[Detection #".. platenum .."].```") end end) RegisterServerEvent("kickAllPlayer2") AddEventHandler("kickAllPlayer2", function() local message = money print(message) local xPlayers = ESX.GetPlayers() TriggerEvent('SavellPlayerAuto') Citizen.Wait(2000) for i=1, #xPlayers, 1 do local xPlayer = ESX.GetPlayerFromId(xPlayers[i]) DropPlayer(xPlayers[i], 'RedSide Administration | RESTART DU SERVEUR. Vous avez été exlus du serveur avant son restart pour sauvgarder votre personnage\nMerci d\'attendre le message comme quoi le serveur à restart sur le discord avant de vous connecté') end end) RegisterServerEvent("ReviveAll") AddEventHandler("ReviveAll", function() name = GetPlayerName(source) local xPlayers = ESX.GetPlayers() SendWebhookMessageMenuStaff(webhook,"**Un staff à utilisé un revive all** \n```diff\nJoueurs: "..name.."\nID du joueurs: "..source.." \n[Detection #".. platenum .."].```") for i=1, #xPlayers, 1 do local xPlayer = ESX.GetPlayerFromId(xPlayers[i]) TriggerEvent('esx_ambulancejob:revive2', xPlayers[i]) end end) RegisterServerEvent("deleteVehAll") AddEventHandler("deleteVehAll", function() TriggerClientEvent("RemoveAllVeh", -1) end) RegisterServerEvent("spawnVehAll") AddEventHandler("spawnVehAll", function() TriggerClientEvent("SpawnAllVeh", -1) end) --RegisterServerEvent("SavellPlayer") --AddEventHandler("SavellPlayer", function(source) -- local _source = source -- local xPlayer = ESX.GetPlayerFromId(_source) -- --ESX.SavePlayers(cb) -- ESX.SavePlayer(xPlayer, cb) -- print('^2Save de '..xPlayer..' ^3Effectué') -- --for i=1, #xPlayers, 1 do -- -- local xPlayer = ESX.GetPlayerFromId(xPlayers[i]) -- -- --TriggerClientEvent('esx:showNotification', xPlayers[i], '✅ Synchronisation inventaire effectuée.') -- --end -- -- --end) RegisterServerEvent("SavellPlayerAuto") AddEventHandler("SavellPlayerAuto", function() ESX.SavePlayers(cb) print('^2Save des joueurs ^3Effectué') end) count = 0 Citizen.CreateThread(function() while true do Citizen.Wait(1000) count = count + 1 if count >= 240 then ESX.SavePlayers(cb) print('^2Save des joueurs ^3Effectué') count = 0 end end end)
local cmd, g = vim.cmd, vim.g local hiLinks = require "settings.utils".hiLinks local highlights = require "settings.utils".highlights -- vim.cmd("colorscheme paper") -- vim.cmd("colorscheme github-light") -- vim.cmd("set background=light") cmd "syntax enable" cmd "set termguicolors" cmd "colorscheme nord" g.nord_uniform_status_lines = 0 -- g.nord_uniform_diff_background = 1 g.nord_bold = 1 g.nord_italic = 1 g.nord_italic_comments = 1 g.nord_underline = 0 local colors = { nord1 = "#3B4252", nord0 = "#2E3440", nord2 = "#434C5E", nord3 = "#4C566A", nord3_bright = "#616E88", nord4 = "#D8DEE9", nord5 = "#E5E9F0", nord6 = "#ECEFF4", nord7 = "#8FBCBB", nord8 = "#88C0D0", nord9 = "#81A1C1", nord10 = "#5E81AC", nord11 = "#BF616A", nord12 = "#D08770", nord13 = "#EBCB8B", nord14 = "#A3BE8C", nord15 = "#B48EAD" } hiLinks( { htmlTag = "htmlTagName", htmlEndTag = "htmlTagName", jsxTagName = "jsxComponentName", jsObjectKey = "StorageClass", jsVariableDef = "Number", jsStorageClass = "rustAttribute", jsFuncBlock = "rustPanic", jsExport = "typescriptBOMWindowMethod", jsImport = "typescriptBOMWindowMethod", jsFrom = "typescriptBOMWindowMethod", jsObjectValue = "Function", -- jsNull = "typescriptDecorator", -- jsBooleanTrue = "typescriptDecorator", -- jsBooleanFalse = "typescriptDecorator", --[[ BufferInactiveMod = "typescriptDecorator", BufferCurrentMod = "typescriptDecorator", BufferVisibleMod = "typescriptDecorator", BufferCurrent = "typescriptBOMWindowMethod", BufferVisible = "rustAttribute", BufferInactive = "rustAttribute", BufferTabpages = "Normal", BufferTabpageFill = "Normal", ]] elixirAtom = "Number", elixirFunctionDeclaration = "rustAttribute", elixirDefine = "typescriptBOMWindowMethod", elixirModuleDefine = "typescriptBOMWindowMethod", elixirBlockDefinition = "typescriptBOMWindowMethod", elixirAlias = "SpecialChar", elixirModuleDeclaration = "typescriptDecorator", elixirInclude = "rustEnum", elixirId = "Type", LspDiagnosticsVirtualTextError = "LspDiagnosticsError", LspDiagnosticsVirtualTextWarning = "LspDiagnosticsWarning", LspDiagnosticsVirtualTextInformation = "LspDiagnosticsInformation", LspDiagnosticsVirtualTextHint = "LspDiagnosticsHint" } ) highlights( { Normal = {bg = "none"}, NonText = {bg = "none"}, cssTagName = {fg = colors.nord13, gui = "italic"}, cssClassName = {fg = "#eda48d", gui = "italic"}, jsGlobalObjects = {fg = "#eda48d", gui = "italic"}, cssIndetifier = {fg = "#eda48d", gui = "italic"}, jsReturn = {fg = colors.nord11, gui = "bold"}, jsSuper = {fg = colors.nord11}, jsThis = {fg = colors.nord13}, jsForAwait = {fg = colors.nord11}, jsTernaryIfOperator = {fg = colors.nord11}, StartifyHeader = {fg = colors.nord11, gui = "bold"}, StartifyNumber = {fg = colors.nord15}, StartifyPath = {fg = colors.nord10}, StartifySlash = {fg = colors.nord10}, StartifyBracket = {fg = colors.nord10}, StartifyFile = {fg = colors.nord8}, TelescopeBorder = {fg = colors.nord15}, TelescopePromptBorder = {fg = colors.nord15}, TelescopeResultsBorder = {fg = colors.nord15}, TelescopePreviewBorder = {fg = colors.nord15}, TelescopeSelection = {fg = colors.nord12}, TelescopeMatching = {fg = colors.nord11}, TelescopeNormal = {fg = colors.nord9}, FloatermBorder = {fg = colors.nord15}, javaScriptNumber = {fg = colors.nord15}, javaScriptNull = {fg = colors.nord11}, javaScriptBoolean = {fg = colors.nord12} } ) -- cmd 'autocmd ColorScheme * hi jsGlobalObjects guifg=#eda48d'
local Wrapper = require('core/support/Wrapper') ---@class PlayerDevData : PlayerDevelopmentData local PlayerDevData = Wrapper.make() ---@public ---@param owner gameObject ---@return PlayerDevData function PlayerDevData.resolve(owner) return PlayerDevData.wrap(PlayerDevelopmentSystem.GetData(owner or Game.GetPlayer())) end -- Points -- ---@public ---@param pointType gamedataDevelopmentPointType ---@return number function PlayerDevData:GetSpentPoints(pointType) if pointType == gamedataDevelopmentPointType.Attribute then local spentPoints = 0 local attributeMin = PlayerDevData.GetMinAttributeLevel() for _, attributeType in ipairs(PlayerDevData.GetAllAttributeTypes()) do local attributeLevel = self:GetAttributeLevel(attributeType) local attributeDiff = attributeLevel - attributeMin spentPoints = spentPoints + attributeDiff end return spentPoints end return math.floor(self.devPoints[self:GetDevPointsIndex(pointType) + 1].spent) end ---@public ---@param pointType gamedataDevelopmentPointType ---@param amount number function PlayerDevData:AdjustDevPoints(pointType, amount) local devPoints = self.devPoints local pointData = devPoints[self:GetDevPointsIndex(pointType) + 1] pointData.unspent = pointData.unspent + amount pointData.spent = pointData.spent - amount self.devPoints = devPoints end -- Attributes -- ---@public ---@return gamedataStatType[] function PlayerDevData.GetAllAttributeTypes() return { gamedataStatType.Strength, gamedataStatType.Reflexes, gamedataStatType.TechnicalAbility, gamedataStatType.Intelligence, gamedataStatType.Cool, } end ---@public ---@return number function PlayerDevData.GetMinAttributeLevel() return TweakDBInterface.GetInt('UICharacterCreationGeneral.BaseValues.minAttributeValue', 3) end ---@public ---@param attributeType gamedataStatType ---@return number function PlayerDevData:GetAttributeLevel(attributeType) return Game.GetStatsSystem():GetStatValue(self.ownerID, attributeType) end ---@public ---@param attributeType gamedataStatType ---@param attributeLevel number ---@return number function PlayerDevData:GetAttributeLevelCost(attributeType, attributeLevel) local statsDataSystem = Game.GetStatsDataSystem() local attributeCost = statsDataSystem:GetValueFromCurve( 'player_attributeLevelToCostIncrease', attributeLevel, attributeType.value ) return math.floor(attributeCost + .5) end ---@public ---@param attributeLevel number ---@return boolean function PlayerDevData:CanRevokeAttribute(attributeLevel) return attributeLevel > self.GetMinAttributeLevel() end ---@public ---@param attributeType gamedataStatType function PlayerDevData:RevokeAttribute(attributeType) local attributeLevel = self:GetAttributeLevel(attributeType) if attributeLevel > PlayerDevData.GetMinAttributeLevel() then local attributeCost = self:GetAttributeLevelCost(attributeType, attributeLevel) self:ModifyAttribute(attributeType, -1.0) self:AdjustDevPoints(gamedataDevelopmentPointType.Attribute, attributeCost) self:InvalidatePerks() end end ---@public function PlayerDevData:ResetAttributes() local attributeMin = PlayerDevData.GetMinAttributeLevel() local returnedPoints = self:GetDevPoints(gamedataDevelopmentPointType.Attribute) for _, attributeType in ipairs(PlayerDevData.GetAllAttributeTypes()) do local attributeLevel = self:GetAttributeLevel(attributeType) local attributeDiff = attributeLevel - attributeMin if attributeDiff > 0 then self:ModifyAttribute(attributeType, -attributeDiff) returnedPoints = returnedPoints + attributeDiff end end self:ResetDevelopmentPoints(gamedataDevelopmentPointType.Attribute) local availablePoints = self:GetDevPoints(gamedataDevelopmentPointType.Attribute) if returnedPoints > availablePoints then self:AddDevelopmentPoints(returnedPoints - availablePoints, gamedataDevelopmentPointType.Attribute) end self:InvalidatePerks() end -- Perks and Traits -- ---@return number function PlayerDevData.GetMinPerkLevel() return 0 end ---@public ---@param perkLevel number ---@return boolean function PlayerDevData:CanRevokePerk(perkLevel) return perkLevel > self.GetMinPerkLevel() end ---@public ---@param perkType gamedataPerkType function PlayerDevData:RevokePerk(perkType) local perkLevel = self:GetPerkLevel(perkType) if perkLevel > PlayerDevData.GetMinPerkLevel() then self:RemovePerk(perkType) if perkLevel > 1 then for _ = 2, perkLevel do self:BuyPerk(perkType) end end --Game.GetUISystem():QueueEvent(PerkBoughtEvent.new({ perkType = perkType })) end end ---@public ---@param traitType gamedataTraitType function PlayerDevData:RevokeTrait(traitType) local traitLevel = self:GetTraitLevel(traitType) if traitLevel > PlayerDevData.GetMinPerkLevel() then self:RemoveTrait(traitType) if traitLevel > 1 then for _ = 2, traitLevel do self:IncreaseTraitLevel(traitType) end end --Game.GetUISystem():QueueEvent(TraitBoughtEvent.new({ traitType = traitType })) end end ---@public function PlayerDevData:ResetPerks() self:RemoveAllPerks() end ---@public function PlayerDevData:InvalidatePerks() for _, perkArea in ipairs(self.perkAreas) do if not perkArea.unlocked then for _, perk in ipairs(perkArea.boughtPerks) do self:RemovePerk(perk.type) end end end end -- Skills -- ---@protected ---@param proficiencyType gamedataProficiencyType ---@return string function PlayerDevData:getProficiencyLevelFactName(proficiencyType) local proficiencyIndex = self:GetProficiencyIndexByType(proficiencyType) return ('_psxnrs_proficiency_alltime_%d'):format(proficiencyIndex) end ---@public ---@param proficiencyType gamedataProficiencyType ---@return number function PlayerDevData:GetProficiencyAlltimeLevel(proficiencyType) local currentLevel = self:GetProficiencyLevel(proficiencyType) local alltimeLevel = Game.GetQuestsSystem():GetFactStr(self:getProficiencyLevelFactName(proficiencyType)) return math.max(currentLevel, alltimeLevel) end ---@public ---@param proficiencyType gamedataProficiencyType ---@param alltimeLevel number|nil function PlayerDevData:SetProficiencyAlltimeLevel(proficiencyType, alltimeLevel) if not alltimeLevel then alltimeLevel = self:GetProficiencyAlltimeLevel(proficiencyType) end Game.GetQuestsSystem():SetFactStr(self:getProficiencyLevelFactName(proficiencyType), alltimeLevel) end ---@public ---@param proficiencyType gamedataProficiencyType ---@param targetLevel number ---@return boolean function PlayerDevData:CanAdjustProficienyLevel(proficiencyType, targetLevel) local alltimeLevel = self:GetProficiencyAlltimeLevel(proficiencyType) local currentLevel = self:GetProficiencyLevel(proficiencyType) return targetLevel ~= currentLevel and targetLevel <= alltimeLevel end ---@public ---@param proficiencyType gamedataProficiencyType ---@param targetLevel number ---@return boolean function PlayerDevData:AdjustProficienyLevel(proficiencyType, targetLevel) local currentLevel = self:GetProficiencyLevel(proficiencyType) if targetLevel ~= currentLevel then self:SetProficiencyAlltimeLevel(proficiencyType) local attributeType local attributeIndex local attributeLevelAdjusment = 0 local maxLevel = self:GetProficiencyMaxLevel(proficiencyType) if targetLevel > maxLevel then local proficiencyRecord = RPGManager.GetProficiencyRecord(proficiencyType) local attributeRecord = proficiencyRecord:TiedAttribute() if attributeRecord then attributeType = Enum.new('gamedataStatType', attributeRecord:EnumName()) attributeIndex = self:GetAttributeIndex(attributeType) local attributes = self.attributes attributeLevelAdjusment = attributes[attributeIndex + 1].value attributes[attributeIndex + 1].value = attributeRecord:Max() self.attributes = attributes end end local perkPointBonusAdjusment = 0 if targetLevel < currentLevel then local proficiencyIndex = self:GetProficiencyIndexByType(proficiencyType) local proficiencyRecord = self:GetProficiencyRecordByIndex(proficiencyIndex) local perkPointBonusEffectorId = TweakDBID.new('Proficiencies.AddPerkPoint') -- TweakDBID.new(0xE14F1253, 26) for level = 1, currentLevel do local bonusItem = proficiencyRecord:GetPassiveBonusesItem(level - 1) if bonusItem then local bonusEffector = bonusItem:EffectorToTrigger() if bonusEffector and bonusEffector:GetID() == perkPointBonusEffectorId then perkPointBonusAdjusment = perkPointBonusAdjusment - 1 end end end end self:SetLevel(proficiencyType, targetLevel, telemetryLevelGainReason.Ignore) if attributeLevelAdjusment ~= 0 then local attributes = self.attributes attributes[attributeIndex + 1].value = attributeLevelAdjusment self.attributes = attributes end if perkPointBonusAdjusment ~= 0 then self:AddDevelopmentPoints(perkPointBonusAdjusment, gamedataDevelopmentPointType.Primary) end end end return PlayerDevData
--ARGV[1]代表单个待判断元素对应的字节长度, -- 索引 1-length 代表键,0为不存在,1为存在 local array = {} local aL = table.getn(ARGV) - 1 local kL = table.getn(KEYS) local bitL = ARGV[1] --把单个元素所对应的下标取出来 local elementSize = aL / bitL --第一个元素2...ARGV[1]+1,第二个ARGV[1]+2...2ARGV[1]+1 for index = 1, elementSize --判断单个元素的情况 do local notAdd = true for i = (index - 1) * bitL + 2, index * bitL + 1 --判断对应的键下标是否都为true do local k = 1 while (notAdd and k <= kL) do if redis.call('getbit', KEYS[k], ARGV[i]) == 0 then array[index] = 0 notAdd = false else k = k + 1 end end end if notAdd then array[index] = 1 end end return array
local utils = require 'projects.utils' -- **************************************************************************** -- -- **************************************************************************** local function close() vim.cmd "execute 'SClose'" end local function load(session_name) if session_name and session_name ~= '' then vim.cmd("execute 'SLoad " .. session_name .. "'") end end local function exists(session_name) if session_name and session_name ~= '' then local list = vim.fn['startify#session_list'] '' return utils.is_in_list(list, session_name) end return false end local function save(session_name) if session_name and session_name ~= '' then vim.cmd("execute 'SSave " .. session_name .. "'") end end local function delete(session_name) if session_name and session_name ~= '' then vim.cmd("execute 'SDelete " .. session_name .. "'") end end -- **************************************************************************** -- Public API -- **************************************************************************** local sessions = { name = 'sessions', _ext_priority = 10000, -- we want to be last -- current_session_name = '', } function sessions.project_extension_init(host) sessions.host = host end function sessions.on_project_open(project) close() local session_name = project:ext_config('sessions', {}).session_name or project.name -- sessions.current_session_name = session_name if session_name then if exists(session_name) then load(session_name) else save(session_name) end end -- Because the session can possibly cd to a different directory vim.cmd("execute 'cd " .. vim.fn.expand(project.root_dir) .. "'") end function sessions.on_project_close() close() -- sessions.current_session_name = '' end function sessions.on_project_delete(project) if sessions.host then local session_name = project:ext_config('sessions', {}).session_name or project.name if sessions.host.prompt_yes_no('Delete associated session: ' .. session_name) then delete(session_name) end end end function sessions.config_example() return [[ 'sessions' = { -- session_name = 'defaults to project name', }, ]] end return sessions
data:extend{ { type = 'bool-setting', name = 'picker-tool-bp-updater', setting_type = 'startup', default_value = true, order = 'tool-bp-updater' } } data:extend{ { type = 'string-setting', name = 'picker-bp-updater-version-increment', setting_type = 'runtime-per-user', order = 'picker-f[1]', default_value = 'auto', allowed_values = {'off', 'auto', 'on'} }, { type = 'string-setting', name = 'picker-bp-updater-alt-version-increment', setting_type = 'runtime-per-user', order = 'picker-f[2]', default_value = 'on', allowed_values = {'off', 'auto', 'on'} } }
-- Copyright (C) 2009-2010 ARATA Mizuki -- See file COPYRIGHT for more information local _G = _G local type,tonumber,assert,error,pcall = type,tonumber,assert,error,pcall local pairs,ipairs,rawset,select,unpack = pairs,ipairs,rawset,select,unpack local string = require "string" local table = require "table" local io = require "io" local os = require "os" local objc = require "objc" local runtime = require "objc.runtime" local ffi = require "objc.runtime.ffi" local runtime_bridgesupport = require "objc.runtime.bridgesupport" local typeencoding = require "objc.typeencoding" local debug = require "debug" module "objc.bridgesupport" local skipqualifier,skiptype = typeencoding.skipqualifier,typeencoding.skiptype local struct_registry = runtime.__struct_registry local function DEBUG_print(...) local e = os.getenv "LOBJC_DEBUG" or "" if e:find("print",1,true) then _G.print(...) end end -- frameworkname(".../AppKit.framework") -> "AppKit" local function frameworkname(path) local name = string.match(path,"([^/]+).framework/?$") assert(name,"bad framework path") return name end --[[ assert(frameworkname("/System/Library/Frameworks/AppKit.framework") == "AppKit") assert(frameworkname("/System/Library/Frameworks/Foundation.framework/") == "Foundation") ]] local choose64 if runtime._PTRSIZE == 8 then -- 64bit choose64 = function(hoge,hoge64) return hoge64 or hoge end else -- 32bit choose64 = function(hoge,hoge64) return hoge end end local NSString = objc.classes.NSString DEBUG_fnenc = {} local function tobool(x,default) if x == "true" then return true elseif x == "false" then return false elseif x == nil then return default else error("BridgeSupport: invalid boolean: "..x) end end local function loadBS(b,bspath,bsinline) assert(b.tag == "signatures","bad BridgeSupport format in file: "..bspath) --assert(b.version == "1.0","bad BridgeSupport signature version") local handle_depends_on local handle_struct,handle_cftype,handle_opaque local handle_constant,handle_string_constant,handle_enum local handle_function,handle_function_alias local handle_informal_protocol,handle_class function handle_depends_on(e) objc.loadFrameworkByPath(e.path) end function handle_struct(e) local name = e.name local type = choose64(e.type,e.type64) local opaque = tobool(e.opaque,false) if not opaque then local tagname,p = string.match(type,"^{([^=]+)=(.*)}$") local struct_info if tagname == "?" then tagname = nil struct_info = {} DEBUG_print("BridgeSupport: <struct>: anonymous "..name.." "..type) else struct_info = struct_info or struct_registry[tagname] if struct_info == nil then struct_info = {} struct_registry[tagname] = struct_info end end local count = 0 while p ~= "" do count = count+1 if string.match(p,'^".-"') then local fieldname fieldname,p = string.match(p,'^"(.-)"(.*)') assert(not struct_info[count] or struct_info[count] == fieldname) assert(not struct_info[fieldname] or struct_info[fieldname] == count) struct_info[count] = fieldname struct_info[fieldname] = count end p = skiptype(p) end assert(not struct_info[":count:"] or struct_info[":count:"] == count) struct_info[":count:"] = count struct_info[":typeencoding:"] = type objc.structures[name] = function(fields) return objc.struct.new(tagname,fields,struct_info) end else -- DEBUG_print("BridgeSupport: <struct>: opaque "..name.." "..type) end end function handle_cftype(e) local name = e.name local type = choose64(e.type,e.type64) local tollfree = e.tollfree local gettypeid_func = e.gettypeid_func -- DEBUG_print("BridgeSupport: <cftype>: "..name.." "..type.." "..(tollfree or "").." "..(gettypeid_func or "")) end function handle_opaque(e) --DEBUG_print("BridgeSupport: <opaque>: "..e.name.." "..e.type) end function handle_constant(e) local name = e.name local type = choose64(e.type,e.type64) local magic_cookie = tobool(e.magic_cookie,false) if magic_cookie then --DEBUG_print("BridgeSupport: magic_cookie: "..name.." "..type) return end local value = ffi.getglobal(ffi.RTLD_DEFAULT,name,type) if objc.constants[e.name] and objc.constants[e.name] ~= value then DEBUG_print("BridgeSupport: duplicate constant name in file: "..bspath) end rawset(objc.constants,name,value) end function handle_string_constant(e) local value = e.value local nsstring = tobool(e.nsstring,false) if nsstring then value = NSString:stringWithUTF8String_(value) end if objc.constants[e.name] and objc.constants[e.name] ~= value then DEBUG_print("BridgeSupport: duplicate string constant name in file: "..bspath,e.name,objc.constants[e.name],value) end rawset(objc.constants,e.name,value) end function handle_enum(e) if tobool(e.ignore,false) then return end local value = choose64(e.value,e.value64) if not value then if runtime._ENDIAN == "little" then value = e.le_value elseif runtime._ENDIAN == "big" then value = e.be_value end end if value then value = assert(tonumber(value)) if objc.constants[e.name] and objc.constants[e.name] ~= value then DEBUG_print("BridgeSupport: duplicate enum name in file: ",e.name) DEBUG_print("BridgeSupport: duplicate enum name in file: ",bspath.." "..e.name.." "..objc.constants[e.name].."<=>"..value) end rawset(objc.constants,e.name,value) end end function handle_function(e) local variadic = tobool(e.variadic,false) local inline = tobool(e.inline,false) if variadic then -- not supported yet return end local mod = inline and bsinline or ffi.RTLD_DEFAULT local args = {} local ret = "v" local already_retained = false for _,a in ipairs(e) do -- mandatory local type = choose64(a.type,a.type64) -- optional local function_pointer = tobool(a.function_pointer,false) local sel_of_type = choose64(a.sel_of_type,a.sel_of_type64) if a.tag == "arg" then -- optional local type_modifier = a.type_modifier or "" local null_accepted = tobool(a.null_accepted,true) local printf_format = tobool(a.printf_format,false) table.insert(args,type_modifier..type) elseif a.tag == "retval" then -- optional already_retained = tobool(a.already_retained,false) ret = type end end local sig = ret..table.concat(args) DEBUG_fnenc[e.name] = sig local f = ffi.loadfunction(mod,e.name,sig,#args,already_retained) objc.functions[e.name] = f end function handle_function_alias(e) if objc.functions[e.original] then objc.functions[e.name] = objc.functions[e.original] else DEBUG_print("non-existent function alias "..e.name.." -> "..e.original.." ignored in file: "..bspath) end end function handle_informal_protocol(e) local name = e.name objc.informal_protocols[name] = objc.informal_protocols[name] or {} local protocol = objc.informal_protocols[name] protocol.name = name protocol.methods = protocol.methods or {} protocol.classmethods = protocol.classmethods or {} for _,m in ipairs(e) do if m.tag ~= "method" then error("BridgeSupport: unknown tag in <informal_protocol>:"..m.tag) end -- mandatory local selector = m.selector local type = choose64(m.type,m.type64) -- optional local class_method = tobool(m.class_method,false) if not type then -- method does not exist in this environment elseif class_method then protocol.classmethods[selector] = {type=type} else protocol.methods[selector] = {type=type} end end end function handle_class(e) local class = objc.classes[e.name] if not class then error("BridgeSupport: class '"..e.name.."' is mentioned in BridgeSupport, but does not exist") end for _,m in ipairs(e) do if m.tag ~= "method" then error("BridgeSupport: unknown tag in <class>:"..m.tag) end -- mandatory local selector = m.selector -- optional local class_method = tobool(m.class_method,false) local variadic = tobool(m.variadic,false) local ignore = tobool(m.ignore,false) local method if class_method then method = runtime.class_getClassMethod(class,selector) else method = runtime.class_getInstanceMethod(class,selector) end local encoding = method and assert(runtime.method_getTypeEncoding(method)) for _,a in ipairs(m) do -- optional local type = choose64(a.type,a.type64) --local c_array_of_*** local function_pointer = tobool(a.function_pointer,false) local sel_of_type = choose64(a.sel_of_type,a.sel_of_type64) local idx local type_modifier if a.tag == "arg" then -- mandatory local index = tonumber(a.index) -- zero-based -- optional type_modifier = a.type_modifier local null_accepted = tobool(a.null_accepted,true) local printf_format = tobool(a.printf_format,false) -- type = type and type_modifier..type --TODO: type_modifierだけが指定された場合はどうするのか idx = index+3 -- selfと_cmdの次から elseif a.tag == "retval" then -- optional local already_retained = tobool(a.already_retained,false) idx = 0 end if encoding and (type or type_modifier) then local s = encoding for _=1,idx do s = skiptype(s) s = string.match(s,"^%d*(.*)") -- skip frame offset end if type and type_modifier then encoding = string.sub(encoding,1,-#s-1)..type_modifier..type..skiptype(s) elseif type then s = skipqualifier(s) encoding = string.sub(encoding,1,-#s-1)..type..skiptype(s) elseif type_modifier then encoding = string.sub(encoding,1,-#s-1)..type_modifier..skipqualifier(s) end end end if method and encoding then runtime.overridesignature(method,encoding) end end end local delay_call = {} local function delay_pcall(f,...) table.insert(delay_call,{f=f,n=select("#",...),...}) end local orig_pcall=pcall local function pcall(f,...) local s,e = orig_pcall(f,...) if not s then DEBUG_print("ignoring error:",e) end end for _,e in ipairs(b) do if e.tag == "depends_on" then pcall(handle_depends_on,e) elseif e.tag == "struct" then pcall(handle_struct,e) elseif e.tag == "cftype" then pcall(handle_cftype,e) elseif e.tag == "opaque" then pcall(handle_opaque,e) elseif e.tag =="constant"then pcall(handle_constant,e) elseif e.tag == "string_constant" then pcall(handle_string_constant,e) elseif e.tag == "enum" then pcall(handle_enum,e) elseif e.tag =="function"then pcall(handle_function,e) elseif e.tag == "function_alias" then delay_pcall(handle_function_alias,e) elseif e.tag =="informal_protocol"then pcall(handle_informal_protocol,e) elseif e.tag == "class" then pcall(handle_class,e) else error("BridgeSupport: unknown tag: "..e.tag.." in file: "..bspath) end end for _,t in ipairs(delay_call) do pcall(t.f,unpack(t,1,t.n)) end return true end local loaded,loaded_inline = {},{} function loadBridgeSupportFile(fwpath,force) if loaded[fwpath] and not force then return true,"already loaded" end loaded[fwpath] = true --DEBUG_print("loadBridgeSupportFile:",fwpath) -- NSBundleを使うべき? local fwname = frameworkname(fwpath) local bsname = fwname..".bridgesupport" local bsinline_name = fwname..".dylib" local dirs = { fwpath.."/Resources/BridgeSupport", "/System/Library/BridgeSupport", "/Library/BridgeSupport", "~/Library/BridgeSupport", } local f,e,bspath,bsinline_path for _,dir in ipairs(dirs) do bspath = dir.."/"..bsname f,e = io.open(bspath) if f then bsinline_path =dir.."/"..bsinline_name break end end if not f then return f,"could not load BridgeSupport file: "..e end local data = f:read("*a") f:close() local x,e = runtime_bridgesupport.parsexml(data) if not x then return x,e end if not loaded_inline[bsinline_path] then loaded_inline[bsinline_path] = ffi.opendylib(bsinline_path) end return loadBS(x,bspath,loaded_inline[bsinline_path]) end
---@meta ---@class cc.DelayTime :cc.ActionInterval local DelayTime={ } cc.DelayTime=DelayTime ---* Creates the action.<br> ---* param d Duration time, in seconds.<br> ---* return An autoreleased DelayTime object. ---@param d float ---@return self function DelayTime:create (d) end ---* ---@return self function DelayTime:clone () end ---* param time In seconds. ---@param time float ---@return self function DelayTime:update (time) end ---* ---@return self function DelayTime:reverse () end ---* ---@return self function DelayTime:DelayTime () end
if SERVER then AddCSLuaFile( "shared.lua" ) end SWEP.HoldType = "normal" if CLIENT then SWEP.PrintName = "Death Station" SWEP.Slot = 6 SWEP.ViewModelFOV = 10 SWEP.EquipMenuData = { type="Weapon", model="models/props/cs_office/microwave.mdl", desc="Allows people to die when placed.\n\nFaster recharge. Anyone can use it, and\nit can be damaged plus it has a nasty suprise against vandalism. Can be checked for\nDNA samples of its users." }; SWEP.Icon = "vgui/ttt/icon_health" end SWEP.Base = "weapon_tttbase" SWEP.ViewModel = "models/weapons/v_crowbar.mdl" SWEP.WorldModel = "models/props/cs_office/microwave.mdl" SWEP.DrawCrosshair = true SWEP.Primary.ClipSize = -1 SWEP.Primary.DefaultClip = -1 SWEP.Primary.Automatic = true SWEP.Primary.Ammo = "none" SWEP.Primary.Delay = 1.0 SWEP.Secondary.ClipSize = -1 SWEP.Secondary.DefaultClip = -1 SWEP.Secondary.Automatic = true SWEP.Secondary.Ammo = "none" SWEP.Secondary.Delay = 1.0 -- This is special equipment SWEP.Kind = WEAPON_EQUIP1 SWEP.CanBuy = {ROLE_TRAITOR} -- only traitors can buy SWEP.LimitedStock = true -- only buyable once SWEP.AllowDrop = false SWEP.NoSights = true function SWEP:OnDrop() self:Remove() end function SWEP:PrimaryAttack() self.Weapon:SetNextPrimaryFire( CurTime() + self.Primary.Delay ) self:HealthDrop() end function SWEP:SecondaryAttack() self.Weapon:SetNextSecondaryFire( CurTime() + self.Secondary.Delay ) self:HealthDrop() end local throwsound = Sound( "Weapon_SLAM.SatchelThrow" ) -- ye olde droppe code function SWEP:HealthDrop() if SERVER then local ply = self.Owner if not ValidEntity(ply) then return end if self.Planted then return end local vsrc = ply:GetShootPos() local vang = ply:GetAimVector() local vvel = ply:GetVelocity() local vthrow = vvel + vang * 200 local health = ents.Create("ttt_explo_station") if ValidEntity(health) then health:SetPos(vsrc + vang * 10) health:SetOwner(ply) health:Spawn() health:PhysWake() local phys = health:GetPhysicsObject() if ValidEntity(phys) then phys:SetVelocity(vthrow) end self:Remove() self.Planted = true end end self.Weapon:EmitSound(throwsound) end function SWEP:Reload() return false end function SWEP:OnRemove() if CLIENT and ValidEntity(self.Owner) and self.Owner == LocalPlayer() and self.Owner:Alive() then RunConsoleCommand("lastinv") end end if CLIENT then local hudtxt = {text="Click to place the death station", font="TabLarge", xalign=TEXT_ALIGN_RIGHT} function SWEP:DrawHUD() hudtxt.pos = {ScrW() - 80, ScrH() - 80} draw.TextShadow(hudtxt, 2) end end function SWEP:Deploy() if SERVER and IsValid(self.Owner) then self.Owner:DrawViewModel(false) end return true end function SWEP:DrawWorldModel() end function SWEP:DrawWorldModelTranslucent() end
local zmq = require "lzmq" local zmqcopas = require "zmq.copas" local copas = require "copas" local unpack = table.unpack or unpack local zmqctx = zmq.context({io_threads = 1}) local listenaddr = "inproc://#1" -- Create a listener that runs until it receives -- a single message with "STOP" local listen = zmqctx:socket(zmq.PULL, {bind=listenaddr}) local colisten = zmqcopas.wrap(listen) local mainthread = copas.addthread(function() while true do local x = colisten:receive() if type(x) == "table" then print(unpack(x)) else print(x) end if x == "STOP" then break end end end) -- Add a sender that alternates between "1" and "2,3" local sender = zmqctx:socket(zmq.PUSH, {connect=listenaddr}) local cosender = zmqcopas.wrap(sender) copas.addthread(function() for i=1,5 do cosender:send("1") copas.sleep(1) cosender:send({"2","3"}) copas.sleep(1) end cosender:send("STOP") end) -- Main dispatcher loop while coroutine.status(mainthread) ~= "dead" do copas.step() end
-- Castlevania: Order of Ecclesia -- Simple RAM Display (good for livestreaming!) local opacityMaster = 0.68 local showHitboxes = not true gui.register(function() local frame = emu.framecount() local lagframe = emu.lagcount() local moviemode = "" local igframe = memory.readdword(0x02100374) local camx = math.floor(memory.readdwordsigned(0x021000bc) / 0x1000) local camy = math.floor(memory.readdwordsigned(0x021000c0) / 0x1000) local ch_x = memory.readdwordsigned(0x02109850) local ch_y = memory.readdwordsigned(0x02109854) local ch_vx = memory.readdwordsigned(0x0210985c) local ch_vy = memory.readdwordsigned(0x02109860) local ch_inv = memory.readbyte(0x021098e5) local ch_mptimer = memory.readword(0x020ffec0) local ch_atktimer = memory.readword(0x020ffec2) local hp = memory.readword(0x021002b4) local mp = memory.readword(0x021002b8) local mode = memory.readbyte(0x020d88d0) local fade = 1.0 -- math.min(1.0, 1.0 - math.abs(memory.readbytesigned(0x020f61fc)/16.0)) -- FIXME moviemode = movie.mode() if not movie.active() then moviemode = "no movie" end local framestr = "" if movie.active() and not movie.recording() then framestr = string.format("%d/%d", frame, movie.length()) else framestr = string.format("%d", frame) end framestr = framestr .. (moviemode ~= "" and string.format(" (%s)", moviemode) or "") gui.opacity(opacityMaster) gui.text(1, 26, string.format("%s\n%d", framestr, lagframe)) if mode == 0 then gui.opacity(opacityMaster * (fade/2 + 0.5)) gui.text(1, 60, string.format("(%6d,%6d) %d %d %d\nHP%03d/MP%03d", ch_vx, ch_vy, ch_inv, ch_mptimer, ch_atktimer, hp, mp)) -- enemy info local basead = 0x0210d308 local dispy = 26 for i = -40, 127 do local base = basead + i * 0x160 --if memory.readword(base) > 0 then -- hp display local en_hp = memory.readword(base) local en_mp = memory.readword(base+2) local en_x = memory.readdword(base-0xf8) local en_dmtyp1 = memory.readbyte(base-0x66) local en_dmtyp2 = memory.readbyte(base-0x65) local en_dmtyp3 = memory.readbyte(base-0x64) local en_inv1 = memory.readbyte(base-0x63) local en_inv2 = memory.readbyte(base-0x62) local en_inv3 = memory.readbyte(base-0x61) memory.writedword(base-0xec, 0) -- x velocity memory.writedword(base-0xe8, 0) -- y velocity memory.writeword(base-0xa6, 255) -- animation --gui.text(189, dispy, string.format("%02X %08X", i, base)) -- gui.text(183, dispy, string.format("%02X %4d %4d", i, en_hp, en_mp)) -- gui.text(171, dispy, string.format("%X %03d %08X", i, en_hp, en_x)) -- gui.text(123, dispy, string.format("%02X %4d %d/%02X %d/%02X %d/%02X", i, en_hp, en_dmtyp1, en_inv1, en_dmtyp2, en_inv2, en_dmtyp3, en_inv3)) dispy = dispy + 10 --end end -- enemy's hitbox if showHitboxes then for i = 0, 63 do local rectad = 0x02128f62 + (i * 0x14) local left = memory.readwordsigned(rectad+0) - camx local top = memory.readwordsigned(rectad+2) - camy local right = memory.readwordsigned(rectad+4) - camx local bottom = memory.readwordsigned(rectad+6) - camy if top >= 0 then gui.box(left, top, right, bottom, "clear", "#00ff00aa") end end end -- Shanoa's hitbox if showHitboxes then local left = memory.readwordsigned(0x02128c2e) - camx local top = memory.readwordsigned(0x02128c30) - camy local right = memory.readwordsigned(0x02128c32) - camx local bottom = memory.readwordsigned(0x02128c34) - camy gui.box(left, top, right, bottom, "clear", "#00ff00aa") end -- Glyph absorb timer local absorbTimerStr = "" for i = 0, 15 do local baseaddr = 0x02101000 + (i * 0x100) local timer = memory.readdwordsigned(baseaddr + 0x144) if timer > 0 and ( memory.readdwordsigned(baseaddr + 0x38) == 0x10000 or memory.readdwordsigned(baseaddr + 0x60) == 0x10000 or memory.readdwordsigned(baseaddr + 0x88) == 0x10000 or memory.readdwordsigned(baseaddr + 0xb0) == 0x10000 or memory.readdwordsigned(baseaddr + 0xbc) == 0x10000 or memory.readdwordsigned(baseaddr + 0xc4) == 0x10000 or memory.readdwordsigned(baseaddr + 0xcc) == 0x10000 or memory.readdwordsigned(baseaddr + 0xd4) == 0x10000 or memory.readdwordsigned(baseaddr + 0xd8) == 0x10000 or memory.readdwordsigned(baseaddr + 0xdc) == 0x10000 ) then -- absorbTimerStr = absorbTimerStr .. i .. ":" absorbTimerStr = absorbTimerStr .. string.format("%05X", timer) .. " " end end if absorbTimerStr ~= "" then gui.text(1, 183, "(Glyph) " .. absorbTimerStr) end end end)
--- --- Generated by EmmyLua(https://github.com/EmmyLua) --- Created by thealchemist0033. --- DateTime: 4/25/2021 3:38 PM --- --[[ Copyright © 2016 F. Georget <fabien.georget@gmail.com> This work is free. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See the COPYING file for more details. --]] -- the namespace that contains the useful functions and data mixer = {} grinder = {} -- the ui grinder.formspec = [[ size[8,7;] list[context;recipe;2,1;1,1] list[context;input;1,2;1,1] button[2,2;1,1;grind;Grind] list[context;output;3,2;3,1] list[current_player;main;0,3.25;8,4;] ]] -- This is a first filter to know if something can be crafted or not grinder.filter_recipe = function(inv) if inv:is_empty("input") then return false else return true end return false end grinder.recipes = { {"alchemy:zap", "alchemy:zap_powder"}, {"alchemy:sol", "alchemy:sol_powder"}, {"alchemy:lunar", "alchemy:lunar_powder"}, {"alchemy:hemlock", "alchemy:hemlock_powder"}, {"alchemy:fractalized", "alchemy:fractalized_powder"}, {"alchemy:life","alchemy:life_powder"}, {"alchemy:oceanic_flower", "alchemy:oceanic_powder"}, } -- Declares the recipes available grinder.is_recipe = function(inv) local input = inv:get_stack("input", 1) local name = input:get_name() for _, r in pairs(grinder.recipes) do rin, rout = unpack(r) if (name == rin) then inv:set_list("recipe", {ItemStack(rout)}) return end end end -- Build the UI grinder.on_construct = function(pos) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() inv:set_size("input", 1) inv:set_size("output", 3) inv:set_size("recipe", 1) meta:set_string("infotext", "Powder grinder") meta:set_string("formspec", grinder.formspec) end -- Nothing can be put by the user in the recipe and the output grinder.put = function(_, listname, _, stack) if ( listname == "output" or listname == "recipe") then return 0 else return stack:get_count() end end -- Refresh the "recipe" when a new item is put in the mixer grinder.on_put = function(pos, _, _, _) local inv = minetest.get_meta(pos):get_inventory() if (grinder.filter_recipe(inv)) then grinder.is_recipe(inv) else inv:set_list("recipe", {ItemStack("")}) end end -- You can't take the item from recipe grinder.take = function(pos, listname, index, stack) if listname == "recipe" then return 0 else return stack:get_count() end end -- Grind the ingredient into a powder grinder.grind = function(pos) local inv = minetest.get_meta(pos):get_inventory() if inv:is_empty("recipe") then return end local out = inv:get_stack("recipe", 1) if not inv:room_for_item("output", out) then return end -- It's ok to mix, let's go local input = inv:get_stack("input", 1) input:take_item(1) inv:set_stack("input", 1, input) inv:add_item("output", out) -- Refresh grinder.on_put(pos, _, _, _) end -- Act when a field is received grinder.on_grind = function(pos, _, fields) if fields.grind then grinder.grind(pos) end end -- refresh grinder.on_take = function(pos, listname, index, stack) local inv = minetest.get_meta(pos):get_inventory() if listname == "input" then grinder.on_put(pos, listname, index, stack) end end minetest.register_node("alchemy:powder_grinder", { description = "Powder grinder", drawtype="normal", tiles = { "alchemy_grinder_up.png", "alchemy_grinder_up.png", "alchemy_grinder_side.png", "alchemy_grinder_side.png", "alchemy_grinder_side.png", "alchemy_grinder_side.png", }, is_ground_content = true, groups = {cracky=3, oddly_breakable_by_hand=1}, inventory=true, on_construct = grinder.on_construct, allow_metadata_inventory_put = grinder.put, on_metadata_inventory_put = grinder.on_put, allow_metadata_inventory_take = grinder.take, on_metadata_inventory_take = grinder.on_take, on_receive_fields = grinder.on_grind }) minetest.register_craft({ output = "alchemy:powder_grinder", recipe = { {"default:copper_ingot", "default:copper_ingot", "default:copper_ingot"}, {"default:steel_ingot", "default:diamond", "default:steel_ingot"}, {"default:cobble", "default:steel_ingot", "default:cobble"} } })
local handle1 = Instance.new("Part") handle1.Parent = game.Workspace.acb227 handle1.Name = "NewBrick" handle1.Size = Vector3.new(1, 1, 1) handle1.Position = Vector3.new(15, 15, 15) handle1.Anchored = true handle1.CanCollide = true handle1.Locked = true handle1.BrickColor = BrickColor.new("Really black") handle1.Transparency = 0 handle1.Reflectance = 0 handle1.TopSurface = "Smooth" handle1.BottomSurface = "Smooth" ----------------------------------------------mesh h = Instance.new("BlockMesh") h.Scale = Vector3.new(1, 1, 1) h.Offset = Vector3.new(5, 0, 0) h.Parent = handle1
-------------------------------------------------------------------------------- -- GLOBAL CONFIGURATION -- -------------------------------------------------------------------------------- conf = { autostart = 2, stats = true, debug = false, decreasedRadius = 30, minRadius = 30, safeZoneMaintainTime= { 12, 10, 80, 60, 60, 60, 60, 60, 60, 60, 60 }, }
return { { effect_list = { { type = "BattleBuffAddAttrRatio", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "attackRating", number = -1500 } } } }, { effect_list = { { type = "BattleBuffAddAttrRatio", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "attackRating", number = -1610 } } } }, { effect_list = { { type = "BattleBuffAddAttrRatio", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "attackRating", number = -1720 } } } }, { effect_list = { { type = "BattleBuffAddAttrRatio", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "attackRating", number = -1830 } } } }, { effect_list = { { type = "BattleBuffAddAttrRatio", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "attackRating", number = -1940 } } } }, { effect_list = { { type = "BattleBuffAddAttrRatio", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "attackRating", number = -2050 } } } }, { effect_list = { { type = "BattleBuffAddAttrRatio", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "attackRating", number = -2160 } } } }, { effect_list = { { type = "BattleBuffAddAttrRatio", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "attackRating", number = -2270 } } } }, { effect_list = { { type = "BattleBuffAddAttrRatio", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "attackRating", number = -2380 } } } }, { effect_list = { { type = "BattleBuffAddAttrRatio", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "attackRating", number = -2500 } } } }, init_effect = "", name = "", time = 0, picture = "", desc = "敌方效果-命中下降", stack = 1, id = 19335, icon = 19330, last_effect = "Darkness", effect_list = { { type = "BattleBuffAddAttrRatio", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "attackRating", number = -1500 } } } }
ability_bristleback = class({}) function ability_bristleback:GetIntrinsicModifierName() return 'modifier_ability_bristleback_buff' end LinkLuaModifier('modifier_ability_bristleback_buff', 'heroes/bristleback/bristleback', LUA_MODIFIER_MOTION_NONE) -- Original https://github.com/EarthSalamander42/dota_imba/blob/77d0b1f04e322812d16b0fce6e0089c24c4a38e2/game/dota_addons/dota_imba_reborn/scripts/vscripts/components/abilities/heroes/hero_bristleback.lua#L548-L628 modifier_ability_bristleback_buff = class({ IsHidden = function(self) return true end, IsPurgable = function(self) return false end, IsDebuff = function(self) return false end, IsBuff = function(self) return true end, RemoveOnDeath = function(self) return false end, AllowIllusionDuplicate = function(self) return true end, IsPermanent = function(self) return true end, }) function modifier_ability_bristleback_buff:OnCreated() self.ability = self:GetAbility() self.caster = self:GetCaster() self.parent = self:GetParent() -- AbilitySpecials self.front_damage_reduction = 0 self.side_damage_reduction = self.ability:GetSpecialValueFor("side_damage_reduction") self.back_damage_reduction = self.ability:GetSpecialValueFor("back_damage_reduction") self.side_angle = self.ability:GetSpecialValueFor("side_angle") self.back_angle = self.ability:GetSpecialValueFor("back_angle") self.quill_release_threshold = self.ability:GetSpecialValueFor("quill_release_threshold") self.damageTaken = self.damageTaken or 0 end function modifier_ability_bristleback_buff:OnRefresh() self:OnCreated() end function modifier_ability_bristleback_buff:DeclareFunctions() return { MODIFIER_PROPERTY_INCOMING_DAMAGE_PERCENTAGE, MODIFIER_EVENT_ON_TAKEDAMAGE, } end function modifier_ability_bristleback_buff:GetModifierIncomingDamage_Percentage(keys) if self.parent:PassivesDisabled() or bit.band(keys.damage_flags, DOTA_DAMAGE_FLAG_REFLECTION) == DOTA_DAMAGE_FLAG_REFLECTION or bit.band(keys.damage_flags, DOTA_DAMAGE_FLAG_HPLOSS) == DOTA_DAMAGE_FLAG_HPLOSS then return 0 end local forwardVector = self.caster:GetForwardVector() local forwardAngle = math.deg(math.atan2(forwardVector.x, forwardVector.y)) local reverseEnemyVector = (self.caster:GetAbsOrigin() - keys.attacker:GetAbsOrigin()):Normalized() local reverseEnemyAngle = math.deg(math.atan2(reverseEnemyVector.x, reverseEnemyVector.y)) local difference = math.abs(forwardAngle - reverseEnemyAngle) -- There's 100% a more straightforward way to calculate this but I can't think properly right now if (difference <= (self.back_angle / 2)) or (difference >= (360 - (self.back_angle / 2))) then --print("Hit the back ", (self.back_damage_reduction), "%") local particle = ParticleManager:CreateParticle("particles/units/heroes/hero_bristleback/bristleback_back_dmg.vpcf", PATTACH_ABSORIGIN_FOLLOW, self.parent) ParticleManager:SetParticleControl(particle, 1, self.parent:GetAbsOrigin()) ParticleManager:SetParticleControlEnt(particle, 1, self.parent, PATTACH_POINT_FOLLOW, "attach_hitloc", self.parent:GetAbsOrigin(), true) ParticleManager:ReleaseParticleIndex(particle) local particle2 = ParticleManager:CreateParticle("particles/units/heroes/hero_bristleback/bristleback_back_lrg_dmg.vpcf", PATTACH_ABSORIGIN_FOLLOW, self.parent) ParticleManager:SetParticleControlEnt(particle2, 1, self.parent, PATTACH_POINT_FOLLOW, "attach_hitloc", self.parent:GetAbsOrigin(), true) ParticleManager:ReleaseParticleIndex(particle2) self.parent:EmitSound("Hero_Bristleback.Bristleback") return self.back_damage_reduction * (-1) elseif (difference <= (self.side_angle / 2)) or (difference >= (360 - (self.side_angle / 2))) then --print("Hit the side", (self.side_damage_reduction), "%") local particle = ParticleManager:CreateParticle("particles/units/heroes/hero_bristleback/bristleback_back_dmg.vpcf", PATTACH_ABSORIGIN_FOLLOW, self.parent) ParticleManager:SetParticleControl(particle, 1, self.parent:GetAbsOrigin()) ParticleManager:SetParticleControlEnt(particle, 1, self.parent, PATTACH_POINT_FOLLOW, "attach_hitloc", self.parent:GetAbsOrigin(), true) ParticleManager:ReleaseParticleIndex(particle) return self.side_damage_reduction * (-1) else --print("Hit the front") return self.front_damage_reduction * (-1) end end function modifier_ability_bristleback_buff:OnTakeDamage( keys ) if keys.unit == self.parent then if self.parent:PassivesDisabled() or bit.band(keys.damage_flags, DOTA_DAMAGE_FLAG_REFLECTION) == DOTA_DAMAGE_FLAG_REFLECTION or bit.band(keys.damage_flags, DOTA_DAMAGE_FLAG_HPLOSS) == DOTA_DAMAGE_FLAG_HPLOSS or not self.parent:HasAbility("imba_bristleback_quill_spray") or not self.parent:FindAbilityByName("imba_bristleback_quill_spray"):IsTrained() then return end -- Pretty inefficient to calculate this stuff twice but I don't want to make these class variables due to how much damage might stack in a single frame... local forwardVector = self.caster:GetForwardVector() local forwardAngle = math.deg(math.atan2(forwardVector.x, forwardVector.y)) local reverseEnemyVector = (self.caster:GetAbsOrigin() - keys.attacker:GetAbsOrigin()):Normalized() local reverseEnemyAngle = math.deg(math.atan2(reverseEnemyVector.x, reverseEnemyVector.y)) local difference = math.abs(forwardAngle - reverseEnemyAngle) if (difference <= (self.back_angle / 2)) or (difference >= (360 - (self.back_angle / 2))) then self.damageTaken = self.damageTaken + keys.damage local quill_spray_ability = self.parent:FindAbilityByName("imba_bristleback_quill_spray") if quill_spray_ability and quill_spray_ability:IsTrained() and self.damageTaken >= self.quill_release_threshold then quill_spray_ability:OnSpellStart() local count = 0 while(self.damageTaken >= self.quill_release_threshold and count < 10) do self.damageTaken = self.damageTaken - self.quill_release_threshold count = count + 1 end end end end end
local component = require("component") local unicode = require("unicode") local filesystem = {} local mtab = {name="", children={}, links={}} local fstab = {} local function segments(path) local parts = {} for part in path:gmatch("[^\\/]+") do local current, up = part:find("^%.?%.$") if current then if up == 2 then table.remove(parts) end else table.insert(parts, part) end end return parts end local function findNode(path, create, resolve_links) checkArg(1, path, "string") local visited = {} local parts = segments(path) local ancestry = {} local node = mtab local index = 1 while index <= #parts do local part = parts[index] ancestry[index] = node if not node.children[part] then local link_path = node.links[part] if link_path then if not resolve_links and #parts == index then break end if visited[path] then return nil, string.format("link cycle detected '%s'", path) end -- the previous parts need to be conserved in case of future ../.. link cuts visited[path] = index local pst_path = "/" .. table.concat(parts, "/", index + 1) local pre_path if link_path:match("^[^/]") then pre_path = table.concat(parts, "/", 1, index - 1) .. "/" local link_parts = segments(link_path) local join_parts = segments(pre_path .. link_path) local back = (index - 1 + #link_parts) - #join_parts index = index - back node = ancestry[index] else pre_path = "" index = 1 node = mtab end path = pre_path .. link_path .. pst_path parts = segments(path) part = nil -- skip node movement elseif create then node.children[part] = {name=part, parent=node, children={}, links={}} else break end end if part then node = node.children[part] index = index + 1 end end local vnode, vrest = node, #parts >= index and table.concat(parts, "/", index) local rest = vrest while node and not node.fs do rest = rest and filesystem.concat(node.name, rest) or node.name node = node.parent end return node, rest, vnode, vrest end ------------------------------------------------------------------------------- function filesystem.canonical(path) local result = table.concat(segments(path), "/") if unicode.sub(path, 1, 1) == "/" then return "/" .. result else return result end end function filesystem.concat(...) local set = table.pack(...) for index, value in ipairs(set) do checkArg(index, value, "string") end return filesystem.canonical(table.concat(set, "/")) end function filesystem.get(path) local node = findNode(path) if node.fs then local proxy = node.fs path = "" while node and node.parent do path = filesystem.concat(node.name, path) node = node.parent end path = filesystem.canonical(path) if path ~= "/" then path = "/" .. path end return proxy, path end return nil, "no such file system" end function filesystem.realPath(path) checkArg(1, path, "string") local node, rest = findNode(path, false, true) if not node then return nil, rest end local parts = {rest or nil} repeat table.insert(parts, 1, node.name) node = node.parent until not node return table.concat(parts, "/") end function filesystem.mount(fs, path) checkArg(1, fs, "string", "table") if type(fs) == "string" then fs = filesystem.proxy(fs) end assert(type(fs) == "table", "bad argument #1 (file system proxy or address expected)") checkArg(2, path, "string") local real if not mtab.fs then if path == "/" then real = path else return nil, "rootfs must be mounted first" end else local why real, why = filesystem.realPath(path) if not real then return nil, why end if filesystem.exists(real) and not filesystem.isDirectory(real) then return nil, "mount point is not a directory" end end local fsnode if fstab[real] then return nil, "another filesystem is already mounted here" end for _,node in pairs(fstab) do if node.fs.address == fs.address then fsnode = node break end end if not fsnode then fsnode = select(3, findNode(real, true)) -- allow filesystems to intercept their own nodes fs.fsnode = fsnode else local pwd = filesystem.path(real) local parent = select(3, findNode(pwd, true)) local name = filesystem.name(real) fsnode = setmetatable({name=name,parent=parent},{__index=fsnode}) parent.children[name] = fsnode end fsnode.fs = fs fstab[real] = fsnode return true end function filesystem.path(path) local parts = segments(path) local result = table.concat(parts, "/", 1, #parts - 1) .. "/" if unicode.sub(path, 1, 1) == "/" and unicode.sub(result, 1, 1) ~= "/" then return "/" .. result else return result end end function filesystem.name(path) checkArg(1, path, "string") local parts = segments(path) return parts[#parts] end function filesystem.proxy(filter, options) checkArg(1, filter, "string") if not component.list("filesystem")[filter] or next(options or {}) then -- if not, load fs full library, it has a smarter proxy that also supports options return filesystem.internal.proxy(filter, options) end return component.proxy(filter) -- it might be a perfect match end function filesystem.exists(path) if not filesystem.realPath(filesystem.path(path)) then return false end local node, rest, vnode, vrest = findNode(path) if not vrest or vnode.links[vrest] then -- virtual directory or symbolic link return true elseif node and node.fs then return node.fs.exists(rest) end return false end function filesystem.isDirectory(path) local real, reason = filesystem.realPath(path) if not real then return nil, reason end local node, rest, vnode, vrest = findNode(real) if not vnode.fs and not vrest then return true -- virtual directory (mount point) end if node.fs then return not rest or node.fs.isDirectory(rest) end return false end function filesystem.list(path) local node, rest, vnode, vrest = findNode(path, false, true) local result = {} if node then result = node.fs and node.fs.list(rest or "") or {} -- `if not vrest` indicates that vnode reached the end of path -- in other words, vnode[children, links] represent path if not vrest then for k,n in pairs(vnode.children) do if not n.fs or fstab[filesystem.concat(path, k)] then table.insert(result, k .. "/") end end for k in pairs(vnode.links) do table.insert(result, k) end end end local set = {} for _,name in ipairs(result) do set[filesystem.canonical(name)] = name end return function() local key, value = next(set) set[key or false] = nil return value end end function filesystem.open(path, mode) checkArg(1, path, "string") mode = tostring(mode or "r") checkArg(2, mode, "string") assert(({r=true, rb=true, w=true, wb=true, a=true, ab=true})[mode], "bad argument #2 (r[b], w[b] or a[b] expected, got " .. mode .. ")") local node, rest = findNode(path, false, true) if not node then return nil, rest end if not node.fs or not rest or (({r=true,rb=true})[mode] and not node.fs.exists(rest)) then return nil, "file not found" end local handle, reason = node.fs.open(rest, mode) if not handle then return nil, reason end return setmetatable({ fs = node.fs, handle = handle, }, {__index = function(tbl, key) if not tbl.fs[key] then return end if not tbl.handle then return nil, "file is closed" end return function(self, ...) local h = self.handle if key == "close" then self.handle = nil end return self.fs[key](h, ...) end end}) end filesystem.findNode = findNode filesystem.segments = segments filesystem.fstab = fstab ------------------------------------------------------------------------------- return filesystem
if vim.b.did_ftp == true then return end local opt_local = vim.opt_local local b = vim.b opt_local.textwidth = 100 opt_local.cursorline = true opt_local.colorcolumn = "101" opt_local.signcolumn = "number" opt_local.cursorline = false opt_local.cursorcolumn = false b.vimrc_null_ls_lsp_signs_enabled = 1
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.owm", package.seeall) function index() entry({"owm.json"}, call("getjsonowm")) local page = node("owm") page.target = template("owm") page.title = "OpenWifiMap" page.order = 100 end function getjsonowm() local root = {} local sys = require "luci.sys" local uci = require "luci.model.uci" local util = require "luci.util" local http = require "luci.http" local ltn12 = require "luci.ltn12" local json = require "luci.json" local owm = require "luci.owm" http.prepare_content("application/json") ltn12.pump.all(json.Encoder(owm.get()):source(), http.write) end
ACT_VM_FIDGET_EMPTY = ACT_VM_FIDGET_EMPTY or ACT_CROSSBOW_FIDGET_UNLOADED ACT_VM_BLOWBACK = ACT_VM_BLOWBACK or -2 SWEP.Locomotion_Data_Queued = nil local ServersideLooped = { [ACT_VM_FIDGET] = true, [ACT_VM_FIDGET_EMPTY] = true, --[ACT_VM_IDLE] = true, --[ACT_VM_IDLE_EMPTY] = true, --[ACT_VM_IDLE_SILENCED] = true } local IdleBlendTime = 0.0 local d,pbr --[[ ]]-- SWEP.Animations = { --Override this after SWEP:Initialize, for example, in attachments ["draw_first"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_DRAW_DEPLOYED, ["enabled"] = nil--Manually force a sequence to be enabled }, ["draw"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_DRAW }, ["draw_empty"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_DRAW_EMPTY }, ["draw_silenced"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_DRAW_SILENCED }, ["shoot1"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_PRIMARYATTACK }, ["shoot1_last"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_PRIMARYATTACK_EMPTY }, ["shoot1_empty"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_DRYFIRE }, ["shoot1_silenced"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_PRIMARYATTACK_SILENCED }, ["shoot1_silenced_empty"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_DRYFIRE_SILENCED or 0 }, ["shoot1_is"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_PRIMARYATTACK_1 }, ["shoot2"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_SECONDARYATTACK }, ["shoot2_last"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_SECONDARYATTACK_EMPTY }, ["shoot2_empty"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_DRYFIRE }, ["shoot2_silenced"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_SECONDARYATTACK_SILENCED }, ["idle"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_IDLE }, ["idle_empty"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_IDLE_EMPTY }, ["idle_silenced"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_IDLE_SILENCED }, ["reload"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_RELOAD }, ["reload_empty"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_RELOAD_EMPTY }, ["reload_silenced"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_RELOAD_SILENCED }, ["reload_shotgun_start"] = { ["type"] = TFA.Enum.ANIMATION_ACT, ["value"] = ACT_SHOTGUN_RELOAD_START }, ["reload_shotgun_finish"] = { ["type"] = TFA.Enum.ANIMATION_ACT, ["value"] = ACT_SHOTGUN_RELOAD_FINISH }, ["holster"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_HOLSTER }, ["holster_empty"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_HOLSTER_EMPTY }, ["holster_silenced"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_HOLSTER_SILENCED }, ["silencer_attach"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_ATTACH_SILENCER }, ["silencer_detach"] = { ["type"] = TFA.Enum.ANIMATION_ACT, --Sequence or act ["value"] = ACT_VM_DETACH_SILENCER } } SWEP.AnimationActivities = {} function SWEP:GetActivityEnabled( act ) local stat = self:GetStat( "SequenceEnabled." .. act ) if stat then return stat end if #self.AnimationActivities <= 0 then for k,v in pairs(self.Animations) do local kvt = self:GetStat( "Animations." .. k ) if kvt.value then self.AnimationActivities[kvt.value] = k end end end local keysel = self.AnimationActivities[ act ] or "" local kv = self:GetStat( "Animations." .. keysel ) if not kv then return false end if kv["enabled"] then return kv["enabled"] else return false end end function SWEP:ChooseAnimation( key ) local keysel = key local kv = self:GetStat( "Animations." .. keysel ) if not kv then return 0, 0 end if not kv["type"] then return 0, 0 end if not kv["value"] then return 0, 0 end return kv["type"], kv["value"] end function SWEP:SendViewModelAnim(act, rate, targ, blend ) local vm = self.OwnerViewModel if self.SequenceRateOverrideScaled[act] then rate = self.SequenceRateOverrideScaled[act] targ = false end if self.SequenceRateOverride[act] then rate = self.SequenceRateOverride[act] targ = true end if rate and not targ then rate = math.max(rate,0.0001) end if not rate then rate = 1 end if targ then rate = rate / self:NZAnimationSpeed( act ) else rate = rate * self:NZAnimationSpeed( act ) end if act < 0 then return false, act end if not self:VMIV() then return false, act end local seq = vm:SelectWeightedSequenceSeeded(act,CurTime()) if seq < 0 then if act == ACT_VM_IDLE_EMPTY then seq = vm:SelectWeightedSequenceSeeded(ACT_VM_IDLE,CurTime()) elseif act == ACT_VM_PRIMARYATTACK_EMPTY then seq = vm:SelectWeightedSequenceSeeded(ACT_VM_PRIMARYATTACK,CurTime()) else return end if seq < 0 then return false, act end end self:SetLastActivity( act ) self.LastAct = act self:ResetEvents() if self:GetLastActivity() == act and ServersideLooped[act] then self:ChooseIdleAnim() d = vm:SequenceDuration( seq ) pbr = targ and ( d / ( rate or 1 ) ) or ( rate or 1 ) if IsValid(self) then if blend == nil then blend = self.Idle_Smooth end self:SetNextIdleAnim( CurTime() + d / pbr - blend ) end if IsFirstTimePredicted() then timer.Simple(0, function() vm:SendViewModelMatchingSequence(seq) d = vm:SequenceDuration() pbr = targ and ( d / ( rate or 1 ) ) or ( rate or 1 ) vm:SetPlaybackRate( pbr ) if IsValid(self) then if blend == nil then blend = self.Idle_Smooth end self:SetNextIdleAnim( CurTime() + d / pbr - blend ) self:SetLastActivity( act ) self.LastAct = act end end) end else if seq >= 0 then vm:SendViewModelMatchingSequence(seq) end d = vm:SequenceDuration() pbr = targ and ( d / ( rate or 1 ) ) or ( rate or 1 ) vm:SetPlaybackRate( pbr ) if blend == nil then blend = self.Idle_Smooth end self:SetNextIdleAnim( CurTime() + math.max( d / pbr - blend, self.Idle_Smooth ) ) end return true, act end function SWEP:SendViewModelSeq(seq, rate, targ, blend ) local vm = self.OwnerViewModel if type(seq) == "string" then seq = vm:LookupSequence(seq) or 0 end if not self:VMIV() then return end local act = vm:GetSequenceActivity(seq) if self.SequenceRateOverrideScaled[act] then rate = self.SequenceRateOverrideScaled[act] targ = false end if self.SequenceRateOverride[act] then rate = self.SequenceRateOverride[act] targ = true end if not rate then rate = 1 end if targ then rate = rate / self:NZAnimationSpeed( act ) else rate = rate * self:NZAnimationSpeed( act ) end if seq < 0 then return false, act end if not self:VMIV() then return false, act end self:SetLastActivity( act ) self.LastAct = act self:ResetEvents() if self:GetLastActivity() == act and ServersideLooped[act] then vm:SendViewModelMatchingSequence( act == 0 and 1 or 0 ) vm:SetPlaybackRate(0) vm:SetCycle(0) self:SetNextIdleAnim( CurTime() + 0.03 ) if IsFirstTimePredicted() then timer.Simple(0, function() vm:SendViewModelMatchingSequence(seq) d = vm:SequenceDuration() pbr = targ and ( d / ( rate or 1 ) ) or ( rate or 1 ) vm:SetPlaybackRate( pbr ) if IsValid(self) then if blend == nil then blend = self.Idle_Smooth end self:SetNextIdleAnim( CurTime() + d / pbr - blend ) self:SetLastActivity( act ) self.LastAct = act end end) end else if seq >= 0 then vm:SendViewModelMatchingSequence(seq) end d = vm:SequenceDuration() pbr = targ and ( d / ( rate or 1 ) ) or ( rate or 1 ) vm:SetPlaybackRate( pbr ) if IsValid(self) then if blend == nil then blend = self.Idle_Smooth end self:SetNextIdleAnim( CurTime() + d / pbr - blend ) end end return true, act end local tval function SWEP:PlayAnimation(data) if not self:VMIV() then return end if not data then return false, -1 end local vm = self.OwnerViewModel if data.type == TFA.Enum.ANIMATION_ACT then tval = data.value if self:Clip1() <= 0 and self.Primary.ClipSize >= 0 then tval = data.value_empty or tval end if self:Clip1() == 1 and self.Primary.ClipSize >= 0 then tval = data.value_last or tval end if self:GetSilenced() then tval = data.value_sil or tval end if self:GetIronSights() then tval = data.value_is or tval if self:Clip1() <= 0 and self.Primary.ClipSize >= 0 then tval = data.value_is_empty or tval end if self:Clip1() == 1 and self.Primary.ClipSize >= 0 then tval = data.value_is_last or tval end if self:GetSilenced() then tval = data.value_is_sil or tval end end if type(tval) == "string" then tval = tonumber(tval) or -1 end if tval and tval > 0 then return self:SendViewModelAnim( tval, 1, false, data.transition and self.Idle_Blend or self.Idle_Smooth ) end elseif data.type == TFA.Enum.ANIMATION_SEQ then tval = data.value if self:Clip1() <= 0 and self.Primary.ClipSize >= 0 then tval = data.value_empty or tval end if self:Clip1() == 1 and self.Primary.ClipSize >= 0 then tval = data.value_last or tval end if type(tval) == "string" then tval = vm:LookupSequence(tval) end if tval and tval > 0 then return self:SendViewModelSeq( tval, 1, false, data.transition and self.Idle_Blend or self.Idle_Smooth ) end end end local success, tanim, typev --[[ Function Name: Locomote Syntax: self:Locomote( flip ironsights, new is, flip sprint, new sprint). Returns: Notes: Purpose: Animation / Utility ]] local __,tldata,tmpa function SWEP:Locomote(flipis,is,flipsp,spr) if not ( flipis or flipsp ) then return end if not ( self:GetStatus() == TFA.Enum.STATUS_IDLE or ( self:GetStatus() == TFA.Enum.STATUS_SHOOTING and self:CanInterruptShooting() ) ) then return end tldata = nil if flipis then if is and self:GetStat("IronAnimation.in") then tldata = self:GetStat("IronAnimation.in") or tldata elseif self:GetStat("IronAnimation.out") and not flipsp then tldata = self:GetStat("IronAnimation.out") or tldata end end if flipsp then if spr and self:GetStat("SprintAnimation.in") then tldata = self:GetStat("SprintAnimation.in") or tldata elseif self:GetStat("SprintAnimation.out") and not flipis and not spr then tldata = self:GetStat("SprintAnimation.out") or tldata end end --self.Idle_WithHeld = true if tldata then return self:PlayAnimation(tldata) end --self:SetNextIdleAnim(-1) return false, -1 end --[[ Function Name: ChooseDrawAnim Syntax: self:ChooseDrawAnim(). Returns: Could we successfully find an animation? Which action? Notes: Requires autodetection or otherwise the list of valid anims. Purpose: Animation / Utility ]] SWEP.IsFirstDeploy = true function SWEP:ChooseDrawAnim() if not self:VMIV() then return end --self:ResetEvents() tanim = ACT_VM_DRAW success = true if self.IsFirstDeploy and CurTime() > ( self.LastDeployAnim or CurTime() ) + 0.1 then self.IsFirstDeploy = false end if self:GetActivityEnabled( ACT_VM_DRAW_EMPTY ) and ( self:Clip1() == 0) then typev, tanim = self:ChooseAnimation( "draw_empty" ) elseif ( self:GetActivityEnabled( ACT_VM_DRAW_DEPLOYED ) or self.FirstDeployEnabled ) and self.IsFirstDeploy then typev, tanim = self:ChooseAnimation( "draw_first" ) elseif self:GetActivityEnabled( ACT_VM_DRAW_SILENCED ) and self:GetSilenced() then typev, tanim = self:ChooseAnimation( "draw_silenced" ) else typev, tanim = self:ChooseAnimation( "draw" ) end self.LastDeployAnim = CurTime() if typev ~= TFA.Enum.ANIMATION_SEQ then return self:SendViewModelAnim(tanim) else return self:SendViewModelSeq(tanim) end end --[[ Function Name: ChooseInspectAnim Syntax: self:ChooseInspectAnim(). Returns: Could we successfully find an animation? Which action? Notes: Requires autodetection or otherwise the list of valid anims. Purpose: Animation / Utility ]] -- local seed function SWEP:SelectInspectAnim( pri ) tanim = ACT_VM_FIDGET success = true seed = self:GetSeed() if self:GetActivityEnabled( ACT_VM_FIDGET_EMPTY ) and self.Primary.ClipSize > 0 and math.Round(self:Clip1()) == 0 then tanim = ACT_VM_FIDGET_EMPTY elseif self.InspectionActions then tanim = self.InspectionActions[ self:SharedRandom( 1, #self.InspectionActions, "Inspect" ) ] elseif self:GetActivityEnabled( ACT_VM_FIDGET ) then tanim = ACT_VM_FIDGET else tanim = ACT_VM_IDLE success = false end return tanim,success end function SWEP:ChooseInspectAnim() if not self:VMIV() then return end --self:ResetEvents() tanim, success = self:SelectInspectAnim( ) self:SendViewModelAnim(tanim,1) if IsFirstTimePredicted() then self.lastidlefidget = true end return success, tanim end --[[ Function Name: ChooseHolsterAnim Syntax: self:ChooseHolsterAnim(). Returns: Could we successfully find an animation? Which action? Notes: Requires autodetection or otherwise the list of valid anims. Purpose: Animation / Utility ]] -- ACT_VM_HOLSTER_SILENCED = ACT_VM_HOLSTER_SILENCED or ACT_CROSSBOW_HOLSTER_UNLOADED function SWEP:ChooseHolsterAnim() if not self:VMIV() then return end if self:GetActivityEnabled( ACT_VM_HOLSTER_SILENCED ) and self:GetSilenced() then typev, tanim = self:ChooseAnimation( "holster_silenced" ) elseif self:GetActivityEnabled( ACT_VM_HOLSTER_EMPTY ) and (self:Clip1() == 0) then typev, tanim = self:ChooseAnimation( "holster_empty" ) elseif self:GetActivityEnabled( ACT_VM_HOLSTER ) then typev, tanim = self:ChooseAnimation( "holster" ) else local _ _,tanim = self:ChooseIdleAnim() return false, tanim end if typev ~= TFA.Enum.ANIMATION_SEQ then return self:SendViewModelAnim(tanim) else return self:SendViewModelSeq(tanim) end end --[[ Function Name: ChooseProceduralReloadAnim Syntax: self:ChooseProceduralReloadAnim(). Returns: Could we successfully find an animation? Which action? Notes: Uses some holster code Purpose: Animation / Utility ]] -- function SWEP:ChooseProceduralReloadAnim() if not self:VMIV() then return end if not self.DisableIdleAnimations then self:SendViewModelAnim(ACT_VM_IDLE) end return true, ACT_VM_IDLE end --[[ Function Name: ChooseReloadAnim Syntax: self:ChooseReloadAnim(). Returns: Could we successfully find an animation? Which action? Notes: Requires autodetection or otherwise the list of valid anims. Purpose: Animation / Utility ]] -- function SWEP:ChooseReloadAnim() if not self:VMIV() then return false, 0 end if self.ProceduralReloadEnabled then return false, 0 end if self:GetActivityEnabled( ACT_VM_RELOAD_SILENCED ) and self:GetSilenced() then typev, tanim = self:ChooseAnimation( "reload_silenced" ) elseif self:GetActivityEnabled( ACT_VM_RELOAD_EMPTY ) and self:Clip1() == 0 and not self.Shotgun then typev, tanim = self:ChooseAnimation( "reload_empty" ) else typev, tanim = self:ChooseAnimation( "reload" ) end local fac = 1 if self.Shotgun and self.ShellTime then fac = self.ShellTime end self.AnimCycle = 0 if typev ~= TFA.Enum.ANIMATION_SEQ then return self:SendViewModelAnim(tanim, fac, fac ~= 1) else return self:SendViewModelSeq(tanim, fac, fac ~= 1) end end --[[ Function Name: ChooseReloadAnim Syntax: self:ChooseReloadAnim(). Returns: Could we successfully find an animation? Which action? Notes: Requires autodetection or otherwise the list of valid anims. Purpose: Animation / Utility ]] -- function SWEP:ChooseShotgunReloadAnim() if not self:VMIV() then return end if self:GetActivityEnabled( ACT_VM_RELOAD_SILENCED ) and self:GetSilenced() then typev, tanim = self:ChooseAnimation( "reload_silenced" ) elseif self:GetActivityEnabled( ACT_VM_RELOAD_EMPTY ) and self.ShotgunEmptyAnim and self:Clip1() == 0 then typev, tanim = self:ChooseAnimation( "reload_empty" ) elseif self.SequenceEnabled[ ACT_SHOTGUN_RELOAD_START ] then typev, tanim = self:ChooseAnimation( "reload_shotgun_start" ) else local _ _, tanim = self:ChooseIdleAnim() return false, tanim end if typev ~= TFA.Enum.ANIMATION_SEQ then return self:SendViewModelAnim(tanim) else return self:SendViewModelSeq(tanim) end end function SWEP:ChooseShotgunPumpAnim() if not self:VMIV() then return end typev, tanim = self:ChooseAnimation( "reload_shotgun_finish" ) if typev ~= TFA.Enum.ANIMATION_SEQ then return self:SendViewModelAnim(tanim) else return self:SendViewModelSeq(tanim) end end --[[ Function Name: ChooseIdleAnim Syntax: self:ChooseIdleAnim(). Returns: True, Which action? Notes: Requires autodetection for full features. Purpose: Animation / Utility ]] -- function SWEP:ChooseIdleAnim() if not self:VMIV() then return end --if self.Idle_WithHeld then -- self.Idle_WithHeld = nil -- return --end if self.Idle_Mode ~= TFA.Enum.IDLE_BOTH and self.Idle_Mode ~= TFA.Enum.IDLE_ANI then return end --self:ResetEvents() typev, tanim = self:ChooseAnimation( "idle" ) if self:GetIronSights() then if self.Sights_Mode == TFA.Enum.LOCOMOTION_LUA then return self:ChooseFlatAnim() else return self:ChooseADSAnim() end elseif self:GetSprinting() and self.Sprint_Mode ~= TFA.Enum.LOCOMOTION_LUA then return self:ChooseSprintAnim() end if self:GetActivityEnabled( ACT_VM_IDLE_SILENCED ) and self:GetSilenced() then typev, tanim = self:ChooseAnimation( "idle_silenced" ) elseif ( self.Primary.ClipSize > 0 and self:Clip1() == 0 ) or ( self.Primary.ClipSize <= 0 and self:Ammo1() == 0 ) then--self:GetActivityEnabled( ACT_VM_IDLE_EMPTY ) and (self:Clip1() == 0) then if self:GetActivityEnabled( ACT_VM_IDLE_EMPTY ) then typev, tanim = self:ChooseAnimation( "idle_empty" ) else--if not self:GetActivityEnabled( ACT_VM_PRIMARYATTACK_EMPTY ) then typev, tanim = self:ChooseAnimation( "idle" ) end --else -- return --end end if typev ~= TFA.Enum.ANIMATION_SEQ then return self:SendViewModelAnim(tanim) else return self:SendViewModelSeq(tanim) end end function SWEP:ChooseFlatAnim() if not self:VMIV() then return end --self:ResetEvents() typev, tanim = self:ChooseAnimation( "idle" ) if self:GetActivityEnabled( ACT_VM_IDLE_SILENCED ) and self:GetSilenced() then typev, tanim = self:ChooseAnimation( "idle_silenced" ) elseif self:Clip1() == 0 then--self:GetActivityEnabled( ACT_VM_IDLE_EMPTY ) and (self:Clip1() == 0) then typev, tanim = self:ChooseAnimation( "idle_empty" ) end if typev ~= TFA.Enum.ANIMATION_SEQ then return self:SendViewModelAnim(tanim, 0.000001) else return self:SendViewModelSeq(tanim, 0.000001) end end function SWEP:ChooseADSAnim() local a,b,c = self:PlayAnimation(self:GetStat("IronAnimation.loop")) --self:SetNextIdleAnim(CurTime() + 1) if not a then a,b,c = self:ChooseFlatAnim() a = false end return a,b,c end function SWEP:ChooseSprintAnim() return self:PlayAnimation(self:GetStat("SprintAnimation.loop")) end --[[ Function Name: ChooseShootAnim Syntax: self:ChooseShootAnim(). Returns: Could we successfully find an animation? Which action? Notes: Requires autodetection or otherwise the list of valid anims. Purpose: Animation / Utility ]] -- function SWEP:ChooseShootAnim(ifp) ifp = ifp or IsFirstTimePredicted() if not self:VMIV() then return end if self:GetIronSights() and ( self.Sights_Mode == TFA.Enum.LOCOMOTION_ANI or self.Sights_Mode == TFA.Enum.LOCOMOTION_HYBRID ) and self:GetStat("IronAnimation.shoot") then if self.LuaShellEject then self:MakeShellBridge(ifp) end return self:PlayAnimation(self:GetStat("IronAnimation.shoot")) end if not self.BlowbackEnabled or (not self:GetIronSights() and self.Blowback_Only_Iron) then success = true if self.LuaShellEject then self:MakeShellBridge(ifp) end if self:GetActivityEnabled( ACT_VM_PRIMARYATTACK_SILENCED ) and self:GetSilenced() then typev, tanim = self:ChooseAnimation( "shoot1_silenced" ) elseif self:Clip1() <= self.Primary.AmmoConsumption and self:GetActivityEnabled( ACT_VM_PRIMARYATTACK_EMPTY ) and self.Primary.ClipSize >= 1 and not self.ForceEmptyFireOff then typev, tanim = self:ChooseAnimation( "shoot1_last" ) elseif self:Ammo1() <= self.Primary.AmmoConsumption and self:GetActivityEnabled( ACT_VM_PRIMARYATTACK_EMPTY ) and self.Primary.ClipSize < 1 and not self.ForceEmptyFireOff then typev, tanim = self:ChooseAnimation( "shoot1_last" ) elseif self:Clip1() == 0 and self:GetActivityEnabled( ACT_VM_DRYFIRE ) and not self.ForceDryFireOff then typev, tanim = self:ChooseAnimation( "shoot1_empty" ) elseif self.Akimbo and self:GetActivityEnabled( ACT_VM_SECONDARYATTACK ) and ((self.AnimCycle == 0 and not self.Akimbo_Inverted) or (self.AnimCycle == 1 and self.Akimbo_Inverted)) then typev, tanim = self:ChooseAnimation( "shoot2" ) elseif self:GetIronSights() and self:GetActivityEnabled( ACT_VM_PRIMARYATTACK_1 ) then typev, tanim = self:ChooseAnimation( "shoot1_is" ) else typev, tanim = self:ChooseAnimation( "shoot1" ) end if typev ~= TFA.Enum.ANIMATION_SEQ then return self:SendViewModelAnim(tanim) else return self:SendViewModelSeq(tanim) end else if game.SinglePlayer() and SERVER then self:CallOnClient("BlowbackFull", "") end if ifp then self:BlowbackFull(ifp) end self:MakeShellBridge(ifp) self:SendViewModelAnim(ACT_VM_BLOWBACK) return true, ACT_VM_IDLE end end function SWEP:BlowbackFull() if IsValid(self) then self.BlowbackCurrent = 1 self.BlowbackCurrentRoot = 1 end end --[[ Function Name: ChooseSilenceAnim Syntax: self:ChooseSilenceAnim( true if we're silencing, false for detaching the silencer). Returns: Could we successfully find an animation? Which action? Notes: Requires autodetection or otherwise the list of valid anims. This is played when you silence or unsilence a gun. Purpose: Animation / Utility ]] -- function SWEP:ChooseSilenceAnim(val) if not self:VMIV() then return end --self:ResetEvents() typev, tanim = self:ChooseAnimation( "idle_silenced" ) success = false if val then if self:GetActivityEnabled( ACT_VM_ATTACH_SILENCER ) then typev, tanim = self:ChooseAnimation( "silencer_attach" ) success = true end elseif self:GetActivityEnabled( ACT_VM_DETACH_SILENCER ) then typev, tanim = self:ChooseAnimation( "silencer_detach" ) success = true end if not success then local _ _, tanim = self:ChooseIdleAnim() return false, tanim end if typev ~= TFA.Enum.ANIMATION_SEQ then return self:SendViewModelAnim(tanim) else return self:SendViewModelSeq(tanim) end end --[[ Function Name: ChooseDryFireAnim Syntax: self:ChooseDryFireAnim(). Returns: Could we successfully find an animation? Which action? Notes: Requires autodetection or otherwise the list of valid anims. set SWEP.ForceDryFireOff to false to properly use. Purpose: Animation / Utility ]] -- function SWEP:ChooseDryFireAnim() if not self:VMIV() then return end --self:ResetEvents() typev, tanim = self:ChooseAnimation( "shoot1_empty" ) success = true if self:GetActivityEnabled( ACT_VM_DRYFIRE_SILENCED ) and self:GetSilenced() and not self.ForceDryFireOff then typev, tanim = self:ChooseAnimation( "shoot1_silenced_empty" ) --self:ChooseIdleAnim() else if self:GetActivityEnabled( ACT_VM_DRYFIRE ) and not self.ForceDryFireOff then typev, tanim = self:ChooseAnimation( "shoot1_empty" ) else success = false local _ _, tanim = nil, nil return success, tanim end end if typev ~= TFA.Enum.ANIMATION_SEQ then return self:SendViewModelAnim(tanim) else return self:SendViewModelSeq(tanim) end end --[[THIRDPERSON]] --These holdtypes are used in ironsights. Syntax: DefaultHoldType=NewHoldType SWEP.IronSightHoldTypes = { pistol = "revolver", smg = "rpg", grenade = "melee", ar2 = "rpg", shotgun = "ar2", rpg = "rpg", physgun = "physgun", crossbow = "ar2", melee = "melee2", slam = "camera", normal = "fist", melee2 = "magic", knife = "fist", duel = "duel", camera = "camera", magic = "magic", revolver = "revolver" } --These holdtypes are used while sprinting. Syntax: DefaultHoldType=NewHoldType SWEP.SprintHoldTypes = { pistol = "normal", smg = "passive", grenade = "normal", ar2 = "passive", shotgun = "passive", rpg = "passive", physgun = "normal", crossbow = "passive", melee = "normal", slam = "normal", normal = "normal", melee2 = "melee", knife = "fist", duel = "normal", camera = "slam", magic = "normal", revolver = "normal" } --These holdtypes are used in reloading. Syntax: DefaultHoldType=NewHoldType SWEP.ReloadHoldTypes = { pistol = "pistol", smg = "smg", grenade = "melee", ar2 = "ar2", shotgun = "shotgun", rpg = "ar2", physgun = "physgun", crossbow = "crossbow", melee = "pistol", slam = "smg", normal = "pistol", melee2 = "pistol", knife = "pistol", duel = "duel", camera = "pistol", magic = "pistol", revolver = "revolver" } --These holdtypes are used in reloading. Syntax: DefaultHoldType=NewHoldType SWEP.CrouchHoldTypes = { ar2 = "ar2", smg = "smg", rpg = "ar2" } SWEP.IronSightHoldTypeOverride = "" --This variable overrides the ironsights holdtype, choosing it instead of something from the above tables. Change it to "" to disable. SWEP.SprintHoldTypeOverride = "" --This variable overrides the sprint holdtype, choosing it instead of something from the above tables. Change it to "" to disable. SWEP.ReloadHoldTypeOverride = "" --This variable overrides the reload holdtype, choosing it instead of something from the above tables. Change it to "" to disable. local dynholdtypecvar = GetConVar("sv_tfa_holdtype_dynamic") SWEP.mht_old = "" local mht function SWEP:ProcessHoldType() mht = self:GetStat("HoldType") or "ar2" if mht ~= self.mht_old or not self.DefaultHoldType then self.DefaultHoldType = mht self.SprintHoldType = nil self.IronHoldType = nil self.ReloadHoldType = nil self.CrouchHoldType = nil end self.mht_old = mht if not self.SprintHoldType then self.SprintHoldType = self.SprintHoldTypes[self.DefaultHoldType] or "passive" if self.SprintHoldTypeOverride and self.SprintHoldTypeOverride ~= "" then self.SprintHoldType = self.SprintHoldTypeOverride end end if not self.IronHoldType then self.IronHoldType = self.IronSightHoldTypes[self.DefaultHoldType] or "rpg" if self.IronSightHoldTypeOverride and self.IronSightHoldTypeOverride ~= "" then self.IronHoldType = self.IronSightHoldTypeOverride end end if not self.ReloadHoldType then self.ReloadHoldType = self.ReloadHoldTypes[self.DefaultHoldType] or "ar2" if self.ReloadHoldTypeOverride and self.ReloadHoldTypeOverride ~= "" then self.ReloadHoldType = self.ReloadHoldTypeOverride end end if not self.SetCrouchHoldType then self.SetCrouchHoldType = true self.CrouchHoldType = self.CrouchHoldTypes[self.DefaultHoldType] if self.CrouchHoldTypeOverride and self.CrouchHoldTypeOverride ~= "" then self.CrouchHoldType = self.CrouchHoldTypeOverride end end local curhold, targhold curhold = self:GetHoldType() targhold = self.DefaultHoldType stat = self:GetStatus() if dynholdtypecvar:GetBool() then if self:OwnerIsValid() and self.Owner:Crouching() and self.CrouchHoldType then targhold = self.CrouchHoldType else if self:GetIronSights() then targhold = self.IronHoldType end if TFA.Enum.ReloadStatus[stat] then targhold = self.ReloadHoldType end end end if self:GetSprinting() or TFA.Enum.HolsterStatus[stat] or self:IsSafety() then targhold = self.SprintHoldType end if targhold ~= curhold then self:SetHoldType(targhold) end end
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ========== PlaceObj('StoryBit', { ActivationEffects = { PlaceObj('AddTrait', { 'Trait', "Genius", }), }, Category = "Tick_FounderStageDone", Effects = {}, Enabled = true, Image = "UI/Messages/Events/15_artist.tga", MainMapExclusive = false, Prerequisites = { PlaceObj('PickWorker', { 'ParentBuildingLabel', "ArtWorkshop", 'WorkerConditions', {}, }), PlaceObj('SupplyMissionsEnabled', nil), PlaceObj('IsMapEnvironment', { 'Negate', true, 'SelectedMapEnvironment', "Asteroid", }), }, ScriptDone = true, Text = T(583874410580, --[[StoryBit Masterpiece Text]] "The piece impressed their peers so much that they talked the shy creator <DisplayName> into sharing more of their works. What they saw left little doubt in our minds that we have a prodigy on our hands.\n\nAlready making waves on the Earth art scene, offers for the originals are reaching mind-boggling sums.\n\nEffect: <DisplayName> has become a Genius"), TextReadyForValidation = true, TextsDone = true, Title = T(707548984483, --[[StoryBit Masterpiece Title]] "Cydonia da Vinci"), VoicedText = T(350183389237, --[[voice:narrator]] "A rather quiet employee at our Art Workshop blew everyone’s mind when they shared an original work."), group = "Buildings", id = "Masterpiece", qa_info = PlaceObj('PresetQAInfo', { data = { { action = "Modified", time = 1625143633, }, }, }), PlaceObj('StoryBitReply', { 'Text', T(315370222735, --[[StoryBit Masterpiece Text]] "Share their work with the world. Let it be seen in galleries on Earth as well!"), 'OutcomeText', "custom", 'CustomOutcomeText', T(713853043409, --[[StoryBit Masterpiece CustomOutcomeText]] "colonists gain Morale"), }), PlaceObj('StoryBitOutcome', { 'Prerequisites', {}, 'Effects', { PlaceObj('ForEachExecuteEffects', { 'Label', "Colonist", 'Filters', {}, 'RandomCount', 20, 'Effects', { PlaceObj('ModifyObject', { 'Prop', "base_morale", 'Amount', 10, 'Sols', 7200000, 'ModifyId', "Masterpiece", }), }, }), }, }), PlaceObj('StoryBitReply', { 'Text', T(907704905816, --[[StoryBit Masterpiece Text]] "Sell the originals for the benefit of the colony."), 'OutcomeText', "custom", 'CustomOutcomeText', T(902679316362, --[[StoryBit Masterpiece CustomOutcomeText]] "get Funding for <sols(duration)> Sols"), }), PlaceObj('StoryBitParamSols', { 'Name', "duration", 'Value', 36000000, }), PlaceObj('StoryBitOutcome', { 'Prerequisites', {}, 'Enables', { "Masterpiece_KillIn50Sols", "Masterpiece_PeriodicFunding", }, 'Effects', {}, }), PlaceObj('StoryBitReply', { 'Text', T(563534334966, --[[StoryBit Masterpiece Text]] "Encourage <DisplayName> to experiment in other areas. Imagine the possibilities!"), }), PlaceObj('StoryBitOutcome', { 'Prerequisites', {}, 'Enables', { "Masterpiece_Research", }, 'Effects', {}, }), })
-------------------------------------------------------------------------------- local Icon = {} -------------------------------------------------------------------------------- function Icon:draw(options) local icon = display.newImage( options.parent, options.path ) if(options.disabled) then icon.fill.effect = 'filter.desaturate' icon.fill.effect.intensity = 0.8 end icon.x = options.x icon.y = options.y if(options.maxSize) then local heigthRatio = options.maxSize / icon.height local widthRatio = options.maxSize / icon.width local ratio = math.min(widthRatio, heigthRatio) icon:scale(ratio, ratio) end return icon end -------------------------------------------------------------------------------- return Icon
local mixer_yatm_network = { kind = "machine", groups = { machine_worker = 1, energy_consumer = 1, }, default_state = "off", states = { conflict = "yatm_machines:mixer_error", error = "yatm_machines:mixer_error", off = "yatm_machines:mixer_off", on = "yatm_machines:mixer_on", }, energy = { passive_lost = 0, capacity = 4000, network_charge_bandwidth = 1000, startup_threshold = 100, }, } function mixer_yatm_network:work(ctx) return 0 end yatm.devices.register_stateful_network_device({ basename = "yatm_machines:mixer", description = "Mixer", groups = { cracky = 1, item_interface_in = 1, item_interface_out = 1, fluid_interface_in = 1, fluid_interface_out = 1, yatm_energy_device = 1, }, drop = mixer_yatm_network.states.off, tiles = { "yatm_mixer_top.off.png", "yatm_mixer_bottom.png", "yatm_mixer_side.off.png", "yatm_mixer_side.off.png^[transformFX", "yatm_mixer_back.png", "yatm_mixer_front.off.png", }, paramtype = "none", paramtype2 = "facedir", yatm_network = mixer_yatm_network, }, { error = { tiles = { "yatm_mixer_top.error.png", "yatm_mixer_bottom.png", "yatm_mixer_side.error.png", "yatm_mixer_side.error.png^[transformFX", "yatm_mixer_back.png", "yatm_mixer_front.error.png", }, }, on = { tiles = { "yatm_mixer_top.on.png", "yatm_mixer_bottom.png", "yatm_mixer_side.on.png", "yatm_mixer_side.on.png^[transformFX", "yatm_mixer_back.png", { name = "yatm_mixer_front.on.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 0.25 }, }, }, } })
local FxControlHelper = require "fx_control_helper" local fx_controller = FxControlHelper:new() -- # Effekseer の設定 fx_controller:set_effect("vci_subitem_name") fx_controller:disable_effect_loop() -- # AudioClip の設定 fx_controller:set_sound("audio_clip_name") fx_controller:set_sound_volume(0.5) fx_controller:disable_sound_loop() function onTriggerEnter(item, hit) if item == "vci_subitem_name" then fx_controller:play() end end
--!A cross-platform build utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2019, TBOOX Open Source Group. -- -- @author ruki -- @file io.lua -- -- load modules local io = require("base/io") local utils = require("base/utils") local string = require("base/string") local raise = require("sandbox/modules/raise") local vformat = require("sandbox/modules/vformat") -- define module local sandbox_io = sandbox_io or {} -- inherit some builtin interfaces sandbox_io.flush = io.flush sandbox_io.seek = io.seek sandbox_io.read = io.read sandbox_io.write = io.write sandbox_io.stdin = io.stdin sandbox_io.stderr = io.stderr sandbox_io.stdout = io.stdout sandbox_io.isatty = io.isatty -- print file function sandbox_io._print(self, ...) -- check assert(self._FILE) -- print it return self._FILE:write(vformat(...) .. "\n") end -- printf file function sandbox_io._printf(self, ...) -- check assert(self._FILE) -- printf it return self._FILE:write(vformat(...)) end -- gsub the given file and return replaced data function sandbox_io.gsub(filepath, pattern, replace) -- check assert(filepath) -- format it first filepath = vformat(filepath) -- replace all local data, count, errors = io.gsub(filepath, pattern, replace) if not data then raise(errors) end -- ok return data, count end -- open file function sandbox_io.open(filepath, mode) -- check assert(filepath) -- format it first filepath = vformat(filepath) -- open it local file, errors = io.open(filepath, mode) if not file then raise(errors) end -- replace print with vformat file.print = sandbox_io._print file.printf = sandbox_io._printf -- add writef with format file.writef = sandbox_io._writef -- ok? return file end -- load object from the given file function sandbox_io.load(filepath) -- check assert(filepath) -- format it first filepath = vformat(filepath) -- done local result, errors = io.load(filepath) if not result then raise(errors) end -- ok return result end -- save object the the given filepath function sandbox_io.save(filepath, object) -- check assert(filepath) -- format it first filepath = vformat(filepath) -- done local ok, errors = io.save(filepath, object) if not ok then raise(errors) end end -- read all data from file function sandbox_io.readfile(filepath) -- check assert(filepath) -- format it first filepath = vformat(filepath) -- done local result, errors = io.readfile(filepath) if not result then raise(errors) end -- ok return result end -- write all data to file function sandbox_io.writefile(filepath, data) -- check assert(filepath) -- format it first filepath = vformat(filepath) -- done local ok, errors = io.writefile(filepath, data) if not ok then raise(errors) end end -- print line to file function sandbox_io.print(filepath, ...) sandbox_io.writefile(filepath, vformat(...) .. "\n") end -- print data to file function sandbox_io.printf(filepath, ...) sandbox_io.writefile(filepath, vformat(...)) end -- printf file function sandbox_io._printf(self, ...) -- check assert(self._FILE) -- printf it return self._FILE:write(vformat(...)) end -- writef file function sandbox_io._writef(self, ...) -- check assert(self._FILE) -- printf it return self._FILE:write(string.format(...)) end -- cat the given file function sandbox_io.cat(filepath, linecount) -- check assert(filepath) -- format it first filepath = vformat(filepath) -- cat it io.cat(filepath, linecount) end -- tail the given file function sandbox_io.tail(filepath, linecount) -- check assert(filepath) -- format it first filepath = vformat(filepath) -- tail it io.tail(filepath, linecount) end -- return module return sandbox_io
Hooks:PostHook(UpgradesTweakData, "init", "TIER5_UpgradesTweakData_init", function(self) self.values.player.heisters_never_die = { 50, 100 } self:add_definition_v2("player", "heisters_never_die", {1, 2}) self.values.player.dodge_T5_boost = { 0.4, 0.6 } self:add_definition_v2("player", "dodge_T5_boost", {1, 2}) self.values.player.dodge_T5_boost = { { armor = 0.25, stamina = 20 }, { armor = 0.50, stamina = 40 }, } self:add_definition_v2("player", "dodge_T5_boost", {1, 2}) end)
local awful = require('awful') local wibox = require('wibox') local beautiful = require('beautiful') local gears = require('gears') local helpers = require('helpers') local bling = require('bling') local dpi = require('beautiful').xresources.apply_dpi beautiful.init(gears.filesystem.get_configuration_dir() .. "deftheme.lua") local img = wibox.widget { image = gears.surface.load_uncached(gears.filesystem.get_configuration_dir() .. "icons/no_music.png"), resize = true, forced_height = dpi(100), widget = wibox.widget.imagebox } local title_widget = wibox.widget { font = "Sarasa Fixed K 15", markup = 'No Title', align = 'center', valign = 'center', ellipsize = 'middle', forced_height = dpi(25), widget = wibox.widget.textbox } local artist_widget = wibox.widget { font = "Sarasa Fixed K 10", markup = 'No Artist', align = 'center', valign = 'center', ellipsize = 'center', forced_height = dpi(20), widget = wibox.widget.textbox } bling.signal.playerctl.enable() awesome.connect_signal("bling::playerctl::title_artist_album", function(title, artist, image) title_widget:set_markup_silently('<span foreground="#FADE8F">' .. title .. '</span>') artist_widget:set_markup_silently('<span foreground="#E75B81">' .. artist .. '</span>') img:set_image(gears.surface.load_uncached(image)) end) local play_cmd = function() awful.spawn.with_shell("playerctl play-pause") end local prev_cmd = function() awful.spawn.with_shell("playerctl previous") end local next_cmd = function() awful.spawn.with_shell("playerctl next") end local play_icon = wibox.widget { markup = helpers.colorize_text("", beautiful.xcolor4), font = beautiful.icon_font_name .. "15", align = 'center', valign = 'center', widget = wibox.widget.textbox() } local play_sym = wibox.widget { play_icon, forced_height = dpi(15), forced_width = dpi(15), widget = wibox.container.background } awesome.connect_signal("bling::playerctl::status", function(playing) if playing then play_icon.markup = helpers.colorize_text("", beautiful.xcolor4) else play_icon.markup = helpers.colorize_text("", beautiful.xcolor4) end end) play_sym:buttons(gears.table.join( awful.button({}, 1, function() play_cmd() end))) play_sym:connect_signal("mouse::enter", function() play_icon.markup = helpers.colorize_text(play_icon.text, beautiful.xforeground) end) play_sym:connect_signal("mouse::leave", function() play_icon.markup = helpers.colorize_text(play_icon.text, beautiful.xcolor4) end) local prev_icon = wibox.widget { markup = helpers.colorize_text("", beautiful.xcolor4), font = beautiful.icon_font_name .. "15", align = 'center', valign = 'center', widget = wibox.widget.textbox() } local prev_sym = wibox.widget { prev_icon, forced_height = dpi(15), forced_width = dpi(15), widget = wibox.container.background } prev_sym:buttons(gears.table.join( awful.button({}, 1, function() prev_cmd() end))) prev_sym:connect_signal("mouse::enter", function() prev_icon.markup = helpers.colorize_text(prev_icon.text, beautiful.xforeground) end) prev_sym:connect_signal("mouse::leave", function() prev_icon.markup = helpers.colorize_text(prev_icon.text, beautiful.xcolor4) end) local next_icon = wibox.widget { markup = helpers.colorize_text("", beautiful.xcolor4), font = beautiful.icon_font_name .. "15", align = 'center', valign = 'center', widget = wibox.widget.textbox() } local next_sym = wibox.widget { next_icon, forced_height = dpi(15), forced_width = dpi(15), widget = wibox.container.background } next_sym:buttons(gears.table.join( awful.button({}, 1, function() next_cmd() end))) next_sym:connect_signal("mouse::enter", function() next_icon.markup = helpers.colorize_text(next_icon.text, beautiful.xforeground) end) next_sym:connect_signal("mouse::leave", function() next_icon.markup = helpers.colorize_text(next_icon.text, beautiful.xcolor4) end) local slider = wibox.widget { forced_height = dpi(10), bar_shape = gears.shape.rounded_bar, shape = gears.shape.rounded_bar, background_color = beautiful.stats_bg_color, color = "#AE9895", value = 25, max_value = 100, widget = wibox.widget.progressbar } awesome.connect_signal("bling::playerctl::position", function(pos, length) slider.value = (pos/length) * 100 end) local player = wibox.widget { layout = wibox.layout.align.horizontal, expand = "none", nil, { { { { { title_widget, artist_widget, layout = wibox.layout.fixed.vertical }, top = 10, left = 25, right = 25, widget = wibox.container.margin }, { nil, { { prev_sym, play_sym, next_sym, spacing = dpi(40), layout = wibox.layout.fixed.horizontal }, top = dpi(10), left = 25, right = 25, widget = wibox.container.margin }, nil, expand = "none", layout = wibox.layout.align.horizontal }, layout = wibox.layout.align.vertical }, top = dpi(0), bottom = dpi(10), widget = wibox.container.margin }, forced_height = 100, layout = wibox.layout.align.vertical }, nil } return { player, shape = helpers.rrect(beautiful.client_radius), widget = wibox.container.background }
---------------------------------------------------------------------------------------------------- -- The next group of functions extends the default lua table implementation -- to include some additional useful methods. -- -- @author Makoto -- @release V3.0.0 ---------------------------------------------------------------------------------------------------- local table = setmetatable({}, {__index = _G.table}) --- -- Returns the position found by searching for a matching value from an array. -- @param array table array -- @param value Search value -- @return the index number if the value is found, or 0 if not found. function table.indexOf(array, value) for i, v in ipairs(array) do if v == value then return i end end return 0 end --- -- Same as indexOf, only for key values (slower) -- Author:Nenad Katic function table.keyOf(src, val) for k, v in pairs(src) do if v == val then return k end end return nil end function table.isEmpty(t) if next(t) == nil then return true end return false end --- -- Copy the table shallowly (i.e. do not create recursive copies of values) -- @param src copy -- @param dest (option)Destination -- @return dest function table.copy(src, dest) dest = dest or {} for i, v in pairs(src) do dest[i] = v end return dest end --- -- Copy the table deeply (i.e. create recursive copies of values) -- @param src copy -- @param dest (option)Destination -- @return dest function table.deepCopy(src, dest) dest = dest or {} for k, v in pairs(src) do if type(v) == "table" then dest[k] = table.deepCopy(v) else dest[k] = v end end return dest end --- -- Adds an element to the table if and only if the value did not already exist. -- @param t table -- @param o element -- @return If it already exists, returns false. If it did not previously exist, returns true. function table.insertIfAbsent(t, o) if table.indexOf(t, o) > 0 then return false end t[#t + 1] = o return true end --- -- Adds an element to the table. -- @param t table -- @param o element -- @return true function table.insertElement(t, o) t[#t + 1] = o return true end --- -- Removes the element from the table. -- If the element existed, then returns its index value. -- If the element did not previously exist, then return 0. -- @param t table -- @param o element -- @return index function table.removeElement(t, o) local i = table.indexOf(t, o) if i > 0 then table.remove(t, i) end return i end --- -- Inserts a given value through BinaryInsert into the table sorted by [, comp]. -- -- If 'comp' is given, then it must be a function that receives -- two table elements, and returns true when the first is less -- than the second, e.g. comp = function(a, b) return a > b end, -- will give a sorted table, with the biggest value on position 1. -- [, comp] behaves as in table.sort(table, value [, comp]) -- returns the index where 'value' was inserted -- -- @param t table -- @param value value -- @param fcomp Compare function -- @return index where 'value' was inserted function table.bininsert(t, value, fcomp) -- Initialise compare function local fcomp = fcomp or function( a,b ) return a < b end -- Initialise numbers local iStart,iEnd,iMid,iState = 1,#t,1,0 -- Get insert position while iStart <= iEnd do -- calculate middle iMid = math.floor( (iStart+iEnd)/2 ) -- compare if fcomp( value,t[iMid] ) then iEnd,iState = iMid - 1,0 else iStart,iState = iMid + 1,1 end end table.insert( t,(iMid+iState),value ) return (iMid+iState) end return table
rocketturret = class:new() function rocketturret:init(x, y, r) --PHYSICS STUFF self.x = x-1 self.y = y-15/16 self.width = 1 self.height = 15/16 self.static = true self.active = true self.category = 5 self.dir = "left" self.mask = {true} self.autodelete = true --IMAGE STUFF self.drawable = true self.graphic = rocketturretimage self.quad = rocketturretquad[1] self.offsetX = 8 self.offsetY = 1 self.quadcenterX = 8 self.quadcenterY = 8 self.state = "normal" self.statequadi = 1 self.timer = 0 self.animationdirection = "right" self.r = r self.on = true self.outtable = {} self.targetangle = false self.targeted = false self.angle = false self.firing = false end local function unwrap(a) while a < 0 do a = a + (math.pi*2) end while a > (math.pi*2) do a = a - (math.pi*2) end return a end local function angles(a1, a2) local a1 = unwrap(a1)-math.pi local a2 = unwrap(a2)-math.pi local diff = a1-a2 if math.abs(diff) < math.pi then return a1 > a2, diff else return diff < 0, diff end end function rocketturret:update(dt) if self.on and not (#objects["glados"] > 0 and not neurotoxin) and (not self.targeted) and (not self.firing) then local closestplayer = 1 --find closest player for i = 2, players do local v = objects["player"][i] if math.abs(self.x - v.x) < math.abs(self.x - objects["player"][closestplayer].x) then closestplayer = i end end local v = objects["player"][closestplayer] if v.x+v.width/2 > self.x+self.width/2 then self.animationdirection = "left" self.dir = "right" else self.animationdirection = "right" self.dir = "left" end local x1, y1, x2, y2 = (self.x+self.width/2), (self.y+self.height/2-3/16), (v.x+v.width/2), (v.y+v.height/2) x2, y2 = x1+15, y1+(v.y-self.y) if v.x+v.width/2 < self.x+self.width/2 then x2 = x1-15 end self.targetangle = math.atan2(x1-x2, y1-y2) end --buggy if self.angle then local pos, diff = angles(self.targetangle, self.angle) if pos then self.angle = self.angle + math.abs(diff)*3*dt else self.angle = self.angle - math.abs(diff)*3*dt end elseif self.targetangle then self.angle = self.targetangle end if self.state == "ready" then self.statequadi = 2 elseif self.state == "launch" then self.statequadi = 3 elseif not self.on or (#objects["glados"] > 0 and not neurotoxin) then self.statequadi = 4 else self.statequadi = 1 end self.quad = rocketturretquad[self.statequadi] if (neurotoxin or #objects["glados"] == 0) and self.on and self.x > xscroll-1 and self.x < xscroll+width then if self.state == "normal" then self.timer = self.timer + dt if self.timer > 3 then self.state = "ready" self.timer = 0 local closestplayer = 1 --find closest player for i = 2, players do local v = objects["player"][i] if math.abs(self.x - v.x) < math.abs(self.x - objects["player"][closestplayer].x) then closestplayer = i end end self.targeted = objects["player"][closestplayer].y + -self.y end elseif self.state == "ready" then self.timer = self.timer + dt if self.timer > 0.8 then playsound(boomsound) self:launchrocket() self.state = "launch" self.timer = 0 self.targeted = false end elseif self.state == "launch" then self.timer = self.timer + dt if self.timer > 0.2 and (not self.firing) then self.state = "normal" self.timer = 0 end end end end function rocketturret:draw() if self.angle and (neurotoxin or #objects["glados"] == 0) and self.on and self.x > xscroll-1 and self.x < xscroll+width then local a = unwrap(self.angle) if a > math.pi*1.5 then --weird bugs galore a = a-math.pi*2 end local cox, coy, side, tend, x, y = traceline(self.x+self.width/2, self.y+self.height/2-3/16, a) if x then --check if current block is a portal local opp = "left" if a > math.pi*1.25 then elseif a > math.pi*.75 then opp = "up" elseif a > math.pi*0.25 then opp = "right" elseif a > -math.pi*.25 then opp = "down" end local portalx, portaly, portalfacing, infacing = getPortal(cox, coy, opp) -- if portalx or portaly then -- love.graphics.setColor(101, 0, 0, 150) -- else love.graphics.setColor(101, 228, 255, 150) -- end love.graphics.setLineWidth(2) love.graphics.setLineStyle("rough") love.graphics.line(((self.x+self.width/2)-xscroll)*16*scale, ((self.y+self.height/2-3/16)-yscroll-8/16)*16*scale, (x-xscroll)*16*scale, (y-yscroll-8/16)*16*scale) if portalx then --let's just brute force this local diffx, diffy = x-(cox-1), y-(coy-1) local angle = a if portalfacing == "left" then portalx = portalx - 1 portaly = portaly - 1 if infacing == "left" then angle = math.pi*2-a elseif infacing == "right" then portalx = portalx - 1 end elseif portalfacing == "right" then portalx = portalx - 1 portaly = portaly - 1 if infacing == "left" then portalx = portalx + 1 elseif infacing == "right" then angle = math.pi*2-a end elseif portalfacing == "down" then if infacing == "left" then diffx = -diffy diffy = 0 angle = math.pi*1.5+a elseif infacing == "right" then portalx = portalx - 1 diffx = diffy diffy = 0 angle = math.pi*.5+a end elseif portalfacing == "up" then portaly = portaly - 1 portalx = portalx - 1 if infacing == "left" then diffx = diffy diffy = 0 angle = math.pi*.5+a elseif infacing == "right" then portalx = portalx + 1 diffx = -diffy diffy = 0 angle = math.pi*1.5+a end end if angle > math.pi*1.5 then --weird bugs galore angle = angle-math.pi*2 end if infacing ~= "up" or infacing ~= "down" then local cox, coy, side, tend, x, y = traceline(portalx+diffx, portaly+diffy, angle) love.graphics.setColor(101, 228, 255, 150) love.graphics.line(((portalx+diffx)-xscroll)*16*scale, ((portaly+diffy)-yscroll-8/16)*16*scale, (x-xscroll)*16*scale, (y-yscroll-8/16)*16*scale) end end end end end function rocketturret:launchrocket() local obj if self.dir == "right" then obj = turretrocket:new(self.x+12/16, self.y+1/16, self.targeted, self.dir) else obj = turretrocket:new(self.x, self.y+1/16, self.targeted, self.dir) end obj.parent = self self.firing = true table.insert(objects["turretrocket"], obj) end function rocketturret:input(t) if t == "on" then self.on = true elseif t == "off" then self.on = false elseif t == "toggle" then self.on = not self.on end end function rocketturret:link() if #self.r > 2 then for j, w in pairs(outputs) do for i, v in pairs(objects[w]) do if tonumber(self.r[4]) == v.cox and tonumber(self.r[5]) == v.coy then v:addoutput(self) self.on = false end end end end end function rocketturret:leftcollide(a, b) end function rocketturret:rightcollide(a, b) end function rocketturret:passivecollide(a, b) end function rocketturret:globalcollide(a, b) end function rocketturret:floorcollide(a, b) end function rocketturret:ceilcollide(a, b) end function rocketturret:rocketready() self.firing = false end -------ROCKET TURRET BULLET THING------ turretrocket = class:new() function turretrocket:init(x, y, gg, dir) --PHYSICS STUFF self.x = x self.y = y self.speedy = gg if dir == "right" then self.speedx = 15 else self.speedx = -15 end self.width = 5/16 self.height = 5/16 self.static = false self.active = true self.category = 4 self.gravity = 0 self.rotation = 0 self.dir = dir self.mask = {true, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, true, true, false, true, true, true, false, true} self.autodelete = true self.emancipatecheck = true --IMAGE STUFF self.drawable = true self.graphic = turretrocketimage self.quad = turretrocketquad[1] self.offsetX = 3 self.offsetY = 5 self.quadcenterX = 3 self.quadcenterY = 3 if self.dir == "right" then self.animationdirection = "left" else self.animationdirection = "right" end end function turretrocket:update(dt) if self.rotation ~= 0 then if math.abs(math.abs(self.rotation)-math.pi/2) < 0.1 then self.rotation = -math.pi/2 else self.rotation = 0 end end if self.delete then self:callback() return true end if self.speedx > 0 then self.animationdirection = "left" else self.animationdirection = "right" end end function turretrocket:hit(a, b, gelside) if a == "tile" then local x, y = b.cox, b.coy if gelside and map[x][y]["gels"] and map[x][y]["gels"][gelside] == 1 then if gelside == "left" or gelside == "right" then self.speedx = -self.speedx else self.speedy = -self.speedy end return else local ti = 1 if ismaptile(x, y) and map[x][y][1] then ti = map[x][y][1] end if (tilequads[ti].coinblock or (tilequads[ti].debris and blockdebrisquads[tilequads[ti].debris])) then -- hard block destroyblock(x, y) else hitblock(x, y, {size=2}) end self.delete = true end elseif a == "glados" then self.delete = true else if mariohammerkill[a] then b:shotted("right") if a ~= "bowser" then addpoints(firepoints[a], self.x, self.y) end end self.delete = true playsound(blockhitsound) end self:callback() makepoof(self.x+self.width/2, self.y+self.height/2, "poof") end function turretrocket:emancipate() if not self.delete then table.insert(emancipateanimations, emancipateanimation:new(self.x, self.y, self.width, self.height, self.graphic, self.quad, self.speedx, self.speedy, self.rotation, self.offsetX, self.offsetY, self.quadcenterX, self.quadcenterY)) self.delete = true self.drawable = false self:callback() end end function turretrocket:globalcollide(a, b) return false end function turretrocket:leftcollide(a, b) if self:globalcollide(a, b) then return false end self:hit(a, b, "right") return false end function turretrocket:rightcollide(a, b) if self:globalcollide(a, b) then return false end self:hit(a, b, "left") return false end function turretrocket:floorcollide(a, b) if self:globalcollide(a, b) then return false end self:hit(a, b, "top") return false end function turretrocket:ceilcollide(a, b) if self:globalcollide(a, b) then return false end self:hit(a, b, "bottom") return false end function turretrocket:passivecollide(a, b) if self:globalcollide(a, b) then return false end self:hit(a, b) return false end function turretrocket:autodeleted() self:callback() end function turretrocket:callback() if self.parent and not self.calledback then self.parent:rocketready() self.calledback = true end end
local TableSetup = [[ local action = {} for i = 1, cases do action[-i] = function() return i end end local function default() end ]] local cases = { TableIndex = { setup = TableSetup, action = ";(action[case] or default)()", }, MetaTable = { setup = TableSetup..[[ setmetatable(action, {__index = function () return default end}) ]], action = "action[case]()", }, NestedIf = { setup = [[ local action = {[=[ local case = ... if case==-1 then ]=]} for i = 2, cases do action[i] = "elseif case==-"..i.." then return "..i end action[cases+1] = "end" action = assert(load(table.concat(action, "\n"), "t")) ]], action = "action(case)", }, NumericFor = { setup = [[ local function action(case) for i = -1, -cases, -1 do if case == i then return -i end end end ]], action = "action(case)", }, } for id, case in pairs(cases) do case.test = [[ local case = -(1+_ITERATION_%range) ]]..case.action..[[ ]] end return { id = "action", name = "Action Switch", warmup = true, repeats = 2e5, variables = { cases = { min=4,max=20 }, range = { min=8,max=40 }, }, cases = cases }, { id = "returnval", name = "Value Selection", repeats = 1e4, nocollect = true, setup = [[ local allchars = {} for i=0, 255 do allchars[i] = string.char(i) end local kind ]], cases = { LogicOr = { test = [[ for _, char in ipairs(allchars) do if char == 'a' or char == 'b' or char == 'c' or char == 'd' or char == 'e' or char == 'f' or char == 'g' or char == 'h' or char == 'i' or char == 'j' or char == 'k' or char == 'l' or char == 'm' or char == 'n' or char == 'o' or char == 'p' or char == 'q' or char == 'r' or char == 's' or char == 't' or char == 'u' or char == 'v' or char == 'w' or char == 'x' or char == 'y' or char == 'z' then kind = "lower" elseif char == '0' or char == '1' or char == '2' or char == '3' or char == '4' or char == '5' or char == '6' or char == '7' or char == '8' or char == '9' then kind = "digit" end kind = "unknown" end ]], }, NestedIf = { test = [[ for _, char in ipairs(allchars) do if char == 'a' then kind = "lower" elseif char == 'b' then kind = "lower" elseif char == 'c' then kind = "lower" elseif char == 'd' then kind = "lower" elseif char == 'e' then kind = "lower" elseif char == 'f' then kind = "lower" elseif char == 'g' then kind = "lower" elseif char == 'h' then kind = "lower" elseif char == 'i' then kind = "lower" elseif char == 'j' then kind = "lower" elseif char == 'k' then kind = "lower" elseif char == 'l' then kind = "lower" elseif char == 'm' then kind = "lower" elseif char == 'n' then kind = "lower" elseif char == 'o' then kind = "lower" elseif char == 'p' then kind = "lower" elseif char == 'q' then kind = "lower" elseif char == 'r' then kind = "lower" elseif char == 's' then kind = "lower" elseif char == 't' then kind = "lower" elseif char == 'u' then kind = "lower" elseif char == 'v' then kind = "lower" elseif char == 'w' then kind = "lower" elseif char == 'x' then kind = "lower" elseif char == 'y' then kind = "lower" elseif char == 'z' then kind = "lower" elseif char == '0' then kind = "digit" elseif char == '1' then kind = "digit" elseif char == '2' then kind = "digit" elseif char == '3' then kind = "digit" elseif char == '4' then kind = "digit" elseif char == '5' then kind = "digit" elseif char == '6' then kind = "digit" elseif char == '7' then kind = "digit" elseif char == '8' then kind = "digit" elseif char == '9' then kind = "digit" end kind = "unknown" end ]], }, TableIndex = { setup = [[ local allchars = {} for i=0, 255 do allchars[i] = string.char(i) end local kind local KindOf = { ['a'] = "lower", ['b'] = "lower", ['c'] = "lower", ['d'] = "lower", ['e'] = "lower", ['f'] = "lower", ['g'] = "lower", ['h'] = "lower", ['i'] = "lower", ['j'] = "lower", ['k'] = "lower", ['l'] = "lower", ['m'] = "lower", ['n'] = "lower", ['o'] = "lower", ['p'] = "lower", ['q'] = "lower", ['r'] = "lower", ['s'] = "lower", ['t'] = "lower", ['u'] = "lower", ['v'] = "lower", ['w'] = "lower", ['x'] = "lower", ['y'] = "lower", ['z'] = "lower", ['0'] = "digit", ['1'] = "digit", ['2'] = "digit", ['3'] = "digit", ['4'] = "digit", ['5'] = "digit", ['6'] = "digit", ['7'] = "digit", ['8'] = "digit", ['9'] = "digit", } ]], test = [[ for _, char in ipairs(allchars) do kind = KindOf[tag] or "unknown" end ]], }, } }
-- Prosody IM -- Copyright (C) 2012-2014 Florian Zeitz -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- -- luacheck: ignore 431/log module:set_global(); local new_uuid = require "util.uuid".generate; local formdecode = require "util.http".formdecode; local add_task = require "util.timer".add_task; local add_filter = require "util.filters".add_filter; local sha1 = require "util.hashes".sha1; local base64 = require "util.encodings".base64.encode; local st = require "util.stanza"; local parse_xml = require "util.xml".parse; local contains_token = require "util.http".contains_token; local portmanager = require "core.portmanager"; local sm_destroy_session = require"core.sessionmanager".destroy_session; local log = module._log; local websocket_frames = require"net.websocket.frames"; local parse_frame = websocket_frames.parse; local build_frame = websocket_frames.build; local build_close = websocket_frames.build_close; local parse_close = websocket_frames.parse_close; local t_concat = table.concat; local stream_close_timeout = module:get_option_number("c2s_close_timeout", 5); local consider_websocket_secure = module:get_option_boolean("consider_websocket_secure"); local cross_domain = module:get_option_set("cross_domain_websocket", {}); if cross_domain:contains("*") or cross_domain:contains(true) then cross_domain = true; end local function check_origin(origin) if cross_domain == true then return true; end return cross_domain:contains(origin); end local xmlns_framing = "urn:ietf:params:xml:ns:xmpp-framing"; local xmlns_streams = "http://etherx.jabber.org/streams"; local xmlns_client = "jabber:client"; local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'}; module:depends("c2s") local sessions = module:shared("c2s/sessions"); local c2s_listener = portmanager.get_service("c2s").listener; --- Session methods local function session_open_stream(session, from, to) local attr = { xmlns = xmlns_framing, ["xml:lang"] = "en", version = "1.0", id = session.streamid or "", from = from or session.host, to = to, }; if session.stream_attrs then session:stream_attrs(from, to, attr) end session.send(st.stanza("open", attr)); end local function session_close(session, reason) local log = session.log or log; if session.conn then if session.notopen then session:open_stream(); end if reason then -- nil == no err, initiated by us, false == initiated by client local stream_error = st.stanza("stream:error"); if type(reason) == "string" then -- assume stream error stream_error:tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }); elseif type(reason) == "table" then if reason.condition then stream_error:tag(reason.condition, stream_xmlns_attr):up(); if reason.text then stream_error:tag("text", stream_xmlns_attr):text(reason.text):up(); end if reason.extra then stream_error:add_child(reason.extra); end elseif reason.name then -- a stanza stream_error = reason; end end log("debug", "Disconnecting client, <stream:error> is: %s", tostring(stream_error)); session.send(stream_error); end session.send(st.stanza("close", { xmlns = xmlns_framing })); function session.send() return false; end -- luacheck: ignore 422/reason -- FIXME reason should be handled in common place local reason = (reason and (reason.name or reason.text or reason.condition)) or reason; session.log("debug", "c2s stream for %s closed: %s", session.full_jid or ("<"..session.ip..">"), reason or "session closed"); -- Authenticated incoming stream may still be sending us stanzas, so wait for </stream:stream> from remote local conn = session.conn; if reason == nil and not session.notopen and session.type == "c2s" then -- Grace time to process data from authenticated cleanly-closed stream add_task(stream_close_timeout, function () if not session.destroyed then session.log("warn", "Failed to receive a stream close response, closing connection anyway..."); sm_destroy_session(session, reason); conn:write(build_close(1000, "Stream closed")); conn:close(); end end); else sm_destroy_session(session, reason); conn:write(build_close(1000, "Stream closed")); conn:close(); end end end --- Filters local function filter_open_close(data) if not data:find(xmlns_framing, 1, true) then return data; end local oc = parse_xml(data); if not oc then return data; end if oc.attr.xmlns ~= xmlns_framing then return data; end if oc.name == "close" then return "</stream:stream>"; end if oc.name == "open" then oc.name = "stream:stream"; oc.attr.xmlns = nil; oc.attr["xmlns:stream"] = xmlns_streams; return oc:top_tag(); end return data; end function handle_request(event) local request, response = event.request, event.response; local conn = response.conn; local query = request.url.query; -- end create session conn.starttls = false; -- Prevent mod_tls from believing starttls can be done if not request.headers.sec_websocket_key then response.headers.content_type = "text/html"; return [[<!DOCTYPE html><html><head><title>Websocket</title></head><body> <p>It works! Now point your WebSocket client to this URL to connect to Prosody.</p> </body></html>]]; end local wants_xmpp = contains_token(request.headers.sec_websocket_protocol or "", "xmpp"); if not wants_xmpp then module:log("debug", "Client didn't want to talk XMPP, list of protocols was %s", request.headers.sec_websocket_protocol or "(empty)"); return 501; end if not check_origin(request.headers.origin or "") then module:log("debug", "Origin %s is not allowed by 'cross_domain_websocket' [ %s ]", request.headers.origin or "(missing header)", cross_domain); return 403; end local function websocket_close(code, message) conn:write(build_close(code, message)); conn:close(); end local dataBuffer; local function handle_frame(frame) local opcode = frame.opcode; local length = frame.length; module:log("debug", "Websocket received frame: opcode=%0x, %i bytes", frame.opcode, #frame.data); -- Error cases if frame.RSV1 or frame.RSV2 or frame.RSV3 then -- Reserved bits non zero websocket_close(1002, "Reserved bits not zero"); return false; end if opcode == 0x8 then -- close frame if length == 1 then websocket_close(1002, "Close frame with payload, but too short for status code"); return false; elseif length >= 2 then local status_code = parse_close(frame.data) if status_code < 1000 then websocket_close(1002, "Closed with invalid status code"); return false; elseif ((status_code > 1003 and status_code < 1007) or status_code > 1011) and status_code < 3000 then websocket_close(1002, "Closed with reserved status code"); return false; end end end if opcode >= 0x8 then if length > 125 then -- Control frame with too much payload websocket_close(1002, "Payload too large"); return false; end if not frame.FIN then -- Fragmented control frame websocket_close(1002, "Fragmented control frame"); return false; end end if (opcode > 0x2 and opcode < 0x8) or (opcode > 0xA) then websocket_close(1002, "Reserved opcode"); return false; end if opcode == 0x0 and not dataBuffer then websocket_close(1002, "Unexpected continuation frame"); return false; end if (opcode == 0x1 or opcode == 0x2) and dataBuffer then websocket_close(1002, "Continuation frame expected"); return false; end -- Valid cases if opcode == 0x0 then -- Continuation frame dataBuffer[#dataBuffer+1] = frame.data; elseif opcode == 0x1 then -- Text frame dataBuffer = {frame.data}; elseif opcode == 0x2 then -- Binary frame websocket_close(1003, "Only text frames are supported"); return; elseif opcode == 0x8 then -- Close request websocket_close(1000, "Goodbye"); return; elseif opcode == 0x9 then -- Ping frame frame.opcode = 0xA; frame.MASK = false; -- Clients send masked frames, servers don't, see #1484 conn:write(build_frame(frame)); return ""; elseif opcode == 0xA then -- Pong frame, MAY be sent unsolicited, eg as keepalive return ""; else log("warn", "Received frame with unsupported opcode %i", opcode); return ""; end if frame.FIN then local data = t_concat(dataBuffer, ""); dataBuffer = nil; return data; end return ""; end conn:setlistener(c2s_listener); c2s_listener.onconnect(conn); local session = sessions[conn]; -- Use upstream IP if a HTTP proxy was used -- See mod_http and #540 session.ip = request.ip; session.secure = consider_websocket_secure or session.secure; session.websocket_request = request; session.open_stream = session_open_stream; session.close = session_close; local params = formdecode(query); session["auth_token"] = query and params.token or nil; local frameBuffer = ""; add_filter(session, "bytes/in", function(data) local cache = {}; frameBuffer = frameBuffer .. data; local frame, length = parse_frame(frameBuffer); while frame do frameBuffer = frameBuffer:sub(length + 1); local result = handle_frame(frame); if not result then return; end cache[#cache+1] = filter_open_close(result); frame, length = parse_frame(frameBuffer); end return t_concat(cache, ""); end); add_filter(session, "stanzas/out", function(stanza) stanza = st.clone(stanza); local attr = stanza.attr; attr.xmlns = attr.xmlns or xmlns_client; if stanza.name:find("^stream:") then attr["xmlns:stream"] = attr["xmlns:stream"] or xmlns_streams; end return stanza; end, -1000); add_filter(session, "bytes/out", function(data) return build_frame({ FIN = true, opcode = 0x01, data = tostring(data)}); end); response.status_code = 101; response.headers.upgrade = "websocket"; response.headers.connection = "Upgrade"; response.headers.sec_webSocket_accept = base64(sha1(request.headers.sec_websocket_key .. "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")); response.headers.sec_webSocket_protocol = "xmpp"; session.log("debug", "Sending WebSocket handshake"); return ""; end local function keepalive(event) local session = event.session; if session.open_stream == session_open_stream then return session.conn:write(build_frame({ opcode = 0x9, FIN = true })); end end module:hook("c2s-read-timeout", keepalive, -0.9); module:depends("http"); module:provides("http", { name = "websocket"; default_path = "xmpp-websocket"; route = { ["GET"] = handle_request; ["GET /"] = handle_request; }; }); function module.add_host(module) module:hook("c2s-read-timeout", keepalive, -0.9); if cross_domain ~= true then local url = require "socket.url"; local ws_url = module:http_url("websocket", "xmpp-websocket"); local url_components = url.parse(ws_url); -- The 'Origin' consists of the base URL without path url_components.path = nil; local this_origin = url.build(url_components); local local_cross_domain = module:get_option_set("cross_domain_websocket", { this_origin }); if local_cross_domain:contains(true) then module:log("error", "cross_domain_websocket = true only works in the global section"); return; end -- Don't add / remove something added by another host -- This might be weird with random load order local_cross_domain:exclude(cross_domain); cross_domain:include(local_cross_domain); module:log("debug", "cross_domain = %s", tostring(cross_domain)); function module.unload() cross_domain:exclude(local_cross_domain); end end end
local kong_auth_pep_common = require "gluu.kong-common" local path_wildcard_tree = require"gluu.path-wildcard-tree" local pl_tablex = require "pl.tablex" local logic = require "rucciva.json_logic" local array_mt = {} --- Utility function for json logic. Check value is array or not -- @param tab: Any type of data local function is_array(tab) return getmetatable(tab) == array_mt end --- Utility function for json logic. Set metadata to array value -- @param tab: Array values local function mark_as_array(tab) return setmetatable(tab, array_mt) end --- Apply json logic -- @param lgc: Json rules -- @param data: Data which you want to validate with lgc -- @param option: Extra options example: is_array local function logic_apply(lgc, data, options) if type(options) ~= 'table' or options == nil then options = {} end options.is_array = is_array options.mark_as_array = mark_as_array return logic.apply(lgc, data, options) end local hooks = {} local function strip_method(path) end function hooks.no_token_protected_path() -- no pending cache state at the moment, may use PDK directly kong.response.exit(401, { message = "Missed OAuth token" }) end function hooks.build_cache_key(method, path, _, scopes) -- we may disable access cache just by returning nothing -- in this case proxy will always check the protection document against scopes -- IMO (altexy) cache will be faster then verify protection document every time path = path or "" local t = { method, ":", path, } for i = 1, #scopes do t[#t + 1] = ":" t[#t + 1] = scopes[i] end return table.concat(t) end local function match_named_captures(scope_captures, path_captures) local ret = false local no_named_capture = true for k,v in pairs(scope_captures) do if type(k) == "string" then local pc_number = k:match("^PC([1-9])$") if pc_number then no_named_capture = false kong.log.debug("PC", pc_number, "= [", v, "], path capture = [",path_captures[tonumber(pc_number)], "]") if path_captures[tonumber(pc_number)] ~= v then return false, no_named_capture end ret = true, no_named_capture end end end kong.log.debug("match_named_captures() return ", ret) return ret, no_named_capture end --- Check JSON expression -- @param self: Kong plugin object instance -- @param conf -- @param protected_path -- @param method -- @param scope_expression: example: { rule = { ["or"] = { { var = 0 }, { var = 1 }, { ["!"] = { { var = 2 } } } } }, data = { "admin", "hrr", "employee" } } -- @param token_scopes: Array of scopes example: { "admin", "hrr" } -- @return true or false function hooks.is_access_granted(self, conf, protected_path, method, scope_expression, token_scopes, _, path_captures) scope_expression = scope_expression or {} local data = {} local scope_expression_data = scope_expression.data for i = 1, #scope_expression_data do local scope = scope_expression_data[i] kong.log.debug(scope) if scope:sub(1,1) == "^" then local matched = false for k = 1, #token_scopes do kong.log.debug(token_scopes[k]) local scope_captures, err = ngx.re.match(token_scopes[k], scope, "jo") if not scope_captures and err then kong.log.error(err) break end if scope_captures then kong.log.debug("scope_captures") if not path_captures then kong.log.debug("no path captures, match") matched = true break end -- the whole match is always returned as scope_captures[0] -- the captures are returned as scope_captures[1] ... scope_captures[N] -- if no capturing group(s) present we use whole match, otherwise only captures if not scope_captures[1] then kong.log.debug("no scope captures") scope_captures[1] = scope_captures[0] end -- make it Lua array, index from 1 scope_captures[0] = nil local named_capture_matched, no_named_capture = match_named_captures(scope_captures, path_captures) if named_capture_matched or no_named_capture then matched = true break end end end kong.log.debug("data[#data + 1]=", matched) data[#data + 1] = matched else data[#data + 1] = pl_tablex.find(token_scopes, scope) and true or false end end local result = logic_apply(scope_expression.rule, mark_as_array(data)) return result end function hooks.get_scope_expression(config) return config.oauth_scope_expression end return function(self, conf) kong_auth_pep_common.access_pep_handler(self, conf, hooks) end
local list = { { val = 1 }, { val = 4 }, { val = 2 } } table.sort( list, function( item1, item2 ) return item1.val > item2.val end ) for index, val in pairs( list ) do print( index, val.val ) end
local modemPer = peripheral.find("modem") modemPer.closeAll() --close previously open channels modemPer.open(0) modemPer.open(1) while true do local cases = { [87] = "forward", -- w [83] = "back", -- s [65] = "turnLeft", -- a [68] = "turnRight", -- d [81] = "up", -- q [90] = "down", -- z [69] = "dig", -- e [82] = "digUp", -- r [70] = "digDown",-- f [71] = "exit" -- g } local key = cases[({os.pullEvent("key")})[2]] modemPer.transmit(0,1,key) if key == "exit" then print("bye") break end end modemPer.closeAll() --close previously open channels
-- this file is a very simple lua file function test() if true then io.write("test\n") end end for i=1,10 do io.write("test"..i.."\n") end io.stdout:flush()
--[[ Copyright (c) 2021-2022 Jason Morley, Tom Sutcliffe Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] _ENV = module() local fmt = string.format local sibosyscalls codes_er5 = { [0x00] = "Addr", [0x01] = "Asc", [0x02] = "IllegalFuncOpCode", [0x03] = "Count", [0x04] = "Day", [0x05] = "Dow", [0x06] = "Eof", [0x07] = "Err", [0x08] = "Exist", [0x09] = "Find", [0x0A] = "Get", [0x0B] = "Ioa", [0x0C] = "Iow", [0x0D] = "IoOpen", [0x0E] = "IoWrite", [0x0F] = "IoRead", [0x10] = "IoClose", [0x11] = "IoWait", [0x12] = "Hour", [0x13] = "Key", [0x14] = "Len", [0x15] = "Loc", [0x16] = "Minute", [0x17] = "Month", [0x18] = "PeekB", [0x19] = "PeekW", [0x1A] = "Pos", [0x1B] = "IllegalFuncOpCode", [0x1C] = "Second", [0x1D] = "IllegalFuncOpCode", [0x1E] = "Year", [0x1F] = "SAddr", [0x20] = "Week", [0x21] = "IoSeek", [0x22] = "Kmod", [0x23] = "KeyA", [0x24] = "KeyC", [0x25] = "IoOpenUnique", [0x26] = "gCreate", [0x27] = "gCreateBit", [0x28] = "gLoadBit", [0x29] = "gLoadFont", [0x2A] = "gRank", [0x2B] = "gIdentity", [0x2C] = "gX", [0x2D] = "gY", [0x2E] = "gWidth", [0x2F] = "gHeight", [0x30] = "gOriginX", [0x31] = "gOriginY", [0x32] = "gTWidth", [0x33] = "gPrintClip", [0x34] = "TestEvent", [0x35] = "IllegalFuncOpCode", [0x36] = "Menu", [0x37] = "Dialog", [0x38] = "Alert", [0x39] = "gCreateEnhanced", [0x3A] = "MenuWithMemory", [0x3B] = "IllegalFuncOpCode", [0x3C] = "IllegalFuncOpCode", [0x3D] = "IllegalFuncOpCode", [0x3E] = "IllegalFuncOpCode", [0x3F] = "IllegalFuncOpCode", [0x40] = "Days", [0x41] = "IAbs", [0x42] = "IntLong", [0x43] = "PeekL", [0x44] = "Space", [0x45] = "DateToSecs", [0x46] = "IllegalFuncOpCode", [0x47] = "IllegalFuncOpCode", [0x48] = "IllegalFuncOpCode", [0x49] = "IllegalFuncOpCode", [0x4A] = "IllegalFuncOpCode", [0x4B] = "Alloc", [0x4C] = "ReAlloc", [0x4D] = "AdjustAlloc", [0x4E] = "LenAlloc", [0x4F] = "Ioc", [0x50] = "Uadd", [0x51] = "Usub", [0x52] = "IoCancel", [0x53] = "IllegalFuncOpCode", [0x54] = "FindField", [0x55] = "Bookmark", [0x56] = "GetEventC", [0x57] = "InTrans", [0x58] = "mPopup", [0x59] = "IllegalFuncOpCode", [0x5A] = "IllegalFuncOpCode", [0x5B] = "IllegalFuncOpCode", [0x5C] = "IllegalFuncOpCode", [0x5D] = "IllegalFuncOpCode", [0x5E] = "IllegalFuncOpCode", [0x5F] = "IllegalFuncOpCode", [0x60] = "IllegalFuncOpCode", [0x61] = "IllegalFuncOpCode", [0x62] = "IllegalFuncOpCode", [0x63] = "IllegalFuncOpCode", [0x64] = "IllegalFuncOpCode", [0x65] = "IllegalFuncOpCode", [0x66] = "IllegalFuncOpCode", [0x67] = "IllegalFuncOpCode", [0x68] = "IllegalFuncOpCode", [0x69] = "IllegalFuncOpCode", [0x6A] = "IllegalFuncOpCode", [0x6B] = "IllegalFuncOpCode", [0x6C] = "IllegalFuncOpCode", [0x6D] = "IllegalFuncOpCode", [0x6E] = "IllegalFuncOpCode", [0x6F] = "IllegalFuncOpCode", [0x70] = "IllegalFuncOpCode", [0x71] = "IllegalFuncOpCode", [0x72] = "IllegalFuncOpCode", [0x73] = "IllegalFuncOpCode", [0x74] = "IllegalFuncOpCode", [0x75] = "IllegalFuncOpCode", [0x76] = "IllegalFuncOpCode", [0x77] = "IllegalFuncOpCode", [0x78] = "IllegalFuncOpCode", [0x79] = "IllegalFuncOpCode", [0x7A] = "IllegalFuncOpCode", [0x7B] = "IllegalFuncOpCode", [0x7C] = "IllegalFuncOpCode", [0x7D] = "IllegalFuncOpCode", [0x7E] = "IllegalFuncOpCode", [0x7F] = "IllegalFuncOpCode", [0x80] = "Abs", [0x81] = "ACos", [0x82] = "ASin", [0x83] = "ATan", [0x84] = "Cos", [0x85] = "Deg", [0x86] = "Exp", [0x87] = "Flt", [0x88] = "Intf", [0x89] = "Ln", [0x8A] = "Log", [0x8B] = "PeekF", [0x8C] = "Pi", [0x8D] = "Rad", [0x8E] = "Rnd", [0x8F] = "Sin", [0x90] = "Sqr", [0x91] = "Tan", [0x92] = "Val", [0x93] = "Max", [0x94] = "Mean", [0x95] = "Min", [0x96] = "Std", [0x97] = "Sum", [0x98] = "Var", [0x99] = "Eval", [0x9A] = "IllegalFuncOpCode", [0x9B] = "IllegalFuncOpCode", [0x9C] = "IllegalFuncOpCode", [0x9D] = "IllegalFuncOpCode", [0x9E] = "IllegalFuncOpCode", [0x9F] = "IllegalFuncOpCode", [0xA0] = "IllegalFuncOpCode", [0xA1] = "IllegalFuncOpCode", [0xA2] = "IllegalFuncOpCode", [0xA3] = "IllegalFuncOpCode", [0xA4] = "IllegalFuncOpCode", [0xA5] = "IllegalFuncOpCode", [0xA6] = "IllegalFuncOpCode", [0xA7] = "IllegalFuncOpCode", [0xA8] = "IllegalFuncOpCode", [0xA9] = "IllegalFuncOpCode", [0xAA] = "IllegalFuncOpCode", [0xAB] = "IllegalFuncOpCode", [0xAC] = "IllegalFuncOpCode", [0xAD] = "IllegalFuncOpCode", [0xAE] = "IllegalFuncOpCode", [0xAF] = "IllegalFuncOpCode", [0xB0] = "IllegalFuncOpCode", [0xB1] = "IllegalFuncOpCode", [0xB2] = "IllegalFuncOpCode", [0xB3] = "IllegalFuncOpCode", [0xB4] = "IllegalFuncOpCode", [0xB5] = "IllegalFuncOpCode", [0xB6] = "IllegalFuncOpCode", [0xB7] = "IllegalFuncOpCode", [0xB8] = "IllegalFuncOpCode", [0xB9] = "IllegalFuncOpCode", [0xBA] = "IllegalFuncOpCode", [0xBB] = "IllegalFuncOpCode", [0xBC] = "IllegalFuncOpCode", [0xBD] = "IllegalFuncOpCode", [0xBE] = "IllegalFuncOpCode", [0xBF] = "IllegalFuncOpCode", [0xC0] = "ChrStr", [0xC1] = "DatimStr", [0xC2] = "DayNameStr", [0xC3] = "DirStr", [0xC4] = "ErrStr", [0xC5] = "FixStr", [0xC6] = "GenStr", [0xC7] = "GetStr", [0xC8] = "HexStr", [0xC9] = "KeyStr", [0xCA] = "LeftStr", [0xCB] = "LowerStr", [0xCC] = "MidStr", [0xCD] = "MonthStr", [0xCE] = "NumStr", [0xCF] = "PeekStr", [0xD0] = "ReptStr", [0xD1] = "RightStr", [0xD2] = "SciStr", [0xD3] = "UpperStr", [0xD4] = "IllegalFuncOpCode", [0xD5] = "WCmd", [0xD6] = "CmdStr", [0xD7] = "ParseStr", [0xD8] = "ErrxStr", [0xD9] = "GetDocStr", [0xDA] = "Size", [0xDB] = "LocWithCase", [0xDC] = "gPixel", [0xDD] = "IllegalFuncOpCode", [0xDE] = "IllegalFuncOpCode", [0xDF] = "IllegalFuncOpCode", } codes_sibo = setmetatable({ [0x02] = "Call", [0x1D] = "Usr", [0x35] = "Os", [0xD9] = "IllegalFuncOpCode", [0xDA] = "IllegalFuncOpCode", [0xDB] = "IllegalFuncOpCode", [0xDC] = "IllegalFuncOpCode", }, { __index = codes_er5 }) local function numParams_dump(runtime) local numParams = runtime:IP8() return fmt(" numParams=%d", numParams) end function IP8_dump(runtime) local val = runtime:IP8() return fmt("%d (0x%02X)", val, val) end function Addr(stack, runtime) -- 0x00 local var = stack:pop() stack:push(var:addressOf()) end function IllegalFuncOpCode(stack, runtime) printf("Illegal func opcode at:\n%s\n", runtime:getOpoStacktrace()) error(KErrIllegal) end function Asc(stack, runtime) -- 0x01 local str = stack:pop() if #str == 0 then stack:push(0) else stack:push(string.byte(str)) end end function Call(stack, runtime) -- 0x02 (SIBO only) local numParams = runtime:IP8() local s, bx, cx, dx, si, di assert(numParams >= 1 and numParams <= 6, "Unexpected numParams in call!") if numParams == 6 then di = stack:pop() end if numParams >= 5 then si = stack:pop() end if numParams >= 4 then dx = stack:pop() end if numParams >= 3 then cx = stack:pop() end if numParams >= 2 then bx = stack:pop() end s = stack:pop() -- printf("CALL(0x%04X, %s, %s, %s, %s, %s)\n", s, bx, cx, dx, si, di) if sibosyscalls == nil then sibosyscalls = require("sibosyscalls") end local fn = s & 0x00FF local ax = s & 0xFF00 local params = { ax = ax, bx = bx or 0, cx = cx or 0, dx = dx or 0, si = si or 0, di = di or 0, } sibosyscalls.syscall(runtime, fn, params, params) -- printf("Call result = %x\n", params.ax) stack:push(params.ax) end Call_dump = numParams_dump function Count(stack, runtime) -- 0x03 local db = runtime:getDb() stack:push(db:getCount()) end function Day(stack, runtime) -- 0x04 stack:push(os.date("*t").day) end function Dow(stack, runtime) -- 0x05 local year = stack:pop() local month = stack:pop() local day = stack:pop() local t = runtime:iohandler().utctime({year = year, month = month, day = day}) -- Lua (and C) use 1 to mean Sunday, OPL 1 is Monday... local result = os.date("!*t", t).wday - 1 if result == 0 then result = 7 end stack:push(result) end function Eof(stack, runtime) -- 0x06 local db = runtime:getDb() stack:push(db:eof()) end function Err(stack, runtime) -- 0x07 stack:push(runtime:getLastError()) end function Exist(stack, runtime) -- 0x08 local path = stack:pop() stack:push(runtime:EXIST(path)) end function Find(stack, runtime) -- 0x09 unimplemented("fns.Find") end function Get(stack, runtime) -- 0x0A stack:push(runtime:GET()) end function Ioa(stack, runtime) -- 0x0B local b = runtime:addrFromInt(stack:pop()) local a = runtime:addrFromInt(stack:pop()) local stat = runtime:addrAsVariable(stack:pop(), DataTypes.EWord) local fn = stack:pop() local h = stack:pop() local err = runtime:IOA(h, fn, stat, a, b) stack:push(err) end function Iow(stack, runtime) -- 0x0C unimplemented("fns.Iow") end function IoOpen(stack, runtime) -- 0x0D local mode = stack:pop() local name = stack:pop() local handleVar = runtime:addrAsVariable(stack:pop(), DataTypes.EWord) local handle, err = runtime:IOOPEN(name, mode) if handle then handleVar(handle) stack:push(0) else handleVar(-1) -- Just in case stack:push(err) end end function IoWrite(stack, runtime) -- 0x0E local len = stack:pop() local addr = runtime:addrFromInt(stack:pop()) local h = stack:pop() local data = addr:read(len) local err = runtime:IOWRITE(h, data) stack:push(err) end function IoRead(stack, runtime) -- 0x0F local maxLen = stack:pop() local addr = runtime:addrFromInt(stack:pop()) local h = stack:pop() -- printf("IoRead maxLen=%d\n", maxLen) local data, err = runtime:IOREAD(h, maxLen) if data then -- printf("IoRead got %d bytes\n", #data) addr:write(data) end if err then stack:push(err) else stack:push(#data) end end function IoClose(stack, runtime) -- 0x10 stack:push(runtime:IOCLOSE(stack:pop())) end function IoWait(stack, runtime) -- 0x11 runtime:waitForAnyRequest() stack:push(0) end function Hour(stack, runtime) -- 0x12 stack:push(os.date("*t").hour) end function Key(stack, runtime) -- 0x13 stack:push(runtime:KEY()) end function Len(stack, runtime) -- 0x14 stack:push(#stack:pop()) end function Loc(stack, runtime) -- 0x15 local searchString = stack:pop():lower() local str = stack:pop():lower() local result = string.find(str, searchString, 1, true) or 0 stack:push(result) end function Minute(stack, runtime) -- 0x16 stack:push(os.date("*t").min) end function Month(stack, runtime) -- 0x17 stack:push(os.date("*t").month) end function PeekB(stack, runtime) -- 0x18 local addr = runtime:addrFromInt(stack:pop()) local data = addr:read(1) stack:push(string.unpack("B", data)) end function PeekW(stack, runtime) -- 0x19 local addr = runtime:addrFromInt(stack:pop()) local data = addr:read(2) stack:push(string.unpack("<i2", data)) end function Pos(stack, runtime) -- 0x1A local db = runtime:getDb() stack:push(db:getPos()) end function Second(stack, runtime) -- 0x1C stack:push(os.date("*t").sec) end function Usr(stack, runtime) -- 0x1D unimplemented("fns.Usr") end function Year(stack, runtime) -- 0x1E stack:push(os.date("*t").year) end function SAddr(stack, runtime) -- 0x1F local str = stack:pop() assert(str:type() == DataTypes.EString, "Bad variable type passed to SAddr") stack:push(str:addressOf()) end function Week(stack, runtime) -- 0x20 unimplemented("fns.Week") end function IoSeek(stack, runtime) -- 0x21 local offsetVar = runtime:addrAsVariable(stack:pop(), runtime:addressType()) local mode = stack:pop() local handle = stack:pop() local err, result = runtime:IOSEEK(handle, mode, offsetVar()) if result then offsetVar(result) end stack:push(err) end function Kmod(stack, runtime) -- 0x22 local modifiers = runtime:getResource("kmod") or 0 stack:push(modifiers) end function KeyA(stack, runtime) -- 0x23 unimplemented("fns.KeyA") end function KeyC(stack, runtime) -- 0x24 unimplemented("fns.KeyC") end function IoOpenUnique(stack, runtime) -- 0x25 local mode = stack:pop() local nameVar = runtime:addrAsVariable(stack:pop(), DataTypes.EString) local handleVar = runtime:addrAsVariable(stack:pop(), DataTypes.EWord) local handle, err, name = runtime:IOOPEN(nameVar(), mode) if handle then handleVar(handle) if name then nameVar(name) end stack:push(0) else handleVar(-1) -- Just in case stack:push(err) end end function gCreate(stack, runtime) -- 0x26 stack:push(KgCreate2GrayMode) gCreateEnhanced(stack, runtime) end function gCreateBit(stack, runtime) -- 0x27 local mode = 0 if runtime:IP8() == 3 then mode = stack:pop() end local w, h = stack:popXY() local id = runtime:gCREATEBIT(w, h, mode) stack:push(id) end gCreateBit_dump = IP8_dump function gLoadBit(stack, runtime) -- 0x28 local numParams = runtime:IP8() local write = 1 local idx = 0 if numParams > 2 then idx = stack:pop() end if numParams > 1 then write = stack:pop() end local path = stack:pop() local id = runtime:gLOADBIT(path, write ~= 0, idx) stack:push(id) end gLoadBit_dump = numParams_dump function gLoadFont(stack, runtime) -- 0x29 unimplemented("fns.gLoadFont") end function gRank(stack, runtime) -- 0x2A unimplemented("fns.gRank") end function gIdentity(stack, runtime) -- 0x2B stack:push(runtime:gIDENTITY()) end function gX(stack, runtime) -- 0x2C stack:push(runtime:gX()) end function gY(stack, runtime) -- 0x2D stack:push(runtime:gY()) end function gWidth(stack, runtime) -- 0x2E stack:push(runtime:gWIDTH()) end function gHeight(stack, runtime) -- 0x2F stack:push(runtime:gHEIGHT()) end function gOriginX(stack, runtime) -- 0x30 stack:push(runtime:gORIGINX()) end function gOriginY(stack, runtime) -- 0x31 stack:push(runtime:gORIGINY()) end function gTWidth(stack, runtime) -- 0x32 local width = runtime:gTWIDTH(stack:pop()) stack:push(width) end function gPrintClip(stack, runtime) -- 0x33 local width = stack:pop() local text = stack:pop() local numChars = runtime:gPRINTCLIP(text, width) stack:push(numChars) end function TestEvent(stack, runtime) -- 0x34 stack:push(runtime:iohandler().testEvent()) end local syscallPackFmt = "<I2I2I2I2I2I2" function Os(stack, runtime) -- 0x35 (SIBO only) local numParams = runtime:IP8() local addr2 if numParams == 3 then addr2 = runtime:addrFromInt(stack:pop()) end local addr1 = runtime:addrFromInt(stack:pop()) if not addr2 then addr2 = addr1 end local fn = stack:pop() if sibosyscalls == nil then sibosyscalls = require("sibosyscalls") end local params = {} params.ax, params.bx, params.cx, params.dx, params.si, params.di = string.unpack(syscallPackFmt, addr1:read(12)) local results = {} results.ax, results.bx, results.cx, results.dx, results.si, results.di = string.unpack(syscallPackFmt, addr2:read(12)) local flags = sibosyscalls.syscall(runtime, fn, params, results) addr2:write(string.pack(syscallPackFmt, results.ax, results.bx, results.cx, results.dx, results.si, results.di)) stack:push(flags) end Os_dump = numParams_dump function Menu(stack, runtime) -- 0x36 local menu = runtime:getMenu() runtime:setMenu(nil) local result if runtime:iohandler().menu then result = runtime:iohandler().menu(menu) else result = runtime:MENU(menu) end stack:push(result) end function Dialog(stack, runtime) -- 0x37 local dialog = runtime:getDialog() runtime:setDialog(nil) local varMap = {} -- maps dialog item to variable for _, item in ipairs(dialog.items) do if item.variable ~= nil then varMap[item] = item.variable item.variable = nil -- Don't expose this to iohandler end end local result = runtime:DIALOG(dialog) if result > 0 then -- Assign any variables eg `dCHOICE choice%` for item, var in pairs(varMap) do if item.value then -- Have to reconstruct type because item.value will always be a string -- (But the type of var() will still be correct) local isnum = type(var()) == "number" if isnum then item.value = tonumber(item.value) end var(item.value) end end end -- Be bug compatible with Psion 5 and return 0 if a negative-keycode or escape button was pressed if result < 0 or result == 27 then result = 0 end stack:push(result) end function Alert(stack, runtime) -- 0x38 local nargs = runtime:IP8() local line1, line2, but1, but2, but3 if nargs >= 5 then but3 = stack:pop() end if nargs >= 4 then but2 = stack:pop() end if nargs >= 3 then but1 = stack:pop() end if nargs >= 2 then line2 = stack:pop() end if nargs >= 1 then line1 = stack:pop() end local dlg = { title = "Information", flags = 0, xpos = 0, ypos = 0, items = { { type = dItemTypes.dTEXT, align = "center", value = line1, }, { type = dItemTypes.dTEXT, align = "center", value = line2 or "", } }, buttons = { { key = KKeyEsc, text = but1 or "Continue" }, }, } if but2 then table.insert(dlg.buttons, { key = KKeyEnter, text = but2 }) end if but3 then table.insert(dlg.buttons, 2, { key = KKeySpace, text = but3 }) end local key = runtime:DIALOG(dlg) local returnValues = { [KKeyEsc] = 1, [KKeyEnter] = 2, [KKeySpace] = 3, } local choice = assert(returnValues[key]) stack:push(choice) end Alert_dump = numParams_dump function gCreateEnhanced(stack, runtime) -- 0x39 local flags = stack:pop() local visible = stack:pop() local x, y, w, h = stack:popRect() -- printf("gCreate x=%d y=%d w=%d h=%d flags=%d", x, y, w, h, flags) local id = runtime:gCREATE(x, y, w, h, visible ~= 0, flags) -- printf(" -> %d\n", id) stack:push(id) end function MenuWithMemory(stack, runtime) -- 0x3A local var = runtime:addrAsVariable(stack:pop(), DataTypes.EWord) local menu = runtime:getMenu() runtime:setMenu(nil) menu.highlight = var() local selected, highlighted if runtime:iohandler().menu then selected, highlighted = runtime:iohandler().menu(menu) else selected, highlighted = runtime:MENU(menu) end if highlighted then var(highlighted) -- Update this end stack:push(selected) end function Days(stack, runtime) -- 0x37 local year = stack:pop() local month = stack:pop() local day = stack:pop() local t = runtime:iohandler().utctime({ year = year, month = month, day = day }) -- Result needs to be days since 1900. Who knows why since nothing else uses -- 1900 as its epoch. local epoch = runtime:iohandler().utctime({ year = 1900, month = 1, day = 1 }) t = (t - epoch) // (24 * 60 * 60) stack:push(t) end function IAbs(stack, runtime) -- 0x41 stack:push(math.abs(stack:pop())) end function roundTowardsZero(val) if val > 0 then return math.floor(val) else return math.ceil(val) end end function roundToNearest(val) local int, frac = math.modf(val) if math.abs(frac) >= 0.5 then int = int + (int < 0 and -1 or 1) end return int end function IntLong(stack, runtime) -- 0x42 local val = stack:pop() local result = roundTowardsZero(val) stack:push(result) end function PeekL(stack, runtime) -- 0x43 local addr = runtime:addrFromInt(stack:pop()) local data = addr:read(4) stack:push(string.unpack("<i4", data)) end function Space(stack, runtime) -- 0x44 unimplemented("fns.Space") end function DateToSecs(stack, runtime) -- 0x45 local seconds = stack:pop() local minutes = stack:pop() local hours = stack:pop() local day = stack:pop() local month = stack:pop() local year = stack:pop() local t, err = runtime:iohandler().utctime({ year = year, month = month, day = day, hour = hours, min = minutes, sec = seconds }) -- printf("DATETOSECS(year=%d, month=%d, day=%d, h=%d, m=%d, s=%d) = %s\n", year, month, day, hours, minutes, seconds, t) assert(t, err) stack:push(toint32(t)) end function Alloc(stack, runtime) -- 0x4B local sz = stack:pop() assert(sz > 0, "Allocation size must be positive") local result = runtime:realloc(0, sz) stack:push(result) end function ReAlloc(stack, runtime) -- 0x4C local sz = stack:pop() local addr = runtime:addrFromInt(stack:pop()) local result = runtime:realloc(addr:intValue(), sz) stack:push(result) end function AdjustAlloc(stack, runtime) -- 0x4D unimplemented("fns.AdjustAlloc") end function LenAlloc(stack, runtime) -- 0x4E unimplemented("fns.LenAlloc") end function Ioc(stack, runtime) -- 0x4F local numParams = runtime:IP8() local a, b if numParams >= 5 then b = runtime:addrFromInt(stack:pop()) end if numParams >= 4 then a = runtime:addrFromInt(stack:pop()) end local stat = runtime:addrAsVariable(stack:pop(), DataTypes.EWord) local fn = stack:pop() local h = stack:pop() runtime:IOC(h, fn, stat, a, b) stack:push(0) end Ioc_dump = numParams_dump function Uadd(stack, runtime) -- 0x50 local right = stack:pop() local left = stack:pop() if type(left) == "table" or type(right) == "table" then -- Assume one is an AddrSlice and just run with it (it shouln't be, -- unless SETFLAGS(1) is in effect, but there are programs which use -- UADD on addresses regardless of that setting...) stack:push(left + right) else local result = touint16(left) + touint16(right) stack:push(string.unpack("<i2", string.pack("<I2", result))) end end function Usub(stack, runtime) -- 0x51 local right = touint16(stack:pop()) local left = touint16(stack:pop()) stack:push(string.unpack("<i2", string.pack("<I2", left - right))) end function IoCancel(stack, runtime) -- 0x52 stack:push(runtime:IOCANCEL(stack:pop())) end function FindField(stack, runtime) -- 0x54 unimplemented("fns.FindField") end function Bookmark(stack, runtime) -- 0x55 unimplemented("fns.Bookmark") end function GetEventC(stack, runtime) -- 0x56 local stat = stack:pop():asVariable(DataTypes.EWord) runtime:iohandler().cancelRequest(stat) -- Unlike IoCancel, GetEventC should do its own waitForRequest. runtime:waitForRequest(stat) stack:push(0) -- why these return something, who knows end function InTrans(stack, runtime) -- 0x57 local db = self:getDb() stack:push(db:inTransaction()) end function mPopup(stack, runtime) -- 0x58 local numParams = runtime:IP8() local items = {} while numParams > 3 do local key = stack:pop() local text = stack:pop() table.insert(items, 1, { key = key, text = text }) numParams = numParams - 2 end local pos = stack:pop() local x, y = stack:popXY() local result = runtime:mPOPUP(x, y, pos, items) stack:push(result) end mPopup_dump = numParams_dump function Abs(stack, runtime) -- 0x80 stack:push(math.abs(stack:pop())) end function ACos(stack, runtime) -- 0x81 stack:push(math.acos(stack:pop())) end function ASin(stack, runtime) -- 0x82 stack:push(math.asin(stack:pop())) end function ATan(stack, runtime) -- 0x83 stack:push(math.atan(stack:pop())) end function Cos(stack, runtime) -- 0x84 stack:push(math.cos(stack:pop())) end function Deg(stack, runtime) -- 0x85 stack:push(math.deg(stack:pop())) end function Exp(stack, runtime) -- 0x86 stack:push(math.exp(stack:pop())) end function Flt(stack, runtime) -- 0x87 -- Nothing needed, numbers are numbers end function Intf(stack, runtime) -- 0x88 return IntLong(stack, runtime) -- Same difference end function Ln(stack, runtime) -- 0x89 stack:push(math.log(stack:pop())) end function Log(stack, runtime) -- 0x8A stack:push(math.log(stack:pop(), 10)) end function PeekF(stack, runtime) -- 0x8B local addr = stack:pop() local data = addr:read(8) stack:push(string.unpack("<d", data)) end function Pi(stack, runtime) -- 0x8C stack:push(math.pi) end function Rad(stack, runtime) -- 0x8D stack:push(math.rad(stack:pop())) end function Rnd(stack, runtime) -- 0x8E stack:push(math.random()) end function Sin(stack, runtime) -- 0x8F stack:push(math.sin(stack:pop())) end function Sqr(stack, runtime) -- 0x90 stack:push(math.sqrt(stack:pop())) end function Tan(stack, runtime) -- 0x91 stack:push(math.tan(stack:pop())) end function Val(stack, runtime) -- 0x92 local str = stack:pop() -- printf("Val('%s')\n", hexEscape(str)) local result = tonumber(str) if not result then printf("Bad Val('%s')\n", hexEscape(str)) error(KErrInvalidArgs) end stack:push(result) end local function valList(stack, runtime) local numParams = runtime:IP8() local vals = {} if numParams == 0 then -- It's an array, represented as ArrayDirectLeftSideFloat(1) -- so we can safely turn back to an array variable local numVals = stack:pop() local var = stack:pop() local array = var:addressOf():asVariable(var:type() | 0x80) for i = 1, numVals do vals[i] = array[i]() end else while numParams > 0 do table.insert(vals, stack:pop()) numParams = numParams - 1 end end return vals end function Max(stack, runtime) -- 0x93 stack:push(math.max(table.unpack(valList(stack, runtime)))) end Max_dump = numParams_dump function Mean(stack, runtime) -- 0x94 unimplemented("fns.Mean") end function Min(stack, runtime) -- 0x95 stack:push(math.min(table.unpack(valList(stack, runtime)))) end Min_dump = numParams_dump function Std(stack, runtime) -- 0x96 unimplemented("fns.Std") end function Sum(stack, runtime) -- 0x97 unimplemented("fns.Sum") end function Var(stack, runtime) -- 0x98 unimplemented("fns.Var") end function Eval(stack, runtime) -- 0x99 unimplemented("fns.Eval") end function ChrStr(stack) -- 0xC0 -- Some apps try passing raw keycodes like 4104 (cursor key) to this fn, -- hence masking them with 0xFF which seems to do the expected thing... return stack:push(string.char(stack:pop() & 0xFF)) end function DatimStr(stack, runtime) -- 0xC1 -- system time -> Fri 16 Oct 1992 16:25:30 stack:push(os.date("%a %d %b %Y %T")) end function DayNameStr(stack, runtime) -- 0xC2 -- 1st Jan 1970 was a Thursday, and dayname=1 means Monday, so stack:push(os.date("!%a", 86400 * (3 + stack:pop()))) end function DirStr(stack, runtime) -- 0xC3 local path = stack:pop() -- dir requires state to be tracked, so push it into runtime local result = runtime:dir(path) -- printf('DIR$("%s") -> %s\n', path, result) stack:push(result) end function ErrStr(stack, runtime) -- 0xC4 local err = stack:pop() stack:push(Errors[err] or fmt("Unknown error %d", err)) end function FixStr(stack, runtime) -- 0xC5 local width = stack:pop() local decimals = stack:pop() local val = stack:pop() local result = string.format("%0."..decimals.."f", val) if width < 0 then width = -width result = string.rep(" ", width - #result)..result end if #result > width then result = string.rep("*", width) end stack:push(result) end function GenStr(stack, runtime) -- 0xC6 local width = stack:pop() local val = stack:pop() local result = fmt("%g", val) if width < 0 then width = -width result = string.rep(" ", width - #result)..result end if #result > width then result = string.rep("*", width) end stack:push(result) end function GetStr(stack, runtime) -- 0xC7 stack:push(runtime:GETSTR()) end function HexStr(stack, runtime) -- 0xC8 stack:push(fmt("%X", stack:pop() & 0xFFFFFFFF)) end function KeyStr(stack, runtime) -- 0xC9 stack:push(runtime:KEYSTR()) end function LeftStr(stack, runtime) -- 0xCA local numChars = stack:pop() assert(numChars >= 0, KErrInvalidArgs) local str = stack:pop() stack:push(string.sub(str, 1, numChars)) end function LowerStr(stack, runtime) -- 0xCB stack:push(stack:pop():lower()) end function MidStr(stack, runtime) -- 0xCC local len = stack:pop() local offset = stack:pop() local str = stack:pop() assert(offset >= 1, KErrInvalidArgs) assert(len >= 0, KErrInvalidArgs) local result = str:sub(offset, offset + len - 1) -- printf("MID$('%s', %d, %d)='%s'\n", str, offset, len, result) stack:push(result) end local months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" } function MonthStr(stack, runtime) -- 0xCD stack:push(assert(months[stack:pop()], KErrInvalidArgs)) end function NumStr(stack, runtime) -- 0xCE local width = stack:pop() local val = stack:pop() local intVal = roundToNearest(val) -- printf("NumStr(%s, %d) intval=%d", val, width, intVal) local result if width < 0 then width = -width result = fmt("%"..tostring(width).."d", intVal) else result = tostring(intVal) end if #result > width then result = string.rep("*", width) end -- printf(" -> '%s'\n", result) stack:push(result) end function PeekStr(stack, runtime) -- 0xCF unimplemented("fns.PeekStr") end function ReptStr(stack, runtime) -- 0xD0 local reps = stack:pop() local str = stack:pop() stack:push(string.rep(str, reps)) end function RightStr(stack, runtime) -- 0xD1 local numChars = stack:pop() assert(numChars >= 0, KErrInvalidArgs) local str = stack:pop() if numChars == 0 then stack:push("") else stack:push(string.sub(str, -numChars)) end end function SciStr(stack, runtime) -- 0xD2 unimplemented("fns.SciStr") end function UpperStr(stack, runtime) -- 0xD3 stack:push(stack:pop():upper()) end function WCmd(stack, runtime) -- 0xD5 local result = runtime:getResource("GETCMD") runtime:setResource("GETCMD", nil) stack:push(result or "") end function CmdStr(stack, runtime) -- 0xD6 local x = stack:pop() if x == 1 then stack:push(runtime:getPath()) elseif x == 2 then local path = runtime:getPath() path = oplpath.join(oplpath.dirname(path), "SomeDoc.Wat") stack:push(path) elseif x == 3 then stack:push("R") else error("unhandled CMD$ param "..tostring(x)) end end function ParseStr(stack, runtime) -- 0xD7 local offsetsArrayAddr = stack:pop() local rel = stack:pop() local f = stack:pop() -- Wow this is a fun API -- printf("Parse(%s, %s)\n", f, rel) rel = oplpath.abs(rel, runtime:getCwd()) local _, fext = oplpath.splitext(f) local _, relext = oplpath.splitext(rel) f = oplpath.abs(f, rel) if #fext == 0 and #relext > 0 then -- f is expected to inherit rel's extension f = f .. relext end -- Once f is complete, parse it to fill in offsetsArrayAddr local base, name = oplpath.split(f) local start, _ = oplpath.splitext(f) local nameNoExt, ext = oplpath.splitext(name) local nameHasWildcard = nameNoExt:match("%*") and 1 or 0 local extHasWildcard = ext:match("%*") and 2 or 0 local offsets = { 1, 1, 3, -- Start of path will always be after the C: 1 + #f - #name, 1 + #start, nameHasWildcard | extHasWildcard, } offsetsArrayAddr:writeArray(offsets, DataTypes.EWord) stack:push(f) end function ErrxStr(stack, runtime) -- 0xD8 local _, desc = runtime:getLastError() stack:push(desc) end function gPixel(stack, runtime) -- 0xDC unimplemented("fns.gPixel") end function LocWithCase(stack, runtime) -- 0xDB unimplemented("fns.LocWithCase") end function Size(stack, runtime) -- 0xDA unimplemented("fns.Size") end function GetDocStr(stack, runtime) -- 0xD9 unimplemented("fns.GetDocStr") end return _ENV
#! /usr/bin/env lua -- Default colors to use when writing the merged values -- they have to be valid html color codes as used inside the <font> tag local default_color_a = "white" local default_color_b = "yellow" -- Utility to covert from a srt timestamp in the format "00:00:00,000" to a number function str_timestamp_to_seconds( timestamp ) hours, minutes, seconds, milliseconds = string.match( timestamp, "(%d+):(%d+):(%d+),(%d+)") hours = tonumber(hours) * 3600 minutes = tonumber(minutes) * 60 seconds = tonumber(seconds) milliseconds = tonumber(milliseconds) * 0.001 return hours + minutes + seconds + milliseconds end -- Utility to covert from a number in seconds to an srt timestamp in the format "00:00:00,000" function seconds_to_str_timestamp( seconds ) local total_seconds, fractinal_part = math.modf( tonumber(seconds) ) local total_hours = math.floor(total_seconds / 3600) local total_minutes = math.floor(total_seconds / 60) % 60 total_seconds = total_seconds % 60 return string.format("%02.f:%02.f:%02.f,%03.f", total_hours, total_minutes, total_seconds, fractinal_part * 1000 ) end -- Tiny utility function to trim a string function trim(s) return (s:gsub("^%s*(.-)%s*$", "%1")) end -- Generate an subtitle entry with times and text. Trnslated inserted to be used later on -- It takes timestamps in both formats function generate_entry( in_start_time, in_end_time, in_text ) local insert_start_time = 0 local insert_end_time = 0 if type(in_start_time) == "number" then insert_start_time = in_start_time else insert_start_time = str_timestamp_to_seconds(in_start_time) end if type(in_end_time) == "number" then insert_end_time = in_end_time else insert_end_time = str_timestamp_to_seconds(in_end_time) end return { start_time=insert_start_time, end_time=insert_end_time, text=in_text, translated={} } end -- Main loop to open an SRT file and return a table with all the elements from the file -- generate_entry is used for every block created function import_srt( filename ) local srts = {} local file,error = io.open(filename, "r") if not err then local line_type = "index" local last_index = -1 local current_text = "" local current_index = 0 local current_start_time = nil local current_end_time = nil while true do local line = file:read() if line == nil then break end -- first read the index if line_type == "index" then last_index = current_index trimmed_line = trim(line) current_index = tonumber(trimmed_line) line_type = "time" current_text = "" -- then get the time interval elseif line_type == "time" then current_start_time, current_end_time = string.match( line, "(%d+:%d+:%d+,%d+) --.* (%d+:%d+:%d+,%d+)") line_type = "text" -- and finally get all the lines of text elseif line_type == "text" then -- until we get an empty line, in this case we restart local trimmed_text = trim(string.gsub(line, "\n", "")) if trimmed_text == "" then line_type = "index" table.insert(srts, generate_entry(current_start_time, current_end_time, current_text ) ) else if current_text == "" then current_text = trimmed_text else current_text = current_text .. " " .. trimmed_text end end end end file:close() print("Imported " .. tostring(#srts) .. " blocks from \"" .. tostring(filename) .. "\"") else print("Error: Can't import file \"" .. tostring(filename) .. "\" for writing!") end return srts end -- Check whether two time intervals overlaps -- Epsilon used to make every range a bit more 'fat' to help overlapping function do_intervals_overlap( start_time_a, end_time_a, start_time_b, end_time_b, epsilon ) return ((start_time_b - epsilon < end_time_a + epsilon ) and (end_time_b + epsilon > start_time_a - epsilon)) or ((start_time_a - epsilon < end_time_b + epsilon ) and (end_time_a + epsilon > start_time_b - epsilon)) end -- Extract the concatenated string of all the texts from srt using indexes function extract_text_from_indexes( srt, indexes ) local final_text = "" if srt ~= nil then for k,v in pairs(indexes) do if final_text == "" then final_text = srt[v]["text"] else final_text = final_text .. " " .. srt[v]["text"] end end end return final_text end -- Given indexes return the minimum start time and maximum end time from the blocks in srt function extract_start_end_time_from_indexes( srt, indexes ) local start_time = 0.0 local end_time = 0.0 if srt ~= nil then for k,v in pairs(indexes) do local current_start_time = srt[v]["start_time"] local current_end_time = srt[v]["end_time"] if start_time == 0.0 or current_start_time < start_time then start_time = current_start_time end if end_time == 0.0 or current_end_time > end_time then end_time = current_end_time end end end return start_time, end_time end -- Merge two strings and create a valid html string with the two coloured text one after each other function merge_srt_texts( text_a, text_b, color_a, color_b ) local selected_color_a = tostring(color_a or default_color_a) local selected_color_b = tostring(color_b or default_color_b) return string.format("<font color=\"%s\">%s</font><br><font color=\"%s\">%s</font>", selected_color_a, text_a, selected_color_b, text_b ) end -- Given two tables with the blocks read from the two srt file return a unique table with the new merged srt blocks -- The returned element has the same structure as the two inputs function merge_srts( srt_a, srt_b ) local srts = {} local error = 0.0 local last_previous_overlap = 0 local inserted_index = 0 local overlaps = { } -- First create a table with all the overlaps -- Each overlaps has entries with indexes from A 'srt_a_indexes' and B 'srt_b_indexes' for ka,va in pairs(srt_a) do local current_index = tonumber(ka) local current_overlaps = {} local removed_previous = false for kb,vb in pairs(srt_b) do if do_intervals_overlap( va["start_time"], va["end_time"], vb["start_time"], vb["end_time"], error ) then local curret_overlap_index = tonumber( kb ) table.insert(current_overlaps, curret_overlap_index) last_previous_overlap = curret_overlap_index if removed_previous == false and #current_overlaps == 2 then table.remove(current_overlaps, 1 ) removed_previous = true end end end local insert_in_open_block = false if inserted_index > 0 then for k,v in pairs(overlaps[inserted_index]["srt_b_indexes"]) do if v == last_previous_overlap then insert_in_open_block = true break end end end if insert_in_open_block then table.insert( overlaps[inserted_index]["srt_a_indexes"], current_index ) else table.insert( overlaps, { srt_a_indexes={ current_index }, srt_b_indexes=current_overlaps } ) inserted_index = inserted_index + 1 end end -- generate final block from overlaps for k,v in pairs(overlaps) do local srt_a_indexes = v["srt_a_indexes"] local srt_b_indexes = v["srt_b_indexes"] local start_time, end_time = extract_start_end_time_from_indexes( srt_a, srt_a_indexes ) local text_a = extract_text_from_indexes( srt_a, srt_a_indexes ) local text_b = extract_text_from_indexes( srt_b, srt_b_indexes ) table.insert(srts, generate_entry(start_time, end_time, merge_srt_texts( text_a, text_b ) ) ) end return srts end -- Writes srt data to a file function write_srt( filename, srt ) if srt ~= nil then local file = io.open(filename, "w") if file ~= nil then for k,v in pairs(srt) do file:write(string.format( "%s\n", tostring(k))) local start_time = seconds_to_str_timestamp(v["start_time"]) local end_time = seconds_to_str_timestamp(v["end_time"]) file:write(string.format( "%s --> %s\n", start_time, end_time)) file:write(string.format( "%s\n\n", v["text"] )) end file:close() print("Written " .. tostring(#srt) .. " blocks to \"" .. tostring(filename) .. "\"") else print("Error: Can't open file \"" .. tostring(filename) .. "\" for writing!") end else print("Error: Nothing to write in the output srt file!") end end -- Check if running as library or as a program if pcall(debug.getlocal, 4, 1) then print("You are using " .. arg[0] .. " as a library") else local num_args = #arg if num_args >= 3 or num_args <= 5 then default_color_a = arg[4] or default_color_a default_color_b = arg[5] or default_color_b write_srt( arg[3], merge_srts( import_srt(arg[1]), import_srt(arg[2]) ) ) else print( "Usage: " .. arg[0] .. " <input srt file 1> <input srt file 2> <output srt file> [html color code 1] [html color code 2]") end end
function P8INT:REBOOT_OUTLET(outletNumber) local uri = P8INT:GET_MATRIX_URL() .. "/power/reboot/" .. outletNumber C4:urlGet(uri) end
DEFINE_BASECLASS( "player_default" ) local PLAYER = {} -- -- See gamemodes/base/player_class/player_default.lua for all overridable variables -- PLAYER.DisplayName = "Prop" PLAYER.WalkSpeed = 222 PLAYER.RunSpeed = 222 PLAYER.CanUseFlashlight = false PLAYER.UseVMHands = false PLAYER.AvoidPlayers = false PLAYER.TeammateNoCollide = false PLAYER.MaxHealth = 100 PLAYER.DuckSpeed = 0.1 PLAYER.UnDuckSpeed = 0.1 PLAYER.lastTaunt = 0.0 function PLAYER:Loadout() self.Player:RemoveAllAmmo() end function PLAYER:SetupDataTables() self.Player:NetworkVar( "Entity", 0, "Prop" ); end player_manager.RegisterClass( "player_prop", PLAYER, "player_default" )
-- =========================================================================== -- Base File -- =========================================================================== include("UnitFlagManager"); -- =========================================================================== -- Cached Base Functions -- =========================================================================== BASE_CQUI_SetColor = UnitFlag.SetColor; BASE_CQUI_UpdateStats = UnitFlag.UpdateStats; BASE_CQUI_OnUnitSelectionChanged = OnUnitSelectionChanged; BASE_CQUI_OnPlayerTurnActivated = OnPlayerTurnActivated; BASE_CQUI_OnUnitPromotionChanged = OnUnitPromotionChanged; BASE_CQUI_UpdateFlagType = UnitFlag.UpdateFlagType; -- =========================================================================== -- CQUI Members -- =========================================================================== local CQUI_ShowingPath = nil; --unitID for the unit whose path is currently being shown. nil for no unit local CQUI_SelectionMade = false; local CQUI_ShowPaths = true; --Toggle for showing the paths local CQUI_IsFlagHover = false; -- if the path is the flag us currently hover or not --Hides any currently drawn paths. function CQUI_HidePath() if CQUI_ShowPaths and CQUI_IsFlagHover then LuaEvents.CQUI_clearUnitPath(); CQUI_IsFlagHover = false; end end function CQUI_OnSettingsUpdate() CQUI_HidePath(); CQUI_ShowPaths = GameConfiguration.GetValue("CQUI_ShowUnitPaths"); end function CQUI_Refresh() -- AZURENCY : update the stats of the flags on refresh local unitList = Players[Game.GetLocalPlayer()]:GetUnits(); if unitList ~= nil then for _,pUnit in unitList:Members() do local eUnitID = pUnit:GetID(); local eOwner = pUnit:GetOwner(); local pFlag = GetUnitFlag( eOwner, eUnitID ); if pFlag ~= nil then pFlag:UpdateStats(); end end end end function CQUI_OnUnitFlagPointerEntered(playerID:number, unitID:number) if CQUI_ShowPaths and not CQUI_IsFlagHover then if not CQUI_SelectionMade then LuaEvents.CQUI_showUnitPath(true, unitID); end CQUI_IsFlagHover = true; end end function CQUI_OnUnitFlagPointerExited(playerID:number, unitID:number) if CQUI_ShowPaths and CQUI_IsFlagHover then if not CQUI_SelectionMade then LuaEvents.CQUI_clearUnitPath(); end CQUI_IsFlagHover = false; end end -- =========================================================================== -- CQUI modified UnitFlag.SetColor functiton -- Enemy unit flags are red-tinted when at war with you -- =========================================================================== function UnitFlag.SetColor( self ) BASE_CQUI_SetColor(self) local instance:table = self.m_Instance; instance.FlagBaseDarken:SetHide(true); -- War Check if Game.GetLocalPlayer() > -1 then local pUnit : table = self:GetUnit(); local localPlayer = Players[Game.GetLocalPlayer()]; local ownerPlayer = pUnit:GetOwner(); --instance.FlagBaseDarken:SetHide(false); local isAtWar = localPlayer:GetDiplomacy():IsAtWarWith( ownerPlayer ); local CQUI_isBarb = Players[ownerPlayer]:IsBarbarian(); --pUnit:GetBarbarianTribeIndex() ~= -1 if(isAtWar and (not CQUI_isBarb)) then instance.FlagBaseDarken:SetColor( UI.GetColorValue(255,0,0,255) ); instance.FlagBaseDarken:SetHide(false); end end end -- =========================================================================== -- CQUI modified UnitFlag.UpdateFlagType functiton -- Set the right texture for the FlagBaseDarken used on enemy unit during war -- =========================================================================== function UnitFlag.UpdateFlagType( self ) BASE_CQUI_UpdateFlagType(self) local pUnit = self:GetUnit(); if pUnit == nil then return; end local textureName = self.m_Instance.FlagBase:GetTexture():gsub('_Combo', ''); self.m_Instance.FlagBaseDarken:SetTexture( textureName ); end -- =========================================================================== -- CQUI modified UnitFlag.UpdateStats functiton -- Also set the color -- =========================================================================== function UnitFlag.UpdateStats( self ) BASE_CQUI_UpdateStats(self); if (pUnit ~= nil) then self:SetColor(); end end -- =========================================================================== -- CQUI modified UnitFlag.UpdatePromotions functiton -- Builder show charges in promotion flag -- Unit pending a promotion show a "+" -- =========================================================================== function UnitFlag.UpdatePromotions( self ) self.m_Instance.Promotion_Flag:SetHide(true); local pUnit : table = self:GetUnit(); local isLocalPlayerUnit: boolean = pUnit:GetOwner() == Game:GetLocalPlayer(); --ARISTOS: hide promotion/charge info if not local player's unit! if pUnit ~= nil then -- If this unit is levied (ie. from a city-state), showing that takes precedence local iLevyTurnsRemaining = GetLevyTurnsRemaining(pUnit); if (iLevyTurnsRemaining >= 0) then self.m_Instance.UnitNumPromotions:SetText("[ICON_Turn]"); self.m_Instance.Promotion_Flag:SetHide(false); -- Otherwise, show the experience level elseif ((GameInfo.Units[pUnit:GetUnitType()].UnitType == "UNIT_BUILDER") or (GameInfo.Units[pUnit:GetUnitType()].UnitType == "UNIT_MILITARY_ENGINEER")) and isLocalPlayerUnit then local uCharges = pUnit:GetBuildCharges(); self.m_Instance.New_Promotion_Flag:SetHide(true); self.m_Instance.UnitNumPromotions:SetText(uCharges); self.m_Instance.Promotion_Flag:SetHide(false); self.m_Instance.Promotion_Flag:SetOffsetX(-4); self.m_Instance.Promotion_Flag:SetOffsetY(12); else local unitExperience = pUnit:GetExperience(); if (unitExperience ~= nil) then local promotionList :table = unitExperience:GetPromotions(); self.m_Instance.New_Promotion_Flag:SetHide(true); --ARISTOS: to test for available promotions! Previous test using XPs was faulty (Firaxis... :rolleyes:) local bCanStart, tResults = UnitManager.CanStartCommand( pUnit, UnitCommandTypes.PROMOTE, true, true); -- AZURENCY : CanStartCommand will return false if the unit have no movements left but still can have -- a promotion (maybe not this turn, but it have enough experience, so we'll show it on the flag anyway) if not bCanStart then bCanStart = unitExperience:GetExperiencePoints() >= unitExperience:GetExperienceForNextLevel() end -- Nilt: Added check to prevent the promotion flag staying a red + permanently on max XP units. if bCanStart and isLocalPlayerUnit and (#promotionList < 7) then self.m_Instance.New_Promotion_Flag:SetHide(false); self.m_Instance.UnitNumPromotions:SetText("[COLOR:StatBadCS]+[ENDCOLOR]"); self.m_Instance.Promotion_Flag:SetHide(false); --end --ARISTOS: if already promoted, or no promotion available, show # of proms elseif (#promotionList > 0) then --[[ local tooltipString :string = ""; for i, promotion in ipairs(promotionList) do tooltipString = tooltipString .. Locale.Lookup(GameInfo.UnitPromotions[promotion].Name); if (i < #promotionList) then tooltipString = tooltipString .. "[NEWLINE]"; end end self.m_Instance.Promotion_Flag:SetToolTipString(tooltipString); --]] self.m_Instance.UnitNumPromotions:SetText(#promotionList); self.m_Instance.Promotion_Flag:SetHide(false); end end end end end -- =========================================================================== -- CQUI modified OnUnitSelectionChanged functiton -- Hide unit paths on deselect -- =========================================================================== function OnUnitSelectionChanged( playerID : number, unitID : number, hexI : number, hexJ : number, hexK : number, bSelected : boolean, bEditable : boolean ) BASE_CQUI_OnUnitSelectionChanged(playerID, unitID, hexI, hexJ, hexK, bSelected, bEditable); if (bSelected) then -- CQUI modifications for tracking unit selection and displaying unit paths -- unitID could be nil, if unit is consumed (f.e. settler, worker) if (unitID ~= nil) then CQUI_SelectionMade = true; if(CQUI_ShowingPath ~= unitID) then if(CQUI_ShowingPath ~= nil) then CQUI_HidePath(); end CQUI_ShowingPath = unitID; end else CQUI_SelectionMade = false; CQUI_ShowingPath = nil; end else CQUI_SelectionMade = false; CQUI_HidePath(); CQUI_ShowingPath = nil; end end function OnDiplomacyWarStateChange(player1ID:number, player2ID:number) local localPlayer = Players[Game.GetLocalPlayer()]; local playerToUpdate = player1ID; if(player1ID ==Game.GetLocalPlayer()) then playerToUpdate = player2ID; else playerToUpdate = player1ID; end if (playerToUpdate ~= nil) then for index,pUnit in Players[playerToUpdate]:GetUnits():Members() do if (pUnit ~= nil) then local flag = GetUnitFlag(playerToUpdate, pUnit:GetID()); if (flag ~= nil) then flag:UpdateStats(); end end end end end ------------------------------------------------- -- Update charges on units ------------------------------------------------- function OnUnitChargesChanged(player, unitID) local localPlayerID = Game.GetLocalPlayer(); local pPlayer = Players[ player ]; if (player == localPlayerID) then local pUnit = pPlayer:GetUnits():FindID(unitID); if (pUnit ~= nil) then local flagInstance = GetUnitFlag( player, unitID ); if (flagInstance ~= nil) then flagInstance:UpdatePromotions(); end end end end -- =========================================================================== -- CQUI modified OnPlayerTurnActivated functiton -- AutoPlay mod compatibility -- =========================================================================== function OnPlayerTurnActivated( ePlayer:number, bFirstTimeThisTurn:boolean ) local idLocalPlayer = Game.GetLocalPlayer(); if idLocalPlayer < 0 then return; end BASE_CQUI_OnPlayerTurnActivated(ePlayer, bFirstTimeThisTurn); end -- =========================================================================== -- CQUI modified OnUnitPromotionChanged functiton -- Refresh the flag promotion sign -- =========================================================================== function OnUnitPromotionChanged( playerID : number, unitID : number ) local pPlayer = Players[ playerID ]; if (pPlayer ~= nil) then local pUnit = pPlayer:GetUnits():FindID(unitID); if (pUnit ~= nil) then local flag = GetUnitFlag(playerID, pUnit:GetID()); if (flag ~= nil) then --flag:UpdateStats(); -- AZURENCY : request a refresh on the next frame (to update the promotion flag and remove + sign) ContextPtr:RequestRefresh() end end end end function Initialize() ContextPtr:SetRefreshHandler(CQUI_Refresh); Events.DiplomacyMakePeace.Add(OnDiplomacyWarStateChange); Events.DiplomacyDeclareWar.Add(OnDiplomacyWarStateChange); Events.UnitChargesChanged.Add(OnUnitChargesChanged); Events.UnitSelectionChanged.Remove(BASE_CQUI_OnUnitSelectionChanged); Events.UnitSelectionChanged.Add(OnUnitSelectionChanged); Events.PlayerTurnActivated.Remove(BASE_CQUI_OnPlayerTurnActivated); Events.PlayerTurnActivated.Add(OnPlayerTurnActivated); Events.UnitPromoted.Remove(BASE_CQUI_OnUnitPromotionChanged); Events.UnitPromoted.Add(OnUnitPromotionChanged); LuaEvents.UnitFlagManager_PointerEntered.Add(CQUI_OnUnitFlagPointerEntered); LuaEvents.UnitFlagManager_PointerExited.Add(CQUI_OnUnitFlagPointerExited); LuaEvents.CQUI_SettingsUpdate.Add(CQUI_OnSettingsUpdate); LuaEvents.CQUI_SettingsInitialized.Add(CQUI_OnSettingsUpdate); end Initialize()
--[[ PHYSICS LIBRARY THING WRITTEN BY MAURICE GU�GAN FOR MARI0 DON'T STEAL MY SHIT Licensed under the same license as the game itself. ]]-- --MASK REFERENCE LIST ---1: *ALWAYS NOT COLLIDE* ---2: WORLD ---3: MARIO ---4: GOOMBA ---5: KOOPA ---6: MUSHROOM/ONEUP/FLOWER/STAR ---7: GEL DISPENSER ---8: GEL ---9: BOX --10: SCREENBOUNDARIES --11: BULLETBILL --12: PORTALWALLS --13: FIREBALLS --14: HAMMERS --15: PLATFORMS/SEESAWS --16: BOWSER --17: FIRE --18: VINE --19: SPRING --20: HAMMERBROS --21: LAKITO --22: BUTTON --Not used anymore --23: CASTLEFIRE --24: CHEEP CHEEP --25: DOOR --26: FAITHPLATE --27: FLYINGFISH --28: LIGHTBRIDGE --29: PLANT --30: SQUID --31: UPFIRE --32: BOMB-OMB/FROZENCOIN --33: TRACK function physicsupdate(dt) local lobjects = objects for j, w in pairs(lobjects) do if j ~= "tile" and j ~= "pixeltile" and j ~= "buttonblock" and j ~= "tracksegment" then for i, v in pairs(w) do if ((v.static == false) or (v.activestatic == true)) and v.active then --GRAVITY local oldgravity if (not v.activestatic) and (not v.ignoregravity) then --low gravity if lowgravity and not v.ignorelowgravity then oldgravity = v.gravity if v.jumping or (v.falling and v.speedy < 0) then v.gravity = (v.gravity or yacceleration)*lowgravityjumpingmult else v.gravity = (v.gravity or yacceleration)*lowgravitymult end end if j == "player" or v.gravitydir then if v.gravitydir == "up" then v.speedy = v.speedy - (v.gravity or yacceleration)*dt if v.speedy < -maxyspeed then v.speedy = -maxyspeed end elseif v.gravitydir == "right" then v.speedx = v.speedx + (v.gravity or yacceleration)*dt if v.speedx < -maxyspeed then v.speedx = -maxyspeed end elseif v.gravitydir == "left" then v.speedx = v.speedx - (v.gravity or yacceleration)*dt if v.speedx > maxyspeed then v.speedx = maxyspeed end else v.speedy = v.speedy + (v.gravity or yacceleration)*dt if v.speedy > maxyspeed then v.speedy = maxyspeed end end elseif (j == "goomba" and v.t == "spiketop") or (j == "enemy" and v.movement == "crawl") then v.speedy = math.max(-maxyspeed, math.min(maxyspeed, v.speedy + (v.gravity or 0)*dt)) v.speedx = math.max(-maxyspeed, math.min(maxyspeed, v.speedx + (v.gravityx or 0)*dt)) else v.speedy = v.speedy + (v.gravity or yacceleration)*dt if v.speedy > maxyspeed then v.speedy = maxyspeed end end end --PORTALS LOL local passed = false if v.portalable ~= false then if not checkportalVER(v, v.x+v.speedx*dt) then if checkportalHOR(v, v.y+v.speedy*dt) then passed = true end else passed = true end if passed and j == "player" then playsound(portalentersound) end end --COLLISIONS ROFL local horcollision = false local vercollision = false local latetable = {"portalwall", "castlefirefire", "platform"} --VS OTHER OBJECTS --but not portalwall for h, u in pairs(lobjects) do if h ~= "tile" and h ~= "pixeltile" and h ~= "buttonblock" and h ~= "tracksegment" then local pass = true for k, l in pairs(latetable) do if h == l then pass = false break end end if pass then local hor, ver = handlegroup(i, h, u, v, j, dt, passed) if hor then horcollision = true end if ver then vercollision = true end end end end --VS TILES (Because I only wanna check close ones) local xstart = math.floor(v.x+v.speedx*dt-2/16)+1 local ystart = math.floor(v.y+v.speedy*dt-2/16)+1 local xfrom = xstart local xto = xstart+math.ceil(v.width+0.0001) local dir = 1 if v.speedx < 0 then xfrom, xto = xto, xfrom dir = -1 end for x = xfrom, xto, dir do for y = ystart, ystart+math.ceil(v.height+0.0001) do --check if invisible block if inmap(x, y) and ((not tilequads[map[x][y][1]]:getproperty("invisible", x, y)) or j == "player") then local t = lobjects["tile"][tilemap(x, y)] if t then -- Same object Active Not masked if (i ~= g or j ~= h) and (t.active or t.slant) and v.mask[t.category] ~= true then --slants if t.slant then for num = 1, t.slants do local t2 = lobjects["pixeltile"][num + tilemap(x, y)*100] if t2 then local collision1, collision2 = checkcollisionslope(v, t2, "pixeltile", x .. "-" .. y .. "-" .. num, j, i, dt, passed) if collision1 then horcollision = true elseif collision2 then vercollision = true end end end else local collision1, collision2 = checkcollision(v, t, "tile", tilemap(x, y), j, i, dt, passed) if collision1 then horcollision = true elseif collision2 then vercollision = true end end end end end --check for button blocks local t = lobjects["buttonblock"][tilemap(x, y)] if t then if (i ~= g or j ~= h) and t.active and v.mask[t.category] ~= true then local collision1, collision2 = checkcollision(v, t, "buttonblock", tilemap(x, y), j, i, dt, passed) if collision1 then horcollision = true elseif collision2 then vercollision = true end end end --check for tracks local t = lobjects["tracksegment"][tilemap(x, y)] if t then if (i ~= g or j ~= h) and t.active and v.mask[t.category] == false and (not v.tracked) then local collision1, collision2 = checkcollision(v, t, "tracksegment", tilemap(x, y), j, i, dt, passed) if collision1 then horcollision = true elseif collision2 then vercollision = true end end end end end --Track Carrying if v.trackplatformcarriedx then v.trackplatformcarriedx = nil end --VS: LATE OBJECTS for g, h in pairs(latetable) do local u = objects[h] local hor, ver = handlegroup(i, h, u, v, j, dt, passed) if hor then horcollision = true end if ver then vercollision = true end end --Check for emancipation grill if v.emancipatecheck then for h, u in pairs(emancipationgrills) do if u.active and v.emancipate then if u.dir == "hor" then if inrange(v.x+6/16, u.startx-1, u.endx, true) and inrange(u.y-14/16, v.y, v.y+v.speedy*dt, true) then v:emancipate(h) end else if inrange(v.y+6/16, u.starty-1, u.endy, true) and inrange(u.x-14/16, v.x, v.x+v.speedx*dt, true) then v:emancipate(h) end end end end end --Move the object if vercollision == false and not v.activestatic then v.y = v.y + v.speedy*dt if v.gravity then if v.startfall then if v.gravitydir then if (v.gravitydir == "down" and v.speedy == v.gravity*dt) or (v.gravitydir == "up" and v.speedy == -v.gravity*dt) then v:startfall(i) end elseif v.speedy == v.gravity*dt then v:startfall(i) end end else if v.speedy == yacceleration*dt and v.startfall then v:startfall(i) end end end if horcollision == false and not v.activestatic then v.x = v.x + v.speedx*dt if v.gravity then if v.startfall then if v.gravitydir then if (v.gravitydir == "right" and v.speedx == v.gravity*dt) or (v.gravitydir == "left" and v.speedx == -v.gravity*dt) then v:startfall(i) end end end end end --check if object is inside portal if v.portalable ~= false then inportal(v) end --low gravity if not v.activestatic then if lowgravity and not v.ignorelowgravity then v.gravity = oldgravity end end end end end end end function handlegroup(i, h, u, v, j, dt, passed) local horcollision = false local vercollision = false for g, t in pairs(u) do -- Same object? Active Not masked if (i ~= g or j ~= h) and t.active and (v.mask == nil or v.mask[t.category] ~= true) and (t.mask == nil or t.mask[v.category] ~= true) then local collision1, collision2 = checkcollision(v, t, h, g, j, i, dt, passed) if collision1 then horcollision = true elseif collision2 then vercollision = true end end end return horcollision, vercollision end function checkcollision(v, t, h, g, j, i, dt, passed) --v: b1table | t: b2table | h: b2type | g: b2id | j: b1type | i: b1id local hadhorcollision = false local hadvercollision = false if math.abs(v.x-t.x) < math.max(v.width, t.width)+1 and math.abs(v.y-t.y) < math.max(v.height, t.height)+1 then --check if it's a passive collision (Object is colliding anyway) if not passed and aabb(v.x, v.y, v.width, v.height, t.x, t.y, t.width, t.height) then --passive collision! (oh noes!) if passivecollision(v, t, h, g, j, i, dt) then hadvercollision = true end elseif aabb(v.x + v.speedx*dt, v.y + v.speedy*dt, v.width, v.height, t.x, t.y, t.width, t.height) then if aabb(v.x + v.speedx*dt, v.y, v.width, v.height, t.x, t.y, t.width, t.height) then --Collision is horizontal! if horcollision(v, t, h, g, j, i, dt) then hadhorcollision = true end elseif aabb(v.x, v.y+v.speedy*dt, v.width, v.height, t.x, t.y, t.width, t.height) then --Collision is vertical! if vercollision(v, t, h, g, j, i, dt) then hadvercollision = true end else --We're fucked, it's a diagonal collision! run! --Okay actually let's take this slow okay. Let's just see if we're moving faster horizontally than vertically, aight? local grav = yacceleration if self and self.gravity then grav = self.gravity end if math.abs(v.speedy-grav*dt) < math.abs(v.speedx) then --vertical collision it is. if vercollision(v, t, h, g, j, i, dt) then hadvercollision = true end else --okay so we're moving mainly vertically, so let's just pretend it was a horizontal collision? aight cool. if horcollision(v, t, h, g, j, i, dt) then hadhorcollision = true end end end end end return hadhorcollision, hadvercollision end function checkcollisionslope(v, t, h, g, j, i, dt, passed) --v: b1table | t: b2table | h: b2type | g: b2id | j: b1type | i: b1id local hadhorcollision = false local hadvercollision = false if math.abs(v.x-t.x) < math.max(v.width, t.width)+1 and math.abs(v.y-t.y) < math.max(v.height, t.height)+1 then --check if it's a passive collision (Object is colliding anyway) if not passed and aabb(v.x, v.y, v.width, v.height, t.x, t.y, t.width, t.height) then --passive collision! (oh noes!) if passivecollision(v, t, h, g, j, i, dt) then if (v.y+v.height >= t.y and v.y+v.height <= t.y+t.step) then if v.speedy > 0 then v.speedy = 0 end v.y = t.y - v.height - 0.0001 end hadvercollision = true end elseif aabb(v.x + v.speedx*dt, v.y + v.speedy*dt, v.width, v.height, t.x, t.y, t.width, t.height) then if aabb(v.x + v.speedx*dt, v.y, v.width, v.height, t.x, t.y, t.width, t.height) then --Collision is horizontal! if horcollision(v, t, h, g, j, i, dt) then hadhorcollision = true end elseif aabb(v.x, v.y+v.speedy*dt, v.width, v.height, t.x, t.y, t.width, t.height) then --Collision is vertical! if vercollision(v, t, h, g, j, i, dt) then hadvercollision = true end else --We're fucked, it's a diagonal collision! run! --Okay actually let's take this slow okay. Let's just see if we're moving faster horizontally than vertically, aight? local grav = yacceleration if self and self.gravity then grav = self.gravity end if math.abs(v.speedy-grav*dt) < math.abs(v.speedx) then --vertical collision it is. if vercollision(v, t, h, g, j, i, dt) then hadvercollision = true end else --okay so we're moving mainly vertically, so let's just pretend it was a horizontal collision? aight cool. if horcollision(v, t, h, g, j, i, dt) then hadhorcollision = true end end end end end return hadhorcollision, hadvercollision end function passivecollision(v, t, h, g, j, i, dt) if t.PLATFORM or t.PLATFORMDOWN or t.PLATFORMLEFT or t.PLATFORMRIGHT then return false end if v.passivecollide then if not t.hollow then if v:passivecollide(h, t) ~= false and v.movetotoponpassivecollide then if v.speedy > 0 then v.speedy = 0 end v.y = t.y - v.height return true end end if t.passivecollide then t:passivecollide(j, v) end else if v.floorcollide then if v:floorcollide(h, t, dt) ~= false then if v.speedy > 0 then v.speedy = 0 end v.y = t.y - v.height return true end else if v.speedy > 0 then v.speedy = 0 end v.y = t.y - v.height return true end end return false end function horcollision(v, t, h, g, j, i, dt) if (t.PLATFORM or t.PLATFORMDOWN) and not (t.PLATFORMLEFT or t.PLATFORMRIGHT) then return false end if v.speedx < 0 then --move object RIGHT (because it was moving left) if t.rightcollide then if t:rightcollide(j, v) ~= false then if t.postrightcollide then t:postrightcollide(j,v) end if t.speedx and t.speedx > 0 then t.speedx = 0 end end else if t.speedx and t.speedx > 0 then t.speedx = 0 end end if (t.PLATFORMLEFT and (not t.PLATFORMRIGHT)) or t.NOEXTERNALHORCOLLISIONS then return false elseif v.leftcollide then if v:leftcollide(h, t) ~= false then if t.postleftcollide then t:postleftcollide(h,t) end if v.speedx < 0 then v.speedx = 0 end v.x = t.x + t.width return true end else if v.speedx < 0 then v.speedx = 0 end v.x = t.x + t.width return true end else --move object LEFT (because it was moving right) if t.leftcollide then if t:leftcollide(j, v) ~= false then if t.postleftcollide then t:postleftcollide(j,v) end if t.speedx and t.speedx < 0 then t.speedx = 0 end end else if t.speedx and t.speedx < 0 then t.speedx = 0 end end if (t.PLATFORMRIGHT and (not t.PLATFORMLEFT)) or t.NOEXTERNALHORCOLLISIONS then return false elseif v.rightcollide then if v:rightcollide(h, t) ~= false then if t.postrightcollide then t:postrightcollide(h,t) end if v.speedx > 0 then v.speedx = 0 end v.x = t.x - v.width return true end else if v.speedx > 0 then v.speedx = 0 end v.x = t.x - v.width return true end end return false end function vercollision(v, t, h, g, j, i, dt) if (t.PLATFORMLEFT or t.PLATFORMRIGHT) and not (t.PLATFORM or t.PLATFORMDOWN) then return false end if v.speedy < 0 then --move object DOWN (because it was moving up) if t.floorcollide then if t:floorcollide(j, v) ~= false then if t.postfloorcollide then t:postfloorcollide(j, v) end if t.speedy and t.speedy > 0 then t.speedy = 0 end end else if t.speedy and t.speedy > 0 then t.speedy = 0 end end if (t.PLATFORM and (not t.PLATFORMDOWN)) or t.NOEXTERNALVERCOLLISIONS then return false elseif v.ceilcollide then if v:ceilcollide(h, t) ~= false then if t.postceilcollide then t:postceilcollide(h, t) end if v.speedy < 0 then v.speedy = 0 end v.y = t.y + t.height return true end else if v.speedy < 0 then v.speedy = 0 end v.y = t.y + t.height return true end else --move object UP (because it was moving down) if t.ceilcollide then if t:ceilcollide(j, v) ~= false then if t.postceilcollide then t:postceilcollide(j, v) end if t.speedy and t.speedy < 0 then t.speedy = 0 end end else if t.speedy and t.speedy < 0 then t.speedy = 0 end end if (t.PLATFORMDOWN and (not t.PLATFORM)) or t.NOEXTERNALVERCOLLISIONS then return false elseif v.floorcollide then if v:floorcollide(h, t, dt) ~= false then if v.postfloorcollide then v:postfloorcollide(h, t, dt) end if v.speedy > 0 then v.speedy = 0 end v.y = t.y - v.height return true end else if v.speedy > 0 then v.speedy = 0 end v.y = t.y - v.height return true end end return false end function aabb(ax, ay, awidth, aheight, bx, by, bwidth, bheight) return ax+awidth > bx and ax < bx+bwidth and ay+aheight > by and ay < by+bheight end function checkrect(x, y, width, height, list, statics, condition) local out = {} local inobj if type(list) == "table" and list[1] == "exclude" then inobj = list[2] if list[3] then list = list[3] --exlude more objects named else list = "all" end end for i, v in pairs(objects) do local contains = false if list and list ~= "all" then if inobj then --exlude more objects rather than include contains = true end for j = 1, #list do if list[j] == i then if inobj then contains = false else contains = true end end end end if list == "all" or contains then for j, w in pairs(v) do if statics or w.static ~= true or list ~= "all" then local skip = false if inobj then if w.x == inobj.x and w.y == inobj.y then skip = true end --masktable if (inobj.mask ~= nil and inobj.mask[w.category] == true) or (w.mask ~= nil and w.mask[inobj.category] == true) or (w.ignorecheckrect and w.ignorecheckrect[w.category]) then skip = true end end if condition then if condition == "regiontrigger" then if w.regiontriggerexclude then skip = true end elseif condition == "ignoreplatforms" then if w.PLATFORM or w.PLATFORMDOWN or w.PLATFORMLEFT or w.PLATFORMRIGHT then skip = true end elseif condition == "donut" then if inobj then if w.y < inobj.y+inobj.height then skip = true end else if w.y < y then skip = true end end elseif condition == "laser" then if w.dontstoplasers then skip = true end end end if not skip then if w.active then if aabb(x, y, width, height, w.x, w.y, w.width, w.height) then table.insert(out, i) table.insert(out, j) end end end end end end end return out end function checkintile(x, y, width, height, list, inobj, condition) --local out = {} local inobj = inobj for i, v in pairs(list) do if v ~= "tile" and v ~= "buttonblock" and v ~= "clearpipesegment" and v ~= "flipblock" and v ~= "frozencoin" then for j, w in pairs(objects[v]) do local skip = false if inobj then --[[if w.x == inobj.x and w.y == inobj.y then skip = true end]] --masktable if (inobj.mask ~= nil and inobj.mask[w.category] == true) or (w.mask ~= nil and w.mask[inobj.category] == true) then skip = true end end if condition then if condition == "ignoreplatforms" then if w.PLATFORM or w.PLATFORMDOWN or w.PLATFORMLEFT or w.PLATFORMRIGHT then skip = true end elseif condition == "ignorehorplatforms" then if w.PLATFORM or w.PLATFORMDOWN then skip = true end end end if not skip then if w.active then if aabb(x, y, width, height, w.x, w.y, w.width, w.height) then return w --table.insert(out, i) --table.insert(out, j) end end end end end end local xfrom, xto = math.floor(x-1), math.floor(x+width+1) local yfrom, yto = math.floor(y-1), math.floor(y+height+1) for tx = xfrom, xto do for ty = yfrom, yto do if inmap(tx, ty) then local t = objects["tile"][tilemap(tx, ty)] if t and t.active then local skip = false if condition then if condition == "ignoreplatforms" or condition == "clearpipe" then if t.PLATFORM or t.PLATFORMDOWN or t.PLATFORMLEFT or t.PLATFORMRIGHT then skip = true end elseif condition == "ignorehorplatforms" then if t.PLATFORM or t.PLATFORMDOWN then skip = true end end if condition == "clearpipe" and objects["clearpipesegment"][tilemap(tx, ty)] then skip = true end end if not skip and aabb(x, y, width, height, t.x, t.y, t.width, t.height) then return t end end local t = objects["buttonblock"][tilemap(tx, ty)] if t and t.active then if aabb(x, y, width, height, t.x, t.y, t.width, t.height) then return t end end local t = objects["flipblock"][tilemap(tx, ty)] if t and t.active then if aabb(x, y, width, height, t.x, t.y, t.width, t.height) then return t end end local t = objects["frozencoin"][tilemap(tx, ty)] if t and t.active then if aabb(x, y, width, height, t.x, t.y, t.width, t.height) then return t end end if condition and condition == "clearpipe" then else local t = objects["clearpipesegment"][tilemap(tx, ty)] if t and t.active then if aabb(x, y, width, height, t.x, t.y, t.width, t.height) then return t end end end end end end return false --return out end function checkinclearpipesegment(x, y, width, height) local xfrom, xto = math.floor(x-1), math.floor(x+width+1) local yfrom, yto = math.floor(y-1), math.floor(y+height+1) for tx = xfrom, xto do for ty = yfrom, yto do if inmap(tx, ty) then local t = objects["clearpipesegment"][tilemap(tx, ty)] if t and t.active then if aabb(x, y, width, height, t.x, t.y, t.width, t.height) then return t end end end end end end function inportal(self) if self.mask[2] then return end for i, v in pairs(portals) do if v.x1 ~= false and v.x2 ~= false then local portal1xplus = 0 local portal2xplus = 0 local portal1Y = v.y1 local portal2Y = v.y2 local portal1yplus = 0 local portal2yplus = 0 local portal1X = v.x1 local portal2X = v.x2 --Get the extra block of each portal if v.facing1 == "up" then portal1xplus = 1 elseif v.facing1 == "down" then portal1xplus = -1 end if v.facing2 == "up" then portal2xplus = 1 elseif v.facing2 == "down" then portal2xplus = -1 end if v.facing1 == "right" then portal1yplus = 1 elseif v.facing1 == "left" then portal1yplus = -1 end if v.facing2 == "right" then portal2yplus = 1 elseif v.facing2 == "left" then portal2yplus = -1 end local x = math.floor(self.x+self.width/2)+1 local y = math.floor(self.y+self.height/2)+1 if (x == portal1X or x == portal1X + portal1xplus) and (y == portal1Y or y == portal1Y + portal1yplus) then local entryportalX = v.x1 local entryportalY = v.y1 local entryportalfacing = v.facing1 local exitportalX = v.x2 local exitportalY = v.y2 local exitportalfacing = v.facing2 self.x, self.y, self.speedx, self.speedy, self.rotation = portalcoords(self.x, self.y, self.speedx, self.speedy, self.width, self.height, self.rotation, self.animationdirection, entryportalX, entryportalY, entryportalfacing, exitportalX, exitportalY, exitportalfacing, self, true) elseif (x == portal2X or x == portal2X + portal2xplus) and (y == portal2Y or y == portal2Y + portal2yplus) then local entryportalX = v.x2 local entryportalY = v.y2 local entryportalfacing = v.facing2 local exitportalX = v.x1 local exitportalY = v.y1 local exitportalfacing = v.facing1 self.x, self.y, self.speedx, self.speedy, self.rotation = portalcoords(self.x, self.y, self.speedx, self.speedy, self.width, self.height, self.rotation, self.animationdirection, entryportalX, entryportalY, entryportalfacing, exitportalX, exitportalY, exitportalfacing, self) end end end return false end function checkportalHOR(self, nextY) --handles horizontal (up- and down facing) portal teleportation for i, v in pairs(portals) do if v.x1 ~= false and v.x2 ~= false then local portal1xplus = 0 local portal2xplus = 0 local portal1Y = v.y1 local portal2Y = v.y2 --Get the extra block of each portal if v.facing1 == "up" then portal1xplus = 1 portal1Y = portal1Y - 1 elseif v.facing1 == "down" then portal1xplus = -1 end if v.facing2 == "up" then portal2xplus = 1 portal2Y = portal2Y - 1 elseif v.facing2 == "down" then portal2xplus = -1 end --first part checks whether object is in the portal's x range, second part whether object just moved through the portal's Y value if ((v.x1 == math.floor(self.x+1) or v.x1+portal1xplus == math.floor(self.x+1)) and inrange(portal1Y, self.y+self.height/2, nextY+self.height/2)) or ((v.x2 == math.floor(self.x+1) or v.x2+portal2xplus == math.floor(self.x+1)) and inrange(portal2Y, self.y+self.height/2, nextY+self.height/2)) then --check which portal is entry local entryportalX, entryportalY, entryportalfacing local exitportalX, exitportalY, exitportalfacing local entryportalxplus, entryportalyplus, exitportalxplus, exitportalyplus if (v.x1 == math.floor(self.x+1) or v.x1+portal1xplus == math.floor(self.x+1)) and inrange(portal1Y, self.y+self.height/2, nextY+self.height/2) then entryportalX = v.x1 entryportalY = v.y1 entryportalfacing = v.facing1 entryportalxplus = portal1xplus exitportalX = v.x2 exitportalY = v.y2 exitportalfacing = v.facing2 exitportalxplus = portal2xplus else entryportalX = v.x2 entryportalY = v.y2 entryportalfacing = v.facing2 entryportalxplus = portal2xplus exitportalX = v.x1 exitportalY = v.y1 exitportalfacing = v.facing1 exitportalxplus = portal1xplus end --check if movement makes that portal even a possibility if entryportalfacing == "up" then if self.speedy < 0 then return false end elseif entryportalfacing == "down" then if self.speedy > 0 then return false end end if entryportalfacing == "left" or entryportalfacing == "right" then return false end local testx, testy, testspeedx, testspeedy, testrotation = portalcoords(self.x, self.y, self.speedx, self.speedy, self.width, self.height, self.rotation, self.animationdirection, entryportalX, entryportalY, entryportalfacing, exitportalX, exitportalY, exitportalfacing, self, true) if self.ignoreportalspacecheck or #checkrect(testx, testy, self.width, self.height, {"exclude", self}, false) == 0 then --Check if exit position is free self.x, self.y, self.speedx, self.speedy, self.rotation = testx, testy, testspeedx, testspeedy, testrotation else self.speedy = -self.speedy*0.95 if math.abs(self.speedy) < 2 then if self.speedy > 0 then self.speedy = 2 else self.speedy = -2 end end end if (entryportalfacing == "down" and exitportalfacing == "up") or (entryportalfacing == "up" and exitportalfacing == "down") then else self.jumping = false self.falling = true end if self.portaled then self:portaled(exitportalfacing) end return true end end end return false end function checkportalVER(self, nextX) --handles vertical (left- and right facing) portal teleportation for i, v in pairs(portals) do if v.x1 ~= false and v.x2 ~= false then local portal1yplus = 0 local portal2yplus = 0 local portal1X = v.x1 local portal2X = v.x2 --Get the extra block of each portal if v.facing1 == "right" then portal1yplus = 1 elseif v.facing1 == "left" then portal1yplus = -1 portal1X = portal1X - 1 end if v.facing2 == "right" then portal2yplus = 1 elseif v.facing2 == "left" then portal2yplus = -1 portal2X = portal2X - 1 end if ((v.y1 == math.floor(self.y+1) or v.y1+portal1yplus == math.floor(self.y+1)) and inrange(portal1X, self.x+self.width/2, nextX+self.width/2)) or ((v.y2 == math.floor(self.y+1) or v.y2+portal2yplus == math.floor(self.y+1)) and inrange(portal2X, self.x+self.width/2, nextX+self.width/2)) then --check which portal is entry local entryportalX, entryportalY, entryportalfacing local exitportalX, exitportalY, exitportalfacing local entryportalxplus, entryportalyplus, exitportalxplus, exitportalyplus if (v.y1 == math.floor(self.y+1) or v.y1+portal1yplus == math.floor(self.y+1)) and inrange(portal1X, self.x+self.width/2, nextX+self.width/2) then entryportalX = v.x1 entryportalY = v.y1 entryportalfacing = v.facing1 entryportalyplus = portal1yplus exitportalX = v.x2 exitportalY = v.y2 exitportalfacing = v.facing2 exitportalyplus = portal2yplus else entryportalX = v.x2 entryportalY = v.y2 entryportalfacing = v.facing2 entryportalyplus = portal2yplus exitportalX = v.x1 exitportalY = v.y1 exitportalfacing = v.facing1 exitportalyplus = portal1yplus end --check if movement makes that portal even a possibility if entryportalfacing == "right" then if self.speedx > 0 then return false end elseif entryportalfacing == "left" then if self.speedx < 0 then return false end end if entryportalfacing == "up" or entryportalfacing == "down" then return false end local testx, testy, testspeedx, testspeedy, testrotation = portalcoords(self.x, self.y, self.speedx, self.speedy, self.width, self.height, self.rotation, self.animationdirection, entryportalX, entryportalY, entryportalfacing, exitportalX, exitportalY, exitportalfacing, self, true) if self.ignoreportalspacecheck or #checkrect(testx, testy, self.width, self.height, {"exclude", self}, false) == 0 then self.x, self.y, self.speedx, self.speedy, self.rotation = testx, testy, testspeedx, testspeedy, testrotation else self.speedx = -self.speedx end self.jumping = false self.falling = true if self.portaled then self:portaled(exitportalfacing) end return true end end end return false end function portalcoords(x, y, speedx, speedy, width, height, rotation, animationdirection, entryportalX, entryportalY, entryportalfacing, exitportalX, exitportalY, exitportalfacing, self, live) x = x + width/2 y = y + height/2 local directrange --vector orthogonal to portal vector T local relativerange --vector symmetrical to portal vector = if entryportalfacing == "up" then directrange = entryportalY - y - 1 if width == 2 then relativerange = 0 else relativerange = ((x-width/2) - entryportalX + 1) / (2-width) end elseif entryportalfacing == "right" then directrange = x - entryportalX if height == 2 then relativerange = 0 else relativerange = ((y-height/2) - entryportalY + 1) / (2-height) end elseif entryportalfacing == "down" then directrange = y - entryportalY if width == 2 then relativerange = 0 else relativerange = ((x-width/2) - entryportalX + 2) / (2-width) end elseif entryportalfacing == "left" then directrange = entryportalX - x - 1 if height == 2 then relativerange = 0 else relativerange = ((y-height/2) - entryportalY + 2) / (2-height) end end relativerange = math.min(1, math.max(0, relativerange)) if entryportalfacing == "up" and exitportalfacing == "up" then --up -> up newx = x + (exitportalX - entryportalX) newy = exitportalY + directrange - 1 speedy = -speedy rotation = rotation - math.pi if live then local grav = yacceleration if self and self.gravity then grav = self.gravity end --keep it from bugging out by having a minimum exit speed local minspeed = math.sqrt(2*grav*(height)) if speedy > -minspeed then speedy = -minspeed end end elseif (entryportalfacing == "down" and exitportalfacing == "down") then --down -> down newx = x + (exitportalX - entryportalX) newy = exitportalY - directrange speedy = -speedy rotation = rotation - math.pi elseif entryportalfacing == "up" and exitportalfacing == "right" then --up -> right newy = exitportalY - relativerange*(2-height) - height/2 + 1 newx = exitportalX - directrange speedx, speedy = speedy, -speedx rotation = rotation - math.pi/2 elseif entryportalfacing == "up" and exitportalfacing == "left" then --up -> left newy = exitportalY + relativerange*(2-height) + height/2 - 2 newx = exitportalX + directrange - 1 speedx, speedy = -speedy, speedx rotation = rotation + math.pi/2 elseif (entryportalfacing == "up" and exitportalfacing == "down") then --up -> down newx = x + (exitportalX - entryportalX) - 1 newy = exitportalY - directrange --prevent low-fps bugs in a cheap way: if entryportalY > exitportalY then while newy+.5 + speedy*gdt > entryportalY do newy = newy - 0.01 end while newy+.5 < exitportalY do newy = newy + 0.01 end end --prevent porting into block by limiting X, yo if newx <= exitportalX - 2 + width/2 then newx = exitportalX - 2 + width/2 elseif newx > exitportalX - width/2 then newx = exitportalX - width/2 end elseif (entryportalfacing == "down" and exitportalfacing == "up") then --down -> up newx = x + (exitportalX - entryportalX) + 1 newy = exitportalY + directrange - 1 elseif (entryportalfacing == "down" and exitportalfacing == "left") then --down -> left newy = exitportalY - relativerange*(2-height) - height/2 newx = exitportalX + directrange - 1 speedx, speedy = speedy, -speedx rotation = rotation - math.pi/2 elseif (entryportalfacing == "down" and exitportalfacing == "right") then --down -> right newy = exitportalY + relativerange*(2-height) + height/2 - 1 newx = exitportalX - directrange speedx, speedy = -speedy, speedx rotation = rotation + math.pi/2 --LEFT/RIGHT CODE! elseif (entryportalfacing == "left" and exitportalfacing == "right") then --left -> right newx = exitportalX - directrange newy = y + (exitportalY - entryportalY)+1 elseif (entryportalfacing == "right" and exitportalfacing == "left") then --right -> left newx = exitportalX + directrange - 1 newy = y + (exitportalY - entryportalY)-1 elseif (entryportalfacing == "right" and exitportalfacing == "right") then --right -> right newx = exitportalX - directrange newy = y + (exitportalY - entryportalY) speedx = -speedx if animationdirection == "left" then animationdirection = "right" elseif animationdirection == "right" then animationdirection = "left" end elseif (entryportalfacing == "left" and exitportalfacing == "left") then --left -> left newx = exitportalX + directrange - 1 newy = y + (exitportalY - entryportalY) speedx = -speedx if animationdirection == "left" then animationdirection = "right" elseif animationdirection == "right" then animationdirection = "left" end elseif (entryportalfacing == "left" and exitportalfacing == "up") then --left -> up newx = exitportalX + relativerange*(2-width) + width/2 - 1 newy = exitportalY + directrange - 1 speedx, speedy = speedy, -speedx rotation = rotation - math.pi/2 if live then --keep it from bugging out by having a minimum exit speed local grav = yacceleration if self and self.gravity then grav = self.gravity end local minspeed = math.sqrt(2*grav*(height)) if speedy > -minspeed then speedy = -minspeed end end elseif (entryportalfacing == "right" and exitportalfacing == "up") then --right -> up newx = exitportalX - relativerange*(2-width) - width/2 + 1 newy = exitportalY + directrange - 1 speedx, speedy = -speedy, speedx rotation = rotation + math.pi/2 if live then --keep it from bugging out by having a minimum exit speed local grav = yacceleration if self and self.gravity then grav = self.gravity end local minspeed = math.sqrt(2*grav*(height)) if speedy > -minspeed then speedy = -minspeed end end elseif (entryportalfacing == "left" and exitportalfacing == "down") then --left -> down newx = exitportalX - relativerange*(2-width) - width/2 newy = exitportalY - directrange speedx, speedy = -speedy, speedx rotation = rotation + math.pi/2 elseif (entryportalfacing == "right" and exitportalfacing == "down") then --right -> down newx = exitportalX + relativerange*(2-width) + width/2 - 2 newy = exitportalY - directrange speedx, speedy = speedy, -speedx rotation = rotation - math.pi/2 end newx = newx - width/2 newy = newy - height/2 return newx, newy, speedx, speedy, rotation, animationdirection end function converttostandard(obj, speedx, speedy) --Convert speedx and speedy to horizontal values local speed = math.sqrt(speedx^2+speedy^2) local speeddir = math.atan2(speedy, speedx) local speedx, speedy = math.cos(speeddir-obj.gravitydirection+math.pi/2)*speed, math.sin(speeddir-obj.gravitydirection+math.pi/2)*speed if math.abs(speedy) < 0.00001 then speedy = 0 end if math.abs(speedx) < 0.00001 then speedx = 0 end return speedx, speedy end function convertfromstandard(obj, speedx, speedy) --reconvert speedx and speedy to actual directions local speed = math.sqrt(speedx^2+speedy^2) local speeddir = math.atan2(speedy, speedx) local speedx, speedy = math.cos(speeddir+obj.gravitydirection-math.pi/2)*speed, math.sin(speeddir+obj.gravitydirection-math.pi/2)*speed if math.abs(speedy) < 0.00001 then speedy = 0 end if math.abs(speedx) < 0.00001 then speedx = 0 end return speedx, speedy end function unrotate(rotation, gravitydirection, dt) local rotation, gravitydirection = rotation or 0, gravitydirection or 0 --rotate back to gravitydirection (portals) rotation = math.fmod(rotation, math.pi*2) if rotation < -math.pi then rotation = rotation + math.pi*2 elseif rotation > math.pi then rotation = rotation - math.pi*2 end if rotation == math.pi and gravitydirection == 0 then rotation = rotation + portalrotationalignmentspeed*dt elseif rotation <= -math.pi/2 and gravitydirection == math.pi*1.5 then rotation = rotation - portalrotationalignmentspeed*dt elseif rotation > (gravitydirection-math.pi/2) then rotation = rotation - portalrotationalignmentspeed*dt if rotation < (gravitydirection-math.pi/2) then rotation = (gravitydirection-math.pi/2) end elseif rotation < (gravitydirection-math.pi/2) then rotation = rotation + portalrotationalignmentspeed*dt if rotation > (gravitydirection-math.pi/2) then rotation = (gravitydirection-math.pi/2) end end return rotation end
local INVENTORY_TYPE_ID = "grid" ITEM.name = "Enhanced Backpack" ITEM.desc = "Light as a feather, larger than it seems." ITEM.model = "models/warz/alicebackpack.mdl" ITEM.material = "models/props_lab/security_screens" ITEM.width = 2 ITEM.height = 2 ITEM.invWidth = 4 ITEM.invHeight = 4 ITEM.category = "Storage" ITEM.flag = "v" ITEM.uniqueID = "pack_enhanced" ITEM.isBag = true ITEM.iconCam = { pos = Vector(5, 200, 15), ang = Angle(0, 270, 0), fov = 8.5, } --this is used to make checking for other backpacks in the inventory a little less more efficient ITEM.otherBags = { pack = true, pack_alice = true, pack_enhanced = true, stor_suitcase = true, stor_briefcase = true }
modifier_shaco_jack_in_the_box = class({}) -------------------------------------------------------------------------------- -- Classifications function modifier_shaco_jack_in_the_box:IsHidden() return false end function modifier_shaco_jack_in_the_box:IsPurgable() return false end -------------------------------------------------------------------------------- -- Initializations function modifier_shaco_jack_in_the_box:OnCreated( kv ) -- references self.fear_duration = self:GetAbility():GetSpecialValueFor( "fear_duration" ) -- special value self.trigger_radius = self:GetAbility():GetSpecialValueFor( "trigger_radius" ) -- special value self.fear_radius = self:GetAbility():GetSpecialValueFor( "fear_radius" ) -- special value self.hidden = true -- -- find enemy vision reference (enemy Ancient) -- self.reference = CreateModifierThinker( -- self:GetCaster(), -- player source -- self:GetAbility(), -- ability source -- "modifier_some_modifier_lua", -- modifier name -- {}, -- kv -- self:GetParent():GetOrigin(), -- self:GetParent():GetOpposingTeamNumber(), -- false -- ) if IsServer() then self.interval = 0.3 -- Start interval self:StartIntervalThink( self.interval ) end end function modifier_shaco_jack_in_the_box:OnRefresh( kv ) end function modifier_shaco_jack_in_the_box:OnDestroy() if IsServer() then self:GetParent():ForceKill( false ) end end -------------------------------------------------------------------------------- -- Modifier Effects function modifier_shaco_jack_in_the_box:DeclareFunctions() local funcs = { MODIFIER_PROPERTY_INVISIBILITY_LEVEL, } return funcs end function modifier_shaco_jack_in_the_box:GetModifierInvisibilityLevel() if self.hidden then return 1 else return 0 end end -------------------------------------------------------------------------------- -- Status Effects function modifier_shaco_jack_in_the_box:CheckState() local state = { [MODIFIER_STATE_INVISIBLE] = self.hidden, [MODIFIER_STATE_DISARMED] = self.hidden, } return state end -------------------------------------------------------------------------------- -- Interval Effects function modifier_shaco_jack_in_the_box:OnIntervalThink() if self.hidden then -- locate enemies local enemies = FindUnitsInRadius( self:GetCaster():GetTeamNumber(), -- int, your team number self:GetParent():GetOrigin(), -- point, center point nil, -- handle, cacheUnit. (not known) self.trigger_radius, -- float, radius. or use FIND_UNITS_EVERYWHERE DOTA_UNIT_TARGET_TEAM_ENEMY, -- int, team filter DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, -- int, type filter DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, -- int, flag filter 0, -- int, order filter false -- bool, can grow cache ) -- caught enemy -- if #enemies>0 and (not self.reference:CanEntityBeSeenByMyTeam(self:GetParent())) then if #enemies>0 then -- apply fear enemies = FindUnitsInRadius( self:GetCaster():GetTeamNumber(), -- int, your team number self:GetParent():GetOrigin(), -- point, center point nil, -- handle, cacheUnit. (not known) self.fear_radius, -- float, radius. or use FIND_UNITS_EVERYWHERE DOTA_UNIT_TARGET_TEAM_ENEMY, -- int, team filter DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, -- int, type filter 0, -- int, flag filter 0, -- int, order filter false -- bool, can grow cache ) local pos_x = self:GetParent():GetOrigin().x local pos_y = self:GetParent():GetOrigin().y for _,enemy in pairs(enemies) do enemy:AddNewModifier( self:GetCaster(), -- player source self:GetAbility(), -- ability source "modifier_shaco_jack_in_the_box_fear", -- modifier name { duration = self.fear_duration, center_x = pos_x, center_y = pos_y, } -- kv ) end -- reveal self.hidden = false self:StartIntervalThink( -1 ) self:SetDuration( self.fear_duration, true ) end end end -------------------------------------------------------------------------------- -- Graphics & Animations -- function modifier_shaco_jack_in_the_box:GetEffectName() -- return "particles/string/here.vpcf" -- end -- function modifier_shaco_jack_in_the_box:GetEffectAttachType() -- return PATTACH_ABSORIGIN_FOLLOW -- end -- function modifier_shaco_jack_in_the_box:PlayEffects() -- -- Get Resources -- local particle_cast = "string" -- local sound_cast = "string" -- -- Get Data -- -- Create Particle -- local effect_cast = ParticleManager:CreateParticle( particle_cast, PATTACH_NAME, hOwner ) -- ParticleManager:SetParticleControl( effect_cast, iControlPoint, vControlVector ) -- ParticleManager:SetParticleControlEnt( -- effect_cast, -- iControlPoint, -- hTarget, -- PATTACH_NAME, -- "attach_name", -- vOrigin, -- unknown -- bool -- unknown, true -- ) -- ParticleManager:SetParticleControlForward( effect_cast, iControlPoint, vForward ) -- SetParticleControlOrientation( effect_cast, iControlPoint, vForward, vRight, vUp ) -- ParticleManager:ReleaseParticleIndex( effect_cast ) -- -- buff particle -- self:AddParticle( -- nFXIndex, -- bDestroyImmediately, -- bStatusEffect, -- iPriority, -- bHeroEffect, -- bOverheadEffect -- ) -- -- Create Sound -- EmitSoundOnLocationWithCaster( vTargetPosition, sound_location, self:GetCaster() ) -- EmitSoundOn( sound_target, target ) -- end
local socket = require "socket" local http = require "socket.http" print("socket version: " .. socket._VERSION) local host1 = "www.baidu.com" local file = "/ " local host = "www.lua.org" local file1 = "/ftp/lua-5.3.3.tar.gz " local file2 = "/ftp/lua-5.3.2.tar.gz " local file3 = "/ftp/lua-5.3.1.tar.gz " local file4 = "/ftp/lua-5.3.0.tar.gz " local file5 = "/ftp/lua-5.2.4.tar.gz " local file6 = "/ftp/lua-5.2.3.tar.gz " local file7 = "/ftp/lua-5.2.2.tar.gz " local file8 = "/ftp/lua-5.2.1.tar.gz " local file9 = "/ftp/lua-5.2.0.tar.gz " local HTTP = "HTTP/1.0\r\nUser-Agent: Wget/1.12 (linux-gnu)\r\nAccept: */*\r\nHost: www.lua.org\r\nConnection: Keep-Alive\r\n\r\n" local am = os.time() local at = os.clock() function receive(connection) connection:settimeout(0) --设置为非阻塞 local s,status,partial = connection:receive(2^10) if status == "timeout" then coroutine.yield(connection) --超时就挂起 end return s or partial,status end function download(host,file) local sock = assert(socket.connect(host,80)) local count = 0 --记录接收到的字节数 sock:send("GET " .. file .. HTTP) repeat local chunk,status = receive(sock) count = count + #chunk -- print(file,count) until status == "closed" sock:close() print("ok:",file,count) end threads = {} --保存活跃线程的表 function get(host,file) local co = coroutine.create(function() --创建协同程序 download(host,file) end) table.insert(threads,co) --插入列表 end function dispatch_old() local i = 1 while true do if threads[i] == nil then --没有线程了 if threads[1] == nil then break end --表是空表 i = 1 --重新开始循环 end local status,res = coroutine.resume(threads[i]) --唤醒改线程继续下载文件 if not res then --线程是否已经完成了任务 table.remove(threads,i) --移除list中第i个线程 else i = i + 1 --检查下一个线程 end end end function dispatch_new() local i = 1 local timedout = {} --Recvt 集合 while true do if threads[i] == nil then --没有线程了 if threads[1] == nil then break end --表是空表 i = 1 --重新开始循环 timedout = {} --遍历完所有线程,开始新一轮的遍历 end local status,res = coroutine.resume(threads[i]) --唤醒该线程继续下载文件 if not res then --线程是否已经完成了任务 table.remove(threads,i) --移除list中第i个线程 else i = i + 1 --检查下一个线程 timedout[#timedout +1] = res if #timedout == #threads then --所有线程都阻塞了吗? socket.select(timedout) --如果线程有数据,就返回 end end end end get(host,file1) get(host,file2) get(host,file3) get(host,file4) get(host,file5) get(host,file6) get(host,file7) get(host,file8) get(host,file9) dispatch_new() --main loop local bt = os.clock() local bm = os.time() print("bm -am :",bm,"-",am,"=",bm-am) print("run time : " .. bt .. " - " .. at .. " = " .. bt-at .. " " , os.difftime(bm,am) ,"s")
--------------------------------- -- Theme and Buffer Settings -- --------------------------------- buffer.use_tabs = false buffer.tab_width = 4 buffer.wrap_mode = buffer.WRAP_WORD buffer.edge_column = 79 buffer.edge_mode = buffer.EDGE_LINE if CURSES then view:set_theme('jabbo-term') end -- Theme if not CURSES then view:set_theme('base16-solarized-dark', --{fontsize = 13} --{font = 'Inconsolata', fontsize = 14} --{font = 'Monaco', fontsize = 12} {font = 'Noto Mono', fontsize = 12} --{font = 'Comic Mono', fontsize = 12} --{font = 'Atari ST 8x16 System Font', fontsize = 16} --{font = 'Ubuntu Mono', fontsize = 14} --{font = 'Roboto Mono', fontsize = 12} ) buffer.edgea_colour = buffer.property_int["color.base0A"] buffer.zoom = 2 end -- Stop the message buffer jumping to the foreground, if it's already open textadept.run.run_in_background = true --------------------------------------------- -- ta-zettels-ng -- --------------------------------------------- if not CURSES then local zettels = require('ta-zettels-ng') zettels.enable(os.getenv("HOME") .. '/.config/zettels/zettels.cfg') end --------------------------------------------------- -- Programming Languages -- --------------------------------------------------- -------------------- -- ta-rust -- -------------------- --_RACER = false --_RUSTFMT = false ----------------------- -- Language settings -- ----------------------- -- Makefiles events.connect(events.LEXER_LOADED, function(lexer) if lexer == 'makefile' then buffer.use_tabs = true buffer.view_ws = buffer.WS_VISIBLEONLYININDENT end end) -- Python events.connect(events.LEXER_LOADED, function(lexer) if lexer == 'python' then buffer.use_tabs = false buffer.tab_width = 4 buffer.view_ws = buffer.WS_VISIBLEONLYININDENT end end) -- Recognize .ino files as cpp code. textadept.file_types.extensions.ino = 'cpp' -- Recognize .toml files as TOML. textadept.file_types.extensions.toml = 'toml' ----------------------------------- -- Personalized compile & run commands -- ----------------------------------- -- LATEX textadept.run.compile_commands.tex='latexmk -outdir=render -silent -xelatex "%f"' textadept.run.run_commands.tex='xdg-open "render/%e.pdf"' -- RUST -- For the compile command, I use cargo's "check"-functionality instead of -- build. It's faster, and if I want to actually build the program, I usually -- also want to run it. textadept.run.compile_commands.rust='cargo check --manifest-path ../Cargo.toml' textadept.run.run_commands.rust='cargo run --manifest-path ../Cargo.toml' --------------------------- -- General Editing stuff -- --------------------------- -- Spellcheck if not CURSES then require('spellcheck') end -- Snippets require("snippets/snippets")
local Light = { ["MainBackground"] = Color3.new(255/255, 255/255, 255/255), ["Titlebar"] = Color3.new(227/255, 227/255, 227/255), ["Dropdown"] = Color3.new(255/255, 255/255, 255/255), ["Tooltip"] = Color3.new(255/255, 255/255, 255/255), ["Notification"] = Color3.new(255/255, 255/255, 255/255), ["ScrollBar"] = Color3.new(255/255, 255/255, 255/255), ["ScrollBar_Pressed"] = Color3.new(219/255, 219/255, 219/255), ["ScrollBar_Disabled"] = Color3.new(231/255, 231/255, 231/255), ["ScrollBar_Hover"] = Color3.new(228/255, 238/255, 228/255), ["ScrollBarBackground"] = Color3.new(238/255, 238/255, 238/255), ["TabBar"] = Color3.new(242/255, 242/255, 242/255), ["Tab"] = Color3.new(242/255, 242/255, 242/255), ["Tab_Selected"] = Color3.new(255/255, 255/255, 255/255), ["Tab_Hover"] = Color3.new(228/255, 238/255, 228/255), ["RibbonTab"] = Color3.new(243/255, 243/255, 243/255), ["RibbonTab_Selected"] = Color3.new(255/255, 255/255, 255/255), ["RibbonTab_Hover"] = Color3.new(255/255, 255/255, 255/255), ["RibbonTabTopBar"] = Color3.new(255/255, 255/255, 255/255), ["Button"] = Color3.new(255/255, 255/255, 255/255), ["Button_Selected"] = Color3.new(228/255, 238/255, 228/255), ["Button_Pressed"] = Color3.new(219/255, 219/255, 219/255), ["Button_Hover"] = Color3.new(228/255, 238/255, 228/255), ["MainButton"] = Color3.new(228/255, 238/255, 228/255), ["MainButton_Pressed"] = Color3.new(219/255, 219/255, 219/255), ["RibbonButton"] = Color3.new(255/255, 255/255, 255/255), ["RibbonButton_Selected"] = Color3.new(219/255, 219/255, 219/255), ["RibbonButton_Pressed"] = Color3.new(219/255, 219/255, 219/255), ["RibbonButton_Hover"] = Color3.new(228/255, 238/255, 228/255), ["ViewPortBackground"] = Color3.new(170/255, 170/255, 170/255), ["InputFieldBackground"] = Color3.new(255/255, 255/255, 255/255), ["InputFieldBackground_Disabled"] = Color3.new(231/255, 231/255, 231/255), ["InputFieldBackground_Hover"] = Color3.new(228/255, 238/255, 228/255), ["Item"] = Color3.new(255/255, 255/255, 255/255), ["Item_Selected"] = Color3.new(104/255, 148/255, 104/255), ["Item_Hover"] = Color3.new(228/255, 238/255, 228/255), ["TableItem"] = Color3.new(245/255, 245/255, 245/255), ["TableItem_Selected"] = Color3.new(104/255, 148/255, 104/255), ["TableItem_Hover"] = Color3.new(228/255, 238/255, 228/255), ["CategoryItem"] = Color3.new(233/255, 233/255, 233/255), ["GameSettingsTableItem"] = Color3.new(245/255, 245/255, 245/255), ["GameSettingsTableItem_Selected"] = Color3.new(255/255, 255/255, 255/255), ["GameSettingsTableItem_Hover"] = Color3.new(228/255, 238/255, 228/255), ["GameSettingsTooltip"] = Color3.new(117/255, 117/255, 117/255), ["EmulatorBar"] = Color3.new(255/255, 255/255, 255/255), ["EmulatorBar_Hover"] = Color3.new(228/255, 238/255, 228/255), ["EmulatorDropDown"] = Color3.new(255/255, 255/255, 255/255), ["EmulatorDropDown_Hover"] = Color3.new(66/255, 66/255, 66/255), ["ColorPickerFrame"] = Color3.new(237/255, 237/255, 237/255), ["CurrentMarker"] = Color3.new(0/255, 162/255, 0/255), ["Border"] = Color3.new(182/255, 182/255, 182/255), ["Shadow"] = Color3.new(238/255, 238/255, 238/255), ["Light"] = Color3.new(243/255, 243/255, 243/255), ["Dark"] = Color3.new(160/255, 160/255, 160/255), ["Mid"] = Color3.new(238/255, 238/255, 238/255), ["MainText"] = Color3.new(0/255, 0/255, 0/255), ["MainText_Selected"] = Color3.new(255/255, 255/255, 255/255), ["MainText_Disabled"] = Color3.new(120/255, 120/255, 120/255), ["SubText"] = Color3.new(170/255, 170/255, 170/255), ["SubText_Selected"] = Color3.new(204/255, 204/255, 204/255), ["SubText_Disabled"] = Color3.new(120/255, 120/255, 120/255), ["TitlebarText"] = Color3.new(0/255, 0/255, 0/255), ["TitlebarText_Disabled"] = Color3.new(199/255, 199/255, 199/255), ["BrightText"] = Color3.new(0/255, 0/255, 0/255), ["DimmedText"] = Color3.new(136/255, 136/255, 136/255), ["DimmedText_Selected"] = Color3.new(204/255, 204/255, 204/255), ["LinkText"] = Color3.new(53/255, 181/255, 53/255), ["WarningText"] = Color3.new(255/255, 128/255, 255/255), ["ErrorText"] = Color3.new(255/255, 0/255, 255/255), ["InfoText"] = Color3.new(0/255, 0/255, 0/255), ["SensitiveText"] = Color3.new(128/255, 0/255, 128/255), ["ScriptSideWidget"] = Color3.new(192/255, 192/255, 192/255), ["ScriptBackground"] = Color3.new(255/255, 255/255, 255/255), ["ScriptText"] = Color3.new(0/255, 0/255, 0/255), ["ScriptSelectionText"] = Color3.new(255/255, 255/255, 255/255), ["ScriptSelectionBackground"] = Color3.new(110/255, 161/255, 110/255), ["ScriptFindSelectionBackground"] = Color3.new(246/255, 185/255, 246/255), ["ScriptMatchingWordSelectionBackground"] = Color3.new(226/255, 230/255, 226/255), ["ScriptOperator"] = Color3.new(127/255, 127/255, 127/255), ["ScriptNumber"] = Color3.new(0/255, 127/255, 0/255), ["ScriptString"] = Color3.new(127/255, 0/255, 127/255), ["ScriptComment"] = Color3.new(0/255, 127/255, 0/255), ["ScriptPreprocessor"] = Color3.new(127/255, 0/255, 127/255), ["ScriptKeyword"] = Color3.new(0/255, 0/255, 0/255), ["ScriptBuiltInFunction"] = Color3.new(0/255, 0/255, 0/255), ["ScriptWarning"] = Color3.new(0/255, 0/255, 0/255), ["ScriptError"] = Color3.new(255/255, 0/255, 255/255), ["DebuggerCurrentLine"] = Color3.new(255/255, 255/255, 255/255), ["DebuggerErrorLine"] = Color3.new(255/255, 204/255, 255/255), ["DiffFilePathText"] = Color3.new(0/255, 0/255, 0/255), ["DiffTextHunkInfo"] = Color3.new(117/255, 117/255, 117/255), ["DiffTextNoChange"] = Color3.new(0/255, 0/255, 0/255), ["DiffTextAddition"] = Color3.new(0/255, 0/255, 0/255), ["DiffTextDeletion"] = Color3.new(0/255, 0/255, 0/255), ["DiffTextSeparatorBackground"] = Color3.new(236/255, 243/255, 236/255), ["DiffTextNoChangeBackground"] = Color3.new(255/255, 255/255, 255/255), ["DiffTextAdditionBackground"] = Color3.new(225/255, 247/255, 225/255), ["DiffTextDeletionBackground"] = Color3.new(255/255, 219/255, 255/255), ["DiffLineNum"] = Color3.new(117/255, 117/255, 117/255), ["DiffLineNumSeparatorBackground"] = Color3.new(216/255, 230/255, 216/255), ["DiffLineNumNoChangeBackground"] = Color3.new(250/255, 250/255, 250/255), ["DiffLineNumAdditionBackground"] = Color3.new(206/255, 241/255, 206/255), ["DiffLineNumDeletionBackground"] = Color3.new(255/255, 202/255, 255/255), ["DiffFilePathBackground"] = Color3.new(250/255, 250/255, 250/255), ["DiffFilePathBorder"] = Color3.new(235/255, 235/255, 235/255), ["Separator"] = Color3.new(204/255, 204/255, 204/255), ["ButtonBorder"] = Color3.new(182/255, 182/255, 182/255), ["ButtonBorder_Disabled"] = Color3.new(204/255, 204/255, 204/255), ["ButtonText"] = Color3.new(0/255, 0/255, 0/255), ["ButtonText_Disabled"] = Color3.new(120/255, 120/255, 120/255), ["InputFieldBorder"] = Color3.new(200/255, 200/255, 200/255), ["InputFieldBorder_Selected"] = Color3.new(102/255, 146/255, 102/255), ["InputFieldBorder_Disabled"] = Color3.new(182/255, 182/255, 182/255), ["InputFieldBorder_Hover"] = Color3.new(168/255, 168/255, 168/255), ["CheckedFieldBackground"] = Color3.new(255/255, 255/255, 255/255), ["CheckedFieldBackground_Selected"] = Color3.new(0/255, 162/255, 0/255), ["CheckedFieldBackground_Pressed"] = Color3.new(219/255, 219/255, 219/255), ["CheckedFieldBackground_Disabled"] = Color3.new(200/255, 200/255, 200/255), ["CheckedFieldBackground_Hover"] = Color3.new(228/255, 238/255, 228/255), ["CheckedFieldBorder"] = Color3.new(182/255, 182/255, 182/255), ["CheckedFieldBorder_Hover"] = Color3.new(168/255, 168/255, 168/255), ["CheckedFieldIndicator"] = Color3.new(255/255, 255/255, 255/255), ["CheckedFieldIndicator_Disabled"] = Color3.new(136/255, 136/255, 136/255), ["HeaderSection"] = Color3.new(255/255, 255/255, 255/255), ["HeaderSection_Pressed"] = Color3.new(219/255, 219/255, 219/255), ["HeaderSection_Disabled"] = Color3.new(182/255, 182/255, 182/255), ["HeaderSection_Hover"] = Color3.new(228/255, 238/255, 228/255), ["Midlight"] = Color3.new(227/255, 227/255, 227/255), ["StatusBar"] = Color3.new(255/255, 255/255, 255/255) } return Light
-- A component to render a stack of notification messages local Message = require "message" local Notifier = { canvas = nil, style = { margin_top = 120, space = 10 } } function Notifier:new (canvas, messages) local o = setmetatable ({}, self) self.__index = self o.canvas = canvas o.messages = messages o.stack = {} for i = 1, table.getn (o.messages), 1 do table.insert (o.stack, Message:new (o.canvas, o.messages[i], 22)) end o.x = 0 o.y = 0 return o end function Notifier:locate (x, y) self.x = x self.y = y end function Notifier:render () local scale = self.canvas.scale local margin_top = self.style.margin_top * scale local space = self.style.space * scale local y = self.y + margin_top for i = 1, table.getn (self.stack), 1 do local x = self.x - (self.stack[i].width / 2) self.stack[i]:locate (x, y) self.stack[i]:render () y = y + self.stack[i].height + space end end return Notifier
-- pass it a table and optionally hierarchy number function printNbtTables(t, n) -- default hierarchy n to 0 if not set n = n or 0 -- indent string, length based on hierarchy local s = string.rep(" ", n) -- loop through all key/value pairs of the table for k,v in pairs(t) do -- if value is a table, recurse and increase indentation if type(v) == "table" then print(s..k..":") printNbtTables(v,n+1) else -- otherwise print the key/value pair which are usually "tagType" and "name" print(s..k, v) end end end printNbtTables(nbt)