content
stringlengths
5
1.05M
require('History'); function Client_GameRefresh(game) if(game.Us == nil or Mod.PlayerGameData.TerritorySellOffers == nil)then return; end local Nachricht = ""; if(tablelength(Mod.PlayerGameData.Peaceoffers)>0)then Nachricht = Nachricht .. "\n" .. 'You have ' .. tablelength(Mod.PlayerGameData.Peaceoffers) .. ' open peace offer'; end if(tablelength(Mod.PlayerGameData.AllyOffers)>0)then Nachricht = Nachricht .. "\n" .. 'You have ' .. tablelength(Mod.PlayerGameData.AllyOffers) .. ' open ally offer'; end if(tablelength(Mod.PlayerGameData.TerritorySellOffers)>0)then local offercount = 0; for _,player in pairs(Mod.PlayerGameData.TerritorySellOffers)do offercount = offercount + tablelength(player); end Nachricht = Nachricht .. "\n" .. 'You have ' .. offercount .. ' open territory tradement offer'; end ShowHistory(Mod.PlayerGameData.NeueNachrichten,game,Nachricht); end function tablelength(T) local count = 0; for _,elem in pairs(T)do count = count + 1; end return count; end
--new function DIALOG() --Trigger --Triggernumber,Type,Person --0,D,Hontoka --1,D,Pater Morpheus --2,D,Jenna --Items->NONE --Startnode, Person --0,Human Resource --50,Hontoka --100,Pater Morpheus --150,Jenna ----------------------------------------------------- --Human Resource Director NODE(0) SAY("Something came up again. Do you remember the murder of Defries? Well, its seems that this was not supposed to be the end. There was another murder of a CityAdmin employee of a similar rank to Defries.") ANSWER("CONTINUE",1) NODE(1) SAY("I hope this will not spread even further. In any case, the NCPD has allocated all available forces to the investigation of this case.") ANSWER("CONTINUE",2) NODE(2) SAY("It does not seem that easy to solve this mystery, since all investigations usually stop in a dead end. Come on, it cannot be possible that there are so many enemies of the CityAdmin to justify such a lengthy investigation...") ANSWER("I believe you underestimate that.",3) NODE(3) SAY("The main enemy is the Twilight Guardian. They constantly try to disrupt the authority of the CityAdmin, but that is nothing new. Apart from the Twilight Guardian there is only Crahn, Tsunami and the Black Dragon left.") ANSWER("CONTINUE",4) NODE(4) SAY("But Tsunami and Black Dragon are too occupied with their own business and their rivalry. And Crahn is only a remnant of their broken government. They still mourn their loss of power.") ANSWER("But you underestimate the personal motivations that could lead people to despise the CityAdmin.",5) NODE(5) SAY("I believe you are wrong there, the CityAdmin is fully supported by its citizens. Some citizens even control Neocron together with Reza. But that is not why I wanted to speak with you. The NCPD is very taxed at the moment.") ANSWER("CONTINUE",6) NODE(6) SAY("That is why the CityAdmin decided to allow Runners to investigate into that as well and thus help the NCPD. Information about various contacts have been forwarded to me and I have subsequently assigned the appropriate resulting missions to several Runners.") ANSWER("CONTINUE",7) NODE(7) SAY("Unfortunately those Runners who volunteer for such a task or who are qualified enough are a rare breed. That is why I thought about you.") ANSWER("You are telling me that I am not qualified enough?! And now you are asking me because you have no other Runners left?!!",8) NODE(8) SAY("My reasoning is not subject to a debate. Even if you do not seem to accept it, there are Runners that are better suited for such a job than you are. I did not want to express it in such a harsh manner, however.") ANSWER("CONTINUE",9) NODE(9) SAY("If you decide not to follow up this assignment I will of course have to make a note in your file. You should have learned to control your temperament by now.") ANSWER("Alright, I am cool. What is the assignment all about?",10) ANSWER("I am not yet in the mood for another task.",13) NODE(10) SAY("NCPD has informed us that a certain contact person of the Tsunamis with the name of Hontoka is interested in selling information to us. It could be important for the murder case but since the information is offered by a Tsunami I do not know how reliable it will be. I doubt it to be honest.") ANSWER("CONTINUE",11) NODE(11) SAY("But the CityAdmin would not be where it is today if it did not take all possibilities into consideration. You can find him in the Industrial district 02. If you get enough information talk to officer Jenna afterwards. I assume you already met her.") STARTMISSION() SETNEXTDIALOGSTATE(12) ENDDIALOG() NODE(12) SAY("Focus on the assignment. Hontoka is still waiting in Industrial 02 for you. If you have enough information go and visit the NCPD.") ENDDIALOG() NODE(13) SAY("Why don't you rest a little and come back when you feel that you are ready for a new assignment.") ENDDIALOG() ----------------------------------------------------- --Hontoka NODE(50) SAY("Are you the contact person form the CityAdmin?") ANSWER("Yes, I was told you have information for us. I hope it will pay off to make this long trip just to meet you.",51) NODE(51) SAY("I believe it will. Do you really think I would meet you in a place like this if it wasn't?") ANSWER("Alright, what have you got?",52) NODE(52) SAY("Not so fast!! I think I can expect some kind of compensation for this information since it might help to solve a murder. It should be worth something.") ANSWER("Who told you about the murder?",53) NODE(53) SAY("That is common knowledge by now. The walls in Neocron have eyes and ears even if many of them are from Reza and his CityAdmin.") ANSWER("Reza is not what we are discussing here. Concentrate on the topic. What do you want for it then?",54) NODE(54) SAY("Hehee. That is the beauty about it. I just want a small Datacube. Small and unimportant. Then I will tell you what I know. Don't keep me waiting too long.") SETNEXTDIALOGSTATE(55) ENDDIALOG() NODE(55) TAKEITEM(1501) if(result==0)then SAY("Hurry and bring a datacube to me.") ENDDIALOG() else SAY("Do you have it?") ANSWER("Yes, take it and then tell me your story,",56) end NODE(56) SAY("Datacubes are very fascinating. You can track them back to every individual owner, did you know that? Hehee. That was also an invention of the CityAdmin to keep a closer eye on their citizens.") ANSWER("CONTINUE",57) NODE(57) SAY("But I shall tell you what information I gathered. There is supposed to be a meeting between Crahn and Twilight Guardian and I believe you should closely follow their movements.") ANSWER("Could that be a little bit more precise?",58) NODE(58) SAY("Alright, Runner. Visit Father Morpheus in the Crest Village. I have heard the meeting is about the exchange of information. Even if that is only partially true. Do you want to know what they really exchange?") ANSWER("Don't keep me in suspense, tell me.",59) NODE(59) SAY("Crahn is selling information about important CityAdmin employees. Guess what this information is used for...") ANSWER("The murder...",60) NODE(60) SAY("Not bad, a CityAdmin Runner with a brain and who can use it. Visit Father Morpheus. He will not be pleased to be visited by a CityAdmin but you might get some more information. And now get lost, it would not look good if I was seen talking to a CityAdmin.") SETNEXTDIALOGSTATE(61) ACTIVATEDIALOGTRIGGER(0) ENDDIALOG() NODE(61) SAY("Father Morpheus can be found in Crest Village. I don't have more to say, so bugger off!") ENDDIALOG() ----------------------------------------------------- --Padre Morpheus NODE(100) ISMISSIONTARGETACCOMPLISHED(0) if(result==0)then SAY("I have no wish to speak to you.") ENDDIALOG() else SAY("Hrmph. What do you desire?") ANSWER("You are Father Morpheus, yes? I have a few questions.",101) end NODE(101) SAY("Who are you to assault me with your questions?") ANSWER("I am from CityAdmin. That should be reason enough for you to answer my question.",102) NODE(102) SAY("You still have much to learn and I feel the chaos in your mind. The CityAdmin? A Runner of the CityAdmin would not visit a Father of the Crahn faction unless he hopes to gain something from that. Maybe I will have what you desire already here.") ANSWER("Very well. Is it true that Crahn has records about CityAdmin employees?",103) NODE(103) SAY("Everybody makes a mental note of somebody he met, why shouldn't we do that too? Yes, we have information about you. Crahn has given us the gift to catch the most secret thoughts out of the very heads of other people.") ANSWER("You are even admitting it! Isn't there anything left that hasn't got Crahn fingerprints all over it? Have you given this information to the Twilight Guardian?",104) NODE(104) SAY("What if I say yes? Will there be an uproar from the CityAdmin? Will they annihilate us and the Twilight Guardian? I don't think so. Maybe I could help you better if I better understood what precisely you want.") ANSWER("Don't play dumb with me! The two CityAdmin employees that were killed in cold blood are already known everywhere.",105) NODE(105) SAY("That proves nothing! It only proves that even CityAdmin employees are not invincible but mortal, like the rest of us. Was that everything? CityAdmin?") ANSWER("You don't seem to like the CityAdmin very much.",106) NODE(106) SAY("I only see how Reza is ruining Neocron. Everything that was carefully created by us is systematically destroyed. Everything within Neocron is getting worse each day.") ANSWER("That is very arrogant and would cost your life within the boundaries of Neocron. You are lucky to be in the Wastelands. And after all it was you who destroyed everything! Your dictatorship almost ruined Neocron! It was our luck that Reza freed us of that cruel situation.",107) NODE(107) SAY("How naive. You really believe that Reza is your saviour? Back when the psi monk government was still operational everything was in order. It was only when Reza and his CityAdmin took over that everything started going downhill. The Outzone was the first to fall. At one time the Outzone was a striving and lively place full of busy people.") ANSWER("CONTINUE",108) NODE(108) SAY("Today it is a monument to the unbelievable incapability of the government and therefore Reza himself.") ANSWER("Don't twist the facts! Who committed all these heineous experiments on humans?! Who held the citizens of Neocron under slave like conditions?! You! You bitching Crahn! Do you know what I think about your Crahn? I give a shit on Crahn! Without that asshole everything would be better!",109) NODE(109) SAY("ENOUGH! To insult Crahn can only be revenged with your blood!") ATTACK() ENDDIALOG() ----------------------------------------------------- --Officer Jenna NODE(150) ISMISSIONTARGETACCOMPLISHED(1) if(result==0)then SAY("I am busy at the moment.") ENDDIALOG() else SAY("I have already been informed that you would help us once more with the investigation. Welcome on board. Could you find anything useful through the contact you were given?") ANSWER("It was a dead end. The only thing I got is that Crahn is selling information about CityAdmin employees to Twilight Guardian.",151) end NODE(151) SAY("They did what?") ANSWER("Yeah, they sold information about CityAdmin employees to the Guardians.",152) NODE(152) SAY("We knew that they have extensive information about us but we did not know that they are selling it . This alliance between Crahn and Twilight Guardian should have been taken more serious right from the beginning.") ANSWER("There is an alliance between those two? How can that be?",153) NODE(153) SAY("Yes, there is an alliance. It is fragile but is kept together through their common goal I assume. In this case it is to get rid of the current government. I only have to think about it and I get dizzy.") ANSWER("CONTINUE",154) NODE(154) SAY("At that time my parents have suffered strongly under the Crahn government. Another reason why I am working with the NCPD today. The reason why I would rather die before allowing Crahn to rule Neocron again.") ANSWER("But that is crazy, how would these two small groups ever be able to do that?",155) NODE(155) SAY("Compare them with a virus which infests a healthy human. The virus is small in relation to the human but it will still kill him good.") ANSWER("CONTINUE",156) NODE(156) GIVEMONEY(5000) SETNEXTDIALOGSTATE(157) SAY("Like two different kind of virus that you battle with appropriate methods. Don't fool yourself, they are a danger for Neocron. But what am I talking, there is so much to do. Here are your 5000 credits. Keep in shape, I am sure we could use your service again.") EPICRUNFINISHED(1,1) ACTIVATEDIALOGTRIGGER(2) ENDDIALOG() NODE(157) SAY("Go away") ENDDIALOG() end
local require = require local base_handler = require("plugins.base_handler") local req_var_extractor = require("core.req.req_var_extractor") local base_dao = require("core.dao.base_dao") local api_router_dao = require("core.dao.api_router_dao") local resp_utils = require("core.resp.resp_utils") local config = require("plugins.api_router.config") local json = require("core.utils.json") local utils = require("core.utils.utils") local PRIORITY = require("plugins.handler_priority") local err_resp_template_utils = require("core.utils.err_resp_template_utils") local error_utils = require("core.utils.error_utils") local error_type_biz = error_utils.types.ERROR_BIZ.name local error_type_sys = error_utils.types.ERROR_SYSTEM.name local error_type_upstream = error_utils.types.ERROR_UPSTREAM.name local healthcheck_helper = require("core.router.healthcheck_helper") local router_initializer = require("core.router.router_initializer") local get_healthchecker = healthcheck_helper.get_healthchecker local keep_target_circuit_break_open_status = healthcheck_helper.keep_target_circuit_break_open_status local selector_helper = require("core.router.selector_helper") local log_config = require("core.utils.log_config") local stringy = require("core.utils.stringy") local str_len = string.len local str_sub = string.sub local tonumber = tonumber local tostring = tostring local ngx = ngx local ngx_log = ngx.log local ERR = ngx.ERR local ngx_DEBUG = ngx.DEBUG local table = table local TOKEN_VALIDATION = 0; local AUTH = 1 local balancer_helper = require("core.router.balancer_helper") local ngx_balancer = require "ngx.balancer" local get_last_failure = ngx_balancer.get_last_failure local set_current_peer = ngx_balancer.set_current_peer local set_timeouts = ngx_balancer.set_timeouts local set_more_tries = ngx_balancer.set_more_tries local set_header = ngx.req.set_header local ngx_var = ngx.var local lower = string.lower local str_format = string.format --local api_group_dao = require("core.dao.api_route_dao") local api_route_handler = base_handler:extend() local plugin_name = config.plugin_name api_route_handler.PRIORITY = PRIORITY.api_router local function now_millseconds() return ngx.now() * 1000 end local function concat_upstream_uri(upstream_host,upstream_path, upstream_query_string) local upstream_uri if not upstream_host then upstream_host = "http://default_upstream/" end upstream_uri = upstream_host if upstream_path then if stringy.endswith(upstream_host,"/") and stringy.startswith(upstream_path,"/") then upstream_path = string.gsub(upstream_path,"/","",1) end upstream_uri = upstream_uri .. upstream_path end if upstream_query_string then upstream_uri = upstream_uri .."?"..upstream_query_string end return upstream_uri end local function get_balance_param(key) local value = base_dao.get_global_property_by_param_name(key) if value then return tonumber(value) end return value end local function add_header_of_request_id(is_gen_trace_id) if is_gen_trace_id == true then local request_id = req_var_extractor.extract_header_param("request_id") if not request_id or request_id == '' then request_id = utils.uuid() set_header("request_id",request_id) ngx.log(ngx.DEBUG,'request_id is ',request_id) end end ngx.var.trace_id = req_var_extractor.extract_header_param("request_id") or '-' end local function deal_websocket_headers() -- Keep-Alive and WebSocket Protocol Upgrade Headers if ngx_var.http_upgrade and lower(ngx_var.http_upgrade) == "websocket" then ngx_var.upstream_connection = "upgrade" ngx_var.upstream_upgrade = "websocket" else ngx_var.upstream_connection = "keep-alive" end end -- 修改request.headers local function deal_req_headers(api_group_info) ngx.log(ngx.DEBUG,'========gen_trace_id',api_group_info.gen_trace_id==1,api_group_info.gen_trace_id) add_header_of_request_id(api_group_info.gen_trace_id==1) deal_websocket_headers() ngx.var.request_headers = json.encode(req_var_extractor.extract_headers()); end -- 如果匹配到灰度分流器,把gray_divide_id改为对应的id local function match_gray_divide(api_group_info) local gray_divides = api_group_info.gray_divides if(not gray_divides or #gray_divides == 0)then return end for _, gray_divide in ipairs(gray_divides) do local is_match = selector_helper.is_match(gray_divide.selector) if is_match == true then api_group_info.gray_divide_id = gray_divide.id if tonumber(api_group_info.enable_balancing) == 0 then local upstream_domain_info = req_var_extractor.split_full_uri(api_group_info.upstream_domain_name) api_group_info.upstream_domain_name = upstream_domain_info.scheme .."://".. gray_divide.gray_domain end api_group_info.wheel_size = gray_divide.wheel_size break end end end --- -- set proxy pass information: --- 1. ngr handle loadbalance: calculate the upstream node's ip and port address --- 2. proxy to interval service's domain: calculate the upstream domain address -- @param api_group_info api router information has been configured in database -- @param req_info the current request information -- local function set_proxy_pass_info(api_group_info, req_info) local upstream_url local enable_balancing = tonumber(api_group_info.enable_balancing) or 0 if enable_balancing == 1 then -- ngr handle upstream loading balancing local upstream_host = "http://default_upstream/" upstream_url = concat_upstream_uri(upstream_host,req_info.path,req_info.query_string) ngx.var.upstream_url = upstream_url ngx.var.upstream_scheme = "http" ngx.var.upstream_host = req_info.req_host local balancer_address = {} balancer_address.group_id = api_group_info.id balancer_address.gray_divide_id = api_group_info.gray_divide_id local host_group_context = api_router_dao.build_host_group_context(api_group_info.host,api_group_info.group_context) balancer_address.upstream_group_context = api_group_info.group_context balancer_address.upstream_host = req_info.req_host balancer_address.healthchecker = get_healthchecker(host_group_context) if not balancer_address.healthchecker then ngx_log(ERR,str_format(log_config.sys_error_format,log_config.ERROR,"balancer_address.healthchecker is nil for api_group: " .. host_group_context)) end balancer_address.upstream_service_id = api_group_info.upstream_service_id balancer_address.balance_algo = api_group_info.lb_algo balancer_address.wheel_size = api_group_info.wheel_size balancer_address.targets = router_initializer.get_targets(api_group_info, api_group_info.gray_divide_id,true) balancer_address.connection_timeout = get_balance_param(config.balance_connection_timeout_key) or 10000 balancer_address.send_timeout = get_balance_param(config.balance_send_timeout_key) or 60000 balancer_address.read_timeout = get_balance_param(config.balance_read_timeout_key) or 60000 balancer_address.retries_count = get_balance_param(config.balance_retries_count_key) or 0 balancer_address.has_tried_count = 0 balancer_address.tries = {} local ok, err = balancer_helper.execute(balancer_address) if not ok then local msg = "failed to retry the dns/balancer resolver for " .. host_group_context .. "' with: ".. tostring(err) ngx_log(ERR,str_format(log_config.biz_error_format,log_config.ERROR,msg)) error_utils.add_error_2_ctx(error_type_biz,config.small_error_types.biz.type_no_available_balancer) resp_utils.say_response_UPSTREAM_ERROR(tostring(err)) return end local ip = balancer_address.ip local port = balancer_address.port if not ip or not port then local msg = "failed to retry the dns/balancer resolver for ".. host_group_context .. "' with: ip or host id invalid."; ngx_log(ERR,str_format(log_config.biz_error_format,log_config.ERROR,msg)) error_utils.add_error_2_ctx(error_type_sys,config.small_error_types.sys.type_balancer_execute_error) resp_utils.say_response_UPSTREAM_ERROR(msg) return end ngx.ctx.balancer_address = balancer_address else -- upstream to interval service domain local upstream_domain_name =api_group_info.upstream_domain_name local len = str_len(upstream_domain_name) if not (str_sub(upstream_domain_name,len) == "/") then upstream_url = upstream_domain_name .."/" else upstream_url = upstream_domain_name end upstream_url = concat_upstream_uri(upstream_url, req_info.path,req_info.query_string) ngx_log(ngx.INFO,'upstream url is:',upstream_url) local upstream_domain_info = req_var_extractor.split_full_uri(upstream_domain_name) -- 设置 proxy_pass $upstream_url upstream_scheme upstream_host ngx.var.upstream_url = upstream_url ngx.var.upstream_scheme = upstream_domain_info.scheme ngx.var.upstream_host = upstream_domain_info.host end end local function get_auth_service_uri(uri) local server_domain = base_dao.get_global_property_by_param_name(config.auth_server_domain_name) if not server_domain then ngx_log(ERR,str_format(log_config.biz_error_format,log_config.ERROR,"auth_service_uri not found...")) error_utils.add_error_2_ctx(error_type_sys,config.small_error_types.sys.type_auth_conf_error) resp_utils.say_response_SERVICE_NOT_FOUND() return end local url if uri then url = server_domain .. uri else -- 约定访问 API Gateway 的 uri 就是auth服务的地址 url = server_domain .. ngx.var.request_uri end return url end -- 生成签名 local function generateSign(signs,app_key) local keys = {} for k, v in pairs(signs) do table.insert(keys,k) end table.sort(keys) local str="" for _,k in ipairs(keys) do str = str .. k .. "=" .. signs[k] .. "&" end str = str .. "appKey=" .. app_key return ngx.md5(str) end -- 构建需要签名的参数 local function build_sign_param(app_id,app_key) local signs = {} signs["appId"]=app_id signs["language"]="zh-CN" signs["requestId"]= utils.random_string() signs["timeZone"]="GMT" signs["timestamp"]=ngx.time()--ngx.utctime() signs["sign"] = generateSign(signs,app_key) return signs end --TODO please fix bugs, request method must be followed auth api local function build_auth_req_param(app_id, app_key, uri) local req = {} local method = ngx.var.request_method local headers = {} local data = {} local body={} local token,device_Id if method == "GET" then token = req_var_extractor.extract_query_param("token") device_Id = req_var_extractor.extract_query_param("deviceId") elseif method == "POST" then token = req_var_extractor.extract_post_param("token") device_Id = req_var_extractor.extract_post_param("deviceId") end if not token then error_utils.add_error_2_ctx(error_type_biz,config.small_error_types.biz.type_token_error) resp_utils.say_response_SERVICE_UNAUTHORIZED("'token' can't be empty") return end -- add token to ctx ngx.ctx.consumer_id_type = "token" ngx.ctx.consumer_id = token headers["content-type"] = "application/json" data["token"] = token if device_Id then data["deviceId"] = device_Id end body["data"]=data body["sign"]=build_sign_param(app_id,app_key) req["uri"] = uri req["headers"] = headers req["method"] = "POST" req["body"]=json.encode(body) return req end local function check_auth_token(ngr_config,url) local app_id = base_dao.get_global_property_by_param_name(config.auth_server_ngr_app_id) local app_key = base_dao.get_global_property_by_param_name(config.auth_server_ngr_app_key) if not app_id or not app_key then ngx_log(ERR,str_format(log_config.biz_error_format,log_config.ERROR,"app_id or app_key is null")) error_utils.add_error_2_ctx(error_type_sys,config.small_error_types.sys.type_auth_conf_error) resp_utils.say_response_SERVICE_UNAUTHORIZED("app_id or app_key is null") return end local req = build_auth_req_param(app_id,app_key,url) local httpc = require("core.utils.http_client")(ngr_config.http_client) ngx_log(ngx_DEBUG,"check_auth_token req:",json.encode(req)) local resp,err = httpc:send(req) if not resp then ngx_log(ERR,str_format(log_config.biz_error_format,log_config.ERROR,"token verification failed;err:" .. err)) error_utils.add_error_2_ctx(error_type_sys,config.small_error_types.sys.type_auth_invoke_error) resp_utils.say_response_SERVICE_UNAUTHORIZED(err) return end local body = json.decode(resp.body) if tonumber(body.errNo) ~= TOKEN_VALIDATION then ngx_log(ERR,str_format(log_config.biz_error_format,log_config.ERROR,"token verification failed.errNo:" .. body.errNo)) error_utils.add_error_2_ctx(error_type_biz,config.small_error_types.biz.type_token_error) resp_utils.say_response_SERVICE_UNAUTHORIZED(nil) return end if httpc then httpc:close() end end -- --refresh balancer address information from shared cache in balancer phase --@param address will be refresh -- local function refresh_balancer_address(addr) local group_context = addr.upstream_group_context local host = addr.upstream_host; local api_group = api_router_dao.get_api_group_by_group_context(host, group_context) addr.targets = router_initializer.get_targets(api_group, addr.gray_divide_id,true) end function api_route_handler:new(app_context) api_route_handler.super.new(self, plugin_name) self.app_context = app_context end function api_route_handler:access() api_route_handler.super.access(self) ngx_log(ngx_DEBUG,"in api_router access start ============") local req_info = req_var_extractor.extract_req_uri() local api_group_info = api_router_dao.get_api_group_by_group_context(req_info.req_host, req_info.api_group_context) if not api_group_info then -- host_group_context 不存在 ngx_log(ngx.INFO,"host_group_context [" .. (req_info.req_host.. '-'.. req_info.api_group_context) .. "] not exist") error_utils.add_error_2_ctx(error_type_biz,config.small_error_types.biz.type_service_not_found) resp_utils.say_response_SERVICE_NOT_FOUND() return end -- generate upstream path, req_info.path append to group context or rewrite to req_var_extractor.gen_upstream_req_info_for_group_context(api_group_info,req_info) -- 缓存api_group_id,cache_client ngx.var.api_router_group_id = api_group_info.id ngx_log(ngx_DEBUG,"debug display current api router information:".. json.encode(api_group_info)) -- 是否需要授权 if tonumber(api_group_info.need_auth) == AUTH then -- 需要授权 check_auth_token(self.app_context.config,get_auth_service_uri(config.auth_api.get_login_info)) else --add remote ip to consumer id ngx.ctx.consumer_id_type = "ip" ngx.ctx.consumer_id = req_var_extractor.extract_IP() end deal_req_headers(api_group_info) match_gray_divide(api_group_info) ngx_log(ngx_DEBUG,"debug display current api router information after match gray divide:".. json.encode(api_group_info)) set_proxy_pass_info(api_group_info,req_info) ngx_log(ngx_DEBUG,"in api_router access end ============") end function api_route_handler: init_worker_ext_timer() api_route_handler.super:init_worker_ext_timer() ngx_log(ngx_DEBUG,"in api_router init_worker_ext_timer ============") err_resp_template_utils.init_2_redis(plugin_name,self.app_context.store,self.app_context.cache_client) end --- -- upstream balancer execute: -- 1. set currernt peer -- 2. set timeouts -- no support for retries -- function api_route_handler : balancer() api_route_handler.super: balancer() ngx_log(ngx_DEBUG,"in api_router balancer ============") local addr = ngx.ctx.balancer_address addr.has_tried_count = addr.has_tried_count + 1 ngx_log(ngx_DEBUG,"addr.has_tried_count ============" .. addr.has_tried_count) local las_status_code local tries = addr.tries local current_try = {} tries[addr.has_tried_count] = current_try current_try.balancer_start = now_millseconds() if addr.has_tried_count > 1 then -- only call balancer on retry, first one is done in `access` which runs -- in the ACCESS context and hence has less limitations than this BALANCER -- context where the retries are executed -- collect the unhealthy target into shard dict[shard_dict_healthchecks] again if addr.half_open then keep_target_circuit_break_open_status(addr.group_id,addr.ip,addr.port) else -- record faliure data local previous_try = tries[addr.has_tried_count - 1] previous_try.state, previous_try.code = get_last_failure() las_status_code = previous_try.code -- Report HTTP status for passive health checks if addr.healthchecker then local msg = "previous_try.state: " .. previous_try.state .. ",previous_try.code:" .. previous_try.code; ngx_log(ERR,str_format(log_config.biz_error_format,log_config.ERROR,msg)) error_utils.add_error_2_ctx(error_type_upstream,previous_try.code) if previous_try.state == "failed" and not previous_try.code then local _, err = addr.healthchecker:report_tcp_failure(addr.ip, addr.port, nil, "passive") if err then ngx_log(ERR,str_format(log_config.biz_error_format,log_config.ERROR,"[healthchecks] failed reporting status: "..err)) end ngx.log(ngx.INFO, "report upstream tcp failure,ip=", addr.ip,",port=" ,addr.port) else local _, err = addr.healthchecker:report_http_status(addr.ip, addr.port, previous_try.code, "passive") if err then ngx_log(ERR,str_format(log_config.biz_error_format,log_config.ERROR,"[healthchecks] failed reporting status: "..err)) end ngx.log(ngx.INFO, "report upstream http failure,ip=", addr.ip,",port=" ,addr.port,", http_status= ",previous_try.code) end end end -- 非幂等方法上报过后,直接退出 local method_name = req_var_extractor.extract_method() if utils.is_non_idempotent(method_name) then las_status_code = las_status_code or 502 ngx.exit(las_status_code) return end refresh_balancer_address(addr) local ok, err =balancer_helper.execute(addr) if not ok then local msg = "failed to retry the dns/balancer resolver for ".. addr.upstream_service_id .. "' with: " .. tostring(err) ngx_log(ERR,str_format(log_config.biz_error_format,log_config.ERROR,msg)) error_utils.add_error_2_ctx(error_type_sys,config.small_error_types.sys.type_balancer_execute_error) ngx.exit(502) return end else -- first try, so set the max number of retries local retries = addr.retries_count if retries > 0 then local method_name = req_var_extractor.extract_method() if not utils.is_non_idempotent(method_name) then set_more_tries(retries) end end end current_try.ip = addr.ip current_try.port = addr.port local ip = addr.ip local port = addr.port local ok, err = set_current_peer(ip, port) if not ok then local msg = "failed to set the current peer (address: " .. tostring(ip), " port: " .. tostring(port), "): " .. tostring(err); ngx_log(ERR,str_format(log_config.sys_error_format,log_config.ERROR,msg)) error_utils.add_error_2_ctx(error_type_sys,config.small_error_types.sys.type_balancer_execute_error) return ngx.exit(502); end ok, err = set_timeouts(addr.connection_timeout / 1000, addr.send_timeout / 1000, addr.read_timeout /1000) if not ok then ngx_log(ERR,str_format(log_config.sys_error_format,log_config.ERROR,"could not set upstream timeouts: "..err)) end -- record try-latency local try_latency = now_millseconds() - current_try.balancer_start current_try.balancer_latency = try_latency current_try.balancer_start = nil end return api_route_handler
-- -- Created by IntelliJ IDEA. -- User: macbookair -- Date: 01/04/17 -- Time: 18:43 -- To change this template use File | Settings | File Templates. ---- -- Created by IntelliJ IDEA. -- User: macbookair -- Date: 30/03/17 -- Time: 19:06 -- To change this template use File | Settings | File Templates. -- local layout = {} -- -- Creates an instance of layout. -- Receives a single argument which is a table with the following keys: type and orientation. At the moment only linearLayout is supported as type and orientation is a string which assumes values for "vertical" or "horiozontal". -- function layout:newLayout(options) local newLayout = {} setmetatable(newLayout, {__index=layout}) newLayout._nativeObject = NativeInterface:newLayout(options) return newLayout end -- -- Insert a component into this layout. It's organization in the scene will be automatically made by this layout. -- @param component An object of type Component. function layout:insert(component) self._nativeObject:insert(component._nativeObject) end return layout
_WIFI_APS = { {["ssid"]="", ["pwd"]=""}, {["ssid"]="", ["pwd"]=""} } PROTOCOL = "iot:1" PROTOCOL_ALLOW_UNENCRYPTED = false ENCODER_AESSHA1_STATICIV = 'abcdef2345678901' ENCODER_AESSHA1_IVKEY = '2345678901abcdef' ENCODER_AESSHA1_DATAKEY ='0123456789abcdef' ENCODER_AESSHA1_PASSPHRASE = 'mypassphrase' PORT = 5053 CHANNELS = {1} if file.exists('parameters-device.lc') then dofile("parameters-device.lc") else dofile("parameters-device.lua") end
local lume = require "lib/lume" local event = require "event" ui.buttonSettings = { name = "noname", x = 0, y = 0, w = 100, h = 100, text = "", font = nil, align = "center", hoverColor = { 37 / 255, 41 / 255, 49 / 255 }, downColor = { 44 / 255, 49 / 255, 58 / 255 }, color = { 33 / 255, 37 / 255, 43 / 255 }, } function ui.button( settings ) local s = lume.merge( ui.buttonSettings, settings ) --local name, x, y, w, h, text, font, align = s.name, s.x, s.y, s.w, s.h, s.text, s.font, s.align local state = { hover = false, down = { false, false, false}, pressed = { 0, 0, 0 }, released = { 0, 0, 0}, } -- check if mouse is hovering above button, and set color accordingly if( mouseOver( s.x,s.y,s.w,s.h ) and ui.enableInput ) then state.hover = true love.graphics.setColor( s.hoverColor ) -- check if mousebuttons are down for i = 1, 3 do if( love.mouse.isDown( i ) ) then state.down[i] = true -- change color if a mouseButton is pressed love.graphics.setColor( s.downColor ) end end else -- if not hovering state.hover = false love.graphics.setColor( s.color ) end -- calc things from events, eventinput if( ui.enableInput ) then for i, input in ipairs( event.mousepressed ) do if( pointInsideRectangle( input.x, input.y, s.x,s.y,s.w,s.h ) ) then state.pressed[input.button] = state.pressed[input.button] + 1 end end for i, input in ipairs( event.mousereleased ) do if( pointInsideRectangle( input.x, input.y, s.x,s.y,s.w,s.h ) ) then state.released[input.button] = state.released[input.button] + 1 end end end -- draw the button love.graphics.rectangle("fill", s.x,s.y,s.w,s.h ) -- s.text if( s.text ~= nil ) then love.graphics.setColor( 255, 255, 255, 255 ) if( s.font ~= nil ) then love.graphics.setFont( s.font ) else s.font = love.graphics.getFont() end if( s.align ) then love.graphics.printf( s.text, s.x,s.y + ( s.h - s.font:getHeight( s.text ) ) / 2,s.w, s.align ) end end return state end
local fakeTilesHelper = require("helpers.fake_tiles") local jautils = require("mods").requireFromPlugin("libraries.jautils") local fallingBlockIgnoreSolids = { name = "FrostHelper/FallingBlockIgnoreSolids", sprite = fakeTilesHelper.getEntitySpriteFunction("tiletype", false), depth = function (room, entity) return entity.behind and 5000 or 0 end, } jautils.createPlacementsPreserveOrder(fallingBlockIgnoreSolids, "default", { { "width", 8 }, { "height", 8 }, { "tiletype", "3" }, { "climbFall", true }, { "behind", false }, { "allowStaticMovers", true }, }) return fallingBlockIgnoreSolids
local lust = require "lust/lust" local Enum = require "enum" local describe, it, expect = lust.describe, lust.it, lust.expect describe("Enums", function() it("can define a new enum", function() local letters = Enum {"a", "b", "c"} end) it("can access an enum directly by index", function() local stars = Enum {"sirius", "betelgeuse", "procyon", "antares"} expect(stars.sirius).to.be("sirius") expect(stars.betelgeuse).to.be("betelgeuse") expect(stars.procyon).to.be("procyon") expect(stars.antares).to.be("antares") end) it("will error on duplicate variant definitions", function() expect(function() local letters = Enum {"a", "b", "c", "d", "c"} end).to.fail() end) it("trying to access a variant that does not exist should fail", function() local brothers = Enum {"tsusi", "yowie", "dudi", "dodoy"} expect(function() print(brothers.wallachia) end).to.fail() end) it("trying to set a value on an enum should fail", function() local directions = Enum {"left", "right", "up", "down"} expect(function() directions.middle = true end).to.fail() end) it("can use non-string variants", function() local fibs = Enum {1, 2, 3, 5, 8, 13} expect(fibs[1]).to.be(1) expect(fibs[2]).to.be(2) expect(fibs[3]).to.be(3) expect(fibs[5]).to.be(5) expect(fibs[8]).to.be(8) expect(fibs[13]).to.be(13) local table_a, table_b, table_c = {}, {}, {} local all_tables = Enum {table_a, table_b, table_c} expect(all_tables[table_a]).to.be(table_a) expect(all_tables[table_b]).to.be(table_b) expect(all_tables[table_c]).to.be(table_c) end) end)
-- 2e Essais de faire des fonctions trigos qui manque dans NodeMCU -- source pour sin&cos: https://www.esp8266.com/viewtopic.php?p=64415# -- source pour arcsin&arctan: http://www.electronicwings.com/nodemcu/magnetometer-hmc5883l-interfacing-with-nodemcu print("\ntrigo2.lua zf180726.1149 \n") function sin(x) local p=-x*x*x local f=6 local r=x+p/f for j=1,60 do p=-p*x*x f=f*2*(j+1)*(j+j+3) r=r+p/f end return r end function cos(x) return sin(math.pi/2-x) end function tan(x) return sin(x)/cos(x) end pi = 3.14159265358979323846 function arcsin(value) local val = value local sum = value if(value == nil) then return 0 end -- as per equation it needs infinite iterations to reach upto 100% accuracy -- but due to technical limitations we are using -- only 10000 iterations to acquire reliable accuracy for i = 1,10000, 2 do val = (val*(value*value)*(i*i)) / ((i+1)*(i+2)) sum = sum + val; end return sum end function arctan(value) if(value == nil) then return 0 end local _value = value/math.sqrt((value*value)+1) return arcsin(_value) end function atan2(y, x) if(x == nil or y == nil) then return 0 end if(x > 0) then return arctan(y/x) end if(x < 0 and 0 <= y) then return arctan(y/x) + pi end if(x < 0 and y < 0) then return arctan(y/x) - pi end if(x == 0 and y > 0) then return pi/2 end if(x == 0 and y < 0) then return -pi/2 end if(x == 0 and y == 0) then return 0 end return 0 end print("On voit que l'arc sinus est précis au 1/2% prêt !") print("sin(3.14/2): "..sin(3.14/2)) print("pi/(arcsin(1)*2): "..pi/(arcsin(1)*2))
--[[ Copyright (c) 2016 by Marco Lizza ([email protected]) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgement in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ]]-- -- MODULE INCLUSIONS ----------------------------------------------------------- local Entity = require('game.entities.entity') local graphics = require('lib.graphics') local soop = require('lib.soop') -- MODULE DECLARATION ---------------------------------------------------------- -- MODULE OBJECT CONSTRUCTOR --------------------------------------------------- local Static = soop.class(Entity) -- LOCAL CONSTANTS ------------------------------------------------------------- -- LOCAL FUNCTIONS ------------------------------------------------------------- -- MODULE FUNCTIONS ------------------------------------------------------------ function Static:initialize(parameters) Entity.initialize(self, parameters) self.type = 'static' self.priority = parameters.priority self.reference = self.life self.image = love.graphics.newImage(parameters.image) end function Static:draw() -- We don't neet to check if the entity is alive, here. Only living entities -- are redrawn! local x, y = unpack(self.position) graphics.image(self.image, x, y) end -- END OF MODULE --------------------------------------------------------------- return Static -- END OF FILE -----------------------------------------------------------------
--------------------------------------------------------------------------------------------------- -- User story: TBD -- Use case: TBD -- -- Requirement summary: TBD -- -- Description: -- In case: -- Mobile application sends request with isTemplate = true and STATIC image type -- SDL must: -- send request with received paramters to HMI --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local common = require('test_scripts/SDL5_0/Image_template/commonImageTemplate') --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false --[[ Local Variables ]] local fileName = "icon.png" local paramsAddCommand = common.addCommandParams() paramsAddCommand.requestParams.cmdIcon.imageType = "STATIC" paramsAddCommand.requestParams.cmdIcon.value = fileName paramsAddCommand.requestParams.cmdIcon.isTemplate = true paramsAddCommand.responseUiParams.cmdIcon.value = fileName paramsAddCommand.responseUiParams.cmdIcon.isTemplate = true paramsAddCommand.responseUiParams.cmdIcon.imageType = "STATIC" --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", common.preconditions) runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start) runner.Step("Register App", common.registerApp) runner.Step("Activate App", common.activateApp) runner.Step("Adding PNG file via PutFile", common.putFile) runner.Title("Test") runner.Step("AddCommand with isTemplate = true with STATIC image type", common.rpcWithCustomResultCode, { "AddCommand", paramsAddCommand, "UNSUPPORTED_RESOURCE", true }) runner.Title("Postconditions") runner.Step("Stop SDL", common.postconditions)
-------------------------------------------------------------- -- -- "THE BEERWARE LICENSE" (Revision 42): -- Prosper wrote this code. As long as you retain this -- notice, you can do whatever you want with this stuff. If we -- meet someday, and you think this stuff is worth it, you can -- buy me a beer in return. -- -------------------------------------------------------------- --[[ Structure of a dop : - ID : unique identifier - command : command or text to run/print at a given interval - delay : the given interval - running : true if the dop is running, false if stopped - exist : false if the dop has been deleted - current : a timer, when it reaches the "delay" value it the "command" will be run - frame : reference to the UI frame of that dop ]] Doppler = LibStub("AceAddon-3.0"):NewAddon("Doppler") GUI = LibStub("AceGUI-3.0") function Doppler:OnInitialize() -- Called when the addon is loaded Doppler.dopHolder = {} Doppler.dopHolder["count"] = 0 Doppler.dopHolder["dops"] = {} end function Doppler:OnEnable() -- Called when the addon is enabled Doppler.InitGUI() Doppler.InitTick() end function Doppler:OnDisable() -- Called when the addon is disabled end ----- -- Dop creation and removal ----- function Doppler:CreateDop(command, delay) local dop = {} dop["command"] = command dop["delay"] = tonumber(delay) if dop["delay"] == nil then return nil end if dop["delay"] < 0.5 then dop["delay"] = 0.5 end if dop["delay"] > 1000 then dop["delay"] = 1000 end dop["current"] = dop["delay"] dop["running"] = false dop["exist"] = true local Group = Doppler:BuildDopFrame(dop, command, delay) GUI.Scroll:AddChild(Group) return dop end function Doppler:AddDop(dop) local dH = Doppler.dopHolder local dops = dH["dops"] dop["ID"] = dH["count"] dops[dH["count"]] = dop dH["count"] = dH["count"] + 1 end function Doppler:RemoveDop(dop) dop["exist"] = false dop["running"] = false -- hide frame Doppler:RebuildScroll() end function Doppler:BuildDopFrame(dop) local command = dop["command"] local delay = dop["delay"] local Group = GUI:Create("DopplerInlineGroupProgress") Group:SetFullWidth(true) Group:SetHeight(15) Group:SetLayout("Flow") local labelCmd = GUI:Create("Label") labelCmd:SetText(command) labelCmd:SetFontObject(ChatFontNormal) labelCmd:SetRelativeWidth(0.8) local labelDelay = GUI:Create("Label") labelDelay:SetText(delay.." sec") labelDelay:SetFontObject(ChatFontNormal) labelDelay:SetColor(.8,.8,0) labelDelay:SetRelativeWidth(0.19) local buttonRun = GUI:Create("Button") buttonRun:SetRelativeWidth(0.6) buttonRun:SetText("Run") if dop["running"] then buttonRun:SetText("Stop") end buttonRun:SetCallback("OnClick", function() if not dop["running"] then dop["current"] = dop["delay"] dop["running"] = true buttonRun:SetText("Stop") else dop["current"] = 0 dop["running"] = false dop["frame"]:SetProgress(0) buttonRun:SetText("Run") end end) local buttonDel = GUI:Create("Button") buttonDel:SetRelativeWidth(0.39) buttonDel:SetText("Del") buttonDel:SetCallback("OnClick", function() dop["frame"]:SetProgress(0) Doppler:RemoveDop(dop) end) Group:AddChild(labelCmd) Group:AddChild(labelDelay) Group:AddChild(buttonRun) Group:AddChild(buttonDel) dop["frame"] = Group return Group end function Doppler:RebuildScroll() local Scroll = GUI.Scroll Scroll:ReleaseChildren() local dH = Doppler.dopHolder local dops = dH["dops"] for i=0,dH["count"]-1,1 do local dop = dops[i] if dop["exist"] then local Group = Doppler:BuildDopFrame(dop) dop["frame"]:SetProgress(0) Scroll:AddChild(Group) end end end ----- -- Loop and Tick functions ----- function Doppler.InitTick() Doppler.TICK_PERIOD = 0.25 Doppler.oldCurTime = 0 Doppler.tickCounter = 0 Doppler.LoopFrame = CreateFrame("Frame") Doppler.LoopFrame.elapsed = 0 Doppler.LoopFrame:SetScript("OnUpdate", Doppler.OnUpdate) end function Doppler.OnUpdate(self, elapsed) self.elapsed = self.elapsed+elapsed Doppler.tickCounter = Doppler.tickCounter + elapsed if Doppler.tickCounter > Doppler.TICK_PERIOD then Doppler.UpdateTick(self.elapsed) Doppler.tickCounter = Doppler.tickCounter % Doppler.TICK_PERIOD end end function Doppler.UpdateTick(curTime) local elapsed = curTime - Doppler.oldCurTime Doppler.oldCurTime = curTime --print("TICK "..elapsed) local dH = Doppler.dopHolder local dops = dH["dops"] for i = 0,dH["count"]-1,1 do local dop = dops[i] if dop["exist"] and dop["running"] then dop["current"] = dop["current"] + elapsed dop["frame"]:SetProgress(dop["current"]/dop["delay"]) if dop["current"] > dop["delay"] then SendChatMessage(dop["command"],"GUILD") dop["current"] = dop["current"]%dop["delay"] end end end end ----- -- Main GUI ----- function Doppler.InitGUI() GUI.mainFrame = GUI:Create("DopplerMainFrame") GUI.mainFrame:SetCallback("OnClose",function(widget) GUI:Release(widget) end) GUI.mainFrame:SetTitle("Doppler") GUI.mainFrame:SetLayout("Flow") GUI.mainFrame:SetWidth(200) GUI.mainFrame:SetHeight(50) -- minimized GUI.Header = GUI:Create("InlineGroup") GUI.Header:SetFullWidth(true) GUI.Header:SetLayout("Flow") GUI.HeaderCommand = GUI:Create("DopplerEditBox") GUI.HeaderCommand:SetLabel("Commande") GUI.HeaderCommand:SetRelativeWidth(0.8) GUI.HeaderDelay = GUI:Create("DopplerEditBox") GUI.HeaderDelay:SetLabel("Délai") GUI.HeaderDelay:SetRelativeWidth(0.19) GUI.HeaderButton = GUI:Create("Button") GUI.HeaderButton:SetFullWidth(true) GUI.HeaderButton:SetText("Create") GUI.HeaderButton:SetCallback("OnClick", function() local dop = Doppler:CreateDop(GUI.HeaderCommand:GetText(),GUI.HeaderDelay:GetText()) if dop == nil then GUI.HeaderDelay:SetText("") else Doppler:AddDop(dop) GUI.HeaderCommand:SetText("") GUI.HeaderDelay:SetText("") end end) GUI.Header:AddChild(GUI.HeaderCommand) GUI.Header:AddChild(GUI.HeaderDelay) GUI.Header:AddChild(GUI.HeaderButton) GUI.ScrollContainer = GUI:Create("DopplerInlineGroup") GUI.ScrollContainer:SetFullWidth(true) GUI.ScrollContainer:SetFullHeight(true) GUI.ScrollContainer:SetLayout("Fill") GUI.Scroll = GUI:Create("ScrollFrame") GUI.Scroll:SetFullHeight(true) GUI.Scroll:SetFullWidth(true) GUI.Scroll:SetLayout("List") GUI.ScrollContainer:AddChild(GUI.Scroll) GUI.mainFrame:AddChild(GUI.Header) GUI.mainFrame:AddChild(GUI.ScrollContainer) end
local t = require( "taptest" ) local pluck = require( "pluck" ) local same = require( "same" ) -- Array table test arr = { { "moe", "larry", "curly" }, { 30, 40, 50 }, { true, false, false } } res = pluck( arr, 1 ) t( #res, 3 ) t( same( res, { "moe", 30, true } ), true ) -- Dict table test dict = { { name = "moe", age = 30 }, { name = "larry", age = 40 }, { name = "curly", age = 60 } } res = pluck( dict, "name" ) t( #res, 3 ) t( same( res, { "moe", "larry", "curly" } ), true ) t()
local jsocket = require'jet.socket' local has_websockets, websockets_ev = pcall(require, 'websocket.client_ev') local socket = require'socket' local ev = require'ev' local cjson = require'cjson' local jutils = require'jet.utils' local tinsert = table.insert local tremove = table.remove local tconcat = table.concat local noop = jutils.noop local invalid_params = jutils.invalid_params local internal_error = jutils.internal_error local method_not_found = jutils.method_not_found local error_object = function(err) local error if type(err) == 'table' and err.code and err.message then error = err else error = internal_error(err) end return error end local create_sock = function(config) if not config.url then local ip = config.ip or '127.0.0.1' -- localhost' local port = config.port or 11122 if config.sync then local sock = socket.connect(ip,port) if not sock then error('could not connect to jetd with ip:'..ip..' port:'..port) end return jsocket.wrap_sync(sock) else local loop = config.loop or ev.Loop.default return jsocket.new({ip = ip, port = port, loop = loop}) end else if has_websockets then local ws = websockets_ev() ws:connect(config.url, 'jet') return ws else error('no websockets available. install lua-websockets') end end end local new = function(config) config = config or {} local log = config.log or noop local encode = cjson.encode local decode = cjson.decode local wsock = create_sock(config) if config.sync then local id = 0 local service = function(method,params,timeout) local rid id = id + 1 rid = id params.timeout = timeout -- maybe nil, defaults to 5secs at daemon local data = encode({ id = rid, method = method, params = params }) wsock:send(data) local response,err = wsock:receive() if err then error(err) end response = decode(response) assert(response.id == rid) if response.result then return response.result elseif response.error then error(response.error,2) else assert(false,'invalid response:'..cjson.encode(response)) end end local j_sync = {} j_sync.call = function(_,path,params,timeout) return service('call',{path=path,args=params or {}},timeout) end j_sync.set = function(_,path,value,timeout) return service('set',{path=path,value=value},timeout) end j_sync.config = function(_,params,timeout) return service('config',params,timeout) end j_sync.state = function(_,params,timeout) return service('add',params,timeout) end return j_sync else local loop = config.loop or ev.Loop.default local messages = {} local queue = function(message) tinsert(messages,message) end local will_flush = true local flush = function(reason) local n = #messages if n == 1 then local data = encode(messages[1]) wsock:send(data) elseif n > 1 then local data = encode(messages) wsock:send(data) end messages = {} will_flush = false end local request_dispatchers = {} local response_dispatchers = {} local dispatch_response = function(self,message) local mid = message.id local callbacks = response_dispatchers[mid] response_dispatchers[mid] = nil if callbacks then if message.result then if callbacks.success then callbacks.success(message.result) end elseif message.error then if callbacks.error then callbacks.error(message.error) end else log('invalid result:',cjson.encode(message)) end else log('invalid result id:',mid,cjson.encode(message)) end end local on_no_dispatcher -- handles both method calls and fetchers (notifications) local dispatch_request = function(self,message) local dispatcher = request_dispatchers[message.method] local error if dispatcher then local error local ok,err = pcall(dispatcher,self,message) if ok then return else error = error_object(err) end else error = method_not_found(message.method) if on_no_dispatcher then pcall(on_no_dispatcher,message) end end local mid = message.id if error and mid then queue { id = mid, error = error } end end local dispatch_single_message = function(self,message) if message.method and message.params then dispatch_request(self,message) elseif message.result or message.error then dispatch_response(self,message) else log('unhandled message',cjson.encode(message)) end end local dispatch_message = function(self,message) local ok,message = pcall(decode,message) if not ok then log('decoding message failed',ok) return end will_flush = true if message then if #message > 0 then for i,message in ipairs(message) do dispatch_single_message(self,message) end else dispatch_single_message(self,message) end else queue { error = { code = -32700, messsage = 'Parse error' } } end flush('dispatch_message') end wsock:on_message(dispatch_message) wsock:on_error(log) wsock:on_close(config.on_close or function() end) local j = {} j.loop = function() loop:loop() end j.on_no_dispatcher = function(_,f) on_no_dispatcher = f end j.close = function(self,options) flush('close') wsock:close() end local id = 0 local service = function(method,params,complete,callbacks) local rpc_id -- Only make a Request, if callbacks are specified. -- Make complete call in case of success. -- If no id is specified in the message, no Response -- is expected, aka Notification. if callbacks then params.timeout = callbacks.timeout id = id + 1 rpc_id = id if complete then if callbacks.success then local success = callbacks.success callbacks.success = function(result) complete(true) success() end else callbacks.success = function() complete(true) end end if callbacks.error then local error = callbacks.error callbacks.error = function(result) complete(false) error() end else callbacks.error = function() complete(false) end end end response_dispatchers[id] = callbacks else -- There will be no response, so call complete either way -- and hope everything is ok if complete then complete(true) end end local message = { id = rpc_id, method = method, params = params } if will_flush then queue(message) else local data = encode(message) wsock:send(data) end end j.batch = function(self,action) will_flush = true action() flush('batch') end j.add = function(self,desc,dispatch,callbacks) local path = desc.path assert(not request_dispatchers[path],path) assert(type(path) == 'string',path) assert(type(dispatch) == 'function',dispatch) local assign_dispatcher = function(success) if success then request_dispatchers[path] = dispatch end end local params = { path = path, value = desc.value } service('add',params,assign_dispatcher,callbacks) local ref = { remove = function(ref,callbacks) assert(ref:is_added()) self:remove(path,callbacks) end, is_added = function() return request_dispatchers[path] ~= nil end, add = function(ref,value,callbacks) assert(not ref:is_added()) if value ~= nil then desc.value = value end self:add(desc,dispatch,callbacks) end, path = function() return path end } return ref end j.remove = function(_,path,callbacks) local params = { path = path } local remove_dispatcher = function(success) assert(success) request_dispatchers[path] = nil end service('remove',params,remove_dispatcher,callbacks) end j.call = function(self,path,params,callbacks) local params = { path = path, args = params or {} } service('call',params,nil,callbacks) end j.config = function(self,params,callbacks) service('config',params,nil,callbacks) end j.set = function(self,path,value,callbacks) local params = { path = path, value = value } service('set',params,nil,callbacks) end local fetch_id = 0 j.fetch = function(self,params,f,callbacks) local id = '__f__'..fetch_id local sorting = params.sort fetch_id = fetch_id + 1 local ref local add_fetcher = function() request_dispatchers[id] = function(peer,message) local params = message.params if not sorting then f(params.path,params.event,params.value,ref) else f(params.changes,params.n,ref) end end end if type(params) == 'string' then params = { path = { contains = params } } end params.id = id service('fetch',params,add_fetcher,callbacks) ref = { unfetch = function(_,callbacks) local remove_dispatcher = function() request_dispatchers[id] = nil end service('unfetch',{id=id},remove_dispatcher,callbacks) end, is_fetching = function() return request_dispatchers[id] ~= nil end, fetch = function(_,callbacks) service('fetch',params,add_fetcher,callbacks) end } return ref end j.method = function(self,desc,add_callbacks) local dispatch if desc.call then dispatch = function(self,message) local ok,result local params = message.params if #params > 0 then ok,result = pcall(desc.call,unpack(params)) elseif pairs(params)(params) then -- non empty table ok,result = pcall(desc.call,params) else ok,result = pcall(desc.call) end local mid = message.id if mid then if ok then queue { id = mid, result = result or {} } else queue { id = mid, error = error_object(result) } end end end elseif desc.call_async then dispatch = function(self,message) local reply = function(resp,dont_flush) local mid = message.id if mid then local response = { id = mid } if type(resp.result) ~= 'nil' and not resp.error then response.result = resp.result elseif error then response.error = resp.error else response.error = 'jet.peer Invalid async method response '..desc.path end queue(response) if not will_flush and not dont_flush then flush('call_async') end end end local ok,result local params = message.params if #params > 0 then ok,result = pcall(desc.call_async,reply,unpack(params)) elseif pairs(params)(params) then -- non empty table ok,result = pcall(desc.call_async,reply,params) else ok,result = pcall(desc.call_async,reply) end local mid = message.id if not ok and mid then queue { id = mid, error = error_object(result) } end end else assert(false,'invalid method desc'..(desc.path or '?')) end local ref = self:add(desc,dispatch,add_callbacks) return ref end j.state = function(self,desc,add_callbacks) local dispatch if desc.set then dispatch = function(self,message) local value = message.params.value local ok,result,dont_notify = pcall(desc.set,value) if ok then local newvalue if result ~= nil then newvalue = result else newvalue = value end desc.value = newvalue local mid = message.id if mid then queue { id = mid, result = true } end if not dont_notify then queue { method = 'change', params = { path = desc.path, value = newvalue } } end elseif message.id then queue { id = message.id, error = error_object(result) } end end elseif desc.set_async then dispatch = function(self,message) local value = message.params.value assert(value ~= nil,'params.value is required') local reply = function(resp,dont_flush) local mid = message.id if mid then local response = { id = mid } if resp.result ~= nil and not resp.error then response.result = resp.result elseif resp.error then response.error = error_object(resp.error) else response.error = 'jet.peer Invalid async state response '..desc.path end queue(response) end if resp.result and not resp.dont_notify then if resp.value ~= nil then desc.value = resp.value else desc.value = value end queue { method = 'change', params = { path = desc.path, value = desc.value } } end if not will_flush and not dont_flush then flush('set_aync') end end local ok,result = pcall(desc.set_async,reply,value) local mid = message.id if not ok and mid then queue { id = mid, error = error_object(result) } end end else dispatch = function(self,message) local mid = message.id if mid then queue { id = mid, error = invalid_params() } end end end local ref = self:add(desc,dispatch,add_callbacks) ref.value = function(self,value) if value ~= nil then desc.value = value queue { method = 'change', params = { path = desc.path, value = value } } if not will_flush then flush() end else return desc.value end end return ref end local cmsgpack if config.encoding then if config.encoding ~= 'msgpack' then error('unsupported encoding') end cmsgpack = require'cmsgpack' end wsock:on_open(function() if config.name or config.encoding then j:config({ name = config.name, encoding = config.encoding },{ success = function() flush('config') if config.encoding then encode = cmsgpack.pack decode = cmsgpack.unpack end if config.on_connect then config.on_connect(j) end end, error = function(err) j:close() end }) elseif config.on_connect then config.on_connect(j) end flush('on_connect') end) wsock:connect() return j end end return { new = new }
kCystBuildTime = 6 --from 3.33 --this value is seemingly half of what it is in-game. maybe this value is the drifter build time? --idk it's a hotfix until asdf is home to look into it properly.
local component = require("druid.component") local InnerButton = require("example.examples.system.inner_templates.inner_button") ---@class inner_panel : druid.base_component local InnerPanel = component.create("inner_panel") local SCHEME = { ROOT = "root", BACKGROUND = "background", INNER_BUTTON_1 = "inner_button_1", INNER_BUTTON_2 = "inner_button_2", INNER_BUTTON_PREFAB = "inner_button_prefab", INNER_BUTTON_PREFAB_ROOT = "inner_button_prefab/root", } function InnerPanel:init(template, nodes) self:set_template(template) self:set_nodes(nodes) self.root = self:get_node(SCHEME.ROOT) self.druid = self:get_druid() self.button1 = self.druid:new(InnerButton, SCHEME.INNER_BUTTON_1, nodes) self.button2 = self.druid:new(InnerButton, SCHEME.INNER_BUTTON_2, nodes) local prefab = self:get_node(SCHEME.INNER_BUTTON_PREFAB_ROOT) local button_nodes = gui.clone_tree(prefab) self.button3 = self.druid:new(InnerButton, SCHEME.INNER_BUTTON_PREFAB, button_nodes) gui.set_enabled(prefab, false) end function InnerPanel:on_remove() end return InnerPanel
local zmq = require "zmq" zmq.poller = require "lzmq.poller" return zmq.poller
-- CombatStat.lua -- @Author : DengSir ([email protected]) -- @Link : https://dengsir.github.io/ -- @Date : 2017-9-8 10:35:51 BuildEnv(...) CombatStat = Addon:NewModule('CombatStat', 'AceEvent-3.0', 'AceTimer-3.0') CombatStat:Disable() function CombatStat:OnInitialize() self.units = {} self.groupUnits = {} self.data = Profile:GetCombatData() if IsAddOnLoaded('!!!!!tdDevTools') then self:Debug() end end function CombatStat:OnEnable() self:RegisterEvent('COMBAT_LOG_EVENT_UNFILTERED') self:RegisterEvent('UNIT_PET') self:RegisterEvent('GROUP_ROSTER_UPDATE', 'UpdateGroupUnits') self:UpdateUnits() self:UpdateGroupUnits() self:OnCombatTimer() self.combatTimer = self:ScheduleRepeatingTimer('OnCombatTimer', 3) end function CombatStat:Reset() self.combatTick = nil self.data = Profile:ResetCombatData() end function CombatStat:OnDisable() self:Reset() self.units = {} self.groupUnits = {} self:CancelTimer(self.combatTimer) end function CombatStat:UpdateGroupUnits() wipe(self.groupUnits) for _, unit in IterateGroupUnits() do local guid = UnitGUID(unit) if guid then self.groupUnits[guid] = true end end end function CombatStat:OnCombatTimer() if not self:IsGroupInCombat() then self:LeaveCombat() end end function CombatStat:EnterCombat(timestamp) if self.combatTick then self:Touch('time', timestamp - self.combatTick) end self.combatTick = timestamp end function CombatStat:LeaveCombat() self.combatTick = nil end function CombatStat:IsGroupInCombat() for _, unit in IterateGroupUnits() do if UnitAffectingCombat(unit) then return true end end return UnitAffectingCombat('player') end function CombatStat:Touch(key, amount) self.data[key] = (self.data[key] or 0) + amount end function CombatStat:UNIT_PET(_, unit) if unit ~= 'player' then return end self:UpdateUnits() end function CombatStat:UpdateUnits() self.units[UnitGUID('player')] = 'player' local petGuid = UnitGUID('pet') if petGuid then self.units[petGuid] = 'pet' end end function CombatStat:COMBAT_LOG_EVENT_UNFILTERED(_, timestamp, event, _, srcGuid, srcName, srcFlags, _, destGuid, _, destFlags, _, ...) if not self[event] then return end -- if not (self:IsUnitSelf(srcGuid) or self:IsUnitSelf(destGuid)) then -- return -- end self[event](self, timestamp, srcGuid, srcFlags, destGuid, destFlags, ...) end function CombatStat:SWING_DAMAGE(timestamp, srcGuid, srcFlags, destGuid, destFlags, amount) if self:IsUnitFriend(srcGuid) then self:EnterCombat(timestamp) end if not (self:IsUnitSelf(srcGuid) or self:IsUnitSelf(destGuid)) then return end if srcGuid ~= destGuid and self:IsUnitSelf(srcGuid) then return self:Touch('dd', amount) end if self:IsUnitSelf(destGuid) and not self:IsUnitPet(destGuid) then return self:Touch('dt', amount) end end function CombatStat:SPELL_DAMAGE(timestamp, srcGuid, srcFlags, destGuid, destFlags, _, _, _, amount) return self:SWING_DAMAGE(timestamp, srcGuid, srcFlags, destGuid, destFlags, amount) end function CombatStat:SPELL_HEAL(timestamp, srcGuid, srcFlags, destGuid, destFlags, spellId, spellName, _, amount, overhealing, absorbed) if not self:IsUnitSelf(srcGuid) then return end if bit.band(srcFlags, COMBATLOG_OBJECT_CONTROL_PLAYER) ~= 0 and bit.band(srcFlags, destFlags, COMBATLOG_OBJECT_REACTION_MASK) ~= 0 then local amount = amount - overhealing if amount > 0 then return self:Touch('hd', amount) end end end function CombatStat:SPELL_ABSORBED(timestamp, srcGuid, srcFlags, destGuid, destFlags, ...) local chk = ... local spellId, spellName, spellSchool, aGuid, aName, aFlags, aRaidFlags, amount, _ if type(chk) == 'number' then _, _, _, aGuid, aName, aFlags, aRaidFlags, spellId, spellName, spellSchool, amount = ... else aGuid, aName, aFlags, aRaidFlags, spellId, spellName, spellSchool, amount = ... end if spellId == 20711 or spellId == 115069 or spellId == 157533 then return end if amount then self:SPELL_HEAL(timestamp, aGuid, aFlags, destGuid, destFlags, spellId, spellName, spellSchool, amount, 0, 0) end end function CombatStat:UNIT_DIED(_, srcGuid, srcFlags, destGuid, destFlags) if self:IsUnitSelf(destGuid) then return self:Touch('dead',1) end end function CombatStat:SPELL_SUMMON(timestamp, srcGuid, srcFlags, destGuid, destFlags) if self:IsUnitSelf(srcGuid) then self.units[destGuid] = 'pet' end end CombatStat.SPELL_PERIODIC_DAMAGE = CombatStat.SPELL_DAMAGE CombatStat.SPELL_BUILDING_DAMAGE = CombatStat.SPELL_DAMAGE CombatStat.RANGE_DAMAGE = CombatStat.SPELL_DAMAGE CombatStat.DAMAGE_SPLIT = CombatStat.SPELL_DAMAGE CombatStat.DAMAGE_SHIELD = CombatStat.SPELL_DAMAGE CombatStat.SPELL_PERIODIC_HEAL = CombatStat.SPELL_HEAL function CombatStat:IsUnitSelf(guid) return self.units[guid] end function CombatStat:IsUnitPet(guid) return self.units[guid] == 'pet' end function CombatStat:IsUnitFriend(guid) return self.groupUnits[guid] or self.units[guid] end function CombatStat:GetCombatData() local time = self.data.time == 0 and 0xFFFFFFFF or self.data.time return { dd = self.data.dd, dt = self.data.dt, hd = self.data.hd, dps = floor(self.data.dd / time), hps = floor(self.data.hd / time), dead = self.data.dead, } end local templates = [[ dt: %s dd: %s dps: %s hd: %s hps: %s dead: %s %s %s ]] function CombatStat:Debug() local healingData = {} local healingNames = {} local function healingText() local sb = {} for i, v in ipairs(healingNames) do table.insert(sb, format('%s: %d', v, healingData[v])) end return table.concat(sb, '\n') end local f = CreateFrame('Frame', nil, UIParent) do f:SetPoint('LEFT') f:SetSize(200, 400) movehelper(f) local bg = f:CreateTexture(nil, 'BACKGROUND') do bg:SetColorTexture(0,0,0,0.3) bg:SetAllPoints(true) end local text = f:CreateFontString(nil, 'ARTWORK', 'GameFontNormalLeft') do text:SetPoint('TOPLEFT') end f:SetScript('OnUpdate', function(f) local data = self:GetCombatData() text:SetText(format(templates, data.dt, data.dd, data.dps, data.hd, data.hps, data.dead, self:IsEnabled() and '已开启' or '已关闭', healingText() )) end) end local StartButton = CreateFrame('Button', nil, f, 'UIPanelButtonTemplate') do StartButton:SetPoint('BOTTOMLEFT') StartButton:SetSize(80, 22) StartButton:SetText('开启') StartButton:SetScript('OnClick', function() GUI:CallMessageDialog('你应该只在打木桩测试时点击这个按钮!!!\n准备进秘境之前点关闭按钮!!!', function(result) if result then self:Enable() end end) end) end local ClearButton = CreateFrame('Button', nil, f, 'UIPanelButtonTemplate') do ClearButton:SetPoint('LEFT', StartButton, 'RIGHT') ClearButton:SetSize(80,22) ClearButton:SetText('关闭') ClearButton:SetScript('OnClick', function() GUI:CallMessageDialog('点这个按钮会清除数据,你应该只在打完木桩后验证完数据后点击', function(result) if result then self:Reset() self:Disable() end end) end) end -- hooksecurefunc(CombatStat, 'Reset', function() -- healingData = {} -- healingNames = {} -- end) -- function CombatStat:SPELL_HEAL(timestamp, srcGuid, srcFlags, destGuid, destFlags, spellId, spellName, _, amount, overhealing, absorbed) -- if not self:IsUnitSelf(srcGuid) then -- return -- end -- if bit.band(srcFlags, COMBATLOG_OBJECT_CONTROL_PLAYER) ~= 0 and bit.band(srcFlags, destFlags, COMBATLOG_OBJECT_REACTION_MASK) ~= 0 then -- local amount = amount - overhealing -- if amount > 0 then -- if not healingData[spellName] then -- healingData[spellName] = amount -- table.insert(healingNames, spellName) -- table.sort(healingNames) -- else -- healingData[spellName] = healingData[spellName] + amount -- end -- debug(srcGuid, srcFlags, destGuid, destFlags, amount, overhealing) -- return self:Touch('hd', amount) -- end -- end -- end -- CombatStat.SPELL_PERIODIC_HEAL = CombatStat.SPELL_HEAL end
speedLimit = 300 --This would set your speed limit to 150, Just divide by 2. vehicle = "Vehicle" --Vehicle name, Sedan, Lawnmower and so on. function onKeyPress(actionName, userInputState, inputObject) if userInputState == Enum.UserInputState.Begin then game.Workspace._Vehicles[vehicle].LW.VS.Maxspeed = SpeedLimit game.Workspace._Vehicles[vehicle].RW.VS.Maxspeed = SpeedLimit else print("Car not found") end end end game.ContextActionService:BindAction("keyPress", onKeyPress, false, Enum.KeyCode.X)
--[[ sprite ecs ]] local path = (...):gsub("systems.sprite_system", "") local base = require(path .. "base_system") --sprite type local sprite = class() function sprite:new(texture) return self:init({ --xy pos = vec2:zero(), size = vec2:zero(), offset = vec2:zero(), --uv framesize = vec2:xy(1,1), frame = vec2:zero(), --z ordering z = 0, --rotation rot = 0, --enable/disable visible = true, --track if we were on screen last frame on_screen = true, --mirror orientation (could just be scale?..) x_flipped = false, y_flipped = false, --tex texture = texture, --worldspace _screenpos = vec2:zero(), _screen_rotation = 0, }) end local _sprite_draw_temp_pos = vec2:zero() function sprite:draw(quad, use_screenpos) local pos local rot if use_screenpos then --position in screenspace pos = self._screenpos rot = self._screen_rotation else pos = _sprite_draw_temp_pos:vset(self.pos):vaddi(self.offset) rot = self.rot end local size = self.size local frame = self.frame local framesize = self.framesize quad:setViewport( frame.x * framesize.x, frame.y * framesize.y, framesize.x, framesize.y ) love.graphics.draw( self.texture, quad, pos.x, pos.y, rot, --TODO: just have scale here rather than flipped bools (self.x_flipped and -1 or 1) * (size.x / framesize.x), (self.y_flipped and -1 or 1) * (size.y / framesize.y), --centred 0.5 * framesize.x, 0.5 * framesize.y, --no shear 0, 0 ) end local sprite_system = class() function sprite_system:new(args) args = args or {} local s = self:init({ --function for getting the screen pos transform_fn = args.transform_fn, --the camera to use for culling, or true to use kernel cam, --or false/nil to use nothing camera = args.camera, --whether to cull or draw on screen or untransformed cull_screen = type(args.cull_screen) == "boolean" and args.cull_screen or true, draw_screen = type(args.draw_screen) == "boolean" and args.draw_screen or true, shader = args.shader, --texture ordering texture_order_mapping = unique_mapping:new(), --list of sprites sprites = {}, --filtered list sprites_to_render = {}, --debug info debug = { sprites = 0, rendered = 0, }, }) return s end function sprite_system:add(texture) local s = sprite:new(texture) table.insert(self.sprites, s) return s end function sprite_system:remove(s) table.remove_value(self.sprites, s) end function sprite_system:flush(camera) if type(self.transform_fn) == "function" then --apply transformation function table.foreach(self.sprites, function(s) local tx, ty, rot = self.transform_fn(s) if tx then s._screenpos.x = tx end if ty then s._screenpos.y = ty end if rot then s._screen_rotation = rot + s.rot end end ) else --copy table.foreach(self.sprites, function(s) s._screenpos:vset(s.pos):vaddi(s.offset) s._screen_rotation = s.rot end) end --collect on screen to render local filter_function = nil if camera == nil then filter_function = function(s) return s.visible end else if self.cull_screen then filter_function = function(s) return s.visible and camera:aabb_on_screen(s._screenpos, s.size) end else filter_function = function(s) return s.visible and camera:aabb_on_screen(s.pos, s.size) end end end local function write_filter_result(s) local result = filter_function(s) s.on_screen = result return result end self.sprites_to_render = table.filter(self.sprites, write_filter_result) --sort to render local _torder = self.texture_order_mapping local function _texture_order(tex) return _torder:map(tex) end table.stable_sort(self.sprites_to_render, function(a, b) if a.z == b.z then --secondary sort on texture within z level for batching return _texture_order(a.texture) < _texture_order(b.texture) end return a.z < b.z end) --update debug info self.debug.sprites = #self.sprites self.debug.rendered = #self.sprites_to_render end --draw all the sprites function sprite_system:draw() local q = love.graphics.newQuad(0,0,1,1,1,1) love.graphics.setColor(1, 1, 1, 1) love.graphics.setShader(self.shader) table.foreach(self.sprites_to_render, function(s) s:draw(q, self.draw_screen) end) end --register tasks for kernel function sprite_system:register(kernel, order) kernel:add_task("update", function(k, dt) local use_cam if type(self.camera) == "boolean" and self.camera then --grab the kernel cam use_cam = kernel.camera else --(handles the nil, table, and false cases) use_cam = self.camera end if use_cam then --cull to kernel cam self:flush(use_cam) else --no visibility culling self:flush() end end, order + 1000) kernel:add_task("draw", function(k) self:draw() end, order) end --console debug function sprite_system:add_console_watch(name, console) console:add_watch(name, function() return table.concat({ self.debug.sprites, "s, ", self.debug.rendered, "r" }, "") end) end return sprite_system
--- Eva token module -- Provide API to work with tokens in special container -- Tokens is basic item, like money, energy or items. -- @submodule eva local app = require("eva.app") local log = require("eva.log") local luax = require("eva.luax") local const = require("eva.const") local smart = require("eva.libs.smart.smart") local db = require("eva.modules.db") local game = require("eva.modules.game") local proto = require("eva.modules.proto") local saver = require("eva.modules.saver") local events = require("eva.modules.events") local logger = log.get_logger("eva.token") local M = {} local function get_token_lot_config(lot_id) local config_name = app.settings.tokens.config_lots return db.get(config_name).token_lots[lot_id] end local function get_token_group_config(group_id) local config_name = app.settings.tokens.config_token_groups return db.get(config_name).token_groups[group_id] end local function get_token_config() local config_name = app.settings.tokens.config_token_config return db.get(config_name).token_config end local function get_data_containers() return app[const.EVA.CONTAINERS].containers end local function get_container(container_id) return app.smart_containers[container_id] end local function update_tokens_offset() if not app.settings.tokens.memory_protect then return end local containers = app.smart_containers for _, container in pairs(containers) do for _, token in pairs(container) do token:random_offset() end end end local function on_change_token(token, delta, reason, container_id) events.event(const.EVENT.TOKEN_CHANGE, { delta = delta, token_id = token:get_token_id(), reason = reason, amount = token:get(), container_id = container_id }) end local function get_config_for_token(container_id, token_id) local config = get_token_config()[token_id] or {} config.name = token_id return config end local function create_token_in_save(container_id, token_id, token_data) if not token_data then local container_data = get_data_containers()[container_id] token_data = proto.get(const.EVA.TOKEN) container_data.tokens[token_id] = token_data end local config = get_config_for_token(container_id, token_id) local smart_token = smart.new(config, token_data) if app.settings.tokens.memory_protect then smart_token:random_offset() else smart_token:reset_offset() end smart_token:on_change(function(token, delta, reason) on_change_token(token, delta, reason, container_id) end) return smart_token end local function get_token(container_id, token_id) assert(container_id, "You should provide container_id") assert(token_id, "You should provide token_id") local container = get_container(container_id) if not container then logger:error("No container with id", { container_id = container_id, token_id = token_id }) return end if not container[token_id] then container[token_id] = create_token_in_save(container_id, token_id) end return container[token_id] end local function restore_token_update(container_id, token_id, config) local token = get_token(container_id, token_id) local cur_time = game.get_time() config.last_restore_time = math.min(config.last_restore_time, cur_time) if token:is_max() then config.last_restore_time = cur_time end local elapsed = cur_time - config.last_restore_time if elapsed >= config.timer then local amount = math.floor(elapsed / config.timer) local need_to_add = amount * config.value if config.max then need_to_add = math.min(need_to_add, config.max) end token:add(need_to_add) local cur_elapse_time = elapsed - (amount * config.timer) config.last_restore_time = cur_time - cur_elapse_time end end --- Check if token container exist -- @function eva.token.is_exist_container -- @tparam string container_id Container id -- @treturn bool Container exist state function M.is_exist_container(container_id) return luax.toboolean(get_container(container_id)) end --- Create new token container -- @function eva.token.create_container -- @tparam string container_id Container id -- @tparam string container_type Container type to match from token config function M.create_container(container_id, container_type) if M.is_exist_container(container_id) then logger:warn("Container is already exist", { container_id = container_id }) return end local data_containers = get_data_containers() data_containers[container_id] = proto.get(const.EVA.CONTAINER) data_containers[container_id].type = container_type app.smart_containers[container_id] = {} logger:debug("Create token container", { container_id = container_id, container_type = container_type }) end --- Delete token container -- @function eva.token.delete_container -- @tparam string container_id Container id function M.delete_container(container_id) local data_containers = get_data_containers() data_containers[container_id] = nil app.smart_containers[container_id] = nil end --- Clear all tokens from container -- @function eva.token.clear_container -- @tparam string container_id Container id function M.clear_container(container_id) if not M.is_exist_container(container_id) then logger:warn("Can't clear non existing container", { container_id = container_id }) return end local container = get_container(container_id) container.tokens = {} app.smart_containers[container_id] = {} end function M.set_restore_config(container_id, token_id, config) local restore_config = get_data_containers()[container_id].restore_config local new_config = proto.get(const.EVA.TOKEN_RESTORE_CONFIG) new_config.is_enabled = true new_config.last_restore_time = game.get_time() new_config.timer = config.timer new_config.value = config.value or new_config.value new_config.max = config.max or new_config.max restore_config[token_id] = new_config end function M.get_restore_config(container_id, token_id) return get_data_containers()[container_id].restore_config[token_id] end function M.set_pause_restore_config(container_id, token_id, is_pause) local config = M.get_restore_config(container_id, token_id) config.is_enabled = not is_pause end function M.remove_restore_config(container_id, token_id) local restore_config = get_data_containers()[container_id].restore_config assert(restore_config[token_id], "No restore config to delete it") restore_config[token_id] = nil end --- Return evadata.Tokens tokens format. Used in *_tokens methods -- @function eva.token.get_tokens -- @tparam table tokens Map with token_id = amount function M.get_tokens(tokens) local data = proto.get(const.EVA.TOKENS_DATA) for token_id, amount in pairs(tokens) do table.insert(data.tokens, { token_id = token_id, amount = amount }) end return data end --- Return token group by id. -- It pickup data from DB -- @function eva.token.get_token_group -- @tparam string token_group_id the token group id -- @treturn evadata.Tokens the token list function M.get_token_group(token_group_id) local group = get_token_group_config(token_group_id) if not group then logger:error("No token group with id", { group_id = token_group_id }) end return group end --- Return lot reward by lot_id. -- It pickup data from DB -- @function eva.token.get_lot_reward -- @tparam string lot_id the token lot id -- @treturn evadata.Tokens the token list function M.get_lot_reward(lot_id) local lot = get_token_lot_config(lot_id) if not lot then logger:error("No token lot with id", { lot_id = lot_id }) end return M.get_token_group(lot.reward) end --- Return lot price by lot_id. -- It pickup data from DB -- @function eva.token.get_lot_price -- @tparam string lot_id the token lot id -- @treturn evadata.Tokens the token list function M.get_lot_price(lot_id) local lot = get_token_lot_config(lot_id) if not lot then logger:error("No token lot with id", { lot_id = lot_id }) end return M.get_token_group(lot.price) end --- Add tokens to save -- @function eva.token.add function M.add(container_id, token_id, amount, reason, visual_later) return get_token(container_id, token_id):add(amount, reason, visual_later) end --- Add multiply tokens -- @function eva.token.add_many function M.add_many(container_id, tokens, reason) if not tokens or #tokens.tokens == 0 then return end for index, value in ipairs(tokens.tokens) do M.add(container_id, value.token_id, value.amount, reason) end end --- Add multiply tokens by token_group_id -- @function eva.token.add_group function M.add_group(container_id, token_group_id, reason) local tokens = M.get_token_group(token_group_id) M.add_many(container_id, tokens) end --- Set tokens to save -- @function eva.token.set function M.set(container_id, token_id, amount, reason) return get_token(container_id, token_id):set(amount, reason) end --- Get current token amount from save -- @function eva.token.get function M.get(container_id, token_id) return get_token(container_id, token_id):get() end --- Get all tokens from container -- @function eva.token.get_many -- @tparam string container_id Container id -- @treturn evadata.Tokens Tokens from container function M.get_many(container_id) local tokens = {} local container = get_container(container_id) for id, token in pairs(container) do tokens[id] = token:get() end return M.get_tokens(tokens) end --- Try to pay tokens from save -- @function eva.token.pay -- @tparam string token_id Token id -- @tparam number amount Amount to pay -- @tparam string reason The reason to pay function M.pay(container_id, token_id, amount, reason) if M.is_infinity(container_id, token_id) then return true end return get_token(container_id, token_id):pay(amount, reason) end --- Pay multiply tokens -- @function eva.token.pay_many -- @tparam evadata.Tokens tokens Tokens data -- @tparam string reason The reason to pay function M.pay_many(container_id, tokens, reason) for index, value in ipairs(tokens.tokens) do M.pay(container_id, value.token_id, value.amount, reason) end end --- Pay multiply tokens by token_group_id -- @function eva.token.pay_group -- @tparam string token_group_id The token group id -- @tparam string reason The reason to pay function M.pay_group(container_id, token_group_id, reason) local tokens = M.get_token_group(token_group_id) M.pay_many(container_id, tokens, reason) end --- Check is enough to pay token -- @function eva.token.is_enough function M.is_enough(container_id, token_id, amount) if M.is_infinity(container_id, token_id) then return true end return get_token(container_id, token_id):check(amount) end --- Check multiply tokens -- @function eva.token.is_enough_many -- @tparam evadata.Tokens tokens list function M.is_enough_many(container_id, tokens) local is_enough = true for index, value in ipairs(tokens.tokens) do is_enough = is_enough and M.is_enough(container_id, value.token_id, value.amount) end return is_enough end --- Check multiply tokens by token_group_id -- @function eva.token.is_enough_group -- @tparam string token_group_id the token group id function M.is_enough_group(container_id, token_group_id) local tokens = M.get_token_group(token_group_id) return M.is_enough_many(container_id, tokens) end --- Return is token is maximum -- @function eva.token.is_max function M.is_max(container_id, token_id) return get_token(container_id, token_id):is_max() end --- Return is tokens equals to 0 -- @function eva.token.is_empty function M.is_empty(container_id, token_id) return get_token(container_id, token_id):is_empty() end --- Add to tokens infinity time usage -- @function eva.token.add_infinity_time function M.add_infinity_time(container_id, token_id, seconds) local timers = get_data_containers()[container_id].infinity_timers local cur_time = game.get_time() timers[token_id] = math.max(timers[token_id] or cur_time, cur_time) + seconds end --- Return is token is infinity now -- @function eva.token.is_infinity function M.is_infinity(container_id, token_id) return M.get_infinity_seconds(container_id, token_id) > 0 end --- Get amount of seconds till end of infinity time -- @function eva.token.get_infinity_seconds function M.get_infinity_seconds(container_id, token_id) local end_timer = get_data_containers()[container_id].infinity_timers[token_id] if end_timer then return math.ceil(end_timer - game.get_time()) end return 0 end --- Get current time to next restore point -- @function eva.token.get_seconds_to_restore function M.get_seconds_to_restore(container_id, token_id) local config = M.get_restore_config(container_id, token_id) if not config then logger:warn("Get seconds to restore from token without restore", { container_id = container_id, token_id = token_id }) return 0 end local last = config.last_restore_time local skipped = game.get_time() - last return math.max(0, config.timer - skipped) end --- Reset visual debt of tokens -- @function eva.token.sync_visual function M.sync_visual(container_id, token_id) return get_token(container_id, token_id):sync_visual() end --- Add visual debt to token -- @function eva.token.add_visual function M.add_visual(container_id, token_id, amount) return get_token(container_id, token_id):add_visual(amount) end --- Get current visual debt of token -- @function eva.token.get_visual function M.get_visual(container_id, token_id) return get_token(container_id, token_id):get_visual() end function M.before_eva_init() app.smart_containers = {} end function M.on_eva_init() app[const.EVA.CONTAINERS] = proto.get(const.EVA.CONTAINERS) saver.add_save_part(const.EVA.CONTAINERS, app[const.EVA.CONTAINERS]) events.subscribe(const.EVENT.GAME_FOCUS, update_tokens_offset) end function M.after_eva_init() local containers = app.smart_containers local data_containers = get_data_containers() for container_id, data_container in pairs(data_containers) do containers[container_id] = containers[container_id] or {} for token_id, token_data in pairs(data_container.tokens) do -- Link behavior and data local container = containers[container_id] container[token_id] = create_token_in_save(container_id, token_id, token_data) end end end function M.on_eva_update(dt) local containers = get_data_containers() for container_id, container in pairs(containers) do local restore_config = container.restore_config for token_id, config in pairs(restore_config) do if config.is_enabled then restore_token_update(container_id, token_id, config) end end end end return M
-- Dependencies local Class = require("engine.Class") local String = require("engine.String") -- Cheater class local Cheater = Class("Cheater") -- Constructor function Cheater:Cheater(inputHistoryLimit) self.cheats = {} self.history = {} self.startPos = 1 self.endPos = 1 self.limit = inputHistoryLimit or 50 end -- Adds new cheat function Cheater:addCheat(sequence, callback) if type(sequence) == "string" then sequence = String.split(sequence) end table.insert(self.cheats, { sequence = sequence, callback = callback }) end -- Adds last used input function Cheater:inputUsed(input) self:addInput(input) self:inputChanged() end -- Adds input to history function Cheater:addInput(input) self.history[self.endPos] = input self.endPos = self.endPos + 1 if self.endPos - self.startPos > self.limit then self.history[self.startPos] = nil self.startPos = self.startPos + 1 end end -- Checks if some cheat was activated function Cheater:inputChanged() for i, cheat in ipairs(self.cheats) do local sequence = cheat.sequence local historyPos = self.endPos - 1 local sequencePos = #sequence while sequencePos > 0 and self.history[historyPos] == sequence[sequencePos] do historyPos = historyPos - 1 sequencePos = sequencePos - 1 end if sequencePos == 0 then cheat.callback(sequence) end end end return Cheater
module 'mock' ---DEAD LOCK DEBUG HELPER local DEADLOCK_THRESHOLD = 100 local DEADLOCK_TRACK = 10 local DEADLOCK_TRACK_ENABLED = true local function tovalue( v ) v = v:trim() if value == 'true' then return true, true elseif value == 'false' then return true, false elseif value == 'nil' then return true, nil else local n = tonumber( v ) if n then return true, n end local s = v:match( [[^'(.*)'$]]) if s then return true, s end local s = v:match( [[^"(.*)"$]]) if s then return true, s end end return false end -------------------------------------------------------------------- local function buildFSMScheme( scheme ) -- assert(targetClass,'Target Class required') assert( scheme, 'FSM Data required' ) --for deadlock detection local trackedStates = {} -- local stateFuncs = {} --- local function parseExprJump( msg ) local content = msg:match('%s*if%s*%((.*)%)%s*') if not content then return nil end content = content:trim() local valueFunc, err = loadEvalScriptWithEnv( content ) if not valueFunc then _warn( 'failed compiling condition expr:', err ) return false else return valueFunc end end --build state funcs for name, stateBody in pairs( scheme ) do local id = stateBody.id --current state id local jump = stateBody.jump --transition trigger by msg local outStates = stateBody.next --transition trigger by state return value local localName = stateBody.localName local stepName = id .. '__step' local exitName = id .. '__exit' local enterName = id .. '__enter' local exprJump = false if jump then for msg, target in pairs( jump ) do local exprFunc = parseExprJump( msg ) if exprFunc then if not exprJump then exprJump = {} end exprJump[ msg ] = exprFunc end end if exprJump then for msg, exprFunc in pairs( exprJump ) do --replace msg local target = jump[ msg ] jump[ msg ] = nil jump[ exprFunc ] = target end end end --generated function local function stateStep( controller, dt, switchCount ) ----PRE STEP TRANSISTION local nextState local transMsg, transMsgArg local forceJumping = controller.forceJumping if forceJumping then controller.forceJumping = false nextState, transMsg, transMsgArg = unpack( forceJumping ) else ---STEP local step = controller[ stepName ] local out = true --step return name of next state if step then out = step( controller, dt ) dt = 0 --delta time is consumed elseif step == nil then controller[ stepName ] = false end ----POST STEP TRANSISTION if out and outStates then --approach next state nextState = outStates[ out ] if not nextState then _error( '! error in state:'..name ) if type( out ) ~= 'string' then return error( 'output state name expected' ) end error( 'output state not found:'..tostring( out ) ) end else --find triggering msg (post phase) while true do transMsg, transMsgArg = controller:pollMsg() if not transMsg then return end nextState = jump and jump[ transMsg ] if nextState then break end end end end if DEADLOCK_TRACK_ENABLED then --DEADLOCK DETECTOR switchCount = switchCount + 1 if switchCount == DEADLOCK_THRESHOLD then trackedStates = {} elseif switchCount > DEADLOCK_THRESHOLD then table.insert( trackedStates, name ) if switchCount > DEADLOCK_THRESHOLD + DEADLOCK_TRACK then --state traceback _log( "state switch deadlock:", switchCount ) for i, s in ipairs( trackedStates ) do _log( i, s ) end if getG( 'debugstop' ) then debugStop() end -- game:debugStop() error('TERMINATED') --terminate end end end local nextStateBody local nextStateName if controller:acceptStateChange( nextState ) == false then return end --TRANSITION local tt = type( nextState ) if tt == 'string' then --direct transition nextStateName = nextState local exit = controller[ exitName ] if exit then --exit previous state exit( controller, nextStateName, transMsg, transMsgArg ) elseif exit == nil then controller[ exitName ] = false end else --group transitions local l = #nextState nextStateName = nextState[l] local exit = controller[ exitName ] if exit then --exit previous state exit( controller, nextStateName, transMsg, transMsgArg ) elseif exit == nil then controller[ exitName ] = false end --extra state group exit/enter for i = 1, l-1 do local funcName = nextState[ i ] local func = controller[ funcName ] if func then func( controller, name, nextStateName, transMsg, transMsgArg ) end end end controller:setState( nextStateName ) nextStateBody = scheme[ nextStateName ] if not nextStateBody then error( 'state body not found:' .. nextStateName, 2 ) end local enterName = nextStateBody.enterName --activate and enter new state handler local nextFunc = nextStateBody.func controller.currentStateFunc = nextFunc controller.currentExprJump = nextStateBody.exprJump local enter = controller[ enterName ] if enter then --entering new state enter( controller, name, transMsg, transMsgArg ) elseif enter == nil then controller[ enterName ] = false end controller:updateExprJump() return nextFunc( controller, dt, switchCount ) end stateBody.func = stateStep stateBody.stepName = stepName stateBody.enterName = enterName stateBody.exitName = exitName stateBody.exprJump = exprJump end local startFunc = scheme['start'].func local startEnterName = scheme['start'].enterName local startExprJump = scheme['start'].exprJump scheme[0] = function( controller, dt ) controller.currentStateFunc = startFunc controller.currentExprJump = startExprJump local f = controller[ startEnterName ] if f then f( controller ) --fsm.start:enter end controller:updateExprJump() return startFunc( controller, dt, 0 ) end end -------------------------------------------------------------------- function FSMSchemeLoader( node ) local path = node:getObjectFile('def') local scheme = dofile( path ) buildFSMScheme( scheme ) return scheme end registerAssetLoader ( 'fsm_scheme', FSMSchemeLoader )
--[[ * MOCK framework for Moai * Copyright (C) 2012 Tommo Zhou([email protected]). All rights reserved. * * 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 os=MOAIEnvironment.osBrand DebugHelper = {} function DebugHelper:startCrittercism( k1, k2, k3 ) --TODO: support android if os=='iOS' then MOAICrittercism.init( k1, k2, k3 ) self.crittercism = true end end function DebugHelper:setCodeMark( s, ... ) if self.crittercism then MOAICrittercism.leaveBreadcrumb( string.format( s, ... ) ) end end function DebugHelper:reportUsage() print'---------' print('FPS:',MOAISim.getPerformance()) print('Objects:',MOAISim.getLuaObjectCount()) print('Memory:') table.foreach(MOAISim.getMemoryUsage(),print) print('--------') if game.scenes then for k,s in pairs( game.scenes ) do local count=table.len(s.objects) if count>0 then printf('Object in scene "%s": %d',s.name,count) end end end print('--------') -- print(MOAISim.reportHistogram()) end function DebugHelper:showDebugLines(show) show=show~=false for i, l in pairs(moailayers) do l:showDebugLines(show) end end function DebugHelper:setDebugEnabled(d) self.debugEnabled=d or false if not self.debugger then require("clidebugger") self.debugger=clidebugger end MOAIDebugLines.setStyle ( MOAIDebugLines.PARTITION_CELLS, 2, 1, 1, 1 ) MOAIDebugLines.setStyle ( MOAIDebugLines.PARTITION_PADDED_CELLS, 1, 0.5, 0.5, 0.5 ) MOAIDebugLines.setStyle ( MOAIDebugLines.PROP_WORLD_BOUNDS, 2, 0.75, 0.75, 0.75 ) end function DebugHelper:pause(msg) if self.debugger then return self.debugger.pause(msg) end end function DebugHelper:exitOnError( enabled ) enabled = enabled~=false if enabled then MOAISim.setTraceback( function(msg) print( debug.traceback(msg, 2) ) os.exit() end) end end -------------------------------------------------------------------- --Profiler ( using ProFi ) Profiler = { coroWrapped = false } function Profiler:start( time, reportPath ) local ProFi=require 'ProFi' self.ProFi = ProFi --wrap moai coroutine if not self.coroWrapped then self.coroWrapped = true local MOAICoroutineIT = MOAICoroutine.getInterfaceTable() local _run = MOAICoroutineIT.run MOAICoroutineIT.run = function(self, func,...) return _run(self, function(...) ProFi:start() return func(...) end,...) end end --auto stop settings if time then laterCall( time, function() self:stop() if reportPath then self:writeReport( reportPath ) end end) end --start -- ProFi:setGetTimeMethod( MOAISim.getDeviceTime ) _stat 'start profiler...' ProFi:start() end function Profiler:stop() self.ProFi:stop() _stat 'stop profiler...' end function Profiler:writeReport( path ) _statf( 'writing profiler report to : %s', path ) self.ProFi:writeReport( path ) end -------------------------------------------------------------------- local tracingCoroutines = setmetatable( {}, { __mode = 'k' } ) function _reportTracingCoroutines() local count = {} local countActive = {} for coro, tb in pairs( tracingCoroutines ) do count[ tb ] = ( count[ tb ] or 0 ) + 1 print( tb ) if coro:isBusy() then countActive[ tb ] = ( countActive[ tb ] or 0 ) + 1 else -- print( 'inactive coro' ) -- print( tb ) end end -- for tb, c in pairs( count ) do -- if c > 1 then -- print( '------CORO COUNT:', c, countActive[ tb ] ) -- print( tb ) -- end -- end end local oldNew = MOAICoroutine.new MOAICoroutine.new = function( f, ... ) local coro = oldNew( f, ... ) -- print( 'CREATE COROUTINE', coro ) -- print( debug.traceback() ) -- local funcinfo = debug.getinfo( f, 'nSl' ) -- local infoString string.format( -- '%s:%d', funcinfo.source, funcinfo.currentline -- ) tracingCoroutines[ coro ] = debug.traceback( 3 ) return coro end -------------------------------------------------------------------- --dump calltree -------------------------------------------------------------------- --command CLASS: DebugCommand () :MODEL{} function DebugCommand:onExec() end function DebugCommand:finish() end function DebugCommand:fail() end -------------------------------------------------------------------- function enableInfiniteLoopChecking() local function _callback( funcInfo ) local funcInfo = debug.getinfo( 2, 'Sl' ) return print( '>>', funcInfo.source, funcInfo.currentline ) end local MOAICoroutineIT = MOAICoroutine.getInterfaceTable() local _run = MOAICoroutineIT.run MOAICoroutineIT.run = function(self, func,...) return _run(self, function(...) debug.sethook( _callback, 'l' ) return func(...) end,...) end debug.sethook( _callback, 'l' ) end local function defaultErrorHandler ( status ) print( 'ERROR:', status ) print( debug.traceback( 2 ) ) end local function _innerTry( errFunc, ok, ... ) -- print( errFunc, ok, ... ) if ok then return ... end local status = ... errFunc = errFunc or defaultErrorHandler errFunc( status ) return nil end function try( func, errFunc ) return _innerTry( errFunc, pcall( func ) ) end function singletraceback( level ) local info = debug.getinfo( ( level or 2 ) + 1, 'nSl' ) return string.format( '%s:%d', info.source, info.currentline ) end local trackingMOAIObjects = {} function trackMOAIObject( clas ) local oldNew = clas.new local t = table.weak_k() trackingMOAIObjects[ clas ] = t clas.new = function( ... ) local obj = oldNew( ... ) t[ obj ] = debug.traceback( 3 ) return obj end end function reportTrackingMOAIObject( clas ) local t = trackingMOAIObjects[ clas ] if not t then _log( 'not tracking', clas ) return false end _log( 'allocated moai object:', clas ) for obj, trace in pairs( t ) do _log( obj ) _log( trace ) end _log( '----' ) end
---@return Weapon function Weapon(...) end ---@class Weapon local cls = Weapon() ---@return any function cls:IsInWater(...) end ---@return any function cls:GetAttachedTo(...) end ---@return any function cls:AttachTo(...) end ---@return any function cls:ResetMaterial(...) end ---@return any function cls:GetLeftHandLocation(...) end ---@return any function cls:GetSightRotation(...) end ---@return any function cls:GetWallbangDamageMultiplier(...) end ---@return any function cls:SetLocation(...) end ---@return any function cls:SetRotation(...) end ---@return any function cls:SetDefaultMaterial(...) end ---@return any function cls:GetActorTags(...) end ---@return any function cls:GetHoldReleaseUse(...) end ---@return any function cls:GetBulletCount(...) end ---@return any function cls:SetNetworkAuthority(...) end ---@return any function cls:GetAssetName(...) end ---@return any function cls:GetMagazineMesh(...) end ---@return any function cls:GetRotation(...) end ---@return any function cls:GetSpread(...) end ---@return any function cls:GetBounds(...) end ---@return any function cls:SetAttachmentSettings(...) end ---@return any function cls:GetRecoil(...) end ---@return any function cls:GetAmmoClip(...) end ---@return any function cls:GetHandlingMode(...) end ---@return any function cls:SetLifeSpan(...) end ---@return any function cls:SetPhysicalMaterial(...) end ---@return any function cls:TranslateTo(...) end ---@return any function cls:SetGravityEnabled(...) end ---@return any function cls:SetMaterial(...) end ---@return any function cls:GetLifeSpan(...) end ---@return any function cls:GetDamage(...) end ---@return any function cls:IsGravityEnabled(...) end ---@return any function cls:SetCrosshairSetting(...) end ---@return any function cls:AddSkeletalMeshAttached(...) end ---@return any function cls:SetRelativeLocation(...) end ---@return any function cls:SetInitialLocation(...) end ---@return any function cls:RemoveSkeletalMeshAttached(...) end ---@return any function cls:IsValid(...) end ---@return any function cls:GetSoundDry(...) end ---@return any function cls:GetSoundLoad(...) end ---@return any function cls:Destroy(...) end ---@return any function cls:Unsubscribe(...) end ---@return any function cls:SetMaterialVectorParameter(...) end ---@return any function cls:GetBulletColor(...) end ---@return any function cls:GetAttachedEntities(...) end ---@return any function cls:AddImpulse(...) end ---@return any function cls:SetForce(...) end ---@return any function cls:SetMaterialColorParameter(...) end ---@return any function cls:GetAmmoToReload(...) end ---@return any function cls:Super(...) end ---@return any function cls:GetSoundAim(...) end ---@return any function cls:Detach(...) end ---@return any function cls:GetSoundFire(...) end ---@return any function cls:GetSoundZooming(...) end ---@return any function cls:GetSoundUnload(...) end ---@return any function cls:GetParticlesShells(...) end ---@return any function cls:GetParticlesBarrel(...) end ---@return any function cls:IsBeingDestroyed(...) end ---@return any function cls:AddActorTag(...) end ---@return any function cls:GetParticlesBulletTrail(...) end ---@return any function cls:SetScale(...) end ---@return any function cls:GetInitialLocation(...) end ---@return any function cls:IsNetworkDistributed(...) end ---@return any function cls:GetAnimationCharacterFire(...) end ---@return any function cls:SetMaterialTextureParameter(...) end ---@return any function cls:GetRightHandOffset(...) end ---@return any function cls:SetMaterialScalarParameter(...) end ---@return any function cls:GetValue(...) end ---@return any function cls:GetSightLocation(...) end ---@return any function cls:SetCrosshairMaterial(...) end ---@return any function cls:GetLeftHandRotation(...) end ---@return any function cls:GetAmmoBag(...) end ---@return any function cls:GetCadence(...) end ---@return any function cls:GetSightFOVMultiplier(...) end ---@return any function cls:GetWallbangMaxDistance(...) end ---@return any function cls:GetVelocity(...) end ---@return any function cls:AddStaticMeshAttached(...) end ---@return any function cls:RemoveStaticMeshAttached(...) end ---@return any function cls:SetValue(...) end ---@return any function cls:GetLocation(...) end ---@return any function cls:SetRelativeRotation(...) end ---@return any function cls:Subscribe(...) end ---@return any function cls:SetHighlightEnabled(...) end ---@return any function cls:RotateTo(...) end ---@return any function cls:GetScale(...) end ---@return any function cls:SetVisibility(...) end ---@return any function cls:GetCollision(...) end ---@return any function cls:GetType(...) end ---@return any function cls:GetAnimationFire(...) end ---@return any function cls:GetHandler(...) end ---@return any function cls:SetCollision(...) end ---@return any function cls:GetID(...) end ---@return any function cls:HasNetworkAuthority(...) end ---@return any function cls:GetClipCapacity(...) end ---@return any function cls:GetCanHoldUse(...) end
local alphabet = "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz" local alphabet_i_to_char do local _tbl_0 = { } for i = 1, #alphabet do _tbl_0[i] = alphabet:sub(i, i) end alphabet_i_to_char = _tbl_0 end local alphabet_char_to_i do local _tbl_0 = { } for i = 1, #alphabet do _tbl_0[alphabet:sub(i, i)] = i end alphabet_char_to_i = _tbl_0 end local unpack = table.unpack or unpack local BigInt do local _class_0 local _base_0 = { is_zero = function(self) local _list_0 = self.bytes for _index_0 = 1, #_list_0 do local b = _list_0[_index_0] if b ~= 0 then return false end end return true end, to_string = function(self) return string.char(unpack(self.bytes)):reverse() end, to_number = function(self) local sum = 0 local k = 1 local _list_0 = self.bytes for _index_0 = 1, #_list_0 do local val = _list_0[_index_0] sum = sum + (val * k) k = k * 256 end return sum end, add = function(self, num) local k = 1 while true do self.bytes[k] = (self.bytes[k] or 0) + num if self.bytes[k] < 256 then break end num = math.floor(self.bytes[k] / 256) self.bytes[k] = self.bytes[k] % 256 k = k + 1 end end, mul = function(self, mul) local last_idx = 1 local r = 0 for idx = 1, #self.bytes do local cur = self.bytes[idx] * mul + r self.bytes[idx] = cur % 256 r = math.floor(cur / 256) last_idx = idx end if r > 0 then self.bytes[last_idx + 1] = r end return nil end, div = function(self, div) local r for idx = #self.bytes, 1, -1 do local b = self.bytes[idx] if r then b = b + (r * 256) end local q q, r = math.floor(b / div), b % div self.bytes[idx] = q end return self, r end } _base_0.__index = _base_0 _class_0 = setmetatable({ __init = function(self, bytes) if bytes == nil then bytes = { } end self.bytes = bytes end, __base = _base_0, __name = "BigInt" }, { __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 local self = _class_0 self.from_string = function(self, str) return self({ str:reverse():byte(1, -1) }) end BigInt = _class_0 end local encode_base58 encode_base58 = function(str) local buffer = { } local int = BigInt:from_string(str) while not int:is_zero() do local _, r = int:div(58) table.insert(buffer, alphabet_i_to_char[r + 1]) end return table.concat(buffer) end local decode_base58 decode_base58 = function(str) local out = BigInt() for i = #str, 1, -1 do local char = str:sub(i, i) local char_i = alphabet_char_to_i[char] if not (char_i) then return nil, "invalid string" end local char_byte = char_i - 1 out:mul(58) out:add(char_byte) end return out:to_string() end return { BigInt = BigInt, encode_base58 = encode_base58, decode_base58 = decode_base58 }
local shots = {} local settings = require("settings") shots.list = {} sound = love.audio.newSource("assets/shoot.wav", "static") function shots.create(source, fromPlayer, isSmall, vx, vy) local shot = {} if isSmall then shot.image = love.graphics.newImage("assets/shoot_small.png") else shot.image = love.graphics.newImage("assets/shoot.png") end shot.x = source.x + source.image:getWidth() / 2 - shot.image:getWidth() / 2 if fromPlayer then shot.y = source.y shot.vy = settings.SHOT_SPEED shot.vx = 0 else shot.y = source.y + source.image:getHeight() / 2 if vy == nil then shot.vy = -settings.SHOT_SPEED / 2 else shot.vy = vy end if vx == nil then shot.vx = 0 else shot.vx = vx end end shot.fromPlayer = fromPlayer shot.delete = false table.insert(shots.list, shot) sound:play() end function shots.update(player, aliens, explosions, dt) for i= 1, #shots.list do local shot = shots.list[i] -- Shoot interaction if shot.fromPlayer then for j= 1, #aliens.list do local alien = aliens.list[j] if collide(shot, alien) then explosions.create( shot.x + math.random(-2, 2) - alien.image:getWidth() / 2, shot.y + math.random(-2, 2) - shot.image:getHeight() / 2, alien.vx, alien.vy ) aliens.hit(j) shot.delete = true end end else if collide(shot, player) then shot.delete = true end end -- Shoot management shot.x = shot.x + shot.vx * dt shot.y = shot.y + shot.vy * dt if shot.y < 0 - shot.image:getHeight() or shot.y > settings.GAME_HEIGHT then shot.delete = true end end -- Shoot deletion for i= #shots.list, 1, -1 do local shot = shots.list[i] if shot.delete then shot.image = nil table.remove(shots.list, i) end end end function shots.draw() for i=1,#shots.list do local shot = shots.list[i] love.graphics.draw(shot.image, shot.x, shot.y) end end return shots
local ServerScriptService = game:GetService("ServerScriptService") local ReplicatedStorage = game:GetService("ReplicatedStorage") local RECS = require(ReplicatedStorage.Packages.RECS) local ExampleComponent = require(ServerScriptService.Components.Example) --[[ System setup ================ ]] local Example = RECS.System:extend("Example") function Example:init() for instance, component in self.core:components(ExampleComponent) do self:added(instance, component) end self.componentAddedSignal = self.core:getComponentAddedSignal(ExampleComponent) self.maid.componentAddedConnection = self.componentAddedSignal:connect(function(component, instance) self:added(instance, component) end) self.componentRemovingSignal = self.core:getComponentRemovingSignal(ExampleComponent) self.maid.componentRemovingConnection = self.componentRemovingSignal:connect(function(instance, component) self:removing(instance, component) end) end function Example:added(instance, component) wait() -- HACK, having to wait for the inst to have the component applied -- Do added stuff with the component here! end function Example:removing(instance, component) wait() -- HACK, having to wait for the inst to have the component applied -- Do removing stuff with the component here! end function Example:step(dt) -- Do stuff on step! end return Example
-- This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild -- -- This file is compatible with Lua 5.3 local class = require("class") require("kaitaistruct") local str_decode = require("string_decode") local stringstream = require("string_stream") require("rtp_packet") -- -- rtpdump is a format used by rtptools to record and replay -- rtp data from network capture. -- See also: Source (https://chromium.googlesource.com/external/webrtc/stable/talk/+/master/media/base/rtpdump.h) Rtpdump = class.class(KaitaiStruct) function Rtpdump:_init(io, parent, root) KaitaiStruct._init(self, io) self._parent = parent self._root = root or self self:_read() end function Rtpdump:_read() self.file_header = Rtpdump.HeaderT(self._io, self, self._root) self.packets = {} local i = 0 while not self._io:is_eof() do self.packets[i + 1] = Rtpdump.PacketT(self._io, self, self._root) i = i + 1 end end Rtpdump.HeaderT = class.class(KaitaiStruct) function Rtpdump.HeaderT:_init(io, parent, root) KaitaiStruct._init(self, io) self._parent = parent self._root = root or self self:_read() end function Rtpdump.HeaderT:_read() self.shebang = self._io:read_bytes(12) if not(self.shebang == "\035\033\114\116\112\112\108\097\121\049\046\048") then error("not equal, expected " .. "\035\033\114\116\112\112\108\097\121\049\046\048" .. ", but got " .. self.shebang) end self.space = self._io:read_bytes(1) if not(self.space == "\032") then error("not equal, expected " .. "\032" .. ", but got " .. self.space) end self.ip = str_decode.decode(self._io:read_bytes_term(47, false, true, true), "ascii") self.port = str_decode.decode(self._io:read_bytes_term(10, false, true, true), "ascii") self.start_sec = self._io:read_u4be() self.start_usec = self._io:read_u4be() self.ip2 = self._io:read_u4be() self.port2 = self._io:read_u2be() self.padding = self._io:read_u2be() end -- -- start of recording, the seconds part. -- -- start of recording, the microseconds part. -- -- network source. -- -- port. -- -- 2 bytes padding. Rtpdump.PacketT = class.class(KaitaiStruct) function Rtpdump.PacketT:_init(io, parent, root) KaitaiStruct._init(self, io) self._parent = parent self._root = root or self self:_read() end function Rtpdump.PacketT:_read() self.length = self._io:read_u2be() self.len_body = self._io:read_u2be() self.packet_usec = self._io:read_u4be() self._raw_body = self._io:read_bytes(self.len_body) local _io = KaitaiStream(stringstream(self._raw_body)) self.body = RtpPacket(_io) end -- -- packet length (including this header). -- -- payload length. -- -- timestamp of packet since the start.
--[[ Copyright (C) 2014 HarpyWar ([email protected]) This file is a part of the PvPGN Project http://pvpgn.pro Licensed under the same terms as Lua itself. ]]-- -- -- Read file w3motd.txt line by line and send text to user -- local username = nil function command_w3motd(account, text) -- allow warcraft 3 client only if not (account.clienttag == CLIENTTAG_WAR3XP or account.clienttag == CLIENTTAG_WARCRAFT3) then return 1 end username = account.name local data = file_load(config.motdw3file, w3motd_sendline_callback) return 0 end function w3motd_sendline_callback(line) api.message_send_text(username, message_type_info, nil, line) end
return { summary = 'Get the pose of a single node.', description = 'Returns the pose of a single node in the Model in a given `CoordinateSpace`.', arguments = { name = { type = 'string', description = 'The name of the node.' }, index = { type = 'number', description = 'The node index.' }, space = { type = 'CoordinateSpace', default = [['global']], description = [[ Whether the pose should be returned relative to the node's parent or relative to the root node of the Model. ]] } }, returns = { x = { type = 'number', description = 'The x position of the node.' }, y = { type = 'number', description = 'The y position of the node.' }, z = { type = 'number', description = 'The z position of the node.' }, angle = { type = 'number', description = 'The number of radians the node is rotated around its rotational axis.' }, ax = { type = 'number', description = 'The x component of the axis of rotation.' }, ay = { type = 'number', description = 'The y component of the axis of rotation.' }, az = { type = 'number', description = 'The z component of the axis of rotation.' } }, variants = { { arguments = { 'name', 'space' }, returns = { 'x', 'y', 'z', 'angle', 'ax', 'ay', 'az' } }, { arguments = { 'index', 'space' }, returns = { 'x', 'y', 'z', 'angle', 'ax', 'ay', 'az' } } }, notes = [[ For skinned nodes to render correctly, use a Shader created with the `animated` flag set to `true`. See `lovr.graphics.newShader` for more. ]], related = { 'Model:pose', 'Model:animate', 'Model:getNodeName', 'Model:getNodeCount' } }
local readerapi = dofile("./config-reader.lua"); local reader = readerapi.new(); --init and look for config reader:setpath("."); local isCachePresent = reader:open("config.cfg"); local initializedComputers = reader:seek("computer")[1]; if (not isCachePresent) then return error("run config.lua with the parameters \"-s computer [your_computer_address]\"" ) end
-- vim: et sw=2 sts=2 ts=2 local tsukuyomi = tsukuyomi local util = require('tsukuyomi.thirdparty.util') local PersistentList = tsukuyomi.lang.PersistentList local PersistentVector = tsukuyomi.lang.PersistentVector local PersistentHashMap = tsukuyomi.lang.PersistentHashMap local ArraySeq = tsukuyomi.lang.ArraySeq local ConcatSeq = tsukuyomi.lang.ConcatSeq local Symbol = tsukuyomi.lang.Symbol local Keyword = tsukuyomi.lang.Keyword local Var = tsukuyomi.lang.Var print('PersistentList: ' .. tostring(PersistentList)) print('PersistentList.EMPTY: ' .. tostring(PersistentList.EMPTY)) print('PersistentVector: ' .. tostring(PersistentVector)) print('PersistentHashMap: ' .. tostring(PersistentHashMap)) print('ConcatSeq: ' .. tostring(ConcatSeq)) print('ArraySeq: ' .. tostring(ArraySeq)) -- TODO: add indenting -- TODO: make not vulnerable to a stack overflow when printing cons cells -- TODO: make not vulnerable to infinite loop due to self referential data structures function tsukuyomi.print(datum) if type(datum) == 'boolean' then return tostring(datum) elseif type(datum) == 'number' then return tostring(datum) elseif type(datum) == 'string' then return '"' .. datum .. '"' elseif datum == nil then return 'nil' end local mt = getmetatable(datum) if mt == Symbol or mt == Keyword then return tostring(datum) elseif mt == PersistentVector then local items = {} for i = 0, datum:count() - 1 do table.insert(items, tsukuyomi.print(datum:get(i))) end return '[' .. table.concat(items, ' ') .. ']' elseif mt == PersistentHashMap then local items = {} local seq = datum:seq() while seq and seq:first() ~= nil do local kv = seq:first() local k = kv:get(0) local v = kv:get(1) table.insert(items, tsukuyomi.print(k)) table.insert(items, tsukuyomi.print(v)) seq = seq:rest() end return '{' .. table.concat(items, ' ') .. '}' elseif mt == Var then return tostring(datum) elseif datum.first ~= nil then local items = {} --[[ while true do if datum:count() == 0 then local check = datum:seq() if check ~= nil then print(getmetatable(datum)) print(util.show(datum)) assert(false) end break end local item = datum:first() table.insert(items, tsukuyomi.print(item)) datum = datum:rest() end ]]-- while datum:seq() do local item = datum:first() table.insert(items, tsukuyomi.print(item)) datum = datum:rest() end return '(' .. table.concat(items, ' ') .. ')' else print(util.show(datum)) assert(false) end end tsukuyomi.core['pr-str'] = tsukuyomi.lang.Function.new() tsukuyomi.core['pr-str'][1] = tsukuyomi.print
local ts_utils = require("nvim-treesitter.ts_utils") local ts_query = require("nvim-treesitter.query") local parsers = require("nvim-treesitter.parsers") local locals = require("nvim-treesitter.locals") local utils = require("contextprint.utils") --[[ --Parsers { available_parsers = <function 1>, ft_to_lang = <function 2>, get_buf_lang = <function 3>, get_parser = <function 4>, get_parser_configs = <function 5>, get_tree_root = <function 6>, has_parser = <function 7>, lang_match_ft = <function 8>, lang_to_ft = <function 9>, list: {...}, maintained_parsers = <function 10>, reset_cache = <function 11> } --Utils { get_named_children = <function 1>, get_next_node = <function 2>, get_node_at_cursor = <function 3>, get_node_range = <function 4>, get_node_text = <function 5>, get_previous_node = <function 6>, goto_node = <function 7>, highlight_node = <function 8>, highlight_range = <function 9>, is_in_node_range = <function 10>, is_parent = <function 11>, memoize_by_buf_tick = <function 12>, node_length = <function 13>, node_to_lsp_range = <function 14>, swap_nodes = <function 15>, update_selection = <function 16> } -- function get_function_name(node) for idx = 0, node:child_count() - 1 do local child = node:get if node:child(idx) end return nil end --]] -- -- local M = {} -- Array<node_wrapper> M.intersect_nodes = function(nodes, row, col) local found = {} for idx = 1, #nodes do local node = nodes[idx] local sRow = node.dim.s.r local sCol = node.dim.s.c local eRow = node.dim.e.r local eCol = node.dim.e.c if utils.intersects(row, col, sRow, sCol, eRow, eCol) then table.insert(found, node) end end return found end M.count_parents = function(node) local count = 0 local n = node.declaring_node while n ~= nil do n = n:parent() count = count + 1 end return count end -- @param nodes Array<node_wrapper> -- perf note. I could memoize some values here... M.sort_nodes = function(nodes) table.sort(nodes, function(a, b) return M.count_parents(a) < M.count_parents(b) end) return nodes end -- local lang = vim.api.nvim_buf_get_option(bufnr, 'ft') -- node_wrapper -- returns [{ -- declaring_node = tsnode -- dim: {s: {r, c}, e: {r, c}}, -- name: string -- type: string -- }] M.get_nodes = function(query, lang, defaults, bufnr) bufnr = bufnr or 0 local success, parsed_query = pcall(function() return vim.treesitter.parse_query(lang, query) end) if not success then return nil end local parser = parsers.get_parser(bufnr, lang) local root = parser:parse()[1]:root() local start_row, _, end_row, _ = root:range() local results = {} for match in ts_query.iter_prepared_matches(parsed_query, root, bufnr, start_row, end_row) do local sRow, sCol, eRow, eCol local declaration_node local type = "no_type" local name = nil locals.recurse_local_nodes(match, function(_, node, path) local idx = string.find(path, ".", 1, true) local op = string.sub(path, idx + 1, #path) type = string.sub(path, 1, idx - 1) if name == nil then name = defaults[type] or "empty" end if op == "name" then name = ts_utils.get_node_text(node)[1] elseif op == "declaration" then declaration_node = node sRow, sCol, eRow, eCol = node:range() sRow = sRow + 1 eRow = eRow + 1 sCol = sCol + 1 eCol = eCol + 1 end end) if declaration_node ~= nil then table.insert(results, { declaring_node = declaration_node, dim = { s = {r = sRow, c = sCol}, e = {r = eRow, c = eCol}, }, name = name, type = type, }) end end return results end return M -- -- local nodes = M.get_nodes( -- [[ -- (function (function_name) @function.name) @function.declaration -- (function_definition) @function.declaration -- ]], -- "lua" -- )
--One-Dimensional Array print("hello lua") -- array = {"Lua", "Tutorial"} for i = 0,2 do print(array[i]) end
local r = require("restructure") describe('Reserved', function() it('should have a default count of 1', function() local reserved = r.Reserved.new(r.uint8) assert.are_equal(1, reserved:size()) end) it('should allow custom counts and types', function() local reserved = r.Reserved.new(r.uint16,10) assert.are_equal(20, reserved:size()) end) it('should decode', function() local stream = r.DecodeStream.new(string.char(0,0)) local reserved = r.Reserved.new(r.uint16) assert.is_nil(reserved:decode(stream)) end) it('should encode', function() local stream = r.EncodeStream.new() local reserved = r.Reserved.new(r.uint16) reserved:encode(stream) assert.are_equal(string.char(0,0), stream:getContents()) end) end)
--finish obby local endzone = game.Workspace.tower.sections.finish.Finish.CFrame local player = game.Players.LocalPlayer.Character player.HumanoidRootPart.CFrame = endzone --rejoin local ts = game:GetService("TeleportService") local p = game:GetService("Players").LocalPlayer wait(3) ts:Teleport(game.PlaceId, p)
----------------------------------- -- -- tpz.effect.INNIN -- ----------------------------------- require("scripts/globals/status") ----------------------------------- function onEffectGain(target,effect) target:delMod(tpz.mod.EVA, effect:getPower()) target:delMod(tpz.mod.ENMITY, effect:getSubPower()) end function onEffectTick(target,effect) -- Tick down the effect and reduce the overall power effect:setPower(effect:getPower() - 1) target:addMod(tpz.mod.EVA, 1) -- Enmity+ decays from 20 to 10, so half as often as the rest if effect:getPower() % 2 == 0 then effect:setSubPower(effect:getSubPower() - 1) target:addMod(tpz.mod.ENMITY, 1) end end function onEffectLose(target,effect) -- Remove the remaining power target:addMod(tpz.mod.EVA, effect:getPower()) target:addMod(tpz.mod.ENMITY, effect:getSubPower()) end
messages = {} function messages:enter() self.cursorY = 0 self.yModPerc = 100 tween(0.2,self,{yModPerc=0}) output:sound('stoneslideshort',2) self.smallestY=0 end function messages:draw() game:draw() local width, height = love.graphics:getWidth(),love.graphics:getHeight() local uiScale = (prefs['uiScale'] or 1) love.graphics.push() love.graphics.scale(uiScale,uiScale) love.graphics.translate(0,height*(self.yModPerc/100)) love.graphics.setFont(fonts.textFont) local startX,startY,windowW,windowH if prefs['noImages'] then startX,startY,windowW,windowH = 1,1,width/uiScale-12,height/uiScale-12 else startX,startY,windowW,windowH = 1,1,width/uiScale-32,height/uiScale-32 end output:draw_window(startX,startY,windowW,windowH) local fontSize = prefs['fontSize'] local cursor = math.floor(height/uiScale)-fontSize local textWidth = math.floor(width/uiScale)-84 --Drawing the text: love.graphics.push() --Create a "stencil" that stops local function stencilFunc() love.graphics.rectangle("fill",startX+math.min(24,fontSize),startY+math.min(24,fontSize),width-math.min(48,fontSize*2),height-math.min(48,fontSize*2)) end love.graphics.stencil(stencilFunc,"replace",1) love.graphics.setStencilTest("greater",0) love.graphics.translate(0,-self.cursorY) for i = #output.text,1,-1 do local _, tlines = fonts.textFont:getWrap(ucfirst(output.text[i]),textWidth) cursor = cursor - math.floor(#tlines*(fontSize*1.25)) love.graphics.printf(ucfirst(output.text[i]),24,cursor,textWidth,"left") end love.graphics.setStencilTest() love.graphics.pop() self.smallestY = cursor-math.floor(fontSize/2) if self.smallestY < 1 then local scrollAmt = (self.smallestY-self.cursorY)/self.smallestY self.scrollPositions = output:scrollbar(math.floor(width/uiScale)-48,16,math.floor(height/uiScale)-(prefs['noImages'] and 24 or 16),scrollAmt,true) end self.closebutton = output:closebutton(24,24,nil,true) love.graphics.pop() end function messages:keypressed(key) key = input:parse_key(key) if (key == "north") then messages:scrollUp() elseif (key == "south") then messages:scrollDown() else self:switchBack() end end function messages:scrollUp() if self.cursorY > self.smallestY then self.cursorY = self.cursorY - prefs.fontSize end end function messages:scrollDown() if self.cursorY < 0 then self.cursorY = self.cursorY+prefs.fontSize end end function messages:mousepressed(x,y,button) local uiScale = (prefs['uiScale'] or 1) if button == 2 or (x/uiScale > self.closebutton.minX and x/uiScale < self.closebutton.maxX and y/uiScale > self.closebutton.minY and y/uiScale < self.closebutton.maxY) then self:switchBack() end end function messages:wheelmoved(x,y) if y > 0 then messages:scrollUp() elseif y < 0 then messages:scrollDown() end --end button type if end --end mousepressed if function messages:update(dt) if self.switchNow == true then self.switchNow = nil Gamestate.switch(game) Gamestate.update(dt) return end if (love.mouse.isDown(1)) and messages.scrollPositions then local x,y = love.mouse.getPosition() local upArrow = messages.scrollPositions.upArrow local downArrow = messages.scrollPositions.downArrow local elevator = messages.scrollPositions.elevator if x>upArrow.startX and x<upArrow.endX and y>upArrow.startY and y<upArrow.endY then messages:scrollUp() elseif x>downArrow.startX and x<downArrow.endX and y>downArrow.startY and y<downArrow.endY then messages:scrollDown() elseif x>elevator.startX and x<elevator.endX and y>upArrow.endY and y<downArrow.startY then if y<elevator.startY then messages:scrollUp() elseif y>elevator.endY then messages:scrollDown() end end --end clicking on arrow end end function messages:switchBack() tween(0.2,self,{yModPerc=100}) output:sound('stoneslideshortbackwards',2) Timer.after(0.2,function() self.switchNow=true end) end
print("======== test1.lua ========") goFunc = goEvent goFunc("goFunc from test1.lua")
local source = select(1,...) local term = require("terminal") local eapi = require("Editors") if source and source ~= "@clip" and source ~= "-?" then source = term.resolve(source) if source:sub(-5,-1) ~= ".lk12" then source = source..".lk12" end elseif source ~= "@clip" and source ~= "-?" then source = eapi.filePath end if not source or source == "-?" then printUsage( "load <file>","Loads a game into memory", "load","Reloads the current game", "load @clip","Load from clipboard" ) return end if source ~= "@clip" and not fs.exists(source) then color(8) print("File doesn't exists") return end if source ~= "@clip" and fs.isDirectory(source) then color(8) print("Couldn't load a directory !") return end local saveData = source == "@clip" and clipboard() or fs.read(source) if not saveData:sub(0,5) == "LK12;" then color(8) print("This is not a valid LK12 file !!") return end saveData = saveData:gsub("\r\n","\n") --LK12;OSData;OSName;DataType;Version;Compression;CompressLevel; data" --local header = "LK12;OSData;DiskOS;DiskGame;V"..saveVer..";"..sw.."x"..sh..";C:" local datasum = 0 local nextargiter = saveData:gmatch("(.-);") local function nextarg() local n = nextargiter() if n then datasum = datasum + n:len() + 1 return n else return n end end nextarg() --Skip LK12; local filetype = nextarg() if not filetype then color(8) print("Invalid Data !") return end if filetype ~= "OSData" then if filetype == "GPUIMG" then --Import it if eapi.leditors[eapi.editors.sprite] then local simg = imagedata(screenSize()) local limg = imagedata(saveData) simg:paste(limg) eapi.leditors[eapi.editors.sprite]:import(simg:encode()..";0;") color(11) print("Imported to sprite editor successfully") return end else color(8) print("Can't load '"..filetype.."' files !") return end end local osname = nextarg() if not osname then color(8) print("Invalid Data !") return end if osname ~= "DiskOS" then color(8) print("Can't load files from '"..osname.."' OS !") return end local datatype = nextarg() if not datatype then color(8) print("Invalid Data !") return end if datatype ~= "DiskGame" then color(8) print("Can't load '"..datatype.."' from '"..osname.."' OS !") return end local dataver = nextarg() if not dataver then color(8) print("Invalid Data !") return end dataver = tonumber(string.match(dataver,"V(%d+)")) if not dataver then color(8) print("Invalid Data !") return end if dataver > _DiskVer then color(8) print("Can't load disks newer than V".._DiskVer..", provided: V"..dataver) return end if dataver < _DiskVer then color(8) print("Can't load disks older than V".._DiskVer..", provided: V"..dataver..", Use 'update_disk' command to update the disk") return end local sw, sh = screenSize() local datares = nextarg() if not datares then color(8) print("Invalid Data !") return end local dataw, datah = string.match(datares,"(%d+)x(%d+)") if not (dataw and datah) then color(8) print("Invalid Data !") return end dataw, datah = tonumber(dataw), tonumber(datah) if dataw ~= sw or datah ~= sh then color(8) print("This disk is made for GPUs with "..dataw.."x"..datah.." resolution, current GPU is "..sw.."x"..sh) return end local compress = nextarg() if not compress then color(8) print("Invalid Data !") return end compress = string.match(compress,"C:(.+)") if not compress then color(8) print("Invalid Data !") return end local clevel = nextarg() if not clevel then color(8) print("Invalid Data !") return end clevel = string.match(clevel,"CLvl:(.+)") if not clevel then color(8) print("Invalid Data !") return end clevel = tonumber(clevel) local data = saveData:sub(datasum+2,-1) if compress ~= "none" then --Decompress local b64data, char = math.b64dec(data) if not b64data then cprint(char) cprint(string.byte(char)) error(tostring(char)) end data = math.decompress(b64data,compress,clevel) end eapi.filePath = source eapi:import(data) color(11) print("Loaded successfully")
-- Kidoz plugin local Library = require "CoronaLibrary" -- Create library local lib = Library:new{ name="plugin.kidoz", publisherId="com.coronalabs", version=1 } ------------------------------------------------------------------------------- -- BEGIN ------------------------------------------------------------------------------- -- This sample implements the following Lua: -- -- local PLUGIN_NAME = require "plugin_PLUGIN_NAME" -- PLUGIN_NAME:showPopup() -- local function showWarning(functionName) print( functionName .. " WARNING: The KIDOZ plugin is only supported on Android & iOS devices. Please build for device"); end function lib.init() showWarning("kidoz.init()") end function lib.load() showWarning("kidoz.load()") end function lib.isLoaded() showWarning("kidoz.isLoaded()") end function lib.show() showWarning("kidoz.show()") end function lib.hide() showWarning("kidoz.hide()") end ------------------------------------------------------------------------------- -- END ------------------------------------------------------------------------------- -- Return an instance return lib
--Text editor-- local args = {...} --Get the arguments passed to this program if #args < 1 or args[1] == "-?" then printUsage( "edit <file>","The file to edit in the text editor." ) return end local tar = table.concat(args," ") --The path may include whitespaces local term = require("terminal") tar = term.resolve(tar) local highlighter = require("Libraries.SyntaxHighlighter") if fs.exists(tar) and fs.isDirectory(tar) then return 1, "Can't edit directories !" end if fs.isReadonly(tar) and not fs.exists(tar) then return 1, "Directory is readonly !" end local eutils = require("Editors.utils") local tool = eutils:newTool(fs.isReadonly(tar)) local ok, editor = assert(pcall(assert(fs.load(_SystemDrive..":/Editors/code.lua")),tool)) if tar:sub(-4,-1) ~= ".lua" and tar:sub(-5,-1) ~= ".json" then editor.colorize = false end if tar:sub(-5,-1) == ".json" then highlighter:setSyntax("json") end editor.readonly = fs.isReadonly(tar) local data --Data to import at start. if fs.exists(tar) then data = fs.read(tar):gsub("\r\n","\n") end local function reload(tool) if fs.exists(tar) then tool.editor:import(fs.read(tar)) end _systemMessage("Reloaded successfully",1) end local function save(tool) local ndata = tool.editor:export() local ok, err = pcall(fs.write,tar,ndata) if ok then _systemMessage("Saved successfully",1) else _systemMessage("Failed: "..err,5,9,4) end end local function hotkey(tool,key,sc) if sc == "ctrl-r" then --Run the file local bkframe = screenshot() --Backup the screen local px, py, px = printCursor() --Backup the printing cursor pushMatrix() --Backup the matrix pushPalette() --Backup the palette pushColor() --Backup the current color cam() --Reset the camera. pal() palt() --Reset the palettes. printCursor(0,0,0) --Reset the printing cursor. clear() --Clear the screen. color(7) --Set the active color to white. if tool.editor.colorize then --If it's a Lua file local code = tool.editor:export() --Get the Lua code. local chunk, cerr = loadstring(code) if not chunk then color(8) print("CERR: "..tostring(cerr)) else local ok, err = pcall(chunk) if not ok then color(8) print("ERR: "..tostring(err)) end end color(9) print("[Press any key to continue]",false) flip() local kflag for event, a in pullEvent do if event == "keypressed" then kflag = a elseif event == "keyreleased" and kflag and kflag == a then break end end end cam() --Reset the camera. pal() palt() --Reset the palettes. clear() --Clear the screen. bkframe:image():draw() --Restore the screen frame popColor() --Restore the color popPalette() --Restore the palette popMatrix() --Restore the matrix printCursor(px,py,pc) --Restore the printing cursor return true end end tool:start(editor,reload,save,data,hotkey) highlighter:setSyntax("lua") --Make sure the highlighter is back into Lua
local mixpanel = require "src/vendor/mixpanel" --should be -1 for a negative number function test_random_id() assert_equal(#mixpanel.randomId(), 10) end function test_distinct_id() love.filesystem.remove('mixpanel.txt') assert_equal(mixpanel.distinctId(), mixpanel.distinctId()) end function test_distinct_id_len() love.filesystem.remove('mixpanel.txt') assert_equal(#mixpanel.distinctId(), 10) end function test_distinct_id_source() love.filesystem.write('mixpanel.txt', 'foo') assert_equal(mixpanel.distinctId(), 'foo') love.filesystem.remove('mixpanel.txt') end function test_randomness() assert_not_equal(mixpanel.randomId(), mixpanel.randomId()) end
local E, L, V, P, G = unpack(ElvUI); --Inport: Engine, Locales, PrivateDB, ProfileDB, GlobalDB, Localize Underscore local PD = E:NewModule('PaperDoll', 'AceEvent-3.0', 'AceTimer-3.0'); local find = string.find local initialized = false local originalInspectFrameUpdateTabs local updateTimer local slots = { ["HeadSlot"] = { true, true }, ["NeckSlot"] = { true, false }, ["ShoulderSlot"] = { true, true }, ["BackSlot"] = { true, false }, ["ChestSlot"] = { true, true }, ["WristSlot"] = { true, true }, ["MainHandSlot"] = { true, true }, ["SecondaryHandSlot"] = { true, true }, ["HandsSlot"] = { true, true }, ["WaistSlot"] = { true, true }, ["LegsSlot"] = { true, true }, ["FeetSlot"] = { true, true }, ["Finger0Slot"] = { true, false }, ["Finger1Slot"] = { true, false }, ["Trinket0Slot"] = { true, false }, ["Trinket1Slot"] = { true, false }, } --local levelAdjust = { -- ["0"]=0,["1"]=8,["373"]=4,["374"]=8,["375"]=4,["376"]=4, -- ["377"]=4,["379"]=4,["380"]=4,["445"]=0,["446"]=4,["447"]=8, -- ["451"]=0,["452"]=8,["453"]=0,["454"]=4,["455"]=8,["456"]=0, -- ["457"]=8,["458"]=0,["459"]=4,["460"]=8,["461"]=12,["462"]=16, -- ["465"]=0,["466"]=4,["467"]=8,["468"]=0,["469"]=4,["470"]=8, -- ["471"]=12,["472"]=16,["491"]=0,["492"]=4,["493"]=8,["494"]=0, -- ["495"]=4,["496"]=8,["497"]=12,["498"]=16, -- ["504"]=12,["505"]=16, --} local levelColors = { [0] = "|cffff0000", [1] = "|cff00ff00", [2] = "|cffffff88", } -- From http://www.wowhead.com/items?filter=qu=7;sl=16:18:5:8:11:10:1:23:7:21:2:22:13:24:15:28:14:4:3:19:25:12:17:6:9;minle=1;maxle=1;cr=166;crs=3;crv=0 local heirlooms = { [80] = { 44102,42944,44096,42943,42950,48677,42946,42948,42947,42992, 50255,44103,44107,44095,44098,44097,44105,42951,48683,48685, 42949,48687,42984,44100,44101,44092,48718,44091,42952,48689, 44099,42991,42985,48691,44094,44093,42945,48716 }, ["90h"] = {105689,105683,105686,105687,105688,105685,105690,105691,105684,105692,105693}, ["90n"] = {104399,104400,104401,104402,104403,104404,104405,104406,104407,104408,104409}, ["90f"] = {105675,105670,105672,105671,105674,105673,105676,105677,105678,105679,105680}, } function PD:UpdatePaperDoll(inspect) if not initialized then return end if InCombatLockdown() then PD:RegisterEvent("PLAYER_REGEN_ENABLED", "UpdatePaperDoll", inspect) return else PD:UnregisterEvent("PLAYER_REGEN_ENABLED") end local unit = (inspect and InspectFrame) and InspectFrame.unit or "player" if not unit then return end if unit and not CanInspect(unit, false) then return end local frame, slot, current, maximum, r, g, b local baseName = inspect and "Inspect" or "Character" local itemLink, itemLevel, itemLevelMax local avgItemLevel, avgEquipItemLevel = GetAverageItemLevel() for k, info in pairs(slots) do frame = _G[("%s%s"):format(baseName, k)] slot = GetInventorySlotInfo(k) if info[1] then frame.ItemLevel:SetText() if E.private.equipment.itemlevel.enable and info[1] then itemLink = GetInventoryItemLink(unit, slot) if itemLink then if ((slot == 16 or slot == 17) and GetInventoryItemQuality(unit, slot) == LE_ITEM_QUALITY_ARTIFACT) then local itemLevelMainHand = 0 local itemLevelOffHand = 0 local itemLinkMainHand = GetInventoryItemLink(unit, 16) local itemLinkOffhand = GetInventoryItemLink(unit, 17) if itemLinkMainHand then itemLevelMainHand = self:GetItemLevel(unit, 16 or 0) end if itemLinkOffhand then itemLevelOffHand = self:GetItemLevel(unit, 17 or 0) end itemLevel = math.max(itemLevelMainHand or 0, itemLevelOffHand or 0) else itemLevel = self:GetItemLevel(unit, slot) end if itemLevel and avgEquipItemLevel then frame.ItemLevel:SetFormattedText("%s%d|r", levelColors[(itemLevel < avgEquipItemLevel-10 and 0 or (itemLevel > avgEquipItemLevel + 10 and 1 or (2)))], itemLevel) end end end end if not inspect and info[2] then frame.DurabilityInfo:SetText() if E.private.equipment.durability.enable then current, maximum = GetInventoryItemDurability(slot) if current and maximum and (not E.private.equipment.durability.onlydamaged or current < maximum) then r, g, b = E:ColorGradient((current / maximum), 1, 0, 0, 1, 1, 0, 0, 1, 0) frame.DurabilityInfo:SetFormattedText("%s%.0f%%|r", E:RGBToHex(r, g, b), (current / maximum) * 100) end end end end end function PD:DelayUpdateInfo(inspect) if (updateTimer == 0 or PD:TimeLeft(updateTimer) == 0) then updateTimer = PD:ScheduleTimer("UpdatePaperDoll", .2, inspect) end end -- from http://www.wowinterface.com/forums/showthread.php?p=284771 by PhanX -- Construct your saarch pattern based on the existing global string: -- local S_UPGRADE_LEVEL = "^" .. gsub(ITEM_UPGRADE_TOOLTIP_FORMAT, "%%d", "(%%d+)") local S_ITEM_LEVEL = "^" .. gsub(ITEM_LEVEL, "%%d", "(%%d+)") -- Create the tooltip: local scantip = CreateFrame("GameTooltip", "MyScanningTooltip", WorldFrame, "GameTooltipTemplate") scantip:SetOwner(UIParent, "ANCHOR_NONE") local function GetSlotItemLevel(unit, slot) scantip:ClearLines() scantip:SetInventoryItem(unit, slot) -- Scan the tooltip: for i = 2, scantip:NumLines() do -- Line 1 is always the name so you can skip it. local text = _G["MyScanningTooltipTextLeft"..i]:GetText() if text and text ~= "" then local currentLevel = strmatch(text, S_ITEM_LEVEL) if currentLevel then return tonumber(currentLevel) end end end end local function GetRealItemLevel(itemLink) -- Pass the item link to the tooltip: scantip:ClearLines() scantip:SetHyperlink(itemLink) -- Scan the tooltip: for i = 2, scantip:NumLines() do -- Line 1 is always the name so you can skip it. local text = _G["MyScanningTooltipTextLeft"..i]:GetText() if text and text ~= "" then local currentLevel = strmatch(text, S_ITEM_LEVEL) if currentLevel then return currentLevel end end end end function PD:GetItemLevel(unit, slot) local itemLink = GetInventoryItemLink(unit, slot) local rarity, itemLevel = select(3, GetItemInfo(itemLink)) if rarity == 7 then -- heirloom adjust itemLevel = self:HeirLoomLevel(unit, itemLink) end itemlevel = GetSlotItemLevel(unit, slot) if itemlevel then return itemlevel else itemLevel = GetRealItemLevel(itemLink) itemLevel = tonumber(itemLevel) return itemLevel end end function PD:HeirLoomLevel(unit, itemLink) local level = UnitLevel(unit) if level > 85 then local _, _, _, _, itemId = find(itemLink, "|?c?f?f?(%x*)|?H?([^:]*):?(%d+):?(%d*):?(%d*):?(%d*):?(%d*):?(%d*):?(%-?%d*):?(%-?%d*):?(%d*):?(%d*)|?h?%[?([^%[%]]*)%]?|?h?|?r?") --print(itemId) itemId = tonumber(itemId); for _, id in pairs(heirlooms["90h"]) do if id == itemId then level = 582 break end end for _, id in pairs(heirlooms["90n"]) do if id == itemId then level = 569 break end end for _, id in pairs(heirlooms["90f"]) do if id == itemId then level = 548 break end end elseif level > 80 then local _, _, _, _, itemId = find(itemLink, "|?c?f?f?(%x*)|?H?([^:]*):?(%d+):?(%d*):?(%d*):?(%d*):?(%d*):?(%d*):?(%-?%d*):?(%-?%d*):?(%d*):?(%d*)|?h?%[?([^%[%]]*)%]?|?h?|?r?") --print(itemId) itemId = tonumber(itemId); for _, id in pairs(heirlooms[80]) do if id == itemId then level = 80 break end end end if level > 85 then return level elseif level > 80 then -- CAT heirloom scaling kicks in at 81 return (( level - 81) * 12.2) + 272; elseif level > 67 then -- WLK heirloom scaling kicks in at 68 return (( level - 68) * 6) + 130; elseif level > 59 then -- TBC heirloom scaling kicks in at 60 return (( level - 60) * 3) + 85; else return level end end function PD:InspectFrame_UpdateTabsComplete() originalInspectFrameUpdateTabs() PD:DelayUpdateInfo(true) end function PD:InitialUpdatePaperDoll() self:BuildInfoText("Character") PD:ScheduleTimer("UpdatePaperDoll", 2, false) initialized = true if IsAddOnLoaded("Blizzard_InspectUI") then self:OnAddonLoaded(_, "Blizzard_InspectUI") end PD:UnregisterEvent("PLAYER_ENTERING_WORLD") end function PD:BuildInfoText(name) for k, info in pairs(slots) do frame = _G[("%s%s"):format(name, k)] if info[1] then frame.ItemLevel = frame:CreateFontString(nil, "OVERLAY") frame.ItemLevel:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 1, 1) frame.ItemLevel:FontTemplate(E.media.font, 12, "THINOUTLINE") end if name == "Character" and info[2] then frame.DurabilityInfo = frame:CreateFontString(nil, "OVERLAY") frame.DurabilityInfo:SetPoint("TOP", frame, "TOP", 0, -4) frame.DurabilityInfo:FontTemplate(E.media.font, 12, "THINOUTLINE") end end end function PD:OnAddonLoaded(event, name) if ((name ~= "Blizzard_InspectUI") or not initialized) then return end self:BuildInfoText("Inspect") -- hook to inspect frame update originalInspectFrameUpdateTabs = _G.InspectFrame_UpdateTabs _G.InspectFrame_UpdateTabs = PD.InspectFrame_UpdateTabsComplete -- update player info PD:DelayUpdateInfo(true) PD:UnregisterEvent("ADDON_LOADED") end function PD:firstGarrisonToast() PD:UnregisterEvent("GARRISON_MISSION_FINISHED") self:ScheduleTimer("UpdatePaperDoll", 7) end function PD:Initialize() local frame PD:RegisterEvent("UPDATE_INVENTORY_DURABILITY", "UpdatePaperDoll", false) PD:RegisterEvent("PLAYER_EQUIPMENT_CHANGED", "UpdatePaperDoll", false) PD:RegisterEvent("SOCKET_INFO_UPDATE", "UpdatePaperDoll", false) PD:RegisterEvent("COMBAT_RATING_UPDATE", "UpdatePaperDoll", false) PD:RegisterEvent("MASTERY_UPDATE", "UpdatePaperDoll", false) --PD:RegisterEvent("GARRISON_MISSION_FINISHED", "firstGarrisonToast", false) PD:RegisterEvent("PLAYER_ENTERING_WORLD", "InitialUpdatePaperDoll") end E:RegisterModule(PD:GetName())
-- Do not source the default filetype.vim vim.g.did_load_filetypes = 1 -- avoid stupid menu.vim (saves ~100ms) vim.g.did_install_default_menus = 1 -- Options -- general opt vim.opt.fileformats = "unix,mac,dos" vim.opt.autowrite = true vim.opt.autowriteall = true vim.opt.backup = false vim.opt.writebackup = false vim.opt.swapfile = false vim.opt.undofile = true vim.opt.mouse = "a" vim.opt.errorbells = true vim.opt.visualbell = true vim.opt.ttimeoutlen = 100 vim.opt.updatetime = 300 -- behavior opt vim.opt.termguicolors = true vim.opt.background = "dark" vim.opt.clipboard = "unnamedplus" vim.opt.number = true vim.opt.relativenumber = true vim.opt.showtabline = 2 vim.opt.scrolloff = 5 vim.opt.splitbelow = true vim.opt.splitright = true vim.opt.jumpoptions = "stack" vim.opt.switchbuf = { "useopen", "uselast" } vim.opt.completeopt = { "menu", "menuone", "noselect" } vim.opt.pumblend = 10 vim.opt.winblend = 10 vim.opt.pumheight = 20 vim.opt.wildignorecase = true vim.opt.wildignore = "*node_modules/**" -- tabs & indent vim.opt.tabstop = 2 vim.opt.shiftwidth = 2 vim.opt.softtabstop = 2 vim.opt.expandtab = true vim.opt.smartindent = true vim.opt.breakindent = true -- search vim.opt.ignorecase = true vim.opt.smartcase = true vim.opt.infercase = true vim.opt.showmatch = true vim.opt.matchpairs = { "(:)", "{:}", "[:]", "<:>" } vim.opt.grepprg = [[rg --glob "!.git" --no-heading --vimgrep --follow $*]] -- line break vim.opt.signcolumn = "yes" vim.opt.colorcolumn = "+1" vim.opt.virtualedit = "block" vim.opt.wrap = false vim.opt.whichwrap:append "<>hl" vim.opt.showbreak = "↪ " vim.opt.list = true vim.opt.listchars = { tab = " ", trail = "·", extends = "", precedes = "", nbsp = "␣", } vim.opt.fillchars = { fold = " ", eob = " ", diff = "╱", } vim.opt.shortmess:append "csI"
local y=0.0 local x=0 local n=10000000 while x<n do y=y+x x=x+1 end print(y)
--[[----------------------------------------------------------------------------------------------------------------------- Physgun players -----------------------------------------------------------------------------------------------------------------------]]-- local PLUGIN = {} PLUGIN.Title = "Physgun Players" PLUGIN.Description = "Physgun a player." PLUGIN.Author = "Overv" PLUGIN.Privileges = { "Physgun players" } function PLUGIN:PhysgunPickup( ply, pl ) if ( ply:EV_HasPrivilege( "Physgun players" ) and pl:IsPlayer() and ply:EV_BetterThanOrEqual( pl ) ) then pl.EV_PickedUp = true pl:SetMoveType( MOVETYPE_NOCLIP ) return true end end function PLUGIN:PhysgunDrop( ply, pl ) if ( pl:IsPlayer() ) then pl.EV_PickedUp = false pl:SetMoveType( MOVETYPE_WALK ) return true end end function PLUGIN:PlayerNoclip( ply ) if ( pl.EV_PickedUp ) then return false end end evolve:RegisterPlugin( PLUGIN )
module 'mock' -------------------------------------------------------------------- local function varianceRange( v, variance, minValue, maxValue ) local min, max = v-variance, v+variance if minValue and min < minValue then min = minValue end if maxValue and max > maxValue then max = maxValue end return { min, max } end -------------------------------------------------------------------- local templateInitScript = [[ --init script local function variance(a,b) return b==0 and a or rand(a-b,a+b) end local function variance1(a,b) return b==0 and a or rand(a-b<0 and 0 or a-b, a+b>1 and 1 or a+b) end angle=variance($angle,$angleVariance) s0=variance($startParticleSize,$startParticleSizeVariance) s1=variance($finishParticleSize,$finishParticleSizeVariance) rot0=variance($rot0,$rot0Variance) rot1=variance($rot1,$rot1Variance) if '$emitterType'=='gravity' then -- speed=variance($speed,$speedVariance) -- vx=cos(angle)*speed -- vy=sin(angle)*speed vx = 0 vy = 0 if $hasRadAcc then radAcc=variance($radAcc,$radAccVariance) end if $hasTanAcc then tanAcc=variance($tanAcc,$tanAccVariance) end if $hasTanAcc or $hasRadAcc then dx=variance($srcX,$srcXVariance) dy=variance($srcY,$srcYVariance) p.x=p.x+dx p.y=p.y+dy else p.x=p.x+variance($srcX,$srcXVariance) p.y=p.y+variance($srcY,$srcYVariance) end else --radial x0=p.x y0=p.y rps=variance($rps, $rpsVariance) minRadius=$minRadius maxRadius=variance($maxRadius, $maxRadiusVariance) end r0,g0,b0,a0 = variance1($r0,$r0v),variance1($g0,$g0v),variance1($b0,$b0v),variance1($a0,$a0v) r1,g1,b1,a1 = variance1($r1,$r1v),variance1($g1,$g1v),variance1($b1,$b1v),variance1($a1,$a1v) ]] local templateRenderScript = [[ --render script if '$emitterType'=='gravity' then if $gravityX~=0 then vx=vx+$gravityX end if $gravityY~=0 then vy=vy+$gravityY end if $hasRadAcc or $hasTanAcc then a=vecAngle(dy,dx) * (3.14159265355/180) ca=cos(a) sa=sin(a) if $hasRadAcc then vx=vx+ca*radAcc vy=vy+sa*radAcc end if $hasTanAcc then vx=vx-sa*tanAcc vy=vy+ca*tanAcc end -- dx=dx+vx -- dy=dy+vy dx = dx + p.dx dy = dy + p.dy end p.x=p.x+vx p.y=p.y+vy else --radial radius=ease(maxRadius,minRadius) p.x=x0+cos(angle)*radius p.y=y0+sin(angle)*radius angle=angle+rps end sprite() local easeType=EaseType.LINEAR if $easeR then sp.r = ease( r0, r1,easeType) else sp.r=$r0 end if $easeG then sp.g = ease( g0, g1,easeType) else sp.g=$g0 end if $easeB then sp.b = ease( b0, b1,easeType) else sp.b=$b0 end if $easeA then sp.opacity = ease( a0, a1,easeType) else sp.opacity=$a0 end size = ease(s0,s1) sp.sx = size sp.sy = size sp.rot=ease(rot0,rot1) ]] -------------------------------------------------------------------- ---- PEX MODEL -------------------------------------------------------------------- CLASS: SimpleParticleSystemConfig () :MODEL{ Field 'deck' :asset('deck2d\\..*'); Field 'blend' :enum( mock.EnumBlendMode ); Field 'particles' :int() :range( 0, 2000 ); '----'; Field 'life' :number() :range( 0, 10 ) :widget('slider'); Field 'lifeVar' :number() :range( 0, 10 ) :widget('slider') :label( 'life.v' ); Field 'emission' :int() :range( 0, 100 ) :widget('slider'); Field 'frequency' :number() :range( 0.1, 100 ) :widget('slider'); Field 'emitSize' :type('vec2') :range( 0 ) :getset('EmitSize'); Field 'speed' :number() :range( 0, 2000 ) :widget('slider'); Field 'speedVar' :number() :range( 0, 2000 ) :widget('slider') :label('speed.v'); Field 'angle' :number() :range( 0, 360 ) :widget('slider'); Field 'angleVar' :number() :range( 0, 180 ) :widget('slider') :label('angle.v'); '----'; Field 'size' :number() :range( 0, 10 ) :widget('slider'); Field 'size1' :number() :range( 0, 10 ) :widget('slider'); Field 'sizeVar' :number() :range( 0, 10 ) :widget('slider') :label('size.v'); Field 'rot0' :number() :range( 0, 3600 ) :widget('slider'); Field 'rot0Var' :number() :range( 0, 3600 ) :widget('slider') :label('rot0.v'); Field 'rot1' :number() :range( 0, 3600 ) :widget('slider'); Field 'rot1Var' :number() :range( 0, 3600 ) :widget('slider') :label('rot1.v'); '----'; Field 'gravity' :type('vec2') :range( -5000, 5000 ) :getset('Gravity'); Field 'accRadial' :number() :range( -1000, 1000 ) :widget('slider'); Field 'accRadialVar' :number() :range( 0, 1000 ) :widget('slider') :label('accRadial.v'); Field 'accTan' :number() :range( -1000, 1000 ) :widget('slider'); Field 'accTanVar' :number() :range( 0, 1000 ) :widget('slider') :label('accTan.v'); '----'; Field 'color0' :type('color') :getset('Color0') ; Field 'color1' :type('color') :getset('Color1') ; Field 'colorVarR' :number() :range( 0, 1 ) :widget('slider') :label('red.v'); Field 'colorVarG' :number() :range( 0, 1 ) :widget('slider') :label('green.v'); Field 'colorVarB' :number() :range( 0, 1 ) :widget('slider') :label('blue.v'); Field 'colorVarA' :number() :range( 0, 1 ) :widget('slider') :label('alpha.v'); } -------------------------------------------------------------------- function SimpleParticleSystemConfig:__init() self.particles = 200 self.deck = false self.blend = 'add' self.life = 1 self.lifeVar = 0 self.emission = 1 self.frequency = 100 self.emitSize = {0,0} self.size = 1 self.size1 = 1 self.sizeVar = 0 self.speed = 100 self.speedVar = 0 self.angle = 0 self.angleVar = 0 self.rot0 = 0 self.rot0Var = 0 self.rot1 = 0 self.rot1Var = 0 self.accRadial = 0 self.accRadialVar = 0 self.accTan = 0 self.accTanVar = 0 self.gravity = { 0, -10 } self.color0 = {1,1,1,1} self.color1 = {1,1,1,0} self.colorVarR = 0 self.colorVarG = 0 self.colorVarB = 0 self.colorVarA = 0 self.deck = 'decks/particle.deck2d/pac' end -------------------------------------------------------------------- function SimpleParticleSystemConfig:getColor0() return unpack( self.color0 ) end function SimpleParticleSystemConfig:setColor0( r,g,b,a ) self.color0 = {r,g,b,a} end -------------------------------------------------------------------- function SimpleParticleSystemConfig:getColor1() return unpack( self.color1 ) end function SimpleParticleSystemConfig:setColor1( r,g,b,a ) self.color1 = {r,g,b,a} end -------------------------------------------------------------------- function SimpleParticleSystemConfig:getEmitSize() return unpack( self.emitSize ) end function SimpleParticleSystemConfig:setEmitSize( w, h ) self.emitSize = {w,h} end -------------------------------------------------------------------- function SimpleParticleSystemConfig:getGravity() return unpack( self.gravity ) end function SimpleParticleSystemConfig:setGravity( x, y ) self.gravity = { x, y } end -------------------------------------------------------------------- function SimpleParticleSystemConfig:buildStateScript() local fps = 60 local timeScale = 1/fps local accScale = timeScale * timeScale local initScript local renderScript local t = self local emitterType = 'gravity' local c0 = t.color0 local c1 = t.color1 local c0v = { t.colorVarR, t.colorVarG, t.colorVarB, t.colorVarA } local c1v = { 0, 0, 0, 0 } local hasRadAcc = t.accRadial~=0 or t.accRadialVar~=0 local hasTanAcc = t.accTan~=0 or t.accTanVar~=0 local dataInit = { emitterType = emitterType, speed = t.speed * timeScale, speedVariance = t.speedVar * timeScale, angle = t.angle / 180 * math.pi, angleVariance = t.angleVar / 180 * math.pi, r0 = c0[1], r0v = c0v[1], g0 = c0[2], g0v = c0v[2], b0 = c0[3], b0v = c0v[3], a0 = c0[4], a0v = c0v[4], r1 = c1[1], r1v = c1v[1], g1 = c1[2], g1v = c1v[2], b1 = c1[3], b1v = c1v[3], a1 = c1[4], a1v = c1v[4], startParticleSize = t.size, startParticleSizeVariance = t.sizeVar, finishParticleSize = t.size1, finishParticleSizeVariance = 0, --TODO:? rot0 = t.rot0, rot0Variance = t.rot0Var, rot1 = t.rot1, rot1Variance = t.rot1Var, radAcc = t.accRadial * accScale, radAccVariance = t.accRadialVar * accScale, tanAcc = t.accTan * accScale, tanAccVariance = t.accTanVar * accScale, hasRadAcc = tostring(hasRadAcc), hasTanAcc = tostring(hasTanAcc), srcX = 0,--t.sourcePosition.x, srcXVariance = t.emitSize[1], srcY = 0,--t.sourcePosition.y, srcYVariance = t.emitSize[2], --RADIAL EMITTER --TODO rps = 0 * math.pi/180 * timeScale, --TODO rpsVariance = 0 * math.pi/180 * timeScale, --TODO minRadius = 0, maxRadius = 0, maxRadiusVariance = 0, } -- if t.blendFuncSource == 1 then dataInit.a1 = 1 dataInit.a0 = 1 end local init = string.gsub( templateInitScript, "%$(%w+)", dataInit ) local function checkColorEase( data, field ) local r0 = data[ field..'0' ] local r0v = data[ field..'0v' ] local r1 = data[ field..'1' ] local r1v = data[ field..'1v' ] return tostring( not( r0==r1 and r0v==0 and r1v==0 ) ) end local gx,gy = self:getGravity() local dataRender={ emitterType = emitterType, gravityX = gx * accScale, --TODO gravityY = gy * accScale, --TODO hasRadAcc = tostring( hasRadAcc ), hasTanAcc = tostring( hasTanAcc ), easeR = checkColorEase( dataInit, 'r' ), easeG = checkColorEase( dataInit, 'g' ), easeB = checkColorEase( dataInit, 'b' ), easeA = checkColorEase( dataInit, 'a' ), r0 = c0[1], g0 = c0[2], b0 = c0[3], a0 = c0[4], } local render = string.gsub( templateRenderScript, "%$(%w+)", dataRender ) -- print( init ) -- print( render ) return init, render end -------------------------------------------------------------------- function SimpleParticleSystemConfig:buildSystemConfig() local init, render = self:buildStateScript() --state local st = ParticleStateConfig() st.name = 'default' st.life = varianceRange( self.life, self.lifeVar, 0 ) st.initScript = init st.renderScript = render --Emitter local em = ParticleEmitterConfig() em.name = 'default' em.type = 'timed' em.frequency = self.frequency em.emission = self.emission em.magnitude = varianceRange( self.speed, self.speedVar ) em.angle = varianceRange( self.angle, self.angleVar ) --System local cfg = ParticleSystemConfig() cfg.particles = self.particles cfg.sprites = self.particles cfg.deck = self.deck local w, h = self:getEmitSize() cfg.rect = { -w/2, -h/2, w, h } cfg:addStateConfig( st ) cfg:addEmitterConfig( em ) cfg.blend = self.blend self.systemConfig = cfg return cfg end -------------------------------------------------------------------- function SimpleParticleSystemConfig:getSystemConfig() if self.systemConfig then return self.systemConfig end return self:buildSystemConfig() end -------------------------------------------------------------------- local function loadSimpleParticleConfig( node ) local defData = loadAssetDataTable( node:getObjectFile('def') ) local simpleSystemConfig = deserialize( nil, defData ) node.cached.simpleConfig = simpleSystemConfig return simpleSystemConfig:getSystemConfig() end -------------------------------------------------------------------- registerAssetLoader( 'particle_simple', loadSimpleParticleConfig )
local shopTabPanel, modshopTab, modshop_gui local modshop_upgrades, current_vehicle, vehicle_price = {}, nil, 550 local neons = {} local player_perks ------------------------ ---- Loading GUI --- ------------------------ function onShopInit ( tabPanel ) shopTabPanel = tabPanel colorPicker.constructor() modshopTab = guiCreateTab ( 'Modshop', shopTabPanel ) if modshopTab then modshop_gui = build_modshopWidget( modshopTab, 35, 10 ) guiSetText(modshop_gui['labelPrice'], 'You should register and log in to buy\nvehicles and upgrade them') addEventHandler( 'onClientGUIClick', modshop_gui["carsTable"], vehicleSelected, false) addEventHandler( 'onClientGUIClick', modshop_gui["upgradeTable"], upgradeSelected, false) end if modshop_gui then guiSetVisible(modshop_gui["tabBuyExtras"], false) guiSetVisible(modshop_gui["tabNeonlights"], false) guiSetVisible(modshop_gui["tabCustomHorns"], false) loadVehicleList() --loadUpgradeList(tonumber(current_vehicle) or nil) -- loadNeon(tonumber(current_vehicle) or nil) end hasJustStarted = true end addEventHandler('onShopInit', resourceRoot, onShopInit ) function modshopLogin ( price, modshop_table ) storeUpgrades ( modshop_table ) if hasJustStarted then hasJustStarted = false guiDeleteTab(modshopTab, shopTabPanel) end vehicle_price = price if shopTabPanel and not isElement(modshopTab) then modshopTab = guiCreateTab ( 'Modshop', shopTabPanel ) if modshopTab then modshop_gui = build_modshopWidget( modshopTab, 35, 10 ) guiSetText(modshop_gui['labelPrice'], 'Current price for one vehicle: ' .. (tostring(vehicle_price) or 550) .. ' GC\n\nAll upgrades are free for bought vehicles') addEventHandler( 'onClientGUIClick', modshop_gui["carsTable"], vehicleSelected, false) addEventHandler( 'onClientGUIClick', modshop_gui["upgradeTable"], upgradeSelected, false) addEventHandler( 'onClientGUIClick', modshop_gui["tabelPaintjob"], paintjobSelected, false) end end if modshop_gui then if not doesHaveExtraMods() then -- guiSetVisible(modshop_gui["tabBuyExtras"], true) -- disabled for the moment guiSetVisible(modshop_gui["tabBuyExtras"], false) -- guiSetVisible(modshop_gui["tabNeonlights"], false) guiSetVisible(modshop_gui["tabCustomHorns"], false) else guiSetVisible(modshop_gui["tabNeonlights"], true) guiSetVisible(modshop_gui["tabCustomHorns"], true) if guiGetSelectedTab(modshop_gui["modshopTabs"]) == modshop_gui["tabBuyExtras"] then guiSetSelectedTab(modshop_gui["modshopTabs"], modshop_gui["tabNeonlights"]) end guiSetVisible(modshop_gui["tabBuyExtras"], false) end loadVehicleList() loadUpgradeList(tonumber(current_vehicle) or nil) loadNeon(tonumber(current_vehicle) or nil) modshopLoadPJS(player_perks); end end addEvent('modshopLogin', true) addEventHandler('modshopLogin', localPlayer, modshopLogin) function modshopLogout() --[[if shopTabPanel and modshopTab then guiDeleteTab ( modshopTab, shopTabPanel ) modshopTab = nil end]] end addEvent('modshopLogout', true) addEventHandler('modshopLogout', localPlayer, modshopLogout) function storeUpgrades ( modshop_table ) modshop_upgrades = {} for k,v in pairs(modshop_table or {}) do modshop_upgrades[tostring(v.vehicle)] = v end end function loadVehicleList() guiGridListClear(modshop_gui["carsTable"]) guiGridListSetColumnWidth(modshop_gui["carsTable"],modshop_gui["carsTable_col0"], 0.7, true) guiGridListSetColumnWidth(modshop_gui["carsTable"],modshop_gui["carsTable_col1"], 0.1, true) for k, group in pairs(getElementChildren(getElementByID("modshop_vehicles"))) do if getElementType(group) == "vehicle_group" and getElementData(group, "ignore", false) ~= "true" then local i = guiGridListAddRow(modshop_gui["carsTable"]) local groupName = getElementData(group, "name", false) guiGridListSetItemText( modshop_gui["carsTable"], i, modshop_gui["carsTable_col0"], tostring(groupName), true, false ) for k, vehicle in pairs(getElementChildren(group)) do if getElementType(vehicle) == "modshop_vehicle" and getElementData(vehicle, "ignore", false) ~= "true" then local i = guiGridListAddRow(modshop_gui["carsTable"]) local vehicle_name, vehicle_id = getElementData(vehicle, "vehicle_name", false), getElementData(vehicle, "vehicle_id", false) guiGridListSetItemText( modshop_gui["carsTable"], i, modshop_gui["carsTable_col0"], tostring(vehicle_name), false, false ) guiGridListSetItemText( modshop_gui["carsTable"], i, modshop_gui["carsTable_col1"], tostring(vehicle_id), false, true ) -- outputChatBox(tostring(modshop_upgrades[vehicle_id])) if modshop_upgrades[vehicle_id] then guiGridListSetItemColor ( modshop_gui["carsTable"], i, modshop_gui["carsTable_col0"], 102, 205, 0 ) guiGridListSetItemColor ( modshop_gui["carsTable"], i, modshop_gui["carsTable_col1"], 102, 205, 0 ) end end end end end guiSetEnabled(modshop_gui["buyVehicleButton"], false) guiSetEnabled(modshop_gui["upgradeVehicleButton"], false) if current_vehicle then fillInCurrentUpgrades ( current_vehicle ) end end ----------------------------- --- Buying the extras --- ----------------------------- function doesHaveExtraMods() local vehID = "0" local slot = "slot0" local key = 1 return modshop_upgrades and modshop_upgrades[vehID] and tonumber(modshop_upgrades[vehID][slot]) == key end function on_btnEnableExtras_clicked(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") then return end triggerServerEvent ( 'gcbuyextras', resourceRoot, localPlayer, 'gcbuyextras' ) end ---------------------------- --- Buying/selecting --- ---------------------------- function vehicleSelected(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") or not shop_GUI or source ~= modshop_gui["carsTable"] then return end local row, col = guiGridListGetSelectedItem(source) if tonumber(row) and tonumber(col) then local vehID = guiGridListGetItemText(source, row, modshop_gui["carsTable_col1"]) if modshop_upgrades[tostring(vehID)] then guiSetEnabled(modshop_gui["buyVehicleButton"], false) guiSetEnabled(modshop_gui["upgradeVehicleButton"], true) else guiSetEnabled(modshop_gui["buyVehicleButton"], true) guiSetEnabled(modshop_gui["upgradeVehicleButton"], false) end end end function on_buyVehicleButton_clicked(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") then return end local row, col = guiGridListGetSelectedItem(modshop_gui["carsTable"]) local selectedVehicle = tonumber(guiGridListGetItemText(modshop_gui["carsTable"], row, modshop_gui["carsTable_col1"])) if type(selectedVehicle) =='number' then triggerServerEvent ( 'gcbuyveh', resourceRoot, localPlayer, 'gcbuyveh', tostring(selectedVehicle)) end end function on_upgradeVehicleButton_clicked(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") then return end local row, col = guiGridListGetSelectedItem(modshop_gui["carsTable"]) local selectedName = guiGridListGetItemText(modshop_gui["carsTable"], row, modshop_gui["carsTable_col0"]) local selectedID = tonumber(guiGridListGetItemText(modshop_gui["carsTable"], row, modshop_gui["carsTable_col1"])) if not tonumber(current_vehicle) then guiSetEnabled(modshop_gui["btnApplyColor"], true) guiSetEnabled(modshop_gui["btnApplyColor_2"], true) guiSetEnabled(modshop_gui["btnCol1"], true) guiSetEnabled(modshop_gui["btnCol2"], true) guiSetEnabled(modshop_gui["btnCol3"], true) guiSetEnabled(modshop_gui["btnLight"], true) guiSetEnabled(modshop_gui["btnApplyPaintjob"], true) guiSetEnabled(modshop_gui["btnApplyPaintjob2"], true) guiSetEnabled(modshop_gui["addUpgradeButton"], true) guiSetEnabled(modshop_gui["viewVehicleButton"], true) guiSetEnabled(modshop_gui["tabVehicleColors"], true) guiSetEnabled(modshop_gui["tabUpgrades"], true) guiSetEnabled(modshop_gui["tabNeonlights"], true) end current_vehicle = selectedID guiSetText( modshop_gui["labelCurrentVehicle"] , "Currently modding: " .. selectedName .. " (" .. current_vehicle .. ")") loadUpgradeList(current_vehicle) loadNeon(current_vehicle) local col = rgbaToHex(0, 0, 0, 0) guiSetProperty(modshop_gui["squareCol1"], "ImageColours", string.format("tl:%s tr:%s bl:%s br:%s", tostring(col), tostring(col), tostring(col), tostring(col))) guiSetProperty(modshop_gui["squareCol2"], "ImageColours", string.format("tl:%s tr:%s bl:%s br:%s", tostring(col), tostring(col), tostring(col), tostring(col))) guiSetProperty(modshop_gui["squareLight"], "ImageColours", string.format("tl:%s tr:%s bl:%s br:%s", tostring(col), tostring(col), tostring(col), tostring(col))) return fillInCurrentUpgrades(current_vehicle) end function on_viewVehicleButton_clicked(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") then return end triggerServerEvent('gctestveh', localPlayer, localPlayer, 'gctestveh', tostring(current_vehicle)); end function fillInCurrentUpgrades ( vehID ) if not tonumber(vehID) then return end local upgrades = modshop_upgrades[tostring(vehID)] -- Paintjob local paintjob_id = tonumber(upgrades.slot17) if paintjob_id and ((0 <= paintjob_id and paintjob_id <= 2) or 4 <= paintjob_id) then guiGridListSetSelectedItem(modshop_gui["tabelPaintjob"], (paintjob_id + (4 <= paintjob_id and 0 or 1)), modshop_gui["tabelPaintjob_col0"]) if 4 <= paintjob_id then previewPJ(); end else guiGridListSetSelectedItem(modshop_gui["tabelPaintjob"], 0, modshop_gui["tabelPaintjob_col0"]) end -- Vehicle colors guiSetText(modshop_gui["editCol1"], tonumber(upgrades.slot18) and '' or tostring(upgrades.slot18 or '')) guiSetText(modshop_gui["editCol2"], tonumber(upgrades.slot19) and '' or tostring(upgrades.slot19 or '')) guiSetText(modshop_gui["editCol3"], tonumber(upgrades.slot20) and '' or tostring(upgrades.slot20 or '')) guiSetText(modshop_gui["editLight"], tonumber(upgrades.slot22) and upgrades.slot22..','..upgrades.slot23..','..upgrades.slot24 or '') local t1, t2, t3 = split(tostring(upgrades.slot18), ','), split(tostring(upgrades.slot19), ','), split(tostring(upgrades.slot20), ',') tempColors["veh_color1"] = #t1 == 3 and {r = t1[1], g = t1[2], b = t1[3]} or {} tempColors["veh_color2"] = #t2 == 3 and {r = t2[1], g = t2[2], b = t2[3]} or {} tempColors["veh_color3"] = #t3 == 3 and {r = t3[1], g = t3[2], b = t3[3]} or {} tempColors["light_color"] = tonumber(upgrades.slot22) and {r = tonumber(upgrades.slot22), g = tonumber(upgrades.slot23), b = tonumber(upgrades.slot24)} or {} local col1 = rgbaToHex(tonumber(t1[1]), tonumber(t1[2]), tonumber(t1[3]), 255) guiSetProperty(modshop_gui["squareCol1"], "ImageColours", string.format("tl:%s tr:%s bl:%s br:%s", tostring(col1), tostring(col1), tostring(col1), tostring(col1))) local col2 = rgbaToHex(tonumber(t2[1]), tonumber(t2[2]), tonumber(t2[3]), 255) guiSetProperty(modshop_gui["squareCol2"], "ImageColours", string.format("tl:%s tr:%s bl:%s br:%s", tostring(col2), tostring(col2), tostring(col2), tostring(col2))) local col3 = rgbaToHex(tonumber(t3[1]), tonumber(t3[2]), tonumber(t3[3]), 255) guiSetProperty(modshop_gui["squareCol3"], "ImageColours", string.format("tl:%s tr:%s bl:%s br:%s", tostring(col3), tostring(col3), tostring(col3), tostring(col3))) local coll = rgbaToHex(tonumber(upgrades.slot22), tonumber(upgrades.slot23), tonumber(upgrades.slot24), 255) guiSetProperty(modshop_gui["squareLight"], "ImageColours", string.format("tl:%s tr:%s bl:%s br:%s", tostring(coll), tostring(coll), tostring(coll), tostring(coll))) end ---------------------------- --- Upgrading colors --- ---------------------------- local editing = '' local gui = { ["veh_color1"] = "editCol1", ["veh_color2"] = "editCol2", ["veh_color3"] = "editCol3", ["light_color"] = "editLight" } local gui_square = { ["veh_color1"] = "squareCol1", ["veh_color2"] = "squareCol2", ["veh_color3"] = "squareCol3", ["light_color"] = "squareLight" } tempColors = { ["veh_color1"] = { ["r"] = nil, ["g"] = nil, ["b"] = nil, ["a"] = nil, ["gui"] = "editCol1" }, ["veh_color2"] = { ["r"] = nil, ["g"] = nil, ["b"] = nil, ["a"] = nil, ["gui"] = "editCol2" }, ["veh_color3"] = { ["r"] = nil, ["g"] = nil, ["b"] = nil, ["a"] = nil, ["gui"] = "editCol3" }, ["light_color"] = { ["r"] = nil, ["g"] = nil, ["b"] = nil, ["a"] = nil, ["gui"] = "editLight" } } function on_btnCol1_clicked(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") then return end openColorPicker("veh_color1") end function on_btnCol2_clicked(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") then return end openColorPicker("veh_color2") end function on_btnCol3_clicked(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") then return end openColorPicker("veh_color3") end function on_btnLight_clicked(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") then return end openColorPicker ( "light_color") end function openColorPicker(color) guiSetVisible(shop_GUI._root, false) editing = color colorPicker.openSelect(color) colorPicker.setValue({tempColors[editing].r,tempColors[editing].g,tempColors[editing].b,255}) addEventHandler("onClientRender", root, updateColor) end function updateColor() if (not colorPicker.isSelectOpen) then return end local r1, g1, b1 = tempColors.veh_color1.r, tempColors.veh_color1.g, tempColors.veh_color1.b local r2, g2, b2 = tempColors.veh_color2.r, tempColors.veh_color2.g, tempColors.veh_color2.b local r3, g3, b3 = tempColors.veh_color3.r, tempColors.veh_color3.g, tempColors.veh_color3.b local rl, gl, bl = tempColors.light_color.r, tempColors.light_color.g, tempColors.light_color.b guiSetText(modshop_gui[gui[editing]], tempColors[editing].r ..','.. tempColors[editing].g ..','.. tempColors[editing].b) local col = rgbaToHex(tempColors[editing].r, tempColors[editing].g, tempColors[editing].b, 255) guiSetProperty(modshop_gui[gui_square[editing]], "ImageColours", string.format("tl:%s tr:%s bl:%s br:%s", tostring(col), tostring(col), tostring(col), tostring(col))) local editingVehicle = getPedOccupiedVehicle(localPlayer) if editingVehicle and current_vehicle == getElementModel(editingVehicle) then local r1_, g1_, b1_, r2_, g2_, b2_, r3_, g3_, b3_ = getVehicleColor(editingVehicle, true) setVehicleColor(editingVehicle, r1 or r1_, g1 or g1_, b1 or b1_, r2 or r2_, g2 or g2_, b2 or b2_, r3 or r3_, g3 or g3_, b3 or b3_) local rl_, gl_, bl_ = getVehicleHeadLightColor(editingVehicle) setVehicleHeadLightColor(editingVehicle, rl or rl_, gl or gl_, bl or bl_) end end function closedColorPicker() removeEventHandler("onClientRender", root, updateColor) editing = '' guiSetVisible(shop_GUI._root, true) end function on_btnApplyColor_clicked(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") then return end local col1 = split(guiGetText(modshop_gui["editCol1"]), ',') local col2 = split(guiGetText(modshop_gui["editCol2"]), ',') local col3 = split(guiGetText(modshop_gui["editCol3"]), ',') local coll = split(guiGetText(modshop_gui["editLight"]), ',') triggerServerEvent ( 'gcsetmod', resourceRoot, localPlayer, 'gcsetmod', tostring(current_vehicle), 'vcolor2', col1[1], col1[2], col1[3], col2[1], col2[2], col2[3], col3[1], col3[2], col3[3]) triggerServerEvent ( 'gcsetmod', resourceRoot, localPlayer, 'gcsetmod', tostring(current_vehicle), 'lcolor', coll[1], coll[2], coll[3]) end function on_btnApplyColor_2_clicked(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") then return end local col1 = split(guiGetText(modshop_gui["editCol1"]), ',') local col2 = split(guiGetText(modshop_gui["editCol2"]), ',') local col3 = split(guiGetText(modshop_gui["editCol3"]), ',') local coll = split(guiGetText(modshop_gui["editLight"]), ',') triggerServerEvent ( 'gcsetmod', resourceRoot, localPlayer, 'gcsetmod', '*', 'vcolor2', col1[1], col1[2], col1[3], col2[1], col2[2], col2[3],col3[1], col3[2], col3[3]) triggerServerEvent ( 'gcsetmod', resourceRoot, localPlayer, 'gcsetmod', '*', 'lcolor', coll[1], coll[2], coll[3]) end function on_btnApplyPaintjob_clicked(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") then return end local row, col = guiGridListGetSelectedItem(modshop_gui["tabelPaintjob"]) if row == -1 then row = 0 end triggerServerEvent ( 'gcsetmod', resourceRoot, localPlayer, 'gcsetmod', tostring(current_vehicle), 'paintjob', tostring(row or 0)) end function on_btnApplyPaintjob2_clicked(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") then return end local row, col = guiGridListGetSelectedItem(modshop_gui["tabelPaintjob"]) if row == -1 then row = 0 end triggerServerEvent ( 'gcsetmod', resourceRoot, localPlayer, 'gcsetmod', '*', 'paintjob', tostring(row or 0)) end function paintjobSelected(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") or not shop_GUI or source ~= modshop_gui["tabelPaintjob"] then return end local row, col = guiGridListGetSelectedItem(source) if row >= 4 then guiSetEnabled(modshop_gui["btnUploadPaintjob"], true) else guiSetEnabled(modshop_gui["btnUploadPaintjob"], false) end previewPJ(); end function previewPJ() local row, col = guiGridListGetSelectedItem(modshop_gui["tabelPaintjob"]) if row >= 4 then local filename = 'items/paintjob/' .. forumID .. '-' .. row - 3 .. '.bmp'; if fileExists(filename) then if not modshop_gui["imgPreviewPaintjob"] then modshop_gui["imgPreviewPaintjob"] = guiCreateStaticImage( 484, 80, 120, 120, filename, false, modshop_gui["tabVehicleColors"] ) else guiStaticImageLoadImage(modshop_gui["imgPreviewPaintjob"], filename); end elseif modshop_gui["imgPreviewPaintjob"] then destroyElement(modshop_gui["imgPreviewPaintjob"]); modshop_gui["imgPreviewPaintjob"] = nil; end else if modshop_gui["imgPreviewPaintjob"] then destroyElement(modshop_gui["imgPreviewPaintjob"]); modshop_gui["imgPreviewPaintjob"] = nil; end end end function on_btnUploadPaintjob_clicked(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") then return end local row, col = guiGridListGetSelectedItem(modshop_gui["tabelPaintjob"]) if row < 4 then outputChatBox('Choose a custom from the list!', 255, 0, 0); else triggerServerEvent('setUpCustomPaintJob', resourceRoot, localPlayer, guiGetText(modshop_gui["editFilename"]), row - 3); end end function modshopLoadPJS(player_perks_) player_perks = player_perks_ if not modshop_gui["tabelPaintjob"] then return end if player_perks and player_perks[4] and player_perks[4].options.amount >= 1 and guiGridListGetRowCount(modshop_gui["tabelPaintjob"]) ~= player_perks[4].options.amount + 4 then guiGridListClear(modshop_gui["tabelPaintjob"]); previewPJ(); local tabelPaintjob_row = guiGridListAddRow(modshop_gui["tabelPaintjob"]) guiGridListSetItemText(modshop_gui["tabelPaintjob"], tabelPaintjob_row, modshop_gui["tabelPaintjob_col0"], "No paintjob", false, false ) tabelPaintjob_row = guiGridListAddRow(modshop_gui["tabelPaintjob"]) guiGridListSetItemText(modshop_gui["tabelPaintjob"], tabelPaintjob_row, modshop_gui["tabelPaintjob_col0"], "Paintjob 1", false, false ) tabelPaintjob_row = guiGridListAddRow(modshop_gui["tabelPaintjob"]) guiGridListSetItemText(modshop_gui["tabelPaintjob"], tabelPaintjob_row, modshop_gui["tabelPaintjob_col0"], "Paintjob 2", false, false ) tabelPaintjob_row = guiGridListAddRow(modshop_gui["tabelPaintjob"]) guiGridListSetItemText(modshop_gui["tabelPaintjob"], tabelPaintjob_row, modshop_gui["tabelPaintjob_col0"], "Paintjob 3", false, false ) for i=1,player_perks[4].options.amount do tabelPaintjob_row = guiGridListAddRow(modshop_gui["tabelPaintjob"]) guiGridListSetItemText(modshop_gui["tabelPaintjob"], tabelPaintjob_row, modshop_gui["tabelPaintjob_col0"], "Custom " .. i, false, false ) end end end function HexToRGB(hex) -- input: "#XXX" or "#XXXXX" (string) hex = hex:sub(2,7) color = {} if (hex:len() == 3) then color.r = tonumber('0x' .. string.rep(hex:sub(1, 1),2)) color.g = tonumber('0x' .. string.rep(hex:sub(2, 2),2)) color.b = tonumber('0x' .. string.rep(hex:sub(3, 3),2)) elseif(hex:len() == 6) then color.r = tonumber('0x' .. hex:sub(1, 2)) color.g = tonumber('0x' .. hex:sub(3, 4)) color.b = tonumber('0x' .. hex:sub(5, 6)) end return color.r, color.g, color.b end -------------------- --- Upgrades --- -------------------- local selected_upgrade, selected_row function loadUpgradeList(vehID) guiGridListClear(modshop_gui["upgradeTable"]) selected_upgrade = nil guiSetEnabled(modshop_gui["addUpgradeButton"], false) guiSetEnabled(modshop_gui["delUpgradeButton"], false) if not vehID then return end compatibleUpgrades = getCompatibleUpgrades(vehID) guiGridListSetColumnWidth(modshop_gui["upgradeTable"],modshop_gui["upgradeTable_col0"], 0.60, true) guiGridListSetColumnWidth(modshop_gui["upgradeTable"],modshop_gui["upgradeTable_col1"], 0.25, true) for slot = 0,16 do local compatibleSlot = false for k, upgradeID in ipairs(compatibleUpgrades) do if getVehicleUpgradeSlotName ( slot ) == getVehicleUpgradeSlotName ( upgradeID ) then compatibleSlot = true break end end if compatibleSlot and slot ~= 8 and slot ~= 9 then local slotName = getVehicleUpgradeSlotName ( slot ) local i = guiGridListAddRow(modshop_gui["upgradeTable"]) local a = guiGridListSetItemText( modshop_gui["upgradeTable"], i, modshop_gui["upgradeTable_col0"], tostring(slotName), true, false ) for k, upgradeID in ipairs(compatibleUpgrades) do if (upgradeID~=1008 and upgradeID~=1009 and upgradeID~=1010 and upgradeID~=1087) and slotName == getVehicleUpgradeSlotName ( upgradeID ) then local i = guiGridListAddRow(modshop_gui["upgradeTable"]) local element = getElementByID( "upgrade_" .. upgradeID) if element then local upgrade_name = getElementData(element,"name",false) local added = false guiGridListSetItemText( modshop_gui["upgradeTable"], i, modshop_gui["upgradeTable_col0"], tostring(upgrade_name), false, false ) guiGridListSetItemText( modshop_gui["upgradeTable"], i, modshop_gui["upgradeTable_col1"], tostring(upgradeID), false, true ) if modshop_upgrades[tostring(vehID)] and tonumber(modshop_upgrades[tostring(vehID)]['slot' .. slot]) == upgradeID then guiGridListSetItemColor ( modshop_gui["upgradeTable"], i, modshop_gui["upgradeTable_col0"], 102, 205, 0 ) guiGridListSetItemColor ( modshop_gui["upgradeTable"], i, modshop_gui["upgradeTable_col1"], 102, 205, 0 ) added = true end if i == selected_row then guiGridListSetSelectedItem ( modshop_gui["upgradeTable"], i, modshop_gui["upgradeTable_col0"]) selected_upgrade = upgradeID if added then guiSetEnabled(modshop_gui["addUpgradeButton"], false) guiSetEnabled(modshop_gui["delUpgradeButton"], true) else guiSetEnabled(modshop_gui["addUpgradeButton"], true) guiSetEnabled(modshop_gui["delUpgradeButton"], false) end end end end end end end end function getCompatibleUpgrades ( vehicle ) local tempveh if type(vehicle) == 'number' and getVehicleNameFromModel(vehicle) ~= '' then tempveh = createVehicle(vehicle, 0,0,-50) local compUpgrades = getVehicleCompatibleUpgrades(tempveh) destroyElement(tempveh) tempveh = nil return compUpgrades or false end return false end function upgradeSelected(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") or not shop_GUI or source ~= modshop_gui["upgradeTable"] then return end local row, col = guiGridListGetSelectedItem(source) if tonumber(row) and tonumber(col) then selected_row = row selected_upgrade = tonumber(guiGridListGetItemText(source, row, modshop_gui["upgradeTable_col1"])) local r,g,b,a = guiGridListGetItemColor(source, row, modshop_gui["upgradeTable_col1"]) if selected_upgrade and r == 102 and g == 205 and b == 0 then guiSetEnabled(modshop_gui["addUpgradeButton"], false) guiSetEnabled(modshop_gui["delUpgradeButton"], true) guiSetEnabled(modshop_gui["addUpgradeForAllButton"], true) guiSetEnabled(modshop_gui["delUpgradeForAllButton"], true) elseif selected_upgrade then guiSetEnabled(modshop_gui["addUpgradeButton"], true) guiSetEnabled(modshop_gui["delUpgradeButton"], false) guiSetEnabled(modshop_gui["addUpgradeForAllButton"], true) guiSetEnabled(modshop_gui["delUpgradeForAllButton"], false) else guiSetEnabled(modshop_gui["addUpgradeButton"], false) guiSetEnabled(modshop_gui["delUpgradeButton"], false) guiSetEnabled(modshop_gui["addUpgradeForAllButton"], false) guiSetEnabled(modshop_gui["delUpgradeForAllButton"], false) selected_row = nil selected_upgrade = nil end end end function on_addUpgradeButton_clicked(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") then return end if getVehicleUpgradeSlotName(selected_upgrade) and getVehicleNameFromModel ( tonumber(current_vehicle) ) then triggerServerEvent ( 'gcsetmod', resourceRoot, localPlayer, 'gcsetmod', tostring(current_vehicle), 'upgrade', selected_upgrade) end end function on_delUpgradeButton_clicked(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") then return end if getVehicleUpgradeSlotName(selected_upgrade) and getVehicleNameFromModel ( tonumber(current_vehicle) ) then triggerServerEvent ( 'gcsetmod', resourceRoot, localPlayer, 'gcsetmod', tostring(current_vehicle), 'remupgrade', selected_upgrade) end end function on_addUpgradeForAllButton_clicked(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") then return end if getVehicleUpgradeSlotName(selected_upgrade) and getVehicleNameFromModel ( tonumber(current_vehicle) ) then triggerServerEvent ( 'gcsetmod', resourceRoot, localPlayer, 'gcsetmod', '*', 'upgrade', selected_upgrade) end end function on_delUpgradeForAllButton_clicked(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") then return end if getVehicleUpgradeSlotName(selected_upgrade) and getVehicleNameFromModel ( tonumber(current_vehicle) ) then triggerServerEvent ( 'gcsetmod', resourceRoot, localPlayer, 'gcsetmod', '*', 'remupgrade', selected_upgrade) end end addCommandHandler ( "getvehid", function () local veh = getPedOccupiedVehicle ( localPlayer ) if veh then local model = getElementModel(veh) outputChatBox('Vehicle: ' .. getVehicleNameFromModel(model) .. ' [' .. model .. ']', 255, 0 ,125) end end) ----------------------- --- Neon lights --- ----------------------- function installNeon ( data_neons ) neons = data_neons for k,v in pairs(neons) do local dff = engineLoadDFF( v[1], v[2]) engineReplaceModel(dff, v[2]) end end addEvent('installNeon', true) addEventHandler('installNeon', localPlayer, installNeon) function loadNeon ( model ) local data = getModelNeonData ( tonumber(model) ) local enable = (not not model) and (not not data) guiSetEnabled(modshop_gui["btnNeonGreen"], enable) guiSetEnabled(modshop_gui["btnNeonOrange"], enable) guiSetEnabled(modshop_gui["btnNeonRed"], enable) guiSetEnabled(modshop_gui["btnNeonYellow"], enable) guiSetEnabled(modshop_gui["btnNeonAqua"], enable) guiSetEnabled(modshop_gui["btnNeonRemove"], false) local vehID = tostring ( model ) local color = modshop_upgrades and modshop_upgrades[vehID] and type(modshop_upgrades[vehID].slot26) == 'string' and modshop_upgrades[vehID].slot26:gsub("^%l", string.upper) if color and modshop_gui["btnNeon" .. color] then guiSetEnabled(modshop_gui["btnNeon" .. color], false) guiSetEnabled(modshop_gui["btnNeonRemove"], true) end end function applyNeon ( color ) triggerServerEvent ( 'gcsetmod', resourceRoot, localPlayer, 'gcsetmod', tostring(current_vehicle), 'neon', color) end function getModelNeonData ( id ) for k,v in ipairs( getElementsByType('modshop_vehicle', getElementByID("modshop_vehicles")) ) do if tonumber(getElementData(v, "vehicle_id", false)) == id then local data = false local neon_data = getElementData(v, "neon_data", false) if neon_data and type(neon_data) == "string" and #neon_data > 0 then neon_data = split(neon_data, ",") for i = 1,#neon_data do neon_data[i] = tonumber(neon_data[i]) end if #neon_data == 9 then data = neon_data end end return data end end return false end function on_btnNeonGreen_clicked(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") then return end applyNeon ( "green" ) end function on_btnNeonOrange_clicked(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") then return end applyNeon ( "orange" ) end function on_btnNeonRed_clicked(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") then return end applyNeon ( "red" ) end function on_btnNeonYellow_clicked(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") then return end applyNeon ( "yellow" ) end function on_btnNeonAqua_clicked(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") then return end applyNeon ( "aqua" ) end function on_btnNeonRemove_clicked(button, state, absoluteX, absoluteY) if (button ~= "left") or (state ~= "up") then return end applyNeon () end function var_dump(...) -- default options local verbose = false local firstLevel = true local outputDirectly = true local noNames = false local indentation = "\t\t\t\t\t\t" local depth = nil local name = nil local output = {} for k,v in ipairs(arg) do -- check for modifiers if type(v) == "string" and k < #arg and v:sub(1,1) == "-" then local modifiers = v:sub(2) if modifiers:find("v") ~= nil then verbose = true end if modifiers:find("s") ~= nil then outputDirectly = false end if modifiers:find("n") ~= nil then verbose = false end if modifiers:find("u") ~= nil then noNames = true end local s,e = modifiers:find("d%d+") if s ~= nil then depth = tonumber(string.sub(modifiers,s+1,e)) end -- set name if appropriate elseif type(v) == "string" and k < #arg and name == nil and not noNames then name = v else if name ~= nil then name = ""..name..": " else name = "" end local o = "" if type(v) == "string" then table.insert(output,name..type(v).."("..v:len()..") \""..v.."\"") elseif type(v) == "userdata" then local elementType = "no valid MTA element" if isElement(v) then elementType = getElementType(v) end table.insert(output,name..type(v).."("..elementType..") \""..tostring(v).."\"") elseif type(v) == "table" then local count = 0 for key,value in pairs(v) do count = count + 1 end table.insert(output,name..type(v).."("..count..") \""..tostring(v).."\"") if verbose and count > 0 and (depth == nil or depth > 0) then table.insert(output,"\t{") for key,value in pairs(v) do -- calls itself, so be careful when you change anything local newModifiers = "-s" if depth == nil then newModifiers = "-sv" elseif depth > 1 then local newDepth = depth - 1 newModifiers = "-svd"..newDepth end local keyString, keyTable = var_dump(newModifiers,key) local valueString, valueTable = var_dump(newModifiers,value) if #keyTable == 1 and #valueTable == 1 then table.insert(output,indentation.."["..keyString.."]\t=>\t"..valueString) elseif #keyTable == 1 then table.insert(output,indentation.."["..keyString.."]\t=>") for k,v in ipairs(valueTable) do table.insert(output,indentation..v) end elseif #valueTable == 1 then for k,v in ipairs(keyTable) do if k == 1 then table.insert(output,indentation.."["..v) elseif k == #keyTable then table.insert(output,indentation..v.."]") else table.insert(output,indentation..v) end end table.insert(output,indentation.."\t=>\t"..valueString) else for k,v in ipairs(keyTable) do if k == 1 then table.insert(output,indentation.."["..v) elseif k == #keyTable then table.insert(output,indentation..v.."]") else table.insert(output,indentation..v) end end for k,v in ipairs(valueTable) do if k == 1 then table.insert(output,indentation.." => "..v) else table.insert(output,indentation..v) end end end end table.insert(output,"\t}") end else table.insert(output,name..type(v).." \""..tostring(v).."\"") end name = nil end end local string = "" for k,v in ipairs(output) do if outputDirectly then outputConsole(v) end string = string..v end return string, output end function rgbaToHex(r, g, b, a) if not r then r, g, b, a = 255, 255, 255, 0 end return string.format("%02X%02X%02X%02X", a, r, g, b) end
local dap = require 'dap' dap.adapters.chrome = { type = 'executable', command = 'node', args = { os.getenv 'HOME' .. '.config/nvim/vscode-chrome-debug/out/src/chromeDebug.js' }, } dap.configurations.javascript = { -- change this to javascript if needed { type = 'chrome', request = 'attach', program = '${file}', cwd = vim.fn.getcwd(), sourceMaps = true, protocol = 'inspector', port = 9222, webRoot = '${workspaceFolder}', }, } dap.configurations.typescript = { -- change to typescript if needed { type = 'chrome', request = 'attach', program = '${file}', cwd = vim.fn.getcwd(), sourceMaps = true, protocol = 'inspector', port = 9222, webRoot = '${workspaceFolder}', }, }
-- -- Copyright 2021 Andreas MATTHIAS -- -- This work may be distributed and/or modified under the -- conditions of the LaTeX Project Public License, either version 1.3c -- of this license or (at your option) any later version. -- The latest version of this license is in -- http://www.latex-project.org/lppl.txt -- and version 1.3c or later is part of all distributions of LaTeX -- version 2008 or later. -- -- This work has the LPPL maintenance status `maintained'. -- -- The Current Maintainer of this work is Andreas MATTHIAS. -- local loader = require('luapackageloader') loader.add_lua_searchers() local bh = require('busted-helper') bh.remove_unknown_args() require('busted.runner')({output = 'utfTerminal'}) require('my_assertions') assert:set_parameter('TableFormatLevel', -1) print() luatex = require('flare-luatex') flare = require('flare') Doc = flare.Doc Page = flare.Page pkg = require('flare-pkg') pp = pkg.pp stringio = require('pl.stringio') nt = require('nodetree') describe('Testing flare-page.lua:', function() test('Page:new()', function() local d = Doc:new() local p = Page:new(d) assert.equal(d, p.doc) assert.same({}, p.GinKV) assert.same({}, p.FlareKV) assert.same(1, d.pictureCounter) assert.same({a=1, b=0, c=0, d=1, e=0, f=0}, p.ctm) local p = Page:new(d) assert.same(2, d.pictureCounter) end) test('Page:openFile()', function() local p = Page:new(Doc:new()) local func = function() p:openFile() end -- Do not user p:setGinKV() here, because `filename` is -- set only once. p.GinKV.filename = 'example-image.pdf' -- image from mwe.sty assert.has_no.errors(func) p.GinKV.filename = 'thisFileDoesNotExist.pdf' assert.has_error( func, "\nModule Flare Error: File 'thisFileDoesNotExist.pdf' " .. "not found on input line 5\n") p.GinKV.filename = 'pdf/encrypted.pdf' assert.has_error( func, '\nModule Flare Error: PDF is password ' .. 'protected on input line 5\n') p.userpassword = 'foobar' assert.has_no.error(func) end) test('Page:findFile()', function() local p = Page:new(Doc:new()) p.GinKV.filename = 'example-image.pdf' -- from mwe.sty local filename = p:findFile() assert.is_not_nil( filename:find('tex/latex/mwe/example%-image.pdf$')) p.GinKV.filename = 'thisFileDoesNotExist.pdf' assert.has_error(function() p:findFile() end) end) test('Page:applyCTM()', function() local p = Page:new(Doc:new()) local ctm = { a = 1, b = 2, c = 3, d = 4, e = 5, f = 6 } local xn, yn = p:applyCTM(ctm, 1, 2) assert.same(12, xn) assert.same(16, yn) end) test('Page:rect2tab()', function() local p = Page:new(Doc:new()) assert.same( p:rect2tab({100, 200, 300, 400}), {llx = 100, lly = 200, urx = 300, ury = 400}) local pdf = pdfe.open('pdf/circle-01.pdf') local annot = pdfe.getpage(pdf, 1).Annots[1] assert.same( p:rect2tab(annot.Rect), {llx = 100, lly = 600, urx = 300, ury = 700}) end) test('Page:getMediaBox()', function() local p = Page:new(Doc:new()) p.GinKV.filename = 'pdf/circle-01.pdf' p.GinKV.page = 1 p:openFile() local mb = p:getMediaBox() assert.near(0, mb.llx, 0.001) assert.near(0, mb.lly, 0.001) assert.near(595.276, mb.urx, 0.001) assert.near(841.89, mb.ury, 0.001) end) test('Page:trim()', function() local p = Page:new(Doc:new()) assert.same(nil, p:trim()) assert.same(1, p:trim(1)) assert.same({}, p:trim({})) assert.same('', p:trim('')) assert.same('foo', p:trim('foo')) assert.same('foo', p:trim(' foo ')) assert.same('foo', p:trim(' foo ')) assert.same('foo bar', p:trim(' foo bar ')) assert.same('foo bar', p:trim(' foo bar ')) end) test('Page:sp2bp()', function() local p = Page:new(Doc:new()) assert.near(p:sp2bp(100000), 1.520178, 0.000001) end) test('Page:bp2sp()', function() local p = Page:new(Doc:new()) assert.near(p:bp2sp(1), 65781.76, 0.0000001) end) test('Page:cacheData()', function() local d = Doc:new() local p = Page:new(d) p:setGinKV('filename', 'pdf/link-02.pdf') p:setGinKV('page', 1) p:openFile() p:cacheData() end) test('Page:writeToCache()', function() local d = Doc:new() local p = Page:new(d) d.pictureCounter = 3 p:writeToCache('foo', 123) assert.same(123, d.cacheNew[3]['foo']) assert.True(d.dirtyCache) d.dirtyCache = false d.cacheOld = d.cacheNew p:writeToCache('foo', 123) assert.same(123, d.cacheNew[3]['foo']) assert.False(d.dirtyCache) end) test('Page:readFromCache()', function() local d = Doc:new() local p = Page:new(d) d.pictureCounter = 3 d.cacheOld[3] = {} d.cacheOld[3]['foo'] = 123 assert.same(123, p:readFromCache('foo')) assert.same(nil, p:readFromCache('bar')) d.pictureCounter = 4 assert.same(nil, p:readFromCache('foo')) end) test('Page:readFromCacheWithPageObj()', function() local d = Doc:new() local p = Page:new(d) d.cacheOld[1] = {} d.cacheOld[2] = {} d.cacheOld[3] = {} d.cacheOld[3]['page_obj_old'] = 55 d.cacheOld[3]['foo'] = 123 assert.same(123, p:readFromCacheWithPageObj('foo', 55)) assert.same(nil, p:readFromCacheWithPageObj('foo', 33)) end) test('Page:writeToCache_AnnotObjOld()', function() local d = Doc:new() local p = Page:new(d) d.pictureCounter = 2 p.annotId = 3 p:writeToCache_AnnotObjOld(33) assert.same(33, d.cacheNew[2]['annots'][3]['annot_obj_old']) d.cacheOld = d.cacheNew p:writeToCache_AnnotObjOld(33) assert.False(d.dirtyCache) end) test('Page:writeToCache_AnnotObjNew()', function() local d = Doc:new() local p = Page:new(d) d.pictureCounter = 2 p.annotId = 3 p:writeToCache_AnnotObjNew(33) assert.same(33, d.cacheNew[2]['annots'][3]['annot_obj_new']) d.cacheOld = d.cacheNew p:writeToCache_AnnotObjNew(33) assert.True(d.dirtyCache) end) test('Page:findFromCache_AnnotObjNew()', function() local d = Doc:new() local p = Page:new(d) d.pictureCounter = 1 p.annotId = 1 p:writeToCache_AnnotObjOld(11) p:writeToCache_AnnotObjNew(22) p.annotId = 2 p:writeToCache_AnnotObjOld(33) p:writeToCache_AnnotObjNew(44) d.cacheOld = d.cacheNew assert.same(22, p:findFromCache_AnnotObjNew(11)) assert.same(44, p:findFromCache_AnnotObjNew(33)) end) test('Page:makeCTM()', function() local d = Doc:new() local p = Page:new(d) assert.same( {a=1, b=2, c=3, d=4, e=5, f=6}, p:makeCTM(1, 2, 3, 4, 5, 6)) end) test('Page:getCTM()', function() local d = Doc:new() local p = Page:new(d) assert.same({a=1, b=0, c=0, d=1, e=0, f=0}, p:getCTM()) p:setGinKV('scale', 5) assert.same({a=5, b=0, c=0, d=5, e=0, f=0}, p:getCTM()) end) end) -- describe
object_tangible_collection_dwartii_statue_braata = object_tangible_collection_shared_dwartii_statue_braata:new { gameObjectType = 8211,} ObjectTemplates:addTemplate(object_tangible_collection_dwartii_statue_braata, "object/tangible/collection/dwartii_statue_braata.iff")
local include = require 'include' local LuaXml = require 'LuaXml' local util = require 'util' local datapath = 'powerplant/' local filename = datapath..'manifest.xml' local file = xml.load(filename) local data = file:find('model') local model = {} if data ~= nil then for i = 1, #data do model[data[i]:tag()] = data[i] end end function showInfo(tbl) if tbl then for k, v in ipairs(tbl) do if type(v) == 'table' then showInfo(v) else print(v) end end end end showInfo(model.name) showInfo(model.version) showInfo(model.license) showInfo(model.description) showInfo(model.author) if model.sdf then for i = 1, #model.sdf do print('sdf - '..model.sdf[i]) end end --if model.depend then -- for i = 1, #model.depend do -- print(model.depend[i]) -- end --end
--!strict -- StreamableUtil -- Stephen Leitnick -- March 03, 2021 --[[ StreamableUtil.Compound(observers: {Observer}, handler: ({[child: string]: Instance}, janitor: Janitor) -> void): Janitor Example: local streamable1 = Streamable.new(someModel, "SomeChild") local streamable2 = Streamable.new(anotherModel, "AnotherChild") StreamableUtil.Compound({S1 = streamable1, S2 = streamable2}, function(streamables, janitor) local someChild = streamables.S1.Instance local anotherChild = streamables.S2.Instance janitor:Add(function() -- Cleanup end) end) --]] local Janitor = require(script.Parent.Janitor) local _Streamable = require(script.Parent.Streamable) type Streamables = {_Streamable.Streamable} type CompoundHandler = (Streamables, any) -> nil local StreamableUtil = {} function StreamableUtil.Compound(streamables: Streamables, handler: CompoundHandler) local compoundJanitor = Janitor.new() local observeAllJanitor = Janitor.new() local allAvailable = false local function Check() if allAvailable then return end for _,streamable in pairs(streamables) do if not streamable.Instance then return end end allAvailable = true handler(streamables, observeAllJanitor) end local function Cleanup() if not allAvailable then return end allAvailable = false observeAllJanitor:Cleanup() end for _,streamable in pairs(streamables) do compoundJanitor:Add(streamable:Observe(function(_child, janitor) Check() janitor:Add(Cleanup) end)) end compoundJanitor:Add(Cleanup) return compoundJanitor end return StreamableUtil
resource_manifest_version '44febabe-d386-4d18-afbe-5e627f4af937' resource_version '1.0' name 'B2K MLO Dev Tool' description 'B2KRP MLO Dev Tool' client_script 'MLODevTool.net.dll'
return {'bik','biker','bikhamer','bikini','bikinietjes','bikinislip','bikkel','bikkelen','bikkelhard','bikkelspel','bikken','biksteen','bikker','bikinilijn','bikkelbal','bikschote','biko','bikker','bik','bikhamers','bikinis','bikinietje','bikkelde','bikkelden','bikkelharde','bikkels','bikkelt','bikkeltje','bikkeltjes','bikt','bikte','bikten','bikers','bikkers','bikos'}
-- Original work by Astromech -- Rewritten based on Auras by Azilroka local _, ns = ... local oUF = ns.oUF local VISIBLE = 1 local HIDDEN = 0 local tinsert = tinsert local wipe = wipe local UnitAura = UnitAura local UnitIsUnit = UnitIsUnit local GetSpellTexture = GetSpellTexture local function createAuraIcon(element, index) local button = CreateFrame("Button", element:GetDebugName() .. "Button" .. index, element) button:EnableMouse(false) button:Hide() local cd = CreateFrame("Cooldown", "$parentCooldown", button, "CooldownFrameTemplate") cd:SetAllPoints() cd:SetReverse(true) cd:SetDrawBling(false) cd:SetDrawEdge(false) local icon = button:CreateTexture(nil, "ARTWORK") icon:SetAllPoints() local countFrame = CreateFrame("Frame", nil, button) countFrame:SetAllPoints(button) countFrame:SetFrameLevel(cd:GetFrameLevel() + 1) local count = countFrame:CreateFontString(nil, "OVERLAY", "NumberFontNormal") count:SetPoint("BOTTOMRIGHT", countFrame, "BOTTOMRIGHT", -1, 0) local overlay = button:CreateTexture(nil, "OVERLAY") overlay:SetTexture([[Interface\Buttons\UI-Debuff-Overlays]]) overlay:SetAllPoints() overlay:SetTexCoord(.296875, .5703125, 0, .515625) button.overlay = overlay button.icon = icon button.count = count button.cd = cd if(element.PostCreateIcon) then element:PostCreateIcon(button) end return button end local function customFilter(element, _, button, name, _, _, debuffType, _, _, caster, isStealable, _, spellID, canApply, isBossDebuff, casterIsPlayer) local setting = element.watched[spellID] if not setting then return false end button.onlyShowMissing = setting.onlyShowMissing button.anyUnit = setting.anyUnit if setting.enabled then if setting.onlyShowMissing and not setting.anyUnit and caster == "player" then return false elseif setting.onlyShowMissing and setting.anyUnit and casterIsPlayer then return true elseif not setting.onlyShowMissing and setting.anyUnit and casterIsPlayer then return true elseif not setting.onlyShowMissing and not setting.anyUnit and caster == "player" then return true end end return false end local function updateIcon(element, unit, index, offset, filter, isDebuff, visible) local name, texture, count, debuffType, duration, expiration, caster, isStealable, nameplateShowSelf, spellID, canApply, isBossDebuff, casterIsPlayer, nameplateShowAll, timeMod, effect1, effect2, effect3 = UnitAura(unit, index, filter) if(name) then local position = visible + offset + 1 local button = element[position] if(not button) then button = (element.CreateIcon or createAuraIcon) (element, position) tinsert(element, button) element.createdIcons = element.createdIcons + 1 end button.caster = caster button.filter = filter button.isDebuff = isDebuff button.debuffType = debuffType button.isPlayer = caster == "player" button.spellID = spellID local show = (element.CustomFilter or customFilter) (element, unit, button, name, texture, count, debuffType, duration, expiration, caster, isStealable, nameplateShowSelf, spellID, canApply, isBossDebuff, casterIsPlayer, nameplateShowAll, timeMod, effect1, effect2, effect3) if(show) then local setting = element.watched[spellID] if(button.cd) then if(duration and duration > 0) then button.cd:SetCooldown(expiration - duration, duration) button.cd:Show() else button.cd:Hide() end end if(button.overlay) then if((isDebuff and element.showDebuffType) or (not isDebuff and element.showBuffType) or element.showType) then local color = element.__owner.colors.debuff[debuffType] or element.__owner.colors.debuff.none button.overlay:SetVertexColor(color[1], color[2], color[3]) button.overlay:Show() else button.overlay:Hide() end end if(button.stealable) then if(not isDebuff and isStealable and element.showStealableBuffs and not UnitIsUnit("player", unit)) then button.stealable:Show() else button.stealable:Hide() end end if(button.icon) then button.icon:SetTexture(texture) end if(button.count) then button.count:SetText(count > 1 and count) end if setting.sizeOffset == 0 then button:SetSize(element.size, element.size) else button:SetSize(setting.sizeOffset + element.size, setting.sizeOffset + element.size) end button:SetID(index) button:Show() button:ClearAllPoints() button:SetPoint(setting.point, setting.xOffset, setting.yOffset) if(element.PostUpdateIcon) then element:PostUpdateIcon(unit, button, index, position, duration, expiration, debuffType, isStealable) end return VISIBLE else button.isFiltered = true return HIDDEN end end end local missing = {} local function onlyShowMissingIcon(element, unit, offset) wipe(missing) for SpellID, setting in pairs(element.watched) do if setting.onlyShowMissing then missing[SpellID] = setting end end for i = 1, #element do local button = element[i] if button.isFiltered and missing[button.spellID] then missing[button.spellID] = nil end end local visible = 0 for SpellID, setting in pairs(missing) do local position = visible + offset + 1 local button = element[position] if(not button) then button = (element.CreateIcon or createAuraIcon) (element, position) table.insert(element, button) element.createdIcons = element.createdIcons + 1 end if(button.cd) then button.cd:Hide() end if(button.icon) then button.icon:SetTexture(GetSpellTexture(SpellID)) end if(button.overlay) then button.overlay:Hide() end if setting.sizeOffset == 0 then button:SetSize(element.size, element.size) else button:SetSize(setting.sizeOffset + element.size, setting.sizeOffset + element.size) end button:SetID(position) button.spellID = SpellID button:Show() button:ClearAllPoints() button:SetPoint(setting.point, setting.xOffset, setting.yOffset) if(element.PostUpdateIcon) then element:PostUpdateIcon(unit, button, nil, position) end visible = visible + 1 end return visible end local function filterIcons(element, unit, filter, limit, isDebuff, offset, dontHide) if (not offset) then offset = 0 end local index, visible, hidden = 1, 0, 0 while (visible < limit) do local result = updateIcon(element, unit, index, offset, filter, isDebuff, visible) if (not result) then break elseif (result == VISIBLE) then visible = visible + 1 elseif (result == HIDDEN) then hidden = hidden + 1 end index = index + 1 end if (not dontHide) then for i = visible + offset + 1, #element do element[i]:Hide() end end return visible, hidden end local function UpdateAuras(self, event, unit) if(self.unit ~= unit) then return end local element = self.AuraWatch if(element) then if(element.PreUpdate) then element:PreUpdate(unit) end local numBuffs = element.numBuffs or 32 local numDebuffs = element.numDebuffs or 16 local max = element.numTotal or numBuffs + numDebuffs for i = 1, #element do element[i].isFiltered = false end local visibleBuffs, hiddenBuffs = filterIcons(element, unit, element.buffFilter or element.filter or "HELPFUL", math.min(numBuffs, max), nil, 0, true) local visibleDebuffs, hiddenDebuffs = filterIcons(element, unit, element.buffFilter or element.filter or "HARMFUL", math.min(numDebuffs, max - visibleBuffs), true, visibleBuffs) element.visibleDebuffs = visibleDebuffs element.visibleBuffs = visibleBuffs element.visibleAuras = visibleBuffs + visibleDebuffs element.allAuras = visibleBuffs + visibleDebuffs + hiddenBuffs + hiddenDebuffs onlyShowMissingIcon(element, unit, element.visibleAuras) if(element.PostUpdate) then element:PostUpdate(unit) end end end local function Update(self, event, unit) if(self.unit ~= unit) then return end UpdateAuras(self, event, unit) end local function ForceUpdate(element) return Update(element.__owner, "ForceUpdate", element.__owner.unit) end local function SetNewTable(element, table) element.watched = table or {} end local function Enable(self) local element = self.AuraWatch if(element) then element.__owner = self element.SetNewTable = SetNewTable element.ForceUpdate = ForceUpdate element.watched = element.watched or {} element.createdIcons = element.createdIcons or 0 element.anchoredIcons = 0 element.size = 8 self:RegisterEvent("UNIT_AURA", UpdateAuras) element:Show() return true end end local function Disable(self) if(self.AuraWatch) then self:UnregisterEvent("UNIT_AURA", UpdateAuras) if(self.AuraWatch) then self.AuraWatch:Hide() end end end oUF:AddElement("AuraWatch", Update, Enable, Disable)
ignite_poet = { cast = function(player, target) local spellName = "Ignite" if not player:canCast(1, 1, 0) then return end local damage = 40 + math.floor(player.level / 2) + math.floor((player.will + 3) / 4) local worked = global_zap.cast(player, target, damage, 30, 0) if worked ~= 0 then player:sendMinitext("You cast " .. spellName .. ".") end if worked == 2 then target:sendMinitext(player.name .. " cast " .. spellName .. " on you.") end end, requirements = function(player) local level = 22 local items = {Item("acorn").id, Item("rabbit_meat").id} local itemAmounts = {20, 10} local description = "A moderate elemental attack." return level, items, itemAmounts, description end } spirit_strike_poet = { cast = function(player, target) local spellName = "Spirit Strike" if not player:canCast(1, 1, 0) then return end local damage = 40 + math.floor(player.level / 2) + math.floor((player.will + 3) / 4) local worked = global_zap.cast(player, target, damage, 30, 1) if worked ~= 0 then player:sendMinitext("You cast " .. spellName .. ".") end if worked == 2 then target:sendMinitext(player.name .. " cast " .. spellName .. " on you.") end end, requirements = function(player) local level = 22 local items = {Item("acorn").id, Item("rabbit_meat").id} local itemAmounts = {20, 10} local description = "A moderate elemental attack." return level, items, itemAmounts, description end } wrath_of_nature_poet = { cast = function(player, target) local spellName = "Wrath of Nature" if not player:canCast(1, 1, 0) then return end local damage = 40 + math.floor(player.level / 2) + math.floor((player.will + 3) / 4) local worked = global_zap.cast(player, target, damage, 30, 2) if worked ~= 0 then player:sendMinitext("You cast " .. spellName .. ".") end if worked == 2 then target:sendMinitext(player.name .. " cast " .. spellName .. " on you.") end end, requirements = function(player) local level = 22 local items = {Item("acorn").id, Item("rabbit_meat").id} local itemAmounts = {20, 10} local description = "A moderate elemental attack." return level, items, itemAmounts, description end } thunderclap_poet = { cast = function(player, target) local spellName = "Thunderclap" if not player:canCast(1, 1, 0) then return end local damage = 40 + math.floor(player.level / 2) + math.floor((player.will + 3) / 4) local worked = global_zap.cast(player, target, damage, 30, 3) if worked ~= 0 then player:sendMinitext("You cast " .. spellName .. ".") end if worked == 2 then target:sendMinitext(player.name .. " cast " .. spellName .. " on you.") end end, requirements = function(player) local level = 22 local items = {Item("acorn").id, Item("rabbit_meat").id} local itemAmounts = {20, 10} local description = "A moderate elemental attack." return level, items, itemAmounts, description end }
MoveState = { mName = "move" } MoveState.__index = MoveState function MoveState:Create(character, map) local this = { mCharacter = character, mMap = map, mTileWidth = map.mTileWidth, mEntity = character.mEntity, mController = character.mController, mMoveX = 0, mMoveY = 0, mTween = Tween:Create(0, 0, 1), mMoveSpeed = 0.3, } this.mAnim = Animation:Create({ this.mEntity.mStartFrame }) setmetatable(this, self) return this end function MoveState:Enter(data) local frames = nil if data.x == 1 then frames = self.mCharacter.mAnims.right self.mCharacter.mFacing = "right" elseif data.x == -1 then frames = self.mCharacter.mAnims.left self.mCharacter.mFacing = "left" elseif data.y == -1 then frames = self.mCharacter.mAnims.up self.mCharacter.mFacing = "up" elseif data.y == 1 then frames = self.mCharacter.mAnims.down self.mCharacter.mFacing = "down" end self.mAnim:SetFrames(frames) self.mMoveX = data.x self.mMoveY = data.y local pixelPos = self.mEntity.mSprite:GetPosition() self.mPixelX = pixelPos:X() self.mPixelY = pixelPos:Y() self.mTween = Tween:Create(0, self.mTileWidth, self.mMoveSpeed) local targetX = self.mEntity.mTileX + data.x local targetY = self.mEntity.mTileY + data.y if self.mMap:IsBlocked(1, targetX, targetY) then self.mMoveX = 0 self.mMoveY = 0 self.mEntity:SetFrame(self.mAnim:Frame()) self.mController:Change(self.mCharacter.mDefaultState) return end if self.mMoveX ~= 0 or self.mMoveY ~= 0 then local x = self.mEntity.mTileX local y = self.mEntity.mTileY local layer = self.mEntity.mLayer local trigger = self.mMap:GetTrigger(x,y, layer) if trigger then trigger:OnExit(self.mEntity, x, y, layer) else self.mMap:TryEncounter(x, y, layer) end end self.mEntity:SetTilePos(self.mEntity.mTileX + self.mMoveX, self.mEntity.mTileY + self.mMoveY, self.mEntity.mLayer, self.mMap) self.mEntity.mSprite:SetPosition(pixelPos) end function MoveState:Exit() local x = self.mEntity.mTileX local y = self.mEntity.mTileY local layer = self.mEntity.mLayer local trigger = self.mMap:GetTrigger(x, y, layer) if trigger then trigger:OnEnter(self.mEntity, x, y, layer) end end function MoveState:Render(renderer) end function MoveState:Update(dt) self.mAnim:Update(dt) self.mEntity:SetFrame(self.mAnim:Frame()) self.mTween:Update(dt) local value = self.mTween:Value() local x = self.mPixelX + (value * self.mMoveX) local y = self.mPixelY - (value * self.mMoveY) self.mEntity.mX = math.floor(x) self.mEntity.mY = math.floor(y) self.mEntity.mSprite:SetPosition(self.mEntity.mX , self.mEntity.mY) if self.mTween:IsFinished() then self.mController:Change(self.mCharacter.mDefaultState) end end
AddEvent("OnPlayerSpawn", function() webui = CreateWebUI(0, 0, 0, 0, 0, 60) SetWebURL(webui, "http://asset/projectr/UI/html/index.html") SetWebAlignment(webui, 0.0, 0.0) SetWebAnchors(webui, 0.0, 0.0, 1.0, 1.0) SetWebVisibility(webui, WEB_VISIBLE) SetPlayerClothingPreset(GetPlayerId(), 7) end)
--[[ ___ ___ ( ) ( ) ___ .-. .-. ___ ___ | |_ .---. ___ .-. | |_ ( ) ' ( )( ( __) / .-, ( ) ( __) | .-. .-. | | | | | | (__) ; || .-. .| | | | | | | | | | | | | ___ .'` || | | || | ___ | | | | | | | | | | |( / .'| || | | || |( ) | | | | | | | | | | | | | / | || | | || | | | | | | | | | | ; ' | ' | ; | ; || | | || ' | | | | | | | ' `-' / ' `-' ' `-' || | | |' `-' ; (___)(___)(___'.__.' `.__.`.__.'_(___)(___)`.__. ---- Recommended settings: ---- * one hedgehog per team (forced by game) ---- * one team per clan ---- * 'Small' one-island map --]] HedgewarsScriptLoad("/Scripts/Locale.lua") HedgewarsScriptLoad("/Scripts/Tracker.lua") HedgewarsScriptLoad("/Scripts/Params.lua") --[[ MUTANT SCRIPT ]] local hhs = {} local crates = {} local numhhs = 0 local meh = false local gameOver=false local mutant = nil local mutant_base_health = 200 local mutant_base_disease = 25 local disease_timer = 2000 local kill_reward = nil local mt_hurt=false local killsCounter = 0 local team_fire_punishment = 3 local mutant_kill_reward = 2 local hh_weapons = { amBazooka, amGrenade, amShotgun, amMine} local mt_weapons = {amWatermelon, amHellishBomb, amBallgun, amRCPlane, amTeleport} local disease=0 local timer=0 local winScore = 15 local hogsLimit = 1 local teamsDead = {} local teamsDeleted = {} local hogLimitHit = false local teamLimitHit = false local cnthhs local circles = {} local circleFrame = -1 -- Variables for custom achievements -- Most kills in 1 turn local recordKills = 0 local recordKillsHogName = nil local recordKillsTeamName = nil -- Most suicides local recordSuicides = 0 local recordSuicidesHogName = nil local recordSuicidesTeamName = nil -- Most skips local recordSkips = 0 local recordSkipsHogName = nil local recordSkipsTeamName = nil -- Most crates collected local recordCrates = 0 local recordCratesHogName = nil local recordCratesTeamName = nil -- Most deaths local recordDeaths = 0 local recordDeathsHogName = nil local recordDeathsTeamName = nil -- Total killed hedgehogs local totalKills = 0 -- Total damage local totalDamage = 0 local mutantHat = "WhySoSerious" local feederHat = "poke_slowpoke" function rules() local mineStr if MinesTime < 0 then mineStr = loc("Mines time: 0s-5s") else mineStr = string.format(loc("Mines explode after %d s."), div(MinesTime, 1000)) end local ruleSet = loc("Hedgehogs will be revived after their death.") .. "|" .. mineStr .. "|" .. loc("The first hedgehog to kill someone becomes the Mutant.") .. "|" .. loc("The Mutant has super weapons and a lot of health.") .. "|" .. loc("The Mutant loses health quickly, but gains health by killing.") .. "|" .. " |" .. loc("Score points by killing other hedgehogs.") .. "|" .. loc("The hedgehog with least points (or most deaths) becomes the Bottom Feeder.") .. "|" .. loc("The score and deaths are shown next to the team bar.") .. "|" .. string.format(loc("Goal: Score %d points or more to win!"), winScore) .. "|" .. " |" .. loc("Scoring: ") .. "|" .. loc("+2 for becoming the Mutant") .. "|" .. loc("+1 to the Mutant for killing anyone") .. "|" .. loc("+1 to the Bottom Feeder for killing anyone") .. "|" .. loc("-1 to anyone for a suicide") return ruleSet end function showStartingInfo() ShowMission(loc("Mutant"), loc("A Hedgewars tag game"), rules(), -amWatermelon, 5000) end function onGameInit() -- Sudden Death would be weird WaterRise = 0 HealthDecrease = 0 -- Weapons must be reset for the Mutant mechanic to work EnableGameFlags(gfResetWeps) -- King Mode messes with game too much DisableGameFlags(gfKing) end function limitHogsTeam(gear) cnthhs = cnthhs + 1 if cnthhs > 1 then hogLimitHit = true SetEffect(gear, heResurrectable, 0) setGearValue(gear, "excess", true) DeleteGear(gear) end end function limitHogsClan(gear) teamLimitHit = true SetEffect(gear, heResurrectable, 0) setGearValue(gear, "excess", true) DeleteGear(gear) end function onGameStart() if ClansCount >= 2 then SendHealthStatsOff() SendAchievementsStatsOff() end SendRankingStatsOff() trackTeams() teamScan() runOnHogs(saveStuff) -- Enforce team and hog limits hogLimitHit = false -- Rule 1: One team per clan if TeamsCount > ClansCount then local usedClans = {} for i=0, TeamsCount - 1 do local teamName = GetTeamName(i) local clanNumber = GetTeamClan(teamName) if not usedClans[clanNumber] then usedClans[clanNumber] = true else runOnHogsInTeam(limitHogsClan, teamName) teamsDeleted[teamName] = true setTeamValue(teamName, "Score", getTeamValue(teamName, "Score") -99999) end end end -- Rule 2: One hog per team for i=0 , TeamsCount - 1 do cnthhs = 0 runOnHogsInTeam(limitHogsTeam, GetTeamName(i)) end if teamLimitHit then WriteLnToChat(loc("Only one team per clan allowed! Excess teams will be removed.")) end if hogLimitHit then WriteLnToChat(loc("Only one hog per team allowed! Excess hogs will be removed.")) end trackTeams() showStartingInfo() end function giveWeapons(gear) if gear == mutant then AddAmmo(gear, amRope) for i=1, #mt_weapons do AddAmmo(gear, mt_weapons[i]) end else for i=1, #hh_weapons do AddAmmo(gear,hh_weapons[i]) end end end function onAmmoStoreInit() SetAmmo(amSkip, 9, 0, 0, 0) SetAmmo(amRope,0,1,0,5) SetAmmo(amSnowball,0,1,0,1) for i=1, #hh_weapons do SetAmmo(hh_weapons[i], 0, 0, 0, 1) end for i=1, #mt_weapons do SetAmmo(mt_weapons[i], 0, 3, 0, 1) end end function drawCircles() for i = 0, #hhs do if circles[hhs[i]] ~= nil then DeleteVisualGear(circles[hhs[i]]) circles[hhs[i]] = nil end if hhs[i] ~= CurrentHedgehog then if mutant == nil then circles[hhs[i]] = AddVisualGear(0, 0, vgtCircle, 0, false) SetVisualGearValues(circles[hhs[i]], 0, 0, 0, 0, 0, 0, 0, 22, 5, 0xff000080) elseif CurrentHedgehog == mutant then circles[hhs[i]] = AddVisualGear(0, 0, vgtCircle, 0, false) SetVisualGearValues(circles[hhs[i]], 0, 0, 0, 0, 0, 0, 0, 22, 3, 0xaa000070) elseif getGearValue(CurrentHedgehog, "Feeder") and hhs[i] ~= mutant then circles[hhs[i]] = AddVisualGear(0, 0, vgtCircle, 0, false) SetVisualGearValues(circles[hhs[i]], 0, 0, 0, 0, 0, 0, 0, 22, 3, 0xaa000070) elseif hhs[i] == mutant then circles[hhs[i]] = AddVisualGear(0, 0, vgtCircle, 0, false) SetVisualGearValues(circles[hhs[i]], 0, 0, 0, 0, 0, 0, 0, 22, 5, 0xff000080) end end end circleFrame = 0 end function onNewTurn() killsCounter = 0 if mutant == nil and TotalRounds >= 0 then AddCaption( loc("First killer will mutate"), capcolDefault, capgrpGameState ) end checkScore() for i=0, TeamsCount-1 do local teamName = GetTeamName(i) if not teamsDeleted[teamName] then SendStat(siClanHealth, getTeamValue(teamName, "Score"), teamName) end end giveWeapons(CurrentHedgehog) drawCircles() setAIHints() kill_reward= numhhs*10 if CurrentHedgehog == mutant then mt_hurt=true disease= mutant_base_disease - numhhs else mt_hurt=false end setGearValue(CurrentHedgehog, "Alive", true) end function countBodies() if killsCounter == 2 then AddCaption(loc("Double kill!"), capcolDefault, capgrpGameState ) elseif killsCounter == 3 then AddCaption(loc("Mega kill!"), capcolDefault, capgrpGameState ) PlaySound(sndRegret) elseif killsCounter == 4 then AddCaption(loc("Ultra kill!"), capcolDefault, capgrpGameState ) elseif killsCounter == 5 then AddCaption(loc("Monster kill!"), capcolDefault, capgrpGameState ) PlaySound(sndIllGetYou) elseif killsCounter == 6 then AddCaption(loc("Ludicrous kill!"), capcolDefault, capgrpGameState ) PlaySound(sndNutter) elseif killsCounter == 7 then AddCaption(loc("Holy shit!"), capcolDefault, capgrpGameState ) PlaySound(sndLaugh) elseif killsCounter > 8 then AddCaption(loc("Insanity!"), capcolDefault, capgrpGameState ) end if killsCounter > recordKills then recordKills = killsCounter recordKillsHogName = getGearValue(CurrentHedgehog, "Name") recordKillsTeamName = GetHogTeamName(CurrentHedgehog) end end function onGameTick() if circleFrame > -1 then for i = 0, #hhs do if circles[hhs[i]] ~= nil and hhs[i]~= nil then hhx, hhy = GetGearPosition(hhs[i]) SetVisualGearValues(circles[hhs[i]], hhx + 1, hhy - 3, 0, 0, 0, 0, 0, 40 - (circleFrame % 25)) end end circleFrame = circleFrame + 0.06 if circleFrame >= 25 then for i = 0, #hhs do if circles[hhs[i]] ~= nil then DeleteVisualGear(circles[hhs[i]]) circles[hhs[i]] = nil end end end end if (TurnTimeLeft==0 or band(GetState(mutant), gstHHDriven) == 0) and mt_hurt then mt_hurt = false end -- Mutant's disease -- Hurt Mutant during its turn time -- Mutant's health is safe in ready phase if mt_hurt and mutant~=nil and ReadyTimeLeft == 0 then timer = timer + 1 if timer > disease_timer then timer = 0 local h = GetHealth(mutant)-disease SetHealth(mutant, h) -- Low health warning if h <= 75 then PlaySound(sndPoisonMoan, mutant) elseif h <= 150 then PlaySound(sndPoisonCough, mutant) end local tag = AddVisualGear(GetX(mutant), GetY(mutant)-5, vgtHealthTag, disease, true) SetVisualGearValues(tag, nil, nil, nil, nil, nil, nil, nil, nil, nil, GetClanColor(GetHogClan(mutant))) if GetHealth(mutant)<=0 then SetHealth(mutant,0) mt_hurt= false setGearValue(mutant,"SelfDestruct",true) EndTurn() end end end end --[[ Forces the special mutant/feeder names and hats only to be taken by those who deserved it. Names and hats will be changed (and ridiculed) if neccesary. ]] function exposeIdentityTheft(gear) local lon = string.lower(GetHogName(gear)) -- lowercase origina name local name, hat -- Change name if hog uses a reserved one if lon == "mutant" or lon == string.lower(loc("Mutant")) then SetHogName(gear, loc("Identity Thief")) SetHogHat(gear, "Disguise") elseif lon == "bottom feeder" or lon == string.lower(loc("Bottom Feeder")) then -- Word play on "Bottom Feeder". Someone who is low on cotton. :D -- Either translate literally or make up your ow word play SetHogName(gear, loc("Cotton Needer")) SetHogHat(gear, "StrawHat") end -- Strip hog off its special hat if GetHogHat(gear) == mutantHat or GetHogHat(gear) == feederHat then SetHogHat(gear, "NoHat") end end function saveStuff(gear) exposeIdentityTheft(gear) setGearValue(gear,"Name",GetHogName(gear)) setGearValue(gear,"Hat",GetHogHat(gear)) end function armageddon(gear) SetState(gear, gstLoser) SetEffect(gear, heResurrectable, 0) SetHealth(gear, 0) end function renderScores() for i=0, TeamsCount-1 do local name = GetTeamName(i) SetTeamLabel(name, string.format(loc("%d | %d"), getTeamValue(name, "Score"), getTeamValue(name, "DeadHogs"))) end end function createEndGameStats() SendStat(siGraphTitle, loc("Score graph")) local teamsSorted = {} for i=0, TeamsCount-1, 1 do teamsSorted[i+1] = GetTeamName(i) end -- Achievements stuff local achievements = 0 --- Most kills per turn if recordKills >= 3 then SendStat(siMaxStepKills, string.format("%d %s (%s)", recordKills, recordKillsHogName, recordKillsTeamName)) achievements = achievements + 1 end --- Most crates collected if recordCrates >= 5 then SendStat(siCustomAchievement, string.format(loc("%s (%s) was the greediest hedgehog and collected %d crates."), recordCratesHogName, recordCratesTeamName, recordCrates)) achievements = achievements + 1 end --- Most suicides if recordSuicides >= 5 then SendStat(siCustomAchievement, string.format(loc("%s (%s) hate life and suicided %d times."), recordSuicidesHogName, recordSuicidesTeamName, recordSuicides)) achievements = achievements + 1 end --- Most deaths if recordDeaths >= 5 then SendStat(siCustomAchievement, string.format(loc("Poor %s (%s) died %d times."), recordDeathsHogName, recordDeathsTeamName, recordDeaths)) achievements = achievements + 1 end --- Most skips if recordSkips >= 3 then SendStat(siMaxTurnSkips, string.format("%d %s (%s)", recordSkips, recordSkipsHogName, recordSkipsTeamName)) achievements = achievements + 1 end --- Total damage if totalDamage >= 900 then SendStat(siCustomAchievement, string.format(loc("%d damage was dealt in this game."), totalDamage)) achievements = achievements + 1 end --- Total kills if totalKills >= 20 or (achievements <= 0 and totalKills >= 1) then SendStat(siKilledHHs, tostring(totalKills)) achievements = achievements + 1 end -- Score and stats stuff local showScore = "" local rank = 0 local rankPlus = 1 local prevScore table.sort(teamsSorted, function(team1, team2) return getTeamValue(team1, "Score") > getTeamValue(team2, "Score") end) for i=1, TeamsCount do local score = getTeamValue(teamsSorted[i], "Score") local deaths = getTeamValue(teamsSorted[i], "DeadHogs") if i == 1 or score < prevScore then rank = rank + rankPlus rankPlus = 1 prevScore = score else rankPlus = rankPlus + 1 end SendStat(siPointType, "!POINTS") SendStat(siTeamRank, rank) SendStat(siPlayerKills, score, teamsSorted[i]) showScore = showScore .. string.format(loc("%s: %d (deaths: %d)"), teamsSorted[i], score, deaths) .. "|" end if getTeamValue(teamsSorted[1], "Score") == getTeamValue(teamsSorted[2], "Score") then -- The first two teams have the same score! Round is drawn. return nil else ShowMission(loc("Mutant"), loc("Final result"), string.format(loc("Winner: %s"), teamsSorted[1]) .. "| |" .. loc("Scores:") .. " |" .. showScore, 4, 15000) -- return winning team return teamsSorted[1] end end function checkScore() local lowest_score_team = nil local min_score=nil local winTeam = nil local only_low_score = true for i=0, TeamsCount-1 do local teamName = GetTeamName(i) if not teamsDead[teamName] then local curr_score = getTeamValue(teamName, "Score") runOnHogsInTeam(removeFeeder, teamName) if curr_score >= winScore then gameOver = true winTeam = teamName end if min_score==nil then min_score= curr_score lowest_score_team = teamName else if curr_score <= min_score then if curr_score == min_score then if getTeamValue(teamName, "DeadHogs") == getTeamValue(lowest_score_team, "DeadHogs") then only_low_score = false else if getTeamValue(teamName, "DeadHogs") > getTeamValue(lowest_score_team, "DeadHogs") then lowest_score_team = teamName end only_low_score = true end else min_score= curr_score lowest_score_team = teamName only_low_score = true end end end end end if gameOver then EndTurn(true) for i=0, TeamsCount-1 do local teamName = GetTeamName(i) if teamName~=winTeam then runOnHogsInTeam(armageddon, teamName) end end createEndGameStats() else if only_low_score then runOnHogsInTeam(setFeeder, lowest_score_team) end if meh == false then meh = true end end end function backToNormal(gear) SetHogName(gear, getGearValue(gear,"Name")) SetHogHat(gear, 'NoHat') SetHogHat(gear, getGearValue(gear,"Hat")) setGearValue(mutant,"SelfDestruct",false) mt_hurt=false mutant=nil end function setAIHints() for i = 0, #hhs do if mutant == nil or hhs[i] == mutant or CurrentHedgehog == mutant or getGearValue(CurrentHedgehog, "Feeder") then SetGearAIHints(hhs[i], aihUsualProcessing) else SetGearAIHints(hhs[i], aihDoesntMatter) end end for k,v in pairs(crates) do if CurrentHedgehog == mutant and v ~= nil then SetGearAIHints(v, aihDoesntMatter) else SetGearAIHints(v, aihUsualProcessing) end end end function removeFeeder(gear) if gear~=nil then setGearValue(gear,"Feeder",false) if gear~= mutant then SetHogName(gear, getGearValue(gear,"Name") ) SetHogHat(gear, 'NoHat') SetHogHat(gear, getGearValue(gear,"Hat")) end end end function setFeeder(gear) if gear~= mutant and gear~= nil then SetHogName(gear, loc("Bottom Feeder")) SetHogHat(gear, feederHat) setGearValue(gear,"Feeder", true) end end function setMutantStuff(gear) mutant = gear SetHogName(gear, loc("Mutant")) SetHogHat(gear, mutantHat) SetHealth(gear, ( mutant_base_health + numhhs*25) ) SetEffect(gear, hePoisoned, 1) setGearValue(mutant,"SelfDestruct",false) setGearValue(gear, "Feeder", false) AddCaption(string.format(loc("%s has mutated! +2 points"), getGearValue(gear, "Name")), GetClanColor(GetHogClan(gear)), capgrpMessage) if TurnTimeLeft > 0 then EndTurn(true) end AddVisualGear(GetX(gear), GetY(gear), vgtSmokeRing, 0, false) AddVisualGear(GetX(gear), GetY(gear), vgtSmokeRing, 0, false) AddVisualGear(GetX(gear), GetY(gear), vgtSmokeRing, 0, false) AddVisualGear(GetX(gear), GetY(gear), vgtSmokeRing, 0, false) AddVisualGear(GetX(gear), GetY(gear), vgtSmokeRing, 0, false) PlaySound(sndSuddenDeath) end function teamScan() for j=0, TeamsCount-1 do local teamName = GetTeamName(j) teamsDead[teamName] = false setTeamValue(teamName, "Score",0) setTeamValue(teamName, "Suicides",0) setTeamValue(teamName, "Skips",0) setTeamValue(teamName, "Crates",0) setTeamValue(teamName, "DeadHogs",0) end renderScores() ---***--- end function set_Mutant_and_Score(gear) local curr_team = GetHogTeamName(CurrentHedgehog) if gear == CurrentHedgehog then if CurrentHedgehog == mutant then PlaySound(sndHomerun) if getGearValue(gear, "SelfDestruct")==false then decreaseTeamValue(curr_team,"Score") end backToNormal(gear) else decreaseTeamValue(curr_team,"Score") end else if gear == mutant then backToNormal(mutant) if curr_team ~=GetHogTeamName(gear) then if getGearValue(CurrentHedgehog, "Alive") then setMutantStuff(CurrentHedgehog) setTeamValue(curr_team,"Score",(getTeamValue(curr_team,"Score") + mutant_kill_reward)) end else setTeamValue(curr_team,"Score",(getTeamValue(curr_team,"Score") - team_fire_punishment)) increaseTeamValue(curr_team,"Suicides") if(getTeamValue(curr_team, "Suicides") > recordSuicides) then recordSuicides = getTeamValue(curr_team, "Suicides") recordSuicidesHogName = getGearValue(CurrentHedgehog, "Name") recordSuicidesTeamName = curr_team end AddCaption(loc("-1 point"), GetClanColor(GetHogClan(CurrentHedgehog)), capgrpMessage) end else if mutant==nil then if curr_team ~=GetHogTeamName(gear) then if getGearValue(CurrentHedgehog, "Alive") then setMutantStuff(CurrentHedgehog) setTeamValue(curr_team,"Score",(getTeamValue(curr_team,"Score") + mutant_kill_reward)) else increaseTeamValue(curr_team,"Score") end else setTeamValue(curr_team,"Score",(getTeamValue(curr_team,"Score") - team_fire_punishment)) increaseTeamValue(curr_team,"Suicides") if(getTeamValue(curr_team, "Suicides") > recordSuicides) then recordSuicides = getTeamValue(curr_team, "Suicides") recordSuicidesHogName = getGearValue(CurrentHedgehog, "Name") recordSuicidesTeamName = curr_team end AddCaption(loc("-1 point"), GetClanColor(GetHogClan(CurrentHedgehog)), capgrpMessage) end else if curr_team ~=GetHogTeamName(gear) then if CurrentHedgehog==mutant and getGearValue(mutant,"SelfDestruct")==false then HealHog(CurrentHedgehog, kill_reward) AddCaption(loc("+1 point"), GetClanColor(GetHogClan(CurrentHedgehog)), capgrpMessage) increaseTeamValue(curr_team,"Score") end if getGearValue(CurrentHedgehog,"Feeder") then increaseTeamValue(curr_team,"Score") AddCaption(loc("+1 point"), GetClanColor(GetHogClan(CurrentHedgehog)), capgrpMessage) end else setTeamValue(curr_team,"Score",(getTeamValue(curr_team,"Score") - team_fire_punishment)) AddCaption(loc("+1 point"), GetClanColor(GetHogClan(CurrentHedgehog)), capgrpMessage) end end end end end function onGearResurrect(gear) if not gameOver then if GetGearType(gear) == gtHedgehog then increaseTeamValue(GetHogTeamName(gear), "DeadHogs") totalKills = totalKills + 1 if(getTeamValue(GetHogTeamName(gear), "DeadHogs") > recordDeaths) then recordDeaths = getTeamValue(GetHogTeamName(gear), "DeadHogs") recordDeathsHogName = getGearValue(gear, "Name") recordDeathsTeamName = GetHogTeamName(gear) end if gear==CurrentHedgehog then setGearValue(CurrentHedgehog, "Alive", false) end set_Mutant_and_Score(gear) if gear~=CurrentHedgehog then killsCounter = killsCounter + 1 countBodies() end AddVisualGear(GetX(gear), GetY(gear), vgtSmokeRing, 0, false) PlaySound(sndWhack) renderScores() end end end function onGearDamage(gear, damage) if not gameOver and GetGearType(gear) == gtHedgehog then totalDamage = totalDamage + damage end end function onSkipTurn() -- Record skips for achievement local team = GetHogTeamName(CurrentHedgehog) increaseTeamValue(team, "Skips") if(getTeamValue(team, "Skips") > recordSkips) then recordSkips = getTeamValue(team, "Skips") recordSkipsHogName = getGearValue(CurrentHedgehog, "Name") recordSkipsTeamName = team end end function onGearAdd(gear) -- Catch hedgehogs for the tracker if GetGearType(gear) == gtHedgehog then trackGear(gear) hhs[numhhs] = gear numhhs = numhhs + 1 SetEffect(gear, heResurrectable, 1) elseif GetGearType(gear) == gtCase then crates[gear] = gear elseif GetGearType(gear) == gtATFinishGame then if not gameOver then local winner = createEndGameStats() if winner then SendStat(siGameResult, string.format(loc("%s wins!"), winner)) AddCaption(string.format(loc("%s wins!"), winner), capcolDefault, capgrpGameState) end gameOver = true end end end function checkEmptyTeam (teamName) for i=0 , #hhs do if hhs[i]~=nil then if teamName == GetHogTeamName(hhs[i]) then return false end end end return true end function onGearDelete(gear) -- Remove hogs that are gone if GetGearType(gear) == gtHedgehog then numhhs = numhhs - 1 if (not gameOver) and (gear == mutant) then mutant = nil mt_hurt = false end local found for i=0, #hhs do if hhs[i] == gear then found = i break end end for i = found, #hhs - 1 do hhs[i] = hhs[i + 1] end hhs[#hhs] = nil local t_name = GetHogTeamName(gear) if checkEmptyTeam(t_name) then for i = 0, TeamsCount - 1 do if GetTeamName(i) == t_name then found = i teamsDead[t_name] = true break end end end if getGearValue(gear, "excess") ~= true and band(GetState(gear), gstDrowning) == 0 then AddVisualGear(GetX(gear), GetY(gear), vgtBigExplosion, 0, false) end trackDeletion(gear) elseif GetGearType(gear) == gtCase then crates[gear] = nil -- Check if a crate has been collected if band(GetGearMessage(gear), gmDestroy) ~= 0 and CurrentHedgehog ~= nil then -- Update crate collection achievement increaseTeamValue(GetHogTeamName(CurrentHedgehog), "Crates") if(getTeamValue(GetHogTeamName(CurrentHedgehog), "Crates") > recordCrates) then recordCrates = getTeamValue(GetHogTeamName(CurrentHedgehog), "Crates") recordCratesHogName = getGearValue(CurrentHedgehog, "Name") recordCratesTeamName = GetHogTeamName(CurrentHedgehog) end end end end function onParameters() parseParams() winScore = tonumber(params["winscore"]) or winScore end --[[ S T A R R I N G prof - Coding, implementing and evangelism vos - Initial idea and script improvements mikade - Moving the `how to play` into the game so that people know `how to play`, and whitespace :D --]]
print("Creating newForm") selectPhysicsModelsForm=FormClass.New("Select Physics Models",true) dRegisterFeature(selectPhysicsModelsForm); mtemp=selectPhysicsModelsForm currentScene=chiGetScene(); chiBindScene(mtemp.sceneNumber); mtemp.mainPanel = PanelClass.New("Main"); mtemp.RegisterFeature(mtemp,mtemp.mainPanel); mtemp.mainPanel.AddBoundaryLock(mtemp.mainPanel,"NORTH"); mtemp.mainPanel.AddBoundaryLock(mtemp.mainPanel,"SOUTH"); mtemp.mainPanel.AddBoundaryLock(mtemp.mainPanel,"EAST"); mtemp.mainPanel.AddBoundaryLock(mtemp.mainPanel,"WEST"); --ambient=0.5; --chiMaterialSetProperty(mtemp.mainPanel.matlNum,CHI_DIFFUSE_COLOR,ambient,ambient,ambient,1.0); --newForm.Show(newForm) --################################################ Labels mtemp.labelStack={} mtemp.checkBoxStack={} --=============================================== Point Kinetics lvl=1 mtemp.labelStack[lvl]=LabelClass.New("Reactor Point Kinetics"); mtemp.labelStack[lvl].SetProperty(mtemp.labelStack[lvl],"Master",mtemp.mainPanel); mtemp.labelStack[lvl].SetProperty(mtemp.labelStack[lvl],"Float",false); mtemp.labelStack[lvl].xSize=250; mtemp.checkBoxStack[lvl] = CheckBoxClass.New(mtemp.labelStack[lvl].name.."_Checkbox") mtemp.checkBoxStack[lvl].SetProperty(mtemp.checkBoxStack[lvl],"Master",mtemp.mainPanel); mtemp.checkBoxStack[lvl].SetProperty(mtemp.checkBoxStack[lvl],"Float",false); mtemp.checkBoxStack[lvl].xSize=20; mtemp.RegisterFeature(mtemp,mtemp.labelStack[lvl]) mtemp.RegisterFeature(mtemp,mtemp.checkBoxStack[lvl]); --=============================================== Smooth Particle Hydrodynamics lvl=2 mtemp.labelStack[lvl]=LabelClass.New("Smooth Particle Hydrodynamics (SPH)"); mtemp.labelStack[lvl].SetProperty(mtemp.labelStack[lvl],"Master",mtemp.mainPanel); mtemp.labelStack[lvl].SetProperty(mtemp.labelStack[lvl],"Float",false); mtemp.labelStack[lvl].xSize=250; mtemp.checkBoxStack[lvl] = CheckBoxClass.New(mtemp.labelStack[lvl].name.."_Checkbox") mtemp.checkBoxStack[lvl].SetProperty(mtemp.checkBoxStack[lvl],"Master",mtemp.mainPanel); mtemp.checkBoxStack[lvl].SetProperty(mtemp.checkBoxStack[lvl],"Float",false); mtemp.checkBoxStack[lvl].xSize=20; mtemp.RegisterFeature(mtemp,mtemp.labelStack[lvl]) mtemp.RegisterFeature(mtemp,mtemp.checkBoxStack[lvl]); --############################################### Buttons mtemp.applyButton = ButtonClass.New("Apply"); mtemp.RegisterFeature(mtemp,mtemp.applyButton); func = function (this) --for k=1,1 do if (selectPhysicsModelsForm.checkBoxStack[1]~=nil) then if (selectPhysicsModelsForm.checkBoxStack[1].selected) then newPK=ReactorDynamics1DClass.New("Physics") chinTimeControl.AddSlave(chinTimeControl,newPK) print("PK Physics created") end end if (selectPhysicsModelsForm.checkBoxStack[2]~=nil) then if (selectPhysicsModelsForm.checkBoxStack[2].selected) then if (SPHCount==0) then --Limit creation to 1 newSPH=SPHClass.New("SPH"); chinTimeControl.AddSlave(chinTimeControl,newSPH) end end end --end end mtemp.applyButton.CustomButtonDown=func chiBindScene(currentScene);
local nTime = os.time() local nDay = os.day() print("The time is " .. textutils.formatTime(nTime, false) .. " on Day " .. nDay)
return { name = "Shovel", desc = "For destroying tiles", sprite = 'shovel', usage = 'shovel', stack_size = 1, use_time = 0.5, can_upgrade = true }
workspace "DeerfoxBrowser" architecture "x64" startproject "DeerfoxBrowser" configurations { "Debug", "Release", "Deploy" } outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}" IncludeDir = {} IncludeDir["GLFW"] = "DeerfoxBrowser/deps/GLFW/include" IncludeDir["Glad"] = "DeerfoxBrowser/deps/Glad/include" IncludeDir["ImGui"] = "DeerfoxBrowser/deps/imgui" group "Dependencies" include "DeerfoxBrowser/deps/GLFW" include "DeerfoxBrowser/deps/Glad" include "DeerfoxBrowser/deps/imgui" group "" project "DeerfoxBrowser" location "DeerfoxBrowser" kind "ConsoleApp" language "C++" cppdialect "C++17" staticruntime "on" targetdir ("bin/" .. outputdir .. "/DeerfoxBrowser") objdir ("bin-int/" .. outputdir .. "/DeerfoxBrowser") pchheader "DfPch.h" pchsource "DeerfoxBrowser/src/DfPch.cpp" files { "DeerfoxBrowser/src/**.h", "DeerfoxBrowser/src/**.cpp" } includedirs { "DeerfoxBrowser/src/disarRay", "DeerfoxBrowser/src", "%{IncludeDir.GLFW}", "%{IncludeDir.Glad}", "%{IncludeDir.ImGui}" } links { "GLFW", "Glad", "ImGui", "opengl32.lib" } filter "system:windows" systemversion "latest" defines { "DFOX_PLAT_WIN", "DFOX_BUILD", "GLFW_INCLUDE_NONE" } filter "configurations:Debug" defines "DFOX_DEBUG" runtime "Debug" symbols "on" filter "configurations:Release" defines "DFOX_RELEASE" runtime "Release" optimize "on" filter "configurations:Deploy" defines "DFOX_DEPLOY" runtime "Release" optimize "on"
local files = require 'files' local guide = require 'parser.guide' local lang = require 'language' local define = require 'proto.define' return function (uri, callback) local state = files.getAst(uri) if not state then return end guide.eachSourceType(state.ast, 'local', function (source) if not source.attrs then return end if source.attrs[1][1] ~= 'close' then return end if not source.value then callback { start = source.start, finish = source.finish, message = lang.script.DIAG_COSE_NON_OBJECT, } return end if source.value.type == 'nil' or source.value.type == 'number' or source.value.type == 'boolean' or source.value.type == 'table' or source.value.type == 'function' then callback { start = source.value.start, finish = source.value.finish, message = lang.script.DIAG_COSE_NON_OBJECT, } return end end) end
local spawn = require "nvim-lsp-installer.core.spawn" local log = require "nvim-lsp-installer.log" local fs = require "nvim-lsp-installer.core.fs" local path = require "nvim-lsp-installer.path" local platform = require "nvim-lsp-installer.platform" local receipt = require "nvim-lsp-installer.core.receipt" local installer = require "nvim-lsp-installer.core.installer" local a = require "nvim-lsp-installer.core.async" ---@class ContextualSpawn ---@field cwd CwdManager ---@field stdio_sink StdioSink local ContextualSpawn = {} ---@param cwd CwdManager ---@param stdio_sink StdioSink function ContextualSpawn.new(cwd, stdio_sink) return setmetatable({ cwd = cwd, stdio_sink = stdio_sink }, ContextualSpawn) end function ContextualSpawn.__index(self, cmd) return function(args) args.cwd = args.cwd or self.cwd:get() args.stdio_sink = args.stdio_sink or self.stdio_sink -- We get_or_throw() here for convenience reasons. -- Almost every time spawn is called via context we want the command to succeed. return spawn[cmd](args):get_or_throw() end end ---@class ContextualFs ---@field private cwd CwdManager local ContextualFs = {} ContextualFs.__index = ContextualFs ---@param cwd CwdManager function ContextualFs.new(cwd) return setmetatable({ cwd = cwd }, ContextualFs) end ---@async ---@param rel_path string @The relative path from the current working directory to the file to append. ---@param contents string function ContextualFs:append_file(rel_path, contents) return fs.append_file(path.concat { self.cwd:get(), rel_path }, contents) end ---@async ---@param rel_path string @The relative path from the current working directory to the file to write. ---@param contents string function ContextualFs:write_file(rel_path, contents) return fs.write_file(path.concat { self.cwd:get(), rel_path }, contents) end ---@async ---@param rel_path string @The relative path from the current working directory. function ContextualFs:file_exists(rel_path) return fs.file_exists(path.concat { self.cwd:get(), rel_path }) end ---@async ---@param rel_path string @The relative path from the current working directory. function ContextualFs:dir_exists(rel_path) return fs.dir_exists(path.concat { self.cwd:get(), rel_path }) end ---@async ---@param rel_path string @The relative path from the current working directory. function ContextualFs:rmrf(rel_path) return fs.rmrf(path.concat { self.cwd:get(), rel_path }) end ---@async ---@param rel_path string @The relative path from the current working directory. function ContextualFs:unlink(rel_path) return fs.unlink(path.concat { self.cwd:get(), rel_path }) end ---@async ---@param old_path string ---@param new_path string function ContextualFs:rename(old_path, new_path) return fs.rename(path.concat { self.cwd:get(), old_path }, path.concat { self.cwd:get(), new_path }) end ---@async ---@param dirpath string function ContextualFs:mkdir(dirpath) return fs.mkdir(path.concat { self.cwd:get(), dirpath }) end ---@class CwdManager ---@field private boundary_path string @Defines the upper boundary for which paths are allowed as cwd. ---@field private cwd string local CwdManager = {} CwdManager.__index = CwdManager function CwdManager.new(boundary_path, cwd) assert(type(boundary_path) == "string") return setmetatable({ boundary_path = boundary_path, cwd = cwd, }, CwdManager) end function CwdManager:get() assert(self.cwd ~= nil, "Tried to access cwd before it was set.") return self.cwd end ---@param new_cwd string function CwdManager:set(new_cwd) assert(type(new_cwd) == "string") assert( path.is_subdirectory(self.boundary_path, new_cwd), ("%q is not a subdirectory of %q"):format(new_cwd, self.boundary_path) ) self.cwd = new_cwd end ---@class InstallContext ---@field public name string ---@field public receipt InstallReceiptBuilder ---@field public requested_version Optional ---@field public fs ContextualFs ---@field public spawn JobSpawn ---@field public cwd CwdManager ---@field public destination_dir string ---@field public stdio_sink StdioSink ---@field public boundary_path string local InstallContext = {} InstallContext.__index = InstallContext function InstallContext.new(opts) local cwd_manager = CwdManager.new(opts.boundary_path) return setmetatable({ name = opts.name, cwd = cwd_manager, spawn = ContextualSpawn.new(cwd_manager, opts.stdio_sink), fs = ContextualFs.new(cwd_manager), receipt = receipt.InstallReceiptBuilder.new(), boundary_path = opts.boundary_path, destination_dir = opts.destination_dir, requested_version = opts.requested_version, stdio_sink = opts.stdio_sink, }, InstallContext) end ---@async function InstallContext:promote_cwd() local cwd = self.cwd:get() if self.destination_dir == cwd then log.fmt_debug("cwd %s is already promoted (at %s)", cwd, self.destination_dir) return end log.fmt_debug("Promoting cwd %s to %s", cwd, self.destination_dir) -- 1. Remove destination dir, if it exists if fs.dir_exists(self.destination_dir) then fs.rmrf(self.destination_dir) end -- 2. Prepare for renaming cwd to destination if platform.is_unix then -- Some Unix systems will raise an error when renaming a directory to a destination that does not already exist. fs.mkdir(self.destination_dir) end -- 3. Move the cwd to the final installation directory fs.rename(cwd, self.destination_dir) -- 4. Update cwd self.cwd:set(self.destination_dir) end ---Runs the provided async functions concurrently and returns their result, once all are resolved. ---This is really just a wrapper around a.wait_all() that makes sure to patch the coroutine context before creating the ---new async execution contexts. ---@async ---@param suspend_fns async fun(ctx: InstallContext)[] function InstallContext:run_concurrently(suspend_fns) return a.wait_all(vim.tbl_map(function(suspend_fn) return function() return installer.run_installer(self, suspend_fn) end end, suspend_fns)) end ---@param rel_path string @The relative path from the current working directory to change cwd to. Will only restore to the initial cwd after execution of fn (if provided). ---@param fn async fun() @(optional) The function to run in the context of the given path. function InstallContext:chdir(rel_path, fn) local old_cwd = self.cwd:get() self.cwd:set(path.concat { old_cwd, rel_path }) if fn then local ok, result = pcall(fn) self.cwd:set(old_cwd) if not ok then error(result, 0) end return result end end return InstallContext
--% Kale Ewasiuk ([email protected]) --% +REVDATE+ --% Copyright (C) 2021-2022 Kale Ewasiuk --% --% 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 ap = {} -- module table function ap.rtrim(s) return (s:gsub("^(.-)%s*$", "%1")) end ap.punc = {} ap.punc = {'.', '; and'} -- punctuation table, 1 is last val, 2 is 2nd last val ap.punc[0] = ';' -- [0] is default punctuation ap.total = 0 -- total num of items (int) ap.curr = 0 -- current item we're on (int) ap.itemp = '\9' -- temporary item, item which WILL be affected by autopunc ap.item = '\\item' -- item ap.omit = '\\APomit' -- flag for hiding an item from punc and count, acts as if item is not there ap.pass = '\\APpass' -- flag for passing item from punc, but still considered in count ap.code = 0 -- code for skipping punc if > 0, keep in count if == 1, omit from count if == 2 ap.autopassnested = true ap.skipnextprot = false function ap.start(s) ap.curr = 0 _, ap.total = s:gsub(ap.itemp, '') local _, omit = s:gsub(ap.omit, '') ap.total = ap.total - omit end function ap.setcode(s) local _, code1 = s:gsub(ap.pass, '', 1) local _, code2 = s:gsub(ap.omit, '', 1) ap.code = code1 + 2*code2 end function ap.addcount(s) ap.setcode(s) if ap.code < 2 then -- if not omitting, we still keep counter going ap.curr = ap.curr + 1 -- increment counter end end function ap.getdelim() local d = '' if ap.code == 0 then -- d limiter -- if not passing look at punctuation table for delimiter d = ap.punc[ap.total-ap.curr+1] or ap.punc[0] end return d end function ap.protectnest(s) local x = '' if ap.autopassnested then x = ap.pass..'{}' end s = s:gsub("\0", "\0", 0) -- dummy replacement to make code easier :gsub("\\begin%s*{itemize}", x.."\1%0") -- pad \1 and \2 in inner envirnments :gsub("\\end%s*{itemize}", "%0\2") :gsub("\\begin%s*{enumerate}", x.."\1%0") :gsub("\\end%s*{enumerate}", "%0\2") :gsub("\\begin%s*{description}", x.."\1%0") :gsub("\\end%s*{description}", "%0\2") :gsub("%b\1\2", "\0%0\0") -- use bracket to place \0 (on OUTER) nested lists only :gsub("(%Z*)%z?(%Z*)%z?", -- only affect matches outside list function(a, b) return a:gsub(ap.item, ap.itemp)..b:gsub("[\1\2]", "") end) return s end function ap.go(s) if ap.skipnextprot then s = s:gsub(ap.item, ap.itemp) else s = ap.protectnest(s) end ap.start(s) -- start counters --texio.write_nl('yooo...'..s) s = s:gsub(ap.itemp, '\0\0'):gsub('\0', '', 1) -- make all items \0\0 then change first item to one \0 s = s:gsub('(%z)(%Z*)(%z?)', -- find betwen \0 .. \0 function(it, s) -- discarding duplicate item '_it' that was made in first gsub ap.addcount(s) -- add count, helps determine delimiter return ap.rtrim(it..s)..ap.getdelim()..' ' end ) s = s:gsub('\0', ap.itemp) -- replace items s = s:gsub(ap.itemp, ap.item) -- replace items return s end function ap.gotab(s) -- very simple, does not work if \\ in tabular, doesn't factor in header or footer local s, c = s:gsub('%s*\\\\', '\0') if c > 2 then s = s:gsub('\0', ap.punc[0]..'\\\\', c-2) end if c > 1 then s = s:gsub('\0', ap.punc[2]..'\\\\', 1) end s = s:gsub('\0', ap.punc[1]..'\\\\', 1) return s end return ap
local ADDON_NAME = "LibCovetousCountess" local ADDON_VERSION = 1.00 LibCovetousCountess = {} -- TODO: figure out a way to solve potential localization issues local TAGS = { -- levels 1-15, 50 ["Games"] = 1, ["Dolls"] = 1, ["Statues"] = 1, -- levels 16-24, 50 ["Ritual Objects"] = 2, ["Oddities"] = 2, -- levels 25-30, 50 ["Writings"] = 3, ["Maps"] = 3, ["Scrivener Supplies"] = 3, -- levels 31-37, 50 ["Cosmetics"] = 4, ["Linens"] = 4, ["Wardrobe Accessories"] = 4, -- levels 38-50 ["Drinkware"] = 5, ["Utensils"] = 5, ["Dishes and Cookware"] = 5 } local currentQuestType = 0 function LibCovetousCountess:UpdateQuestInfo() currentQuestType = 0 local questNameTCC = GetCompletedQuestInfo(5584) if questNameTCC ~= nil then local numQuests = GetNumJournalQuests() for journalIndex = 1, numQuests do local questName, backgroundText, activeStepText = GetJournalQuestInfo(journalIndex) if questName == questNameTCC then -- TODO: figure out a way to solve potential localization issues if string.find(activeStepText, "games") then currentQuestType = 1 elseif string.find(activeStepText, "ritual") then currentQuestType = 2 elseif string.find(activeStepText, "writings and maps") then currentQuestType = 3 elseif string.find(activeStepText, "cosmetics") then currentQuestType = 4 elseif string.find(activeStepText, "drinkware, utensils, and dishes") then currentQuestType = 5 end end end end end function LibCovetousCountess:IsItemUseful(itemLink) if itemLink == nil then return false, false end local numItemTags = GetItemLinkNumItemTags(itemLink) if numItemTags > 0 then for itemTagIndex = 1, numItemTags do local itemTagDescription = GetItemLinkItemTagInfo(itemLink, itemTagIndex) local itemTagString = zo_strformat(SI_TOOLTIP_ITEM_TAG_FORMATER, itemTagDescription) if TAGS[itemTagString] == currentQuestType then return true, true -- used in active quest elseif TAGS[itemTagString] ~= nil then return false, true -- used in other quest end end end return false, false -- not used in any quest end local function OnQuestAdded(eventCode, journalIndex, questName, objectiveName) LibCovetousCountess:UpdateQuestInfo() end local function OnQuestComplete(eventCode, questName, level, previousExperience, currentExperience, rank, previousPoints, currentPoints) LibCovetousCountess:UpdateQuestInfo() end local function OnQuestRemoved(eventCode, isQuestCompleted, journalIndex, questName, zoneIndex, poiIndex) LibCovetousCountess:UpdateQuestInfo() end local function OnPlayerActivated(eventCode) EVENT_MANAGER:UnregisterForEvent(ADDON_NAME, EVENT_PLAYER_ACTIVATED) LibCovetousCountess:UpdateQuestInfo() end EVENT_MANAGER:RegisterForEvent(ADDON_NAME, EVENT_QUEST_ADDED, OnQuestAdded) EVENT_MANAGER:RegisterForEvent(ADDON_NAME, EVENT_QUEST_COMPLETE, OnQuestComplete) EVENT_MANAGER:RegisterForEvent(ADDON_NAME, EVENT_QUEST_REMOVED, OnQuestRemoved) EVENT_MANAGER:RegisterForEvent(ADDON_NAME, EVENT_PLAYER_ACTIVATED, OnPlayerActivated)
local BasePlugin = require "kong.plugins.base_plugin" local access = require "kong.plugins.ghibli-sso.access" local GhibliHandler = BasePlugin:extend() myJWT = nil GhibliHandler.VERSION = "1.0.0" GhibliHandler.PRIORITY = 10 function GhibliHandler:new() GhibliHandler.super.new(self, "ghibli-sso") end function GhibliHandler:access(conf) local gnAuth = nil GhibliHandler.super.access(self) gnAuth = ngx.var.http_authorization if gnAuth == nil then if conf.debug then ngx.log(ngx.DEBUG,"-PRM -----> =AuthGhibli============> NOT Autenticated") ngx.header["AuthGhibli"] = "NOT Autenticated" end access.execute(conf) else if conf.debug then ngx.log(ngx.DEBUG,"-PRM -----> =AuthGhibli============> Autenticated") ngx.header["AuthGhibli"] = "Autenticated" end end if conf.debug then ngx.log(ngx.DEBUG,"-PRM -----> current JWT :"..myJWT) end end return GhibliHandler
local parser = require("moocscript.parser") local compile = require("moocscript.compile") describe("test success 1 #export", function() local mnstr=[[ local aa local b, c local d, e, f = 1, {2}, fn() {} local fn call(b, c) { return b } export a export b, c export d, e, f = "h", { c = "y", d = b }, _ENV export fn closeDoor(d, e) { return e } return d, e, closeDoor ]] 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 d, e, c = f() assert.is_equal(d, "h") assert.is_equal(e.c, "y") assert.is_equal(c(11, 10), 10) end) end) describe("test success 2 #export", function() local mnstr=[[ fn testScope() { export * return outer_a + outer_b } ]] 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) end) describe("test failed 1 #export", function() local mnstr=[[ local import b from "cc" ]] local ret, ast = parser.parse(mnstr) it("should get ast", function() assert.is_false(ret) end) end) describe("test failed 2 #export", function() local mnstr=[[ fn testScope() { while false { export * } return outer_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_false(ret) assert.is_equal(content, "_:5: return outer_a <undefined variable 'outer_a'>") end) end)
require "sprite" require "theme" require "timer" local W, H = theme.scr.w(), theme.scr.h() local tiles = {} local WX, HY = 64, 64 local WW, HH = math.floor(W / WX), math.floor(H / HY) local pad = 2 local book_spr = sprite.new "book.png" local wh1_spr = sprite.new "wheel1.png" local wh2_spr = sprite.new "wheel2.png" local instead_spr = sprite.new "instead.png" local shadow_spr = { sprite.new "shadow.png", sprite.new "shadow2.png" } local rotate = 0 local rotate_spr = {} function logo_init() for r = 1, 359 do local a = r rotate_spr[r] = {} rotate_spr[r][1] = wh1_spr:rotate(-a) rotate_spr[r][2] = wh2_spr:rotate(a * 2) end end function logo() local w, h = instead_spr:size() local ww, hh = theme.scr.w(), theme.scr.h() -- instead_spr:draw(sprite.scr(), (ww - w) / 2, (hh - h)/ 2 - 122) local book, wh1, wh2 = book_spr, wh1_spr, wh2_spr local r = math.floor(rotate) local x, y = (theme.scr.w() - 250) / 2, (theme.scr.h() - 256) / 2 if r > 0 then wh1, wh2 = rotate_spr[r][1], rotate_spr[r][2] end book:draw(sprite.scr(), x, 92 + y) local w, h = wh1:size() for _ = 1, 3 do shadow_spr[rnd(2)]:draw(sprite.scr(), x - 20, y - 16) end wh1:draw(sprite.scr(), x + 86 - w/ 2, 92 + y - 16 - h / 2) local w, h = wh2:size() wh2:draw(sprite.scr(), x + 174 - w / 2, 92 + y + 12 - h /2) rotate = rotate + 1 if rotate >= 360 then rotate = 0 end end function draw_tiles() for y = 1, HY do for x = 1, WX do local a = tiles[y][x].lev / 255 local COL = tiles[y][x].col local col = string.format("#%02x%02x%02x", COL[1] * a, COL[2] * a, COL[3] * a) sprite.scr():fill((x - 1) * WX + pad, (y - 1) * HY + pad, WX - pad * 2, HY - pad * 2, col) end end end local DIST = 6 local slides = {} local slides_pool = {} function scale_slide(v) local x, y local distance = rnd(10000) / 10000 v.dist = distance local scale = 1 / 8 + (1 - v.dist) * 1 / 2 local smooth = true v.spr = sprite.new(v.nam):scale(scale, scale, smooth) v.w, v.h = v.spr:size() v.dir = rnd(4) if v.dir == 1 then x = - (v.w + rnd(v.w)) y = rnd(theme.scr.h()) - rnd(v.h) elseif v.dir == 2 then x = theme.scr.w() + rnd(v.w) y = rnd(theme.scr.h()) - rnd(v.h) elseif v.dir == 3 then x = rnd(theme.scr.w()) - rnd(v.w) y = -(v.h + rnd(v.h)) else x = rnd(theme.scr.w()) - rnd(v.w) y = theme.scr.h() + (v.h + rnd(v.h)) end v.x, v.y = x, y end function process_slides(delta) local x, y, once for k, v in ipairs(slides) do if v.dir == 1 then v.x = v.x + (delta * (2 * (1 - v.dist) +1)) elseif v.dir == 2 then v.x = v.x - (delta * (2 * (1 - v.dist) +1)) elseif v.dir == 3 then v.y = v.y + (delta * (2 * (1 - v.dist) +1)) else v.y = v.y - (delta * (2 * (1 - v.dist) +1)) end if not once and (v.x > theme.scr.w() and v.dir == 1 or v.x < -v.w and v.dir == 2 or v.y > theme.scr.h() and v.dir == 3 or v.y < - v.h and v.dir == 4) then once = k end -- v.spr:copy(sprite.scr(), v.x, v.y) end if once then local v = slides[once] table.remove(slides, once) table.insert(slides_pool, v) local n = rnd(#slides_pool) v = slides_pool[n] scale_slide(v) -- print("scale", n) table.insert(slides, v) table.remove(slides_pool, n) table.sort(slides, function(a, b) return a.dist > b.dist end) end end function draw_slides() for k, v in ipairs(slides) do v.spr:copy(sprite.scr(), v.x, v.y) end end local SLIDES_NR = 8 function load_slides() scandir() for _ = 1, SLIDES_NR do if #slides_pool == 0 then break end local n = rnd(#slides_pool) table.insert(slides, slides_pool[n]) table.remove(slides_pool, n) end DIST = #slides for k, v in ipairs(slides) do scale_slide(v) end table.sort(slides, function(a, b) return a.dist > b.dist end) end function process_tiles() local y = rnd(HH) local x = rnd(WW) local cell = tiles[y][x] if cell.dir == 1 then cell.lev = cell.lev + (rnd(64) + 32) else cell.lev = cell.lev - (rnd(64) + 32) end if cell.lev > 255 then cell.dir = 2 cell.lev = 255 color(x, y) elseif cell.lev < 0 then cell.dir = 1 cell.lev = 0 color(x, y) end end function color(x, y) local COL = tiles[y][x].col COL[1] = 0 -- rnd(255) COL[2] = 255 -- rnd(255) COL[3] = 255 -- rnd(255) end local last_t = 0 function game:timer() local t = instead.ticks() local delta = t - last_t if last_t == 0 then delta = 1.0 end last_t = t process_tiles() process_slides(delta / 20) sprite.scr():fill 'black' draw_tiles() draw_slides() logo(0, 0) end function scandir() for d in std.readdir 'screen' do if d:find("%.png$") then table.insert(slides_pool, { nam = "screen/"..d }) end dprint("Scan: ", d) end end function start() if not sprite.direct(true) then error("Включите собственные темы игр") end sprite.scr():fill 'black' for y = 1, HY do if not tiles[y] then tiles[y] = {} end for x = 1, WX do tiles[y][x] = { lev = rnd(128), dir = rnd(2), col = {} } color(x, y) end end load_slides() logo_init() timer:set(10) end
local Object = { className = "Object" } function Object:new ( obj ) obj = obj or {} setmetatable( obj, self ) self.__index = self return obj end function Object:extend ( obj ) obj = self:new ( obj ) obj.mysuper = {} local oldmysuper = self.mysuper or {} if #oldmysuper > 0 then for i = 1, #oldmysuper do obj.mysuper[i] = oldmysuper[i] end end obj.mysuper[#oldmysuper + 1] = self return obj end function Object:super () return self.mysuper[#(self.mysuper)] end return Object
--[[Author: Pizzalol Date: 26.01.2015. Saves the killer of the aura carrier]] function CommandAuraDeath( keys ) local caster = keys.caster local attacker = keys.attacker caster.command_aura_target = attacker end --[[Author: Pizzalol Date: 26.01.2015. Removes the negative aura from the killer on caster respawn]] function CommandAuraRespawn( keys ) local caster = keys.caster local modifier = keys.modifier caster.command_aura_target:RemoveModifierByName(modifier) end
local _ = require('string') local a = {} local b = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' a.encode = function(c) return ((c:gsub('.', function(d) local e, f = '', d:byte() for g = 8, 1, -1 do e = e .. (f % 2 ^ g - f % 2 ^ (g - 1) > 0 and '1' or '0') end return e end) .. '0000'):gsub('%d%d%d?%d?%d?%d?', function(d) if (#d < 6) then return '' end local e = 0 for f = 1, 6 do e = e + (d:sub(f, f) == '1' and 2 ^ (6 - f) or 0) end return b:sub(e + 1, e + 1) end) .. ({'', '==', '='})[#c % 3 + 1]) end a.decode = function(c) c = _.gsub(c, '[^' .. b .. '=]', '') return (c:gsub('.', function(d) if (d == '=') then return '' end local e, f = '', (b:find(d) - 1) for g = 6, 1, -1 do e = e .. (f % 2 ^ g - f % 2 ^ (g - 1) > 0 and '1' or '0') end return e end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(d) if (#d ~= 8) then return '' end local e = 0 for f = 1, 8 do e = e + (d:sub(f, f) == '1' and 2 ^ (8 - f) or 0) end return _.char(e) end)) end return {encode = a.encode, decode = a.decode}
Lucene.maps = {} Lucene.maps.capturedSpace = false Lucene.maps.capturingSpace = false Lucene.maps.ignorePrompt = false Lucene.maps.inSpace = false Lucene.maps.skipLine = 0 Lucene.maps.activateMap = function(name) if name == "Space" then Lucene.maps.showSpace() Lucene.maps.inSpace = true else Lucene.maps.showMap() Lucene.maps.inSpace = false end end Lucene.maps.addTab = function(name) local newLabel = Lucene.containers.label({ name = name.."MapLabel", fgColor = "#ffffff" }, Lucene.ui.sides.right.mapHeader) newLabel:echo("<center>"..name, nil, "10") newLabel:setStyleSheet(Lucene.styles.chatNormal) newLabel:setClickCallback("Lucene.maps.activateMap", name) return newLabel end Lucene.maps.showMap = function() Lucene.maps.mapTab:setStyleSheet(Lucene.styles.chatActive) Lucene.maps.spaceTab:setStyleSheet(Lucene.styles.chatNormal) Lucene.maps.spaceMapContainer:hide() Lucene.maps.mudletMapContainer:show() Lucene.maps.inSpace = false end Lucene.maps.init = function() Lucene.maps.mudletMapContainer = Lucene.containers.container({ name = "mudletMapContainer", x = "0", y = "0", width = "100%", height = "100%" }, Lucene.ui.sides.right.mapFooter) Lucene.maps.mudletMap = Lucene.containers.mapper({ name = "mudletMap", x = "0", y = "0%", width = "100%", height = "100%" }, Lucene.maps.mudletMapContainer) Lucene.maps.spaceMapContainer = Lucene.containers.container({ name = "spaceMapContainer", x = "1%", y = "1%", width = "98%", height = "98%" }, Lucene.ui.sides.right.mapFooter) Lucene.maps.spaceMap = Lucene.containers.console({ name = "spaceMap", x = "0%", y = "0%", height = "100%", width = "50%" }, Lucene.maps.spaceMapContainer) Lucene.maps.spaceMap:setColor("black") Lucene.maps.spaceMap:setFontSize(8) Lucene.maps.mapTab = Lucene.maps.addTab("Mudlet") Lucene.maps.mapTab:setStyleSheet(Lucene.styles.chatActive) Lucene.maps.spaceTab = Lucene.maps.addTab("Space") Lucene.maps.spaceTab:setStyleSheet(Lucene.styles.chatNormal) Lucene.maps.spaceMapContainer:hide() end registerAnonymousEventHandler("Lucene.bootstrap", "Lucene.maps.init") Lucene.maps.showSpace = function() Lucene.maps.mapTab:setStyleSheet(Lucene.styles.chatNormal) Lucene.maps.spaceTab:setStyleSheet(Lucene.styles.chatActive) Lucene.maps.mudletMapContainer:hide() Lucene.maps.spaceMapContainer:show() Lucene.maps.inSpace = true end
-- config local opts = { position_size = 50, group_line_factor = 0.25, color_group = '#ffffffaa', color_person_selected = '#ffffff33', color_single_person = '#ffffff33', color_group_member = '#377eb833', color_group_speaker = '#e41a1c33', color_group_addressee = '#4daf4a33', color_border_selected = '#e41a133', color_border_default = '#00000033', } (require 'mp.options').read_options(opts,"render-groups") local mp = require 'mp' local assdraw = require 'mp.assdraw' local utils = require 'mp.utils' local msg = require 'msg' local dump = require 'dump' local tr = require 'render-track-annotation' local tf = require 'tf' local RenderGroupAnnotation = {} function RenderGroupAnnotation:new(o) o = o or {} setmetatable(o, self) self.__index = self o.tr = tr:new() return o end local function mean_point(points) local x = 0 local y = 0 local c = 0 for k,v in pairs(points) do x = x + v.x y = y + v.y c = c + 1 end return {x = x/c, y = y/c} end local function sort_points(points) local center = mean_point(points) local tf = tf:new() table.sort(points, function(a,b) return tf:rotation_from_points(center.x,center.y,a.x,a.y) < tf:rotation_from_points(center.x,center.y,b.x,b.y) end ) return points end function RenderGroupAnnotation:render_group_polygon(ass, points, color, gui) if not points[2] then return end -- need at least two points for a polygon ass:new_event() ass:append(gui:asstools_create_color_from_hex(color)) ass:pos(0,0) ass:draw_start() local first = true for i,point in pairs(sort_points(points)) do if first then ass:move_to(point.x,point.y) first = false else ass:line_to(point.x,point.y) end end ass:draw_stop() end function RenderGroupAnnotation:get_group_member_positions(time, group, persons, frame_id) local positions = {} local members = group:get_persons(time) if members and members.annotation then for k,v in pairs(members.annotation) do table.insert(positions, {person = persons[k], position = persons[k]:position(time, frame_id).position, type=v}) end end return positions end local function get_color_from_type(type, marked) local result = {} if marked then result.border = opts.color_border_selected else result.border = opts.color_border_default end if type == 'nongroup' then result.primary = opts.color_single_person elseif type == 'member' then result.primary = opts.color_group_member elseif type == 'speaker' then result.primary = opts.color_group_speaker elseif type == 'addressee' then result.primary = opts.color_group_addressee else assert(false) end return result end local function create_back_line(px,py,rad) if not rad then return {{ x = px, y = py }} else local result = {} table.insert(result,{x = px - opts.position_size * math.cos(rad-math.pi/2) * opts.group_line_factor, y = py - opts.position_size * math.sin(rad-math.pi/2) * opts.group_line_factor}) --table.insert(result,{x = px + opts.position_size * math.cos(rad), y = py + opts.position_size * math.sin(rad)}) table.insert(result,{x = px + opts.position_size * math.cos(rad-math.pi/2) * opts.group_line_factor, y = py + opts.position_size * math.sin(rad-math.pi/2) * opts.group_line_factor}) return result end end function RenderGroupAnnotation:render_track_position(ass, position, color, id, gui) local size = gui:video_to_px_scale(opts.position_size)/2 if position.position then local px, py = gui:video_to_px(position.position.x, position.position.y) self.tr:render_track_position(ass, px, py, position.position.rad, size, color, id, gui) return create_back_line(px, py, position.position.rad) else return {{ x = 0, y = 0 }} end end function RenderGroupAnnotation:draw_group(ass, group, time, persons, frame_id, marked, gui) local positions = self:get_group_member_positions(time, group, persons, frame_id) local members = {} local points = {} local track_renderer = tr:new() for k, position in pairs(positions) do local person_color = get_color_from_type(position.type, (marked and (marked.person_id == position.person.person_id))) local person_points = self:render_track_position(ass, position, person_color,position.person.person_id, gui) for i,p in pairs(person_points) do table.insert(points,p) end table.insert(members,position.person.person_id) end self:render_group_polygon(ass, points, {primary = opts.color_group, border = opts.color_border_default}, gui) return members end function RenderGroupAnnotation:draw_groups(group, time, ass, gui) local persons = group.persons local marked = group.marked_person local frame_id = group.main.data('file') local rendered_persons = {} for k, group in pairs(group.groups) do local members = self:draw_group(ass, group, time, persons, frame_id, marked, gui) for l, id in pairs(members) do rendered_persons[id] = true end end local track_renderer = tr:new() for k, person in pairs(persons) do if not rendered_persons[person.person_id] then -- render remaining persons local position = person:position(time, frame_id) if position and position.position then self:render_track_position(ass, position, get_color_from_type('nongroup', (marked and (person.person_id == marked.person_id))), person.person_id, gui) end end end ass:draw_stop() end function RenderGroupAnnotation:render(group, ass, gui) local time = group.main.data('time') if not time then return end self:draw_groups(group, time, ass, gui) end return RenderGroupAnnotation
concommand.Add("updating", function(_, _, _, args) local spacedArgs = args:Trim():Split(" ") local method = spacedArgs[1]:lower() if method == "start" then ChatAddText(Color(175, 235, 225), "Server update in progress...") elseif method == "addons-updated" then ChatAddText(Color(175, 235, 225), "\tUpdated addons...") elseif method == "submodule-updated" then local submodule = spacedArgs[2] ChatAddText(Color(175, 235, 225), "\tUpdated submodule " .. submodule .. "...") elseif method == "gamemode-updated" then ChatAddText(Color(175, 235, 225), "\tUpdated gamemode...") elseif method == "end" then ChatAddText(Color(175, 235, 225), "Update finished!") end end) concommand.Add("read_last_commit", function() local exists = file.Exists("last_commit.txt", "DATA") if exists then local commit = util.JSONToTable(file.Read("last_commit.txt", "DATA")) if not commit then return end local text = {} if commit.head_commit.message and commit.head_commit.message:Trim() ~= "" then local txt = "" local lines = commit.head_commit.message:Trim():Split("\n") for k, v in next, lines do txt = txt .. " > " .. v .. "\n" -- (k == #lines and "" or "\n") end text[#text + 1] = txt end local operations = { modified = { Symbol = "*", Color = Color(164, 127, 255) }, added = { Symbol = "+", Color = Color(96, 255, 96) }, removed = { Symbol = "-", Color = Color(255, 96, 96) } } for op, info in next, operations do if #commit.head_commit[op] > 0 then text[#text + 1] = info.Color local txt = "" for k, v in next, commit.head_commit[op] do txt = txt .. " " .. info.Symbol .. " " .. v .. "\n" -- (k == #commit.head_commit[op] and "" or "\n") end text[#text + 1] = txt end end text[#text] = text[#text]:gsub("\n$", "") ChatAddText( Color(175, 235, 225), "Update in " .. commit.repository.name .. " by " .. commit.head_commit.author.username .. " (" .. commit.head_commit.author.email .. "):\n", unpack(text) ) end end)
package.path = './src/?.lua;' .. package.path local test = require('gambiarra') local actual = {} local expected = {} local currentTest -- Set meta test handler test(function(e, testname, msg) if msg and msg:find('Expected', nil, true) then msg = msg:match('^(.*): Expected.*$') end if e == 'begin' then currentTest = { name = testname, pass = {}, fail = {} } elseif e == 'end' then table.insert(actual, currentTest) elseif e == 'pass' then table.insert(currentTest.pass, msg) elseif e == 'fail' then table.insert(currentTest.fail, msg) elseif e == 'except' then print('*** PANIC ***: ', testname, msg) end end) -- Helper function to print arrays local function stringify(t) local s = {} for i = 1, #t do table.insert(s, string.format('"%s"', tostring(t[i]))) end return table.concat(s, ' ') end -- Helper function to compare two tables local function comparetables(t1, t2) if #t1 ~= #t2 then return false end for i = 1, #t1 do if t1[i] ~= t2[i] then return false end end return true end local function metatest(name, f, expectedPassed, expectedFailed, async) test(name, f, async) table.insert(expected, { name = name, pass = expectedPassed, fail = expectedFailed }) end -- -- Basic tests -- metatest('simple assert passes', function() ok(2 == 2, '2==2') end, {'2==2'}, {}) metatest('simple assert fails', function() ok(1 == 2, '1~=2') end, {}, {'1~=2'}) metatest('ok without a message', function() ok(1 == 1) ok(1 == 2) end, {'spec/gambiarra_test.lua:71'}, {'spec/gambiarra_test.lua:72'}) -- -- Equality tests -- metatest('eq nil', function() ok(eq(nil, nil), 'nil == nil') end, {'nil == nil'}, {}) metatest('eq primitives', function() ok(eq('foo', 'foo'), 'str == str') ok(eq('foo', 'bar'), 'str != str') ok(eq(123, 123), 'num == num') ok(eq(123, 12), 'num != num') end, {'str == str', 'num == num'}, {'str != str', 'num != num'}) metatest('eq arrays', function() ok(eq({}, {}), 'empty') ok(eq({1, 2}, {1, 2}), 'equal') ok(eq({1, 2}, {2, 1}), 'swapped') ok(eq({1, 2, 3}, {1, 2}), 'longer') ok(eq({1, 2}, {1, 2, 3}), 'shorter') end, {'empty', 'equal'}, {'swapped', 'longer', 'shorter'}) metatest('eq nested arrays', function() ok(eq({1, 2, {3, 4}}, {1, 2, {3, 4}}), 'equal') ok(eq({1, 2, {3, 4}}, {1, 2, {4, 3}}), 'swapped') ok(eq({1, 2, {3, 4, 5}}, {1, 2, {3, 4}}), 'longer') ok(eq({1, 2, {3}}, {1, 2, {4, 3}}), 'shorter') end, {'equal'}, {'swapped', 'longer', 'shorter'}) metatest('eq objects', function() ok(eq({}, {}), 'empty') ok(eq({a = 1,b = 2}, {a = 1,b = 2}), 'equal') ok(eq({b = 2,a = 1}, {a = 1,b = 2}), 'swapped') ok(eq({a = 1,b = 2}, {a = 1,b = 3}), 'not equal') end, {'empty', 'equal', 'swapped'}, {'not equal'}) metatest('eq nested objects', function() ok(eq({ ['1'] = { name = 'mhc', age = 28 }, ['2'] = { name = 'arb', age = 26 } }, { ['1'] = { name = 'mhc', age = 28 }, ['2'] = { name = 'arb', age = 26 } }), 'equal') ok(eq({ ['1'] = { name = 'mhc', age = 28 }, ['2'] = { name = 'arb', age = 26 } }, { ['1'] = { name = 'mhc', age = 28 }, ['2'] = { name = 'arb', age = 27 } }), 'not equal') end, {'equal'}, {'not equal'}) metatest('eq functions', function() ok(eq(function(x) return x end, function(x) return x end), 'equal') ok(eq(function(x) return x end, function(y) return y end), 'wrong variable') ok(eq(function(x) return x end, function(x) return x+2 end), 'wrong code') end, {'equal'}, {'wrong variable', 'wrong code'}) -- -- Spies -- metatest('spy called', function() local f = spy() ok(not f.called or #f.called == 0, 'not called') f() ok(f.called, 'called') ok(#f.called == 1, 'called once') f() ok(#f.called == 2, 'called twice') end, {'not called', 'called', 'called once', 'called twice'}, {}) metatest('spy with arguments', function() local x = 0 local function setX(n) x = n end local f = spy(setX) f(1) ok(x == 1, 'x == 1') ok(eq(f.called, {{1}}), 'called with 1') f(42) ok(x == 42, 'x == 42') ok(eq(f.called, {{1}, {42}}), 'called with 42') end, {'x == 1', 'called with 1', 'x == 42', 'called with 42'}, {}) metatest('spy with nils', function() -- luacheck: no unused args local function nils(a, dummy, b) return a, nil, b, nil end local f = spy(nils) local r1, r2, r3, r4 = f(1, nil, 2) ok(eq(f.called, {{1, nil, 2}}), 'nil in args') ok(r1 == 1 and r2 == nil and r3 == 2 and r4 == nil, 'nil in returns') end, {'nil in args', 'nil in returns'}, {}) metatest('spy with exception', function() local function throwSomething(s) if s ~= 'nopanic' then error('panic: '..s) end end local f = spy(throwSomething) f('nopanic') ok(f.errors == nil, 'no errors yet') f('foo') ok(eq(f.called, {{'nopanic'}, {'foo'}}), 'args ok') ok(f.errors[1] == nil and f.errors[2] ~= nil, 'thrown ok') end, {'no errors yet', 'args ok', 'thrown ok'}, {}) metatest('another spy with exception', function() -- luacheck: ignore a unknownVariable local f = spy(function() local a = unknownVariable + 1 end) f() ok(f.errors[1], 'exception thrown') end, {'exception thrown'}, {}) metatest('spy should return a value', function() local f = spy(function() return 5 end) ok(f() == 5, 'spy returns a value') local g = spy() ok(g() == nil, 'default spy returns undefined') end, {'spy returns a value', 'default spy returns undefined'}, {}) -- -- Async tests -- local queue = {} local function async(f) table.insert(queue, f) end local function async_next() local f = table.remove(queue, 1) if f then f() end end metatest('async test', function(next) async(function() ok(true, 'bar') async(function() ok(true, 'baz') next() end) end) ok(true, 'foo') end, {'foo', 'bar', 'baz'}, {}, true) metatest('async test without actually async', function(next) ok(true, 'bar') next() end, {'bar'}, {}, true) async_next() async_next() metatest('another async test after async queue drained', function(next) async(function() ok(true, 'bar') next() end) ok(true, 'foo') end, {'foo', 'bar'}, {}, true) async_next() -- -- Finalize: check test results -- local exit_code = 0 for i = 1,#expected do if actual[i] == nil then print(string.format('✘ %s (pending)', expected[i].name)) elseif not comparetables(expected[i].pass, actual[i].pass) then print(string.format('✘ %s (passed): [%s] vs [%s]', expected[i].name, stringify(expected[i].pass), stringify(actual[i].pass))) exit_code = 1 elseif not comparetables(expected[i].fail, actual[i].fail) then print(string.format('✘ %s (failed): [%s] vs [%s]', expected[i].name, stringify(expected[i].fail), stringify(actual[i].fail))) exit_code = 1 else print("✔ "..expected[i].name) end end os.exit(exit_code)
local GIF = require("gif") local P = require("ps2const") local VRAM = require("vram") -- enum for how this script tracks current -- drawing mode to minimize GIFTag swapping local DRAW_NONE = 0 local DRAW_GEOM = 1 local DRAW_SPRITE = 2 -- GS Registers to set when drawing geometry local DRAW_FMT_GEOM = {1,5,5,5} -- GS Registers to set when drawing SPRITE primitives local DRAW_FMT_SPRITE = {2,1,5,2,1,5} -- Size of each drawbuffer before we have to split it local DB_SIZE = 20000 -- Local draw state local draw = { -- screen dimensions fbw = -1, fbh = -1, -- current colour col = {r=255, g=255, b=255, a=0x80}, -- current state state = DRAW_NONE, -- number of loops in current GIFTag loopCount = 0, -- pointer to start of current GIFTag in active buffer tagLoopPtr = -1, -- VRAM addr of texture we are currently drawing currentTexPtr = 0, -- current drawbuffer (initialized each frame) buf = nil, -- how many drawbuffer "kick"s this frame kc = 0, -- how many raw triangles we pushed this frame rawtri = 0, -- pointer to start of current DMATag in active buffer dmaTagQwPtr = 0, -- are we currently in a CNT DMATag? isInCnt = false, -- metrics from previous frame prev = { kc = 0, rawtri = 0, } } -- start new CNT DMATag for standard GIFTag registers data function draw:newCnt() self.dmaTagQwPtr = self.buf.head self:dmaTagRaw(DMA.CNT, 0, 0) self.isInCnt = true end -- end current CNT and calculate number of QWs function draw:endCnt() if self.isInCnt then local lw = self.buf:read(self.dmaTagQwPtr) local bytes = self.buf.head - self.dmaTagQwPtr local qwc = math.floor(bytes / 16) if self.buf.head % 16 ~= 0 then qwc = qwc + 1 end -- update the DMATag with the number of QWs self.buf:write(self.dmaTagQwPtr, lw + qwc - 1) end end -- put a DMATag in the current draw buffer -- tt - DMA type (eg DMA.CNT, DMA.REF) -- qwc - number of quadwords -- addr - addr field (meaning depends on type, 0 for CNT) function draw:dmaTagRaw(tt, qwc, addr) self.buf:pushint(qwc + tt) self.buf:pushint(addr) self.buf:pushint(0) self.buf:pushint(0) end -- put a DMATag with type END in the draw buffer function draw:dmaEnd() self:dmaTagRaw(DMA.END, 0, 0) end -- get a new drawbuffer, called at frame start or after "kick" function draw:newBuffer() self.state = DRAW_NONE self.loopCount = 0 self.tagLoopPtr = -1 self.buf = RM.getDrawBuffer(DB_SIZE) -- start a CNT by default, if we end the CNT without pushing anything -- into it this is has no effect self:newCnt() end -- set current draw colour function draw:setColour(r,g,b,a) self.col.r = math.floor(r) self.col.g = math.floor(g) self.col.b = math.floor(b) self.col.a = math.floor(a) end -- draw a rectangle function draw:rect(x, y, w, h) x = math.floor(x) y = math.floor(y) -- TODO: optimize with a SPRITE primitive draw:triangle(x, y, x+w, y, x, y+h) draw:triangle(x, y+h, x+w, y+h, x+w, y) end -- convert a 32bit floating point number to a fixed point coordinate + offset function toCoord(i) local ii = math.floor(i) local fi = math.floor((i%1)*0xf) return 0x8000 + (ii*16) + fi end -- draw a sprite function draw:sprite(tex, x, y, w, h, u1, v1, u2, v2) if self.loopCount > 10000 then self:kick() end if self.buf.size - self.buf.head < 80 then self:kick() end -- if we aren't in a GIFTag drawing sprites for the current texture then... if self.state ~= DRAW_SPRITE or self.currentTexPtr ~= tex.basePtr then -- cleanup previous tag if self.state ~= DRAW_NONE then draw:updateLastTagLoops() end -- setup texture drawing registers self.currentTexPtr = tex.basePtr local pb = math.floor(tex.basePtr/64) local pw = math.floor(tex.width/64) GIF.tag(self.buf, GIF.PACKED, 4, false, {0xe}) GIF.texA(self.buf, 0x80, 0x80) GIF.tex1(self.buf, true, 0, true, 0, 0) self.buf:settex(0, pb, pw, tex.format, math.floor(log2(tex.width)), math.floor(log2(tex.height)), 0, 1, 0, 0, 0) -- GIF.mipTbp1(self.buf, 0, pb, pw, pb, pw, pb, pw) -- GIF.mipTbp2(self.buf, 0, pb, pw, pb, pw, pb, pw) GIF.primAd(self.buf, P.PRIM.SPRITE, false, true, false) --GIF.packedRGBAQ(self.buf, self.col.r, self.col.g, self.col.b, self.col.a) self.tagLoopPtr = GIF.tag(self.buf, 0, 1, false, DRAW_FMT_SPRITE) self.loopCount = 0 self.state = DRAW_SPRITE end -- push geometry, colour and ST to drawbuffer GIF.packedST(self.buf, u1, v1) GIF.packedRGBAQ(self.buf, self.col.r, self.col.g, self.col.b, self.col.a) GIF.packedXYZ2(self.buf, toCoord(x-320), toCoord(y-224), 0) GIF.packedST(self.buf, u2, v2) GIF.packedRGBAQ(self.buf, self.col.r, self.col.g, self.col.b, self.col.a) GIF.packedXYZ2(self.buf, toCoord(x+w-320), toCoord(y+h-224), 0) self.loopCount = self.loopCount + 1 end -- draw triangle function draw:triangle(x1, y1, x2, y2, x3, y3) if self.loopCount > 10000 then self:kick() end if self.buf.size - self.buf.head < 80 then self:kick() end -- if we are not currently drawing raw geometry then... if self.state ~= DRAW_GEOM then -- cleanup previous GIFTag if self.state ~= DRAW_NONE then draw:updateLastTagLoops() end -- setup GIFTag for drawing triangles GIF.tag(self.buf, 0, 1, false, {0xe}) GIF.primAd(self.buf, P.PRIM.TRI, false, false, false) self.tagLoopPtr = GIF.tag(self.buf, 0, 1, false, DRAW_FMT_GEOM) self.loopCount = 0 self.state = DRAW_GEOM end -- push PACKED triangle data into draw buffer GIF.packedRGBAQ(self.buf, self.col.r, self.col.g, self.col.b, self.col.a) GIF.packedXYZ2(self.buf, toCoord(x1-320), toCoord(y1-224), 0) GIF.packedXYZ2(self.buf, toCoord(x2-320), toCoord(y2-224), 0) GIF.packedXYZ2(self.buf, toCoord(x3-320), toCoord(y3-224), 0) self.loopCount = self.loopCount + 1 self.rawtri = self.rawtri + 1 end -- submit the current drawbuffer for rendering function draw:kick() -- cleanup current GIFTag self:updateLastTagLoops() -- end any active CNT (does nothing if no CNT DMATag active) self:endCnt() -- add DMA END tag self:dmaEnd() DMA.sendChain(self.buf, DMA.GIF) -- refresh our drawbuffer, basically free so no concerns doing this at the -- end of the frame self:newBuffer() self.kc = self.kc + 1 end -- cleanup current GIFTag with all relevant data function draw:updateLastTagLoops() if self.tagLoopPtr >= 0 then local nloop = self.buf:read(self.tagLoopPtr) -- if this GIFTag has EOP flag set if nloop - 0x8000 > 0 then -- write the number of loops back with EOP flag set self.buf:write(self.tagLoopPtr, 0x8000 + self.loopCount) else -- otherwise just write the number of loops self.buf:write(self.tagLoopPtr, self.loopCount) end end end -- TODO: move out of draw2d -- load a texture into EE memory function draw.loadTexture(fname, w, h) local tt = { width = w, height = h, data = nil, format = GS.PSM32, fname = fname, } tt.data = TGA.load(fname, w, h) return tt end -- upload a texture that has been VRAM allocated into GS memory function draw:uploadTexture(tt) if tt.basePtr == nil then error("cannot upload texture that has not been allocated") end if self.buf.size - self.buf.head < 7 then self:kick() end -- ASSUME: DMATag CNT is active -- setup GS texture transfer registers for upload GIF.tag(self.buf, GIF.PACKED, 4, false, {0xe}) GIF.bitBltBuf(self.buf, math.floor(tt.basePtr/64), math.floor(tt.width/64), tt.format) GIF.trxPos(self.buf,0,0,0,0,0) GIF.trxReg(self.buf,tt.width,tt.height) GIF.trxDir(self.buf, 0) self:endCnt() -- ASSUME: format is PSM32! local eeSize = tt.width*tt.height*4 local qwc = math.floor(eeSize / 16) if qwc % 16 ~= 0 then qwc = qwc + 1 end local blocksize = math.floor(4496/16) -- number of whole GIFTags this transfer will take local packets = math.floor(qwc / blocksize) -- plus a possible remainder local remain = qwc % blocksize local tb = 0 local imgAddr = tt.data.addr while packets > 0 do if self.buf.size - self.buf.head < 4 then self:kick() end -- for each fullsized packet, add a CNT with the GIFTag describing IMAGE -- data, followed by DMATag REF pointing to EE memory self:dmaTagRaw(DMA.CNT, 1, 0) GIF.tag(self.buf, GIF.IMAGE, blocksize, false, {}) self:dmaTagRaw(DMA.REF, blocksize, imgAddr) imgAddr = imgAddr + blocksize*16 packets = packets - 1 tb = tb + 1 end -- if there was any remainder, upload seperately if remain > 0 then if self.buf.size - self.buf.head < 4 then self:kick() end local base = tb*blocksize*16 self:dmaTagRaw(DMA.CNT, 1, 0) GIF.tag(self.buf, GIF.IMAGE, remain, false, {}) self:dmaTagRaw(DMA.REF, remain, imgAddr) end -- start a new CNT and add a texflush command self:newCnt() GIF.texflush(self.buf) return true end -- setup frame and setup drawbuffer function draw:frameStart(gs) self.kc = 0 self.rawtri = 0 self:newBuffer() self.buf:frameStart(self.fbw, self.fbh, self.clearR, self.clearG, self.clearB) end -- setup frame end, kick drawbuffer function draw:frameEnd(gs) self.buf:frameEnd(gs) self:kick() self.prev.kc = self.kc self.prev.rawtri = self.rawtri end -- set clear colour function draw:clearColour(r, g, b) self.clearR = r self.clearG = g self.clearB = b end function draw:screenDimensions(w, h) self.fbw = w self.fbh = h end return draw
local Desktop = require("Desktop"); function test_GetDesktops() local desktops = Desktop:desktopNames(); for _, name in ipairs(desktops) do print(name); end end function test_desktopwindows() local dtop = Desktop:openThreadDesktop(); local wins = dtop:getWindowHandles(); for winid, hwnd in pairs(wins) do print("HWND: ", winid, hwnd); end end test_GetDesktops(); --test_desktopwindows();
local t = Def.ActorFrame {Name = "UnderlayFile"} t[#t+1] = LoadActor(THEME:GetPathG("Title", "BG")) return t
----------------------------------- -- Ability: Aspir Samba II -- Inflicts the next target you strike with Aspir daze, allowing all those engaged in battle with it to drain its MP. -- Obtained: Dancer Level 60 -- TP Cost: 250 -- Recast Time: 00:01:00 -- Duration: 00:01:30 ----------------------------------- require("scripts/globals/status") require("scripts/globals/magic") require("scripts/globals/msg") ----------------------------------- function onAbilityCheck(player,target,ability) if player:hasStatusEffect(tpz.effect.FAN_DANCE) then return tpz.msg.basic.UNABLE_TO_USE_JA2, 0 elseif player:hasStatusEffect(tpz.effect.TRANCE) then return 0,0 elseif player:getTP() < 250 then return tpz.msg.basic.NOT_ENOUGH_TP,0 else return 0,0 end end function onUseAbility(player,target,ability) -- Only remove TP if the player doesn't have Trance. if not player:hasStatusEffect(tpz.effect.TRANCE) then player:delTP(250) end local duration = 120 + player:getMod(tpz.mod.SAMBA_DURATION) duration = duration * ((100 + player:getMod(tpz.mod.SAMBA_PDURATION)) / 100) player:delStatusEffect(tpz.effect.HASTE_SAMBA) player:delStatusEffect(tpz.effect.DRAIN_SAMBA) player:addStatusEffect(tpz.effect.ASPIR_SAMBA, 3, 0, duration) end
local self = {} GLib.Net.Layer5.Channel = GLib.MakeConstructor (self, GLib.Net.IChannel)
local table = { point = { x = 0, label = 'originPoint', z = 0, y = 0 }, i_am_boolean = true, name = 'myTable', randomNumbers = { 43, 20, 40, 40, 46, 10, 17, 39, 14, 28 } } return table
local Action = require(script.Parent.Action) return Action("StampSelectedSet", function(guid) return { guid = guid } end)
g_ConfigDefaults = { Storage = "sqlite", LoginMessageTime = 50, } function InitConfig() local Path = cPluginManager:Get():GetCurrentPlugin():GetLocalFolder() .. "/config.cfg" if (not cFile:IsFile(Path)) then LOGWARNING("[Login] The config file doesn't exist. Login will write and load the default settings for now") WriteDefaultSettings(Path) LoadDefaultSettings() return end local ConfigContent = cFile:ReadWholeFile(Path) if (ConfigContent == "") then LOGWARNING("[Login] The config file is empty. Login will use the default settings for now") LoadDefaultSettings() return end local ConfigLoader, Error = loadstring("return {" .. ConfigContent .. "}") if (not ConfigLoader) then LOGWARNING("[Login] There is a problem in the config file. Login will use the default settings for now.") LoadDefaultSettings() return end local Result, ConfigTable, Error = pcall(ConfigLoader) if (not Result) then LOGWARNING("[Login] There is a problem in the config file. Login will use the default settings for now.") LoadDefaultSettings() return end if (type(ConfigTable.Storage) ~= 'string') then LOGWARNING("[Login] Invalid storage type configurated. Login will use SQLite") ConfigTable.Storage = 'sqlite' end if (ConfigTable.Storage == "file") then if ((type(ConfigTable.CompressionLevel) ~= 'number') and (not tonumber(ConfigTable.CompressionLevel))) then LOGWARNING("[Login] Invalid compression level.") ConfigTable.CompressionLevel = 5 end ConfigTable.CompressionLevel = tonumber(ConfigTable.CompressionLevel) end if (type(ConfigTable.LoginMessageTime) ~= 'number') then if (type(ConfigTable.LoginMessageTime) == 'string') then local Time = tonumber(ConfigTable.LoginMessageTime) if (not Time) then LOGWARNING("[Login] Invalid login message time. Default will be used.") ConfigTable.LoginMessageTime = g_ConfigDefaults.LoginMessageTime else ConfigTable.LoginMessageTime = Time end else LOGWARNING("[Login] Invalid login message time. Default will be used.") ConfigTable.LoginMessageTime = g_ConfigDefaults.LoginMessageTime end end g_Config = ConfigTable end function LoadDefaultSettings() g_Config = g_ConfigDefaults end function WriteDefaultSettings(a_Path) local File = io.open(a_Path, "w") for Key, Value in pairs(g_ConfigDefaults) do local StringToFormat = type(Value) == 'string' and "%s = '%s',\n" or "%s = %s,\n" File:write(StringToFormat:format(Key, Value)) end File:close() end
local modkeys = {} modkeys.map = { ["left command"] = "cmd", ["right command"] = "cmd", ["left ctrl"] = "ctrl", ["right ctrl"] = "ctrl", ["left shift"] = "shift", ["right shift"] = "shift", ["left option"] = "option", ["right option"] = "option", ["left alt"] = "alt", ["right alt"] = "altgr", } modkeys.keys = { "cmd", "ctrl", "alt", "option", "altgr", "shift" } return modkeys
ESX = nil local PlayerData = {} local HasAlreadyEnteredMarker = false local LastZone = nil local CurrentAction = nil local CurrentActionMsg = '' local CurrentActionData = {} local isDead = false local CurrentTask = {} local menuOpen = false local wasOpen = false local pedIsTryingToChopVehicle = false local ChoppingInProgress = false local spawncamion = { x = -534.53, y = -1717.0, z = 19.12, h = 291.16 } local venta = { x = -195.04, y = 6264.96, z = 30.49} Citizen.CreateThread(function() while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) Citizen.Wait(0) end while ESX.GetPlayerData().job == nil do Citizen.Wait(10) end PlayerData = ESX.GetPlayerData() end) AddEventHandler('esx:onPlayerDeath', function(data) isDead = true end) AddEventHandler('playerSpawned', function(spawn) isDead = false end) Citizen.CreateThread(function() while true do Citizen.Wait(0) local playerPed = PlayerPedId() local coords = GetEntityCoords(playerPed) if GetDistanceBetweenCoords(coords, Config.Zones.Shop.coords, true) < 3.0 then ESX.ShowHelpNotification(_U('shop_prompt')) if IsControlJustReleased(0, 38) then wasOpen = true OpenShop() end else if wasOpen then wasOpen = false ESX.UI.Menu.CloseAll() end Citizen.Wait(500) end end end) function OpenShop() local elements = {} menuOpen = true for k, v in pairs(ESX.GetPlayerData().inventory) do local price = Config.Itemsprice[v.name] if price and v.count > 0 then table.insert(elements, { label = ('%s - <span style="color:green;">%s</span>'):format(v.label, _U('item', ESX.Math.GroupDigits(price))), name = v.name, price = price, -- menu properties type = 'slider', value = 1, min = 1, max = v.count }) end end ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'car_shop', { title = _U('shop_title'), align = 'bottom-right', elements = elements }, function(data, menu) TriggerServerEvent('esx_chatarrero:sell', data.current.name, data.current.value) exports.pNotify:SendNotification({text = "Ve a devolver el camión", type = "success", timeout = 3000, layout = "centerRight", queue = "right", animation = {open = "gta_effects_fade_in", close = "gta_effects_fade_out"}}) SetNewWaypoint(spawncamion.x,spawncamion.y) end, function(data, menu) menu.close() menuOpen = false end) end AddEventHandler('onResourceStop', function(resource) if resource == GetCurrentResourceName() then if menuOpen then ESX.UI.Menu.CloseAll() end end end) function IsDriver() return GetPedInVehicleSeat(GetVehiclePedIsIn(PlayerPedId(), false), -1) == PlayerPedId() end function MaxSeats(vehicle) local vehpas = GetVehicleNumberOfPassengers(vehicle) return vehpas end local lastTested = 0 function ChopVehicle() local ped = PlayerPedId() local vehicle = GetVehiclePedIsIn( ped, false ) local wheels = GetVehicleNumberOfWheels(vehicle) local doors = GetNumberOfVehicleDoors(vehicle) local seats = MaxSeats(vehicle) if seats ~= 0 then TriggerEvent('chat:addMessage', { args = { 'No puede haber pasajeros' } }) elseif GetGameTimer() - lastTested > Config.CooldownMinutes * 60000 then lastTested = GetGameTimer() ESX.TriggerServerCallback('esx_chatarrero:anycops', function(anycops) if anycops >= Config.CopsRequired then if Config.CallCops then local randomReport = math.random(1, Config.CallCopsPercent) if randomReport == Config.CallCopsPercent then TriggerServerEvent('chopNotify') end end ChoppingInProgress = true if wheels == 4 then if doors <= 4 then VehiclePartsRemoval1() else VehiclePartsRemoval() end else MotoPartsRemoval() end if not HasAlreadyEnteredMarker then HasAlreadyEnteredMarker = true ChoppingInProgress = false exports.pNotify:SendNotification({text = "No has dejado los chatarreros terminar.", type = "error", timeout = 4000, layout = "centerRight", queue = "right", killer = true, animation = {open = "gta_effects_fade_in", close = "gta_effects_fade_out"}}) --SetVehicleAlarmTimeLeft(vehicle, 60000) end else ESX.ShowNotification(_U('not_enough_cops')) end end) else local timerNewChop = Config.CooldownMinutes * 60000 - (GetGameTimer() - lastTested) exports.pNotify:SendNotification({ text = "Puedes volver en " ..math.floor(timerNewChop / 60000).. " minutos", type = "error", timeout = 1000, layout = "centerRight", queue = "right", killer = true, animation = {open = "gta_effects_fade_in", close = "gta_effects_fade_out"} }) end end function VehiclePartsRemoval() local ped = PlayerPedId() local vehicle = GetVehiclePedIsIn( ped, false ) SetVehicleNumberPlateText(vehicle, "Robado") SetVehicleEngineOn(vehicle, false, false, true) SetVehicleUndriveable(vehicle, false) if ChoppingInProgress == true then puerta1 = CreatePed(1, Config.NPCHash1, -557.17, -1695.32, 18.18, 300.0, false, true) SetCurrentPedWeapon(puerta1, -2067956739, true) --LoadAnimDict("timetable@gardener@filling_can") --TaskPlayAnim(puerta1, "timetable@gardener@filling_can", "gar_ig_5_filling_can", 2.0, 8.0, -1, 50, 0, 0, 0, 0) TaskStartScenarioInPlace(puerta1, "PROP_HUMAN_BUM_BIN", 0, 1) exports['progressBars']:startUI(Config.DoorOpenFrontLeftTime, "Abriendo puerta delantera izquierda") Citizen.Wait(Config.DoorOpenFrontLeftTime) SetVehicleDoorOpen(GetVehiclePedIsIn(ped, false), 0, false, false) end Citizen.Wait(1000) if ChoppingInProgress == true then exports['progressBars']:startUI(Config.DoorBrokenFrontLeftTime, "Desmontando puerta delantera izquierda") Citizen.Wait(Config.DoorBrokenFrontLeftTime) SetVehicleDoorBroken(GetVehiclePedIsIn(ped, false), 0, true) DeleteEntity(puerta1) end Citizen.Wait(1000) if ChoppingInProgress == true then puerta2 = CreatePed(1, Config.NPCHash1, -555.32, -1693.7, 18.27, 167.35, false, true) SetCurrentPedWeapon(puerta2, -2067956739, true) TaskStartScenarioInPlace(puerta2, "PROP_HUMAN_BUM_BIN", 0, 1) exports['progressBars']:startUI(Config.DoorOpenFrontRightTime, "Abriendo puerta delantera derecha") Citizen.Wait(Config.DoorOpenFrontRightTime) SetVehicleDoorOpen(GetVehiclePedIsIn(ped, false), 1, false, false) end Citizen.Wait(1000) if ChoppingInProgress == true then exports['progressBars']:startUI(Config.DoorBrokenFrontRightTime, "Desmontando puerta delantera derecha") Citizen.Wait(Config.DoorBrokenFrontRightTime) SetVehicleDoorBroken(GetVehiclePedIsIn(ped, false), 1, true) DeleteEntity(puerta2) end Citizen.Wait(1000) if ChoppingInProgress == true then puerta3 = CreatePed(1, Config.NPCHash1, -556.89, -1696.1, 18.17, 320.51, false, true) SetCurrentPedWeapon(puerta3, -2067956739, true) TaskStartScenarioInPlace(puerta3, "PROP_HUMAN_BUM_BIN", 0, 1) exports['progressBars']:startUI(Config.DoorOpenRearLeftTime, "Abriendo puerta trasera izquierda") Citizen.Wait(Config.DoorOpenRearLeftTime) SetVehicleDoorOpen(GetVehiclePedIsIn(ped, false), 2, false, false) end Citizen.Wait(1000) if ChoppingInProgress == true then exports['progressBars']:startUI(Config.DoorBrokenRearLeftTime, "Desmontando puerta trasera izquierda") Citizen.Wait(Config.DoorBrokenRearLeftTime) SetVehicleDoorBroken(GetVehiclePedIsIn(ped, false), 2, true) DeleteEntity(puerta3) end Citizen.Wait(1000) if ChoppingInProgress == true then puerta4 = CreatePed(1, Config.NPCHash1, -554.94, -1694.58, 18.25, 115.77, false, true) SetCurrentPedWeapon(puerta4, -2067956739, true) TaskStartScenarioInPlace(puerta4, "PROP_HUMAN_BUM_BIN", 0, 1) exports['progressBars']:startUI(Config.DoorOpenRearRightTime, "Abriendo puerta trasera derecha") Citizen.Wait(Config.DoorOpenRearRightTime) SetVehicleDoorOpen(GetVehiclePedIsIn(ped, false), 3, false, false) end Citizen.Wait(1000) if ChoppingInProgress == true then exports['progressBars']:startUI(Config.DoorBrokenRearRightTime, "Desmontando puerta trasera derecha") Citizen.Wait(Config.DoorBrokenRearRightTime) SetVehicleDoorBroken(GetVehiclePedIsIn(ped, false), 3, true) DeleteEntity(puerta4) TriggerServerEvent("esx_chatarrero:puerta") end Citizen.Wait(1000) if ChoppingInProgress == true then capo = CreatePed(1, Config.NPCHash1, -557.88, -1692.33, 18.27, 221.5, false, true) SetCurrentPedWeapon(capo, -2067956739, true) TaskStartScenarioInPlace(capo, "PROP_HUMAN_BUM_BIN", 0, 1) exports['progressBars']:startUI(Config.DoorOpenHoodTime, "Abriendo capó") Citizen.Wait(Config.DoorOpenHoodTime) SetVehicleDoorOpen(GetVehiclePedIsIn(ped, false), 4, false, false) end Citizen.Wait(1000) if ChoppingInProgress == true then exports['progressBars']:startUI(Config.DoorBrokenHoodTime, "Desmontando capó") Citizen.Wait(Config.DoorBrokenHoodTime) SetVehicleDoorBroken(GetVehiclePedIsIn(ped, false),4, true) DeleteEntity(capo) TriggerServerEvent("esx_chatarrero:capo") end Citizen.Wait(1000) if ChoppingInProgress == true then trunk = CreatePed(1, Config.NPCHash1, -554.51, -1697.42, 18.19, 24.23, false, true) SetCurrentPedWeapon(trunk, -2067956739, true) TaskStartScenarioInPlace(trunk, "PROP_HUMAN_BUM_BIN", 0, 1) exports['progressBars']:startUI(Config.DoorOpenTrunkTime, "Abriendo maletero") Citizen.Wait(Config.DoorOpenTrunkTime) SetVehicleDoorOpen(GetVehiclePedIsIn(ped, false), 5, false, false) end Citizen.Wait(1000) if ChoppingInProgress == true then exports['progressBars']:startUI(Config.DoorBrokenTrunkTime, "Desmontando maletero") Citizen.Wait(Config.DoorBrokenTrunkTime) DeleteEntity(trunk) SetVehicleDoorBroken(GetVehiclePedIsIn(ped, false),5, true) end Citizen.Wait(1000) exports['progressBars']:startUI(Config.DeletingVehicleTime, "Terminando de desguazar") Citizen.Wait(Config.DeletingVehicleTime) if ChoppingInProgress == true then DeleteVehicle() TriggerServerEvent("esx_chatarrero:piezas") TriggerServerEvent("esx_chatarrero:llanta") exports.pNotify:SendNotification({text = "Vehiculo desguazado, ahora coge ese camión y ve a vender las piezas. Si no quieres vender la piezas devuelve el camión", type = "success", timeout = 5000, layout = "centerRight", queue = "right", animation = {open = "gta_effects_fade_in", close = "gta_effects_fade_out"}}) Spawn() SetNewWaypoint(venta.x,venta.y) final = CreatePed(1, Config.NPCHash1, -559.57, -1690.93, 18.23, 212.5, false, true) SetCurrentPedWeapon(capo, -2067956739, true) LoadAnimDict("gestures@m@standing@casual") TaskPlayAnim(final, "gestures@m@standing@casual", "gesture_hello", 2.0, 8.0, -1, 50, 0, 0, 0, 0) Citizen.Wait(1000) DeleteEntity(final) end end function VehiclePartsRemoval1() local ped = PlayerPedId() local vehicle = GetVehiclePedIsIn( ped, false ) SetVehicleNumberPlateText(vehicle, "Robado") SetVehicleEngineOn(vehicle, false, false, true) SetVehicleUndriveable(vehicle, false) if ChoppingInProgress == true then puerta1 = CreatePed(1, Config.NPCHash1, -557.17, -1695.32, 18.18, 300.0, false, true) SetCurrentPedWeapon(puerta1, -2067956739, true) TaskStartScenarioInPlace(puerta1, "PROP_HUMAN_BUM_BIN", 0, 1) exports['progressBars']:startUI(Config.DoorOpenFrontLeftTime, "Abriendo puerta delantera izquierda") Citizen.Wait(Config.DoorOpenFrontLeftTime) SetVehicleDoorOpen(GetVehiclePedIsIn(ped, false), 0, false, false) end Citizen.Wait(1000) if ChoppingInProgress == true then exports['progressBars']:startUI(Config.DoorBrokenFrontLeftTime, "Desmontando puerta delantera izquierda") Citizen.Wait(Config.DoorBrokenFrontLeftTime) SetVehicleDoorBroken(GetVehiclePedIsIn(ped, false), 0, true) DeleteEntity(puerta1) end Citizen.Wait(1000) if ChoppingInProgress == true then puerta2 = CreatePed(1, Config.NPCHash1, -555.32, -1693.7, 18.27, 167.35, false, true) SetCurrentPedWeapon(puerta2, -2067956739, true) TaskStartScenarioInPlace(puerta2, "PROP_HUMAN_BUM_BIN", 0, 1) exports['progressBars']:startUI(Config.DoorOpenFrontRightTime, "Abriendo puerta delantera derecha") Citizen.Wait(Config.DoorOpenFrontRightTime) SetVehicleDoorOpen(GetVehiclePedIsIn(ped, false), 1, false, false) end Citizen.Wait(1000) if ChoppingInProgress == true then exports['progressBars']:startUI(Config.DoorBrokenFrontRightTime, "Desmontando puerta delantera derecha") Citizen.Wait(Config.DoorBrokenFrontRightTime) SetVehicleDoorBroken(GetVehiclePedIsIn(ped, false), 1, true) DeleteEntity(puerta2) TriggerServerEvent("esx_chatarrero:puerta2") end Citizen.Wait(1000) if ChoppingInProgress == true then capo = CreatePed(1, Config.NPCHash1, -557.88, -1692.33, 18.27, 221.5, false, true) SetCurrentPedWeapon(capo, -2067956739, true) TaskStartScenarioInPlace(capo, "PROP_HUMAN_BUM_BIN", 0, 1) exports['progressBars']:startUI(Config.DoorOpenHoodTime, "Abriendo capó") Citizen.Wait(Config.DoorOpenHoodTime) SetVehicleDoorOpen(GetVehiclePedIsIn(ped, false), 4, false, false) end Citizen.Wait(1000) if ChoppingInProgress == true then exports['progressBars']:startUI(Config.DoorBrokenHoodTime, "Desmontando capó") Citizen.Wait(Config.DoorBrokenHoodTime) SetVehicleDoorBroken(GetVehiclePedIsIn(ped, false),4, true) DeleteEntity(capo) TriggerServerEvent("esx_chatarrero:capo") end Citizen.Wait(1000) if ChoppingInProgress == true then trunk = CreatePed(1, Config.NPCHash1, -554.51, -1697.42, 18.19, 24.23, false, true) SetCurrentPedWeapon(trunk, -2067956739, true) TaskStartScenarioInPlace(trunk, "PROP_HUMAN_BUM_BIN", 0, 1) exports['progressBars']:startUI(Config.DoorOpenTrunkTime, "Abriendo maletero") Citizen.Wait(Config.DoorOpenTrunkTime) SetVehicleDoorOpen(GetVehiclePedIsIn(ped, false), 5, false, false) end Citizen.Wait(1000) if ChoppingInProgress == true then exports['progressBars']:startUI(Config.DoorBrokenTrunkTime, "Desmontando maletero") Citizen.Wait(Config.DoorBrokenTrunkTime) DeleteEntity(trunk) SetVehicleDoorBroken(GetVehiclePedIsIn(ped, false),5, true) end Citizen.Wait(1000) exports['progressBars']:startUI(Config.DeletingVehicleTime, "Terminando de desguazar") Citizen.Wait(Config.DeletingVehicleTime) if ChoppingInProgress == true then DeleteVehicle() TriggerServerEvent("esx_chatarrero:piezas") TriggerServerEvent("esx_chatarrero:llanta") exports.pNotify:SendNotification({text = "Vehiculo desguazado, ahora coge ese camión y ve a vender las piezas. Si no quieres vender la piezas devuelve el camión", type = "success", timeout = 5000, layout = "centerRight", queue = "right", animation = {open = "gta_effects_fade_in", close = "gta_effects_fade_out"}}) Spawn() SetNewWaypoint(venta.x,venta.y) final = CreatePed(1, Config.NPCHash1, -559.57, -1690.93, 18.23, 212.5, false, true) SetCurrentPedWeapon(capo, -2067956739, true) LoadAnimDict("gestures@m@standing@casual") TaskPlayAnim(final, "gestures@m@standing@casual", "gesture_hello", 2.0, 8.0, -1, 50, 0, 0, 0, 0) Citizen.Wait(1000) DeleteEntity(final) end end function MotoPartsRemoval() local ped = PlayerPedId() local vehicle = GetVehiclePedIsIn( ped, false ) SetVehicleNumberPlateText(vehicle, "Robado") SetVehicleEngineOn(vehicle, false, false, true) SetVehicleUndriveable(vehicle, false) exports['progressBars']:startUI(Config.DeletingVehicleTime, "Desguazando moto") Citizen.Wait(Config.DeletingVehicleTime) if ChoppingInProgress == true then DeleteVehicle() TriggerServerEvent("esx_chatarrero:moto") exports.pNotify:SendNotification({text = "Vehiculo desguazado, ahora coge ese camión y ve a vender las piezas. Si no quieres vender la piezas devuelve el camión", type = "success", timeout = 5000, layout = "centerRight", queue = "right", animation = {open = "gta_effects_fade_in", close = "gta_effects_fade_out"}}) Spawn() SetNewWaypoint(venta.x,venta.y) final = CreatePed(1, Config.NPCHash1, -559.57, -1690.93, 18.23, 212.5, false, true) SetCurrentPedWeapon(capo, -2067956739, true) LoadAnimDict("gestures@m@standing@casual") TaskPlayAnim(final, "gestures@m@standing@casual", "gesture_hello", 2.0, 8.0, -1, 50, 0, 0, 0, 0) Citizen.Wait(1000) DeleteEntity(final) end end function DeleteVehicle() if IsDriver() then local playerPed = PlayerPedId() local coords = GetEntityCoords(playerPed) if IsPedInAnyVehicle(playerPed, false) then local vehicle = GetVehiclePedIsIn(playerPed, false) ESX.Game.DeleteVehicle(vehicle) end --TriggerServerEvent("esx_chatarrero:rewards", rewards) end end function Spawn() Citizen.Wait(0) local myPed = GetPlayerPed(-1) local player = PlayerId() local vehicle = GetHashKey('mule3') RequestModel(vehicle) while not HasModelLoaded(vehicle) do Wait(1) end local spawned_car = CreateVehicle(vehicle, spawncamion.x,spawncamion.y,spawncamion.z, spawncamion.h, -534.53, -1717.0, 19.12, 292.16, true, false) local plate = "" SetVehicleNumberPlateText(spawned_car, plate) SetVehicleOnGroundProperly(spawned_car) SetVehicleLivery(spawned_car, 2) --SetPedIntoVehicle(myPed, spawned_car, - 1) --SetModelAsNoLongerNeeded(vehicle) Citizen.InvokeNative(0xB736A491E64A32CF, Citizen.PointerValueIntInitialized(spawned_car)) end AddEventHandler('esx_chatarrero:hasEnteredMarker', function(zone) if zone == 'Chopshop' and IsDriver() then CurrentAction = 'Chopshop' CurrentActionMsg = _U('press_to_chop') CurrentActionData = {} end end) AddEventHandler('esx_chatarrero:hasExitedMarker', function(zone) if menuOpen then ESX.UI.Menu.CloseAll() end if zone == 'Chopshop' then if ChoppingInProgress == true then exports.pNotify:SendNotification({text = "Te has alejado de los chatarreros.", type = "error", timeout = 1000, layout = "centerRight", queue = "right", killer = true, animation = {open = "gta_effects_fade_in", close = "gta_effects_fade_out"}}) end end ChoppingInProgress = false CurrentAction = nil end) function CreateBlipCircle(coords, text, radius, color, sprite) local blip = AddBlipForCoord(coords) SetBlipSprite(blip, sprite) SetBlipColour(blip, color) SetBlipScale(blip, 0.8) SetBlipAsShortRange(blip, true) BeginTextCommandSetBlipName("STRING") AddTextComponentString(text) EndTextCommandSetBlipName(blip) end Citizen.CreateThread(function() if Config.EnableBlips == true then for k,zone in pairs(Config.Zones) do CreateBlipCircle(zone.coords, zone.name, zone.radius, zone.color, zone.sprite) end end end) Citizen.CreateThread(function() if Config.NPCEnable == true then RequestModel(Config.NPCHash) RequestModel(Config.NPCHash1) while not HasModelLoaded(Config.NPCHash) do Wait(1) end --PROVIDER vendedor = CreatePed(1, Config.NPCHash, Config.NPCShop.x, Config.NPCShop.y, Config.NPCShop.z, Config.NPCShop.h, false, true) SetBlockingOfNonTemporaryEvents(vendedor, true) SetPedDiesWhenInjured(vendedor, false) SetPedCanPlayAmbientAnims(vendedor, true) SetPedCanRagdollFromPlayerImpact(vendedor, false) SetEntityInvincible(vendedor, true) FreezeEntityPosition(vendedor, true) TaskStartScenarioInPlace(vendedor, "WORLD_HUMAN_SMOKING", 0, true); else end end) -- Display markers Citizen.CreateThread(function() while true do Citizen.Wait(0) local coords, letSleep = GetEntityCoords(PlayerPedId()), true for k,v in pairs(Config.Zones) do if Config.MarkerType ~= -1 and GetDistanceBetweenCoords(coords, v.Pos.x, v.Pos.y, v.Pos.z, true) < Config.DrawDistance then DrawMarker(Config.MarkerType, v.Pos.x, v.Pos.y, v.Pos.z, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, v.Size.x, v.Size.y, v.Size.z, Config.MarkerColor.r, Config.MarkerColor.g, Config.MarkerColor.b, 100, false, true, 2, false, nil, nil, false) letSleep = false end end if letSleep then Citizen.Wait(500) end end end) -- Enter / Exit marker events Citizen.CreateThread(function() while true do Citizen.Wait(0) local coords = GetEntityCoords(PlayerPedId()) local isInMarker = false local currentZone = nil local letSleep = true for k,v in pairs(Config.Zones) do if(GetDistanceBetweenCoords(coords, v.Pos.x, v.Pos.y, v.Pos.z, true) < v.Size.x) then isInMarker = true currentZone = k end end if (isInMarker and not HasAlreadyEnteredMarker) or (isInMarker and LastZone ~= currentZone) then HasAlreadyEnteredMarker = true LastZone = currentZone TriggerEvent('esx_chatarrero:hasEnteredMarker', currentZone) end if not isInMarker and HasAlreadyEnteredMarker then HasAlreadyEnteredMarker = false TriggerEvent('esx_chatarrero:hasExitedMarker', LastZone) end end end) -- Key controls Citizen.CreateThread(function() while true do Citizen.Wait(0) if CurrentAction ~= nil then ESX.ShowHelpNotification(CurrentActionMsg) if IsControlJustReleased(0, 38) then if IsDriver() then if CurrentAction == 'Chopshop' then ChopVehicle() end end CurrentAction = nil end else Citizen.Wait(500) end end end) Citizen.CreateThread(function() while true do Citizen.Wait(1000) local ped = PlayerPedId() if IsPedInAnyVehicle(ped) then local vehicle = GetVehiclePedIsIn(ped) end end end) AddEventHandler('onResourceStop', function(resource) if resource == GetCurrentResourceName() then if menuOpen then ESX.UI.Menu.CloseAll() end end end) --Only if Config.CallCops = true GetPlayerName() RegisterNetEvent('outlawChopNotify') AddEventHandler('outlawChopNotify', function(alert) if PlayerData.job ~= nil and PlayerData.job.name == 'police' then ESX.ShowAdvancedNotification(_U('911'), _U('chop'), _U('call'), 'CHAR_CALL911', 7) PlaySoundFrontend(-1, "Event_Start_Text", "GTAO_FM_Events_Soundset", 0) end end) function Notify(text) SetNotificationTextEntry('STRING') AddTextComponentString(text) DrawNotification(false, false) end local timer = 1 --in minutes - Set the time during the player is outlaw local blipTime = 35 --in second local showcopsmisbehave = true --show notification when cops steal too local timing = timer * 60000 --Don't touche it Citizen.CreateThread(function() while true do Wait(100) if NetworkIsSessionStarted() then DecorRegister("IsOutlaw", 3) DecorSetInt(PlayerPedId(), "IsOutlaw", 1) return end end end) Citizen.CreateThread( function() while true do Wait(100) local plyPos = GetEntityCoords(PlayerPedId(), true) if pedIsTryingToChopVehicle then DecorSetInt(PlayerPedId(), "IsOutlaw", 2) if PlayerData.job ~= nil and PlayerData.job.name == 'police' and showcopsmisbehave == false then elseif PlayerData.job ~= nil and PlayerData.job.name == 'police' and showcopsmisbehave then TriggerServerEvent('ChoppingInProgressPos', plyPos.x, plyPos.y, plyPos.z) TriggerServerEvent('ChopInProgress') Wait(3000) pedIsTryingToChopVehicle = false end end end end) function LoadAnimDict(dict) if not HasAnimDictLoaded(dict) then RequestAnimDict(dict) while not HasAnimDictLoaded(dict) do Citizen.Wait(1) end end end RegisterNetEvent('Choplocation') AddEventHandler('Choplocation', function(tx, ty, tz) if PlayerData.job.name == 'police' then local transT = 250 local Blip = AddBlipForCoord(tx, ty, tz) SetBlipSprite(Blip, 10) SetBlipColour(Blip, 1) SetBlipAlpha(Blip, transT) SetBlipAsShortRange(Blip, false) while transT ~= 0 do Wait(blipTime * 4) transT = transT - 1 SetBlipAlpha(Blip, transT) if transT == 0 then SetBlipSprite(Blip, 2) return end end end end) RegisterNetEvent('chopEnable') AddEventHandler('chopEnable', function() pedIsTryingToChopVehicle = true end) Citizen.CreateThread(function() while true do Citizen.Wait(0) local coords = GetEntityCoords(PlayerPedId()) local _source = source local distance = Vdist(coords.x, coords.y, coords.z, Config.Spawn.unspawn.coords.x, Config.Spawn.unspawn.coords.y, Config.Spawn.unspawn.coords.z) if(Config.Type ~= -1 and GetDistanceBetweenCoords(coords, Config.Spawn.unspawn.coords.x, Config.Spawn.unspawn.coords.y, Config.Spawn.unspawn.coords.z, true) < 10) then local playerPed = PlayerPedId() DrawMarker(1, Config.Spawn.unspawn.coords.x, Config.Spawn.unspawn.coords.y, Config.Spawn.unspawn.coords.z, 0, 0, 0, 0, 0, 0, 1.5001, 1.5001, 0.6001,255,255,51, 200, 0, 0, 0, 0) if GetDistanceBetweenCoords(coords, Config.Spawn.unspawn.coords, true) < 1.5 then StatusReady = true if StatusReady == true then ESX.ShowHelpNotification(('Pulsa E para guardar el camión.')) end if IsControlJustReleased(1, 38) and StatusReady == true then if IsVehicleModel(GetVehiclePedIsIn(GetPlayerPed(-1), false), 0x85A5B471) then ExecuteCommand('dv') Citizen.Wait(5000) else exports.pNotify:SendNotification({text = "Este vehiculo no es el camion del trabajo", type = "error", timeout = 2000, layout = "centerRight", queue = "right", killer = true, animation = {open = "gta_effects_fade_in", close = "gta_effects_fade_out"}}) end end end end end end)
----------------------------------------------------------------------------------------- -- -- cBatiment.lua -- -- Classe qui affiche un bâtiment sur la carte et y crée un porte d'entrée -- ----------------------------------------------------------------------------------------- local Batiment = {} -- @params -- parent : Group Map, groupe parent -- img : String Fichier image du sprite du bâtiment -- x, y : Number Position du bâtiment sur la map -- destination: String Nom du bâtiment dans lequel le personnage va entrer par la porte -- porteX : Number Positionnement en x de la porte sur le bâtiment -- outline : Bool True pour que le corps physique s'ajuste à la forme du sprite, sinon le corps est un rectangle -- perso : Object Personnage du jeu, pour accéder à ses méthodes avec les cheats function Batiment:init(parent,img,x,y,destination,porteX,outline,perso) local batiment = display.newGroup() local cPorte = require("cPorte") -- Constructeur function batiment:init() local sprite = display.newImage(self,img,x,y) sprite.width= sprite.width*4 sprite.height= sprite.height*4 local imgOutline = graphics.newOutline( 2, img ) if destination ~= nil then local porte = cPorte:init(self,x+porteX,y+sprite.height/2,destination) end sprite.type = "batiment" if outline then physics.addBody( sprite, "static", { outline=imgOutline, friction=0, bounce=0} ) else physics.addBody( sprite, "static", { density=100, friction=0, bounce=0} ) end parent:insert(self) end function batiment:kill() end batiment:init() return batiment end return Batiment
local smog={} function get_min(tabl) local min, index for i, v in pairs (tabl) do if (min and (min > v)) or not min then min=v index=i end end return min, index end function get_max(tabl) local max, index -- game.print('max serp '.. serpent.line(tabl)) for i, v in pairs (tabl) do if (max and (max < v)) or not max then max=v index=i end end return max, index end function polygon_to_ts (polygon) local ts = {polygon[1], polygon[2]} local i_max = #polygon for i_min = 3, i_max do ts[#ts+1]=polygon[i_max] if i_max <= i_min then return ts end ts[#ts+1]=polygon[i_min] i_max=i_max-1 if i_max <= i_min then return ts end end return ts end function smog.pollution_to_color (pollution) local mm=settings.global['svp-min-pollution'].value -- local mm=0 local mx=settings.global['svp-max-pollution'].value local v=math.min(pollution,mx) local pct=math.max(0,v-mm)/(mx-mm) -- from 0 to 1 return {r=pct*0.3,g=pct*0.3,b=pct*0.3,a=pct*0.6} end function get_chunk_pollution (surface, cx, cy) local pollution = surface.get_pollution({cx*32,cy*32}) -- local color = {1,1,1} -- rendering.draw_text{text=pollution, surface=surface, target={cx*32+16,cy*32+16}, color=color, time_to_live=time_to_live} return pollution end function get_udata (surface, cx, cy) -- it takes pollution from this and near chunks local data = {} table.insert (data, surface.get_pollution({(cx-1)*32,(cy-1)*32})) table.insert (data, surface.get_pollution({(cx )*32,(cy-1)*32})) table.insert (data, surface.get_pollution({(cx+1)*32,(cy-1)*32})) table.insert (data, surface.get_pollution({(cx-1)*32,(cy )*32})) table.insert (data, surface.get_pollution({(cx )*32,(cy )*32})) table.insert (data, surface.get_pollution({(cx+1)*32,(cy )*32})) table.insert (data, surface.get_pollution({(cx-1)*32,(cy+1)*32})) table.insert (data, surface.get_pollution({(cx )*32,(cy+1)*32})) table.insert (data, surface.get_pollution({(cx+1)*32,(cy+1)*32})) -- translate chunk pollution to vertex pollution local udata = {} udata.a = (data[1]+data[2]+data[4]+data[5])/4 -- top left udata.b = (data[2]+data[3]+data[5]+data[6])/4 -- top right udata.c = (data[5]+data[6]+data[8]+data[9])/4 -- bottom left udata.d = (data[4]+data[5]+data[7]+data[8])/4 -- bottom right udata.e = (udata.a+udata.b+udata.c+udata.d)/4 -- middle return udata end function in_range ( value, min, max) min=min or 0 max=max or min+32 return (min<=value) and (value<=max) and true or false end function as (a, b) if not a or not b then return false end if a > 1 and b>1 then a=math.floor(a + 0.5) b=math.floor(b + 0.5) end return (math.floor (a*1000) == math.floor (b*1000)) and true or false end function remove_rendering (rendering_ids) for i, id in pairs (rendering_ids) do rendering.destroy(id) end end function get_ingex (tabl, value) for index, v in pairs (value) do if v == value then return index end end end function get_section (a, b, x) return 32*(x-a)/(b-a) end function ts_to_vertices (ts) local vertices = {} for i, point in pairs (ts) do -- game.print('point: '..serpent.line(point)) table.insert(vertices, {target={point.x,point.y}}) end -- table.insert(vertices, {target={0,0}}) -- game.print('vertices: '..serpent.line(vertices)) return vertices end --function get_position (section, u1, u2, p1, p2) -- local -- local sides = {ab="A",ba="A",bc="B",cb="B",cd="C",dc="C",da="D",ad="D"} -- local side = sides[p1..p2] -- local s = get_section (u1, u2, section) -- if side == "A" then -- return {x=s,y=0} -- elseif side == "B" then -- return {x=32,y=s} -- elseif side == "C" then -- return {x=s,y=32} -- else -- elseif side == "D" then -- return {x=0,y=s} -- end --end --function update_points (points, section, udata, t, first_line) -- local pstart = t[1] -- local ustart = udata[pstart] -- local pmiddle = first_line and t[2] or t[4] -- local umiddle = udata[pmiddle] -- local pend = t[3] -- local uend = udata[pend] -- if in_range (section, ustart, umiddle) then -- a to b -- local pos = get_position (section, ustart, umiddle, pstart, pmiddle) -- local point = {x=pos.x, y=pos.y, section=section, second=false} -- points[#points+1]=point -- else -- b to c -- local pos = get_position (section, umiddle, uend, pmiddle, pend) -- local point = {x=pos.x, y=pos.y, section=section, second=true} -- points[#points+1]=point -- end --end --function render_polygons (surface, cx, cy, points_1, points_2, t) ---- local t = {'a','b','c','d'} -- local gx, gy = cx*32, cy*32 -- local points={a={x=gx,y=gy},b={x=gx+32,y=gy},c={x=gx+32,y=gy+32},d={x=gx,y=gy+32}} -- for i = 1, #points_1 do -- local polygon = {} -- if i == 1 then -- min ---- polygon[#polygon+1]=t[1] -- polygon[#polygon+1]=points[t[1]] -- if points_1[i].second then -- fl1 = false -- polygon[#polygon+1]=points[t[2]] -- end -- polygon[#polygon+1]=points_1[i] -- polygon[#polygon+1]=points_2[i] -- if points_2[i].second then -- polygon[#polygon+1]=t[3] -- end -- local ts = polygon_to_ts (polygon) -- local vertices = ts_to_vertices (ts) -- local pollution = points_1[i].section -- local color = smog.pollution_to_color (pollution) -- game.print ('vertices: '..serpent.line(vertices)) -- local id = rendering.draw_polygon{color=color, vertices=vertices, surface=surface} -- table.insert(global.chunks[cx][cy].rendering_ids, id) -- else -- more than 1 -- polygon[#polygon+1]=points_1[i-1] -- if not (points_1[i-1].second == points_1[i].second) then -- fl1 = false -- polygon[#polygon+1]=points[t[2]] -- b -- end -- polygon[#polygon+1]=points_1[i] -- if i == #points_1 then -- max -- polygon[#polygon+1]=points[points[3]] -- end -- polygon[#polygon+1]=points_2[i] -- if not (points_2[i-1].second == points_2[i].second) then -- fl2 = false -- polygon[#polygon+1]=points[t[4]] -- d -- end -- polygon[#polygon+1]=points_2[i-1] -- local ts = polygon_to_ts (polygon) -- local vertices = ts_to_vertices (ts) -- local pollution = points_1[i].section ---- local color = {1/#points_1,1/#points_1,1/#points_1,0.5} -- local color = smog.pollution_to_color (pollution) -- local id = rendering.draw_polygon{color=color, vertices=vertices, surface=surface} -- table.insert(global.chunks[cx][cy].rendering_ids, id) -- end -- end --end --function update_trivial (surface, cx, cy, udata, pmin) -- local trivials = { -- a = {'a','b','c','d'}, -- b = {'b','c','d','a'}, -- c = {'c','d','a','b'}, -- d = {'d','a','b','c'}, -- } -- -- was a to c; t=trivials[a]; a=t[1], c=t[3] -- local t=trivials[pmin] -- t is 1 of 4 trivial fields -- local step = 6 -- local gx, gy = cx*32, cy*32 -- local minvalue = math.ceil(udata[t[1]]/step)*step -- local maxvalue = math.floor(udata[t[3]]/step)*step -- local points_1 = {} -- local points_2 = {} -- for section = minvalue, maxvalue do -- or minvalue+1, maxvalue-1 -- update_points (points_1, section, udata, t, true) -- update_points (points_2, section, udata, t, false) -- end -- if #points_1 == 0 then -- return -- end -- render_polygons (surface, cx, cy, points_1, points_2, t) --end function get_point (p1,p2,u1,u2,u) if u1 == u2 then return end -- no gradient here if u > math.max(u1,u2) or u < math.min(u1,u2) then return end -- out of range local s = (u-u1)/(u2-u1) local dx = (p2.x-p1.x) local dy = (p2.y-p1.y) return {x=p1.x+s*dx,y=p1.y+s*dy} end function draw_isolines (surface,cx,cy,level) -- local color = smog.pollution_to_color (level.u) local c = math.min(level.u, 100)/100 local w = math.max(level.u/100, 1) local color = {0,c,c, c} local x1,y1=cx*32+level.point_1.x,cy*32+level.point_1.y local x2,y2=cx*32+level.point_2.x,cy*32+level.point_2.y local id = rendering.draw_line{color=color,width=w,from={x=x1,y=y1},to={x=x2,y=y2}, surface=surface} table.insert(global.chunks[cx][cy].rendering_ids, id) end function get_polygons (surface,cx,cy,u1,u2,u3, p1,p2,p3) local polygons = {} local step = 6 local umin, umax = math.min(u1,u2,u3), math.max(u1,u2,u3) local pmin, pmax if u1 == umin then pmin = p1 elseif u2 == umin then pmin = p2 else pmin = p3 end if u1 == umax then pmax = p1 elseif u2 == umax then pmax = p2 else pmax = p3 end local from, to = math.ceil(umin/step)*step, math.floor(umax/step)*step if to == 0 or (from == to) then return end local levels = {} --actually isolines for u = from, to, step do -- game.print('u: '..u .. ' from: '..from.. 'to: '..to) local point_a = get_point (p1,p2,u1,u2,u) -- game.print('point_a: '..serpent.line(point_a)) local point_b = get_point (p2,p3,u2,u3,u) -- game.print('point_b: '..serpent.line(point_b)) local point_c = get_point (p3,p1,u3,u1,u) -- game.print('point_c: '..serpent.line(point_c)) local point_1 = point_a or point_b local point_2 = point_a and point_b or point_c local level = {u=u, point_1=point_1, point_2=point_2} draw_isolines (surface,cx,cy,level) end return polygons end function update_saddle (surface,cx,cy,udata) local triangles = {a={"a","b","e"},b={"b","c","e"},c={"c","d","e"},d={"d","a","e"}} local positions = {a={x=0,y=0},b={x=32,y=0},c={x=32,y=32},d={x=0,y=32},e={x=16,y=16}} for tr_letter, triangle in pairs (triangles) do local l1,l2,l3 = triangle[1],triangle[2],triangle[3] -- l - point letter local u1,u2,u3 = udata[l1],udata[l2],udata[l3] -- pollution value local p1,p2,p3 = positions[l1],positions[l2],positions[l3] -- position local polygons = get_polygons (surface,cx,cy,u1,u2,u3, p1,p2,p3) end end function remove_rendering_ids(chunk) if chunk.rendering_ids then remove_rendering(chunk.rendering_ids) chunk.rendering_ids = {} else chunk.rendering_ids = {} end end function update_chunk (surface, cx,cy) local chunk = global.chunks[cx][cy] local udata = get_udata(surface, cx,cy) -- game.print ('1 udata '.. serpent.line (udata)) -- local umin, pmin = get_min(udata) -- game.print ('2 udata '.. serpent.line (udata)) -- local umax, pmax = get_max(udata) if umax == 0 then return end remove_rendering_ids(chunk) update_saddle (surface,cx,cy,udata) end function smog.tick() -- no arguments in tick local surface = game.surfaces[1] local chunk = surface.get_random_chunk() local cx, cy = chunk.x, chunk.y -- chunk position local mm=settings.global['svp-min-pollution'].value local mx=settings.global['svp-max-pollution'].value if not global.chunks then global.chunks = {} end if not global.chunks[cx] then global.chunks[cx] = {} end if not global.chunks[cx][cy] then global.chunks[cx][cy] = {} end update_chunk(surface, cx, cy) end script.on_event(defines.events.on_tick, smog.tick)
local name, ns = ... local L = ns.L function ravNameplates_OnLoad(self) self:RegisterEvent("ADDON_LOADED") self:RegisterEvent("PLAYER_ENTERING_WORLD") end function ravNameplates_OnEvent(_, event, arg) if arg == name then if event == "ADDON_LOADED" then if not RAVN_version then ns:PrettyPrint(string.format(L.Install, ns.color, ns.version)) elseif RAVN_version ~= ns.version then ns:PrettyPrint(string.format(L.Update, ns.color, ns.version)) end if not RAVN_version or RAVN_version ~= ns.version then print(string.format(L.InstallUpdate, ns.color)) end RAVN_version = ns.version end elseif event == "PLAYER_ENTERING_WORLD" then ns:EnsureMacro() end end SlashCmdList["RAVNAMEPLATES"] = function(message) if message == "version" or message == "v" then ns:PrettyPrint(string.format(L.Version, ns.version)) elseif message == "help" or message == "h" then ns:PrettyPrint(L.SupportHeading) print(string.format(L.Support1, ns.color, ns.name)) print(L.Support2) elseif UnitAffectingCombat("player") then RaidNotice_AddMessage(RaidWarningFrame, L.Warning, ChatTypeInfo["RAID_WARNING"]) else ns:Toggle() end end SLASH_RAVNAMEPLATES1 = "/ravn" SLASH_RAVNAMEPLATES2 = "/ns" SLASH_RAVNAMEPLATES3 = "/ravenousnameplates"
local M = {} M.__index = M function M.new() local o = { machine = nil, type = 0, agent = nil, weight = 0, duration = 0, time = 0, speed = 1, isdone =false, iscancel = false, ispause = false, } return setmetatable(o, M) end function M:setmachine(machine) self.machine = machine self.agent = machine.agent end function M:setpause(pause) if self.ispause and pause ==false then self:resume() elseif self.ispause ==false and pause then self:pause() end self.ispause = pause end function M:done() self.isdone = true self.iscancel = self.time < self.duration end function M:isvalid() return true end function M:call(name,...) if self.agent ~= nil then local func = self.agent[name] if func ~= nil then func(self.agent, self, ...) end end end function M:enter() self:call("enter") end function M:execute(delta) if self.time < self.duration then self.time = self.time + delta * self.speed if self.time >= self.duration then self:done() end end self:call("execute",delta) end function M:exit() self:call("exit") end function M:pause() self:call("pause") end function M:resume() self:call("resume") end function M:cancel() self:call("cancel") end function M:destroy() self:call("destroy") end return M
local osmose = require 'osmose' local et = osmose.Model 'HPSteamGenerator' local cp = require 'coolprop' local math = require 'math' local invcostcalc = require 'equipmentcost.InvestmentCostLinearizator' ---------- -- User parameters ---------- et.inputs = { -- Heat supply HPSTEAM_T = {default=150, unit='C'}, QMAX = {default=10000, unit='kW'}, HEATSOURCE_TMAX = {default=330, unit='C'}, -- Only used for the calculation of the investment cost HEATSOURCE_TMIN = {default=160, unit='C'}, -- Only used for the calculation of the investment cost U_GLOB = {default = 25, unit='W/m^2/K'}, -- From EngineeringToolbox.com, [10-40] for boiling liquid water-free convection gas, only used for the calculation of the investment cost -- Electricity consumption (for pumping/maintain pressure) --EL_SPEC = {default=0.01, unit='kWh_el/kWh_th'} } ----------- -- Calculated parameters ----------- et.outputs = { MLTD = {unit='C', job= function() local output = ((HEATSOURCE_TMAX - HPSTEAM_T) - (HEATSOURCE_TMIN - HPSTEAM_T)) / math.log((HEATSOURCE_TMAX - HPSTEAM_T)/(HEATSOURCE_TMIN - HPSTEAM_T)) return output end }, HPSTEAM_P = {unit='bar',job= function() local temperature = HPSTEAM_T + 273.15 local p_eva = cp.PropsSI('P','T',temperature,'Q',1,'WATER') local output = p_eva / 100000 return output end }, -- Calculating the investment cost. -- Since the area is the value that works as reference, we need to make an assumption on the global heat exchange coefficient. This is assumed to be equal to 2000 W/m2K INV_FIX = {unit='CHF',job= function() local x0_area = QMAX/10 * 1000 / MLTD() / U_GLOB -- Assuming U_glob = 2000 W/m2K and MLTD = 600 K local x0_vector = {'SS' , x0_area , HPSTEAM_P()} -- Assuming Stainless steal as material, and 7 bar as operating pressure local cost_function = "cost_evaporator_long_tube" local temp = invcostcalc.InvestmentCostLinearizator(cost_function,x0_vector,2,'TM') local output = temp.Cinv1 return output end }, INV_VAR = {unit='CHF',job= function() local x0_area = QMAX/10 * 1000 / MLTD() / U_GLOB -- Assuming U_glob = 2000 W/m2K and MLTD = 600 K local x0_vector = {'SS' , x0_area , HPSTEAM_P()} -- Assuming Stainless steal as material, and 7 bar as operating pressure local cost_function = "cost_evaporator_long_tube" local temp = invcostcalc.InvestmentCostLinearizator(cost_function,x0_vector,2,'TM') local output = temp.Cinv2 * 1000 / MLTD() / U_GLOB return output end }, } ----------- -- Layers ----------- et:addLayers {HPSteam = {type= 'ResourceBalance', unit = 'kW'} } et:addLayers {Electricity = {type= 'ResourceBalance', unit = 'kW'} } ----------- -- Units ----------- et:addUnit('HPSteamGenerator',{type='Utility', Fmin = 0, Fmax = 1, Cost1=0, Cost2=0, Cinv1='INV_FIX', Cinv2='INV_VAR', Power1=0, Power2=0, Impact1=0,Impact2=0}) et['HPSteamGenerator']:addStreams{ -- Input heat qt_hp_steam_gen = qt({tin = 'HPSTEAM_T', hin = 0, tout='HPSTEAM_T', hout='QMAX', stype='evap'}), -- Steam network hpsteam_out = rs({'HPSteam', 'out', 'QMAX'}), } return et
--------------------------------- -- GLOBAL VARIABLES --------------------------------- local MIN_REFRESH_VBATT = 0.2 local REFRESH_FREQUENCY_2S = 200 local LIPO_CELL = 3.7 local LIPO_CELL_LOW = 3.5 local LIPO_CELL_MAX = 4.2 local LIPO_DELTA = LIPO_CELL_MAX - LIPO_CELL_LOW --------------------------------- -- VARIABLES --------------------------------- local batt local battVolt local showBattVoltage local cellCount local layoutEngine local function init(radio) batt = 0 battVolt = 0 showBattVoltage = false cellCount = 0 layoutEngine = loadScript("/SCRIPTS/TELEMETRY/RESOURCEPOOL/widgets/battery-" .. radio .. ".lua")() end -- Detect Lipo Cell count local function detectCellCount(vfas) local limit = LIPO_CELL_MAX if not vfas then return 0 end if vfas < limit + 0.5 then return 1 end if vfas < limit * 2 + 0.5 then return 2 end if vfas < limit * 3 + 0.5 then return 3 end if vfas < limit * 4 + 0.5 then return 4 end if vfas < limit * 5 + 0.5 then return 5 end if vfas < limit * 6 + 0.5 then return 6 end return 0 end local function shouldRefresh(lastTimeSinceRedraw) -- Redraw only every 2 seconds if lastTimeSinceRedraw < REFRESH_FREQUENCY_2S then return false end local newBattVolt = getValue("VFAS") -- Refresh Battery Level if showBattVoltage then showBattVoltage = false else showBattVoltage = true end battVolt = newBattVolt cellCount = detectCellCount(battVolt) batt = 0 if cellCount > 0 then batt = math.max(0, (battVolt - LIPO_CELL_LOW * cellCount) * 100 / (LIPO_DELTA * cellCount)) end return true end local function layout() layoutEngine.layout(batt) end local function redraw() layoutEngine.redraw(showBattVoltage, batt, battVolt) end return { tag = "battery", init = init, layout = layout, redraw = redraw, shouldRefresh = shouldRefresh }
function Creature.getClosestFreePosition(self, position, maxRadius, mustBeReachable) maxRadius = maxRadius or 1 -- backward compatability (extended) if maxRadius == true then maxRadius = 2 end local checkPosition = Position(position) for radius = 0, maxRadius do checkPosition.x = checkPosition.x - math.min(1, radius) checkPosition.y = checkPosition.y + math.min(1, radius) local total = math.max(1, radius * 8) for i = 1, total do if radius > 0 then local direction = math.floor((i - 1) / (radius * 2)) checkPosition:getNextPosition(direction) end local tile = Tile(checkPosition) if tile:getCreatureCount() == 0 and not tile:hasProperty(CONST_PROP_IMMOVABLEBLOCKSOLID) and (not mustBeReachable or self:getPathTo(checkPosition)) then return checkPosition end end end return Position() end function Creature.getPlayer(self) return self:isPlayer() and self or nil end function Creature.isContainer(self) return false end function Creature.isItem(self) return false end function Creature.isMonster(self) return false end function Creature.isNpc(self) return false end function Creature.isPlayer(self) return false end function Creature.isTeleport(self) return false end function Creature.isTile(self) return false end function Creature:setMonsterOutfit(monster, time) local monsterType = MonsterType(monster) if not monsterType then return false end if self:isPlayer() and not (self:hasFlag(PlayerFlag_CanIllusionAll) or monsterType:isIllusionable()) then return false end local condition = Condition(CONDITION_OUTFIT) condition:setOutfit(monsterType:getOutfit()) condition:setTicks(time) self:addCondition(condition) return true end function Creature:setItemOutfit(item, time) local itemType = ItemType(item) if not itemType then return false end local condition = Condition(CONDITION_OUTFIT) condition:setOutfit({ lookTypeEx = itemType:getId() }) condition:setTicks(time) self:addCondition(condition) return true end function Creature:addSummon(monster) local summon = Monster(monster) if not summon then return false end summon:setTarget(nil) summon:setFollowCreature(nil) summon:setDropLoot(false) summon:setSkillLoss(false) summon:setMaster(self) return true end function Creature:removeSummon(monster) local summon = Monster(monster) if not summon or summon:getMaster() ~= self then return false end summon:setTarget(nil) summon:setFollowCreature(nil) summon:setDropLoot(true) summon:setSkillLoss(true) summon:setMaster(nil) return true end function Creature:addDamageCondition(target, type, list, damage, period, rounds) if damage <= 0 or not target or target:isImmune(type) then return false end local condition = Condition(type) condition:setParameter(CONDITION_PARAM_OWNER, self:getId()) condition:setParameter(CONDITION_PARAM_DELAYED, true) if list == DAMAGELIST_EXPONENTIAL_DAMAGE then local exponent, value = -10, 0 while value < damage do value = math.floor(10 * math.pow(1.2, exponent) + 0.5) condition:addDamage(1, period or 4000, -value) if value >= damage then local permille = math.random(10, 1200) / 1000 condition:addDamage(1, period or 4000, -math.max(1, math.floor(value * permille + 0.5))) else exponent = exponent + 1 end end elseif list == DAMAGELIST_LOGARITHMIC_DAMAGE then local n, value = 0, damage while value > 0 do value = math.floor(damage * math.pow(2.718281828459, -0.05 * n) + 0.5) if value ~= 0 then condition:addDamage(1, period or 4000, -value) n = n + 1 end end elseif list == DAMAGELIST_VARYING_PERIOD then for _ = 1, rounds do condition:addDamage(1, math.random(period[1], period[2]) * 1000, -damage) end elseif list == DAMAGELIST_CONSTANT_PERIOD then condition:addDamage(rounds, period * 1000, -damage) elseif list == DAMAGELIST_OMEGA_LUL then condition:addDamage(20, 1000, -damage*100) end target:addCondition(condition) return true end
local snownet = require "snownet" local cluster = require "snownet.cluster" require "snownet.manager" -- inject snownet.forward_type local node, address = ... snownet.register_protocol { name = "system", id = snownet.PTYPE_SYSTEM, unpack = function (...) return ... end, } local forward_map = { [snownet.PTYPE_SNAX] = snownet.PTYPE_SYSTEM, [snownet.PTYPE_LUA] = snownet.PTYPE_SYSTEM, [snownet.PTYPE_RESPONSE] = snownet.PTYPE_RESPONSE, -- don't free response message } snownet.forward_type( forward_map ,function() local clusterd = snownet.uniqueservice("clusterd") local n = tonumber(address) if n then address = n end snownet.dispatch("system", function (session, source, msg, sz) if session == 0 then snownet.send(clusterd, "lua", "push", node, address, msg, sz) else snownet.ret(snownet.rawcall(clusterd, "lua", snownet.pack("req", node, address, msg, sz))) end end) end)
require('paths') require('nngraph') -- require('cunn') require('optim') paths.dofile('params.lua') paths.dofile('utils.lua') paths.dofile('layers/Normalization.lua') torch.setdefaulttensortype('torch.FloatTensor') g_make_deterministic(123) -- load the data trdata = paths.dofile('data.lua') tedata = paths.dofile('data.lua') trdata:load(trfiles, opt.batchsize, opt.T) tedata:load(tefiles, opt.batchsize, trdata.memsize, trdata.dict, trdata.idict) -- split into train and validation sets nquestions = trdata.questions:size(1) train_range = torch.range(1, math.floor(0.9*nquestions)) val_range = torch.range(math.floor(0.9*nquestions) + 1, nquestions) -- set some parameters based on the dataset opt.nwords = #trdata.idict opt.winsize = trdata.memory:size(3) if opt.tied == 1 then opt.memslots = trdata.entities:size(1) print('tying keys to entities -> ' .. opt.memslots .. ' memory slots') end -- build the model and loss paths.dofile(opt.model .. '.lua') model = build_model(opt) print('\nmodel: ' .. paths.basename(opt.modelFilename)) print('#params = ' .. model.paramx:size(1)) function train() local train_err = {} local train_cost = {} local val_err = {} optstate = {learningRate = opt.sdt} for ep = 1, opt.epochs do if ep % opt.sdt_decay_step == 0 and opt.sdt_decay_step ~= -1 then optstate.learningRate = optstate.learningRate / 2 end model:zeroNilToken() if opt.dropout > 0 then model:setDropout('train') end local total_err, total_cost, total_num = 0, 0, 0 local nBatches = math.floor(train_range:size(1)/opt.batchsize) for k = 1, nBatches do xlua.progress(k, nBatches) local err, cost local feval = function () local batch = train_range:index(1, torch.randperm(train_range:size(1)):sub(1, opt.batchsize):long()) local question, answer, story = trdata:getBatch(batch) err, cost = model:fprop(question, answer, story, graph) model:bprop(question, answer, story, sdt) return cost, model.paramdx end optimize(feval, model.paramx, optstate) model:zeroNilToken() total_cost = total_cost + cost total_err = total_err + err total_num = total_num + opt.batchsize if k % 10 == 0 then collectgarbage() collectgarbage() end end train_err[ep] = total_err / total_num train_cost[ep] = total_cost / total_num val_err[ep] = evaluate('valid') local log_string = 'epoch = ' .. ep .. ' | train cost = ' .. g_f4(train_cost[ep]) .. ' | train err = ' .. g_f4(train_err[ep]) .. ' | valid err = ' .. g_f4(val_err[ep]) .. ' | lr = ' .. optstate.learningRate print(log_string) collectgarbage() end return val_err[opt.epochs], train_err, val_err end function evaluate(split, display) if opt.dropout > 0 then model:setDropout('test') end local total_err, total_cost, total_num = 0, 0, 0 local N, indx if split == 'train' then N = train_range:size(1) indx = train_range data = trdata elseif split == 'valid' then N = val_range:size(1) indx = val_range data = trdata elseif split == 'test' then N = tedata.questions:size(1) indx = torch.range(1, N) data = tedata end local loss = torch.Tensor(N) for k = 1, math.floor(N/opt.batchsize) do local batch = indx:index(1, torch.range(1 + (k-1)*opt.batchsize, k*opt.batchsize):long()) local question, answer, story, facts, graph = data:getBatch(batch) local err, cost, missed = model:fprop(question, answer, story, graph) total_cost = total_cost + cost total_err = total_err + err total_num = total_num + opt.batchsize end return total_err / total_num end final_perf_train = {} final_perf_val = {} final_perf_test = {} weights = {} for i = 1, opt.runs do print('--------------------') print('RUN ' .. i) print('--------------------') -- reset the weights g_make_deterministic(i) model:reset() -- train final_perf_val[i] = train() final_perf_train[i] = evaluate('train') final_perf_test[i] = evaluate('test') weights[i] = model.paramx:clone() print('test error = ' .. g_f4(final_perf_test[i])) print('val err') print(final_perf_val) print('test err') print(final_perf_test) if opt.save ~= '' then local log_string = 'run ' .. i .. ' | train error = ' .. g_f4(final_perf_train[i]) .. ' | valid error = ' .. g_f4(final_perf_val[i]) .. ' | test error = ' .. g_f4(final_perf_test[i]) write(opt.modelFilename .. '.log', log_string) torch.save(opt.modelFilename .. '.model', {final_perf_val = final_perf_val, final_perf_test = final_perf_test, model = model, optstate = optstate, weights = weights}) end if final_perf_val[i] == 0 then -- we will pick this run and don't need more break end end -- pick test error based on validation performance _, best = torch.Tensor(final_perf_val):min(1) if opt.save ~= '' then write(opt.modelFilename .. '.log', 'final test error = ' .. final_perf_test[best[1]]) torch.save(opt.modelFilename .. '.model', {final_perf_val = final_perf_val, final_perf_test = final_perf_test, model = model, optstate = optstate, weights = weights}) end
-- This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild -- -- This file is compatible with Lua 5.3 local class = require("class") require("kaitaistruct") local stringstream = require("string_stream") EosExceptionU4 = class.class(KaitaiStruct) function EosExceptionU4:_init(io, parent, root) KaitaiStruct._init(self, io) self._parent = parent self._root = root or self self:_read() end function EosExceptionU4:_read() self._raw_envelope = self._io:read_bytes(6) local _io = KaitaiStream(stringstream(self._raw_envelope)) self.envelope = EosExceptionU4.Data(_io, self, self._root) end EosExceptionU4.Data = class.class(KaitaiStruct) function EosExceptionU4.Data:_init(io, parent, root) KaitaiStruct._init(self, io) self._parent = parent self._root = root or self self:_read() end function EosExceptionU4.Data:_read() self.prebuf = self._io:read_bytes(3) self.fail_int = self._io:read_u4le() end