content
stringlengths
5
1.05M
sprites = {} sprites.all = {} sprites.Add = function (ent) -- validate ent if not ent.Load then print("Error, sprite does not have Load method.") return nil elseif not ent.X then print("Error, sprite missing X property") return nil elseif not ent.Y then print("Error, sprite missing Y property") return nil else sprites.all[#sprites.all + 1] = ent end -- return entity as success indicator return ent end sprites.Load = function() for _,sprite in ipairs(sprites.all) do sprite:Load() end end -- simply just draw the sprite collection sprites.Draw = function () local draw = love.graphics.draw local sees = gGame.Camera.Sees for _,sprite in ipairs(sprites.all) do if sees(sprite.X, sprite.Y) then draw(sprite.image, sprite.X, sprite.Y) end end end return sprites
--transaction request format: list of {string function, {arg1, ... argN} } --arg format: {arg} or {dependency:{prev_response_index}} or {dependency:{prev_response_index, fieldname}} local transaction = { execute = function(transaction) local results = {} local currentOperationResult = {} box.begin() for index, request in pairs(transaction) do currentOperationResult[1], currentOperationResult[2] = pcall( art.core.functionFromString(request[1]), unpack(art.transaction.insertDependencies(request[2], results)) ) if not(currentOperationResult[1]) then box.rollback() return {false, 'Operation ' .. index .. ':' .. currentOperationResult[2]} end results[index] = {currentOperationResult[2]} end box.commit() return {true, results} end, insertDependencies = function(args, prevResults) local result = {} for index, argument in pairs(args) do result[index] = argument if type(argument)=='table' and argument.dependency then result[index] = art.transaction.getDependency(argument.dependency, prevResults) end end return result end, getDependency = function(dependencyRecord, prevResults) local dependency = prevResults[dependencyRecord[1]][1] if dependencyRecord[2] then return art.transaction.extractFieldFromTuple(dependency, dependencyRecord[2]) end return dependency end, extractFieldFromTuple = function(tuple, fieldName) local data = tuple[1] local schema = tuple[2] for index = 2, #schema do if schema[index][2] == fieldName then return data[index - 1] end end end } return transaction
-- The nebulae generator is tasked with generating random nebulae for -- display in the star background -- the implementation is heavily based on randomnoise ideas explored here: -- http://lodev.org/cgtutor/randomnoise.html -- So many thanks to Lode -- -- Generating clouds takes time and should be done once on startup not -- during game time (or worse: during draw operations) -- -- One should remember that randomseeds that are nearly identically tend -- tend to produce similiar distributions of numbers -- -- The nebulator is implemented as a thread as it takes a while to generate -- even one background. This allows us to generate backgrounds while the -- player is in the menu and show a loading bar/play the game without background -- until it is finished -- -- load modules needed to run a thread require 'love.filesystem' require 'love.image' require 'love.timer' local output = love.thread.getChannel("nebulator_output") local percentage = love.thread.getChannel("nebulator_percentage") local input = love.thread.getChannel("nebulator_input") -- define noise parameters locally so that they can used in all nebulator methods local noiseWidth = 400 local noiseHeight = 400 local noise = {} -- smooth the noise at a specified position by interpolating -- over nearby points local function smoothNoise(x, y) -- get fractional part of x and y local fractX = x - math.floor(x) local fractY = y - math.floor(y) -- wrap around local x1 = (math.floor(x) + noiseWidth) % noiseWidth; local y1 = (math.floor(y) + noiseHeight) % noiseHeight; -- neighbor values local x2 = (x1 + noiseWidth - 1) % noiseWidth; local y2 = (y1 + noiseHeight - 1) % noiseHeight; -- smooth the noise with bilinear interpolation local value = 0.0; value = value + fractX * fractY * noise[x1][y1] value = value + fractX * (1 - fractY) * noise[x1][y2] value = value + (1 - fractX) * fractY * noise[x2][y1] value = value + (1 - fractX) * (1 - fractY) * noise[x2][y2] return value end -- add turbulence at specified position -- basically mixes everything up by the factor size -- the larger the size the smoother the end result will seem local function turbulence(x, y, size) local value = 0.0 local currentSize = size while currentSize >= 1 do value = value + smoothNoise(x / currentSize, y / currentSize) * currentSize currentSize = currentSize / 2 end return(128.0 * value / size) end -- (re)fill the noise array local function initNoise(w, h) -- if the size parameters are set use them if w ~= nil and h ~= nil then noiseWidth = w noiseHeight = h else noiseWidth = 500 noiseHeight = noiseWidth end -- create noise. -- basically a 2d array with values between 0 and 1 noise= {} for i=0,noiseWidth do noise[i] = {} for j=0,noiseHeight do noise[i][j] = math.random(0,10000) / 10000 end end end percentage:push(0) local w = input:pop() local h = input:pop() local id = input:pop() -- randomseeds that are nearly identically tend to produce the same math.randomseed(id) initNoise(w, h) -- create imgData to write into local imgData = love.image.newImageData( noiseWidth + 1, noiseHeight + 1) -- number of rifts with general orientation (horizontal/vertical) local xPeriod = 0 -- number of base lines in x local yPeriod = 0 -- number of base lines in y local turbPower = 2 -- 0 = no twists, the higher the more twists local turbSize = 768 -- initial turbulence size -- copy the individual pixels into the imageData for i=1,noiseWidth do percentage:push(i/noiseWidth) for j=1,noiseHeight do local xyValue = i * xPeriod / noiseHeight + j * yPeriod / noiseWidth + turbPower * turbulence(i, j, turbSize) / 256.0 local sineValue = 256 * math.abs(math.sin(xyValue * 3.14159)) imgData:setPixel( i, j, sineValue, sineValue, sineValue, 255 ) end end -- pass data and set finished --local file = love.filesystem.newFile("output.png") --imgData:encode(file) output:push(imgData)
--- -- @section changes -- some micro-optimizations (localizing globals) local os = os local hook = hook local table = table --- -- @realm client -- @internal local changesVersion = CreateConVar("changes_version", "v0.0.0.0", FCVAR_ARCHIVE) local changes, currentVersion --- -- Adds a change into the changes list -- @param string version -- @param string text -- @param[opt] number date the date when this update got released -- @realm client function AddChange(version, text, date) changes = changes or {} -- adding entry to table -- if no date is given, a negative index is stored as secondary sort parameter table.insert(changes, 1, {version = version, text = text, date = date or -1 * (#changes + 1)}) currentVersion = version end --- -- Creates the changes list -- @realm client -- @internal function CreateChanges() if changes then return end changes = {} AddChange("TTT2 Base - v0.3.5.6b", [[ <ul> <li><b>many fixes</b></li> <li>enabled picking up grenades in prep time</li> <li>roundend scoreboard fix</li> <li>disabled useless prints that have spammed the console</li> </ul> ]]) AddChange("TTT2 Base - v0.3.5.7b", [[ <ul> <li><b>code optimization</b></li> <br /> <li>added different CVars</li> <br /> <li>fixed loadout and model issue on changing the role</li> <li>bugfixes</li> <br /> <li>removed <code>PLAYER:UpdateRole()</code> function and hook <code>TTT2RoleTypeSet</code></li> </ul> ]]) AddChange("TTT2 Base - v0.3.5.8b", [[ <ul> <li><b>selection system update</b></li> <br /> <li>added different ConVars</li> <li>added possibility to force a role in the next roleselection</li> <br /> <li>bugfixes</li> </ul> ]]) AddChange("TTT2 Base - v0.3.6b", [[ <ul> <li>new <b>networking system</b></li> <br /> <li>added <b>gs_crazyphysics detector</b></li> <li>added RoleVote support</li> <li>added new multilayed icons (+ multilayer system)</li> <li>added credits</li> <li>added changes window</li> <li>added <b>detection for registered incompatible add-ons</b></li> <li>added autoslay support</li> <br /> <li>karma system improvement</li> <li>huge amount of bugfixes</li> </ul> ]]) AddChange("TTT2 Base - v0.3.7b", [[ <ul> <li>added hook <code>TTT2ToggleRole</code></li> <li>added <code>GetActiveRoles()</code></li> <br /> <li>fixed TTT spec label issue</li> <br /> <li>renamed hook <code>TTT_UseCustomPlayerModels</code> into <code>TTTUseCustomPlayerModels</code></li> <li>removed <code>Player:SetSubRole()</code> and <code>Player:SetBaseRole()</code></li> </ul> ]]) AddChange("TTT2 Base - v0.3.7.1b", [[ <ul> <li>added possibility to disable roundend if a player is reviving</li> <li>added own Item Info functions</li> <li>added debugging function</li> <li>added TEAM param <code>.alone</code></li> <li>added possibility to set the cost (credits) for any equipment</li> <li>added <code>Player:RemoveEquipmentItem(id)</code> and <code>Player:RemoveItem(id)</code> / <code>Player:RemoveBought(id)</code></li> <li>added possibility to change velocity with hook <code>TTT2ModifyRagdollVelocity</code></li> <br /> <li>improved external icon addon support</li> <li>improved binding system</li> <br /> <li>fixed loadout bug</li> <li>fixed loadout item reset bug</li> <li>fixed respawn loadout issue</li> <li>fixed bug that items were removed on changing the role</li> <li>fixed search icon display issue</li> <li>fixed model reset bug on changing role</li> <li>fixed <code>Player:GiveItem(...)</code> bug used on round start</li> <li>fixed dete glasses bug</li> <li>fixed rare corpse bug</li> <li>fixed Disguiser</li> <li>Some more small fixes</li> </ul> ]]) AddChange("TTT2 Base - v0.3.7.2b", [[ <ul> <li>reworked the <b>credit system</b> (Thanks to Nick!)</li> <li>added possibility to override the init.lua and cl_init.lua file in TTT2</li> <br /> <li>fixed server errors in combination with TTT Totem (now, TTT2 will just not work)</li> <li>fixed ragdoll collision server crash (issue is still in the normal TTT)</li> </ul> ]]) AddChange("TTT2 Base - v0.3.7.3b", [[ <ul> <li>reworked the <b>selection system</b> (balancing and bugfixes)</li> <br /> <li>fixed playermodel issue</li> <li>fixed toggling role issue</li> <li>fixed loadout doubling issue</li> </ul> ]]) AddChange("TTT2 Base - v0.3.7.4b", [[ <ul> <li>fixed playermodel reset bug (+ compatibility with PointShop 1)</li> <li>fixed external HUD support</li> <li>fixed credits bug</li> <li>fixed detective hat bug</li> <li>fixed selection and jester selection bug</li> </ul> ]]) AddChange("TTT2 Base - v0.3.8b", [[ <ul> <li>added new TTT2 Logo</li> <li>added ShopEditor missing icons (by Mineotopia)</li> <br /> <li><b>reworked weaponshop → ShopEditor</b></li> <li>changed file based shopsystem into sql</li> </ul> ]]) AddChange("TTT2 Base - v0.3.8.1b", [[ <ul> <li>fixed credit issue in ShopEditor (all Data will load and save correct now)</li> <li>fixed item credits and minPlayers issue</li> <li>fixed radar, disguiser and armor issue in ItemEditor</li> <li>fixed shop syncing issue with ShopEditor</li> <br /> <li>small performance improvements</li> <li>cleaned up some useless functions</li> <li>removed <code>ALL_WEAPONS</code> table (SWEP will cache the initialized data now in it's own table / entity data)</li> <li>some function renaming</li> </ul> ]]) AddChange("TTT2 Base - v0.3.8.2b", [[ <ul> <li>added <b>russian translation</b> (by Satton2)</li> <li>added <code>.minPlayers</code> indicator for the shop</li> <br /> <li>replaced <code>.globalLimited</code> param with <code>.limited</code> param to toggle whether an item is just one time per round buyable for each player</li> </ul> ]]) AddChange("TTT2 Base - v0.3.8.3b", [[ <ul> <li>ammoboxes will store the correct amount of ammo now <li>connected <b>radio commands</b> with <b>scoreboard #tagging</b> (https://github.com/Exho1/TTT-ScoreboardTagging/blob/master/lua/client/ttt_scoreboardradiocmd.lua)</li> </ul> ]]) AddChange("TTT2 Base - v0.3.9b", [[ <ul> <li>reimplemented all these nice unaccepted PullRequest for TTT on GitHub: <ul> <li><b>Custom Crosshairs</b> (<code>F1 → Settings</code>): 'https://github.com/Facepunch/garrysmod/pull/1376/' by nubpro</li> <li>Performance improvements with the help of 'https://github.com/Facepunch/garrysmod/pull/1287' by markusmarkusz and Alf21</li> </ul> </li> <br /> <li>added possibility to use <b>random shops!</b> (<code>ShopEditor → Options</code>)</li> <li>balanced karma system (Roles that are aware of their teammates can't earn karma anymore. This will lower teamkilling)</li> </ul> ]]) AddChange("TTT2 Base - v0.4.0b", [[ <ul> <li>ShopEditor: <ul> <li>added <code>.notBuyable</code> param to hide item in the shops</li> <li>added <code>.globalLimited</code> and <code>.teamLimited</code> params to limit equipment</li> </ul> </li> <br /> <li>added <b>new shop</b> (by tkindanight)</li> <ul> <li>you can toggle the shop everytime (your role doesn't matter)</li> <li>the shop will update in real time</li> </ul> </li> <br /> <li>added new icons</li> <li>added warming up for <b>randomness</b> to make things happen... yea... random</li> <li>added auto-converter for old items</li> <br /> <li>decreased speed modification lags</li> <li>improved performance</li> <li>implemented <b>new item system!</b> TTT2 now supports more than 16 passive items!</li> <li>huge amount of fixes</li> </ul> ]]) AddChange("TTT2 Base - v0.5.0b", [[ <h2>New:</h2> <ul> <li>Added new <b>HUD system</b></li> <ul> <li>Added <b>HUDSwitcher</b> (<code>F1 → Settings → HUDSwitcher</code>)</li> <li>Added <b>HUDEditor</b> (<code>F1 → Settings → HUDSwitcher</code>)</li> <li>Added old TTT HUD</li> <li>Added <b>new</b> PureSkin HUD, an improved and fully integrated new HUD</li> <ul> <li>Added a Miniscoreboard / Confirm view at the top</li> <li>Added support for SubRole informations in the player info (eg. used by TTT Heroes)</li> <li>Added a team icon to the top</li> <li>Redesign of all other HUD elements...</li> </ul> </li> </ul> </li> <li>Added possibility to give every player his <b>own random shop</b></li> <li>Added <b>sprint</b> to TTT2</li> <li>Added a <b>drowning indicator</b> into TTT2</li> <li>Added possibility to toggle auto afk</li> <li>Added possibility to modify the time a player can dive</li> <li>Added parameter to the bindings to detect if a player released a key</li> <li>Added possibility to switch between team-synced and individual random shops</li> <li>Added some nice <b>badges</b> to the scoreboard</li> <li>Added a sql library for saving and loading specific elements (used by the HUD system)</li> <li>Added and fixed Bulls draw lib</li> <li>Added an improved player-target add-on</li> </ul> <br /> <h2><b>Changed:</b></h2> <ul> <li>Changed convar <code>ttt2_confirm_killlist</code> to default <code>1</code></li> <li>Improved the changelog (as you can see :D)</li> <li>Improved Workshop page :)</li> <li>Reworked <b>F1 menu</b></li> <li>Reworked the <b>slot system</b> (by LeBroomer)</li> <ul> <li>Amount of carriable weapons are customizable</li> <li>Weapons won't block slots anymore automatically</li> <li>Slot positions are generated from weapon types</li> </ul> </li> <li>Reworked the <b>ROLES</b> system</li> <ul> <li>Roles can now be created like weapons utilizing the new roles lua module</li> <li>They can also inherit from other roles</li> </ul> </ul> <li>Improved the MSTACK to also support messages with images</li> <li>Confirming a player will now display an imaged message in the message stack</li> </ul> <br /> <h2>Fixed:</h2> <ul> <li>Fixed TTT2 binding system</li> <li>Fixed Ammo pickup</li> <li>Fixed karma issue with detective</li> <li>Fixed DNA Scanner bug with the radar</li> <li>Fixed loading issue in the items module</li> <li>Fixed critical bug in the process of saving the items data</li> <li>Fixed the Sidekick color in corpses</li> <li>Fixed bug that detective were not able to transfer credits</li> <li>Fixed kill-list confirm role syncing bug</li> <li>Fixed crosshair reset bug</li> <li>Fixed confirm button on corpse search still showing after the corpse was confirmed or when a player was spectating</li> <li>Fixed draw.GetWrappedText() containing a ' ' in its first row</li> <li>Fixed shop item information not readable when the panel is too small -> added a scrollbar</li> <li>Fixed shop item being displayed as unbuyable when the items price is set to 0 credits</li> <li>Other small bugfixes</li> </ul> ]], os.time({year = 2019, month = 03, day = 03})) AddChange("TTT2 Base - v0.5.1b", [[ <h2>Improved:</h2> <ul> <li>Improved the binding library and extended the functions</li> </ul> <br> <h2>Fixed:</h2> <ul> <li>Fixed target reset bug</li> <li>Fixed / Adjusted hud element resize handling</li> <li>Fixed strange weapon switch error</li> <li>Fixed critical model reset bug</li> <li>Fixed hudelements borders, childs will now extend the border of their parents</li> <li>Fixed mstack shadowed text alpha fadeout</li> <li>Fixed / Adjusted scaling calculations</li> <li>Fixed render order</li> <li>Fixed "player has no SteamID64" bug</li> </ul> ]], os.time({year = 2019, month = 03, day = 05})) AddChange("TTT2 Base - v0.5.2b", [[ <h2>New:</h2> <ul> <li>Added spectator indicator in the Miniscoreboard</li> <li>Added icons with higher resolution (native 512x512)</li> <li>Added Heroes badge</li> <li>Added HUD documentation</li> <li>Added some more hooks to modify TTT2 externally</li> </ul> <br> <h2>Improved:</h2> <ul> <li>Improved the project structure / <b>Code refactoring</b></li> <li>Improved HUD sidebar of items / perks</li> <li>Improved HUD loading</li> <li>Improved the sql library</li> <li>Improved item handling and item converting</li> <li><b>Improved performance / performance optimization</b></li> </ul> <br> <h2>Fixed:</h2> <ul> <li>Fixed SetModel bugs</li> <li>Fixed some model-selector bugs</li> <li>Fixed a sprint bug</li> <li>Fixed some ConVars async bugs</li> <li>Fixed some shopeditor bugs</li> <li>Fixed an HUD scaling bug</li> <li>Fixed old_ttt HUD</li> <li>Fixed border's alpha value</li> <li>Fixed confirmed player ordering in the Miniscoreboard</li> <li><b>Fixed <u>critical</u> TTT2 bug</b></li> <li><b>Fixed a crash that randomly happens in the <u>normal TTT</u></b></li> <li>Fixed PS2 incompatibility</li> <li>Fixed spectator bug with Roundtime and Haste Mode</li> <li>Fixed many small HUD bugs</li> </ul> ]], os.time({year = 2019, month = 04, day = 32})) AddChange("TTT2 Base - v0.5.3b", [[ <h2>New:</h2> <li>Added a <b>Reroll System</b> for the <b>Random Shop</b></li> <ul> <li>Rerolls can be done in the Traitor Shop similar to the credit transferring</li> <li>Various parameters in the <b>ShopEditor</b> are possible (reroll, cost, reroll per buy)</li> <li>Added the reroll possibility for the <b>Team Random Shop</b> (very funny)</li> </ul> <br> <h2>Improved:</h2> <ul> <li>Added a separate slot for class items</li> <li>Added help text to the <b>"Not Alive"-Shop</b></li> <li>Minor design tweaks</li> </ul> <br> <h2>Fixed:</h2> <ul> <li>Fixed critical crash issue (ty to @nick)</li> </ul> ]], os.time({year = 2019, month = 05, day = 09})) AddChange("TTT2 Base - v0.5.4b", [[ <h2>New:</h2> <ul> <li>Added a noTeam indicator to the HUD</li> <li>intriduced a new drowned death symbol</li> <li><i>ttt2_crowbar_shove_delay<i> is now used to set the crowbar attack delay</li> <li>introduced a status system alongside the perk system</li> </ul> <br> <h2>Improved:</h2> <ul> <li>Included LeBroomer in the TTT2 logo</li> </ul> <br> <h2>Fixed:</h2> <ul> <li>Fixed a problem with colors (seen with sidekick death confirms)</li> <li>Fixed the team indicator when in spectator mode</li> <li>Credits now can be transfered to everyone, this fixes a bug with the spy</li> </ul> ]], os.time({year = 2019, month = 06, day = 18})) AddChange("TTT2 Base - v0.5.5b", [[ <h2>New:</h2> <ul> <li>Added convars to hide scoreboard badges</li> <li>A small text that explains the spectator mode</li> <li>Weapon pickup notifications are now moved to the new HUD system</li> <li>Weapon pickup notifications support now pure_skin</li> <li>New shadowed text rendering with font mipmapping</li> </ul> <br> <h2>Improved:</h2> <ul> <li>Refactored the code to move all language strings into the language files</li> </ul> <br> <h2>Fixed:</h2> <ul> <li>Fixed the reroll per buy bug</li> <li>Fixed HUD switcher bug, now infinite amounts of HUDs are supported</li> <li>Fixed the outline border of the sidebar beeing wrong</li> <li>Fixed problem with the element restriction</li> </ul> ]], os.time({year = 2019, month = 07, day = 07})) AddChange("TTT2 Base - v0.5.6b", [[ <h2>New:</h2> <ul> <li>Marks module</li> <li>New sprint and stamina hooks for add-ons</li> <li>Added a documentation of TTT2</li> <li>Added GetColumns function for the scoreboard</li> </ul> <br> <h2>Improved:</h2> <ul> <li>Restrict HUD element movement when element is not rendered</li> <li>Sidebar icons now turn black if the hudcolor is too bright</li> <li>Binding functions are no longer called when in chat or in console</li> <li>Improved the functionality of the binding system</li> <li>Improved rendering of overhead role icons</li> <li>Improved equipment searching</li> <li>Improved the project structure</li> <li>Improved shadow color for dark texts</li> <li>Some small performance improvements</li> <li>Removed some unnecessary debug messages</li> <li>Updated the TTT2 .fgd file</li> </ul> <br> <h2>Fixed:</h2> <ul> <li>Fixed the shop bug that occured since the new GMod update</li> <li>Fixed search sometimes not working</li> <li>Fixed a shop reroll bug</li> <li>Fixed GetAvoidDetective compatibility</li> <li>Fixel two cl_radio errors</li> <li>Fixed animation names</li> <li>Fixed wrong karma print</li> <li>Fixed a language module bug</li> <li>Fixed an inconsistency in TellTraitorsAboutTraitors function</li> <li>Fixed the empty weaponswitch bug on first spawn</li> <li>Fixed an error in the shadow rendering of a font</li> <li>Small bugfixes</li> </ul> ]], os.time({year = 2019, month = 09, day = 03})) AddChange("TTT2 Base - v0.5.6b-h1 (Hotfix)", [[ <h2>Fixed:</h2> <ul> <li>Traitor shop bug (caused by the september'19 GMod update)</li> <li>ShopEditor bugs and added a response for non-admins</li> <li>Glitching head icons</li> </ul> ]], os.time({year = 2019, month = 09, day = 06})) AddChange("TTT2 Base - v0.5.7b", [[ <h2>New:</h2> <ul> <li>New Loadout Give/Remove functions to cleanup role code and fix item raceconditions</li> <ul> <li>Roles now always get their equipment on time</li> <li>On role changes, old equipment gets removed first</li> </ul> <li>New armor system</li> <ul> <li>Armor is now displayed in the HUD</li> <li>Previously it was a simple stacking percetual calculation, which got stupid with multiple armor effects. Three times armoritems with 70% damage each resulted in 34% damage recveived</li> <li>The new system has an internal armor value that is displayed in the HUD</li> <li>It works basically the same as the vanilla system, only the stacking is a bit different</li> <li>Reaching an armor value of 50 (by default) increases its strength</li> <li>Armor depletes over time</li> </ul> <li>Allowed items to be bought multiple times, if <i>.limited</i> is set to <i>true</i></li> </ul> <br> <h2>Improved:</h2> <ul> <li>Dynamic loading of role icons</li> <li>Improved performance slightly</li> <li>Improved code consistency</li> <li>Caching role icons in <i>ROLE.iconMaterial</i> to prevent recreation of icon materials</li> <li>Improved bindings menu and added language support</li> <li>Improved SQL module</li> <li>Improved radar icon</li> <li>Made parameterized overheadicon function callable</li> <li>Improved codereadablity by refactoring huge parts</li> </ul> <br> <h2>Fixed:</h2> <ul> <li>Fixed sometimes unavailable shops even if set</li> <li>Team confirmation convar issue in network-syncing</li> <li>Reset radar timer on item remove, fixes problems with rolechanges</li> <li>Fixed an exploitable vulnerability</li> </ul> ]], os.time({year = 2019, month = 10, day = 06})) AddChange("TTT2 Base - v0.6b", [[ <h2>New:</h2> <ul> <li>Added new weapon switch system</li> <ul> <li>Players can now manually pick up focused weapons</li> <li>If the slot is blocked, the current weapon is automatically dropped</li> <li>Added new convar to prevent auto pickup: <i>ttt_weapon_autopickup (default: 1)</i></li> </ul> <li>Added new targetID system</li> <ul> <li>Looking at entities shows now more detailed ans structured info</li> <li>Integrated into the new weapon switch system</li> <li>Supports all TTT entities by default</li> <li>Supports doors</li> <li>Added a new hook to add targetID support to custom entities: <i>TTTRenderEntityInfo</i></li> </ul> <li>Added the outline module for better performance</li> <li><i>TTT2DropAmmo</i> hook to prevent/change the ammo drop of a weapon</li> <li>Added new HUD element: the eventpopup</li> <li>Added a new <i>TTT2PlayerReady</i> hook that is called once a player is ingame and can move around</li> <li>Added new removable decals</li> <li>Added a new default loading screen</li> <li>Added new convar to allow Enhanced Player Model Selector to overwrite TTT2 models: <i>ttt_enforce_playermodel (default: 1)</i></li> <li>Added new hooks to jam the chat</li> <li>Allow any key double tap sprint</li> <li>Regenerate sprint stamina after a delay if exhausted</li> <li>Moved voice bindings to the TTT2 binding system (F1 menu)</li> <li>Added new voice and text chat hooks to prevent the usage in certain situations</li> <li>Added new client only convar (F1->Gameplay->Hold to aim) to change to a "hold rightclick to aim" mode</li> <li>Added a new language file system for addons, language files have to be in <i>lua/lang/<the_language>/<addon>.lua</i></li> <li>New network data system including network data tables to better manage state updates on different clients</li> </ul> <br> <h2>Improved:</h2> <ul> <li>Microoptimization to improve code performance</li> <li>Improved the icon rendering for the pure_skin HUD</li> <li>Improved multi line text rendering in the MSTACK</li> <li>Improved role color handling</li> <li>Improved language (german, english, russian)</li> <li>Improved traitor buttons</li> <ul> <li>By default only players in the traitor team can use them</li> <li>Each role has a convar to enable traitor button usage for them - yes, innocents can use traitor buttons if you want to</li> <li>There is an admin mode to edit each button individually</li> <li>Uses the new targetID</li> </ul> <li>Improved damage indicator overlay with customizability in the F1 settings</li> <li>Improved hud help font</li> <li>Added a new flag to items to hide them from the bodysearch panel</li> <li>Moved missing hardcoded texts to language files</li> </ul> <br> <h2>Fixed:</h2> <ul> <li>Fixed a bug with baserole initialization</li> <li>Small other bugfixes</li> <li>added legacy supported for limited items</li> <li>Fixed C4 defuse for non-traitor roles</li> <li>Fixed radio, works now for all roles</li> <li>Restricted huds are hidden in HUD Switcher</li> <li>Fixed ragdoll skins (hairstyles, outfits, ...)</li> <li>Prevent give_equipment timer to block the shop in the next round</li> <li>Fix sprint consuming stamina when there is no move input</li> <li>Fix confirmation of players with no team</li> <li>Fix voice still sending after death</li> </ul> ]], os.time({year = 2020, month = 02, day = 16})) AddChange("TTT2 Base - v0.6.1b", [[ <h2>Fixed:</h2> <ul> <li>Fixed a bug with the spawn wave interval</li> </ul> ]], os.time({year = 2020, month = 02, day = 17})) AddChange("TTT2 Base - v0.6.2b", [[ <h2>Fixed:</h2> <ul> <li>Increased the maximum number of roles that can be used. (Fixes weird role issues with many roles installed)</li> </ul> ]], os.time({year = 2020, month = 03, day = 1})) AddChange("TTT2 Base - v0.6.3b", [[ <h2>New:</h2> <ul> <li>Added a Polish translation (Thanks @Wukerr)</li> <li>Added fallback icons for equipment</li> </ul> <br> <h2>Fixed:</h2> <ul> <li>Fix <i>body_found</i> for bots</li> <li>Fix NWVarSyncing when using <i>TTT2NET:Set()</i></li> </ul> ]], os.time({year = 2020, month = 03, day = 05})) AddChange("TTT2 Base - v0.6.4b", [[ <h2>New:</h2> <ul> <li>Added an Italian translation (Thanks @PinoMartirio)</li> </ul> <br> <h2>Fixed:</h2> <ul> <li>Fixed a rare bug where the player had the default GMod sprint on top of the TTT2 sprint</li> <li>Fixed some convars that did not save in ulx by removing them all from the gamemode file</li> <li>Fixed a bug that happened when TTT2 is installed but not the active gamemode</li> <li>Fixed a few Polish language strings</li> </ul> ]], os.time({year = 2020, month = 04, day = 03})) AddChange("TTT2 Base - v0.7.0b", [[ <h2>New:</h2> <ul> <li>Added two new convars to change the behavior of the armor</li> <li>Added two new convars to change the confirmation behaviour</li> <li>Added essential items: 8 different types of items that are often used in other addons. You can remove them from the shop if you don't like them.</li> <li>Added a new HUD element to show information about an ongoing revival to the player that is revived</li> <li>Added the possibility to change the radar time</li> <li>Added a few new modules that are used by TTT2 and can be used by different addons</li> </ul> <br> <h2>Improved:</h2> <ul> <li>Updated addon checker list</li> <li>Migrated the HUDManager settings to the new network sync system</li> <li>Reworked the old DNA Scanner and replaced it with an improved version</li> <ul> <li>New world- and viewmodel with an interactive screen</li> <li>Removed the overcomplicated UI menu (simple handling with default keys instead)</li> <li>The new default scanner behavior shows the direction and distance to the target</li> </ul> <li>Changed TargetID colors for confirmed bodies</li> <li>Improved the player revival system</li> <ul> <li>Revive makes now sure the position is valid and the player is not stuck in the wall</li> <li>All revival related messages are now localized</li> <li>Integration with the newly added revival HUD element</li> </ul> <li>Improved the player spawn handling, no more invalid spawn points where a player will be stuck or spawn in the air and fall to their death</li> <li>Refactored the role selection code to reside in its own module and cleaned up the code</li> <li>Improved the round end screen to support longer round end texts</li> </ul> <br> <h2>Fixed:</h2> <ul> <li>Fixed round info (the top panel with the miniscoreboard) being displayed in other HUDs</li> <li>Fixed an error with the pickup system in singleplayer</li> <li>Fixed propsurfing with the magneto stick</li> <li>Fixed healthstation TargetID text</li> <li>Fixed keyinfo for doors where no key can be used</li> <li>Fixed role selection issues with subroles not properly replacing their baserole etc</li> <li>Fixed map lock/unlock trigger of doors not updating targetID</li> <li>Fixed roles having sometimes the wrong radar color</li> <li>Fixed miniscoreboard update issue and players not getting shown when entering force-spec mode</li> </ul> ]], os.time({year = 2020, month = 06, day = 01})) AddChange("TTT2 Base - v0.7.1b", [[ <h2>Fixed:</h2> <ul> <li>Fixed max roles / max base roles interaction with the roleselection. Also does not crash with values != 0 anymore.</li> </ul> ]], os.time({year = 2020, month = 06, day = 02})) AddChange("TTT2 Base - v0.7.2b", [[ <h2>New:</h2> <ul> <li>Added Hooks to the targetID system to modify the displayed data</li> <li>Added Hooks to interact with door destruction</li> <li>Added a new function to force a new radar scan</li> <li>Added a new convar to change the default radar time for players without custom radar times: <i>ttt2_radar_charge_time</i></li> <li>Added a new client ConVar <i>ttt_crosshair_lines</i> to add the possibility to disable the crosshair lines</li> </ul> <br> <h2>Improved:</h2> <ul> <li>Moved the disguiser icon to the status system to be only displayed when the player is actually disguised</li> <li>Reworked the addonchecker and added a command to execute the checker at a later point</li> <li>Updated Italian translation (Thanks @ThePlatinumGhost)</li> <li>Removed Is[ROLE] functions of all roles except default TTT ones</li> <li>ttt_end_round now resets when the map changes</li> <li>Reworked the SWEP HUD help (legacy function SWEP:AddHUDHelp is still supported)</li> <li>Players who disconnect now leave a corpse</li> </ul> <br> <h2>Fixed:</h2> <ul> <li>Fixed shadow texture of the "Pure Skin HUD" for low texture quality settings</li> <li>Fixed inno subrole upgrading if many roles are installed</li> <li>Fixed and improved the radar role/team modification hook</li> <li>Fixed area portals on servers for destroyed doors</li> <li>Fixed revive fail function reference reset</li> <li>Removed the DNA Scanner hudelement for spectators</li> <li>Fixed the image in the confirmation notification whenever a bot's corpse gets identified</li> <li>Fixed bad role selection due to RNG reseeding</li> <li>Fixed missing role column translation</li> <li>Fixed viewmodel not showing correct hands on model change</li> </ul> ]], os.time({year = 2020, month = 06, day = 26})) AddChange("TTT2 Base - v0.7.3b", [[ <h2>New:</h2> <ul> <li>Added a new custom file loader that loads lua files from <i>lua/terrortown/autorun/</i></li> <ul> <li>it basically works the same as the native file loader</li> <li>there are three subfolders: <i>client</i>, <i>server</i> and <i>shared</i></li> <li>the files inside this folder are loaded after all TTT2 gamemode files and library extensions are loaded</li> </ul> <li>Added Spanish version for base addon (by @Tekiad and @DennisWolfgang)</li> <li>Added Chinese Simplified translation (by @TheOnly8Z)</li> <li>Added double-click buying</li> <li>Added a default avatar for players and an avatar for bots</li> </ul> <br> <h2>Improved:</h2> <ul> <li>Roles are now only getting synced to clients if the role is known, not just the body being confirmed</li> <li>Airborne players can no longer replenish stamina</li> <li>Detective overhead icon is now shown to innocents and traitors</li> <li>moved language files from <i>lua/lang/</i> to <i>lua/terrortown/lang</i></li> <li>Stopped teleporting players to players they're not spectating if they press the "duck"-Key while roaming</li> <li>Moved shop's equipment list generation into a coroutine</li> <li>Removed TTT2PlayerAuthedCacheReady hook</li> <li>Internal changes to the b-draw library for fetching avatars</li> </ul> <br> <h2>Fixed:</h2> <ul> <li>Fixed death handling spawning multiple corpses when killed multiple times in the same frame</li> <li>Radar now shows bombs again, that do not have the team property set</li> <li>Fix HUDManager not saving forcedHUD and defaultHUD values</li> <li>Fixed wrong parameter default in <i>EPOP:AddMessage</i> documentation</li> <li>Fixed shop switching language issue</li> <li>Fixed shop refresh activated even not buyable equipments</li> <li>Fixed wrong shop view displayed as forced spectator</li> </ul> ]], os.time({year = 2020, month = 08, day = 09})) AddChange("TTT2 Base - v0.7.4b", [[ <h2>New:</h2> <ul> <li>Added ConVar to toggle double-click buying</li> <li>Added Japanese translation (by @Westoon)</li> <li>Added <i>table.ExtractRandomEntry(tbl, filterFn)</i> function</li> <li>Added a team indicator in front of every name in the scoreboard (just known teams will be displayed)</li> <li>Added a hook <i>TTT2ModifyCorpseCallRadarRecipients</i> that is called once "call detective" is pressed</li> </ul> <br> <h2>Improved:</h2> <ul> <li>The weapon pickup system has been improved to increase stability and remove edge cases in temporary weapon teleportation</li> <li>Updated Spanish translation (by @DennisWolfgang)</li> </ul> <br> <h2>Fixed:</h2> <ul> <li>Fixed foregoing avatar fetch fix</li> <li>Fixed HUD savingKeys variable not being unique across all HUDs</li> <li>Fixed drawing web images, seamless web images and avatar images</li> <li>Fixed correctly saving setting a bind to NONE, while a default is defined</li> <li>Fixed a weapon pickup targetID bug where the +use key was displayed even though pickup has its own keybind</li> <li>Fixed DNA scanner crash if using an old/different weapon base</li> <li>Fixed rare initialization bug in the speed calculation when joining as a spectator</li> </ul> ]], os.time({year = 2020, month = 09, day = 28})) AddChange("TTT2 Base - v0.8.0b", [[ <h2>New:</h2> <ul> <li>Added new vgui system with new F1 menu</li> <li>Introduced a global scale factor based on screen resolution to scale HUD elements accordingly</li> <li>Added automatical scale factor change on resolution change that works even if the resolution was changed while TTT2 wasn't loaded</li> <li>Added Drag&Drop role layering VGUI (preview), accessible with the console command <i>ttt2_edit_rolelayering</i></li> <li>Added a new event system</li> <li>Credits can now be transferred across teams and from roles whom the recipient does not know</li> </ul> <br> <h2>Improved:</h2> <ul> <li>TargetID text is now scaled with the global scale factor</li> <li>Removed C4 defuse restriction for teammates</li> <li>Changed the language identifiers to generic english names</li> <li>Updated Simplified Chinese localization (by @TheOnly8Z)</li> <li>Updated Italian localization (by @ThePlatynumGhost)</li> <li>Updated English localization (by @Satton2)</li> <li>Updated Russian localization (by @scientistnt and @Satton2)</li> <li>Updated German translation (by @Creyox)</li> </ul> <br> <h2>Fixed:</h2> <ul> <li>Fixed weapon pickup bug, where weapons would not get dropped but stayed in inventory</li> <li>Fixed a roleselection bug, where forced roles would not be deducted from the available roles</li> <li>Fixed a credit award bug, where detectives would receive a pointless notification about being awarded with 0 credits</li> <li>Fixed a karma bug, where damage would still be reduced even though the karma system was disabled</li> <li>Fixed a roleselection bug, where invalid layers led to skipping the next layer too</li> <li>Fixed Magneto Stick ragdoll pinning instructions not showing for innocents when <i>ttt_ragdoll_pinning_innocents</i> is enabled</li> <li>Fixed a bug where the targetID info broke if the pickup key is unbound</li> </ul> ]], os.time({year = 2021, month = 02, day = 06})) AddChange("TTT2 Base - v0.8.1b", [[ <h2>Fixed:</h2> <ul> <li>Fixed inheriting from the same base using the classbuilder in different folders</li> </ul> ]], os.time({year = 2021, month = 02, day = 19})) AddChange("TTT2 Base - v0.8.2b", [[ <h2>Improved:</h2> <ul> <li>Added global alias for IsOffScreen function to util.IsOffScreen</li> <li>Updated Japanese localization (by @Westoon)</li> <li>Moved rendering modules to libraries</li> <li>Assigned PvP category to the gamemode.</li> </ul> <h2>Fixed:</h2> <ul> <li>TTT: fix instant reload of dropped weapon (by @svdm)</li> <li>TTT: fix ragdoll pinning HUD for innocents (by @Flapchik)</li> <li>Fixed outline library not working</li> </ul> ]], os.time({year = 2021, month = 03, day = 25})) AddChange("TTT2 Base - v0.9.0b", [[ <h2>Added:</h2> <ul> <li>All new roundend menu</li> <ul> <li>new info panel that shows detailed role distribution during the round</li> <li>info panel also states detailed score events</li> <li>new timeline that displays the events that happened during the round</li> <li>added two new round end conditions: `time up` and `no one wins`</li> </ul> <li>Added `ROLE_NONE` (ID `3` by default)</li> <ul> <li>Players now default to `ROLE_NONE` instead of `ROLE_INNOCENT`</li> <li>Enables the possibility to give Innocents access to a custom shop (`shopeditor`)</li> </ul> <li>Karma now stores changes</li> <ul> <li>Is shown in roundend menu</li> </ul> <li>Added a new hook `TTT2ModifyLogicCheckRole` that can be used to modify the tested role for map related role checks</li> <li>Added the ConVar `ttt2_random_shop_items` for the number of items in the randomshop</li> <li>Added per-player voice control by hovering over the mute icon and scrolling</li> </ul> <h2>Fixed</h2> <ul> <li>Updated French translation (by @MisterClems)</li> <li>Fixed IsOffScreen function being global for compatibility</li> <li>Fixed a German translation string (by @FaRLeZz)</li> <li>Fixed a Polish translation by adding new lines (by @Wuker)</li> <li>Fixed a data initialization bug that appeared on the first (initial) spawn</li> <li>Fixed silent Footsteps, while crouched bhopping</li> <li>Fixed issue where base innocents could bypass the TTT2AvoidGeneralChat and TTT2AvoidTeamChat hooks with the team chat key</li> <li>Fixed issue where roles with unknownTeam could see messages sent with the team chat key</li> <li>Fixed the admin section label not being visible in the main menu</li> <li>Fixed the auto resizing of the buttons based on the availability of a scrollbar not working</li> <li>Fixed reopening submenus of the legacy addons in F1 menu not working</li> <li>TTT: Fixed karma autokick evasion</li> <li>TTT: Fixed karma being applied to weapon damage even though karma is disabled</li> </ul> <h2>Changed</h2> <ul> <li>Microoptimization to improve code performance</li> <li>Converted `roles`, `huds`, `hudelements`, `items` and `pon` modules into libraries</li> <li>Moved `bind` library to the libraries folder</li> <li>Moved favorites functions for equipment to the equipment shop and made them local functions</li> <li>Code cleanup and removed silly negations</li> <li>Extended some ttt2net functions</li> <li>Changed `bees` win to `nones` win</li> <li>By default all evil roles are now counted as traitor roles for map related checks</li> <li>Changed the ConVar `ttt2_random_shops` to only disable the random shop (if set to `0`)</li> <li>Shopeditor settings are now available in the F1 Menu</li> <li>Moved the F1 menu generating system from a hook based system to a file based system</li> <ul> <li>removed the hooks `TTT2ModifyHelpMainMenu` and `TTT2ModifyHelpSubMenu`</li> <li>menus are now generated based on files located in `lua/terrortown/menus/gamemode/`</li> <li>submenus are generated from files located in folders with the menu name</li> </ul> <li>Menus without content are now always hidden in the main menu</li> <li>Moved Custom Shopeditor and linking shop to roles to the F1 menu</li> <li>Moved inclusion of cl_help to the bottom as nothing depends on it, but menus created by it could depend on other client files</li> <li>Shopeditor equipment is now available in F1 menu</li> <li>Moved the role layering menu to the F1 menu (administration submenu)</li> <ul> <li>removed the command `ttt2_edit_rolelayering`</li> </ul> <li>moved the internal path of `lang/`, `vskin/` and `events/` (this doesn't change anything for addons)</li> <li>Sort teammates first in credit transfer selection and add an indicator to them</li> </ul> <h2>Removed</h2> <ul> <li>Removed the custom loading screen (GMOD now only accepts http(s) URLs for sv_loadingurl)</li> </ul> <h2>Breaking Changes</h2> <ul> <li>Adjusted `Player:HasRole()` and `Player:HasTeam()` to support simplified role and team checks (no parameter are supported anymore, use `Player:GetRole()` or `Player:GetTeam()` instead)</li> <li>Moved global roleData to the `roles` library (e.g. `INNOCENT` to `roles.INNOCENT`). `INNOCENT`, `TRAITOR` etc. is not supported anymore. `ROLE_<ROLENAME>` is still supported and won't be changed.</li> <li>Shopeditor function `ShopEditor.ReadItemData()` now only updates a number of key-parameters, must be given as UInt. Messages were changed accordingly (`TTT2SESaveItem`,`TTT2SyncDBItems`)</li> <li>Equipment shop favorite functions are now local and not global anymore (`CreateFavTable`, `AddFavorite`, `RemoveFavorite`, `GetFavorites` & `IsFavorite`)</li> </ul> ]], os.time({year = 2021, month = 06, day = 19})) AddChange("TTT2 Base - v0.9.1b", [[ <h2>Fixed</h2> <ul> <li>Fixed shop convars not being shared / breaking the shop</li> </ul> ]], os.time({year = 2021, month = 06, day = 19})) AddChange("TTT2 Base - v0.9.2b", [[ <h2>Fixed</h2> <ul> <li>Fixed low karma autokick convar</li> <li>Fixed multi-layer inheritance by introducing a recursion based approach</li> </ul> ]], os.time({year = 2021, month = 06, day = 20})) --- -- run hook for other addons to add their changelog as well -- @realm client hook.Run("TTT2AddChange", changes, currentVersion) end --- -- @realm client function GetSortedChanges() CreateChanges() -- sort changes list by date table.sort(changes, function(a, b) if a.date < 0 and b.date < 0 then return a.date < b.date else return a.date > b.date end end) return changes end net.Receive("TTT2DevChanges", function(len) if changesVersion:GetString() == GAMEMODE.Version then return end --ShowChanges() RunConsoleCommand("changes_version", GAMEMODE.Version) end)
---@class EquipGrow_Awaken ---@field curEquipData EquipMgr_EquipData 当前质点信息 ---@field openedFold EquipGrow_Awaken_FoldData 当前打开的折叠框 local EquipGrow_Awaken = DClass("EquipGrow_Awaken", BaseComponent) _G.EquipGrow_Awaken = EquipGrow_Awaken ---@class EquipGrow_Awaken_FoldData ---@field node table ---@field index number function EquipGrow_Awaken:ctor() self.messager = Messager.new(self) self.listSkillSlotItem = {} self.openedFold = {} end function EquipGrow_Awaken:initPrefab(prefab) self.equipCell = prefab end function EquipGrow_Awaken:addListener() self.messager:addListener(Msg.EQUIP_GROW_EQUIPDATA, self.onUpdateData) end function EquipGrow_Awaken:onDispose() self.messager:dispose() end function EquipGrow_Awaken:onStart() self:addListener() self:onInit() end function EquipGrow_Awaken:onInitUI() self:onUpdateUI() end function EquipGrow_Awaken:onInit() self:addEventHandler(self.nodes.btnClosePopups.onClick, self.onClosePopups) self.nodes.btnClosePopups.gameObject:SetActive(false) end ---@param data EquipMgr_EquipData function EquipGrow_Awaken:onUpdateData(data, updateUI) self.curEquipData = data if updateUI then self:onUpdateUI() end end function EquipGrow_Awaken:onUpdateUI() self:onClosePopups() self:showAwakenSkill() end ---显示技能框个数 function EquipGrow_Awaken:showAwakenSkill() self.nodes.prefabBtnAwake.gameObject:SetActive(false) self:clearAllSlotObjs() self.listSlot = {} local countSkills = self.curEquipData.skills and #self.curEquipData.skills or 0 for i = 1, countSkills do self:initSkillSlotUI(i) end end ---清理所有技能槽UI function EquipGrow_Awaken:clearAllSlotObjs() for key, value in pairs(self.listSkillSlotItem) do GameObject.Destroy(value) end self.listSkillSlotItem = {} end ---初始化技能槽 function EquipGrow_Awaken:initSkillSlotUI(index) local objSlot = GameObject.Instantiate(self.nodes.prefabBtnAwake.gameObject) objSlot.gameObject:SetActive(true) objSlot.transform:SetParent(self.nodes.parentAwakens) objSlot.transform.localScale = Vector3(1, 1, 1) objSlot.transform:GetComponent(typeof(RectTransform)).anchoredPosition3D = Vector3(220, 240 - 135 * (index - 1), 0) objSlot.name = string.format("SkillSlot_%d", index) self:updateSkillSlotUI(index, objSlot) table.insert(self.listSkillSlotItem, objSlot) end ---刷新技能槽位置 function EquipGrow_Awaken:updataSlotsPosition(ctrlIndex, isOpen) isOpen = false for index, value in ipairs(self.listSlot) do value.btnSelf:GetComponent(typeof(RectTransform)).anchoredPosition3D = Vector3(220, 240 - 135 * (index - 1), 0) value.nodeFold:SetActive(false) if index == ctrlIndex then value.nodeFold:SetActive(not value.isOpenedFold) isOpen = not value.isOpenedFold value.isOpenedFold = not value.isOpenedFold else value.isOpenedFold = false end if isOpen then self:resetSelectedData() if index > ctrlIndex then value.btnSelf:GetComponent(typeof(RectTransform)).anchoredPosition3D = Vector3(220, 240 - 135 * (index - 1) - 425, 0) elseif index == ctrlIndex then --value.nodeFold:SetActive(isOpen) else end end end end ---重置选中信息 function EquipGrow_Awaken:resetSelectedData() self.selectedEquipId = "" self.selectedItemId = 0 self.selectedHeroId = 0 end ---刷新技能槽UI function EquipGrow_Awaken:updateSkillSlotUI(index, node) local skillData = self.curEquipData.skills[index] local slotId = skillData.slotId local skillCache = {} for key, value in pairs(self.curEquipData.skillsCache) do if value.slotId == slotId then skillCache = value break end end local slotData = {} slotData.index = index slotData.btnSelf = node:GetComponent(typeof(Button)) local imgAdd = node.transform:Find("Image_Add") slotData.nodeAwakedSkill = node.transform:Find("Image_Awaked").gameObject slotData.nodeFold = node.transform:Find("Fold_Awaken").gameObject slotData.nodeFold:SetActive(false) slotData.isOpenedFold = false self:addEventHandler( slotData.btnSelf.onClick, function() if skillCache.skillId > 0 then MsgCenter.sendMessage(Msg.EQUIP_GROW_SHOWAWAKEN, true) else local isOpen = not slotData.isOpenedFold self:updataSlotsPosition(index, not slotData.isOpenedFold) --slotData.isOpenedFold = not slotData.isOpenedFold if isOpen then self:setSlotFoldUI(slotData.nodeFold, index) end end end ) imgAdd.gameObject:SetActive(skillData.skillId <= 0) slotData.nodeAwakedSkill.gameObject:SetActive(skillData.skillId > 0) if skillData.skillId > 0 then self:setSkillAwakedSlotUI(slotData.nodeAwakedSkill, skillData) end table.insert(self.listSlot, slotData) end ---设置已有技能的技能槽UI ---@param data EquipMgr_AwakeSkill function EquipGrow_Awaken:setSkillAwakedSlotUI(node, data) local imgIcon = node.transform:Find("Image_Icon"):GetComponent(typeof(Image)) local txtName = node.transform:Find("Text_Name"):GetComponent(typeof(Text)) local txtAttr = node.transform:Find("Text_Attr"):GetComponent(typeof(Text)) local nodeBinding = node.transform:Find("Image_Binding").gameObject local imgHeroIcon = nodeBinding.transform:Find("Image_Icon"):GetComponent(typeof(Image)) local cfgSkill = Config.EquipSkill[data.skillId] EquipManager:setSkillIcon(self, imgIcon, cfgSkill.id) txtName.text = cfgSkill.name txtAttr.text = cfgSkill.Des nodeBinding:SetActive(data.heroId > 0) if data.heroId > 0 then EquipManager:setHeroIcon(self, imgHeroIcon, data.heroId) end end ---设置技能折叠槽UI function EquipGrow_Awaken:setSlotFoldUI(node, index) ---@type EquipMgr_AwakeSkill local data = self.curEquipData.skills[index] local btnSelectEquip = node.transform:Find("NodeAwaken/Button_SelectEquip"):GetComponent(typeof(Button)) local btnSelectHero = node.transform:Find("NodeAwaken/Button_SelectHero"):GetComponent(typeof(Button)) local btnAwake = node.transform:Find("NodeAwaken/Button_Awaken"):GetComponent(typeof(Button)) self:addEventHandler( btnSelectEquip.onClick, function() self:onOpenPopupEquips(self.curEquipData.gId) end ) self:addEventHandler( btnSelectHero.onClick, function() self:onOpenPopupHero(EquipMgr:getCurSelectHero().id) end ) self:addEventHandler( btnAwake.onClick, function() ---@type HERO_REQ_EQUIP_AWAKE local sdata = {} sdata.equipId = self.curEquipData.gId sdata.heroId = self.selectedHeroId sdata.slotId = data.slotId sdata.itemId = self.selectedItemId sdata.consumeEquipId = self.selectedEquipId if sdata.consumeEquipId == "" and sdata.itemId == 0 then return end EquipMgr:sendEquipAwake(sdata) end ) self.openedFold.node = node self.openedFold.index = index self.curEquipData.heroId = EquipMgr:getCurSelectHero().id self:setSeletedEquipUI(node, nil) self:setSelectedHeroUI(node, 0) --data.heroId) end ---设置选中的英雄头像 function EquipGrow_Awaken:setSelectedHeroUI(node, heroId) local nodeHero = node.transform:Find("NodeAwaken/Button_SelectHero").gameObject local nodeSelectEquip = node.transform:Find("NodeAwaken/Button_SelectEquip").gameObject local nodeAdd = nodeHero.transform:Find("Image_Add").gameObject local imgIcon = nodeHero.transform:Find("Image_Icon"):GetComponent(typeof(Image)) if EquipManager:checkCanBindingHeroByEquipGid(self.selectedEquipId, self.selectedItemId) or heroId > 0 then nodeHero:SetActive(true) nodeSelectEquip:GetComponent(typeof(RectTransform)).anchoredPosition3D = Vector3(-120, -280, 0) else nodeHero:SetActive(false) nodeSelectEquip:GetComponent(typeof(RectTransform)).anchoredPosition3D = Vector3(0, -280, 0) return end nodeAdd:SetActive(heroId <= 0) imgIcon.gameObject:SetActive(heroId > 0) if heroId > 0 then EquipManager:setHeroIcon(self, imgIcon, heroId) end end ---设置选中的消耗Ui ---@param data EquipGrow_Awaken_CostData function EquipGrow_Awaken:setSeletedEquipUI(node, data) local nodeSelect = node.transform:Find("NodeAwaken/Button_SelectEquip").gameObject local nodeAdd = nodeSelect.transform:Find("Image_Add").gameObject local nodeEquip = nodeSelect.transform:Find("Image_Equip").gameObject nodeAdd:SetActive(data == nil) nodeEquip:SetActive(data ~= nil) local imgCostIcon = node.transform:Find("NodeAwaken/Image_Cost/Image_Icon"):GetComponent(typeof(Image)) local txtCost = node.transform:Find("NodeAwaken/Image_Cost/Text"):GetComponent(typeof(Text)) txtCost.text = 0 if data == nil then return end local imgIcon = nodeEquip.transform:Find("Image_EquipIcon"):GetComponent(typeof(Image)) local imgStage = nodeEquip.transform:Find("Image_Stage"):GetComponent(typeof(Image)) local txtPlace = nodeEquip.transform:Find("Image_Place/Text_Place"):GetComponent(typeof(Text)) local txtLv = nodeEquip.transform:Find("Image_Lv/Text"):GetComponent(typeof(Text)) for i = 1, 6 do local starObj = nodeEquip.transform:Find("Stars/Image" .. i).gameObject starObj:SetActive(i <= data.star) end if data.isEquip then local cfg = Config.Equip[data.cId] EquipManager:setEquipIcon(self, imgIcon, data.cId) EquipManager:setQuility(self, imgStage, cfg.star, EquipManager.STAGE_TYPE.TITLE) txtPlace.text = EquipManager.NAME_PLACE[cfg.item_position] txtLv.text = string.format("Lv.%d", data.cLv) txtCost.text = cfg.gold else ---@type BagMgr_BagItemInfo local itemData = BagMgr:getItemDataByGid(data.gId) local cfg = BagManager.getItemConfigDataById(itemData.cId) BagManager.setItemIcon(self, imgIcon, itemData.cId) EquipManager:setQuility(self, imgStage, cfg.star, EquipManager.STAGE_TYPE.BG_CUBE) txtPlace.text = "" txtLv.text = "" txtCost.text = 0 end end --关闭弹框 function EquipGrow_Awaken:onClosePopups() self.nodes.btnClosePopups.gameObject:SetActive(false) self.nodes.popupEquips:SetActive(false) self.nodes.popupHero.gameObject:SetActive(false) end ---打开消耗道具选择框 function EquipGrow_Awaken:onOpenPopupEquips(gId) self.nodes.btnClosePopups.gameObject:SetActive(true) self.nodes.popupEquips:SetActive(true) local listCostItems = EquipManager:getCostAwakeShows(gId) self.nodes.contentEquip:InitPool( #listCostItems, function(index, obj) local gIdShow = listCostItems[index] local isEquip = false ---@type EquipMgr_EquipData local equipData = EquipMgr:getEquipDataByGid(gIdShow) if equipData == nil then isEquip = false else isEquip = true end local selectNode = obj.transform:Find("Image_Select").gameObject selectNode:SetActive(false) local imgIcon = obj.transform:Find("Image_Icon"):GetComponent(typeof(Image)) local imgStage = obj.transform:Find("Image_Quilty"):GetComponent(typeof(Image)) local txtPlace = obj.transform:Find("Image_Place/Text_Place"):GetComponent(typeof(Text)) local txtLv = obj.transform:Find("Image_Lv/Text_Lv"):GetComponent(typeof(Text)) local imgStageIcon = obj.transform:Find("Tage/Image1"):GetComponent(typeof(Image)) local imgLock = obj.transform:Find("Image_Lock").gameObject local awake1 = obj.transform:Find("Image_Awaken1").gameObject local awake2 = obj.transform:Find("Image_Awaken2").gameObject imgStageIcon.gameObject:SetActive(isEquip) awake1:SetActive(isEquip) awake2:SetActive(isEquip) imgLock:SetActive(isEquip) local btnSelf = obj:GetComponent(typeof(Button)) ---@type EquipGrow_Awaken_CostData local data = {} data.gId = gIdShow data.isEquip = isEquip imgStageIcon.gameObject:SetActive(isEquip) if isEquip then local cfg = Config.Equip[equipData.cId] data.cId = equipData.cId data.cLv = equipData.lv data.star = cfg.star data.quality = equipData.quality local cpt_Equip = self:createComponent(obj.gameObject, Equip_ItemCell) cpt_Equip:onUpdateUI(equipData) else ---@type BagMgr_BagItemInfo local itemData = BagMgr:getItemDataByGid(gIdShow) local cfg = BagManager.getItemConfigDataById(itemData.cId) BagManager.setItemIcon(self, imgIcon, itemData.cId) EquipManager:setQuility(self, imgStage, cfg.star, EquipManager.STAGE_TYPE.BG_CUBE) txtPlace.text = "" txtLv.text = "" data.cLv = 0 data.cId = itemData.cId data.star = cfg.star data.quality = cfg.quality for i = 1, 6 do local starObj = obj.transform:Find("Stars/Image" .. i).gameObject starObj:SetActive(i <= data.star) end end self:addEventHandler( btnSelf.onClick, function() self:onSelectEquip(data) end ) end ) end ---打开英雄选择框 function EquipGrow_Awaken:onOpenPopupHero(oldHeroId) self.nodes.btnClosePopups.gameObject:SetActive(true) self.nodes.popupHero.gameObject:SetActive(true) local listHero = HeroMgr:getAllHeros(false) self.nodes.contentHero:InitPool( #listHero, function(index, obj) local dHero = listHero[index] local imgIcon = obj.transform:Find("Image_Icon"):GetComponent(typeof(Image)) local nodeCurrent = obj.transform:Find("Image_Current").gameObject local imgIconBg = obj.transform:Find("Image_IconBg"):GetComponent(typeof(Image)) local btnHero = obj:GetComponent(typeof(Button)) nodeCurrent:SetActive(dHero.id == oldHeroId) if imgIcon then EquipManager:setHeroIcon(self, imgIcon, dHero.id) EquipManager:setHeroTypeIcon(self, imgIconBg, dHero.id) end self:addEventHandler( btnHero.onClick, function() self:onSelectHero(dHero.id) self:onClosePopups() end ) end ) end ---选中绑定英雄 function EquipGrow_Awaken:onSelectHero(id) self.selectedHeroId = id self:setSelectedHeroUI(self.openedFold.node, id) end ---选中消耗的道具 ---@class EquipGrow_Awaken_CostData ---@field gId string ---@field cId number ---@field isEquip boolean ---@field cLv number ---@field star number ---@field quality number ---选中的消耗道具 ---@param data EquipGrow_Awaken_CostData function EquipGrow_Awaken:onSelectEquip(data) if data.isEquip then self.selectedEquipId = data.gId else self.selectedItemId = data.cId end local funcSelect = function() self:setSeletedEquipUI(self.openedFold.node, data) if EquipManager:checkCanBindingHeroByEquipGid(self.selectedEquipId, self.selectedItemId) then self:setSelectedHeroUI(self.openedFold.node, self.curEquipData.heroId) self.selectedHeroId = self.curEquipData.heroId else self:setSelectedHeroUI(self.openedFold.node, 0) end self:onClosePopups() end local equipData = EquipMgr:getEquipDataByGid(self.selectedEquipId) local isLockStar, des = EquipManager:checkEquipLockOrStar(equipData) if equipData and isLockStar == 1 then local tData = {} tData.title = "" tData.content = string.format(Lang(GL_EquipGrow_Intensify_QueRenXiao), des) --"确认消耗%s的装备吗?" tData.buttonNames = {Lang(GL_BUTTON_SURE), Lang(GL_BUTTON_CANNEL)} tData.buttonTypes = {1, 2} tData.callback = function(sort) if sort == 1 then funcSelect() end end MsgCenter.sendMessage(Msg.NOTIFY, tData) else funcSelect() end end
-- luacheck: globals love local Stack = require 'stack' local View = require 'view' _G.team = {} local _game local _stack _G.image = {} _G.contImg = 1 function love.load() _G.image[1] = love.graphics.newImage('assets/textures/conan.jpg') _G.image[2] = love.graphics.newImage('assets/textures/redsonja.jpg') _G.image[3] = love.graphics.newImage('assets/textures/icegiant.jpg') _G.image[4] = love.graphics.newImage('assets/textures/gameOver.jpg') _G.gameOver = false _game = { view = View() } _stack = Stack(_game) _stack:push('choose_quest') end function love.update(dt) local g = love.graphics g.setBackgroundColor(0,0,250) _stack:update(dt) _game.view:update(dt) if _G.gameOver then print("GAME OVER") --love.event.quit() end end function love.draw() local g = love.graphics if _G.gameOver == false then g.draw(_G.image[_G.contImg]) _game.view:draw() else g.draw(_G.image[4]) _game.view:draw() end end for eventname, _ in pairs(love.handlers) do love[eventname] = function (...) _stack:forward(eventname, ...) end end
local net = require("net") local log = require("log") local syslog = { protocol = "syslog", } autoload(syslog, "net.syslog", "Server") function syslog.log(msg) log.debug(textutils.serialize(msg)) net.broadcast({ src=net.hostname(), msg=msg, }, syslog.protocol) --print(msg) end return syslog
local dailyWithdraws = {} QBCore.Functions.CreateCallback('qb-debitcard:server:requestCards', function(source, cb) local src = source local xPlayer = QBCore.Functions.GetPlayer(src) local visas = self.Functions.GetItemsByName('visa') local masters = self.Functions.GetItemsByName('mastercard') local cards = {} if visas ~= nil and masters ~= nil then for _, v in visas do table.insert(cards, v.info) end for _, v in masters do table.insert(cards, v.info) end end return cards end) QBCore.Functions.CreateCallback('qb-debitcard:server:deleteCard', function(source, cb, data) local cn = data.cardNumber local ct = data.cardType local src = source local xPlayer = QBCore.Functions.GetPlayer(src) local found = xPlayer.Functions.GetCardSlot(cn, ct) if found ~= nil then xPlayer.Functions.RemoveItem(ct, 1, found) cb(true) else cb(false) end end) function tprint (t, s) for k, v in pairs(t) do local kfmt = '["' .. tostring(k) ..'"]' if type(k) ~= 'string' then kfmt = '[' .. k .. ']' end local vfmt = '"'.. tostring(v) ..'"' if type(v) == 'table' then tprint(v, (s or '')..kfmt) else if type(v) ~= 'string' then vfmt = tostring(v) end print(type(t)..(s or '')..kfmt..' = '..vfmt) end end end RegisterCommand('atm', function(source, args, rawCommand) local src = source local xPlayer = QBCore.Functions.GetPlayer(src) local visas = xPlayer.Functions.GetItemsByName('visa') local masters = xPlayer.Functions.GetItemsByName('mastercard') local cards = {} if visas ~= nil and masters ~= nil then for _, v in pairs(visas) do local info = v.info local cardNum = info.cardNumber local cardHolder = info.citizenid local xCH = QBCore.Functions.GetPlayerByCitizenId(cardHolder) if xCH ~= nil then if xCH.PlayerData.charinfo.card ~= cardNum then info.cardActive = false end else local player = exports.ghmattimysql:executeSync('SELECT charinfo FROM players WHERE citizenid=@citizenid', {['@citizenid'] = info.citizenid}) local xCH = json.decode(player[1].charinfo) if xCH.card ~= cardNum then info.cardActive = false end end table.insert(cards, v.info) end for _, v in pairs(masters) do local info = v.info local cardNum = info.cardNumber local cardHolder = info.citizenid local xCH = QBCore.Functions.GetPlayerByCitizenId(cardHolder) if xCH ~= nil then if xCH.PlayerData.charinfo.card ~= cardNum then info.cardActive = false end else local player = exports.ghmattimysql:executeSync('SELECT charinfo FROM players WHERE citizenid=@citizenid', {['@citizenid'] = info.citizenid}) xCH = json.decode(player[1].charinfo) if xCH.card ~= cardNum then info.cardActive = false end end table.insert(cards, v.info) end end TriggerClientEvent('qb-atms:client:loadATM', src, cards) end) Citizen.CreateThread(function() while true do Wait(3600000) dailyWithdraws = {} TriggerClientEvent('QBCore:Notify', -1, "Daily Withdraw Limit Reset", "success") end end) RegisterServerEvent('qb-atms:server:doAccountWithdraw') AddEventHandler('qb-atms:server:doAccountWithdraw', function(data) if data ~= nil then local src = source local xPlayer = QBCore.Functions.GetPlayer(src) local cardHolder = data.cid local xCH = QBCore.Functions.GetPlayerByCitizenId(cardHolder) if not dailyWithdraws[cardHolder] then dailyWithdraws[cardHolder] = 0 end local dailyWith = tonumber(dailyWithdraws[cardHolder]) + tonumber(data.amount) if dailyWith < 5000 then local banking = {} if xCH ~= nil then local bank = xCH.Functions.GetMoney('bank') local bankCount = xCH.Functions.GetMoney('bank') - tonumber(data.amount) if bankCount > 0 then xCH.Functions.RemoveMoney('bank', tonumber(data.amount)) xPlayer.Functions.AddMoney('cash', tonumber(data.amount)) dailyWithdraws[cardHolder] = dailyWithdraws[cardHolder] + tonumber(data.amount) TriggerClientEvent('QBCore:Notify', src, "Withdraw $" .. data.amount .. ' from credit card. Daily Withdraws: ' .. dailyWithdraws[cardHolder], "success") else TriggerClientEvent('QBCore:Notify', src, "You cant go into minus in ATM.", "error") end banking['online'] = true banking['name'] = xCH.PlayerData.charinfo.firstname .. ' ' .. xCH.PlayerData.charinfo.lastname banking['bankbalance'] = xCH.Functions.GetMoney('bank') banking['accountinfo'] = xCH.PlayerData.charinfo.account banking['cash'] = xPlayer.Functions.GetMoney('cash') else local player = exports.ghmattimysql:executeSync('SELECT * FROM players WHERE citizenid=@citizenid', {['@citizenid'] = cardHolder}) local xCH = json.decode(player[1]) local bankCount = tonumber(xCH.money.bank) - tonumber(data.amount) if bankCount > 0 then xPlayer.Functions.AddMoney('cash', tonumber(data.amount)) xCH.money.bank = bankCount exports.ghmattimysql:execute('UPDATE players SET money=@money WHERE citizenid=@citizenid', {['@money'] = xCH.money, ['@citizenid'] = cardHolder}) dailyWithdraws[cardHolder] = dailyWithdraws[cardHolder] + tonumber(data.amount) TriggerClientEvent('QBCore:Notify', src, "Withdraw $" .. data.amount .. ' from credit card. Daily Withdraws: ' .. dailyWithdraws[cardHolder], "success") else TriggerClientEvent('QBCore:Notify', src, "You cant go into minus in ATM.", "error") end banking['online'] = false banking['name'] = xCH.charinfo.firstname .. ' ' .. xCH.charinfo.lastname banking['bankbalance'] = xCH.money.bank banking['accountinfo'] = xCH.charinfo.account banking['cash'] = xPlayer.Functions.GetMoney('cash') end TriggerClientEvent('qb-atms:client:updateBankInformation', src, banking) else TriggerClientEvent('QBCore:Notify', src, "You have reached the daily limit.", "error") end end end) QBCore.Functions.CreateCallback('qb-atms:server:loadBankAccount', function(source, cb, cid, cardnumber) local src = source local xPlayer = QBCore.Functions.GetPlayer(src) local cardHolder = cid local xCH = QBCore.Functions.GetPlayerByCitizenId(cardHolder) local banking = {} if xCH ~= nil then banking['online'] = true banking['name'] = xCH.PlayerData.charinfo.firstname .. ' ' .. xCH.PlayerData.charinfo.lastname banking['bankbalance'] = xCH.Functions.GetMoney('bank') banking['accountinfo'] = xCH.PlayerData.charinfo.account banking['cash'] = xPlayer.Functions.GetMoney('cash') else local player = exports.ghmattimysql:executeSync('SELECT * FROM players WHERE citizenid=@citizenid', {['@citizenid'] = cardHolder}) local xCH = json.decode(player[1]) banking['online'] = false banking['name'] = xCH.charinfo.firstname .. ' ' .. xCH.charinfo.lastname banking['bankbalance'] = xCH.money.bank banking['accountinfo'] = xCH.charinfo.account banking['cash'] = xPlayer.Functions.GetMoney('cash') end cb(banking) end)
package.path = package.path .. ";/libs/?.lua" local Logger = {} function Logger.log(msg) print(Logger.formattedLocalTime() .. " " .. msg) end function Logger.debug(msg) print(Logger.formattedLocalTime() .. " " .. msg) end function Logger.warn(msg) print(Logger.formattedLocalTime() .. " ! " .. msg) end function Logger.error(msg) print(Logger.formattedLocalTime() .. " E " .. msg) end function Logger.formattedLocalTime() local osTime = os.time("local") local hours = math.floor(osTime) local minutes = math.floor((osTime % 1) * 60) if minutes < 10 then minutes = "0" .. minutes end return "[" .. hours .. ":" .. minutes .. "]" end return Logger
--[[ Copyright 2020 Manticore Games, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] local API = {} -- nil RegisterResourceManager(table) [Client, Server] function API.RegisterResourceManager(functionTable, baseStats) if _G.APIResources then error("A game cannot have resource managers.") end _G.APIResources = functionTable API.BASE_DAMAGE = baseStats.BASE_DAMAGE API.BASE_MAX_HP = baseStats.BASE_MAX_HP API.BASE_WALK_SPEED = baseStats.BASE_WALK_SPEED API.DAMAGE_RESOURCE = baseStats.DAMAGE_RESOURCE API.MAX_HP_RESOURCE = baseStats.MAX_HP_RESOURCE API.SPEED_RESOURCE = baseStats.SPEED_RESOURCE end -- bool IsResourceManagerRegistered() [Client, Server] function API.IsResourceManagerRegistered() if _G.APIResources then return true end return false end -- table GetResourceInfo(string) [Client, Server] function API.GetResourceInfo(resource) if not _G.APIResources then warn("Cannot get the resource info without resource manager registered.") return nil end return _G.APIResources.GetResourceInfo(resource) end -- number, number, number GetResourceTier(string) [Client, Server] function API.GetResourceTier(resource, amount) if not _G.APIResources then warn("Cannot get the resource tier without resource manager registered.") return nil end return _G.APIResources.GetResourceTier(resource, amount) end -- table GetDamageValue(int) [Client, Server] function API.GetDamageValue(amount) if amount == 0 then return API.BASE_DAMAGE, 0 end local newAmount = math.ceil(.4 * math.log(amount ^ 21, 10)) return API.BASE_DAMAGE + newAmount, newAmount end -- table GetMaxWalkSpeed(int) [Client, Server] function API.GetMaxHP(amount) if amount == 0 then return API.BASE_MAX_HP, 0 end local newAmount = math.ceil(amount / 2) return math.ceil(API.BASE_MAX_HP + newAmount), newAmount end -- table GetMaxWalkSpeed(int) [Client, Server] function API.GetMaxWalkSpeed(amount) if amount == 0 then return API.BASE_WALK_SPEED, 0 end local newAmount = math.ceil(3 * math.log(amount ^ 15, 10)) return API.BASE_WALK_SPEED + newAmount, newAmount end -- table ClearResources(Player) [Server] function API.ClearResources(player) if not _G.APIResources then warn("Cannot clear player resources without resource manager registered.") return nil end return _G.APIResources.ClearResources(player) end return API
-- use different transfer functions in the hidden layer -- original model with Tanh() print('Module initiated:') module = nn.Sequential() module:add(nn.Convert('bchw', 'bf')) module:add(nn.Linear(1*28*28, 20)) module:add(nn.Tanh()) module:add(nn.Linear(20, 10)) module:add(nn.LogSoftMax()) module = module print(module) -- model with SoftSign() print('Module initiated:') module = nn.Sequential() module:add(nn.Convert('bchw', 'bf')) module:add(nn.Linear(1*28*28, 20)) module:add(nn.SoftSign()) module:add(nn.Linear(20, 10)) module:add(nn.LogSoftMax()) module = module print(module) -- model with LogSigmoid() print('Module initiated:') module = nn.Sequential() module:add(nn.Convert('bchw', 'bf')) module:add(nn.Linear(1*28*28, 20)) module:add(nn.LogSigmoid()) module:add(nn.Linear(20, 10)) module:add(nn.LogSoftMax()) module = module print(module) -- model with Sigmoid() print('Module initiated:') module = nn.Sequential() module:add(nn.Convert('bchw', 'bf')) module:add(nn.Linear(1*28*28, 20)) module:add(nn.Sigmoid()) module:add(nn.Linear(20, 10)) module:add(nn.LogSoftMax()) module = module print(module) -- model with HardTanh() print('Module initiated:') module = nn.Sequential() module:add(nn.Convert('bchw', 'bf')) module:add(nn.Linear(1*28*28, 20)) module:add(nn.HardTanh()) module:add(nn.Linear(20, 10)) module:add(nn.LogSoftMax()) module = module print(module)
if not (GetLocale() == "itIT") then return end local _, db = ...
workspace "CherriesX" architecture "x64" startproject "CherryJam" configurations { "Debug", "Release", "Distribution" } flags { "MultiProcessorCompile" } outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}" IncludeDirs = {}; IncludeDirs["CherriesSTL"] = "%{wks.location}/CherriesX/vendor/CherriesSTL/include" IncludeDirs["CherryMath"] = "%{wks.location}/CherriesX/vendor/CherryMath/include/CherryMath" IncludeDirs["GLFW"] = "%{wks.location}/CherriesX/vendor/GLFW/include" IncludeDirs["spdlog"] = "%{wks.location}/CherriesX/vendor/spdlog/include" IncludeDirs["glm"] = "%{wks.location}/CherriesX/vendor/glm" IncludeDirs["Glad"] = "%{wks.location}/CherriesX/vendor/Glad/include" IncludeDirs["ImGui"] = "%{wks.location}/CherriesX/vendor/ImGui" IncludeDirs["assimp"] = "%{wks.location}/CherriesX/vendor/assimp/include" IncludeDirs["yaml_cpp"] = "%{wks.location}/CherriesX/vendor/yaml-cpp/include" IncludeDirs["freetype"] = "%{wks.location}/CherriesX/vendor/freetype/include" IncludeDirs["msdf_atlas_gen"] = "%{wks.location}/CherriesX/vendor/msdf-atlas-gen" group "Dependencies" include "CherriesX/vendor/GLFW" include "CherriesX/vendor/Glad" include "CherriesX/vendor/ImGui" include "CherriesX/vendor/yaml-cpp" include "CherriesX/vendor/msdf-atlas-gen" group "" include "CherriesX" group "Tools" include "CherryJam" group ""
fx_version 'cerulean' game 'gta5' description 'QB-Lockpick' version '1.0.0' ui_page 'html/index.html' client_script 'client/main.lua' files { 'html/index.html', 'html/script.js', 'html/style.css', 'html/reset.css' }
local ObjectManager = require("managers.object.object_manager") SuiAmpPuzzle = {} function SuiAmpPuzzle:openPuzzle(pPlayer, pPuzzle, pCalibrator) local sui = SuiCalibrationGame2.new("SuiAmpPuzzle", "defaultCallback") local playerID = SceneObject(pPlayer):getObjectID() writeData(playerID .. ":calibratorComponentID", SceneObject(pPuzzle):getObjectID()) sui.setTargetNetworkId(SceneObject(pCalibrator):getObjectID()) sui.setForceCloseDistance(10) local bar1 = getRandomNumber(0, 2) local bar2 = getRandomNumber(0, 1) if (bar2 == 0) then bar2 = -1 end bar2 = bar2 + bar1 if (bar2 == -1) then bar2 = 2 elseif (bar2 == 3) then bar2 = 0 end local bar3 = 0 for i = 0, 2, 1 do if (i ~= bar1 and i ~= bar2) then bar3 = i end end local playerID = SceneObject(pPlayer):getObjectID() writeData(playerID .. ":ampPuzzle:bar1", bar1) writeData(playerID .. ":ampPuzzle:bar2", bar2) writeData(playerID .. ":ampPuzzle:bar3", bar3) local coefficient1 = getRandomNumber(1, 100) / 100 local coefficient2 = getRandomNumber(1, 100) / 100 local coefficient3 = getRandomNumber(1, 100) / 100 writeData(playerID .. ":ampPuzzle:coefficient1", coefficient1 * 100) writeData(playerID .. ":ampPuzzle:coefficient2", coefficient2 * 100) writeData(playerID .. ":ampPuzzle:coefficient3", coefficient3 * 100) local sliderPos1 = getRandomNumber(1, 100) / 100 local sliderPos2 = getRandomNumber(1, 100) / 100 local sliderPos3 = getRandomNumber(1, 100) / 100 writeData(playerID .. ":ampPuzzle:sliderPos1", sliderPos1) writeData(playerID .. ":ampPuzzle:sliderPos2", sliderPos2) writeData(playerID .. ":ampPuzzle:sliderPos3", sliderPos3) sui.setProperty("top.sliders.1.slider", "Value", "" .. (100 * sliderPos1)) sui.setProperty("top.sliders.2.slider", "Value", "" .. (100 * sliderPos2)) sui.setProperty("top.sliders.3.slider", "Value", "" .. (100 * sliderPos3)) sui.setProperty("top.sliders.1.title", "Text", "@quest/force_sensitive/fs_crafting:sui_amp_slider1") sui.setProperty("top.sliders.2.title", "Text", "@quest/force_sensitive/fs_crafting:sui_amp_slider2") sui.setProperty("top.sliders.3.title", "Text", "@quest/force_sensitive/fs_crafting:sui_amp_slider3") local tries = 25 writeData(playerID .. ":ampPuzzle:tries", tries) writeData(playerID .. ":ampPuzzle:maxTries", tries) sui.setTitle("@quest/force_sensitive/fs_crafting:sui_amp_title") sui.setDescription("@quest/force_sensitive/fs_crafting:sui_amp_description") sui.setAttemptsDesc("@quest/force_sensitive/fs_crafting:sui_attempts_remaining" .. " 100%") local c1, c2, c3 if (bar1 == 0) then c1 = sliderPos1 elseif (bar1 == 1) then c1 = sliderPos2 else c1 = sliderPos3 end if (bar2 == 0) then c2 = sliderPos1 elseif (bar2 == 1) then c2 = sliderPos2 else c2 = sliderPos3 end if (bar3 == 0) then c3 = sliderPos1 elseif (bar3 == 1) then c3 = sliderPos2 else c3 = sliderPos3 end for i = 1, 7, 1 do local n = (i - 1) / 7 local value = (c1 + (c2 * n) + (c3 * n * n)) / 3 if value < 0 then value = 0 elseif value > 1 then value = 1 end sui.setProperty("top.bars.yours." .. i, "Value", "" .. math.floor(100 * value)) sui.setProperty("top.bars.yours." .. i, "OnRunScript", "sizeY = (parent.sizeY * Value) / 100\nlocationY = parent.sizeY - sizeY") sui.setProperty("top.bars.yours." .. i, "RunScript", "") value = (coefficient1 + (coefficient2 * n) + (coefficient3 * n * n)) / 3 if value < 0 then value = 0 elseif value > 1 then value = 1 end sui.setProperty("top.bars.servers." .. i, "Value", "" .. math.floor(100 * value)) sui.setProperty("top.bars.servers." .. i, "OnRunScript", "sizeY = (parent.sizeY * Value) / 100\nlocationY = parent.sizeY - sizeY") sui.setProperty("top.bars.servers." .. i, "RunScript", "") writeData(playerID .. ":ampPuzzle:serverBarVal" .. i, math.floor(100 * value)) end sui.setProperty("btnOk", "IsDefaultButton", "true") sui.subscribeToEvent(SuiEventType.SET_onButton, "btnOk", "SuiAmpPuzzle:defaultCallback") sui.subscribeToPropertyForEvent(SuiEventType.SET_onButton, "top.sliders.1.slider", "Value") sui.subscribeToPropertyForEvent(SuiEventType.SET_onButton, "top.sliders.2.slider", "Value") sui.subscribeToPropertyForEvent(SuiEventType.SET_onButton, "top.sliders.3.slider", "Value") local pageId = sui.sendTo(pPlayer) writeData(playerID .. ":ampPuzzle:Pid", pageId) end function SuiAmpPuzzle:noCallback(pPlayer, pSui, eventIndex, ...) end function SuiAmpPuzzle:defaultCallback(pPlayer, pSui, eventIndex, ...) local pGhost = CreatureObject(pPlayer):getPlayerObject() if (pGhost == nil) then return end local cancelPressed = (eventIndex == 1) local playerID = SceneObject(pPlayer):getObjectID() local pageId = readData(playerID .. ":ampPuzzle:Pid") if (pageId == 0) then return end local pPageData = LuaSuiBoxPage(pSui):getSuiPageData() if (pPageData == nil) then printLuaError("SuiAmpPuzzle:defaultCallback, pageData is nil.") return end local suiPageData = LuaSuiPageData(pPageData) if (cancelPressed) then CreatureObject(pPlayer):sendSystemMessage("@quest/force_sensitive/fs_crafting:phase1_msg_calibration_aborted") self:doDataCleanup(pPlayer) return end local puzzleID = readData(playerID .. ":calibratorComponentID") local pPuzzle = getSceneObject(puzzleID) if (pPuzzle == nil) then printLuaError("SuiAmpPuzzle:defaultCallback, pPuzzle nil.") return end local pInventory = CreatureObject(pPlayer):getSlottedObject("inventory") if pInventory == nil or SceneObject(pPuzzle):getParentID() ~= SceneObject(pInventory):getObjectID() then return end PlayerObject(pGhost):addSuiBox(pSui) local args = {...} local sliderPos = { } local coefficients = { } local barValues = { } for i = 1, 3 , 1 do sliderPos[i] = args[i] / 100 coefficients[i] = readData(playerID .. ":ampPuzzle:coefficient" .. i) / 100 barValues[i] = readData(playerID .. ":ampPuzzle:bar" .. i) suiPageData:setProperty("top.sliders." .. i .. ".slider", "Value", tostring(sliderPos[i] * 100)) end local c1, c2, c3 if (barValues[1] == 0) then c1 = sliderPos[1] elseif (barValues[1] == 1) then c1 = sliderPos[2] else c1 = sliderPos[3] end if (barValues[2] == 0) then c2 = sliderPos[1] elseif (barValues[2] == 1) then c2 = sliderPos[2] else c2 = sliderPos[3] end if (barValues[3] == 0) then c3 = sliderPos[1] elseif (barValues[3] == 1) then c3 = sliderPos[2] else c3 = sliderPos[3] end local e = 0 for i = 1, 7, 1 do local n = (i - 1) / 7 local value = (c1 + (c2 * n) + (c3 * n * n)) / 3 if value < 0 then value = 0 elseif value > 1 then value = 1 end suiPageData:setProperty("top.bars.yours." .. i, "Value", "" .. math.floor(100 * value)) suiPageData:setProperty("top.bars.yours." .. i, "RunScript", "") local targetValue = (coefficients[1] + (coefficients[2] * n) + (coefficients[3] * n * n)) / 3 e = e + math.abs(value - targetValue) suiPageData:setProperty("top.bars.servers." .. i, "Value", "" .. readData(playerID .. ":ampPuzzle:serverBarVal" .. i)) suiPageData:setProperty("top.bars.servers." .. i, "OnRunScript", "sizeY = (parent.sizeY * Value) / 100\nlocationY = parent.sizeY - sizeY") suiPageData:setProperty("top.bars.servers." .. i, "RunScript", "") end local wonPuzzle = false if (e < 0.2) then wonPuzzle = true end local tries = readData(playerID .. ":ampPuzzle:tries") local maxTries = readData(playerID .. ":ampPuzzle:maxTries") tries = tries - 1 local integrity = math.floor((tries / maxTries) * 100) if (wonPuzzle or tries <= 0) then suiPageData:subscribeToEvent(SuiEventType.SET_onButton, "btnOk", "SuiAmpPuzzle:noCallback") suiPageData:setProperty("top.sliders.1.slider", "GetsInput", "false") suiPageData:setProperty("top.sliders.2.slider", "GetsInput", "false") suiPageData:setProperty("top.sliders.3.slider", "GetsInput", "false") suiPageData:setProperty("btnOk", "Visible", "false") if (wonPuzzle) then LuaFsCraftingComponentObject(pPuzzle):setStatus(1) suiPageData:setProperty("description.desc", "Text", "@quest/force_sensitive/fs_crafting:sui_calibration_success") else LuaFsCraftingComponentObject(pPuzzle):setStatus(-1) suiPageData:setProperty("description.desc", "Text", "@quest/force_sensitive/fs_crafting:sui_calibration_failure") suiPageData:setProperty("description.attempts", "Text", "@quest/force_sensitive/fs_crafting:sui_attempts_remaining" .. " " .. integrity .. "%") end self:doDataCleanup(pPlayer) else suiPageData:setProperty("description.attempts", "Text", "@quest/force_sensitive/fs_crafting:sui_attempts_remaining" .. " " .. integrity .. "%") writeData(playerID .. ":ampPuzzle:tries", tries) end suiPageData:sendUpdateTo(pPlayer) end function SuiAmpPuzzle:doDataCleanup(pPlayer) local playerID = SceneObject(pPlayer):getObjectID() deleteData(playerID .. ":ampPuzzle:tries") deleteData(playerID .. ":ampPuzzle:maxTries") for i = 1, 3, 1 do deleteData(playerID .. ":ampPuzzle:sliderPos" .. i) deleteData(playerID .. ":ampPuzzle:coefficient" .. i) deleteData(playerID .. ":ampPuzzle:bar" .. i) end for i = 1, 7, 1 do deleteData(playerID .. ":ampPuzzle:serverBarVal" .. i) end deleteData(playerID .. ":ampPuzzle:Pid") end
package.path = package.path .. ";?" local extraTierDistributions = {} extraTierDistributions[Difficulty.Insane] = 0.33 extraTierDistributions[Difficulty.Hardcore] = 0.31 extraTierDistributions[Difficulty.Expert] = 0.29 extraTierDistributions[Difficulty.Veteran] = 0.27 extraTierDistributions[Difficulty.Normal] = 0.25 extraTierDistributions[Difficulty.Easy] = 0.21 extraTierDistributions[Difficulty.Beginner] = 0.19 SpawnUtility._Debug = 0 local xmods = Mods() local hasIncreasingThreat = false for _, p in pairs(xmods) do if p.id == "2208370349" then hasIncreasingThreat = true break end end local Ferocity_addToughness = SpawnUtility.addToughness function SpawnUtility.addToughness(entity, level) local _MethodName = "Add Toughness" if not entity or not valid(entity) then return end SpawnUtility.Log(_MethodName, "Adding toughness.") local _Difficulty = GameSettings().difficulty local _dt = extraTierDistributions[_Difficulty] local _Hatred = 0 if hasIncreasingThreat then local ITUtil = include("increasingthreatutility") local hatedplayers = ITUtil.getSectorPlayersByHatred(entity.factionIndex) _Hatred = math.min(hatedplayers[1].hatred, 1000) --cap at +20% @ 1000 _dt = _dt + ((_Hatred / 50) / 100) end local _EnemyTier = 1 if random():test(_dt) then _EnemyTier = _EnemyTier + 1 --T2 if random():test(_dt) then _EnemyTier = _EnemyTier + 1 --T3 if random():test(_dt) then _EnemyTier = _EnemyTier + 1 --T4 end end end SpawnUtility.Log(_MethodName, "Adding tier " .. tostring(_EnemyTier) .. " enemy.") if _EnemyTier == 1 then SpawnUtility.Log(_MethodName, "adding a standard buff.") Ferocity_addToughness(entity, level) elseif _EnemyTier == 2 then SpawnUtility.Log(_MethodName, "adding a tier 2 buff.") SpawnUtility.addTier2Buff(entity, level) elseif _EnemyTier == 3 then SpawnUtility.Log(_MethodName, "adding a tier 3 buff.") SpawnUtility.addTier3Buff(entity, level) elseif _EnemyTier == 4 then SpawnUtility.Log(_MethodName, "adding a tier 4 buff.") SpawnUtility.addTier4Buff(entity, level, _Hatred) end end function SpawnUtility.addTier2Buff(entity, level) local _MethodName = "Add Tier 2 Buff" if not entity or not valid(entity) then SpawnUtility.Log(_MethodName, "ERROR - Entity not valid - returning.") return else SpawnUtility.Log(_MethodName, "Adding buff...") end local hpFactor = 4 local dmgFactor = 2 local isUnreal = false if level == 1 then if entity.title then local titleArgs = entity:getTitleArguments() if titleArgs then titleArgs.toughness = "Deadly "%_T entity:setTitleArguments(titleArgs) else entity.title = "Deadly "%_T .. entity.title end end hpFactor = 4 dmgFactor = 2 elseif level == 2 then if entity.title then local titleArgs = entity:getTitleArguments() if titleArgs then titleArgs.toughness = "Ferocious "%_T entity:setTitleArguments(titleArgs) else entity.title = "Ferocious "%_T .. entity.title end end hpFactor = 5 dmgFactor = 3 elseif level == 3 then if entity.title then local titleArgs = entity:getTitleArguments() if titleArgs then titleArgs.toughness = "Unreal "%_T entity:setTitleArguments(titleArgs) else entity.title = "Unreal "%_T .. entity.title end end isUnreal = true hpFactor = 5 dmgFactor = 4 end local durability = Durability(entity) if durability then durability.maxDurabilityFactor = (durability.maxDurabilityFactor or 0) + hpFactor end local shield = Shield(entity) if shield then shield.maxDurabilityFactor = (shield.maxDurabilityFactor or 0) + hpFactor end if dmgFactor ~= 1 then entity.damageMultiplier = (entity.damageMultiplier or 1) * dmgFactor end -- increase resistances if existing local x, y = Sector():getCoordinates() local distToCenter = math.sqrt(x * x + y * y) SpawnUtility.applyResistanceFactorBuff(entity, level, distToCenter) if isUnreal then --Add a special script. entity:addScriptOnce("ferocityphasemode.lua") end end function SpawnUtility.addTier3Buff(entity, level) if not entity or not valid(entity) then return end local hpFactor = 5 local dmgFactor = 3 local isEternal = false if level == 1 then if entity.title then local titleArgs = entity:getTitleArguments() if titleArgs then titleArgs.toughness = "Ultimate "%_T entity:setTitleArguments(titleArgs) else entity.title = "Ultimate "%_T .. entity.title end end hpFactor = 5 dmgFactor = 3 elseif level == 2 then if entity.title then local titleArgs = entity:getTitleArguments() if titleArgs then titleArgs.toughness = "Paragon "%_T entity:setTitleArguments(titleArgs) else entity.title = "Paragon "%_T .. entity.title end end hpFactor = 5 dmgFactor = 4 elseif level == 3 then if entity.title then local titleArgs = entity:getTitleArguments() if titleArgs then titleArgs.toughness = "Eternal "%_T entity:setTitleArguments(titleArgs) else entity.title = "Eternal "%_T .. entity.title end end isEternal = true hpFactor = 6 dmgFactor = 5 end local durability = Durability(entity) if durability then durability.maxDurabilityFactor = (durability.maxDurabilityFactor or 0) + hpFactor end local shield = Shield(entity) if shield then shield.maxDurabilityFactor = (shield.maxDurabilityFactor or 0) + hpFactor end if dmgFactor ~= 1 then entity.damageMultiplier = (entity.damageMultiplier or 1) * dmgFactor end -- increase resistances if existing local x, y = Sector():getCoordinates() local distToCenter = math.sqrt(x * x + y * y) SpawnUtility.applyResistanceFactorBuff(entity, level, distToCenter) if isEternal then --Add a special script. entity:addScriptOnce("ferocityeternal.lua") end end function SpawnUtility.addTier4Buff(entity, level, highestHatred) if not entity or not valid(entity) then return end local hatredFactor = highestHatred / 100 local hpFactor = 6 local dmgFactor = 5 local addUnreal = false local addEternal = false if level == 1 then if entity.title then local titleArgs = entity:getTitleArguments() if titleArgs then titleArgs.toughness = "Cataclysmic "%_T entity:setTitleArguments(titleArgs) else entity.title = "Cataclysmic "%_T .. entity.title end end hpFactor = hpFactor + (hatredFactor * 0.01) dmgFactor = dmgFactor + (hatredFactor * 0.01) elseif level == 2 then if entity.title then local titleArgs = entity:getTitleArguments() if titleArgs then titleArgs.toughness = "Apocalyptic "%_T entity:setTitleArguments(titleArgs) else entity.title = "Apocalyptic "%_T .. entity.title end end hpFactor = hpFactor + (hatredFactor * 0.015) dmgFactor = dmgFactor + (hatredFactor * 0.015) addUnreal = true elseif level == 3 then if entity.title then local titleArgs = entity:getTitleArguments() if titleArgs then titleArgs.toughness = "Eschaton "%_T entity:setTitleArguments(titleArgs) else entity.title = "Eschaton "%_T .. entity.title end end hpFactor = hpFactor + (hatredFactor * 0.02) dmgFactor = dmgFactor + (hatredFactor * 0.02) addUnreal = true addEternal = true end local durability = Durability(entity) if durability then durability.maxDurabilityFactor = (durability.maxDurabilityFactor or 0) + hpFactor end local shield = Shield(entity) if shield then shield.maxDurabilityFactor = (shield.maxDurabilityFactor or 0) + hpFactor end if dmgFactor ~= 1 then entity.damageMultiplier = (entity.damageMultiplier or 1) * dmgFactor end -- increase resistances if existing local x, y = Sector():getCoordinates() local distToCenter = math.sqrt(x * x + y * y) SpawnUtility.applyResistanceFactorBuff(entity, level, distToCenter) if addUnreal then entity:addScriptOnce("ferocityphasemode.lua") end if addEternal then --Add a special script. entity:addScriptOnce("ferocityeternal.lua") end end function SpawnUtility.Log(_MethodName, _Msg) if SpawnUtility._Debug == 1 then print("[Ferocity] - [" .. tostring(_MethodName) .. "] - " .. tostring(_Msg)) end end
return function(...) local matcher_functions = {...} return function(...) for _, fn in ipairs(matcher_functions) do local ret = fn(...) if ret ~= nil then return ret end end return nil end end
BigWigs:AddColors("Amalgam of Souls", { [194956] = "yellow", [195254] = "yellow", [196587] = {"red","yellow"}, }) BigWigs:AddColors("Illysanna Ravencrest", { [197797] = {"blue","yellow"}, [197974] = "red", }) BigWigs:AddColors("Smashspite", { [198073] = "orange", [198079] = {"blue","yellow"}, [198245] = "green", [198446] = "red", }) BigWigs:AddColors("Kurtalos Ravencrest", { [198641] = "yellow", [198820] = "yellow", [202019] = {"red","yellow"}, }) BigWigs:AddColors("Black Rook Hold Trash", { [197974] = "orange", [200248] = "yellow", [200261] = "orange", [200291] = "red", [200343] = "yellow", [203163] = {"blue","orange"}, [214003] = "red", [225573] = "yellow", [227913] = "yellow", })
------------------------------------------------------------------- -- identical to the socket.smtp module except that it uses -- async wrapped Copas sockets local copas = require("copas") local smtp = require("socket.smtp") local create = function() return copas.wrap(socket.tcp()) end local forwards = { -- setting these will be forwarded to the original smtp module PORT = true, SERVER = true, TIMEOUT = true, DOMAIN = true, TIMEZONE = true } copas.smtp = setmetatable({}, { -- use original module as metatable, to lookup constants like socket.SERVER, etc. __index = smtp, -- Setting constants is forwarded to the luasocket.smtp module. __newindex = function(self, key, value) if forwards[key] then smtp[key] = value return end return rawset(self, key, value) end, }) local _M = copas.smtp _M.send = function(mailt) mailt.create = mailt.create or create return smtp.send(mailt) end return _M
local mpq = require 'map-builder.archive_mpq' local dir = require 'map-builder.archive_dir' local search = require 'map-builder.search' local os_clock = os.clock local mt = {} mt.__index = mt function mt:number_of_files() if self:get_type() == 'mpq' then return self.handle:number_of_files() else return self.handle:count_files() end end function mt:search_files() return self.handle:search_files() end function mt:get_type() return self._type end function mt:is_readonly() return self._read end function mt:save_file(name, buf, filetime) return self.handle:save_file(name, buf, filetime) end function mt:close() if self._attach then return false end return self.handle:close() end function mt:save(w3i, progress, encrypt) if self:is_readonly() then return false end local max = 0 for _ in pairs(self) do max = max + 1 end if not self.handle:save(self.path, w3i, max, encrypt) then return false end local clock = os_clock() local count = 0 for name, buf in pairs(self) do self.handle:save_file(name, buf) count = count + 1 if os_clock() - clock > 0.1 then clock = os_clock() progress(count / max) if self:get_type() == 'mpq' then print(('正在打包文件... (%d/%d)'):format(count, max)) else print(('正在导出文件... (%d/%d)'):format(count, max)) end end end return true end function mt:flush() if self:is_readonly() then return false end self._flushed = true self.write_cache = {} self.read_cache = {} end local function unify(name) return name:lower():gsub('/', '\\'):gsub('\\[\\]+', '\\') end function mt:has(name) name = unify(name) if not self.handle then return false end if self.read_cache[name] == false then return false end if self.read_cache[name] then return true end if self._flushed then return end local buf = self.handle:load_file(name) if buf then self.read_cache[name] = buf return true else self.read_cache[name] = false return false end end function mt:set(name, buf) name = unify(name) self.write_cache[name] = buf end function mt:remove(name) name = unify(name) self.write_cache[name] = false end function mt:get(name) name = unify(name) if self.write_cache[name] then return self.write_cache[name] end if self.write_cache[name] == false then return nil end if not self.handle then return nil end if self._flushed then return nil end if self.read_cache[name] == false then return nil end if self.read_cache[name] then return self.read_cache[name] end local buf = self.handle:load_file(name) if buf then self.read_cache[name] = buf else self.read_cache[name] = false end return buf end function mt:__pairs() local tbl = {} for k, v in pairs(self.write_cache) do if v then tbl[k] = v end end return next, tbl end function mt:search_files(progress) if not self._searched then self._searched = true search(self, progress) end local files = {} for name, buf in pairs(self.read_cache) do if buf and self.write_cache[name] == nil then files[name] = buf end end return next, files end return function (pathorhandle, tp) local read_only = tp ~= 'w' local ar = { write_cache = {}, read_cache = {}, path = pathorhandle, _read = read_only, } if type(pathorhandle) == 'number' then ar.handle = mpq(pathorhandle) ar._type = 'mpq' ar._attach = true ar._read = false elseif read_only then if fs.is_directory(pathorhandle) then ar.handle = dir(pathorhandle) ar._type = 'dir' else ar.handle = mpq(pathorhandle, true) ar._type = 'mpq' end if not ar.handle then print('地图打开失败') return nil end else if fs.is_directory(pathorhandle) then ar.handle = dir(pathorhandle) ar._type = 'dir' else ar.handle = mpq(pathorhandle) ar._type = 'mpq' end end return setmetatable(ar, mt) end
local bufferline = prequire "bufferline" local M = {} if not bufferline then return end local function is_ft(b, ft) return vim.bo[b].filetype == ft end local function diagnostics_indicator(_, _, diagnostics) local result = {} local symbols = { error = "", warning = "", info = "" } for name, count in pairs(diagnostics) do if symbols[name] and count > 0 then table.insert(result, symbols[name] .. count) end end result = table.concat(result, " ") return #result > 0 and result or "" end local function custom_filter(buf, buf_nums) local logs = vim.tbl_filter(function(b) return is_ft(b, "log") end, buf_nums) if vim.tbl_isempty(logs) then return true end local tab_num = vim.fn.tabpagenr() local last_tab = vim.fn.tabpagenr "$" local is_log = is_ft(buf, "log") if last_tab == 1 then return true end -- only show log buffers in secondary tabs return (tab_num == last_tab and is_log) or (tab_num ~= last_tab and not is_log) end local options = { numbers = "none", -- | "ordinal" | "buffer_id" | "both" | function({ ordinal, id, lower, raise }): string, close_command = "bdelete! %d", -- can be a string | function, see "Mouse actions" right_mouse_command = "vert sbuffer %d", -- can be a string | function, see "Mouse actions" left_mouse_command = "buffer %d", -- can be a string | function, see "Mouse actions" middle_mouse_command = nil, -- can be a string | function, see "Mouse actions" -- NOTE: this plugin is designed with this icon in mind, -- and so changing this is NOT recommended, this is intended -- as an escape hatch for people who cannot bear it for whatever reason indicator_icon = "▎", buffer_close_icon = "", -- buffer_close_icon = '', modified_icon = "●", close_icon = "", -- close_icon = '', left_trunc_marker = "", right_trunc_marker = "", --- name_formatter can be used to change the buffer's label in the bufferline. --- Please note some names can/will break the --- bufferline so use this at your discretion knowing that it has --- some limitations that will *NOT* be fixed. -- name_formatter = function(buf) -- buf contains a "name", "path" and "bufnr" -- -- remove extension from markdown files for example -- if buf.name:match('%.md') then -- return vim.fn.fnamemodify(buf.name, ':t:r') -- end -- end, max_name_length = 18, max_prefix_length = 15, -- prefix used when a buffer is de-duplicated tab_size = 18, diagnostics = "nvim_lsp", diagnostics_update_in_insert = false, diagnostics_indicator = diagnostics_indicator, -- NOTE: this will be called a lot so don't do any heavy processing here custom_filter = custom_filter, offsets = { { filetype = "undotree", text = "Undotree", highlight = "PanelHeading", padding = 1, }, { filetype = "NvimTree", text = "Explorer", highlight = "PanelHeading", padding = 1, }, { filetype = "DiffviewFiles", text = "Diff View", highlight = "PanelHeading", padding = 1, }, { filetype = "flutterToolsOutline", text = "Flutter Outline", highlight = "PanelHeading", }, { filetype = "packer", text = "Packer", highlight = "PanelHeading", padding = 1, }, }, show_buffer_icons = true, show_buffer_close_icons = true, show_close_icon = true, show_tab_indicators = true, persist_buffer_sort = true, -- whether or not custom sorted buffers should persist -- can also be a table containing 2 custom separators -- [focused and unfocused]. eg: { '|', '|' } separator_style = "thin", -- | "thick" | "thin" | { 'any', 'any' }, enforce_regular_tabs = true, always_show_bufferline = true, sort_by = "id", } local highlights = { background = { gui = "italic", }, buffer_selected = { gui = "bold", }, } bufferline.setup { options = options, highlights = highlights, } -- Common kill function for bdelete and bwipeout -- credits: based on bbye and nvim-bufdel ---@param kill_command string defaults to "bd" ---@param bufnr number defaults to the current buffer ---@param force boolean defaults to false function M.buf_kill(kill_command, bufnr, force) local bo = vim.bo local api = vim.api if bufnr == 0 or bufnr == nil then bufnr = api.nvim_get_current_buf() end kill_command = kill_command or "bd" -- If buffer is modified and force isn't true, print error and abort if not force and bo[bufnr].modified then return api.nvim_err_writeln( string.format("No write since last change for buffer %d (set force to true to override)", bufnr) ) end -- Get list of windows IDs with the buffer to close local windows = vim.tbl_filter(function(win) return api.nvim_win_get_buf(win) == bufnr end, api.nvim_list_wins()) if #windows == 0 then return end if force then kill_command = kill_command .. "!" end -- Get list of active buffers local buffers = vim.tbl_filter(function(buf) return api.nvim_buf_is_valid(buf) and bo[buf].buflisted end, api.nvim_list_bufs()) -- If there is only one buffer (which has to be the current one), vim will -- create a new buffer on :bd. -- For more than one buffer, pick the previous buffer (wrapping around if necessary) if #buffers > 1 then for i, v in ipairs(buffers) do if v == bufnr then local prev_buf_idx = i == 1 and (#buffers - 1) or (i - 1) local prev_buffer = buffers[prev_buf_idx] for _, win in ipairs(windows) do api.nvim_win_set_buf(win, prev_buffer) end end end end -- Check if buffer still exists, to ensure the target buffer wasn't killed -- due to options like bufhidden=wipe. if api.nvim_buf_is_valid(bufnr) and bo[bufnr].buflisted then vim.cmd(string.format("%s %d", kill_command, bufnr)) end end return M
--------------------------------------------------------------- --- Base demo of promise framework --------------------------------------------------------------- -- The testcase: Do A(), and do B,C,D, and do E() base a,b,c -- *) print messages: -- 20 -- andThen: nil -- 40 -- 30 -- nil ok nil -- *) and catch a reson: -- FIRE --------------------------------------------------------------- local inspect = require "IO/inspect" Promise = require('Promise') --Promise = require("promises/Promise/Promise") print("---") return10 = function() return 10 end returnDoubled = function(a) print(a * 2) ; return a * 2 end printX4 = function(a) print(a * 4) return Promise.resolve('ok') -- return 'ok' end printX3 = function(a) print(a * 3) ; return a * 3 end unpackAndReject = function(result) local b, c, d = unpack(result) print(b, c, d) return Promise.reject('FIRE') end -- promise_A = Promise.resolve(A()) promise_r10 = Promise.new(function(resolve, reject) local ok, result = pcall(return10) print("after pcall " .. tostring(ok) .. " " .. result .. ".") return (ok and resolve or reject)(result) end) promise_r10 = Promise.resolve(10) -- promise_B = promise_A:andThen(B) local err = function(r) print("catch:", r) end local log = function(r) print("andThen:", r); return r end promise_B = promise_r10:andThen(returnDoubled):catch(err):andThen(log) promise_C = promise_r10:andThen(printX4) promise_D = promise_r10:andThen(printX3) print(inspect({"hi"})) promises = {promise_B, promise_C, promise_D} Promise.all(promises):andThen(function(o) print(inspect(o)) return o end) :andThen(unpackAndReject) :catch(print)
return Def.Sprite{ BeginCommand=function(self) local extraType = "extra1" -- relies on the fact that the next stage is set before eval is loaded if GAMESTATE:GetCurrentStage() == 'Stage_Extra2' then extraType = "extra2" end self:Load(THEME:GetPathG("ScreenEvaluation","TryExtraStage/"..extraType)) end; };
return { id1 = 3, id2 = 5, id3 = "ab3", num = 3, desc = "desc3", }
local function get_uri_scheme(uri) local _, _, uri_scheme = string.find(uri, "^([a-z]+)://") return uri_scheme end local function is_local_link(uri) return nil == get_uri_scheme(uri) end local function ensure_trailing_slash(str) return string.gsub(str, "/$", "") .. "/" end local initial_slash_replacement_prefix = ensure_trailing_slash( os.getenv("PANDOC_MD_WIKI_REL_PATH_FROM_PAGE_TO_ROOT_DIR")) function Link(el) if not is_local_link(el.target) then return nil -- Leave link untouched. end -- print(string.format("site_root_dir: %s", rel_path_to_site_root_dir)) el.target = string.gsub( el.target, "^/", initial_slash_replacement_prefix) return el end
--[[ As we have seen, a tail call is a goto in disguise. Using this idea, reimplement the simple maze game from Section 4.4 using tail calls. Each block should become a new function, and each goto becomes a tail call. ]] --[[ The second solution in e4_4.lua (states_as_functions) already implemented the maze using functions. ]]
project "Script-Squirrel" AddModuleConfig() uuid "05885A51-71F1-4606-A989-2AA3C69EEA91" pchheader "stdafx_Squirrel.h" pchsource "../src/stdafx_Squirrel.cpp" defines { "SQ_EXCLUDE_DEFAULT_MEMFUNCTIONS", "SCRAT_USE_CXX11_OPTIMIZATIONS", } includedirs { "../Externals/squirrel/include", "../Externals/sqrat/include", }
function table_to_string(t) if type(t) == 'table' then local s = '{' for k, v in pairs(t) do if type(k) ~= 'number' then k = '"' .. k .. '"' end s = s .. '[' .. k .. '] = ' .. table_to_string(v) .. ', ' end return s .. '}' else return tostring(t) end end --[[ function table.val_to_str (v) if "string" == type(v) then v = string.gsub(v, "\n", "\\n") if string.match(string.gsub(v, "[^'\"]", ""), '^" + $') then return "'" .. v .. "'" end return '"' .. string.gsub(v, '"', '\\"') .. '"' else return "table" == type(v) and table.to_string(v) or tostring(v) end end function table.key_to_str (k) if "string" == type(k) and string.match(k, "^[_%a][_%a%d]*$") then return k else return "[" .. table.val_to_str(k) .. "]" end end function table.to_string(tbl) local result, done = {}, {} for k, v in ipairs(tbl) do table.insert(result, table.val_to_str(v)) done[k] = true end for k, v in pairs(tbl) do if not done[k] then table.insert(result, table.key_to_str(k) .. "=" .. table.val_to_str(v)) end end return "{" .. table.concat(result, ",") .. "}" end ]]
return {'cnossen'}
local autocmd = require'utils.autocmd'.autocmd autocmd('TextYankPost * silent! lua vim.highlight.on_yank()')
require("common/popupWindow"); local match_hall_record_info_rank_layout = require(ViewPath .. "hall/matchHall/widget/match_hall_record_info_rank_layout"); local match_record_pin_map = require("qnFiles/qnPlist/hall/match_record_pin"); -- 好友排行信息弹框 local GameMatchHallRecordRankInfo = class(PopupWindow, false); local h_index = 0; local getIndex = function(self) h_index = h_index + 1; return h_index; end GameMatchHallRecordRankInfo.s_controls = { contentView = getIndex(), contentBg = getIndex(), textPlay = getIndex(), textLevel = getIndex(), textScore = getIndex(), advanceFinalsCount = getIndex(), advanceCircleCount = getIndex(), winCount = getIndex(), }; GameMatchHallRecordRankInfo.Delegate = { } GameMatchHallRecordRankInfo.s_cmds = { }; GameMatchHallRecordRankInfo.ctor = function(self) super(self, match_hall_record_info_rank_layout); self:setFillParent(true, true); self:setAlign(kAlignCenter); self:setEventTouch(self, self.onBgTouch); self:setEventDrag(self, function() end) self:_initView(); self:addToRoot(); MatchRecordDataInterface.getInstance():setObserver(self); end GameMatchHallRecordRankInfo.dtor = function(self) MatchRecordDataInterface.getInstance():clearObserver(self); end GameMatchHallRecordRankInfo.isShowing = function(self) return self.m_isShowing; end GameMatchHallRecordRankInfo.show = function(self, data) PopupWindow.show(self, PopupWindowStyle.NORMAL); self.m_isShowing = true; self:_resetView(); self:_initData(data); self:_showData(); end GameMatchHallRecordRankInfo.hidden = function(self) if self.m_isShowing then self.m_isShowing = false; PopupWindow.hidden(self, PopupWindowStyle.NORMAL); end end GameMatchHallRecordRankInfo.setContentPos = function(self, x, y, delta) local contentView = self:findViewById(self.s_controls.contentView); local contentBg = self:findViewById(self.s_controls.contentBg); local sHeight = System.getScreenScaleHeight(); local w, h = contentView:getSize(); contentView:setAlign(kAlignTopLeft); local isShowUp = (y + delta + h) > sHeight; local viewX = x - w / 2; local viewY = isShowUp and (y - h - delta) or (y + delta); contentView:setPos(viewX, viewY); local file = isShowUp and match_record_pin_map["popup_bg_up.png"] or match_record_pin_map["popup_bg_down.png"] local align = isShowUp and kAlignTop or kAlignBottom; contentBg:setFile(file); contentBg:setAlign(align) end GameMatchHallRecordRankInfo.onBgTouch = function(self, finger_action, x, y, drawing_id_first,drawing_id_current, event_time) if finger_action == kFingerUp then self:_closeView(); end end -- interface callback GameMatchHallRecordRankInfo.onGetMatchRecordStatistics = function(self, data, mid) if mid ~= self.m_data.mid then return; end Log.d("GameMatchHallRecordRankInfo.onGetMatchRecordStatistics", "mid", mid); self:findViewById(self.s_controls.advanceFinalsCount):setText(tostring(data.finals_total or 0)); self:findViewById(self.s_controls.advanceCircleCount):setText(tostring(data.awards_total or 0)); self:findViewById(self.s_controls.winCount):setText(tostring(data.champion_total or 0)); if not string.isEmpty(data.favorite_match) then self.m_textPlay:setText(string.format("最近常玩 %s", data.favorite_match)); else self.m_textPlay:setText("暂无参赛记录"); end end -------------------------------------------------------------------------------------- GameMatchHallRecordRankInfo._closeView = function(self) EventDispatcher.getInstance():dispatch(kClosePopupWindows); end GameMatchHallRecordRankInfo._initData = function(self, data) self.m_data = data; -- 请求比赛统计数据 MatchRecordDataInterface.getInstance():getMatchRecordStatistics(self.m_data.mid); end GameMatchHallRecordRankInfo._showData = function(self) local data = self.m_data; self.m_textLevel:setText(string.format("等级:Lv.%s", data.level)); self.m_textScore:setText(string.format("大师分:%s", data.masterpoints)); end GameMatchHallRecordRankInfo._initView = function(self) self.m_textPlay = self:findViewById(self.s_controls.textPlay); self.m_textLevel = self:findViewById(self.s_controls.textLevel); self.m_textScore = self:findViewById(self.s_controls.textScore); end GameMatchHallRecordRankInfo._resetView = function(self) self:findViewById(self.s_controls.advanceFinalsCount):setText(""); self:findViewById(self.s_controls.advanceCircleCount):setText(""); self:findViewById(self.s_controls.winCount):setText(""); self.m_textPlay:setText(""); end -------------------------------------------------------------------------------- GameMatchHallRecordRankInfo.s_controlConfig = { [GameMatchHallRecordRankInfo.s_controls.contentView] = {"contentView"}; [GameMatchHallRecordRankInfo.s_controls.contentBg] = {"contentView", "contentBg"}; [GameMatchHallRecordRankInfo.s_controls.textPlay] = {"contentView", "textPlay"}; [GameMatchHallRecordRankInfo.s_controls.textLevel] = {"contentView", "textLevel"}; [GameMatchHallRecordRankInfo.s_controls.textScore] = {"contentView", "textScore"}; [GameMatchHallRecordRankInfo.s_controls.advanceFinalsCount] = {"contentView", "statisticsView", "statisticsCenterView", "text"}; [GameMatchHallRecordRankInfo.s_controls.advanceCircleCount] = {"contentView", "statisticsView", "statisticsLeftView", "text"}; [GameMatchHallRecordRankInfo.s_controls.winCount] = {"contentView", "statisticsView", "statisticsRightView", "text"}; }; GameMatchHallRecordRankInfo.s_controlFuncMap = { }; GameMatchHallRecordRankInfo.s_cmdConfig = { }; return GameMatchHallRecordRankInfo;
dofile(minetest.get_modpath("better_swords").."/swords.lua") dofile(minetest.get_modpath("better_swords").."/knives.lua") dofile(minetest.get_modpath("better_swords").."/craftings.lua")
local _, Engine = ... local Module = Engine:GetModule("ActionBars") local ControllerWidget = Module:SetWidget("Controller: Stance") local L = Engine:GetLocale() -- Lua API local pairs = pairs local setmetatable = setmetatable local tconcat, tinsert = table.concat, table.insert -- WoW API local GetNumShapeshiftForms = GetNumShapeshiftForms ControllerWidget.OnEnable = function(self) local config = Module.config local control_config = Module.config.structure.controllers.stance local button_config = Module.config.visuals.stance.button local window_config = Module.config.visuals.stance.window local UICenter = Engine:GetFrame() local Main = Module:GetWidget("Controller: Main"):GetFrame() local Side = Module:GetWidget("Controller: Side"):GetFrame() local MenuButton = Module:GetWidget("Template: MenuButton") local FlyoutBar = Module:GetWidget("Template: FlyoutBar") local point = control_config.position.point local anchor = control_config.position.anchor local anchor_point = control_config.position.anchor_point local xoffset = control_config.position.xoffset local yoffset = control_config.position.yoffset if anchor == "UICenter" then anchor = UICenter elseif anchor == "Main" then anchor = Main elseif anchor == "Side" then anchor = Side end self.Controller = CreateFrame("Frame", nil, UICenter, "SecureHandlerAttributeTemplate") self.Controller:SetFrameStrata("BACKGROUND") self.Controller:SetPoint(point, anchor, anchor_point, xoffset, yoffset) self.Controller:SetSize(unpack(control_config.size)) -- Main Button --------------------------------------------- local StanceButton = MenuButton:New(self.Controller) StanceButton:SetSize(unpack(button_config.size)) StanceButton:SetPoint(unpack(button_config.position)) StanceButton:SetFrameStrata("MEDIUM") StanceButton:SetFrameLevel(50) -- get it above the actionbars StanceButton.Normal = StanceButton:CreateTexture(nil, "BORDER") StanceButton.Normal:ClearAllPoints() StanceButton.Normal:SetPoint(unpack(button_config.texture_position)) StanceButton.Normal:SetSize(unpack(button_config.texture_size)) StanceButton.Normal:SetTexture(button_config.textures.normal) StanceButton.Pushed = StanceButton:CreateTexture(nil, "BORDER") StanceButton.Pushed:Hide() StanceButton.Pushed:ClearAllPoints() StanceButton.Pushed:SetPoint(unpack(button_config.texture_position)) StanceButton.Pushed:SetSize(unpack(button_config.texture_size)) StanceButton.Pushed:SetTexture(button_config.textures.pushed) StanceButton.OnButtonState = function(self, state, lock) if state == "PUSHED" then self.Pushed:Show() self.Normal:Hide() else self.Normal:Show() self.Pushed:Hide() end end hooksecurefunc(StanceButton, "SetButtonState", StanceButton.OnButtonState) StanceButton.OnEnter = function(self) if StanceButton:GetButtonState() == "PUSHED" then GameTooltip:Hide() return end GameTooltip_SetDefaultAnchor(GameTooltip, self) GameTooltip:AddLine(L["Stances"]) -- different text based on class GameTooltip:AddLine(L["<Left-click> to toggle stance bar."], 0, .7, 0) GameTooltip:Show() end StanceButton:SetScript("OnEnter", StanceButton.OnEnter) StanceButton:SetScript("OnLeave", function(self) GameTooltip:Hide() end) StanceButton.OnClick = function(self, button) if button == "LeftButton" then self:OnEnter() -- update tooltips end end StanceButton:RegisterForClicks("AnyDown") StanceButton:SetHitRectInsets(0, 0, 0, 0) StanceButton:OnButtonState(StanceButton:GetButtonState()) -- Stance Window --------------------------------------------- local StanceWindow = FlyoutBar:New(StanceButton) StanceWindow:AttachToButton(StanceButton) StanceWindow:SetPoint(unpack(window_config.position)) StanceWindow:SetSize(unpack(window_config.size)) self.StanceButton = StanceButton self.StanceWindow = StanceWindow self:RegisterEvent("PLAYER_ENTERING_WORLD", "OnEvent") self:RegisterEvent("UPDATE_BONUS_ACTIONBAR", "OnEvent") self:RegisterEvent("UPDATE_VEHICLE_ACTIONBAR", "OnEvent") self:RegisterEvent("UPDATE_OVERRIDE_ACTIONBAR", "OnEvent") self:RegisterEvent("ACTIONBAR_PAGE_CHANGED", "OnEvent") self:RegisterEvent("UPDATE_SHAPESHIFT_FORM", "OnEvent") self:RegisterEvent("UPDATE_SHAPESHIFT_FORMS", "OnEvent") self:RegisterEvent("UPDATE_SHAPESHIFT_USABLE", "OnEvent") self:RegisterEvent("UPDATE_POSSESS_BAR", "OnEvent") end ControllerWidget.OnEvent = function(self, event, ...) if event == "PLAYER_ENTERING_WORLD" then self:UpdateBarArtwork() -- this is where we style the stancebuttons self:UnregisterEvent("PLAYER_ENTERING_WORLD", "OnEvent") -- should only need it once end self:UpdateStanceButton() end ControllerWidget.UpdateStanceButton = Engine:Wrap(function(self) local Controller = self.Controller local num_forms = GetNumShapeshiftForms() if num_forms == 0 then UnregisterStateDriver(Controller, "visibility") RegisterStateDriver(Controller, "visibility", "hide") else local driver = {} if Engine:IsBuild("MoP") then -- also applies to WoD and (possibly) Legion tinsert(driver, "[overridebar][possessbar][shapeshift]hide") tinsert(driver, "[vehicleui]hide") elseif Engine:IsBuild("WotLK") then -- also applies to Cata tinsert(driver, "[bonusbar:5]hide") tinsert(driver, "[vehicleui]hide") end tinsert(driver, "show") UnregisterStateDriver(Controller, "visibility") RegisterStateDriver(Controller, "visibility", tconcat(driver, "; ")) end -- should be options somewhere for this local Bar = Module:GetWidget("Bar: Stance"):GetFrame() if Bar then self.StanceWindow:SetSize(Bar:GetSize()) end end) -- Callback to update the actual stance bar's button artwork. -- The bar and buttons are created later, so it can't be done on controller init. ControllerWidget.UpdateBarArtwork = function(self) local Bar = Module:GetWidget("Bar: Stance"):GetFrame() if Bar then Bar:UpdateStyle() end end ControllerWidget.GetFrame = function(self) return self.StanceWindow end
Locales ['pl'] = { ['press_button'] = "Naciśnij ~INPUT_CONTEXT~, aby zakupić lub sprawdzić swoje ubezpieczenie", ['ins_time'] = "~g~Twoje ubezpieczenie %s jest ważne do %s", ['buy_ins'] = "Zakup ubezpieczenia %s", ['3_days'] = "3 dni (15000$)", ['7_days'] = "7 dni (33000$)", ['14_days'] = "14 dni (55000$)", ['31_days'] = "31 dni (105000$)", ['insurance'] = "Ubezpieczenie %s", ['not_enought'] = "~r~Nie masz wystarczającej ilości pieniędzy!", ['bought_ins'] = "~g~Zakupiono ubezpieczenie %s na %s dni" }
--region logic.bootstrap.lua --Author : OWenT --Date : 2014/10/29 --启动载入项 return { } --endregion
function onCreate() -- background shit makeLuaSprite('cupheadbg', 'mouse/cupheadbg', -100, -100); setLuaSpriteScrollFactor('cupheadbg', 0.9, 0.9); addLuaSprite('cupheadbg', false); close(true); --For performance reasons, close this script once the stage is fully loaded, as this script won't be used anymore after loading the stage end
function RegistreOpen(Panel,Arg0) FicheJoueurOngletRegistre:Disable(); FicheJoueurOngletRegistreIcon:SetAlpha(0.5); FicheJoueurFond:SetTexture("Interface\\Stationery\\Stationery_ill1.blp"); FicheJoueurFondDroite:SetTexture("Interface\\Stationery\\Stationery_ill2.blp"); RegistreFicheButtonListeEpurerIcon:SetTexture("Interface\\ICONS\\Ability_Rogue_Eviscerate.blp"); FicheJoueurPanelRegistre:Show(); RegistrePanelConsulte:Hide(); RegistrePanelListe:Hide(); RegistreSousPanelGeneral:Hide(); RegistreSousPanelDescription:Hide(); RegistreFrameModelePerso:Hide(); RegistreFicheButtonPanelListe:Show(); RegistreFicheButtonPanelGeneral:Hide(); RegistreFicheButtonPanelDescription:Hide(); RegistreFicheButtonPanelListe:Enable(); RegistreFicheButtonPanelGeneral:Enable(); RegistreFicheButtonPanelDescription:Enable(); FichePersonnageBoutonDelete:Hide(); FichePersonnageBoutonNotesGen:Hide(); if Panel == nil or Panel == "Liste" then RegistrePanelListe:Show(); RegistreFicheButtonPanelListe:Disable(); RegistreFicheButtonPanelListeIcon:SetAlpha(0.50); ChargerListe(); FicheJoueurPanelTitle:SetText(LISTE); else RegistreFichePersonnageNomHidden:SetText(Arg0); ShowFicheOf(Arg0); RegistrePanelConsulte:Show(); RegistreFicheButtonPanelGeneral:Show(); RegistreFicheButtonPanelDescription:Show(); if Panel == "General" then RegistreSousPanelGeneral:Show(); RegistreFicheButtonPanelGeneral:Disable(); FichePersonnageBoutonDelete:Show(); FichePersonnageBoutonNotesGen:Show(); RegistreFicheModelPerso_StartAnim(); RegistreFicheButtonPanelGeneralIcon:SetAlpha(0.50); elseif Panel == "Description" then RegistreSousPanelDescription:Show(); RegistreFicheButtonPanelDescription:Disable(); FichePersonnageBoutonDelete:Show(); FichePersonnageBoutonNotesGen:Show(); RegistreFicheButtonPanelDescriptionIcon:SetAlpha(0.50); RegistreFicheModelPerso_StartAnim(); end end end function ShowFicheOf(nom) if TRP_Module_Registre[Royaume][nom] == nil then debugMess("Internal error : ShowFicheOf d'une personne inconnue !") return; end local personnage = TRP_Module_Registre[Royaume][nom]; local relations = TRP_Module_PlayerInfo_Relations[Royaume][nom][Joueur]; if relations == nil then relations = 3; TRP_Module_PlayerInfo_Relations[Royaume][nom][Joueur] = relations; end --Affichage : FicheJoueurPanelTitle:SetText(TOOLTIP_FICHE..nom); -- SOUS TITRE if personnage["SousTitre"] and personnage["SousTitre"] ~= "" then RegistreFicheSousTitre:SetText("< "..personnage["SousTitre"].." >"); else RegistreFicheSousTitre:SetText(""); end -- IN FORMATION DE BASE if personnage["Prenom"] and personnage["Prenom"] ~= "" then RegistreFichePrenom:SetText("|cffffc300 "..PRENOM.."|cffffffff "..personnage["Prenom"]); else RegistreFichePrenom:SetText("|cffffc300 "..PRENOM.."|cffffffff "..nom); end if personnage["Nom"] and personnage["Nom"] ~= "" then RegistreFicheNom:SetText("|cffffc300 "..NOM.."|cffffffff "..personnage["Nom"]); else RegistreFicheNom:SetText("|cffffc300 "..NOM.."|cff999999 "..INCONNU); end if personnage["Age"] and personnage["Age"] ~= "" then RegistreFicheAge:SetText("|cffffc300 "..AGE.."|cffffffff "..personnage["Age"]); else RegistreFicheAge:SetText("|cffffc300 "..AGE.."|cff999999 "..INCONNU); end if personnage["Origine"] and personnage["Origine"] ~= "" then RegistreFicheNaissance:SetText("|cffffc300 "..NAISSANCE.."|cffffffff "..personnage["Origine"]); else RegistreFicheNaissance:SetText("|cffffc300 "..NAISSANCE.."|cff999999 "..INCONNU); end --INFORMATION PHYSIQUE if personnage["Taille"] then RegistreFicheTaille:SetText("|cffffc300 "..TAILLE.."|cffffffff "..TAILLE_TEXTE[personnage["Taille"]]); else RegistreFicheTaille:SetText("|cffffc300 "..TAILLE.."|cff999999 "..INCONNU); end if personnage["Corpulence"] then RegistreFicheCorpulence:SetText("|cffffc300 "..CORPULENCE.."|cffffffff "..CORPULENCE_TEXTE[personnage["Corpulence"]]); else RegistreFicheCorpulence:SetText("|cffffc300 "..CORPULENCE.."|cff999999 "..INCONNU); end if personnage["Silhouette"] then RegistreFicheSilhouette:SetText("|cffffc300 "..SILHOUETTE.."|cffffffff "..SILHOUETTE_TEXTE[personnage["Silhouette"]]); else RegistreFicheSilhouette:SetText("|cffffc300 "..SILHOUETTE.."|cff999999 "..INCONNU); end if personnage["QualiteVetement"] then RegistreFicheVetement:SetText("|cffffc300 "..QUALITEVETEMENT.."|cffffffff "..QUALITEVETEMENT_TEXTE[personnage["QualiteVetement"]]); else RegistreFicheVetement:SetText("|cffffc300 "..QUALITEVETEMENT.."|cff999999 "..INCONNU); end --DESCRIPTION if RecollageDescription(nom,true) == "" and personnage["Actuellement"] == "" then RegistreFicheDescriScrollText:SetText(NO_DESCR); else RegistreFicheDescriScrollText:SetText(DESCACTUAL..setTRPColorToString(personnage["Actuellement"])..DESCPHYS..RecollageDescription(nom,true)); end -- ALIGNEMENT RegistreFicheAlignementText:SetFont("Fonts\\ARIALN.TTF",16); if TRP_Module_Configuration["Modules"]["Registre"]["bShowAlignement"] and personnage["Ethique"] ~= nil and personnage["Morale"] ~= nil then local texteMorale,texteEthique,vertMorale,rougeMorale,vertEthique,rougeEthique = getNameAndColorAlignement(nom); RegistreFicheAlignementText:SetText("|cff"..deciToHexa(rougeEthique)..deciToHexa(vertEthique).."00"..texteEthique.."|cffffc300 - ".."|cff"..deciToHexa(rougeMorale)..deciToHexa(vertMorale).."00"..texteMorale); else RegistreFicheAlignementText:SetText(moral_color[4]..TEXTE_ETHIQUE[4].."|cffffc300 - "..moral_color[4]..TEXTE_MORALE[4]); end --RELATION RegistreFicheRelationSlider:SetValue(relations); RegistreFicheNomComplet:SetText(relation_color[relations]..nomComplet(RegistreFichePersonnageNomHidden:GetText())); -- NOTES RegistreFicheNotesScrollText:SetText(TRP_Module_PlayerInfo_Notes[Royaume][nom]); -- FRAMEMODEL RegistreFicheModelPerso_StartAnim(); if personnage["Humeur"] ~= nil then RegistreFicheHumeurText:SetText(humeur_color[personnage["Humeur"]]..HUMEUR_SET[personnage["Humeur"]]); else RegistreFicheHumeurText:SetText(humeur_color[7]..HUMEUR_SET[7]); end if personnage["StatutRP"] ~= nil then RegistreFicheStatutRP:SetText(statut_color[personnage["StatutRP"]]..STATUTRP[personnage["StatutRP"]]); else RegistreFicheStatutRP:SetText(statut_color[3]..STATUTRP[3]); end -- ICONE PERSONNALISEE RegistreFicheButtonPanelGeneralIcon:SetTexture("Interface\\ICONS\\Ability_Warrior_Revenge.blp"); if personnage["Race"] ~= nil and personnage["Sex"] ~= nil and personnage["Sex"] >= 2 then local textureFinale = "Interface\\ICONS\\Achievement_Character_"..textureRace[personnage["Race"]].."_"..textureSex[personnage["Sex"]]..".blp"; RegistreFicheButtonPanelGeneralIcon:SetTexture(textureFinale); end if TRP_Module_Configuration["Modules"]["Registre"]["bForceUpdate"] then TRPSecureSendAddonMessage("GTI",DonnerInfos(),nom); end end function RegistreFicheModelPerso_OnUpdate(elapsed,sequence) seqtime = seqtime + (elapsed * 1000); RegistreFicheModelPerso:SetSequenceTime(sequence, seqtime); end function RegistreFicheModelPerso_StartAnim() if UnitName("target") == RegistreFichePersonnageNomHidden:GetText() and CheckInteractDistance("target", 4) then RegistreFrameModelePerso:Show(); seqtime = 0; animationPlayed = 67; RegistreFicheModelPerso:SetUnit("target"); else RegistreFrameModelePerso:Hide(); end end function SetAttributTo(nom,attribut,valeur) if nom == nil or TRP_Module_Registre[Royaume][nom] == nil then debugMess("Erreur : SetAttributeTo : nom invalide"); return; elseif attribut == nil then debugMess("Erreur : SetAttributeTo : attribut nul"); return; elseif valeur == nil then debugMess("Erreur : SetAttributeTo : valeure nulle"); return; end if attribut == "Relation" then TRP_Module_PlayerInfo_Relations[Royaume][nom][Joueur] = valeur; else TRP_Module_Registre[Royaume][nom][attribut] = valeur; end end function GlobaliserRelation() local nom = RegistreFichePersonnageNomHidden:GetText(); local message = string.gsub(GLOBALBASE,"{target}",nom); message = string.gsub(message,"{col}",relation_color[TRP_Module_PlayerInfo_Relations[Royaume][nom][Joueur]]); message = string.gsub(message,"{rel}",RELATIONARRAY[TRP_Module_PlayerInfo_Relations[Royaume][nom][Joueur]]); table.foreach(TRP_Module_PlayerInfo[Royaume], function(personnage) TRP_Module_PlayerInfo_Relations[Royaume][nom][personnage] = TRP_Module_PlayerInfo_Relations[Royaume][nom][personnage]; message = message.."- "..personnage.."\n"; end); TRP_ShowStaticPopup("TRP_REG_GLOBAL_RELATION",GLOBALISERRELATION,message); end function ChangeSliderValue() RegistreFicheRelation:SetText(relation_color[RegistreFicheRelationSlider:GetValue()]..RELATIONTEXT..RELATIONARRAY[RegistreFicheRelationSlider:GetValue()]); RegistreFicheNomComplet:SetText(relation_color[RegistreFicheRelationSlider:GetValue()]..nomComplet(RegistreFichePersonnageNomHidden:GetText())); -- Icone if UnitName("target") == RegistreFichePersonnageNomHidden:GetText() and RegistreFicheRelationSlider:IsVisible() then TargetPortraitButton:SetNormalTexture(relation_texture[RegistreFicheRelationSlider:GetValue()]) end end function RecupDescri(descri,nom) -- Appell\195\169 quand on recois la description de quelqu'un Numero = tonumber(string.sub(descri,1,1)); if TRP_Module_Registre[Royaume][nom]["Description"] == nil or Numero == 1 then TRP_Module_Registre[Royaume][nom]["Description"] = nil; TRP_Module_Registre[Royaume][nom]["Description"] = {}; end TRP_Module_Registre[Royaume][nom]["Description"][Numero] = string.sub(descri,2); RegistreFicheDescriScrollText:SetText(RecollageDescription(nom,true)); if nom == UnitName("target") then changeTarget(); end end function RecupRegistre(infos,nom) -- Ajouter au registre si il y est pas if TRP_Module_Registre[Royaume][nom] == nil then AjouterAuRegistre(nom); end TRP_Module_Registre[Royaume][nom]["Prenom"] = infos[1]; TRP_Module_Registre[Royaume][nom]["Nom"] = infos[2]; TRP_Module_Registre[Royaume][nom]["Titre"] = infos[3]; TRP_Module_Registre[Royaume][nom]["SousTitre"] = infos[4]; TRP_Module_Registre[Royaume][nom]["Age"] = infos[5]; TRP_Module_Registre[Royaume][nom]["Origine"] = infos[6]; TRP_Module_Registre[Royaume][nom]["Taille"] = tonumber(infos[7]); TRP_Module_Registre[Royaume][nom]["Corpulence"] = tonumber(infos[8]); TRP_Module_Registre[Royaume][nom]["Silhouette"] = tonumber(infos[9]); TRP_Module_Registre[Royaume][nom]["QualiteVetement"] = tonumber(infos[10]); -- Infos 11 et 12 == ancienne version de l'alignement TRP_Module_Registre[Royaume][nom]["Type"] = 1; TRP_Module_Registre[Royaume][nom]["VerNum"] = tonumber(infos[13]); TRP_Module_Registre[Royaume][nom]["Morale"] = tonumber(infos[14]); TRP_Module_Registre[Royaume][nom]["Ethique"] = tonumber(infos[15]); if not TRP_Module_Registre[Royaume][nom]["Morale"] then TRP_Module_Registre[Royaume][nom]["Morale"] = 0; end if not TRP_Module_Registre[Royaume][nom]["Ethique"] then TRP_Module_Registre[Royaume][nom]["Ethique"] = 0; end TRP_Module_Registre[Royaume][nom]["Description"] = {}; if (RegistreFicheButtonPanelGeneral:IsVisible() or RegistreFicheButtonPanelDescription:IsVisible()) and RegistreFichePersonnageNomHidden:GetText() == nom then -- On refresh sa fiche uniquement si elle est actuellement visible PanelOpen("FicheJoueurOngletRegistre","General",nom); elseif RegistrePanelListe:IsVisible() then -- Si liste visible, on la refresh aussi PanelOpen("FicheJoueurOngletRegistre","Liste"); end -- Si pas, cela veut dire que la personne a été ajoutée automatiquement à la sélection if nom == UnitName("target") or nom == UnitName("mouseover") then changeTarget(); MouseOverTooltip(true); end debugMess(DATAOK..nom.."."); end function confirmDeletePersonnage(nom) TRP_ShowStaticPopup("TRP_REG_DELETE_PERSO",DELETEPERSO.." "..nom,TRP_TEXT_STATIC_POPUP.TRP_REG_DELETE_PERSO..CAREFULL,nom); end function deletePersonnage(nom) if nom == nil then debugMess("Erreur : Suppression NIL"); return; end if TRP_Module_Registre[Royaume][nom] ~= nil then wipe(TRP_Module_Registre[Royaume][nom]); TRP_Module_Registre[Royaume][nom] = nil; end debugMess("Suppression de "..nom.." r\195\169ussie."); if UnitName("target") == nom then changeTarget(); end if FicheJoueur:IsVisible() then PanelOpen("FicheJoueurOngletRegistre","Liste"); end end function epurerListe() table.foreach(TRP_Module_Registre[Royaume], function(personnage) if not TRP_Module_Registre[Royaume][personnage]["Connu"] then wipe(TRP_Module_Registre[Royaume][personnage]); TRP_Module_Registre[Royaume][personnage] = nil; end end); ChargerListe(); end ------------------------------------------------------------------------------- -- TRAITEMENT DE DESCRIPTIONS ------------------------------------------------------------------------------- function DecoupageDescription(description) local ok = true; local morceaux = string.reverse(description); local i = 1; TRP_Module_PlayerInfo[Royaume][Joueur]["Description"] = nil; TRP_Module_PlayerInfo[Royaume][Joueur]["Description"] = {}; while ok do local indice = string.find(morceaux," ",-200); if string.len(morceaux) < 200 then -- Dernier Morceaux TRP_Module_PlayerInfo[Royaume][Joueur]["Description"][i] = string.reverse(morceaux); ok = false; elseif indice == nil then if string.len(morceaux) > 200 then -- Pas d'espace dans les 200 derniers charactères : erreur StaticPopupDialogs["TRP_TEXT_ONLY_SHADE"].text = setTRPColorToString(TRP_ENTETE.." \n "..TRPWARNING.."\n\n"..ERROR_DESCR); TRP_ShowStaticPopup("TRP_TEXT_ONLY_SHADE"); ok = false; end else TRP_Module_PlayerInfo[Royaume][Joueur]["Description"][i] = string.reverse(string.sub(morceaux,indice)); i = i + 1; morceaux = string.sub(morceaux,1,indice-1); end end end function isBanned(nom) if TRP_Module_PlayerInfo_Relations[Royaume][nom] ~= nil and TRP_Module_PlayerInfo_Relations[Royaume][nom][Joueur] == 1 then return true; else return false; end end function RecollageDescription(nom,color) -- color true = color, color false = rien, color nil = balises DescriptionCollee = ""; -- Renvoie au minimum un string vide. if nom == Joueur then table.foreach(TRP_Module_PlayerInfo[Royaume][Joueur]["Description"], function(DescriptionNum) DescriptionCollee = DescriptionCollee..TRP_Module_PlayerInfo[Royaume][Joueur]["Description"][DescriptionNum]; end); else if TRP_Module_Registre[Royaume][nom]["Description"] ~= nil then table.foreach(TRP_Module_Registre[Royaume][nom]["Description"], function(DescriptionNum) DescriptionCollee = DescriptionCollee..TRP_Module_Registre[Royaume][nom]["Description"][DescriptionNum]; end); end end if color == true then -- Pour affichage TRP DescriptionCollee = setTRPColorToString(DescriptionCollee); elseif color == false then DescriptionCollee = setTRPColorToString(DescriptionCollee,true); end return DescriptionCollee; end function EnvoiInfo(cible) debugMess(cible..QUERYARSKING); result = FormatInformations(); TRPSecureSendAddonMessage("GVR", result, cible); local i = 1; while true do if TRP_Module_PlayerInfo[Royaume][Joueur]["Description"][i] ~= nil then toSend = i..TRP_Module_PlayerInfo[Royaume][Joueur]["Description"][i]; TRPSecureSendAddonMessage("GVD", toSend, cible); i = i+1; else break; end end end function FormatInformations() local info = ""; info = info..TRP_Module_PlayerInfo[Royaume][Joueur]["Prenom"].."|"; -- 25 info = info..TRP_Module_PlayerInfo[Royaume][Joueur]["Nom"].."|"; -- 25 info = info..TRP_Module_PlayerInfo[Royaume][Joueur]["Titre"].."|"; -- 25 info = info..TRP_Module_PlayerInfo[Royaume][Joueur]["SousTitre"].."|"; -- 50 info = info..TRP_Module_PlayerInfo[Royaume][Joueur]["Age"].."|"; -- 9 info = info..TRP_Module_PlayerInfo[Royaume][Joueur]["Origine"].."|"; -- 25 info = info..TRP_Module_PlayerInfo[Royaume][Joueur]["Taille"].."|"; -- 1 info = info..TRP_Module_PlayerInfo[Royaume][Joueur]["Corpulence"].."|"; -- 1 info = info..TRP_Module_PlayerInfo[Royaume][Joueur]["Silhouette"].."|"; -- 1 info = info..TRP_Module_PlayerInfo[Royaume][Joueur]["QualiteVetement"].."|"; -- 1 info = info.."4|4|"; -- Ancienne version de l'alignement, pour éviter les probleme avec ceux qui ont une vieille version -- 2 info = info..TRP_Module_PlayerInfo[Royaume][Joueur]["VerNum"].."|"; -- 4 if TRP_Module_Configuration["Modules"]["Registre"]["bSendAlignement"] then info = info..TRP_Module_PlayerInfo[Royaume][Joueur]["Morale"].."|"; -- 3 info = info..TRP_Module_PlayerInfo[Royaume][Joueur]["Ethique"].."|"; -- 3 else info = info.."0|0|"; end -- 15 élément => 15 -- Total actuel = 190 -- Dispo = 110 return info; end function DonnerInfos() -- 1 : Version de TRP : 4 -- 2 : Version du profil : 4 -- 3 : Humeur : 1 -- 4 : StatutRP : 1 -- 5 : Description actuelle : 230 -- Total : 244/248 local demande = ""; demande = demande..TRP_version.."|"; demande = demande..TRP_Module_PlayerInfo[Royaume][Joueur]["VerNum"].."|"; demande = demande..TRP_Module_PlayerInfo[Royaume][Joueur]["Humeur"].."|"; demande = demande..TRP_Module_PlayerInfo[Royaume][Joueur]["StatutRP"].."|"; demande = demande..TRP_Module_PlayerInfo[Royaume][Joueur]["Actuellement"]; return demande; end function RecupInfos(infos,sender) if not tonumber(infos[1]) then return end --[[ Plus nécéssaire vu que TRP 1.106 est la dernière version de TRP 1 :) if TRP_Module_Configuration["Modules"]["General"]["bNotifyNewVersion"] and tonumber(TRP_version) < tonumber(infos[1]) and not hasBeenAlerted then -- Message de mise à jour if not FicheJoueur:IsVisible() then PanelOpen("FicheJoueurOngletOptions","General"); end StaticPopupDialogs["TRP_TEXT_ONLY_SHADE"].text = setTRPColorToString(TRP_ENTETE.." \n "..TOTALRP.."\n\n"..NEWVERSION..string.sub(infos[1],1,1).."."..string.sub(infos[1],2,2).." (Build "..infos[1]..")"); TRP_ShowStaticPopup("TRP_TEXT_ONLY_SHADE"); hasBeenAlerted = true; end]] if TRP_Module_Registre[Royaume][sender] == nil then -- Demander Info AjouterAuRegistre(sender); TRPSecureSendAddonMessage("GTR","",sender); changeTarget(); else if TRP_Module_Registre[Royaume][sender]["VerNum"] ~= tonumber(infos[2]) then TRPSecureSendAddonMessage("GTR","",sender); end end TRP_Module_Registre[Royaume][sender]["Humeur"] = tonumber(infos[3]); TRP_Module_Registre[Royaume][sender]["StatutRP"] = tonumber(infos[4]); TRP_Module_Registre[Royaume][sender]["Actuellement"] = infos[5]; MouseOverTooltip(true); end ------------------------------------------------------------------ ----- PET ------------------------------------------------------------------ function DonnerInfosPet(sender) for i=1,GetNumCompanions("CRITTER") do local creatureID, creatureName, creatureSpellID, icon, issummoned = GetCompanionInfo("CRITTER", i); if issummoned then if TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][creatureName] then local demande = creatureName.."|"; demande = demande..TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][creatureName]["Nom"].."|"; demande = demande..TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][creatureName]["Description"].."|"; demande = demande..tostring(TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][creatureName]["bMount"]); TRPSecureSendAddonMessage("GVP",demande,sender); end end end local monture = GetActualMountName(); if monture and TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][monture] then local demande = monture.."|"; demande = demande..TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][monture]["Nom"].."|"; demande = demande..TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][monture]["Description"].."|"; demande = demande..tostring(TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][monture]["bMount"]); TRPSecureSendAddonMessage("GVP",demande,sender); return; end local pet = UnitName("pet"); if pet and TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][pet] then local demande = pet.."|"; demande = demande..TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][pet]["Nom"].."|"; demande = demande..TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][pet]["Description"].."|"; demande = demande..tostring(TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][pet]["bMount"]); TRPSecureSendAddonMessage("GVP",demande,sender); return; end end function RecupInfosPet(tab,sender) SavePetInfos(sender,tab[1],tab[2],tab[3],tab[4]); end function SavePetInfos(maitre,petName,Nom,Descri,bMount) if maitre and petName and Nom and Descri then if maitre == Joueur then if not TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][petName] then TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][petName] = {} end TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][petName]["Nom"] = Nom; TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][petName]["Description"] = Descri; TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][petName]["bMount"] = bMount; else if TRP_Module_Registre[Royaume][maitre] then if not TRP_Module_Registre[Royaume][maitre]["Pet"] then TRP_Module_Registre[Royaume][maitre]["Pet"] = {}; end if not TRP_Module_Registre[Royaume][maitre]["Pet"][petName] then TRP_Module_Registre[Royaume][maitre]["Pet"][petName] = {}; end TRP_Module_Registre[Royaume][maitre]["Pet"][petName]["Nom"] = Nom; TRP_Module_Registre[Royaume][maitre]["Pet"][petName]["Description"] = Descri; TRP_Module_Registre[Royaume][maitre]["Pet"][petName]["bMount"] = bMount; if bMount and bMount == "true" then MouseOverTooltip(true); end end end end end function GetActualMountName() for i=1,GetNumCompanions("MOUNT") do local creatureID, creatureName, creatureSpellID, icon, issummoned = GetCompanionInfo("MOUNT", i); if issummoned then return creatureName; end end return nil; end function initPetButton() for i=1,12 do getglobal("CompanionButton"..i):SetScript("OnEnter", function(self) if self.creatureID then if ( PetPaperDollFrameCompanionFrame.mode == "CRITTER" ) then for i=1,GetNumCompanions("CRITTER") do local ID, creatureName, creatureSpellID, icon, issummoned = GetCompanionInfo("CRITTER", i); if ID == self.creatureID then GameTooltip_SetDefaultAnchor(GameTooltip, UIParent) GameTooltip:AddLine(setTRPColorToString("{v}"..creatureName)); GameTooltip:AddLine(setTRPColorToString("{w}Instant")); GameTooltip:AddLine(setTRPColorToString("{o}Click to summon your companion.")); if TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][creatureName] and (TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][creatureName]["Nom"] ~= "" or TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][creatureName]["Description"] ~= "") then GameTooltip:AddLine(setTRPColorToString(" ")); GameTooltip:AddLine(setTRPColorToString("{o}Customizing companion :")); if TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][creatureName]["Nom"] ~= "" then GameTooltip:AddLine(setTRPColorToString("{w}Name :{v} "..TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][creatureName]["Nom"])); else GameTooltip:AddLine(setTRPColorToString("{w}Name :{v} "..creatureName)); end if TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][creatureName]["Description"] ~= "" then GameTooltip:AddLine(setTRPColorToString("{w}Description :")) decouperForTooltip("\""..TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][creatureName]["Description"].."\"",35,1,0.75,0); end end GameTooltip:AddLine(setTRPColorToString(" ")); GameTooltip:AddLine(setTRPColorToString("{v}Ctrl + click to customize the companion")); GameTooltip:Show(); end end elseif ( PetPaperDollFrameCompanionFrame.mode == "MOUNT" ) then for i=1,GetNumCompanions("MOUNT") do local ID, creatureName, creatureSpellID, icon, issummoned = GetCompanionInfo("MOUNT", i); if ID == self.creatureID then GameTooltip_SetDefaultAnchor(GameTooltip, UIParent) GameTooltip:AddLine(setTRPColorToString("{v}"..creatureName)); GameTooltip:AddLine(setTRPColorToString("{w}Instant")); GameTooltip:AddLine(setTRPColorToString("{o}Click to summon your mount.")); if TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][creatureName] and (TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][creatureName]["Nom"] ~= "" or TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][creatureName]["Description"] ~= "") then GameTooltip:AddLine(setTRPColorToString(" ")); GameTooltip:AddLine(setTRPColorToString("{o}Customizing the mount :")); if TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][creatureName]["Nom"] ~= "" then GameTooltip:AddLine(setTRPColorToString("{w}Name :{v} "..TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][creatureName]["Nom"])); else GameTooltip:AddLine(setTRPColorToString("{w}Name :{v} "..creatureName)); end if TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][creatureName]["Description"] ~= "" then GameTooltip:AddLine(setTRPColorToString("{w}Description :")) decouperForTooltip("\""..TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][creatureName]["Description"].."\"",35,1,0.75,0); end end GameTooltip:AddLine(setTRPColorToString(" ")); GameTooltip:AddLine(setTRPColorToString("{v}Ctrl + click to customize the mount")); GameTooltip:Show(); end end end end end); end end function openPetPage(nom,bMount) TRPModifyPetInfo.creatureName = nom; if TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][nom] then if TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][nom]["Nom"] then TRPModifyPetInfoNomSaisie:SetText(TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][nom]["Nom"]); else TRPModifyPetInfoNomSaisie:SetText(nom); end if TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][nom]["Description"] then TRPModifyPetInfoDescriSaisie:SetText(TRP_Module_PlayerInfo[Royaume][Joueur]["Pet"][nom]["Description"]); else TRPModifyPetInfoDescriSaisie:SetText(""); end else TRPModifyPetInfoNomSaisie:SetText(""); TRPModifyPetInfoDescriSaisie:SetText(""); end TRPModifyPetInfoNomSaisie:SetFocus(); if bMount then TRPModifyPetInfoNom:SetText("Mount name :"); else TRPModifyPetInfoNom:SetText("Companion name :"); end TRPModifyPetInfoBoutonSave:SetScript("OnClick",function() SavePetInfos(Joueur,nom,TRPModifyPetInfoNomSaisie:GetText(),TRPModifyPetInfoDescriSaisie:GetText(),bMount) TRPModifyPetInfo:Hide(); end); TRPModifyPetInfo:Show() end function CompanionButton_OnModifiedClick(self) local id = self.spellID; if IsControlKeyDown() then if ( PetPaperDollFrameCompanionFrame.mode == "CRITTER" ) then for i=1,GetNumCompanions("CRITTER") do local ID, creatureName, creatureSpellID, icon, issummoned = GetCompanionInfo("CRITTER", i); if id == creatureSpellID then openPetPage(creatureName,false); end end elseif ( PetPaperDollFrameCompanionFrame.mode == "MOUNT" ) then for i=1,GetNumCompanions("MOUNT") do local ID, creatureName, creatureSpellID, icon, issummoned = GetCompanionInfo("MOUNT", i); if creatureSpellID == id then openPetPage(creatureName,true); end end end elseif ( IsModifiedClick("CHATLINK") ) then if ( MacroFrame and MacroFrame:IsShown() ) then local spellName = GetSpellInfo(id); ChatEdit_InsertLink(spellName); else local spellLink = GetSpellLink(id) ChatEdit_InsertLink(spellLink); end elseif ( IsModifiedClick("PICKUPACTION") ) then CompanionButton_OnDrag(self); end PetPaperDollFrame_UpdateCompanions(); --Set up the highlights again end ------------------------------------------------------------------ ------------------------------------------------------------------ function AjouterAuRegistre(nom, selected) TRP_Module_Registre[Royaume][nom] = {}; if TRP_Module_PlayerInfo_Relations[Royaume][nom] == nil then TRP_Module_PlayerInfo_Relations[Royaume][nom] = {}; end if TRP_Module_PlayerInfo_Relations[Royaume][nom][Joueur] == nil then TRP_Module_PlayerInfo_Relations[Royaume][nom][Joueur] = 3; end if TRP_Module_PlayerInfo_Notes[Royaume][nom] == nil then TRP_Module_PlayerInfo_Notes[Royaume][nom] = NO_NOTES; end TRP_Module_Registre[Royaume][nom]["Faction"] = UnitFactionGroup("player"); if selected then GenererNotes(nom); local race, raceEn = UnitRace("target"); TRP_Module_Registre[Royaume][nom]["Race"] = raceEn; TRP_Module_Registre[Royaume][nom]["Sex"] = UnitSex("target"); TRP_Module_Registre[Royaume][nom]["Connu"] = true; TRP_Module_Registre[Royaume][nom]["Faction"] = UnitFactionGroup("target"); end TRP_Module_Registre[Royaume][nom]["Description"] = {}; TRP_Module_Registre[Royaume][nom]["Type"] = 3; TRP_Module_Registre[Royaume][nom]["Humeur"] = 7; TRP_Module_Registre[Royaume][nom]["VerNum"] = 0; TRP_Module_Registre[Royaume][nom]["Actuellement"] = ""; TRP_Module_Registre[Royaume][nom]["Date"] = date("%d/%m/%y"); if TRP_Module_Configuration["Modules"]["Registre"]["bNotifyAjout"] then sendMessage("{j}".."|Hplayer:"..nom.."|h[|cffaaaaff"..nom.."{j}]|h"..AJOUTREG); end if nom == UnitName("target") then changeTarget(); end if RegistrePanelListe:IsVisible() then PanelOpen("FicheJoueurOngletRegistre","Liste"); end end function GenererNotes(nom) if UnitName("target") ~= nom then StaticPopupDialogs["TRP_TEXT_ONLY_SHADE"].text = setTRPColorToString(TRP_ENTETE.." \n "..GENNOTES.."\n\n"..GENNOTESBAD); TRP_ShowStaticPopup("TRP_TEXT_ONLY_SHADE"); return; end local guilde,grade = GetGuildInfo("target"); local classe = UnitClass("target"); local faction = UnitFactionGroup("target"); local cercle = UnitLevel("target"); local race = UnitRace("target"); local genre = UnitSex("target"); local informations = "----------------------------------------\nInformation :\n----------------------------------------\n"; informations = informations.."- Faction : "..faction.."\n"; informations = informations.."- Race : "..race.."\n"; informations = informations.."- Class : "..classe.."\n"; if guilde == nil or guilde == "" then informations = informations.."- Guild : < Aucune >\n" grade = nil; else informations = informations.."- Guild : < "..guilde.." >\n" if grade == nil or grade == "" then informations = informations.."- Rank : < Aucun >\n"; else informations = informations.."- Rank : < "..grade.." >\n"; end end informations = informations.."- Level : "..cercle.."\n"; if genre == 2 then informations = informations.."- Sex : Male\n"; elseif genre == 3 then informations = informations.."- Sex : Female\n"; end informations = informations.."----------------------------------------"; -- Place les info a la fin des notes TRP_Module_PlayerInfo_Notes[Royaume][nom] = TRP_Module_PlayerInfo_Notes[Royaume][nom].."\n\n"..informations; RegistreFicheNotesScrollText:SetText(TRP_Module_PlayerInfo_Notes[Royaume][nom]); end function ChargerListe() local i = 0; local j = 0; local num = ListeTypeSlider:GetValue(); local numB = ListeTypeBSlider:GetValue(); wipe(PersoTab); getTabMember(); ListeButtonSlider:SetOrientation("VERTICAL"); ListeButtonSlider:Hide(); ListeButtonSlider:SetValue(0); FicheListeTypeTri:SetText(TRIAGE_SET[num+1]); FicheListeTypeBTri:SetText(TRIAGEB_SET[numB+1]); table.foreach(TRP_Module_Registre[Royaume], function(liste) if liste ~= Joueur then i = i + 1; if TRP_Module_PlayerInfo_Relations[Royaume][liste][Joueur] == nil then TRP_Module_PlayerInfo_Relations[Royaume][liste][Joueur] = 3; end local matching = string.lower(ListeSaisieRecherche:GetText()); local matchingB = string.lower(nomComplet(liste)); if string.find(matchingB,matching) or string.find(liste,matching) then if num == 0 or TRP_Module_PlayerInfo_Relations[Royaume][liste][Joueur] == num or (TRP_Module_PlayerInfo_Relations[Royaume][liste][Joueur] == nil and num == 3) then -- Check relation if numB == 0 or numB == TRP_Module_Registre[Royaume][liste]["Type"] then if (ListeConnectedCheck:GetChecked() and TabMember[liste]) or not ListeConnectedCheck:GetChecked() then j = j + 1; PersoTab[j] = liste; end end end end end; end); RegistreFicheNomComplet:SetText(j..LISTETOTAL..i..")"); RegistreFicheSousTitre:SetText(LISTELEGENDE); if j > 0 then PanelRegistreListeEmpty:SetText(""); else PanelRegistreListeEmpty:SetText(LISTEEMPTYREG); end if j > 10 then ListeButtonSlider:Show(); local total = floor((j-1)/10); ListeButtonSlider:SetMinMaxValues(0,total); end -- Tri de PersoTab[j] table.sort(PersoTab); ChargerListeVertical(ListeButtonSlider:GetValue()); end function cacherCroixDeletePerso() for k=0,9,1 do --Initialisation getglobal("ListeButtonPerso"..k.."Delete"):Hide(); end end function getTabMember() local id, name; wipe(TabMember); for i=1, MAX_CHANNEL_BUTTONS, 1 do name = GetChannelDisplayInfo(i); if name == "xtensionxtooltip2" then id = i; break; end end local i=1; while GetChannelRosterInfo(id, i) and i < 250 do name = GetChannelRosterInfo(id, i); TabMember[name] = 1; i = i + 1; end end function ChargerListeVertical(num) for k=0,9,1 do --Initialisation getglobal("ListeButtonPerso"..k):Hide(); getglobal("ListeButtonPerso"..k):SetText(FICHE); getglobal("ListeButtonPerso"..k.."Text"):Hide(); getglobal("ListeButtonPerso"..k.."Icon"):Hide(); end cacherCroixDeletePerso(); -- Construction du tableau de nom; if PersoTab ~= nil then local i = 1; local j = 0; table.foreach(PersoTab, function(PersonnageButton) if i > num*10 and i <= (num+1)*10 then local Nom = PersoTab[PersonnageButton]; getglobal("ListeButtonPerso"..j):Show(); getglobal("ListeButtonPerso"..j):SetScript("OnClick", function() PanelOpen("FicheJoueurOngletRegistre","General",Nom) end ); getglobal("ListeButtonPerso"..j.."Text"):Show(); getglobal("ListeButtonPerso"..j.."Date"):SetText(TRP_Module_Registre[Royaume][Nom]["Date"]); getglobal("ListeButtonPerso"..j.."DeleteNom"):SetText(Nom); local NomComplet = relation_color[TRP_Module_PlayerInfo_Relations[Royaume][Nom][Joueur]]; if TRP_Module_Registre[Royaume][Nom]["Prenom"] and TRP_Module_Registre[Royaume][Nom]["Prenom"] ~= "" then NomComplet = NomComplet..TRP_Module_Registre[Royaume][Nom]["Prenom"]; else NomComplet = NomComplet..Nom; end if TRP_Module_Registre[Royaume][Nom]["Nom"] and TRP_Module_Registre[Royaume][Nom]["Nom"] ~= "" then NomComplet = NomComplet.." "..TRP_Module_Registre[Royaume][Nom]["Nom"]; end if TabMember[Nom] then local prefixe = "("; if TabMember[Nom] then prefixe = prefixe.."|TInterface\\BUTTONS\\UI-CheckBox-Check.blp:25:25|t"; end prefixe = prefixe..") "; NomComplet = prefixe..NomComplet; end getglobal("ListeButtonPerso"..j.."Text"):SetText(NomComplet); if TRP_Module_Registre[Royaume][Nom]["Faction"] == "Alliance" then getglobal("ListeButtonPerso"..j.."Icon"):SetTexture("Interface\\BattlefieldFrame\\Battleground-Alliance.blp"); elseif TRP_Module_Registre[Royaume][Nom]["Faction"] == "Horde" then getglobal("ListeButtonPerso"..j.."Icon"):SetTexture("Interface\\BattlefieldFrame\\Battleground-Horde.blp"); end getglobal("ListeButtonPerso"..j.."Icon"):Show(); j = j + 1; end i = i + 1; end); end end function nomComplet(nom) if nom == nil or nom == "" then return "Erreur de Nom"; end local Prenom = nom; local NomFamille = ""; local Titre = ""; local tableau; if nom == Joueur then tableau = TRP_Module_PlayerInfo; else tableau = TRP_Module_Registre; end if tableau == nil then return "Not loaded yet." end -- Si tentative de nomComplet avant la fin du chargement de l'add-on if tableau[Royaume][nom]~=nil and tableau[Royaume][nom]["Titre"] ~= nil and tableau[Royaume][nom]["Titre"] ~= "" then Titre = tableau[Royaume][nom]["Titre"].." "; end if tableau[Royaume][nom]~=nil and tableau[Royaume][nom]["Prenom"] ~= nil and tableau[Royaume][nom]["Prenom"] ~= "" then Prenom = tableau[Royaume][nom]["Prenom"]; end if tableau[Royaume][nom]~=nil and tableau[Royaume][nom]["Nom"] ~= nil and tableau[Royaume][nom]["Nom"] ~= "" then NomFamille = " "..tableau[Royaume][nom]["Nom"]; end return tostring(Titre..Prenom..NomFamille); end function DecodeRSP(arg1, arg2) -- R\195\169cup\195\169ration des info de ["xtensionxtooltip2"] . C'est crade comme fonction : normal ca viens de FlagRSP2 if string.find(arg1,"<") == nil then return; end if arg2 == Joueur then RSPInit = true; return; end -- arg1 = l'information , arg2 = le personnage if TRP_Module_Registre[Royaume][arg2] ~= nil then if TRP_Module_Registre[Royaume][arg2]["Type"] == 1 or isBanned(nom) then return; -- Joueur TRP ou joueur banni ! else TRP_Module_Registre[Royaume][arg2]["Type"] = 2;--Joueur RSP end end if string.find(string.sub(arg1,2,string.len(arg1)),"<") ~= nil then firstBrack = string.find(string.sub(arg1,2,string.len(arg1)),"<"); firstComm = string.sub(arg1,1,firstBrack); rest = string.sub(arg1,firstBrack+1, string.len(arg1)); DecodeRSP(firstComm, arg2); DecodeRSP(rest, arg2); elseif string.find(string.sub(arg1,2,string.len(arg1)),"<") == nil then --Sous Titre if string.sub(arg1, 1, 3) == "<T>" then if string.sub(arg1, 4, string.len(arg1)) ~= "" then if TRP_Module_Registre[Royaume][arg2] == nil then AjouterAuRegistre(arg2); TRP_Module_Registre[Royaume][arg2]["Nom"] = ""; TRP_Module_Registre[Royaume][arg2]["Titre"] = ""; TRP_Module_Registre[Royaume][arg2]["SousTitre"] = ""; TRP_Module_Registre[Royaume][arg2]["Type"] = 2; end TRP_Module_Registre[Royaume][arg2]["SousTitre"] = string.sub(arg1, 4, string.len(arg1)); if arg2 == UnitName("target") then changeTarget(); end end --Titre et Nom elseif string.sub(arg1, 1, 3) == "<AN" then local cAN = string.sub(arg1,4,4); if cAN == "1" then if string.sub(arg1, 6, string.len(arg1)) ~= "" then if TRP_Module_Registre[Royaume][arg2] == nil then AjouterAuRegistre(arg2); TRP_Module_Registre[Royaume][arg2]["Nom"] = ""; TRP_Module_Registre[Royaume][arg2]["Titre"] = ""; TRP_Module_Registre[Royaume][arg2]["SousTitre"] = ""; TRP_Module_Registre[Royaume][arg2]["Type"] = 2; end TRP_Module_Registre[Royaume][arg2]["Titre"] = string.sub(arg1, 6, string.len(arg1)); end elseif cAN == "3" then if string.sub(arg1, 6, string.len(arg1)) ~= "" then if TRP_Module_Registre[Royaume][arg2] == nil then AjouterAuRegistre(arg2); TRP_Module_Registre[Royaume][arg2]["Nom"] = ""; TRP_Module_Registre[Royaume][arg2]["Titre"] = ""; TRP_Module_Registre[Royaume][arg2]["SousTitre"] = ""; TRP_Module_Registre[Royaume][arg2]["Type"] = 2; end TRP_Module_Registre[Royaume][arg2]["Nom"] = string.sub(arg1, 6, string.len(arg1)); TRPSecureSendAddonMessage("GTI",DonnerInfos(),arg2); end end if arg2 == UnitName("target") then changeTarget(); end -- Description elseif (string.sub(arg1, 1, 2) == "<D" and tonumber(string.sub(arg1, 3, 4)) ~= nil ) then local position = tonumber(string.sub(arg1, 3, 4)) local descri = string.gsub(string.sub(arg1, 6, string.len(arg1)),"\\l","\n"); descri = string.gsub(descri,"\\eod","") if descri ~= "" then if TRP_Module_Registre[Royaume][arg2] == nil then AjouterAuRegistre(arg2); TRP_Module_Registre[Royaume][arg2]["Nom"] = ""; TRP_Module_Registre[Royaume][arg2]["Titre"] = ""; TRP_Module_Registre[Royaume][arg2]["SousTitre"] = ""; TRP_Module_Registre[Royaume][arg2]["Type"] = 2; end local pattern = "%[Ce joueur utilise Total RP!%]" if string.find(descri,pattern) ~= nil then descri = string.gsub(descri,pattern,""); TRP_Module_Registre[Royaume][arg2]["Type"] = 1; end if TRP_Module_Registre[Royaume][arg2]["Description"] == nil then TRP_Module_Registre[Royaume][arg2]["Description"] = {}; end TRP_Module_Registre[Royaume][arg2]["Description"][position] = descri; end if arg2 == UnitName("target") then changeTarget(); end end end end function Reinit_Personnages() for k=1,42,1 do --Initialisation getglobal("ListePersonnagesSlot"..k.."ID"):SetText(""); getglobal("ListePersonnagesSlot"..k.."Royaume"):SetText(""); getglobal("ListePersonnagesSlot"..k.."Icon"):SetTexture("Interface\\ICONS\\INV_Misc_GroupLooking.blp"); getglobal("ListePersonnagesSlot"..k):SetButtonState("NORMAL"); getglobal("ListePersonnagesSlot"..k):Hide(); end end function calculerListePersonnage(selfPerso) local recherche = TRPPersonnageListRecherche:GetText(); local j = 0; ListePersonnagesSlider:Hide(); ListePersonnagesSlider:SetValue(0); wipe(PersonnageTab); TRPListePersonnagesEmpty:Hide(); if TRPListePersonnagesType:GetText() == "2" then table.foreach(TRP_Module_PlayerInfo, function(royaumes) table.foreach(TRP_Module_PlayerInfo[royaumes], function(perso) if (recherche ~= "" and string.find(string.lower(perso),string.lower(recherche)) ~= nil) or (recherche ~= "" and string.find(string.lower(royaumes),string.lower(recherche)) ~= nil) or recherche == "" then if royaumes ~= Royaume or (royaumes == Royaume and perso ~= Joueur) then PersonnageTab[j+1] = {}; PersonnageTab[j+1][1] = perso; PersonnageTab[j+1][2] = royaumes; j = j+1; end end end); end); else table.foreach(TRP_Module_Registre[Royaume], function(perso) if (recherche ~= "" and string.find(string.lower(perso),string.lower(recherche)) ~= nil) or recherche == "" then PersonnageTab[j+1] = {}; PersonnageTab[j+1][1] = perso; j = j+1; end end); end --table.sort(PersonnageTab); if j > 42 then local total = floor((j-1)/42); ListePersonnagesSlider:Show(); ListePersonnagesSlider:SetMinMaxValues(0,total); elseif j == 0 then TRPListePersonnagesEmpty:Show(); end ChargerSliderListePersonnages(0); end function ChargerSliderListePersonnages(num) Reinit_Personnages(); if PersonnageTab ~= nil then for k=1,42,1 do local i = num*42 + k; if PersonnageTab[i] ~= nil then getglobal("ListePersonnagesSlot"..k):Show(); getglobal("ListePersonnagesSlot"..k.."ID"):SetText(PersonnageTab[i][1]); if PersonnageTab[i][2] ~= nil then getglobal("ListePersonnagesSlot"..k.."Royaume"):SetText(PersonnageTab[i][2]); if TRP_Module_PlayerInfo[PersonnageTab[i][2]][PersonnageTab[i][1]]["Race"] ~= nil and TRP_Module_PlayerInfo[PersonnageTab[i][2]][PersonnageTab[i][1]]["Sex"] ~= nil and TRP_Module_PlayerInfo[PersonnageTab[i][2]][PersonnageTab[i][1]]["Sex"] >= 2 then local textureFinale = "Interface\\ICONS\\Achievement_Character_"..textureRace[TRP_Module_PlayerInfo[PersonnageTab[i][2]][PersonnageTab[i][1]]["Race"]].."_"..textureSex[TRP_Module_PlayerInfo[PersonnageTab[i][2]][PersonnageTab[i][1]]["Sex"]]..".blp"; getglobal("ListePersonnagesSlot"..k.."Icon"):SetTexture(textureFinale); end else if TRP_Module_Registre[Royaume][PersonnageTab[i][1]]["Race"] ~= nil and TRP_Module_Registre[Royaume][PersonnageTab[i][1]]["Sex"] ~= nil and TRP_Module_Registre[Royaume][PersonnageTab[i][1]]["Sex"] >= 2 then local textureFinale = "Interface\\ICONS\\Achievement_Character_"..textureRace[TRP_Module_Registre[Royaume][PersonnageTab[i][1]]["Race"]].."_"..textureSex[TRP_Module_Registre[Royaume][PersonnageTab[i][1]]["Sex"]]..".blp"; getglobal("ListePersonnagesSlot"..k.."Icon"):SetTexture(textureFinale); end end end end end end
--[[-- Additions to the core io module. The module table returned by `std.io` also contains all of the entries from the core `io` module table. An hygienic way to import this module, then, is simply to override core `io` locally: local io = require "std.io" @module std.io ]] local base = require "atf.stdlib.std.base" local debug = require "atf.stdlib.std.debug" local argerror = debug.argerror local catfile, dirsep, insert, len, leaves, split = base.catfile, base.dirsep, base.insert, base.len, base.leaves, base.split local ipairs, pairs = base.ipairs, base.pairs local setmetatable = debug.setmetatable local M, monkeys local function input_handle (h) if h == nil then return io.input () elseif type (h) == "string" then return io.open (h) end return h end local function slurp (file) local h, err = input_handle (file) if h == nil then argerror ("std.io.slurp", 1, err, 2) end if h then local s = h:read ("*a") h:close () return s end end local function readlines (file) local h, err = input_handle (file) if h == nil then argerror ("std.io.readlines", 1, err, 2) end local l = {} for line in h:lines () do l[#l + 1] = line end h:close () return l end local function writelines (h, ...) if io.type (h) ~= "file" then io.write (h, "\n") h = io.output () end for v in leaves (ipairs, {...}) do h:write (v, "\n") end end local function monkey_patch (namespace) namespace = namespace or _G namespace.io = base.copy (namespace.io or {}, monkeys) if namespace.io.stdin then local mt = getmetatable (namespace.io.stdin) or {} mt.readlines = M.readlines mt.writelines = M.writelines setmetatable (namespace.io.stdin, mt) end return M end local function process_files (fn) -- N.B. "arg" below refers to the global array of command-line args if len (arg) == 0 then insert (arg, "-") end for i, v in ipairs (arg) do if v == "-" then io.input (io.stdin) else io.input (v) end fn (v, i) end end local function warnfmt (msg, ...) local prefix = "" if (prog or {}).name then prefix = prog.name .. ":" if prog.line then prefix = prefix .. tostring (prog.line) .. ":" end elseif (prog or {}).file then prefix = prog.file .. ":" if prog.line then prefix = prefix .. tostring (prog.line) .. ":" end elseif (opts or {}).program then prefix = opts.program .. ":" if opts.line then prefix = prefix .. tostring (opts.line) .. ":" end end if #prefix > 0 then prefix = prefix .. " " end return prefix .. string.format (msg, ...) end local function warn (msg, ...) writelines (io.stderr, warnfmt (msg, ...)) end --[[ ================= ]]-- --[[ Public Interface. ]]-- --[[ ================= ]]-- local function X (decl, fn) return debug.argscheck ("std.io." .. decl, fn) end M = { --- Concatenate directory names into a path. -- @function catdir -- @string ... path components -- @return path without trailing separator -- @see catfile -- @usage dirpath = catdir ("", "absolute", "directory") catdir = X ("catdir (string...)", function (...) return (table.concat ({...}, dirsep):gsub("^$", dirsep)) end), --- Concatenate one or more directories and a filename into a path. -- @function catfile -- @string ... path components -- @treturn string path -- @see catdir -- @see splitdir -- @usage filepath = catfile ("relative", "path", "filename") catfile = X ("catfile (string...)", base.catfile), --- Die with error. -- This function uses the same rules to build a message prefix -- as @{warn}. -- @function die -- @string msg format string -- @param ... additional arguments to plug format string specifiers -- @see warn -- @usage die ("oh noes! (%s)", tostring (obj)) die = X ("die (string, [any...])", function (...) error (warnfmt (...), 0) end), --- Remove the last dirsep delimited element from a path. -- @function dirname -- @string path file path -- @treturn string a new path with the last dirsep and following -- truncated -- @usage dir = dirname "/base/subdir/filename" dirname = X ("dirname (string)", function (path) return (path:gsub (catfile ("", "[^", "]*$"), "")) end), --- Overwrite core `io` methods with `std` enhanced versions. -- -- Also adds @{readlines} and @{writelines} metamethods to core file objects. -- @function monkey_patch -- @tparam[opt=_G] table namespace where to install global functions -- @treturn table the `std.io` module table -- @usage local io = require "std.io".monkey_patch () monkey_patch = X ("monkey_patch (?table)", monkey_patch), --- Process files specified on the command-line. -- Each filename is made the default input source with `io.input`, and -- then the filename and argument number are passed to the callback -- function. In list of filenames, `-` means `io.stdin`. If no -- filenames were given, behave as if a single `-` was passed. -- @todo Make the file list an argument to the function. -- @function process_files -- @tparam fileprocessor fn function called for each file argument -- @usage -- #! /usr/bin/env lua -- -- minimal cat command -- local io = require "std.io" -- io.process_files (function () io.write (io.slurp ()) end) process_files = X ("process_files (function)", process_files), --- Read a file or file handle into a list of lines. -- The lines in the returned list are not `\n` terminated. -- @function readlines -- @tparam[opt=io.input()] file|string file file handle or name; -- if file is a file handle, that file is closed after reading -- @treturn list lines -- @usage list = readlines "/etc/passwd" readlines = X ("readlines (?file|string)", readlines), --- Perform a shell command and return its output. -- @function shell -- @string c command -- @treturn string output, or nil if error -- @see os.execute -- @usage users = shell [[cat /etc/passwd | awk -F: '{print $1;}']] shell = X ("shell (string)", function (c) return slurp (io.popen (c)) end), --- Slurp a file handle. -- @function slurp -- @tparam[opt=io.input()] file|string file file handle or name; -- if file is a file handle, that file is closed after reading -- @return contents of file or handle, or nil if error -- @see process_files -- @usage contents = slurp (filename) slurp = X ("slurp (?file|string)", slurp), --- Split a directory path into components. -- Empty components are retained: the root directory becomes `{"", ""}`. -- @function splitdir -- @param path path -- @return list of path components -- @see catdir -- @usage dir_components = splitdir (filepath) splitdir = X ("splitdir (string)", function (path) return split (path, dirsep) end), --- Give warning with the name of program and file (if any). -- If there is a global `prog` table, prefix the message with -- `prog.name` or `prog.file`, and `prog.line` if any. Otherwise -- if there is a global `opts` table, prefix the message with -- `opts.program` and `opts.line` if any. @{std.optparse:parse} -- returns an `opts` table that provides the required `program` -- field, as long as you assign it back to `_G.opts`. -- @function warn -- @string msg format string -- @param ... additional arguments to plug format string specifiers -- @see std.optparse:parse -- @see die -- @usage -- local OptionParser = require "std.optparse" -- local parser = OptionParser "eg 0\nUsage: eg\n" -- _G.arg, _G.opts = parser:parse (_G.arg) -- if not _G.opts.keep_going then -- require "std.io".warn "oh noes!" -- end warn = X ("warn (string, [any...])", warn), --- Write values adding a newline after each. -- @function writelines -- @tparam[opt=io.output()] file h open writable file handle; -- the file is **not** closed after writing -- @tparam string|number ... values to write (as for write) -- @usage writelines (io.stdout, "first line", "next line") writelines = X ("writelines (?file|string|number, [string|number...])", writelines), } monkeys = base.copy ({}, M) -- before deprecations and core merge return base.merge (M, io) --- Types -- @section Types --- Signature of @{process_files} callback function. -- @function fileprocessor -- @string filename filename -- @int i argument number of *filename* -- @usage -- local fileprocessor = function (filename, i) -- io.write (tostring (i) .. ":\n===\n" .. io.slurp (filename) .. "\n") -- end -- io.process_files (fileprocessor)
local default_config= { center_text_zoom= .5, item_text_zoom= .5, center_radius= 28, item_radius= 8, item_pad= 8, item_focus_zoom= 1.5, xoff= 0, yoff= 0, } steps_menu_config= create_setting( "steps menu config", "steps_menu_config.lua", default_config, -1) steps_menu_config:load()
RegisterCommand( "dv", function() TriggerEvent( "wk:deleteVehicle" ) end, false ) TriggerEvent( "chat:addSuggestion", "/dv", "Deletes the vehicle you're sat in, or standing next to." ) -- The distance to check in front of the player for a vehicle local distanceToCheck = 5.0 -- The number of times to retry deleting a vehicle if it fails the first time local numRetries = 5 -- Add an event handler for the deleteVehicle event. Gets called when a user types in /dv in chat RegisterNetEvent( "wk:deleteVehicle" ) AddEventHandler( "wk:deleteVehicle", function() local ped = GetPlayerPed( -1 ) if ( DoesEntityExist( ped ) and not IsEntityDead( ped ) ) then local pos = GetEntityCoords( ped ) if ( IsPedSittingInAnyVehicle( ped ) ) then local vehicle = GetVehiclePedIsIn( ped, false ) if ( GetPedInVehicleSeat( vehicle, -1 ) == ped ) then DeleteGivenVehicle( vehicle, numRetries ) else Notify( "You must be in the driver's seat!" ) end else local inFrontOfPlayer = GetOffsetFromEntityInWorldCoords( ped, 0.0, distanceToCheck, 0.0 ) local vehicle = GetVehicleInDirection( ped, pos, inFrontOfPlayer ) if ( DoesEntityExist( vehicle ) ) then DeleteGivenVehicle( vehicle, numRetries ) else Notify( "~y~You must be in or near a vehicle to delete it." ) end end end end ) function DeleteGivenVehicle( veh, timeoutMax ) local timeout = 0 SetEntityAsMissionEntity( veh, true, true ) DeleteVehicle( veh ) if ( DoesEntityExist( veh ) ) then Notify( "~r~Failed to delete vehicle, trying again..." ) -- Fallback if the vehicle doesn't get deleted while ( DoesEntityExist( veh ) and timeout < timeoutMax ) do DeleteVehicle( veh ) -- The vehicle has been banished from the face of the Earth! if ( not DoesEntityExist( veh ) ) then Notify( "~g~Vehicle deleted." ) end -- Increase the timeout counter and make the system wait timeout = timeout + 1 Citizen.Wait( 500 ) -- We've timed out and the vehicle still hasn't been deleted. if ( DoesEntityExist( veh ) and ( timeout == timeoutMax - 1 ) ) then Notify( "~r~Failed to delete vehicle after " .. timeoutMax .. " retries." ) end end else Notify( "~g~Vehicle deleted." ) end end -- Gets a vehicle in a certain direction -- Credit to Konijima function GetVehicleInDirection( entFrom, coordFrom, coordTo ) local rayHandle = StartShapeTestCapsule( coordFrom.x, coordFrom.y, coordFrom.z, coordTo.x, coordTo.y, coordTo.z, 5.0, 10, entFrom, 7 ) local _, _, _, _, vehicle = GetShapeTestResult( rayHandle ) if ( IsEntityAVehicle( vehicle ) ) then return vehicle end end -- Shows a notification on the player's screen function Notify( text ) SetNotificationTextEntry( "STRING" ) AddTextComponentString( text ) DrawNotification( false, false ) end
----------------------------------------------------------------------------------------------- -- Ferns - Tree Fern 0.1.1 ----------------------------------------------------------------------------------------------- -- by Mossmanikin -- License (everything): WTFPL -- Contains code from: biome_lib -- Looked at code from: default , trees ----------------------------------------------------------------------------------------------- assert(abstract_ferns.config.enable_treefern == true) abstract_ferns.grow_tree_fern = function(pos) local pos_01 = {x = pos.x, y = pos.y + 1, z = pos.z} if minetest.get_node(pos_01).name ~= "air" and minetest.get_node(pos_01).name ~= "ferns:sapling_tree_fern" and minetest.get_node(pos_01).name ~= "default:junglegrass" then return end local size = math.random(1, 4) + math.random(1, 4) if (size > 5) then size = 10 - size end size = size + 1 local crown = ({ "ferns:tree_fern_leaves", "ferns:tree_fern_leaves_02" })[math.random(1, 2)] local i = 1 while (i < size-1) do if minetest.get_node({x = pos.x, y = pos.y + i + 1, z = pos.z}).name ~= "air" then break end minetest.set_node({x = pos.x, y = pos.y + i, z = pos.z}, { name = "ferns:fern_trunk" }) i = i + 1 end minetest.set_node({x = pos.x, y = pos.y + i, z = pos.z}, { name = crown }) end ----------------------------------------------------------------------------------------------- -- TREE FERN LEAVES ----------------------------------------------------------------------------------------------- -- TODO: Both of these nodes look the same? minetest.register_node("ferns:tree_fern_leaves", { description = "Tree Fern Crown (Dicksonia)", drawtype = "plantlike", visual_scale = 2, paramtype = "light", paramtype2 = "facedir", --tiles = {"[combine:32x32:0,0=top_left.png:0,16=bottom_left.png:16,0=top_right.png:16,16=bottom_right.png"}, tiles = {"ferns_fern_tree.png"}, inventory_image = "ferns_fern_tree_inv.png", walkable = false, groups = {snappy=3,flammable=2,attached_node=1}, drop = { max_items = 2, items = { { -- occasionally, drop a second sapling instead of leaves -- (extra saplings can also be obtained by replanting and -- reharvesting leaves) items = {"ferns:sapling_tree_fern"}, rarity = 10, }, { items = {"ferns:sapling_tree_fern"}, }, -- { -- items = {"ferns:tree_fern_leaves"}, -- } } }, sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = {-7/16, -1/2, -7/16, 7/16, 0, 7/16}, }, }) minetest.register_node("ferns:tree_fern_leaves_02", { drawtype = "plantlike", visual_scale = 2, paramtype = "light", tiles = {"ferns_fern_big.png"}, walkable = false, groups = {snappy=3,flammable=2,attached_node=1,not_in_creative_inventory=1}, drop = { max_items = 2, items = { { -- occasionally, drop a second sapling instead of leaves -- (extra saplings can also be obtained by replanting and -- reharvesting leaves) items = {"ferns:sapling_tree_fern"}, rarity = 10, }, { items = {"ferns:sapling_tree_fern"}, }, -- { -- items = {"ferns:tree_fern_leaves"}, -- } } }, sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = {-7/16, -1/2, -7/16, 7/16, 0, 7/16}, }, }) ----------------------------------------------------------------------------------------------- -- FERN TRUNK ----------------------------------------------------------------------------------------------- minetest.register_node("ferns:fern_trunk", { description = "Fern Trunk (Dicksonia)", drawtype = "nodebox", paramtype = "light", tiles = { "ferns_fern_trunk_top.png", "ferns_fern_trunk_top.png", "ferns_fern_trunk.png" }, node_box = { type = "fixed", fixed = {-1/8, -1/2, -1/8, 1/8, 1/2, 1/8}, }, selection_box = { type = "fixed", fixed = {-1/7, -1/2, -1/7, 1/7, 1/2, 1/7}, }, groups = {tree=1,choppy=2,oddly_breakable_by_hand=2,flammable=3,wood=1}, sounds = default.node_sound_wood_defaults(), after_dig_node = function(pos, oldnode, oldmetadata, digger) local node = minetest.get_node({x=pos.x,y=pos.y+1,z=pos.z}) if node.name == "ferns:fern_trunk" then minetest.node_dig({x=pos.x,y=pos.y+1,z=pos.z}, node, digger) end end, }) ----------------------------------------------------------------------------------------------- -- TREE FERN SAPLING ----------------------------------------------------------------------------------------------- minetest.register_node("ferns:sapling_tree_fern", { description = "Tree Fern Sapling (Dicksonia)", drawtype = "plantlike", paramtype = "light", paramtype2 = "facedir", tiles = {"ferns_sapling_tree_fern.png"}, inventory_image = "ferns_sapling_tree_fern.png", walkable = false, groups = {snappy=3,flammable=2,flora=1,attached_node=1}, sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = {-7/16, -1/2, -7/16, 7/16, 0, 7/16}, }, }) -- abm minetest.register_abm({ nodenames = "ferns:sapling_tree_fern", interval = 1000, chance = 4, action = function(pos, node, _, _) abstract_ferns.grow_tree_fern({x = pos.x, y = pos.y-1, z = pos.z}) end }) ----------------------------------------------------------------------------------------------- -- GENERATE TREE FERN ----------------------------------------------------------------------------------------------- -- in jungles if abstract_ferns.config.enable_treeferns_in_jungle == true then biome_lib:register_generate_plant({ surface = { "default:dirt_with_grass", "default:sand", "default:desert_sand", }, max_count = 35,--27, avoid_nodes = {"default:tree"}, avoid_radius = 4, rarity = 50, seed_diff = 329, min_elevation = -10, near_nodes = {"default:jungletree"}, near_nodes_size = 6, near_nodes_vertical = 2,--4, near_nodes_count = 1, plantlife_limit = -0.9, humidity_max = -1.0, humidity_min = 0.4, temp_max = -0.5, temp_min = 0.13, }, abstract_ferns.grow_tree_fern ) end -- for oases & tropical beaches if abstract_ferns.config.enable_treeferns_in_oases == true then biome_lib:register_generate_plant({ surface = { "default:sand"--, --"default:desert_sand" }, max_count = 35, rarity = 50, seed_diff = 329, neighbors = {"default:desert_sand"}, ncount = 1, min_elevation = 1, near_nodes = {"default:water_source"}, near_nodes_size = 2, near_nodes_vertical = 1, near_nodes_count = 1, plantlife_limit = -0.9, humidity_max = -1.0, humidity_min = 1.0, temp_max = -1.0, temp_min = 1.0, }, abstract_ferns.grow_tree_fern ) end
local MaskCrossEntropyCriterion, parent = torch.class('nn.MaskCrossEntropyCriterion', 'nn.Module') function MaskCrossEntropyCriterion:__init(weights) parent.__init(self) self.crc = nn.CrossEntropyCriterion(weights) end function MaskCrossEntropyCriterion:updateOutput(input, target) self.output = 0 local valid_idx = torch.nonzero(target) if valid_idx:nElement() > 0 then valid_idx = valid_idx:view(-1):long() local val_input = input:index(1, valid_idx):contiguous() local val_target = target:index(1, valid_idx):contiguous() self.crc:updateOutput(val_input, val_target) self.output = self.crc.output end return self.output end function MaskCrossEntropyCriterion:updateGradInput(input, target) self.gradInput:resizeAs(input):zero() local valid_idx = torch.nonzero(target) if valid_idx:nElement() > 0 then valid_idx = valid_idx:view(-1):long() local val_input = input:index(1, valid_idx):contiguous() local val_target = target:index(1, valid_idx):contiguous() self.crc:updateGradInput(val_input, val_target) self.gradInput:indexCopy(1, valid_idx, self.crc.gradInput) end return self.gradInput end
function model.setFrameDoorState(s) simBWF.callCustomizationScriptFunction('model.ext.adjustFrame',model.handles.frameModel,nil,nil,nil,s) end function model.setFrameState(s) simBWF.callCustomizationScriptFunction('model.ext.adjustFrame',model.handles.frameModel,s,nil,nil,nil) end function model.hideHousing(hide) for i=1,#model.handles.housingItems,1 do local l=1 if hide then l=0 end sim.setObjectInt32Parameter(model.handles.housingItems[i],sim.objintparam_visibility_layer,l) end end function model.getAvailableTrackingWindows(pick) local theType=0 if not pick then theType=1 end local l=sim.getObjectsInTree(sim.handle_scene,sim.handle_all,0) local retL={} for i=1,#l,1 do local data=sim.readCustomDataBlock(l[i],simBWF.modelTags.TRACKINGWINDOW) if data then data=sim.unpackTable(data) if data['type']==theType then -- 0 is for pick, 1 is for place retL[#retL+1]={simBWF.getObjectAltName(l[i]),l[i]} end end end return retL end function model.getAvailableFrames(pick) local theType=0 if not pick then theType=1 end local l=sim.getObjectsInTree(sim.handle_scene,sim.handle_all,0) local retL={} for i=1,#l,1 do local data=sim.readCustomDataBlock(l[i],simBWF.modelTags.LOCATIONFRAME) if data then data=sim.unpackTable(data) if data['type']==theType then -- 0 is for pick, 1 is for place retL[#retL+1]={simBWF.getObjectAltName(l[i]),l[i]} end end end return retL end function model.getAvailableConveyors() local l=sim.getObjectsInTree(sim.handle_scene,sim.handle_all,0) local retL={} for i=1,#l,1 do local data=sim.readCustomDataBlock(l[i],simBWF.modelTags.CONVEYOR) if data then retL[#retL+1]={simBWF.getObjectAltName(l[i]),l[i]} end end return retL end function model.getAvailableInputBoxes() local l=sim.getObjectsInTree(sim.handle_scene,sim.handle_all,0) local retL={} for i=1,#l,1 do local data=sim.readCustomDataBlock(l[i],simBWF.modelTags.INPUTBOX) if data then retL[#retL+1]={simBWF.getObjectAltName(l[i]),l[i]} end end return retL end function model.getAvailableOutputBoxes() local l=sim.getObjectsInTree(sim.handle_scene,sim.handle_all,0) local retL={} for i=1,#l,1 do local data=sim.readCustomDataBlock(l[i],simBWF.modelTags.OUTPUTBOX) if data then retL[#retL+1]={simBWF.getObjectAltName(l[i]),l[i]} end end return retL end function model.getModelInputOutputConnectionIndex(modelHandle,input) -- returns the connection index (1-6) if yes, otherwise -1: if modelHandle~=-1 then for i=1,8,1 do if input then if simBWF.getReferencedObjectHandle(model.handle,model.objRefIdx.INPUT1+i-1)==modelHandle then return i end else if simBWF.getReferencedObjectHandle(model.handle,model.objRefIdx.OUTPUT1+i-1)==modelHandle then return i end end end end return -1 end function model.disconnectInputOrOutputBoxConnection(modelHandle,input) local refreshDlg=false if modelHandle~=-1 then for i=1,8,1 do if simBWF.getReferencedObjectHandle(model.handle,model.objRefIdx.INPUT1+i-1)==modelHandle then simBWF.setReferencedObjectHandle(model.handle,model.objRefIdx.INPUT1+i-1,-1) refreshDlg=true break end if simBWF.getReferencedObjectHandle(model.handle,model.objRefIdx.OUTPUT1+i-1)==modelHandle then simBWF.setReferencedObjectHandle(model.handle,model.objRefIdx.OUTPUT1+i-1,-1) refreshDlg=true break end end end if refreshDlg then model.dlg.refresh() end end function model.getPlatform() return model.platform end function model.getPlatformUniqueId() local retVal='' if model.platform>=0 then retVal=sim.getObjectStringParameter(model.platform,sim.objstringparam_unique_id) end return retVal end function model.getGripper() return model.gripper end function model.getGripperUniqueId() local retVal='' if model.gripper>=0 then retVal=sim.getObjectStringParameter(model.gripper,sim.objstringparam_unique_id) end return retVal end function model.updateWs() local gripper=model.getGripper() if gripper>=0 then local grData=sim.unpackTable(sim.readCustomDataBlock(gripper,simBWF.modelTags.RAGNARGRIPPER)) local inf=model.readInfo() local primaryArmL=inf['primaryArmLengthInMM']/1000 local secondaryArmL=inf['secondaryArmLengthInMM']/1000 local alpha=sim.getJointPosition(model.handles.alphaOffsetJ1) local beta=sim.getJointPosition(model.handles.betaOffsetJ1) local ax=sim.getJointPosition(model.handles.xOffsetJ1) local ay=sim.getJointPosition(model.handles.yOffsetJ1) local r=grData.kinematricsParams[1] -- 0.15 local gamma1=grData.kinematricsParams[2] -- 0.5236 -- i.e. 30 deg local gamma2=grData.kinematricsParams[3] -- 2.0944 -- i.e. 120 deg local data={} data.details=1 -- See the ragnar.pdf document in the repository for the meaning of following arm parameters. -- For now, the plugin expects arm in following order: 3,4,1,2 -- Also, the plugin uses the negative of beta. local arm1Param={-ax, -ay, -alpha, -beta, primaryArmL, secondaryArmL, r, -gamma2} local arm2Param={ax, -ay, alpha, beta, primaryArmL, secondaryArmL, r, -gamma1} local arm3Param={ax, ay, -alpha, beta, primaryArmL, secondaryArmL, r, gamma1} local arm4Param={-ax, ay, alpha, -beta, primaryArmL, secondaryArmL, r, gamma2} local makeCorrections=true if makeCorrections then data.armParams={arm3Param,arm4Param,arm1Param,arm2Param} for i=1,4,1 do data.armParams[i][4]=data.armParams[i][4]*-1 end else data.armParams={arm1Param,arm2Param,arm3Param,arm4Param} end local res,retDat=simBWF.query("ragnar_ws",data) sim.removePointsFromPointCloud(model.handles.ragnarWs,0,nil,0) sim.insertPointsIntoPointCloud(model.handles.ragnarWs,1,retDat.points) end end function model.adjustRobot() ---[[ local inf=model.readInfo() local primaryArmLengthInMM=inf['primaryArmLengthInMM'] local secondaryArmLengthInMM=inf['secondaryArmLengthInMM'] -- local a=0.2+((primaryArmLengthInMM-200)/50)*0.05+0.0005 local a=primaryArmLengthInMM/1000 local b=secondaryArmLengthInMM/1000 local c=0.025 local x=math.sqrt(a*a-c*c) local primaryAdjust=x-math.sqrt(0.3*0.3-c*c) -- Initial lengths are 300 and 550 local secondaryAdjust=b-0.55 local dx=a*28/30 local ddx=dx-0.28 for i=1,4,1 do sim.setJointPosition(model.handles.primaryArmsEndAdjust[i],primaryAdjust) end for i=1,8,1 do sim.setJointPosition(model.handles.secondaryArmsEndAdjust[i],secondaryAdjust) end for i=1,4,1 do sim.setJointPosition(model.handles.primaryArmsLAdjust[i],primaryAdjust*0.5) end for i=1,8,1 do sim.setJointPosition(model.handles.secondaryArmsLAdjust[i],secondaryAdjust*0.5) end for i=1,2,1 do sim.setJointPosition(model.handles.leftAndRightSideAdjust[i],dx) end -- Scale the central elements in the X-direction: for i=1,#model.handles.centralCover,1 do local h=model.handles.centralCover[i] local r,minX=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_min_x) local r,maxX=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_max_x) local s=maxX-minX local desiredXSize=((a*28/30)-0.233+0.025+0.03)*2 if desiredXSize<0.049 then desiredXSize=0.05 end sim.scaleObject(h,desiredXSize/s,1,1) end -- Scale the "Ragnar Robot" meshes: for i=1,2,1 do local h=model.handles.nameElement[i] local r,minZ=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_min_z) local r,maxZ=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_max_z) local s=maxZ-minZ local d=0.3391 if a<0.399 then d=0.22 end if a<0.29 then d=0.1 end if a<0.24 then d=0.03 end --[[ local p=sim.getObjectPosition(h,-1) if d/s>1.1 then p[1]=p[1]+ end if d/s<0.9 then end --]] sim.scaleObject(h,d/s,d/s,d/s) end for i=1,4,1 do local h=model.handles.primaryArms[i] local r,minZ=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_min_z) local r,maxZ=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_max_z) local s=maxZ-minZ local d=0.242+primaryAdjust sim.scaleObject(h,1,1,d/s) end for i=1,8,1 do local h=model.handles.secondaryArms[i] local r,minZ=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_min_z) local r,maxZ=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_max_z) local s=maxZ-minZ local r,minX=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_min_x) local r,maxX=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_max_x) local sx=maxX-minX local d=0.5+secondaryAdjust local diam=0.01 if d>=0.5 then diam=0.014 end sim.scaleObject(h,diam/sx,diam/sx,d/s) end model.executeIk(true) -- The frame (width and height): local z=inf['frameHeightInMM']/1000 simBWF.callCustomizationScriptFunction('model.ext.adjustFrame',model.handles.frameModel,nil,2*ddx+0.9525,z+0.349,nil) local p=sim.getObjectPosition(model.handles.ragnarRef,sim.handle_parent) sim.setObjectPosition(model.handles.ragnarRef,sim.handle_parent,{p[1],p[2],z}) local p=sim.getObjectPosition(model.handles.frameModel,sim.handle_parent) sim.setObjectPosition(model.handles.frameModel,sim.handle_parent,{0,0,0}) model.workspaceUpdateRequest=sim.getSystemTimeInMs(-1) --]] end function model.setArmLength(primaryArmLengthInMM,secondaryArmLengthInMM) local allowedB={} -- in multiples of 50 allowedB[200]={400,450} allowedB[250]={450,600} allowedB[300]={550,700} allowedB[350]={650,800} allowedB[400]={750,900} allowedB[450]={850,1000} allowedB[500]={900,1150} allowedB[550]={1000,1250} local allowedA={} -- in multiples of 50 allowedA[400]={200,200} allowedA[450]={200,250} allowedA[500]={250,250} allowedA[550]={250,300} allowedA[600]={250,300} allowedA[650]={300,350} allowedA[700]={300,350} allowedA[750]={350,400} allowedA[800]={350,400} allowedA[850]={400,450} allowedA[900]={400,500} allowedA[950]={450,500} allowedA[1000]={450,550} allowedA[1050]={500,550} allowedA[1100]={500,550} allowedA[1150]={500,550} allowedA[1200]={550,550} allowedA[1250]={550,550} local c=model.readInfo() if primaryArmLengthInMM then -- We changed the primary arm length c['primaryArmLengthInMM']=primaryArmLengthInMM local allowed=allowedB[primaryArmLengthInMM] secondaryArmLengthInMM=c['secondaryArmLengthInMM'] if secondaryArmLengthInMM<allowed[1] then secondaryArmLengthInMM=allowed[1] end if secondaryArmLengthInMM>allowed[2] then secondaryArmLengthInMM=allowed[2] end c['secondaryArmLengthInMM']=secondaryArmLengthInMM else -- We changed the secondary arm length c['secondaryArmLengthInMM']=secondaryArmLengthInMM local allowed=allowedA[secondaryArmLengthInMM] primaryArmLengthInMM=c['primaryArmLengthInMM'] if primaryArmLengthInMM<allowed[1] then primaryArmLengthInMM=allowed[1] end if primaryArmLengthInMM>allowed[2] then primaryArmLengthInMM=allowed[2] end c['primaryArmLengthInMM']=primaryArmLengthInMM end model.writeInfo(c) simBWF.markUndoPoint() model.adjustRobot() model.dlg.refresh() end function model.setObjectSize(h,x,y,z) local r,mmin=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_min_x) local r,mmax=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_max_x) local sx=mmax-mmin local r,mmin=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_min_y) local r,mmax=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_max_y) local sy=mmax-mmin local r,mmin=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_min_z) local r,mmax=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_max_z) local sz=mmax-mmin sim.scaleObject(h,x/sx,y/sy,z/sz) end function model.adjustWsBox() local c=model.readInfo() local s={c.wsBox[2][1]-c.wsBox[1][1],c.wsBox[2][2]-c.wsBox[1][2],c.wsBox[2][3]-c.wsBox[1][3]} local p={(c.wsBox[2][1]+c.wsBox[1][1])/2,(c.wsBox[2][2]+c.wsBox[1][2])/2,(c.wsBox[2][3]+c.wsBox[1][3])/2} model.setObjectSize(model.handles.ragnarWsBox,s[1],s[2],s[3]) sim.setObjectPosition(model.handles.ragnarWsBox,model.handles.ragnarRef,p) end function model.adjustMaxVelocityMaxAcceleration() local c=model.readInfo() local mv=C.MOTORTYPES[c.motorType].maxVel local ma=C.MOTORTYPES[c.motorType].maxAccel if c['maxVel']>mv then c['maxVel']=mv simBWF.markUndoPoint() end if c['maxAccel']>ma then c['maxAccel']=ma simBWF.markUndoPoint() end model.writeInfo(c) end function model.attachOrDetachReferencedItem(previousItem,newItem) -- We keep the tracking windows and location frames as orphans, otherwise we might run into trouble with the calibration balls, etc. --[[ if previousItem>=0 then sim.setObjectParent(previousItem,-1,true) -- detach previous item end if newItem>=0 then sim.setObjectParent(newItem,model.handle,true) -- attach current item end --]] end function model.executeIk(platformInNominalConfig) if model.platform>=0 then if platformInNominalConfig then local inf=model.readInfo() local primaryArmLengthInMM=inf['primaryArmLengthInMM'] local secondaryArmLengthInMM=inf['secondaryArmLengthInMM'] sim.setObjectPosition(model.platform,sim.handle_parent,{0,0,-(secondaryArmLengthInMM-primaryArmLengthInMM)/1000-0.2}) sim.setObjectOrientation(model.platform,sim.handle_parent,{0,0,0}) end for i=1,4,1 do -- We handle each branch individually: local ld=sim.getLinkDummy(model.handles.ikTips[i]) if ld>=0 then -- We make sure we don't perform too large jumps: local p=sim.getObjectPosition(model.handles.ikTips[i],ld) local l=math.sqrt(p[1]*p[1]+p[2]*p[2]+p[3]*p[3]) local steps=math.ceil(0.00001+l/0.05) local start=sim.getObjectPosition(model.handles.ikTips[i],-1) local goal=sim.getObjectPosition(ld,-1) for j=1,steps,1 do local t=j/steps local pos={start[1]*(1-t)+goal[1]*t,start[2]*(1-t)+goal[2]*t,start[3]*(1-t)+goal[3]*t} sim.setObjectPosition(ld,-1,pos) sim.handleIkGroup(model.handles.ikGroups[i]) end end end end end function model.checkAndHandlePlatformAttachment() -- Here we need to check and react to following situations: -- 1. The user deleted the gripper or platform via the del or cut operation -- 2. The user detached the gripper or platform via the assembly/desassembly toolbar button -- 3. The user attached the gripper or platform via the assembly/desassembly toolbar button -- Platform attachment happens in 2 steps normally: -- a) the user attaches the platform to the robot via the toolbar button -- b) this routine detects that, and attaches the platform to the attachement point of the robot, handles IK, etc. local previousPlatform=model.platform local previousGripper=model.gripper local previousPlatformUniqueId=model.platformUniqueId local previousGripperUniqueId=model.gripperUniqueId local action=false -- Check if we want to attach a new platform to Ragnar (independently of whether there is already a platform attached): local objs=sim.getObjectsInTree(model.handle,sim.handle_all,1+2)-- first children of Ragnar model base only local newPlatform=-1 for i=1,#objs,1 do if sim.readCustomDataBlock(objs[i],simBWF.modelTags.RAGNARGRIPPERPLATFORM) then -- Yes! newPlatform=objs[i] break end end -- Now check if there is already a platform attached, remove it if we wanna attach a new platform: local currentPlatform=sim.getObjectChild(model.handles.ragnarGripperPlatformAttachment,0) if currentPlatform>=0 then -- Yes! if newPlatform>=0 then model.removeAndDeletePlatform() -- we remove the old platform, including a possible gripper attached to it. This also sets the arms into nominal configuration currentPlatform=-1 action=true end end if currentPlatform==-1 then -- Ok, we have no platform attached -- Check if a previous platform was detached but is still linked via IK (can happen if the user changes the parent of the platform): for i=1,#model.handles.ikTips,1 do local ld=sim.getLinkDummy(model.handles.ikTips[i]) if ld>=0 then sim.removeObject(ld) -- Yes, we delete the linked dummy on that old platform end end -- Did we have a platform attached previously? if previousPlatform>=0 then -- yes! Set the arm joints into nominal position model.removeAndDeletePlatform() action=true end -- Did we want to attach a new platform? if newPlatform>=0 then -- Now correctly attach the new platform and create target dummies model.attachPlatformToEmptySpot(newPlatform) action=true end end -- If we didn't have any action here, update the gripper handle and ID if not action then if model.platform>=0 then model.gripper=simBWF.callCustomizationScriptFunction('model.ext.getGripper',model.platform) model.gripperUniqueId=model.getGripperUniqueId() else model.gripper=-1 model.gripperUniqueId='' end end -- If something has changed, update the job data and serialized job-related models. Refresh the dialog: if previousPlatformUniqueId~=model.platformUniqueId or previousGripperUniqueId~=model.gripperUniqueId then model.updateJobDataFromCurrentSituation(model.currentJob) model.dlg.updateEnabledDisabledItems() end end function model.removeAndDeletePlatform() local platf=sim.getObjectChild(model.handles.ragnarGripperPlatformAttachment,0) if platf>=0 then -- remove the model: sim.removeModel(platf) end -- Set the arm joints into nominal position: for i=1,#model.handles.motorJoints,1 do local objs=sim.getObjectsInTree(model.handles.motorJoints[i],sim.object_joint_type,0) for j=1,#objs,1 do if sim.getJointMode(objs[j])==sim.jointmode_ik then sim.setJointPosition(objs[j],0) end end end model.platform=-1 model.gripper=-1 model.platformUniqueId='' model.gripperUniqueId='' model.dlg.updateEnabledDisabledItems() end function model.attachPlatformToEmptySpot(newPlatform) sim.setObjectParent(newPlatform,model.handles.ragnarGripperPlatformAttachment,true) local objs=sim.getObjectsInTree(newPlatform,sim.object_dummy_type,1) for i=1,#objs,1 do local data=sim.readCustomDataBlock(objs[i],simBWF.modelTags.RAGNARGRIPPERPLATFORMIKPT) if data then data=sim.unpackTable(data) local dum=sim.copyPasteObjects({objs[i]},0)[1] sim.setObjectParent(dum,objs[i],true) sim.setLinkDummy(model.handles.ikTips[data.index],dum) sim.setObjectInt32Parameter(dum,sim.dummyintparam_link_type,sim.dummy_linktype_ik_tip_target) end end model.platform=newPlatform model.gripper=simBWF.callCustomizationScriptFunction('model.ext.getGripper',model.platform) model.platformUniqueId=model.getPlatformUniqueId() model.gripperUniqueId=model.getGripperUniqueId() model.executeIk(true) model.dlg.updateEnabledDisabledItems() end function sysCall_init() model.codeVersion=1 model.dlg.init() model.adjustMaxVelocityMaxAcceleration() model.gripper=-1 model.platform=sim.getObjectChild(model.handles.ragnarGripperPlatformAttachment,0) if model.platform>=0 then -- Dont' call simBWF.callCustomizationScriptFunction('model.ext.getGripper',model.platform) -- since that can trigger many other calls. local objs=sim.getObjectsInTree(model.platform,sim.handle_all,1) for i=1,#objs,1 do if sim.readCustomDataBlock(objs[i],simBWF.modelTags.RAGNARGRIPPER) then model.gripper=objs[i] break end end end model.platformUniqueId=model.getPlatformUniqueId() model.gripperUniqueId=model.getGripperUniqueId() model.handleJobConsistency(simBWF.isModelACopy_ifYesRemoveCopyTag(model.handle)) model.checkAndHandlePlatformAttachment() model.updatePluginRepresentation() end function sysCall_nonSimulation() model.dlg.showOrHideDlgIfNeeded() model.checkAndHandlePlatformAttachment() model.updatePluginRepresentation() if model.workspaceUpdateRequest and sim.getSystemTimeInMs(model.workspaceUpdateRequest)>2000 then model.workspaceUpdateRequest=nil model.updateWs() end -- model.applyCalibrationData() -- can potentially change the position/orientation of the robot end function sysCall_sensing() if model.simJustStarted then model.dlg.updateEnabledDisabledItems() end model.simJustStarted=nil model.dlg.showOrHideDlgIfNeeded() model.ext.outputPluginRuntimeMessages() end function sysCall_suspended() model.dlg.showOrHideDlgIfNeeded() end function sysCall_afterSimulation() if model.ragnarNormalM then sim.setObjectMatrix(model.handle,-1,model.ragnarNormalM) model.ragnarNormalM=nil end model.dlg.updateEnabledDisabledItems() local c=model.readInfo() if sim.boolAnd32(c['bitCoded'],256)==256 then sim.setObjectInt32Parameter(model.handles.ragnarWs,sim.objintparam_visibility_layer,1) else sim.setObjectInt32Parameter(model.handles.ragnarWs,sim.objintparam_visibility_layer,0) end if sim.boolAnd32(c['bitCoded'],1)==1 then sim.setObjectInt32Parameter(model.handles.ragnarWsBox,sim.objintparam_visibility_layer,1) else sim.setObjectInt32Parameter(model.handles.ragnarWsBox,sim.objintparam_visibility_layer,0) end end function sysCall_beforeSimulation() model.simJustStarted=true model.ext.outputBrSetupMessages() model.ext.outputPluginSetupMessages() local c=model.readInfo() local showWs=simBWF.modifyAuxVisualizationItems(sim.boolAnd32(c['bitCoded'],256+512)==256+512) if showWs then sim.setObjectInt32Parameter(model.handles.ragnarWs,sim.objintparam_visibility_layer,1) else sim.setObjectInt32Parameter(model.handles.ragnarWs,sim.objintparam_visibility_layer,0) end local showWsBox=simBWF.modifyAuxVisualizationItems(sim.boolAnd32(c['bitCoded'],1+4)==1+4) if showWsBox then sim.setObjectInt32Parameter(model.handles.ragnarWsBox,sim.objintparam_visibility_layer,1) else sim.setObjectInt32Parameter(model.handles.ragnarWsBox,sim.objintparam_visibility_layer,0) end if sim.getBoolParameter(sim.boolparam_online_mode) then model.ragnarNormalM=sim.getObjectMatrix(model.handle,-1) model.applyCalibrationData() -- can potentially change the position/orientation of the robot model.setAttachedLocationFramesIntoCalibrationPose() end end function sysCall_beforeInstanceSwitch() model.dlg.removeDlg() model.removeFromPluginRepresentation() end function sysCall_afterInstanceSwitch() model.updatePluginRepresentation() end function sysCall_cleanup() model.dlg.removeDlg() model.removeFromPluginRepresentation() model.dlg.cleanup() end
------------------------------------------------------------------------------- -- actor ------------------------------------------------------------------------------- local _PACKAGE = (...):match("^(.+)[%./][^%./]+") or "" local setmetatable,error, tostring = setmetatable,error, tostring local table_unpack = unpack or table.unpack local coroutine = coroutine local coroutine_create = coroutine.create local coroutine_yield = coroutine.yield local coroutine_resume = coroutine.resume local coroutine_running = coroutine.running local coroutine_wrap = coroutine.wrap local cmsgpack = require "cmsgpack" local c = require "tengine.c" local pool = require(_PACKAGE .. "/pool") local send = c.send local pack = cmsgpack.pack local unpack = cmsgpack.unpack local INFO_MSG = tengine.INFO_MSG local DEBUG_MSG = tengine.DEBUG_MSG local ERROR_MSG = tengine.ERROR_MSG local actor = {} local session_to_coroutine = {} local coroutine_to_session = {} local coroutine_to_service = {} local raw_callback function actor.suspend(co, succ, command, ...) if not succ then error(debug.traceback(co, tostring(command))) end if command == "RETURN" then local session = coroutine_to_session[co] local service = coroutine_to_service[co] local ret if session > 0 then ret = send(service, session, pack({...})) else -- for send don't return end actor.suspend(co, coroutine_resume(co, ret)) elseif command == "CONTINUE" then else end end function actor.rpc(service, ...) local session = send(service, -1, pack({...})) return session end function actor.send(service, ...) local session = send(service, -1, pack({...})) return session end function actor.callback(service, callback, ...) local session = send(service, 0, pack({...})) if callback then local co = pool.new(callback) session_to_coroutine[session] = co end end function actor.call(service, ...) local thread = coroutine_running() actor.callback(service, function(...) actor.suspend(thread, coroutine_resume(thread, ...)) end, ...) return coroutine_yield("CALL") end function actor.ret(...) coroutine_yield("RETURN", ...) end local function callback(type, service, self, session, data) if type == 13 then local co = session_to_coroutine[session] if co then coroutine_resume(co, table_unpack(unpack(data))) session_to_coroutine[session] = nil end else if raw_callback then local co = pool.new(function(...) local r = raw_callback(table_unpack(unpack(...))) actor.ret(true, r) end) coroutine_to_service[co] = service coroutine_to_session[co] = session actor.suspend(co, coroutine_resume(co, data)) end end end function actor.start(func) c.dispatch(callback) raw_callback = func end function actor.newservice(name, ...) local args = table.concat({...}, " ") return c.start(name, args) end function actor.self() return __Service__ end function actor.wrap(id) return setmetatable({}, {__index = function(t, key) local id = id local func = key return function(...) return actor.call(id, key, ...) end end}) end function actor.sync(id) return setmetatable({}, {__index = function(t, key) local id = id local func = key return function(...) return actor.call(id, key, ...) end end}) end function actor.async(id) return setmetatable({}, {__index = function(t, key) local id = id local func = key return function(...) return actor.send(id, key, ...) end end}) end return actor
--------------------------------------------------------------------------------------------------- -- Common module --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local common = require("test_scripts/Protocol/commonProtocol") local constants = require("protocol_handler/ford_protocol_constants") --[[ General configuration parameters ]] common.testSettings.isSelfIncluded = false config.defaultProtocolVersion = 5 --[[ Common Variables ]] common.SERVICE_TYPE = constants.SERVICE_TYPE common.FRAME_TYPE = constants.FRAME_TYPE common.FRAME_INFO = constants.FRAME_INFO --[[ Common Functions ]] function common.startServiceNACKwithNonExistedSessionId(pServiceParams, pNonExistedSessionId, isEncrypted) isEncrypted = isEncrypted or false local mobSession = common.getMobileSession() mobSession.sessionId = pNonExistedSessionId local msg = { serviceType = pServiceParams.serviceType, frameType = common.FRAME_TYPE.CONTROL_FRAME, frameInfo = common.FRAME_INFO.START_SERVICE, encryption = isEncrypted, binaryData = common.bson_to_bytes(pServiceParams.reqParams) } mobSession:Send(msg) mobSession:ExpectControlMessage(pServiceParams.serviceType, { frameInfo = common.FRAME_INFO.START_SERVICE_NACK, encryption = false }) :ValidIf(function(_, data) local act = common.bson_to_table(data.binaryData) return compareValues(pServiceParams.nackParams, act, "binaryData") end) :Timeout(1000) common.hmi.getConnection():ExpectNotification("BasicCommunication.OnServiceUpdate", { serviceEvent = "REQUEST_RECEIVED", serviceType = pServiceParams.serviceName}, { serviceEvent = "REQUEST_REJECTED", serviceType = pServiceParams.serviceName }) :Times(2) end function common.startUnprotectedRPCservice() local session = common.getMobileSession() local msg = { serviceType = common.serviceType.RPC, frameType = constants.FRAME_TYPE.CONTROL_FRAME, frameInfo = constants.FRAME_INFO.START_SERVICE, encryption = false, binaryData = common.bson_to_bytes({ protocolVersion = { type = common.bsonType.STRING, value = "5.4.0" }}) } session:Send(msg) session:ExpectControlMessage(common.serviceType.RPC, { frameInfo = common.frameInfo.START_SERVICE_ACK, encryption = false }) end function common.startProtectedServiceWithOnServiceUpdate(pServiceParams) local appId = 1 common.startServiceProtectedNACK(appId, pServiceParams.serviceType, pServiceParams.reqParams, pServiceParams.nackParams) common.hmi.getConnection():ExpectNotification("BasicCommunication.OnServiceUpdate", { serviceEvent = "REQUEST_RECEIVED", serviceType = pServiceParams.serviceName }, { serviceEvent = "REQUEST_REJECTED", serviceType = pServiceParams.serviceName }) :Times(2) end function common.startWithoutOnSystemTimeReady(pHMIParams) local event = common.run.createEvent() common.init.SDL() :Do(function() common.init.HMI() :Do(function() common.init.HMI_onReady(pHMIParams) :Do(function() common.init.connectMobile() :Do(function() common.init.allowSDL() :Do(function() common.hmi.getConnection():RaiseEvent(event, "Start event") end) end) end) end) end) return common.hmi.getConnection():ExpectEvent(event, "Start event") end return common
local site_config = {} site_config.LUA_INCDIR=[[C:\Program Files (x86)\PUC-Lua\5.3\include]] site_config.LUA_LIBDIR=[[C:\Program Files (x86)\PUC-Lua\5.3\bin]] site_config.LUA_BINDIR=[[C:\Program Files (x86)\PUC-Lua\5.3\bin]] site_config.LUA_INTERPRETER=[[lua.exe]] site_config.LUAROCKS_UNAME_S=[[WindowsNT]] site_config.LUAROCKS_UNAME_M=[[x86]] site_config.LUAROCKS_ROCKS_TREE=[[c:\program files (x86)\puc-lua\5.3\]] site_config.LUAROCKS_PREFIX=[[C:\Program Files (x86)\LuaRocks]] site_config.LUAROCKS_DOWNLOADER=[[wget]] site_config.LUAROCKS_MD5CHECKER=[[md5sum]] return site_config
xChat = xChat or {} AddCSLuaFile("xchat/lib/chatdraw.lua") if SERVER then include("xchat/config.lua") include("xchat/commands.lua") include("xchat/lib/misc.lua") include("xchat/lib/get.lua") include("xchat/lib/init.lua") else include("xchat/lib/chatdraw.lua") end
--[[ TheNexusAvenger Test for camera animations. --]] local Workspace = game:GetService("Workspace") local BaseTest = require(script.Parent:WaitForChild("BaseTest")) local CameraTweensTest = BaseTest:Extend() CameraTweensTest:SetClassName("CameraTweensTest") --[[ Creates the test. --]] function CameraTweensTest:__new() self:InitializeSuper() --Set up the initial state. self.Name = "Camera Animations" self.Icon = "NONE" self.Status = "Not Detected" self.ProblemText = "Camera animations can cause motion sickness while playing in VR since it moves the player's view without the player moving." self.SolutionText = "Disable camera animations in VR." --Connect camera changes. local Camera = Workspace.CurrentCamera Camera:GetPropertyChangedSignal("CameraType"):Connect(function() self.LastScriptableTime = (Camera.CameraType == Enum.CameraType.Scriptable and tick() or 0) end) Camera:GetPropertyChangedSignal("CFrame"):Connect(function() if self.LastScriptableTime and tick() - self.LastScriptableTime > 1/60 then self.Icon = "WARNING" self.Status = "Problem Detected" end end) end return CameraTweensTest
return core.ComponentConstructor("CollisionComponent",{ make = function(entity) end, remove = function(entity) end })
-- @module core.theme local theme = {} local naughty = require("naughty") local beautiful = require("beautiful") local wallpaper = require("gears.wallpaper") local dpi = require("beautiful.xresources").apply_dpi local themes_path = require("gears.filesystem").get_themes_dir() function theme.setup() local color = { background = "#383838", foreground = "#e5dbd0", dark_gray = "#454545", red = "#da7c72", green = "#b8b48a", orange = "#dfa883", blue = "#93b3a3", magenta = "#cc9999", cyan = "#9fb193", bright_white = "#f2e7e0", gray = "#998f85", yellow = "#f7d0a2" } -- use a simple solid color as wallpaper to avoid distraction wallpaper.set(color.background) local config = {} config.default_dir = themes_path .. "default" config.font = "Source Code Pro 10" config.useless_gap = dpi(7) config.border_width = dpi(4) -- define color theme config.bg_normal = color.background config.bg_focus = config.bg_normal config.bg_urgent = config.bg_normal config.bg_minimize = config.bg_normal config.bg_systray = config.bg_normal config.fg_normal = color.foreground config.fg_focus = color.green config.fg_urgent = color.orange config.fg_minimize = color.gray config.border_normal = color.gray config.border_focus = color.dark_gray config.border_marked = config.fg_urgent config.taglist_bg_focus = color.green config.taglist_fg_focus = config.bg_normal config.taglist_bg_occupied = color.gray config.taglist_fg_occupied = config.bg_normal config.taglist_bg_urgent = config.fg_urgent config.taglist_fg_urgent = config.bg_normal config.taglist_bg_volatile = color.red config.taglist_fg_volatile = config.bg_normal config.titlebar_bg_normal = config.border_normal config.titlebar_bg_focus = config.border_focus config.titlebar_fg_focus = color.foreground config.tasklist_fg_normal = color.gray config.tasklist_fg_focus = color.foreground config.tasklist_bg_normal = color.gray config.tasklist_bg_focus = color.green config.tasklist_bg_urgent = color.red config.tasklist_bg_minimize = color.yellow -- define text view of layouts config.layout_txt_tile = "[t]" config.layout_txt_tileleft = "[l]" config.layout_txt_tilebottom = "[b]" config.layout_txt_tiletop = "[tt]" config.layout_txt_fairv = "[fv]" config.layout_txt_fairh = "[fh]" config.layout_txt_spiral = "[s]" config.layout_txt_dwindle = "[d]" config.layout_txt_max = "[m]" config.layout_txt_fullscreen = "[F]" config.layout_txt_magnifier = "[M]" config.layout_txt_floating = "[*]" -- variables set for theming tooltips: config.tooltip_opacity = 0.9 config.tooltip_bg = color.background config.tooltip_fg = color.foreground config.tooltip_border_width = dpi(1) config.tooltip_border_color = color.gray config.tooltip_align = "top" config.tooltip_font = "Source Code Pro 9" -- variables set for theming the calendar: config.calendar_spacing = dpi(10) config.calendar_week_numbers = true config.calendar_start_sunday = false config.calendar_month_padding = dpi(20) config.calendar_month_border_color = color.dark_gray config.calendar_header_border_width = 0 config.calendar_weekday_padding = dpi(5) config.calendar_weekday_border_width = 0 config.calendar_weekday_fg_color = color.gray config.calendar_weeknumber_padding = config.calendar_weekday_padding config.calendar_weeknumber_border_width = config.calendar_weekday_border_width config.calendar_weeknumber_fg_color = config.calendar_weekday_fg_color config.calendar_normal_padding = config.calendar_weekday_padding config.calendar_normal_border_width = config.calendar_weekday_border_width config.calendar_focus_padding = config.calendar_weekday_padding config.calendar_focus_border_width = config.calendar_weekday_border_width config.calendar_focus_fg_color = color.background config.calendar_focus_bg_color = color.green -- define the image to load local custom_icon_path = os.getenv("XDG_CONFIG_HOME") .. "/awesome/icons" config.titlebar_close_button_normal = custom_icon_path .. "/titlebar/close_normal.svg" config.titlebar_close_button_focus = custom_icon_path .. "/titlebar/close_focus.svg" config.titlebar_close_button_focus_hover = custom_icon_path .. "/titlebar/close_focus_hover.svg" config.titlebar_minimize_button_normal = custom_icon_path .. "/titlebar/minimize_normal.svg" config.titlebar_minimize_button_focus = custom_icon_path .. "/titlebar/minimize_focus.svg" config.titlebar_minimize_button_focus_hover = custom_icon_path .. "/titlebar/minimize_focus_hover.svg" config.titlebar_ontop_button_normal_inactive = custom_icon_path .. "/titlebar/ontop_normal_inactive.svg" config.titlebar_ontop_button_focus_inactive = custom_icon_path .. "/titlebar/ontop_focus_inactive.svg" config.titlebar_ontop_button_focus_inactive_hover = custom_icon_path .. "/titlebar/ontop_focus_inactive_hover.svg" config.titlebar_ontop_button_normal_active = custom_icon_path .. "/titlebar/ontop_normal_active.svg" config.titlebar_ontop_button_focus_active = custom_icon_path .. "/titlebar/ontop_focus_active.svg" config.titlebar_ontop_button_focus_active_hover = custom_icon_path .. "/titlebar/ontop_focus_active_hover.svg" -- define the icon theme for application icons. if not set then the icons -- from /usr/share/icons and /usr/share/icons/hicolor will be used. config.icon_theme = nil -- variables set for theming notifications config.notification_font = "Source Code Pro 9" config.notification_width = dpi(270) config.notification_max_height = dpi(500) config.notification_margin = dpi(20) config.notification_border_width = config.border_width config.notification_border_color = color.dark_gray naughty.config.padding = dpi(14) naughty.config.spacing = dpi(7) naughty.config.defaults.timeout = 10 naughty.config.defaults.border_width = config.notification_border_width naughty.config.defaults.margin = config.notification_margin naughty.config.defaults.title = "System Notification" naughty.config.presets.low.fg = color.gray naughty.config.presets.critical.fg = color.red naughty.config.presets.critical.bg = color.background naughty.config.notify_callback = function (args) -- disable any kind of actions args.actions = nil -- disable any kind of icon args.icon = nil return args end beautiful.init(config) end return theme
-- _ _ _ _ _ -- / \ | | | | | __ ___ _(_) -- / _ \ | | |_ | |/ _` \ \ / / | -- / ___ \| | | |_| | (_| |\ V /| | -- /_/ \_\_|_|\___/ \__,_| \_/ |_| -- -- github: @AllJavi -- local gears = require("gears") local beautiful = require('beautiful') local awful = require("awful") require("awful.autofocus") --[[ -- Notification library local naughty = require("naughty") -- {{{ Error handling -- Check if awesome encountered an error during startup and fell back to -- another config (This code will only ever execute for the fallback config) if awesome.startup_errors then naughty.notify({ preset = naughty.config.presets.critical, title = "Oops, there were errors during startup!", text = awesome.startup_errors }) end -- Handle runtime errors after startup do local in_error = false awesome.connect_signal("debug::error", function(err) -- Make sure we don't go into an endless error loop if in_error then return end in_error = true naughty.notify({ preset = naughty.config.presets.critical, title = "Oops, an error happened!", text = tostring(err) }) in_error = false end) end -- }}} --]] awful.util.shell = 'sh' beautiful.init(require("theme")) require("layout") require('configuration.client') require('configuration.tags') root.keys(require('configuration.keys.global')) require('module.notifications') require('module.auto-start') require("module.titlebar") require('module.volume-osd')
include("terms") velocity = math.random(3) * 10 number = (10 + math.random(15)) * 10 hour = math.floor(number/60) minute = number - hour * 60 value = number * velocity volume = math.floor(value/100) rest = value - volume * 100 quest = tostring(math.floor(volume)) .. "hl " if (rest ~=0) then quest = quest .. " " .. tostring(math.floor(rest)) .. "l" end answ = lib.check_number(number) .. msg_min if (minute ~=0) then answ = answ .. " = " .. lib.check_number(hour,20) .. msg_hour .. " " .. lib.check_number(minute) .. msg_min .. "." else answ = answ .. " = " .. lib.check_number(hour,20) .. msg_hour .. "." end
--[[ GUI: okienko pomocy @author Jakub 'XJMLN' Starzak <jack@pszmta.pl @package PSZMTA.psz-gui @copyright Jakub 'XJMLN' Starzak <jack@pszmta.pl> Nie mozesz uzywac tego skryptu bez mojej zgody. Napisz - byc moze sie zgodze na uzycie. ]]-- local x,y = guiGetScreenSize() local window = guiCreateWindow((x-850)/2, (y-550)/2, 850, 550, "Panel pomocy", false ) local textBox = guiCreateMemo( 246, 30, 594, 510, "", false, window ) local gList = guiCreateGridList( 10, 30, 230, 510, false, window ) guiGridListSetSelectionMode(gList,2) guiMemoSetReadOnly(textBox, true) guiGridListAddColumn(gList,"Działy",0.9) guiSetVisible(window,false) showCursor(false) local F2wndShowing = false bindKey('f9','down', function() if F2wndShowing == true then guiSetVisible(window, false) showCursor(false) guiSetInputEnabled( false ) F2wndShowing = false else guiSetVisible(window, true) showCursor(true) guiSetInputEnabled( true ) F2wndShowing = true end end) local Text = { } for i,val in ipairs(dzialy) do local rowID = guiGridListAddRow(gList) if val[2] == 0 then guiGridListSetItemText(gList, rowID, 1, val[1], true, true) guiGridListSetItemColor( gList, rowID, 1, 100, 100, 100 ) else guiGridListSetItemText(gList, rowID, 1, val[1], false, true) Text[rowID] = dzialy[rowID+1][3] end end guiSetText(textBox,Text[1]) addEventHandler('onClientGUIClick',root, function() local row,col = guiGridListGetSelectedItem ( gList ) if Text[row] then guiSetText(textBox,Text[row]) end end)
--异态魔女·路-02 local m=14000502 local cm=_G["c"..m] cm.named_with_Spositch=1 xpcall(function() require("expansions/script/c14000501") end,function() require("script/c14000501") end) function cm.initial_effect(c) --splimit spo.splimit(c) --spelleffect spo.SpositchSpellEffect(c,CATEGORY_DESTROY+CATEGORY_TOEXTRA,EFFECT_FLAG_CARD_TARGET,cm.destg,cm.desop) --peneffect spo.SpositchPendulumEffect(c,CATEGORY_TOEXTRA+CATEGORY_TOHAND,cm.thtg,cm.thop) --[[spsummon condition --local e1=Effect.CreateEffect(c) --e1:SetType(EFFECT_TYPE_SINGLE) --e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) --e1:SetCode(EFFECT_SPSUMMON_CONDITION) --e1:SetValue(cm.splimit) --c:RegisterEffect(e1)]]-- end function cm.splimit(e,se,sp,st) local sc=se:GetHandler() return sc and spo.named(sc) end function cm.filter(c) return c:IsType(TYPE_SPELL+TYPE_TRAP) end function cm.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) local c=e:GetHandler() if chkc then return chkc:IsOnField() and cm.filter(chkc) and chkc~=e:GetHandler() end if chk==0 then local checknum=0 local e1_2=Effect.CreateEffect(c) e1_2:SetType(EFFECT_TYPE_SINGLE) e1_2:SetCode(EFFECT_CHANGE_TYPE) e1_2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1_2:SetValue(TYPE_SPELL+TYPE_QUICKPLAY) e1_2:SetReset(RESET_EVENT+0x47c0000) c:RegisterEffect(e1_2,true) local ce=c:GetActivateEffect() if ce:IsActivatable(tp,false,true) then checknum=1 end e1_2:Reset() return checknum==1 and Duel.IsExistingTarget(cm.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,c) and not c:IsForbidden() end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g=Duel.SelectTarget(tp,cm.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,e:GetHandler()) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,LOCATION_ONFIELD) Duel.SetOperationInfo(0,CATEGORY_TOEXTRA,e:GetHandler(),1,tp,LOCATION_SZONE) c:CancelToGrave(false) end function cm.desop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() local c=e:GetHandler() if tc:IsRelateToEffect(e) then Duel.Destroy(tc,REASON_EFFECT) if c:IsRelateToEffect(e) then c:CancelToGrave() Duel.SendtoExtraP(c,nil,REASON_EFFECT) end end end function cm.thfilter(c) return c:IsType(TYPE_QUICKPLAY) and c:IsType(TYPE_SPELL) and c:IsAbleToHand() end function cm.thtg(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return not c:IsForbidden() end Duel.SetOperationInfo(0,CATEGORY_TOEXTRA,e:GetHandler(),1,tp,LOCATION_SZONE) Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_GRAVE) end function cm.thop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if not c:IsType(TYPE_PENDULUM) or not c:IsRelateToEffect(e) then return end if Duel.SendtoExtraP(c,nil,REASON_EFFECT)==0 then return end if not Duel.IsExistingTarget(cm.thfilter,tp,LOCATION_GRAVE,0,1,nil) then return end if not Duel.SelectYesNo(tp,aux.Stringid(m,1)) then return end Duel.BreakEffect() Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,cm.thfilter,tp,LOCATION_GRAVE,0,1,1,nil) local tc=g:GetFirst() if tc then Duel.SendtoHand(tc,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,tc) end end
--=========== Copyright © 2018, Planimeter, All rights reserved. ===========-- -- -- Purpose: Scheme class -- --==========================================================================-- class( "scheme" ) scheme._schemes = scheme._schemes or {} local properties = {} function scheme.clear( name ) properties[ name ] = {} end function scheme.getProperty( name, property ) local cachedProperty = properties[ name ][ property ] if ( cachedProperty ) then return cachedProperty end local value = scheme._schemes[ name ] local type = type( value ) if ( type ~= "scheme" ) then error( "attempt to index scheme '" .. name .. "' " .. "(a " .. type .. " value)", 3 ) end for key in string.gmatch( property .. ".", "(.-)%." ) do if ( value and value[ key ] ) then value = value[ key ] properties[ name ][ property ] = value else error( "attempt to index property '" .. property .. "' " .. "(a nil value)", 3 ) end end return value end function scheme.isLoaded( name ) return scheme._schemes[ name ] ~= nil end function scheme.load( name ) require( "schemes." .. name ) end function scheme:scheme( name ) self.name = name scheme._schemes[ name ] = self scheme.clear( name ) end function scheme:__tostring() return "scheme: \"" .. self.name .. "\"" end
local t = Def.ActorFrame{}; t[#t+1] = Def.Sprite{ Texture="back.png"; InitCommand=function(self) self:Center() end; }; return t
do --- nometatable local t = {} for i=1,10 do t[i] = i+100 end local a, b = 0, 0 for j=1,100 do for k,v in ipairs(t) do a = a + k; b = b + v end end assert(a == 5500) assert(b == 105500) a, b = 0, 0 for j=1,100 do for k,v in pairs(t) do a = a + k; b = b + v end end assert(a == 5500) assert(b == 105500) end do --- empty metatable local t = setmetatable({}, {}) for i=1,10 do t[i] = i+100 end local a, b = 0, 0 for j=1,100 do for k,v in ipairs(t) do a = a + k; b = b + v end end assert(a == 5500) assert(b == 105500) a, b = 0, 0 for j=1,100 do for k,v in pairs(t) do a = a + k; b = b + v end end assert(a == 5500) assert(b == 105500) end do --- metamethods +compat5.2 local function iter(t, i) i = i + 1 if t[i] then return i, t[i]+2 end end local function itergen(t) return iter, t, 0 end local t = setmetatable({}, { __pairs = itergen, __ipairs = itergen }) for i=1,10 do t[i] = i+100 end local a, b = 0, 0 for j=1,100 do for k,v in ipairs(t) do a = a + k; b = b + v end end assert(a == 5500) assert(b == 107500) a, b = 0, 0 for j=1,100 do for k,v in pairs(t) do a = a + k; b = b + v end end assert(a == 5500) assert(b == 107500) end do --- _G local n = 0 for k,v in pairs(_G) do assert(_G[k] == v) n = n + 1 end assert(n >= 35) end do --- count local function count(t) local n = 0 for i,v in pairs(t) do n = n + 1 end return n; end assert(count({ 4,5,6,nil,8,nil,10}) == 5) assert(count({ [0] = 3, 4,5,6,nil,8,nil,10}) == 6) assert(count({ foo=1, bar=2, baz=3 }) == 3) assert(count({ foo=1, bar=2, baz=3, boo=4 }) == 4) assert(count({ 4,5,6,nil,8,nil,10, foo=1, bar=2, baz=3 }) == 8) local t = { foo=1, bar=2, baz=3, boo=4 } t.bar = nil; t.boo = nil assert(count(t) == 2) end
local parser = require 'pegparser.parser' local pretty = require 'pegparser.pretty' local newSeq = parser.newSeq local newNode = parser.newNode local newSimpCap = parser.newSimpCap local newTabCap = parser.newTabCap local newNameCap = parser.newNameCap local function addCaptures (p, g) if p.tag == 'empty' or p.tag == 'char' or p.tag == 'set' or p.tag == 'any' then return newSimpCap(p) elseif p.tag == 'posCap' then return p elseif p.tag == 'simpCap' then return p elseif p.tag == 'tabCap' then return p elseif p.tag == 'nameCap' then return p elseif p.tag == 'anonCap' then return p elseif p.tag == 'var' then if p.p1 ~= 'SKIP' and p.p1 ~= 'SPACE' and parser.isLexRule(p.p1) then return newSimpCap(p) else return p end elseif p.tag == 'ord' or p.tag == 'con' then return parser.newNode(p.tag, addCaptures(p.p1, g), addCaptures(p.p2, g)) elseif p.tag == 'and' or p.tag == 'not' then return p elseif p.tag == 'opt' or p.tag == 'star' or p.tag == 'plus' then return parser.newNode(p.tag, addCaptures(p.p1, g)) elseif p.tag == 'throw' then return p else error("Unknown tag: " .. p.tag) end end local function buildAST (g) local newg = parser.initgrammar() newg.plist = g.plist for i, v in ipairs(newg.plist) do if not parser.isLexRule(v) then local p = addCaptures(g.prules[v], g) p = parser.newSeq(newNameCap('rule', parser.newConstCap(v)), p) newg.prules[v] = newTabCap(p) elseif parser.isErrRule(v) then print("isErrRule", v) local p = g.prules[v] p = parser.newSeq(p, parser.newConstCap('NONE' .. v)) newg.prules[v] = p elseif v == 'EatToken' then local p = g.prules[v] p = parser.newSeq(p, parser.newDiscardCap()) newg.prules[v] = p else newg.prules[v] = g.prules[v] end end return newg end local function printAST (t, tab) tab = tab or 0 if type(t) == 'table' then if #t == 1 and type(t[1]) == 'table' then printAST(t[1], tab) else --io.write(string.rep(' ', tab)) io.write(t.rule .. '{') --io.write('\n') for i, v in ipairs(t) do printAST(v, tab + 2) io.write(', ') end --io.write('\n' .. string.rep(' ', tab)) io.write('}') end else io.write('"'.. t .. '"') end end local function getTokens_aux (ast, tabTk) if type(ast) == 'table' then for i, v in ipairs(ast) do getTokens_aux(v, tabTk) end else table.insert(tabTk, ast) end end local function getTokens (ast) local tabTk = {} getTokens_aux(ast, tabTk) return tabTk end return { buildAST = buildAST, printAST = printAST, getTokens = getTokens, }
--@native string --@native tostring --@native rawget --@native rawset --@native tonumber --@import see.base.Array --@import see.base.System --@import see.util.ArgumentUtils --@import see.util.Matcher --[[ An Array-backed string. Faster and more memory efficient than native strings. ]] --[[ Casts a value to a String. @param any:value The value to be casted. @return see.base.String The casted value. ]] function String.__cast(value) local type = typeof(value) if not isprimitive(value) then if value.__type == String then return value end return value:toString() end local str = tostring(value) local ret = String:new() for i = 1, #str do ret.charArray:add(str:sub(i, i):byte()) end return ret end --[[ Converts bytes to a String. @param ... The bytes to convert. @return see.base.String A string representation of the given bytes. ]] function String.char(...) return String:new(string.char(...)) end --[[ Constructs a new String which copies the given string. @param strings:str... The strings to be copied. ]] function String:init(...) local args = {...} self.charArray = Array:new() for i = 1, #args do local str = cast(args[i], String) if not str then return end for i = 1, str:length() do self.charArray:add(str[i]) end end end function String:opIndex(index) if typeof(index) == "number" then return self.charArray[index] end end function String:opNewIndex(index, value) if typeof(value) == "string" then value = string.byte(value) end if typeof(index) == "number" then self.charArray[index] = value return true end return false end --[[ Gets a Lua string from this String. @return string The Lua string. ]] function String:lstr() local str = "" for i = 1, self:length() do str = str .. string.char(self[i]) end return str end --[[ Gets the length of this String. @return number The length of this String. ]] function String:length() return self.charArray:length() end function String:opConcat(other) return STR(self, other) end --[[ Gets a substring of this String. @param number:a Start index. @param number:b End index. Defaults to the length of this String. @return see.base.String A substring of this String. ]] function String:sub(a, b) if not b then b = self:length() end ArgumentUtils.check(1, a, "number") ArgumentUtils.check(2, b, "number") a = a < 0 and self:length() + a + 1 or a b = b < 0 and self:length() + b + 1 or b if a > b then a, b = b, a end local substring = String:new() for i = a, b do substring:add(string.char(self[i])) end return substring end --[[ Adds a string to this String. @param see.base.String:str The string to append. @return see.base.String This String. ]] function String:add(str) str = cast(str, String) for i = 1, str:length() do self.charArray:add(str[i]) end return self end --[[ Inserts a given string into this String at the given index. @param number:index The index to insert at. @param see.base.String:str The string to insert. @return see.base.String This String. ]] function String:insert(index, str) ArgumentUtils.check(1, index, "number") str = cast(str, String) for i = str:length(), 1, -1 do self.charArray:insert(index, str[i]) end return self end --[[ Removes a given amount of characters from this String at the given index. @param number:index The index to remove characters from. @param number:amount The amount of characters to remove. @return see.base.String This String. ]] function String:remove(index, amount) ArgumentUtils.check(1, index, "number") ArgumentUtils.check(2, amount, "number") for i = 1, amount do self.charArray:remove(index) end return self end --[[ Finds a given substring in this string. @param see.base.String:str The string to search for. @param number:init The index to start searching from. Defaults to 1. @return number The index that the substring occurs. ]] function String:find(str, init) str = cast(str, String) if not init then init = 1 end ArgumentUtils.check(2, init, "number") local j = 1 for i = init, self:length() do if self[i] == str[j] then if j == str:length() then return i - j + 1 end j = j + 1 else j = 1 end end end --[[ Formats this String using the native string.format. @param native:values... The values to pass to string.format. @return see.base.String The formatted string. ]] function String:format(...) return String:new(self:lstr():format(...)) end --[[ Replaces all instances of str with rep. @param see.base.String:str The string to be replaced. @param see.base.String:rep The string to replace with. @return see.base.String This String. ]] function String:replace(str, rep) str = cast(str, String) rep = cast(rep, String) local found = self:find(str) while found do self:remove(found, str:length()):insert(found, rep) found = self:find(str, found + 1) end return self end --[[ Returns a lower case version of this String. @return see.base.String The lower case string. ]] function String:lower() local ret = String:new() for i = 1, self:length() do if self[i] >= 65 and self[i] <= 90 then ret[i] = self[i] + 32 else ret[i] = self[i] end end return ret end --[[ Returns an upper case version of this String. @return see.base.String The upper case string. ]] function String:upper() local ret = String:new() for i = 1, self:length() do if self[i] >= 97 and self[i] <= 122 then ret[i] = self[i] - 32 else ret[i] = self[i] end end return ret end --[[ Duplicates this String over n times. @param number:n The number of times to duplicate this String. @return see.base.String A duplicated String. ]] function String:duplicate(n) ArgumentUtils.check(1, n, "number") local ret = String:new() for i = 1, n do ret:add(self) end return ret end --[[ Reverses this String. @return see.base.String A reversed String. ]] function String:reverse() local ret = String:new() for i = self:length(), 1, -1 do ret:add(String.char(self[i])) end return ret end --[[ Splits this String into strings separated by sep. @param see.base.String sep The separator. @return see.base.Array The split strings. ]] function String:split(sep) local ret = Array:new() local matcher = Matcher:new(sep, self) local l = 1 while matcher:find() do ret:add(self:sub(l, matcher.left - 1)) l = matcher.right + 1 end ret:add(self:sub(l, -1)) return ret end function String:trim() local ret = String:new() for i = 1, self:length() do if self[i] ~= STR(' ')[1] and self[i] ~= STR('\n')[1] and self[i] ~= STR('\t')[1] and self[i] ~= STR('\r')[1] then ret:add(String.char(self[i])) end end return ret end --[[ Converts this String to a number. @return number The converted number. ]] function String:toNumber() return tonumber(self:lstr()) end function String:equals(other) return self:lstr() == cast(other, "string") end function String:toString() return self end
local function removeInterpreters() local whitelist = { luadeb = true, love2d = true } for interpreter in pairs(ide.interpreters) do if not whitelist[interpreter] then ide:RemoveInterpreter(interpreter) end end end local function disableOutputText() local _displayOutputLn = DisplayOutputLn DisplayOutputLn = function(str, ...) if str ~= "" then _displayOutputLn(str, ...) end end local _tr = TR TR = function(msg, count) local altered = { ["Program starting as '%s'."] = "", ["Program '%s' started in '%s' (pid: %d)."] = "", ["Debugger server started at %s:%d."] = "", ["Debugging session started in '%s'."] = "", ["Debugging session completed (%s)."] = "" } return altered[msg] or _tr(msg, count) end end local function runOnDebug() ide.config.debugger.runonstart = true end return { name = "Da Vinci Environment plugin", description = "Sets up ZeroBrane Studio for use in the classes taught at the Da Vinci College in Dordrecht, The Netherlands.", author = "William Willing", version = 1, onRegister = function (self) removeInterpreters() -- Only show the interpreters we actually use. disableOutputText() -- When you run your program, you should see only the text your program generates and not some preamble. runOnDebug() -- Debugging your program should run immediately and not break on the first line. end }
while true do local m = Instance.new("Message") m.Parent = game.Workspace m.Text = "A meteor is coming towards us!!! AHHH!!!" wait(3) m:remove() local b = Instance.new("Part") b.Parent = game.Workspace b.Position = Vector3.new(0,1000,0) b.Size = Vector3.new(5,1,5) b.BrickColor = BrickColor.new(199) b.Transparency = 0 wait(10) local n = Instance.new("Message") n.Parent = game.Workspace n.Text = "Oh, it was just a small rock..." wait(3) n:remove() wait(10) b:remove() wait(1000) end
--- Credit To FunTrator . --- Do Whatever You Want . LIFE SUCKS . --- Discord : Discord.io/SomeoneShark local PSG = Instance.new("ScreenGui") local bar1 = Instance.new("Frame") local SF = Instance.new("TextButton") local UEA = Instance.new("TextButton") local UA = Instance.new("TextButton") local N = Instance.new("TextLabel") local AT = Instance.new("TextButton") local No = Instance.new("TextLabel") local TextLabel = Instance.new("TextLabel") local MF = Instance.new("TextButton") local AF = Instance.new("TextButton") local WS = Instance.new("TextButton") local JP = Instance.new("TextButton") local bar2 = Instance.new("Frame") local Stor = Instance.new("TextButton") local P2 = Instance.new("TextButton") local P1 = Instance.new("TextButton") local P3 = Instance.new("TextButton") local P4 = Instance.new("TextButton") local M1 = Instance.new("TextButton") local P5 = Instance.new("TextButton") local M2 = Instance.new("TextButton") local Spawn = Instance.new("TextButton") local C = Instance.new("TextButton") local X = Instance.new("TextButton") PSG.Name = "PSG" PSG.Parent = game.CoreGui bar1.Name = "bar1" bar1.Parent = PSG bar1.BackgroundColor3 = Color3.new(0.172549, 0, 0.0627451) bar1.BorderSizePixel = 2 bar1.Position = UDim2.new(0.241050124, 0, 0.177033499, 0) bar1.Size = UDim2.new(0, 263, 0, 356) bar1.Style = Enum.FrameStyle.RobloxRound bar1.Active = true bar1.Draggable = true SF.Name = "SF" SF.Parent = bar1 SF.BackgroundColor3 = Color3.new(1, 0.0392157, 0.215686) SF.Position = UDim2.new(0.0570342205, 0, 0.151685402, 0) SF.Size = UDim2.new(0, 107, 0, 42) SF.Style = Enum.ButtonStyle.RobloxRoundDropdownButton SF.Font = Enum.Font.SciFi SF.Text = "Small FARM" SF.TextColor3 = Color3.new(0, 0, 0) SF.TextSize = 14 SF.MouseButton1Down:connect(function() local amount = 100 -- experiment with this value, 1000 is maximum and for pets with high levels local coins = game.Workspace:WaitForChild("__REMOTES"):WaitForChild("Coins") local save = game.Workspace:WaitForChild("__REMOTES"):WaitForChild("Get Other Stats"):InvokeServer() local plr = game:GetService("Players").LocalPlayer local petids = {} local pets = game:GetService("Workspace")["__REMOTES"].Pets local a = #save[plr.Name]["Save"]["Pets"] local done = "lol meme" function random(t) local keys = {} for key, value in pairs(t) do keys[#keys+1] = key end index = keys[math.random(1, #keys)] return t[index] end for i=1,a do if(save[plr.Name]["Save"]["Pets"][a].e == true) then table.insert(petids, save[plr.Name]["Save"]["Pets"][a].id) end a = a - 1 end function co(b) local done = b print("Mining coin: " .. b.Name) while(b:FindFirstChild"Health" ~= nil and b:FindFirstChild"Health".Value > 0) do warn(b.Name .. "- Health: " .. b.Health.Value) wait(0.2) coins:FireServer("Mine",b.Name, amount, random(petids)) end end for _,b in next, workspace.__THINGS.Coins:GetChildren() do if(done ~= b) then coroutine.wrap(function()co(b)end)() end end end) UEA.Name = "UEA" UEA.Parent = bar1 UEA.BackgroundColor3 = Color3.new(1, 0.0392157, 0.215686) UEA.Position = UDim2.new(0.258555144, 0, 0.601123571, 0) UEA.Size = UDim2.new(0, 118, 0, 42) UEA.Style = Enum.ButtonStyle.RobloxRoundDropdownButton UEA.Font = Enum.Font.SciFi UEA.Text = "Un-Equip Pets" UEA.TextColor3 = Color3.new(0, 0, 0) UEA.TextSize = 14 UEA.MouseButton1Down:connect(function() local Event = game:GetService("Workspace")["__REMOTES"].Pets local save = game.Workspace:WaitForChild("__REMOTES"):WaitForChild("Get Other Stats"):InvokeServer() for _,x in next, game:GetService"Players":GetPlayers() do if(x.Name ~= game:GetService"Players".LocalPlayer.Name) then local a = #save[x.Name]["Save"]["Pets"] for i=1,a do Event:FireServer("Remove", x, save[x.Name]["Save"]["Pets"][a].id) a = a - 1 end end end end) UA.Name = "UA" UA.Parent = bar1 UA.BackgroundColor3 = Color3.new(1, 0.0392157, 0.215686) UA.Position = UDim2.new(0.524714828, 0, 0.30898878, 0) UA.Size = UDim2.new(0, 118, 0, 42) UA.Style = Enum.ButtonStyle.RobloxRoundDropdownButton UA.Font = Enum.Font.SciFi UA.Text = "Unlock All" UA.TextColor3 = Color3.new(0, 0, 0) UA.TextSize = 14 UA.MouseButton1Down:connect(function() local barriers_table = { "Barrier1", "Barrier2", "Barrier3", "Barrier4", "Barrier5" } local barriers = game:GetService("Workspace").__THINGS["Barriers"] barriers:Destroy() end) N.Name = "N" N.Parent = bar1 N.BackgroundColor3 = Color3.new(1, 1, 1) N.BackgroundTransparency = 1 N.Position = UDim2.new(0.022813689, 0, 0.0188706424, 0) N.Size = UDim2.new(0, 234, 0, 23) N.Font = Enum.Font.SciFi N.Text = "Pet Simulator Gui - By FunTrator" N.TextColor3 = Color3.new(0.992157, 0.00784314, 0.141176) N.TextSize = 17 AT.Name = "AT" AT.Parent = bar1 AT.BackgroundColor3 = Color3.new(1, 0.0392157, 0.215686) AT.Position = UDim2.new(0.174904943, 0, 0.767000616, 0) AT.Size = UDim2.new(0, 162, 0, 42) AT.Style = Enum.ButtonStyle.RobloxButtonDefault AT.Font = Enum.Font.SciFi AT.Text = "Teleports" AT.TextColor3 = Color3.new(0.980392, 0.0235294, 0.121569) AT.TextSize = 26 AT.MouseButton1Down:connect(function() bar2.Visible = true end) No.Name = "No" No.Parent = bar1 No.BackgroundColor3 = Color3.new(1, 0.00392157, 0.0196078) No.Position = UDim2.new(0.0342205316, 0, 0.100694448, 0) No.Size = UDim2.new(0, 233, 0, 1) No.Font = Enum.Font.SourceSans No.Text = "" No.TextColor3 = Color3.new(0, 0, 0) No.TextSize = 14 TextLabel.Parent = bar1 TextLabel.BackgroundColor3 = Color3.new(1, 1, 1) TextLabel.BackgroundTransparency = 1 TextLabel.Position = UDim2.new(0.022813689, 0, 0.921862781, 0) TextLabel.Size = UDim2.new(0, 233, 0, 23) TextLabel.Font = Enum.Font.SciFi TextLabel.Text = "Discord : Discord.io/SomeoneShark" TextLabel.TextColor3 = Color3.new(0.980392, 0.980392, 0.980392) TextLabel.TextSize = 13 MF.Name = "MF" MF.Parent = bar1 MF.BackgroundColor3 = Color3.new(1, 0.0392157, 0.215686) MF.Position = UDim2.new(0.524714828, 0, 0.149288639, 0) MF.Size = UDim2.new(0, 118, 0, 42) MF.Style = Enum.ButtonStyle.RobloxRoundDropdownButton MF.Font = Enum.Font.SciFi MF.Text = "Med. FARM" MF.TextColor3 = Color3.new(0, 0, 0) MF.TextSize = 14 MF.MouseButton1Down:connect(function() local amount = 500 -- experiment with this value, 1000 is maximum and for pets with high levels local coins = game.Workspace:WaitForChild("__REMOTES"):WaitForChild("Coins") local save = game.Workspace:WaitForChild("__REMOTES"):WaitForChild("Get Other Stats"):InvokeServer() local plr = game:GetService("Players").LocalPlayer local petids = {} local pets = game:GetService("Workspace")["__REMOTES"].Pets local a = #save[plr.Name]["Save"]["Pets"] local done = "lol meme" function random(t) local keys = {} for key, value in pairs(t) do keys[#keys+1] = key end index = keys[math.random(1, #keys)] return t[index] end for i=1,a do if(save[plr.Name]["Save"]["Pets"][a].e == true) then table.insert(petids, save[plr.Name]["Save"]["Pets"][a].id) end a = a - 1 end function co(b) local done = b print("Mining coin: " .. b.Name) while(b:FindFirstChild"Health" ~= nil and b:FindFirstChild"Health".Value > 0) do warn(b.Name .. "- Health: " .. b.Health.Value) wait(0.2) coins:FireServer("Mine",b.Name, amount, random(petids)) end end for _,b in next, workspace.__THINGS.Coins:GetChildren() do if(done ~= b) then coroutine.wrap(function()co(b)end)() end end end) AF.Name = "AF" AF.Parent = bar1 AF.BackgroundColor3 = Color3.new(1, 0.0392157, 0.215686) AF.Position = UDim2.new(0.0532319397, 0, 0.30898878, 0) AF.Size = UDim2.new(0, 108, 0, 42) AF.Style = Enum.ButtonStyle.RobloxRoundDropdownButton AF.Font = Enum.Font.SciFi AF.Text = "MAX FARM" AF.TextColor3 = Color3.new(0, 0, 0) AF.TextSize = 14 AF.MouseButton1Down:connect(function() local amount = 1000 -- experiment with this value, 1000 is maximum and for pets with high levels local coins = game.Workspace:WaitForChild("__REMOTES"):WaitForChild("Coins") local save = game.Workspace:WaitForChild("__REMOTES"):WaitForChild("Get Other Stats"):InvokeServer() local plr = game:GetService("Players").LocalPlayer local petids = {} local pets = game:GetService("Workspace")["__REMOTES"].Pets local a = #save[plr.Name]["Save"]["Pets"] local done = "lol meme" function random(t) local keys = {} for key, value in pairs(t) do keys[#keys+1] = key end index = keys[math.random(1, #keys)] return t[index] end for i=1,a do if(save[plr.Name]["Save"]["Pets"][a].e == true) then table.insert(petids, save[plr.Name]["Save"]["Pets"][a].id) end a = a - 1 end function co(b) local done = b print("Mining coin: " .. b.Name) while(b:FindFirstChild"Health" ~= nil and b:FindFirstChild"Health".Value > 0) do warn(b.Name .. "- Health: " .. b.Health.Value) wait(0.2) coins:FireServer("Mine",b.Name, amount, random(petids)) end end for _,b in next, workspace.__THINGS.Coins:GetChildren() do if(done ~= b) then coroutine.wrap(function()co(b)end)() end end end) WS.Name = "WS" WS.Parent = bar1 WS.BackgroundColor3 = Color3.new(1, 0.0392157, 0.215686) WS.Position = UDim2.new(0.0570342205, 0, 0.449438214, 0) WS.Size = UDim2.new(0, 108, 0, 42) WS.Style = Enum.ButtonStyle.RobloxRoundDropdownButton WS.Font = Enum.Font.SciFi WS.Text = "WalkSpeed" WS.TextColor3 = Color3.new(0, 0, 0) WS.TextSize = 14 WS.MouseButton1Down:connect(function() game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 100 end) JP.Name = "JP" JP.Parent = bar1 JP.BackgroundColor3 = Color3.new(1, 0.0392157, 0.215686) JP.Position = UDim2.new(0.520912528, 0, 0.449438214, 0) JP.Size = UDim2.new(0, 119, 0, 42) JP.Style = Enum.ButtonStyle.RobloxRoundDropdownButton JP.Font = Enum.Font.SciFi JP.Text = "Jump Power" JP.TextColor3 = Color3.new(0, 0, 0) JP.TextSize = 14 WS.MouseButton1Down:connect(function() game.Players.LocalPlayer.Character.Humanoid.JumpPower = 200 end) bar2.Name = "bar2" bar2.Parent = PSG bar2.BackgroundColor3 = Color3.new(1, 1, 1) bar2.Position = UDim2.new(0.564439118, 0, 0.178628385, 0) bar2.Size = UDim2.new(0, 214, 0, 329) bar2.Style = Enum.FrameStyle.RobloxRound bar2.Active = true bar2.Draggable = true bar2.Visible = false Stor.Name = "Stor" Stor.Parent = bar2 Stor.BackgroundColor3 = Color3.new(1, 1, 1) Stor.Position = UDim2.new(0.532710254, 0, 0.0186170191, 0) Stor.Size = UDim2.new(0, 92, 0, 39) Stor.Style = Enum.ButtonStyle.RobloxRoundDropdownButton Stor.Font = Enum.Font.SourceSans Stor.Text = "Store" Stor.TextColor3 = Color3.new(0, 0, 0) Stor.TextSize = 14 Stor.MouseButton1Down:connect(function() game.Players.LocalPlayer.Character:MoveTo(Vector3.new(719.225952, -33.6261177, 894.049072)) end) P2.Name = "P2" P2.Parent = bar2 P2.BackgroundColor3 = Color3.new(1, 1, 1) P2.Position = UDim2.new(0.532710254, 0, 0.177342772, 0) P2.Size = UDim2.new(0, 92, 0, 39) P2.Style = Enum.ButtonStyle.RobloxRoundDropdownButton P2.Font = Enum.Font.SourceSans P2.Text = "Place 2" P2.TextColor3 = Color3.new(0, 0, 0) P2.TextSize = 14 P2.MouseButton1Down:connect(function() game.Players.LocalPlayer.Character:MoveTo(Vector3.new(-374.2388, -37.0378761, 885.253296)) end) P1.Name = "P1" P1.Parent = bar2 P1.BackgroundColor3 = Color3.new(1, 1, 1) P1.Position = UDim2.new(0.0140186772, 0, 0.174303263, 0) P1.Size = UDim2.new(0, 92, 0, 39) P1.Style = Enum.ButtonStyle.RobloxRoundDropdownButton P1.Font = Enum.Font.SourceSans P1.Text = "Place 1" P1.TextColor3 = Color3.new(0, 0, 0) P1.TextSize = 14 P1.MouseButton1Down:connect(function() game.Players.LocalPlayer.Character:MoveTo(Vector3.new(0.295806587, -37.0378761, 890.214355)) end) P3.Name = "P3" P3.Parent = bar2 P3.BackgroundColor3 = Color3.new(1, 1, 1) P3.Position = UDim2.new(0.0140186772, 0, 0.335101962, 0) P3.Size = UDim2.new(0, 92, 0, 39) P3.Style = Enum.ButtonStyle.RobloxRoundDropdownButton P3.Font = Enum.Font.SourceSans P3.Text = "Place 3" P3.TextColor3 = Color3.new(0, 0, 0) P3.TextSize = 14 P3.MouseButton1Down:connect(function() game.Players.LocalPlayer.Character:MoveTo(Vector3.new(-760.199097, -37.0378761, 880.302246)) end) P4.Name = "P4" P4.Parent = bar2 P4.BackgroundColor3 = Color3.new(1, 1, 1) P4.Position = UDim2.new(0.528037369, 0, 0.332062453, 0) P4.Size = UDim2.new(0, 92, 0, 39) P4.Style = Enum.ButtonStyle.RobloxRoundDropdownButton P4.Font = Enum.Font.SourceSans P4.Text = "Place 4" P4.TextColor3 = Color3.new(0, 0, 0) P4.TextSize = 14 P4.MouseButton1Down:connect(function() game.Players.LocalPlayer.Character:MoveTo(Vector3.new(-1140.22437, -37.0378761, 885.195129)) end) M1.Name = "M1" M1.Parent = bar2 M1.BackgroundColor3 = Color3.new(1, 1, 1) M1.Position = UDim2.new(0.065420568, 0, 0.647416413, 0) M1.Size = UDim2.new(0, 173, 0, 39) M1.Style = Enum.ButtonStyle.RobloxRoundDropdownButton M1.Font = Enum.Font.SourceSans M1.Text = "Moon 1 [ Use This To Use Below ]" M1.TextColor3 = Color3.new(0, 0, 0) M1.TextSize = 14 M1.MouseButton1Down:connect(function() local mapname = "Moon" local Event = game:GetService("Workspace")["__REMOTES"]["Load Map"] Event:FireServer(mapname) end) P5.Name = "P5" P5.Parent = bar2 P5.BackgroundColor3 = Color3.new(1, 1, 1) P5.Position = UDim2.new(0.247663543, 0, 0.493842274, 0) P5.Size = UDim2.new(0, 92, 0, 39) P5.Style = Enum.ButtonStyle.RobloxRoundDropdownButton P5.Font = Enum.Font.SourceSans P5.Text = "Place 5" P5.TextColor3 = Color3.new(0, 0, 0) P5.TextSize = 14 P5.MouseButton1Down:connect(function() game.Players.LocalPlayer.Character:MoveTo(Vector3.new(-1534.46313, -33.038002, 887.088318)) end) M2.Name = "M2" M2.Parent = bar2 M2.BackgroundColor3 = Color3.new(1, 1, 1) M2.Position = UDim2.new(0.0280373693, 0, 0.817688882, 0) M2.Size = UDim2.new(0, 92, 0, 39) M2.Style = Enum.ButtonStyle.RobloxRoundDropdownButton M2.Font = Enum.Font.SourceSans M2.Text = "Moon 2" M2.TextColor3 = Color3.new(0, 0, 0) M2.TextSize = 14 M2.MouseButton1Down:connect(function() game.Players.LocalPlayer.Character:MoveTo(Vector3.new(80.3468018, 144.27951, -1706.91724)) end) Spawn.Name = "Spawn" Spawn.Parent = bar2 Spawn.BackgroundColor3 = Color3.new(1, 1, 1) Spawn.Position = UDim2.new(0.00934579503, 0, 0.0186170191, 0) Spawn.Size = UDim2.new(0, 92, 0, 39) Spawn.Style = Enum.ButtonStyle.RobloxRoundDropdownButton Spawn.Font = Enum.Font.SourceSans Spawn.Text = "Spawn" Spawn.TextColor3 = Color3.new(0, 0, 0) Spawn.TextSize = 14 Spawn.MouseButton1Down:connect(function() game.Players.LocalPlayer.Character:MoveTo(Vector3.new(536.137939, -36.409977, 886.542542)) end) C.Name = "C" C.Parent = bar2 C.BackgroundColor3 = Color3.new(1, 1, 1) C.Position = UDim2.new(0.532710254, 0, 0.813751876, 0) C.Size = UDim2.new(0, 92, 0, 39) C.Style = Enum.ButtonStyle.RobloxRoundDropdownButton C.Font = Enum.Font.SourceSans C.Text = "Candy" C.TextColor3 = Color3.new(0, 0, 0) C.TextSize = 14 C.MouseButton1Down:connect(function() game.Players.LocalPlayer.Character:MoveTo(Vector3.new(8.77877998, 144.27951, -1443.94481)) end) X.Name = "X" X.Parent = bar2 X.BackgroundColor3 = Color3.new(1, 0.0313726, 0.160784) X.Position = UDim2.new (0.888, 0,0,0.964, 0) X.Size = UDim2.new(0, 25, 0, 17) X.Font = Enum.Font.SciFi X.Text = "X" X.TextColor3 = Color3.new(0, 0, 0) X.TextSize = 14 X.MouseButton1Down:connect(function() bar2.Visible = false end)
object_tangible_loot_creature_loot_kashyyyk_loot_snake_blood = object_tangible_loot_creature_loot_kashyyyk_loot_shared_snake_blood:new { } ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_kashyyyk_loot_snake_blood, "object/tangible/loot/creature_loot/kashyyyk_loot/snake_blood.iff")
function BlackMarketManager:zm_locked_bm() return false end
-- Copyright 2015 Alex Browne. All rights reserved. -- Use of this source code is governed by the MIT -- license, which can be found in the LICENSE file. -- exctract_ids_from_field_index is a lua script that takes the following arguments: -- 1) setKey: The key of a sorted set for a field index (either numeric or bool) -- 2) destKey: The key of a sorted set where the resulting ids will be stored -- 3) min: The min argument for the ZRANGEBYSCORE command -- 4) max: The max argument for the ZRANGEBYSCORE command -- The script then calls ZRANGEBYSCORE on setKey with the given min and max arguments, -- and then stores the resulting set in destKey. It does not preserve the existing -- scores, and instead just replaces scores with sequential numbers to keep the members -- in the same order. -- IMPORTANT: If you edit this file, you must run go generate . to rewrite ../scripts.go -- Assign keys to variables for easy access local setKey = ARGV[1] local destKey = ARGV[2] local min = ARGV[3] local max = ARGV[4] -- Get all the members (value+id pairs) from the sorted set local members = redis.call('ZRANGEBYSCORE', setKey, min, max) -- Iterate over the members and add each to the destKey for i, member in ipairs(members) do redis.call('ZADD', destKey, i, member) end
local t = Def.ActorFrame { Name = "GeneralBoxFile", LoginMessageCommand = function(self) self:playcommand("UpdateLoginStatus") end, LogOutMessageCommand = function(self) self:playcommand("UpdateLoginStatus") end, LoginFailedMessageCommand = function(self) self:playcommand("UpdateLoginStatus") end, OnlineUpdateMessageCommand = function(self) self:playcommand("UpdateLoginStatus") end } local ratios = { LeftGap = 1140 / 1920, -- left side of screen to left edge of frame TopGap = 468 / 1080, -- top of screen to top of frame Width = Var("widthRatio"), -- width of the box taken from the loading file default.lua Height = 612 / 1080, LowerLipHeight = 57 / 1080, } local actuals = { LeftGap = ratios.LeftGap * SCREEN_WIDTH, TopGap = ratios.TopGap * SCREEN_HEIGHT, Width = ratios.Width * SCREEN_WIDTH, Height = ratios.Height * SCREEN_HEIGHT, LowerLipHeight = ratios.LowerLipHeight * SCREEN_HEIGHT } -- the page names in the order they go local choiceNames = { "General", "Scores", "Profile", "Goals", "Playlists", "Tags", } SCUFF.generaltabcount = #choiceNames local choiceTextSize = 0.8 local buttonHoverAlpha = 0.6 local textzoomFudge = 5 -- controls the focus of the frame -- starts true because it starts visible on the screen -- goes false when forced away, such as when pressing search local focused = true local function createChoices() local selectedIndex = 1 local function createChoice(i) return UIElements.TextButton(1, 1, "Common Normal") .. { Name = "ButtonTab_"..choiceNames[i], InitCommand = function(self) local txt = self:GetChild("Text") local bg = self:GetChild("BG") -- this position is the center of the text -- divides the space into slots for the choices then places them half way into them -- should work for any count of choices -- and the maxwidth will make sure they stay nonoverlapping self:x((actuals.Width / #choiceNames) * (i-1) + (actuals.Width / #choiceNames / 2)) txt:zoom(choiceTextSize) txt:maxwidth(actuals.Width / #choiceNames / choiceTextSize - textzoomFudge) txt:settext(choiceNames[i]) registerActorToColorConfigElement(txt, "main", "PrimaryText") bg:zoomto(actuals.Width / #choiceNames, actuals.LowerLipHeight) end, ColorConfigUpdatedMessageCommand = function(self) self:playcommand("UpdateSelectedIndex") end, UpdateSelectedIndexCommand = function(self) local txt = self:GetChild("Text") if selectedIndex == i then txt:strokecolor(Brightness(COLORS:getMainColor("PrimaryText"), 0.7)) else txt:strokecolor(color("0,0,0,0")) end end, ClickCommand = function(self, params) if self:IsInvisible() then return end if params.update == "OnMouseDown" then selectedIndex = i MESSAGEMAN:Broadcast("GeneralTabSet", {tab = i}) self:GetParent():playcommand("UpdateSelectedIndex") end end, RolloverUpdateCommand = function(self, params) if self:IsInvisible() then return end if params.update == "in" then self:diffusealpha(buttonHoverAlpha) else self:diffusealpha(1) end end } end local t = Def.ActorFrame { Name = "Choices", InitCommand = function(self) self:y(actuals.Height - actuals.LowerLipHeight / 2) self:z(201) self:playcommand("UpdateSelectedIndex") self:draworder(3) end, BeginCommand = function(self) local snm = SCREENMAN:GetTopScreen():GetName() local anm = self:GetName() -- this keeps track of whether or not the user is allowed to use the keyboard to change tabs CONTEXTMAN:RegisterToContextSet(snm, "Main1", anm) -- enable the possibility to press the keyboard to switch tabs SCREENMAN:GetTopScreen():AddInputCallback(function(event) -- if locked out, dont allow if not CONTEXTMAN:CheckContextSet(snm, "Main1") then return end if event.type == "InputEventType_FirstPress" then -- must be a number and control not held down if event.char and tonumber(event.char) and not INPUTFILTER:IsControlPressed() then local n = tonumber(event.char) if n == 0 then n = 10 end -- n must be a valid option or we must not have focus on the general box (not in search for example) if n >= 1 and n <= #choiceNames or not focused then selectedIndex = n MESSAGEMAN:Broadcast("GeneralTabSet", {tab = n}) self:GetParent():hurrytweening(0.5):playcommand("UpdateSelectedIndex") end elseif event.DeviceInput.button == "DeviceButton_space" and focused and SCUFF.generaltab == SCUFF.generaltabindex then -- toggle chart preview if the general tab is the current tab visible SCUFF.preview.active = not SCUFF.preview.active -- this should propagate off to the right places self:GetParent():playcommand("ToggleChartPreview") end end end) end } for i = 1, #choiceNames do t[#t+1] = createChoice(i) end return t end t[#t+1] = Def.ActorFrame { Name = "Container", InitCommand = function(self) self:xy(actuals.LeftGap, actuals.TopGap) end, GeneralTabSetMessageCommand = function(self) focused = true end, PlayerInfoFrameTabSetMessageCommand = function(self) focused = false end, Def.Quad { Name = "BG", InitCommand = function(self) self:halign(0):valign(0) self:zoomto(actuals.Width, actuals.Height) self:diffusealpha(0.6) registerActorToColorConfigElement(self, "main", "PrimaryBackground") end }, Def.Quad { Name = "Lip", InitCommand = function(self) self:halign(0):valign(1) self:y(actuals.Height) self:zoomto(actuals.Width, actuals.LowerLipHeight) self:diffusealpha(0.6) registerActorToColorConfigElement(self, "main", "SecondaryBackground") self:draworder(3) end }, createChoices(), LoadActorWithParams("generalPages/general.lua", {ratios = ratios, actuals = actuals}) .. { BeginCommand = function(self) -- this will cause the general tab to become visible first on screen startup self:playcommand("GeneralTabSet", {tab = SCUFF.generaltabindex}) -- skip animation self:finishtweening() end }, LoadActorWithParams("generalPages/scores.lua", {ratios = ratios, actuals = actuals}), LoadActorWithParams("generalPages/profile.lua", {ratios = ratios, actuals = actuals}), LoadActorWithParams("generalPages/goals.lua", {ratios = ratios, actuals = actuals}), LoadActorWithParams("generalPages/playlists.lua", {ratios = ratios, actuals = actuals}), LoadActorWithParams("generalPages/tags.lua", {ratios = ratios, actuals = actuals}), } return t
local UISprite = require('UISprite') GImage = class('GImage', GObject) local getters = GImage.getters local setters = GImage.setters function GImage:ctor() GImage.super.ctor(self) end function GImage:dispose() if self._disposed then return end GImage.super.dispose(self) self._isMask = nil end function getters:color() return self._content.color end function setters:color(value) if self._content.color~=value then self._content.color = value self:updateGear(4) end end function getters:fillMethod() return self._content.fillMethod end function setters:fillMethod(value) self._content.fillMethod = value end function getters:fillOrigin() return self._content.fillOrigin end function setters:fillOrigin(value) self._content.fillOrigin = value end function getters:fillClockwise() return self._content.fillClockwise end function setters:fillClockwise(value) self._content.fillClockwise = value end function getters:fillAmount() return self._content.fillAmount end function setters:fillAmount(value) self._content.fillAmount = value end function GImage:constructFromResource() local texture = self.packageItem.owner:getItemAsset(self.packageItem) self.sourceWidth = self.packageItem.width self.sourceHeight = self.packageItem.height self.initWidth = self.sourceWidth self.initHeight = self.sourceHeight self._content = UISprite.new(self) if not self.packageItem.is_mask then self._content:initImage(texture, self.packageItem.scaleOption, self.packageItem.scale9Grid) local obj = self._content.nativeObject obj.gOwner = self self.displayObject = obj else self._isMask = graphics.newMask(texture.filename, texture.baseDir) end self:setSize(self.sourceWidth, self.sourceHeight) end function GImage:setup_BeforeAdd(buffer, beginPos) GImage.super.setup_BeforeAdd(self, buffer, beginPos) buffer:seek(beginPos, 5) local ct = self._content if buffer:readBool() then ct.color = buffer:readColor() end ct.flip = buffer:readByte() ct.fillMethod = buffer:readByte() if ct.fillMethod ~= FillMethod.None then ct.fillOrigin = buffer:readByte() ct.fillClockwise = buffer:readBool() ct.fillAmount = buffer:readFloat() end end
#!/bin/lua if not os.execute('test -f config.lua') then os.execute('cp config.def.lua config.lua') end dofile 'ninja.lua' config = dofile 'config.lua' local recurse = not arg[1] function subgen(dir) local file = '$dir/'..dir..'/local.ninja' subninja(file) table.insert(pkg.inputs.ninja, '$dir/'..dir..'/ninja') table.insert(pkg.inputs.index, '$outdir/'..dir..'/root.index') table.insert(pkg.inputs.perms, '$outdir/'..dir..'/root.perms') local cmd = string.format('test -f %s/%s/local.ninja', pkg.dir, dir) if recurse or not os.execute(cmd) then local oldpkg, oldout = pkg, io.output() if pkg.dir ~= '.' then dir = pkg.dir..'/'..dir end gen(dir) pkg = oldpkg io.output(oldout) end end function gen(dir) pkg={ name=dir:match('[^/]*$'), dir=dir, inputs={ perms={}, index={}, gen={ 'setup.lua', 'ninja.lua', 'config.lua', 'sets.lua', }, ninja={'$dir/local.ninja'}, fetch={}, }, perms={}, } local outdir = config.builddir..'/'..dir if not os.execute('mkdir -p '..outdir) then error('failed to create '..outdir) end io.output(dir..'/local.ninja.tmp') set('dir', dir) if dir ~= '.' then set('outdir', '$builddir/$dir') set('srcdir', '$dir/src') end load('gen.lua') build('gen', '$dir/local.ninja', {'|', pkg.inputs.gen}) phony('ninja', pkg.inputs.ninja) if pkg.hdrs then phony('headers', pkg.hdrs) if pkg.hdrs.install then for hdr in iterstrings(pkg.hdrs) do if not hdr:hasprefix('$outdir/include/') then error('header is not in $outdir/include: '..hdr) end file(hdr:sub(9), '644', hdr) end end end if pkg.deps then phony('deps', pkg.deps) end if next(pkg.perms) then table.sort(pkg.perms, function(s1, s2) return s1:sub(8) < s2:sub(8) end) local f = io.open(outdir..'/local.perms', 'w') table.insert(pkg.perms, '') f:write(table.concat(pkg.perms, '\n')) table.insert(pkg.inputs.perms, '$outdir/local.perms') f:close() end if next(pkg.inputs.perms) then build('mergeperms', '$outdir/root.perms', pkg.inputs.perms) else build('empty', '$outdir/root.perms') end if next(pkg.inputs.index) then build('cat', '$outdir/root.index', pkg.inputs.index, { description=' INDEX $outdir/root.index', }) else build('empty', '$outdir/root.index') end io.close() os.rename(dir..'/local.ninja.tmp', dir..'/local.ninja') end gen(arg[1] or '.')
local function tx(cmd, f) require("vGenPin")(cmd, f) end local function debounce(f) local l = 0 local t = 1000000 return function(...) local n = tmr.now() local d = n - l if d < 0 then d = d + 2147483647 end; if d < t then return end; l = n return f(...) end end do local o = 6 gpio.trig(3, "down", debounce(function() tx("DG P"..o, function(v) if v and #v > 4 then v = v:sub(5) local n = tonumber(v) tx("DS P"..o.." V"..(n == 1 and 0 or 1), function(r) end) end end) end)) end
getglobal game getfield -1 GetService pushvalue -2 pushstring Players pcall 2 1 0 getfield -1 LocalPlayer getfield -1 Data getfield -1 Att pushnumber 99999999999999 setfield -2 Value emptystack
--[[ s:UI Debugging Stuff Not needed for any module or the core itself. Martin Karer / Sezz, 2014 http://www.sezz.at --]] local S = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:GetAddon("SezzUI"); -- Lua API local tinsert, pairs, ipairs = table.insert, pairs, ipairs; ----------------------------------------------------------------------------- function S:DumpAbility(strName, bCompleteDump) local tAbilities = AbilityBook.GetAbilitiesList(); for _, tAbility in pairs(tAbilities) do if (tAbility.strName == strName) then S.Log:debug("ID: %d", tAbility.nId); S.Log:debug("Icon: %s", tAbility.tTiers[1].splObject:GetIcon()); if (bCompleteDump) then S.Log:debug(tAbility); end return tAbility; end end end ----------------------------------------------------------------------------- -- Log Messages Queue ----------------------------------------------------------------------------- local tLogQueue = {}; S.Log = setmetatable({}, { __index = function(t, k) return function(self, ...) if (not tLogQueue[k]) then tLogQueue[k] = {}; end if (#{...} == 1 and type(...) == "table") then tinsert(tLogQueue[k], { S:Clone(...) }); else tinsert(tLogQueue[k], {...}); end end end}); function S:FlushLogQueue() if (not tLogQueue) then return; end for strLogLevel, tQueuedMessages in pairs(tLogQueue) do for _, tData in ipairs(tQueuedMessages) do self.Log[strLogLevel](self.Log, unpack(tData)); end end tLogQueue = nil; end
local build_func = require("build_func") require("build_setup") print(">>> Cleaning bin") os.execute(rmdir("bin\\Debug")) os.execute(rmdir("bin\\Release")) print(">>> Cleaning obj") os.execute(rmdir("obj")) os.execute(mkdir("obj"))
if onServer() then include("randomext") Azimuth = include("azimuthlib-basic") local bof_configOptions = { _version = { default = "1.0", comment = "Config version. Don't touch." }, ChanceToDestroyUpgrade = { default = 0, min = 0, max = 1, comment = "Chance to break Hyperspace Overloader when player destroys Bottan's hyperdrive. 0.75 = 75%" }, UpgradeDeletionDelay = { default = 3, min = 0, max = 10, comment = "Delay in seconds before Hyperspace Overloader upgrade will break. Used to display 'Bottan's hyperdrive destroyed' message on client" } } local bof_config, bof_isModified = Azimuth.loadConfig("BottanFixes", bof_configOptions) if bof_isModified then Azimuth.saveConfig("BottanFixes", bof_config, bof_configOptions) end bof_configOptions = nil function bof_destroySmugglerBlocker() local craft = Player().craft if not craft then return end if bof_config.ChanceToDestroyUpgrade ~= 0 and bof_config.ChanceToDestroyUpgrade >= math.random() then deferredCallback(bof_config.UpgradeDeletionDelay, "bof_deferredDestroySmugglerBlocker", craft.index) -- we can't immediately remove system, because this crashes the game :/ end end function bof_deferredDestroySmugglerBlocker(craftIndex) local craft = Sector():getEntity(craftIndex) if not craft then return end -- remove Hyperspace Overloader from a ship local shipSystem = ShipSystem(craft) if not shipSystem then return end for i = 0, shipSystem.numSlots - 1 do local upgrade = shipSystem:getUpgrade(i) if upgrade and upgrade.script == "data/scripts/systems/smugglerblocker.lua" then shipSystem:removeUpgrade(i) break end end -- it will return to player/alliance inventory, now we need to find and destroy it local inventory = Faction(craft.factionIndex):getInventory() local upgrades = inventory:getItemsByType(InventoryItemType.SystemUpgrade) for idx, item in pairs(upgrades) do if item.item.script == "data/scripts/systems/smugglerblocker.lua" then inventory:remove(idx) break end end Player():sendChatMessage("Server", 0, "Hyperspace Overloader couldn't withstand the pressure! The job is done, but the system upgrade broke."%_t) end end
local modules = { "keymaps", "options", "plugins", "colorscheme", } for i = 1, #modules, 1 do local status_ok, _ = pcall(require, modules[i]) if not status_ok then vim.notify(modules[i] .. " not ok") end end
local Melee = { -1569615261, 1737195953, 1317494643, -1786099057, 1141786504, -2067956739, -868994466 } local Bullet = { 453432689, 1593441988, 584646201, -1716589765, 324215364, 736523883, -270015777, -1074790547, -2084633992, -1357824103, -1660422300, 2144741730, 487013001, 2017895192, -494615257, -1654528753, 100416529, 205991906, 1119849093 } local Knife = { -1716189206, 1223143800, -1955384325, -1833087301, 910830060, } local Car = { 133987706, -1553120962 } local Animal = { -100946242, 148160082 } local FallDamage = { -842959696 } local Explosion = { -1568386805, 1305664598, -1312131151, 375527679, 324506233, 1752584910, -1813897027, 741814745, -37975472, 539292904, 341774354, -1090665087 } local Gas = { -1600701090 } local Burn = { 615608432, 883325847, -544306709 } local Drown = { -10959621, 1936677264 } local BlacklistedCar = { 1171614426, 1127131465, -1647941228, 1938952078, -2007026063, 2046537925, -1627000575, 1912215274, -1973172295, -1536924937, -1779120616, 456714581, -34623805, 353883353, 741586030, -488123221, -1205689942, -1683328900, 1922257928 } local alreadyDead = false local alreadyInCar = false function checkDeathCause(array, val) for name, value in ipairs(array) do if value == val then return true end end return false end function isBlackListedCar(Hash) for _,v in pairs(BlacklistedCar) do if v == Hash then return true end end end Citizen.CreateThread(function() while true do Citizen.Wait(50) local playerPed = GetPlayerPed(-1) if IsEntityDead(playerPed) and not alreadyDead then local playerName = GetPlayerName(PlayerId()) killer = GetPedKiller(playerPed) killername = false for id = 0, 256 do if killer == GetPlayerPed(id) then killername = GetPlayerName(id) end end local death = GetPedCauseOfDeath(playerPed) if checkDeathCause (Melee, death) then TriggerServerEvent("Fd_Logs:SendLogs", "Kill", "Red", "Mort d'un joueur", ""..playerName.." a était tabasser par "..killername) elseif checkDeathCause (Bullet, death) then TriggerServerEvent("Fd_Logs:SendLogs", "Kill", "Red", "Mort d'un joueur", ""..playerName.." a était shooter par "..killername) elseif checkDeathCause (Knife, death) then TriggerServerEvent("Fd_Logs:SendLogs", "Kill", "Red", "Mort d'un joueur", ""..playerName.." a était assassiner par "..killername) elseif checkDeathCause (Car, death) then TriggerServerEvent("Fd_Logs:SendLogs", "Kill", "Red", "Mort d'un joueur", ""..playerName.." a était percuter par "..killername) elseif checkDeathCause (Animal, death) then TriggerServerEvent("Fd_Logs:SendLogs", "Kill", "Red", "Mort d'un joueur", ""..playerName.." a était tuer par un animal.") elseif checkDeathCause (FallDamage, death) then TriggerServerEvent("Fd_Logs:SendLogs", "Kill", "Red", "Mort d'un joueur", ""..playerName.." est mort suite à une chute.") elseif checkDeathCause (Explosion, death) then TriggerServerEvent("Fd_Logs:SendLogs", "Kill", "Red", "Mort d'un joueur", ""..playerName.." est mort suite à une explosion.") elseif checkDeathCause (Gas, death) then TriggerServerEvent("Fd_Logs:SendLogs", "Kill", "Red", "Mort d'un joueur", ""..playerName.." est mort d'asphyxie.") elseif checkDeathCause (Burn, death) then TriggerServerEvent("Fd_Logs:SendLogs", "Kill", "Red", "Mort d'un joueur", ""..playerName.." est mort de brûlure.") elseif checkDeathCause (Drown, death) then TriggerServerEvent("Fd_Logs:SendLogs", "Kill", "Red", "Mort d'un joueur", ""..playerName.." est mort d'asphyxie.") else TriggerServerEvent("Fd_Logs:SendLogs", "Kill", "Red", "Mort d'un joueur", ""..playerName.." est mort de raison inconnue.") end alreadyDead = true end if IsPedSittingInAnyVehicle(playerPed) and not alreadyInCar then local vehicle = GetVehiclePedIsIn(playerPed, false) local playerName = GetPlayerName(PlayerId()) if isBlackListedCar(GetEntityModel(vehicle)) then TriggerServerEvent("Fd_Logs:SendLogs", "Car", "Blue", "Utilisation d'un véhicule", ""..playerName.." est monter dans un véhicule interdit.") alreadyInCar = true end end if not IsPedSittingInAnyVehicle(playerPed) and alreadyInCar then alreadyInCar = false end if not IsEntityDead(playerPed) and alreadyDead then alreadyDead = false end end end)
local M = {} M.bounds_min = vmath.vector3(-0.439571797848, -0.500100135803, -0.125) M.bounds_max = vmath.vector3(0.439570665359, 0.500603556633, 0.125000506639) M.size = vmath.vector3(0.879142463207, 1.00070369244, 0.250000506639) return M
function onEvent(n,v1,v2) if n == "Red Screen" then if not lowQuality then runTimer('hide',1); makeAnimatedLuaSprite('redload','Red Screen',-250,-150) addAnimationByPrefix('redload','redpog','red appear',14,true) objectPlayAnimation('redload','redpog',false) setScrollFactor('redload', 0, 0); scaleObject('redload', 1.4, 1.4); addLuaSprite('redload', true); end end end function onTimerCompleted(tag, loops, loopsLeft) if tag == 'hide' then removeLuaSprite('redload', false); end end
local ParentGroup = script.parent--script:GetCustomProperty("RootGroup"):WaitForObject() local LocalPlayer = Game.GetLocalPlayer() local VELOCITY_Z_RESTRICTION = ParentGroup:GetCustomProperty("VelocityZRestriction") local RADIUS_DOT_PRODUCT = ParentGroup:GetCustomProperty("RadiusDotProduct") local BINDING_PUSH = ParentGroup:GetCustomProperty("PushBinding") local FORCE = ParentGroup:GetCustomProperty("Force") local DESTROY_TIME = ParentGroup:GetCustomProperty("DestroyTime") local RADIUS = ParentGroup:GetCustomProperty("Radius") local EVENT = ParentGroup:GetCustomProperty("Event") local PUSH_VECTOR = ParentGroup:GetCustomProperty("PushVector") local function PushObject(object) if(not Object.IsValid(object)) then return end if(not object:IsA("StaticMesh")) then return end --[[llocal vector = object:GetWorldPosition() - LocalPlayer:GetWorldPosition() if(vector.size > RADIUS) then return end local normal = vector:GetNormalized() ocal forwardVector = player:GetWorldTransform():GetForwardVector() local dot = normal .. forwardVector if dot < RADIUS_DOT_PRODUCT then return end]] --[[if(VELOCITY_Z_RESTRICTION >= 0) then if(vector.z < VELOCITY_Z_RESTRICTION) then vector.z = VELOCITY_Z_RESTRICTION end end]] object.isSimulatingDebrisPhysics = true object:SetVelocity(PUSH_VECTOR * FORCE) --object:MoveContinuous(vector * 10) return true end local function DestroyObject(object) if(not Object.IsValid(object)) then return end if(not object:IsA("StaticMesh")) then return end object:Destroy() end local function PushObjects() local taggedObjects = {} for _, object in pairs(ParentGroup:GetChildren()) do local tagged = PushObject(object) if(tagged) then table.insert(taggedObjects, object) end end if(#taggedObjects < 1) then return end Task.Wait(DESTROY_TIME) for _, object in pairs(taggedObjects) do DestroyObject(object) end end local function OnBindingReleased(player, binding) if(binding ~= BINDING_PUSH) then return end PushObjects() end LocalPlayer.bindingReleasedEvent:Connect(OnBindingReleased) Events.Connect(EVENT, PushObjects)
local _c = LPPS_C_LIB local _cLog = _c.log local log = {} local _lv = 0 function log.level(lv) if lv and type(lv) == 'number' and lv >= 0 and lv <= 3 then _lv = lv end return _lv end -- function log.debug(str,...) assert(str) if _lv <= 0 then _cLog(0,str,...) end end function log.info(str,...) assert(str) if _lv <= 1 then _cLog(1,str,...) end end function log.warn(str,...) assert(str) if _lv <= 2 then _cLog(2,str,...) end end function log.error(str,...) assert(str) if _lv <= 3 then _cLog(3,str,...) end end return log
--[[ $Id$ Copyright © 2010 VideoLAN and AUTHORS Authors: Julien 'Lta' BALLET <contact at lta dot io> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] local config = {} config["base_url"] = "http://api.icast.io" config["api_base_url"] = config.base_url.."/1" local json = nil local roots = nil function json_init() if json ~= nil then return false end vlc.msg.dbg("JSON parser lazy initialization") json = require ("dkjson") -- Use vlc.stream to grab a remote json file, place it in a string, -- decode it and return the decoded data. json["parse_url"] = function(url) local stream = vlc.stream(url) local string = "" local line = "" repeat line = stream:readline() string = string..line until line ~= nil --print(string) return json.decode(string) end end -- VLC SD mandatory method, return the name and capabilities of this SD. function descriptor() return { title = "iCast Stream Directory", capabilities = {"search"} } end -- Utility function to replace nils by an empty string, borrowed from icecast.lua function dropnil(s) if s == nil then return "" else return s end end function roots_init() if roots ~= nil then return nil end roots = { locals = vlc.sd.add_node({title="Local Streams"}), cats = vlc.sd.add_node({title="Categories"}), search = nil } end -- Add this station to the discovered service list. function station_add(node, station) if station.streams == nil or station.streams[1] == nil then return nil end item = node:add_subitem({ title = station.name, path = station.streams[1]["uri"], meta = { ["Listing Source"] = "icast.io", ["Listing Type"] = "radio", ["Icecast Bitrate"] = dropnil(station.streams[1].bitrate) } }) if station.slogan then item:set_name(station.name..": "..station.slogan) end if station.genre_list then item:set_genre(table.concat(station.genre_list, ", ")) end if station.language then item:set_language(station.language) end if station.logo.medium then item:set_arturl(config.base_url..station.logo.medium) end end -- Get an url to iCast's API, parse the returned stations and add them -- to the list of discovered medias. function stations_fetch(node, url) json_init() vlc.msg.info("Fetching stations from API ("..url..")") local result = json.parse_url(config.api_base_url..url) if result.stations == nil then return nil end for _, station in ipairs(result.stations) do station_add(node, station) end end -- VLC SD API - Search entry point function search(query) if roots.search then vlc.sd.remove_node(roots.search) end roots.search = vlc.sd.add_node({title="Search Results"}) stations_fetch(roots.search, "/stations/search.json?q="..query.."*") end -- VLC SD API - Main listing entry point function main() roots_init() stations_fetch(roots.locals, "/stations/local.json") vlc.msg.dbg("Fetching list of genre from API (/genres.json)") local result = json.parse_url(config.api_base_url.."/genres.json") for genre, sub_genres in pairs(result.genres) do local node = roots.cats:add_subnode({title=genre}) for _, sub_genre in ipairs(sub_genres) do local sub_node = node:add_subnode({title=sub_genre}) stations_fetch(sub_node, "/stations/genre/"..sub_genre..".json") end end end
-- PeanutLabs plugin local Library = require "CoronaLibrary" -- Create library local lib = Library:new{ name="plugin.peanutlabs", publisherId="com.coronalabs" } ------------------------------------------------------------------------------- -- BEGIN ------------------------------------------------------------------------------- -- This sample implements the following Lua: -- -- local peanutlabs = require "plugin.peanutlabs" -- peanutlabs.init() -- local function showWarning(functionName) print( functionName .. " WARNING: The PeanutLabs plugin is only supported on Android & iOS devices. Please build for device") end function lib.init() showWarning("peanutlabs.init()") end function lib.show() showWarning("peanutlabs.show()") end ------------------------------------------------------------------------------- -- END ------------------------------------------------------------------------------- -- Return an instance return lib
return { 1296,1263,1263,1263,1263,1263,1297,1521,1457,1843,1844,1844,1844,1844,1845,1521,2147485268,1296,1263,1263,1263,1263,1263,1263,1263,1263,1263,1263,1263,1263,1263,1263,1263,1263,1263,1263,1263,1263,1297,1521,1457,1843,1844,1844,1844,1844,1844,1845, 1329,0,0,0,0,0,1330,1521,1457,2147485195,1987,1988,1989,0,1879,1521,1457,1329,0,0,0,778,779,780,0,0,0,778,779,780,0,0,0,778,779,780,0,0,1330,1521,1457,2147485195,0,0,0,0,0,1879, 2024,2025,2026,2024,2025,2026,0,1521,1457,2147485195,0,0,0,0,1879,1521,1457,1329,778,779,780,811,812,813,778,779,780,811,812,813,778,779,780,811,812,813,0,0,1330,1521,1457,2147485195,1953,1987,1988,1989,1955,1879, 1953,1954,1955,1953,1954,1955,0,1521,1457,2147485195,0,0,0,0,1879,1521,2147485268,1329,811,812,813,844,845,846,811,812,813,844,845,846,811,812,813,844,845,846,0,0,1330,1521,1457,2147485195,2017,2018,2018,2018,2020,1879, 1987,1988,1989,1987,1988,1989,0,1521,1457,2147485195,0,0,0,1878,1879,1521,1523,1329,844,845,846,0,0,0,844,845,846,0,0,0,844,845,846,0,0,0,0,0,1330,1521,1457,2147485195,1948,1961,1961,1961,1982,1879, 2016,2018,2018,2018,2018,2050,0,1521,1457,2147485195,0,0,0,1878,1879,1521,1457,1362,1264,1264,1264,1264,1264,1264,1264,1264,1264,1264,1264,1264,1264,1264,1264,1264,1264,1264,1264,1264,1363,1521,1457,2147485195,1948,2055,2056,2057,1982,1879, 2022,2018,2022,2018,2022,2050,0,1521,1457,2147485195,0,0,0,1878,1879,1521,1457,0,0,0,0,0,3221227412,1912,1912,1912,1912,1912,1912,1912,1912,1912,1912,1912,1912,1912,1912,1912,1913,1521,1457,2147485561,2153,2061,2059,2062,2147485801,1913, 2021,2055,2056,2056,2057,2023,0,1521,1457,2147485195,1878,1878,1878,1878,1879,1521,1457,1877,1878,1878,1878,1878,1879,536872301,1553,1553,1553,1553,1553,1553,1553,1553,1553,1553,1553,1553,1553,1553,1553,1554,2147485202,1553,1553,1553,1553,1553,1553,1553, 2147485807,2058,2059,2059,2060,2159,1330,1521,1457,2147485195,1878,1878,1878,1878,1879,1521,1457,1877,1878,1878,1878,1878,1879,1521,2147485268,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1620,2147485268,1619,1619,1619,1619,1619,1619,1619, 1329,1334,1273,1272,1336,0,1330,1521,1457,2147485195,1878,1878,1878,1878,1879,1521,1457,1877,1878,1878,1878,1878,1879,1521,1457,2147485162,2147485159,2147485159,2147485159,2147485159,2147485159,1844,1844,1511,1511,1511,1511,1511,1514,1521,1457,2147485162,2147485159,2147485159,2147485159,2147485159,2147485159,1845, 1329,0,1301,1303,0,0,1330,1521,1457,1877,1878,1878,1878,1878,1879,1521,1457,1877,1878,1878,1878,1878,1879,1521,1457,1877,1953,1954,1955,1953,1954,1955,1953,1954,1955,1953,1954,1955,1879,1521,1457,1877,1878,1878,2024,2025,2026,1879, 1329,0,1301,1305,1270,0,1330,1521,1457,2147485195,1878,1878,1878,1878,1879,1521,1457,1877,1878,1878,1878,1878,1879,1521,1457,2147485195,1987,1988,1989,1987,1988,1989,1987,1988,1989,1987,1988,1989,1547,1521,1457,2147485195,1878,1878,1987,1988,1989,1879, 1329,0,1334,1273,1303,0,1330,1521,1457,2147485195,1878,1878,1878,1878,1879,1521,1457,1877,1878,1878,1878,1878,1879,1521,1457,2147485195,1948,2022,1982,1948,2022,1982,1948,2022,1982,1948,2022,1982,1547,1521,1457,2147485195,1878,1878,1948,2022,1982,1879, 1329,0,0,1301,1303,0,1330,1521,1457,1543,1878,1073743766,1912,1912,1913,1521,1457,1911,1912,1912,3221227414,1878,1879,1521,1457,1543,2017,2018,2019,2017,2018,2019,2017,2018,2019,2017,2018,2019,1547,1521,1457,1543,1878,1878,2017,2018,2019,1879, 1329,0,0,1301,1303,0,1330,1521,1457,1543,1878,1879,1389,1553,1553,1554,1556,1553,1553,1391,1877,1878,1879,1521,1457,1543,1953,1954,1955,770,770,770,770,770,770,1953,1954,1955,1547,1521,1457,1543,1878,1878,2024,2025,2026,1879, 1329,0,0,1301,1303,0,1330,1521,1457,1877,1878,1879,1521,3221227026,1619,1619,1619,1619,1073743378,1457,1877,1878,1879,1521,1457,1877,1987,1988,1989,770,770,837,770,770,770,1987,1988,1989,1879,1521,1457,1877,1878,1878,1987,1988,1989,1879, 1329,0,0,1301,1303,0,1330,1521,1457,1877,1878,1879,1521,1457,1878,1878,1878,1878,2147485105,1457,1877,1878,1879,1521,1457,1877,1948,2022,1982,770,778,779,780,836,770,1948,2022,1982,1879,1521,1457,1877,1878,1878,1948,2022,1982,1879, 1329,0,0,1301,1303,0,1330,1521,1457,2147485195,1878,1879,1521,1457,1878,1878,1878,1878,2147485105,1457,1877,1878,1547,1521,1457,2147485195,2017,2018,2019,770,811,812,813,770,770,2017,2018,2019,1547,1521,1457,1877,1878,1878,2017,2018,2019,1879, 1329,0,0,1301,1305,1270,1330,1521,1457,2147485195,1878,1879,1521,2147485202,1553,1553,1553,1553,1554,1457,1877,1878,1547,1521,1457,2147485195,1953,1954,1955,1953,844,845,846,0,1955,1953,1954,1955,1547,1521,1457,1877,1878,1878,2024,2025,2026,1879, 1329,0,0,1334,1273,1303,1330,1521,1457,2147485195,1878,1879,1610614125,1619,1619,1619,1619,1619,1619,3758097773,1877,1878,1547,1521,1457,2147485195,1987,1988,1989,1987,0,0,0,0,1989,1987,1988,1989,1547,1521,1457,1877,1878,1878,1987,1988,1989,1879, 1329,0,0,0,1301,1305,1270,1521,1457,2147485195,1878,1942,1844,1844,1844,1844,1844,1844,1844,1844,2147485590,1878,1547,1521,1457,2147485195,1948,2022,1982,1948,2022,1982,1948,2022,1982,1948,2022,1982,1547,1521,1457,1877,1878,1878,1948,2022,1982,1879, 1362,1264,1264,1264,1301,0,1303,1521,1457,2147485195,1878,1878,1878,1878,1878,1878,1878,1878,1878,1878,1878,1878,1547,1521,1457,1877,2017,2018,2019,2017,2018,2019,2017,2018,2019,2017,2018,2019,1547,1521,1457,1877,1878,1878,2017,2018,2019,1879, 1911,1912,1912,1912,1912,1912,1913,197,1457,2147485561,2147485560,2147485560,2147485560,2147485560,2147485560,1912,1912,1912,1912,1912,1912,1912,1913,1521,2147485169,1911,1912,2147485560,2147485560,2147485560,2147485560,1912,1912,1912,1912,1912,1912,1912,1913,1521,1457,1877,1878,1878,2024,2025,2026,1879, 1553,1553,1553,1553,1553,1553,1553,1554,1556,1553,1553,1553,1553,1553,1553,1553,1553,1553,1553,1553,1553,1553,1553,1554,2147485202,2147485201,1553,1553,1553,1553,1553,1553,1553,1553,1553,1553,1551,1553,1553,1554,1457,1877,1878,1878,1987,1988,1989,1879, 1619,1619,1619,1619,1616,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1588,1622,1619,1616,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1358,1877,1878,1878,1948,2022,1982,1879, 1843,1844,1844,1844,1844,1844,1844,1844,1844,1844,1844,1844,1844,1844,1844,1844,1844,1511,1511,1511,1511,1511,1514,1521,1457,0,2147485159,2147485159,2147485159,2147485159,2147485159,1844,1844,1844,1844,1844,1844,1844,1844,1844,1844,1940,1878,1878,2017,2018,2019,1879, 1877,2024,2025,2026,2024,2025,2026,2024,2025,2026,2024,2025,2026,2024,2025,2026,2024,2025,2026,2024,2025,2026,1879,1521,1457,0,2024,2025,2026,0,0,0,2024,2025,2026,2024,2025,2026,2024,2025,2026,0,0,0,2024,2025,2026,1879, 1877,1987,1988,1989,1987,1988,1989,1987,1988,1989,1987,1988,1989,1987,1988,1989,1987,1988,1989,1987,1988,1989,1547,1521,1457,736,770,1988,1989,737,737,737,1987,1988,1989,1987,1988,1989,1987,1988,1989,737,737,737,1987,1988,1989,738, 1877,1948,2022,1982,1948,2022,1982,1948,2022,1982,1948,2022,1982,1948,2022,1982,1948,2022,1982,1948,2022,1982,1547,1521,1457,769,770,0,1982,0,0,0,1948,2022,1982,1948,2022,1982,1948,2022,1982,0,0,0,1948,2022,1982,771, 1877,2016,2018,2019,2147485667,2018,2020,2016,2018,2019,2147485667,2018,2020,2016,2018,2019,2147485667,2018,2020,2016,2018,2019,1547,1521,1457,769,770,0,2019,0,0,0,2017,2018,2019,2017,2018,2019,2017,2018,2019,0,0,0,2017,2018,2019,771, 1877,2024,2025,2026,736,737,737,737,737,737,737,737,737,737,737,737,737,737,738,2147485674,2147485673,2147485672,1547,1521,1457,769,770,0,2026,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2024,2025,2026,771, 1877,1987,1988,1989,769,0,0,0,0,0,0,0,0,0,0,0,0,0,771,2147485637,2147485636,2147485635,1879,1521,1457,769,770,0,1989,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1987,1988,1989,771, 1877,1948,2022,1982,769,0,0,0,0,0,0,0,0,0,0,0,0,0,771,2147485630,2147485670,2147485596,1879,1521,1457,769,770,0,1982,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1948,2022,1982,771, 1877,2017,2018,2019,769,0,0,0,0,0,0,0,0,0,0,0,0,0,771,2147485667,2147485666,2147485665,1879,1521,1457,769,770,0,2019,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2017,2018,2019,771, 1877,2024,2025,2026,769,0,0,0,0,0,0,0,0,0,0,0,0,0,771,2147485674,2147485673,2147485672,1879,1521,1457,769,770,0,2026,2024,2025,2026,2024,2025,2026,2024,2025,2026,2024,2025,2026,2024,2025,2026,2024,2025,2026,771, 1877,1987,1988,1989,769,0,0,0,0,0,0,0,0,0,0,0,0,0,771,2147485637,2147485636,2147485635,1879,1521,1457,769,770,0,1989,1987,1988,1989,1987,1988,1989,1987,1988,1989,1987,1988,1989,1987,1988,1989,1987,1988,1989,771, 1877,1948,2022,1982,769,0,0,0,0,0,0,0,0,0,0,0,0,0,771,2147485630,2147485670,2147485596,1879,1521,1457,769,770,0,1982,1948,2022,1982,1948,2022,1982,1948,2022,1982,1948,2022,1982,1948,2022,1982,1948,2022,1982,771, 1877,2017,2018,2019,802,803,803,803,803,803,671,0,0,0,0,0,0,0,771,2147485667,2147485666,2147485665,1879,1521,2147485169,769,770,2018,2019,2017,2018,2019,2017,2018,2019,2017,2018,2019,2017,2018,2019,2017,2018,2019,2017,2018,2019,771, 1911,1912,1912,1912,1912,1912,1912,1912,1912,3221227414,769,0,0,0,0,0,0,0,771,2147485674,2147485673,2147485672,1879,1521,2147485169,802,803,803,803,803,803,803,803,803,803,803,803,803,803,803,803,803,803,803,803,803,803,804, 1553,1553,1553,1553,1553,1553,1553,1553,1457,1877,769,0,0,0,0,0,0,0,771,2147485637,2147485636,2147485635,1879,1521,2147485202,1553,1551,1553,1553,1553,1553,1553,1553,1553,1553,1553,1553,1553,1553,1553,1553,1553,1550,1553,1553,1553,1553,1553, 1619,1619,1619,1619,1619,1619,1619,1620,1457,1877,769,0,0,0,0,0,0,0,771,2147485630,2147485670,2147485596,1879,1521,3221227026,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619,1619, 0,0,0,0,0,0,0,1521,1457,1877,802,803,803,803,803,803,803,803,804,2147485667,2147485666,2147485665,1879,1521,1457,2147485162,2147485159,2147485159,2147485159,2147485159,2147485159,1844,1844,1511,1511,1511,1511,1511,1511,1511,1511,1511,2147485159,2147485159,2147485159,2147485159,2147485159,1845, 0,0,0,0,0,0,0,1521,1457,1877,105,2025,2026,2024,2025,2026,2024,2025,2026,2024,2025,2026,1879,1521,1457,1877,736,737,737,737,737,737,738,736,737,737,737,737,737,737,738,1878,1878,1878,1878,1878,1878,1879, 0,0,0,0,1791,0,0,1521,1457,1877,1987,1988,1989,1987,1988,1989,1987,1988,1989,1987,1988,1989,1879,1521,1457,2147485195,769,770,770,770,770,837,703,704,770,770,770,770,770,836,703,737,737,737,737,738,0,1879, 1718,1719,0,2052,160,0,0,1521,1457,1877,1948,2022,1982,1948,2022,1982,1948,2022,1982,1948,2022,1982,1879,1521,1457,2147485195,769,770,770,770,837,770,770,770,770,770,770,770,770,770,770,770,770,770,770,771,1878,1879, 1752,1753,0,1756,0,1756,0,1455,1457,1877,2147485667,2018,2020,2017,2018,2019,2147485667,2018,2020,2017,2018,2019,1879,1521,1457,1543,802,803,803,803,803,803,803,803,671,770,770,770,770,770,770,770,836,670,803,804,1878,1879, 0,0,0,0,0,0,0,1521,1457,1877,1878,1878,1878,1878,1878,1878,1878,1878,1878,1878,1878,1878,1879,1521,1457,1543,1878,1878,1878,1878,1878,1878,1878,1878,802,803,803,803,803,803,803,803,803,804,1878,1878,1878,1879, 0,0,0,0,0,0,0,1521,1457,1911,1912,1912,1912,1912,1912,1912,1912,1912,1912,1912,1912,1912,1913,1521,1457,1911,1912,1912,1912,1912,1912,1912,1912,1912,1912,1912,1912,1912,1912,1912,1912,1912,1912,1912,1912,1912,1912,1913 }
local comp = require("component") local fs = require("filesystem") local internet = comp.internet local api = {} function api.internetRequest(url) checkArg(1, url, "string") local success, response = pcall(internet.request, url) if success then local responseData = "" while true do local data, responseChunk = response.read() if data then responseData = responseData..data else if responseChunk then return false, responseChunk else return true, responseData end end end else return false, reason end end function api.download(url, path) checkArg(1, url, "string") checkArg(2, path, "string") local success, response = api.internetRequest(url) if success then fs.makeDirectory(fs.path(path) or "/") local file = io.open(path, "w") file:write(response) file:close() end return success end function api.runFromUrl(url, ...) checkArg(1, url, "string") local success, response = api.internetRequest(url) if success then response, reason = load(response) if response then response = { pcall(response, ...) } if response[1] then return table.unpack(response, 2) else return false, "Failed to run script: "..tostring(response[2]) end else return false, "Failed to run script: "..tostring(loadReason) end else return false, response end end return api
--[[ A pandoc filter that generates Lists Of Figures and Tables (loft). This filter enables the lot and lof options as in LaTeX output formats. The user can also customise the titles with lot-title and lof-title: --- lof: lof-title: "Illustrations" # markdown styling is supported --- --]] -- REQUIREMENTS: Load shared lua function - see `shared.lua` in rmarkdown for more details. -- * pandocAvailable() -- * pandoc_type() function (backward compatible type() after 2.17 changes) -- * print_debug() dofile(os.getenv 'RMARKDOWN_LUA_SHARED') --[[ About the requirement: * PANDOC_VERSION -> 2.2.3 ]] if (not pandocAvailable {2,2,3}) then io.stderr:write("[WARNING] (jss.lua) requires at least Pandoc 2.1. Lua Filter skipped.\n") return {} end -- START OF THE FILTER'S FUNCTIONS -- local options = {} -- where we store pandoc Meta local tablesList = {} -- where we store the list of tables local figuresList = {} -- where we store the list of figures -- The following function stores pandoc Meta in the options local variable local function getMeta(meta) options = meta -- If there is no given titles, use default titles if not options["lot-title"] then options["lot-title"] = pandoc.MetaInlines(pandoc.Str("List of Tables")) end if not options["lof-title"] then options["lof-title"] = pandoc.MetaInlines(pandoc.Str("List of Figures")) end return nil -- Do not modify Meta end -- Helpers function -- -- From a caption text, retrieve the reference and find it in reference list local function refFromCaption(captionText, refList) local ref -- build figure reference from figure caption ref = "@ref" .. string.gsub(captionText, "#", "") ref = string.gsub(ref, "%)", ") ") -- add a space -- insert figure reference in figuresList table.insert(refList, {pandoc.Plain(pandoc.Str(ref))}) end -- This function is called only for Div of class figure inserted by bookdown local function getFigCaption(div) local listOfBlocks = div.content local found for i, block in ipairs(listOfBlocks) do if block.t == "RawBlock" then if block.text == '<p class="caption">' then found = i + 1 break end end end if found then return pandoc.utils.stringify(div.content[found]) else return nil end end -- Main AST processing functions -- This function looks for caption in div of class figures. Usually raw HTML of this -- structure is inserted by knitr::include_graphics() when `fig.cap` is provided -- which identified as a Div in AST (bc of native_divs). -- It builds and saves the items used by the list of figures. local function addFigRef(div) local captionText local figref -- do not build the lof if not required if not options.lof then return nil end if div.classes:includes("figure") then captionText = getFigCaption(div) if not captionText then return nil end refFromCaption(captionText, figuresList) end return nil -- Do not modify Div end -- This function inspects the Images captions when Images are part of Figures -- (when Pandoc adds fig: in title meaning implicit_figures have identified it) -- When a bookdown id is found, it builds and saves the items used by -- the list of figures. local function addFigRef2(img) local captionText local figref -- do not build the lof if not required if not options.lof then return nil end -- Identified a figure if img.title and img.title:sub(1,4) == "fig:" then captionText = pandoc.utils.stringify(img.caption) found = string.find(captionText, "%(#fig:.*%)") if found then refFromCaption(captionText, figuresList) end end end -- This function inspects the tables captions. -- When a bookdown id is found, it builds and saves the items used by -- the list of tables. local function addTabRef(tab) local caption local found local tabref -- do not build the lot if not required if not options.lot then return nil end caption = pandoc.utils.stringify(tab.caption) -- test the presence of a bookdown table id found = string.find(caption, "%(#tab:.*%)") if found then refFromCaption(caption, tablesList) end return nil -- Do not modify Table end -- This function appends the LOT/LOF to the document using custom titles -- if provided and is insert the new section into TOC unless opt-out local function appendLoft(doc) local lotHeader local lofHeader local lotClasses = {"lot", "unnumbered", "front-matter"} local lofClasses = {"lof", "unnumbered", "front-matter"} local idprefix = options.idprefix or "" if options.lof then table.insert(doc.blocks, 1, pandoc.BulletList(figuresList)) if options["lof-unlisted"] then table.insert(lofClasses, "unlisted") end lofHeader = pandoc.Header(1, {table.unpack(options["lof-title"])}, pandoc.Attr(idprefix .. "LOF", lofClasses, {}) ) table.insert(doc.blocks, 1, lofHeader) end if options.lot then table.insert(doc.blocks, 1, pandoc.BulletList(tablesList)) if options["lot-unlisted"] then table.insert(lotClasses, "unlisted") end lotHeader = pandoc.Header(1, {table.unpack(options["lot-title"])}, pandoc.Attr(idprefix .. "LOT", lotClasses, {}) ) table.insert(doc.blocks, 1, lotHeader) end return pandoc.Pandoc(doc.blocks, doc.meta) end -- Organize filters: Meta filter needs to run before others return { {Meta = getMeta}, {Div = addFigRef, Image = addFigRef2, Table = addTabRef, Pandoc = appendLoft} }
-- Loads the `conf` var from layerset INI file require "layerset" local driver = require('luasql.postgres') local env = driver.postgres() local pgosm_conn_env = os.getenv("PGOSM_CONN") local pgosm_conn = nil if pgosm_conn_env then pgosm_conn = pgosm_conn_env else error('ENV VAR PGOSM_CONN must be set.') end layers = {'amenity', 'building', 'indoor', 'infrastructure', 'landuse' , 'leisure' , 'natural', 'place', 'poi', 'public_transport' , 'road', 'road_major', 'shop', 'tags' , 'traffic', 'unitable', 'water'} local function post_processing(layerset) print(string.format('Post-processing %s', layerset)) local filename = string.format('sql/%s.sql', layerset) local sql_file = io.open(filename, 'r') sql_raw = sql_file:read( '*all' ) sql_file:close() local result = con:execute(sql_raw) --print(result) -- Returns 0.0 on success? nil on error? end -- Establish connection to Postgres con = assert (env:connect(pgosm_conn)) -- simple query to verify connection cur = con:execute"SELECT version() AS pg_version;" row = cur:fetch ({}, "a") while row do print(string.format("Postgres version: %s", row.pg_version)) -- reusing the table of results row = cur:fetch (row, "a") end post_processing('pgosm-meta') for ix, layer in ipairs(layers) do if conf['layerset'][layer] then post_processing(layer) end end -- close everything cur:close() con:close() env:close()
local Deque = require('class')('Deque') function Deque:__init() self._objects = {} self._first = 0 self._last = -1 end function Deque:getCount() return self._last - self._first + 1 end function Deque:pushLeft(obj) self._first = self._first - 1 self._objects[self._first] = obj end function Deque:pushRight(obj) self._last = self._last + 1 self._objects[self._last] = obj end function Deque:popLeft() if self._first > self._last then return nil end local obj = self._objects[self._first] self._objects[self._first] = nil self._first = self._first + 1 return obj end function Deque:popRight() if self._first > self._last then return nil end local obj = self._objects[self._last] self._objects[self._last] = nil self._last = self._last - 1 return obj end function Deque:peekLeft() return self._objects[self._first] end function Deque:peekRight() return self._objects[self._last] end function Deque:iter() local t = self._objects local i = self._first - 1 return function() i = i + 1 return t[i] end end return Deque
module(..., package.seeall) require "source/sound/sound" local flower = flower local widget = widget local view = nil function onCreate(e) layer = flower.Layer() layer:setTouchEnabled(false) scene:addChild(layer) view = widget.UIView { scene = scene, layout = widget.BoxLayout { gap = {5, 5}, padding = {10, 10, 10, 10}, align = {"center", "top"}, }, children = {{ widget.Button { size = {0, flower.viewHeight/5} }, flower.Label("Little Red Comet Games", nil, nil, nil, 64), widget.Button { normalTexture = "logo.png", size = {flower.viewWidth/2.5, flower.viewWidth/2.5}, }, flower.Label("Loading assets, please wait...", nil, nil, nil, 24), }} } end function onStart(e) flower.Executors.callLaterFrame(1, function() loadResources() flower.gotoScene("source/scenes/mainMenu", {animation="fade"}) end) end function loadResources() soundManager = SoundManager { soundDir = "assets/sounds/soundtrack/", } end
local sqrt, cos, sin = math.sqrt, math.cos, math.sin local function str(x,y) return "("..tonumber(x)..","..tonumber(y)..")" end local function mul(s, x,y) return s*x, s*y end local function div(s, x,y) return x/s, y/s end local function add(x1,y1, x2,y2) return x1+x2, y1+y2 end local function sub(x1,y1, x2,y2) return x1-x2, y1-y2 end local function permul(x1,y1, x2,y2) return x1*x2, y1*y2 end local function dot(x1,y1, x2,y2) return x1*x2 + y1*y2 end local function det(x1,y1, x2,y2) return x1*y2 - y1*x2 end local function eq(x1,y1, x2,y2) return x1 == x2 and y1 == y2 end local function lt(x1,y1, x2,y2) return x1 < x2 or (x1 == x2 and y1 < y2) end local function le(x1,y1, x2,y2) return x1 <= x2 and y1 <= y2 end local function len2(x,y) return x*x + y*y end local function len(x,y) return sqrt(x*x + y*y) end local function dist(x1,y1, x2,y2) return len(x1-x2, y1-y2) end local function normalize(x,y) local l = len(x,y) return x/l, y/l end local function rotate(phi, x,y) local c, s = cos(phi), sin(phi) return c*x - s*y, s*x + c*y end local function perpendicular(x,y) return -y, x end local function project(x,y, u,v) local s = (x*u + y*v) / (u*u + v*v) return s*u, s*v end local function mirror(x,y, u,v) local s = 2 * (x*u + y*v) / (u*u + v*v) return s*u - x, s*v - y end -- the module return { str = str, -- arithmetic mul = mul, div = div, add = add, sub = sub, permul = permul, dot = dot, det = det, cross = det, -- relation eq = eq, lt = lt, le = le, -- misc operations len2 = len2, len = len, dist = dist, normalize = normalize, rotate = rotate, perpendicular = perpendicular, project = project, mirror = mirror, }
local vmf = get_mod("VMF") local _vmf_users = {} local _rpc_callbacks = {} local _local_mods_map = {} local _local_rpcs_map = {} local _shared_mods_map = "" local _shared_rpcs_map = "" local _network_module_is_initialized = false local _network_debug = false local VERMINTIDE_CHANNEL_ID = 1 local RPC_VMF_REQUEST_CHANNEL_ID = 3 local RPC_VMF_RESPONCE_CHANNEL_ID = 4 local RPC_VMF_UNKNOWN_CHANNEL_ID = 5 -- Note(Siku): No clue what 5 is supposed to mean. -- #################################################################################################################### -- ##### Local functions ############################################################################################## -- #################################################################################################################### local function is_rpc_registered(mod_name, rpc_name) local success = pcall(function() return _rpc_callbacks[mod_name][rpc_name] end) return success end -- CONVERTING local function convert_names_to_numbers(peer_id, mod_name, rpc_name) local user_rpcs_dictionary = _vmf_users[peer_id] if user_rpcs_dictionary then local mod_number = user_rpcs_dictionary[1][mod_name] if mod_number then local rpc_number = user_rpcs_dictionary[2][mod_number][rpc_name] if rpc_number then return mod_number, rpc_number end end end return nil end local function convert_numbers_to_names(mod_number, rpc_number) local mod_name = _local_mods_map[mod_number] if mod_name then local rpc_name = _local_rpcs_map[mod_number][rpc_number] if rpc_name then return mod_name, rpc_name end end return nil end -- SERIALIZATION local function serialize_data(...) return cjson.encode({...}) end local function deserialize_data(data) data = cjson.decode(data) local args_number = #data for i, _ in ipairs(data) do if type(data[i]) == "userdata" then -- userdata [nullptr (deleted)] -> nil data[i] = nil end end return unpack(data, 1, args_number) end -- DEBUG local function network_debug(rpc_type, action_type, peer_id, mod_name, rpc_name, data) if _network_debug then local debug_message if action_type == "local" then debug_message = "[NETWORK][LOCAL]" else local msg_direction = (action_type == "sent" and "<-" or "->") local player_string = tostring(Managers.player:player_from_peer_id(peer_id)) --NOTE (Siku): Multiple concatenation requires the creation of multiple strings, look into it. --debug_message = string.format("[NETWORK][%s (%s)] %s", peer_id, player_string, msg_direction) debug_message = "[NETWORK][" .. peer_id .. " (" .. player_string .. ")]" .. msg_direction end if rpc_type == "ping" then debug_message = debug_message .. "[PING]" elseif rpc_type == "pong" then debug_message = debug_message .. "[PONG]" elseif rpc_type == "data" then --debug_message = string.format("%s[DATA][%s][%s]: ", debug_message, mod_name, rpc_name) debug_message = debug_message .. "[DATA][" .. mod_name .. "][" .. rpc_name .. "]: " if type(data) == "string" then debug_message = debug_message .. data else local success, serialized_data = pcall(serialize_data, unpack(data)) if success then debug_message = debug_message .. serialized_data end end end vmf:info(debug_message) end end -- NETWORK local function rpc_chat_message(member, channel_id, message_sender, message, localization_param, is_system_message, pop_chat, is_dev) if VT1 then RPC.rpc_chat_message(member, channel_id, message_sender, message, localization_param, is_system_message, pop_chat, is_dev) else RPC.rpc_chat_message(member, channel_id, message_sender, 0, message, {localization_param}, false, false, is_system_message, pop_chat, is_dev) end end local function send_rpc_vmf_ping(peer_id) network_debug("ping", "sent", peer_id) rpc_chat_message(peer_id, 3, Network.peer_id(), "", "", false, true, false) end local function send_rpc_vmf_pong(peer_id) network_debug("pong", "sent", peer_id) rpc_chat_message(peer_id, 4, Network.peer_id(), _shared_mods_map, _shared_rpcs_map, false, true, false) end local function send_rpc_vmf_data(peer_id, mod_name, rpc_name, ...) local mod_number, rpc_number = convert_names_to_numbers(peer_id, mod_name, rpc_name) if mod_number then local rpc_info = cjson.encode({mod_number, rpc_number}) local success, data = pcall(serialize_data, ...) if success then network_debug("data", "sent", peer_id, mod_name, rpc_name, data) rpc_chat_message(peer_id, 5, Network.peer_id(), rpc_info, data, false, true, false) end end end local function send_rpc_vmf_data_local(mod_name, rpc_name, ...) local mod = get_mod(mod_name) if mod:is_enabled() then network_debug("data", "local", nil, mod_name, rpc_name, {...}) local error_prefix = "(local rpc) " .. tostring(rpc_name) vmf.safe_call_nr(mod, error_prefix, _rpc_callbacks[mod_name][rpc_name], Network.peer_id(), ...) end end -- #################################################################################################################### -- ##### VMFMod ####################################################################################################### -- #################################################################################################################### VMFMod.network_register = function (self, rpc_name, rpc_function) if _network_module_is_initialized then self:error("(network_register): you can't register new rpc after mod initialization") return end if vmf.check_wrong_argument_type(self, "network_register", "rpc_name", rpc_name, "string") or vmf.check_wrong_argument_type(self, "network_register", "rpc_function", rpc_function, "function") then return end _rpc_callbacks[self:get_name()] = _rpc_callbacks[self:get_name()] or {} _rpc_callbacks[self:get_name()][rpc_name] = rpc_function end -- recipient = "all", "local", "others", peer_id VMFMod.network_send = function (self, rpc_name, recipient, ...) if not is_rpc_registered(self:get_name(), rpc_name) then self:error("(network_send): attempt to send non-registered rpc") return end if recipient == "all" then for peer_id, _ in pairs(_vmf_users) do send_rpc_vmf_data(peer_id, self:get_name(), rpc_name, ...) end send_rpc_vmf_data_local(self:get_name(), rpc_name, ...) elseif recipient == "others" then for peer_id, _ in pairs(_vmf_users) do send_rpc_vmf_data(peer_id, self:get_name(), rpc_name, ...) end elseif recipient == "local" or recipient == Network.peer_id() then send_rpc_vmf_data_local(self:get_name(), rpc_name, ...) else -- recipient == peer_id send_rpc_vmf_data(recipient, self:get_name(), rpc_name, ...) end end -- #################################################################################################################### -- ##### Hooks ######################################################################################################## -- #################################################################################################################### vmf:hook("ChatManager", "rpc_chat_message", function(func, self, sender, channel_id, message_sender, arg1, arg2, arg3, ...) if channel_id == VERMINTIDE_CHANNEL_ID then func(self, sender, channel_id, message_sender, arg1, arg2, arg3, ...) else if not _network_module_is_initialized then return end local rpc_data1, rpc_data2 if VT1 then rpc_data1 = arg1 rpc_data2 = arg2 else rpc_data1 = arg2 rpc_data2 = arg3[1] end if channel_id == RPC_VMF_REQUEST_CHANNEL_ID then -- rpc_vmf_request network_debug("ping", "received", sender) send_rpc_vmf_pong(sender) elseif channel_id == RPC_VMF_RESPONCE_CHANNEL_ID then -- rpc_vmf_responce -- @TODO: maybe I should protect it from sending by the player who's not in the game? network_debug("pong", "received", sender) if _network_debug then vmf:info("[RECEIVED MODS TABLE]: " .. rpc_data1) vmf:info("[RECEIVED RPCS TABLE]: " .. rpc_data2) end pcall(function() local user_rpcs_dictionary = {} user_rpcs_dictionary[1] = cjson.decode(rpc_data1) -- mods user_rpcs_dictionary[2] = cjson.decode(rpc_data2) -- rpcs _vmf_users[sender] = user_rpcs_dictionary vmf:info("Added %s to the VMF users list.", sender) -- event local player = Managers.player:player_from_peer_id(sender) if player then for mod_name, _ in pairs(user_rpcs_dictionary[1]) do local mod = get_mod(mod_name) if mod then vmf.mod_user_joined_the_game(mod, player) end end end end) elseif channel_id == RPC_VMF_UNKNOWN_CHANNEL_ID then local mod_number, rpc_number = unpack(cjson.decode(rpc_data1)) local mod_name, rpc_name = convert_numbers_to_names(mod_number, rpc_number) if mod_name and get_mod(mod_name):is_enabled() then network_debug("data", "received", sender, mod_name, rpc_name, rpc_data2) -- can be error in both callback_function() and deserialize_data() local error_prefix = "(network) " .. tostring(rpc_name) vmf.safe_call_nr( get_mod(mod_name), error_prefix, function() _rpc_callbacks[mod_name][rpc_name](sender, deserialize_data(rpc_data2)) end ) end end end end) vmf:hook(PlayerManager, "add_remote_player", function (func, self, peer_id, player_controlled, ...) if player_controlled then send_rpc_vmf_ping(peer_id) end return func(self, peer_id, player_controlled, ...) end) vmf:hook(PlayerManager, "remove_player", function (func, self, peer_id, ...) if _vmf_users[peer_id] then -- make sure it's not the bot for _, player in pairs(Managers.player:human_players()) do if player.peer_id == peer_id then vmf:info("Removed %s from the VMF users list.", peer_id) -- event for mod_name, _ in pairs(_vmf_users[peer_id][1]) do local mod = get_mod(mod_name) if mod then vmf.mod_user_left_the_game(mod, player) end end _vmf_users[peer_id] = nil break end end end func(self, peer_id, ...) end) -- #################################################################################################################### -- ##### VMF internal functions and variables ######################################################################### -- #################################################################################################################### vmf.create_network_dictionary = function() _shared_mods_map = {} _shared_rpcs_map = {} local i = 0 for mod_name, mod_rpcs in pairs(_rpc_callbacks) do i = i + 1 _shared_mods_map[mod_name] = i _local_mods_map[i] = mod_name _shared_rpcs_map[i] = {} _local_rpcs_map[i] = {} local j = 0 for rpc_name, _ in pairs(mod_rpcs) do j = j + 1 _shared_rpcs_map[i][rpc_name] = j _local_rpcs_map[i][j] = rpc_name end end _shared_mods_map = cjson.encode(_shared_mods_map) _shared_rpcs_map = cjson.encode(_shared_rpcs_map) _network_module_is_initialized = true end vmf.ping_vmf_users = function() if Managers.player then for _, player in pairs(Managers.player:human_players()) do if player.peer_id ~= Network.peer_id() then send_rpc_vmf_ping(player.peer_id) send_rpc_vmf_pong(player.peer_id) end end end end vmf.load_network_settings = function() _network_debug = vmf:get("developer_mode") and vmf:get("show_network_debug_info") end -- #################################################################################################################### -- ##### Script ####################################################################################################### -- #################################################################################################################### vmf.load_network_settings()
-- Common settings for LaTeX2e development repo -- The LaTeX2e kernel is needed by everything except 'base' -- There is an over-ride for that case checkdeps = checkdeps or {maindir .. "/base"} unpackdeps = unpackdeps or {maindir .. "/base"} -- Set up the check system to work in 'stand-alone' mode -- This relies on a format being built by the 'base' dependency asciiengines = asciiengines or {"etex"} checkformat = checkformat or "latex" checkengines = checkengines or {"etex", "xetex", "luatex"} checkruns = checkruns or 2 checksuppfiles = checksuppfiles or {"color.cfg", "graphics.cfg", "test209.tex", "test2e.tex", "xetex.def", "dvips.def"} stdengine = stdengine or "etex" typesetsuppfiles = typesetsuppfiles or {"ltxdoc.cfg", "ltxguide.cfg"} -- Build TDS-style zips packtdszip = true -- Global searching is disabled when unpacking and checking if checksearch == nil then checksearch = false end if unpacksearch == nil then unpacksearch = false end
--[[-- 游戏命令 ]] local cmd = cmd or {} --游戏标识 cmd.KIND_ID = 200 --游戏人数 cmd.PLAYER_COUNT = 3 --非法视图 cmd.INVALID_VIEWID = 0 --左边玩家视图 cmd.LEFT_VIEWID = 1 --自己玩家视图 cmd.MY_VIEWID = 2 --右边玩家视图 cmd.RIGHT_VIEWID = 3 --最大数目 cmd.MAX_COUNT = 20 --全牌数目 cmd.FULL_COUNT = 54 --常规数目 cmd.NORMAL_COUNT = 17 --派发数目 cmd.DISPATCH_COUNT = 51 --游戏状态 cmd.GAME_SCENE_FREE = 0 --等待开始 cmd.GAME_SCENE_CALL = 100 --叫分状态 cmd.GAME_SCENE_PLAY = 101 --游戏进行 cmd.GAME_SCENE_END = 255 --游戏结束 -- 倒计时 cmd.TAG_COUNTDOWN_READY = 1 cmd.TAG_COUNTDOWN_CALLSCORE = 2 cmd.TAG_COUNTDOWN_OUTCARD = 3 -- 游戏倒计时 cmd.COUNTDOWN_READY = 30 -- 准备倒计时 cmd.COUNTDOWN_CALLSCORE = 20 -- 叫分倒计时 cmd.COUNTDOWN_OUTCARD = 20 -- 出牌倒计时 cmd.COUNTDOWN_HANDOUTTIME = 30 -- 首出倒计时 -- 游戏胜利方 cmd.kDefault = -1 cmd.kLanderWin = 0 cmd.kLanderLose = 1 cmd.kFarmerWin = 2 cmd.kFarmerLose = 3 -- 春天标记 cmd.kFlagDefault = 0 cmd.kFlagChunTian = 1 cmd.kFlagFanChunTian = 2 --------------------------------------------------------------------------------------- --服务器命令结构 cmd.SUB_S_GAME_START = 100 --游戏开始 cmd.SUB_S_CALL_SCORE = 101 --用户叫分 cmd.SUB_S_BANKER_INFO = 102 --庄家信息 cmd.SUB_S_OUT_CARD = 103 --用户出牌 cmd.SUB_S_PASS_CARD = 104 --用户放弃 cmd.SUB_S_GAME_CONCLUDE = 105 --游戏结束 ------ --服务端消息结构 ------ --空闲状态 cmd.CMD_S_StatusFree = { --游戏属性 {k = "lCellScore", t = "int"}, --基础积分 --时间信息 {k = "cbTimeOutCard", t = "byte"}, --出牌时间 {k = "cbTimeCallScore", t = "byte"}, --叫分时间 {k = "cbTimeStartGame", t = "byte"}, --开始时间 {k = "cbTimeHeadOutCard", t = "byte"}, --首出时间 --历史积分 {k = "lTurnScore", t = "score", l = {cmd.PLAYER_COUNT}}, --积分信息 {k = "lCollectScore", t = "score", l = {cmd.PLAYER_COUNT}}, --积分信息 } --叫分状态 cmd.CMD_S_StatusCall = { --时间信息 {k = "cbTimeOutCard", t = "byte"}, --出牌时间 {k = "cbTimeCallScore", t = "byte"}, --叫分时间 {k = "cbTimeStartGame", t = "byte"}, --开始时间 {k = "cbTimeHeadOutCard", t = "byte"}, --首出时间 --游戏信息 {k = "lCellScore", t = "int"}, --单元积分 {k = "wCurrentUser", t = "word"}, --当前玩家 {k = "cbBankerScore", t = "byte"}, --庄家叫分 {k = "cbScoreInfo", t = "byte", l = {cmd.PLAYER_COUNT}}, --叫分信息 {k = "cbHandCardData", t = "byte", l = {cmd.NORMAL_COUNT}}, --手上扑克 --历史积分 {k = "lTurnScore", t = "score", l = {cmd.PLAYER_COUNT}}, --积分信息 {k = "lCollectScore", t = "score", l = {cmd.PLAYER_COUNT}}, --积分信息 } --游戏状态 cmd.CMD_S_StatusPlay = { --时间信息 {k = "cbTimeOutCard", t = "byte"}, --出牌时间 {k = "cbTimeCallScore", t = "byte"}, --叫分时间 {k = "cbTimeStartGame", t = "byte"}, --开始时间 {k = "cbTimeHeadOutCard", t = "byte"}, --首出时间 --游戏变量 {k = "lCellScore", t = "int"}, --单元积分 {k = "cbBombCount", t = "byte"}, --炸弹次数 {k = "wBankerUser", t = "word"}, --庄家用户 {k = "wCurrentUser", t = "word"}, --当前庄家 {k = "cbBankerScore", t = "byte"}, --庄家叫分 --出牌信息 {k = "wTurnWiner", t = "word"}, --胜利玩家 {k = "cbTurnCardCount", t = "byte"}, --出牌数目 {k = "cbTurnCardData", t = "byte", l = {cmd.MAX_COUNT}}, --出牌数据 --扑克信息 {k = "cbBankerCard", t = "byte", l = {3}}, --游戏底牌 {k = "cbHandCardData", t = "byte", l = {cmd.MAX_COUNT}}, --手上扑克 {k = "cbHandCardCount", t = "byte", l = {cmd.PLAYER_COUNT}},--扑克数目 --历史积分 {k = "lTurnScore", t = "score", l = {cmd.PLAYER_COUNT}}, --积分信息 {k = "lCollectScore", t = "score", l = {cmd.PLAYER_COUNT}}, --积分信息 } --发送扑克/游戏开始 cmd.CMD_S_GameStart = { {k = "wStartUser", t = "word"}, --开始玩家 {k = "wCurrentUser", t = "word"}, --当前玩家 {k = "cbValidCardData", t = "byte"}, --明牌扑克 {k = "cbValidCardIndex", t = "byte"}, --明牌位置 {k = "cbCardData", t = "byte", l = {cmd.NORMAL_COUNT}}, --扑克列表 } --用户叫分 cmd.CMD_S_CallScore = { {k = "wCurrentUser", t = "word"}, --当前玩家 {k = "wCallScoreUser", t = "word"}, --叫分玩家 {k = "cbCurrentScore", t = "byte"}, --当前叫分 {k = "cbUserCallScore", t = "byte"}, --上次叫分 } --庄家信息 cmd.CMD_S_BankerInfo = { {k = "wBankerUser", t = "word"}, --庄家玩家 {k = "wCurrentUser", t = "word"}, --当前玩家 {k = "cbBankerScore", t = "byte"}, --庄家叫分 {k = "cbBankerCard", t = "byte", l = {3}}, --庄家扑克 } --用户出牌 cmd.CMD_S_OutCard = { {k = "cbCardCount", t = "byte"}, --出牌数目 {k = "wCurrentUser", t = "word"}, --当前玩家 {k = "wOutCardUser", t = "word"}, --出牌玩家 {k = "cbCardData", t = "byte", l = {cmd.MAX_COUNT}}, --扑克列表 } --放弃出牌 cmd.CMD_S_PassCard = { {k = "cbTurnOver", t = "byte"}, --一轮结束 {k = "wCurrentUser", t = "word"}, --当前玩家 {k = "wPassCardUser", t = "word"}, --放弃玩家 } --游戏结束 cmd.CMD_S_GameConclude = { --积分变量 {k = "lCellScore", t = "int"}, --单元积分 {k = "lGameScore", t = "score", l = {3}}, --游戏积分 --春天标识 {k = "bChunTian", t = "byte"}, --春天 {k = "bFanChunTian", t = "byte"}, --反春天 --炸弹信息 {k = "cbBombCount", t = "byte"}, --炸弹个数 {k = "cbEachBombCount", t = "byte", l = {cmd.PLAYER_COUNT}},--炸弹个数 --游戏信息 {k = "cbBankerScore", t = "byte"}, --叫分数目 {k = "cbCardCount", t = "byte", l = {cmd.PLAYER_COUNT}}, --扑克数目 {k = "cbHandCardData", t = "byte", l = {cmd.FULL_COUNT}}, --扑克列表 } --客户端命令结构 cmd.SUB_C_CALL_SCORE = 1 --用户叫分 cmd.SUB_C_OUT_CARD = 2 --用户出牌 cmd.SUB_C_PASS_CARD = 3 --用户放弃 ------ --客户端消息结构 ------ --用户叫分 cmd.CMD_C_CallScore = { {k = "cbCallScore", t = "byte"}, --叫分数目 } --用户出牌 cmd.CMD_C_OutCard = { {k = "cbCardCount", t = "byte"}, --出牌数目 {k = "cbCardData", t = "byte", l = {cmd.MAX_COUNT}}, --扑克数据 } return cmd
local resources = { chest= { {name="coal", tint={r=100,g=100,b=100,a=255}}, {name="stone", tint={r=200,g=200,b=100, a=255}}, {name="iron-ore", tint={r=180,g=190,b=255,a=255}}, {name="copper-ore",tint={r=255,g=160,b=130,a=255}}, {name="uranium-ore",tint={r=130,g=230,b=50, a=255}} }, pipe = { {name="water",tint={r=100,g=100,b=255,a=255}}, {name="crude-oil", tint={r=100,g=100,b=100,a=255}} } } return resources
--- CFrame representation as a quaternion -- @module QFrame local QFrame = {} QFrame.__index = QFrame function QFrame.new(x, y, z, W, X, Y, Z) local self = setmetatable({}, QFrame) self.x = x or 0 self.y = y or 0 self.z = z or 0 self.W = W or 1 self.X = X or 0 self.Y = Y or 0 self.Z = Z or 0 return self end function QFrame.isQFrame(value) return getmetatable(value) == QFrame end function QFrame.fromCFrameClosestTo(cframe, closestTo) assert(typeof(cframe) == "CFrame", "Bad cframe") assert(QFrame.isQFrame(closestTo), "Bad closestTo") local axis, angle = cframe:toAxisAngle() local W = math.cos(angle/2) local X = math.sin(angle/2)*axis.x local Y = math.sin(angle/2)*axis.y local Z = math.sin(angle/2)*axis.z local dot = W*closestTo.W + X*closestTo.X + Y*closestTo.Y + Z*closestTo.Z if dot < 0 then return QFrame.new(cframe.x, cframe.y, cframe.z, -W, -X, -Y, -Z) end return QFrame.new(cframe.x, cframe.y, cframe.z, W, X, Y, Z) end function QFrame.fromVector3(vector, qFrame) assert(typeof(vector) == "Vector3", "Bad vector") assert(QFrame.isQFrame(qFrame)) return QFrame.new(vector.x, vector.y, vector.z, qFrame.W, qFrame.X, qFrame.Y, qFrame.Z) end function QFrame.toCFrame(self) local cframe = CFrame.new(self.x, self.y, self.z, self.X, self.Y, self.Z, self.W) if cframe == cframe then return cframe else return nil end end function QFrame.toPosition(self) return Vector3.new(self.x, self.y, self.z) end function QFrame.isNAN(a) return a.x == a.x and a.y == a.y and a.z == a.z and a.W == a.W and a.X == a.X and a.Y == a.Y and a.Z == a.Z end function QFrame.__unm(a) return QFrame.new(-a.x, -a.y, -a.z, -a.W, -a.X, -a.Y, -a.Z) end function QFrame.__add(a, b) assert(QFrame.isQFrame(a) and QFrame.isQFrame(b), "QFrame + non-QFrame attempted") return QFrame.new(a.x + b.x, a.y + b.y, a.z + b.z, a.W + b.W, a.X + b.X, a.Y + b.Y, a.Z + b.Z) end function QFrame.__sub(a, b) assert(QFrame.isQFrame(a) and QFrame.isQFrame(b), "QFrame - non-QFrame attempted") return QFrame.new(a.x - b.x, a.y - b.y, a.z - b.z, a.W - b.W, a.X - b.X, a.Y - b.Y, a.Z - b.Z) end function QFrame.__pow(a, b) assert(QFrame.isQFrame(a) and type(b) == "number", "Bad a or b") -- Center of mass agnostic power formula -- It will move an object in the same arc regardless of where it's center is -- O*(O^-1*B*O)^t*O^-1 = B^t local ax, ay, az = a.x, a.y, a.z local aW, aX, aY, aZ = a.W, a.X, a.Y, a.Z -- first let's power the quaternion local aMag = math.sqrt(aW*aW + aX*aX + aY*aY + aZ*aZ) local aIm = math.sqrt(aX*aX + aY*aY + aZ*aZ) local cMag = aMag^b if aIm <= 1e-8*aMag then return QFrame.new(b*ax, b*ay, b*az, cMag, 0, 0, 0) end local rx = aX/aIm local ry = aY/aIm local rz = aZ/aIm local cAng = b*math.atan2(aIm, aW) local cCos = math.cos(cAng) local cSin = math.sin(cAng) local cW = cMag*cCos local cX = cMag*cSin*rx local cY = cMag*cSin*ry local cZ = cMag*cSin*rz -- now we power the position local k = ax*rx + ay*ry + az*rz local wx, wy, wz = k*rx, k*ry, k*rz local ux, uy, uz = ax - wx, ay - wy, az - wz local vx, vy, vz = ry*az - rz*ay, rz*ax - rx*az, rx*ay - ry*ax local re = cSin*(aW/aIm*cCos + cSin) local im = cSin*(aW/aIm*cSin - cCos) local cx = re*ux + im*vx + b*wx local cy = re*uy + im*vy + b*wy local cz = re*uz + im*vz + b*wz return QFrame.new(cx, cy, cz, cW, cX, cY, cZ) end function QFrame.__mul(a, b) if type(a) == "number" and QFrame.isQFrame(b) then return QFrame.new(a*b.x, a*b.y, a*b.z, a*b.W, a*b.X, a*b.Y, a*b.Z) elseif QFrame.isQFrame(a) and type(b) == "number" then return QFrame.new(a.x*b, a.y*b, a.z*b, a.W*b, a.X*b, a.Y*b, a.Z*b) elseif QFrame.isQFrame(a) and QFrame.isQFrame(b) then local A2 = a.W*a.W + a.X*a.X + a.Y*a.Y + a.Z*a.Z return QFrame.new( a.x + ((a.W*a.W + a.X*a.X - a.Y*a.Y - a.Z*a.Z)*b.x + 2*(a.X*a.Y - a.W*a.Z)*b.y + 2*(a.W*a.Y + a.X*a.Z)*b.z) /A2, a.y + (2*(a.X*a.Y + a.W*a.Z)*b.x + (a.W*a.W - a.X*a.X + a.Y*a.Y - a.Z*a.Z)*b.y + 2*(a.Y*a.Z - a.W*a.X)*b.z) /A2, a.z + (2*(a.X*a.Z - a.W*a.Y)*b.x + 2*(a.W*a.X + a.Y*a.Z)*b.y + (a.W*a.W - a.X*a.X - a.Y*a.Y + a.Z*a.Z)*b.z) /A2, a.W*b.W - a.X*b.X - a.Y*b.Y - a.Z*b.Z, a.W*b.X + a.X*b.W + a.Y*b.Z - a.Z*b.Y, a.W*b.Y - a.X*b.Z + a.Y*b.W + a.Z*b.X, a.W*b.Z + a.X*b.Y - a.Y*b.X + a.Z*b.W) else error("QFrame * non-QFrame attempted") end end function QFrame.__div(a, b) if type(b) == "number" then return QFrame.new(a.x/b, a.y/b, a.z/b, a.W/b, a.X/b, a.Y/b, a.Z/b) else error("QFrame / non-QFrame attempted") end end function QFrame.__eq(a, b) return a.x == b.x and a.y == b.y and a.z == b.z and a.W == b.W and a.X == b.X and a.Y == b.Y and a.Z == b.Z end return QFrame
building_lib.register_placement({ name = "slope", check = function(mapblock_pos) local mapblock_pos_upper = vector.add(mapblock_pos, {x=0, y=1, z=0}) local lower_building = building_lib.get_building_at_pos(mapblock_pos) local upper_building = building_lib.get_building_at_pos(mapblock_pos_upper) if lower_building or upper_building then return false, "already occupied" end return true end, place = function(mapblock_pos, building_def) local mapblock_pos_upper = vector.add(mapblock_pos, {x=0, y=1, z=0}) local mapblock_data = mapblock_lib.get_mapblock_data(mapblock_pos) local mapgen_info = mapblock_data.mapgen_info local options = building_lib.get_deserialize_options(mapblock_pos, building_def) options.transform = options.transform or {} options.transform.rotate = { axis = "y", angle = 0 } -- TODO: rotate in view direction -- rotate (z+ is default) if mapgen_info.direction == "x+" then options.transform.rotate.angle = 90 elseif mapgen_info.direction == "z-" then options.transform.rotate.angle = 180 elseif mapgen_info.direction == "x-" then options.transform.rotate.angle = 270 end local affected_offsets = { {x=0,y=0,z=0} } mapblock_lib.deserialize(mapblock_pos, building_def.schematics.slope_lower, options) if building_def.schematics.slope_upper then mapblock_lib.deserialize(mapblock_pos_upper, building_def.schematics.slope_upper, options) table.insert(affected_offsets, {x=0,y=1,z=0}) end return affected_offsets, options.transform.rotate.angle end, after_place = function(mapblock_pos) -- update connections local mapblock_pos_upper = vector.add(mapblock_pos, {x=0, y=1, z=0}) building_lib.update_connections(mapblock_pos) building_lib.update_connections(mapblock_pos_upper) end })
local util = require('util') local HexCoord = {} HexCoord.__eq = function(a, b) return a.x == b.x and a.y == b.y and a.z == b.z end HexCoord.__sub = function(a, b) return HexCoord:new(a.x - b.x, a.y - b.y, a.z - b.z) end HexCoord.__tostring = function(self) return "HexCoord(" .. self.x .. ", " .. self.y .. ", " .. self.z .. ")" end local SQRT_3 = math.sqrt(3) function HexCoord:hash() return tostring(self) end function HexCoord:pixelCoordinates(size) local x = size * 1.5 * self.x local y = size * (SQRT_3 / 2 * self.x + SQRT_3 * self.z) return x, y end function HexCoord:new(x, y, z) local coord = {["x"] = x, ["y"] = y, ["z"] = z} if coord.x == -0 then coord.x = 0 end if coord.y == -0 then coord.y = 0 end if coord.z == -0 then coord.z = 0 end setmetatable(coord, self) self.__index = self return coord end function HexCoord:fromPixelCoordinate(pixelX, pixelY, size) local x = (2.0 / 3) * pixelX / size local z = (-1.0 / 3 * pixelX + SQRT_3 / 3.0 * pixelY) / size local y = -x - z local rx = math.floor(x + 0.5) local ry = math.floor(y + 0.5) local rz = math.floor(z + 0.5) local xDiff = math.abs(rx - x) local yDiff = math.abs(ry - y) local zDiff = math.abs(rz - z) if (xDiff > yDiff) and (xDiff > zDiff) then rx = -ry - rz elseif (yDiff > zDiff) then ry = -rx - rz else rz = -rx - ry end return self:new(rx, ry, rz) end function HexCoord:neighbors() return { HexCoord:new(self.x + 1, self.y - 1, self.z), HexCoord:new(self.x + 1, self.y, self.z - 1), HexCoord:new(self.x - 1, self.y + 1, self.z), HexCoord:new(self.x, self.y + 1, self.z - 1), HexCoord:new(self.x - 1, self.y, self.z + 1), HexCoord:new(self.x, self.y - 1, self.z + 1) } end function HexCoord:rotate(degrees, rotationCenter) local dx = self.x - rotationCenter.x local dy = self.y - rotationCenter.y local dz = self.z - rotationCenter.z for rotations=1, util.round(degrees / util.DEG_60) do local oldX = dx dx = -dz dz = -dy dy = -oldX end return HexCoord:new(rotationCenter.x + dx, rotationCenter.y + dy, rotationCenter.z + dz) end return HexCoord
local schema_def = require "kong.plugins.opentelemetry.schema" local validate_plugin_config_schema = require "spec.helpers".validate_plugin_config_schema describe("Plugin: OpenTelemetry (schema)", function() it("rejects invalid attribute keys", function() local ok, err = validate_plugin_config_schema({ endpoint = "http://example.dev", resource_attributes = { [123] = "", }, }, schema_def) assert.is_falsy(ok) assert.same({ config = { resource_attributes = "expected a string" } }, err) end) it("rejects invalid attribute values", function() local ok, err = validate_plugin_config_schema({ endpoint = "http://example.dev", resource_attributes = { foo = "", }, }, schema_def) assert.is_falsy(ok) assert.same({ config = { resource_attributes = "length must be at least 1" } }, err) end) end)
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end local function creatureSayCallback(cid, type, msg) if not npcHandler:isFocused(cid) then return false end local player = Player(cid) if msgcontains(msg, "mission") then if player:getStorageValue(Storage.TheIceIslands.Questline) == 3 then if player:getStorageValue(Storage.TheIceIslands.Mission02) < 1 then npcHandler:say({ "We could indeed need some help. These are very cold times. The ice is growing and becoming thicker everywhere ...", "The problem is that the chakoyas may use the ice for a passage to the west and attack Svargrond ...", "We need you to get a pick and to destroy the ice at certain places to the east. You will quickly recognise those spots by their unstable look ...", "Use the pickaxe on at least three of these places and the chakoyas probably won't be able to pass the ice. Once you are done, return here and report about your mission." }, cid) player:setStorageValue(Storage.TheIceIslands.Mission02, 1) -- Questlog The Ice Islands Quest, Nibelor 1: Breaking the Ice npcHandler.topic[cid] = 0 end elseif player:getStorageValue(Storage.TheIceIslands.Questline) == 4 then npcHandler:say("The spirits are at peace now. The threat of the chakoyas is averted for now. I thank you for your help. Perhaps you should ask Silfind if you can help her in some matters. ", cid) player:setStorageValue(Storage.TheIceIslands.Questline, 5) player:setStorageValue(Storage.TheIceIslands.Mission02, 5) -- Questlog The Ice Islands Quest, Nibelor 1: Breaking the Ice npcHandler.topic[cid] = 0 elseif player:getStorageValue(Storage.TheIceIslands.Questline) == 29 then npcHandler:say({ "There is indeed an important mission. For a long time, the spirits have been worried and have called us for help. It seems that some of our dead have not reached the happy hunting grounds of after life ...", "Everything we were able to find out leads to a place where none of our people is allowed to go. Just like we would never allow a stranger to go to that place ...", "But you, you are different. You are not one of our people, yet you have proven worthy to be one us. You are special, the child of two worlds ...", "We will grant you permission to travel to that isle of Helheim. Our legends say that this is the entrance to the dark world. The dark world is the place where the evil and lost souls roam in eternal torment ...", "There you find for sure the cause for the unrest of the spirits. Find someone in Svargrond who can give you a passage to Helheim and seek for the cause. Are you willing to do that?" }, cid) npcHandler.topic[cid] = 1 elseif player:getStorageValue(Storage.TheIceIslands.Questline) == 31 then npcHandler:say({ "There is no need to report about your mission. To be honest, Ive sent a divination spirit with you as well as a couple of destruction spirits that were unleashed when you approached the altar ...", "Forgive me my secrecy but you are not familiar with the spirits and you might have get frightened. The spirits are at work now, destroying the magic with that those evil creatures have polluted Helheim ...", "I cant thank you enough for what you have done for the spirits of my people. Still I have to ask: Would you do us another favour?" }, cid) npcHandler.topic[cid] = 2 elseif player:getStorageValue(Storage.TheIceIslands.Questline) == 38 then npcHandler:say({ "These are alarming news and we have to act immediately. Take this spirit charm of cold. Travel to the mines and find four special obelisks to mark them with the charm ...", "I can feel their resonance in the spirits world but we cant reach them with our magic yet. They have to get into contact with us in a spiritual way first ...", "This will help us to concentrate all our frost magic on this place. I am sure this will prevent to melt any significant number of demons from the ice ...", "Report about your mission when you are done. Then we can begin with the great ritual of summoning the children of Chyll ...", "I will also inform Lurik about the events. Now go, fast!" }, cid) player:setStorageValue(Storage.TheIceIslands.Questline, 39) player:setStorageValue(Storage.TheIceIslands.Mission11, 2) -- Questlog The Ice Islands Quest, Formorgar Mines 3: The Secret player:setStorageValue(Storage.TheIceIslands.Mission12, 1) -- Questlog The Ice Islands Quest, Formorgar Mines 4: Retaliation player:addItem(7289, 1) npcHandler.topic[cid] = 0 elseif player:getStorageValue(Storage.TheIceIslands.Questline) == 39 and player:getStorageValue(Storage.TheIceIslands.Obelisk01) == 5 and player:getStorageValue(Storage.TheIceIslands.Obelisk02) == 5 and player:getStorageValue(Storage.TheIceIslands.Obelisk03) == 5 and player:getStorageValue(Storage.TheIceIslands.Obelisk04) == 5 then if player:removeItem(7289, 1) then player:setStorageValue(Storage.TheIceIslands.Questline, 40) player:setStorageValue(Storage.TheIceIslands.yakchalDoor, 1) player:setStorageValue(Storage.TheIceIslands.Mission12, 6) -- Questlog The Ice Islands Quest, Formorgar Mines 4: Retaliation player:setStorageValue(Storage.OutfitQuest.NorsemanAddon, 1) -- Questlog Norseman Outfit Quest player:setStorageValue(Storage.OutfitQuest.DefaultStart, 1) --this for default start of Outfit and Addon Quests player:addOutfit(251, 0) player:addOutfit(252, 0) player:getPosition():sendMagicEffect(CONST_ME_MAGIC_BLUE) npcHandler:say({ "Yes, I can feel it! The spirits are in touch with the obelisks. We will begin to channel a spell of ice on the caves. That will prevent the melting of the ice there ...", "If you would like to help us, you can turn in frostheart shards from now on. We use them to fuel our spell with the power of ice. ...", "Oh, and before I forget it - since you have done a lot to help us and spent such a long time in this everlasting winter, I have a special present for you. ...", "Take this outfit to keep your warm during your travels in this frozen realm!" }, cid) end npcHandler.topic[cid] = 0 else npcHandler:say("I have now no mission for you.", cid) npcHandler.topic[cid] = 0 end elseif msgcontains(msg, "shard") then if player:getStorageValue(Storage.TheIceIslands.Questline) == 40 then npcHandler:say("Do you bring frostheart shards for our spell?", cid) npcHandler.topic[cid] = 3 elseif player:getStorageValue(Storage.TheIceIslands.Questline) == 42 then npcHandler:say("Do you bring frostheart shards for our spell? ", cid) npcHandler.topic[cid] = 4 elseif player:getStorageValue(Storage.TheIceIslands.Questline) == 44 then npcHandler:say("Do you want to sell all your shards for 2000 gold coins per each? ", cid) npcHandler.topic[cid] = 5 end elseif msgcontains(msg, "reward") then if player:getStorageValue(Storage.TheIceIslands.Questline) == 41 then npcHandler:say("Take this. It might suit your Nordic outfit fine. ", cid) player:addOutfitAddon(252, 1) player:addOutfitAddon(251, 1) player:getPosition():sendMagicEffect(CONST_ME_MAGIC_BLUE) player:setStorageValue(Storage.TheIceIslands.Questline, 42) player:setStorageValue(Storage.OutfitQuest.NorsemanAddon, 2) -- Questlog Norseman Outfit Quest npcHandler.topic[cid] = 3 elseif player:getStorageValue(Storage.TheIceIslands.Questline) == 43 then player:addOutfitAddon(252, 2) player:addOutfitAddon(251, 2) player:getPosition():sendMagicEffect(CONST_ME_MAGIC_BLUE) npcHandler:say("Take this. It might suit your Nordic outfit fine. From now on we only can give you 2000 gold pieces for each shard. ", cid) player:setStorageValue(Storage.TheIceIslands.Questline, 44) player:setStorageValue(Storage.OutfitQuest.NorsemanAddon, 3) -- Questlog Norseman Outfit Quest npcHandler.topic[cid] = 4 end elseif msgcontains(msg, "tylaf") then if player:getStorageValue(Storage.TheIceIslands.Questline) == 36 then npcHandler:say({ "You encountered the restless ghost of my apprentice Tylaf in the old mines? We must find out what has happened to him. I enable you to talk to his spirit ...", "Talk to him and then report to me about your mission." }, cid) player:setStorageValue(Storage.TheIceIslands.Questline, 37) player:setStorageValue(Storage.TheIceIslands.Mission10, 1) -- Questlog The Ice Islands Quest, Formorgar Mines 2: Ghostwhisperer npcHandler.topic[cid] = 0 end elseif msgcontains(msg, 'cookie') then if player:getStorageValue(Storage.WhatAFoolishQuest.Questline) == 31 and player:getStorageValue(Storage.WhatAFoolishQuest.CookieDelivery.Hjaern) ~= 1 then npcHandler:say('You want to sacrifice a cookie to the spirits?', cid) npcHandler.topic[cid] = 6 end elseif msgcontains(msg, "yes") then if npcHandler.topic[cid] == 1 then npcHandler:say("This is good news. As I explained, travel to Helheim, seek the reason for the unrest there and then report to me about your mission. ", cid) player:setStorageValue(Storage.TheIceIslands.Questline, 30) player:setStorageValue(Storage.TheIceIslands.Mission07, 2) -- Questlog The Ice Islands Quest, The Secret of Helheim npcHandler.topic[cid] = 0 elseif npcHandler.topic[cid] == 2 then npcHandler:say({ "Thank you my friend. The local representative of the explorers society has asked for our help ...", "You know their ways better than my people do and are probably best suited to represent us in this matter.", "Search for Lurik and talk to him about aprobable mission he might have for you." }, cid) player:setStorageValue(Storage.TheIceIslands.Questline, 32) player:setStorageValue(Storage.TheIceIslands.Mission08, 1) -- Questlog The Ice Islands Quest, The Contact npcHandler.topic[cid] = 0 elseif npcHandler.topic[cid] == 3 then if layer:removeItem(7290, 5) then npcHandler:say("Excellent, you collected 5 of them. If you have collected 5 or more, talk to me about your {reward}. ", cid) player:setStorageValue(Storage.TheIceIslands.Questline, 41) npcHandler.topic[cid] = 0 end elseif npcHandler.topic[cid] == 4 then if player:removeItem(7290, 10) then npcHandler:say("Excellent, you collected 10 of them. If you have collected 15 or more, talk to me about your {reward}. ", cid) player:setStorageValue(Storage.TheIceIslands.Questline, 43) npcHandler.topic[cid] = 0 end elseif npcHandler.topic[cid] == 5 then if player:getItemCount(7290) > 0 then local count = player:getItemCount(7290) player:addMoney(count * 2000) player:removeItem(7290, count) npcHandler:say("Here your are. " .. count * 2000 .. " gold coins for " .. count .. " shards.", cid) npcHandler.topic[cid] = 0 end elseif npcHandler.topic[cid] == 6 then if not player:removeItem(8111, 1) then npcHandler:say('You have no cookie that I\'d like.', cid) npcHandler.topic[cid] = 0 return true end player:setStorageValue(Storage.WhatAFoolishQuest.CookieDelivery.Hjaern, 1) if player:getCookiesDelivered() == 10 then player:addAchievement('Allow Cookies?') end Npc():getPosition():sendMagicEffect(CONST_ME_GIFT_WRAPS) npcHandler:say('In the name of the spirits I accept this offer ... UHNGH ... The spirits are not amused!', cid) npcHandler:releaseFocus(cid) npcHandler:resetNpc(cid) end elseif msgcontains(msg, 'no') then if npcHandler.topic[cid] == 6 then npcHandler:say('I see.', cid) npcHandler.topic[cid] = 0 end end return true end npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback) npcHandler:addModule(FocusModule:new())
local PLUGIN_NAME = "sritestplugin" -- helper function to validate data against a schema local validate do local validate_entity = require("spec.helpers").validate_plugin_config_schema local plugin_schema = require("kong.plugins."..PLUGIN_NAME..".schema") function validate(data) return validate_entity(data, plugin_schema) end end describe(PLUGIN_NAME .. ": (schema)", function() it("validates successfully when all the schema fields are supplied correctly", function() local ok, err = validate({ europe_upstream_service = "some-service-1", italy_upstream_service = "some-service-2", italy_header_rules = {"X-Country=Italy"}, }) assert.is_nil(err) assert.is_truthy(ok) end) it("does not accept identical europe_upstream_service and italy_upstream_service", function() local ok, err = validate({ europe_upstream_service = "some-service-1", italy_upstream_service = "some-service-1", italy_header_rules = {"X-Country=Italy"}, }) assert.is_same({ ["config"] = { ["@entity"] = { [1] = "values of these fields must be distinct: 'europe_upstream_service', 'italy_upstream_service'" } } }, err) assert.is_falsy(ok) end) it("does not accept invalid rules for italy_header_rules", function() local ok, err = validate({ europe_upstream_service = "some-service-1", italy_upstream_service = "some-service-2", italy_header_rules = {"X-Country=Usa"}, }) assert.is_same({ ["config"] = { ["italy_header_rules"] = { [1] = "expected one of: X-Country=Italy, X-Regione=Abruzzo" } } }, err) assert.is_falsy(ok) end) it("does not accept empty rules for italy_header_rules", function() local ok, err = validate({ europe_upstream_service = "some-service-1", italy_upstream_service = "some-service-2", }) assert.is_same({ ["config"] = { ["italy_header_rules"] = "required field missing" } }, err) assert.is_falsy(ok) end) end)
--没有完成,暂不实装 return{ zh_CN={ app_title="图萌", title_home1="精选", title_home2="广场", home_drawer_item1="主页", home_drawer_item2="喜欢", home_drawer_item3="往期", home_drawer_item4="投稿", home_drawer_item5="设置", home_drawer_item6="捐赠", home_drawer_item7="关于", string_save="保存", string_download="下载", string_share="分享", string_retry="重试", string_delete="删除", string_loading="加载中", string_wait="请等待", string_ok="确认", string_cancel="取消", string_cancel2="手滑了", string_add_fav="喜欢", string_input_text="输入", string_input="导入", string_output="导出", string_fail_connect="连接服务器失败", string_fail_read_data="读取数据失败", string_fail_write_data="写入数据失败", string_fail_load="加载失败", string_success_connect="连接服务器成功", }, zh_HK={ }, zh_TW={ }, en_US={ }, en_WW={ }, ja_JP={ } }
#!/usr/bin/env lua require "gd" local im = gd.createPalette(90, 90) local white = im:colorAllocate(255, 255, 255) local blue = im:colorAllocate(0, 0, 255) local red = im:colorAllocate(255, 0, 0) im:colorTransparent(white) im:filledRectangle(10, 10, 50, 50, blue) im:filledRectangle(40, 40, 80, 80, red) im:gif("out.gif") os.execute("display out.gif")