content
stringlengths
5
1.05M
ys = ys or {} ys.Battle.BattleTorpedoUnit = class("BattleTorpedoUnit", ys.Battle.BattleWeaponUnit) ys.Battle.BattleTorpedoUnit.__name = "BattleTorpedoUnit" ys.Battle.BattleTorpedoUnit.Ctor = function (slot0) slot0.Battle.BattleTorpedoUnit.super.Ctor(slot0) end ys.Battle.BattleTorpedoUnit.TriggerBuffOnFire = function (slot0) slot0._host:TriggerBuff(slot0.Battle.BattleConst.BuffEffectType.ON_TORPEDO_FIRE, { equipIndex = slot0._equipmentIndex }) end ys.Battle.BattleTorpedoUnit.TriggerBuffWhenSpawn = function (slot0, slot1) slot0._host:TriggerBuff(slot0.Battle.BattleConst.BuffEffectType.ON_BULLET_CREATE, slot2) slot0._host:TriggerBuff(slot0.Battle.BattleConst.BuffEffectType.ON_TORPEDO_BULLET_CREATE, { _bullet = slot1, equipIndex = slot0._equipmentIndex }) end return
--------------------------------------------- -- Blood Drain -- Steals an enemy's HP. Ineffective against undead. --------------------------------------------- require("scripts/globals/monstertpmoves") require("scripts/globals/settings") require("scripts/globals/status") --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0 end function onMobWeaponSkill(target, mob, skill) local dmgmod = 1 local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*2,tpz.magic.ele.DARK,dmgmod,TP_MAB_BONUS,1) local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,tpz.attackType.MAGICAL,tpz.damageType.DARK,MOBPARAM_IGNORE_SHADOWS) skill:setMsg(MobPhysicalDrainMove(mob, target, skill, MOBDRAIN_HP, dmg)) return dmg end
__g_module_function__ = {} __g_function_name__ = {} __g_all_processer_request__ = {} __g_result_value_to_name__ = {} function require_ex( _mname ) if package.loaded[_mname] then print( string.format("require_ex module[%s] reload", _mname)) end package.loaded[_mname] = nil return require( _mname ) end function AddModule(name,bm) __g_module_function__[name] = bm end function BuildRequestList() for module_name, funcs in pairs(__g_module_function__) do for func_name, func_info in pairs(funcs) do local id = pb.enum(module_name,func_name) __g_function_name__[id] = func_name __g_all_processer_request__[id] = func_info; end end end function LoadResultValue() Succeed = pb.enum('Base.ResultType','Succeed') Error = pb.enum('Base.ResultType','Error') Warning = pb.enum('Base.ResultType','Warning') Retry = pb.enum('Base.ResultType','Retry') Invalid = pb.enum('Base.ResultType','Invalid') __g_result_value_to_name__[Succeed] = 'Succeed' __g_result_value_to_name__[Error] = 'Error' __g_result_value_to_name__[Warning] = 'Warning' __g_result_value_to_name__[Retry] = 'Retry' __g_result_value_to_name__[Invalid] = 'Invalid' end Init = function( path ) package.path = string.format('%s;%s/?.lua;%s/librarys/?.lua',package.path,path,path) package.cpath = string.format('%s;%s/?.so;%s/librarys/?.so',package.cpath,path,path) pb = require "pb" assert(pb.loadfile(path .. "/protobuf/base.pb")) assert(pb.loadfile(path .. "/protobuf/processer.pb")) JSON = (assert(loadfile(path .. '/librarys/json.lua')))() assert(require_ex('comm'),'load comm lua file failed.') assert(require_ex('main'),'load main lua file failed.') BuildRequestList() LoadResultValue() end OnError = function( msg ) print('error proc:' .. tostring(msg)); end SocketCloseProcess = function( u) Info("socket closed") end ProgressMessage = function( funcid, uinfo, str_req, str_extend ) local func_info = __g_all_processer_request__[funcid]; local func_name = __g_function_name__[funcid] or '' Info('Call process function : ' .. func_name ); local result,resmsg if type(func_info[1]) == 'function' then local req_table = nil local res_table = {} if #func_info[2] > 0 then req_table = assert(pb.decode(func_info[2],str_req)) end result,errmsg = func_info[1]( uinfo, req_table, res_table ); if result == Succeed and #func_info[3]>0 then resmsg = assert(pb.encode(func_info[3], res_table)) else resmsg = errmsg end else result = Error resmsg = string.format('not find the processer. the name is %s.' ,func_name); end Info( string.format('Function [%s] << [%s]', func_name, __g_result_value_to_name__[result] )) return result,resmsg end
local classes = require('../classes') local base = require('./base') local Channel = require('./Channel') local constants = require('../constants') local User = classes.new(base) function User:__constructor () self.servers = classes.Cache() end function User:sendMessage (...) if not self.channel then local data = self.parent.rest:request( { method = 'POST', path = constants.rest.endPoints.ME_DMS, data = { recipient_id = self.id, }, } ) if not data then return end self.channel = Channel(self) self.channel:update(data) self.parent.__channels:add(self.channel) end return self.channel:sendMessage(...) end return User
data:extend({ -- Speed { type = "recipe", name = "speed-module-4", enabled = false, ingredients = { {"speed-module-3", 5}, {"advanced-circuit", 10}, {"processing-unit", 10} }, energy_required = 120, result = "speed-module-4" }, { type = "recipe", name = "speed-module-5", enabled = false, ingredients = { {"speed-module-4", 5}, {"advanced-circuit", 15}, {"processing-unit", 15} }, energy_required = 240, result = "speed-module-5" }, { type = "recipe", name = "speed-module-6", enabled = false, ingredients = { {"speed-module-5", 5}, {"advanced-circuit", 15}, {"processing-unit", 15} }, energy_required = 480, result = "speed-module-6" }, -- Productivity { type = "recipe", name = "productivity-module-4", enabled = false, ingredients = { {"productivity-module-3", 5}, {"advanced-circuit", 10}, {"processing-unit", 10} }, energy_required = 120, result = "productivity-module-4" }, { type = "recipe", name = "productivity-module-5", enabled = false, ingredients = { {"productivity-module-4", 5}, {"advanced-circuit", 15}, {"processing-unit", 15} }, energy_required = 240, result = "productivity-module-5" }, { type = "recipe", name = "productivity-module-6", enabled = false, ingredients = { {"productivity-module-5", 5}, {"advanced-circuit", 15}, {"processing-unit", 15} }, energy_required = 480, result = "productivity-module-6" }, -- Effectivity { type = "recipe", name = "effectivity-module-4", enabled = false, ingredients = { {"effectivity-module-3", 5}, {"advanced-circuit", 10}, {"processing-unit", 10} }, energy_required = 120, result = "effectivity-module-4" }, { type = "recipe", name = "effectivity-module-5", enabled = false, ingredients = { {"effectivity-module-4", 5}, {"advanced-circuit", 15}, {"processing-unit", 15} }, energy_required = 240, result = "effectivity-module-5" }, { type = "recipe", name = "effectivity-module-6", enabled = false, ingredients = { {"effectivity-module-5", 5}, {"advanced-circuit", 15}, {"processing-unit", 15} }, energy_required = 480, result = "effectivity-module-6" }, -- Speed-effectivity { type = "recipe", name = "speed-effectivity-module", enabled = false, ingredients = { {"advanced-circuit", 2}, {"electronic-circuit", 2}, {"speed-module", 1}, {"effectivity-module", 1} }, energy_required = 10, result = "speed-effectivity-module" }, { type = "recipe", name = "speed-effectivity-module-2", enabled = false, ingredients = { {"advanced-circuit", 3}, {"electronic-circuit", 3}, {"speed-module-2", 1}, {"effectivity-module-2", 1} }, energy_required = 20, result = "speed-effectivity-module-2" }, { type = "recipe", name = "speed-effectivity-module-3", enabled = false, ingredients = { {"advanced-circuit", 4}, {"electronic-circuit", 4}, {"speed-module-3", 1}, {"effectivity-module-3", 1}, {"processing-unit", 1} }, energy_required = 30, result = "speed-effectivity-module-3" }, { type = "recipe", name = "speed-effectivity-module-4", enabled = false, ingredients = { {"advanced-circuit", 5}, {"electronic-circuit", 5}, {"speed-module-4", 1}, {"effectivity-module-4", 1}, {"processing-unit", 2} }, energy_required = 40, result = "speed-effectivity-module-4" }, { type = "recipe", name = "speed-effectivity-module-5", enabled = false, ingredients = { {"advanced-circuit", 6}, {"electronic-circuit", 6}, {"speed-module-5", 1}, {"effectivity-module-5", 1}, {"processing-unit", 3} }, energy_required = 50, result = "speed-effectivity-module-5" }, { type = "recipe", name = "speed-effectivity-module-6", enabled = false, ingredients = { {"advanced-circuit", 7}, {"electronic-circuit", 7}, {"speed-module-6", 1}, {"effectivity-module-6", 1}, {"processing-unit", 3} }, energy_required = 60, result = "speed-effectivity-module-6" }, -- Productivity-effectivity { type = "recipe", name = "productivity-effectivity-module", enabled = false, ingredients = { {"advanced-circuit", 2}, {"electronic-circuit", 2}, {"productivity-module", 1}, {"effectivity-module", 1} }, energy_required = 10, result = "productivity-effectivity-module" }, { type = "recipe", name = "productivity-effectivity-module-2", enabled = false, ingredients = { {"advanced-circuit", 3}, {"electronic-circuit", 3}, {"productivity-module-2", 1}, {"effectivity-module-2", 1} }, energy_required = 20, result = "productivity-effectivity-module-2" }, { type = "recipe", name = "productivity-effectivity-module-3", enabled = false, ingredients = { {"advanced-circuit", 4}, {"electronic-circuit", 4}, {"productivity-module-3", 1}, {"effectivity-module-3", 1}, {"processing-unit", 1} }, energy_required = 30, result = "productivity-effectivity-module-3" }, { type = "recipe", name = "productivity-effectivity-module-4", enabled = false, ingredients = { {"advanced-circuit", 5}, {"electronic-circuit", 5}, {"productivity-module-4", 1}, {"effectivity-module-4", 1}, {"processing-unit", 2} }, energy_required = 40, result = "productivity-effectivity-module-4" }, { type = "recipe", name = "productivity-effectivity-module-5", enabled = false, ingredients = { {"advanced-circuit", 6}, {"electronic-circuit", 6}, {"productivity-module-5", 1}, {"effectivity-module-5", 1}, {"processing-unit", 3} }, energy_required = 50, result = "productivity-effectivity-module-5" }, { type = "recipe", name = "productivity-effectivity-module-6", enabled = false, ingredients = { {"advanced-circuit", 7}, {"electronic-circuit", 7}, {"productivity-module-6", 1}, {"effectivity-module-6", 1}, {"processing-unit", 3} }, energy_required = 60, result = "productivity-effectivity-module-6" }, -- Speed-productivity { type = "recipe", name = "speed-productivity-module", enabled = false, ingredients = { {"advanced-circuit", 2}, {"electronic-circuit", 2}, {"speed-module", 1}, {"productivity-module", 1} }, energy_required = 10, result = "speed-productivity-module" }, { type = "recipe", name = "speed-productivity-module-2", enabled = false, ingredients = { {"advanced-circuit", 3}, {"electronic-circuit", 3}, {"speed-module-2", 1}, {"productivity-module-2", 1} }, energy_required = 20, result = "speed-productivity-module-2" }, { type = "recipe", name = "speed-productivity-module-3", enabled = false, ingredients = { {"advanced-circuit", 4}, {"electronic-circuit", 4}, {"speed-module-3", 1}, {"productivity-module-3", 1}, {"processing-unit", 1} }, energy_required = 30, result = "speed-productivity-module-3" }, { type = "recipe", name = "speed-productivity-module-4", enabled = false, ingredients = { {"advanced-circuit", 5}, {"electronic-circuit", 5}, {"speed-module-4", 1}, {"productivity-module-4", 1}, {"processing-unit", 2} }, energy_required = 40, result = "speed-productivity-module-4" }, { type = "recipe", name = "speed-productivity-module-5", enabled = false, ingredients = { {"advanced-circuit", 6}, {"electronic-circuit", 6}, {"speed-module-5", 1}, {"productivity-module-5", 1}, {"processing-unit", 3} }, energy_required = 50, result = "speed-productivity-module-5" }, { type = "recipe", name = "speed-productivity-module-6", enabled = false, ingredients = { {"advanced-circuit", 7}, {"electronic-circuit", 7}, {"speed-module-6", 1}, {"productivity-module-6", 1}, {"processing-unit", 3} }, energy_required = 60, result = "speed-productivity-module-6" } })
local saws = {}; local sawTimer = nil; local saw3SliderJoint = scene:getJoints("saw3_slider_joint")[1]; local saw6SliderJoint = scene:getJoints("saw6_slider_joint")[1]; local spike1Joint = scene:getJoints("spike1_joint")[1]; local spike4Joint = scene:getJoints("spike4_joint")[1]; local spike6Joint = scene:getJoints("spike6_joint")[1]; local saw7Slider = nil; local doorMoves = {}; local function stoneDoorMove(jointName, upper, tremor) local j = scene:getJoints(jointName)[1]; local snd = nil; if doorMoves[jointName] ~= nil then snd = doorMoves[jointName].snd; cancelTimeout(doorMoves[jointName].cookie); doorMoves[jointName] = nil; end if (upper and j:getJointTranslation() >= j.upperLimit) or (not upper and j:getJointTranslation() <= j.lowerLimit) then if snd ~= nil then snd:stop(); snd = nil; scene.camera:findCameraComponent():tremor(false); end return; end doorMoves[jointName] = {}; if (snd == nil) and tremor then doorMoves[jointName].snd = audio:createSound("stone_moving.ogg"); doorMoves[jointName].snd:play(); scene.camera:findCameraComponent():tremorStart(0.3); else if (not tremor) and (snd ~= nil) then snd:stop(); snd = nil; scene.camera:findCameraComponent():tremor(false); end doorMoves[jointName].snd = snd; end if upper then j.motorSpeed = math.abs(j.motorSpeed); else j.motorSpeed = -math.abs(j.motorSpeed); end doorMoves[jointName].cookie = addTimeout0(function(cookie, dt, args) if (upper and j:getJointTranslation() >= j.upperLimit) or (not upper and j:getJointTranslation() <= j.lowerLimit) then cancelTimeout(cookie); if tremor then doorMoves[jointName].cookie = addTimeoutOnce(0.2, function() doorMoves[jointName].snd:stop(); doorMoves[jointName] = nil; scene.camera:findCameraComponent():tremor(false); end); else doorMoves[jointName] = nil; end end end); end local function loopPrismatic(j) if (j:getJointTranslation() >= j.upperLimit) then j.motorSpeed = -math.abs(j.motorSpeed); elseif (j:getJointTranslation() <= j.lowerLimit) then j.motorSpeed = math.abs(j.motorSpeed); end end local function loopSpike(j, direct) if j.myMotorSpeed == nil then j.myMotorSpeed = math.abs(j.motorSpeed); end if (j:getJointTranslation() >= j.upperLimit) then if direct then j.motorSpeed = -j.myMotorSpeed / 4; else j.motorSpeed = -j.myMotorSpeed; end elseif (j:getJointTranslation() <= j.lowerLimit) then if direct then j.motorSpeed = j.myMotorSpeed; else j.motorSpeed = j.myMotorSpeed / 4; end end end local function enableSaws() for _, obj in pairs(saws) do obj.active = true; end sawTimer = addTimeout0(function(cookie, dt) loopPrismatic(saw3SliderJoint); loopPrismatic(saw6SliderJoint); loopSpike(spike1Joint, true); loopSpike(spike4Joint, true); loopSpike(spike6Joint, false); end); end local function disableSaws() for _, obj in pairs(saws) do obj.active = false; end cancelTimeout(sawTimer); end -- main for i = 1, 6, 1 do local saw = scene:getObjects("saw"..i)[1]; saw.type = const.SceneObjectTypeEnemyBuilding; table.insert(saws, saw); end for i = 8, 11, 1 do local saw = scene:getObjects("saw"..i)[1]; saw.type = const.SceneObjectTypeEnemyBuilding; table.insert(saws, saw); end for i = 1, 6, 1 do local spike = scene:getObjects("spike"..i)[1]; spike.type = const.SceneObjectTypeEnemyBuilding; table.insert(saws, spike); end table.insert(saws, scene:getObjects("saw3_slider")[1]); table.insert(saws, scene:getObjects("saw4_slider")[1]); table.insert(saws, scene:getObjects("saw5_slider")[1]); table.insert(saws, scene:getObjects("saw4_holder")[1]); table.insert(saws, scene:getObjects("saw6_slider")[1]); table.insert(saws, scene:getObjects("saw9_slider")[1]); setSensorListener("saw_activate_cp", function(other, self) if self.timer ~= nil then cancelTimeout(self.timer); self.timer = nil; else enableSaws(); end end, function (other, self) if other:scene() ~= nil then scene.respawnPoint = scene:getObjects("saw0_cp")[1]:getTransform(); end self.timer = addTimeoutOnce(5.0, function() disableSaws(); self.timer = nil; end); end, { timer = nil }); setSensorEnterListener("saw0_cp", false, function(other) if not isAmbient then startAmbientMusic(true); end end); setSensorEnterListener("saw1_cp", false, function(other) scene.respawnPoint = scene:getObjects("saw1_cp")[1]:getTransform(); setupBgMetal(); if isAmbient then startMusic("action4.ogg", true); end end); setSensorEnterListener("saw2_cp", false, function(other) setupBgAir(); end); setSensorEnterListener("saw3_cp", false, function(other, self) if self.obj == nil then scene.respawnPoint = scene:getObjects("saw3_cp")[1]:getTransform(); stoneDoorMove("door10_joint", true, true); end if self.obj ~= other then if self.obj ~= nil then setupBgAir(); end if self.sawObjs ~= nil then for _, obj in pairs(self.sawObjs) do local c = obj:findPhysicsBodyComponent(); if c ~= nil then c:removeFromParent(); end obj:addComponent(FadeOutComponent(1.0)); end end local sawObjs = scene:instanciate("e1m2_saw7.json", scene:getObjects("saw7_ph")[1]:getTransform()).objects; for _, obj in pairs(sawObjs) do obj.type = const.SceneObjectTypeEnemyBuilding; if obj.name == "saw7_slider" then saw7Slider = obj; end end local saw7path = scene:getObjects("saw7_path")[1]; saw7Slider.roamBehavior:reset(); saw7Slider.roamBehavior.linearVelocity = 5.0; saw7Slider.roamBehavior.linearDamping = 3.0; saw7Slider.roamBehavior.dampDistance = 5.0; saw7Slider.roamBehavior.changeAngle = false; saw7Slider.roamBehavior:changePath(saw7path:findPathComponent().path, saw7path:getTransform()); saw7Slider.roamBehavior:start(); self.sawObjs = sawObjs; end self.obj = other; end, { obj = nil, sawObjs = nil }); setSensorListener("saw4_cp", function(other, self) stoneDoorMove("door11_joint", true, true); end, function (other, self) stoneDoorMove("door11_joint", false, false); end); makeGear("spike1", "spike1_joint", "spike2", "spike2_joint", -1); makeGear("spike1", "spike1_joint", "spike3", "spike3_joint", 1); setSensorListener("saw5_cp", function(other, self) stoneDoorMove("door12_joint", true, true); end, function (other, self) stoneDoorMove("door12_joint", false, false); end); makeGear("spike4", "spike4_joint", "spike5", "spike5_joint", 1); setSensorListener("saw6_cp", function(other, self) stoneDoorMove("saw9_slider_joint", true, false); saw7Slider.roamBehavior.linearVelocity = 10.0; end, function (other, self) stoneDoorMove("saw9_slider_joint", false, false); end); setSensorEnterListener("saw7_cp", false, function(other) setupBgMetal(); end); setSensorEnterListener("saw8_cp", true, function(other) scene.respawnPoint = scene:getObjects("saw8_cp")[1]:getTransform(); stoneDoorMove("door9_joint", true, true); end); setSensorEnterListener("saw9_cp", true, function(other) scene:getObjects("ga4")[1]:findGoalAreaComponent():addGoal(scene:getObjects("red_door")[1].pos); end);
match_reward_layout_2= { name="match_reward_layout_2",type=0,typeName="View",time=0,x=0,y=0,width=1280,height=720,visible=1,nodeAlign=kAlignTopLeft,fillParentWidth=1,fillParentHeight=1, { name="contentBg",type=0,typeName="Image",time=103127199,x=0,y=0,width=497,height=358,nodeAlign=kAlignCenter,visible=1,fillParentWidth=0,fillParentHeight=0,file="games/common/popup_bg.png", { name="rewardListView",type=0,typeName="ListView",time=103128227,x=0,y=0,width=64,height=64,nodeAlign=kAlignTopLeft,visible=1,fillParentWidth=0,fillParentHeight=0,fillTopLeftX=10,fillBottomRightX=10,fillBottomRightY=2,fillTopLeftY=52 }, { name="topView",type=0,typeName="View",time=110025677,x=0,y=0,width=64,height=50,nodeAlign=kAlignTop,visible=1,fillParentWidth=1,fillParentHeight=0, { name="title",type=4,typeName="Text",time=58516441,report=0,x=0,y=0,width=1,height=40,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=22,textAlign=kAlignCenter,colorRed=255,colorGreen=254,colorBlue=162,string=[[比赛奖励]] }, { name="line",type=0,typeName="Image",time=110025803,x=0,y=0,width=483,height=2,nodeAlign=kAlignBottom,visible=1,fillParentWidth=1,fillParentHeight=0,file="games/common/popup_line.png",fillTopLeftX=5,fillBottomRightX=5,fillTopLeftY=48,fillBottomRightY=0 } } } } return match_reward_layout_2;
--[[ This script is under MIT license For more details, please read this https://github.com/Bilal2453/Chapter-Genrator/blob/master/LICENSE For instructions about using this plugin https://github.com/Bilal2453/Chapter-Genrator/blob/master/readme TODO: Support chapter merging on MacOS & Linux -- ?BUG: Does '?data/automation/include/' directory exists on MacOS? Can't tell... -- If not, please open an issue on github ]] script_name = "Chapters Generator" script_namespace = "Bilal2453.Chapters-Generator" script_description= "Generates Video's Chapters Using Aegisub's Timeline." script_version = '2.5.1' script_author = "Bilal Bassam, Bilal2453@github.com" script_modified = "14 March 2020" local settingsCheckboxes = {} local dp = aegisub.decode_path local mkvmergePath = dp'?data/automation/include/mkvmerge.exe' local mkvpropeditPath = dp'?data/automation/include/mkvpropedit.exe' local function fileExists(path) return io.open(path, 'r') and true or false end local function escapePath(path) if jit.os == "Windows" then return path:gsub('/', '\\\\'):gsub('\\', '\\\\') else return path:gsub('/', '\\/') end end -- I might remove this function, it isn't really needed local function newChapter(startTime, endTime, cpString, flaghidden, lang) local tO = type(startTime) == 'table' return { endTime = tO and startTime.endTime or endTime, cpString = tO and startTime.cpString or cpString, lang = tO and startTime.lang or lang, flaghidden = tO and startTime.flaghidden or flaghidden, startTime = tO and startTime.startTime or startTime, } end local function hTime(time) if not time then return '' end local hours, mins, secs, ms hours= math.floor((time / 1000) / 3600) mins = math.floor((time / 1000 % 3600) / 60) secs = math.floor((time / 1000) % 60) ms = math.floor((time % 1000)) return ('%02i:%02i:%02i.%03i'):format(hours, mins, secs, ms) end local function OGMAssembler(num, time, name) time = hTime(time) if type(num) == 'table' then time = hTime(num.startTime) name = num.cpString num = num.num end return ("CHAPTER%02i=%s\nCHAPTER%02iNAME=%s\n"):format(num, time, num, name) end local function XMLAssembler(obj) local endTime = obj.endTime > obj.startTime and hTime(obj.endTime) endTime = endTime and ('\n\t\t\t<ChapterTimeEnd>%s</ChapterTimeEnd>'):format(endTime) or '' local startTime = hTime(obj.startTime) local cpString = obj.cpString or '' local lang = type(obj.lang) == 'string' and obj.lang or 'und' local flaghidden = obj.flaghidden and 1 or 0 return ("\n\t\t<ChapterAtom>\n\t\t\t<ChapterTimeStart>%s</ChapterTimeStart>%s\n\t\t\t<ChapterFlagHidden>%d</ChapterFlagHidden>\n\t\t\t<ChapterDisplay>\n\t\t\t\t<ChapterString>%s</ChapterString>\n\t\t\t\t<ChapterLanguage>%s</ChapterLanguage>\n\t\t\t</ChapterDisplay>\n\t\t</ChapterAtom>") :format(startTime, endTime, flaghidden, cpString, lang) end --------------------------------- local sett = {} sett.path = dp('?user/ChapterGen.settings') function sett.createSettFile() if not io.open(sett.path, 'r') then io.open(sett.path, 'w'):close() return true end return false end function sett.readSett(sel) if sett.createSettFile() then return {} end local file = io.open(sett.path, 'r') local s = file:read('*a'); file:close(); local data = {} for i, v in s:gmatch('(.-)%s*=%s*(.-)\n') do data[i] = v end return (sel and data[sel]) or (not sel and data) end function sett.readBol(sel) if not settingsCheckboxes[sel] then return end -- No settings were found local results = sett.readSett(sel) return (results and results ~= 'false') or (not results and settingsCheckboxes[sel].value) end function sett.writeSett(d) sett.createSettFile() local ldat = sett.readSett() local file = io.open(sett.path, 'w') for i, v in pairs(d) do if v == 'nil' then v = nil end if i and i ~= '' then ldat[i] = v end end for i, v in pairs(ldat) do file:write(i..' = '.. tostring(v)..'\n') end file:close() end -- Remove old settings files, so some updates can take effect if sett.readSett('lastUsedVersion') ~= script_version then -- Old versions were using these paths os.remove(dp('?user/ChapterGen.setting')) os.remove(dp('?user/ChapterGen.config')) os.remove(dp('?user/config/ChapterGen.setting')) -- Delete default settings file and re-create it os.remove(sett.path) sett.createSettFile() sett.writeSett{lastUsedVersion = script_version} end --------- --------- local function parseInput(tx) local options = { flaghidden = 'boolean', lang = 'string', } local oInput = {} for n, v in tx:gmatch('%-(.-):%s*(.-)%-') do -- Uhh, this is ugly... -- TODO: Better input handling if options[n] then if tonumber(v) and options[n] == 'boolean' then oInput[n] = tonumber(v) == 1 or tonumber(v) == 0 and false elseif tonumber(v) and options[n] == 'number' then oInput[n] = tonumber(v) elseif options[n] == 'string' and not tonumber(v) then oInput[n] = v else error_dialog("Invalid value '%s' for argument '%s'\nvalue type must be a %s", v, n, options[n]..' (1 or 0)') end else error_dialog('Unknown Argument "%s"', n) end end return oInput end local function OGMWriter(lines) local str = '' local obj for i, line in ipairs(lines) do obj = newChapter(line) obj.num = i str = str.. OGMAssembler(obj) end return str end local function XMLWriter(lines) local str = ('<?xml version="1.0"?>\n<!-- <!DOCTYPE Chapters SYSTEM "matroskachapters.dtd"> -->\n<Chapters>\n\t<EditionEntry>') for _, line in ipairs(lines) do str = str.. XMLAssembler(newChapter(line)) end return str.. '\n\t</EditionEntry>\n</Chapters>' end --------- --------- -- All supported extensions local extensions = { ['.txt (OGG/OGM)'] = { writer = OGMWriter, GUIText = "OGG/OGM text (.txt)|.txt|All Files (.)|.", ext = ".txt", }, ['.xml (Matroska Chapters)'] = { writer = XMLWriter, GUIText = "Matroska Chapters (.xml)|.xml|All Files (.)|.", ext = ".xml", }, } extensions.allNames = (function() local s = {} for i,_ in pairs(extensions) do table.insert(s, i) end return table.sort(s) or s end)() extensions.getAt = function(n) return extensions[extensions.allNames[n]] end local function createCheckbox(name, label, hint, defaultValue) name, label, hint = name or #settingsCheckboxes+1, tostring(label), tostring(hint) local self = {label = label, hint = hint, value = defaultValue and defaultValue} settingsCheckboxes[name] = self end createCheckbox('ignoreValidityRules', 'Ignore Validity Rules', "This option Makes the Plug-in Treat all Lines as they had 'chapter' Written inside the Effect Field and as they're Comments.\n\nRecommended when Using Aegisub only for Chapters without Subtitles.", true) createCheckbox('useSelectedLines', 'Use Selected Lines', "This would Make the Plug-in Use Selected Lines when there's and Ignores everything else.\n\nBy Default it Doesn't Ignore validity Rules.") createCheckbox('deleteLinesAfterExport', 'Delete Lines After Exporting', "This will Delete Chapter Lines that have been Used after Exporting the Chapters.\n\nTo Restore Deleted Lines, Undo Changes.") createCheckbox('saveLastUsedPath', 'Remember Last Used Path', "Saves the Last Directory You Used to Export the Chapters, Also Saves the Last Used 'Extension'.", true) createCheckbox('ignoreEndTime', 'Ignore End Time', "Don't Use End Time, So only Start Time would be Used and Written.\n\nUseful when Using 'XML/Matroska extension.'", true) createCheckbox('askBeforeConverting', 'Ask Before Convert to MKV', "Asks you to Convert non-supported Videos to MKV before Merging Start.\nNote that only MKV Videos Can have Chapters\n\nUncheck this Box to Convert Videos without Asking.", true) function show_export_ext(sel) local db = sett.readSett('dialogExtentionBehavior') if db and db:match('".*"$') then return true, {dropdown = db:match('"(.-)"$')} end local lastUsedExt = sett.readSett('lastUsedExt') local dialog = { {class = "label", label = "File extension: ", x = 1}, dropMenu = { class = "dropdown", name = "dropdown", items = extensions.allNames, value = (sel or extensions[lastUsedExt] and lastUsedExt) or extensions.allNames[1], x = 2, } } return aegisub.dialog.display(dialog, {"&Save", "&Cancel"}, {save = "&Save", cancel = "&Cancel"}) end function info_dialog(tx, buttons, ...) local args = {...} args = #args < 1 and {''} or args buttons = buttons or {close = "Close"} tx = tx and tostring(tx) or "Unknown Error" tx = string.format(tx, table.unpack(args)) local txSt = '' for i in tx:gmatch('[^\n]+') do txSt = txSt..i..string.rep(' ', 6)..'\n' end tx = txSt; txSt = nil; local dialogT = { label = { class = "label", label = tx, x = 1, } } local buttonsNames = {} for _, n in pairs(buttons) do table.insert(buttonsNames, n) end return aegisub.dialog.display(dialogT, buttonsNames, buttons) end function error_dialog(tx, ...) info_dialog(tx, ...) aegisub.cancel() end function settings_gui() local db = sett.readSett('dialogExtentionBehavior') local gui = { {class='label',label='Chapter Extention Dialog Behavior',x=1,y=0}, dialogExtentionBehavior = { name = 'dialogExtentionBehavior', class = 'dropdown', items = {'Always Ask'}, hint = "Always Ask: Always Ask about the Chapter's Extension before Exporting.\nOther Values: Never Ask, Use the Chosen Value Instead.", x = 1, y = 1, } } -- Set extensions names as values (for the dropmenu) for _, q in ipairs(extensions.allNames) do table.insert(gui.dialogExtentionBehavior.items, q) end gui.dialogExtentionBehavior.value = extensions[db] and db or 'Always Ask' -- Merge 'GUI' table with 'settingsCheckboxes' table local i = 4 for q, v in pairs(settingsCheckboxes) do v.name, v.class = q, "checkbox" v.x, v.y = 1, i - 1 v.value = sett.readBol(v.name) v.label = ' '.. v.label table.insert(gui, v) i = i + 1 end return aegisub.dialog.display(gui) end --------- --------- local function setLastUsedPath(path, ext) if sett.readBol('saveLastUsedPath') then if type(path) == 'string' then sett.writeSett { lastUsedPath = path:gsub('(.+%p).-%..+', '%1'), lastUsedName = path:gsub('.+%p(.-)%..+', '%1'), } end if extensions[ext].ext then sett.writeSett { lastUsedExt = ext, } end end end local function getFileExt(path) return path:match('.+(%..-)$'):lower() end local function isExtSupported(ext) local supEx = "*.mkv;*.mp4;*.m4v;*.ts;*.m2ts;*.mts;*.ogg;*.ogm;*.ogv;*.webm;*.webmv;*.mpv;*.mpg;*.mpeg;*.m1v;*.m2v;*.evo;*.evob;*.vob;*.rmvb;*.avi;*.mov;*.3gp;*.flac;*.flv"; for exten in supEx:gmatch('%*(%..-);') do if exten:lower() == tostring(ext):lower():match('(%..-)$') then return true end end return (ext and false) or (not ext and supEx) -- if ext is nil return all supported exts end local function executeMKVTools(tool, ...) tools = {['mkvmerge'] = mkvmergePath, ['mkvpropedit'] = mkvpropeditPath} tool, tools = tools[tool], tool -- Change 'tools' to the name of the tool if not fileExists(tool) then return false, ("%s Is Missing\nPlease Make sure %s does Exists at 'automation/include/' then Try again"):format(tools,tools) end local args = {...}; args = type(args[1]) == "table" and args[1] or args local jsonPath = dp('?temp/%s-flags.json'):format(tools) local jsonFile = io.open(jsonPath, "w") jsonFile:write('[\n') for i, v in ipairs(args) do jsonFile:write('\t"'..escapePath(v)..'"'..(i == #args and '\n' or ',\n')) end jsonFile:write(']') jsonFile:close() local success, errMesg, errCode = os.execute(('"%s" @%s'):format(tool, jsonPath)) if not success then return false, errMesg, errCode end success, errMesg = os.remove(jsonPath) if not success then aegisub.debug.out('Warning: Attempt to remove a temporary file:\n'.. jsonPath.. '\n'.. errMesg.. '\n\n') end return true end local function mkvmerge(...) return executeMKVTools('mkvmerge', ...) end local function mkvpropedit(...) return executeMKVTools('mkvpropedit', ...) end local function convertVideoToMKV(sourcePath, targetPath) if getFileExt(sourcePath) == '.mkv' then return false, "The Video is already .MKV !!" end sourcePath = tostring(sourcePath) or "" targetPath = targetPath or sourcePath:gsub('%..-$', '.mkv') local success, err, code = mkvmerge{sourcePath, "--compression", "-1:none", "-o", targetPath} if not success then return success, err, code else return success, targetPath end end local function generateChapterFile(lines, selected, targetPath, ext) local cLines = {} local iLines = {} local iTable local useSelectedLines = sett.readBol('useSelectedLines') local ignoreValidityRules = sett.readBol('ignoreValidityRules') local ignoreEndTime = sett.readBol('ignoreEndTime') if useSelectedLines then selected.n = #selected -- A table with holes... what a great idea ! for i, v in ipairs(selected) do selected[i] = nil; selected[v] = true end end -- Filtering sub lines for i, v in ipairs(lines) do if v.class == "dialogue" and (ignoreValidityRules or (v.comment and v.effect:lower():find("chapter"))) and (useSelectedLines and (selected.n > 1 and selected[i] or selected.n <= 1) or not useSelectedLines) then -- Create a (similar) chapter object iTable = { cpString = v.text, startTime= v.start_time, endTime = ignoreEndTime and v.start_time or v.end_time, } -- Handle additional user inputs for k, n in pairs(parseInput(v.effect:lower())) do iTable[k] = n end table.insert(cLines, iTable) table.insert(iLines, i) end end if #cLines < 1 then return false, "No Chapters were found, Are you sure you aren't drunk ?" end local tData = extensions[ext].writer(cLines) -- Write the chapter file local file = io.open(targetPath, 'wb') if not file then return false, "Cannot Create the Chapter File\nPlease try Choosing another Directory for the File." end file:write(tData) file:close() -- Delete filtered Lines if user chooses to if sett.readBol('deleteLinesAfterExport') then lines.delete(iLines) end return tData end local function exportChapterToVideo(lines, selected, videoSource, ext) if not fileExists(mkvpropeditPath) then return false, "mkvpropedit Is Missing\nPlease Make sure mkvpropedit does Exists at 'automation/include/' then Try again" end if not isExtSupported(videoSource) then return false, ("Cannot Convert %s Video to .MKV (Matroska) Video.\nPlease Convert the Video to MKV then Try Again."):format(getFileExt(videoSource):upper()) end if getFileExt(videoSource) ~= ".mkv" then local s = sett.readBol("askBeforeConverting") local b = s and info_dialog("The video isn't .MKV (Matroska).\nTo process the Video with chapters the Video has to be a Matroska.\nThe Plug-in will Create a copy of the Video and Convert it to Matroska.\n\nDo you want to Convert the Video to Matroska ?\n(NOTE: Processing time depends on the Video and on your Computer's processor.)", {yes = "Convert", cancel = "Cancel"}) if (not b and s) or b == "Cancel" then aegisub.cancel() elseif not s or b then local success, videoOrErr, code = convertVideoToMKV(videoSource) if not success then return success, 'Error: '..tostring(videoOrErr)..'\nError code: '..tostring(code) end videoSource = videoOrErr end end local tmpChapPath = dp('?temp/tmp_chapter'..extensions[ext].ext) local s, e = generateChapterFile(lines, selected, tmpChapPath, ext) if not s then return false, e end local success, err, code = mkvpropedit{videoSource, "--chapters", tmpChapPath} if not success then aegisub.debug.out("Error: Merging Failed !\nPlease make sure that you have all required permissions and the video's extension is actually supported\n") aegisub.debug.out("If you can't fix this issue, please report it on github at 'Bilal2453/Chapter-Generator'\n") aegisub.debug.out('Status: '..tostring(err)..' | '.. 'Error Code: '..tostring(code)..' | mkvpropedit: '..tostring(fileExists(mkvpropeditPath))..'\n\n') end s, e = os.remove(tmpChapPath) if not s then aegisub.debug.out('Warning: Attempt to remove a temporary file: '.. tmpChapPath.. '\n'.. e.. '\n') end return success, tostring(err).. '\nError Code: '.. tostring(code) end --------- --------- function macro_export_as(lines, selectedLines) local rSett = sett.readSett() local b, data = show_export_ext() if not b then aegisub.cancel() end local chapterExt = extensions[data.dropdown] and extensions[data.dropdown].ext local saveFile = aegisub.dialog.save("Export Chapter", rSett.lastUsedPath or '', rSett.lastUsedName or 'Chapter', chapterExt or extensions.getAt(1).ext) if not saveFile then aegisub.cancel() end setLastUsedPath(saveFile, data.dropdown) local s, err = generateChapterFile(lines, selectedLines, saveFile, data.dropdown) if not s then error_dialog(err) end end function macro_export_to_video(lines, selectedLines) local button, ext = show_export_ext() if not button then aegisub.cancel() end ext = ext.dropdown local videoSource = aegisub.dialog.open('Choose a video...', sett.readSett('lastUsedPath') or '', '', 'All supported videos|'..isExtSupported()..';*;', false, true) if not videoSource then aegisub.cancel() end setLastUsedPath(nil, ext) local success, mesg = exportChapterToVideo(lines, selectedLines, videoSource, ext) if not success then error_dialog(mesg) end end function macro_export_to_opened_video(lines, selectedLines) local button, chapterExt = show_export_ext() if not button then aegisub.cancel() end chapterExt = chapterExt.dropdown setLastUsedPath(nil, chapterExt) local videoSource = aegisub.project_properties()['video_file'] if not videoSource then error_dialog("Cannot get Video's Path... believe me Aegisub is weird !\nTechniclly, it's impossible to get this Error, So Please Report This at github.com/Bilal2453/Chapter-Generator") end local supported = isExtSupported(videoSource) if not supported then error_dialog("Unsupported videos' extension.\nPlease, Convert the Video to MKV then Try Again.") end local success, mesg = exportChapterToVideo(lines, selectedLines, videoSource, chapterExt) if not success then error_dialog(mesg) end end function macro_change_settings() local button, data = settings_gui() if not button then aegisub.cancel() end sett.writeSett(data) -- Remove old used paths data if not sett.readBol('saveLastUsedPath') then sett.writeSett{ lastUsedPath = 'nil', lastUsedName = 'nil', lastUsedExt = 'nil', } end end --------- --------- function is_video_opened() local p = aegisub.project_properties() if not p.video_file or p.video_file == '' or p.video_file:find("?dummy") then return false else return true end end aegisub.register_macro(script_name..'/Export/Export As...', "Exports Chapters as a File.", macro_export_as) aegisub.register_macro(script_name..'/Export/Export To Video...', "Exports Chapters directly to a Video.", macro_export_to_video) aegisub.register_macro(script_name..'/Export/Export To Opened Video...', "Exports Chapters directly to the Opened Video.", macro_export_to_opened_video, is_video_opened) aegisub.register_macro(script_name..'/Settings/Plugin Configs', 'Configure Plug-in Behavior.', macro_change_settings)
MODULE.Name = "Network" MODULE.Libraries = { "NazaraCore" } MODULE.OsFiles.Windows = { "../src/Nazara/Network/Win32/**.hpp", "../src/Nazara/Network/Win32/**.cpp" } MODULE.OsFiles.Posix = { "../src/Nazara/Network/Posix/**.hpp", "../src/Nazara/Network/Posix/**.cpp" } MODULE.OsFiles.Linux = { "../src/Nazara/Network/Linux/**.hpp", "../src/Nazara/Network/Linux/**.cpp" } MODULE.OsFilesExcluded.Linux = { "../src/Nazara/Network/Posix/SocketPollerImpl.hpp", "../src/Nazara/Network/Posix/SocketPollerImpl.cpp" } MODULE.OsLibraries.Windows = { "ws2_32" }
require "x_functions"; if not x_requires then -- Sanity check. If they require a newer version, let them know. timer = 1; while (true) do timer = timer + 1; for i = 0, 32 do gui.drawbox( 6, 28 + i, 250, 92 - i, "#000000"); end; gui.text( 10, 32, string.format("This Lua script requires the x_functions library.")); gui.text( 53, 42, string.format("It appears you do not have it.")); gui.text( 39, 58, "Please get the x_functions library at"); gui.text( 14, 69, "http://xkeeper.shacknet.nu/"); gui.text(114, 78, "emu/nes/lua/x_functions.lua"); warningboxcolor = string.format("%02X", math.floor(math.abs(30 - math.fmod(timer, 60)) / 30 * 0xFF)); gui.drawbox(7, 29, 249, 91, "#ff" .. warningboxcolor .. warningboxcolor); FCEU.frameadvance(); end; else x_requires(4); end; while true do pixel(0, 0, "clear"); for i = 0, 0x0C do v = memory.readbyte(0x00A3 + i); if (v > 0x80) then v = v - 0x80; lifebar( 8, 8 + i * 8, 0x1C * 2, 4, v, 0x1C, "#ffffff", "#000000"); text(68, 8 + i * 8, string.format("%2X", v)); end; end; FCEU.frameadvance(); end;
local PATH = (...):gsub('%.[^%.]+$', '') local Component = require(PATH .. '.component') local StateMachine = Component:extend() function StateMachine:new() StateMachine.super.new(self) self.states = {} end function StateMachine:add(name, state) self.states[name] = state if not self.initial then self.initial = state end end function StateMachine:switch(name) local newState = self.states[name] if not newState then log.error('no state named', name) return end if self.current then self.current:leave() end self.current = newState self.current:enter() end function StateMachine:gobAdded(gob) StateMachine.super.gobAdded(self, gob) if not self.current then self.current = self.initial self.current:enter() end end function StateMachine:update(dt) StateMachine.super.update(self, dt) -- log.debug('update') local transitionTo = self.current:update(dt) if transitionTo then local nextState = self.states[transitionTo] if nextState then self.current:leave() self.current = nextState self.current:enter() end end end function StateMachine:draw() StateMachine.super.draw(self) if not self.current then return end self.current:draw() end function StateMachine:isInState(name) return self.current == self.states[name] end function StateMachine:__tostring() return 'StateMachine' end return StateMachine
local ControllerAction = require('Action.ControllerAction') local PlayTransitionAction = class('PlayTransitionAction', ControllerAction) function PlayTransitionAction:enter(controller) local trans = controller.parent:getTransition(self.transitionName) if trans ~= nil then if self._currentTransition ~= nil and self._currentTransition.playing then trans:changePlayTimes(self.playTimes) else trans:play(self.playTimes, self.delay) end self._currentTransition = trans end end function PlayTransitionAction:leave(controller) if self.stopOnExit and self._currentTransition ~= nil then self._currentTransition:stop() self._currentTransition = nil end end function PlayTransitionAction:setup(buffer) PlayTransitionAction.super.setup(self, buffer) self.transitionName = buffer:readS() self.playTimes = buffer:readInt() self.delay = buffer:readFloat() self.stopOnExit = buffer:readBool() end return PlayTransitionAction
--[[ This addon designed to be as lightweight as possible. It will only track, Mine, Herb, Fish, Gas and some Treasure nodes. This mods whole purpose is to be lean, simple and feature complete. ]] -- Mixin AceEvent local GatherMate = LibStub("AceAddon-3.0"):NewAddon("GatherMate2","AceConsole-3.0","AceEvent-3.0") local L = LibStub("AceLocale-3.0"):GetLocale("GatherMate2",false) _G["GatherMate2"] = GatherMate GatherMate.HBD = LibStub("HereBeDragons-2.0") local HBDMigrate = LibStub("HereBeDragons-Migrate") local WoWClassic = (WOW_PROJECT_ID == WOW_PROJECT_CLASSIC) -- locals local db, gmdbs, filter local reverseTables = {} -- defaults for storage local defaults = { profile = { scale = 1.0, miniscale = 0.75, alpha = 1, show = { ["Treasure"] = "always", ["Logging"] = "active", ["*"] = "with_profession" }, showMinimap = true, showWorldMap = true, worldMapIconsInteractive = true, minimapTooltips = true, filter = { ["*"] = { ["*"] = true, }, }, trackColors = { ["Herb Gathering"] = {Red = 0, Green = 1, Blue = 0, Alpha = 1}, ["Fishing"] = {Red = 1, Green = 1, Blue = 0, Alpha = 1}, ["Mining"] = {Red = 1, Green = 0, Blue = 0, Alpha = 1}, ["Extract Gas"] = {Red = 0, Green = 1, Blue = 1, Alpha = 1}, ["Treasure"] = {Red = 1, Green = 0, Blue = 1, Alpha = 1}, ["Archaeology"] = {Red = 1, Green = 1, Blue = 0.5, Alpha = 1}, ["Logging"] = {Red = 0, Green = 0.8, Blue = 1, Alpha = 1}, ["*"] = {Red = 1, Green = 0, Blue = 1, Alpha = 1}, }, trackDistance = 100, trackShow = "always", nodeRange = true, cleanupRange = { ["Herb Gathering"] = 15, ["Fishing"] = 15, ["Mining"] = 15, ["Extract Gas"] = 50, ["Treasure"] = 15, ["Archaeology"] = 10, ["Logging"] = 20, }, dbLocks = { ["Herb Gathering"] = false, ["Fishing"] = false, ["Mining"] = false, ["Extract Gas"] = false, ["Treasure"] = false, ["Archaeology"] = false, ["Logging"] = false, }, importers = { ["*"] = { ["Style"] = "Merge", ["Databases"] = {}, ["lastImport"] = 0, ["autoImport"] = false, ["bcOnly"] = false, }, } }, } local floor = floor local next = next --[[ Setup a few databases, we sub divide namespaces for resetting/importing :OnInitialize() is called at ADDON_LOADED so savedvariables are loaded ]] function GatherMate:OnInitialize() self.db = LibStub("AceDB-3.0"):New("GatherMate2DB", defaults, "Default") self.db.RegisterCallback(self, "OnProfileChanged", "OnProfileChanged") self.db.RegisterCallback(self, "OnProfileCopied", "OnProfileChanged") self.db.RegisterCallback(self, "OnProfileReset", "OnProfileChanged") -- Setup our saved vars, we dont use AceDB, cause it over kills -- These 4 savedvars are global and doesnt need char specific stuff in it GatherMate2HerbDB = GatherMate2HerbDB or {} GatherMate2MineDB = GatherMate2MineDB or {} GatherMate2FishDB = GatherMate2FishDB or {} GatherMate2TreasureDB = GatherMate2TreasureDB or {} if not WoWClassic then GatherMate2GasDB = GatherMate2GasDB or {} GatherMate2ArchaeologyDB = GatherMate2ArchaeologyDB or {} GatherMate2LoggingDB = GatherMate2LoggingDB or {} end self.gmdbs = {} self.db_types = {} gmdbs = self.gmdbs self:RegisterDBType("Herb Gathering", GatherMate2HerbDB) self:RegisterDBType("Mining", GatherMate2MineDB) self:RegisterDBType("Fishing", GatherMate2FishDB) self:RegisterDBType("Treasure", GatherMate2TreasureDB) if not WoWClassic then self:RegisterDBType("Extract Gas", GatherMate2GasDB) self:RegisterDBType("Archaeology", GatherMate2ArchaeologyDB) self:RegisterDBType("Logging", GatherMate2LoggingDB) end db = self.db.profile filter = db.filter -- depractaion scan if (self.db.global.data_version or 0) == 1 then self:RemoveDepracatedNodes() self.db.global.data_version = 2 end if (self.db.global.data_version or 0) < 4 then self:RemoveGarrisonNodes() self.db.global.data_version = 4 end if (self.db.global.data_version or 0) < 5 then self:MigrateData80() self.db.global.data_version = 5 end end function GatherMate:RemoveGarrisonNodes() for _, database in pairs({"Herb Gathering", "Mining"}) do gmdbs[database][971] = {} gmdbs[database][976] = {} end end function GatherMate:RemoveDepracatedNodes() for database,storage in pairs(self.gmdbs) do for zone,data in pairs(storage) do for coord,value in pairs(data) do local name = self:GetNameForNode(database,value) if not name then data[coord] = nil end end end end end function GatherMate:MigrateData80() for database,storage in pairs(self.gmdbs) do local migrated_storage = {} for zone,data in pairs(storage) do for coord,value in pairs(data) do local level = coord % 100 local newzone = HBDMigrate:GetUIMapIDFromMapAreaId(zone, level) if newzone then newzone = self.phasing[newzone] or newzone if not migrated_storage[newzone] then migrated_storage[newzone] = {} end migrated_storage[newzone][coord] = value end end storage[zone] = nil end for zone,data in pairs(migrated_storage) do storage[zone] = migrated_storage[zone] migrated_storage[zone] = nil end end end --[[ Register a new node DB for usage in GatherMate ]] function GatherMate:RegisterDBType(name, db) tinsert(self.db_types, name) self.gmdbs[name] = db end function GatherMate:OnProfileChanged(db,name) db = self.db.profile filter = db.filter GatherMate:SendMessage("GatherMate2ConfigChanged") end --[[ create a reverse lookup table for input table (we use it for english names of nodes) ]] function GatherMate:CreateReversedTable(tbl) if reverseTables[tbl] then return reverseTables[tbl] end local reverse = {} for k, v in pairs(tbl) do reverse[v] = k end reverseTables[tbl] = reverse return setmetatable(reverse, getmetatable(tbl)) end --[[ Clearing function ]] function GatherMate:ClearDB(dbx) -- for our own DBs we just discard the table and be happy -- db lock check if GatherMate.db.profile.dbLocks[dbx] then return end if dbx == "Herb Gathering" then GatherMate2HerbDB = {}; gmdbs[dbx] = GatherMate2HerbDB elseif dbx == "Fishing" then GatherMate2FishDB = {}; gmdbs[dbx] = GatherMate2FishDB elseif dbx == "Mining" then GatherMate2MineDB = {}; gmdbs[dbx] = GatherMate2MineDB elseif dbx == "Treasure" then GatherMate2TreasureDB = {}; gmdbs[dbx] = GatherMate2TreasureDB elseif not WoWClassic and dbx == "Extract Gas" then GatherMate2GasDB = {}; gmdbs[dbx] = GatherMate2GasDB elseif not WoWClassic and dbx == "Archaeology" then GatherMate2ArchaeologyDB = {}; gmdbs[dbx] = GatherMate2ArchaeologyDB elseif not WoWClassic and dbx == "Logging" then GatherMate2LoggingDB = {}; gmdbs[dbx] = GatherMate2LoggingDB else -- for custom DBs we dont know the global name, so we clear it old-fashion style local db = gmdbs[dbx] if not db then error("Trying to clear unknown database: "..dbx) end for k in pairs(db) do db[k] = nil end end end --[[ Add an item to the DB ]] function GatherMate:AddNode(zone, x, y, nodeType, name) local db = gmdbs[nodeType] if not db then return end local id = self:EncodeLoc(x,y) -- db lock check if GatherMate.db.profile.dbLocks[nodeType] then return end db[zone] = db[zone] or {} db[zone][id] = self.nodeIDs[nodeType][name] self:SendMessage("GatherMate2NodeAdded", zone, nodeType, id, name) end --[[ These 2 functions are only called by the importer/sharing. These do NOT fire GatherMateNodeAdded or GatherMateNodeDeleted messages. Renamed to InjectNode2/DeleteNode2 to ensure data addon compatibility with 8.0 zone IDs ]] function GatherMate:InjectNode2(zone, coords, nodeType, nodeID) local db = gmdbs[nodeType] if not db then return end -- db lock check if GatherMate.db.profile.dbLocks[nodeType] then return end if (nodeType == "Mining" or nodeType == "Herb Gathering") and GatherMate.mapBlacklist[zone] then return end db[zone] = db[zone] or {} db[zone][coords] = nodeID end function GatherMate:DeleteNode2(zone, coords, nodeType) if not gmdbs[nodeType] then return end -- db lock check if GatherMate.db.profile.dbLocks[nodeType] then return end local db = gmdbs[nodeType][zone] if db then db[coords] = nil end end -- Do-end block for iterator do local emptyTbl = {} local tablestack = setmetatable({}, {__mode = 'k'}) local function dbCoordIterNearby(t, prestate) if not t then return nil end local data = t.data local state, value = next(data, prestate) local xLocal, yLocal, yw, yh = t.xLocal, t.yLocal, t.yw, t.yh local radiusSquared, filterTable, ignoreFilter = t.radiusSquared, t.filterTable, t.ignoreFilter while state do if filterTable[value] or ignoreFilter then -- inline the :getXY() here in critical minimap update loop local x2, y2 = floor(state/1000000)/10000, floor(state % 1000000 / 100)/10000 local x = (x2 - xLocal) * yw local y = (y2 - yLocal) * yh if x*x + y*y <= radiusSquared then return state, value end end state, value = next(data, state) end tablestack[t] = true return nil, nil end --[[ Find all nearby nodes within the radius of the given (x,y) for a nodeType and zone this function returns an iterator ]] function GatherMate:FindNearbyNode(zone, x, y, nodeType, radius, ignoreFilter) local tbl = next(tablestack) or {} tablestack[tbl] = nil tbl.data = gmdbs[nodeType][zone] or emptyTbl tbl.yw, tbl.yh = self.HBD:GetZoneSize(zone) tbl.radiusSquared = radius * radius tbl.xLocal, tbl.yLocal = x, y tbl.filterTable = filter[nodeType] tbl.ignoreFilter = ignoreFilter return dbCoordIterNearby, tbl, nil end local function dbCoordIter(t, prestate) if not t then return nil end local data = t.data local state, value = next(data, prestate) local filterTable = t.filterTable while state do if filterTable[value] then return state, value end state, value = next(data, state) end tablestack[t] = true return nil, nil end --[[ This function returns an iterator for the given zone and nodeType ]] function GatherMate:GetNodesForZone(zone, nodeType, ignoreFilter) local t = gmdbs[nodeType][zone] or emptyTbl if ignoreFilter then return pairs(t) else local tbl = next(tablestack) or {} tablestack[tbl] = nil tbl.data = t tbl.filterTable = filter[nodeType] return dbCoordIter, tbl, nil end end end --[[ Node id function forward and reverse ]] function GatherMate:GetIDForNode(type, name) return self.nodeIDs[type][name] end --[[ Get the name for a nodeID ]] function GatherMate:GetNameForNode(type, nodeID) return self.reverseNodeIDs[type][nodeID] end --[[ Remove an item from the DB ]] function GatherMate:RemoveNode(zone, x, y, nodeType) if not gmdbs[nodeType] then return end local db = gmdbs[nodeType][zone] local coord = self:EncodeLoc(x,y) if db[coord] then local t = self.reverseNodeIDs[nodeType][db[coord]] db[coord] = nil self:SendMessage("GatherMate2NodeDeleted", zone, nodeType, coord, t) end end --[[ Remove an item from the DB by node ID and type ]] function GatherMate:RemoveNodeByID(zone, nodeType, coord) if not gmdbs[nodeType] then return end -- db lock check if GatherMate.db.profile.dbLocks[nodeType] then return end local db = gmdbs[nodeType][zone] if db[coord] then local t = self.reverseNodeIDs[nodeType][db[coord]] db[coord] = nil self:SendMessage("GatherMate2NodeDeleted", zone, nodeType, coord, t) end end --[[ Function to cleanup the databases by removing nearby nodes of similar types As of 02/17/2013 will be converted to become a coroutine --]] local CleanerUpdateFrame = CreateFrame("Frame") CleanerUpdateFrame.running = false function CleanerUpdateFrame:OnUpdate(elapsed) local finished = coroutine.resume(self.cleanup) if finished then if coroutine.status(self.cleanup) == "dead" then self:SetScript("OnUpdate",nil) self.running = false self.cleanup = nil GatherMate:Print(L["Cleanup Complete."]) end else self:SetScript("OnUpdate",nil) self.runing = false self.cleanup = nil GatherMate:Print(L["Cleanup Failed."]) end end function GatherMate:IsCleanupRunning() return CleanerUpdateFrame.running end function GatherMate:SweepDatabase() local Collector = GatherMate:GetModule("Collector") local rares = Collector.rareNodes for v,zone in pairs(GatherMate.HBD:GetAllMapIDs()) do --self:Print(L["Processing "]..zone) coroutine.yield() for profession in pairs(gmdbs) do local range = db.cleanupRange[profession] for coord, nodeID in self:GetNodesForZone(zone, profession, true) do local x,y = self:DecodeLoc(coord) for _coord, _nodeID in self:FindNearbyNode(zone, x, y, profession, range, true) do if coord ~= _coord and (nodeID == _nodeID or (rares[_nodeID] and rares[_nodeID][nodeID])) then self:RemoveNodeByID(zone, profession, _coord) end end end end end self:RemoveDepracatedNodes() self:SendMessage("GatherMate2Cleanup") end function GatherMate:CleanupDB() if not CleanerUpdateFrame.running then CleanerUpdateFrame.cleanup = coroutine.create(GatherMate.SweepDatabase) CleanerUpdateFrame:SetScript("OnUpdate",CleanerUpdateFrame.OnUpdate) CleanerUpdateFrame.running = true local status = coroutine.resume(CleanerUpdateFrame.cleanup,GatherMate) if not status then CleanerUpdateFrame.running = false CleanerUpdateFrame:SetScript("OnUpdate",nil) CleanerUpdateFrame.cleanup = nil self:Print(L["Cleanup Failed."]) else self:Print(L["Cleanup Started."]) end else self:Print(L["Cleanup in progress."]) end end --[[ Function to delete all of a specified node from a specific zone ]] function GatherMate:DeleteNodeFromZone(nodeType, nodeID, zone) if not gmdbs[nodeType] then return end local db = gmdbs[nodeType][zone] if db then for coord, node in pairs(db) do if node == nodeID then self:RemoveNodeByID(zone, nodeType, coord) end end self:SendMessage("GatherMate2Cleanup") end end --[[ Encode location ]] function GatherMate:EncodeLoc(x, y) if x > 0.9999 then x = 0.9999 end if y > 0.9999 then y = 0.9999 end return floor( x * 10000 + 0.5 ) * 1000000 + floor( y * 10000 + 0.5 ) * 100 end --[[ Decode location ]] function GatherMate:DecodeLoc(id) return floor(id/1000000)/10000, floor(id % 1000000 / 100)/10000 end function GatherMate:MapLocalize(map) return self.HBD:GetLocalizedMap(map) end
-- RGB API version 1.0 by CrazedProgrammer -- You can find info and documentation on these pages: -- -- You may use this in your ComputerCraft programs and modify it without asking. -- However, you may not publish this API under your name without asking me. -- If you have any suggestions, bug reports or questions then please send an email to: -- crazedprogrammer@gmail.com local hex = {"F0F0F0", "F2B233", "E57FD8", "99B2F2", "DEDE6C", "7FCC19", "F2B2CC", "4C4C4C", "999999", "4C99B2", "B266E5", "3366CC", "7F664C", "57A64E", "CC4C4C", "191919"} local rgb = {} for i=1,16,1 do rgb[i] = {tonumber(hex[i]:sub(1, 2), 16), tonumber(hex[i]:sub(3, 4), 16), tonumber(hex[i]:sub(5, 6), 16)} end local rgb2 = {} for i=1,16,1 do rgb2[i] = {} for j=1,16,1 do rgb2[i][j] = {(rgb[i][1] * 34 + rgb[j][1] * 20) / 54, (rgb[i][2] * 34 + rgb[j][2] * 20) / 54, (rgb[i][3] * 34 + rgb[j][3] * 20) / 54} end end colors.fromRGB = function (r, g, b) local dist = 1e100 local d = 1e100 local color = -1 for i=1,16,1 do d = math.sqrt((math.max(rgb[i][1], r) - math.min(rgb[i][1], r)) ^ 2 + (math.max(rgb[i][2], g) - math.min(rgb[i][2], g)) ^ 2 + (math.max(rgb[i][3], b) - math.min(rgb[i][3], b)) ^ 2) if d < dist then dist = d color = i - 1 end end return 2 ^ color end colors.toRGB = function(color) return unpack(rgb[math.floor(math.log(color) / math.log(2) + 1)]) end colors.fromRGB2 = function (r, g, b) local dist = 1e100 local d = 1e100 local color1 = -1 local color2 = -1 for i=1,16,1 do for j=1,16,1 do d = math.sqrt((math.max(rgb2[i][j][1], r) - math.min(rgb2[i][j][1], r)) ^ 2 + (math.max(rgb2[i][j][2], g) - math.min(rgb2[i][j][2], g)) ^ 2 + (math.max(rgb2[i][j][3], b) - math.min(rgb2[i][j][3], b)) ^ 2) if d < dist then dist = d color1 = i - 1 color2 = j - 1 end end end return 2 ^ color1, 2 ^ color2 end colors.toRGB2 = function(color1, color2, str) local c1 = math.floor(math.log(color1) / math.log(2) + 1) local c2 = math.floor(math.log(color2) / math.log(2) + 1) return math.floor(rgb2[c1][c2][1]), math.floor(rgb2[c1][c2][2]), math.floor(rgb2[c1][c2][3]) end colours.fromRGB = colors.fromRGB colours.toRGB = colors.toRGB colours.fromRGB2 = colors.fromRGB2 colours.toRGB2 = colors.toRGB2
local async = {} async._error = error local function dummyFunc() end -- Call only once -- local function onlyOnce(fn) local called = false return function(...) if called then error("Callback was already called.") end called = true fn(...) end end async.onlyOnce = onlyOnce -- Iterate arr in parallel -- and passes all results to the final callback. -- async.each = function(arr, iterator, callback) callback = callback or dummyFunc if #arr == 0 then return callback(nil, {}) end local results = {} local completed = 0 local function reduce(i, err, r) if err then local func = callback callback = dummyFunc return func(err) end results[i] = r completed = completed + 1 if completed == #arr then return callback(nil, results) end end for i = 1, #arr do iterator(arr[i], onlyOnce(function(...) reduce(i, ...) end)) end end -- Iterate arr in one by one -- and passes all results to the final callback. -- async.eachSeries = function(arr, iterator, callback) callback = callback or dummyFunc local results = {} local function iterate(i, err) if err or i > #arr then return callback(err, results) end return iterator(arr[i], onlyOnce(function(err, r) results[i] = r iterate(i + 1, err) end)) end iterate(1) end -- Do tasks one by one, -- and passes all results to the final callback. -- async.series = function(tasks, callback) return async.eachSeries(tasks, function(task, cb) return task(cb) end, callback) end -- Do tasks one by one, -- and allow each function to pass its results to the next function, -- async.waterfall = function(tasks, callback) callback = callback or dummyFunc local function iterate(i, err, ...) if err or i > #tasks then return callback(err, ...) end return tasks[i](..., onlyOnce(function(...) iterate(i + 1, ...) end)) end iterate(1) end -- Do tasks in parallel -- async.parallel = function(tasks, callback) return async.each(tasks, function(task, cb) return task(cb) end, callback) end return async
test_run = require('test_run').new() fiber = require('fiber') net_box = require('net.box') net_msg_max = box.cfg.net_msg_max box.cfg{net_msg_max = 64} box.schema.user.grant('guest', 'read,write,execute', 'universe') s = box.schema.space.create('test') _ = s:create_index('primary', {unique=true, parts={1, 'unsigned', 2, 'unsigned', 3, 'unsigned'}}) n_errors = 0 n_workers = 0 test_run:cmd("setopt delimiter ';'") function worker(i) n_workers = n_workers + 1 for j = 1,2 do local status, conn = pcall(net_box.connect, box.cfg.listen) if not status then n_errors = n_errors + 1 break end for k = 1,10 do conn.space.test:insert{i, j, k} end conn:close() fiber.sleep(0.1) end n_workers = n_workers - 1 end; test_run:cmd("setopt delimiter ''"); for i = 1,400 do fiber.create(worker, i) end fiber.sleep(0.1) -- check that iproto doesn't deplete tx fiber pool on wal stall (see gh-1892) box.error.injection.set("ERRINJ_WAL_DELAY", true) fiber.sleep(0.1) box.error.injection.set("ERRINJ_WAL_DELAY", false) attempt = 0 while n_workers > 0 and attempt < 100 do fiber.sleep(0.1) attempt = attempt + 1 end n_workers -- 0 n_errors -- 0 box.schema.user.revoke('guest', 'read,write,execute', 'universe') s:drop() box.cfg{net_msg_max = net_msg_max}
local ffi = require("ffi") local exports = {} ffi.cdef[[ /* The ovs_be<N> types indicate that an object is in big-endian, not * native-endian, byte order. They are otherwise equivalent to uint<N>_t. */ typedef uint16_t ovs_be16; typedef uint32_t ovs_be32; typedef uint64_t ovs_be64; ]] exports.OVS_BE16_MAX = ffi.cast("ovs_be16", 0xffff); exports.OVS_BE32_MAX = ffi.cast("ovs_be32", 0xffffffff); exports.OVS_BE64_MAX = ffi.cast("ovs_be64", 0xffffffffffffffffULL); --[[ /* These types help with a few funny situations: * * - The Ethernet header is 14 bytes long, which misaligns everything after * that. One can put 2 "shim" bytes before the Ethernet header, but this * helps only if there is exactly one Ethernet header. If there are two, * as with GRE and VXLAN (and if the inner header doesn't use this * trick--GRE and VXLAN don't) then you have the choice of aligning the * inner data or the outer data. So it seems better to treat 32-bit fields * in protocol headers as aligned only on 16-bit boundaries. * * - ARP headers contain misaligned 32-bit fields. * * - Netlink and OpenFlow contain 64-bit values that are only guaranteed to * be aligned on 32-bit boundaries. * * lib/unaligned.h has helper functions for accessing these. */ --]] --[[ A 32-bit value, in host byte order, that is only aligned on a 16-bit boundary. --]] if ffi.abi("be") then ffi.cdef[[ typedef struct { uint16_t hi, lo; } ovs_16aligned_u32; ]] else ffi.cdef[[ typedef struct { uint16_t lo, hi; } ovs_16aligned_u32; ]] end ffi.cdef[[ /* A 32-bit value, in network byte order, that is only aligned on a 16-bit * boundary. */ typedef struct { ovs_be16 hi, lo; } ovs_16aligned_be32; ]] if ffi.abi("be") then ffi.cdef[[ /* A 64-bit value, in host byte order, that is only aligned on a 32-bit * boundary. */ typedef struct { uint32_t lo, hi; } ovs_32aligned_u64; ]] else ffi.cdef[[ typedef struct { uint32_t hi, lo; } ovs_32aligned_u64; ]] end ffi.cdef[[ typedef union { uint32_t u32[4]; struct { uint64_t lo, hi; } u64; } ovs_u128; ]] -- Returns non-zero if the parameters have equal value. --local function ovs_u128_equal(const ovs_u128 *a, const ovs_u128 *b) local function ovs_u128_equal(a, b) return (a.u64.hi == b.u64.hi) and (a.u64.lo == b.u64.lo); end exports.ovs_u128_equal = ovs_u128_equal; ffi.cdef[[ /* A 64-bit value, in network byte order, that is only aligned on a 32-bit * boundary. */ typedef struct { ovs_be32 hi, lo; } ovs_32aligned_be64; ]] --[[ /* ofp_port_t represents the port number of a OpenFlow switch. * odp_port_t represents the port number on the datapath. * ofp11_port_t represents the OpenFlow-1.1 port number. */ --]] ffi.cdef[[ typedef uint16_t ofp_port_t; typedef uint32_t odp_port_t; typedef uint32_t ofp11_port_t; ]] local ofp_port_t = ffi.typeof("ofp_port_t") local odp_port_t = ffi.typeof("odp_port_t") local ofp11_port_t = ffi.typeof("ofp11_port_t") exports.ofp_port_t = ofp_port_t; exports.odp_port_t = odp_port_t; exports.ofp11_port_t = ofp11_port_t; -- Macro functions that cast int types to ofp/odp/ofp11 types. exports.OFP_PORT_C = function(X) return ofp_port_t(X) end exports.ODP_PORT_C = function(X) return odp_port_t(X) end exports.OFP11_PORT_C = function(X) return ofp11_port_t(X) end --]] return exports;
require 'io' require 'lfs' -- POSTSCRIPT for an image download -- This script runs after an image is downloaded -- to tell the user the size of their cache directory -- arguments are: the image directory, the downloaded file, and the module name local images_dn_abs = arg[1] local target_fn = arg[2] local my_module_name = arg[3] function isDir(name) -- via https://stackoverflow.com/a/21637668/3313859 local cd = lfs.currentdir() local is = lfs.chdir(name) and true or false lfs.chdir(cd) return is end function os.capture(cmd, raw) -- via https://stackoverflow.com/a/326715/3313859 local f = assert(io.popen(cmd, 'r')) local s = assert(f:read('*a')) f:close() if raw then return s end s = string.gsub(s, '^%s+', '') s = string.gsub(s, '%s+$', '') s = string.gsub(s, '[\n\r]+', ' ') return s end function check_image_sizes() io.stderr:write("[CC] checking image sizes at " .. images_dn_abs .. "\n") total_size = 0 has_sandboxes = false for path in lfs.dir(images_dn_abs) do -- better way to select only files? if path ~= "." and path ~= ".." then if isDir(images_dn_abs .. "/" .. path) then local result_du = os.capture( "du -s " .. images_dn_abs .. "/" .. path) local size = tonumber(string.match(result_du,'^%d+')) total_size = total_size + size/1024 local size_str = string.format("%6.0fMB",size/1024) io.stderr:write(size_str .. " " .. path .. "\n") has_sandboxes = true else -- pathJoin is not available outside lmod local size = tonumber(lfs.attributes( images_dn_abs .. "/" .. path, "size")) total_size = total_size + size/1000000 local size_str = string.format("%6.0fMB",size/1000000) io.stderr:write(size_str .. " " .. path .. "\n") end end end local size_str = string.format("%6.0fMB TOTAL",total_size) io.stderr:write(size_str .. "\n") if has_sandboxes then io.stderr:write("[CC] note that your image folder contains " .. "sandboxes\n[CC] and sandboxes often have many files!" .. "\n") end -- run du on the singularity folder as a warning if isDir(os.getenv("HOME") .. "/" .. ".singularity") then local result_du = os.capture( "du -s " .. os.getenv("HOME") .. "/" .. ".singularity") local size = tonumber(string.match(result_du,'^%d+')) if size>16 then total_size = total_size + size/1024 io.stderr:write(string.format( "[CC] the ~/.singularity folder is also %.0fMB\n",size/1024)) io.stderr:write("[CC] you can clear the singularity cache with: " .. "\"singularity cache clean -f\"" .. "\n") end end end io.stderr:write("[CC] downloaded the image: " .. target_fn .. "\n") check_image_sizes() io.stderr:write("[CC] please be mindful of your quota\n") io.stderr:write("[CC] the module is ready: " .. my_module_name .. "\n")
object_tangible_furniture_decorative_wod_sm_potted_plant_01 = object_tangible_furniture_decorative_shared_wod_sm_potted_plant_01:new { } ObjectTemplates:addTemplate(object_tangible_furniture_decorative_wod_sm_potted_plant_01, "object/tangible/furniture/decorative/wod_sm_potted_plant_01.iff")
-- ============================================================= -- Copyright Roaming Gamer, LLC. 2008-2018 (All Rights Reserved) -- ============================================================= -- Actions Library - Move Functions -- ============================================================= local move = {} _G.ssk.actions = _G.ssk.actions or {} _G.ssk.actions.move = move -- Forward Declarations -- SSK local angle2Vector = ssk.math2d.angle2Vector local vector2Angle = ssk.math2d.vector2Angle local scaleVec = ssk.math2d.scale local addVec = ssk.math2d.add local subVec = ssk.math2d.sub local getNormals = ssk.math2d.normals local lenVec = ssk.math2d.length local len2Vec = ssk.math2d.length2 local normVec = ssk.math2d.normalize local isValid = display.isValid -- Lua and Corona local mAbs = math.abs local mRand = math.random local mDeg = math.deg local mRad = math.rad local mCos = math.cos local mSin = math.sin local mAcos = math.acos local mAsin = math.asin local mSqrt = math.sqrt local mCeil = math.ceil local mFloor = math.floor local mAtan2 = math.atan2 local mPi = math.pi local getTimer = system.getTimer -- Limit the bounds within with object may move move.limit = function( obj, params ) end -- Limit the radial bounds within with object may move move.limitr = function( obj, params ) end local lastForwardTime = {} -- Move object forward at fixed rate move.forward = function( obj, params ) if( not isValid( obj ) ) then return end params = params or {} local curTime = getTimer() if( not lastForwardTime[obj]) then lastForwardTime[obj] = curTime end local dt = curTime - lastForwardTime[obj] lastForwardTime[obj] = curTime local pps = params.rate or 100 local rate = pps * dt/1000 local v = angle2Vector( obj.rotation, true ) v = scaleVec( v, rate ) obj:translate( v.x, v.y ) end -- Move object in x,y direction at fixed rate per-second or per-frame move.at = function( obj, params ) if( not isValid( obj ) ) then return end params = params or {} local perSecond = not params.perFrame -- set this to true to move perFrame local x = params.x or 0 local y = params.y or 0 if( perSecond ) then local curTime = getTimer() if( not obj.__last_move_at_time) then obj.__last_move_at_time = curTime end local dt = curTime - obj.__last_move_at_time obj.__last_move_at_time = curTime x = x * dt/1000 y = y * dt/1000 obj:translate( x, y ) else obj:translate( x, y ) end end return move
local Concord = require("lib.concord") return Concord.component()
local Screen = require "widgets/screen" local Button = require "widgets/button" local AnimButton = require "widgets/animbutton" local ImageButton = require "widgets/imagebutton" local Text = require "widgets/text" local Image = require "widgets/image" local UIAnim = require "widgets/uianim" local Widget = require "widgets/widget" local EndGameDialog = Class(Screen, function(self, buttons) Screen._ctor(self, "EndGameDialog") --darken everything behind the dialog self.black = self:AddChild(Image("images/global.xml", "square.tex")) self.black:SetVRegPoint(ANCHOR_MIDDLE) self.black:SetHRegPoint(ANCHOR_MIDDLE) self.black:SetVAnchor(ANCHOR_MIDDLE) self.black:SetHAnchor(ANCHOR_MIDDLE) self.black:SetScaleMode(SCALEMODE_FILLSCREEN) self.black:SetTint(0,0,0,1) self.proot = self:AddChild(Widget("ROOT")) self.proot:SetVAnchor(ANCHOR_MIDDLE) self.proot:SetHAnchor(ANCHOR_MIDDLE) self.proot:SetPosition(0,0,0) self.proot:SetScaleMode(SCALEMODE_PROPORTIONAL) --throw up the background self.bg = self.proot:AddChild(Image("images/globalpanels.xml", "panel_upsell.tex")) self.bg:SetVRegPoint(ANCHOR_MIDDLE) self.bg:SetHRegPoint(ANCHOR_MIDDLE) self.bg:SetScale(0.8,0.8,0.8) --title self.title = self.proot:AddChild(Text(TITLEFONT, 50)) self.title:SetPosition(0, 180, 0) self.title:SetString(STRINGS.UI.ENDGAME.TITLE) --text self.text = self.proot:AddChild(Text(BODYTEXTFONT, 30)) self.text:SetVAlign(ANCHOR_TOP) local character = GetPlayer().profile:GetValue("characterinthrone") or "wilson" self.text:SetPosition(0, -60, 0) self.text:SetString(STRINGS.UI.ENDGAME.BODY1.. STRINGS.CHARACTER_NAMES[character].. string.format(STRINGS.UI.ENDGAME.BODY2,STRINGS.UI.GENDERSTRINGS[GetGenderStrings(character)].ONE , STRINGS.UI.GENDERSTRINGS[GetGenderStrings(character)].TWO)) self.text:EnableWordWrap(true) self.text:SetRegionSize(700, 350) --create the menu itself local button_w = 200 local space_between = 20 local spacing = button_w + space_between self.menu = self.proot:AddChild(Widget("menu")) local total_w = #buttons*button_w if #buttons > 1 then total_w = total_w + space_between*(#buttons-1) end self.menu:SetPosition(-(total_w / 2) + button_w/2, -220,0) local pos = Vector3(0,0,0) for k,v in ipairs(buttons) do local button = self.menu:AddChild(ImageButton()) button:SetPosition(pos) button:SetText(v.text) button:SetOnClick( function() TheFrontEnd:PopScreen(self) v.cb() end ) button.text:SetColour(0,0,0,1) button:SetFont(BUTTONFONT) button:SetTextSize(40) pos = pos + Vector3(spacing, 0, 0) self.default_focus = button end self.buttons = buttons end) return EndGameDialog
RegisterNetEvent('pma-voice:syncRadioData') AddEventHandler('pma-voice:syncRadioData', function(radioTable) radioData = radioTable for tgt, enabled in pairs(radioTable) do if tgt ~= playerServerId then toggleVoice(tgt, enabled) end end playerTargets(radioData, callData) end) RegisterNetEvent('pma-voice:setTalkingOnRadio') AddEventHandler('pma-voice:setTalkingOnRadio', function(tgt, enabled) if tgt ~= playerServerId then toggleVoice(tgt, enabled) radioData[tgt] = enabled playerTargets(radioData, callData) playMicClicks(enabled) end end) RegisterNetEvent('pma-voice:addPlayerToRadio') AddEventHandler('pma-voice:addPlayerToRadio', function(plySource) radioData[plySource] = false playerTargets(radioData, callData) end) RegisterNetEvent('pma-voice:removePlayerFromRadio') AddEventHandler('pma-voice:removePlayerFromRadio', function(plySource) if plySource == playerServerId then for tgt, enabled in pairs(radioData) do if tgt ~= playerServerId then toggleVoice(tgt, false) end end radioData = {} playerTargets(radioData, callData) else radioData[plySource] = nil toggleVoice(plySource, false) playerTargets(radioData, callData) end end) function setRadioChannel(channel) TriggerServerEvent('pma-voice:setPlayerRadio', channel) voiceData.radio = channel if GetConvarInt('voice_enableUi', 1) == 1 then SendNUIMessage({ radioChannel = channel, radioEnabled = Cfg.radioEnabled }) end end exports('setRadioChannel', setRadioChannel) exports('removePlayerFromRadio', function() setRadioChannel(0) end) exports('addPlayerToRadio', function(radio) local radio = tonumber(radio) if radio then setRadioChannel(radio) end end) RegisterCommand('+radiotalk', function() -- since this is a shared resource (between my server and the public), probably don't want to try and use our export :P -- use fallback in this case. if GetResourceState("pma-ambulance") ~= "missing" then if exports["pma-ambulance"]:isPlayerDead() then return false end elseif IsPlayerDead(PlayerId()) then return false end if not Cfg.radioPressed and Cfg.radioEnabled then if voiceData.radio > 0 then TriggerServerEvent('pma-voice:setTalkingOnRadio', true) Cfg.radioPressed = true playMicClicks(true) Citizen.CreateThread(function() TriggerEvent("pma-voice:radioActive", true) while Cfg.radioPressed do Wait(0) SetControlNormal(0, 249, 1.0) SetControlNormal(1, 249, 1.0) SetControlNormal(2, 249, 1.0) end end) end end end, false) RegisterCommand('-radiotalk', function() if voiceData.radio > 0 or Cfg.radioEnabled then Cfg.radioPressed = false TriggerEvent("pma-voice:radioActive", false) playMicClicks(false) TriggerServerEvent('pma-voice:setTalkingOnRadio', false) end end, false) RegisterKeyMapping('+radiotalk', 'Talk over Radio', 'keyboard', GetConvar('voice_defaultRadio', 'LMENU')) RegisterNetEvent('pma-voice:clSetPlayerRadio') AddEventHandler('pma-voice:clSetPlayerRadio', function(radioChannel) voiceData.radio = radioChannel end)
function start() play_music("music/castle.mid"); process_outline() add_wall_group(3, 10, 6, 2, 3, 0) pig = add_npc("pig_guard", 3, 119, 134) set_character_role(pig, "wander", 48, 0.25, 1.0) going_down = Active_Block:new{x=1, y=10, width=3, height=2} going_out = Active_Block:new{x=5, y=13, width=3, height=2} end function logic() if (going_down:entity_is_colliding(0)) then next_player_layer = 4 change_areas("castle_knight_right1", DIR_S, 38, 86) elseif (going_out:entity_is_colliding(0)) then next_player_layer = 6 change_areas("castle", DIR_S, 832, 391) end end function activate(activator, activated) if (activated == pig) then speak(false, false, true, t("PIG_TOWER_6"), "", pig, pig) end end function collide(id1, id2) end function uncollide(id1, id2) end function action_button_pressed(n) end function attacked(attacker, attackee) end function stop() end
---------------------------------------- -- Group Calendar 5 Copyright (c) 2018 John Stephen -- This software is licensed under the MIT license. -- See the included LICENSE.txt file for more information. ---------------------------------------- ---------------------------------------- GroupCalendar._WhisperLog = {} ---------------------------------------- function GroupCalendar._WhisperLog:Construct() self.Players = {} GroupCalendar.EventLib:RegisterEvent("CHAT_MSG_WHISPER", function (pMessage, pPlayerName) self:AddWhisper(pPlayerName, pMessage) end) end function GroupCalendar._WhisperLog:AddWhisper(pPlayerName, pMessage) -- If no event is active then just ignore all whispers if not GroupCalendar.RunningEvent then return end -- Ignore whispers which appear to be data from other addons local vFirstChar = string.sub(pMessage, 1, 1) if vFirstChar == "<" or vFirstChar == "[" or vFirstChar == "{" or vFirstChar == "!" then return end -- Filter if requested if self.WhisperFilterFunc and not self.WhisperFilterFunc(self.WhisperFilterParam, pPlayerName) then return end -- Create a new entry for the player if necessary local vPlayerLog = self.Players[pPlayerName] if not vPlayerLog then vPlayerLog = {} vPlayerLog.Name = pPlayerName vPlayerLog.Date, vPlayerLog.Time = GroupCalendar.DateLib:GetServerDateTime60() vPlayerLog.Whispers = {} self.Players[pPlayerName] = vPlayerLog end -- Keep only the most recent 3 whispers from any one player if #vPlayerLog.Whispers > 3 then table.remove(vPlayerLog.Whispers, 1) end -- Add the new message table.insert(vPlayerLog.Whispers, pMessage) -- Notify if self.NotificationFunc then self.NotificationFunc(self.NotifcationParam) end end function GroupCalendar._WhisperLog:AskClear() StaticPopup_Show("CONFIRM_CALENDAR_CLEAR_WHISPERS") end function GroupCalendar._WhisperLog:Clear() self.Players = {} if self.NotificationFunc then self.NotificationFunc(self.NotifcationParam) end end function GroupCalendar._WhisperLog:GetPlayerWhispers(pEvent) if GroupCalendar.RunningEvent ~= pEvent then return end return self.Players end function GroupCalendar._WhisperLog:SetNotificationFunc(pFunc, pParam) self.NotificationFunc = pFunc self.NotifcationParam = pParam end function GroupCalendar._WhisperLog:SetWhisperFilterFunc(pFunc, pParam) self.WhisperFilterFunc = pFunc self.WhisperFilterParam = pParam end function GroupCalendar._WhisperLog:RemovePlayer(pPlayerName) self.Players[pPlayerName] = nil -- Notify if self.NotificationFunc then self.NotificationFunc(self.NotifcationParam) end end function GroupCalendar._WhisperLog:GetNextWhisper(pPlayerName) -- Make an indexed list of the whispers local vWhispers = {} for vName, vWhisper in pairs(self.Players) do table.insert(vWhispers, vWhisper) end -- Sort by time table.sort(vWhispers, function (pWhisper1, pWhisper2) if pWhisper1.Date < pWhisper2.Date then return true elseif pWhisper1.Date > pWhisper2.Date then return false elseif pWhisper1.Time < pWhisper2.Time then return true elseif pWhisper1.Time > pWhisper2.Time then return false else return pWhisper1.Name < pWhisper2.Name end end) -- local vLowerName = strlower(pPlayerName) local vUseNext = false for vIndex, vWhisper in ipairs(vWhispers) do if vUseNext then return vWhisper end if vLowerName == strlower(vWhisper.Name) then vUseNext = true end end return nil end
------------------------------------------------ -- Copyright © 2013-2020 Hugula: Arpg game Engine -- -- author pu ------------------------------------------------ local require = require local rawset = rawset local rawget = rawget local setmetatable = setmetatable local VMConfig = require("vm_config")[1] ---根据 WindowConfig的配置来require view model文件 local function _require_vm(t, k) local raw = rawget(t, k) if raw == nil then --require local conf = VMConfig[k] if conf and conf.vm then local re = require(conf.vm) local initialize = re.initialize rawset(t, k, re) rawset(re, "name", k) ---设置view model的 name if initialize then --调用初始化函数 initialize(re) end return re else error(string.format("/vm_config.lua does't contains vm_config.%s", k)) end else return raw end end --@overload fun(self:VMBase,key:string,hold_child:boolean) local function _reload_vm(t, k, hold_child) --@type VMBase local raw = rawget(t, k) if raw ~= nil then -- local conf = VMConfig[k] if conf and conf.vm then require("core.mvvm.vm_manager"):deactive(k) package.loaded[conf.vm] = nil local re = require(conf.vm) --重新require lua local initialize = re.initialize rawset(t, k, re) rawset(re, "name", k) ---设置view model的 name if initialize then --调用初始化函数 initialize(re) end return re else error(string.format("/vm_config.lua does't contains vm_config.%s", k)) end else return raw end end local mt = {} mt.__index = _require_vm --- ---@class vm_generate local vm_generate = {} setmetatable(vm_generate, mt) vm_generate.reload_vm = _reload_vm VMGenerate = vm_generate --增加全局访问 --- 保持对所有view models的实例引用 __index回自动require vm_config 对应路径的viewmodel lua文件 ---@class VMGenerate ---@field index string return vm_generate
local C = hog.C local HOG, parent = torch.class('hog.HOG', 'nn.Module') function HOG:__init(sbin) parent.__init(self) self.sbin = sbin or 8 self.grad_v = torch.CudaTensor() self.grad_i = torch.CudaTensor() self.hist = torch.CudaTensor() self.norm = torch.CudaTensor() self.output = torch.CudaTensor() self.gradInput = torch.CudaTensor() end function HOG:updateOutput(input) hog.typecheck(input) C['HOGForward'](cutorch.getState(), input:cdata(), self.output:cdata(), self.grad_v:cdata(), self.grad_i:cdata(), self.hist:cdata(), self.norm:cdata(), self.sbin) return self.output end
local highlight = function(group, color) local style = color.style and 'gui=' .. color.style or 'gui=NONE' local fg = color.fg and 'guifg=' .. color.fg or 'guifg=NONE' local bg = color.bg and 'guibg=' .. color.bg or 'guibg=NONE' local sp = color.sp and 'guisp=' .. color.sp or '' local hl = 'highlight ' .. group .. ' ' .. style .. ' ' .. fg .. ' ' .. bg .. ' ' .. sp if color.link then vim.cmd('highlight! link ' .. group .. ' ' .. color.link) else vim.cmd(hl) end end return function(color_groups) if not color_groups or type(color_groups) ~= 'table' then error('A color_groups table is required') end if vim.g.colors_name then vim.cmd('hi clear') end vim.o.termguicolors = true vim.g.colors_name = 'undercity' for group, color in pairs(color_groups) do highlight(group, color) end end
local opts = { noremap = true, silent = true } local term_opts = { silent = true } -- shorten function name local keymap = vim.api.nvim_set_keymap -- Remap space as leader key keymap("", "<Space>", "<Nop>", opts) vim.g.mapleader = " " vim.g.maplocalleader = " " -- Modes -- normal_mode = "n", -- insert_mode = "i", -- visual_mode = "v", -- visual_block_mode = "x", -- term_mode = "t", -- command_mode = "c" -- Normal -- -- Better window navigation keymap("n", "<C-h>", "<C-w>h" , opts) keymap("n", "<C-j>", "<C-w>j" , opts) keymap("n", "<C-k>", "<C-w>k" , opts) keymap("n", "<C-l>", "<C-w>l" , opts) -- Replaced with nvim-tree --keymap("n", "<leader>e", ":Lexplore 20<cr>", opts) keymap("n", "<leader>e", ":NvimTreeToggle<cr>", opts) -- Resize with arrows keymap("n", "<C-Up>", ":resize +2<cr>", opts) keymap("n", "<C-Down>", ":resize -2<CR>", opts) keymap("n", "<C-Left>", ":vertical resize +2<CR>", opts) keymap("n", "<C-Right>", ":vertical resize -2<CR>", opts) -- Navigate buffers keymap("n", "<S-l>", ":bnext<CR>", opts) keymap("n", "<S-h>", ":bprevious<CR>", opts) -- Insert -- -- Press jk fast to escape keymap("i", "jk", "<ESC>", opts) -- Visual -- -- Stay in indent mode keymap("v", "<", "<gv", opts) keymap("v", ">", ">gv", opts) -- Move text up and down keymap("v", "<A-j>", ":m .+1<CR>==", opts) keymap("v", "<A-k>", ":m .-2<CR>==", opts) keymap("v", "p", '"_dP', opts) -- Visual Block -- -- Move text up and down keymap("x", "J", ":move '>+1<CR>gv-gv", opts) keymap("x", "K", ":move '<-2<CR>gv-gv", opts) keymap("x", "<A-j>", ":move '>+1<CR>gv-gv", opts) keymap("x", "<A-k>", ":move '<-2<CR>gv-gv", opts) -- Terminal -- -- Better terminal navigation keymap("t", "<C-h>", "<C-\\><C-N><C-w>h", term_opts) keymap("t", "<C-j>", "<C-\\><C-N><C-w>j", term_opts) keymap("t", "<C-k>", "<C-\\><C-N><C-w>k", term_opts) keymap("t", "<C-l>", "<C-\\><C-N><C-w>l", term_opts) -- open terminal in split keymap("n", "<leader>tv", ":vsplit | term<cr>:vertical resize 90<cr>i", opts) keymap("n", "<leader>th", ":split | term<cr>:resize 15<cr>i", opts) keymap("n", "<leader>x", ":bw<cr>", opts) keymap("n", "<leader>X", ":bw!<cr>", opts) --keymap("n", "<leader>f", "<cmd>Telescope find_files<cr>", opts) keymap("n", "<leader>f", "<cmd>Telescope find_files<cr>", opts) keymap("n", "<leader>dd", "<cmd>Telescope git_files<cr>", opts) keymap("n", "<leader>b", ":Telescope buffers<cr><esc>", opts) keymap("n", "<leader>?", ":Telescope keymaps<cr>", opts) -- default Live Grep keymap("n", "<leader>g", "<cmd>Telescope live_grep<cr>", opts) -- Live Grep with hidden hiles keymap("n", "<leader>GH", "<cmd>lua require'telescope.builtin'.live_grep({vimgrep_arguments={'rg', '--color=never', '--no-heading', '--with-filename', '--line-number', '--column', '--smart-case', '--hidden', '--trim'}})<cr>", opts) keymap("n", "<leader>s", "<cmd>lua require'telescope.builtin'.current_buffer_fuzzy_find()<cr>", opts) -- keymap("n", "<leader>s", "<cmd>lua require'telescope.builtin'.lsp_workspace_symbols()<cr>", opts) keymap("n", "<leader>.", "<cmd>lua require'telescope.builtin'.lsp_code_actions()<cr><esc>", opts) keymap("n", "<leader>dld", "<cmd>lua require'telescope.builtin'.diagnostics()<cr>", opts) -- Telescope DAP keymap("n", "<leader>dlb", ":Telescope dap list_breakpoints<CR>", opts) keymap("n", "<leader>dlc", ":Telescope dap configurations<CR>", opts) keymap("n", "<leader>dlx", ":Telescope dap commands<CR>", opts) keymap("n", "<leader>dlv", ":Telescope dap variables<CR>", opts) keymap("n", "<leader>dlf", ":Telescope dap frames<CR>", opts) keymap("n","<F10>", ":lua require'dap'.step_over()<CR>", opts) keymap("n","<F5>", ":lua require'dap'.continue()<CR>", opts) keymap("n","<F11>", ":lua require'dap'.step_into()<CR>", opts) keymap("n","<F12>", ":lua require'dap'.step_out()<CR>", opts) keymap("n","<leader>db", ":lua require'dap'.toggle_breakpoint()<CR>", opts) keymap("n","<leader>dB", ":lua require'dap'.set_breakpoint(vim.fn.input('Breakpoint condition: '))<CR>", opts) keymap("n","<leader>lp", ":lua require'dap'.set_breakpoint(nil, nil, vim.fn.input('Log point message: '))<CR>", opts) keymap("n","<leader>dr", ":lua require'dap'.repl.open()<CR>", opts) keymap("n","<F6>", ":lua require'dap'.run_last()<CR>", opts) keymap("n","<F4>", ":lua require'dapui'.toggle()<CR>", opts) keymap("n", "<leader>di", ":lua require'dapui'.eval()<CR>", opts) keymap("v", "<leader>di", ":lua require'dapui'.eval()<CR>", opts) -- require("dapui").eval(<expression>) -- Cheatsheet -- keymap("n", "<leader>?", ":Cheatsheet<cr>", opts) -- lazygit --keymap("n", "<leader>k", ":LazyGit<CR>", opts) -- Toggleterm keybindings: see toggleterm.lua file --keymap("n", "<leader>h", ":lua _HTOP_TOGGLE()<cr>", opts) --keymap("n", "<leader>l", ":lua _LAZYGIT_TOGGLE()<cr>", opts) -- Open links on gx (remap needed because nvim-tree overrides it) -- xgd-open needs to be replaced with whatever you want to topen the link keymap("n","gx", [[:execute '!xdg-open ' . shellescape(expand('<cfile>'), 1)<CR>]], opts) -- vimspector keybindings -- mnemonic 'di' = 'debug inspect' (pick your own, if you prefer!) -- for normal mode - the word under the cursor -- e.g. vim.cmd("nmap <Leader>di <Plug>VimspectorBalloonEval") -- vim.cmd("xmap <Leader>di <Plug>VimspectorBalloonEval") --keymap("n", "<leader>di", "<Plug>VimspectorBalloonEval", term_opts) --keymap("v", "<leader>di", "<Plug>VimspectorBalloonEval", term_opts) -- Calendar keymap keymap("n", "<leader>k", "<Plug>(calendar)", term_opts) -- Zen mode keymap("n", "<leader><SPACE>","<cmd>lua require'zen-mode'.toggle()<CR>", opts) -- Undotree keymap("n", "<leader>u",":UndotreeToggle<CR>", opts) keymap("n", "<leader>U",":UndotreeToggle<CR>", opts) -- Turn editor transparent keymap("n", "<leader>P",":TransparentToggle<CR>", opts) -- Remove search highlights -- keymap("n", "<leader>l",":set hls!<CR>", opts) --Toggle instead keymap("n", "<leader>h",":nohl<CR>:VMClear<CR>", opts) -- Vim Visual multi cursor keymaps vim.g.VM_mouse_mappings = 1 vim.g.VM_theme = 'sand' vim.g.VM_highlight_matches = 'red' vim.g.VM_maps = { ['Find Under'] = '<C-d>', ['Find Subword Under'] = '<C-d>', ["Undo"] = 'u', ["Redo"] = '<C-r>' }
position = {x = 48.2880554199219, y = 0.947854280471802, z = 15.9168872833252} rotation = {x = 1.17175068226061E-05, y = 269.985107421875, z = 2.19253470277181E-05}
function i(n) if n < 12 then return n; end return i(n - 1); end print(i(1)); print(i(100));
-- AreaPreview.lua -- Implements the AreaPreview class providing area previews for webadmin --[[ The webadmin handlers use this class to request images of the areas. This class uses a network connection to MCSchematicToPng to generate the images, and stores them in the Storage DB as a cache. Since the webadmin needs to finish the request as soon as possible (no async), if an image doesn't exist, nil is returned; and if an image is stale, it is still returned (and a refresh is scheduled). An additional periodic task is used to schedule image refresh for existing out-of-date images. Usage: Call InitAreaPreview(a_Config) to create a new object of the AreaPreview class, then use its functions to query previews. Note that the preview generator works in an asynchronous way, call RefreshPreview() to schedule a refresh and GetPreview() to retrieve the PNG image; if GetPreview fails, check back later if the image has been generated. No completion callbacks are currently provided. local areaPreview = InitAreaPreview(config) areaPreview:RefreshPreview(areaID, numRotations) ... local pngImage = areaPreview:GetPreview(areaID, numRotations) if not(pngImage) then -- No preview available yet, check back later else -- Use the image in pngImage end --]] local AreaPreview = { m_RenderQueue = {}, -- Queued requests for rendering, to be sent once the MCSchematicToPng connection is established m_IsFullyConnected = false, -- True iff MCSchematicToPng connection has been fully established (can send requests) m_LastWorld = nil, -- The cWorld object of the last export (used for partial cleanup) m_LastGalleryName = "", -- The name of the last export area's gallery (used for partial cleanup) m_NumExported = 0, -- Number of exported previews (used for partial cleanup) m_HostName = "localhost", -- Hostname where to connect to the MCSchematicToPng jsonnet service m_Port = 9999, -- Port where to connect to the MCSchematicToPng jsonnet service m_Link = nil, -- When connected to MCSchematicToPng, contains the cTCPLink for the connection m_IncomingData = "", -- Buffer for the data incoming on m_Link, before being parsed m_PendingRenderCommands = {}, -- The render commands that have been sent to MCSchematicToPng, but not finished yet m_NextCmdID = 0, -- The CmdID to be used for the next command } AreaPreview.__index = AreaPreview --- Class used for the AreaPreview's m_DB member, providing (and hiding) DB access local AreaPreviewDB = {} -- If assigned to an open file, the comm to MCSchematicToPng will be written to it local g_LogFile = nil -- io.open("MCSchematicToPng-comm.log", "wb") --- Returns the chunk coords of chunks that intersect the given area's export cuboid -- The returned value has the form of { {Chunk1x, Chunk1z}, {Chunk2x, Chunk2z}, ...} local function GetAreaChunkCoords(a_Area) assert(type(a_Area) == "table") local MinChunkX = math.floor(a_Area.StartX / 16) local MinChunkZ = math.floor(a_Area.StartZ / 16) local MaxChunkX = math.floor((a_Area.EndX + 15) / 16) local MaxChunkZ = math.floor((a_Area.EndZ + 15) / 16) local res = {} for z = MinChunkZ, MaxChunkZ do for x = MinChunkX, MaxChunkX do table.insert(res, {x, z}) end end assert(res[1]) -- Check that at least one chunk coord pair is being returned return res end --- Returns the 6 coords for the area's bounds for export -- MinX, MaxX, MinY, MaxY, MinZ, MaxZ -- The returned coords are in world coordinates local function GetAreaExportCoords(a_Area) -- a_Area's ExportMinX and StartX are world-coords, while EditMinX is relative-to-StartX, so we need to unify. -- EditMaxX is still relative to StartX, therefore the min / max processing is different. -- MinX: local minX = a_Area.ExportMinX if not(minX) then minX = a_Area.StartX + (a_Area.EditMinX or 0) end -- MaxX: local maxX = a_Area.ExportMaxX if not(maxX) then if (a_Area.EditMaxX) then maxX = a_Area.StartX + a_Area.EditMaxX else maxX = a_Area.EndX end end -- MinZ: local minZ = a_Area.ExportMinZ if not(minZ) then minZ = a_Area.StartZ + (a_Area.EditMinZ or 0) end -- MaxX: local maxZ = a_Area.ExportMaxZ if not(maxZ) then if (a_Area.EditMaxZ) then maxZ = a_Area.StartZ + a_Area.EditMaxZ else maxZ = a_Area.EndZ end end -- If the area is the same as the template (hasn't been edited yet), return a single block: if (minX > maxX) then return a_Area.StartX, a_Area.StartX, 255, 255, a_Area.StartZ, a_Area.StartZ end return minX, maxX, a_Area.ExportMinY or a_Area.EditMinY or 0, a_Area.ExportMaxY or a_Area.EditMaxY or 255, minZ, maxZ end -------------------------------------------------------------------------------- -- AreaPreview: --- Starts the connection to MCSchematicToPng function AreaPreview:Connect() -- Check params: assert(self) assert(self.m_HostName) assert(self.m_Port) assert(not(self.m_Link)) -- Start the connection: cNetwork:Connect(self.m_HostName, self.m_Port, { OnError = function (a_Link, a_ErrorCode, a_ErrorMsg) LOGWARNING(PLUGIN_PREFIX .. "Error in connection to MCSchematicToPng (" .. self.m_HostName .. ":" .. self.m_Port .. "): " .. (a_ErrorMsg or "<unknown error>")) self:Disconnected() end, OnRemoteClosed = function (a_Link) self:Disconnected() end, OnReceivedData = function (a_Link, a_Data) self.m_Link = a_Link self:ProcessIncomingData(a_Data) end }) end --- Called when the connection to MCSchematicToPng is disconnected. -- Resets all internal variables to their defaults, so that reconnection works function AreaPreview:Disconnected() -- Check params: assert(self) -- Reset link-related state: self.m_Link = nil self.m_IncomingData = "" self.m_IsFullyConnected = false -- Move m_PendingRenderCommands back into the m_RenderQueue: for _, cmd in pairs(self.m_PendingRenderCommands) do cmd.CmdID = nil -- Reset the Command ID table.insert(self.m_RenderQueue, cmd) end self.m_PendingRenderCommands = {} end --- Retrieves the DB area description -- a_DBAreaOrID is either the DB area (in which case this function just returns it) or the ID of a DB area -- Returns the DB area description on success, or nil and optional error message on failure function AreaPreview:GetDBArea(a_DBAreaOrID) -- Check params: assert(self) assert((type(a_DBAreaOrID) == "table") or (type(a_DBAreaOrID) == "number")) if (type(a_DBAreaOrID) == "table") then -- Assume this is the DB area. Check that it has some of the members normally associated with an area: if ( a_DBAreaOrID.ID and a_DBAreaOrID.WorldName and a_DBAreaOrID.MinX and a_DBAreaOrID.GalleryName ) then return a_DBAreaOrID end return nil, "GetDBArea() was given a table that doesn't look like a DB area" end -- We were given a number, consider it a DB area ID and load the area description from the DB: return g_DB:LoadAreaByID(a_DBAreaOrID) end --- Returns an unused CmdID for a new command function AreaPreview:GetNextCmdID() -- Check params: assert(self) local cmdID = self.m_NextCmdID or 0 self.m_NextCmdID = cmdID + 1 return cmdID end --- Returns a preview for the specified area -- a_DBAreaOrID is the table describing the area, or a single number - the area's ID -- a_NumRotations is the number specifying the number of rotations -- Returns the PNG data as a string, with optional second value "true" if the image is outdated -- Returns nil and an optional error msg on failure -- If the image is missing or outdated, automatically schedules a refresh function AreaPreview:GetPreview(a_DBAreaOrID, a_NumRotations) -- Check params: assert(self) assert((type(a_DBAreaOrID) == "table") or (type(a_DBAreaOrID) == "number")) assert(type(a_NumRotations) == "number") -- If the area is specified using an ID, retrieve the whole DB area table: local area = self:GetDBArea(a_DBAreaOrID) if not(area) then return nil, "Invalid area ID" end -- Retrieve the PNG data from the DB: local imgRec, msg = self.m_DB:GetAreaPreview(area.ID, a_NumRotations) if not(imgRec) then self:RefreshPreview(area, a_NumRotations) return nil, "Failed to retrieve PNG image from the DB: " .. (msg or "<no message>") end -- If the image is outdated, schedule a refresh: if (area.TickLastChanged > imgRec.TickExported) then self:RefreshPreview(area,a_NumRotations) return imgRec.PngData, true end -- Image is up to date: return imgRec.PngData end --- Processes a reply to a previously sent command incoming from the network connection -- a_CmdReply is the command reply parsed into a table function AreaPreview:ProcessIncomingCmdReply(a_CmdReply) -- Check params: assert(self) assert(type(a_CmdReply) == "table") -- Find the command: local cmdID = a_CmdReply.CmdID if not(cmdID) then LOG(PLUGIN_PREFIX .. "MCSchematicToPng connection received a cmd reply without CmdID; ignoring message.") return end if (cmdID == "SetNameCmdID") then -- Ignore this response, it was the SetName command return end local cmd = self.m_PendingRenderCommands[cmdID] if not(cmd) then LOG(string.format("%sMCSchematicToPng connection received a cmd reply with an invalid CmdID %q; ignoring message.", PLUGIN_PREFIX, cmdID )) return end self.m_PendingRenderCommands[cmdID] = nil -- Check the command status: local status = a_CmdReply.Status if (status == "error") then LOG(string.format("%sMCSchematicToPng connection received a cmd reply with an error for CmdID %q: %s", PLUGIN_PREFIX, cmdID, a_CmdReply.ErrorText or "[no message]" )) return end if (status ~= "ok") then LOG(string.format("%sMCSchematicToPng connection received a cmd reply with an unknown status %q for CmdID %q: %s", PLUGIN_PREFIX, tostring(status), cmdID, a_CmdReply.ErrorText or "[no message]" )) return end -- Store the image data into DB: if not(a_CmdReply.PngData) then LOG(string.format("%sMCSchematicToPng connection received a cmd reply with no PNG data for CmdID %q", PLUGIN_PREFIX, cmdID )) return end local pngData = Base64Decode(a_CmdReply.PngData) self.m_DB:SetAreaPreview(cmd.AreaID, cmd.NumCWRotations, cmd.TickExported, pngData) end --- Processes the data incoming from the network connection function AreaPreview:ProcessIncomingData(a_Data) -- Check params: assert(self) assert(type(a_Data) == "string") -- Log the incoming data to the logfile: if (g_LogFile) then g_LogFile:write("Incoming data (", string.len(a_Data), " bytes):\n", a_Data, "\n\n") end -- Split data on message boundaries self.m_IncomingData = self.m_IncomingData .. a_Data while (true) do local found = self.m_IncomingData:find("\23") if not(found) then return end -- Got a full JSON message from the peer, parse, process and remove it from buffer: local json, msg = cJson:Parse(self.m_IncomingData:sub(1, found)) if not(json) then LOGWARNING(string.format("%sMCSchematicToPng connection received unparsable data: %s", PLUGIN_PREFIX, msg or "[no message]")) self.m_Link:Close() self:Disconnected() return "" end self:ProcessIncomingMessage(json) self.m_IncomingData = self.m_IncomingData:sub(found + 1) end end --- Processes a single incoming message from the network connection function AreaPreview:ProcessIncomingMessage(a_Message) -- Check params: assert(self) assert(type(a_Message) == "table") if (self.m_IsFullyConnected) then return self:ProcessIncomingCmdReply(a_Message) end -- Receiving the initial handshake - name and version information: if not(a_Message.MCSchematicToPng) then LOGWARNING(PLUGIN_PREFIX .. "MCSchematicToPng connection received invalid handshake.") self.m_Link:Close() self:Disconnected() end if (tostring(a_Message.MCSchematicToPng) ~= "2") then LOGWARNING(string.format("%sMCSchematicToPng connection received unhandled protocol version: %s", PLUGIN_PREFIX, tostring(a_Message.MCSchematicToPng)) ) self.m_Link:Close() self:Disconnected() end self.m_IsFullyConnected = true LOG(string.format("%sMCSchematicToPng connected successfully to %s:%s", PLUGIN_PREFIX, self.m_HostName, self.m_Port )) self:SendJson({Cmd = "SetName", Name = "GalExport", CmdID = "SetNameCmdID"}) -- Send the export requests that have been queued: for _, qi in ipairs(self.m_RenderQueue or {}) do self:SendRenderCommand(qi) end self.m_RenderQueue = {} end --- Schedules a refresh for the specified area's preview, if the area has changed since the last preview was -- made (or there's no preview available at all). -- a_DBAreaOrID is the table describing the area, or a single number - the area's ID -- a_NumRotations is the number specifying the number of rotations -- Returns nil and optional error message on failure, true on regeneration success, true and "up-to-date" on -- success when no regen needed function AreaPreview:RefreshPreview(a_DBAreaOrID, a_NumRotations) -- Check params: assert(self) assert((type(a_DBAreaOrID) == "table") or (type(a_DBAreaOrID) == "number")) assert(type(a_NumRotations) == "number") -- If the area is specified using an ID, retrieve the whole DB area table: local area = self:GetDBArea(a_DBAreaOrID) if not(area) then return nil, "Invalid area ID" end -- Check if the preview image is stale: local previewTick, msg = self.m_DB:GetAreaPreviewTickExported(area.ID, a_NumRotations) if not(previewTick) then return nil, "Failed to query last export's tick from DB: " .. (msg or "<no message>") end if (previewTick >= area.TickLastChanged) then return true, "up-to-date" end return self:RegeneratePreview(area, a_NumRotations) end --- Schedules the specified area's preview to be regenerated. -- a_DBAreaOrID is the table describing the area, or a single number - the area's ID -- a_NumRotations is the number specifying the number of rotations -- Returns true on success, nil and optional error message on failure function AreaPreview:RegeneratePreview(a_DBAreaOrID, a_NumRotations) -- Check params: assert(self) assert((type(a_DBAreaOrID) == "table") or (type(a_DBAreaOrID) == "number")) assert(type(a_NumRotations) == "number") -- If the area is specified using an ID, retrieve the whole DB area table: local area = self:GetDBArea(a_DBAreaOrID) if not(area) then return nil, "Invalid area ID" end -- Prepare the request: local request = { Cmd = "RenderSchematic", HorzSize = 6, VertSize = 8, AreaID = area.ID, NumCWRotations = a_NumRotations, } -- Read the area contents from the world: local ba = cBlockArea() local world = cRoot:Get():GetWorld(area.WorldName) world:QueueTask( function () world:ChunkStay( GetAreaChunkCoords(area), nil, function () -- OnAllChunksAvailable callback -- Read the block data into the Json request: ba:Read(world, GetAreaExportCoords(area)) request.BlockData = Base64Encode(ba:SaveToSchematicString()) if not(request.BlockData) then LOGWARNING(string.format("%sFailed to export block area for web preview: AreaID = %d, NumRotations = %d", PLUGIN_PREFIX, area.ID, a_NumRotations )) return end request.TickExported = world:GetWorldAge() -- Send the MCSchematicToPng Json request: if (self.m_IsFullyConnected) then self:SendRenderCommand(request) else table.insert(self.m_RenderQueue, request) self:Connect() end -- Partial cleanup: if ( (self.m_LastWorld ~= world) or -- If exporting in another world than the previous export (self.m_LastGalleryName ~= area.GalleryName) or -- If exporting from a different gallery than the previous export (self.m_NumExported % 10 == 0) -- At regular intervals ) then if (self.m_LastWorld) then self.m_LastWorld:QueueUnloadUnusedChunks() end self.m_LastWorld = world end end -- OnAllChunksAvailable callback ) -- ChunkStay end -- Task callback ) return true end --- Sends the given table as a JSON message to the connected MCSchematicToPng -- a_JsonTable is a table that will be serialized and sent over the network connection function AreaPreview:SendJson(a_JsonTable) -- Check params and preconditions: assert(self) assert(self.m_Link) local json = cJson:Serialize(a_JsonTable) -- DEBUG: Log into file: if (g_LogFile) then g_LogFile:write("Sending JSON:\n", json, "\n\n") end self.m_Link:Send(json) self.m_Link:Send('\23') end --- Sends the specified render command to the connected MCSchematicToPng -- Assumes that the connection is already established -- a_QueueItem is a table describing the export request function AreaPreview:SendRenderCommand(a_RenderCommand) -- Check params and preconditions: assert(self) assert(type(a_RenderCommand) == "table") assert(self.m_IsFullyConnected) -- Assignd CmdID, add to PendingCommands: a_RenderCommand.CmdID = self:GetNextCmdID() self.m_PendingRenderCommands[a_RenderCommand.CmdID] = a_RenderCommand -- Write to the link: self:SendJson(a_RenderCommand) end --- Returns the DB row corresponding to the specified area preview description -- a_AreaID is the ID of the area (in the Areas table) -- a_NumRotations is the number of CW rotations applied before visualising the area -- Returns the entire DB row as a key-value table on success, or nil and optional error message on failure function AreaPreviewDB:GetAreaPreview(a_AreaID, a_NumRotations) -- Check params: assert(self) assert(type(a_AreaID) == "number") assert(type(a_NumRotations) == "number") local res local isSuccess, msg = self:ExecuteStatement( "SELECT * FROM AreaPreviews WHERE AreaID = ? AND NumRotations = ?", { a_AreaID, a_NumRotations, }, function(a_Values) res = a_Values end ) if not(isSuccess) then return nil, msg end return res end --- Returns the TickExported value for the specified area preview description -- a_AreaID is the ID of the area (in the Areas table) -- a_NumRotations is the number of CW rotations applied before visualising the area -- Returns the TickExported value from the DB on success, -1 if there's no such preview in the DB, -- nil and error message on failure function AreaPreviewDB:GetAreaPreviewTickExported(a_AreaID, a_NumRotations) -- Check params: assert(self) assert(type(a_AreaID) == "number") assert(type(a_NumRotations) == "number") local res = -1 local isSuccess, msg = self:ExecuteStatement( "SELECT TickExported FROM AreaPreviews WHERE AreaID = ? AND NumRotations = ?", { a_AreaID, a_NumRotations, }, function(a_Values) res = a_Values.TickExported end ) if not(isSuccess) then return nil, msg end return res end --- Stores the preview for the specified area into the DB -- a_AreaID is the ID of the area (in the Areas table) -- a_NumRotations is the number of CW rotations applied before visualising the area -- a_TickExported is the age of the area's world, in ticks, when the area was exported -- a_PngData is the raw PNG image data (string) -- Returns true on success, nil and optional error message on failure function AreaPreviewDB:SetAreaPreview(a_AreaID, a_NumRotations, a_TickExported, a_PngData) -- Check params: assert(self) assert(type(a_AreaID) == "number") assert(type(a_NumRotations) == "number") assert(type(a_TickExported) == "number") assert(type(a_PngData) == "string") -- Delete any previous image (ignore errors): self:ExecuteStatement( "DELETE FROM AreaPreviews WHERE AreaID = ? AND NumRotations = ?", { a_AreaID, a_NumRotations } ) -- Store new image: return self:ExecuteStatement( "INSERT INTO AreaPreviews (AreaID, NumRotations, TickExported, PngData) VALUES (?, ?, ?, ?)", { a_AreaID, a_NumRotations, a_TickExported, a_PngData } ) end --- Creates a new AreaPreview object based on the specified config -- a_MCSchematicToPngConfig is a table from which the HostName and Port members are used (default: "localhost:9999") -- Returns a AreaPreview object function InitAreaPreview(a_MCSchematicToPngConfig) -- Check params: assert(type(a_MCSchematicToPngConfig) == "table") -- Create the object and extend it with and AreaPreview functions: local res = {} for k, v in pairs(AreaPreview) do assert(not(res[k])) -- Has an implementation with a duplicate name? res[k] = v end -- Create the DB member object: res.m_DB = {} SQLite_extend(res.m_DB) for k, v in pairs(AreaPreviewDB) do assert(not(res.m_DB[k])) -- Has an implementation with a duplicate name? res.m_DB[k] = v end -- Open the DB file: local isSuccess, errCode, errMsg = res.m_DB:OpenDB("GalleryPreviews.sqlite") if not(isSuccess) then LOGWARNING(PLUGIN_PREFIX .. "Cannot open the Previews database: " .. (errCode or "<no errCode>") .. ", " .. (errMsg or "<no message>")) error(errMsg or "<no message>") -- Abort the plugin end -- Create the DB tables and columns, if not already present: local AreaPreviewsColumns = { {"AreaID", "INTEGER"}, {"NumRotations", "INTEGER"}, {"PngData", "BLOB"}, -- The PNG image binary data {"TickExported", "INTEGER"}, -- The world tick on which the preview data was exported } if (not(res.m_DB:CreateDBTable("AreaPreviews", AreaPreviewsColumns))) then error("Cannot create AreaPreviews DB table") end -- Connect to MCSchematicToPng's jsonnet service: res.m_HostName = tostring(a_MCSchematicToPngConfig.HostName) or "localhost" res.m_Port = tonumber(a_MCSchematicToPngConfig.Port) or 9999 res.m_RenderQueue = {} res.m_PendingRenderCommands = {} res.m_IncomingData = "" res:Connect() return res end
require "scripts.core.item" require "gamemode.Spark.modifiers.modifier_armor" require "gamemode.Spark.modifiers.modifier_all_stats"; require "gamemode.Spark.modifiers.modifier_attack_speed"; require "gamemode.Spark.modifiers.modifier_aura_movement_speed"; AegisOfTheHound = class(Item) function AegisOfTheHound:OnCreated () self:SetCastingBehavior(CastingBehavior(CastingBehavior.PASSIVE,CastingBehavior.IMMEDIATE)); end function AegisOfTheHound:OnSpellStart() local caster = self:GetCaster() caster:AddNewModifier(caster, self, "modifier_aura_movement_speed", {duration = self:GetSpecialValue("duration")}) end function AegisOfTheHound:GetModifiers () return { "modifier_armor", "modifier_all_stats", "modifier_aura_attack_speed" } end return AegisOfTheHound
local vehicles = {} local particles = {} function IsVehicleLightTrailEnabled(vehicle) return vehicles[vehicle] == true end function SetVehicleLightTrailEnabled(vehicle, enabled) if IsVehicleLightTrailEnabled(vehicle) == enabled then return end if enabled then local ptfxs = {} local leftTrail = CreateVehicleLightTrail(vehicle, GetEntityBoneIndexByName(vehicle, "taillight_l"), 1.0) local rightTrail = CreateVehicleLightTrail(vehicle, GetEntityBoneIndexByName(vehicle, "taillight_r"), 1.0) table.insert(ptfxs, leftTrail) table.insert(ptfxs, rightTrail) vehicles[vehicle] = true particles[vehicle] = ptfxs else if particles[vehicle] and #particles[vehicle] > 0 then for _, particleId in ipairs(particles[vehicle]) do StopVehicleLightTrail(particleId, 500) end end vehicles[vehicle] = nil particles[vehicle] = nil end end
-- Natural Selection 2 Competitive Mod -- Source located at - https://github.com/xToken/CompMod -- lua\CompMod\Structures\Alien\Shift\shared.lua -- - Dragon -- SHIFT local networkVars = { energizing = "boolean" } AddMixinNetworkVars(InfestationMixin, networkVars) local originalShiftOnInitialized originalShiftOnInitialized = Class_ReplaceMethod("Shift", "OnInitialized", function(self) InitMixin(self, InfestationMixin) originalShiftOnInitialized(self) self.energizing = false end ) function Shift:GetInfestationRadius() return kStructureInfestationRadius end function Shift:GetInfestationMaxRadius() return kStructureInfestationRadius end function Shift:GetIsEnergizing() return self.energizing end function Shift:ShouldGenerateInfestation() return not self.moving end function Shift:TriggerEnergize() self.energizing = true self.energizeStart = Shared.GetTime() self:TriggerEffects("fireworks") return true, true end function Shift:GetTechAllowed(techId, techNode, player) if techId == kTechId.ShiftEnergize and self:GetMaturityLevel() ~= kMaturityLevel.Flourishing then return false, false end return ScriptActor.GetTechAllowed(self, techId, techNode, player) end function Shift:GetTechButtons(techId) return { kTechId.ShiftEnergize, kTechId.Move, kTechId.None, kTechId.None, kTechId.None, kTechId.None, kTechId.None, kTechId.None } end function Shift:EnergizeInRange() if self:GetIsBuilt() then --[[if self:GetIsEnergizing() then local energizeAbles = GetEntitiesWithMixinForTeamWithinXZRange("Energize", self:GetTeamNumber(), self:GetOrigin(), kEnergizeRange) for _, entity in ipairs(energizeAbles) do if (not entity.GetIsEnergizeAllowed or entity:GetIsEnergizeAllowed()) and entity.timeLastEnergizeUpdate + kEnergizeUpdateRate < Shared.GetTime() and entity ~= self then entity:AddEnergy(kPlayerEnergyPerEnergize * self:GetMaturityScaling()) entity.timeLastEnergizeUpdate = Shared.GetTime() end end if self.energizeStart + kShiftEnergizeDuration < Shared.GetTime() then self.energizing = false end else--]] -- Passive energy local energizeAbles = GetEntitiesWithMixinForTeamWithinXZRange("Energize", self:GetTeamNumber(), self:GetOrigin(), kEnergizeRange) for _, entity in ipairs(energizeAbles) do if (not entity.GetIsEnergizeAllowed or entity:GetIsEnergizeAllowed()) and entity.timeLastEnergizeUpdate + kEnergizeUpdateRate < Shared.GetTime() and entity ~= self then entity:AddEnergy(kPlayerPassiveEnergyPerEnergize * self:GetMaturityScaling()) entity.timeLastEnergizeUpdate = Shared.GetTime() end end --end end return self:GetIsAlive() end local originalShiftOnUpdateAnimationInput originalShiftOnUpdateAnimationInput = Class_ReplaceMethod("Shift", "OnUpdateAnimationInput", function(self, modelMixin) originalShiftOnUpdateAnimationInput(self, modelMixin) --modelMixin:SetAnimationInput("asdf", self.energizing) end ) Shared.LinkClassToMap("Shift", Shift.kMapName, networkVars)
require("deepcore/std/class") require("deepcore/std/callable") ---@class SpawnHeroBuilder SpawnHeroBuilder = class() ---@param hero_name string function SpawnHeroBuilder:new(hero_name) self.hero_name = hero_name ---@type PlayerObject self.faction = nil ---@type string self.planet = nil end ---@param faction string function SpawnHeroBuilder:for_faction(faction) self.faction = faction return self end ---@param planet string function SpawnHeroBuilder:on_planet(planet) self.planet = planet return self end function SpawnHeroBuilder:build() return callable { faction = self.faction, hero = self.hero_name, planet = self.planet, call = function(self) local object_type = Find_Object_Type(self.hero) local planet_object = FindPlanet(self.planet) local player_object = Find_Player(self.faction) Spawn_Unit(object_type, planet_object, player_object) end } end
------------------------------------------------------------------------------- -- AdiBags - Korthian Relics By Crackpot (US, Arthas) ------------------------------------------------------------------------------- local addonName, addon = ... local L = setmetatable( {}, { __index = function(self, key) if key then rawset(self, key, tostring(key)) end return tostring(key) end } ) addon.L = L local locale = GetLocale() if locale == "deDE" then --Translation missing elseif locale == "enUS" then L["Korthian Relics"] = true L["Korthian Relics for new the new reputation added in 9.1."] = true L["Korthian Items"] = true L["Random items from Korthia."] = true L["Kothrian Consumables"] = true L["Consumables added from Kothria in 9.1."] = true elseif locale == "esES" then --Translation missing elseif locale == "esMX" then --Translation missing elseif locale == "frFR" then L["Reliques Korthiennes"] = true L["Reliques Korthiennes ajoutées à la 9.1."] = true L["Objets Korthiens"] = true L["Objets aléatoires de Korthia."] = true L["Consommables Korthiens"] = true L["Consommables de Korthia ajoutés à la 9.1."] = true elseif locale == "itIT" then --Translation missing elseif locale == "koKR" then --Translation missing elseif locale == "ptBR" then --Translation missing elseif locale == "ruRU" then --Translation missing elseif locale == "zhCN" then --Translation missing elseif locale == "zhTW" then --Translation missing end -- values by their key for k, v in pairs(L) do if v == true then L[k] = k end end
-- vim: ft=lua ts=2 sw=2 et: local function obj(self, new) local function order(t) table.sort(t); return t end local function str(t, u,ks) ks={}; for k,v in pairs(t) do ks[1+#ks] = k end u={}; for _,k in pairs(order(ks)) do u[1+#u]= #t>0 and tostring(t[k]) or fmt("%s=%s",k,t[k]) end return "{"..table.concat(u,", ").."}" end ------------------------------------- self.__tostring, self.__index = str, self return setmetatable(new or {}, self) end local function from(lo,hi) return lo+(hi-lo)*math.random() end local function within(t) return t[math.random(#t)] end local cocomo={} function cocomo.defaults() local _,ne,nw,nw4,sw,sw4,ne46,w26,sw46 local p,n,s="+","-","*" _ = 0 ne={{_,_,_,1,2,_}, -- bad if lohi {_,_,_,_,1,_}, {_,_,_,_,_,_}, {_,_,_,_,_,_}, {_,_,_,_,_,_}, {_,_,_,_,_,_}} nw={{2,1,_,_,_,_}, -- bad if lolo {1,_,_,_,_,_}, {_,_,_,_,_,_}, {_,_,_,_,_,_}, {_,_,_,_,_,_}, {_,_,_,_,_,_}} nw4={{4,2,1,_,_,_}, -- very bad if lolo {2,1,_,_,_,_}, {1,_,_,_,_,_}, {_,_,_,_,_,_}, {_,_,_,_,_,_}, {_,_,_,_,_,_}} sw={{_,_,_,_,_,_}, -- bad if hilo {_,_,_,_,_,_}, {_,_,_,_,_,_}, {1,_,_,_,_,_}, {2,1,_,_,_,_}, {_,_,_,_,_,_}} sw4={{_,_,_,_,_,_}, -- very bad if hilo {_,_,_,_,_,_}, {1,_,_,_,_,_}, {2,1,_,_,_,_}, {4,2,1,_,_,_}, {_,_,_,_,_,_}} -- bounded by 1..6 ne46={{_,_,_,1,2,4}, -- very bad if lohi {_,_,_,_,1,2}, {_,_,_,_,_,1}, {_,_,_,_,_,_}, {_,_,_,_,_,_}, {_,_,_,_,_,_}} sw26={{_,_,_,_,_,_}, -- bad if hilo {_,_,_,_,_,_}, {_,_,_,_,_,_}, {_,_,_,_,_,_}, {1,_,_,_,_,_}, {2,1,_,_,_,_}} sw46={{_,_,_,_,_,_}, -- very bad if hilo {_,_,_,_,_,_}, {_,_,_,_,_,_}, {1,_,_,_,_,_}, {2,1,_,_,_,_}, {4,2,1,_,_,_}} return { loc = {"1",2,200}, acap= {n,1,5}, cplx={p,1,6}, prec={s,1,6}, aexp= {n,1,5}, data={p,2,5}, flex={s,1,6}, ltex= {n,1,5}, docu={p,1,5}, arch={s,1,6}, pcap= {n,1,5}, pvol={p,2,5}, team={s,1,6}, pcon= {n,1,5}, rely={p,1,5}, pmat={s,1,6}, plex= {n,1,5}, ruse={p,2,6}, sced= {n,1,5}, stor={p,3,6}, site= {n,1,5}, time={p,3,6}, tool= {n,1,5} }, { cplx= {acap=sw46, pcap=sw46, tool=sw46}, --12 ltex= {pcap=nw4}, -- 4 pmat= {acap=nw, pcap=sw46}, -- 6 pvol= {plex=sw}, --2 rely= {acap=sw4, pcap=sw4, pmat=sw4}, -- 12 ruse= {aexp=sw46, ltex=sw46}, --8 sced= {cplx=ne46, time=ne46, pcap=nw4, aexp=nw4, acap=nw4, plex=nw4, ltex=nw, pmat=nw, rely=ne, pvol=ne, tool=nw}, -- 34 stor= {acap=sw46, pcap=sw46}, --8 team= {aexp=nw, sced=nw, site=nw}, --6 time= {acap=sw46, pcap=sw46, tool=sw26}, --10 tool= {acap=nw, pcap=nw, pmat=nw}} end -- 6 --- Effort and rist estimation -- For moldes defined in `risk.lua` and `coc.lua`. --- Define the internal `cocomo` data structure: -- `x` slots (for business-level decisions) and -- `y` slots (for things derived from those decisions, -- like `self.effort` and `self.risk') function cocomo:new(coc,risk) return obj(cocomo, {x={}, y={},coc=coc,risk=risk}) end --- Change the keys `x1,x2...` -- in a model, (and wipe anyting computed from `x`). -- @tab self : a `cocomo` table -- @tab t : a list of key,value pairs that we will update. -- @return tab : an updated `cocomo` table function cocomo:set(t) self.y = {} for k,v in pairs(t) do self.x[k] = v end end --- Compute effort -- @tab self : what we know about a project -- @tab coc : background knowledge about `self` -- @return number : the effort function cocomo:effort() local em,sf=1,0 for k,t in pairs(self.coc) do if t[1] == "+" then em = em * self.y[k] elseif t[1] == "-" then em = em * self.y[k] elseif t[1] == "*" then sf = sf + self.y[k] end end return self.y.a*self.x.loc^(self.y.b + 0.01*sf) * em end --- Compute risk -- @tab self : what we know about a project -- @tab coc : background knowledge about `self` -- @return number : the risk function cocomo:risks() local n=0 for a1,t in pairs(self.risk) do for a2,m in pairs(t) do n = n + m[self.x[a1]][self.x[a2]] end end return n end --- Return a `y` value from `x` -- @tab w : type of column (\*,+,-,1) -- @number x -- @return number function cocomo:y(w,x) if w=="1" then return x end if w=="+" then return (x-3)*from( 0.073, 0.21 ) + 1 end if w=="-" then return (x-3)*from(-0.187, -0.078) + 1 end return (x-6)*from(-1.56, -1.014) end --- Mutatble objects, pairs of `{x,y}` -- Ensures that `y` is up to date with the `x` variables. -- self cocomo:new( function cocomo:ready(coc,risk) local y,effort,ready,lo,hi coc0, risk0 = cocomo.defaults() coc = coc or coc0 risk = risk or risk0 for k,t in pairs(coc) do lo,hi = t[2],t[3] self.x[k] = int(self.x[k] and within(self.x[k],lo,hi) or from(lo,hi)) self.y[k] = self.y[k] or self:y(t[1], self.x[k]) end self.y.a = self.y.a or from(2.3, 9.18) self.y.b = self.y.b or (.85-1.1)/(9.18-2.2)*self.y.a+.9+(1.2-.8)/2 self.y.effort = self.y.effort or cocomo:effort() self.y.risk = self.y.risk or cocomo.risks() return self end Eg.all { one = function(self) local function say() print("") --lib.o(i.x) lib.oo {effort= self.y.effort, loc = self.x.loc, risk = self.y.risk, pcap = self.x.pcap} end self = cocomo.ready() cocomo.new(self, {pcap=4}) self = cocomo.ready(self) say() cocomo.set(self, {pcap=1}) self = cocomo.ready(self) say() end}
local status_ok, grammar_guard = pcall(require, "grammar_guard") if not status_ok then return end grammar_guard.setup({ settings = { ltex = { enabled = { "latex", "txt", "tex", "bib", "markdown", "text" }, language = "en", diagnosticSeverity = "information", setenceCacheSize = 2000, additionalRules = { enablePickyRules = true, motherTongue = "en", }, trace = { server = "verbose" }, dictionary = { ["*"] = { "/usr/share/dict/british-english" }, }, disabledRules = {}, hiddenFalsePositives = {}, }, }, })
#!/usr/bin/env lua -- MoonFLTK example: fonts.lua -- -- Derived from the FLTK test/fonts.cxx example (http://www.fltk.org) -- fl = require("moonfltk") function FontDisplay (B, X, Y, W, H, L) local t = {} t.widget = fl.widget_sub(X, Y, W, H, L) t.font = 0 t.size = 14 t.widget:box(B) t.widget:override_draw(function(wid) assert(wid==t.widget) wid:draw_box() fl.font(t.font, t.size) fl.color(fl.BLACK) fl.draw(wid:label(), wid:x()+3, wid:y()+3, wid:w()-6, wid:h()-6, wid:align()) end) return t end pickedsize = 14 function font_cb() local fn = fontobj:value() if fn == 0 then return end fn = fn - 1 textobj.font = fn sizeobj:clear() local s = sizes[fn] local n = #s if n == 0 then -- no sizes elseif s[1] == 0 then -- many sizes for i = 1, 64 do sizeobj:add(tostring(i)) end sizeobj:value(pickedsize) else -- some sizes local w = 0 for i = 1, #s do if s[i] <= pickedsize then w = i end sizeobj:add(buf) end sizeobj:value(w+1) end textobj.widget:redraw() end function size_cb() local i = sizeobj:value() if i==0 then return end local c = sizeobj:text(i) textobj.size = tonumber(c) textobj.widget:redraw() end function create_the_forms() -- create the sample string local n = 0 local label = "Hello world!\n" for c = 33,126 do n = n + 1 if (n & 0x1f) == 0 then label = label ..'\n' end if c == 64 then label = label .. string.format("%c%c", c, c) -- '@' else label = label .. string.format("%c", c) end end label = label .. "\n" n = 0 for c = 0xA1, 0x600-1, 9 do n = n + 1 if (n & 0x1f) == 0 then label = label ..'\n' end label = label .. utf8.char(c) -- same as fl.utf8encode(c) end label = label .. '\0' -- create the basic layout form = fl.double_window(550,370, arg[0]) tile = fl.tile(0, 0, 550, 370) local textgroup = fl.group(0, 0, 550, 185) textgroup:box("flat box") textobj = FontDisplay("engraved box",10,10,530,170,label) textobj.widget:align("top", "left", "inside", "clip") textobj.widget:color(9,47) textgroup:resizable(textobj.widget) textgroup:done() local fontgroup = fl.group(0, 185, 550, 185) fontgroup:box("flat box") fontobj = fl.hold_browser(10, 190, 390, 170) fontobj:box("engraved box") fontobj:color(53,3) fontobj:callback(font_cb) sizeobj = fl.hold_browser(410, 190, 130, 170) sizeobj:box("engraved box") sizeobj:color(53,3) sizeobj:callback(size_cb) fontgroup:resizable(fontobj) fontgroup:done() tile:done() form:resizable(tile) form:done() end -- main ---------------------------------------------------- fl.scheme() --fl.args(argc, argv) fl.get_system_colors() create_the_forms() -- For the Unicode test, get all fonts... nfonts = fl.set_fonts("-*") sizes = {} for i = 0, nfonts-1 do local name, attr = fl.get_font_name(i) name = ((attr & fl.BOLD) == 0 and "" or "@b") .. ((attr & fl.ITALIC) == 0 and "" or "@i") .. "@." .. -- suspend subsequent formatting (some MS fonts have '@' in their name) name fontobj:add(name) sizes[i] = { fl.get_font_sizes(i) } end fontobj:value(1) font_cb(fontobj,0) form:show(argc,argv) return fl.run()
while true do print(io.read("*n")+1) end
minetest.register_privilege("lavastone_remove", { description = "Can remove lavastone in an area" }) minetest.register_privilege("lava_remove", { description = "Can remove flowing lava in an area" }) minetest.register_privilege("water_remove", { description = "Can remove flowing water in an area" }) if minetest.get_modpath("technic") then minetest.register_privilege("chernobylite_remove", { description = "Can remove chernobylite in an area" }) end
-- == File Module == -- Copyright (c) 2018 by Rene K. Mueller <spiritdude@gmail.com> -- -- License: MIT (see LICENSE file) -- -- Description: -- basic file operations, alike io with some slight alterations like file.read() -- -- History: -- 2018/02/27: 0.0.3: fh:*() cleaner setup using file.*(self,[...]) and argument checking if file.read() or fh:read() is called -- 2018/02/27: 0.0.2: file.open(), file.read() and file.close() work, fh:read() and fh:*() do not yet, file.stat() and file.list() work -- 2018/02/21: 0.0.1: first version, mostly using io.open():xyz convention, but needs to be tested for proper compatibility local lfs = require("lfs") local os = require("os") file = { _VERSION = '0.0.3' } file.chdir = function(d) -- Change current directory (and drive). return lfs.chdir(d) end file.exists = function(fn) -- Determines whether the specified file exists. if true then local st = lfs.attributes(fn) -- better return st and true or false else local f = io.open(fn,"r") -- fallback if f then io.close(f) end return f and true or false end end file.format = function() -- Format the file system. _syslog.print(_syslog.ERROR,"file.format() not yet implemented") end file.fscfg = function() -- Returns the flash address and physical size of the file system area, in bytes. local path, total, used, avail, usep, mount = file.fsinfo() return 0, total * 1024 end file.fsinfo = function() -- Return size information for the file system in kbytes local f = io.popen("df -k .") _ = f:read("*line") _ = f:read("*line") f:close() local path, total, used, avail, usep, mount = _:match("^(%S+)%s+(%d+)%s+(%d+)%s+(%d+)%s+(%S+)%s+(%S+)"); return avail, used, total end file.list = function(d) -- Lists all files in the file system. local fl = { } for f in lfs.dir(d or ".") do local st = lfs.attributes((d or ".").."/"..f) fl[f] = st.size or 0 end return fl end file.mount = function() -- Mounts a FatFs volume on SD card. _syslog.print(_syslog.ERROR,"file.mount() not implemented yet") end file.on = function() -- Registers callback functions. _syslog.print(_syslog.ERROR,"file.on() not implemented yet") end file.open = function(fn,m) file._fh = io.open(fn,m) if file._fh then return { _fh = file._fh, read = file.read, readline = file.readline, write = file.write, writeline = file.writeline, flush = file.flush, close = file.close, seek = file.seek } end return nil end file.remove = function(fn) -- Remove a file from the file system. return os.remove(fn) end file.rename = function(fno,fnn) -- Renames a file. return os.rename(fno,fnn) end file.stat = function(fn) -- Get attribtues of a file or directory in a table. local st = lfs.attributes(fn) local s = { } if st then s.size = st.size or null s.name = fn s.is_dir = st.mode == 'directory' s.is_rdonly = false s.is_hidden = false s.is_sys = false s.is_arch = false s.time = rtctime.epoch2cal(st.modification) return s else return st end end -- Basic model: In the basic model there is max one file opened at a time. -- Object model: Files are represented by file objects which are created by file. file.close = function(self) (self and self._fh or file._fh):close() end file.flush = function(self) -- Flushes any pending writes to the file system, ensuring no data is lost on a restart. (self and self._fh or file._fh):flush() end file.read = function(self,sep) local fh if type(self)=='table' then -- called as f:read(sep) --print("fh:read",type(self),self,sep) fh = self._fh else -- called as file.read(sep) --print("file.read",type(self),self,sep) fh = file._fh sep = self end if not sep then return fh:read("*all") elseif type(sep)=='number' then return fh:read(sep) else local c local b repeat c = fh:read(1) if c then b = (b or "") .. (c or '') end until c == sep or not c return b end end file.readline = function(self) return (self._fh or file._fh):read("*line") end file.seek = function(...) -- Sets and gets the file position, measured from the beginning of the file, to the position given by offset plus a base specified by the string whence. local fh = type(arg[1])=='table' and table.remove(arg,1)._fh or file._fh local w, o = arg[1], arg[2] return fh:seek(w,o) end file.write = function(self,s) -- Write a string to the open file. local fh if type(self)=='table' then fh = self._fh else fh = file._fh s = self end return fh:write(s) end file.writeline = function(self,s) -- Write a string to the open file and append '\n' at the end. local fh if type(self)=='table' then fh = self._fh else fh = file._fh s = self end return fh:write(s.."\n") end table.insert(node.modules,'file') return file;
local fs = fs or {} -- props to capsadmin for dis -- https://raw.githubusercontent.com/CapsAdmin/goluwa/master/src/lua/modules/fs.lua if WINDOWS then local ffi = require("ffi") ffi.cdef([[ typedef struct hexed_file_time { unsigned long high; unsigned long low; } hexed_file_time; typedef struct hexed_find_data { unsigned long dwFileAttributes; hexed_file_time ftCreationTime; hexed_file_time ftLastAccessTime; hexed_file_time ftLastWriteTime; unsigned long nFileSizeHigh; unsigned long nFileSizeLow; unsigned long dwReserved0; unsigned long dwReserved1; char cFileName[260]; char cAlternateFileName[14]; } hexed_find_data; void *FindFirstFileA(const char *lpFileName, hexed_find_data *find_data); bool FindNextFileA(void *handle, hexed_find_data *find_data); bool FindClose(void *); unsigned long GetCurrentDirectoryA(unsigned long length, char *buffer); bool SetCurrentDirectoryA(const char *path); bool CreateDirectoryA(const char *path, void *lpSecurityAttributes); typedef struct hexed_file_attributes { unsigned long dwFileAttributes; hexed_file_time ftCreationTime; hexed_file_time ftLastAccessTime; hexed_file_time ftLastWriteTime; unsigned long nFileSizeHigh; unsigned long nFileSizeLow; } hexed_file_attributes; bool GetFileAttributesExA( const char *lpFileName, int fInfoLevelId, hexed_file_attributes *lpFileInformation ); ]]) local data = ffi.new("hexed_find_data[1]") function fs.find(dir, exclude_dot) local out = {} if dir:sub(-1) ~= "/" then dir = dir .. "/" end local handle = ffi.C.FindFirstFileA(dir .. "*", data) if ffi.cast("unsigned long", handle) ~= 0xffffffff then local i = 1 while ffi.C.FindNextFileA(handle, data) do local name = ffi.string(data[0].cFileName) if not exclude_dot or (name ~= "." and name ~= "..") then out[i] = name i = i + 1 end end ffi.C.FindClose(handle) end return out end function fs.getcd() local buffer = ffi.new("char[260]") local length = ffi.C.GetCurrentDirectoryA(260, buffer) return ffi.string(buffer, length) end function fs.setcd(path) ffi.C.SetCurrentDirectoryA(path) end function fs.createdir(path) ffi.C.CreateDirectoryA(path, nil) end local flags = { archive = 0x20, -- A file or directory that is an archive file or directory. Applications typically use this attribute to mark files for backup or removal . compressed = 0x800, -- A file or directory that is compressed. For a file, all of the data in the file is compressed. For a directory, compression is the default for newly created files and subdirectories. device = 0x40, -- This value is reserved for system use. directory = 0x10, -- The handle that identifies a directory. encrypted = 0x4000, -- A file or directory that is encrypted. For a file, all data streams in the file are encrypted. For a directory, encryption is the default for newly created files and subdirectories. hidden = 0x2, -- The file or directory is hidden. It is not included in an ordinary directory listing. integrity_stream = 0x8000, -- The directory or user data stream is configured with integrity (only supported on ReFS volumes). It is not included in an ordinary directory listing. The integrity setting persists with the file if it's renamed. If a file is copied the destination file will have integrity set if either the source file or destination directory have integrity set. normal = 0x80, -- A file that does not have other attributes set. This attribute is valid only when used alone. not_content_indexed = 0x2000, -- The file or directory is not to be indexed by the content indexing service. no_scrub_data = 0x20000, -- The user data stream not to be read by the background data integrity scanner (AKA scrubber). When set on a directory it only provides inheritance. This flag is only supported on Storage Spaces and ReFS volumes. It is not included in an ordinary directory listing. offline = 0x1000, -- The data of a file is not available immediately. This attribute indicates that the file data is physically moved to offline storage. This attribute is used by Remote Storage, which is the hierarchical storage management software. Applications should not arbitrarily change this attribute. readonly = 0x1, -- A file that is read-only. Applications can read the file, but cannot write to it or delete it. This attribute is not honored on directories. For more information, see You cannot view or change the Read-only or the System attributes of folders in Windows Server 2003, in Windows XP, in Windows Vista or in Windows 7. reparse_point = 0x400, -- A file or directory that has an associated reparse point, or a file that is a symbolic link. sparse_file = 0x200, -- A file that is a sparse file. system = 0x4, -- A file or directory that the operating system uses a part of, or uses exclusively. temporary = 0x100, -- A file that is being used for temporary storage. File systems avoid writing data back to mass storage if sufficient cache memory is available, because typically, an application deletes a temporary file after the handle is closed. In that scenario, the system can entirely avoid writing the data. Otherwise, the data is written after the handle is closed. virtual = 0x10000, -- This value is reserved for system use. } local function flags_to_table(bits) local out = {} for k,v in pairs(flags) do out[k] = bit.bor(bits, v) == v end return out end local info = ffi.new("hexed_file_attributes[1]") local COMBINE = function(hi, lo) return bit.band(bit.lshift(hi, 8), lo) end function fs.getattributes(path) if fs.debug then logn(path) end if ffi.C.GetFileAttributesExA(path, 0, info) then --local flags = flags_to_table(info[0].dwFileAttributes) -- overkill local type -- hmmm if --[[flags.archive]] bit.bor(info[0].dwFileAttributes, flags.archive) == flags.archive or bit.bor(info[0].dwFileAttributes, flags.normal) == flags.normal then type = "file" else type = "directory" local file = io.open(path, "r") if file then io.close(file) type = "file" end end local info = { creation_time = COMBINE(info[0].ftCreationTime.high, info[0].ftCreationTime.low), last_accessed = COMBINE(info[0].ftLastAccessTime.high, info[0].ftLastAccessTime.low), last_modified = COMBINE(info[0].ftLastWriteTime.high, info[0].ftLastWriteTime.low), last_changed = -1, -- last permission changes size = info[0].nFileSizeLow,--COMBINE(info[0].nFileSizeLow, info[0].nFileSizeHigh), type = type, --- flags = flags, } return info end end else -- fuck off linux were not ready for you end return fs
-- Tests for avg.lua (Mathematical class library) -- Written by Michiel Fokke <michiel@fokke.org> -- MIT license, http://opensource.org/licenses/MIT -- use with 'shake' (http://shake.luaforge.net) package.path = package.path..';../?.lua' require 'mcl' a = newRingbuffer() assert (type(a) == 'table', "a should be a table") assert (a.avg() ~= a.avg(), "avg should be -nan") assert (a.push(1) == 1, "return should be equal to input parameter") assert (a.avg() == 1, "avg should be 1") assert (a.push(1) == 1, "return should be equal to input parameter") assert (a.push(4) == 4, "return should be equal to input parameter") assert (a.sum() == 6, "sum should be 6") assert (a.avg() == 2, "avg should be 2") assert (a.push(4) == 4, "return should be equal to input parameter") assert (a.avg() == 3, "avg should be 3") a2 = newRingbuffer() assert (a2.push(2) == 2, "return should be equal to input parameter") assert (a2.avg() == 2, "avg should be 2") assert (a2.push(2) == 2, "return should be equal to input parameter") assert (a2.push(5) == 5, "return should be equal to input parameter") assert (a2.sum() == 9, "sum should be 3") assert (a2.avg() == 3, "avg should be 9") b = newRunningAverage() assert (type(b) == 'table', "b should be a table") assert (b.avg() ~= b.avg(), "avg should be -nan") assert (b.push(2) == 1, "n should be 1") assert (b.push(1) == 2, "n should be 2") assert (b.avg() == 1.5, "avg should be 1.5") assert (b.push(3) == 3, "n should be 3") assert (b.avg() == 2, "avg should be 2") assert (b.reset() == 0, "return should be 0") assert (b.avg() ~= b.avg(), "avg should be -nan") assert (b.push(2) == 1, "n should be 1") assert (b.push(1) == 2, "n should be 2") assert (b.avg() == 1.5, "avg should be 1.5") assert (b.push(3) == 3, "n should be 3") assert (b.avg() == 2, "avg should be 2") size = 5 maxElements = 100 c = newRunningAverageList{size=size, maxElements=maxElements} assert (c.avg() ~= c.avg(), "current average should be -nan") sum = 0 assert (type(c) == 'table', "c should be a table") for i=1,size*2 do sum = sum + 3 for j=1,maxElements,1 do c.push(3) end end assert (c.index() == 0, "index should be 0 again") assert (c.avg() == sum/(2*size), "current average is wrong") for i=1,size do assert (c.avg(i) == sum/(2*size), "average is wrong") end result = { 3.6, 4.2, 4.8, 5.4, 6 } for i=1,size do for j=1,maxElements do c.push(6) end print(string.format("avg==result[%d]", i)) assert (c.avg() == result[i], "average is wrong") end -- vim: set si ts=2 sw=2 expandtab:
--[[ Copyright (c) 2019 Void Works See LICENSE in the project directory for license information. Most of the credit for this mod goes to authors below whose code was compiled: Original "Fluid Void" mod by Rseding91 - redesigned by Nibuja05 (control code used for fluid voiding) "High Pressure Pipe" mod by kendfrey (code used for void pipe creation and tinting) "Void Chest +" mod by Optera (code used for void chest creation and function) --]] require("prototypes.entity") require("prototypes.item") require("prototypes.recipe") require("prototypes.technology")
Stat = Object:extend() function Stat:new(base) self.base = base self.additive = 0 self.additives = {} self.value = self.base*(1 + self.additive) end function Stat:update(dt) for _, additive in ipairs(self.additives) do self.additive = self.additive + additive end if self.additive >= 0 then self.value = self.base*(1 + self.additive) else self.value = self.base/(1 - self.additive) end self.additive = 0 self.additives = {} end function Stat:increase(percentage) table.insert(self.additives, percentage*0.01) end function Stat:decrease(percentage) table.insert(self.additives, -percentage*0.01) end
local Bar = script:GetCustomProperty("Bar"):WaitForObject() local Cursor = script:GetCustomProperty("Cursor"):WaitForObject() local Root = script:GetCustomProperty("Root"):WaitForObject() local GetAbsoluteUI = require(script:GetCustomProperty("GetAbsoluteUI")) local LOCAL_PLAYER = Game.GetLocalPlayer() local EventSetUp = require(script:GetCustomProperty("EventSetUp")) local ScreenSizeChanged = require(script:GetCustomProperty("ScreenSizeChanged")) local percent = 0 local Slider = { beingPressed = false, updateEvent = EventSetUp.New(), changedEvent = EventSetUp.New(), x = 0, y = 0, } local function SetUp() local Pos = GetAbsoluteUI.GetAbsoluteLocation(Bar) Slider.x = Pos.x Slider.y = Pos.y if Cursor then Cursor.x = Bar.width* Bar.progress end Root.clientUserData.Slider = Slider end local function Update() local Pos = GetAbsoluteUI.GetAbsoluteLocation(Bar) Slider.x = Pos.x Slider.y = Pos.y end local function Checkmouse(mouse) if not Object.IsValid(Bar) then return end if mouse.x >= Slider.x and mouse.x <= Slider.x+Bar.width then if mouse.y >= Slider.y and mouse.y <= Slider.y + Bar.height then return true end end end local function CalPercent(mouse) return (mouse.x - Slider.x )/ Bar.width end local function UpdateSlider() Bar.progress = percent if Cursor then Cursor.x = Bar.width* percent end Slider.changedEvent:_Fire(Slider, percent) end local function UpdateSliderMouse() local mouse = UI.GetCursorPosition() mouse.x = math.max(Slider.x,math.min(Slider.x+Bar.width,mouse.x)) local NewPercent = CalPercent(mouse) Slider.updateEvent:_Fire(Slider, NewPercent) if percent == NewPercent then return end percent = NewPercent UpdateSlider() end function Slider:SetPercent(newPercent) percent = newPercent UpdateSlider() end function Slider:IsA(type) return type == "Slider" end local function Pressed(_,binding) local mouse = UI.GetCursorPosition() if binding == "ability_primary" then if Checkmouse(mouse) then Slider.beingPressed = true end end end local function Released(_,binding) if binding == "ability_primary" then Slider.beingPressed = false end end function Tick() if Slider.beingPressed then UpdateSliderMouse() end end SetUp() local ScreenEvent = ScreenSizeChanged.screensizeUpdated:Connect( Update) local PresedEvent = LOCAL_PLAYER.bindingPressedEvent:Connect(Pressed) local ReleaseddEvent =LOCAL_PLAYER.bindingReleasedEvent:Connect(Released) script.destroyEvent:Connect(function() ScreenEvent:Disconnect() PresedEvent:Disconnect() ReleaseddEvent:Disconnect() end)
--[[ 代理服务器 ]] local skynet = require "skynet" local socket = require "skynet.socket" local cjson = require("cjson"); require("LuaKit._load"); local WATCHDOG local host local send_request local Agent = {} local client_fd local function send_package(cmd,data) local struct = string; local body = cjson.encode(data) local len = 6 + #body; local head = struct.pack('>I2I4',len,cmd); local package = head .. body; socket.write(client_fd, package) end function Agent.onRecv(fd,cmd,data) dump(data,cmd) if cmd == 101 then skynet.send("LoginService", "lua", "login",fd,cmd,data) else skynet.send("TableManager", "lua", "onRecv",fd,cmd,data) end end ---主动关闭连接 -- function REQUEST:quit() -- skynet.call(WATCHDOG, "lua", "close", client_fd) -- end skynet.register_protocol { name = "client", id = skynet.PTYPE_CLIENT, unpack = function (msg, sz) local buf = skynet.tostring(msg,sz) local struct = string; local len,cmd,position position = 1 cmd,position = struct.unpack('>I4',buf,position) --获取命令字 cmd local bodyBuf = string.sub(buf,5,sz) local data = cjson.decode(bodyBuf); return cmd,data end, dispatch = function (fd, _, cmd, ...) assert(fd == client_fd) -- You can use fd to reply message skynet.ignoreret() -- session is fd, don't call skynet.ret -- skynet.trace() Agent.onRecv(fd,cmd, ...) return fd, _, cmd, ... end } function Agent.start(conf) --- watchdog 调用过来 local fd = conf.client local gate = conf.gate WATCHDOG = conf.watchdog client_fd = fd --调用网关 gate forward 向前 打开 fd socket skynet.call(gate, "lua", "forward", fd) end function Agent.disconnect(fd) -- todo: do something before exit print("agent.lua disconnect") skynet.call("TableManager", "lua", "user_disconnect", client_fd) print("用户断开连接",client_fd); client_fd = nil; skynet.exit() end skynet.start(function() skynet.dispatch("lua", function(_,_, command, ...) local f = Agent[command] skynet.ret(skynet.pack(f(...))) end) end)
--- --- Generated by EmmyLua(https://github.com/EmmyLua) --- Created by norguhtar. --- DateTime: 26.02.19 13:02 --- local lapis = require('data-mapper.db.lapis') local postgres = require('data-mapper.db.postgres') local mysql = require('data-mapper.db.mysql') local pg = require("data-mapper.db.pg") local db = {} local drivers = { lapis = lapis, postgres = postgres, mysql = mysql, ["tarantool-pg"] = pg } function db:new(obj) obj = obj or {} local config = obj.config if drivers[config.driver] then return drivers[config.driver]:new(obj) else return nil end end return db
#!/usr/bin/env luajit require 'ext' local env = setmetatable({}, {__index=_G}) if setfenv then setfenv(1, env) else _ENV = env end require 'symmath'.setup{env=env, MathJax={title='Platonic Solids'}} printbr[[ $n =$ dimension of manifold which our shape resides in.<br> $\tilde{T}_i \in \mathbb{R}^{n \times n} =$ i'th isomorphic transform in the minimal set.<br> $\tilde{\textbf{T}} = \{ 1 \le i \le p, \tilde{T}_i \} =$ minimum set of isomorphic transforms that can be used to recreate all isomorphic transforms.<br> $p = |\tilde{\textbf{T}}| =$ the number of minimal isomorphic transforms.<br> $T_i \in \mathbb{R}^{n \times n} =$ i'th isomorphic transform in the set of all unique transforms.<br> $\textbf{T} = \{ T_i \} = \{ 1 \le k, i_1, ..., i_k \in [1,m], \tilde{T}_{i_1} \cdot ... \cdot \tilde{T}_{i_k} \} =$ set of all unique isomorphic transforms.<br> $q = |\textbf{T}| =$ the number of unique isomorphic transforms.<br> $v_1 \in \mathbb{R}^n =$ some arbitrary initial vertex.<br> $\textbf{v} = \{v_i \} = \{ T_i \cdot v_1 \} =$ the set of all vertices.<br> $m = |\textbf{v}| =$ the number of vertices.<br> (Notice that $m \le q$, i.e. the number of vertices is $\le$ the number of unique isomorphic transforms.) <br> $V \in \mathbb{R}^{n \times m}=$ matrix with column vectors the set of all vertices, such that $V_{ij} = (v_j)_i$.<br> $P_i \in \mathbb{R}^{m \times m} =$ permutation transform of vertices corresponding with i'th transformation, such that $T_i V = V P_i$.<br> <br> ]] --[[ ok here's another thought ... rotation from a to b, assuming a and b are orthonormal: R v = v - a (v.a) - b (v.b) + (a (v.a) + b (v.b)) cos(θ) + (b (v.a) - a (v.b)) sin(θ) = v - a (v.a) - b (v.b) + (a (v.a) + b (v.b)) cos(θ) + (b (v.a) - a (v.b)) sin(θ) = (I + (cos(θ)-1) aa' - sin(θ) ab' + sin(θ) ba' + (cos(θ)-1) bb') v = (I + (cos(θ)-1) (aa' + bb') + sin(θ) (ba' - ab')) v --]] local function rotfromto(theta, from, to) from = from:unit() to = (Matrix.projection(from:T()[1]) * to)():unit() return ( Matrix.identity(#from) + (cos(theta) - 1) * (from * from:T() + to * to:T()) + sin(theta) * (to * from:T() - from * to:T()) )() end --[=[ --[[ for a 3D platonic solid, if you know the vertices, you can make a rotation from (proj a) * b to (proj a) * c --]] printbr(rotfromto( frac(2*pi,3), (Matrix.projection{1,0,0} * Matrix{-frac(1,3), sqrt(frac(2,3)), -frac(sqrt(2),3)}:T())(), (Matrix.projection{1,0,0} * Matrix{-frac(1,3), 0, frac(sqrt(8),3)}:T())() )) os.exit() --]=] local phi = (sqrt(5) - 1) / 2 -- [[ local tetRot = Matrix.identity(3) --]] --[[ matrix to rotate 1/sqrt(3) (1,1,1) to (1,0,0) -- applying this isn't as isometric as I thought it would be -- cubeRot = Matrix.rotation(acos(1/sqrt(3)), Matrix(1,1,1):cross{1,0,0}:unit()) -- rotate from unit(1,1,1) to (1,0,0) local cubeRot = Matrix( { 1/sqrt(3), 1/sqrt(3), 1/sqrt(3) }, { -1/sqrt(3), (1 + sqrt(3))/(2*sqrt(3)), (1 - sqrt(3))/(2*sqrt(3)) }, { -1/sqrt(3), (1 - sqrt(3))/(2*sqrt(3)), (1 + sqrt(3))/(2*sqrt(3)) } ) --]] -- [[ use [1,1,1]/sqrt(3) local cubeRot = Matrix.identity(3) --]] --[[ local dodVtx = Matrix{ (-1 - sqrt(5)) / (2 * sqrt(3)), 0, (1 - sqrt(5)) / (2 * sqrt(3)) } local dodRot = Matrix.rotation(acos(dodVtx[1][1]), dodVtx[1]:cross{1, 0, 0}:unit()) --]] -- [[ local dodRot = Matrix.identity(3) --]] --[[ produces an overly complex poly that can't simplify --[=[ local icoRot = Matrix.rotation(acos(0), Array(0, 1, phi):cross{1,0,0}:unit()) --]=] local icoVtx = Matrix{0, 1, phi} printbr(icoVtx) local icoRot = Matrix.rotation( acos(icoVtx[1][1]), icoVtx[1]:cross{1,0,0}:unit()) --]] -- [[ works local icoRot = Matrix.identity(3) --]] --[[ how to define the transforms? these should generate the vertexes, right? the vertex set should be some identity vertex times any combination of these transforms so we should be able to define a cube by a single vertex v_0 = [1,1,1] times any combination of traversals along its edges which for [1,1,1] would just three transforms, where the other 3 are redundant: identity transforms: this can be the axis from the center of object to any vertex, with rotation angle equal to the edge-vertex-edge angle or it can be the axis from center of object to center of any face, with rotation angle equal to 2π/n for face with n edges or it can be the axis through any edge (?right?) with ... some other kind of rotation ... --]] local shapes = { -- [=[ { -- self-dual name = 'Tetrahedron', vtx1 = (tetRot * Matrix{0, 0, 1}:T())(), dim = 3, xforms = (function() local a = {-sqrt(frac(2,3)), -sqrt(2)/3, -frac(1,3)} local b = {sqrt(frac(2,3)), -sqrt(2)/3, -frac(1,3)} local c = {0, sqrt(8)/3, -frac(1,3)} local d = {0, 0, 1} return table{ (tetRot * --Matrix.rotation(frac(2*pi,3), { -frac(1,3), 0, sqrt(frac(8,9)) }) rotfromto( frac(2*pi,3), (Matrix.projection(c) * Matrix(a):T())(), (Matrix.projection(c) * Matrix(b):T())() ) * tetRot:T())(), (tetRot * --Matrix.rotation(frac(2*pi,3), { -frac(1,3), -sqrt(frac(2,3)), -sqrt(frac(2,9)) }) rotfromto( frac(2*pi,3), (Matrix.projection(d) * Matrix(a):T())(), (Matrix.projection(d) * Matrix(b):T())() ) * tetRot:T())(), } end)(), }, --]=] --[=[ -- dual of octahedron { name = 'Cube', dim = 3, --vtx1 = (cubeRot * Matrix{ 1/sqrt(3), 1/sqrt(3), 1/sqrt(3) }:T())(), vtx1 = (cubeRot * Matrix{ 1, 1, 1 }:T())(), xforms = { (cubeRot * Matrix.rotation(frac(pi,2), {1,0,0}) * cubeRot:T())(), (cubeRot * Matrix.rotation(frac(pi,2), {0,1,0}) * cubeRot:T())(), --(cubeRot * Matrix.rotation(frac(pi,2), {0,0,1}) * cubeRot:T())(), -- z = x*y --(cubeRot * Matrix.diagonal(-1, 1, 1) * cubeRot:T())(), reflection? }, }, --]=] --[=[ -- dual of cube { name = 'Octahedron', dim = 3, xforms = { Matrix.rotation(frac(pi,2), {1,0,0})(), Matrix.rotation(frac(pi,2), {0,1,0})(), --Matrix.rotation(frac(pi,2), {0,0,1})(), -- z = x*y }, }, --]=] --[=[ -- dual of icosahedron { name = 'Dodecahedron', dim = 3, --vtx1 = (dodRot * Matrix{1/phi, 0, phi}:T():unit())(), vtx1 = (dodRot * Matrix{1/phi, 0, phi}:T())(), xforms = { -- axis will be the center of the face adjacent to the first vertex at [1,0,0] (dodRot * Matrix.rotation(frac(2*pi,3), Matrix{-1/phi, 0, phi}:unit()[1] ) * dodRot:T())(), -- correctly produces 3 vertices (dodRot * Matrix.rotation(frac(2*pi,3), Matrix{0, phi, 1/phi}:unit()[1] ) * dodRot:T())(), -- the first 2 transforms will produces 12 vertices and 12 transforms (dodRot * Matrix.rotation(frac(2*pi,3), Matrix{1,1,1}:unit()[1] ) * dodRot:T())(), -- all 3 transforms produces all 20 vertices and 60 transforms }, }, --]=] --[=[ -- dual of dodecahedron { name = 'Icosahedron', dim = 3, --vtx1 = (icoRot * Matrix{ 0, 1, phi }:T():unit())(), vtx1 = (icoRot * Matrix{ 0, 1, phi }:T())(), -- don't unit. xforms = { (icoRot * Matrix.rotation(frac(2*pi,5), Matrix{0, -1, phi}:unit()[1] ) * icoRot:T())(), (icoRot * Matrix.rotation(frac(2*pi,5), Matrix{1, phi, 0}:unit()[1] ) * icoRot:T())(), (icoRot * Matrix.rotation(frac(2*pi,5), Matrix{-1, phi, 0}:unit()[1] ) * icoRot:T())(), }, }, --]=] --[=[ { -- self-dual name = '5-cell', dim = 4, vtx1 = Matrix{frac(sqrt(15),4), 0, 0, -frac(1,4)}:T(), --vtx1 = Matrix{0, 0, 0, 1}:T(), xforms = (function() local a = {sqrt(15)/4, 0, 0, -frac(1,4)} local b = {-sqrt(frac(5,3))/4, 0, sqrt(frac(5,6)), -frac(1,4)} local c = {-sqrt(frac(5,3))/4, sqrt(frac(5,2))/2, -sqrt(frac(5,24)), -frac(1,4)} local d = {0,0,0,1} --local e = {-sqrt(frac(5,3))/4, -sqrt(frac(5,2))/2, -sqrt(frac(5,24)), -frac(1,4)} -- not used, in the cd rotation plane anyways return table{ -- generate a tetrahedron: rotfromto( frac(2*pi,3), (Matrix.projection(d) * Matrix.projection( (Matrix.projection(d) * Matrix(c):T())():T()[1] ) * Matrix(a):T())(), (Matrix.projection(d) * Matrix.projection( (Matrix.projection(d) * Matrix(c):T())():T()[1] ) * Matrix(b):T())() ), rotfromto( frac(2*pi,3), (Matrix.projection(d) * Matrix.projection( (Matrix.projection(d) * Matrix(a):T())():T()[1] ) * Matrix(c):T())(), (Matrix.projection(d) * Matrix.projection( (Matrix.projection(d) * Matrix(a):T())():T()[1] ) * Matrix(b):T())() ), -- generate the entire 5-cell rotfromto( frac(2*pi,3), (Matrix.projection(a) * Matrix.projection( (Matrix.projection(a) * Matrix(b):T())():T()[1] ) * Matrix(c):T())(), (Matrix.projection(a) * Matrix.projection( (Matrix.projection(a) * Matrix(b):T())():T()[1] ) * Matrix(d):T())() ), } --]] end)(), } --]=] --[=[ { -- hypercube, dual to 16-cell name = '8-cell', dim = 4, --vtx1 = Matrix{1/sqrt(4), 1/sqrt(4), 1/sqrt(4), 1/sqrt(4)}:T(), vtx1 = Matrix{1, 1, 1, 1}:T(), xforms = { Matrix( -- xy {0,-1,0,0}, {1,0,0,0}, {0,0,1,0}, {0,0,0,1} )(), Matrix( -- xz {0,0,1,0}, {0,1,0,0}, {-1,0,0,0}, {0,0,0,1} )(), Matrix( -- xw {0,0,0,-1}, {0,1,0,0}, {0,0,1,0}, {1,0,0,0} )(), }, }, --]=] --[=[ { -- dual to 8-cell name = '16-cell', dim = 4, vtx1 = Matrix{1, 0, 0, 0}:T(), xforms = { Matrix( {0,-1,0,0}, {1,0,0,0}, {0,0,1,0}, {0,0,0,1} )(), Matrix( {0,0,1,0}, {0,1,0,0}, {-1,0,0,0}, {0,0,0,1} )(), Matrix( {0,0,0,-1}, {0,1,0,0}, {0,0,1,0}, {1,0,0,0} )(), }, }, --]=] -- TODO 4D 24-cell self-dual -- TODO 4D 600-cell dual to 120-cell -- TODO 4D 120-cell dual to 600-cell -- TODO 5D 5-simplex self-dual -- TODO 5D 5-cube dual to 5-orthoplex -- TODO 5D 5-orthoplex dual to 5-cube -- TODO 6D 6-simplex -- TODO 6D 6-orthoplex -- TODO 6D 6-cube -- TODO 7D 7-simplex self-dual -- TODO 7D 7-cube dual to 7-orthoplex -- TODO 7D 7-orthoplex dual to 7-cube -- TODO 8D 8-simplex self-dual -- TODO 8D 8-cube dual to 8-orthoplex -- TODO 8D 8-orthoplex dual to 8-cube } for _,shape in ipairs(shapes) do shapes[shape.name] = shape end local MathJax = symmath.export.MathJax MathJax.header.pathToTryToFindMathJax = '..' symmath.tostring = MathJax os.mkdir'output/Platonic Solids' for _,shape in ipairs(shapes) do printbr('<a href="Platonic Solids/'..shape.name..'.html">'..shape.name..'</a> ('..shape.dim..' dim)') end printbr() local cache = {} local cacheFilename = 'Platonic Solids - cache.lua' if os.fileexists(cacheFilename) then cache = load('return '..io.readfile(cacheFilename), nil, nil, env)() end for _,shape in ipairs(shapes) do io.stderr:write(shape.name,'\n') io.stderr:flush() MathJax.header.title = shape.name local f = assert(io.open('output/Platonic Solids/'..shape.name..'.html', 'w')) local function write(...) return f:write(...) end local function print(...) write(table{...}:mapi(tostring):concat'\t'..'\n') end local function printbr(...) print(...) print'<br>' end print(MathJax.header) print[[ <style> table { border : 1px solid black; border-collapse : collapse; } table td { border : 1px solid black; } </style> ]] local shapeCache = cache[shape.name] if not shapeCache then shapeCache = {} cache[shape.name] = shapeCache end --print('<a name="'..shape.name..'">') print('<h3>'..shape.name..'</h3>') local n = shape.dim shapeCache.n = shape.dim local vtx1 = shape.vtx1 or Matrix:lambda({n,1}, function(i,j) return i==1 and 1 or 0 end) shapeCache.vtx1 = vtx1 printbr('Initial vertex:', var'v''_1':eq(vtx1)) printbr() local xforms = table(shape.xforms) xforms:insert(1, Matrix.identity(n)) shapeCache.xforms = xforms printbr'Transforms for vertex generation:' printbr() printbr(var'\\tilde{T}''_i', [[$\in \{$]], xforms:mapi(tostring):concat',', [[$\}$]]) printbr() printbr'Vertexes:' printbr() local vtxs = table{vtx1()} shapeCache.vtxs = vtxs local function buildvtxs(j, depth) depth = depth or 1 local v = vtxs[j] for i,xform in ipairs(xforms) do local xv = (xform * v)() local k = vtxs:find(xv) if not k then vtxs:insert(xv) k = #vtxs printbr((var'T'('_'..i) * var'V'('_'..j)):eq(xv):eq(var'V'('_'..k))) buildvtxs(k, depth + 1) else -- printbr((var'T'('_'..i) * var'V'('_'..j)):eq(xv):eq(var'V'('_'..k))) end end end buildvtxs(1) printbr() -- number of vertexes local nvtxs = #vtxs shapeCache.nvtxs = nvtxs local allxforms = table(xforms) shapeCache.allxforms = allxforms -- [[ printbr'All Transforms:' printbr() local function buildxforms(j, depth) depth = depth or 1 local M = allxforms[j] for i,xform in ipairs(xforms) do local xM = (xform * M)() local k = allxforms:find(xM) if not k then allxforms:insert(xM) k = #allxforms printbr((var'T'('_'..i) * var'T'('_'..j)):eq(xM):eq(var'T'('_'..k))) buildxforms(k, depth + 1) else -- printbr((var'T'('_'..i) * var'V'('_'..j)):eq(xv):eq(var'V'('_'..k))) end end end for i=1,#xforms do buildxforms(i) end printbr() --]] local VmatT = Matrix(vtxs:mapi(function(v) return v:T()[1] end):unpack()) local Vmat = VmatT:T() shapeCache.Vmat = Vmat printbr'Vertexes as column vectors:' printbr() printbr(var'V':eq(Vmat)) printbr() printbr'Vertex inner products:' printbr() local vdots = (Vmat:T() * Vmat)() shapeCache.vdots = vdots printbr((var'V''^T' * var'V'):eq(Vmat:T() * Vmat):eq(vdots)) printbr() --[[ T V = V P we are first finding all T's from a basis of T's, then using all T's to determine associated P's but alternatively, because there are a fixed number of P's, we can solve: T = V P V^T and then filter only T's that coincide with proper rotations: A^-1 = A^T <=> A A^T = I actually depending on the permutation (i.e. a permutation that flipped vertexes 1 and 2 but left 3-n untouched), they can't be represented by linear transforms, will the result T be zero? or have a >{} nullspace at least? either way, if you have all the vertices, here's how you can find all the transforms. especially easy for simplexes. --]] printbr'Transforms of all vertexes vs permutations of all vertexes:' printbr() printbr(var'T''_i', [[$\in \{$]], allxforms:mapi(tostring):concat',', [[$\}$]]) printbr() for i,xform in ipairs(allxforms) do local xv = (xform * Vmat)() local xvT = xv:T() local rx = Matrix:lambda({nvtxs, nvtxs}, function(i,j) return xvT[j]() == VmatT[i]() and 1 or 0 end) printbr((var'T'('_'..i) * var'V'):eq(xv):eq(var'V' * rx)) printbr() local Vmat_rx = (Vmat * rx)() local diff = (xv - Vmat_rx)() local zeros = Matrix:zeros{n, nvtxs} if diff ~= zeros then printbr('expected', xv:eq(Vmat * rx), 'found difference', (xv - Vmat * rx)()) end end -- show if there are any simplification errors for j=2,#allxforms do for i=1,j-1 do if (allxforms[i] - allxforms[j])() == Matrix:zeros{n,n} then printbr(var'T'('_'..i), 'should equal', var'T'('_'..j), ':', allxforms[i], ',', allxforms[j]) end end end -- show vtx multiplication table -- btw, do i need to show the details of this above? or should I just show this? local function printVtxMulTable() printbr[[Table of $T_i \cdot v_j = v_k$:]] print'<table>\n' print'<tr><td></td>' for j=1,#vtxs do print('<td>V'..j..'</td>') end print'</tr>\n' -- print the multiplcation table for i,xi in ipairs(allxforms) do print('<tr><td>T'..i..'</td>') for j,vj in ipairs(vtxs) do local k = vtxs:find((xi * vj)()) print'<td>' if not k then print("couldn't find xform for ", var'T'('_'..i) * var'V'('_'..j)) else print('V'..k) end print'</td>' end print('</tr>\n') end print'</table>\n' printbr() printbr() end printVtxMulTable() local mulTable = {} shapeCache.mulTable = mulTable for i,xi in ipairs(allxforms) do mulTable[i] = {} for j,xj in ipairs(allxforms) do mulTable[i][j] = allxforms:find((xi * xj)()) end end local function printXformMulTable() printbr[[Table of $T_i \cdot T_j = T_k$:]] print'<table>\n' print'<tr><td></td>' for i=1,#allxforms do print('<td>T'..i..'</td>') end print'</tr>\n' -- print the multiplcation table for i=1,#allxforms do print('<tr><td>T'..i..'</td>') for j=1,#allxforms do local k = mulTable[i][j] print'<td>' if not k then print("couldn't find xform for ", var'T'('_'..i) * var'T'('_'..j)) else print('T'..k) end print'</td>' end print('</tr>\n') end print'</table>\n' printbr() printbr() end printXformMulTable() --[=[ rename by trying to put the Ti*Tj=T1 transforms closest to the diagonal: local dist = table() for i=1,#allxforms do for j=1,#allxforms do if mulTable[i][j] == 1 then dist[i] = math.abs(i - j) break end end end dist = dist:mapi(function(v,k) return {k,v} end):sort(function(a,b) if a[2] == b[2] then return a[1] < b[1] end -- for matching dist's, keep smallest indexes first return a[2] < b[2] end) -- ok now, the renaming: dist[i][1] is the 'from', i is the 'to' local rename = table() for i=1,#dist do rename[dist[i][1]] = i end --]=] --[=[ rename by grouping transforms -- rename[to] = from local whatsleft = range(#allxforms) local rename = table() rename:insert(whatsleft:remove(1)) local function process(last) if not last then if #whatsleft == 0 then return end last = whatsleft:remove(1) rename:insert(last) return process(last) end local next = mulTable[2][last] local k = whatsleft:find(next) if not k then return process() end whatsleft:remove(k) rename:insert(next) return process(next) end process() -- change to rename[from] = to rename = rename:mapi(function(v,k) return k,v end) --]=] --[=[ -- now first remap mulTable[i][j] -- then remap the indexes of mulTable local mulTableRenamed = {} for i=1,#allxforms do mulTableRenamed[rename[i]] = {} for j=1,#allxforms do mulTableRenamed[rename[i]][rename[j]] = rename[mulTable[i][j]] end end printbr('relabeled', tolua(rename)) printbr() mulTable = mulTableRenamed printXformMulTable() --]=] --[=[ not sure if this is useful. can't seem to visualize anything useful from it. file['tmp.dot'] = table{ 'digraph {', }:append(edges:mapi(function(e) return '\t'..table.concat(e, ' -> ')..';' end)):append{ '}', }:concat'\n' os.execute('circo tmp.dot -Tsvg > "Platonic Solids/'..shape.name..'.svg"') os.remove'tmp.dot' printbr("<img src='"..shape.name..".svg'>/") --]=] print(MathJax.footer) f:close() end -- can symmath.export.SymMath export Lua tables? --io.writefile(cacheFilename, symmath.export.SymMath(cache)) io.writefile(cacheFilename, tolua(cache, { serializeForType = { table = function(state, x, tab, path, keyRef, ...) local mt = getmetatable(x) if mt and ( Expression:isa(mt) -- TODO 'or' any other classes in symmath that aren't subclasses of Expression (are there any?) ) then return symmath.export.SymMath(x) end return tolua.defaultSerializeForType.table(state, x, tab, path, keyRef, ...) end, } })) -- is there some sort of tolua args that will encode the symmath with symmath.export.SymMath? --[[ local s = table() s:insert'{' for k,v in pairs(cache) do end s:insert'}' io.writefile(cacheFilename, s:concat'\n') --]] print(export.MathJax.footer)
slot0 = class("BattleAirFightResultLayer", import(".BattleResultLayer")) slot0.getUIName = function (slot0) return "BattleAirFightResultUI" end slot0.init = function (slot0) slot0._grade = slot0:findTF("grade") slot0._levelText = slot0:findTF("chapterName/Text22", slot0._grade) slot0._main = slot0:findTF("main") slot0._blurConatiner = slot0:findTF("blur_container") slot0._bg = slot0:findTF("main/jiesuanbeijing") slot0._painting = slot0:findTF("painting", slot0._blurConatiner) slot0._chat = slot0:findTF("chat", slot0._painting) slot0._rightBottomPanel = slot0:findTF("rightBottomPanel", slot0._blurConatiner) slot0._confirmBtn = slot0:findTF("confirmBtn", slot0._rightBottomPanel) slot0._statisticsBtn = slot0:findTF("statisticsBtn", slot0._rightBottomPanel) slot0._skipBtn = slot0:findTF("skipLayer", slot0._tf) slot0._conditions = slot0:findTF("main/conditions") slot0._conditionContainer = slot0:findTF("bg16/list", slot0._conditions) slot0._conditionTpl = slot0:findTF("bg16/conditionTpl", slot0._conditions) slot0._conditionSubTpl = slot0:findTF("bg16/conditionSubTpl", slot0._conditions) slot0._conditionContributeTpl = slot0:findTF("bg16/conditionContributeTpl", slot0._conditions) slot0._conditionBGContribute = slot0:findTF("bg16/bg_contribute", slot0._conditions) slot0:setGradeLabel() SetActive(slot0._levelText, false) slot0._delayLeanList = {} end slot0.setPlayer = function (slot0) return end slot0.setGradeLabel = function (slot0) slot1 = { "d", "c", "b", "a", "s" } setActive(slot0:findTF("jieuan01/BG/bg_victory", slot0._bg), ys.Battle.BattleConst.BattleScore.C < slot0.contextData.score) setActive(slot0:findTF("jieuan01/BG/bg_fail", slot0._bg), not (ys.Battle.BattleConst.BattleScore.C < slot0.contextData.score)) LoadImageSpriteAsync(nil, slot0:findTF("grade/Xyz/bg13"), false) LoadImageSpriteAsync("battlescore/battle_score_" .. nil .. "/label_" .. slot6, slot0:findTF("grade/Xyz/bg14"), false) end slot0.didEnter = function (slot0) slot0:setStageName() slot0._gradeUpperLeftPos = rtf(slot0._grade).localPosition rtf(slot0._grade).localPosition = Vector3(0, 25, 0) pg.UIMgr.GetInstance():BlurPanel(slot0._tf) slot0._grade.transform.localScale = Vector3(1.5, 1.5, 0) LeanTween.scale(slot0._grade, Vector3(0.88, 0.88, 1), slot0.DURATION_WIN_SCALE):setOnComplete(System.Action(function () SetActive(slot0._levelText, true) SetActive:rankAnimaFinish() end)) slot0._tf.GetComponent(slot2, typeof(Image)).color = Color.New(0, 0, 0, 0.5) slot0._stateFlag = BattleResultLayer.STATE_RANK_ANIMA onButton(slot0, slot0._skipBtn, function () slot0:skip() end, SFX_CONFIRM) end slot0.rankAnimaFinish = function (slot0) SetActive(slot1, true) slot0:setCondition(i18n("fighterplane_destroy_tip") .. slot0.contextData.statistics._airFightStatistics.kill, slot0.contextData.statistics._airFightStatistics.score, COLOR_BLUE) slot0:setCondition(i18n("fighterplane_hit_tip") .. slot0.contextData.statistics._airFightStatistics.hit, -slot0.contextData.statistics._airFightStatistics.lose, COLOR_BLUE) slot0:setCondition(i18n("fighterplane_score_tip"), slot0.contextData.statistics._airFightStatistics.total, COLOR_YELLOW) table.insert(slot0._delayLeanList, LeanTween.delayedCall(1, System.Action(function () slot0._stateFlag = slot1.STATE_REPORTED SetActive(slot0:findTF("jieuan01/tips", slot0._bg), true) end)).id) slot0._stateFlag = slot0.STATE_REPORT end slot0.setCondition = function (slot0, slot1, slot2, slot3) slot4 = cloneTplTo(slot0._conditionContributeTpl, slot0._conditionContainer) setActive(slot4, false) slot5 = nil slot4:Find("text"):GetComponent(typeof(Text)).text = setColorStr(slot1, "#FFFFFFFF") slot4:Find("value"):GetComponent(typeof(Text)).text = setColorStr(slot2, slot3) if slot0._conditionContainer.childCount - 1 > 0 then table.insert(slot0._delayLeanList, LeanTween.delayedCall(slot0.CONDITIONS_FREQUENCE * slot8, System.Action(function () setActive(setActive, true) end)).id) else setActive(slot4, true) end end slot0.displayBG = function (slot0) LeanTween.moveX(rtf(slot0._conditions), 1300, slot0.DURATION_MOVE) LeanTween.scale(slot0._grade, Vector3(0.6, 0.6, 0), slot0.DURATION_MOVE) LeanTween.moveLocal(go(slot1), slot0._gradeUpperLeftPos, slot0.DURATION_MOVE):setOnComplete(System.Action(function () slot0._stateFlag = slot1.STATE_DISPLAY slot0:showPainting() slot0.showPainting._stateFlag = slot0.STATE_DISPLAYED end)) setActive(slot0.findTF(slot0, "jieuan01/Bomb", slot0._bg), false) end slot0.showPainting = function (slot0) SetActive(slot0._painting, true) slot0.paintingName = "yanzhan" setPaintingPrefabAsync(slot0._painting, slot0.paintingName, "jiesuan", function () if findTF(slot0._painting, "fitter").childCount > 0 then ShipExpressionHelper.SetExpression(findTF(slot0._painting, "fitter"):GetChild(0), slot0.paintingName, "win_mvp") end end) slot1 = (slot0.contextData.score > 1 and ShipWordHelper.WORD_TYPE_MVP) or ShipWordHelper.WORD_TYPE_LOSE slot2, slot3, slot7 = ShipWordHelper.GetWordAndCV(205020, slot1) setText(slot0._chat:Find("Text"), slot4) if CHAT_POP_STR_LEN < #slot0._chat:Find("Text"):GetComponent(typeof(Text)).text then slot5.alignment = TextAnchor.MiddleLeft else slot5.alignment = TextAnchor.MiddleCenter end SetActive(slot0._chat, true) slot0._chat.transform.localScale = Vector3.New(0, 0, 0) LeanTween.moveX(rtf(slot0._painting), 50, 0.1):setOnComplete(System.Action(function () LeanTween.scale(rtf(slot0._chat.gameObject), Vector3.New(1, 1, 1), 0.1):setEase(LeanTweenType.easeOutBack) end)) end slot0.skip = function (slot0) if slot0._stateFlag == BattleResultLayer.STATE_REPORTED then slot0:emit(BattleResultMediator.ON_BACK_TO_LEVEL_SCENE) end end slot0.showRightBottomPanel = function (slot0) SetActive(slot0._skipBtn, false) SetActive(slot0._rightBottomPanel, true) SetActive(slot0._subToggle, false) onButton(slot0, slot0._confirmBtn, function () slot0:emit(BattleResultMediator.ON_BACK_TO_LEVEL_SCENE) end, SFX_CONFIRM) slot0._stateFlag = nil end slot0.onBackPressed = function (slot0) triggerButton(slot0._skipBtn) end slot0.willExit = function (slot0) LeanTween.cancel(go(slot0._tf)) pg.UIMgr.GetInstance():UnblurPanel(slot0._tf) end return slot0
return {'joechjachen','joeg','joego','joekel','joelen','joelfeest','joep','joepen','joepie','joetje','joegoslavische','joegoslavisch','joegoslavie','joegoslavier','joep','joes','joel','joe','joeke','joel','joelle','joeri','joerie','joey','joelle','joegoslaven','joegen','joekels','joel','joelde','joelden','joelend','joelende','joelfeesten','joelt','joept','joepte','joetjes','joegos','joes','joekes','joels','joelles','joeps','joeris','joeries','joes','joeys','joels','joelles'}
----------------------------------- -- Area: North Gustaberg (S) (F-8) -- NPC: ??? -- Involved in Quests -- !pos -232 41 425 ----------------------------------- require("scripts/globals/quests") ----------------------------------- function onTrade(player, npc, trade) end function onTrigger(player, npc) if (player:getQuestStatus(CRYSTAL_WAR, tpz.quest.id.crystalWar.BETTER_PART_OF_VALOR) == QUEST_ACCEPTED and player:getCharVar("BetterPartOfValProg") == 1) then player:startEvent(3) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) if (csid == 3) then player:setCharVar("BetterPartOfValProg", 2) end end
SKILL.name = "Incinerate" SKILL.LevelReq = 5 SKILL.SkillPointCost = 2 SKILL.Incompatible = { } SKILL.RequiredSkills = { } SKILL.icon = "vgui/skills/spell_fire_burnout.png" SKILL.category = "Psychic Powers"-- Common Passives, Warrior, Lore of Light, Dark Magic SKILL.slot = "AOE" -- ULT, RANGED, MELEE, AOE, PASSIVE SKILL.class = { "librarian" } SKILL.desc = [[ This skill burns targets. Damage: 42(+4.0 Magic)/s. Duration: 3 Seconds. Cost: 70 Energy Cooldown: 30 Seconds Ability Slot: 3 Level Requirement: ]] .. SKILL.LevelReq .. [[ Skill Point Cost:]] .. SKILL.SkillPointCost .. [[ ]] SKILL.coolDown = 30 local function ability(SKILL, ply ) local nospam = ply:GetNWBool( "nospamAOE" ) if (nospam) then if timer.Exists(ply:SteamID().."nospamAOE") then return end timer.Create(ply:SteamID().."nospamAOE", SKILL.coolDown, 1, function() ply:SetNWBool( "nospamAOE", false ) print("ready") end) return end local mana = ply:getLocalVar("mana", 0) if mana < 70 then return end ply:setLocalVar("mana", mana - 70) local pos = ply:GetPos() if SERVER then ply:SetNWBool( "nospamAOE", true ) print("Cdstart") net.Start( "UltActivated" ) net.Send( ply ) end local pos = ply:GetPos() timer.Create(ply:SteamID().."Incinerate", 0.25, 12, function() local Entities = ents.FindInSphere( ply:GetPos(), 500 ) for k, v in pairs(Entities) do if ((v:IsNPC()) or (v:IsPlayer() and v != ply)) then v:TakeDamage( 42 + (ply:getChar():getAttrib("mgc", 0) * 1.0), ply, ply ) ParticleEffectAttach( "fantasy_purple_flame", PATTACH_ABSORIGIN_FOLLOW, v, 0 ) end end end) if SERVER then if timer.Exists(ply:SteamID().."nospamAOE") then return end timer.Create(ply:SteamID().."nospamAOE", SKILL.coolDown, 1, function() ply:SetNWBool( "nospamAOE", false ) print("ready") end) end end SKILL.ability = ability
-- On one pin, a button that has 3 (callback) functions for short or 1-sec or 3-sec presses. -- BL Oct 2015 _tstamps={} smartButton = function(pin, k0, k1, k3) _tstamps[pin+1]=0 gpio.mode(pin,gpio.INT) gpio.trig(pin, "both", function(level) local dur = tmr.now() - _tstamps[pin+1] _tstamps[pin+1] = tmr.now() if gpio.read(pin) == 1 then -- BUTTON UP? note "level" seems unreliable if (dur < 500000) then if (k0 ~= nil) then k0() end -- SHORT elseif (dur < 1800000) then if (k1 ~= nil) then k1() end -- 1 Sec elseif (dur < 6000000) then if (k3 ~= nil) then k3() end -- 3 sec end end end ) end
--[[ Author: Jagoba Marcos Date: 01/08/2014 Description: Simple Games ]] function main () -- Guess the number math.randomseed( os.time() ); math.random(); local number = math.random ( 100 ); local count = 0; local guess; io.write( "Guess my number (1-100): " ); guess = io.read( "*n" ); count = count + 1 while guess ~= number do if guess > number then io.write( guess , " is too high." ); elseif guess < number then io.write( guess , " is too low." ); end io.write( "Guess again: " ); guess = io.read( "*n" ); count = count + 1 end io.write( "You got it right after ", count, " tries!\n\n" ); -- Guess the number v2 local guess1 = math.random ( 100 ); local guess2; local count = 0; local number; io.write( "Enter a number for me to guess (1-100): " ); number = io.read( "*n" ); io.write( "I guess ", guess1 , "\n"); count = count + 1 while guess1 ~= number do if guess1 < number then io.write( "That's not right. " ); guess2 = math.random ( guess1, 100 ); while guess2 <= guess1 do guess2 = math.random ( guess2, 100 ); end io.write( "I guess ", guess2 , "\n"); count = count + 1 elseif guess1 > number then io.write( "That's not right. " ); guess2 = math.random ( guess1 ); while guess2 >= guess1 do guess2 = math.random ( guess2 ); end io.write( "I guess ", guess2 , "\n"); count = count + 1 end guess1 = guess2; end io.write( "You got it right after ", count, " tries!\n\n" ); -- Rock-Paper-Scissors local computer = math.random( 1, 3); local player; local move = {} move[1] = "Rock"; move[2] = "Paper"; move[3] = "Scissors"; io.write( "Rock Paper Scissors Time! \n" ); io.write( "1) Rock\n" ); io.write( "2) Paper\n" ); io.write( "3) Scissors\n\n" ); io.write( "Enter your choice: " ); player = io.read( "*n" ); io.write( "Player chose ", move[player], "\n" ); io.write( "Computer chose ", move[computer], "\n\n" ); if player == computer then io.write( "It's a draw.\n\n" ); elseif (player == 1 and computer == 2) or (player == 2 and computer == 3) or (player == 3 and computer == 1) then io.write( "Computer wins!\n\n" ); elseif (player == 2 and computer == 1) or (player == 3 and computer == 2) or (player == 1 and computer == 3) then io.write( "Player wins!\n\n" ); end end
-- tostring() functions for Tensor and Storage local function Storage__printformat(self) local intMode = true local type = torch.typename(self) if type == 'torch.FloatStorage' or 'torch.DoubleStorage' then for i=1,self:size() do if self[i] ~= math.ceil(self[i]) then intMode = false break end end end local tensor = torch.Tensor(torch.DoubleStorage(self:size()):copy(self), 1, self:size()):abs() local expMin = tensor:min() if expMin ~= 0 then expMin = math.floor(math.log10(expMin)) + 1 end local expMax = tensor:max() if expMax ~= 0 then expMax = math.floor(math.log10(expMax)) + 1 end local format local scale local sz if intMode then if expMax > 9 then format = "%11.4e" sz = 11 else format = "%SZd" sz = expMax + 1 end else if expMax-expMin > 4 then format = "%SZ.4e" sz = 11 if math.abs(expMax) > 99 or math.abs(expMin) > 99 then sz = sz + 1 end else if expMax > 5 or expMax < 0 then format = "%SZ.4f" sz = 7 scale = math.pow(10, expMax-1) else format = "%SZ.4f" if expMax == 0 then sz = 7 else sz = expMax+6 end end end end format = string.gsub(format, 'SZ', sz) if scale == 1 then scale = nil end return format, scale, sz end local function Storage__tostring(self) local str = '' local format,scale = Storage__printformat(self) if scale then str = str .. string.format('%g', scale) .. ' *\n' for i = 1,self:size() do str = str .. string.format(format, self[i]/scale) .. '\n' end else for i = 1,self:size() do str = str .. string.format(format, self[i]) .. '\n' end end str = str .. '[' .. torch.typename(self) .. ' of size ' .. self:size() .. ']\n' return str end rawset(torch.getmetatable('torch.CharStorage'), '__tostring__', Storage__tostring) rawset(torch.getmetatable('torch.ShortStorage'), '__tostring__', Storage__tostring) rawset(torch.getmetatable('torch.IntStorage'), '__tostring__', Storage__tostring) rawset(torch.getmetatable('torch.LongStorage'), '__tostring__', Storage__tostring) rawset(torch.getmetatable('torch.FloatStorage'), '__tostring__', Storage__tostring) rawset(torch.getmetatable('torch.DoubleStorage'), '__tostring__', Storage__tostring) local function Tensor__printMatrix(self, indent) local format,scale,sz = Storage__printformat(self:storage()) -- print('format = ' .. format) scale = scale or 1 indent = indent or '' local str = indent local nColumnPerLine = math.floor((80-#indent)/(sz+1)) -- print('sz = ' .. sz .. ' and nColumnPerLine = ' .. nColumnPerLine) local firstColumn = 1 local lastColumn = -1 while firstColumn <= self:size(2) do if firstColumn + nColumnPerLine - 1 <= self:size(2) then lastColumn = firstColumn + nColumnPerLine - 1 else lastColumn = self:size(2) end if nColumnPerLine < self:size(2) then if firstColumn ~= 1 then str = str .. '\n' end str = str .. 'Columns ' .. firstColumn .. ' to ' .. lastColumn .. '\n' .. indent end if scale ~= 1 then str = str .. string.format('%g', scale) .. ' *\n ' .. indent end for l=1,self:size(1) do local row = self:select(1, l) for c=firstColumn,lastColumn do str = str .. string.format(format, row[c]/scale) if c == lastColumn then str = str .. '\n' if l~=self:size(1) then if scale ~= 1 then str = str .. indent .. ' ' else str = str .. indent end end else str = str .. ' ' end end end firstColumn = lastColumn + 1 end return str end local function Tensor__printTensor(self) local counter = torch.LongStorage(self:nDimension()-2) local str = '' local finished counter:fill(1) counter[1] = 0 while true do for i=1,self:nDimension()-2 do counter[i] = counter[i] + 1 if counter[i] > self:size(i) then if i == self:nDimension()-2 then finished = true break end counter[i] = 1 else break end end if finished then break end -- print(counter) if str ~= '' then str = str .. '\n' end str = str .. '(' local tensor = self for i=1,self:nDimension()-2 do tensor = tensor:select(1, counter[i]) str = str .. counter[i] .. ',' end str = str .. '.,.) = \n' str = str .. Tensor__printMatrix(tensor, ' ') end return str end local function Tensor__tostring(self) local str = '\n' if self:nDimension() == 0 then str = str .. '[' .. torch.typename(self) .. ' with no dimension]\n' else local tensor = torch.Tensor():resize(self:size()):copy(self) if tensor:nDimension() == 1 then local format,scale,sz = Storage__printformat(tensor:storage()) if scale then str = str .. string.format('%g', scale) .. ' *\n' for i = 1,tensor:size(1) do str = str .. string.format(format, tensor[i]/scale) .. '\n' end else for i = 1,tensor:size(1) do str = str .. string.format(format, tensor[i]) .. '\n' end end str = str .. '[' .. torch.typename(self) .. ' of dimension ' .. tensor:size(1) .. ']\n' elseif tensor:nDimension() == 2 then str = str .. Tensor__printMatrix(tensor) str = str .. '[' .. torch.typename(self) .. ' of dimension ' .. tensor:size(1) .. 'x' .. tensor:size(2) .. ']\n' else str = str .. Tensor__printTensor(tensor) str = str .. '[' .. torch.typename(self) .. ' of dimension ' for i=1,tensor:nDimension() do str = str .. tensor:size(i) if i ~= tensor:nDimension() then str = str .. 'x' end end str = str .. ']\n' end end return str end rawset(torch.getmetatable('torch.CharTensor'), '__tostring__', Tensor__tostring) rawset(torch.getmetatable('torch.ShortTensor'), '__tostring__', Tensor__tostring) rawset(torch.getmetatable('torch.IntTensor'), '__tostring__', Tensor__tostring) rawset(torch.getmetatable('torch.LongTensor'), '__tostring__', Tensor__tostring) rawset(torch.getmetatable('torch.FloatTensor'), '__tostring__', Tensor__tostring) rawset(torch.getmetatable('torch.Tensor'), '__tostring__', Tensor__tostring)
return (require 'util').requirer(...) { 'Character', 'CharacterClass', 'Chest', 'Item', 'Monster', 'Race', }
-- main.lua -- Implements the main plugin entrypoint -- Configuration -- Use prefixes or not. -- If set to true, messages are prefixed, e. g. "[FATAL]". If false, messages are colored. g_UsePrefixes = true -- Called by Cuberite on plugin start to initialize the plugin function Initialize(Plugin) Plugin:SetName("CoreAntiCheat") Plugin:SetVersion(tonumber(g_PluginInfo["Version"])) -- Register for all hooks needed cPluginManager:AddHook(cPluginManager.HOOK_PLAYER_MOVING, OnPlayerMoving); -- Load the InfoReg shared library: dofile(cPluginManager:GetPluginsPath() .. "/InfoReg.lua") -- Bind all the commands: RegisterPluginInfoCommands() -- Bind all the console commands: RegisterPluginInfoConsoleCommands() -- Initialise variables CACenabled = true LOG("Initialised " .. Plugin:GetName() .. " v." .. Plugin:GetVersion()) return true end function OnDisable() LOG( "Disabled CoreAntiCheat!" ) end -- Global Functions -- Command Functions function CoreAntiCheatCommand(Split, Player, World) if Split[2] == "toggle" then if CACenabled then CACenabled = false Player:SendMessageInfo("CoreAntiCheat Disabled!") else CACenabled = true Player:SendMessageInfo("CoreAntiCheat Enabled!") end else if CACenabled then if Split[2] == "test" then cRoot:Get():BroadcastChat("test") elseif Split[2] == "config" then Player:SendMessageInfo("-- Config --") Player:SendMessageInfo("Ping Allowance: " .. getconfig(1)) Player:SendMessageInfo("MovementRestriction: " .. getconfig(2)) else Player:SendMessageFailure("Incorrect Argument") end else Player:SendMessageFailure("CoreAntiCheat is disabled!") end end return true end -- Command SubFunctions -- AntiCheat Logic function OnPlayerMoving(Player, OldPosition, NewPosition) local XD = math.abs(OldPosition.x-NewPosition.x) local YD = math.abs(OldPosition.y-NewPosition.y) local ZD = math.abs(OldPosition.z-NewPosition.z) local Speed = math.sqrt(math.pow(XD,2) + math.pow(ZD, 2)) local MaxSpeed = (Player:GetMaxSpeed() * 0.22) + (getconfig(2) * 0.1) if getconfig(3) then Player:SendMessageInfo(Speed .. " out of " .. MaxSpeed) end if Speed > MaxSpeed then return true end end
collectgarbage(); local TimeFiles = {} if Hour() > 20 or Hour() < 8 then --Night TimeFiles[1] = "Cricket.ogg" TimeFiles[2] = color("0,0,0,1") TimeFiles[3] = color("1,1,1,1") else --Day TimeFiles[1] = "Bird.ogg" TimeFiles[2] = color("1,1,1,1") TimeFiles[3] = color("0,0,0,1") end local Letters = Def.ActorFrame{} local Sizestr = 0 for i = 1,8 do Letters[#Letters+1] = Def.Sprite{ Texture=i..".png", InitCommand=function(self) self:x(-100+Sizestr):halign(0):valign(1):y(30):zoom(1/12):glow(TimeFiles[3]) Sizestr = Sizestr + (self:GetWidth()/12) + 5 end, OnCommand=function(self) self:sleep(2+(0.4*i)):linear(0.25):zoomy(1.5/12):y(-5):linear(0.125):zoomy(1/12):y(0) end } end return Def.ActorFrame { InitCommand=function(self) self:zoom(3) end, Def.Quad { InitCommand=function(self) self:FullScreen():diffuse(TimeFiles[2]):xy(-SCREEN_CENTER_X/2,-SCREEN_CENTER_Y/2) end }, Def.ActorFrame{ InitCommand=function(self) self:y(-290) end, OnCommand=function(self) self:accelerate(2.2):y(-10) :decelerate(.2):y(-50) :accelerate(.2):y(-10) :decelerate(.2):y(-50) :accelerate(.2):y(-10) :decelerate(.2):y(-50) :accelerate(.2):y(-10) :decelerate(.2):y(-50) :accelerate(.2):y(-10) :decelerate(.2):y(-50) :accelerate(.2):y(-10) :decelerate(.2):y(-50) :accelerate(.2):y(-10) :decelerate(.2):y(-50) :accelerate(.2):y(-10) :decelerate(.6):y(-160) :accelerate(.6):y(-90) end, Def.Sprite{ Texture="Acorn.png", InitCommand=function(self) self:zoom(1/42):x(-410) end, OnCommand=function(self) self:decelerate(2.2):x(-90) -- T :accelerate(.2):x(-80) :decelerate(.2):x(-70) -- E :accelerate(.2):x(-60) :decelerate(.2):x(-45) -- A :accelerate(.2):x(-27.5) :decelerate(.2):x(-10) -- M :accelerate(.2):x(5) :decelerate(.2):x(20) -- R :accelerate(.2):x(27.5) :decelerate(.2):x(35) -- I :accelerate(.2):x(45) :decelerate(.2):x(55) -- Z :accelerate(.2):x(70) :decelerate(.2):x(80) -- U :accelerate(.6):x(40) :decelerate(.6):x(0) :sleep(1/math.huge):linear(1):zoom(1/6):rotationz(360*2) end }, Def.Sound{ File="Grass.ogg", OnCommand=function(self) self:sleep(2.2):queuecommand("Play") :sleep(.4):queuecommand("Play") :sleep(.4):queuecommand("Play") :sleep(.4):queuecommand("Play") :sleep(.4):queuecommand("Play") :sleep(.4):queuecommand("Play") :sleep(.4):queuecommand("Play") :sleep(.4):queuecommand("Play") end, PlayCommand=function(self) self:play() end }, Def.Sound{ File=TimeFiles[1], OnCommand=function(self) self:sleep(6.2):queuecommand("Play") end, PlayCommand=function(self) self:play() end } }, Letters, Def.Quad { InitCommand=function(self) self:FullScreen():diffuse(TimeFiles[2]):x(-SCREEN_CENTER_X/2):fadetop(.005) end }, Def.Quad { InitCommand=function(self) self:FullScreen():diffuse(0,0,0,1):xy(-SCREEN_CENTER_X/2,-SCREEN_CENTER_Y/2):linear(1):diffusealpha(0):sleep(8.2):linear(1):diffusealpha(1):sleep(1):queuecommand("Transfer") end, TransferCommand=function(self) SCREENMAN:GetTopScreen():StartTransitioningScreen("SM_GoToNextScreen"); end } }
PLAYER1 = Core.class() function PLAYER1:init(xworld, xobjpath, xobjname, xparams, xBIT, xCOLBIT) -- the params local params = xparams or {} params.posx = xparams.posx or 0 params.posy = xparams.posy or 0 params.posz = xparams.posz or 0 -- the obj self.obj = loadObj(xobjpath, xobjname) local minx, miny, minz = self.obj.min[1], self.obj.min[2], self.obj.min[3] local maxx, maxy, maxz = self.obj.max[1], self.obj.max[2], self.obj.max[3] local width, height, length = maxx - minx, maxy - miny, maxz - minz local matrix = self.obj:getMatrix() matrix:setPosition(params.posx, params.posy, params.posz) self.obj:setMatrix(matrix) -- the obj body self.body = xworld:createBody(self.obj:getMatrix()) -- the obj shape self.shape = r3d.SphereShape.new(height / 2) -- the obj fixture local fixture = self.body:createFixture(self.shape, nil, 16) -- shape, transform, mass fixture:setCollisionCategoryBits(xBIT) fixture:setCollideWithMaskBits(xCOLBIT) -- damping self.body:setLinearDamping(0.95) self.body:setAngularDamping(1) -- keyboard controls self.isup, self.isdown, self.isleft, self.isright, self.isshoot = false, false, false, false, false end function PLAYER1:setPosition(xposx, xposy, xposz) local matrix = self.obj:getMatrix() matrix:setPosition(xposx, xposy, xposz) self.body:setTransform(matrix) end
local room_recruitWnd = require("view/kScreen_1280_800/games/common2/room_recruitWnd"); --[[ 招募玩家的确认弹框 ]] local RecruitWnd = class(CommonGameLayer,false); --------------------------------------------------------------------- ----------------- config tables ------------------------------------- --------------------------------------------------------------------- RecruitWnd.s_controls = { mask = ToolKit.getIndex(); inviteInputView = ToolKit.getIndex(); sendBtn = ToolKit.getIndex(); editText = ToolKit.getIndex(); broadcastTips = ToolKit.getIndex(); }; --------------------------------------------------------------------- ----------------- 构造函数 ------------------------------------- --------------------------------------------------------------------- RecruitWnd.ctor = function(self) super(self,room_recruitWnd); self:setFillParent(true,true) self.m_ctrls = RecruitWnd.s_controls; self:init(); end RecruitWnd.dtor = function(self) self.data=nil; delete(self.m_listener); self.m_listener = nil; end RecruitWnd.init = function(self) self.inviteInputView = self:findViewById(self.m_ctrls.inviteInputView); self.m_editText = self:findViewById(self.m_ctrls.editText); self.m_editText:setEnable(false); local radioMoney = RadioIsolater.getInstance():getRadioMoney(); self:findViewById(self.m_ctrls.broadcastTips):setText(string.format("发送广播将扣除%s银币",radioMoney)); end RecruitWnd.show = function(self, text) self.shareTxt = text; self.m_editText:setText(self.shareTxt); self:setVisible(true); DialogLogic.getInstance():pushDialogStack(self,self.colseWnd); end RecruitWnd.colseWnd = function(self) self:setVisible(false); DialogLogic.getInstance():popDialogStack(); local action = GameMechineConfig.ACTION_NS_CLOSE_RECRUITEWND; MechineManage.getInstance():receiveAction(action); end --------------------------------------------------------------------- ----------------- Button event response functions ------------------- --------------------------------------------------------------------- RecruitWnd.onMaskClick = function(self , finger_action , x , y, drawing_id_first , drawing_id_current) if finger_action == kFingerUp then self:colseWnd(); end end RecruitWnd.onSendClck = function(self) local radioMoney = RadioIsolater.getInstance():getRadioMoney(); local remainMoney = UserPropertyIsolater.getInstance():getMoney() - radioMoney; if BankruptIsolater.getInstance():checkIsBankrupt(remainMoney) then Toast.getInstance():showText(string.format(kTextFirstRecharger,radioMoney), 50, 30, kAliginCenter, "", 24, 255, 255, 255); return; end if UserPropertyIsolater.getInstance():getMoney() < RadioIsolater.getInstance():getSendPrivateBroadcastLimitMoney() then Toast.getInstance():showText(string.format(kTextSendBroadCastLimit,RadioIsolater.getInstance():getSendPrivateBroadcastLimitMoney()), 50, 30, kAliginCenter, "", 24, 255, 255, 255); return; end local textView = self:findViewById(self.m_ctrls.editText); local inputContent = textView:getText(); inputContent=string.trim(inputContent); local strNum = string.count(inputContent); if strNum>60 or string.isEmpty(inputContent) then Toast.getInstance():showText("文字为1-60个字符", 50, 30, kAliginCenter, "", 24, 255, 255, 255); return; else RadioIsolater.getInstance():sendRadio(inputContent, RadioIsolater.getInstance():getPrivateRoomRadioType()); self:colseWnd(); end end --------------------------------------------------------------------- ----------------- config tables ------------------------------------- --------------------------------------------------------------------- RecruitWnd.s_controlConfig = { [RecruitWnd.s_controls.mask] = {"mask"}; [RecruitWnd.s_controls.inviteInputView] = {"inviteInputView"}; [RecruitWnd.s_controls.sendBtn] = {"inviteInputView","sendBtn"}; [RecruitWnd.s_controls.editText] = {"inviteInputView","editBg","editText"}; [RecruitWnd.s_controls.broadcastTips] = {"inviteInputView","tips"}; }; RecruitWnd.s_controlFuncMap = { [RecruitWnd.s_controls.mask] = RecruitWnd.onMaskClick; [RecruitWnd.s_controls.sendBtn] = RecruitWnd.onSendClck; }; return RecruitWnd;
local _M = {} _M["1"] = { ["id"] = 1, ["comment"] = "背包模块", ["opentype"] = 1, ["level"] = 1, } _M["2"] = { ["id"] = 2, ["comment"] = "", ["opentype"] = 1, ["level"] = 1, } _M["3"] = { ["id"] = 3, ["comment"] = "", ["opentype"] = 1, ["level"] = 1, } _M["4"] = { ["id"] = 4, ["comment"] = "", ["opentype"] = 1, ["level"] = 1, } return _M
--# selene: allow(unused_variable) ---@diagnostic disable: unused-local -- **WARNING**: EXPERIMENTAL MODULE. DO **NOT** USE IN PRODUCTION. -- This module is *for testing purposes only*. It can undergo breaking API changes or *go away entirely* **at any point and without notice**. -- (Should you encounter any issues, please feel free to report them on https://github.com/Hammerspoon/hammerspoon/issues -- or #hammerspoon on irc.libera.chat) -- -- Window management -- -- Windowlayouts work by selecting certain windows via windowfilters and arranging them onscreen according to specific rules. -- -- A **layout** is composed of a list of rules and, optionally, a screen arrangement definition. -- Rules within a layout are evaluated in order; once a window is acted upon by a rule, subsequent rules will not affect it further. -- A **rule** needs a **windowfilter**, producing a dynamic list of windows (the "window pool") to which the rule is applied, -- and a list of commands, evaluated in order. -- A **command** acts on one or more of the windows, and is composed of: -- * an **action**, it can be -- - `move`: moves the window(s) to a specified onscreen rect (if the action is omitted, `move` is assumed) -- - `minimize`, `maximize`, `fullscreen` -- - `tile`, `fit`: tiles the windows onto a specified rect, using `hs.window.tiling.tileWindows()`; for `fit`, the -- `preserveRelativeArea` parameter will be set to true -- - `hide`, `unhide`: hides or unhides the window's application (like when using cmd-h) -- - `noaction`: skip action on the window(s) -- * a **maxn** number, indicating how many windows from this rule's window pool will be affected (at most) by this command; -- if omitted (or if explicitly the string `all`) all the remaining windows will be processed by this command; processed -- windows are "consumed" and are excluded from the window pool for subsequent commands in this rule, and from subsequent rules -- * a **selector**, describing the sort order used to pick the first *maxn* windows from the window pool for this command; -- it can be one of `focused` (pick *maxn* most recently focused windows), `frontmost` (pick the recent focused window if its -- application is frontmost applicaion, otherwise the command will be skipped), `newest` (most recently created), `oldest` -- (least recently created), or `closest` (pick the *maxn* windows that are closest to the destination rect); if omitted, -- defaults to `closest` for move, tile and fit, and `newest` for everything else -- * an `hs.geometry` *size* (only valid for tile and fit) indicating the desired optimal aspect ratio for the tiled windows; -- if omitted, defaults to 1x1 (i.e. square windows) -- * for move, tile and fit, an `hs.geometry` *rect*, or a *unit rect* plus a *screen hint* (for `hs.screen.find()`), -- indicating the destination rect for the command -- * for fullscreen and maximize, a *screen hint* indicating the desired screen; if omitted, uses the window's current screen -- -- You should place higher-priority rules (with highly specialized windowfilters) first, and "fallback" rules -- (with more generic windowfilters) last; similarly, *within* a rule, you should have commands for the more "important" -- (i.e. relevant to your current workflow) windows first (move, maximize...) and after that deal with less prominent -- windows, if any remain, e.g. by placing them out of the way (minimize). -- `unhide` and `hide`, if used, should usually go into their own rules (with a windowfilter that allows invisible windows -- for `unhide`) that come *before* other rules that deal with actual window placement - unlike the other actions, -- they don't "consume" windows making them unavailable for subsequent rules, as they act on applications. -- -- In order to avoid dealing with deeply nested maps, you can define a layout in your scripts via a list, where each element -- (or row) denotes a rule; in turn every rule can be a simplified list of two elements: -- - a windowfilter or a constructor argument table for one (see `hs.window.filter.new()` and `hs.window.filter:setFilters()`) -- - a single string containing all the commands (action and parameters) in order; actions and selectors can be shortened to -- 3 characters; all tokens must be separated by spaces (do not use spaces inside `hs.geometry` constructor strings); -- for greater clarity you can separate commands with `|` (pipe character) -- -- Some command string examples: -- - `"move 1 [0,0,50,50] -1,0"` moves the closest window to the topleft quadrant of the left screen -- - `"max 0,0"` maximizes all the windows onto the primary screen, one on top of another -- - `"move 1 foc [0,0,30,100] 0,0 | tile all foc [30,0,100,100] 0,0"` moves the most recently focused window to the left third, -- and tiles the remaining windows onto the right side, keeping the most recently focused on top and to the left -- - `"1 new [0,0,50,100] 0,0 | 1 new [50,0,100,100] 0,0 | min"` divides the primary screen between the two newest windows -- and minimizes any other windows -- -- Each layout can work in "passive" or "active" modes; passive layouts must be triggered manually (via `hs.hotkey.bind()`, -- `hs.menubar`, etc.) while active layouts continuously keep their rules enforced (see `hs.window.layout:start()` -- for more information); in general you should avoid having multiple active layouts targeting the same windows, as the -- results will be unpredictable (if such a situation is detected, you'll see an error in the Hammerspoon console); you -- *can* have multiple active layouts, but be careful to maintain a clear "separation of concerns" between their respective windowfilters. -- -- Each layout can have an associated screen configuration; if so, the layout will only be valid while the current screen -- arrangement satisfies it; see `hs.window.layout:setScreenConfiguration()` for more information. ---@class hs.window.layout local M = {} hs.window.layout = M -- Applies the layout -- -- Parameters: -- * None -- -- Returns: -- * the `hs.window.layout` object -- -- Notes: -- * if a screen configuration is defined for this windowfilter, and currently not satisfied, this method will do nothing function M:apply() end -- When "active mode" windowlayouts apply a rule, they will pause briefly for this amount of time in seconds, to allow windows -- to "settle" in their new configuration without triggering other rules (or the same rule), which could result in a -- cascade (or worse, a loop) or rules being applied. Defaults to 1; increase this if you experience unwanted repeated -- triggering of rules due to sluggish performance. M.applyDelay = nil -- Applies a layout -- -- Parameters: -- * rules - see `hs.window.layout.new()` -- -- Returns: -- * None -- -- Notes: -- * this is a convenience wrapper for "passive mode" use that creates, applies, and deletes a windowlayout object; -- do *not* use shared windowfilters in `rules`, as they'll be deleted; you can just use constructor argument maps instead function M.applyLayout(rules, ...) end -- Return a table with all the rules (and the screen configuration, if present) defined for this windowlayout -- -- Parameters: -- * None -- -- Returns: -- * a table containing the rules of this windowlayout; you can pass this table (optionally -- after performing valid manipulations) to `hs.window.layout.new()` function M:getRules() end -- Creates a new hs.window.layout instance -- -- Parameters: -- * rules - a table containing the rules for this windowlayout (see the module description); additionally, if a special key `screens` -- is present, its value must be a valid screen configuration as per `hs.window.layout:setScreenConfiguration()` -- * logname - (optional) name of the `hs.logger` instance for the new windowlayout; if omitted, the class logger will be used -- * loglevel - (optional) log level for the `hs.logger` instance for the new windowlayout -- -- Returns: -- * a new windowlayout instance ---@return hs.window.layout function M.new(rules, logname, loglevel, ...) end -- Pauses an active windowlayout instance; while paused no automatic window management will occur -- -- Parameters: -- * None -- -- Returns: -- * the `hs.window.layout` object ---@return hs.window.layout function M:pause() end -- Pauses all active windowlayout instances -- -- Parameters: -- * None -- -- Returns: -- * None function M.pauseAllInstances() end -- Resumes an active windowlayout instance after it was paused -- -- Parameters: -- * None -- -- Returns: -- * the `hs.window.layout` object -- -- Notes: -- * if a screen configuration is defined for this windowfilter, and currently not satisfied, this method will do nothing ---@return hs.window.layout function M:resume() end -- Resumes all active windowlayout instances -- -- Parameters: -- * None -- -- Returns: -- * None function M.resumeAllInstances() end -- The number of seconds to wait, after a screen configuration change has been detected, before -- resuming any active windowlayouts that are allowed in the new configuration; defaults -- to 10, to give sufficient time to OSX to do its own housekeeping M.screensChangedDelay = nil -- Determines the screen configuration that permits applying this windowlayout -- -- Parameters: -- * screens - a map, where each *key* must be a valid "hint" for `hs.screen.find()`, and the corresponding -- value can be: -- * `true` - the screen must be currently present (attached and enabled) -- * `false` - the screen must be currently absent -- * an `hs.geometry` point (or constructor argument) - the screen must be present and in this specific -- position in the current arragement (as per `hs.screen:position()`) -- -- Returns: -- * the `hs.window.layout` object -- -- Notes: -- * If `screens` is `nil`, any previous screen configuration is removed, and this windowlayout will be always allowed -- * For "active" windowlayouts, call this method *before* calling `hs.window.layout:start()` -- * By using `hs.geometry` size objects as hints you can define separate layouts for the same physical screen at different resolutions -- * With this method you can define different windowlayouts for different screen configurations (as per System Preferences->Displays->Arrangement). -- * For example, suppose you define two "graphics design work" windowlayouts, one for "desk with dual monitors" and one for "laptop only mode": -- * "passive mode" use: you call `:apply()` on *both* on your chosen hotkey (via `hs.hotkey:bind()`), but only the appropriate layout for the current arrangement will be applied -- * "active mode" use: you just call `:start()` on both windowlayouts; as you switch between workplaces (by attaching or detaching external screens) the correct layout "kicks in" automatically - this is in effect a convenience wrapper that calls `:pause()` on the no longer relevant layout, and `:resume()` on the appropriate one, at every screen configuration change -- -- Examples: -- ```lua -- local laptop_layout,desk_layout=... -- define your layouts -- -- just the laptop screen: -- laptop_layout:setScreenConfiguration{['Color LCD']='0,0',dell=false,['3840x2160']=false}:start() -- -- attached to a 4k primary + a Dell on the right: -- desk_layout:setScreenConfiguration{['3840x2160']='0,0',['dell']='1,0',['Color LCD']='-1,0'}:start() -- -- as above, but in clamshell mode (laptop lid closed): -- clamshell_layout:setScreenConfiguration{['3840x2160']='0,0',['dell']='1,0',['Color LCD']=false}:start() -- ``` ---@return hs.window.layout function M:setScreenConfiguration(screens, ...) end -- Puts a windowlayout instance in "active mode" -- -- Parameters: -- * None -- -- Returns: -- * the `hs.window.layout` object -- -- Notes: -- * If a screen configuration is defined for this windowfilter, and currently not satisfied, this windowfilter will be put in "active mode" but will remain paused until the screen configuration requirements are met -- * When in active mode, a windowlayout instance will constantly monitor the windowfilters for its rules, by subscribing to all the relevant events. As soon as any change is detected (e.g. when you drag a window, switch focus, open or close apps/windows, etc.) the relative rule will be automatically re-applied. In other words, the rules you defined will remain enforced all the time, instead of waiting for manual intervention via `hs.window.layout:apply()`. ---@return hs.window.layout function M:start() end -- Stops a windowlayout instance (i.e. not in "active mode" anymore) -- -- Parameters: -- * None -- -- Returns: -- * the `hs.window.layout` object ---@return hs.window.layout function M:stop() end
return PlaceObj("ModDef", { "title", "Change Rocket Skin", "id", "ChoGGi_ChangeRocketSkin", "steam_id", "1570126808", "pops_any_uuid", "16b2049c-41cb-42de-9c26-6b21c0311967", "lua_revision", 1007000, -- Picard "version", 9, "version_major", 0, "version_minor", 9, "image", "Preview.jpg", "author", "ChoGGi", "code", { "Code/Script.lua", }, --~ "has_options", true, "TagCosmetics", true, "description", [[ Makes the Change Skin button mean something. Some skins are from DLC. The skin may not "stick" the first time it comes back from earth. ]], })
classtools = require 'classtools' tools = require 'tools' Vector = require 'classes/Vector' local MovingThing = {} function MovingThing:constructor(velocity) self.velocity = velocity or Vector() end function MovingThing:new_coords() return self.coords + self.velocity end function MovingThing:update_coords() self.coords = self:new_coords() end -- function MovingThing:display_coords() -- local coords = Vector() -- for i = 0, 1 do -- coords[i] = tools.round(self.coords[i]) -- if coords[i] % 1 == .5 then -- coords[i] = coords[i] + .6 -- end -- end -- -- print(coords) -- return coords -- end function MovingThing:reset_velocity() self.velocity = Vector() end return MovingThing
local mt = {} function mt.__newindex() error("attempt to modify a Null value.", 2) end function mt.__index() error("attempt to index a Null value.", 2) end return setmetatable({}, mt)
-- add requires add_requires("coroutine", {optional = true}) -- add target target("coroutine_switch_coroutine") -- set kind set_kind("binary") -- add files add_files("*.c") -- add package add_packages("coroutine", "tbox") -- enable to build this target? on_load(function (target) target:set("enabled", has_package("coroutine") and true or false) end)
QG = require("QGame") ET = require("EasyTool") MIN_SIZE = {width = 627, height = 627} -- 定义窗口最大尺寸 TEXT_COLOR = {R = 185, G = 185, B = 185, A = 255} -- 定义文字颜色 DRAW_COLOR = {R = 34, G = 34, B = 34, A = 255} -- 定义绘图颜色 MARGIN_WIDTH = 40 -- 定义显示图片的面板与窗口边框间的距离 BUTTON_WIDTH = MARGIN_WIDTH -- 定义按钮宽度 BUTTON_HEIGHT = 80 -- 定义按钮高度 FRAME_DELAY = 20 -- 定义帧间隔,单位为毫秒 SLIDE_DELAY = 150 -- 定义幻灯片切换的帧数间隔 isFirstImg = true -- 当前图片是否是第一张图片 isLastImg = true -- 当前图片是否是最后一张图片 isFullScreen = false -- 当前窗口是否全屏显示 isStartSlide = false -- 当前是否开启幻灯片播放 slideCounter = 0 -- 幻灯片播放计时器 function showInfo(width, height) -- 定义无附加启动参数时的提示信息显示函数,参数分别为窗口宽度和高度 QG.SetDrawColor(DRAW_COLOR.R, DRAW_COLOR.G, DRAW_COLOR.B, DRAW_COLOR.A) -- 设置绘图颜色 QG.SetTextColor(TEXT_COLOR.R, TEXT_COLOR.G, TEXT_COLOR.B, TEXT_COLOR.A) -- 设置文字颜色 QG.Clear() -- 使用当前绘图颜色清空窗口 if not font then font = QG.LoadFont(basePath.."res/SIMYOU.TTF", 100) end QG.DrawText( font, "请 使 用 Q Photo Viewer 打 开 图 片 文 件", width / 2 - width * 0.4 / 2, height / 2 - height * 0.035 / 2, width * 0.4, height * 0.035 ) QG.Update() end function showError(width, height) -- 定义打开文件失败时的错误信息显示函数,参数分别为窗口宽度和高度 QG.SetDrawColor(DRAW_COLOR.R, DRAW_COLOR.G, DRAW_COLOR.B, DRAW_COLOR.A) -- 设置绘图颜色 QG.SetTextColor(TEXT_COLOR.R, TEXT_COLOR.G, TEXT_COLOR.B, TEXT_COLOR.A) -- 设置文字颜色 QG.Clear() -- 使用当前绘图颜色清空窗口 if not font then font = QG.LoadFont(basePath.."res/SIMYOU.TTF", 100) end QG.DrawText( font, "打 开 图 片 失 败 ,不 支 持 的 格 式 或 文 件 已 损 坏", width / 2 - width * 0.5 / 2, height / 2 - height * 0.035 / 2, width * 0.5, height * 0.035 ) QG.Update() end function showImage(image, width, height) -- 定义图片加载成功后的显示函数,参数分别为图片标识、窗口宽度和高度 QG.SetDrawColor(DRAW_COLOR.R, DRAW_COLOR.G, DRAW_COLOR.B, DRAW_COLOR.A) -- 设置绘图颜色 QG.Clear() -- 使用当前绘图颜色清空窗口 imgWidth, imgHeight = QG.GetImageSize(image) -- 获取需要显示的图片的尺寸 panelSize = { x = MARGIN_WIDTH, y = MARGIN_WIDTH, width = width - MARGIN_WIDTH * 2, height = height - MARGIN_WIDTH * 2 } -- 定义用于显示图片的面板尺寸 showSize = {x = 0, y = 0, width = 0, height = 0} -- 定义图片的实际显示尺寸 widthScaleRatio = panelSize.width / imgWidth -- 根据图片和窗口宽度计算可能的水平缩放比例 heightScaleRatio = panelSize.height / imgHeight -- 根据图片和窗口高度计算可能的垂直缩放比例 if widthScaleRatio < 1 or heightScaleRatio < 1 then -- 若水平或垂直缩放比小于1,则进一步计算实际的缩放比 if widthScaleRatio < heightScaleRatio then -- 实际缩放比取二者中的较小值 realScaleRatio = widthScaleRatio else realScaleRatio = heightScaleRatio end showSize.width = imgWidth * realScaleRatio -- 根据图片的实际缩放比计算出图片的实际显示宽度 showSize.height = imgHeight * realScaleRatio -- 根据图片的实际缩放比计算出图片的实际显示高度 else showSize.width = imgWidth -- 若不需要进行缩放,则图片的实际显示宽度即为图片宽度 showSize.height = imgHeight -- 若不需要进行缩放,则图片的实际显示高度即为图片高度 end showSize.x = MARGIN_WIDTH + panelSize.width / 2 - showSize.width / 2 showSize.y = MARGIN_WIDTH + panelSize.height / 2 - showSize.height / 2 QG.ShowImage(image, showSize.x, showSize.y, showSize.width, showSize.height) QG.Update() end function getFileIndex(fileName, fileList) -- 定义在文件列表中获取指定文件索引的函数 local index = 1 for _, file in pairs(fileList) do if fileName == file then break end index = index + 1 end return index end function changePage(width, height, type) -- 定义切换图片函数,type为切页类型,1代表下一页,-1代表上一页 index = index + type if index > #imgList then index = #imgList elseif index < 1 then index = 1 end -- 控制当前图片的索引值不越界 isFirstImg = index == 1 isLastImg = index == #imgList QG.SetWindowTitle("Q Photo Viewer - "..imgList[index]) -- 切页后重新设置窗口标题 QG.SetDrawColor(DRAW_COLOR.R, DRAW_COLOR.G, DRAW_COLOR.B, DRAW_COLOR.A) -- 设置绘图颜色 QG.Clear() -- 使用当前绘图颜色清空窗口 QG.UnloadImage(image) -- 释放当前已加载的图片所占用的资源 image = QG.LoadImage(dirPath.."\\"..imgList[index]) -- 加载图片列表中当前索引所指定的图片 if image == -1 then -- 若图片文件加载失败,则输出错误信息 showError(width, height) else showImage(image, width, height) QG.Update() end end function redraw(width, height) -- 定义重新绘制当前窗口内容的函数 QG.SetDrawColor(DRAW_COLOR.R, DRAW_COLOR.G, DRAW_COLOR.B, DRAW_COLOR.A) -- 设置绘图颜色 QG.Clear() -- 使用当前绘图颜色清空窗口 if not imgList then showError(width, height) -- 若imgList未定义,则首次打开图片失败,重绘内容为错误信息 elseif _argc < 2 then showInfo(width, height) -- 若程序启动参数小于两个,则并未打开其他文件,重绘内容为提示信息 else showImage(image, width, height) -- 否则,重绘的内容为重绘前的图片 end QG.Update() end QG.Init() basePath = QG.GetBasePath() -- 获取当前程序运行目录 QG.CreateWindow("Q Photo Viewer", -1, -1, 1280, 720, "RM") -- 创建窗口,设置窗口默认最大化并且大小可变 QG.SetWindowMinSize(MIN_SIZE.width, MIN_SIZE.height) -- 设置窗口最小尺寸 width, height = QG.GetWindowSize() -- 获取当前最大化的窗口的宽度和高度 img_pgDn = QG.LoadImage(basePath.."res/PgDn.png") -- 下一页按钮图片 img_pgUp = QG.LoadImage(basePath.."res/PgUp.png") -- 上一页按钮图片 if (_argc > 1) then -- 若程序的启动参数大于1个,则是作为打开方式打开其他文件 filePath = _argv[2] -- 目标图片文件路径 imgName = string.match(_argv[2], ".+\\([^\\]*%.%w+)$") -- 目标图片文件名 if not imgName then -- 如果文件名不合法则输出错误信息 showError(width, height) else dirPath = string.match(_argv[2], "(.+)\\[^\\]*%.%w+$") -- 目标图片文件所在目录 QG.SetWindowTitle("Q Photo Viewer - "..imgName) -- 设置窗口标题后添加文件名 image = QG.LoadImage(filePath) -- 加载指定的图片文件 if image == -1 then -- 若图片文件加载失败,则输出错误信息 showError(width, height) else showImage(image, width, height) -- 若图片文件加载成功,则直接显示 fileList = ET.GetFileList(dirPath) imgList = {} for _, fileName in pairs(fileList) do if (#fileName > 3 and ( -- 根据文件扩展名判断文件是否为图片文件 string.sub(fileName, #fileName - 3) == ".jpg" or string.sub(fileName, #fileName - 3) == ".png" or string.sub(fileName, #fileName - 3) == ".gif" or string.sub(fileName, #fileName - 3) == ".bmp" or string.sub(fileName, #fileName - 3) == ".ico" or string.sub(fileName, #fileName - 3) == ".tif" or string.sub(fileName, #fileName - 3) == ".tga" )) or ( #fileName > 4 and ( string.sub(fileName, #fileName - 4) == ".jpeg" or string.sub(fileName, #fileName - 4) == ".jfif" or string.sub(fileName, #fileName - 4) == ".webp" )) then table.insert(imgList, fileName) -- 若扩展名为图片格式则将此文件添加到图片列表中 end end if #imgList == 0 then table.insert(imgList, imgName) end -- 如果无法在目录下获取到图片文件,则将已打开的图片文件加入到文件列表中 index = getFileIndex(imgName, imgList) -- 获取当前图片位于图片列表中的索引 isFirstImg = index == 1 -- 根据索引判断当前图片是否为第一张图片 isLastImg = index == #imgList -- 根据索引判断当前图片是否为最后一张图片 end end else showInfo(width, height) -- 若不作为打开方式打开其他文件,则显示提示信息 end PgUpBtnSize = {x = 0, y = 0, width = BUTTON_WIDTH, height = BUTTON_HEIGHT} -- 定义上一页按钮显示尺寸 PgDnBtnSize = {x = 0, y = 0, width = BUTTON_WIDTH, height = BUTTON_HEIGHT} -- 定义下一页按钮显示尺寸 while true do if isFullScreen and isStartSlide then -- 如果窗口全屏并开启了幻灯片播放,则对计时器累加 slideCounter = slideCounter + 1 if slideCounter >= SLIDE_DELAY then -- 若计时器累加至指定时间间隔则尝试切换图片,并重置计时器 slideCounter = 0 changePage(width, height, 1) end else isStartSlide = false slideCounter = 0 -- 否则关闭幻灯片播放并重置计时器 end if QG.UpdateEvent() == 0 then eventType = QG.GetEventType() if eventType == "QUIT" then QG.Quit() break -- 若检测到退出事件或Esc按键事件,退出QGame库并且跳出循环 elseif eventType == "KEYDOWN_ESC" then -- 若检测Esc按键事件,则退出全屏或退出程序 if isFullScreen then -- 若当前为全屏模式,则退出全屏,重新获取窗口尺寸并重绘窗口 isFullScreen = false QG.SetWindowMode(0) width, height = QG.GetWindowSize() redraw(width, height) else QG.Quit() break end elseif eventType == "MOUSEMOTION" then -- 若检测到鼠标移动事件,更新鼠标位置坐标 x, y = QG.GetCursorPosition() elseif eventType == "MOUSEBUTTON_U_L" then -- 若检测到鼠标左键抬起事件,判断是否点击到按钮上 if x <= PgUpBtnSize.width then changePage(width, height, -1) -- 若鼠标点击在"上一页"按钮位置则尝试显示上一页 elseif x >= width - PgDnBtnSize.width then changePage(width, height, 1) -- 若鼠标点击在"下一页"按钮位置则尝试显示下一页 end elseif imgList and (eventType == "KEYDOWN_RIGHT" or eventType == "KEYDOWN_DOWN") then -- 将imgList是否定义加入判断条件,从而使当前事件只在图片正常显示的情况下被处理 changePage(width, height, 1) elseif imgList and (eventType == "KEYDOWN_LEFT" or eventType == "KEYDOWN_UP") then -- 将imgList是否定义加入判断条件,从而使当前事件只在图片正常显示的情况下被处理 changePage(width, height, -1) elseif eventType == "WINDOWRESIZE" then width, height = QG.GetWindowSize() -- 若检测到窗口大小改变事件,则重新获取当前的窗口的宽度和高度 redraw(width, height) -- 重新绘制当前窗口内容 elseif eventType == "MOUSESCROLL_U" or eventType == "MOUSESCROLL_D" then -- 若检测到鼠标滚轮事件,则对图片进行缩放显示 -- [[ 未完成功能,代码待补充 ]] elseif eventType == "KEYDOWN_F11" then isFullScreen = not isFullScreen -- F11按下后反转当前是否全屏标志 if isFullScreen then QG.SetWindowMode(2) else QG.SetWindowMode(0) end -- 根据是否全屏标志设置窗口显示模式 width, height = QG.GetWindowSize() -- 重新获取当前的窗口的宽度和高度 redraw(width, height) -- 重新绘制当前窗口内容 elseif eventType == "KEYDOWN_F5" then isStartSlide = true -- F5按下后开始播放幻灯片 isFullScreen = true QG.SetWindowMode(2) -- 设置窗口全屏 width, height = QG.GetWindowSize() -- 重新获取当前的窗口的宽度和高度 redraw(width, height) -- 重新绘制当前窗口内容 elseif imgList and eventType == "KEYDOWN_HOME" then -- 将imgList是否定义加入判断条件,从而使当前事件只在图片正常显示的情况下被处理 index = 1 -- Home键按下后将当前图片索引重置到图片列表的第一张图片 redraw(width, height) -- 重新绘制当前窗口内容 elseif imgList and eventType == "KEYDOWN_END" then -- 将imgList是否定义加入判断条件,从而使当前事件只在图片正常显示的情况下被处理 index = #imgList -- End键按下后将当前图片索引重置到图片列表的最后一张图片 redraw(width, height) -- 重新绘制当前窗口内容 end end if not x then x, y = QG.GetCursorPosition() end -- 如果鼠标x坐标未定义则获取鼠标位置坐标 PgUpBtnSize.y = height / 2 - PgUpBtnSize.height / 2 -- 根据当前窗口尺寸计算上一页按钮显示位置y坐标(x坐标始终位于窗口左上角,故不需要计算) PgDnBtnSize.x = width - PgDnBtnSize.width -- 根据当前窗口尺寸计算下一页按钮显示位置x坐标 PgDnBtnSize.y = height / 2 - PgDnBtnSize.height / 2 -- 根据当前窗口尺寸计算下一页按钮显示位置y坐标 if x <= PgUpBtnSize.width and not isFirstImg then QG.ShowImage(img_pgUp, PgUpBtnSize.x, PgUpBtnSize.y, PgUpBtnSize.width, PgUpBtnSize.height) -- 如果当前鼠标所在位置在"上一页"按钮位置则显示此按钮 elseif x >= width - PgDnBtnSize.width and not isLastImg then QG.ShowImage(img_pgDn, PgDnBtnSize.x, PgDnBtnSize.y, PgDnBtnSize.width, PgDnBtnSize.height) -- 如果当前鼠标所在位置在"下一页"按钮位置则显示此按钮 else -- 若鼠标不位于按钮位置,则使用填充矩形覆盖按钮位置,达到按钮消失的效果 QG.SetDrawColor(DRAW_COLOR.R, DRAW_COLOR.G, DRAW_COLOR.B, DRAW_COLOR.A) QG.FillRectangle(PgUpBtnSize.x, PgUpBtnSize.y, PgUpBtnSize.width, PgUpBtnSize.height) QG.FillRectangle(PgDnBtnSize.x, PgDnBtnSize.y, PgDnBtnSize.width, PgDnBtnSize.height) end QG.Update() -- 刷新渲染缓冲区内容 QG.Sleep(FRAME_DELAY) -- 延迟帧间隔 end os.exit()
--[[ A module allowing accsess to the one instance allowed of any singleton module. The module's themselves do not enforce that only one instance can be instantiated, but rather through accessing the modules through this interface, only one instance of the selected class is needed. The instances are created the first time they are accessed, then live for the life of the application session. ]]-- -- Modules local logger = require "src.controller.logger" local crudGUIController = require "src.controller.crudGUIController" local ytgAnalytics = require "src.controller.ytgAnalytics" local ANAYLITICS_KEY = require "flurry_key" -- Just put the key in a seperate file and place in the root folder local noteController = require "src.controller.noteController" local notecardController = require "src.controller.notecardController" local speechController = require "src.controller.speechController" local speechRecordingController = require "src.controller.speechRecordingController" local strings = require "src.model.strings" local ytgAnalytics = require "src.controller.ytgAnalytics" local singletons = {} function singletons.new() local this = {} local loggerI local noteControllerI local notecardControllerI local speechControllerI local speechRecordingControllerI local stringsI local ytgAnalyticsI local analyticsInitialized = false function this.getLoggerI() if loggerI == nil then loggerI = logger.new() end return loggerI end function this.getCrudGUIController() return crudGUIController end function this.getYtgAnalyticsI() if ytgAnalyticsI == nil then ytgAnalyticsI = ytgAnalytics.new(ANAYLITICS_KEY) end return ytgAnalyticsI end function this.getNoteControllerI(notecard) if noteControllerI == nil then noteControllerI = noteController.new(this.getLoggerI(), notecard) else noteControllerI.setParent(notecard) end return noteControllerI end function this.getNotecardControllerI(speech) if notecardControllerI == nil then notecardControllerI = notecardController.new(this.getLoggerI(), speech) else notecardControllerI.setParent(speech) end return notecardControllerI end function this.getSpeechRecordingControllerI(speech, audioControllerI) if speechRecordingControllerI == nil then speechRecordingControllerI = speechRecordingController.new(this.getLoggerI(), speech, audioControllerI) else speechRecordingControllerI.setParent(speech) end return speechRecordingControllerI end function this.getSpeechControllerI() if speechControllerI == nil then speechControllerI = speechController.new(this.getLoggerI()) end return speechControllerI end function this.getStrings() return strings end return this end return singletons
local playsession = { {"ronnaldy", {1954}}, {"Menander", {298461}}, {"VincentMonster", {83784}}, {"Asorr", {1278}}, {"naniboi", {6587}}, {"Conan_Doyil", {12687}}, {"rlidwka", {43879}}, {"longda88", {326}}, {"ETK03", {29145}}, {"rocifier", {425831}}, {"Fingerdash", {18847}}, {"Immo", {84891}} } return playsession
function start (song) math.randomseed(os.time()) microList = {'warm up!', 'spooky dance', 'help tankman is stuttering', 'stay fresh', 'break hearts'}; curSong = 0; end function update (elapsed) -- example https://twitter.com/KadeDeveloper/status/1382178179184422918 -- do nothing end function beatHit (beat) --if beat % 4 == 0 then --newsong = math.random(#microList) --newsong = 1 -- playInst('warehouse/'+tostring(newsong)) --replaceNoteDataFromJSON('warehouse/'+tostring(newsong)) -- end --if beat == 0 then --makeText(microList[newsong], "infiniteugh") -- end --if beat % 4 == 0 then -- destroySprite('infiniteugh') -- end print(beat); print(songNotes); if beat % 4 == 0 then destroySprite('infiniteugh') hasdoneit = 0 end end function stepHit (step) if step >= (((songNotes)* 4) * 4) then hasdoneit = 1 local newsong = math.random(#microList); if (newsong == curSong) then newsong = newsong + 1 if (newsong >= microList) then newsong = 0 end end print(microList[newsong]); replaceNoteDataFromJSON("warehouse/" .. newsong) if hasdoneit == 1 then makeText(microList[newsong], "infiniteugh") curSong = newsong else makeText('warm up', "infiniteugh") end playInst('warehouse/' .. newsong); end end function keyPressed (key) -- do nothing end print("Mod Chart script loaded :)")
--- === plugins.core.tangent.commandpost.functions === --- --- CommandPost Functions for Tangent. local require = require local i18n = require("cp.i18n") local plugin = { id = "core.tangent.commandpost.functions", group = "core", dependencies = { ["core.tangent.commandpost"] = "cpGroup", ["core.console"] = "coreConsole", ["core.helpandsupport.developerguide"] = "developerguide", ["core.helpandsupport.feedback"] = "feedback", ["core.helpandsupport.userguide"] = "userguide", ["core.preferences.manager"] = "prefsMan", ["core.watchfolders.manager"] = "watchfolders", } } function plugin.init(deps) local group = deps.cpGroup:group(i18n("functions")) local id = 0x0AF00001 -------------------------------------------------------------------------------- -- Global Console: -------------------------------------------------------------------------------- group:action(id, i18n("cpGlobalConsole_title")) :onPress(deps.coreConsole.show) id = id + 1 -------------------------------------------------------------------------------- -- Developers Guide: -------------------------------------------------------------------------------- group:action(id, i18n("cpDeveloperGuide_title")) :onPress(deps.developerguide.show) id = id + 1 -------------------------------------------------------------------------------- -- Feedback: -------------------------------------------------------------------------------- group:action(id, i18n("cpFeedback_title")) :onPress(deps.feedback.show) id = id + 1 -------------------------------------------------------------------------------- -- User Guide: -------------------------------------------------------------------------------- group:action(id, i18n("cpUserGuide_title")) :onPress(deps.userguide.show) id = id + 1 -------------------------------------------------------------------------------- -- Open Debug Console: -------------------------------------------------------------------------------- group:action(id, i18n("cpOpenDebugConsole_title")) :onPress(function() hs.openConsole() end) id = id + 1 -------------------------------------------------------------------------------- -- Preferences: -------------------------------------------------------------------------------- group:action(id, i18n("cpPreferences_title")) :onPress(deps.prefsMan.show) id = id + 1 -------------------------------------------------------------------------------- -- Setup Watch Folders: -------------------------------------------------------------------------------- group:action(id, i18n("cpSetupWatchFolders_title")) :onPress(deps.watchfolders.show) end return plugin
pfUI:RegisterModule("buff", function () -- Hide Blizz BuffFrame:Hide() BuffFrame:UnregisterAllEvents() TemporaryEnchantFrame:Hide() TemporaryEnchantFrame:UnregisterAllEvents() local function RefreshBuffButton(buff) buff.id = buff.gid - (buff.btype == "HELPFUL" and pfUI.buff.buffs.offset or 0) buff.bid = GetPlayerBuff(buff.id-1, buff.btype) -- detect weapon buffs if buff.gid <= pfUI.buff.buffs.offset and buff.btype == "HELPFUL" then local mh, mhtime, mhcharge, oh, ohtime, ohcharge = GetWeaponEnchantInfo() if pfUI.buff.buffs.offset == 2 then if buff.gid == 1 then buff.mode = "MAINHAND" else buff.mode = "OFFHAND" end else buff.mode = oh and "OFFHAND" or mh and "MAINHAND" end -- Set Weapon Texture and Border if buff.mode == "MAINHAND" then buff.texture:SetTexture(GetInventoryItemTexture("player", 16)) buff.backdrop:SetBackdropBorderColor(GetItemQualityColor(GetInventoryItemQuality("player", 16) or 1)) elseif buff.mode == "OFFHAND" then buff.texture:SetTexture(GetInventoryItemTexture("player", 17)) buff.backdrop:SetBackdropBorderColor(GetItemQualityColor(GetInventoryItemQuality("player", 17) or 1)) end elseif buff.bid >= 0 and (( buff.btype == "HARMFUL" and C.buffs.debuffs == "1" ) or ( buff.btype == "HELPFUL" and C.buffs.buffs == "1" )) then -- Set Buff Texture and Border buff.mode = buff.btype buff.texture:SetTexture(GetPlayerBuffTexture(buff.bid)) CreateBackdrop(buff) if buff.btype == "HARMFUL" then local dtype = GetPlayerBuffDispelType(buff.bid) if dtype == "Magic" then buff.backdrop:SetBackdropBorderColor(0,1,1,1) elseif dtype == "Poison" then buff.backdrop:SetBackdropBorderColor(0,1,0,1) elseif dtype == "Curse" then buff.backdrop:SetBackdropBorderColor(1,0,1,1) elseif dtype == "Disease" then buff.backdrop:SetBackdropBorderColor(1,1,0,1) else buff.backdrop:SetBackdropBorderColor(1,0,0,1) end end else buff:Hide() return end buff:Show() end local function CreateBuffButton(i, btype) local buff = CreateFrame("Button", ( btype == "HELPFUL" and "pfBuffFrameBuff" or "pfDebuffFrameBuff" ) .. i, ( btype == "HARMFUL" and pfUI.buff.debuffs or pfUI.buff.buffs )) buff.texture = buff:CreateTexture("BuffIcon" .. i, "BACKGROUND") buff.texture:SetTexCoord(.07,.93,.07,.93) buff.texture:SetAllPoints(buff) buff.timer = buff:CreateFontString(nil, "OVERLAY", "GameFontNormal") buff.timer:SetTextColor(1,1,1,1) buff.timer:SetJustifyH("CENTER") buff.timer:SetJustifyV("CENTER") buff.stacks = buff:CreateFontString(nil, "OVERLAY", "GameFontNormal") buff.stacks:SetTextColor(1,1,1,1) buff.stacks:SetJustifyH("RIGHT") buff.stacks:SetJustifyV("BOTTOM") buff.stacks:SetAllPoints(buff) buff:RegisterForClicks("RightButtonUp") buff.btype = btype buff.gid = i buff:SetScript("OnUpdate", function() if not this.next then this.next = GetTime() + .1 end if this.next > GetTime() then return end this.next = GetTime() + .1 local timeleft = 0 local stacks = 0 if this.mode == this.btype then timeleft = GetPlayerBuffTimeLeft(this.bid, this.btype) stacks = GetPlayerBuffApplications(this.bid, this.btype) elseif this.mode == "MAINHAND" then local _, mhtime, mhcharge = GetWeaponEnchantInfo() timeleft = mhtime/1000 stacks = mhcharge elseif this.mode == "OFFHAND" then local _, _, _, _, ohtime, ohcharge = GetWeaponEnchantInfo() timeleft = ohtime/1000 charge = ohcharge end this.timer:SetText(timeleft > 0 and GetColoredTimeString(timeleft) or "") this.stacks:SetText(stacks > 1 and stacks or "") end) buff:SetScript("OnEnter", function() GameTooltip:SetOwner(this, "ANCHOR_BOTTOMRIGHT") if this.mode == this.btype then GameTooltip:SetPlayerBuff(this.bid) if IsShiftKeyDown() then local texture = GetPlayerBuffTexture(this.bid) local playerlist = "" local first = true if UnitInRaid("player") then for i=1,40 do local unitstr = "raid" .. i if not UnitHasBuff(unitstr, texture) and UnitName(unitstr) then playerlist = playerlist .. ( not first and ", " or "") .. GetUnitColor(unitstr) .. UnitName(unitstr) .. "|r" first = nil end end else if not UnitHasBuff("player", texture) then playerlist = playerlist .. ( not first and ", " or "") .. GetUnitColor(unitstr) .. UnitName("player") .. "|r" first = nil end for i=1,4 do local unitstr = "party" .. i if not UnitHasBuff(unitstr, texture) and UnitName(unitstr) then playerlist = playerlist .. ( not first and ", " or "") .. GetUnitColor(unitstr) .. UnitName(unitstr) .. "|r" first = nil end end end if strlen(playerlist) > 0 then GameTooltip:AddLine(" ") GameTooltip:AddLine(T["Unbuffed"] .. ":", .3, 1, .8) GameTooltip:AddLine(playerlist,1,1,1,1) GameTooltip:Show() end end elseif this.mode == "MAINHAND" then GameTooltip:SetInventoryItem("player", 16) elseif this.mode == "OFFHAND" then GameTooltip:SetInventoryItem("player", 17) end end) buff:SetScript("OnLeave", function() GameTooltip:Hide() end) buff:SetScript("OnClick", function() CancelPlayerBuff(this.bid) end) CreateBackdrop(buff) RefreshBuffButton(buff) return buff end local function GetNumBuffs() local mh, mhtime, mhcharge, oh, ohtime, ohcharge = GetWeaponEnchantInfo() local offset = (mh and 1 or 0) + (oh and 1 or 0) for i=1,32 do local bid, untilCancelled = GetPlayerBuff(i-1, "HELPFUL") if bid < 0 then return i - 1 + offset end end return 0 + offset end pfUI.buff = CreateFrame("Frame", "pfGlobalBuffFrame", UIParent) pfUI.buff:RegisterEvent("PLAYER_AURAS_CHANGED") pfUI.buff:RegisterEvent("UNIT_INVENTORY_CHANGED") pfUI.buff:RegisterEvent("UNIT_MODEL_CHANGED") pfUI.buff:SetScript("OnEvent", function() if C.buffs.weapons == "1" then local mh, mhtime, mhcharge, oh, ohtime, ohcharge = GetWeaponEnchantInfo() pfUI.buff.buffs.offset = (mh and 1 or 0) + (oh and 1 or 0) else pfUI.buff.buffs.offset = 0 end for i=1,32 do RefreshBuffButton(pfUI.buff.buffs.buttons[i]) end for i=1,16 do RefreshBuffButton(pfUI.buff.debuffs.buttons[i]) end end) -- Buff Frame pfUI.buff.buffs = CreateFrame("Frame", "pfBuffFrame", UIParent) pfUI.buff.buffs.offset = 0 pfUI.buff.buffs.buttons = {} for i=1,32 do pfUI.buff.buffs.buttons[i] = CreateBuffButton(i, "HELPFUL") end -- Debuffs pfUI.buff.debuffs = CreateFrame("Frame", "pfDebuffFrame", UIParent) pfUI.buff.debuffs.buttons = {} for i=1,16 do pfUI.buff.debuffs.buttons[i] = CreateBuffButton(i, "HARMFUL") end -- config loading function pfUI.buff:UpdateConfigBuffButton(buff) local fontsize = C.buffs.fontsize == "-1" and C.global.font_size or C.buffs.fontsize local rowcount = floor((buff.gid-1) / tonumber(C.buffs.rowsize)) buff:SetWidth(tonumber(C.buffs.size)) buff:SetHeight(tonumber(C.buffs.size)) buff:ClearAllPoints() buff:SetPoint("TOPRIGHT", ( buff.btype == "HARMFUL" and pfUI.buff.debuffs or pfUI.buff.buffs ), "TOPRIGHT", -(buff.gid-1-rowcount*tonumber(C.buffs.rowsize))*(tonumber(C.buffs.size)+2*tonumber(C.buffs.spacing)), -(rowcount) * ((C.buffs.textinside == "1" and 0 or (fontsize*1.5))+tonumber(C.buffs.size)+2*tonumber(C.buffs.spacing))) buff.timer:SetFont(pfUI.font_default, fontsize, "OUTLINE") buff.stacks:SetFont(pfUI.font_default, fontsize+1, "OUTLINE") buff.timer:SetHeight(fontsize * 1.3) buff.timer:ClearAllPoints() if C.buffs.textinside == "1" then buff.timer:SetAllPoints(buff) else buff.timer:SetPoint("TOP", buff, "BOTTOM", 0, -3) end end function pfUI.buff:UpdateConfig() local fontsize = C.buffs.fontsize == "-1" and C.global.font_size or C.buffs.fontsize pfUI.buff.buffs:SetWidth(tonumber(C.buffs.rowsize) * (tonumber(C.buffs.size)+2*tonumber(C.buffs.spacing))) pfUI.buff.buffs:SetHeight(ceil(32/tonumber(C.buffs.rowsize)) * ((C.buffs.textinside == "1" and 0 or (fontsize*1.5))+tonumber(C.buffs.size)+2*tonumber(C.buffs.spacing))) pfUI.buff.buffs:SetPoint("TOPRIGHT", pfUI.minimap or UIParent, "TOPLEFT", -2*tonumber(C.buffs.spacing), 0) UpdateMovable(pfUI.buff.buffs) pfUI.buff.debuffs:SetWidth(tonumber(C.buffs.rowsize) * (tonumber(C.buffs.size)+2*tonumber(C.buffs.spacing))) pfUI.buff.debuffs:SetHeight(ceil(16/tonumber(C.buffs.rowsize)) * ((C.buffs.textinside == "1" and 0 or (fontsize*1.5))+tonumber(C.buffs.size)+2*tonumber(C.buffs.spacing))) pfUI.buff.debuffs:SetPoint("TOPRIGHT", pfUI.buff.buffs, "BOTTOMRIGHT", 0, 0) UpdateMovable(pfUI.buff.debuffs) for i=1,32 do pfUI.buff:UpdateConfigBuffButton(pfUI.buff.buffs.buttons[i]) end for i=1,16 do pfUI.buff:UpdateConfigBuffButton(pfUI.buff.debuffs.buttons[i]) end pfUI.buff:GetScript("OnEvent")() end pfUI.buff:UpdateConfig() end)
-- This script uses writes to 0x7fd, 0x7fe, and 0x7ff to determine when to store the start of an IRQ, game loop, or NMI respectively. -- If you write the value 2 to the address when you start the area you'd like to time, you then write the value 1 to that same address -- to stop the timer and calculate the cycles elapsed and display it on screen. For example, to time your NMI code, at the beginning of -- your NMI routine, write 2 to 0x7ff and then after you're done with your NMI, before calling RTI, write 1 to 0x7ff and that will display -- the number of cycles it took to complete your NMI code. Hopefully it's not too many! --emu.speedmode("normal") -- Set the speed of the emulator -- Declare and set variables or functions if needed timing = false; nminowcount = 0; gamelooplast = 0; irqlast = 0; function getTypeLabel(etype) if etype == 1 then return "Blaster"; elseif etype == 2 then return "Bullet"; elseif etype == 3 then return "FlyBy"; elseif etype == 4 then return "Player"; else return "Unknown"; end end function calcframes(address, size) value = memory.readbyte(address); if value == 2 then if address == 0x07ff then nmilastcount = debugger.getcyclescount(); elseif address == 0x07fe then gamelooplast = debugger.getcyclescount(); elseif address == 0x07fd then irqlast = debugger.getcyclescount(); end return elseif value == 1 then if address == 0x07ff then diff = debugger.getcyclescount() - nmilastcount; gui.text(10,10,"NMI: " .. diff); elseif address == 0x07fe then diff = debugger.getcyclescount() - gamelooplast; gui.text(10,20,"GL: " .. diff); elseif address == 0x07fd then diff = debugger.getcyclescount() - irqlast; gui.text(10,30,"IRQ: " .. diff); end end end memory.registerwrite(0x07ff, 1, calcframes); memory.registerwrite(0x07fe, 1, calcframes); memory.registerwrite(0x07fd, 1, calcframes); --while true do --for i = 0,18 --do --baseaddr = 0x0021 + (i*6); --x = memory.readbyte(baseaddr) --y = memory.readbyte(baseaddr+1) --xv = memory.readbyte(baseaddr+2) --if xv > 127 then --xv = xv - 256 --end --yv = memory.readbyte(baseaddr+3) --if yv > 127 then --yv = yv - 256 --end --etype = memory.readbyte(baseaddr+4) --if etype ~= 0 then ----gui.text(10,40 + (i*10),i .. ": " .. getTypeLabel(etype) .. " " .. x .. ", " .. y .. ": " .. xv .. ", " .. yv); --end --end emu.frameadvance() -- This essentially tells FCEUX to keep running end
-- Generated by CSharp.lua Compiler local System = System System.namespace("Slipe.Client.Enums", function (namespace) -- <summary> -- Represents a room used in setInteriorFurnitureEnabled -- </summary> namespace.enum("RoomFurniture", function () return { Shop = 0, Office = 1, Lounge = 2, Bedroom = 3, Kitchen = 4 } end) end)
require "Window" local TrackLineGroup = {} setmetatable(TrackLineGroup, { __call = function (cls, ...) return cls.new(...) end, }) TrackLineGroup.TrackMode = { Line = 1, Circle = 2 } function TrackLineGroup.new(parent) local self = setmetatable({}, { __index = TrackLineGroup }) self.Enabled = false self.parent = parent self.bgColor = CColor.new(0,1,0,1) self.intermediateColor = CColor.new(0, 0, 1, 1) self.complementaryColor = CColor.new(1, 0, 1, 1) self.clearDistance = 0 --20 self.target = nil self.Sprite = "Icons:Arrow" self.trackMode = TrackLineGroup.TrackMode.Line --self.trackMode = TrackLine.TrackMode.Circle self.rotation = 0 self.updateRotation = true self.isVisible = false self.distance = 10 self.distanceMarker = 2 self.showDistanceMarker = true self.TrackLines = {} return self end function TrackLineGroup:Load(saveData) if saveData ~= nil then self.Enabled = saveData.Enabled self:SetBGColor(CColor.new(saveData.bgColor[1], saveData.bgColor[2], saveData.bgColor[3], saveData.bgColor[4])) self.Sprite = saveData.Sprite if saveData.trackMode ~= nil then self:SetTrackMode(saveData.trackMode) end if saveData.distance ~= nil then self:SetDistance(saveData.distance) end if saveData.showDistanceMarker ~= nil then self.showDistanceMarker = saveData.showDistanceMarker end GeminiPackages:Require("AuraMastery:TrackLine", function(trackLine) for i = 1, saveData.numberOfTrackLines or 0, 1 do local line = trackLine.new(self) line:Load(saveData) table.insert(self.TrackLines, line) end end) end end function TrackLineGroup:Save() local saveData = { } saveData.Enabled = self.Enabled saveData.Sprite = self.Sprite saveData.bgColor = { self.bgColor.r, self.bgColor.g, self.bgColor.b, self.bgColor.a } saveData.trackMode = self.trackMode saveData.distance = self.distance saveData.showDistanceMarker = self.showDistanceMarker saveData.numberOfTrackLines = #self.TrackLines return saveData end function TrackLineGroup:SetConfig(configWnd) self.Enabled = configWnd:FindChild("TrackLineEnabled"):IsChecked() local numberOfTrackLines = tonumber(configWnd:FindChild("TrackLineNumberOfLines"):GetText()) if #self.TrackLines < numberOfTrackLines then for i = #self.TrackLines + 1, numberOfTrackLines, 1 do GeminiPackages:Require("AuraMastery:TrackLine", function(trackLine) local line = trackLine.new(self) line:Load(self:Save()) table.insert(self.TrackLines, line) end) end elseif #self.TrackLines > numberOfTrackLines then for i = #self.TrackLines, numberOfTrackLines + 1, -1 do self.TrackLines[i]:Destroy() table.remove(self.TrackLines, i) end end end function TrackLineGroup:NumberOfLines() return #self.TrackLines end function TrackLineGroup:Update() if not self.Enabled then return end self:UpdateTarget() for _, trackLine in pairs(self.TrackLines) do trackLine:Update() end end function TrackLineGroup:UpdateTarget() local targets = self.parent:GetTargets() or {} local i = 1 for _, target in pairs(targets) do if self.TrackLines[i] == nil then return end self.TrackLines[i]:SetTarget(target.Unit) i = i + 1 end local numOfLines = #self.TrackLines for i = i, numOfLines, 1 do self.TrackLines[i]:SetTarget(nil) end end function TrackLineGroup:DrawTracker(target) self.isVisible = true if GameLib.GetPlayerUnit() ~= nil then local player = GameLib.GetPlayerUnit() local playerPos = GameLib.GetPlayerUnit():GetPosition() local playerVec = Vector3.New(playerPos.x, playerPos.y, playerPos.z) local targetVec = nil if Vector3.Is(target) then targetVec = target elseif Unit.is(target) then local targetPos = target:GetPosition() if targetPos then targetVec = Vector3.New(targetPos.x, targetPos.y, targetPos.z) end end if targetVec ~= nil then if self.trackMode == TrackLine.TrackMode.Line then self:DrawLineBetween(playerVec, targetVec) elseif self.trackMode == TrackLine.TrackMode.Circle then self:DrawCircleAround(playerVec, targetVec) end else self:HideLine() end else self:HideLine() end end function TrackLineGroup:SetBGColor(color) self.bgColor = color self.intermediateColor = color self.complementaryColor = color --self.intermediateColor = self.trackMaster.colorPicker:GetComplementaryOffset(self.bgColor) --self.complementaryColor = self.trackMaster.colorPicker:GetComplementary(self.bgColor) --self.marker[self.distanceMarker]:FindChild("Distance"):SetTextColor(color) end function TrackLineGroup:SetTrackMode(mode) self.trackMode = mode end function TrackLineGroup:SetDistance(distance) self.distance = distance end function TrackLineGroup:SetShowDistanceMarker(isShown) self.showDistanceMarker = isShown if self.showDistanceMarker then self.marker[self.distanceMarker]:FindChild("Distance"):Show(true, true) self.marker[self.distanceMarker]:FindChild("Distance"):SetTextColor(self.bgColor) self.marker[self.distanceMarker]:SetSprite("") self.marker[self.distanceMarker]:SetRotation(0) else self.marker[self.distanceMarker]:SetSprite(self.Sprite) self.marker[self.distanceMarker]:FindChild("Distance"):Show(false, true) end end local GeminiPackages = _G["GeminiPackages"] GeminiPackages:NewPackage(TrackLineGroup, "AuraMastery:TrackLineGroup", 1)
--Template for addition of new protocol 'overlay' --[[ Necessary changes to other files: -- - packet.lua: if the header has a length member, adapt packetSetLength; -- if the packet has a checksum, adapt createStack (loop at end of function) and packetCalculateChecksums -- - proto/proto.lua: add PROTO.lua to the list so it gets loaded --]] local ffi = require "ffi" local dpdkc = require "dpdkc" require "bitfields_def" require "utils" require "proto.template" local initHeader = initHeader local ntoh, hton = ntoh, hton local ntoh16, hton16 = ntoh16, hton16 local bor, band, bnot, rshift, lshift= bit.bor, bit.band, bit.bnot, bit.rshift, bit.lshift local istype = ffi.istype local format = string.format function hton64(int) int = int or 0 endianness = string.dump(function() end):byte(7) if endianness==0 then return int end low_int = lshift(hton(band(int,0xFFFFFFFFULL)),32) high_int = rshift(hton(band(int,0xFFFFFFFF00000000ULL)),32) endianness = string.dump(function() end):byte(7) return (high_int+low_int) end local ntoh64, hton64 = ntoh64, hton64 ----------------------------------------------------- ---- netchain_overlay header and constants ----------------------------------------------------- local netchain_overlay = {} netchain_overlay.headerFormat = [[ uint32_t swip; ]] -- variable length fields netchain_overlay.headerVariableMember = nil -- Module for netchain_overlay_address struct local netchain_overlayHeader = initHeader() netchain_overlayHeader.__index = netchain_overlayHeader ----------------------------------------------------- ---- Getters, Setters and String functions for fields ----------------------------------------------------- function netchain_overlayHeader:getSWIP() return hton(self.swip) end function netchain_overlayHeader:getSWIPstring() return self:getSWIP() end function netchain_overlayHeader:setSWIP(int) int = int or 0 self.swip = hton(int) end ----------------------------------------------------- ---- Functions for full header ----------------------------------------------------- -- Set all members of the PROTO header function netchain_overlayHeader:fill(args,pre) args = args or {} pre = pre or 'netchain_overlay' self:setSWIP(args[pre .. 'SWIP']) end -- Retrieve the values of all members function netchain_overlayHeader:get(pre) pre = pre or 'netchain_overlay' local args = {} args[pre .. 'SWIP'] = self:getSWIP() return args end function netchain_overlayHeader:getString() return 'netchain_overlay \n' .. 'SWIP' .. self:getSWIPString() .. '\n' end -- Dictionary for next level headers local nextHeaderResolve = { netchain_nc_hdr = 0x00000000, netchain_overlay = default, } function netchain_overlayHeader:resolveNextHeader() local key = self:getSWIP() for name, value in pairs(nextHeaderResolve) do if key == value then return name end end return nil end function netchain_overlayHeader:setDefaultNamedArgs(pre, namedArgs, nextHeader, accumulatedLength) if not namedArgs[pre .. 'SWIP'] then for name, _port in pairs(nextHeaderResolve) do if nextHeader == name then namedArgs[pre .. 'SWIP'] = _port break end end end return namedArgs end ----------------------------------------------------- ---- Metatypes ----------------------------------------------------- netchain_overlay.metatype = netchain_overlayHeader return netchain_overlay
--[[ This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:29' using the latest game version. NOTE: This file should only be used as IDE support; it should NOT be distributed with addons! **************************************************************************** CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC. **************************************************************************** ]] ZO_CharacterCreateTriangle_Gamepad = ZO_CharacterCreateTriangle_Base:Subclass() function ZO_CharacterCreateTriangle_Gamepad:New(triangleControl, setterFn, updaterFn, triangleStringId, topStringId, leftStringId, rightStringId) local triangle = ZO_CharacterCreateTriangle_Base.New(self, triangleControl, setterFn, updaterFn, triangleStringId, topStringId, leftStringId, rightStringId) -- Prevent the Focus Movement Controller from interfering with the triangle movement triangle.disableFocusMovementController = true return triangle end function ZO_CharacterCreateTriangle_Gamepad:UpdateDirectionalInput() if self:IsLocked() then return end local x, y = self.picker:GetThumbPosition() x = x / self.width y = y / self.height local mx, my = DIRECTIONAL_INPUT:GetXY(ZO_DI_LEFT_STICK, ZO_DI_DPAD) local deadZone = 0.0 local scale = 0.02 local changed = false if math.abs(mx) > deadZone then x = x + mx * scale changed = true end if math.abs(my) > deadZone then y = y - my * scale changed = true end if changed then self:SetValue(self.width * x, self.height * y) self:Update() end end function ZO_CharacterCreateTriangle_Gamepad:EnableFocus(enabled) if enabled then DIRECTIONAL_INPUT:Activate(self, self.control) else DIRECTIONAL_INPUT:Deactivate(self) end end
local print = print local tostring = tostring local type = type local pairs = pairs local insert_table = table.insert local concat_table = table.concat local rep_str = string.rep local function is_table(t, name) if "table" ~= type(t) then if name then print(tostring(name) .. " = [" .. tostring(t) .. "]") else print(t) end return false end return true end local function print_rm(t, name) if not is_table(t, name) then return end local cache = { [t] = "." } --To filter cycle reference local output = {} local maxlines = 30 local space = " " local outtop = 1 local function insert_output(str) output[outtop] = str outtop = outtop + 1 if maxlines < outtop then print(concat_table(output, "\n")) outtop = 1 end end local function _dump(t, depth, name) for k, v in pairs(t) do local kname = tostring(k) local text if cache[v] then --Cycle reference insert_output(rep_str(space, depth) .. "|- " .. kname .. "\t{" .. cache[v] .. "}") elseif "table" == type(v) then local new_table_key = name .. "." .. kname cache[v] = new_table_key insert_output(rep_str(space, depth) .. "|- " .. kname) _dump(v, depth + 1, new_table_key) else insert_output(rep_str(space, depth) .. "|- " .. kname .. "\t[" .. tostring(v) .. "]") end end local mt = getmetatable(t) if mt then if cache[mt] then insert_output(rep_str(space, depth) .. "|- {__metatable}\t{" .. cache[v] .. "}") else local new_table_key = name .. ".{__metatable}" cache[mt] = new_table_key insert_output(rep_str(space, depth) .. "|- {__metatable}") _dump(mt, depth + 1, new_table_key) end end end if name then print(name) end _dump(t, 0, "") print(concat_table(output, "\n", 1, outtop - 1)) end local function print_r(t, name) if not is_table(t, name) then return end local cache = { [t] = "." } --To filter cycle reference local output = {} local maxlines = 30 local space = " " local function insert_output(str) insert_table(output, str) if maxlines <= #output then --flush output print(concat_table(output, "\n")) output = {} end end local function _dump(t, depth, name) for k, v in pairs(t) do local kname = tostring(k) local text if cache[v] then --Cycle reference insert_output(rep_str(space, depth) .. "|- " .. kname .. "\t{" .. cache[v] .. "}") elseif "table" == type(v) then local new_table_key = name .. "." .. kname cache[v] = new_table_key insert_output(rep_str(space, depth) .. "|- " .. kname) _dump(v, depth + 1, new_table_key) else insert_output(rep_str(space, depth) .. "|- " .. kname .. "\t[" .. tostring(v) .. "]") end end end if name then print(name) end _dump(t, 0, "") print(concat_table(output, "\n")) end local function print_m(t, name) if not is_table(t, name) then return end if name then print(name) end for k, v in pairs(t) do print("|- " .. tostring(k) .. "\t[" .. tostring(v) .. "]") end meta = getmetatable(t) if meta then print("|- {__metatable}") for k, v in pairs(meta) do print(" |- " .. tostring(k) .. "\t[" .. tostring(v) .. "]") end end end local function print_t(t, name) if not is_table(t, name) then return end if name then print(name) end for k, v in pairs(t) do print("|- " .. tostring(k) .. " [" .. tostring(v) .. "]") end end local function print_c(c, name) --Print table as a class if not is_table(c, name) then return end local funcs = {} local vars = {} local function _dump(t) for k, v in pairs(t) do if "function" == type(v) and not funcs[k] then funcs[k] = v elseif not vars[k] then vars[k] = v end end local mt = getmetatable(t) if mt then _dump(mt) if "table" == type(mt.__index) then return _dump(mt.__index) end end end _dump(c) vars.__index = undef --Compatibility for Lua5.4 if name then print(name) end print("methods") for k in pairs(funcs) do print("|- " .. tostring(k)) end print("vars") for k, v in pairs(vars) do print("|- " .. tostring(k) .. "\t[" ..tostring(v) .. "]") end return vars end table.print_rm = print_rm table.print_r = print_r table.print_m = print_m table.print_c = print_c table.print = print_t
function ulx.spark(calling_ply, target_plys) for _, ply in ipairs(target_plys) do if not ply:Alive() then return ULib.tsay(calling_ply, ply:Nick() .. " is dead", true) elseif ply.jail then return ULib.tsay(calling_ply, ply:Nick() .. " is in jail", true) elseif ply.ragdoll then return ULib.tsay(calling_ply, ply:Nick() .. " is a ragdoll", true) end ply:Kill() local ragdoll = ply.corpse ragdoll:GetPhysicsObject():ApplyForceCenter(Vector(0, 0, -10000000)) ragdoll:EmitSound("ambient/atmosphere/thunder1.wav", 100, 125, 1, CHAN_AUTO) for i = 0, ragdoll:GetBoneCount() do local id = ragdoll:TranslateBoneToPhysBone(i) if id ~= -1 then ragdoll:GetPhysicsObjectNum(id):ApplyForceCenter(Vector(math.random(-5000, 5000), math.random(-5000, 5000), math.random(0, 5000))) end end for i = 1, 25 do timer.Simple(math.random(0, 100)/100, function() local effectdata = EffectData() effectdata:SetOrigin(ragdoll:GetPos() + Vector(math.random(-20, 20), math.random(-20, 20), math.random(0, 50))) effectdata:SetStart(ragdoll:GetPos() + Vector(math.random(-100, 100), math.random(-100, 100), 500 + math.random(-50, 50))) util.Effect("ToolTracer", effectdata) end) end end ulx.fancyLogAdmin(calling_ply, "#A has stricken lightning upon #T!", target_plys) end local cmd = ulx.command("Fun", "ulx spark", ulx.spark, "!spark") cmd:addParam{type = ULib.cmds.PlayersArg} cmd:defaultAccess(ULib.ACCESS_ADMIN) cmd:help("Strikes lightning upon your poor victem.")
-- ============================================= -- Server PlayerList handler -- ============================================= --Check Environment if GetConvar('txAdminServerMode', 'false') ~= 'true' then return end local oneSyncConvar = GetConvar('onesync', 'off') local onesyncEnabled = oneSyncConvar == 'on' or oneSyncConvar == 'legacy' -- Variables local intervalUpdateTime = 5000 --FIXME: use convar local epochDuration = 30 --FIXME: use convar, seconds local epochTimestamp = 0 local epochData = {} local epochDiff = false local respCacheEpoch = false --json cache local respCacheDiff = false --json cache local disconnectedAfterEpoch = {} --the ID of the ones that disconnected between epochs local playerSelfReportData = {} TX_PLAYERLIST = {} -- available globally in tx, is always updated -- Optimizations local ceil = math.ceil local max = math.max local min = math.min local sub = string.sub local len = string.len local tonumber = tonumber local tostring = tostring local pairs = pairs --FIXME: https://github.com/tabarra/txAdmin/pull/434/files is for the old function only, apply here --[[ Emit player list to clients ]] CreateThread(function() while false do Wait(intervalUpdateTime) local rightNow = os.time() local tmpPlayerlist = {} local tmpPlayerlistDiff = {} local shouldDiff = (rightNow - epochTimestamp < epochDuration) if not shouldDiff then disconnectedAfterEpoch = {} end -- For each player local players = GetPlayers() for _, serverID in pairs(players) do -- defaults local health = 0 local coords = -1 local vehClass = 'unknown' -- from self-report if type(playerSelfReportData[serverID]) == 'table' then vehClass = playerSelfReportData[serverID].vehClass or vehClass health = playerSelfReportData[serverID].health or health coords = playerSelfReportData[serverID].coords or coords end -- from server if onesyncEnabled == true then local ped = GetPlayerPed(serverID) health = ceil(((GetEntityHealth(ped) - 100) / 100) * 100) coords = GetEntityCoords(ped) or -1 end -- Updating TX_PLAYERLIST if type(TX_PLAYERLIST[serverID]) ~= 'table' then TX_PLAYERLIST[serverID] = { name = sub(GetPlayerName(serverID) or "unknown", 1, 75), ids = GetPlayerIdentifiers(serverID), h = health, c = coords, v = vehClass, } else TX_PLAYERLIST[serverID].h = health TX_PLAYERLIST[serverID].c = coords TX_PLAYERLIST[serverID].v = vehClass end -- We actually need this locally, can't do tmpPlayerlist[serverID] = TX_PLAYERLIST[serverID] tmpPlayerlist[serverID] = { name = TX_PLAYERLIST[serverID].name, ids = TX_PLAYERLIST[serverID].ids, h = TX_PLAYERLIST[serverID].h, c = TX_PLAYERLIST[serverID].c, v = TX_PLAYERLIST[serverID].v, } -- Process the diff if shouldDiff then if type(epochData[serverID]) ~= 'table' then tmpPlayerlistDiff[serverID] = tmpPlayerlist[serverID] else local playerDiffData = {} local anyChanged = false if epochData[serverID].h ~= tmpPlayerlist[serverID].h then anyChanged = true playerDiffData.h = tmpPlayerlist[serverID].h end if epochData[serverID].c ~= tmpPlayerlist[serverID].c then anyChanged = true playerDiffData.c= tmpPlayerlist[serverID].c end if epochData[serverID].v ~= tmpPlayerlist[serverID].v then anyChanged = true playerDiffData.v = tmpPlayerlist[serverID].v end if anyChanged then tmpPlayerlistDiff[serverID] = playerDiffData end end end Wait(0) end --end for players --Applies the changes to epoch or diff and prepare cached json response if shouldDiff then debugPrint('Updating ^5epochDiff') epochDiff = tmpPlayerlistDiff for _, id in pairs(disconnectedAfterEpoch) do epochDiff[id] = false end respCacheDiff = json.encode({ ts = epochTimestamp, diff = epochDiff }) else debugPrint('Updating ^1epochData') epochDiff = false; epochTimestamp = rightNow; epochData = tmpPlayerlist; respCacheDiff = false end respCacheEpoch = json.encode({ ts = epochTimestamp, data = epochData }) -- DEBUG -- print(json.encode({ -- ts = epochTimestamp; -- diff = epochDiff; -- data = epochData; -- }, {indent = true})) -- debugPrint("====================================") end --end while true end) --[[ Sets self-reported data ]] local vehClassMap = { ["nil"] = "unknown", ["0"] = "walking", ["8"] = "biking", ["14"] = "boating", ["15"] = "flying", --heli ["16"] = "flying", --planes } RegisterNetEvent('txAdmin:selfDataReport', function(vehClass, health, coords) local s = source vehClass = tostring(vehClass) if vehClassMap[vehClass] ~= nil then vehClass = vehClassMap[vehClass] else vehClass = "driving" end if onesyncEnabled == true then playerSelfReportData[tostring(s)] = { vehClass = vehClass } else playerSelfReportData[tostring(s)] = { vehClass = vehClass, health = min(max(tonumber(health or -100), -100), 200), coords = coords or -1 } end end) --[[ Handle player disconnects ]] AddEventHandler('playerDropped', function() local s = tostring(source) TX_PLAYERLIST[s] = nil playerSelfReportData[s] = nil disconnectedAfterEpoch[#disconnectedAfterEpoch+1] = s end) --[[ Handle Playerlist HTTP Requests ]] txHttpPlayerlistHandler = function(req, res) -- Sanity check if type(req.headers['x-txadmin-token']) ~= 'string' or len(req.headers['x-txadmin-token']) ~= 20 then return res.send(json.encode({error = 'token not found or invalid length'})) end local reqToken = req.headers['x-txadmin-token'] -- Perms check if not (debugModeEnabled and reqToken == 'xxxx_Debug_Token_xxx') then local allow = false for id, admin in pairs(ADMIN_DATA) do if reqToken == admin.token then allow = true break end end if not allow then return res.send(json.encode({error = 'no admin for the provided token'})) end end -- Sending response local reqEpoch = req.headers['x-txadmin-epoch'] if reqEpoch == tostring(epochTimestamp) and respCacheDiff then return res.send(respCacheDiff) else return res.send(respCacheEpoch) end end
-- Buff Lead 3 seablock.lib.substresult('anode-lead-smelting', 'slag', 'quartz', 1) seablock.lib.substingredient('anode-lead-smelting', 'liquid-hexafluorosilicic-acid', nil, 20) -- Compost void recipe angelsmods.functions.make_void('solid-compost', 'bio', 5) -- Remove recipe Wood pellets > Carbon dioxide -- Move recipe Charcoal > Carbon dioxide from Basic chemistry to Wood processing 2 bobmods.lib.tech.remove_recipe_unlock('bio-wood-processing-2', 'gas-carbon-dioxide-from-wood') seablock.lib.remove_recipe('gas-carbon-dioxide-from-wood') bobmods.lib.tech.remove_recipe_unlock('basic-chemistry', 'carbon-separation-2') bobmods.lib.tech.add_recipe_unlock('bio-wood-processing-2', 'sb-wood-bricks-charcoal') bobmods.lib.tech.add_recipe_unlock('bio-wood-processing-2', 'carbon-separation-2')
Librw = os.getenv("LIBRW") Librwgta = os.getenv("LIBRWGTA") workspace "rwio" configurations { "Release", "Debug" } platforms { "x86", "amd64" } location "build" system "Windows" filter { "platforms:x86" } architecture "x86" filter { "platforms:amd64" } architecture "x86_64" filter {} files { "src/*.*" } includedirs { Librw } includedirs { path.join(Librwgta, "src") } libdirs { path.join(Librw, "lib/win-%{cfg.platform}-null/%{cfg.buildcfg}") } libdirs { path.join(Librwgta, "lib/win-%{cfg.platform}-null/%{cfg.buildcfg}") } links { "rw", "rwgta" } links { "core", "geom", "gfx", "mesh", "maxutil", "maxscrpt", "bmm" } function maxplugin1(maxsdk) kind "SharedLib" language "C++" targetdir "lib/%{cfg.platform}/%{cfg.buildcfg}" targetextension ".dli" characterset ("MBCS") includedirs { path.join(maxsdk, "include") } filter { "platforms:amd64" } libdirs { path.join(maxsdk, "x64/lib") } buildoptions { "\"%40" .. maxsdk .. "ProjectSettings/AdditionalCompilerOptions64.txt\"" } filter { "platforms:x86" } libdirs { path.join(maxsdk, "lib") } buildoptions { "\"%40" .. maxsdk .. "ProjectSettings/AdditionalCompilerOptions.txt\"" } filter "configurations:Debug" defines { "DEBUG" } symbols "On" filter "configurations:Release" defines { "NDEBUG" } optimize "On" filter {} end function maxplugin2(maxsdk) kind "SharedLib" language "C++" targetdir "lib/%{cfg.platform}/%{cfg.buildcfg}" targetextension ".dli" characterset ("Unicode") removeplatforms { "x86" } includedirs { path.join(maxsdk, "include") } libdirs { path.join(maxsdk, "lib/x64/Release") } buildoptions { "/GR /we4706 /we4390 /we4557 /we4546 /we4545 /we4295 /we4310 /we4130 /we4611 /we4213 /we4121 /we4715 /w34701 /w34265 /wd4244 /wd4018 /wd4819" } filter "configurations:Debug" defines { "DEBUG" } symbols "On" filter "configurations:Release" defines { "NDEBUG" } optimize "On" filter {} end project "rwio2009" maxsdk = "C:/Users/aap/src/maxsdk/3ds Max 2009 SDK/maxsdk/" maxplugin1(maxsdk) project "rwio2010" maxsdk = "C:/Users/aap/src/maxsdk/3ds Max 2010 SDK/maxsdk/" maxplugin1(maxsdk) project "rwio2012" maxsdk = "C:/Program Files (x86)/Autodesk/3ds Max 2012/maxsdk/" maxplugin1(maxsdk) filter { "platforms:amd64" } debugdir "C:/Program Files/Autodesk/3ds Max 2012" debugcommand "C:/Program Files/Autodesk/3ds Max 2012/3dsmax.exe" postbuildcommands "copy /y \"$(TargetPath)\" \"C:\\Program Files\\Autodesk\\3ds Max 2012\\plugins\\\"" project "rwio2014" maxsdk = "C:/Users/aap/src/maxsdk/3ds Max 2014 SDK/maxsdk/" maxplugin2(maxsdk) project "rwio2015" maxsdk = "C:/Users/aap/src/maxsdk/3ds Max 2015 SDK/maxsdk/" maxplugin2(maxsdk) project "rwio2017" maxsdk = "C:/Users/aap/src/maxsdk/3ds Max 2017 SDK/maxsdk/" maxplugin2(maxsdk) project "rwio2018" maxsdk = "C:/Users/aap/src/maxsdk/3ds Max 2018 SDK/maxsdk/" maxplugin2(maxsdk)
require("plugins") require("opts") vim.cmd('colo one') require("setup") require("binds") require("lsp") -- Plugins require("plugins.compe") require("plugins.treesitter") require("plugins.lspsaga") -- LSP require("lsp.servers") require('hardline').setup {}
require("src/State") require("src/Util") require("src/Bind") require("src/Scene") require("src/Camera") require("src/AudioManager") require("src/FieldAnimator") require("src/Animator") require("src/AssetLoader") require("src/Asset") local M = def_module("STUBScene", { bind_table = nil, bind_group = nil, -- Singleton --[[ __initialized = false, instance = nil, impl = nil --]] }) M.data.bind_table = Bind.redefine_group(M.data.bind_table, { ["escape"] = { on_release = true, passthrough = false, handler = function(_, _, _, _) Event.quit() end }, }) -- class Impl M.Impl = class(M.Impl) function M.Impl:__init() -- TODO: INITIALIZE end function M.Impl:notify_pushed() -- TODO: PUSH-INIT end function M.Impl:notify_became_top() end function M.Impl:notify_popped() -- TODO: POP-DEINIT end function M.Impl:focus_changed(focused) if not State.pause_lock then Core.pause(not focused) end end function M.Impl:bind_gate(bind, ident, dt, kind) return not State.paused end function M.Impl:update(dt) if not State.paused then -- TODO: UPDATE THE THINGS end end function M.Impl:render() Camera.lock() -- TODO: RENDER ALL THE THINGS Camera.unlock() end -- STUBScene interface -- Instantiable set_functable(M, function(_, transparent) if not M.data.bind_group then M.data.bind_group = Bind.Group(M.data.bind_table) end return Scene(M.Impl(), M.data.bind_group, transparent) end ) -- Singleton --[[ function M.init(_) assert(not M.data.__initialized) if not M.data.bind_group then M.data.bind_group = Bind.Group(M.data.bind_table) end M.data.instance = Scene(M.Impl(), M.data.bind_group, false) M.data.impl = M.data.instance.impl M.data.__initialized = true return M.data.instance end function M.get_instance() return M.data.instance end --]] return M
local RunService = game:GetService("RunService") local MessagingService = game:GetService("MessagingService") local MockMessagingService = {} local topics = {} function MockMessagingService:PublishAsync(topicName, message) local topic = topics[topicName] if topic then topic:Fire( { Sent = tick(), Data = message } ) end end function MockMessagingService:SubscribeAsync(topicName, callback) local topic = topics[topicName] if not topic then topic = Instance.new("BindableEvent") topic.Parent = script topic.Name = topicName topics[topicName] = topic end return topic.Event:Connect(callback) end local service if RunService:IsStudio() then service = MockMessagingService else service = MessagingService end return service
game 'rdr3' fx_version 'adamant' rdr3_warning 'I acknowledge that this is a prerelease build of RedM, and I am aware my resources *will* become incompatible once RedM ships.' author 'szymczakovv#1937' client_script 'client.lua'
-- Natural Selection 2 Competitive Mod -- Source located at - https://github.com/xToken/CompMod -- lua\CompMod\Weapons\Marine\Shotgun\shared.lua -- - Dragon -- Recalc this Shotgun.kSpreadVectors = { GetNormalizedVector(Vector(-0.1, 0.1, kShotgunSpreadDistance)), GetNormalizedVector(Vector(0.1, -0.1, kShotgunSpreadDistance)), GetNormalizedVector(Vector(-0.15, 0, kShotgunSpreadDistance)), GetNormalizedVector(Vector(0.15, 0, kShotgunSpreadDistance)), GetNormalizedVector(Vector(0, -0.15, kShotgunSpreadDistance)), GetNormalizedVector(Vector(0, 0.15, kShotgunSpreadDistance)), GetNormalizedVector(Vector(-0.175, -0.175, kShotgunSpreadDistance)), GetNormalizedVector(Vector(-0.175, 0.175, kShotgunSpreadDistance)), GetNormalizedVector(Vector(0.175, 0.175, kShotgunSpreadDistance)), GetNormalizedVector(Vector(0.175, -0.175, kShotgunSpreadDistance)) } local kBulletSize = 0.016 local networkVars = { shotgun_upg1 = "boolean", shotgun_upg2 = "boolean", } local originalShotgunOnInitialized originalShotgunOnInitialized = Class_ReplaceMethod("Shotgun", "OnInitialized", function(self) originalShotgunOnInitialized(self) self.shotgun_upg1 = false self.shotgun_upg2 = false if Server then self:AddTimedCallback(Shotgun.OnTechOrResearchUpdated, 0.1) end end ) function Shotgun:OnTechOrResearchUpdated() if GetHasTech(self, kTechId.ShotgunUpgrade1) then self.shotgun_upg1 = true else self.shotgun_upg1 = false end if GetHasTech(self, kTechId.ShotgunUpgrade2) then self.shotgun_upg2 = true else self.shotgun_upg2 = false end end function Shotgun:GetUpgradeTier() if self.shotgun_upg2 then return kTechId.ShotgunUpgrade2, 2 elseif self.shotgun_upg1 then return kTechId.ShotgunUpgrade1, 1 end return kTechId.None, 0 end function Shotgun:GetCatalystSpeedBase() return self.shotgun_upg1 and kShotgunUpgradedReloadSpeed or 1 end function Shotgun:GetBulletDamage(player, endPoint) local distanceTo = (player:GetEyePos() - endPoint):GetLength() if distanceTo > kShotgunMaxRange then return 1 elseif distanceTo <= kShotgunDropOffStartRange then return kShotgunDamage else return kShotgunDamage * (1 - (distanceTo - kShotgunDropOffStartRange) / (kShotgunMaxRange - kShotgunDropOffStartRange)) end end function Shotgun:GetBaseAttackSpeed() return self.shotgun_upg2 and kShotgunUpgradedROF or kShotgunBaseROF end function Shotgun:FirePrimary(player) local viewAngles = player:GetViewAngles() viewAngles.roll = NetworkRandom() * math.pi * 2 local shootCoords = viewAngles:GetCoords() -- Filter ourself out of the trace so that we don't hit ourselves. local filter = EntityFilterTwo(player, self) local range = self:GetRange() local numberBullets = self:GetBulletsPerShot() local startPoint = player:GetEyePos() self:TriggerEffects("shotgun_attack_sound") self:TriggerEffects("shotgun_attack") for bullet = 1, math.min(numberBullets, #self.kSpreadVectors) do if not self.kSpreadVectors[bullet] then break end local spreadDirection = shootCoords:TransformVector(self.kSpreadVectors[bullet]) local endPoint = startPoint + spreadDirection * range --startPoint = player:GetEyePos() + shootCoords.xAxis * self.kSpreadVectors[bullet].x * self.kStartOffset + shootCoords.yAxis * self.kSpreadVectors[bullet].y * self.kStartOffset local targets, trace, hitPoints = GetBulletTargets(startPoint, endPoint, spreadDirection, kBulletSize, filter) HandleHitregAnalysis(player, startPoint, endPoint, trace) local direction = (trace.endPoint - startPoint):GetUnit() local hitOffset = direction * kHitEffectOffset local impactPoint = trace.endPoint - hitOffset local effectFrequency = self:GetTracerEffectFrequency() local showTracer = bullet % effectFrequency == 0 local numTargets = #targets if numTargets == 0 then self:ApplyBulletGameplayEffects(player, nil, impactPoint, direction, 0, trace.surface, showTracer) end if Client and showTracer then TriggerFirstPersonTracer(self, impactPoint) end for i = 1, numTargets do local target = targets[i] local hitPoint = hitPoints[i] local damage = self:GetBulletDamage(player, hitPoint) if Server then --Print(string.format("Pellet %s dealt %s damage to %s entity %sm away", bullet, damage, target:GetClassName(), (player:GetEyePos() - hitPoint):GetLength())) end self:ApplyBulletGameplayEffects(player, target, hitPoint - hitOffset, direction, damage, "", showTracer and i == numTargets) local client = Server and player:GetClient() or Client if not Shared.GetIsRunningPrediction() and client.hitRegEnabled then RegisterHitEvent(player, bullet, startPoint, trace, damage) end end end end Shared.LinkClassToMap("Shotgun", Shotgun.kMapName, networkVars)
local S = homedecor_i18n.gettext local longsofa_cbox = { type = "wallmounted", wall_side = {-0.5, -0.5, -0.5, 0.5, 0.5, 2.5}, } minetest.register_node("lrfurn:longsofa", { description = S("Long Sofa"), drawtype = "mesh", mesh = "lrfurn_sofa_long.obj", tiles = { "lrfurn_upholstery.png", { name = "lrfurn_sofa_bottom.png", color = 0xffffffff } }, paramtype = "light", paramtype2 = "colorwallmounted", palette = "unifieddyes_palette_colorwallmounted.png", inventory_image = "lrfurn_longsofa_inv.png", wield_scale = { x = 0.6, y = 0.6, z = 0.6 }, groups = {snappy=3, ud_param2_colorable = 1}, sounds = default.node_sound_wood_defaults(), selection_box = longsofa_cbox, node_box = longsofa_cbox, on_rotate = screwdriver.disallow, after_place_node = function(pos, placer, itemstack, pointed_thing) lrfurn.fix_sofa_rotation_nsew(pos, placer, itemstack, pointed_thing) unifieddyes.recolor_on_place(pos, placer, itemstack, pointed_thing) local playername = placer:get_player_name() if minetest.is_protected(pos, placer:get_player_name()) then return true end local fdir = minetest.dir_to_facedir(placer:get_look_dir(), false) if lrfurn.check_right(pos, fdir, true, placer) then if not creative.is_enabled_for(playername) then itemstack:take_item() end else minetest.chat_send_player(placer:get_player_name(), S("No room to place the sofa!")) minetest.set_node(pos, { name = "air" }) end return itemstack end, after_dig_node = unifieddyes.after_dig_node, on_rightclick = function(pos, node, clicker, itemstack, pointed_thing) if not clicker:is_player() then return itemstack end pos.y = pos.y-0.5 clicker:setpos(pos) clicker:set_hp(20) return itemstack end }) minetest.register_craft({ output = "lrfurn:longsofa", recipe = { {"wool:white", "wool:white", "wool:white", }, {"stairs:slab_wood", "stairs:slab_wood", "stairs:slab_wood", }, {"group:stick", "group:stick", "group:stick", } } }) minetest.register_craft({ output = "lrfurn:longsofa", recipe = { {"wool:white", "wool:white", "wool:white", }, {"moreblocks:slab_wood", "moreblocks:slab_wood", "moreblocks:slab_wood", }, {"group:stick", "group:stick", "group:stick", } } }) -- convert old static nodes to param2 colorization lrfurn.old_static_longsofas = {} for _, color in ipairs(lrfurn.colors) do table.insert(lrfurn.old_static_longsofas, "lrfurn:longsofa_"..color) end minetest.register_lbm({ name = "lrfurn:convert_longsofas", label = "Convert lrfurn long sofas to use param2 color", run_at_every_load = false, nodenames = lrfurn.old_static_longsofas, action = function(pos, node) local name = node.name local color = string.sub(name, string.find(name, "_")+1) if color == "red" then color = "medium_red" elseif color == "dark_green" then color = "medium_green" elseif color == "magenta" then color = "medium_magenta" elseif color == "cyan" then color = "medium_cyan" end local paletteidx, _ = unifieddyes.getpaletteidx("unifieddyes:"..color, "wallmounted") local old_fdir = math.floor(node.param2 % 32) local new_fdir = 3 if old_fdir == 0 then new_fdir = 3 elseif old_fdir == 1 then new_fdir = 4 elseif old_fdir == 2 then new_fdir = 2 elseif old_fdir == 3 then new_fdir = 5 end local param2 = paletteidx + new_fdir minetest.set_node(pos, { name = "lrfurn:longsofa", param2 = param2 }) local meta = minetest.get_meta(pos) meta:set_string("dye", "unifieddyes:"..color) end }) if minetest.settings:get("log_mods") then minetest.log("action", "[lrfurn/longsofas] "..S("Loaded!")) end
fx_version 'bodacious' game 'gta5' shared_scripts{ "config.lua" } client_scripts{ '@PolyZone/client.lua', '@PolyZone/BoxZone.lua', 'client.lua', "jobs/legal.lua", "jobs/zones.lua" }
workspace "Dodo" architecture "x64" startproject "Dodeditor" outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}" configurations { "Debug", "Release" } group "Dependencies" include "Dodo/lib/glad" include "Dodo/lib/imgui" include "Dodo/lib/assimp" group "" -- Go to root level project "Dodo" kind "StaticLib" location "Dodo" language "C++" cppdialect "C++17" staticruntime "on" characterset "MBCS" configuration "Debug" targetdir ("bin/Debug-%{cfg.architecture}/%{prj.name}/") objdir ("bin/Debug-%{cfg.architecture}/%{prj.name}/intermediates/") configuration "Release" targetdir ("bin/Release-%{cfg.architecture}/%{prj.name}/") objdir ("bin/Release-%{cfg.architecture}/%{prj.name}/intermediates/") configuration "*" pchheader "pch.h" pchsource "%{prj.name}/src/pch.cpp" files { "%{prj.name}/src/**.h", "%{prj.name}/src/**.cpp", "%{prj.name}/lib/stb_image/stb_image.h", "%{prj.name}/lib/stb_image/stb_image.cpp" } includedirs { "%{prj.name}/src", "%{prj.name}/lib/stb_image/" } sysincludedirs { "%{prj.name}/lib/spdlog/include", "%{prj.name}/lib/glad/include", "%{prj.name}/lib/imgui/include", "%{prj.name}/lib/assimp/include" } defines { "_CRT_SECURE_NO_WARNINGS" } links { "glad", "opengl32.lib", "imgui", "Assimp" } disablewarnings { "26812", "26451" } buildoptions { "/bigobj", "/Ob1" } filter "system:windows" systemversion "latest" defines { "DD_x64", "DD_API_WIN32" } filter "configurations:Debug" defines { "DD_DEBUG" } symbols "On" filter "configurations:Release" defines { "DD_RELEASE" } optimize "On" project "Sandbox" location "Sandbox" language "C++" cppdialect "C++17" staticruntime "On" characterset "MBCS" configuration "Debug" targetdir ("bin/Debug-%{cfg.architecture}/%{prj.name}/") objdir ("bin/Debug-%{cfg.architecture}/%{prj.name}/intermediates/") configuration "Release" targetdir ("bin/Release-%{cfg.architecture}/%{prj.name}/") objdir ("bin/Release-%{cfg.architecture}/%{prj.name}/intermediates/") configuration "*" files { "%{prj.name}/src/**.h", "%{prj.name}/src/**.cpp" } includedirs { "Dodo/src" } sysincludedirs { "Dodo/lib/spdlog/include", "Dodo/lib/glad/include", "Dodo/lib/imgui/include", "Dodo/lib/assimp/include" } links { "Dodo" } defines { "_CRT_SECURE_NO_WARNINGS" } filter "system:windows" systemversion "latest" defines { "DD_x64", "DD_API_WIN32" } filter "configurations:Debug" kind "ConsoleApp" defines { "DD_DEBUG" } symbols "On" filter "configurations:Release" -- entrypoint "mainCRTStartup" -- kind "WindowedApp" kind "ConsoleApp" defines { "DD_RELEASE" } optimize "On" project "Dodeditor" location "Dodeditor" language "C++" cppdialect "C++17" staticruntime "On" characterset "MBCS" configuration "Debug" targetdir ("bin/Debug-%{cfg.architecture}/%{prj.name}/") objdir ("bin/Debug-%{cfg.architecture}/%{prj.name}/intermediates/") configuration "Release" targetdir ("bin/Release-%{cfg.architecture}/%{prj.name}/") objdir ("bin/Release-%{cfg.architecture}/%{prj.name}/intermediates/") configuration "*" disablewarnings { "26812", "26451" } files { "%{prj.name}/src/**.h", "%{prj.name}/src/**.cpp", "%{prj.name}/res/**.*" } includedirs { "Dodo/src" } sysincludedirs { "Dodo/lib/spdlog/include", "Dodo/lib/glad/include", "Dodo/lib/imgui/include", "Dodo/lib/assimp/include" } links { "Dodo" } defines { "_CRT_SECURE_NO_WARNINGS" } filter "system:windows" systemversion "latest" defines { "DD_x64", "DD_API_WIN32" } filter "configurations:Debug" kind "ConsoleApp" defines { "DD_DEBUG" } symbols "On" filter "configurations:Release" -- entrypoint "mainCRTStartup" -- kind "WindowedApp" kind "ConsoleApp" defines { "DD_RELEASE" } optimize "On"
--[[ Copyright (c) 2014, Hardcrawler Games LLC This library is free software; you can redistribute it and/or modify it under the terms of the MIT license. See LICENSE for details. I haven't actually read the MIT license. I think it's permissive and stuff. Send me a keg of Newcastle beer if this makes you rich. usage: local Spriter = require("libs/Spriter") --Animation filename assumed to be animationDirectory/animationDirectory.scon local spriterData = Spriter:loadSpriter("./", "animationDirectory") Note: loadSpriter is primary entry point to class. --]] --Spriter files are "scml" (xml) or "scon" (json). We will use the dkjson library to load json "scon" files local json = require("modules/libs/dkjson") local Spriter = {} ---------------------------------------------------------------------------- --Skip this block. It's just for debugging --printTable For debugging of data structure: --Table print that won't recurse into self-referential keys --Based on naming convention prefix "cyc" to denote cyclic ---------------------------------------------------------------------------- local function printf(fmt, ...) return print(string.format(fmt, ...)) end --Note, I got this printTable off of a programming forum, but can't remember where --I customized with "cyc" exception local function printTable(table, indent) indent = indent or 4; if indent > 16 then printf("%s ...(maxdepth)", string.rep(' ', indent)); return end local keys = {}; print(string.rep(' ', indent)..'{'); indent = indent + 1; for k, v in pairs(table) do local key = k; if (type(key) == 'string') then if not (string.match(key, '^[A-Za-z_][0-9A-Za-z_]*$')) then key = "['"..key.."']"; end elseif (type(key) == 'number') then key = "["..key.."]"; end if (type(v) == 'table') then if (next(v)) then printf("%s%s =", string.rep(' ', indent), tostring(key)); if string.find(key, "cyc") then local id = "(nil)" if v.id then id = v.id end if v.name then id = v.name end printf("%s(cyclic reference id: '" .. id .. "')", string.rep(' ', indent+1)) else printTable(v, indent); end else printf("%s%s = {},", string.rep(' ', indent), tostring(key)); end elseif (type(v) == 'string') then printf("%s%s = %s,", string.rep(' ', indent), tostring(key), "'"..v.."'"); else printf("%s%s = %s,", string.rep(' ', indent), tostring(key), tostring(v)); end end indent = indent - 1; print(string.rep(' ', indent)..'}'); end --printTable --So main can use it Spriter.printTable = printTable --End of Skip this block. ---------------------------------------------------------------------------- function Spriter:loadTexturePackerData( filename ) --For renderer to know how to render self.usingTexturePacker = true --Load and decode texturepacker json data local contents, size = love.filesystem.read( filename ) assert(size, "Error loading file " .. filename) local tpData, pos, err = json.decode(contents, 1, nil) assert( not err, "Parse error!") self.textureAtlas = {} --We are calling info about each texture stored in the texturepacker sheet "tiles" self.textureAtlas.tiles = {} --Load actual image local textureFilename = self.path .. "/" .. tpData.meta.image self.textureAtlas.texture = love.graphics.newImage( textureFilename ) assert(self.textureAtlas.texture, "File " .. textureFilename .. " not found") --Initialize spriteBatch for efficient rendering. Could just render rects, but sprite batches are faster --Should probably compute some sort of sensible value for max sprites...maybe optionally pass it in? self.spriteBatch = love.graphics.newSpriteBatch( self.textureAtlas.texture, 300, "stream" ) local imageWidth = self.textureAtlas.texture:getWidth() local imageHeight = self.textureAtlas.texture:getHeight() --Build love quads from info in parsed json for filename, data in pairs(tpData.frames) do local tile = {} tile.filename = filename tile.quad = love.graphics.newQuad(data.frame.x, data.frame.y, data.frame.w, data.frame.h, imageWidth, imageHeight ) local x, y, w, h = tile.quad:getViewport() tile.w = w tile.h = h --[[ --NOTE: Currently NOT HANDLING trimmed source images!!! tile.xOffset = -(data.sourceSize.w - data.frame.w) tile.yOffset = -(data.sourceSize.h - data.frame.h) --]] self.textureAtlas.tiles[filename] = tile self.filenameLookup[filename] = tile end --Update spriterData file data to reference the tiles we have created for i = 1, # self.folder do local files = self.folder[i].file for j = 1, # files do local file = files[j] local tileName = file.name local tile = self.textureAtlas.tiles[tileName] assert(tile, "Unable to find tile " .. tostring(tileName)) file.tile = tile end end end --loadTexturePackerData --Dig through data structure, ensure files exist, load images, and store references within data structure function Spriter:loadFilesAndFolders() --Creating a quick reference for retrieving file entries based on filename --Not 100% sure there isn't an easy way to do it already, but I don't see one self.filenameLookup = {} --By convention, we assume that a .json file that matches the directory name is --The output of TexturePacker Spriter export. If the file exists, load texturepacker atlas --Instead of the individual images local jsonFilename = self.path .. "/" .. self.baseName .. ".json" if love.filesystem.isFile( jsonFilename ) then return self:loadTexturePackerData( jsonFilename ) end for i = 1, # self.folder do local files = self.folder[i].file for j = 1, # files do local file = files[j] --Parse out filename without path and store it local dir, filename, extension = string.match(file.name, "(.-)([^/]-([^%.]+))$") file.filename = filename --Store LOVE image reference in image object local image = love.graphics.newImage( self.path .. "/" .. file.name) assert(image, "nil image!") file.image = image self.filenameLookup[file.name] = file end end return files, folders end --loadFilesAndFolders --Recurse through data structure and add 1 to all c-style 0-indexed references so they are Lua-style 1-indexed tables function Spriter:updateIds( spriterData ) for k, v in pairs( spriterData ) do if k == "id" or k == "parent" or k == "obj" or k == "file" or k == "folder" or k == "key" or k == "timeline" then --After B10 download, timelineID started getting exported as a string, --so I added the if-string-and-can-be-cast if type(v) == "number" or (type(v) == "string" and tonumber(v)) then spriterData[k] = v + 1 end end if type(v) == "table" then self:updateIds( v ) end end end --updateIds --Recurse through data structure and convert all angles from degrees to radians --Who uses degrees these days? Sheesh. Actually, I prefer degrees. But math libraries don't. Sad face. function Spriter:anglesToRadians( spriterData ) for k, v in pairs( spriterData ) do if k == "angle" then if type(v) == "number" then spriterData[k] = (spriterData[k] * 0.0174532925) end end if type(v) == "table" then self:anglesToRadians( v ) end end end --updateIds --Create "next" references in mainline keys so we can easily access the next key from the data structure function Spriter:createKeyReferences() for animationIndex = 1, # self.entity[1].animation do local animation = self.entity[1].animation[animationIndex] local keys = animation.mainline.key for keyIndex = 1, # keys do local key = keys[keyIndex] --Last mainline's "next" keyframe is the first frame if keyIndex == # keys then key.cycNextKey = keys[ 1 ] else key.cycNextKey = keys[ keyIndex + 1 ] end end end end --createKeyReferences --Map timeline/key reference pairs within data structure to actual object references function Spriter:updateTimelineReferences() --I believe that the only timeline references are in the mainlines of the animations --NOTE: hard-coding for 1 entity for i = 1, # self.entity[1].animation do local animation = self.entity[1].animation[i] assert(animation, "nil animation on index " .. i) local mainline = animation.mainline assert(animation.mainline, "nil mainline on animation " .. i) for keyIndex = 1, # mainline.key do local key = mainline.key[keyIndex] assert(key, "Key " .. tostring(keyIndex) .. " not found") for boneRefIndex = 1, # key.bone_ref do local boneRef = key.bone_ref[boneRefIndex] assert(boneRef, "Key " .. tostring(keyIndex) .. " boneRef " .. tostring(boneRefIndex) .. " has no boneref") boneRef.cycKey, boneRef.boneName = self:getTimelineKeyById( i, boneRef.timeline, boneRef.key ) boneRef.cycBone = self:getBoneByName( boneRef.boneName ) --Copy values so we don't have to dig into the key during animation boneRef.scale_x = boneRef.cycKey.bone.scale_x boneRef.scale_y = boneRef.cycKey.bone.scale_y boneRef.angle = boneRef.cycKey.bone.angle boneRef.x = boneRef.cycKey.bone.x boneRef.y = boneRef.cycKey.bone.y end for objectRefIndex = 1, # key.object_ref do local objectRef = key.object_ref[objectRefIndex] assert(objectRef, "Key " .. tostring(keyIndex) .. " objectRef " .. tostring(objectRefIndex) .. " has no objectref") objectRef.cycKey = self:getTimelineKeyById( i, objectRef.timeline, objectRef.key ) assert(objectRef.cycKey, "objectRef " .. tostring(objectRefIndex) .. " has no key") --Copy values so we don't have to dig into the key during animation objectRef.scale_x = objectRef.cycKey.object.scale_x objectRef.scale_y = objectRef.cycKey.object.scale_y objectRef.x = objectRef.cycKey.object.x objectRef.y = objectRef.cycKey.object.y objectRef.angle = objectRef.cycKey.object.angle end end end end --updateTimelineReferences --Map parent references to actual data structure references --Note: according to Spriter forum, ALL parent references are indices into object_ref --Huzzah for documentation! function Spriter:updateParentReferences() --I believe that the only parent references are in the mainlines of the animations to bone_ref objects --NOTE: hard-coding for 1 entity for i = 1, # self.entity[1].animation do local animation = self.entity[1].animation[i] assert(animation, "nil animation on index " .. i) local mainline = animation.mainline assert(animation.mainline, "nil mainline on animation " .. i) for keyIndex = 1, # mainline.key do local key = mainline.key[keyIndex] assert(key, "Key " .. tostring(keyIndex) .. " not found") for boneRefIndex = 1, # key.bone_ref do local boneRef = key.bone_ref[boneRefIndex] assert(boneRef, "Key " .. tostring(keyIndex) .. " boneRef " .. tostring(boneRefIndex) .. " has no boneref") if boneRef.parent then boneRef.cycParentBoneRef = self:getBoneRefById( i, keyIndex, boneRef.parent ) end end for objectRefIndex = 1, # key.object_ref do local objectRef = key.object_ref[objectRefIndex] assert(objectRef, "Key " .. tostring(keyIndex) .. " objectRef " .. tostring(objectRefIndex) .. " has no objectref") if objectRef.parent then objectRef.cycParentBoneRef = self:getBoneRefById( i, keyIndex, objectRef.parent ) end end end end end --updateParentReferences --Map file id references to data structure references for the actual file data --I made this recursive to match all possible cases, but in retrospect, it looks like only timeline keys have images. function Spriter:updateFileReferences( node ) node = node or self if node.file and node.folder then node.cycFile = self:getFileById( node.folder, node.file ) end for k, v in pairs( node ) do if type(v) == "table" then self:updateFileReferences( v ) end end end --updateFileReferences --Get folder by index. Die if invalid folder index --I am assuming that the folder index in the lua array *should* be the same as its id --Note: **I make this assumption globally throughout this parser** function Spriter:getFolderByIndex( index ) local folder = self.folder[index] assert(folder) return folder end --Read the name of the function. This and then next several "get" methods basically dig --Through the data structure for what you're looking for and die if they can't find it function Spriter:getTimelineById( animationID, timelineID ) assert(animationID, "animationID has no value") assert(timelineID, "timelineID has no value") --NOTE: hard-coding for 1 entity local animation = self.entity[1].animation[animationID] assert(animation, "Animation " .. tostring(animationID) .. " not found") local timeline = animation.timeline[timelineID] assert(timeline, "Timeline " .. tostring(timelineID) .. " not found") return timeline end --See comments above function Spriter:getTimelineKeyById( animationID, timelineID, keyID ) assert(animationID, "animationID has no value") assert(timelineID, "timelineID has no value") --NOTE: hard-coding for 1 entity local animation = self.entity[1].animation[animationID] assert(animation, "Animation " .. tostring(animationID) .. " not found") --After B10 download, timelineID started getting exported as a string, so I'm casting it local timeline = animation.timeline[tonumber(timelineID)] assert(timeline, "Timeline " .. tostring(timelineID) .. " not found") local key = timeline.key[keyID] assert(key, "Key " .. tostring(keyID) .. " not found") return key, timeline.name end --The timelines refer to bones by name, which doesn't quite match the paradigm of id/index, so --We provide this helper function to grab bones by name function Spriter:getBoneByName( boneName ) local obj_info = self.entity[1].obj_info for i = 1, # obj_info do if obj_info[i].type == "bone" and obj_info[i].name == boneName then return obj_info[i] end end assert(false, "Bone '" .. tostring(boneName) .. "' not found") end --See comments above function Spriter:getBoneRefById( animationID, keyID, boneRefID ) assert(animationID, "animationID has no value") assert(keyID, "animationID has no value") assert(boneRefID, "boneRefID has no value") --NOTE: hard-coding for 1 entity local animation = self.entity[1].animation[animationID] assert(animation, "Animation " .. tostring(animationID) .. " not found") local mainline = animation.mainline; assert(mainline, "Mainline not found") local key = mainline.key[keyID]; assert(key, "Key " .. tostring(keyID) .. " not found") local boneRef = key.bone_ref[boneRefID] return boneRef end --See comments above function Spriter:getFileById( folderID, fileID ) local folder = self.folder[folderID] assert(folder, "Folder " .. tostring(folderID) .. " not found") local file = folder.file[fileID] assert(file, "File " .. tostring(fileID) .. " not found") return file end --The actual user code will most likely (sanely) use animation names rather than indices into the array --This method is for them function Spriter:getAnimationByName( animationName ) for i = 1, # self.entity[1].animation do local animation = self.entity[1].animation[i] if animation.name == animationName then return animation end end assert(false, "Unable to find animation '" .. tostring(animationName) .. "'") end --animationName --Apply all timeline transformations to heirarchy - no need to compute every frame --NOTE: this method is deprecated. My previous approach was incorrect. I'm leaving this here temporarily in case I need to reference it function Spriter:applyTransformations() for animationIndex = 1, # self.entity[1].animation do local animation = self.entity[1].animation[animationIndex] assert(animation, "Animation " .. tostring(animationIndex) .. " not found") local timeline = animation.timeline assert(timeline, "Animation timeline " .. tostring(animationName) .. " not found") local mainline = animation.mainline assert(mainline, "Animation mainline " .. tostring(animationName) .. " not found") for keyIndex = 1, # mainline.key do local key = mainline.key[keyIndex] assert(key, "Animation key[1] " .. tostring(keyIndex) .. " not found") --Apply all transformations through bone_ref heirarchy for boneRefIndex = 1, # key.bone_ref do local boneRef = key.bone_ref[boneRefIndex] --Create "blank" transformations to avoid Lua complaining about adding etc. nil values boneRef.x = boneRef.x or 0 boneRef.y = boneRef.y or 0 boneRef.angle = boneRef.angle or 0 boneRef.scale_x = boneRef.scale_x or 1 boneRef.scale_y = boneRef.scale_y or 1 local parent = boneRef.cycParentBoneRef if parent then --Multiply our scale by parent's scale boneRef.scale_x = boneRef.scale_x * parent.scale_x boneRef.scale_y = boneRef.scale_y * parent.scale_y --Add our rotation to parent's rotation boneRef.angle = boneRef.angle + parent.angle --Our position gets multiplied by *parent* scale boneRef.x = boneRef.x * parent.scale_x boneRef.y = boneRef.y * parent.scale_y --Translate our x, y by parent's translation boneRef.x = boneRef.x + parent.x boneRef.y = boneRef.y + parent.y --Now rotate our x, y by our parents rotation *around its x,y* boneRef.x, boneRef.y = self:rotatePoint( boneRef.x, boneRef.y, parent.angle, parent.x, parent.y ) else --We still need scale unparented objects boneRef.x = boneRef.x * boneRef.scale_x boneRef.y = boneRef.y * boneRef.scale_y end end --for through bone_ref --Apply all transformations through object_ref heirarchy for objectRefIndex = 1, # key.object_ref do local objectRef = key.object_ref[objectRefIndex] --Create "blank" transformations to avoid Lua complaining about adding etc. nil values objectRef.x = objectRef.x or 0 objectRef.y = objectRef.y or 0 objectRef.angle = objectRef.angle or 0 objectRef.scale_x = objectRef.scale_x or 1 objectRef.scale_y = objectRef.scale_y or 1 local parent = objectRef.cycParentBoneRef if parent then local filename = objectRef.cycKey.object.cycFile.name --Multiply our scale by parent's scale objectRef.scale_x = objectRef.scale_x * parent.scale_x objectRef.scale_y = objectRef.scale_y * parent.scale_y --Add our rotation to parent's rotation objectRef.angle = objectRef.angle + parent.angle --Our position gets multiplied by *parent* scale objectRef.x = objectRef.x * parent.scale_x objectRef.y = objectRef.y * parent.scale_y --Translate our x, y by parent's translation objectRef.x = objectRef.x + parent.x objectRef.y = objectRef.y + parent.y --Now rotate our x, y by our parents rotation *around its x,y* objectRef.x, objectRef.y = self:rotatePoint( objectRef.x, objectRef.y, parent.angle, parent.x, parent.y ) else --We still need scale unparented objects objectRef.x = objectRef.x * objectRef.scale_x objectRef.y = objectRef.y * objectRef.scale_y end end --for through object_ref end --for through mainline keys end --for through animatins end --Helper function: rotate point px, py around center cx,cy. If cx, cy not passed, rotate around origin --FUNCTION EXPECTS RADIANS function Spriter:rotatePoint( px, py, angle, cx, cy ) cx = cx or 0 cy = cy or 0 local s = math.sin(angle) local c = math.cos(angle) px = px - cx; py = py - cy; local xnew = (px * c) - (py * s) local ynew = (px * s) + (py * c) --translate point back: px = xnew + cx; py = ynew + cy; --To avoid crazy scientific notation prints during debugging local function round(num, idp) local mult = 10^(idp or 2) return math.floor(num * mult + 0.5) / mult end px = round(px,5) py = round(py,5) return px, py end --rotatePoint --For debugging - distance between two points function Spriter:pointDistance( x1, y1, x2, y2 ) local xd = x2-x1 local yd = y2-y1 local distance = math.sqrt(xd*xd + yd*yd) return distance end --Created this because the inTransition variable couldn't be used (was false while still in transition). -- I don't remember its internal logic, so I created a method for callers to use. I can refactor it later if necessary function Spriter:isInTransition() if self.transitions and #self.transitions > 0 then return true end return false end --Set the animation referenced by animationName as the current animation --Die is animationName is not a valid animation. function Spriter:setCurrentAnimationName( animationName, animationType, inTransition ) --Unless this animation change was initiated by a transition, override any existing transitions if not self.inTransition then self.transitions = {} end self:setTime( 0 ) self.looped = nil --Used for emitting key changes self.currentKeyIndex = nil self.stopped = nil self.animationType = animationType or "looping" local animation = self:getAnimationByName( animationName ) assert(animation, "Animation " .. tostring(animationName) .. " not found") self.animationName = animationName end function Spriter:getCurrentAnimationName() return self.animationName end function Spriter:setInterpolation( interpolation ) self.interpolation = interpolation end function Spriter:getInterpolation() return self.interpolation end function Spriter:start() self.stopped = nil end function Spriter:stop() self.stopped = true end --Get a reference to the current animation function Spriter:getCurrentAnimation() local animationName = self.animationName assert(animationName, "nil animationName") local animation = self:getAnimationByName( animationName ) assert(animation, "Animation " .. tostring(animationName) .. " not found") return animation end --Get a reference to the current mainline key, chosed based on dt updates and current animation value function Spriter:getCurrentMainlineKey() local animation = self:getCurrentAnimation() local time = self:getTime() local milliseconds = time * 1000 local mainline = animation.mainline assert(mainline, "Animation mainline not found") local currentKey = mainline.key[1] local currentKeyIndex = 1 for keyIndex = 1, # mainline.key do local key = mainline.key[keyIndex] if key.time then if milliseconds > key.time then currentKey = key currentKeyIndex = keyIndex end end end if not self.currentKeyIndex or currentKeyIndex ~= self.currentKeyIndex then self.currentKeyIndex = currentKeyIndex self:keyChanged( currentKeyIndex ) end return currentKey, currentKeyIndex end --Rescale time elapsed vs duration to min1, max1 (x, y angle, or whatever) local function rescale( val, min0, max0, min1, max1 ) return (((val - min0) / (max0 - min0)) * (max1 - min1)) + min1 end --Given a bone at position x,y pointing at angle angle with length length, return the x, y of the other end of the bone function Spriter:getBoneEndpoint( x, y, angle, length ) local x2, y2 = x, y --By convention, bone is a ray of length cycBone.w pointed in direction boneRef.angle local length = length --Rotate a ray centered at origin on the x axies to be a ray that points at the specified angle local x2, y2 = self:rotatePoint( length, 0, angle, 0, 0 ) --Translate this ray by the bone position x2 = x2 + x y2 = y2 + y return x2, y2 end --getBoneEndpoint --Special interpolation function for angles. Need to be smart enough to "loop" around the 0 degree mark to --Find nearby angles rather than take the long way around. i.e. rotating from 10 degrees to 350 degrees should --Go DOWN from 10 to 0, then down 360 to 350. NOT a linear interpolation from 10 and increasing to 350 --Based on http://stackoverflow.com/questions/2708476/rotation-interpolation local function lerpAngle( a1, a2, amount ) local radians360 = 6.28318531 local radians180 = 3.14159265 local degree = 0.0174532925 local difference = math.abs(a2 - a1); if difference > radians180 then -- We need to add on to one of the values. if a2 > a1 then --We'll add it on to start... a1 = a1 + radians360 else --Add it on to end. a2 = a2 + radians360; end end --Interpolate it. local value = (a1 + ((a2 - a1) * amount)); --Wrap it.. local rangeZero = radians360 if value >= 0 and value <= radians360 then return value end return value % rangeZero end --lerpAngle --object_ref indices are not necessarily consistent among keyframes. Nor are the images that the "actual" --object references (they can be swapped out). The only reliable way I was able to see if two object refs on --Separate keyframes were the same "object" was to compare the timeline value. id is just its position in the array, so it's useless local function getNextObjectRef( objectRef, objectRefIndex, nextKey ) if nextKey.object_ref[objectRefIndex] then if objectRef.timeline == nextKey.object_ref[objectRefIndex].timeline then return nextKey.object_ref[objectRefIndex] end end for i = 1, #nextKey.object_ref do if objectRef.timeline == nextKey.object_ref[i].timeline then return nextKey.object_ref[i] end end return nil end --getNextObjectRef --Build one frame of data that is the current "state" of the rig, with interpolation behaviors --Defined for the next timeline key function Spriter:buildFrameData() local animation = self:getCurrentAnimation() local timeline = animation.timeline assert(timeline, "Animation timeline " .. tostring(animationName) .. " not found") local mainline = animation.mainline assert(mainline, "Animation mainline " .. tostring(animationName) .. " not found") local key, keyIndex = self:getCurrentMainlineKey() assert(key, "Animation key[1] " .. tostring(animationName) .. " not found") --Alias time because we (stupidly) override the key reference with a local below local currentKeyTime = key.time local nextKey = key.cycNextKey assert(nextKey, "Unable to load nextKey") local frameData = {} --Loop for bone ref frames (images) for boneRefIndex = 1, # key.bone_ref do local boneRef = key.bone_ref[boneRefIndex] local key = boneRef.cycKey local boneData = { dataType = "bone", x = boneRef.x or 0, y = boneRef.y or 0, boneLength = boneRef.cycBone.w or 0, scale_x = boneRef.scale_x or 1, scale_y = boneRef.scale_y or 1, angle = boneRef.angle or 0, } --Note -- we are not creating a frame if the bone_ref on the next key is null. This might be premature? --Should we create a "static" frame? if nextKey.bone_ref[boneRefIndex] then local xNext = nextKey.bone_ref[boneRefIndex].x or 0 local yNext = nextKey.bone_ref[boneRefIndex].y or 0 local angleNext = nextKey.bone_ref[boneRefIndex].angle or 0 local currentSpin = boneRef.cycKey.spin if not currentSpin then currentSpin = 0 end assert(xNext and yNext and angleNext, "nil next key value") local angle1, angle2 = boneData.angle, angleNext local nextTime = nextKey.time local duration if currentKeyTime and nextTime then --If both keys have time, duration is distance between keys duration = nextTime - currentKeyTime elseif not currentKeyTime and nextTime then --If current key does not have a time, it's first, duration is next key's time duration = nextTime elseif currentKeyTime and not nextTime then --If next key does not have a time, we're looping. Duration is total anim length minus current key's start time duration = animation.length - currentKeyTime else print(tostring(currentKeyTime) .. ", " .. tostring(nextTime)) assert(false, "Neither key has a time. This should not happen") end assert(duration, "Invalid duration value") --Key time is milliseconds, interpolation expects seconds duration = duration / 1000 boneData.angleStart = boneData.angle boneData.xStart = boneData.x boneData.yStart = boneData.y boneData.xNext = xNext boneData.yNext = yNext boneData.angleNext = angleNext boneData.duration = duration local elapsed = self:getTime() if currentKeyTime then elapsed = elapsed - (currentKeyTime/1000) end boneData.x = rescale( elapsed, 0, boneData.duration, boneData.xStart, boneData.xNext ) boneData.y = rescale( elapsed, 0, boneData.duration, boneData.yStart, boneData.yNext ) local angleAmount = rescale( elapsed, 0, boneData.duration, 0, 1 ) boneData.angle = lerpAngle( boneData.angleStart, boneData.angleNext, angleAmount ) --Interpolation behavior --[[ local that = self boneData.update = function(self, dt) self.elapsed = self.elapsed + dt self.x = rescale( self.elapsed, 0, self.duration, self.xStart, self.xNext ) self.y = rescale( self.elapsed, 0, self.duration, self.yStart, self.yNext ) local angleAmount = rescale( self.elapsed, 0, self.duration, 0, 1 ) self.angle = lerpAngle( self.angleStart, self.angleNext, angleAmount ) local x2, y2 = that:getBoneEndpoint( self.x, self.y, self.angle, self.scale_x * self.boneLength, self.angle ) self.x2 = x2 self.y2 = y2 end --]] end --if next one has data frameData[ # frameData + 1 ] = boneData local parent = frameData[ boneRef.parent ] if parent then --Multiply our scale by parent's scale boneData.scale_x = boneData.scale_x * parent.scale_x boneData.scale_y = boneData.scale_y * parent.scale_y --Add our rotation to parent's rotation boneData.angle = boneData.angle + parent.angle --Our position gets multiplied by *parent* scale boneData.x = boneData.x * parent.scale_x boneData.y = boneData.y * parent.scale_y --Translate our x, y by parent's translation boneData.x = boneData.x + parent.x boneData.y = boneData.y + parent.y --Now rotate our x, y by our parents rotation *around its x,y* boneData.x, boneData.y = self:rotatePoint( boneData.x, boneData.y, parent.angle, parent.x, parent.y ) else --We still need scale unparented objects boneData.x = boneData.x * boneData.scale_x boneData.y = boneData.y * boneData.scale_y end local x2, y2 = self:getBoneEndpoint( boneData.x, boneData.y, boneData.angle, boneData.scale_x * boneData.boneLength, boneData.angle ) boneData.x2 = x2 boneData.y2 = y2 end --for --Loop for object ref frames (images) for objectRefIndex = 1, # key.object_ref do local objectRef = key.object_ref[objectRefIndex] local key = objectRef.cycKey local object = key.object local file = object.cycFile local altFile = self:getSwappedImage( file.name ) local image = altFile.image --Love2D image handle --Optionally, images can pivot rotations from a non-standard point (default is bottom right corner {top right in Love coords}) local pivotX, pivotY if object.pivot_x then pivotX = object.pivot_x else pivotX = file.pivot_x end if object.pivot_y then pivotY = object.pivot_y else pivotY = file.pivot_y end local imageData = { dataType = "image", image = image, tile = file.tile, --Texturepacker load specific x = objectRef.x or 0, y = objectRef.y or 0, pivotX = pivotX, pivotY = pivotY, scale_x = objectRef.scale_x or 1, scale_y = objectRef.scale_y or 1, angle = objectRef.angle or 0, } local parent = frameData[ objectRef.parent ] if parent then local filename = objectRef.cycKey.object.cycFile.name --Multiply our scale by parent's scale imageData.scale_x = imageData.scale_x * parent.scale_x imageData.scale_y = imageData.scale_y * parent.scale_y --Add our rotation to parent's rotation imageData.angle = imageData.angle + parent.angle --Our position gets multiplied by *parent* scale imageData.x = imageData.x * parent.scale_x imageData.y = imageData.y * parent.scale_y --Translate our x, y by parent's translation imageData.x = imageData.x + parent.x imageData.y = imageData.y + parent.y --Now rotate our x, y by our parents rotation *around its x,y* imageData.x, imageData.y = self:rotatePoint( imageData.x, imageData.y, parent.angle, parent.x, parent.y ) else --We still need scale unparented objects imageData.x = imageData.x * imageData.scale_x imageData.y = imageData.y * imageData.scale_y end local nextObjectRef = getNextObjectRef( objectRef, objectRefIndex, nextKey ) --If there is no keyframe for us in the next key, do no interpolation if not nextObjectRef then nextObjectRef = { x = objectRef.x, y = objectRef.y, angle = objectRef.angle, } else --print(objectRef.timeline .. " - " .. nextObjectRef.timeline) end --Note -- we are not creating a frame if the object_ref on the next key is null. This might be premature? --Should we create a "static" frame? local xNext = nextObjectRef.x or 0 local yNext = nextObjectRef.y or 0 local angleNext = nextObjectRef.angle or 0 local currentSpin = objectRef.cycKey.spin if not currentSpin then currentSpin = 0 end assert(xNext and yNext and angleNext, "nil next key value") local angle1, angle2 = imageData.angle, angleNext local nextTime = nextKey.time local duration if currentKeyTime and nextTime then --If both keys have time, duration is distance between keys duration = nextTime - currentKeyTime elseif not currentKeyTime and nextTime then --If current key does not have a time, it's first, duration is next key's time duration = nextTime elseif currentKeyTime and not nextTime then --If next key does not have a time, we're looping. Duration is total anim length minus current key's start time duration = animation.length - currentKeyTime else print(tostring(currentKeyTime) .. ", " .. tostring(nextTime)) assert(false, "Neither key has a time. This should not happen") end assert(duration, "Invalid duration value") --Key time is milliseconds, interpolation expects seconds duration = duration / 1000 imageData.angleStart = imageData.angle imageData.xStart = imageData.x imageData.yStart = imageData.y imageData.xNext = xNext imageData.yNext = yNext imageData.angleNext = angleNext imageData.elapsed = 0 imageData.duration = duration --Interpolation behavior --[[ imageData.update = function(self, dt) self.elapsed = self.elapsed + dt self.x = rescale( self.elapsed, 0, self.duration, self.xStart, self.xNext ) self.y = rescale( self.elapsed, 0, self.duration, self.yStart, self.yNext ) local angleAmount = rescale( self.elapsed, 0, self.duration, 0, 1 ) self.angle = lerpAngle( self.angleStart, self.angleNext, angleAmount ) end --]] frameData[ # frameData + 1 ] = imageData end --for return frameData end --buildFrameData --Get current frame data, or build it if it does not exist function Spriter:getFrameData() if self.stopped and self.lastFrameData then return self.lastFrameData end local animation = self:getCurrentAnimation() local timeline = animation.timeline assert(timeline, "Animation timeline " .. tostring(animationName) .. " not found") local mainline = animation.mainline assert(mainline, "Animation mainline " .. tostring(animationName) .. " not found") local key = self:getCurrentMainlineKey() assert(key, "Animation key[1] " .. tostring(animationName) .. " not found") local frameData = self.currentFrameData --[[ --Rebuild frameData when our mainline key changes, or when one does not exist if not self.currentFrameData or (self.currentMainlineKey and self.currentMainlineKey ~= key) then frameData = self:buildFrameData() self.currentMainlineKey = key self.currentFrameData = frameData end --]] frameData = self:buildFrameData() self.lastFrameData = frameData return frameData end --getFrameData function Spriter:getTime() if not self.time then self.time = 0 end return self.time end function Spriter:setTime( time ) self.time = time end --Push a transition onto the stack (first in, first out) --Transitions are animations that we wish to switch to after the current animation finishes function Spriter:pushTransition( transition ) self.transitions[ # self.transitions + 1 ] = transition end function Spriter:updateTransition() if # self.transitions > 0 then local transition = self.transitions[1] --Transitions can allow a certain number of loops before switching if transition.loopCount and transition.loopCount > 0 then transition.loopCount = transition.loopCount - 1 else table.remove( self.transitions, 1 ) local animationType = "loop" local inTransition = true self:setCurrentAnimationName( transition.animationName, animationType, inTransition ) end end end --Do nothing by default - intended for "inheriting" class to react function Spriter:animationLooped() self:updateTransition() end --Do nothing by default - intended for "inheriting" class to react function Spriter:animationStopped() self:updateTransition() end --Do nothing by default - intended for "inheriting" class to react function Spriter:animationStarted() end --Do nothing by default - intended for "inheriting" class to react function Spriter:keyChanged( keyIndex ) end --Add delta time to the current time tracking. Figure out if our animation stopped or looped and notify listeners function Spriter:incrementTime( dt ) local time = self:getTime() if time == 0 then self:animationStarted() elseif self.looped then self.looped = nil self:animationStarted() end time = time + dt local animation = self:getCurrentAnimation() local animationName = self:getCurrentAnimationName() local milliseconds = time * 1000 if milliseconds > animation.length then local remainder = milliseconds % animation.length time = remainder / 1000 --Force a rebuild of frame data - avoid "infinite interpolation bug" self.currentFrameData = nil if self.animationType == "looping" then self:animationLooped() --Let ourselves know on next update that we looped for animationStarted signal self.looped = true elseif self.animationType == "once" then self.stopped = true self:animationStopped() end end --This is kind of a hack...it is possible the above events resulted in an animation switch, --If so, emit the animationStarted signal (won't trigger by above code block) --Thinking this may need to go in setCurrentAnimationName if animationName ~= self:getCurrentAnimationName() then self:animationStarted() end self:setTime( time ) end --Called once per Love2D "tick." dt is a delta of time elapsed since last update call. dt is a float - Number of seconds elapsed function Spriter:update( dt ) --Allow user to "freeze" animation if self.stopped then return end --[[ --Can turn interpolation on and off for debug (or other nefarious) purposes if self:getInterpolation() then local frameDatas = self:getFrameData() for i = 1, #frameDatas do local frameData = frameDatas[i] if frameData.update then frameData:update( dt ) end end end --]] self:incrementTime( dt ) end --getFrameData --Get list of animation names we can use with setCurrentAnimationName function Spriter:getAnimationNames() local animationNames = {} for i = 1, # self.entity[1].animation do local animation = self.entity[1].animation[i] animationNames[ # animationNames + 1 ] = animation.name end return animationNames end function Spriter:getCanvasOffset() local offsetX = self.canvasOffsetX or 0 local offsetY = self.canvasOffsetY or 0 return offsetX, offsetY end function Spriter:setCanvasOffset( canvasOffsetX, canvasOffsetY ) self.canvasOffsetX = canvasOffsetX self.canvasOffsetY = canvasOffsetY end --Convert spriter coordinates to Love-style coordinates. --0,0 is center of screen positive y moves up from center of screen function Spriter:spriterToScreen( x, y ) local centerx = Spriter.canvas:getWidth() / 2 local centery = Spriter.canvas:getHeight() -200 x = centerx + x y = centery - y if self.canvasOffsetX then x = x + self.canvasOffsetX end if self.canvasOffsetY then y = y + self.canvasOffsetY end return x, y end --Using a shared canvas to avoid creating too many --Not sure if the best idea, and certainly clunky to hard-code w/h function Spriter:getCanvas(xx,yy) if not self.canvas then self.canvas = love.graphics.newCanvas(xx, yy) end self.offsetX, self.offsetY = -self.canvas:getWidth()/2, -self.canvas:getHeight()/2 return self.canvas end --Offset at which to render the spriter data. function Spriter:setOffset( offsetX, offsetY) self.offsetX = offsetX self.offsetY = offsetY end function Spriter:getOffset() local offsetX = self.offsetX or 0 local offsetY = self.offsetY or 0 return offsetX, offsetY end --Scale at which to render the spriter data function Spriter:setScale( scaleX, scaleY ) self.scaleX = scaleX self.scaleY = scaleY end function Spriter:getScale() local scaleX = self.scaleX or 1 local scaleY = self.scaleY or 1 return scaleX, scaleY end --When inverting the animation, it is usually necessary to render with a corresponding offset --This controls the offset used when rendering inverted function Spriter:setInversionOffset( inversionOffset ) self.inversionOffset = inversionOffset end function Spriter:getInversionOffset() local inversionOffset = self.inversionOffset or 0 return inversionOffset end --Determines whether we are rendering the bones or not function Spriter:setDebug( debug ) self.debug = debug end function Spriter:getDebug() return self.debug end --If true, we render the spriter data inverted function Spriter:getInverted() return self.inverted end function Spriter:setInverted( inverted ) self.inverted = inverted end --Debugging function - draw bones. function Spriter:drawDebugInfo() local frameData = self:getFrameData() local currentColor = 1 local colors = { {r=255,g=0,b=0}, {r=0,g=255,b=0}, {r=0,g=0,b=255}, {r=255,g=255,b=0}, } local testImage if spew then --This loop is to draw the corners of the image for image rotation debugging --It is very noisy and spewy, so I only turn it on when I need to debug for i = 1, # frameData do local imageData = frameData[i] if imageData.dataType == "image" then local x, y = self:spriterToScreen( imageData.x, imageData.y ) local corners = { {x=x, y=y}, {x=x+imageData.image:getWidth(), y=y}, {x=x+imageData.image:getWidth(), y=y+imageData.image:getHeight()}, {x=x, y=y+imageData.image:getHeight()}, } local pivotx = corners[1].x local pivoty = corners[1].y for cornerIndex = 1, # corners do local x, y = corners[cornerIndex].x, corners[cornerIndex].y local tlx, tly = Spriter:rotatePoint( x, y, -imageData.angle, pivotx, pivoty ) love.graphics.setColor(colors[currentColor].r, colors[currentColor].g, colors[currentColor].b) currentColor = currentColor + 1 if currentColor > # colors then currentColor = 1 end love.graphics.circle( "fill", tlx, tly, 3, 100 ) end love.graphics.setColor(255, 255, 255) love.graphics.setColor(255, 255, 255) end end end --spew --Bone render for debugging currentColor = 1 for i = 1, # frameData do local data = frameData[i] if data.dataType == "bone" then local r = colors[currentColor].r local g = colors[currentColor].g local b = colors[currentColor].b currentColor = currentColor + 1 if currentColor > # colors then currentColor = 1 end love.graphics.setColor(r, g, b) local startx, starty = self:spriterToScreen( data.x, data.y ) local x2, y2 = self:spriterToScreen( data.x2, data.y2 ) love.graphics.circle( "fill", x2, y2, 3, 100 ) love.graphics.line(startx,starty, x2,y2) love.graphics.setColor(255, 255, 255) love.graphics.circle( "fill", startx, starty, 5, 100 ) end end end --drawDebugInfo function Spriter:draw( x, y ) local lastcanvas = lg.getCanvas() local scanvas = self:getCanvas(700,700) --Only possible to use sprite batch if we used texture packer structure - default is series of disparate images if self.usingTexturePacker then self.spriteBatch:clear() self.spriteBatch:bind() end local frameData = self:getFrameData() --In my engine I had transformations active during rendering --I had to re-set everything to origin to render at origin of canvas --This should be safe love.graphics.push() love.graphics.origin() --I'm not sure how to cleanly build a bounding rect to create a good canvas size, so I'm just doing screen w/h for now --All graphics operations from this point forward render to canvas instead of screen love.graphics.setCanvas(scanvas) scanvas:clear() -- lg.rectangle("fill", 0,0,self.canvas:getWidth(), self.canvas:getHeight()) love.graphics.setBlendMode('alpha') --Loop through framedata and render images (bones are also in array) for i = 1, # frameData do local imageData = frameData[i] if imageData.dataType == "image" then local x, y = self:spriterToScreen( imageData.x, imageData.y ) love.graphics.setColor(255, 255, 255) --Pivot data is stored as 0-1, but actually represents an offset of 0-width or 0-height for rotation purposes local pivotX = imageData.pivotX or 0 local pivotY = imageData.pivotY or 1 --Rescape pivot data from 0,1 to 0,w/h pivotX = rescale( pivotX, 0, 1, 0, imageData.image:getWidth() ) --Love2D has Y inverted from Spriter behavior -- pivotY is height - pivotY value pivotY = imageData.image:getHeight() - rescale( pivotY, 0, 1, 0, imageData.image:getHeight() ) love.graphics.draw(imageData.image, x, y - self.canvas:getHeight()/4, -imageData.angle, imageData.scale_x, imageData.scale_y, pivotX, pivotY) end end if self:getDebug() then self:drawDebugInfo() end --Turn off canvas. Graphics operations now apply to screen love.graphics.setCanvas(lastcanvas) -- The rectangle from the Canvas was already alpha blended. -- Use the premultiplied blend mode when drawing the Canvas itself to prevent another blending. love.graphics.setBlendMode('premultiplied') --Return to transformations active prior to our draw love.graphics.pop() local scaleX, scaleY = self:getScale() local xOffset, yOffset = self:getOffset() local inversionOffset = self:getInversionOffset() x = x + xOffset y = y + yOffset local canvasOffsetX, canvasOffsetY = self:getCanvasOffset() --We offset things in the canvas purely to avoid clipping of the sprite. If we do so, --We have to un-do the offset prior to rendering the canvas x = x - (canvasOffsetX * scaleX) y = y - (canvasOffsetY * scaleY) local inverted = self:getInverted() --I'm sure there's a more elegant way to handle this, but I'm being lazy. --Handle flips by rendering with -1 x scaling if not inverted then love.graphics.draw(scanvas, x, y, 0, scaleX, scaleY) else --Need to offset x position due to scaling love.graphics.draw(scanvas, x + inversionOffset, y, 0, -scaleX, scaleY) end --Turn default back on love.graphics.setBlendMode('alpha') end --draw --Tell library to render replacementImageName any time there is an attempt to render the image referenced by imageName --If nil is passed in for replacementImageName, resets back to original function Spriter:swapImage( imageName, replacementImageName ) self.imageSwaps[imageName] = replacementImageName end --Based on passed imageName, return the swapped image reference if there is a imageSwap entry for it, --Or return the image reference for the passed imageName if not function Spriter:getSwappedImage( imageName ) local name = imageName if self.imageSwaps[imageName] then name = self.imageSwaps[imageName] end local altFile = self.filenameLookup[name] assert(altFile, "Unable to lookup image " .. tostring(name)) return altFile end --Undo all mapping done via calls to swapImage function Spriter:resetImageSwaps() self.imageSwaps = {} end --Load a spriter file and return an object that can be used to animate and render this data --NOTE: the object returned has Spriter set as a metatable reference, so the spriterData returned --Essentially "inherits" all of the methods in Spriter --All of the "self" references used in the above Spriter methods are expected to be referring to a valid spriterData --Object loaded from a .scon file function Spriter:loadSpriter( path, file ) --All spriter assets are expected to be relative to path/directory self.baseName = file self.path = path .. "/" --By convention, we will assume filename is animationDirectory/animationDirectory.scon local filename = path .. file .. ".scon" assert(love.filesystem.isFile( filename ), "File " .. filename .. " not found") --Load file contents into string local contents, size = love.filesystem.read( filename ) assert(size, "Error loading file") --.scon file is json, parse the json into a Lua data structure local spriterData, pos, err = json.decode (contents, 1, nil) assert( not err, "Parse error!") --Quasi "inheritance" of Spriter "class" so spriterData can call methods on itself setmetatable(spriterData, {__index = function (table, key) return Spriter[key] end } ) --Boolean for debugging switch on/off of interpolation spriterData.interpolation = true --Array of animation transitions -- see usage above spriterData.transitions = {} --Change 0-index id, parent etc. references to 1-indexed for Lua spriterData:updateIds( spriterData ) --Spriter stores angles as degrees, convert to radians spriterData:anglesToRadians( spriterData ) --Use Love functions to load image references, store handle to loaded graphic in folder/file structure of spriterData spriterData:loadFilesAndFolders() --Update all objects in spriterData that contain folder/file IDs to reference the actual data in the spriterData object spriterData:updateFileReferences() --Create ->next references in mainline keys so we can easily access the next key from the data structure spriterData:createKeyReferences() --Update all objects in spriterData that contain timeline IDs to reference the actual data in the spriterData object spriterData:updateTimelineReferences() --Update all objects in spriterData that parent IDs to reference the actual data in the spriterData object spriterData:updateParentReferences() --NOTE: this method is deprecated. My previous approach was incorrect. I'm leaving this here temporarily in case I need to reference it -- spriterData:applyTransformations() --Table of image filenames that allows user to swap out images at runtime. see swapImage spriterData.imageSwaps = {} --Adding this because somehow it was not initialized local canvas = self:getCanvas() return spriterData end --loadSpriter --[[ usage: local Spriter = require("libs/Spriter") --Animation filename assumed to be animationDirectory/animationDirectory.scon local spriterData = Spriter:loadSpriter("./", "animationDirectory") --]] return Spriter
local opts = {noremap = true, silent = true} local map = vim.api.nvim_set_keymap -- Files map("n", "<leader>ff", "<cmd>lua require'telescope.builtin'.find_files{}<CR>", opts) map("n", "<leader>fg", "<cmd>lua require'telescope.builtin'.live_grep{}<CR>", opts) map("n", "<leader>fb", "<cmd>lua require'telescope.builtin'.buffers{}<CR>", opts) map("n", "<leader>fh", "<cmd>lua require'telescope.builtin'.help_tags{}<CR>", opts) -- LSP map("n", "gr", "<cmd>lua require'telescope.builtin'.lsp_references{}<CR>", opts) -- Git -- Remember: Ctrl-a create a new brnach, Ctrl-d remove selected branch map("n", "<leader>gb", "<cmd>lua require'telescope.builtin'.git_branches{}<CR>", opts) map("n", "<leader>gc", "<cmd>lua require'telescope.builtin'.git_bcommits{}<CR>", opts) map("n", "<leader>gt", "<cmd>lua require'telescope.builtin'.git_stash{}<CR>", opts) -- Repo List map("n", "<leader>rl", "<cmd>Telescope repo list<CR>", opts) -- Neoclip map("n", "<leader>yl", "<cmd>Telescope neoclip<CR>", opts)
local Ui = require("api.Ui") local IUiLayer = require("api.gui.IUiLayer") local IInput = require("api.gui.IInput") local InputHandler = require("api.gui.InputHandler") local UiTheme = require("api.gui.UiTheme") local UiMousePanel = require("mod.mouse_ui.api.gui.UiMousePanel") local UiMouseButton = require("mod.mouse_ui.api.gui.UiMouseButton") local UiMouseRoot = require("mod.mouse_ui.api.gui.UiMouseRoot") local UiMouseHBox = require("mod.mouse_ui.api.gui.UiMouseHBox") local UiMouseVBox = require("mod.mouse_ui.api.gui.UiMouseVBox") local UiMousePadding = require("mod.mouse_ui.api.gui.UiMousePadding") local UiMouseSlider = require("mod.mouse_ui.api.gui.UiMouseSlider") local UiMouseText = require("mod.mouse_ui.api.gui.UiMouseText") local MapEditorNewPanel = class.class("MapEditorNewPanel", IUiLayer) MapEditorNewPanel:delegate("input", IInput) function MapEditorNewPanel:init() self.text_width = UiMouseText:new {} self.text_height = UiMouseText:new {} self.slider_width = UiMouseSlider:new { value = 20, min_value = 1, max_value = 100, on_changed = function(v) self.text_width:set_text(tostring(v)) end } self.slider_height = UiMouseSlider:new { value = 20, min_value = 1, max_value = 100, on_changed = function(v) self.text_height:set_text(tostring(v)) end } self.root = UiMouseRoot:new { child = UiMousePanel:new { padding = UiMousePadding:new_all(4), child = UiMouseVBox:new { children = { UiMouseHBox:new { children = { self.slider_width, UiMouseVBox:new { children = { UiMouseText:new { text = "Width" }, self.text_width } } } }, UiMouseHBox:new { children = { self.slider_height, UiMouseVBox:new { children = { UiMouseText:new { text = "Height" }, self.text_height } } } }, UiMouseHBox:new { children = { UiMouseButton:new { text = "OK", callback = function() self.finished = true end }, UiMouseButton:new { text = "Cancel", callback = function() self.canceled = true end } } } } } } } self.input = InputHandler:new() self.input:bind_keys(self:make_keymap()) self.input:bind_mouse(self:make_mousemap()) self.input:bind_mouse_elements(self:get_mouse_elements(true)) self.input:forward_to(self.root) end function MapEditorNewPanel:make_keymap() return { cancel = function() self.canceled = true end, escape = function() self.canceled = true end, } end function MapEditorNewPanel:make_mousemap() return {} end function MapEditorNewPanel:get_mouse_elements(recursive) return self.root:get_mouse_elements(recursive) end function MapEditorNewPanel:relayout(x, y, width, height) self.width = 600 self.height = 400 self.x, self.y = Ui.params_centered(self.width, self.height) self.t = UiTheme.load(self) self.root:relayout(self.x, self.y, self.width, self.height) end function MapEditorNewPanel:draw() self.root:draw() end function MapEditorNewPanel:update(dt) local canceled = self.canceled local finished = self.finished self.canceled = false self.finished = false self.root:update(dt) if canceled then return nil, "canceled" end if finished then return { width = self.slider_width:get_value(), height = self.slider_height:get_value() }, nil end end return MapEditorNewPanel
return { { effect_list = { { type = "BattleBuffAddAttrBloodrage", trigger = { "onAttach", "onHPRatioUpdate" }, arg_list = { threshold = 0.3, value = 2, attr = "damageRatioBullet" } } } }, { effect_list = { { type = "BattleBuffAddAttrBloodrage", trigger = { "onAttach", "onHPRatioUpdate" }, arg_list = { threshold = 0.33, value = 2, attr = "damageRatioBullet" } } } }, { effect_list = { { type = "BattleBuffAddAttrBloodrage", trigger = { "onAttach", "onHPRatioUpdate" }, arg_list = { threshold = 0.36, value = 2, attr = "damageRatioBullet" } } } }, { effect_list = { { type = "BattleBuffAddAttrBloodrage", trigger = { "onAttach", "onHPRatioUpdate" }, arg_list = { threshold = 0.39, value = 2, attr = "damageRatioBullet" } } } }, { effect_list = { { type = "BattleBuffAddAttrBloodrage", trigger = { "onAttach", "onHPRatioUpdate" }, arg_list = { threshold = 0.43, value = 2, attr = "damageRatioBullet" } } } }, { effect_list = { { type = "BattleBuffAddAttrBloodrage", trigger = { "onAttach", "onHPRatioUpdate" }, arg_list = { threshold = 0.47, value = 2, attr = "damageRatioBullet" } } } }, { effect_list = { { type = "BattleBuffAddAttrBloodrage", trigger = { "onAttach", "onHPRatioUpdate" }, arg_list = { threshold = 0.52, value = 2, attr = "damageRatioBullet" } } } }, { effect_list = { { type = "BattleBuffAddAttrBloodrage", trigger = { "onAttach", "onHPRatioUpdate" }, arg_list = { threshold = 0.57, value = 2, attr = "damageRatioBullet" } } } }, { effect_list = { { type = "BattleBuffAddAttrBloodrage", trigger = { "onAttach", "onHPRatioUpdate" }, arg_list = { threshold = 0.63, value = 2, attr = "damageRatioBullet" } } } }, { effect_list = { { type = "BattleBuffAddAttrBloodrage", trigger = { "onAttach", "onHPRatioUpdate" }, arg_list = { threshold = 0.7, value = 2, attr = "damageRatioBullet" } } } }, time = 0, name = "好斗的玛丽", init_effect = "jinengchufared", color = "red", picture = "", desc = "增伤效果", stack = 1, id = 10971, icon = 10971, last_effect = "", blink = { 1, 0, 0, 0.3, 0.3 }, effect_list = { { type = "BattleBuffAddAttrBloodrage", trigger = { "onAttach", "onHPRatioUpdate" }, arg_list = { threshold = 0.3, value = 2, attr = "damageRatioBullet" } } } }
module(..., package.seeall) NODE = { title="Templates", category="_special_pages", prototype="@Lua_Config", } NODE.search_form = [===[ ]===] NODE.content=[=====[--- this is the template that generates the outer tags of the page --- TRANSLATIONS = "Translations:Main" -------------------------------------------------------------------------------- ------- BASIC TEMPLATES -------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- ------- HISTORY, ETC ----------------------------------------------------------- -------------------------------------------------------------------------------- DATE_SELECTOR = [===[ <div id="date_selector" style="border:1px solid #bbb; background: #eee8aa; padding: 5 5 5 5"> _(CHANGES_BY_DATE) ($current_month): <span class="history_dates"> $do_dates[=[$if_current_date[[$date]]|[[<a $date_link>$date</a>]] ]=] </span> <br/> _(CHOOSE_ANOTHER_MONTH) ($current_year) : <span class="history_months"> $do_months[=[$if_current_month[[$month]]$if_other_month[[<a $month_link>$month</a>]] ]=] </span> <br/> </div> <!-- end of "date_selector" div--> <br/> ]===] HISTORY = [===[ <form action="$base_url"> <input type="hidden" class="hidden" name="p" value="$node_name.diff"/> <input type="submit" value="_(DIFF_SELECTED_VERSIONS)"/> <table width="100%"> <tbody> $do_revisions[==[ <tr> $if_new_date[=[ <tr><td style="border-right: 0; border-left: 0" colspan="3"><h2>$date</h2></td></tr> ]=] $if_edit[=[ <td width="5px" $if_minor[[bgcolor="#f0f0f0"]]> <input class="diff_radio" type="radio" value="$version" name="other"/> </td> <td width="5px" $if_minor[[bgcolor="#f0f0f0"]]> <input class="diff_radio" type="radio" value="$version" name="version"/> </td> <td width="400px" $if_minor[[bgcolor="#f0f0f0"]]> _(AUTHOR_SAVED_VERSION) $if_summary[[<ul><li>$summary</li></ul>]] </td> ]=] </tr> ]==] </tbody> </table> </form> ]===] COMPLETE_HISTORY = [===[ <table width="100%"> <tbody> $do_revisions[==[ $if_new_date[=[ <tr><td style="border-right: 0; border-left: 0" colspan="3"><h2>$date</h2></td></tr> ]=] $if_edit[=[ <tr> <td width="50px" $if_stale[[style="display:none"]] rowspan="$row_span"> &nbsp;<a $latest_link>$title</a> </td> <td width="300px" $if_minor[[bgcolor="#f0f0f0"]] style="border-right: 0px"> _(AUTHOR_SAVED_VERSION) $if_summary[[<p>$summary</p>]] </td> <td width="10%" $if_minor[[bgcolor="#f0f0f0"]] style="border-left: 0px" align="right"> <a $diff_link title="_(DIFF)"><img alt="_(DIFF)" src="$diff_icon"/></a> <a $history_link title="_(HISTORY)"><img alt="_(HISTORY)" src="$history_icon"/></a> </td> </tr> ]=] ]==] </tbody> </table> ]===] DIFF = [===[ <ul> <li><a $link1><ins class='diffmod'>$version1</ins></a> _(BY_AUTHOR1)</li> $if_version2_exists[[<li><a $link2><del class='diffmod'>$version2</del></a> _(BY_AUTHOR2)</li>]] </ul> $diff ]===] RSS = [===[<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"> <channel> <title>$title</title> <description/> <link>$channel_url</link> $items[==[ <item> <link>$link</link> <title>$title</title> <guid isPermaLink="$ispermalink">$guid</guid> <pubDate>$pub_date</pubDate> <dc:creator>$author</dc:creator> <description>$summary</description> </item>]==] </channel> </rss> ]===] RSS_SUMMARY = [===[ $if_summary_exists[[$summary]] $if_no_summary[[_(NO_EDIT_SUMMARY)]] <hr/> <a href="$history_url">_(HISTORY)</a> <a href="$diff_url">_(SHOW_CHANGES_SINCE_PREVIOUS)</a>]===] LIST_OF_ALL_PAGES = [===[ $do_nodes[[<a href="$url">$name</a><br/>]] ]===] SITEMAP_XML = [===[<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> $do_urls[[<url> <loc>$url</loc> <lastmod>$lastmod</lastmod> <changefreq>$changefreq</changefreq> <priority>$priority</priority> </url>]] </urlset> ]===] -------------------------------------------------------------------------------- ------- MISCELLANEOUS ---------------------------------------------------------- -------------------------------------------------------------------------------- EDIT = [===[ <form class="edit" method="post" enctype="multipart/form-data" action="$action_url"> $captcha <input class="hidden" type="hidden" name="p" value="$node_name.post"/> <input class="hidden" type="hidden" name="post_token" value="$post_token"/> <input class="hidden" type="hidden" name="post_timestamp" value="$post_timestamp"/> <input class="hidden" type="hidden" name="post_fields" value="$post_fields"/> $if_preview[[ <h2>_(PREVIEWING_UNSAVED_CHANGES)</h2> <div class="preview">$preview</div> <a href="#new_page_content_header" class="button">_(CHANGE)</a> <div class="submit"> <button class="positive" type="submit" name="action_save" accesskey="s">_(SAVE)</button> <button class="negative" type="submit" name="action_show" accesskey="c">_(CANCEL)</button> </div> ]] $html_for_fields <div class="submit"> <button class="positive" type="submit" accesskey="s" name="action_save">_(SAVE)</button> <button class="positive" type="submit" accesskey="s" name="action_preview">_(PREVIEW)</button> <button class="negative" type="submit" accesskey="s" name="action_cancel">_(CANCEL)</button> </div> </form> ]===] EDIT_FORM_HEADER = [[<a name="$anchor"></a><h2>$label</h2>]] EDIT_FORM_NOTE = [[<h3>$label</h3>]] EDIT_FORM_LABEL = [[<label>$label</label>]] EDIT_FORM_INLINE_LABEL = [[<label class="inline">$label</label>]] EDIT_FORM_FILE = [[<input type="file" value="$value" name="$name"/>]] EDIT_FORM_HONEYPOT = [[<input type="text" value="$value" name="$name"/>]] EDIT_FORM_TEXT_FIELD = [[<input type="text" value="$value" name="$name" class="textfield"/>]] EDIT_FORM_HIDDEN = [[<input type="hidden" class="hidden" value="$value" name="$name"/>]] EDIT_FORM_READONLY_TEXT = [[<input type="text" value="$value" name="$name" class="readonly textfield" readonly="readonly" />]] EDIT_FORM_PASSWORD = [[<input type="password" value="$value" name="$name" size="20" class="textfield"></input>]] EDIT_FORM_TEXTAREA = [[<textarea class="$class" name="$name" cols="80" rows="$rows">$value</textarea>]] EDIT_FORM_EDITOR = [[<textarea class="$class" name="$name" cols="80" rows="$rows">$value</textarea>]] EDIT_FORM_BIG_TEXTAREA = [[<textarea class="$class" name="$name" id="main_text_area" cols="80" rows="$rows">$value</textarea><br/> <a href="#" onclick="expandTextArea(); return false;">expand</a>]] EDIT_FORM_CHECKBOX = [[<input class="checkbox" style="border:1px solid black" type="checkbox" name="$name" value="yes" $if_checked[=[checked="checked"]=] /><br/>]] EDIT_FORM_CHECKBOX_TEXT = [[<input class="checkbox" style="border:1px solid black" type="checkbox" name="$name" value="yes" $if_checked[=[checked="checked"]=] />$text<br/>]] EDIT_FORM_SELECT = [[<select name="$name" tabindex="$tab_index"> $do_options[===[<option value="$value" $if_selected[=[selected="yes"]=]>$display</option>]===] </select>]] EDIT_FORM_SHOW_ADVANCED = [[<a id="more_fields" href="#" class="local" onclick="toggleElements('advanced_field')"> <div id="toggle_advanced_fields">_(SHOW_ADVANCED_OPTIONS)</div></a>]] EDIT_FORM_DIV_START = [=[$do_collapse[[<h2 id="trigger_$id" class="ctrigger $state">$label</h2>]]<div id="$id" class="$class">]=] EDIT_FORM_DIV_END = [[</div>]] LOGIN_FORM = [===[ <form method="post" action="$action_url"> <input class="hidden" type="hidden" name="post_token" value="$post_token"/> <input class="hidden" type="hidden" name="post_timestamp" value="$post_timestamp"/> <input class="hidden" type="hidden" name="post_fields" value="$post_fields"/> $html_for_fields <button class="submit" type="submit" accesskey="c" name="action_login">_(LOGIN)</button> </form> ]===] -------------------------------------------------------------------------------- ------- DEALING WITH LUA CODE -------------------------------------------------- -------------------------------------------------------------------------------- LUA_CODE = [===[ $if_ok[[<font color="green">_(THIS_LUA_CODE_PARSES_CORRECTLY)</font>]] $if_errors[[ <font color='red'> <p><b>_(THIS_LUA_CODE_HAS_PROBLEMS)</b></p> <code> $errors </code> </font> ]] <div width="100%"> <style> table.code { width: 100%; border-collapse: collapse background: red; border-style: none; } table.body { background: yellow; } table.code tbody th { font-size: 90%; } table.code tbody th a{ text-decoration: none; color: white; } table.code th.lineno { width: 4em; } table.code th.bad { background: red; } table.code tbody td { border: none; } table.code tbody td code { background: white; } table.code tbody td code.bad{ background: yellow; } </style> <table class="code"> <tbody> $do_lines[[ <tr> <th id="L$i" class="$class"><a href="#L$i">$i</a></th> <td><code class="$class">$line</code></td> </tr> ]] </tbody> </table> </div> ]===] ACTION_NOT_FOUND = [===[ <div class="error_message"> <p>_(PAGE_DOES_NOT_SUPPORT_ACTION)</p> $if_custom_actions[[ <p>_(THIS_PAGE_DEFINED_THE_FOLLOWING_ACTIONS)</p> <pre><code>$actions</code></pre> ]] </div> ]===] REGISTRATION = [===[ <h3>Create new account</h3> <form class="register" method="post" enctype="multipart/form-data" action="$action_url"> <input class="hidden" type="hidden" name="p" value="$node_name.$action"/> <input class="hidden" type="hidden" name="post_token" value="$post_token"/> <input class="hidden" type="hidden" name="post_timestamp" value="$post_timestamp"/> <input class="hidden" type="hidden" name="post_fields" value="$post_fields"/> $html_for_fields $captcha <div class="submit"> <button class="submit positive" type="submit" accesskey="s" name="action_submit">Register</button> </div> </form> ]===] VERSION = [=[ <h2>Installer Version</h2> $installer <h2>Specific Rocks</h2> <table> $rocks[[ <tr> <th>$rock</th> <td>$version</td> </tr> ]] </table> ]=] ]=====]
--アメイズメント・スペシャルショー --Amazement Special Show --Scripted by Kohana Sonogami function c101104057.initial_effect(c) --tohand and spsummon local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_TOHAND) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_CHAINING) e1:SetCondition(c101104057.spcon) e1:SetTarget(c101104057.sptg) e1:SetOperation(c101104057.spop) c:RegisterEffect(e1) end function c101104057.thfilter(c,tp,e) return c:IsFaceup() and c:IsSetCard(0x25e) and c:IsLocation(LOCATION_MZONE) and c:IsControler(tp) and c:IsCanBeEffectTarget(e) and c:IsAbleToHand() end function c101104057.spcon(e,tp,eg,ep,ev,re,r,rp) if rp==tp or not re:IsHasProperty(EFFECT_FLAG_CARD_TARGET) then return false end local tg=Duel.GetChainInfo(ev,CHAININFO_TARGET_CARDS) return tg and tg:IsExists(c101104057.thfilter,1,nil,tp,e) end function c101104057.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) local g=Duel.GetChainInfo(ev,CHAININFO_TARGET_CARDS) if chkc then return eg:IsContains(chkc) and c101104057.thfilter(chkc,tp,e) end if chk==0 then return true end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND) local sg=g:FilterSelect(tp,c101104057.thfilter,1,1,nil,tp,e) Duel.SetTargetCard(sg) Duel.SetOperationInfo(0,CATEGORY_TOHAND,sg,1,0,0) end function c101104057.spfilter(c,e,tp) return c:IsSetCard(0x25e) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c101104057.spop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and Duel.SendtoHand(tc,nil,REASON_EFFECT)~=0 then local g=Duel.GetMatchingGroup(c101104057.spfilter,tp,LOCATION_HAND,0,nil,e,tp) if #g>0 and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.SelectYesNo(tp,aux.Stringid(101104057,1)) then Duel.BreakEffect() Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local sg=g:Select(tp,1,1,nil) Duel.SpecialSummon(sg,0,tp,tp,false,false,POS_FACEUP) end end end
local Player = { color = {255,255,255} } function Player.new(x,y,width,height) local self = {x=x,y=y,width=width,height=height,_speed=400,speed=400,keys={right='right',left='left'}} self.lastx = x self.lasty = y setmetatable(self, {__index=Player}) return self end function Player:update(dt) self.lastx = self.x self.lasty = self.y local k = self.keys if k then local dir if love.keyboard.isDown(k.right) then dir = 1 elseif love.keyboard.isDown(k.left) then dir = -1 else dir = 0 end self:setDirection(dir) end self.x = self.x+self.speed*dt end function Player:setDirection(dir) self.speed = self._speed*dir end function Player:draw() love.graphics.setColor(self.color) love.graphics.rectangle('fill',self.x-self.width/2,self.y-self.height/2,self.width,self.height) end return Player