content
stringlengths
5
1.05M
function plugindef() finaleplugin.RequireSelection = true finaleplugin.Author = "Nick Mazuk" finaleplugin.Copyright = "CC0 https://creativecommons.org/publicdomain/zero/1.0/" finaleplugin.Version = "1.0.1" finaleplugin.Date = "March 30, 2021" finaleplugin.CategoryTags = "Pitch" finaleplugin.AuthorURL = "https://nickmazuk.com" return "Rotate Chord Down", "Rotate Chord Down", "Rotates the chord upwards, taking the top note and moving it below the rest of the chord" end local path = finale.FCString() path:SetRunningLuaFolderPath() package.path = package.path .. ";" .. path.LuaString .. "?.lua" local transposition = require("library.transposition") local note_entry = require("library.note_entry") function pitch_rotate_chord_up() for entry in eachentrysaved(finenv.Region()) do if (entry.Count >= 2) then local num_octaves = note_entry.calc_spans_number_of_octaves(entry) local top_note = entry:CalcHighestNote(nil) local bottom_note = entry:CalcLowestNote(nil) transposition.change_octave(top_note, -1*math.max(1,num_octaves)) --octave-spanning chords (such as common 4-note piano chords) need some special attention if top_note:IsIdenticalPitch(bottom_note) and (entry.Count > 2) then local new_top_note = entry:CalcHighestNote(nil) top_note.Displacement = new_top_note.Displacement top_note.RaiseLower = new_top_note.RaiseLower transposition.change_octave(top_note, -1*math.max(1,num_octaves)) end end end end pitch_rotate_chord_up()
object_tangible_container_loot_npe_loot_crate_high = object_tangible_container_loot_shared_npe_loot_crate_high:new { } ObjectTemplates:addTemplate(object_tangible_container_loot_npe_loot_crate_high, "object/tangible/container/loot/npe_loot_crate_high.iff")
------------------------------ -- Area: Carpenters Landing -- NM: Mycophile ------------------------------ require("scripts/globals/hunts") ------------------------------ function onMobDeath(mob, player, isKiller) tpz.hunts.checkHunt(mob, player, 166) end
local status, config = pcall(require, "mods/i18n/config/i18nConfig") if not status then eprint("[ERROR][i18n]: Couldn't load config, using default settings") config = { LogLevel = 1, SecondaryLanguages = { "en" } } end local LogLevel = { Error = 1, Warn = 2, Info = 3, Debug = 4 } local logLevelLabel = { "ERROR", "WARN", "INFO", "DEBUG" } local function log(level, msg, ...) if level > config.LogLevel then return end if level == LogLevel.Error then eprint(string.format("[%s][i18n]: "..msg, logLevelLabel[level], ...)) else print(string.format("[%s][i18n]: "..msg, logLevelLabel[level], ...)) end end i18n = {} local L10n = {} -- table that contains all loaded translations local localizedMods = {} -- array of mods that use i18n, where each key is modname local languages = config.SecondaryLanguages -- use first lang code in 'SecondaryLanguages' for server if getCurrentLanguage ~= nil then -- use getCurrentLanguage() result as first lang code for client local lang = getCurrentLanguage() for k, v in ipairs(languages) do if v == lang then table.remove(languages, k) -- remove duplicate lang code break end end table.insert(languages, 1, lang) end local oldInterp -- save old interp local function newInterp(s, tab) if tab or not L10n[s] then return oldInterp(s, tab) end return L10n[s] end -- Register mod and load it's localization function i18n.registerMod(modname, custompath) -- ModName -> mods/ModName/localization if not status then return 1 end log(LogLevel.Debug, "Trying to load translation for mod '%s'", modname) if localizedMods[modname] then -- don't register mod twice return 2 end localizedMods[modname] = true -- try to load translation files local s, translation, path for i = 1, #languages do path = custompath and custompath..languages[i] or "mods/"..modname.."/localization/"..languages[i] s, translation = pcall(require, path) if not s then -- now 'translation' contains the reason why file wasn't loaded log(LogLevel.Info, "Can't load localization files for mod '%s' - %s", modname, translation) else break end end if not s then -- if there is an actual error if not translation or not translation:match("^[^\r\n]+not found:[\r\n]+") then return 3, translation end -- if file wasn't found return 4 end for k, v in pairs(translation) do L10n[k] = v end if oldInterp == nil then -- override interp oldInterp = getmetatable("").__mod getmetatable("").__mod = newInterp end return 0 end -- Get list of all mods that tried or succeeded in calling 'i18n.registerMod' function i18n.getMods() local r = {} for k,_ in pairs(localizedMods) do r[#r+1] = k end return r end
json=require("dkjson") http = require("socket.http") ltn12 = require("ltn12") function removeFromPluginRepresentation() end function updatePluginRepresentation() end function createPalletPointsIfNeeded(objectHandle) local data=readPartInfo(objectHandle) if #data['palletPoints']==0 then data['palletPoints']=simBWF.generatePalletPoints(data) end writePartInfo(objectHandle,data) end function updatePalletPoints(objectHandle) local data=readPartInfo(objectHandle) if data['palletPattern']~=5 then data['palletPoints']={} -- remove them writePartInfo(objectHandle,data) createPalletPointsIfNeeded(objectHandle) end end function getDefaultInfoForNonExistingFields(info) if not info['version'] then info['version']=_MODELVERSION_ end if not info['subtype'] then info['subtype']='repository' end if not info['bitCoded'] then info['bitCoded']=0 -- all free for now end end function readInfo() local data=sim.readCustomDataBlock(model,simBWF.modelTags.OLDPARTREPO) if data then data=sim.unpackTable(data) else data={} end getDefaultInfoForNonExistingFields(data) return data end function writeInfo(data) if data then sim.writeCustomDataBlock(model,simBWF.modelTags.OLDPARTREPO,sim.packTable(data)) else sim.writeCustomDataBlock(model,simBWF.modelTags.OLDPARTREPO,'') end end function readPartInfo(handle) local data=simBWF.readPartInfoV0(handle) -- Additional fields here: -- if not data['palletPoints'] then -- data['palletPoints']={} -- end return data end function writePartInfo(handle,data) return simBWF.writePartInfo(handle,data) end function getPartTable() local l=sim.getObjectsInTree(originalPartHolder,sim.handle_all,1+2) local retL={} for i=1,#l,1 do local data=sim.readCustomDataBlock(l[i],simBWF.modelTags.PART) if data then data=sim.unpackTable(data) retL[#retL+1]={data['name']..' ('..sim.getObjectName(l[i])..')',l[i]} end end return retL end function displayPartProperties() if #parts>0 then local h=parts[partIndex+1][2] local prop=readPartInfo(h) simUI.setEditValue(ui1,5,prop['name'],true) simUI.setEditValue(ui1,6,prop['destination'],true) simUI.setCheckboxValue(ui1,41,simBWF.getCheckboxValFromBool(sim.boolAnd32(prop['bitCoded'],1)~=0),true) simUI.setCheckboxValue(ui1,42,simBWF.getCheckboxValFromBool(sim.boolAnd32(prop['bitCoded'],2)~=0),true) end end function comboboxChange_callback(ui,id,newIndex) partIndex=newIndex displayPartProperties() end function getSpacelessString(str) return string.gsub(str," ","_") end function partName_callback(ui,id,newVal) if #parts>0 then local h=parts[partIndex+1][2] local prop=readPartInfo(h) newVal=getSpacelessString(newVal) if prop['name']~=newVal and #newVal>0 then local allNames=getAllPartNameMap() if allNames[newVal] then sim.msgBox(sim.msgbox_type_warning,sim.msgbox_buttons_ok,'Duplicate naming',"A part named '"..newVal.."' already exists.") else prop['name']=newVal simBWF.markUndoPoint() writePartInfo(h,prop) local partTable=getPartTable() parts,partIndex=simBWF.populateCombobox(ui1,4,partTable,nil,newVal..' ('..sim.getObjectName(h)..')',true,nil) end end displayPartProperties() end end function defaultDestination_callback(ui,id,newVal) if #parts>0 then local h=parts[partIndex+1][2] local prop=readPartInfo(h) newVal=getSpacelessString(newVal) if #newVal>0 then prop['destination']=newVal writePartInfo(h,prop) simBWF.markUndoPoint() end displayPartProperties() end end function updateEnabledDisabledItemsDlg1() if ui1 then local enabled=sim.getSimulationState()==sim.simulation_stopped local config=readInfo() if #parts<=0 then enabled=false end simUI.setEnabled(ui1,4,enabled,true) simUI.setEnabled(ui1,5,enabled,true) simUI.setEnabled(ui1,6,enabled,true) simUI.setEnabled(ui1,41,enabled,true) simUI.setEnabled(ui1,42,enabled,true) simUI.setEnabled(ui1,18,enabled,true) simUI.setEnabled(ui1,53,enabled,true) simUI.setEnabled(ui1,56,enabled,true) end end function invisiblePart_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) c['bitCoded']=sim.boolOr32(c['bitCoded'],1) if newVal==0 then c['bitCoded']=c['bitCoded']-1 end simBWF.markUndoPoint() writePartInfo(h,c) end function invisibleToOtherParts_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) c['bitCoded']=sim.boolOr32(c['bitCoded'],2) if newVal==0 then c['bitCoded']=c['bitCoded']-2 end simBWF.markUndoPoint() writePartInfo(h,c) end function setPalletDlgItemContent() if palletUi then local h=parts[partIndex+1][2] local config=readPartInfo(h) local sel=simBWF.getSelectedEditWidget(palletUi) local pattern=config['palletPattern'] simUI.setRadiobuttonValue(palletUi,101,simBWF.getRadiobuttonValFromBool(pattern==0),true) simUI.setRadiobuttonValue(palletUi,103,simBWF.getRadiobuttonValFromBool(pattern==2),true) simUI.setRadiobuttonValue(palletUi,104,simBWF.getRadiobuttonValFromBool(pattern==3),true) simUI.setRadiobuttonValue(palletUi,105,simBWF.getRadiobuttonValFromBool(pattern==4),true) simUI.setRadiobuttonValue(palletUi,106,simBWF.getRadiobuttonValFromBool(pattern==5),true) local circular=config['circularPatternData3'] local off=circular[1] simUI.setEditValue(palletUi,3004,simBWF.format("%.0f , %.0f , %.0f",off[1]*1000,off[2]*1000,off[3]*1000),true) --offset simUI.setEditValue(palletUi,3000,simBWF.format("%.0f",circular[2]/0.001),true) -- radius simUI.setEditValue(palletUi,3001,simBWF.format("%.0f",circular[3]),true) -- count simUI.setEditValue(palletUi,3002,simBWF.format("%.0f",180*circular[4]/math.pi),true) -- angle off simUI.setCheckboxValue(palletUi,3003,simBWF.getCheckboxValFromBool(circular[5]),true) --center simUI.setEditValue(palletUi,3005,simBWF.format("%.0f",circular[6]),true) -- layers simUI.setEditValue(palletUi,3006,simBWF.format("%.0f",circular[7]/0.001),true) -- layer step local lin=config['linePatternData'] off=lin[1] simUI.setEditValue(palletUi,4000,simBWF.format("%.0f , %.0f , %.0f",off[1]*1000,off[2]*1000,off[3]*1000),true) --offset simUI.setEditValue(palletUi,4001,simBWF.format("%.0f",lin[2]),true) -- rows simUI.setEditValue(palletUi,4002,simBWF.format("%.0f",lin[3]/0.001),true) -- row step simUI.setEditValue(palletUi,4003,simBWF.format("%.0f",lin[4]),true) -- cols simUI.setEditValue(palletUi,4004,simBWF.format("%.0f",lin[5]/0.001),true) -- col step simUI.setEditValue(palletUi,4005,simBWF.format("%.0f",lin[6]),true) -- layers simUI.setEditValue(palletUi,4006,simBWF.format("%.0f",lin[7]/0.001),true) -- layer step local honey=config['honeycombPatternData'] off=honey[1] simUI.setEditValue(palletUi,5000,simBWF.format("%.0f , %.0f , %.0f",off[1]*1000,off[2]*1000,off[3]*1000),true) --offset simUI.setEditValue(palletUi,5001,simBWF.format("%.0f",honey[2]),true) -- rows simUI.setEditValue(palletUi,5002,simBWF.format("%.0f",honey[3]/0.001),true) -- row step simUI.setEditValue(palletUi,5003,simBWF.format("%.0f",honey[4]),true) -- cols simUI.setEditValue(palletUi,5004,simBWF.format("%.0f",honey[5]/0.001),true) -- col step simUI.setEditValue(palletUi,5005,simBWF.format("%.0f",honey[6]),true) -- layers simUI.setEditValue(palletUi,5006,simBWF.format("%.0f",honey[7]/0.001),true) -- layer step simUI.setCheckboxValue(palletUi,5007,simBWF.getCheckboxValFromBool(honey[8]),true) -- firstRowOdd simUI.setEnabled(palletUi,201,(pattern==0),true) simUI.setEnabled(palletUi,203,(pattern==2),true) simUI.setEnabled(palletUi,204,(pattern==3),true) simUI.setEnabled(palletUi,205,(pattern==4),true) simUI.setEnabled(palletUi,206,(pattern==5),true) simBWF.setSelectedEditWidget(palletUi,sel) end end function removePart_callback(ui,id,newVal) local h=parts[partIndex+1][2] local p=sim.getModelProperty(h) if sim.boolAnd32(p,sim.modelproperty_not_model)>0 then sim.removeObject(h) else sim.removeModel(h) end simBWF.markUndoPoint() partIndex=-1 removeDlg1() -- triggers a refresh end function onVisualizeCloseClicked() if visualizeData then local x,y=simUI.getPosition(visualizeData.ui) previousVisualizeDlgPos={x,y} simUI.destroy(visualizeData.ui) sim.removeObject(visualizeData.sensor) sim.removeCollection(visualizeData.collection) visualizeData=nil end end function updateVisualizeImage() if visualizeData then sim.setObjectPosition(visualizeData.sensor,visualizeData.part,{0,0,0}) sim.setObjectOrientation(visualizeData.sensor,-1,{90*math.pi/180,0,0}) local m=sim.getObjectMatrix(visualizeData.sensor,-1) m[4]=m[4]-visualizeData.params[1]*m[3] m[8]=m[8]-visualizeData.params[1]*m[7] m[12]=m[12]-visualizeData.params[1]*m[11] m=sim.rotateAroundAxis(m,{1,0,0},sim.getObjectPosition(visualizeData.part,-1),visualizeData.params[3]) m=sim.rotateAroundAxis(m,{0,0,1},sim.getObjectPosition(visualizeData.part,-1),visualizeData.params[2]) sim.setObjectMatrix(visualizeData.sensor,-1,m) sim.setModelProperty(visualizeData.part,0) sim.handleVisionSensor(visualizeData.sensor) sim.setModelProperty(visualizeData.part,sim.modelproperty_not_visible+sim.modelproperty_not_renderable+sim.modelproperty_not_showasinsidemodel) local img,x,y=sim.getVisionSensorCharImage(visualizeData.sensor) simUI.setImageData(visualizeData.ui,1,img,x,y) end end function onVisualizeZoomInClicked() if visualizeData.params[1]>0.03 then visualizeData.params[1]=visualizeData.params[1]-0.04 end end function onVisualizeZoomOutClicked() if visualizeData.params[1]<1 then visualizeData.params[1]=visualizeData.params[1]+0.04 end end function onVisualizeRotLeftClicked() visualizeData.params[2]=visualizeData.params[2]-0.1745 end function onVisualizeRotRightClicked() visualizeData.params[2]=visualizeData.params[2]+0.1745 end function onVisualizeRotUpClicked() if visualizeData.params[3]<1.3964 then visualizeData.params[3]=visualizeData.params[3]+0.1745 end end function onVisualizeRotDownClicked() if visualizeData.params[3]>0.169 then visualizeData.params[3]=visualizeData.params[3]-0.1745 end end function visualizePart_callback(ui,id,newVal) if not visualizeData then local xml =[[ <image width="512" height="512" id="1"/> <group layout="hbox" flat="true"> <group layout="vbox" flat="true"> <button text="Zoom in" on-click="onVisualizeZoomInClicked" autoRepeat="true" autoRepeatDelay="500" autoRepeatInterval="330"/> <button text="Zoom out" on-click="onVisualizeZoomOutClicked" autoRepeat="true" autoRepeatDelay="500" autoRepeatInterval="330" /> </group> <group layout="hbox" flat="true"> <button text="Rotate left" on-click="onVisualizeRotLeftClicked" autoRepeat="true" autoRepeatDelay="500" autoRepeatInterval="330" /> <button text="Rotate right" on-click="onVisualizeRotRightClicked" autoRepeat="true" autoRepeatDelay="500" autoRepeatInterval="330" /> </group> <group layout="vbox" flat="true"> <button text="Rotate up" on-click="onVisualizeRotUpClicked" autoRepeat="true" autoRepeatDelay="500" autoRepeatInterval="330" /> <button text="Rotate down" on-click="onVisualizeRotDownClicked" autoRepeat="true" autoRepeatDelay="500" autoRepeatInterval="330" /> </group> </group> <button text="OK" on-click="onVisualizeCloseClicked" /> ]] visualizeData={} visualizeData.ui=simBWF.createCustomUi(xml,"Part and pallet visualization",previousVisualizeDlgPos and previousVisualizeDlgPos or 'center',true,'onVisualizeCloseClicked',true--[[,activate,additionalUiAttribute--]]) visualizeData.sensor=sim.createVisionSensor(1+2+128,{512,512,0,0},{0.001,5,60*math.pi/180,0.1,0.1,0.1,0.4,0.5,0.5,0,0}) sim.setObjectInt32Parameter(visualizeData.sensor,sim.objintparam_visibility_layer ,0) local p=sim.boolOr32(sim.getObjectProperty(visualizeData.sensor),sim.objectproperty_dontshowasinsidemodel) sim.setObjectProperty(visualizeData.sensor,p) local part=parts[partIndex+1][2] local info=readPartInfo(part) if sim.boolAnd32(sim.getModelProperty(part),sim.modelproperty_not_model)>0 then part=sim.copyPasteObjects({part},0) part=part[1] sim.setObjectInt32Parameter(part,sim.objintparam_visibility_layer,1) sim.setObjectSpecialProperty(part,sim.objectspecialproperty_renderable+sim.objectspecialproperty_detectable_all) local prop=sim.boolOr32(sim.getObjectProperty(part),sim.objectproperty_dontshowasinsidemodel)-sim.objectproperty_dontshowasinsidemodel sim.setObjectProperty(part,prop) sim.setModelProperty(part,sim.modelproperty_not_visible+sim.modelproperty_not_renderable+sim.modelproperty_not_showasinsidemodel) -- makes it a model else part=sim.copyPasteObjects({part},1) part=part[1] sim.setModelProperty(part,sim.modelproperty_not_visible+sim.modelproperty_not_renderable+sim.modelproperty_not_showasinsidemodel) end visualizeData.part=part visualizeData.collection=sim.createCollection('',0) sim.addObjectToCollection(visualizeData.collection,part,sim.handle_tree,0) sim.setObjectInt32Parameter(visualizeData.sensor,sim.visionintparam_entity_to_render,visualizeData.collection) sim.setObjectParent(visualizeData.part,functionalPartHolder,true) sim.setObjectParent(visualizeData.sensor,visualizeData.part,true) visualizeData.params={0.35,math.pi/4,math.pi/4} if #info['palletPoints']>0 then -- Check the detection point (for the z-position of the pallet): local res,bbMax=sim.getObjectFloatParameter(visualizeData.part,sim.objfloatparam_modelbbox_max_z) sim.setObjectPosition(proxSensor,visualizeData.part,{0,0,bbMax*1.001}) sim.setObjectOrientation(proxSensor,visualizeData.part,{math.pi,0,0}) local shapes=sim.getObjectsInTree(visualizeData.part,sim.object_shape_type,0) local zMin=1 for i=1,#shapes,1 do if sim.boolAnd32(sim.getObjectSpecialProperty(shapes[i]),sim.objectspecialproperty_detectable_all)>0 then local r,dist=sim.checkProximitySensor(proxSensor,shapes[i]) if r>0 and dist<zMin then zMin=dist end end end -- Now the pallet: for i=1,#info['palletPoints'],1 do local plpt=info['palletPoints'][i] local h=sim.createPureShape(0,4+16,{0.01,0.01,0.01},0.1,nil) sim.setShapeColor(h,nil,sim.colorcomponent_ambient_diffuse,{1,0,1}) sim.setObjectSpecialProperty(h,sim.objectspecialproperty_renderable) sim.setObjectPosition(h,visualizeData.part,{plpt['pos'][1],plpt['pos'][2],plpt['pos'][3]+bbMax*1.001-zMin}) sim.setObjectParent(h,visualizeData.part,true) end end updateVisualizeImage() end end function palletCreation_callback(ui,id,newVal) createPalletDlg() end function circularPattern_offsetChange_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) local i=1 local t={0,0,0} for token in (newVal..","):gmatch("([^,]*),") do t[i]=tonumber(token) if t[i]==nil then t[i]=0 end t[i]=t[i]*0.001 if t[i]>0.2 then t[i]=0.2 end if t[i]<-0.2 then t[i]=-0.2 end i=i+1 end c['circularPatternData3'][1]={t[1],t[2],t[3]} simBWF.markUndoPoint() writePartInfo(h,c) setPalletDlgItemContent() end function circularPattern_radiusChange_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) local v=tonumber(newVal) if v then v=v*0.001 if v<0.01 then v=0.01 end if v>0.5 then v=0.5 end if v~=c['circularPatternData3'][2] then simBWF.markUndoPoint() c['circularPatternData3'][2]=v writePartInfo(h,c) end end setPalletDlgItemContent() end function circularPattern_angleOffsetChange_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) local v=tonumber(newVal) if v then if v<-359 then v=-359 end if v>359 then v=359 end v=v*math.pi/180 if v~=c['circularPatternData3'][4] then simBWF.markUndoPoint() c['circularPatternData3'][4]=v writePartInfo(h,c) end end setPalletDlgItemContent() end function circularPattern_countChange_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) local v=tonumber(newVal) if v then v=math.floor(v) if v<2 then v=2 end if v>40 then v=40 end if v~=c['circularPatternData3'][3] then simBWF.markUndoPoint() c['circularPatternData3'][3]=v writePartInfo(h,c) end end setPalletDlgItemContent() end function circularPattern_layersChange_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) local v=tonumber(newVal) if v then v=math.floor(v) if v<1 then v=1 end if v>10 then v=10 end if v~=c['circularPatternData3'][6] then simBWF.markUndoPoint() c['circularPatternData3'][6]=v writePartInfo(h,c) end end setPalletDlgItemContent() end function circularPattern_layerStepChange_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) local v=tonumber(newVal) if v then v=v*0.001 if v<0.01 then v=0.01 end if v>0.2 then v=0.2 end if v~=c['circularPatternData3'][7] then simBWF.markUndoPoint() c['circularPatternData3'][7]=v writePartInfo(h,c) end end setPalletDlgItemContent() end function circularPattern_centerChange_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) c['circularPatternData3'][5]=(newVal~=0) simBWF.markUndoPoint() writePartInfo(h,c) setPalletDlgItemContent() end function linePattern_offsetChange_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) local i=1 local t={0,0,0} for token in (newVal..","):gmatch("([^,]*),") do t[i]=tonumber(token) if t[i]==nil then t[i]=0 end t[i]=t[i]*0.001 if t[i]>0.2 then t[i]=0.2 end if t[i]<-0.2 then t[i]=-0.2 end i=i+1 end c['linePatternData'][1]={t[1],t[2],t[3]} simBWF.markUndoPoint() writePartInfo(h,c) setPalletDlgItemContent() end function linePattern_rowsChange_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) local v=tonumber(newVal) if v then v=math.floor(v) if v<1 then v=1 end if v>10 then v=10 end if v~=c['linePatternData'][2] then simBWF.markUndoPoint() c['linePatternData'][2]=v writePartInfo(h,c) end end setPalletDlgItemContent() end function linePattern_rowStepChange_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) local v=tonumber(newVal) if v then v=v*0.001 if v<0.01 then v=0.01 end if v>0.2 then v=0.2 end if v~=c['linePatternData'][3] then simBWF.markUndoPoint() c['linePatternData'][3]=v writePartInfo(h,c) end end setPalletDlgItemContent() end function linePattern_colsChange_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) local v=tonumber(newVal) if v then v=math.floor(v) if v<1 then v=1 end if v>10 then v=10 end if v~=c['linePatternData'][4] then simBWF.markUndoPoint() c['linePatternData'][4]=v writePartInfo(h,c) end end setPalletDlgItemContent() end function linePattern_colStepChange_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) local v=tonumber(newVal) if v then v=v*0.001 if v<0.01 then v=0.01 end if v>0.2 then v=0.2 end if v~=c['linePatternData'][5] then simBWF.markUndoPoint() c['linePatternData'][5]=v writePartInfo(h,c) end end setPalletDlgItemContent() end function linePattern_layersChange_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) local v=tonumber(newVal) if v then v=math.floor(v) if v<1 then v=1 end if v>10 then v=10 end if v~=c['linePatternData'][6] then simBWF.markUndoPoint() c['linePatternData'][6]=v writePartInfo(h,c) end end setPalletDlgItemContent() end function linePattern_layerStepChange_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) local v=tonumber(newVal) if v then v=v*0.001 if v<0.01 then v=0.01 end if v>0.2 then v=0.2 end if v~=c['linePatternData'][7] then simBWF.markUndoPoint() c['linePatternData'][7]=v writePartInfo(h,c) end end setPalletDlgItemContent() end function honeyPattern_offsetChange_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) local i=1 local t={0,0,0} for token in (newVal..","):gmatch("([^,]*),") do t[i]=tonumber(token) if t[i]==nil then t[i]=0 end t[i]=t[i]*0.001 if t[i]>0.2 then t[i]=0.2 end if t[i]<-0.2 then t[i]=-0.2 end i=i+1 end c['honeycombPatternData'][1]={t[1],t[2],t[3]} simBWF.markUndoPoint() writePartInfo(h,c) setPalletDlgItemContent() end function honeyPattern_rowsChange_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) local v=tonumber(newVal) if v then v=math.floor(v) if v<2 then v=2 end if v>10 then v=10 end if v~=c['honeycombPatternData'][2] then simBWF.markUndoPoint() c['honeycombPatternData'][2]=v writePartInfo(h,c) end end setPalletDlgItemContent() end function honeyPattern_rowStepChange_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) local v=tonumber(newVal) if v then v=v*0.001 if v<0.01 then v=0.01 end if v>0.2 then v=0.2 end if v~=c['honeycombPatternData'][3] then simBWF.markUndoPoint() c['honeycombPatternData'][3]=v writePartInfo(h,c) end end setPalletDlgItemContent() end function honeyPattern_colsChange_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) local v=tonumber(newVal) if v then v=math.floor(v) if v<2 then v=2 end if v>10 then v=10 end if v~=c['honeycombPatternData'][4] then simBWF.markUndoPoint() c['honeycombPatternData'][4]=v writePartInfo(h,c) end end setPalletDlgItemContent() end function honeyPattern_colStepChange_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) local v=tonumber(newVal) if v then v=v*0.001 if v<0.01 then v=0.01 end if v>0.2 then v=0.2 end if v~=c['honeycombPatternData'][5] then simBWF.markUndoPoint() c['honeycombPatternData'][5]=v writePartInfo(h,c) end end setPalletDlgItemContent() end function honeyPattern_layersChange_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) local v=tonumber(newVal) if v then v=math.floor(v) if v<1 then v=1 end if v>10 then v=10 end if v~=c['honeycombPatternData'][6] then simBWF.markUndoPoint() c['honeycombPatternData'][6]=v writePartInfo(h,c) end end setPalletDlgItemContent() end function honeyPattern_layerStepChange_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) local v=tonumber(newVal) if v then v=v*0.001 if v<0.01 then v=0.01 end if v>0.2 then v=0.2 end if v~=c['honeycombPatternData'][7] then simBWF.markUndoPoint() c['honeycombPatternData'][7]=v writePartInfo(h,c) end end setPalletDlgItemContent() end function honeyPattern_rowIsOddChange_callback(ui,id,newVal) local h=parts[partIndex+1][2] local c=readPartInfo(h) c['honeycombPatternData'][8]=(newVal~=0) simBWF.markUndoPoint() writePartInfo(h,c) setPalletDlgItemContent() end function editPatternItems_callback(ui,id,newVal) local h=parts[partIndex+1][2] local prop=readPartInfo(h) local s="600 400" local p="200 200" if customPalletDlgSize then s=customPalletDlgSize[1]..' '..customPalletDlgSize[2] end if customPalletDlgPos then p=customPalletDlgPos[1]..' '..customPalletDlgPos[2] end local xml = [[ <editor title="Pallet points" size="]]..s..[[" position="]]..p..[[" tabWidth="4" textColor="50 50 50" backgroundColor="190 190 190" selectionColor="128 128 255" useVrepKeywords="true" isLua="true"> <keywords1 color="152 0 0" > </keywords1> <keywords2 color="220 80 20" > </keywords2> </editor> ]] local initialText=simBWF.palletPointsToString(prop['palletPoints']) initialText=initialText.."\n\n--[[".."\n\nFormat as in following example:\n\n"..[[ {{pt1X,pt1Y,pt1Z},{pt1Alpha,pt1Beta,pt1Gamma},pt1Layer}, {{pt2X,pt2Y,pt2Z},{pt2Alpha,pt2Beta,pt2Gamma},pt2Layer}]].."\n\n--]]" local modifiedText while true do modifiedText,customPalletDlgSize,customPalletDlgPos=sim.openTextEditor(initialText,xml) local newPalletPoints=simBWF.stringToPalletPoints(modifiedText) if newPalletPoints then if not simBWF.arePalletPointsSame_posOrientAndLayer(newPalletPoints,prop['palletPoints']) then prop['palletPoints']=newPalletPoints writePartInfo(h,prop) simBWF.markUndoPoint() end break else if sim.msgbox_return_yes==sim.msgBox(sim.msgbox_type_warning,sim.msgbox_buttons_yesno,'Input Error',"The input is not formated correctly. Do you wish to discard the changes?") then break end initialText=modifiedText end end end function importPallet_callback(ui,id,newVal) local file=sim.fileDialog(sim.filedlg_type_load,'Loading pallet items','','','pallet items','txt') if file then local newPalletPoints=simBWF.readPalletFromFile(file) if newPalletPoints then local h=parts[partIndex+1][2] local prop=readPartInfo(h) prop['palletPoints']=newPalletPoints writePartInfo(h,prop) simBWF.markUndoPoint() else sim.msgBox(sim.msgbox_type_warning,sim.msgbox_buttons_ok,'File Read Error',"The specified file could not be read.") end end end function patternTypeClick_callback(ui,id) local h=parts[partIndex+1][2] local c=readPartInfo(h) local changed=(c['palletPattern']~=id-101) c['palletPattern']=id-101 -- if c['palletPattern']==5 and changed then -- c['palletPoints']={} -- clear the pallet points when we select 'imported' -- end simBWF.markUndoPoint() writePartInfo(h,c) setPalletDlgItemContent() end function onPalletCloseClicked() if palletUi then local x,y=simUI.getPosition(palletUi) previousPalletDlgPos={x,y} simUI.destroy(palletUi) palletUi=nil local h=parts[partIndex+1][2] updatePalletPoints(h) end end function createPalletDlg() if not palletUi then local xml =[[ <tabs id="77"> <tab title="None"> <radiobutton text="Do not create a pallet" on-click="patternTypeClick_callback" id="101" /> <group layout="form" flat="true" id="201"> </group> <label text="" style="* {margin-left: 380px;}"/> </tab> <tab title="Circular type"> <radiobutton text="Create a pallet with items arranged in a circular pattern" on-click="patternTypeClick_callback" id="103" /> <group layout="form" flat="true" id="203"> <label text="Offset (X, Y, Z, in mm)"/> <edit on-editing-finished="circularPattern_offsetChange_callback" id="3004"/> <label text="Items on circumference"/> <edit on-editing-finished="circularPattern_countChange_callback" id="3001"/> <label text="Angle offset (deg)"/> <edit on-editing-finished="circularPattern_angleOffsetChange_callback" id="3002"/> <label text="Radius (mm)"/> <edit on-editing-finished="circularPattern_radiusChange_callback" id="3000"/> <label text="Center in use"/> <checkbox text="" on-change="circularPattern_centerChange_callback" id="3003" /> <label text="Layers"/> <edit on-editing-finished="circularPattern_layersChange_callback" id="3005"/> <label text="Layer step (mm)"/> <edit on-editing-finished="circularPattern_layerStepChange_callback" id="3006"/> </group> </tab> <tab title="Line type"> <radiobutton text="Create a pallet with items arranged in a rectangular pattern" on-click="patternTypeClick_callback" id="104" /> <group layout="form" flat="true" id="204"> <label text="Offset (X, Y, Z, in mm)"/> <edit on-editing-finished="linePattern_offsetChange_callback" id="4000"/> <label text="Rows"/> <edit on-editing-finished="linePattern_rowsChange_callback" id="4001"/> <label text="Row step (mm)"/> <edit on-editing-finished="linePattern_rowStepChange_callback" id="4002"/> <label text="Columns"/> <edit on-editing-finished="linePattern_colsChange_callback" id="4003"/> <label text="Columns step (mm)"/> <edit on-editing-finished="linePattern_colStepChange_callback" id="4004"/> <label text="Layers"/> <edit on-editing-finished="linePattern_layersChange_callback" id="4005"/> <label text="Layer step (mm)"/> <edit on-editing-finished="linePattern_layerStepChange_callback" id="4006"/> </group> </tab> <tab title="Honeycomb type"> <radiobutton text="Create a pallet with items arranged in a honeycomb pattern" on-click="patternTypeClick_callback" id="105" /> <group layout="form" flat="true" id="205"> <label text="Offset (X, Y, Z, in mm)"/> <edit on-editing-finished="honeyPattern_offsetChange_callback" id="5000"/> <label text="Rows (longest)"/> <edit on-editing-finished="honeyPattern_rowsChange_callback" id="5001"/> <label text="Row step (mm)"/> <edit on-editing-finished="honeyPattern_rowStepChange_callback" id="5002"/> <label text="Columns"/> <edit on-editing-finished="honeyPattern_colsChange_callback" id="5003"/> <label text="Columns step (mm)"/> <edit on-editing-finished="honeyPattern_colStepChange_callback" id="5004"/> <label text="Layers"/> <edit on-editing-finished="honeyPattern_layersChange_callback" id="5005"/> <label text="Layer step (mm)"/> <edit on-editing-finished="honeyPattern_layerStepChange_callback" id="5006"/> <label text="1st row is odd"/> <checkbox text="" on-change="honeyPattern_rowIsOddChange_callback" id="5007" /> </group> </tab> <tab title="Custom/imported"> <radiobutton text="Create a pallet with items arranged in a customized pattern" on-click="patternTypeClick_callback" id="106" /> <group layout="vbox" flat="true" id="206"> <button text="Edit pallet items" on-click="editPatternItems_callback" id="6000"/> <button text="Import pallet items" on-click="importPallet_callback" id="6001"/> <label text="" style="* {margin-left: 380px;}"/> </group> </tab> </tabs> ]] palletUi=simBWF.createCustomUi(xml,"Pallet Creation",'center',true,'onPalletCloseClicked',true--[[,resizable,activate,additionalUiAttribute--]]) setPalletDlgItemContent() local h=parts[partIndex+1][2] local c=readPartInfo(h) local pattern=c['palletPattern'] local pat={} pat[0]=0 pat[2]=1 pat[3]=2 pat[4]=3 pat[5]=4 simUI.setCurrentTab(palletUi,77,pat[pattern],true) end end function createDlg1() if (not ui1) and simBWF.canOpenPropertyDialog() then local xml =[[ <combobox id="4" on-change="comboboxChange_callback"> </combobox> <group layout="form" flat="true"> <label text="Name"/> <edit on-editing-finished="partName_callback" id="5"/> <label text="Default destination"/> <edit on-editing-finished="defaultDestination_callback" id="6"/> <label text="Pallet creation"/> <button text="Adjust" on-click="palletCreation_callback" id="18" /> <label text="Invisible"/> <checkbox text="" on-change="invisiblePart_callback" id="41" /> <label text="Invisible to other parts"/> <checkbox text="" on-change="invisibleToOtherParts_callback" id="42" /> </group> <group layout="hbox" flat="true"> <button text="Visualize part and pallet" on-click="visualizePart_callback" id="56" /> <button text="Remove part" on-click="removePart_callback" id="53" /> </group> ]] ui1=simBWF.createCustomUi(xml,simBWF.getUiTitleNameFromModel(model,_MODELVERSION_,_CODEVERSION_),previousDlg1Pos--[[,closeable,onCloseFunction,modal,resizable,activate,additionalUiAttribute--]]) local previousItemName=nil if parts and #parts>0 and (partIndex>=0) then previousItemName=parts[partIndex+1][1]..' ('..sim.getObjectName(parts[partIndex+1][2])..')' end local partTable=getPartTable() parts,partIndex=simBWF.populateCombobox(ui1,4,partTable,nil,previousItemName,true,nil) displayPartProperties() updateEnabledDisabledItemsDlg1() end end function showDlg1() if not ui1 then createDlg1() end end function removeDlg1() if ui1 then local x,y=simUI.getPosition(ui1) previousDlg1Pos={x,y} simUI.destroy(ui1) ui1=nil end end function getPotentialNewParts() local p=sim.getObjectsInTree(model,sim.handle_all,1+2) local i=1 while i<=#p do if p[i]==functionalPartHolder then table.remove(p,i) else i=i+1 end end return p end function getAllPartNameMap() local allNames={} local parts=sim.getObjectsInTree(originalPartHolder,sim.handle_all,1+2) for i=1,#parts,1 do local info=readPartInfo(parts[i]) local nm=info['name'] allNames[nm]=parts[i] end return allNames end function resolveDuplicateNames() local allNames={} local parts=sim.getObjectsInTree(originalPartHolder,sim.handle_all,1+2) for i=1,#parts,1 do local info=readPartInfo(parts[i]) local nm=info['name'] if nm=='<partName>' then nm=sim.getObjectName(parts[i]) end while allNames[nm] do nm=nm..'_COPY' end allNames[nm]=true info['name']=nm writePartInfo(parts[i],info) end end if (sim_call_type==sim.customizationscriptcall_initialization) then partToEdit=-1 lastT=sim.getSystemTimeInMs(-1) model=sim.getObjectAssociatedWithScript(sim.handle_self) _MODELVERSION_=0 _CODEVERSION_=0 local _info=readInfo() simBWF.checkIfCodeAndModelMatch(model,_CODEVERSION_,_info['version']) writeInfo(_info) originalPartHolder=sim.getObjectHandle('partRepository_modelParts') functionalPartHolder=sim.getObjectHandle('partRepository_functional') proxSensor=sim.getObjectHandle('partRepository_sensor') sim.setScriptAttribute(sim.handle_self,sim.customizationscriptattribute_activeduringsimulation,false) -- Following because of a bug in V-REP V3.3.3 and before: local p=sim.boolOr32(sim.getModelProperty(originalPartHolder),sim.modelproperty_scripts_inactive) if sim.getInt32Parameter(sim.intparam_program_version)>30303 then sim.setModelProperty(originalPartHolder,p) else sim.setModelProperty(originalPartHolder,p-sim.modelproperty_scripts_inactive) end -- Following for backward compatibility: local parts=sim.getObjectsInTree(originalPartHolder,sim.handle_all,1+2) for i=1,#parts,1 do createPalletPointsIfNeeded(parts[i]) end -- Following for backward compatibility: resolveDuplicateNames() sim.setIntegerSignal('__brUndoPointCounter__',0) previousUndoPointCounter=0 undoPointStayedSameCounter=-1 previousPalletDlgPos,algoDlgSize,algoDlgPos,previousDlg1Pos=simBWF.readSessionPersistentObjectData(model,"dlgPosAndSize") -- Allow only one part repository per scene: local objs=sim.getObjectsWithTag(simBWF.modelTags.OLDPARTREPO,true) if #objs>1 then sim.removeModel(model) sim.removeObjectFromSelection(sim.handle_all) objs=sim.getObjectsWithTag(simBWF.modelTags.OLDPARTREPO,true) sim.addObjectToSelection(sim.handle_single,objs[1]) else updatePluginRepresentation() end end showOrHideUi1IfNeeded=function() local s=sim.getObjectSelection() if s and #s>=1 and s[#s]==model then showDlg1() else removeDlg1() end end removeAssociatedCustomizationScriptIfAvailable=function(h) local sh=sim.getCustomizationScriptAssociatedWithObject(h) if sh>0 then sim.removeScript(sh) end end checkPotentialNewParts=function(potentialParts) local retVal=false -- true means update the part list in the dialog (i.e. rebuild the dialog's part combo) local functionType=0 -- 0=question, 1=make parts, 2=make orphans for modC=1,#potentialParts,1 do local h=potentialParts[modC] local data=sim.readCustomDataBlock(h,simBWF.modelTags.PART) if not data then -- This is not yet flagged as part simBWF.markUndoPoint() if functionType==0 then local msg="Detected new children of object '"..sim.getObjectName(model).."'. Objects attached to that object should be repository parts. Do you wish to turn those new objects into repository parts? If you click 'no', then those new objects will be made orphan. If you click 'yes', then those new objects will be adjusted appropriately. Only shapes or models can be turned into repository parts." local ret=sim.msgBox(sim.msgbox_type_question,sim.msgbox_buttons_yesno,'Part Definition',msg) if ret==sim.msgbox_return_yes then functionType=1 else functionType=2 end end if functionType==1 then -- We want to accept it as a part local allNames=getAllPartNameMap() data=readPartInfo(h) local nm=sim.getObjectName(h) while true do if not allNames[nm] then data['name']=nm -- ok, that name doesn't exist yet! break end nm=nm..'_COPY' end writePartInfo(h,data) -- attach the XYZ_FEEDERPART_INFO tag sim.setObjectPosition(h,model,{0,0,0}) -- keep the orientation as it is if sim.boolAnd32(sim.getModelProperty(h),sim.modelproperty_not_model)>0 then -- Shape local p=sim.boolOr32(sim.getObjectProperty(h),sim.objectproperty_dontshowasinsidemodel) sim.setObjectProperty(h,p) else -- Model local p=sim.boolOr32(sim.getModelProperty(h),sim.modelproperty_not_showasinsidemodel) sim.setModelProperty(h,p) end createPalletPointsIfNeeded(h) removeAssociatedCustomizationScriptIfAvailable(h) sim.setObjectParent(h,originalPartHolder,true) retVal=true end if functionType==2 then -- We reject it as a part sim.setObjectParent(h,-1,true) end else -- This is already flagged as part data=readPartInfo(h) local allNames=getAllPartNameMap() local nm=data['name'] while true do if not allNames[nm] then data['name']=nm -- ok, that name doesn't exist yet! break end nm=nm..'_COPY' end writePartInfo(h,data) -- append additional tags that were maybe missing previously -- just in case we are adding an item that was already tagged previously sim.setObjectPosition(h,model,{0,0,0}) -- keep the orientation as it is -- Make the model static, non-respondable, non-collidable, non-measurable, non-visible, etc. if sim.boolAnd32(sim.getModelProperty(h),sim.modelproperty_not_model)>0 then -- Shape local p=sim.boolOr32(sim.getObjectProperty(h),sim.objectproperty_dontshowasinsidemodel) sim.setObjectProperty(h,p) else -- Model local p=sim.boolOr32(sim.getModelProperty(h),sim.modelproperty_not_showasinsidemodel) sim.setModelProperty(h,p) end createPalletPointsIfNeeded(h) removeAssociatedCustomizationScriptIfAvailable(h) sim.setObjectParent(h,originalPartHolder,true) retVal=true end end return retVal end if (sim_call_type==sim.customizationscriptcall_nonsimulation) then showOrHideUi1IfNeeded() updateVisualizeImage() -- Following is the central part where we set undo points: --------------------------------- local cnt=sim.getIntegerSignal('__brUndoPointCounter__') if cnt~=previousUndoPointCounter then undoPointStayedSameCounter=8 previousUndoPointCounter=cnt end if undoPointStayedSameCounter>0 then undoPointStayedSameCounter=undoPointStayedSameCounter-1 else if undoPointStayedSameCounter==0 then sim.announceSceneContentChange() -- to have an undo point undoPointStayedSameCounter=-1 end end --------------------------------- if sim.getSystemTimeInMs(lastT)>3000 then lastT=sim.getSystemTimeInMs(-1) local potentialNewParts=getPotentialNewParts() if #potentialNewParts>0 then if checkPotentialNewParts(potentialNewParts) then removeDlg1() -- we need to update the dialog with the new parts end end end pricingRequest_executeIfNeeded() end if (sim_call_type==sim.customizationscriptcall_firstaftersimulation) then sim.setObjectInt32Parameter(model,sim.objintparam_visibility_layer,1) end if (sim_call_type==sim.customizationscriptcall_lastbeforesimulation) then sim.setObjectInt32Parameter(model,sim.objintparam_visibility_layer,0) removeDlg1() end if (sim_call_type==sim.customizationscriptcall_lastbeforeinstanceswitch) then removeDlg1() removeFromPluginRepresentation() end if (sim_call_type==sim.customizationscriptcall_firstafterinstanceswitch) then updatePluginRepresentation() end function sendPricingRequest(payload) local path = "http://service.blueworkforce.com/public_html/generate/report" local response_body = { } http.TIMEOUT=5 -- default is 60 local res, code, response_headers, response_status_line = http.request { url = path, method = "POST", headers = { ["Content-Type"] = "application/json", ["Content-Length"] = payload:len() }, source = ltn12.source.string(payload), sink = ltn12.sink.table(response_body) } return res,code,response_status_line,table.concat(response_body) end function pricingRequest_executeIfNeeded() if pricingRequest then if pricingRequest.counter>0 then pricingRequest.counter=pricingRequest.counter-1 else local res,code,response_status_line,data=sendPricingRequest(pricingRequest.payload) -- sim.auxiliaryConsoleClose(pricingRequest.requestAuxConsole) if res and code==200 then local aux=sim.auxiliaryConsoleOpen('Pricing reply',500,4,{600,100},{800,800},nil,{0.95,1,0.95}) sim.auxiliaryConsolePrint(aux,data) else -- code contains the error msg if res is nil. Otherwise, it contains a status code local msg="Failed to retrieve the pricing information.\n" if not res then msg=msg.."Status code is: "..code else msg=msg.."Error message is: "..res end sim.msgBox(sim.msgbox_type_warning,sim.msgbox_buttons_ok,"Pricing inquiry",msg) end simUI.destroy(pricingRequest.ui) pricingRequest=nil end end end function pricing_callback() if not pricingRequest then local objects={} local tags={simBWF.modelTags.RAGNAR,simBWF.modelTags.RAGNARGRIPPER,simBWF.modelTags.OLDLOCATION,simBWF.modelTags.TRACKINGWINDOW,"XYZ_STATICPICKWINDOW_INFO","XYZ_DETECTIONWINDOW_INFO",simBWF.modelTags.CONVEYOR} for i=1,#tags,1 do local obj=sim.getObjectsWithTag(tags[i],true) for j=1,#obj,1 do local ob=sim.callScriptFunction('ext_getItemData_pricing@'..sim.getObjectName(obj[j]),sim.scripttype_customizationscript) objects[#objects+1]=ob end end pricingRequest={} pricingRequest.payload=json.encode(objects,{indent=true}) --[=[ -- Testing: pricingRequest.payload = [[ { "version":1, "robot":"Ragnar", "gripper":"fcm", "frame":"experimental", "exterior":"wd", "motors":"standard", "primary_arms":"250", "secondary_arms":"500", "software":"load sharing" } ]] --]=] pricingRequest.requestAuxConsole=sim.auxiliaryConsoleOpen('Pricing request',500,4,{100,100},{800,800},nil,{1,0.95,0.95}) sim.auxiliaryConsolePrint(pricingRequest.requestAuxConsole,pricingRequest.payload) local xml =[[ <label text="Please wait a few seconds..." style="* {qproperty-alignment: AlignCenter; min-width: 300px; min-height: 100px;}"/> ]] pricingRequest.ui=simBWF.createCustomUi(xml,'Pricing request','center',false,nil,true,false,false) pricingRequest.counter=3 end end if (sim_call_type==sim.customizationscriptcall_br+2) then pricing_callback() end if (sim_call_type==sim.customizationscriptcall_cleanup) then removeDlg1() removeFromPluginRepresentation() if sim.isHandleValid(model)==1 then -- The associated model might already have been destroyed simBWF.writeSessionPersistentObjectData(model,"dlgPosAndSize",previousPalletDlgPos,algoDlgSize,algoDlgPos,previousDlg1Pos) end end
local wibox = require("wibox") local beautiful = require("beautiful") local clock = {} function clock:init(config) clock.widget = wibox.widget { wibox.widget { format = "<span font='Alarm Clock 14'>%H:%M</span>", widget = wibox.widget.textclock, forced_height = config.height }, bg = config.bg, fg = "#000000", widget = wibox.container.background } end return clock
function HeapInit(pc) pc.HeapMemory = {} pc.HeapStackTop = 0 pc.StackFrame = 0 pc.TopStackFrameId = 0 end function HeapCleanup(pc) pc.HeapMemory = nil collectgarbage() end function HeapAllocStack(pc) local NewTop = pc.HeapStackTop + 1 local NewMem = { StackId = NewTop } pc.HeapMemory[NewTop] = NewMem pc.HeapStackTop = NewTop return NewMem end function HeapUnpopStack(pc) local NewTop = pc.HeapStackTop + 1 if pc.HeapMemory[NewTop] ~= nil then pc.HeapStackTop = NewTop end end -- Pop stack without actually removing the item -- Just move the top pointer function HeapPopStack(pc, n, ExpectedAddress) if n > pc.HeapStackTop then return false end --[[ if ExpectedAddress then assert(pc.HeapStackTop - n == ExpectedAddress, string.format("HeapPopStack assertion failed: Stack location expected at %d, but got %d", ExpectedAddress, pc.HeapStackTop - n)) end --]] pc.HeapStackTop = pc.HeapStackTop - n return true end function HeapPushStackFrame(pc) local NewTop = pc.HeapStackTop + 1 local NewMem = { StackId = NewTop, PreviousFrameLoc = pc.StackFrame } pc.HeapMemory[NewTop] = NewMem pc.StackFrame = pc.HeapStackTop + 1 pc.HeapStackTop = NewTop end function HeapPopStackFrame(pc) local StackFrameItem = pc.HeapMemory[pc.StackFrame] if StackFrameItem ~= nil then local PreviousFrameLoc = StackFrameItem.PreviousFrameLoc if PreviousFrameLoc ~= nil then pc.HeapStackTop = pc.StackFrame - 1 pc.StackFrame = PreviousFrameLoc return true else return false end else return false end end function HeapGetStackNode(pc, n) return pc.HeapMemory[n] end
local awful = require('awful') local gears = require('gears') require('awful.autofocus') local modkey = require('configuration.keys.mod').modKey local altkey = require('configuration.keys.mod').altKey local dpi = require('beautiful').xresources.apply_dpi local xrandr = require('module.xrandr') local clientKeys = awful.util.table.join( -- toggle fullscreen awful.key( {modkey}, 'f', function(c) -- Toggle fullscreen c.fullscreen = not c.fullscreen c:raise() end, {description = 'toggle fullscreen', group = 'client'} ), -- close client awful.key( {modkey}, 'q', function(c) c:kill() end, {description = 'close', group = 'client'} ), -- Default client focus awful.key( {modkey}, 'd', function() awful.client.focus.byidx(1) end, {description = 'focus next by index', group = 'client'} ), awful.key( {modkey}, 'a', function() awful.client.focus.byidx(-1) end, {description = 'focus previous by index', group = 'client'} ), awful.key( { modkey, "Shift" }, "d", function () awful.client.swap.byidx(1) end, {description = "swap with next client by index", group = "client"} ), awful.key( { modkey, "Shift" }, "a", function () awful.client.swap.byidx(-1) end, {description = "swap with next client by index", group = "client"} ), awful.key( {modkey}, 'u', awful.client.urgent.jumpto, {description = 'jump to urgent client', group = 'client'} ), awful.key( {modkey}, 'Tab', function() awful.client.focus.history.previous() if client.focus then client.focus:raise() end end, {description = 'go back', group = 'client'} ), awful.key( {modkey, 'Control'}, 'n', function() local c = awful.client.restore() -- Focus restored client if c then client.focus = c c:raise() end end, {description = 'restore minimized', group = 'client'} ), -- move floating client to center awful.key( { modkey, "Shift" }, "c", function(c) local focused = awful.screen.focused() awful.placement.centered(c, { honor_workarea = true }) end, {description = 'align a client to the center of the focused screen.', group = "client"} ), -- toggle client floating mode awful.key( {modkey}, 'c', function(c) c.fullscreen = false c.maximized = false c.floating = not c.floating c:raise() end, {description = 'toggle floating', group = 'client'} ), -- move client position awful.key( {modkey}, 'Up', function(c) if c.floating then c:relative_move(0, dpi(-10), 0, 0) end end, {description = 'move floating client up by 10 px', group = 'client'} ), awful.key( {modkey}, 'Down', function(c) if c.floating then c:relative_move(0, dpi(10), 0, 0) end end, {description = 'move floating client down by 10 px', group = 'client'} ), awful.key( {modkey}, 'Left', function(c) if c.floating then c:relative_move(dpi(-10), 0, 0, 0) end end, {description = 'move floating client to the left by 10 px', group = 'client'} ), awful.key( {modkey}, 'Right', function(c) if c.floating then c:relative_move(dpi(10), 0, 0, 0) end end, {description = 'move floating client to the right by 10 px', group = 'client'} ), -- Increasing floating client size awful.key( {modkey, 'Shift'}, 'Up', function(c) if c.floating then c:relative_move(0, dpi(-10), 0, dpi(10)) end end, {description = 'increase floating client size vertically by 10 px up', group = 'client'} ), awful.key( {modkey, 'Shift'}, 'Down', function(c) if c.floating then c:relative_move(0, 0, 0, dpi(10)) end end, {description = 'increase floating client size vertically by 10 px down', group = 'client'} ), awful.key( {modkey, 'Shift'}, 'Left', function(c) if c.floating then c:relative_move(dpi(-10), 0, dpi(10), 0) end end, {description = 'increase floating client size horizontally by 10 px left', group = 'client'} ), awful.key( {modkey, 'Shift'}, 'Right', function(c) if c.floating then c:relative_move(0, 0, dpi(10), 0) end end, {description = 'increase floating client size horizontally by 10 px right', group = 'client'} ), -- Decreasing floating client size awful.key( {modkey, 'Control'}, 'Up', function(c) if c.floating and c.height > 10 then c:relative_move(0, 0, 0, dpi(-10)) end end, {description = 'decrease floating client size vertically by 10 px up', group = 'client'} ), awful.key( {modkey, 'Control'}, 'Down', function(c) if c.floating and c.height > 10 then c:relative_move(0, dpi(10), 0, dpi(-10)) end end, {description = 'decrease floating client size vertically by 10 px down', group = 'client'} ), awful.key( {modkey, 'Control'}, 'Left', function(c) if c.floating and c.width > 10 then c:relative_move(0, 0, dpi(-10), 0) end end, {description = 'decrease floating client size horizontally by 10 px left', group = 'client'} ), awful.key( {modkey, 'Control'}, 'Right', function(c) if c.floating and c.width > 10 then c:relative_move(dpi(10), 0 , dpi(-10), 0) end end, {description = 'decrease floating client size horizontally by 10 px right', group = 'client'} ), awful.key( {modkey, 'Control', 'Shift'}, 'Up', function(c) c:move_to_screen(c.screen.index+1) end, {description = 'Move active window to next screen'} ), awful.key( {modkey, 'Control', 'Shift'}, 'Down', function(c) c:move_to_screen(c.screen.index-1) end, {description = 'Move active window to previous screen'} ), awful.key( {modkey, 'Control'}, 'Return', function() xrandr.xrandr() end, {description = 'Change monitor layout'} ) ) return clientKeys
local Players = game:GetService("Players") local CorePackages = game:GetService("CorePackages") local InGameMenuDependencies = require(CorePackages.InGameMenuDependencies) local Roact = InGameMenuDependencies.Roact local t = InGameMenuDependencies.t local InGameMenu = script.Parent.Parent local PageNavigationWatcher = require(InGameMenu.Components.PageNavigationWatcher) local Page = require(InGameMenu.Components.Page) local ReportList = require(script.ReportList) local function getReportablePlayers() local players = {} for _, player in ipairs(Players:GetPlayers()) do if player ~= Players.LocalPlayer then table.insert(players, { Id = player.UserId, Username = player.Name, }) end end return players end local ReportPage = Roact.PureComponent:extend("ReportPage") ReportPage.validateProps = t.strictInterface({ pageTitle = t.string, }) function ReportPage:init() self:setState({ players = getReportablePlayers(), }) end function ReportPage:render() return Roact.createElement(Page, { pageTitle = self.props.pageTitle, }, { PlayerList = Roact.createElement(ReportList, { players = self.state.players, }), Watcher = Roact.createElement(PageNavigationWatcher, { desiredPage = "Report", onNavigateTo = function() self:setState({ players = getReportablePlayers(), }) end, }) }) end return ReportPage
---===================================== ---luastg user global value ---===================================== local LOG_MODULE_NAME="[lstg][debug]" local SCALE=1 local REFRESH_INTERVAL=1 ---@class lstg.debug lstg.debug={} ---------------------------------------- ---几大函数执行时间计时 ---高精度计时器接口 lstg.debug.usTimer=lstg.StopWatch() local startT={} local endT={} local useT={} local aimtype={"objframe","usersystem","boundcheck","collicheck","updateXY","afterframe","objrender","all"} local function resetT() for _,v in pairs(aimtype) do startT[v]=0 endT[v]=0 useT[v]=0 end alluseT=0 end resetT() function lstg.debug.FuncTimeStart(k) startT[k]=lstg.debug.usTimer:GetElapsed() end function lstg.debug.FuncTimeEnd(k) endT[k]=lstg.debug.usTimer:GetElapsed() useT[k]=useT[k]+(endT[k]-startT[k]) end function lstg.debug.GetFuncTimeUse(k) return useT[k] end ---------------------------------------- ---debug lib lstg.debug.timer=0 function lstg.debug.ResetTimer() lstg.debug.usTimer:Reset() if lstg.debug.timer%REFRESH_INTERVAL==0 then resetT() end lstg.debug.timer=lstg.debug.timer+1 lstg.debug.FuncTimeStart("all") end function lstg.debug.RenderInfo() lstg.debug.FuncTimeEnd("all") SetViewMode("ui") SetImageState("white","",Color(128,0,0,0)) SetFontState("menu","",Color(0xFFFFFFFF)) --函数执行时间 RenderRect("white",0,SCALE*128,screen.height-128*SCALE,screen.height) RenderText("menu",'info:\ ObjectFrame\ UserSystemOp...\ BoundCheck\ CollisionCheck\ UpdateXY\ AfterFrame\ ObjectRender\ PerFrame\ ', 4*SCALE,screen.height-4*SCALE,SCALE*0.1125,"left","top") RenderText("menu", string.format('0.000 ms\ %.3f ms\ %.3f ms\ %.3f ms\ %.3f ms\ %.3f ms\ %.3f ms\ %.3f ms\ %.3f ms\ ', useT["objframe"]*1000/REFRESH_INTERVAL, useT["usersystem"]*1000/REFRESH_INTERVAL, useT["boundcheck"]*1000/REFRESH_INTERVAL, useT["collicheck"]*1000/REFRESH_INTERVAL, useT["updateXY"]*1000/REFRESH_INTERVAL, useT["afterframe"]*1000/REFRESH_INTERVAL, useT["objrender"]*1000/REFRESH_INTERVAL, useT["all"]*1000/REFRESH_INTERVAL ), 124*SCALE,screen.height-4*SCALE,SCALE*0.1125,"right","top") SetViewMode("world") end
resource_manifest_version "44febabe-d386-4d18-afbe-5e627f4af937" this_is_a_map "yes" data_file('DLC_ITYP_REQUEST')('stream/prison_props.ytyp')
local rpc = require 'rpc' --- @param lsp LSP --- @return boolean return function (lsp) if #lsp.workspaces > 0 then for _, ws in ipairs(lsp.workspaces) do -- 请求工作目录 local uri = ws.uri -- 请求配置 rpc:request('workspace/configuration', { items = { { scopeUri = uri, section = 'Lua', }, { scopeUri = uri, section = 'files.associations', }, { scopeUri = uri, section = 'files.exclude', } }, }, function (configs) lsp:onUpdateConfig(configs[1], { associations = configs[2], exclude = configs[3], }) end) end else -- 请求配置 rpc:request('workspace/configuration', { items = { { section = 'Lua', }, { section = 'files.associations', }, { section = 'files.exclude', } }, }, function (configs) lsp:onUpdateConfig(configs[1], { associations = configs[2], exclude = configs[3], }) end) end rpc:request('client/registerCapability', { registrations = { -- 监视文件变化 { id = '0', method = 'workspace/didChangeWatchedFiles', registerOptions = { watchers = { { globPattern = '**/', kind = 1 | 2 | 4, } }, }, }, -- 配置变化 { id = '1', method = 'workspace/didChangeConfiguration', } } }, function () log.debug('client/registerCapability Success!') end) return true end
--- A bouncy box "DVD" screen saver demo -- -- @author Calle Englund &lt;git@notcalle.xyz&gt; -- @copyright &copy; 2020 Calle Englund -- @license -- The MIT License (MIT) -- -- 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. -- Seed the random generator for less predictable randomness math.randomseed(os.time()) -- Configure the game window at 1280x720, for HD Ready displays only local window = am.window{ width = 1280, height = 720, title = "Bouncy Box" } -- Pick a random binary direction local function direction() if math.random() > 0.5 then return 1 else return -1 end end -- Change color of a node to a new random color local function randomcolor(node) local new_color = math.randvec3() while node.color.rgb == new_color do new_color = math.randvec3() end node.color = vec4(new_color, 1.0) end -- Bounce the thing along the X axis local dx = direction() local function bounce_x(node) node.x1 = node.x1 + dx node.x2 = node.x2 + dx if node.x1 <= window.left or node.x2 >= window.right then dx = -dx randomcolor(node) end end -- Bounce the thing along the Y axis local dy = direction() local function bounce_y(node) node.y1 = node.y1 + dy node.y2 = node.y2 + dy if node.y1 <= window.bottom or node.y2 >= window.top then dy = -dy randomcolor(node) end end -- Toggle the paused state of our 'box' node when the player presses space local function pause(node) if window:key_pressed'space' then node'box'.paused = not node'box'.paused end end -- Attach scene graph to window window.scene = am.group{ -- The player character sprite, with a name tag, so that scene wide actions -- can find it amongst all the nodes in the graph. am.rect(-25, -25, 25, 25) :tag'box' :action(am.parallel{ bounce_x, bounce_y }) } :action(pause)
-- Clear script environment --[====[ devel/clear-script-env ====================== Clears the environment of the specified lua script(s). ]====] local args = {...} if #args < 1 then qerror("script name(s) required") end for _, name in pairs(args) do local file = dfhack.findScript(name) if file then local script = dfhack.internal.scripts[file] if script then --luacheck: skip local env = script.env while next(env) do env[next(env)] = nil end else dfhack.printerr("Script not loaded: " .. name) end else dfhack.printerr("Can't find script: " .. name) end end
--[[ TheNexusAvenger Class for a King Of The Hill round. --]] local ReplicatedStorage = game:GetService("ReplicatedStorage") local NexusReplication = require(ReplicatedStorage:WaitForChild("External"):WaitForChild("NexusReplication")) local KingOfTheHill = require(ReplicatedStorage:WaitForChild("Round"):WaitForChild("BaseRound")):Extend() KingOfTheHill:SetClassName("KingOfTheHill") NexusReplication:RegisterType("KingOfTheHill",KingOfTheHill) --[[ Creates the round object. --]] function KingOfTheHill:__new() self:InitializeSuper() self.Name = "KingOfTheHill" --Add the time stat. table.insert(self.RoundStats,1,{ Name = "Time", ValueType = "IntValue", DefaultValue = 0, ShowInLeaderstats = true, Prefer = "Higher", }) end --[[ Starts the round. --]] function KingOfTheHill:RoundStarted() --Set the starter inventories of the players. for _,Player in pairs(self.Players:GetAll()) do self:SetStarterTools(Player,{"Sword","Superball","Slingshot","Bomb","RocketLauncher","Reflector"}) end --Spawn the players. for _,Player in pairs(self.Players:GetAll()) do self:SetSpawningEnabled(Player,true) self:SpawnPlayer(Player) end --Update the King Of The Hill times until the round ends. local TimeTotals = {} local KingPart = self.Map:WaitForChild("KingPart") local KingPartCenter,KingPartSizeHalf = KingPart.Position,KingPart.Size/2 local MinX,MaxX = KingPartCenter.X - KingPartSizeHalf.X,KingPartCenter.X + KingPartSizeHalf.X local MinY,MaxY = KingPartCenter.Y - KingPartSizeHalf.Y,KingPartCenter.Y + KingPartSizeHalf.Y local MinZ,MaxZ = KingPartCenter.Z - KingPartSizeHalf.Z,KingPartCenter.Z + KingPartSizeHalf.Z while self.Timer.State ~= "COMPLETE" do --Wait and get the time that passed. local DeltaTime = wait() --Get the players in the zone. local PlayersInZone = {} for _,Player in pairs(self.Players:GetAll()) do local Character = Player.Character if Player.Character then local Humanoid = Character:FindFirstChild("Humanoid") local HumanoidRootPart = Character:FindFirstChild("HumanoidRootPart") if Humanoid and Humanoid.Health > 0 and HumanoidRootPart then local PlayerPosition = HumanoidRootPart.Position if PlayerPosition.X >= MinX and PlayerPosition.X <= MaxX and PlayerPosition.Y >= MinY and PlayerPosition.Y <= MaxY and PlayerPosition.Z >= MinZ and PlayerPosition.Z <= MaxZ then table.insert(PlayersInZone,Player) end end end end --Add the time to the player if ther eis one. if #PlayersInZone == 1 then local KingOfTheHillPlayer = PlayersInZone[1] --Add the time to the player. if not TimeTotals[KingOfTheHillPlayer] then TimeTotals[KingOfTheHillPlayer] = 0 end TimeTotals[KingOfTheHillPlayer] = TimeTotals[KingOfTheHillPlayer] + DeltaTime --Mirror the time to the temporary stat. local Stats = self:GetService("StatService"):GetTemporaryStats(KingOfTheHillPlayer) if Stats then Stats:Get("Time"):Set(TimeTotals[KingOfTheHillPlayer]) end end end --End the round. self:End() end return KingOfTheHill
local patch_id = "CONVO_OVERRIDE_HELPER" if rawget(_G, patch_id) then return end rawset(_G, patch_id, true) print("Loaded patch:"..patch_id) -- Get an existing state of the convo function Convo:GetState(id) self.default_state = self.states[id] return self end -- Clear all functions under this convo function Convo:ClearFn() assert(self.default_state, "NO STATE PUSHED") self.default_state.fns = {} return self end
-- Preprocessor definitions that carryover from lua54.lua defines { "GRIT_POWER_BLOB", -- Enable 'raw string' usage --[[ Experimental Intrinsics See: citizen-server-impl/include/state/ServerGameState.h --]] 'GLM_FORCE_DEFAULT_ALIGNED_GENTYPES', 'GLM_FORCE_SSE2', --'GLM_FORCE_SSE3', } if os.istarget('windows') and not _OPTIONS['with-asan'] then flags { "LinkTimeOptimization" } buildoptions '/Zc:threadSafeInit- /EHa /fp:fast' end if not os.isfile('./src/Component.cpp') then term.pushColor(term.errorColor) print('ERROR: Could not find citizen-scripting-lua54/src/Component.cpp. If building on Windows, did you have Git `core.symlinks` enabled?') term.popColor() os.exit(1) end
--[[ ************************************************************* * This script is developed by Scouser, it uses modules * created by other developers but I have made minor / subtle * changes to get the effects I required. * Feel free to distribute and modify code, * but keep reference to its creator ************************************************************** ]]-- slider = Core.class(Sprite) --local imgBase = getImgBase() --local barTexture = Texture.new("./sliderbar.png") --local pillTexture = Texture.new("./sliderpill.png") local imgBase = "resources/images/" local barTexture = Texture.new(imgBase.."sliderbar.png") local pillTexture = Texture.new(imgBase.."sliderpill.png") --local font = getFont() local fontBase = "resources/fonts/" --local font = Font.new(fontBase.."font24.txt", fontBase.."font24.png") local sw = 0 local sh = 0 local pw = 0 local ph = 0 function slider:init(tx, ty, pos, title, col, keepfocus) self.area = Sprite:new() self.keepFocus = keepfocus self:setClickCallback(nil,self) self:setMoveCallback(nil, self) self.bar = Bitmap.new(barTexture) self.pill = Bitmap.new(pillTexture) self:setCol(col) pw = self.pill:getWidth() sw = self.bar:getWidth() sh = self.bar:getHeight() tx = (application:getLogicalHeight() - sw) / 2 -- centre the bar self.focus = false self.bx = tx self.by = ty self.minx = tx + (pw/2) self.maxx = self.minx + sw - pw self.bar:setPosition(tx, ty-(sh/2)) self.area:addChild(self.bar) self.px = self.minx self.ty = ty if pos > 100 then pos = 100 end self.tx = self.px + ((pos * (sw-pw)) / 100) self.pill:setAnchorPoint(0.5, 0.5) self.pill:setPosition(self.tx, self.ty) if title then local text = TextField.new(font, title) local width = text:getWidth() text:setPosition(tx+(sw/2)-(width/2),ty+6) text:setTextColor(0xffffff); self.area:addChild(text) end self.area:addChild(self.pill) self:addChild(self.area) self.area:addEventListener(Event.MOUSE_UP, self.onMouseUp, self) self.area:addEventListener(Event.MOUSE_MOVE, self.onMouseMove, self) self.area:addEventListener(Event.MOUSE_DOWN, self.onMouseDown, self) self:addEventListener(Event.ENTER_FRAME, self.frameStart, self) end function slider:onExitEnd() self.area:removeEventListener(Event.MOUSE_UP, self.onMouseUp) self.area:removeEventListener(Event.MOUSE_MOVE, self.onMouseMove) self.area:removeEventListener(Event.MOUSE_DOWN, self.onMouseDown) self:removeEventListener(Event.ENTER_FRAME, self.frameStart) collectgarbage() end function slider:setClickCallback(cb) self.clickCallback = cb end function slider:setMoveCallback(cb) self.moveCallback = cb end function slider:onMouseDown(event) if self:hitTestPoint(event.x, event.y) then self.focus = true event:stopPropagation() end end function slider:onMouseMove(event) if self.focus then if not self.keepFocus then if not self:hitTestPoint(event.x, event.y) then self.focus = false end end if self.focus then if event.x < self.minx then self.tx = self.minx elseif event.x > self.maxx then self.tx = self.maxx else self.tx = event.x end if self.moveCallback then self.moveCallback(self) end event:stopPropagation() end end end function slider:onMouseUp(event) if self.focus then if event.x < self.minx then self.tx = self.minx elseif event.x > self.maxx then self.tx = self.maxx else self.tx = event.x end self.focus = false event:stopPropagation() if self.clickCallback then self.clickCallback(self) else self:dispatchEvent(Event.new("click")) end end end function slider:getPos() local temp = ((self.tx-self.minx) * 100) / sw if temp < 0 then temp = 0 elseif temp > 100 then temp = 100 end return temp end function slider:setCol(col) self.area:setColorTransform(col.r, col.g, col.b, col.a) end function slider:frameStart(event) self.pill:setPosition(self.tx, self.ty) end
local a = require 'plenary.async' local cli = require('neogit.lib.git.cli') local input = require('neogit.lib.input') local M = {} local function parse_branches(branches) local other_branches = {} for _, b in ipairs(branches) do local branch_name = b:match('^ (.+)') if branch_name then table.insert(other_branches, branch_name) end end return other_branches end local function get_local_branches() local branches = cli.branch .list .call() return parse_branches(branches) end function M.get_all_branches() local branches = cli.branch .list .all .call() return parse_branches(branches) end function M.get_upstream() local full_name = cli["rev-parse"].abbrev_ref().show_popup(false).args("@{upstream}").call() local current = cli.branch.current.show_popup(false).call() if #full_name > 0 and #current > 0 then local remote = cli.config .show_popup(false) .get(string.format("branch.%s.remote", current[1])) .call() if #remote > 0 then return { remote = remote[1], branch = full_name[1]:sub(#remote[1] + 2, -1), } end end end function M.prompt_for_branch(options) a.util.scheduler() local chosen = input.get_user_input_with_completion('branch > ', options) if not chosen or chosen == '' then return nil end local truncate_remote_name = chosen:match('.+/.+/(.+)') if truncate_remote_name and truncate_remote_name ~= '' then return truncate_remote_name end return chosen end function M.checkout_local() local branches = get_local_branches() a.util.scheduler() local chosen = M.prompt_for_branch(branches) if not chosen then return end cli.checkout.branch(chosen).call() end function M.checkout() local branches = M.get_all_branches() a.util.scheduler() local chosen = M.prompt_for_branch(branches) if not chosen then return end cli.checkout.branch(chosen).call() end function M.create() a.util.scheduler() local name = input.get_user_input('branch > ') if not name or name == '' then return end cli.interactive_git_cmd(tostring(cli.branch.name(name))) return name end function M.delete() local branches = M.get_all_branches() a.util.scheduler() local chosen = M.prompt_for_branch(branches) if not chosen then return end cli.interactive_git_cmd(tostring(cli.branch.delete.name(chosen))) return chosen end function M.checkout_new() a.util.scheduler() local name = input.get_user_input('branch > ') if not name or name == '' then return end cli.interactive_git_cmd(tostring(cli.checkout.new_branch(name))) end return M
require "tundra.syntax.glob" require "tundra.syntax.osx-bundle" require "tundra.path" require "tundra.util" ----------------------------------------------------------------------------------------------------------------------- ----------------------------------------------- EXTERNAL LIBS --------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------- StaticLibrary { Name = "stb", Env = { CCOPTS = { { "-Werror", "-Wno-parentheses", "-Wno-unused-variable", "-Wno-pointer-to-int-cast", "-Wno-int-to-pointer-cast", "-Wno-unused-but-set-variable", "-Wno-return-type", "-Wno-unused-function" ; Config = "linux-*-*" }, { "-Wno-everything"; Config = "macosx-*-*" }, { "/wd4244", "/wd4267", "/wd4133", "/wd4047", "/wd4204", "/wd4201", "/wd4701", "/wd4703", "/wd4024", "/wd4100", "/wd4053", "/wd4431", "/wd4189", "/wd4127"; Config = "win64-*-*" }, }, }, Sources = { Glob { Dir = "src/external/stb", Extensions = { ".c", ".h" }, }, }, } ----------------------------------------------------------------------------------------------------------------------- StaticLibrary { Name = "jansson", Env = { CPPPATH = { "src/external/jansson/include", }, CCOPTS = { { "-Wno-everything"; Config = "macosx-*-*" }, { "/wd4267", "/wd4706", "/wd4244", "/wd4701", "/wd4334", "/wd4127"; Config = "win64-*-*" }, }, }, Sources = { Glob { Dir = "src/external/jansson/src", Extensions = { ".c", ".h" }, }, }, } ----------------------------------------------------------------------------------------------------------------------- StaticLibrary { Name = "yaml", Env = { CPPPATH = { "src/external/libyaml/include", }, CCOPTS = { { "-Wno-everything"; Config = "macosx-*-*" }, { "/wd4267", "/wd4706", "/wd4244", "/wd4701", "/wd4334", "/wd4127", "/wd4245", "/wd4100", "/wd4702"; Config = "win64-*-*" }, }, }, Sources = { Glob { Dir = "src/external/libyaml/src", Extensions = { ".c", ".h" }, }, }, } ----------------------------------------------------------------------------------------------------------------------- StaticLibrary { Name = "uv", Env = { CPPPATH = { "src/external/libuv/include", "src/external/libuv/src", }, CCOPTS = { { "-Wno-everything"; Config = "macosx-*-*" }, { "/wd4201", "/wd4127", "/wd4244", "/wd4100", "/wd4245", "/wd4204", "/wd4701", "/wd4703", "/wd4054", "/wd4702", "/wd4267"; Config = "win64-*-*" }, }, }, Sources = { -- general { Glob { Dir = "src/external/libuv/src", Extensions = { ".c", ".h" }, Recursive = false }, }, -- Windows { Glob { Dir = "src/external/libuv/src/win", Extensions = { ".c", ".h" }, Recursive = false } ; Config = "win64-*-*" }, -- Unix { Glob { Dir = "src/external/libuv/src/unix", Extensions = { ".c", ".h" }, Recursive = false } ; Config = { "macosx-*-*", "linux-*-*" } }, -- Mac { "src/external/libuv/src/unix/darwin/darwin-proctitle.c", "src/external/libuv/src/unix/darwin/darwin.c" ; Config = "macosx-*-*" }, -- Linux { "src/external/libuv/src/unix/linux/linux-core.c", "src/external/libuv/src/unix/linux/linux-inotify.c", "src/external/libuv/src/unix/linux/linux-syscalls.c" ; Config = "linux-*-*" }, }, } ----------------------------------------------------------------------------------------------------------------------- StaticLibrary { Name = "bgfx", Env = { CPPPATH = { "src/external/bgfx/include", "src/external/bx/include", "src/external/bgfx/3rdparty/khronos", }, CXXOPTS = { { "-Wno-variadic-macros", "-Wno-everything" ; Config = "macosx-*-*" }, { "/EHsc"; Config = "win64-*-*" }, }, }, Sources = { { "src/external/bgfx/src/bgfx.cpp", "src/external/bgfx/src/image.cpp", "src/external/bgfx/src/vertexdecl.cpp", "src/external/bgfx/src/renderer_gl.cpp", "src/external/bgfx/src/renderer_null.cpp", "src/external/bgfx/src/renderer_d3d9.cpp", "src/external/bgfx/src/renderer_d3d11.cpp" }, { "src/external/bgfx/src/glcontext_wgl.cpp" ; Config = "win64-*-*" }, -- { "src/external/bgfx/src/glcontext_glx.cpp" ; Config = "linux-*-*" }, { "src/external/bgfx/src/glcontext_nsgl.mm" ; Config = "macosx-*-*" }, }, } ----------------------------------------------------------------------------------------------------------------------- StaticLibrary { Name = "nanovg", Env = { CPPPATH = { "src/external/nanovg", "src/external/stb", "src/external/bgfx/include", }, CXXOPTS = { "-Wno-variadic-macros", "-Wno-everything" ; Config = "macosx-*-*" }, }, Sources = { Glob { Dir = "src/external/nanovg", Extensions = { ".cpp", ".h" }, }, }, } ----------------------------------------------------------------------------------------------------------------------- StaticLibrary { Name = "cmocka", Env = { CPPPATH = { "src/external/cmocka/include", }, CCOPTS = { { "-Wno-everything" ; Config = "macosx-*-*" }, { "/wd4204", "/wd4701", "/wd4703" ; Config = "win64-*-*" }, }, }, Sources = { Glob { Dir = "src/external/cmocka/src", Extensions = { ".c", ".h" }, }, }, } ----------------------------------------------------------------------------------------------------------------------- StaticLibrary { Name = "remote_api", Env = { CPPPATH = { "api/include" }, CCOPTS = { "-Wno-visibility", "-Wno-conversion", "-Wno-pedantic", "-Wno-conversion", "-Wno-covered-switch-default", "-Wno-unreachable-code", "-Wno-bad-function-cast", "-Wno-missing-field-initializers", "-Wno-float-equal", "-Wno-conversion", "-Wno-switch-enum", "-Wno-format-nonliteral"; Config = "macosx-*-*" }, }, Sources = { Glob { Dir = "api/src/remote", Extensions = { ".c" }, }, }, } ----------------------------------------------------------------------------------------------------------------------- ----------------------------------------------- INTERNAL LIBS --------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------- StaticLibrary { Name = "core", Env = { CPPPATH = { "src/external/stb", "src/external/libuv/include", "api/include", "src/prodbg", }, }, Sources = { Glob { Dir = "src/prodbg/core", Extensions = { ".cpp", ".h" }, }, }, } ----------------------------------------------------------------------------------------------------------------------- StaticLibrary { Name = "session", Env = { CPPPATH = { "src/external/stb", "src/external/libuv/include", "api/include", "src/prodbg", }, CXXOPTS = { { "/EHsc"; Config = "win64-*-*" }, }, }, Sources = { Glob { Dir = "src/prodbg/session", Extensions = { ".cpp", ".h" }, }, }, } ----------------------------------------------------------------------------------------------------------------------- StaticLibrary { Name = "ui", Env = { CXXOPTS = { { "-Wno-gnu-anonymous-struct", "-Wno-global-constructors", "-Wno-switch-enum", "-Wno-nested-anon-types", "-Wno-float-equal", "-Wno-cast-align", "-Wno-exit-time-destructors", "-Wno-format-nonliteral"; Config = "macosx-*-*" }, }, CPPPATH = { "api/include", "src/external/nanovg", "src/external/stb", "src/external/libyaml/include", "src/prodbg", }, }, Sources = { FGlob { Dir = "src/prodbg/ui", Extensions = { ".c", ".cpp", ".m", ".mm", ".h" }, Filters = { { Pattern = "mac"; Config = "macosx-*-*" }, { Pattern = "windows"; Config = "win64-*-*" }, { Pattern = "linux"; Config = "linux-*-*" }, }, Recursive = true, }, }, } ----------------------------------------------------------------------------------------------------------------------- StaticLibrary { Name = "api", Env = { CPPPATH = { "api/include", "src/prodbg", }, }, Sources = { Glob { Dir = "src/prodbg/api", Extensions = { ".c", ".cpp", ".h" }, }, }, }
object_mobile_lifeday_saun_dann = object_mobile_shared_lifeday_saun_dann:new { } ObjectTemplates:addTemplate(object_mobile_lifeday_saun_dann, "object/mobile/lifeday_saun_dann.iff")
object_tangible_door_exar_kun_door_s3 = object_tangible_door_shared_exar_kun_door_s3:new { } ObjectTemplates:addTemplate(object_tangible_door_exar_kun_door_s3, "object/tangible/door/exar_kun_door_s3.iff")
---------------------------------------------------------------------------------------------------- -- ElvUI module, to display datatex in ElvUI -- --if ElvUI its not present, dont use this module if not IsAddOnLoaded( "ElvUI" ) then return; end --get the engine and create the module local Engine = select(2,...); local mod = Engine.AddOn:NewModule("ElvUIDataText"); --debug local debug = Engine.AddOn:GetModule("debug"); --get locale local L = Engine.Locale; --not in use function mod.OnEvent() end --updata the ElvUI datatext using our generic module function mod.OnUpdate(self, t) mod.datatext:UpdateText(self.text,t); end --button click on the datatext, is always locked so left click toggle, right config function mod.OnClick(self,button) if button=="LeftButton" then mod.datatext.meter:toggle(); elseif button=="RightButton" then Engine.AddOn:ShowConfig(); end end --mouse enter in the datatext function mod.OnEnter(self) local tooltip = nil; if not Engine.Profile.overlay.elvtukoverride then --get tooltip from elvui tooltip = mod.ElvDT.tooltip; mod.ElvDT:SetupTooltip(self); else --get our tooltip local parent = self:GetParent(); tooltip = mod.datatext.tooltip; tooltip:SetOwner(parent, parent.anchor, parent.xOff, parent.yOff); end mod.datatext:OnEnter(self,tooltip); --if we need to add the tip to the overlay if (Engine.Profile.overlay.tip) then tooltip:AddLine(" "); tooltip:AddLine(L["TIP_LOCK"]); end if Engine.Profile.overlay.elvtukoverride then --format the tooltip mod.datatext:FormatTooltip(tooltip); end --show the overlay tooltip:Show(); end --mouse leaves out the datatext function mod.OnLeave(self) local tooltip = nil; if not Engine.Profile.overlay.elvtukoverride then --get tooltip from elvui tooltip = mod.ElvDT.tooltip; else --get our tooltip tooltip = mod.datatext.tooltip; end mod.datatext:OnLeave(self,tooltip); end --initialize module registering in ElvUI the datatext function mod:OnInitialize() --get ElvUI datatext module local E = select(1,unpack(ElvUI)); mod.ElvDT = E:GetModule('DataTexts') --store our generic datatext module mod.datatext = Engine.AddOn:GetModule("datatext"); --register in ElvUI mod.ElvDT:RegisterDatatext(L["CONFIG_NAME"], { "PLAYER_ENTERING_WORLD" } , mod.OnEvent, mod.OnUpdate, mod.OnClick,mod.OnEnter,mod.OnLeave); debug("ElvUI DataText registered"); end
--[[ ------------------------------------------------------------------------------- Menori @author rozenmad 2021 ------------------------------------------------------------------------------- --]] --[[-- Perspective camera class. ]] -- @module menori.PerspectiveCamera local modules = (...):match('(.*%menori.modules.)') local class = require (modules .. 'libs.class') local ml = require (modules .. 'ml') local app = require (modules .. 'application') local mat4 = ml.mat4 local vec2 = ml.vec2 local vec3 = ml.vec3 local vec4 = ml.vec4 local PerspectiveCamera = class('PerspectiveCamera') --- init -- @tparam number fov -- @tparam number aspect -- @tparam number nclip -- @tparam number fclip function PerspectiveCamera:init(fov, aspect, nclip, fclip) fov = fov or 60 aspect = aspect or 1.6666667 nclip = nclip or 0.1 fclip = fclip or 512.0 self.m_projection = mat4():perspective_LH_NO(fov, aspect, nclip, fclip) self.m_inv_projection = self.m_projection:clone():inverse() self.m_view = mat4() self.center = vec3( 0, 0, 0 ) self.eye = vec3( 0, 0, 1 ) self.up = vec3( 0,-1, 0 ) end -- Updating the view matrix. function PerspectiveCamera:update_view_matrix() self.m_view:identity() self.m_view:look_at(self.eye, self.center, self.up) end --- Returns a ray going from camera through a screen point. -- @tparam number x screen position x -- @tparam number y screen position y -- @tparam table viewport (optional) viewport rectangle (x, y, w, h) -- @treturn vec3 function PerspectiveCamera:screen_point_to_ray(x, y, viewport) viewport = viewport or {app.ox, app.oy, app.w * app.sx, app.h * app.sy} local m_pos = vec3(mat4.unproject(vec3(x, y, 1), self.m_view, self.m_projection, viewport)) local c_pos = self.eye:clone() return { position = c_pos, direction = m_pos - self.eye } end function PerspectiveCamera:world_to_screen_point(x, y, z) if type(x) == 'table' then x, y, z = x.x, x.y, x.z end local m_proj = self.m_projection local m_view = self.m_view local view_p = m_view:multiply_vec4(vec4(x, y, z, 1)) local proj_p = m_proj:multiply_vec4(view_p) if proj_p.w < 0 then return vec2(0, 0) end local ndc_space_pos = vec2( proj_p.x / proj_p.w, proj_p.y / proj_p.w ) local screen_space_pos = vec2( (ndc_space_pos.x + 1) / 2 * app.w * app.sx, (ndc_space_pos.y + 1) / 2 * app.h * app.sy ) return screen_space_pos end --- Get direction. -- @treturn vec3 function PerspectiveCamera:get_direction() return (self.center - self.eye):normalize() end return PerspectiveCamera
term = {} qA = {} qB = {} answA = {} answB = {} diffA = math.random(59) + 10; term[2] = math.random(90 - diffA) + 10; diffB = math.random(59) + 10 ; term[4] = math.random(90 - diffB) + 10; term[1] = diffA + term[2]; term[3] = diffB + term[4]; for i=1,4 do term[i] = term[i]; end diffA = diffA diffB = diffB qA[1] = term[1] qA[2] = term[1] - math.random(9) qA[3] = term[1] + math.random(9) if (qA[3] > 100) then qA[3] = 100 end qA[4] = term[2] + math.random(9) for i = 1,3 do if(qA[4] == qA[i]) then qA[4] = 0 end end answA = lib.math.random_shuffle(qA) for i = 1,4 do if(answA[i] == term[1]) then indA = i-1 end end qB[1] = term[4] qB[2] = term[4] + math.random(9) qB[3] = term[4] - math.random(9) qB[4] = term[3] - math.random(9) for i = 1,3 do if(qB[4] == qB[i]) then qB[4] = 0 end end answB = lib.math.random_shuffle(qB) for i = 1,4 do if(answB[i] == term[4]) then indB = i-1 end end
vim.g.everforest_background = 'hard' vim.o.background = 'dark' vim.cmd('colorscheme everforest')
if not modules then modules = { } end modules ['data-bin'] = { version = 1.001, comment = "companion to luat-lib.mkiv", author = "Hans Hagen, PRAGMA-ADE, Hasselt NL", copyright = "PRAGMA ADE / ConTeXt Development Team", license = "see context related readme files" } local resolvers = resolvers local methodhandler = resolvers.methodhandler function resolvers.findbinfile(filename,filetype) return methodhandler('finders',filename,filetype) end function resolvers.openbinfile(filename) return methodhandler('loaders',filename) -- a bit weird: load end function resolvers.loadbinfile(filename,filetype) local fname = methodhandler('finders',filename,filetype) if fname and fname ~= "" then return resolvers.openbinfile(fname) -- a bit weird: open else return resolvers.loaders.notfound() end end
Script.ReloadScript("scripts/Utils/EntityUtils.lua") GeomEntity = { Client = {}, Server = {}, Editor={ Icon="physicsobject.bmp", IconOnTop=1, } } -------------------------------------------------------------------------- function GeomEntity.Server:OnInit() self:SetFlags(ENTITY_FLAG_CLIENT_ONLY,0); end -------------------------------------------------------------------------- function GeomEntity.Client:OnInit() self:SetFlags(ENTITY_FLAG_CLIENT_ONLY,0); end ------------------------------------------------------------------------------------------------------ function GeomEntity:OnPhysicsBreak( vPos,nPartId,nOtherPartId ) self:ActivateOutput("Break",nPartId+1 ); end ------------------------------------------------------------------------------------------------------ function GeomEntity:Event_Remove() self:DrawSlot(0,0); self:DestroyPhysics(); self:ActivateOutput( "Remove", true ); end ------------------------------------------------------------------------------------------------------ function GeomEntity:Event_Hide() self:Hide(1); self:ActivateOutput( "Hide", true ); end ------------------------------------------------------------------------------------------------------ function GeomEntity:Event_UnHide() self:Hide(0); self:ActivateOutput( "UnHide", true ); end function GeomEntity:OnLoad(table) self.health = table.health; self.dead = table.dead; if(table.bAnimateOffScreenShadow) then self.bAnimateOffScreenShadow = table.bAnimateOffScreenShadow; else self.bAnimateOffScreenShadow = false; end end function GeomEntity:OnSave(table) table.health = self.health; table.dead = self.dead; if(self.bAnimateOffScreenShadow) then table.bAnimateOffScreenShadow = self.bAnimateOffScreenShadow; else table.bAnimateOffScreenShadow = false; end end ------------------------------------------------------- function GeomEntity:OnPropertyChange() self:OnReset(); end GeomEntity.FlowEvents = { Inputs = { Hide = { GeomEntity.Event_Hide, "bool" }, UnHide = { GeomEntity.Event_UnHide, "bool" }, Remove = { GeomEntity.Event_Remove, "bool" }, }, Outputs = { Hide = "bool", UnHide = "bool", Remove = "bool", Break = "int", }, } MakeTargetableByAI(GeomEntity); MakeKillable(GeomEntity); MakeRenderProxyOptions(GeomEntity);
-- These commands will navigate through buffers in order regardless of which mode you are using -- e.g. if you change the order of buffers :bnext and :bprevious will not respect the custom ordering vim.api.nvim_set_keymap("n", "<tab>", "<cmd>BufferLineCycleNext<CR>", { noremap = true, silent = true }) vim.api.nvim_set_keymap("n", "<s-tab>", "<cmd>BufferLineCyclePrev<CR>", { noremap = true, silent = true }) -- Remove a buffer vim.api.nvim_set_keymap("n", "<leader>bd", "<cmd>bdelete<CR>", { noremap = true, silent = true })
ITEM.name = "Металлическая лопата" ITEM.desc = "Старая металлическая лопата, используется в различных целей в Зоне. Может быть быстро заточека. \n\nХАРАКТЕРИСТИКИ: \n-повсеместное применение \n-используется для: установки палатки (многоразовый) \n-используется как: инструмент для разборки (многоразовый) \n-многоразовый инструмент" ITEM.price = 1071 ITEM.exRender = false ITEM.weight = 1.64 ITEM.model = "models/kek1ch/shovel.mdl" ITEM.width = 1 ITEM.height = 2 ITEM.iconCam = { pos = Vector(477.88369750977, 400.97088623047, 315.34320068359), ang = Angle(25, 220, -9.1719741821289), fov = 2 }
local mod = require 'mod' -- def_ show(expr) print(_STR_(expr),expr) assert(mod.one() == 42) f = mod.Fred(22) assert(f:get() == 22) f:set2() assert(f:get() == 0) a = mod.Alice() a:set2() assert(a:get() == 1) a:set(66) assert(tostring(a) == "Alice 66")
local class = require 'middleclass' local TankTurret = class('littletanks.TankTurret') function TankTurret:initialize() end function TankTurret:destroy() -- Nothing to do here (yet) end function TankTurret:update( timeDelta ) -- Nothing to do here (yet). end function TankTurret:draw() error('Missing implementation.') end function TankTurret:onTurretRotation( angle ) -- Nothing to do here (yet). end return TankTurret
------------------------------------------------------------------ -- Configuration options for scripted systems in this pack ------------------------------------------------------------------ EXPERIMENTAL_ENABLE_DYNAMIC_REQUIREMENTS = false
local wk = require('which-key') local lspinstaller = require('nvim-lsp-installer') local lspconfig = require('lspconfig') local illum = require('illuminate') local aerial = require('aerial') local lsp = vim.lsp local diag = vim.diagnostic wk.register( { l = { name = 'LSP', a = { '<Cmd>AerialToggle<Cr>', 'Toggle Aerial' } , e = { '<Cmd>lua vim.lsp.buf.code_action()<Cr>', 'Code Actions' }, f = { function() lsp.buf.formatting() end, 'Format' }, i = { function() lsp.buf.implementation() end, 'Implementation' }, k = { function() lsp.buf.hover() end, 'Hover' }, l = { function() diag.open_float() end, 'Show Line Diagnostics' }, q = { function() diag.setloclist() end, 'Set Location List' }, R = { '<Cmd>LspRestart<Cr>', 'Restart LSP' }, m = { function() lsp.buf.rename() end, 'Rename' }, y = { function() lsp.buf.type_definition() end, 'Type Definition' }, -- Telescope lsp maps D = { '<Cmd>Telescope lsp_document_diagnostics<Cr>', 'Diagnostics' }, I = { '<Cmd>Telescope lsp_implementations<Cr>', 'Implementations' }, d = { '<Cmd>Telescope lsp_definitions<Cr>', 'Definitions' }, r = { '<Cmd>Telescope lsp_references<Cr>', 'References' }, s = { '<Cmd>Telescope lsp_document_symbols<Cr>', 'Symbols' }, -- nvim-lsp-installer maps L = { '<Cmd>LspInstallInfo<Cr>', 'nvim-lsp-installer UI' }, }, }, { prefix = '<Leader>', } ) wk.register( { ['[d'] = { function() diag.goto_prev() end, 'Previous Diagnostic' }, [']d'] = { function() diag.goto_next() end, 'Next Diagnostic' }, -- vim-illuminate maps [']i'] = { function() illum.next_reference({ wrap = true }) end, 'Move to next doc highlight' }, ['[i'] = { function() illum.next_reference({ wrap = true, reverse = true }) end, 'Move to prev doc highlight' }, } ) local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities = require('cmp_nvim_lsp').update_capabilities(capabilities) local function disable_formatting(client) client.resolved_capabilities.document_formatting = false client.resolved_capabilities.document_range_formatting = false end local enhance_server_opts = { ['tsserver'] = function(opts, client) -- Prefer prettier formatting over null-ls disable_formatting(client) end, ['jsonls'] = function(opts, client) -- Prefer prettier formatting over null-ls disable_formatting(client) end, } lspinstaller.setup() local servers = { 'tsserver', 'jsonls', 'eslint' } for _, server in ipairs(servers) do lspconfig[server].setup({ capabilities = capabilities, on_attach = function(client, bufnr) if enhance_server_opts[server] then -- Enhance the default opts with the server-specific ones enhance_server_opts[server](opts, client) end -- Automatically format for servers which support it if client.resolved_capabilities.document_formatting then vim.cmd("autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync()") end -- Attach vim-illuminate illum.on_attach(client) -- Attach aerial.nvim aerial.on_attach(client, bufnr) end, }) end -- Disable illuminate in fugitiveblame vim.g.Illuminate_ftblacklist = { 'fugitiveblame' }
local RunService = game:GetService("RunService") local Loading = script.Parent local App = Loading.Parent local UIBlox = App.Parent local Packages = UIBlox.Parent local Roact = require(Packages.Roact) local t = require(Packages.t) local ExternalEventConnection = require(UIBlox.Utility.ExternalEventConnection) local ImageSetComponent = require(UIBlox.Core.ImageSet.ImageSetComponent) local function floorVector2(vector2) return Vector2.new(math.floor(vector2.X), math.floor(vector2.Y)) end local validateProps = t.strictInterface({ -- The anchor point of the panel anchorPoint = t.optional(t.Vector2), -- The layout order of the panel layoutOrder = t.optional(t.integer), -- The background color of the panel backgroundColor3 = t.optional(t.Color3), -- The background transparency of the panel backgroundTransparency = t.optional(t.number), -- The position of the panel position = t.optional(t.UDim2), -- The corner radius of the image's rounded corners. Defaults to UDim(0, 0) for corners with no rounding. cornerRadius = t.optional(t.UDim), -- The image that will move across the panel image = t.string, -- The tranparency of the moving image imageTransparency = t.optional(t.number), -- The anchor point of the moving image rect imageAnchorPoint = t.optional(t.Vector2), -- The start position of the moving image rect imageRectOffsetStart = t.Vector2, -- The end position of the moving image rect imageRectOffsetEnd = t.Vector2, -- The take it takes for the image to move from the start positon -- to the end positions imageScrollCycleTime = t.optional(t.number), -- The size of the image rect that is projected onto the panel imageRectSize = t.Vector2, -- The size point of the panel size = t.optional(t.UDim2), }) local TextureScroller = Roact.PureComponent:extend("TextureScroller") TextureScroller.defaultProps = { backgroundTransparency = 1, cornerRadius = UDim.new(0, 0), imageAnchorPoint = Vector2.new(0, 0), imageScrollCycleTime = 1, } function TextureScroller:init() self.lerpValue = 0 self.imageRef = Roact.createRef() self.renderSteppedCallback = function(dt) local imageScrollCycleTime = self.props.imageScrollCycleTime local imageRectOffsetStart = self.props.imageRectOffsetStart local imageRectOffsetEnd = self.props.imageRectOffsetEnd local imageRectSize = self.props.imageRectSize local imageAnchorPoint = self.props.imageAnchorPoint local anchoredImageOffsetStart = Vector2.new( imageRectOffsetStart.X - imageAnchorPoint.X * imageRectSize.X, imageRectOffsetStart.Y - imageAnchorPoint.Y * imageRectSize.Y) local anchoredImageOffsetEnd = Vector2.new( imageRectOffsetEnd.X - imageAnchorPoint.X * imageRectSize.X, imageRectOffsetEnd.Y - imageAnchorPoint.Y * imageRectSize.Y) local lerpPerFrame = 0 if imageScrollCycleTime ~= 0 then lerpPerFrame = (dt / imageScrollCycleTime) end self.lerpValue = (self.lerpValue + lerpPerFrame) % 1 if self.imageRef.current then self.imageRef.current.ImageRectOffset = floorVector2( anchoredImageOffsetStart:lerp(anchoredImageOffsetEnd, self.lerpValue)) end end end function TextureScroller:render() assert(validateProps(self.props)) local anchorPoint = self.props.anchorPoint local backgroundColor = self.props.backgroundColor3 local backgroundTransparency = self.props.backgroundTransparency local cornerRadius = self.props.cornerRadius local image = self.props.image local imageRectSize = self.props.imageRectSize local imageTransparency = self.props.imageTransparency local layoutOrder = self.props.layoutOrder local position = self.props.position local size = self.props.size return Roact.createElement("Frame", { AnchorPoint = anchorPoint, BackgroundColor3 = backgroundColor, BackgroundTransparency = backgroundTransparency, BorderSizePixel = 0, LayoutOrder = layoutOrder, Position = position, Size = size, }, { TextureScrollerImage = Roact.createElement(ImageSetComponent.Label, { BackgroundTransparency = 1, Image = image, ImageTransparency = imageTransparency, Size = UDim2.new(1, 0, 1, 0), ScaleType = Enum.ScaleType.Slice, SliceCenter = Rect.new(0, 0, imageRectSize.X, imageRectSize.Y), [Roact.Ref] = self.imageRef, ImageRectSize = imageRectSize, }, { UICorner = cornerRadius ~= UDim.new(0, 0) and Roact.createElement("UICorner", { CornerRadius = cornerRadius, }) or nil, }), renderStepped = Roact.createElement(ExternalEventConnection, { callback = self.renderSteppedCallback, event = RunService.renderStepped, }), UICorner = cornerRadius ~= UDim.new(0, 0) and Roact.createElement("UICorner", { CornerRadius = cornerRadius, }) or nil, }) end return TextureScroller
if not modules then modules = { } end modules ['font-prv'] = { version = 1.001, comment = "companion to font-ini.mkiv and hand-ini.mkiv", author = "Hans Hagen, PRAGMA-ADE, Hasselt NL", copyright = "PRAGMA ADE / ConTeXt Development Team", license = "see context related readme files" } local type = type local formatters = string.formatters local fonts = fonts local helpers = fonts.helpers local fontdata = fonts.hashes.identifiers local setmetatableindex = table.setmetatableindex local currentprivate = 0xE000 local maximumprivate = 0xEFFF local extraprivates = { } helpers.extraprivates = extraprivates function fonts.helpers.addextraprivate(name,f) extraprivates[#extraprivates+1] = { name, f } end -- if we run out of space we can think of another range but by sharing we can -- use these privates for mechanisms like alignments-on-character and such local sharedprivates = setmetatableindex(function(t,k) v = currentprivate if currentprivate < maximumprivate then currentprivate = currentprivate + 1 else -- reuse last slot, todo: warning end t[k] = v return v end) function helpers.addprivate(tfmdata,name,characterdata) local properties = tfmdata.properties local characters = tfmdata.characters local privates = properties.privates if not privates then privates = { } properties.privates = privates end if not name then name = formatters["anonymous_private_0x%05X"](currentprivate) end local usedprivate = sharedprivates[name] privates[name] = usedprivate characters[usedprivate] = characterdata return usedprivate end function helpers.getprivates(tfmdata) if type(tfmdata) == "number" then tfmdata = fontdata[tfmdata] end local properties = tfmdata.properties return properties and properties.privates end function helpers.hasprivate(tfmdata,name) if type(tfmdata) == "number" then tfmdata = fontdata[tfmdata] end local properties = tfmdata.properties local privates = properties and properties.privates return privates and privates[name] or false end
local M = {} M.home = os.getenv('HOME') or os.getenv('USERPROFILE') function M.find_dotfiles(opts) opts = opts or {} opts.cwd = opts.cwd or vim.loop.cwd() local Path = require('plenary.path') opts.entry_maker = opts.entry_maker or function(entry) local path = Path:new(Path:new(M.home .. entry):make_relative(opts.cwd)):normalize(opts.cwd) return { path = path, value = path, display = path, ordinal = path, } end -- c ls-tree --full-tree -r --name-only HEAD local custom_cmd = { 'git', '--git-dir=' .. M.home .. '/.dotfiles', '--work-tree=' .. M.home, 'ls-tree', '--full-tree', '-r', '--name-only', 'HEAD' } require('telescope.pickers').new(opts, { results_title = 'dotfiles', finder = require('telescope.finders').new_oneshot_job(custom_cmd, opts), sorter = require('telescope.sorters').get_fuzzy_file(), previewer = require('telescope.config').values.file_previewer(opts) }):find() end function M.map(mode, lhs, rhs, opts) local options = {noremap = true} if opts then options = vim.tbl_extend('force', options, opts) end vim.api.nvim_set_keymap(mode, lhs, rhs, options) end function M.buf_map(mode, lhs, rhs, opts) local options = {noremap = true} if opts then options = vim.tbl_extend('force', options, opts) end vim.api.nvim_set_keymap(mode, lhs, rhs, options) end function M.sanitize_binary(path) if vim.fn.has('win32') ~= 0 then path = path .. '.exe' end return path end function M.on_attach(_, bufnr) vim.api.nvim_buf_set_option(bufnr, 'omnifunc', 'v:lua.vim.lsp.omnifunc') M.map('n', 'gd', '<CMD>lua vim.lsp.buf.definition()<CR>') M.map('n', 'gr', '<CMD>lua vim.lsp.buf.references()<CR>') M.map('n', 'K', '<CMD>lua vim.lsp.buf.hover()<CR>') M.map('n', 'gi', '<CMD>lua vim.lsp.buf.implementation()<CR>') M.map('n', '<Leader>D', '<CMD>lua vim.lsp.buf.type_definition()<CR>') M.map('n', '<Leader>rn', '<CMD>lua vim.lsp.buf.rename()<CR>') M.map('n', '<Leader>e', '<CMD>lua vim.diagnostic.open_float(nil, {scope = "line"})<CR>') M.map('n', ']d', '<CMD>lua vim.diagnostic.goto_next()<CR>') M.map('n', '[d', '<CMD>lua vim.diagnostic.goto_prev()<CR>') M.map('n', '<Leader>q', '<CMD>lua vim.diagnostic.set_loclist()<CR>') vim.cmd [[ hi LspDiagnosticsVirtualTextError guifg=red hi LspDiagnosticsVirtualTextWarning guifg=orange hi LspDiagnosticsVirtualTextInformation guifg=gray hi LspDiagnosticsVirtualTextHint guifg=green ]] require('lsp_signature').on_attach() end M.capabilities = vim.lsp.protocol.make_client_capabilities() M.capabilities = require('cmp_nvim_lsp').update_capabilities(M.capabilities) return M
data:extend({ { type = "bool-setting", name = "xtreme-fishing-enablepipes", setting_type = "startup", default_value = true, order = "a[pipes]", }, { type = "int-setting", name = "xtreme-fishing-ugpipestart", setting_type = "startup", default_value = 11, minimum_value = 1, maximum_value = 101, order = "a[pipes-beginning]", }, { type = "int-setting", name = "xtreme-fishing-ugpipeinterval", setting_type = "startup", default_value = 2, minimum_value = 0, maximum_value = 16, order = "a[pipes-continued]", }, { type = "int-setting", name = "xtreme-fishing-pipestacksize", setting_type = "startup", default_value = 100, minimum_value = 1, maximum_value = 1000, order = "a[pipes-stacksize]", }, { type = "int-setting", name = "xtreme-fishing-ugpipestacksize", setting_type = "startup", default_value = 50, minimum_value = 1, maximum_value = 1000, order = "a[pipes-stacksize-ug]", }, { type = "int-setting", name = "xtreme-fishing-waterpercycle", setting_type = "startup", default_value = 250, minimum_value = 50, maximum_value = 500, order = "ab[farm-water]", }, { type = "int-setting", name = "xtreme-fishing-yieldpercycle", setting_type = "startup", default_value = 40, minimum_value = 1, maximum_value = 100, order = "ab[farm-yield]", }, { type = "string-setting", name = "xtreme-fishing-puffer_type", setting_type = "startup", hidden = true, default_value = "coal", allow_blank = false, auto_trim = true, order = "ac[puffer-type]", }, { type = "int-setting", name = "xtreme-fishing-puffer_yield", setting_type = "startup", hidden = true, default_value = 6, minimum_value = 1, maximum_value = 100, order = "ac[puffer-yield]", }, { type = "int-setting", name = "xtreme-fishing-squid_oil", setting_type = "startup", hidden = true, default_value = 10, minimum_value = 5, maximum_value = 100, order = "ad[fishlube-squid]", }, { type = "int-setting", name = "xtreme-fishing-puffer_gas", setting_type = "startup", hidden = true, default_value = 10, minimum_value = 5, maximum_value = 100, order = "ad[fishlube-puffer]", }, { type = "int-setting", name = "xtreme-fishing-crab_plastic", setting_type = "startup", hidden = true, default_value = 2, minimum_value = 1, maximum_value = 10, order = "ad[fishlube-crabplastic]", }, { type = "int-setting", name = "xtreme-fishing-fishlube", setting_type = "startup", hidden = true, default_value = 10, minimum_value = 5, maximum_value = 100, order = "ad[fishlube]", }, { type = "string-setting", name = "xtreme-fishing-crab_catalyst", setting_type = "startup", hidden = true, default_value = "lubricant", allowed_values = { "lubricant", "petroleum-gas", "steam", "sulfuric-acid" }, order = "ad[fishlube-crabcatalyst]", }, { type = "bool-setting", name = "xtreme-fishing-campfire-cooking", setting_type = "startup", hidden = true, default_value = true, order = "ac[campfire-cooking]", } }) -- pufferfish settings (cooked fish) if mods["factorio-cooked-fish"] then data.raw["string-setting"]["xtreme-fishing-puffer_type"].hidden = false data.raw["int-setting"]["xtreme-fishing-puffer_yield"].hidden = false end -- campfire settings (fire-place) if mods["fire-place"] and (mods["GreenTec"] or mods["factorio-cooked-fish"]) then data.raw["bool-setting"]["xtreme-fishing-campfire-cooking"].hidden = false end -- fish lube settings if mods["Fish_Lube"] then data.raw["int-setting"]["xtreme-fishing-squid_oil"].hidden = false data.raw["int-setting"]["xtreme-fishing-puffer_gas"].hidden = false data.raw["int-setting"]["xtreme-fishing-crab_plastic"].hidden = false data.raw["int-setting"]["xtreme-fishing-fishlube"].hidden = false data.raw["int-setting"]["xtreme-fishing-fishlube"].hidden = false data.raw["string-setting"]["xtreme-fishing-crab_catalyst"].hidden = false end
if nil ~= require then require "fritomod/ListenerList"; end; Callbacks = Callbacks or {}; local function ActivateKeyboard(frame) local KEYBOARD_ENABLER = "__KeyboardEnabler"; if not frame[KEYBOARD_ENABLER] then frame[KEYBOARD_ENABLER] = Functions.Install(function() frame:EnableKeyboard(true); return Functions.OnlyOnce(frame, "EnableKeyboard", false); end); end; return frame[KEYBOARD_ENABLER](); end; local function KeyListener(event) return function(frame, func, ...) frame = Frames.AsRegion(frame); assert(frame.EnableKeyboard, "Frame must support keyboard events"); local list = Frames.GetCallbackHandler(frame, event, ActivateKeyboard, frame); return list:Add(func, ...); end; end; Callbacks.Char=KeyListener("OnChar"); Callbacks.KeyDown=KeyListener("OnKeyDown"); Callbacks.KeyPress=Callbacks.KeyDown; Callbacks.KeyUp=KeyListener("OnKeyUp"); Callbacks.KeyRelease=Callbacks.KeyUp; local modifierFor = { SHIFT = "SHIFT", LSHIFT = "SHIFT", RSHIFT = "SHIFT", CONTROL = "CONTROL", LCONTROL = "CONTROL", RCONTROL = "CONTROL", }; function Callbacks.Keys(frame, func, ...) func = Curry(func, ...); local callbacks = {}; return Functions.OnlyOnce(Lists.CallEach, { Callbacks.KeyDown(frame, function(pressedKey, ...) if modifierFor[pressedKey] then -- Refuse to handle modifiers return; end; if callbacks[pressedKey] then -- Redundant keypress, so just ignore it return; end; callbacks[pressedKey] = func(pressedKey, ...) or Noop; end), Callbacks.KeyUp(frame, function(pressedKey, ...) if callbacks[pressedKey] then callbacks[pressedKey](pressedKey, ...); callbacks[pressedKey] = nil; end; end) }); end; function Callbacks.Modifiers(frame, func, ...) func = Curry(func, ...); local callbacks = {}; local modCounts = {}; return Functions.OnlyOnce(Lists.CallEach, { Callbacks.KeyPress(frame, function(key, ...) local mod = modifierFor[tostring(key):upper()]; if not mod then return; end; if not modCounts[mod] then callbacks[mod] = func(mod, ...) or Noop; modCounts[mod] = 0; end; modCounts[mod] = modCounts[mod] + 1; end), Callbacks.KeyUp(frame, function(key, ...) local mod = modifierFor[tostring(key):upper()]; if not mod then return; end; if not modCounts[mod] then return; end; modCounts[mod] = modCounts[mod] - 1; if modCounts[mod] > 0 then return; end; modCounts[mod] = nil; callbacks[mod](mod, ...); callbacks[mod] = nil; end) }); end; function Callbacks.Key(key, func, ...) key=key:lower(); func=Curry(func, ...); local onKeyUp; return Functions.OnlyOnce(Lists.CallEach, { Callbacks.KeyDown(function(pressedKey) pressedKey=pressedKey:lower(); if pressedKey == key then func(); end; end), Callbacks.KeyUp(function(pressedKey) if onKeyUp then pressedKey=pressedKey:lower(); if pressedKey == key then onKeyUp(); onKeyUp=nil; end; end end) }); end; function Callbacks.Modifier(key, func, ...) key=key:upper(); func=Curry(func, ...); local onUp; return Events.MODIFIER_STATE_CHANGED(function(what, isDown) -- I use EndsWith to allow for key to be either 'ALT' or 'LALT' without -- requiring any extra code. if not Strings.EndsWith(what, key) then return; end; if isDown == 1 and not onUp then onUp = func() or Noop; elseif onUp then onUp(); onUp = nil; end; end); end; -- vim: set noet :
--- === cp.ui.Alert === --- --- Alert UI Module. local require = require local axutils = require "cp.ui.axutils" local Sheet = require "cp.ui.Sheet" local Alert = Sheet:subclass("cp.ui.Alert") --- cp.ui.Alert:new(app) -> Alert --- Constructor --- Creates a new `Alert` instance. It will automatically search the parent's children for Alerts. --- --- Parameters: --- * parent - The parent object. --- --- Returns: --- * A new `Browser` object. function Alert:initialize(parent) local UI = parent.UI:mutate(function(original) return axutils.childMatching(original(), Alert.matches) end) Sheet.initialize(self, parent, UI) end return Alert
defines { "rsc_FullName=\"Yakuza Arcade Machines Player\"", "rsc_MinorVersion=0", "rsc_RevisionID=1", "rsc_BuildID=1", "rsc_Copyright=\"2021\"", "rsc_UpdateURL=\"https://github.com/CookiePLMonster/YAMP/releases\"" }
-- -- -- minetest.register_craftitem("yatm_dscs:item_drive_t1", { basename = "yatm_dscs:item_drive", base_description = "Item Drive", description = "Item Drive [32 Cells]", groups = {inventory_drive = 1, item_drive = 1}, inventory_image = "yatm_inventory_drives_item_tier1.png", drive_capacity = 32, stack_max = 1, }) minetest.register_craftitem("yatm_dscs:item_drive_t2", { basename = "yatm_dscs:item_drive", base_description = "Item Drive", description = "Item Drive [128 Cells]", groups = {inventory_drive = 2, item_drive = 2}, inventory_image = "yatm_inventory_drives_item_tier2.png", drive_capacity = 128, stack_max = 1, }) minetest.register_craftitem("yatm_dscs:item_drive_t3", { basename = "yatm_dscs:item_drive", base_description = "Item Drive", description = "Item Drive [512 Cells]", groups = {inventory_drive = 3, item_drive = 3}, inventory_image = "yatm_inventory_drives_item_tier3.png", drive_capacity = 512, stack_max = 1, })
function single() return "test" end function test ( param1, param2 ) method() return 1 end local tbl = {} function tbl:method() self.value = 1 end function tbl:method2() return 12345678 < 12345678 + 1 end -- Result -- function single() return "test" end function test(param1, param2) method() return 1 end local tbl = {} function tbl:method() self.value = 1 end function tbl:method2() return 12345678 < 12345678 + 1 end
local Consts = require "consts" local NoteInfo = require "noteinfo" local Envelope = require "envelope" local Soundwave = require "soundwave" local NoteWave = require "util.class" "NoteWave" -- envelope is optional? function NoteWave:__init(note, speed, startTime) self._note = note self._noteStart = startTime self._env = Envelope:new({ intensity = 0.25 + 2 * speed / 0x80 }) end function NoteWave:setStopTime(stopTime) self._env:setStopTime(stopTime - self._noteStart) end function NoteWave:hasStopTime() return self._env:hasStopTime() end function NoteWave:setEnvelope(envelope) self._env = envelope end function NoteWave:isDead(tPrevious) return self._env:isDead(tPrevious - self._noteStart) end function NoteWave:calculateWavePoint(tAbsolute) local frequency = NoteInfo.getNoteFrequency(self._note) + 10e-7 * math.sin(tAbsolute * 32) local x = tAbsolute * frequency local wavePoint = Soundwave.triangle(x) * 0.3 + Soundwave.sin(x) * 0.7 local envelope = self._env:calculate(tAbsolute - self._noteStart) return wavePoint * envelope end return NoteWave
-- Polished marble nodes greek.marble_groups = {cracky = 2} greek.marble_sounds = greek.default_sounds("node_sound_stone_defaults") greek.register_node_and_stairs("greek:marble_polished", { description = "Polished Marble", tiles = {"greek_marble_polished.png"}, groups = greek.marble_groups, sounds = greek.marble_sounds, }) for _, item in pairs(greek.settings_list("marble")) do greek.add_group(item, "marble") end minetest.register_craft({ output = "greek:marble_polished 9", recipe = { {"group:greek:marble", "group:greek:marble", "group:greek:marble"}, {"group:greek:marble", "group:greek:marble", "group:greek:marble"}, {"group:greek:marble", "group:greek:marble", "group:greek:marble"}, }, }) minetest.register_craft({ output = "greek:marble_polished", recipe = "greek:marble_cobble", type = "cooking", cooktime = 5, }) greek.register_node_and_stairs("greek:marble_polished_block", { description = "Polished Marble Block", tiles = {"greek_marble_polished_block.png"}, groups = greek.marble_groups, sounds = greek.marble_sounds, }) minetest.register_craft({ output = "greek:marble_polished_block 4", recipe = { {"greek:marble_polished", "greek:marble_polished"}, {"greek:marble_polished", "greek:marble_polished"}, } }) greek.register_node_and_stairs("greek:marble_cobble", { description = "Marble Cobble", tiles = {"greek_marble_cobble.png"}, groups = greek.marble_groups, sounds = greek.marble_sounds, }) minetest.register_craft({ output = "greek:marble_cobble 5", recipe = { {"greek:marble_polished", "", "greek:marble_polished"}, {"", "greek:marble_polished", ""}, {"greek:marble_polished", "", "greek:marble_polished"}, }, }) -- Marble pillars greek.register_node_and_stairs("greek:marble_pillar", { description = "Marble Pillar", tiles = {"greek_marble_pillar_top.png", "greek_marble_pillar_top.png", "greek_marble_pillar_side.png"}, paramtype2 = "facedir", groups = greek.marble_groups, sounds = greek.marble_sounds, on_place = minetest.rotate_node, }) minetest.register_craft({ output = "greek:marble_pillar 2", recipe = { {"greek:marble_polished"}, {"greek:marble_polished"}, }, }) local pillar_heads = {"doric", "ionic", "corinthian"} for _, head in pairs(pillar_heads) do minetest.register_node("greek:marble_pillar_head_" .. head, { description = head:gsub("^%l", string.upper) .. " Marble Pillar Head", tiles = {"greek_marble_pillar_top.png", "greek_marble_pillar_top.png", "greek_marble_pillar_head_" .. head .. ".png"}, paramtype2 = "facedir", groups = greek.marble_groups, sounds = greek.marble_sounds, on_place = minetest.rotate_node, }) minetest.register_node("greek:marble_pillar_base_" .. head, { description = head:gsub("^%l", string.upper) .. " Marble Pillar Base", tiles = {"greek_marble_pillar_top.png", "greek_marble_pillar_top.png", "greek_marble_pillar_base_" .. head .. ".png"}, paramtype2 = "facedir", groups = greek.marble_groups, sounds = greek.marble_sounds, on_place = minetest.rotate_node, }) end -- Ionic pillar head has some special side tiles minetest.override_item("greek:marble_pillar_head_ionic", { tiles = { "greek_marble_pillar_top.png", "greek_marble_pillar_top.png", "greek_marble_pillar_head_ionic_side.png", "greek_marble_pillar_head_ionic_side.png", "greek_marble_pillar_head_ionic.png", "greek_marble_pillar_head_ionic.png", }, }) greek.register_craftring("greek:marble_pillar_head_%s", pillar_heads) greek.register_craftring("greek:marble_pillar_base_%s", pillar_heads) minetest.register_craft({ output = "greek:marble_pillar_head_" .. pillar_heads[1] .. " 4", recipe = { {"greek:marble_pillar", "greek:marble_polished", "greek:marble_pillar"}, {"", "greek:marble_pillar", ""}, }, }) minetest.register_craft({ output = "greek:marble_pillar_base_" .. pillar_heads[1] .. " 4", recipe = { {"", "greek:marble_pillar", ""}, {"greek:marble_pillar", "greek:marble_polished", "greek:marble_pillar"}, }, }) -- Carved marble tiles local tile_total = 6 for i = 1, tile_total do greek.register_node_and_stairs("greek:marble_tile_" .. i, { description = "Marble Tile " .. i, tiles = {"greek_marble_tile_" .. i .. ".png"}, paramtype2 = "facedir", groups = greek.marble_groups, sounds = greek.marble_sounds, }) end greek.register_craftring("greek:marble_tile_%s", tile_total) minetest.register_craft({ output = "greek:marble_tile_1 4", recipe = { {"greek:marble_polished_block", "greek:marble_polished_block"}, {"greek:marble_polished_block", "greek:marble_polished_block"}, } }) -- Painted marble tiles -- type name = {total, list of recipe shapes} local types = { center = {12, {{ {0, 1, 0}, {1, 1, 1}, {0, 1, 0}, }}}, corner = {12, { {{1, 0, 0}, {1, 0, 0}, {1, 1, 1}}, {{0, 0, 1}, {0, 0, 1}, {1, 1, 1}}, {{1, 1, 1}, {0, 0, 1}, {0, 0, 1}}, {{1, 1, 1}, {1, 0, 0}, {1, 0, 0}} }}, edge = {12, {{ {1, 0, 1}, {0, 1, 0}, {1, 0, 1}, }}} } -- Palette colors and corresponding dyes local dyes = {["dye:blue"] = 0, ["dye:yellow"] = 1, ["dye:black"] = 2, ["dye:red"] = 3, ["dye:orange"] = 4, ["dye:green"] = 5, ["dye:violet"] = 6, ["dye:pink"] = 7} for type, data in pairs(types) do local total = data[1] for i = 1, total do local name = ("greek:marble_painted_%s_%s"):format(type, i) local tile = ("greek_marble_painted_%s_%s.png"):format(type, i) local registered = greek.register_node_and_stairs(name, { description = ("Painted %s Marble %s"):format(type:gsub("^%l", string.upper), i), tiles = {{name = "greek_marble_polished.png", color = "white"}}, overlay_tiles = {tile, tile .. "^[transformFX", tile, tile .. "^[transformFY", tile .. "^[transformFX", tile .. "^[transformR180"}, paramtype2 = "colorfacedir", palette = "greek_marble_painted_palette.png", color = "#0058af", -- This is used for inventory color use_texture_alpha = true, groups = greek.marble_groups, sounds = greek.marble_sounds, on_punch = greek.dye_punch(dyes), }) -- Recipes for coloring tiles for _, item in pairs(registered) do for dye, color in pairs(dyes) do minetest.register_craft({ output = minetest.itemstring_with_palette(item, color * 32), recipe = {item, dye}, replacements = not greek.settings_get("consume_dye") and {{dye, dye}} or nil, type = "shapeless", }) end end end greek.register_craftring("greek:marble_painted_" .. type .. "_%s", total) -- Use specific dye to craft colored tile -- Is it possible to have a fallback group:dye recipe to output black? (mixed dyes) for dye, color in pairs(dyes) do -- Fill recipe template with items local items = {[0] = "greek:marble_polished", dye} for _, recipe in pairs(data[2]) do local filled = {} for row in pairs(recipe) do filled[row] = {} for col in pairs(recipe[row]) do filled[row][col] = items[recipe[row][col]] end end minetest.register_craft({ output = minetest.itemstring_with_palette(("greek:marble_painted_%s_1 4"):format(type), color * 32), recipe = filled, }) end end end
port = {} port.GPoint = gincu.GVector2 port.GSize = gincu.GSize port.createPoint = function(x, y) local p = port.GPoint(); p.x = x; p.y = y; return p; end port.createScale = function(x, y) local p = port.GPoint(); p.x = x; p.y = y; return p; end port.createSize = function(w, h) local p = port.GSize(); p.width = w; p.height = h; return p; end
SampleScript = {} local Trans = nil; local Speed = 2; local InputLeft = 0; local InputRight = 0; local InputUp = 0; local InputDown = 0; local SwordTrans = nil; local function ChangeFacing(facingDir) Trans.Rotation.y = math.pi * facingDir; end function SampleScript:OnCreate() --Maybe try Scene:GetEntity(self.entity); self.Entity:GetSpriteRenderComponent().Offset.Pivot.x = 0.5; end function SampleScript:OnUpdate(ts) Trans = self.Entity:GetTransfromComponent().Transform; local dir = vec3:new(InputRight - InputLeft, InputDown - InputUp, 0.0); if(dir.x ~= 0.0 or dir.y ~= 0.0) then dir = dir:normalize(); end -- --Trans.Position:add(vec3:new(0.8, 0.0, 0.0)); Trans.Position:add(dir * Speed * ts * 60.0); end function SampleScript:OnKeyPressed(key) if(key == Keys.A) then InputLeft = 1; ChangeFacing(1); elseif (key == Keys.D) then InputRight = 1; ChangeFacing(0); elseif (key == Keys.S) then InputDown = 1; elseif (key == Keys.W) then InputUp = 1; end end function SampleScript:OnKeyReleased(key) if(key == Keys.A) then InputLeft = 0; elseif (key == Keys.D) then InputRight = 0; elseif (key == Keys.S) then InputDown = 0; elseif (key == Keys.W) then InputUp = 0; end end return SampleScript; -- function SampleScript:OnMessageReceived(entity, messageData) -- end
return (function(self, event) return api.RegisterEvent(self, event) end)(...)
HYPEX.MapLoader.Print = function(msg,val) val = val == 1 and "SUCCESS" || val == 2 and "FAIL" || val == 3 and "RUNNING" || "INFO" print("[HYPEX] [MapLoader] [" .. val .. "] " .. msg) end local print, config = HYPEX.MapLoader.Print, HYPEX.MapLoader.Config hook.Add("Initialize", "HYPEX.MAPLOADER.Execute", function() print("Getting Current map...", 3) local curMap = game.GetMap() print("Map is reporting as " .. curMap) print("Executing MapLoader") return config[curMap] and resource.AddWorkshop(config[curMap]) and print("Added map for WorkshopDL.", 1) || print("Could not find map in config.", 2) end) print("Loaded sv_execute.lua")
--- @class DungeonPokemonPlayer : DungeonPokemon a class that represents a player into a Dungeon. local DungeonPokemonPlayer = _C.DungeonPokemon:new_void() DungeonPokemonPlayer.__index = DungeonPokemonPlayer --- Creates a new DungeonPokemonPlayer. --- @param number number the PokéDex number of the Pokémon. --- @param level number the level. --- @param position Vector the Vector that represents the position. --- @param current_floor number the Floor on which the player is. function DungeonPokemonPlayer:new(number, level, position, current_floor) local new = setmetatable(_C.DungeonPokemon:new(number, level, position), self) new.current_floor = current_floor or 1 new.draw_position = _C.Vector:new(position:get_x(), position:get_y()) return new end --- Creates an DungeonPokemonPlayer with no atributes, useful for inheritance. --- @return DungeonPokemonPlayer a new void DungeonPokemonPlayer. function DungeonPokemonPlayer:new_void() return setmetatable(_C.DungeonPokemon:new_void(), self) end --- Returns the floor on which the player is. --- @return number the floor on which the player is. function DungeonPokemonPlayer:get_current_floor() return self.current_floor end --- Converts the DungeonPokemonPlayer into a string with its information. --- @return string a string with the object information. function DungeonPokemonPlayer:__tostring() return string.format( "DungeonPokemonPlayer = {number = %d, level = %d, position = (%d, %d)}", self.number, self.level, self.move_final_pos:get_x(), self.move_final_pos:get_y() ) end return DungeonPokemonPlayer
function initEvents() local m = Slipe.Shared.Elements.ElementManager.getInstance() local _elementEvents = Slipe.Shared.Elements.Events local _colShapeEvents = Slipe.Shared.CollisionShapes.Events local _sharedPickupEvents = Slipe.Shared.Pickups.Events local _markerEvents = Slipe.Shared.Markers.Events local events = {} -- 1: MTA event name -- 2: events namespace -- 3: table reference to static class, if static event (optional) if triggerServerEvent == nil then local _pickupEvents = Slipe.Server.Pickups.Events local _pedEvents = Slipe.Server.Peds.Events local _vehicleEvents = Slipe.Server.Vehicles.Events local _accountEvents = Slipe.Server.Accounts.Events local _gameEvents = Slipe.Server.Game.Events local _ioEvents = Slipe.Server.IO.Events -- Root Element events.onAccountDataChange = {"OnDataChange", _accountEvents, Slipe.Server.Accounts.Account} events.onBan = {"OnAdded", _accountEvents, Slipe.Server.Accounts.Ban} events.onUnban = {"OnRemoved", _accountEvents, Slipe.Server.Accounts.Ban} events.onPlayerConnect = {"OnPlayerConnect", _gameEvents, Slipe.Server.Game.GameServer} events.onResourcePreStart = {"OnPreStart", _gameEvents, Slipe.Server.Game.GameServer } events.onResourceStart = {"OnStart", _gameEvents, Slipe.Server.Game.GameServer} events.onResourceStop = {"OnStop", _gameEvents, Slipe.Server.Game.GameServer} events.onChatMessage = {"OnChatMessage", _ioEvents, Slipe.Server.IO.ChatBox} events.onDebugMessage = {"OnDebugMessage", _ioEvents, Slipe.Server.IO.MtaDebug} events.onSettingChange = {"OnSettingChange", _gameEvents, Slipe.Server.Game.GameServer} -- PhysicalElement events.onElementColShapeHit = {"OnCollisionShapeHit", _elementEvents} events.onElementColShapeLeave = {"OnCollisionShapeLeave", _elementEvents} events.onElementClicked = {"OnClicked", _elementEvents} events.onElementModelChange = {"OnModelChange", _elementEvents} events.onElementStartSync = {"OnStartSync", _elementEvents} events.onElementStopSync = {"OnStopSync", _elementEvents} -- Collisionshape events.onColShapeHit = {"OnHit", _colShapeEvents} events.onColShapeLeave = {"OnLeave", _colShapeEvents} -- Element events.onElementDestroy = {"OnDestroy", _elementEvents} -- Pickup events.onPickupHit = {"OnHit", _sharedPickupEvents} events.onPickupLeave = {"OnLeave", _sharedPickupEvents} events.onPickupSpawn = {"OnSpawn", _pickupEvents} events.onPickupUse = {"OnUse", _pickupEvents} -- Marker events.onMarkerHit = {"OnHit", _markerEvents} events.onMarkerLeave = {"OnLeave", _markerEvents} -- Ped events.onPedWasted = {"OnWasted", _pedEvents} events.onPedWeaponSwitch = {"OnWeaponSwitch", _pedEvents} -- Player events.onPlayerJoin = {"OnJoin", _pedEvents, Slipe.Server.Peds.Player} events.onConsole = {"OnConsole", _pedEvents} events.onPlayerACInfo = {"OnAcInfo", _pedEvents} events.onBan = {"OnBanAdded", _pedEvents} events.onPlayerBan = {"OnBanned", _pedEvents} events.onPlayerChangeNick = {"OnNicknameChanged", _pedEvents} events.onPlayerChat = {"OnChat", _pedEvents} events.onPlayerClick = {"OnClick", _pedEvents} events.onPlayerCommand = {"OnCommand", _pedEvents} events.onPlayerContact = {"OnContact", _pedEvents} events.onPlayerDamage = {"OnDamage", _pedEvents} events.onPlayerWasted = {"OnWasted", _pedEvents} events.onPlayerLogin = {"OnLogin", _pedEvents} events.onPlayerLogout = {"OnLogout", _pedEvents} events.onPlayerMarkerHit = {"OnMarkerHit", _pedEvents} events.onPlayerMarkerLeave = {"OnMarkerLeave", _pedEvents} events.onPlayerModInfo = {"OnModInfo", _pedEvents} events.onPlayerMute = {"OnMuted", _pedEvents} events.onPlayerUnMute = {"OnUnmuted", _pedEvents} events.onPlayerNetworkStatus = {"OnNetworkInteruption", _pedEvents} events.onPlayerPickupHit = {"OnPickupHit", _pedEvents} events.onPlayerPickupLeave = {"OnPickupLeave", _pedEvents} events.onPlayerPickupUse = {"OnPickupUse", _pedEvents} events.onPlayerPrivateMessage = {"OnPrivateMessage", _pedEvents} events.onPlayerQuit = {"OnQuit", _pedEvents} events.onPlayerScreenShot = {"OnScreenShot", _pedEvents} events.onPlayerSpawn = {"OnSpawn", _pedEvents} events.onPlayerStealthKill = {"OnStealthKill", _pedEvents} events.onPlayerTarget = {"OnTarget", _pedEvents} events.onPlayerVehicleEnter = {"OnVehicleEnter", _pedEvents} events.onPlayerVehicleExit = {"OnVehicleExit", _pedEvents} events.onPlayerVoiceStart = {"OnVoiceStart", _pedEvents} events.onPlayerVoiceStop = {"OnVoiceStop", _pedEvents} events.onPlayerWeaponFire = {"OnWeaponFire", _pedEvents} events.onPlayerWeaponSwitch = {"OnWeaponSwitch", _pedEvents} -- Vehicle events.onTrailerAttach = {"OnAttach", _vehicleEvents} events.onTrailerDetach = {"OnDetach", _vehicleEvents} events.onVehicleDamage = {"OnDamage", _vehicleEvents} events.onVehicleEnter = {"OnEnter", _vehicleEvents} events.onVehicleExit = {"OnExit", _vehicleEvents} events.onVehicleStartEnter = {"OnStartEnter", _vehicleEvents} events.onVehicleStartExit = {"OnStartExit", _vehicleEvents} events.onVehicleExplode = {"OnExplode", _vehicleEvents} events.onVehicleRespawn = {"OnRespawn", _vehicleEvents} else local _browserEvents = Slipe.Client.Browsers.Events local _ioEvents = Slipe.Client.IO.Events local _renderEvents = Slipe.Client.Rendering.Events local _gameEvents = Slipe.Client.Game.Events local _clientElementEvents = Slipe.Client.Elements.Events local _guiEvents = Slipe.Client.Gui.Events local _pedEvents = Slipe.Client.Peds.Events local _worldEvents = Slipe.Client.GameWorld.Events local _weaponEvents = Slipe.Client.Weapons.Events local _soundEvents = Slipe.Client.Sounds.Events local _vehicleEvents = Slipe.Client.Vehicles.Events -- Browser events.onClientBrowserCreated = {"OnCreated", _browserEvents} events.onClientBrowserCursorChange = {"OnCursorChange", _browserEvents} events.onClientBrowserDocumentReady = {"OnDocumentReady", _browserEvents} events.onClientBrowserInputFocusChanged = {"OnInputFocusChange", _browserEvents} events.onClientBrowserLoadingFailed = {"OnLoadFail", _browserEvents} events.onClientBrowserLoadingStart = {"OnLoadStart", _browserEvents} events.onClientBrowserNavigate = {"OnNavigate", _browserEvents} events.onClientBrowserPopup = {"OnPopup", _browserEvents} events.onClientBrowserResourceBlocked = {"OnResourceBlocked", _browserEvents} events.onClientBrowserTooltip = {"OnTooltip", _browserEvents} -- Resource root element events.onClientFileDownloadComplete = {"OnFileDownloadComplete", _gameEvents, Slipe.Client.Game.GameClient} events.onClientResourceStart = {"OnStart", _gameEvents, Slipe.Client.Game.GameClient} events.onClientResourceStop = {"OnStop", _gameEvents, Slipe.Client.Game.GameClient} -- Root element events.onClientKey = {"OnKey", _ioEvents, Slipe.Client.IO.Input} events.onClientRender = {"OnRender", _renderEvents, Slipe.Client.Rendering.Renderer} events.onClientPreRender = {"OnUpdate", _gameEvents, Slipe.Client.Game.GameClient} events.onClientHUDRender = {"OnHUDRender", _renderEvents, Slipe.Client.Rendering.Renderer} events.onClientBrowserWhitelistChange = {"OnWhiteListChange", _browserEvents, Slipe.Client.Browsers.Browser} events.onClientCharacter = {"OnCharacter", _ioEvents, Slipe.Client.IO.Input} events.onClientClick = {"OnClick", _ioEvents, Slipe.Client.IO.Cursor} events.onClientCursorMove = {"OnCursorMove", _ioEvents, Slipe.Client.IO.Cursor} events.onClientDoubleClick = {"OnDoubleClick", _ioEvents, Slipe.Client.IO.Cursor} events.onClientChatMessage = {"OnChatMessage", _ioEvents, Slipe.Client.IO.ChatBox} events.onClientDebugMessage = {"OnDebugMessage", _ioEvents, Slipe.Client.IO.MtaDebug} events.onClientMinimize = {"OnMinimize", _gameEvents, Slipe.Client.Game.GameClient} events.onClientPlayerNetworkStatus = {"OnNetworkInteruption", _gameEvents, Slipe.Client.Game.GameClient} events.onClientRestore = {"OnRestore", _gameEvents, Slipe.Client.Game.GameClient} -- Misc events.onClientExplosion = {"OnExplosion", _clientElementEvents} -- Colshape events.onClientColShapeHit = {"OnHit", _colShapeEvents} events.onClientColShapeLeave = {"OnLeave", _colShapeEvents} -- Element events.onClientElementDestroy = {"OnDestroy", _elementEvents} -- Physical Element events.onClientElementColShapeHit = {"OnCollisionShapeHit", _elementEvents} events.onClientElementColShapeLeave = {"OnCollisionShapeLeave", _elementEvents} events.onClientElementStreamIn = {"OnStreamIn", _elementEvents} events.onClientElementStreamOut = {"OnStreamOut", _elementEvents} -- Marker events.onClientMarkerHit = {"OnHit", _markerEvents} events.onClientMarkerLeave = {"OnLeave", _markerEvents} -- Gui events.onClientGUIAccepted = {"OnAccepted", _guiEvents} events.onClientGUIBlur = {"OnBlur", _guiEvents} events.onClientGUIFocus = {"OnFocus", _guiEvents} events.onClientGUIChanged = {"OnChanged", _guiEvents} events.onClientGUIClick = {"OnClick", _guiEvents} events.onClientGUIComboBoxAccepted = {"OnAccepted", _guiEvents} events.onClientGUIDoubleClick = {"OnDoubleClick", _guiEvents} events.onClientGUIMouseDown = {"OnMouseDown", _guiEvents} events.onClientGUIMouseUp = {"OnMouseUp", _guiEvents} events.onClientGUIMove = {"OnMove", _guiEvents} events.onClientGUIScroll = {"OnScroll"} events.onClientGUISize = {"OnResize", _guiEvents} events.onClientGUITabSwitched = {"OnOpen", _guiEvents} events.onClientMouseEnter = {"OnMouseEnter", _guiEvents} events.onClientMouseLeave = {"OnMouseLeave", _guiEvents} events.onClientMouseMove = {"OnMouseMove", _guiEvents} events.onClientMouseWheel = {"OnMouseWheel", _guiEvents} -- Pickup events.onClientPickupHit = {"OnHit", _sharedPickupEvents} events.onClientPickupLeave = {"OnLeave", _sharedPickupEvents} -- Ped events.onClientPedDamage = {"OnDamage", _pedEvents} events.onClientPedHeliKilled = {"OnHeliKilled", _pedEvents} events.onClientPedWasted = {"OnWasted", _pedEvents} events.onClientPedWeaponFire = {"OnWeaponFire", _pedEvents} events.onClientPedStep = {"OnStep", _pedEvents} -- Player events.onClientPlayerJoin = {"OnJoin", _pedEvents, Slipe.Client.Peds.Player} events.onClientConsole = {"OnConsole", _pedEvents} events.onPlayerChangeNick = {"OnNicknameChanged", _pedEvents} events.onClientPlayerChoke = {"OnChoke", _pedEvents} events.onClientPlayerDamage = {"OnDamage", _pedEvents} events.onClientPlayerHeliKilled = {"OnHeliKilled", _pedEvents} events.onClientPlayerPickupHit = {"OnPickupHit", _pedEvents} events.onClientPlayerPickupLeave = {"OnPickupLeave", _pedEvents} events.onClientPlayerQuit = {"OnQuit", _pedEvents} events.onClientPlayerRadioSwitch = {"OnRadioSwitch", _pedEvents} events.onClientPlayerSpawn = {"OnSpawn", _pedEvents} events.onClientPlayerStealthKill = {"OnStealthKill", _pedEvents} events.onClientPlayerStuntStart = {"OnStuntStart", _pedEvents} events.onClientPlayerStuntFinish = {"OnStuntFinish", _pedEvents} events.onClientPlayerTarget = {"OnTarget", _pedEvents} events.onClientPlayerVehicleEnter = {"OnVehicleEnter", _pedEvents} events.onClientPlayerVehicleExit = {"OnVehicleExit", _pedEvents} events.onClientPlayerVoicePause = {"OnVoicePaused", _pedEvents} events.onClientPlayerVoiceResumed = {"OnVoiceResumed", _pedEvents} events.onClientPlayerVoiceStart = {"OnVoiceStart", _pedEvents} events.onClientPlayerVoiceStop = {"OnVoiceStop", _pedEvents} events.onClientPlayerWasted = {"OnWasted", _pedEvents} events.onClientPlayerWeaponFire = {"OnWeaponFire", _pedEvents} events.onClientPlayerWeaponSwitch = {"OnWeaponSwitch", _pedEvents} -- Object events.onClientObjectBreak = {"OnBreak", _worldEvents} events.onClientObjectDamage = {"OnDamage", _worldEvents} -- Projectile events.onClientProjectileCreation = {"OnCreated", _weaponEvents} -- Sound events.onClientSoundBeat = {"OnBeat", _soundEvents} events.onClientSoundChangedMeta = {"OnMetaChanged", _soundEvents} events.onClientSoundFinishedDownload = {"OnDownloadFinished", _soundEvents} events.onClientSoundStarted = {"OnStart", _soundEvents} events.onClientSoundStopped = {"OnStop", _soundEvents} events.onClientSoundStream = {"OnStream", _soundEvents} -- Vehicle events.onClientTrailerAttach = {"OnAttach", _vehicleEvents} events.onClientTrailerDetach = {"OnDetach", _vehicleEvents} events.onClientVehicleCollision = {"OnCollision", _vehicleEvents} events.onClientVehicleDamage = {"OnDamage", _vehicleEvents} events.onVehicleEnter = {"OnEnter", _vehicleEvents} events.onVehicleExit = {"OnExit", _vehicleEvents} events.onVehicleStartEnter = {"OnStartEnter", _vehicleEvents} events.onVehicleStartExit = {"OnStartExit", _vehicleEvents} events.onVehicleExplode = {"OnExplode", _vehicleEvents} events.onVehicleRespawn = {"OnRespawn", _vehicleEvents} events.onClientVehicleNitroStateChange = {"OnNitroStateChange", _vehicleEvents} events.onClientPedHitByWaterCannon = {"OnPedHit", _vehicleEvents} events.onClientPlayerHitByWaterCannon = {"OnPedHit", _vehicleEvents} -- Custom Weapon events.onClientWeaponFire = {"OnFire", _weaponEvents} end for e, v in pairs(events) do addEventHandler(e, root, function(...) local src = m:GetElement1(source) local cls = v[3] and v[3] or src if cls and cls[v[1]] then cls[v[1]](src, v[2][v[1] .. "EventArgs"](...)) end end) end local allElementTypes = { "player", "ped", "water", "sound", "vehicle", "object", "pickup", "marker", "colshape", "blip", "radararea", "team", "projectile", "effect", "light", "searchlight", "weapon" } for _,type in ipairs(allElementTypes) do for _, element in pairs(getElementsByType(type)) do m:GetElement1(element) end end end
--------------------------------------------------------------------- -- Project: irc -- Author: MCvarial -- Contact: mcvarial@gmail.com -- Version: 1.0.3 -- Date: 31.10.2010 --------------------------------------------------------------------- local numberOfPlayers = 0 local players = {} local eventsAdded = false local events = { "onIRCMessage", "onIRCUserJoin", "onIRCUserPart", "onIRCUserQuit", "onIRCLevelChange", "onIRCUserChangeNick" } ------------------------------------ -- Irc client ------------------------------------ addCommandHandler("irc", function (player) if players[player] then return end if get("irc-client") == "true" then if not eventsAdded then addEvents() end local channels = {} for i,channel in ipairs (ircGetChannels()) do local users = {} for i,user in ipairs (ircGetChannelUsers(channel)) do table.insert(users,{name=ircGetUserNick(user),level=ircGetUserLevel(user,channel)}) end table.insert(channels,{name=ircGetChannelName(channel),users=users,topic=ircGetChannelTopic(channel)}) end players[player] = true numberOfPlayers = numberOfPlayers+1 triggerClientEvent(player,"ircStartClient",resourceRoot,channels) end end,false,false ) addEvent("ircStopClient",true) addEventHandler("ircStopClient",root, function (player) if players[player] then numberOfPlayers = numberOfPlayers-1 players[player] = nil end end ) addEvent("ircSendMessage",true) addEventHandler("ircSendMessage",root, function (player,channel,message) local channel = ircGetChannelFromName(channel) if channel then ircSay(channel,getPlayerName(player)..": "..tostring(message)) end end ) addEventHandler("onPlayerQuit",root, function () if players[source] then players[source] = nil end end ) function triggerClientIRCEvent (event,...) local args = {...} for i,arg in ipairs (args) do if isElement(arg) then if getElementType(arg) == "irc-user" then args[i] = ircGetUserNick(arg) end if getElementType(arg) == "irc-channel" then args[i] = ircGetChannelName(arg) end end end for player,_ in pairs (players) do triggerClientEvent(player,event,resourceRoot,unpack(args)) end end function addEvents () eventsAdded = true for i,event in ipairs (events) do addEvent(event) addEventHandler(event,root,function (...) if numberOfPlayers > 0 then triggerClientIRCEvent(event,source,...) end end) end end
-- Resizes windows require("../common") hs.window.animationDuration = 0 -- hs.loadSpoon("MiroWindowsManager") -- spoon.MiroWindowsManager:bindHotkeys({ -- up = {hyper, "up"}, -- right = {hyper, "right"}, -- down = {hyper, "down"}, -- left = {hyper, "left"}, -- fullscreen = {hyper, "f"} -- }) hs.hotkey.bind(hyper, "left", function() local win = hs.window.focusedWindow(); if not win then return end win:moveToUnit(hs.layout.left50) end) hs.hotkey.bind(hyper, "up", function() local win = hs.window.focusedWindow(); if not win then return end win:moveToUnit(hs.layout.maximized) end) hs.hotkey.bind(hyper, "down", function() local win = hs.window.focusedWindow(); if not win then return end win:moveToScreen(win:screen():next()) end) hs.hotkey.bind(hyper, "right", function() local win = hs.window.focusedWindow(); if not win then return end win:moveToUnit(hs.layout.right50) end)
local skynet = require 'skynet' local dns = require 'skynet.dns' skynet.start(function() -- dns.server() -- local ip, ips = dns.resolve('github.com') -- skynet.error('ip = ', ip) -- for _, v in pairs(ips) do -- skynet.error('v = ', v) -- end local dnsservice = skynet.localname('.dnsservice') local ipaddress = skynet.call(dnsservice, 'lua', 'reslove', 'gitbub.com', true) skynet.error('ipaddress = ', ipaddress) end)
" JAPANESE lol inoremap <leader>ja <C-v>u3041 inoremap <leader>ji <C-v>u3043 inoremap <leader>ju <C-v>u3045 inoremap <leader>je <C-v>u3047 inoremap <leader>jo <C-v>u3049 inoremap <leader>jka <C-v>u304b inoremap <leader>jki <C-v>u304d inoremap <leader>jku <C-v>u304f inoremap <leader>jke <C-v>u3051 inoremap <leader>jko <C-v>u3053 inoremap <leader>jsa <C-v>u3055 inoremap <leader>jsi <C-v>u3057 inoremap <leader>jsu <C-v>u3059 inoremap <leader>jse <C-v>u305b inoremap <leader>jso <C-v>u305d inoremap <leader>jta <C-v>u305f inoremap <leader>jchi <C-v>u3061 inoremap <leader>jtu <C-v>u3063 inoremap <leader>jte <C-v>u3065 inoremap <leader>jto <C-v>u3068 inoremap <leader>jna <C-v>u306a inoremap <leader>jni <C-v>u306b inoremap <leader>jnu <C-v>u306c inoremap <leader>jne <C-v>u306d inoremap <leader>jno <C-v>u306e inoremap <leader>jha <C-v>u306f inoremap <leader>jhi <C-v>u3072 inoremap <leader>jhu <C-v>u3075 inoremap <leader>jhe <C-v>u3078 inoremap <leader>jho <C-v>u307b inoremap <leader>jma <C-v>u307e inoremap <leader>jmi <C-v>u307f inoremap <leader>jmu <C-v>u3081 inoremap <leader>jme <C-v>u3082 inoremap <leader>jmo <C-v>u3083 inoremap <leader>jya <C-v>u3084 inoremap <leader>jyu <C-v>u3086 inoremap <leader>jyo <C-v>u3088 inoremap <leader>jra <C-v>u3089 inoremap <leader>jri <C-v>u308a inoremap <leader>jru <C-v>u308b inoremap <leader>jre <C-v>u308c inoremap <leader>jro <C-v>u308d inoremap <leader>jwa <C-v>u308f inoremap <leader>jwo <C-v>u3092 inoremap <leader>jn <C-V>u3093 " Temp obviously augroup StrismJapanese autocmd! autocmd BufEnter,BufNew *.jp inoremap <space> <space><space> " [Middle-West] autocmd BufEnter,BufNew *.jp inoremap jg ん autocmd BufEnter,BufNew *.jp inoremap jf く autocmd BufEnter,BufNew *.jp inoremap jd つ autocmd BufEnter,BufNew *.jp inoremap js ふ autocmd BufEnter,BufNew *.jp inoremap ja る " [Middle-East] autocmd BufEnter,BufNew *.jp inoremap fh う autocmd BufEnter,BufNew *.jp inoremap fj す autocmd BufEnter,BufNew *.jp inoremap fk ぬ autocmd BufEnter,BufNew *.jp inoremap fl む autocmd BufEnter,BufNew *.jp inoremap f; ゆ " [Diacritic-Middle-West] autocmd BufEnter,BufNew *.jp inoremap kf ぐ autocmd BufEnter,BufNew *.jp inoremap kd づ autocmd BufEnter,BufNew *.jp inoremap ks ぶ autocmd BufEnter,BufNew *.jp inoremap ls ぷ " [Diacritic-Middle-East] autocmd BufEnter,BufNew *.jp inoremap dj ず " [Upper-West] autocmd BufEnter,BufNew *.jp inoremap ut わ autocmd BufEnter,BufNew *.jp inoremap ur か autocmd BufEnter,BufNew *.jp inoremap ue た autocmd BufEnter,BufNew *.jp inoremap uw は autocmd BufEnter,BufNew *.jp inoremap uq ら " [Upper-East] autocmd BufEnter,BufNew *.jp inoremap ry あ autocmd BufEnter,BufNew *.jp inoremap ru さ autocmd BufEnter,BufNew *.jp inoremap ri な autocmd BufEnter,BufNew *.jp inoremap ro ま autocmd BufEnter,BufNew *.jp inoremap rp や " [Diacritic-Upper-West] autocmd BufEnter,BufNew *.jp inoremap ir が autocmd BufEnter,BufNew *.jp inoremap ie だ autocmd BufEnter,BufNew *.jp inoremap iw ば autocmd BufEnter,BufNew *.jp inoremap ow ぱ " [Diacritic-Upper-East] autocmd BufEnter,BufNew *.jp inoremap ru ざ " [Upper-Middle-West] autocmd BufEnter,BufNew *.jp inoremap jr き autocmd BufEnter,BufNew *.jp inoremap je ち autocmd BufEnter,BufNew *.jp inoremap jw ひ autocmd BufEnter,BufNew *.jp inoremap jq り " [Upper-Middle-East] autocmd BufEnter,BufNew *.jp inoremap fy い autocmd BufEnter,BufNew *.jp inoremap fu し autocmd BufEnter,BufNew *.jp inoremap fi に autocmd BufEnter,BufNew *.jp inoremap fo み " [Diacritic-Upper-Middle-West] autocmd BufEnter,BufNew *.jp inoremap kr ぎ autocmd BufEnter,BufNew *.jp inoremap ke ぢ autocmd BufEnter,BufNew *.jp inoremap kw び autocmd BufEnter,BufNew *.jp inoremap kw ぴ " [Diacritic-Upper-Middle-East] autocmd BufEnter,BufNew *.jp inoremap du じ " [Lower-West] autocmd BufEnter,BufNew *.jp inoremap nb を autocmd BufEnter,BufNew *.jp inoremap nv こ autocmd BufEnter,BufNew *.jp inoremap nc と autocmd BufEnter,BufNew *.jp inoremap nx へ autocmd BufEnter,BufNew *.jp inoremap mz ろ " [Lower-East] autocmd BufEnter,BufNew *.jp inoremap vn お autocmd BufEnter,BufNew *.jp inoremap vm そ autocmd BufEnter,BufNew *.jp inoremap v, の autocmd BufEnter,BufNew *.jp inoremap v. も autocmd BufEnter,BufNew *.jp inoremap v/ よ " [Diacritic-Lower-West] autocmd BufEnter,BufNew *.jp inoremap ,v ご autocmd BufEnter,BufNew *.jp inoremap ,c ど autocmd BufEnter,BufNew *.jp inoremap ,x べ autocmd BufEnter,BufNew *.jp inoremap .x ぺ " [Diacritic-Lower-East] autocmd BufEnter,BufNew *.jp inoremap cm ぞ " [Lower-Middle-West] autocmd BufEnter,BufNew *.jp inoremap jv け autocmd BufEnter,BufNew *.jp inoremap jc て autocmd BufEnter,BufNew *.jp inoremap jx ひ autocmd BufEnter,BufNew *.jp inoremap jz れ " [Lower-Middle-East] autocmd BufEnter,BufNew *.jp inoremap fn え autocmd BufEnter,BufNew *.jp inoremap fm せ autocmd BufEnter,BufNew *.jp inoremap f, ね autocmd BufEnter,BufNew *.jp inoremap f. め " [Diacritic-Lower-Middle-West] autocmd BufEnter,BufNew *.jp inoremap kv げ autocmd BufEnter,BufNew *.jp inoremap kc で autocmd BufEnter,BufNew *.jp inoremap kx び autocmd BufEnter,BufNew *.jp inoremap lx ぴ " [Diacritic-Lower-Middle-East] autocmd BufEnter,BufNew *.jp inoremap dm ぜ augroup end let g:aniseed#env = v:true let g:conjure#client#fennel#aniseed#aniseed_module_prefix = "aniseed."
#!/usr/bin/env lua -- vim: paste filetype=lua nospell ts=2 sw=2 sts=2 et : ---------- --------- --------- --------- --------- -- require "./lib" rogues()
require "test-setup" local lunit = require "lunit" local Cairo = require "oocairo" local assert_error = lunit.assert_error local assert_true = lunit.assert_true local assert_false = lunit.assert_false local assert_equal = lunit.assert_equal local assert_userdata = lunit.assert_userdata local assert_table = lunit.assert_table local assert_number = lunit.assert_number local assert_match = lunit.assert_match local assert_string = lunit.assert_string local assert_boolean = lunit.assert_boolean local assert_not_equal = lunit.assert_not_equal local module = { _NAME="test.font_opt" } function module.test_create () local opt = Cairo.font_options_create() assert_userdata(opt) assert_equal("cairo font options object", opt._NAME) assert_equal(nil, opt:status()) end function module.test_double_gc () local opt = Cairo.font_options_create() opt:__gc() opt:__gc() end function module.test_antialias () local opt = Cairo.font_options_create() assert_error("bad value", function () opt:set_antialias("foo") end) assert_error("missing value", function () opt:set_antialias(nil) end) assert_equal("default", opt:get_antialias()) for _, aa in ipairs{ "default", "none", "gray", "subpixel" } do opt:set_antialias(aa) assert_equal(aa, opt:get_antialias()) end -- Boolean values also select reasonable values. opt:set_antialias(true) assert_equal("default", opt:get_antialias()) opt:set_antialias(false) assert_equal("none", opt:get_antialias()) end function module.test_subpixel_order () local opt = Cairo.font_options_create() assert_error("bad value", function () opt:set_subpixel_order("foo") end) assert_error("missing value", function () opt:set_subpixel_order(nil) end) assert_equal("default", opt:get_subpixel_order()) for _, aa in ipairs{ "default", "rgb", "bgr", "vrgb", "vbgr" } do opt:set_subpixel_order(aa) assert_equal(aa, opt:get_subpixel_order()) end end function module.test_hint_style () local opt = Cairo.font_options_create() assert_error("bad value", function () opt:set_hint_style("foo") end) assert_error("missing value", function () opt:set_hint_style(nil) end) assert_equal("default", opt:get_hint_style()) for _, aa in ipairs{ "default", "none", "slight", "medium", "full" } do opt:set_hint_style(aa) assert_equal(aa, opt:get_hint_style()) end end function module.test_hint_metrics () local opt = Cairo.font_options_create() assert_error("bad value", function () opt:set_hint_metrics("foo") end) assert_error("missing value", function () opt:set_hint_metrics(nil) end) assert_equal("default", opt:get_hint_metrics()) for _, aa in ipairs{ "default", "off", "on" } do opt:set_hint_metrics(aa) assert_equal(aa, opt:get_hint_metrics()) end end function module.test_hash_and_equality () local opt1 = Cairo.font_options_create() local opt2 = Cairo.font_options_create() assert_number(opt1:hash()) assert_number(opt2:hash()) -- Different objects, but they are equal because they represent the -- same options, until they are set to hold different values. assert_not_equal(tostring(opt1), tostring(opt2)) assert_equal(opt1:hash(), opt2:hash()) assert_true(opt1 == opt2) opt1:set_antialias("none") assert_not_equal(opt1:hash(), opt2:hash()) assert_false(opt1 == opt2) end function module.test_copy () local opt1 = Cairo.font_options_create() opt1:set_antialias("gray") local opt2 = opt1:copy() assert_not_equal(tostring(opt1), tostring(opt2)) assert_equal(opt1:hash(), opt2:hash()) assert_true(opt1 == opt2) assert_equal("gray", opt1:get_antialias()) assert_equal("gray", opt2:get_antialias()) opt1:set_antialias("subpixel") assert_not_equal(opt1:hash(), opt2:hash()) assert_false(opt1 == opt2) end function module.test_merge () local opt1 = Cairo.font_options_create() local opt2 = Cairo.font_options_create() -- Give them a different non-default option each. opt1:set_antialias("gray") opt2:set_subpixel_order("bgr") opt1:merge(opt2) -- opt1 should now have both options set. assert_equal("gray", opt1:get_antialias()) assert_equal("bgr", opt1:get_subpixel_order()) -- opt2 should be unchanged. assert_equal("default", opt2:get_antialias()) assert_equal("bgr", opt2:get_subpixel_order()) end lunit.testcase(module) return module -- vi:ts=4 sw=4 expandtab
local ADDON, Addon = ... local Util = Addon.Util -- `HereticRaidInfo` implements a cache for player infos in raids. It's main -- use is to provide class coloring for the addon. The class uses a timer -- to continously index the players in the raid, which gets initialized in -- `RequestReindexing`. HereticRaidInfo:Update iterates over all players in -- the raid and records class information. The information may be persisted -- via Serialize/Deserialize to a saved variable. HereticRaidInfo = {} function HereticRaidInfo:Initialize() HereticRaidInfo.unitids = {} HereticRaidInfo.newPlayers = {} HereticRaidInfo.stale = "stale" HereticRaidInfo.timer = nil HereticRaidInfo.classCache = {} end local function RaidInfoUpdate() Util.dbgprint("Reindexing Raid through timer...") HereticRaidInfo:Update() end function HereticRaidInfo:ProvideReindexing() if HereticRaidInfo.timer then HereticRaidInfo.timer:Cancel() end HereticRaidInfo.timer = nil end function HereticRaidInfo:RequestReindexing() if (HereticRaidInfo.timer == nil) then Util.dbgprint("Request Reindexing...") HereticRaidInfo.timer = C_Timer.NewTimer(2, RaidInfoUpdate) end end function HereticRaidInfo:markStale() for i,v in pairs(HereticRaidInfo.unitids) do HereticRaidInfo.unitids[i] = HereticRaidInfo.stale end end function HereticRaidInfo:clearStale() for i,v in pairs(HereticRaidInfo.unitids) do if (v == HereticRaidInfo.stale ) then HereticRaidInfo.unitids[i] = nil end end end function HereticRaidInfo:recordByUnitId(unitId) local fullName = Util.GetFullUnitName(unitId) if (not fullName) then return end local first, _ = Util.DecomposeName(fullName) if (first == UNKNOWNOBJECT) then HereticRaidInfo:RequestReindexing() return end if HereticRaidInfo.unitids[fullName] == nil then table.insert(HereticRaidInfo.newPlayers, fullName) end HereticRaidInfo.unitids[fullName] = unitId if HereticRaidInfo.classCache[fullName] == nil then table.insert(HereticRaidInfo.classCache, fullName) end local class, classFileName = UnitClass(unitId) HereticRaidInfo.classCache[fullName] = {class, classFileName} end function HereticRaidInfo:GetPlayerClassColor(fullName) local cacheEntry = HereticRaidInfo.classCache[fullName] local class, classFileName if not cacheEntry then local name = Util.ShortenFullName(fullName) class, classFileName = UnitClass(name) if class and classFileName then HereticRaidInfo.classCache[fullName] = {class, classFileName} end else classFileName = cacheEntry[2] end local color = RAID_CLASS_COLORS[classFileName] return (color and color.colorStr) end function HereticRaidInfo:GetColoredPlayerName(fullName) local name = Util.ShortenFullName(fullName) local color = HereticRaidInfo:GetPlayerClassColor(fullName) if color then return "|c" .. color .. name .. "|r" else return name end end function HereticRaidInfo:printNewPlayers(unitId) local players = "" for i,v in pairs(HereticRaidInfo.newPlayers) do players = players .. " " .. v end Util.dbgprint ("New players (" .. table.getn(HereticRaidInfo.newPlayers) .. "):" .. players) end function HereticRaidInfo:GetNewPlayers() return HereticRaidInfo.newPlayers end function HereticRaidInfo:Update() HereticRaidInfo:ProvideReindexing() HereticRaidInfo:markStale() wipe(HereticRaidInfo.newPlayers) HereticRaidInfo.unitids [Util.GetFullUnitName("player")] = "player"; local numMembers = GetNumGroupMembers(LE_PARTY_CATEGORY_HOME) if (numMembers > 0) then local prefix = "raid" if ( not IsInRaid(LE_PARTY_CATEGORY_HOME) ) then prefix = "party" -- Party ids don't include the player, hence decrement. numMembers = numMembers - 1 end for index = 1, numMembers do local unitId = prefix .. index HereticRaidInfo:recordByUnitId(unitId) end end HereticRaidInfo:printNewPlayers() HereticRaidInfo:clearStale() end function HereticRaidInfo:GetUnitId(name) local id = HereticRaidInfo.unitids[name] if id then return id end local realm = GetRealmName():gsub("%s+", "") return HereticRaidInfo.unitids[name .. "-" .. realm] end function HereticRaidInfo:DebugPrint() for index,value in pairs(HereticRaidInfo.unitids) do Util.dbgprint(index," ",value) end end function HereticRaidInfo:Serialize(obj) obj.HereticRaidInfo = {} obj.HereticRaidInfo.classCache = HereticRaidInfo.classCache end function HereticRaidInfo:Deserialize(obj) if not obj.HereticRaidInfo then return end if not obj.HereticRaidInfo.classCache then return end local cache = HereticRaidInfo.classCache for k,v in pairs(obj.HereticRaidInfo.classCache) do if (#v == 2) then cache[k] = v end end end
return function(newENV) _ENV = newENV ----- DO NOT MODIFY ABOVE ----- -- A basic Enemy Entity script skeleton you can copy and modify for your own creations. comments = { "Smells like the work of an enemy stand.", "Poseur is posing like his life depends on it.", "Poseur's limbs shouldn't be moving in this way." } commands = { "Check", "Talk", "Flirt", "Pose", "Working?" } randomdialogue = { { "Check it out.", "Please" }, { "Check it out again.", "...", "For real now" }, { "I'll show you something.", "Trust me." }, { "Keep looking!", "Harder!", "I SAID HARDER!" }, "It's working." } AddAct("Check", "", 0) AddAct("Talk", "Little chit-chat", 0) AddAct("Flirt", "Seduce the enemy", 0, { "Kris" }) AddAct("Pose", "Show him who's cool!", 5, { "Ralsei" }) AddAct("Working?", "Is this working?", 50, { "Ralsei" }) hp = 250 atk = 10 def = 2 dialogbubble = "DRBubble" -- See documentation for what bubbles you have available. canspare = false check = "Check message goes here." -- CYK variables mag = 9001 -- MAGIC stat of the enemy targetType = "single" -- Specifies how many (or which) target(s) this enemy's bullets will target tired = false -- If true, the Player will be able to spare this enemy using the spell "Pacify" -- Check the "Special Variables" page of the documentation to learn how to modify this mess animations = { Hurt = { { 0 }, 1 , { next = "Idle" } }, Idle = { { 0, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 1 / 15, { } }, Spareable = { { 0, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 1 / 15, { } }, } -- Triggered just before computing an attack on this target function BeforeDamageCalculation(attacker, damageCoeff) -- Good location to set the damage dealt to this enemy using self.SetDamage() if damageCoeff > 0 then --SetDamage(666) end end -- Triggered when a Player attacks (or misses) this enemy in the ATTACKING state function HandleAttack(attacker, attackstatus) if currentdialogue == nil then currentdialogue = { } end if attackstatus == -1 then -- Player pressed fight but didn't press Z afterwards table.insert(currentdialogue, "Do no harm, " .. attacker.name .. ".\n") else -- Player did actually attack if attackstatus < 50 then table.insert(currentdialogue, "You're strong, " .. attacker.name .. "!\n") else table.insert(currentdialogue, "Too strong, " .. attacker.name .. "...\n") end end end posecount = 0 -- Triggered when a Player uses an Act on this enemy. -- You don't need an all-caps version of the act commands here. function HandleCustomCommand(user, command) local text = { "" } if command == "Check" then text = { name .. " - " .. atk .. " ATK " .. def .. " DEF\n" .. check } elseif command == "Talk" then if not tired then table.insert(comments, "Poseur has trouble staying up.") end tired = true currentdialogue = {"... *yawns*"} text = {"You try to talk with Poseur, but all you seem to be able to do is make him yawn."} elseif command == "Flirt" then currentdialogue = {"Thank you."} text = {"You tell Poseur you like his hairstyle.\nHe doesn't seem to mind."} elseif command == "Pose" then if posecount == 0 then currentdialogue = {"Not bad."} text = {"You posed dramatically."} elseif posecount == 1 then currentdialogue = {"Not bad at all...!"} text = {"You posed even more dramatically."} else if not canspare then table.insert(comments, "Poseur is impressed by your posing power.") end currentdialogue = {"That's it...!"} text = {"You posed so dramatically your anatomy became incorrect."} canspare = true SetCYKAnimation("Idle") -- Refresh the animation end posecount = posecount + 1 elseif command == "Working?" then currentdialogue = {"Good one."} text = {"Is this working?", "[func:SetFaceSprite,Players.Ralsei.Mad][voice:v_ralsei]IT'S WORKING!!!", "Poseur smiles and seems to calm down."} canspare = true SetCYKAnimation("Idle") -- refresh the animation end BattleDialog(text) end -- Function called whenever this entity's animation is changed. -- Make it return true if you want the animation to be changed like normal, otherwise do your own stuff here! function HandleAnimationChange(newAnim) local oldAnim = self.sprite["currAnim"] if newAnim == "Idle" and canspare then SetCYKAnimation("Spareable") return false end end ----- DO NOT MODIFY BELOW ----- end
return (function(self, scale) if scale > 0 then u(self).scale = scale end end)(...)
local helpers = {} local util = require('lapis.util') local lunamark = require('lunamark') local md_opts = {} local md_writer = lunamark.writer.html.new(md_opts) local md_parse = lunamark.reader.markdown.new(md_writer, md_opts) function helpers.is_same_user(session, username) return session.current_user.username == username end function helpers.is_logged_in(session) return session.current_user.id > 0 end function helpers.can_edit(page) if not page or not page.acl or not page.acl.mode then return false end return page.acl.mode > 1 end function helpers.cloak_mail(s) return s and string.gsub(tostring(s), '[%a%d]', 'x') or '' end --- Split a string using a pattern. -- @param str The string to search in -- @param pat The pattern to search with -- @see http://lua-users.org/wiki/SplitJoin function helpers.split(str, pat) local t = {} -- NOTE: use {n = 0} in Lua-5.0 local fpat = '(.-)' .. pat local last_end = 1 local s, e, cap = str:find(fpat, 1) while s do if s ~= 1 or cap ~= '' then t[#t+1] = cap end last_end = e+1 s, e, cap = str:find(fpat, last_end) end if last_end <= #str then cap = str:sub(last_end) t[#t+1] = cap end return t end function helpers.md_parse(s) return md_parse(s or '') end function helpers.clean_md(s) local md = s md = md:gsub("\r\n", "\n") md = md:gsub("\r", "\n") return util.trim(md) end function helpers.show_date(s) if not s then return '' end local m, x = string.match(s, '(%d+-%d+-%d+ %d+:%d+:%d+).(%d+)') return m and m or s end return helpers
----------------------------------------- -- INFORMATION -- Guide events and actions (e.g. "goto") ----------------------------------------- ----------------------------------------- -- LOCALIZED GLOBAL VARIABLES ----------------------------------------- local ZGV = _G.ZGV local GetCurrentMapIndex = _G.GetCurrentMapIndex local GuideViewer = _G.GuideViewer local GetNumPOIs = _G.GetNumPOIs local IsPOIWayshrine = _G.IsPOIWayshrine local GetPOIInfo = _G.GetPOIInfo local zo_plainstrfind = _G.zo_plainstrfind local GetPOIMapInfo = _G.GetPOIMapInfo local MAP_PIN_TYPE_POI_COMPLETE = _G.MAP_PIN_TYPE_POI_COMPLETE local GetLoreBookInfo = _G.GetLoreBookInfo local GetAchievementInfo = _G.GetAchievementInfo local GetAchievementCriterion = _G.GetAchievementCriterion local zo_loadstring = _G.zo_loadstring local zo_max = _G.zo_max local GoalProto = {} local Goal = ZGV.Class:New("Goal") local GoalProto_mt = { __index=Goal } local GOALTYPES = {} local empty_table = {} local tinsert, min, type, ipairs = table.insert, math.min, type, ipairs local L = ZGV.L local split = _G.zo_strsplit -- Parser functions local ParseMapXYDist = ZGV.Parser.ParseMapXYDist local MakeCondition = ZGV.Parser.MakeCondition local ParseQuest = ZGV.Parser.ParseQuest local ParseId = ZGV.Parser.ParseId local INDENT = "" ----------------------------------------- -- SAVED REFERENCES ----------------------------------------- ZGV.GoalProto = GoalProto ZGV.GOALTYPES = GOALTYPES ----------------------------------------- -- LOAD TIME SETUP ----------------------------------------- setmetatable( GOALTYPES, { __index = function() return empty_table end } ) ----------------------------------------- -- LOCAL FUNCTIONS ----------------------------------------- local function COLOR_LOC(s) return "|cffee77"..tostring(s).."|r" end local function COLOR_COUNT(s) return "|cffffcc"..tostring(s).."|r" end local function COLOR_ITEM(s) return "|caaeeff"..tostring(s).."|r" end local function COLOR_QUEST(s) return "|ceebbff"..tostring(s).."|r" end local function COLOR_NPC(s) return "|caaffaa"..tostring(s).."|r" end local function COLOR_TIP(s) return "|ceeeecc"..tostring(s).."|r" end ----------------------------------------- -- GOALHANDLERS ----------------------------------------- -- Pretty much Goal Types, but not exactly. GOALTYPES['only'] = { -- |only, |only if parse = function(self,params,step,data) local chunkcount = data.chunkcount local cond = params:match("^if%s+(.*)$") if cond then -- condition match and is a |only if local subject = chunkcount == 1 and step or self -- If this is the first chunk for this line, then it is a |only if for a step. local fun,err = MakeCondition(cond,true) if not fun then return err end subject.condition_visible_raw = cond subject.condition_visible = fun return false,"cancel goal" else self.requirement = params end end, } GOALTYPES['complete'] = { parse = function(self,params) --local chunkcount = data.chunkcount local cond = params:match("^if%s+(.*)$") if cond then -- condition match and is a |only if local subject = self -- If this is the first chunk for this line, then it is a |only if for a step. local fun,err = MakeCondition(cond,true) if not fun then return err end subject.condition_complete_raw = cond subject.condition_complete = fun else ZGV:Error("||complete needs 'if'. because.") self.action = nil -- rip in peace goal. wipe out because this is a command for steps. end end, } GOALTYPES['next'] = { parse = function(self,params) params = params:gsub("^\"(.-)\"$","%1") if params == "" then params = "+1" end self.next = params end, } GOALTYPES['nextreload'] = { parse = function(self,params) params = params:gsub("^\"(.-)\"$","%1") if params == "" then params = "+1" end self.nextreload = params end, } GOALTYPES['sticky'] = { parse = function(self) self.sticky = true end, } GOALTYPES['n'] = { parse = function(self) self.force_nocomplete = true end, } GOALTYPES['c'] = { parse = function(self) self.force_complete = true end, } GOALTYPES['sub'] = { parse = function(self) self.subgoal = true -- obsolete! do not use! end, } GOALTYPES['opt'] = { parse = function(self) self.optional = true end, } GOALTYPES['future'] = { parse = function(self) self.future = true end, } GOALTYPES['noway'] = { parse = function(self) self.force_noway = true end, } GOALTYPES['or'] = { parse = function(self,params) self.orlogic = params and tonumber(params) or 1 end, } GOALTYPES['override'] = { parse = function(self) self.override = true end, } GOALTYPES['tip'] = { parse = function(self,params) self.tooltip = params end, } GOALTYPES['q'] = { parse = function(self,params) self.quest, self.questcondtxt = ParseQuest(params) if not self.quest then return "no quest in parameter" end end, } GOALTYPES['_item'] = { parse = function(self,params) local count,objinfo,objid local obj = "" -- 4 Itemname##id count,objinfo = params:match("^([0-9]*)%s*(.*)$") if not count then objinfo = params end local function parse(str) -- check for plural local name,plural = str:match("^(.+)(%+)$") if plural then str = name end local tar, tarid = ParseId(str) if plural and tar then tar = GuideViewer("Specials").plural(tar) end return tar,tarid end self.count = tonumber(count) or 0 local mult = {split(",",objinfo)} if #mult > 1 then local targets = {} self.targets = targets for i,info in ipairs(mult) do -- Name##Id are split, parse each individually and then put it in the targets table. local tar,tarid = parse(info) tinsert(targets,{tar,tarid}) objid = objid or tarid -- TODO only the first targetid is returned. This isn't an issue 3/1/14 but if we strip out english names then will have to use multiple ids to create the obj. if tar then obj = obj .. tar .. (i<#mult and ", " or "") -- Append the target name to the obj, if not the last one then include a , end end else obj, objid = parse(objinfo) end -- now object##id self.target,self.targetid = obj,objid -- something missing? if not self.targetid and not self.target then return "no parameter" end end } GOALTYPES['count'] = { parse = function(self,params) self.count = tonumber(params) end } ----------------------------------------- -- GOALTYPES ----------------------------------------- GOALTYPES['goto'] = { parse = function(self,params,step,data) -- Called on the game's initial load local prevmap = data.prevmap local params2,title = params:match('^(.-)%s*"(.*)"') if title then params = params2 end local map,x,y,dist,err = ParseMapXYDist(params) if err then return err end self.map = (map or self.map or step.map or prevmap) if not self.map then return "'".. (self.action or "?") .."' has no map parameter, neither has one been given before." end self.x = x or self.x self.y = y or self.y -- Adjusting the speed between zone maps and non-zone maps self.dist = ZGV.Utils.DistanceOffsetForGoto(dist,self.dist) self.waytitle = title end, iscompletable = function(self) -- Called repeatedly local step = self.parentStep local all_gotos = true for _,goal in ipairs(step.goals) do if goal.action ~= "goto" -- A non-goto step or a goto step that is force_complete or goal.force_complete then all_gotos = false break end end return (self.force_complete or all_gotos) -- If the goto has a |c then it is completable. Or if there are only gotos present in this step. end, iscomplete = function(self) -- Called repeatedly -- if the player isn't in the zone map then adjust the distance -- GetGameTimeMilliseconds self.dist = ZGV.Utils.DistanceOffsetForIsComplete() local dist = ZGV.Pointer:GetDistToCoords(self.map,self.x,self.y) if self.dist and ( ( self.dist > 0 and dist < self.dist ) or ( self.dist < 0 and dist > self.dist ) ) then return true,true end return false,true end, } GOALTYPES['buy'] = GOALTYPES['collect'] GOALTYPES['gather'] = GOALTYPES['collect'] GOALTYPES['collect'] = { parse = GOALTYPES['_item'].parse, } GOALTYPES['kill'] = { parse = GOALTYPES['_item'].parse, } GOALTYPES['wayshrine'] = { parse = function(self,params,_,_) local mapid, map = string.match(params,"([^/]+)/([^/]+)") if tonumber(mapid) then self.wayshrine_zoneid = tonumber(mapid) self.wayshrine = map elseif mapid then -- string self.wayshrine_zoneid = ZGV.Pointer.Zones[mapid] and ZGV.Pointer.Zones[mapid].id self.wayshrine = map else self.wayshrine = params end end, iscomplete = function(self) if not self.wayshrine_POIIndex then local zoneid = self.wayshrine_zoneid -- screw it, search them all if there's none given. for zid = (zoneid or 1),(zoneid or 999) do -- oh whatever, less code is good. for i = 1,GetNumPOIs(zid) do if IsPOIWayshrine(zid,i) or (zid == 488 and i == 9) then -- West Gash Wayshrine is not a wayshrine. Go figure. local text,_,_,_ = GetPOIInfo(zid,i) local fb,fi = zo_plainstrfind(text,self.wayshrine) if fb and fi == 1 then self.wayshrine_zoneid = zid self.wayshrine_POIIndex = i if ZGV.db.profile.debug_wayshrines then ZGV:Debug("Found wayshrine '%s' on map id %d. POI %d.", self.wayshrine, self.wayshrine_zoneid, self.wayshrine_POIIndex) end break -- out of 2 loops end end end if self.wayshrine_POIIndex then break end end -- Index wasn't found... okay well we don't want to spam looking through POI's because it isn't efficient. Assign the index to 0 which returns an empty POI (no match) then reset it every 10s to try to match again. if not self.wayshrine_POIIndex then --ZGV:Debug("Wayshrine '%s' not found, will retry in 10s.", self.wayshrine) ZGV:Debug("Wayshrine '%s' not found.", self.wayshrine) self.wayshrine_POIIndex = 0 -- ZGV:ScheduleTimer(function() self.wayshrine_POIIndex = nil end, 10) end end local _,_,typ,_ = GetPOIMapInfo( self.wayshrine_zoneid, self.wayshrine_POIIndex, true ) --true=truthful call! don't be fooled by our own Pointer.lua and its foglight! if typ == MAP_PIN_TYPE_POI_COMPLETE then return true,true else return false,self.wayshrine_POIIndex > 0 end end, } GOALTYPES['learnskill'] = { parse = function(self,params) self.skillname = params end, } GOALTYPES['click'] = { parse = GOALTYPES['_item'].parse, } GOALTYPES['accept'] = { parse = function(self,params) if not params then return "no quest parameter" end self.quest = ParseId(params) -- legacy. Get rid of the ID. if not self.quest then return "no quest parameter" end end, iscomplete = function(self) return (ZGV.Quests:HasQuest(self.quest) or ZGV.Quests:IsQuestComplete(self.quest)) , true end, } GOALTYPES['turnin'] = { parse = GOALTYPES['accept'].parse, iscomplete = function(self) local completed = ZGV.Quests:IsQuestComplete(self.quest) local hasQuest = ZGV.Quests:HasQuest(self.quest) return completed,hasQuest end, } GOALTYPES['talk'] = { parse = function(self,params) self.npc,self.npcid = ParseId(params) if not self.npc and not self.npcid then return "no npc" end end, } GOALTYPES['equip'] = { parse = GOALTYPES['_item'].parse, } GOALTYPES['confirm'] = { parse = function(self,params) self.action = self.action or "confirm" self.always = (params == "always") end, iscomplete = function(self) local complete = not not self.clicked return complete,true end, onclick = function(self) -- damn, special functionality HERE of all places... self.clicked = true if self.nextreload then ZGV.sv.char.guidename = self.nextreload ZGV.sv.char.step = 1 _G.ReloadUI() return true -- oh wait... end end, } GOALTYPES['lorebook'] = { parse = function(self,params,_,_) if not params then return "no lorebook parameter" end local _,cat,col,book = params:match("^(.-)(%d+)/(%d+)/(%d+)$") self.lorebook_cat = tonumber(cat) self.lorebook_col = tonumber(col) self.lorebook_book = tonumber(book) if not self.lorebook_book then return "no lorebook cat/col/book parameter" end end, iscomplete = function(self) local _,_,known = GetLoreBookInfo(self.lorebook_cat,self.lorebook_col,self.lorebook_book) return known , true end, gettext = function(self) local title = GetLoreBookInfo(self.lorebook_cat,self.lorebook_col,self.lorebook_book) return L['stepgoal_lorebook']:format(title) end } GOALTYPES['achieve'] = { parse = function(self,params) if not params then return "no achieve parameter" end self.achieve_id,self.achieve_crit = params:match("(%d+)/(%d+)$") if not self.achieve_crit then self.achieve_id = params:match("(%d+)$") end self.achieve_id = tonumber(self.achieve_id) self.achieve_crit = tonumber(self.achieve_crit) if not self.achieve_id then return "no achieve id" end end, iscomplete = function(self,override_achieve_id,override_achieve_crit) local _,_,_,_,isCompleted,_,_ = GetAchievementInfo(override_achieve_id or self.achieve_id) if isCompleted or not (override_achieve_crit or self.achieve_crit) then return isCompleted , true else local _,numcom,numreq = GetAchievementCriterion(override_achieve_id or self.achieve_id,override_achieve_crit or self.achieve_crit) return numcom == numreq, true, (numcom/zo_max(1,(numreq or 1))) end end, gettext = function(self) local name if not self.achieve_crit then name = GetAchievementInfo(self.achieve_id) else name = GetAchievementCriterion(self.achieve_id,self.achieve_crit) end return L['stepgoal_achieve']:format(name) end } GOALTYPES['ding'] = { parse = function(self,params) self.dinglevel = tonumber(params) end, iscomplete = function(self) return ZGV.Utils.GetPlayerPreciseLevel()>=self.dinglevel,true end, } GOALTYPES['text'] = { parse = function(self,params) -- highlight _text_ params = params:gsub("_(.-)_","|cffee88%1|r") self.text = params end, } ----------------------------------------- -- GUIDEPROTO FUNCTIONS ----------------------------------------- function GoalProto:New() local goal = {} setmetatable(goal,GoalProto_mt) return goal end ----------------------------------------- -- GOAL CLASS FUNCTIONS ----------------------------------------- function Goal:GetQuest() if not self.quest then return end return ZGV.Quests:GetQuest(self.quest) end function Goal:GetQuestGoalStatus() if not self.quest then return false,"no quest" end return ZGV.Quests:GetCompletionStatus(self.quest,self.questcondtxt) end function Goal:GetQuestGoalCounts() local _,_,expl,curv,maxv,_ = self:GetQuestGoalStatus() if expl ~= "cond completion" then return end if not curv then return end local goalcountnow,goalcountneeded,remaining goalcountnow = curv or 0 goalcountneeded = min(self.count or 9999,maxv or 9999) -- If limit is < maxvalue then prefer that to allow guide to dictate only collecting a certain number in a single area. remaining = goalcountneeded-goalcountnow if remaining <= 0 then remaining = goalcountneeded end if goalcountneeded == 1 then remaining = nil end -- If we only need 1 then don't need to explictly show a number. Nil this out to not show a num return goalcountnow,goalcountneeded,remaining end function Goal:GetText() local GOALTYPE = GOALTYPES[self.action] local text = "?" local progtext local _done local complete,ext local goalcountnow,goalcountneeded,remaining local base, data if self.quest then -- Is there a quest to go with this step? goalcountnow,goalcountneeded,remaining = self:GetQuestGoalCounts() end complete,ext = self:IsComplete() _done = complete and "_done" or "" if self.text then --TODO expand on this if straight self.text doesn't cut it. And what is it doing? --~~ This handles {scriptable text entries} in goal texts. local nsub = 1 -- Generates a parser proc with said behaviour, to evade calling loadstring too much local function make_parser(parser) -- function to generate code return function(s) if not self.textsubs then self.textsubs = {} end local f = self.textsubs[nsub] if not f then f = parser(s) self.textsubs[nsub] = f end nsub = nsub + 1 if type(f)=="function" then ZGV.Parser.ConditionEnv._SetLocal(self.parentStep.parentGuide,self.parentStep,self) return tostring(f()) else return tostring(f) end end end local function parser_simple(s) local fun,err = zo_loadstring(s:find("return") and s or "return "..s) if fun then setfenv(fun,ZGV.Parser.ConditionEnv) return fun else return "("..err..")" end end local function parser_ternary(s) local condcode,a,b = s:match("(.*)%?%?(.*)::(.*)") if condcode and a and b then local condfun,err = zo_loadstring(condcode:find("return") and condcode or "return "..condcode) if condfun then local fun = function() -- Generating a real worker function return condfun() and a or b end setfenv(fun,ZGV.Parser.ConditionEnv) return fun else return "("..err..")" end else return "(Wrong conditional syntax)" end end -- TODO support nesting of conditionals text = self.text :gsub("{([^}]-%?%?[^}]-::[^}]-)}",make_parser(parser_ternary)) :gsub("{(.-)}",make_parser(parser_simple)) :gsub("#(%d+)#",COLOR_COUNT(remaining)) elseif self.action == "tip" then text = self.tooltip elseif self.action == "accept" then base = L["stepgoal_accept".._done] data = COLOR_QUEST(L["questtitle"]:format(self.quest or "?quest?")) elseif self.action == "turnin" then base = L["stepgoal_turnin".._done] data = COLOR_QUEST(L["questtitle"]:format(self.quest or "?quest?")) elseif self.action == "talk" then base = L["stepgoal_talk".._done] data = COLOR_NPC(self.npc) elseif self.action == "kill" then base = L["stepgoal_kill".._done] data = COLOR_NPC(self.target) elseif self.action == "equip" then base = L["stepgoal_equip".._done] data = COLOR_NPC(self.target) elseif self.action == "collect" then base = L["stepgoal_collect".._done] data = COLOR_NPC(self.target) elseif self.action == "buy" then base = L["stepgoal_buy".._done] data = COLOR_NPC(self.target) elseif self.action == "gather" then base = L["stepgoal_gather".._done] data = COLOR_NPC(self.target) elseif self.action == "learnskill" then base = L["stepgoal_learnskill".._done] data = COLOR_NPC(self.target) elseif self.action == "confirm" then text = L["stepgoal_confirm"] elseif self.action == "click" then base = L["stepgoal_click".._done] data = COLOR_ITEM(self.target) elseif self.action == "wayshrine" then base = L["stepgoal_wayshrine".._done] data = COLOR_NPC(self.wayshrine) elseif self.action == "goto" then local curZone = _G.GetMapName() local mapname = ZGV.Pointer.Zones[self.map] and ZGV.Pointer.Zones[self.map].name or self.map or curZone.."(?)" if mapname ~= curZone then if self.x and self.y then -- different map text = COLOR_LOC(L['map_coords']:format(ZGV.Utils.Delocalize(mapname),self.x * 100,self.y * 100)) -- and coords else text = COLOR_LOC(ZGV.Utils.Delocalize(mapname)) -- just the map end else if self.x and self.y then text = COLOR_LOC(L['coords']:format(self.x*100,self.y * 100)) -- same map else text = COLOR_LOC(ZGV.Utils.Delocalize(mapname)) -- just the map end end if self.waytitle then text = self.waytitle.." ("..text..")" end text = ( L["stepgoal_goto"]):format( text ) end if base and data then local num = remaining or self.count if num and num > 1 then data = num .. " " .. data end text = base:format(data) end if text == "?" and GOALTYPE.gettext then text = GOALTYPE.gettext(self) end if text == "?" and L["stepgoal_"..self.action] then -- fallback: just plain text in L text = L["stepgoal_"..self.action] end -- Add the indent! local indent = INDENT:rep(self.indent or 0) text = text and indent..text -- apply the (2/4) totals now, or not if goalcountnow and goalcountneeded and goalcountneeded>0 then progtext=L["completion_goal"]:format(goalcountnow,goalcountneeded) end if progtext then local col1,col2 if complete then col1,col2 = "","" elseif ext then col1,col2 = " |cffbbbb","|r" else col1,col2 = " |caaaaaa","|r" end text = text .. col1 .. progtext .. col2 end return text end function Goal:tostring() return self:GetText() end function Goal:GetTipText() if not self.tooltip then return end local indent = INDENT:rep(self.indent or 0) local text = indent..COLOR_TIP(self.tooltip) return text end function Goal:IsVisible() if self.hidden then return false end if self.condition_visible then if self.condition_visible_raw == "default" then -- oo, special case: show this only if no others are visible! for _,goal in ipairs(self.parentStep.goals) do if goal ~= self and goal.condition_visible and goal:IsVisible() then return false end end return true else ZGV.Parser.ConditionEnv._SetLocal(self.parentStep.parentGuide,self.parentStep,self) local ok,ret = pcall(self.condition_visible) if ok then return ret else ZGV:Error("Error in step %s, goal %s, only if %s: %s", self.parentStep.num, self.num, self.condition_visible_raw or "", ret:gsub("\n.*","")) end end end if self.requirement then return ZGV.Utils.RaceClassMatch(self.requirement) end return true end -- returns: true = complete, false = incomplete -- second return: true = completable, false = incompletable function Goal:IsComplete() -- is now a wrapper for sticky reasons. if self.sticky_complete then return true,true end local iscomplete,ispossible,v1,v2,v3 = self:IsCompleteCheck() if iscomplete and self.sticky then self.sticky_complete=true end if self:IsCompletable() then if iscomplete and not self.was_complete then self:OnComplete() elseif not iscomplete and self.was_complete then self:OnDiscomplete() end self.was_complete=iscomplete end if self.map then self:CheckVisited() end -- TODO: this is a bad place to call other checks. return iscomplete,ispossible,v1,v2,v3 end function Goal:OnComplete() if self.parentStep.current_waypoint_goal == self.num then ZGV.Pointer:CycleWaypoint(1,"no cycle") end end function Goal:OnDiscomplete() end function Goal:CheckVisited() if self.map then if self.status == "incomplete" then return end local isvisited = GOALTYPES['goto'].iscomplete(self) -- "test as if it's a goto step" if isvisited and not self.was_visited then self:OnVisited() elseif not isvisited and self.was_visited then self:OnDevisited() end self.was_visited=isvisited end end function Goal:OnVisited() self.parentStep.current_waypoint_goal = self.num ZGV.Pointer:CycleWaypoint(1,"no cycle") end function Goal:OnDevisited() end function Goal:IsCompleteCheck() -- If the quest is complete then all related goals are complete. local iscomplete,ispossible,explanation,curv,maxv,debugs if self.condition_complete then ZGV.Parser.ConditionEnv._SetLocal(self.parentStep.parentGuide, self.parentStep, self) local ok,iscomplete = pcall(self.condition_complete) if ok then if iscomplete then return true,true else -- fall through! end else ZGV:Error("Error in step %s, goal %s, complete if %s: %s", self.parentStep.num, self.num, self.condition_complete_raw or "", iscomplete:gsub("\n.*","")) end end if self.quest and self.action~="accept" and self.action~="turnin" then -- let accept goals complete on their own repeat ZGV:Debug("&goal completing..............") iscomplete,ispossible,explanation,curv,maxv,debugs = ZGV.Quests:GetCompletionStatus(self.quest, self.questcondtxt) ZGV:Debug("&goal completion: complete:|cffffff%s|r, possible:|cffffff%s|r, why:|cffffff%s|r ... match: |cffaaee%s|r",tostring(iscomplete),tostring(ispossible),tostring(explanation),tostring(debugs)) local _ = ZGV.Quests:GetQuest(self.quest) if iscomplete then -- complete means complete, leave it at that! if explanation == "quest complete" or explanation == "quest POI complete" or explanation == "past stage" or explanation == "cond recently completed" then return "past",true end return true,true,self.count and 1 elseif false and explanation == "step END" and self.optstep then return true,true elseif false and explanation == "future stage" then if self.future then break end -- fall through return false,false elseif explanation == "not in journal" then if self.future and GOALTYPES[self.action].iscomplete then break end -- fall through if can complete if self.future and not GOALTYPES[self.action].iscomplete then -- pretend completable. EVIL. SHAME. return false,true, "future step? pretend completable. shame!" end return false,false elseif false and explanation == "no stagenum" or explanation == "stage completion" then -- quest in journal, but no stage mentioned, and surely not complete -- or, stage mentioned, but it's current, so if self:IsCompletable("by type") then break end -- fall through return iscomplete,ispossible -- always false,true elseif explanation == "step completion" or explanation == "step overrides cond" then if ispossible and self:IsCompletable("by type") then break end -- fall through return iscomplete,ispossible elseif explanation == "cond completion" then -- possible, countable if self.count and self.count > 0 and curv then -- If we only want a specific amount of items at this point then allow them to collect 1/5 and complete this step. if curv >= self.count then iscomplete = true end end if iscomplete then return true, ispossible, (curv and curv / (self.count or maxv or 1)) end if self:IsCompletable("by type") then break end -- let the goto complete it! return false, ispossible, (curv and curv / (self.count or maxv or 1)) elseif false and explanation == "current stage unknown" then -- RAISE ALARM? return false,false elseif self.future and not GOALTYPES[self.action].iscomplete then -- simulate completability. EVIL. return false,true, "future step? pretend completable" elseif self.future then -- how did we end up here? break else return iscomplete,ispossible end -- letting possibles through. They'll be either current-stages-only, or incomplete vague objectives. until false end if self.achieve_id then iscomplete,ispossible = GOALTYPES['achieve'].iscomplete(self) if iscomplete then return true,true end end if self.lorebook_book then -- it's lore-based, then? iscomplete,ispossible = GOALTYPES['lorebook'].iscomplete(self) if iscomplete then return true,true end end local giscomplete,gispossible local GOALTYPE = GOALTYPES[self.action] if GOALTYPE and GOALTYPE.iscomplete then giscomplete,gispossible = GOALTYPE.iscomplete(self) end return giscomplete or iscomplete,gispossible or ispossible end function Goal:IsCompletable(by_type) local GOALTYPE = GOALTYPES[self.action] -- All goals have goaltypes if self.force_nocomplete then return false end -- the almighty |n if self.condition_complete then return true end -- we have a script, so obey if not by_type and self.action ~= "goto" then if self.quest or self.lorebook or self.achieve_id then return true end -- there is a quest/lore/achieve associated with this goal so can be completed. Unless it's a goto. These are only completed by |c. end if GOALTYPE.iscompletable then return GOALTYPE.iscompletable(self) end -- This may or maynot be there if it is only sometimes completable. if GOALTYPE.iscomplete then return true end -- There is a way to complete this goal -- Nothing above? Okay can't complete. return false end function Goal:UpdateStatus() self.status = self:GetStatus() return self.status end function Goal:GetQuest() if self.quest then return ZGV.Quests:GetQuest(self.quest) end end function Goal:GetStatus() -- a good place to check for quest coordinates as any... if self.action == "goto" and self.quest and self.questcondtxt then local quest = ZGV.Quests:GetQuest(self.quest) if quest and quest.steps then local snum,cnum = quest:FindStepCond(self.questcondtxt) if snum then local cond = quest.steps[snum] and quest.steps[snum].conditions and quest.steps[snum].conditions[cnum] if cond and cond.x and cond.x ~= self.x then self.x,self.y = cond.x,cond.y self.m = ZGV.Pointer:GetMapTex() ZGV:SetWaypoint() -- update, really end end end end if not self:IsVisible() then return "hidden" end if not self:IsCompletable() then return "passive" end local iscomplete,_,progress,_ = self:IsComplete() if iscomplete then return "complete" end return "incomplete",progress end function Goal:OnClick() if GOALTYPES[self.action].onclick then return GOALTYPES[self.action].onclick(self) end end ----------------------------------------- -- DEBUG ----------------------------------------- function GoalProto:Debug(...) local str = ... ZGV:Debug("&goal "..str, select(2,...) ) end
local queue = require("base.queue") local M ={} M.__index = M function M.new( agent) local o = { previous = nil, current = nil, agent = agent, states = queue.new(), ispause = false } return setmetatable(o, M) end function M:setpause(pause) self.ispause = pause if self.current then self.current:setpause(pause) end end function M:addfirst( state ) if state == nil then return end state:setmachine(self) if self.states:count() < 2 then self.states:enqueue(state) else table.insert( self.states.items, 2, state ) end self:checknext() end function M:addlast( state ) if state == nil then return end state:setmachine(self) self.states:enqueue(state) self:checknext() end function M:checknext() if self.states:count() > 1 and self.states.items[2].weight > self.states.items[1].weight then if self.current.isdone ==false then self.current:done() end end end function M:getfirst(type) for i,v in ipairs(self.states.items) do if v.type == type then return v end end return nil end function M:getlast( type ) for i = self.states:count(), 1, -1 do if self.states.items[i].type == type then return self.states.items[i] end end return nil end function M:donext() if self.current ~= nil then if self.current.iscancel then self.current:cancel() end self.current:exit() self.states:dequeue() end if self.previous ~= nil then self.previous:destroy() end self.previous = self.current self.current = nil while self.states:count() > 0 do if self.states:peek():isvalid() == false then local state = self.states:dequeue() state:destroy() else break end end if self.states:count() > 0 then self.current = self.states:peek() self.current:enter() end end function M:update(delta) if self.ispause then return end if self.current == nil or self.current.isdone or (self.states:count() > 1 and self.states.items[2].weight > self.current.weight) then self:donext() end if self.current ~= nil then self.current:execute(delta) end end function M:clear( ) -- body end return M
local http = require("http") local plugin = require("plugin") local time = require("time") local plugin_body = [[ local http = require("http") local err = http.serve_static("./test/data", "127.0.0.1:2115") if err then error(err) end ]] local p = plugin.do_string(plugin_body) p:run() time.sleep(1) if not p:is_running() then error(p:error()) end local client = http.client() local req, err = http.request("GET", "http://127.0.0.1:2115") if err then error(err) end local resp, err = client:do_request(req) if err then error(err) end if not(resp.code == 200) then error("resp code") end if not(resp.body == "OK") then error("resp body, get:"..resp.body) end
local Enabled = true script.Parent.Touched:connect(function(hit) if Enabled then local human = hit.Parent:FindFirstChild("Humanoid") if human then local Player = game.Players:GetPlayerFromCharacter(human.Parent) if Player ~= nil then Enabled = false script.Parent.Open:Play() wait(0.3) Instance.new("Sparkles",script.Parent) local Amount = script.Parent.PointsBase.Value*(math.random(50,150)/100) spawn(function() game.PointsService:AwardPoints(Player.userId,Amount) end) game.ReplicatedStorage.Currency:FireClient(Player,script.Parent,"+"..Amount.."RP",Color3.new(0.4,0.5,1),2,245520987) local chance = math.random(3,6) if chance == 5 then local Box = game.ReplicatedStorage.Boxes.Unreal game.ReplicatedStorage.CurrencyPopup:FireClient(Player,Box.Name.." Box",Box.BoxColor.Value,"rbxassetid://"..Box.ThumbnailId.Value) --game.ReplicatedStorage.Hint:FireClient(Player,"Woah! You found an unreal box!") Player.Crates.Unreal.Value = Player.Crates.Unreal.Value + 1 spawn(function() wait(0.3) game.ReplicatedStorage.Currency:FireClient(Player,script.Parent,"+1 Unreal Box",Color3.new(17/25, 4/25, 1),3,131144461) end) end wait(0.35) script.Parent.Anchored = true script.Parent.CanCollide = false for i,v in pairs(script.Parent:GetChildren()) do if v:IsA("Decal") then v:Destroy() end end for i=1,10 do script.Parent.Transparency = script.Parent.Transparency + 0.1 wait(0.1) end wait(2.5) script.Parent:Destroy() end end end end)
-- startup (runs on boot) -- load the APIs os.loadAPI("/utils/TextUtils") os.loadAPI("/utils/FileUtils") -- variables userServerID = 43 -- fin -- clear the terminal term.clear() term.setCursorPos(1,1) -- print the servers ID to allow it to be run on any server print("Email Server (ID: "..os.getComputerID()..")") -- open networking if a modem is attached on the back rednet.open("back") -- email is {id,recipient,sender,subj,body,read} -- main loop, don't exit (but Ctrl + T causes interupt) while true do -- enable light on the bottom to show that server is idle redstone.setOutput("bottom",true) -- wait for network message s,m = rednet.receive() -- disable light to show that server is processing request redstone.setOutput("bottom",false) -- can receive: -- COUNT (unread count, send username too) -- FETCHHEAD (same as fetch but no message body after) -- FETCH (sends count then all mail one at a time?, 2 parts (header+body)) -- SEND (Verifies recipient & sender, also takes subject then asks for message) -- can send: -- COUNT (number of unread) -- HEADER (sender, recipient, subject) -- BODY (message body after header) -- READY (if ready for response) -- ERROR (sends if an error occured) -- user requested just the number of unread emails if TextUtils.startsWith(m, "COUNT") then ms = TextUtils.split(m,":") user = ms[2] -- ask user to verify they are logged in rednet.send(userServerID, "VERIFY:"..user..":"..tostring(s)) -- wait 5 seconds for response, if none then timeout s1, m1 = rednet.receive(5) if m1 == nil or TextUtils.startsWith(m1,"FAIL") then rednet.send(s, "ERROR:Failed to verify user") else -- verified, process the request if not fs.exists("/mailto/"..user) then rednet.send(s, "COUNT:0") else usersMail = FileUtils.readVariableFile("/mailto/"..user) unread = 0 for i=1,#usersMail do TOPKEK = usersMail[i] if TOPKEK[6] == true then unread = unread + 1 end end -- send the size of the users email inbox back rednet.send(s, "COUNT:"..tostring(unread)) end end -- get the headers for the emails, to show on the inbox elseif TextUtils.startsWith(m, "FETCHHEAD") then ms = TextUtils.split(m,":") user = ms[2] -- standard user verification rednet.send(userServerID, "VERIFY:"..user..":"..s) s1,m1 = rednet.receive(3) if m1 == nil or TextUtils.startsWith(m1,"FAIL") then rednet.send(s,"ERROR:Failed to verify user") else -- send the email count then sent that many email headers if not fs.exists("/mailto/"..user) then rednet.send(s,"COUNT:0") else usersMail = FileUtils.readVariableFile("/mailto/"..user) rednet.send(s,"COUNT:"..tostring(#usersMail)) for i=1,#usersMail do thisMail = usersMail[i] headerStr = thisMail[1]..":"..thisMail[2]..":"..thisMail[3]..":"..thisMail[4]..":"..tostring(thisMail[6]) rednet.send(s,"HEADER:"..headerStr) end end end -- user requests an email so send the header seperate then the body elseif TextUtils.startsWith(m, "FETCH") then -- fetch:user:id ms = TextUtils.split(m,":") user = ms[2] id = tonumber(ms[3]) -- standard verification rednet.send(userServerID,"VERIFY:"..user..":"..s) s1,m1 = rednet.receive(3) if m1 == nil or TextUtils.startsWith(m1,"FAIL") then rednet.send(s,"ERROR:Failed to verify user") else if not fs.exists("/mailto/"..user) then rednet.send(s,"ERROR:No mail found.") else -- find the email then send the header as before then send the whole body userMail = FileUtils.readVariableFile("/mailto/"..user) sent = false for i=1,#userMail do thisMail = userMail[i] if id == tonumber(thisMail[1]) then rednet.send(s,"HEADER:"..thisMail[1]..":"..thisMail[2]..":"..thisMail[3]..":"..thisMail[4]) thisMail[6] = false userMail[i] = thisMail sent = true FileUtils.writeVariableFile("/mailto/"..user, userMail) rednet.send(s,"BODY:"..thisMail[5]) end end if not sent then rednet.send(s,"ERROR:Failed to find mail") end end end -- user wants to send new email elseif TextUtils.startsWith(m, "SEND") then -- SEND:sender,recipient,subj ms = TextUtils.split(m,":") user = ms[2] recip = ms[3] subj = ms[4] -- standard verification rednet.send(userServerID, "VERIFY:"..user..":"..s) s1,m1 = rednet.receive(3) if m1 == nil or TextUtils.startsWith(m1,"FAIL") then rednet.send(s,"ERROR:Failed to verify user") else -- save new mail to user file recipMail = {} if fs.exists("/mailto/"..recip) then recipMail = FileUtils.readVariableFile("/mailto/"..recip) end id = #recipMail + 1 rednet.send(s,"READY") s2,m2 = rednet.receive() if m2 == nil or not TextUtils.startsWith(m2,"BODY:") then -- email body not received after header rednet.send(s,"ERROR:No Body received") else body = string.sub(m2,-1 * (#m2 - 5)) email = {id,recip,user,subj,body,true} table.insert(recipMail,email) end FileUtils.writeVariableFile("/mailto/"..recip,recipMail) end else rednet.send(s, "ERROR:Unknown protocol") end end
local L = LibStub("AceLocale-3.0"):NewLocale("HandyNotes_DungeonLocations", "zhCN") if not L then return end L["Allow left click to open journal to dungeon or raid"] = "允许使用左键打开地下城或团队副本的冒险指南" L["Allow right click to create waypoints with TomTom"] = "允许使用右键建立 TomTom 的引导箭头" L["Continent Alpha"] = "世界地图图标透明度" L["Continent Scale"] = "世界地图图标缩放大小" L["Don't show discovered dungeons"] = "隐藏已被发现的地下城副本" L["Enable TomTom integration"] = "启用 TomTom 整合" L["Filter Options"] = "过滤选项" L["Hide all BfA nodes from the map"] = "隐藏地图上所有争霸艾泽拉斯的副本图标" L["Hide all Broken Isle nodes from the map"] = "隐藏地图上所有破碎群岛的副本图标" L["Hide all Cataclysm nodes from the map"] = "隐藏地图上所有大地的裂变的副本图标" L["Hide all Draenor nodes from the map"] = "隐藏地图上所有德拉诺的副本图标" L["Hide all Northrend nodes from the map"] = "隐藏地图上所有诺森德的副本图标" L["Hide all Outland nodes from the map"] = "隐藏地图上所有外域的副本图标" L["Hide all Pandaria nodes from the map"] = "隐藏地图上所有潘达利亚的副本图标" L["Hide all Vanilla nodes from the map"] = "隐藏地图上所有艾泽拉斯的副本图标" L["Hide Battle for Azeroth"] = "隐藏争霸艾泽拉斯" L["Hide Broken Isles"] = "隐藏破碎群岛" L["Hide Cataclysm"] = "隐藏大地的裂变" L["Hide Draenor"] = "隐藏德拉诺" L["Hide Instances"] = "隐藏副本" L["Hide Northrend"] = "隐藏诺森德" L["Hide Outland"] = "隐藏外域" L["Hide Pandaria"] = "隐藏潘达利亚" L["Hide Vanilla"] = "隐藏艾泽拉斯" L["Invert Lockout"] = "反向显示已击杀" L["Journal Integration"] = "启用冒险指南整合" L["Lockout Alpha"] = "已击杀透明度" L["Lockout Gray Icon"] = "已击杀灰色图标" L["Lockout Options"] = "首領已击杀选项" L["Lockout Tooltip"] = "鼠标提示已击杀" L["Show dungeon locations on the map"] = "在地图上显示5人地下城的位置" L["Show Dungeons"] = "显示地下城" L["Show icons on continent map"] = "在世界地图上显示图标" L["Show lockout information on tooltips"] = "在鼠标提示中显示首领已击杀的信息" L["Show Mixed"] = "都显示" L["Show mixed (dungeons + raids) locations on the map"] = "在地图上显示地下城和团队副本的位置" L["Show on Continent"] = "在世界地图上显示" L["Show raid locations on the map"] = "在地图上显示团队副本的位置" L["Show Raids"] = "显示团队" L["The alpha of dungeons and raids that are locked to any extent"] = "任何难度的地下城和团队副本首领已击杀的透明度" L["The alpha of the icons shown on the continent map"] = "世界地图上的图标透明度" L["The alpha of the icons shown on the zone map"] = "区域地图上的图标透明度" L["The scale of the icons shown on the continent map"] = "世界地图上的图标大小" L["The scale of the icons shown on the zone map"] = "区域地图上的图标大小" L["These settings control the look and feel of the icon."] = "这些设定控制图标的外观及风格。" L["This will check for legion and bfa dungeons that have already been discovered. THIS IS KNOWN TO CAUSE TAINT, ENABLE AT OWN RISK."] = "启用后将检测军团再临和争霸艾泽拉斯已被发现的地下城副本,这可能会造成污染,请慎用。" L["Turn mixed icons grey when ANY dungeon or raid listed is locked"] = "列出的任何地下城或团队已击杀时,将混合的图标显示为灰色。" L["Use a different alpha for dungeons and raids that are locked to any extent"] = "使用不同的透明度来显示首领已击杀的地下城和团队副本(任何难度)" L["Use gray icon for dungeons and raids that are locked to any extent"] = "使用灰色图标来显示首领已击杀的地下城和团队副本(任何难度)" L["Use Lockout Alpha"] = "使用已击杀透明度" L["Zone Alpha"] = "区域地图图标透明度" L["Zone Scale"] = "区域地图图标缩放大小"
--------------------------------------------------------------------------------------------------- -- Proposal: https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0296-Update-video-streaming-capabilities-during-ignition-cycle.md -- -- Description: Processing of OnSystemCapabilityUpdated notification with invalid -- number of additionalVideoStreamingCapabilities array items -- -- Preconditions: -- 1. HMI capabilities contain data about videoStreamingCapability -- 2. SDL and HMI are started -- 3. App is registered, activated and subscribed on videoStreamingCapability updates -- -- Sequence: -- 1. HMI sends OnSystemCapabilityUpdated notification for "VIDEO_STREAMING" to SDL with invalid -- number of additionalVideoStreamingCapabilities array items -- SDL does: -- a. not send OnSystemCapabilityUpdated (videoStreamingCapability) notification to mobile --------------------------------------------------------------------------------------------------- -- [[ Required Shared libraries ]] local common = require('test_scripts/Capabilities/UpdateVideoStreamingCapabilities/common') --[[ Local Variables ]] local appSessionId = 1 local notExpected = 0 local isSubscribe = true local arraySize = { minSize = 0, maxSize = 101 } --[[ Scenario ]] common.Title("Preconditions") common.Step("Clean environment", common.preconditions) common.Step("Set HMI Capabilities", common.setVideoStreamingCapabilities) common.Step("Start SDL, HMI, connect Mobile, start Session", common.start) common.Step("Register App", common.registerAppWOPTU) common.Step("Activate App", common.activateApp) common.Step("Subscribe App on VIDEO_STREAMING updates", common.getSystemCapability, { isSubscribe }) common.Title("Test") for parameter, value in pairs(arraySize) do common.Step("Check OnSystemCapabilityUpdated notification processing out of range " .. parameter .. " " .. value, common.sendOnSystemCapabilityUpdated, { appSessionId, notExpected, common.buildVideoStreamingCapabilities(value) }) end common.Title("Postconditions") common.Step("Stop SDL", common.postconditions)
require "brains/bunnymanbrain" require "stategraphs/SGbunnyman" local assets = { Asset("ANIM", "anim/manrabbit_basic.zip"), Asset("ANIM", "anim/manrabbit_actions.zip"), Asset("ANIM", "anim/manrabbit_attacks.zip"), Asset("ANIM", "anim/manrabbit_build.zip"), Asset("ANIM", "anim/manrabbit_beard_build.zip"), Asset("ANIM", "anim/manrabbit_beard_basic.zip"), Asset("ANIM", "anim/manrabbit_beard_actions.zip"), Asset("SOUND", "sound/bunnyman.fsb"), } local prefabs = { "meat", "monstermeat", "manrabbit_tail", } local MAX_TARGET_SHARES = 5 local SHARE_TARGET_DIST = 30 local function ontalk(inst, script) inst.SoundEmitter:PlaySound("dontstarve/creatures/bunnyman/idle_med") --inst.SoundEmitter:PlaySound("dontstarve/pig/grunt") end local function CalcSanityAura(inst, observer) if inst.beardlord then return -TUNING.SANITYAURA_MED end if inst.components.follower and inst.components.follower.leader == observer then return TUNING.SANITYAURA_SMALL end return 0 end local function ShouldAcceptItem(inst, item) if item.components.equippable and item.components.equippable.equipslot == EQUIPSLOTS.HEAD then return true end if item.components.edible then if (item.prefab == "carrot" or item.prefab == "carrot_cooked") and inst.components.follower.leader and inst.components.follower:GetLoyaltyPercent() > 0.9 then return false end return true end end local function OnGetItemFromPlayer(inst, giver, item) --I eat food if item.components.edible then if (item.prefab == "carrot" or item.prefab == "carrot_cooked") then if inst.components.combat.target and inst.components.combat.target == giver then inst.components.combat:SetTarget(nil) elseif giver.components.leader then inst.SoundEmitter:PlaySound("dontstarve/common/makeFriend") giver.components.leader:AddFollower(inst) inst.components.follower:AddLoyaltyTime(TUNING.RABBIT_CARROT_LOYALTY) end end if inst.components.sleeper:IsAsleep() then inst.components.sleeper:WakeUp() end end --I wear hats if item.components.equippable and item.components.equippable.equipslot == EQUIPSLOTS.HEAD then local current = inst.components.inventory:GetEquippedItem(EQUIPSLOTS.HEAD) if current then inst.components.inventory:DropItem(current) end inst.components.inventory:Equip(item) inst.AnimState:Show("hat") end end local function OnRefuseItem(inst, item) inst.sg:GoToState("refuse") if inst.components.sleeper:IsAsleep() then inst.components.sleeper:WakeUp() end end local function OnAttacked(inst, data) --print(inst, "OnAttacked") local attacker = data.attacker inst.components.combat:SetTarget(attacker) inst.components.combat:ShareTarget(attacker, SHARE_TARGET_DIST, function(dude) return dude.prefab == inst.prefab end, MAX_TARGET_SHARES) end local function OnNewTarget(inst, data) inst.components.combat:ShareTarget(data.target, SHARE_TARGET_DIST, function(dude) return dude.prefab == inst.prefab end, MAX_TARGET_SHARES) end local function is_meat(item) return item.components.edible and item.components.edible.foodtype == "MEAT" end local function NormalRetargetFn(inst) return FindEntity(inst, TUNING.PIG_TARGET_DIST, function(guy) if guy.components.health and not guy.components.health:IsDead() and inst.components.combat:CanTarget(guy) then if guy:HasTag("monster") then return guy end if guy:HasTag("player") and guy.components.inventory and guy:GetDistanceSqToInst(inst) < TUNING.BUNNYMAN_SEE_MEAT_DIST*TUNING.BUNNYMAN_SEE_MEAT_DIST and guy.components.inventory:FindItem(is_meat ) then return guy end end end) end local function NormalKeepTargetFn(inst, target) return inst.components.combat:CanTarget(target) and not (target.sg and target.sg:HasStateTag("hiding")) end local function giveupstring(combatcmp, target) return STRINGS.RABBIT_GIVEUP[math.random(#STRINGS.RABBIT_GIVEUP)] end local function battlecry(combatcmp, target) if target and target.components.inventory then local item = target.components.inventory:FindItem(function(item) return item.components.edible and item.components.edible.foodtype == "MEAT" end ) if item then return STRINGS.RABBIT_MEAT_BATTLECRY[math.random(#STRINGS.RABBIT_MEAT_BATTLECRY)] end end return STRINGS.RABBIT_BATTLECRY[math.random(#STRINGS.RABBIT_BATTLECRY)] end local function SetBeardlord(inst) if not inst.beardlord then inst.AnimState:SetBuild("manrabbit_beard_build") inst.beardlord = true inst.components.combat:SetDefaultDamage(TUNING.BEARDLORD_DAMAGE) inst.components.combat:SetAttackPeriod(TUNING.BEARDLORD_ATTACK_PERIOD) inst.components.combat.panic_thresh = TUNING.BEARDLORD_PANIC_THRESH inst.components.lootdropper:SetLoot({"beardhair", "beardhair", "monstermeat"}) inst.components.sleeper:SetSleepTest(function() return false end) inst.components.sleeper:SetWakeTest(function() return true end) end end local function SetNormalRabbit(inst) if inst.beardlord or inst.beardlord == nil then inst.beardlord = false inst.AnimState:SetBuild("manrabbit_build") inst.components.combat:SetDefaultDamage(TUNING.BUNNYMAN_DAMAGE) inst.components.combat:SetAttackPeriod(TUNING.BUNNYMAN_ATTACK_PERIOD) inst.components.combat.panic_thresh = TUNING.BUNNYMAN_PANIC_THRESH inst.components.lootdropper:SetLoot({"carrot","carrot"}) inst.components.lootdropper:AddRandomLoot("meat",3) inst.components.lootdropper:AddRandomLoot("manrabbit_tail",1) inst.components.lootdropper.numrandomloot = 1 inst.components.sleeper:SetDefaultTests() end end local function CheckTransformState(inst) if not inst.components.health:IsDead() then if GetPlayer().components.sanity:GetPercent() > TUNING.BEARDLING_SANITY then SetNormalRabbit(inst) else SetBeardlord(inst) end end end local function OnWake(inst) CheckTransformState(inst) inst.checktask = inst:DoPeriodicTask(10, CheckTransformState) end local function OnSleep(inst) if inst.checktask then inst.checktask:Cancel() inst.checktask = nil end end local function fn() local inst = CreateEntity() local trans = inst.entity:AddTransform() local anim = inst.entity:AddAnimState() local sound = inst.entity:AddSoundEmitter() local shadow = inst.entity:AddDynamicShadow() shadow:SetSize( 1.5, .75 ) inst.Transform:SetFourFaced() local s = 1.25 inst.Transform:SetScale(s,s,s) inst.entity:AddLightWatcher() MakeCharacterPhysics(inst, 50, .5) inst:AddComponent("locomotor") -- locomotor must be constructed before the stategraph inst.components.locomotor.runspeed = TUNING.PIG_RUN_SPEED --5 inst.components.locomotor.walkspeed = TUNING.PIG_WALK_SPEED --3 inst:AddTag("character") inst:AddTag("pig") inst:AddTag("manrabbit") inst:AddTag("scarytoprey") anim:SetBank("manrabbit") anim:PlayAnimation("idle_loop") anim:Hide("hat") inst.CheckTransformState = CheckTransformState --used for purpleamulet ------------------------------------------ inst:AddComponent("eater") inst.components.eater:SetVegetarian() table.insert(inst.components.eater.foodprefs, "RAW") table.insert(inst.components.eater.ablefoods, "RAW") ------------------------------------------ inst:AddComponent("combat") inst.components.combat.hiteffectsymbol = "manrabbit_torso" inst.components.combat.panic_thresh = TUNING.BUNNYMAN_PANIC_THRESH inst.components.combat.GetBattleCryString = battlecry inst.components.combat.GetGiveUpString = giveupstring MakeMediumBurnableCharacter(inst, "manrabbit_torso") inst:AddComponent("named") inst.components.named.possiblenames = STRINGS.BUNNYMANNAMES inst.components.named:PickNewName() ------------------------------------------ inst:AddComponent("follower") inst.components.follower.maxfollowtime = TUNING.PIG_LOYALTY_MAXTIME ------------------------------------------ inst:AddComponent("health") inst.components.health:StartRegen(TUNING.BUNNYMAN_HEALTH_REGEN_AMOUNT, TUNING.BUNNYMAN_HEALTH_REGEN_PERIOD) ------------------------------------------ inst:AddComponent("inventory") ------------------------------------------ inst:AddComponent("lootdropper") ------------------------------------------ inst:AddComponent("knownlocations") inst:AddComponent("talker") inst.components.talker.ontalk = ontalk inst.components.talker.fontsize = 24 inst.components.talker.font = TALKINGFONT inst.components.talker.offset = Vector3(0,-500,0) ------------------------------------------ inst:AddComponent("trader") inst.components.trader:SetAcceptTest(ShouldAcceptItem) inst.components.trader.onaccept = OnGetItemFromPlayer inst.components.trader.onrefuse = OnRefuseItem ------------------------------------------ inst:AddComponent("sanityaura") inst.components.sanityaura.aurafn = CalcSanityAura ------------------------------------------ inst:AddComponent("sleeper") ------------------------------------------ MakeMediumFreezableCharacter(inst, "pig_torso") ------------------------------------------ inst:AddComponent("inspectable") inst.components.inspectable.getstatus = function(inst) if inst.components.follower.leader ~= nil then return "FOLLOWER" end end ------------------------------------------ inst:ListenForEvent("attacked", OnAttacked) inst:ListenForEvent("newcombattarget", OnNewTarget) --inst.components.werebeast:SetOnWereFn(SetBeardlord) --inst.components.werebeast:SetOnNormaleFn(SetNormalRabbit) CheckTransformState(inst) inst.OnEntityWake = OnWake inst.OnEntitySleep = OnSleep inst.components.sleeper:SetResistance(2) inst.components.sleeper.nocturnal = true inst.components.combat:SetDefaultDamage(TUNING.BUNNYMAN_DAMAGE) inst.components.combat:SetAttackPeriod(TUNING.BUNNYMAN_ATTACK_PERIOD) inst.components.combat:SetKeepTargetFunction(NormalKeepTargetFn) inst.components.combat:SetRetargetFunction(3, NormalRetargetFn) inst.components.locomotor.runspeed = TUNING.BUNNYMAN_RUN_SPEED inst.components.locomotor.walkspeed = TUNING.BUNNYMAN_WALK_SPEED inst.components.lootdropper:SetLoot({"carrot","carrot"}) inst.components.lootdropper:AddRandomLoot("meat",3) inst.components.lootdropper:AddRandomLoot("manrabbit_tail",1) inst.components.lootdropper.numrandomloot = 1 inst.components.health:SetMaxHealth(TUNING.BUNNYMAN_HEALTH) inst.components.trader:Enable() --inst.Label:Enable(true) --inst.components.talker:StopIgnoringAll() local brain = require "brains/bunnymanbrain" inst:SetBrain(brain) inst:SetStateGraph("SGbunnyman") return inst end return Prefab( "common/characters/bunnyman", fn, assets, prefabs)
local class = require 'ext.class' local ffi = require 'ffi' local gl = require 'gl' local Tex2D = require 'gl.tex2d' local Tex3D = require 'gl.tex3d' local glreport = require 'gl.report' local fboErrors = { 'GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT', 'GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT', 'GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER', 'GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER', 'GL_FRAMEBUFFER_UNSUPPORTED', } local fboErrorNames = {} for i,var in ipairs(fboErrors) do fboErrorNames[gl[var]] = var end local FrameBuffer = class() function FrameBuffer:init(args) args = args or {} -- store these for reference later, if we get them -- they're actually not needed for only-color buffer fbos self.width = args.width self.height = args.height local id = ffi.new('GLuint[1]') gl.glGenFramebuffers(1, id) self.id = id[0] gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.id) -- make a depth buffer render target only if you need it self.depthID = 0 if args.useDepth then gl.glGenRenderbuffers(1, id) self.depthID = id[0] gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, self.depthID) gl.glRenderbufferStorage(gl.GL_RENDERBUFFER, gl.GL_DEPTH_COMPONENT, self.width, self.height) gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, 0) gl.glFramebufferRenderbuffer(gl.GL_FRAMEBUFFER, gl.GL_DEPTH_ATTACHMENT, gl.GL_RENDERBUFFER, self.depthID) end gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0) end function FrameBuffer:bind() gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.id) end function FrameBuffer:unbind() gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0) end -- static function function FrameBuffer.check() local status = gl.glCheckFramebufferStatus(gl.GL_FRAMEBUFFER) if status ~= gl.GL_FRAMEBUFFER_COMPLETE then local errstr = 'glCheckFramebufferStatus status='..status local name = fboErrorNames[status] if name then errstr = errstr..' error='..name end return false, errstr end return true end -- TODO - should we bind() beforehand for assurance's sake? -- (while texture doesn't support this philosophy with its bind() which doesn't enable() beforehand -- (thought a texture bind() without enable() would still fulfill its operation, yet wouldn't be visible in some render methods -- on the other hand, a fbo setColorAttachmet() without bind() wouldn't fulfill its operation -- or should we leave the app to do this (and reduce the possible binds/unbinds?) -- or should we only bind, and leave it to the caller to unbind? function FrameBuffer:setColorAttachmentTex2D(index, tex, target, level) self:bind() gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0 + index, target or gl.GL_TEXTURE_2D, tex, level or 0) self:unbind() end function FrameBuffer:setColorAttachmentTexCubeMapSide(index, tex, side, level) self:bind() gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0 + index, gl.GL_TEXTURE_CUBE_MAP_POSITIVE_X + (side or index), tex, level or 0) self:unbind() end function FrameBuffer:setColorAttachmentTexCubeMap(tex, level) self:bind() for i=0,5 do gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0 + i, gl.GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, tex, level or 0) end self:unbind() end function FrameBuffer:setColorAttachmentTex3D(index, tex, slice, target, level) if not tonumber(slice) then error("unable to convert slice to number: " ..tostring(slice)) end slice = tonumber(slice) self:bind() gl.glFramebufferTexture3D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0 + index, target or gl.GL_TEXTURE_3D, tex, level or 0, slice) self:unbind() end --general, object-based type-deducing function FrameBuffer:setColorAttachment(index, tex, ...) if type(tex) == 'table' then local mt = getmetatable(tex) if mt == Tex2D then self:setColorAttachmentTex2D(index, tex.id, ...) -- cube map? side or all at once? elseif mt == Tex3D then self:setColorAttachmentTex3D(index, tex.id, ...) else error("Can't deduce how to attach the object. Try using an explicit attachment method") end elseif type(tex) == 'number' then self:setColorAttachmentTex2D(index, tex, ...) -- though this could be a 3d slice or a cube side... else error("Can't deduce how to attach the object. Try using an explicit attachment method") end end local glint = ffi.new('GLint[1]') --[[ if index is a number then it binds the associated color attachment at 'GL_COLOR_ATTACHMENT0+index' and runs the callback if index is a table then it runs through the ipairs, binding the associated color attachment at 'GL_COLOR_ATTACHMENT0+index[side]' and running the callback for each, passing the side as a parameter --]] function FrameBuffer:drawToCallback(index, callback, ...) self:bind() local res,err = self.check() if not res then print(err) print(debug.traceback()) else gl.glGetIntegerv(gl.GL_DRAW_BUFFER, glint) local drawbuffer = glint[0] if type(index)=='number' then gl.glDrawBuffer(gl.GL_COLOR_ATTACHMENT0 + index) callback(...) elseif type(index)=='table' then -- TODO - table attachments should probably make use of glDrawBuffers for multiple draw to's -- cubemaps should go through the tedious-but-readable chore of calling this method six times for side,colorAttachment in ipairs(index) do gl.glDrawBuffer(gl.GL_COLOR_ATTACHMENT0 + colorAttachment) --index[side]) callback(side, ...) end end gl.glDrawBuffer(drawbuffer) end self:unbind() end function FrameBuffer.drawScreenQuad() gl.glBegin(gl.GL_TRIANGLE_STRIP) gl.glTexCoord2f(0,0) gl.glVertex2f(0,0) gl.glTexCoord2f(1,0) gl.glVertex2f(1,0) gl.glTexCoord2f(0,1) gl.glVertex2f(0,1) gl.glTexCoord2f(1,1) gl.glVertex2f(1,1) gl.glEnd() end function FrameBuffer:draw(args) glreport('begin drawScreenFBO') if args.viewport then local vp = args.viewport gl.glPushAttrib(gl.GL_VIEWPORT_BIT) gl.glViewport(vp[1], vp[2], vp[3], vp[4]) end glreport('drawScreenFBO glViewport') if args.resetProjection then gl.glMatrixMode(gl.GL_PROJECTION) gl.glPushMatrix() gl.glLoadIdentity() gl.glOrtho(0,1,0,1,-1,1) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPushMatrix() gl.glLoadIdentity() end glreport('drawScreenFBO resetProjection') if args.shader then local sh = args.shader if type(sh) == 'table' then sh:use() else gl.glUseProgram(sh) end end glreport('drawScreenFBO glUseProgram') if args.uniforms then assert(args.shader) for k,v in pairs(args.uniforms) do args.shader:setUniform(k,v) -- uniformf only, but that still supports vectors =) glreport('drawScreenFBO glUniform '..tostring(k)..' '..tostring(v)) end end if args.texs then for i,t in ipairs(args.texs) do gl.glActiveTexture(gl.GL_TEXTURE0+i-1) glreport('drawScreenFBO glActiveTexture '..tostring(gl.GL_TEXTURE0+i-1)) if type(t) == 'table' then -- assume tables are texture objects t:bind() glreport('drawScreenFBO glBindTexture '..tostring(t.target)..', '..tostring(t.id)) else -- texture2d by default gl.glBindTexture(gl.GL_TEXTURE_2D, t) glreport('drawScreenFBO glBindTexture '..tostring(t)) end end end if args.color then gl.glColor(args.color) glreport('drawScreenFBO glColor') end if args.dest then self:setColorAttachment(0, args.dest) end glreport('drawScreenFBO before callback') -- no one seems to use fbo:draw... at all... -- so why preserve a function that no one uses? -- why not just merge it in here? self:drawToCallback(args.colorAttachment or 0, args.callback or self.drawScreenQuad) glreport('drawScreenFBO after callback') if args.texs then for i=#args.texs,1,-1 do -- step -1 so we end up at zero local t = args.texs[i] gl.glActiveTexture(gl.GL_TEXTURE0+i-1) glreport('drawScreenFBO glActiveTexture '..(gl.GL_TEXTURE0+i-1)) if type(t) == 'table' then gl.glBindTexture(t.target, 0) glreport('drawScreenFBO glBindTexture '..tostring(t.target)..', 0') else gl.glBindTexture(gl.GL_TEXTURE_2D, 0) glreport('drawScreenFBO glBindTexture '..(gl.GL_TEXTURE_2D)..', 0') end end end if args.shader then gl.glUseProgram(0) glreport('drawScreenFBO glUseProgram nil') end if args.resetProjection then gl.glMatrixMode(gl.GL_PROJECTION) gl.glPopMatrix() gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPopMatrix() glreport('drawScreenFBO resetProjection') end if args.viewport then gl.glPopAttrib() glreport('drawScreenFBO glPopAttrib') end glreport('end drawScreenFBO') end return FrameBuffer
-- TODO -- local Runner = require "nvim-test.runner" local cargotest = Runner:init({ command = "cargo test" }, { rust = [[ ( (mod_item name: (identifier) @module-name) @scope-root) ( (function_item name: (identifier) @function-name) @scope-root) ]], }) function cargotest:is_test(name) return string.match(name, "[Tt]est") and true end function cargotest:build_args(filename, opts) -- for whole suite do nothing local args = self.config.args if not filename then return args end local parts = vim.fn.split(vim.fn.fnamemodify(filename, ":.:r"), "/") if parts[#parts] == "main" or parts[#parts] == "lib" or parts[#parts] == "mod" then parts[#parts] = nil end if parts[1] == "src" then table.remove(parts, 1) end local modname = (#parts > 0) and table.concat(parts, "::") if modname then modname = " " .. vim.fn.shellescape(modname .. "::") end if opts.tests and #opts.tests > 0 then return args .. " " .. table.concat(opts.tests, "::") .. " -- --exact" end return args .. (modname or "") end return cargotest
function DIALOG() NODE(0) --047 SAYSPEECH("Keine Zeit zum Plaudern. Sie sehen doch, dass ich beschaeftigt bin...",3047) ENDDIALOG() end
local ffi = require("ffi") local bit = require("bit") local lshift = bit.lshift; local rshift = bit.rshift; local bnot = bit.bnot; local S = require("syscall") local nr = require "syscall.linux.nr" local _IO, _IOW = S.c.IOCTL._IO, S.c.IOCTL._IOW local shared = require("shared") -- The table which will hold anything we want exported -- from this module local exports = {} exports.nr = nr; ffi.cdef[[ /* * attr->type field values */ enum perf_type_id { PERF_TYPE_HARDWARE = 0, PERF_TYPE_SOFTWARE = 1, PERF_TYPE_TRACEPOINT = 2, PERF_TYPE_HW_CACHE = 3, PERF_TYPE_RAW = 4, PERF_TYPE_BREAKPOINT = 5, PERF_TYPE_MAX }; /* * attr->config values for generic HW PMU events * * they get mapped onto actual events by the kernel */ enum perf_hw_id { PERF_COUNT_HW_CPU_CYCLES = 0, PERF_COUNT_HW_INSTRUCTIONS = 1, PERF_COUNT_HW_CACHE_REFERENCES = 2, PERF_COUNT_HW_CACHE_MISSES = 3, PERF_COUNT_HW_BRANCH_INSTRUCTIONS = 4, PERF_COUNT_HW_BRANCH_MISSES = 5, PERF_COUNT_HW_BUS_CYCLES = 6, PERF_COUNT_HW_STALLED_CYCLES_FRONTEND = 7, PERF_COUNT_HW_STALLED_CYCLES_BACKEND = 8, PERF_COUNT_HW_REF_CPU_CYCLES = 9, PERF_COUNT_HW_MAX }; /* * attr->config values for generic HW cache events * * they get mapped onto actual events by the kernel */ enum perf_hw_cache_id { PERF_COUNT_HW_CACHE_L1D = 0, PERF_COUNT_HW_CACHE_L1I = 1, PERF_COUNT_HW_CACHE_LL = 2, PERF_COUNT_HW_CACHE_DTLB = 3, PERF_COUNT_HW_CACHE_ITLB = 4, PERF_COUNT_HW_CACHE_BPU = 5, PERF_COUNT_HW_CACHE_NODE = 6, PERF_COUNT_HW_CACHE_MAX }; enum perf_hw_cache_op_id { PERF_COUNT_HW_CACHE_OP_READ = 0, PERF_COUNT_HW_CACHE_OP_WRITE = 1, PERF_COUNT_HW_CACHE_OP_PREFETCH = 2, PERF_COUNT_HW_CACHE_OP_MAX }; enum perf_hw_cache_op_result_id { PERF_COUNT_HW_CACHE_RESULT_ACCESS = 0, PERF_COUNT_HW_CACHE_RESULT_MISS = 1, PERF_COUNT_HW_CACHE_RESULT_MAX }; /* * attr->config values for SW events */ enum perf_sw_ids { PERF_COUNT_SW_CPU_CLOCK = 0, PERF_COUNT_SW_TASK_CLOCK = 1, PERF_COUNT_SW_PAGE_FAULTS = 2, PERF_COUNT_SW_CONTEXT_SWITCHES = 3, PERF_COUNT_SW_CPU_MIGRATIONS = 4, PERF_COUNT_SW_PAGE_FAULTS_MIN = 5, PERF_COUNT_SW_PAGE_FAULTS_MAJ = 6, PERF_COUNT_SW_ALIGNMENT_FAULTS = 7, PERF_COUNT_SW_EMULATION_FAULTS = 8, PERF_COUNT_SW_MAX }; /* * attr->sample_type values */ enum perf_event_sample_format { PERF_SAMPLE_IP = 1U << 0, PERF_SAMPLE_TID = 1U << 1, PERF_SAMPLE_TIME = 1U << 2, PERF_SAMPLE_ADDR = 1U << 3, PERF_SAMPLE_READ = 1U << 4, PERF_SAMPLE_CALLCHAIN = 1U << 5, PERF_SAMPLE_ID = 1U << 6, PERF_SAMPLE_CPU = 1U << 7, PERF_SAMPLE_PERIOD = 1U << 8, PERF_SAMPLE_STREAM_ID = 1U << 9, PERF_SAMPLE_RAW = 1U << 10, PERF_SAMPLE_BRANCH_STACK = 1U << 11, PERF_SAMPLE_REGS_USER = 1U << 12, PERF_SAMPLE_STACK_USER = 1U << 13, PERF_SAMPLE_WEIGHT = 1U << 14, PERF_SAMPLE_DATA_SRC = 1U << 15, PERF_SAMPLE_MAX = 1U << 16, }; /* * branch_sample_type values */ enum perf_branch_sample_type { PERF_SAMPLE_BRANCH_USER = 1U << 0, PERF_SAMPLE_BRANCH_KERNEL = 1U << 1, PERF_SAMPLE_BRANCH_HV = 1U << 2, PERF_SAMPLE_BRANCH_ANY = 1U << 3, PERF_SAMPLE_BRANCH_ANY_CALL = 1U << 4, PERF_SAMPLE_BRANCH_ANY_RETURN = 1U << 5, PERF_SAMPLE_BRANCH_IND_CALL = 1U << 6, PERF_SAMPLE_BRANCH_MAX = 1U << 7, }; enum perf_sample_regs_abi { PERF_SAMPLE_REGS_ABI_NONE = 0, PERF_SAMPLE_REGS_ABI_32 = 1, PERF_SAMPLE_REGS_ABI_64 = 2, }; /* * attr->read_format values */ enum perf_event_read_format { PERF_FORMAT_TOTAL_TIME_ENABLED = 1U << 0, PERF_FORMAT_TOTAL_TIME_RUNNING = 1U << 1, PERF_FORMAT_ID = 1U << 2, PERF_FORMAT_GROUP = 1U << 3, PERF_FORMAT_MAX = 1U << 4, }; ]] exports.PERF_ATTR_SIZE_VER0 = 64; -- sizeof first published struct exports.PERF_ATTR_SIZE_VER1 = 72; -- add: config2 exports.PERF_ATTR_SIZE_VER2 = 80; -- add: branch_sample_type ffi.cdef[[ /* * perf_event_attr struct passed to perf_event_open() */ typedef struct perf_event_attr { uint32_t type; uint32_t size; uint64_t config; union { uint64_t sample_period; uint64_t sample_freq; } sample; uint64_t sample_type; uint64_t read_format; /* uint64_t disabled : 1; uint64_t inherit : 1; uint64_t pinned : 1; uint64_t exclusive : 1; uint64_t exclude_user : 1; uint64_t exclude_kernel : 1; uint64_t exclude_hv : 1; uint64_t exclude_idle : 1; uint64_t mmap : 1; uint64_t comm : 1; uint64_t freq : 1; uint64_t inherit_stat : 1; uint64_t enable_on_exec : 1; uint64_t task : 1; uint64_t watermark : 1; uint64_t precise_ip : 2; uint64_t mmap_data : 1; uint64_t sample_id_all : 1; uint64_t exclude_host : 1; uint64_t exclude_guest : 1; uint64_t exclude_callchain_kernel : 1; uint64_t exclude_callchain_user : 1; uint64_t __reserved_1 : 41; */ // TODO - need a better way to represent the uint64_t // based bitfields uint64_t bitfield_flag; union { uint32_t wakeup_events; uint32_t wakeup_watermark; } wakeup; uint32_t bp_type; union { uint64_t bp_addr; uint64_t config1; // extend config } bpa; union { uint64_t bp_len; uint64_t config2; // extend config1 } bpb; uint64_t branch_sample_type; uint64_t sample_regs_user; uint32_t sample_stack_user; uint32_t __reserved_2; } perf_event_attr_t; ]] --[[ As of LuaJIT 2.1, 64-bit values can not be used as bitfields in C structures. This is probably according to the C standard the the C parser follows, as the standard only indicates bitfields will work with 'int' fields. So, we construct this metatype with the bitfield ranges, and implement the __newindex, and __index functions so that we can do the bit manipulations ourselves. Of course, if you want to add any other function to the metatype, you'll have to change this code. More than likely, you can simply do it in a convenient table class instead of in here. --]] local perf_event_attr = ffi.typeof("struct perf_event_attr") local perf_event_attr_mt = {} perf_event_attr_mt.bitfield_ranges = { disabled = { 0, 1}; inherit = { 1, 1}; pinned = { 2, 1}; exclusive = { 3, 1}; exclude_user = { 4, 1}; exclude_kernel = { 5, 1}; exclude_hv = { 6, 1}; exclude_idle = { 7, 1}; mmap = { 8, 1}; comm = { 9, 1}; freq = { 10, 1}; inherit_stat = { 11, 1}; enable_on_exec = { 12, 1}; task = { 13, 1}; watermark = { 14, 1}; precise_ip = { 15, 2}; mmap_data = { 17, 1}; sample_id_all = { 18, 1}; exclude_host = { 19, 1}; exclude_guest = { 20, 1}; exclude_callchain_kernel = { 21, 1}; exclude_callchain_user = { 22, 1}; __reserved_1 = { 23, 41}; } perf_event_attr_mt.__index = function(self, key) local keyrange = perf_event_attr_mt.bitfield_ranges[key] if not keyrange then return nil; end return shared.extractbits64(self.bitfield_flag, keyrange[1], keyrange[2]); end perf_event_attr_mt.__newindex = function(self, key, value) --print("perf_event_attr, setting field value: ", key, value) local kr = perf_event_attr_mt.bitfield_ranges[key] if not kr then return nil; end self.bitfield_flag = shared.setbits64(self.bitfield_flag, kr[1], kr[2], value); return res; end ffi.metatype(perf_event_attr, perf_event_attr_mt); ffi.cdef[[ struct perf_branch_entry { uint64_t from; uint64_t to; /* uint64_t mispred:1, // target mispredicted predicted:1, // target predicted reserved:62; */ uint64_t bitfield_flag; }; ]] local perf_branch_entry = ffi.typeof("struct perf_branch_entry") local perf_branch_entry_mt = {} perf_branch_entry_mt.bitfield_ranges = { mispred = {0,1}; predicted = {1,1}; reserved = {2,62}; } perf_branch_entry_mt.__index = function(self, key) local kr = perf_branch_entry_mt.bitfield_ranges[key] if not kr then return nil end return shared.extractbits64(self.bitfield_flag, kr[1], kr[2]); end perf_branch_entry_mt.__newindex = function(self, key, value) --print("perf_event_attr, setting field value: ", key, value) local kr = perf_branch_entry_mt.bitfield_ranges[key] if not kr then return end self.bitfield_flag = shared.setbits64(self.bitfield_flag, kr[1], kr[2], value); end ffi.metatype(perf_branch_entry, perf_branch_entry_mt); ffi.cdef[[ /* * branch stack layout: * nr: number of taken branches stored in entries[] * * Note that nr can vary from sample to sample * branches (to, from) are stored from most recent * to least recent, i.e., entries[0] contains the most * recent branch. */ struct perf_branch_stack { uint64_t nr; struct perf_branch_entry entries[0]; }; ]] -- perf_events ioctl commands, use with event fd exports.PERF_EVENT_IOC_ENABLE = _IO ('$', 0) exports.PERF_EVENT_IOC_DISABLE = _IO ('$', 1) exports.PERF_EVENT_IOC_REFRESH = _IO ('$', 2) exports.PERF_EVENT_IOC_RESET = _IO ('$', 3) exports.PERF_EVENT_IOC_PERIOD = _IOW('$', 4, "uint64") exports.PERF_EVENT_IOC_SET_OUTPUT = _IO ('$', 5) exports.PERF_EVENT_IOC_SET_FILTER = _IOW('$', 6, "char") ffi.cdef[[ /* * ioctl() 3rd argument */ enum perf_event_ioc_flags { PERF_IOC_FLAG_GROUP = 1U << 0, }; ]] ffi.cdef[[ /* * mmapped sampling buffer layout * occupies a 4kb page */ struct perf_event_mmap_page { uint32_t version; uint32_t compat_version; uint32_t lock; uint32_t index; int64_t offset; uint64_t time_enabled; uint64_t time_running; union { uint64_t capabilities; /* uint64_t cap_usr_time:1, cap_usr_rdpmc:1, cap_____res:62; */ uint64_t bitfield_flag; } rdmap_cap; uint16_t pmc_width; uint16_t time_shift; uint32_t time_mult; uint64_t time_offset; uint64_t __reserved[120]; uint64_t data_head; uint64_t data_tail; }; /* * sampling buffer event header */ struct perf_event_header { uint32_t type; uint16_t misc; uint16_t size; }; ]] -- event header misc field values exports.PERF_EVENT_MISC_CPUMODE_MASK = lshift(3,0) exports.PERF_EVENT_MISC_CPUMODE_UNKNOWN = lshift(0,0) exports.PERF_EVENT_MISC_KERNEL = lshift(1,0) exports.PERF_EVENT_MISC_USER = lshift(2,0) exports.PERF_EVENT_MISC_HYPERVISOR = lshift(3,0) exports.PERF_RECORD_MISC_GUEST_KERNEL = lshift(4,0) exports.PERF_RECORD_MISC_GUEST_USER = lshift(5,0) exports.PERF_RECORD_MISC_EXACT = lshift(1, 14) exports.PERF_RECORD_MISC_EXACT_IP = lshift(1, 14) exports.PERF_RECORD_MISC_EXT_RESERVED = lshift(1, 15) ffi.cdef[[ // header->type values enum perf_event_type { PERF_RECORD_MMAP = 1, PERF_RECORD_LOST = 2, PERF_RECORD_COMM = 3, PERF_RECORD_EXIT = 4, PERF_RECORD_THROTTLE = 5, PERF_RECORD_UNTHROTTLE = 6, PERF_RECORD_FORK = 7, PERF_RECORD_READ = 8, PERF_RECORD_SAMPLE = 9, PERF_RECORD_MMAP2 = 10, PERF_RECORD_MAX }; enum perf_callchain_context { PERF_CONTEXT_HV = (uint64_t)-32, PERF_CONTEXT_KERNEL = (uint64_t)-128, PERF_CONTEXT_USER = (uint64_t)-512, PERF_CONTEXT_GUEST = (uint64_t)-2048, PERF_CONTEXT_GUEST_KERNEL = (uint64_t)-2176, PERF_CONTEXT_GUEST_USER = (uint64_t)-2560, PERF_CONTEXT_MAX = (uint64_t)-4095, }; ]] -- flags for perf_event_open() exports.PERF_FLAG_FD_NO_GROUP = lshift(1, 0) exports.PERF_FLAG_FD_OUTPUT = lshift(1, 1) exports.PERF_FLAG_PID_CGROUP = lshift(1, 2) local __NR_perf_event_open = 0; if ffi.arch == "x64" then __NR_perf_event_open = 298; end if ffi.arch == "x86" then __NR_perf_event_open = 336; end if ffi.arch == "ppc" then __NR_perf_event_open = 319; end if ffi.arch == "arm" then __NR_perf_event_open = 364; end if ffi.arch == "arm64" then __NR_perf_event_open = 241; end if ffi.arch == "mips" then __NR_perf_event_open = 4333; end -- perf_event_open() syscall stub --local function perf_event_open( -- struct perf_event_attr *hw_event_uptr, -- pid_t pid, -- int cpu, -- int group_fd, -- unsigned long flags) local function perf_event_open( hw_event_uptr, pid, cpu, group_fd, flags) --print("perf_event_open: ", S.perf_event_open, hw_event_uptr, pid, cpu, group_fd, flags) local fd = ffi.C.syscall(nr.SYS.perf_event_open, hw_event_uptr, pid, cpu, group_fd, flags); fd = S.t.fd(fd); return fd; end exports.perf_event_open = perf_event_open exports.PR_TASK_PERF_EVENTS_ENABLE = 32 exports.PR_TASK_PERF_EVENTS_DISABLE = 31 ffi.cdef[[ union perf_mem_data_src { uint64_t val; struct { /* uint64_t mem_op:5, // type of opcode mem_lvl:14, // memory hierarchy level mem_snoop:5, // snoop mode mem_lock:2, // lock instr mem_dtlb:7, // tlb access mem_rsvd:31; */ }; }; ]] local perf_mem_data_src = ffi.typeof("union perf_mem_data_src") local perf_mem_data_src_mt = {} perf_mem_data_src_mt.bitfield_ranges = { mem_op = {0,5}; mem_lvl = {5,14}; mem_snoop = {19,5}; mem_lock = {24,2}; mem_dtlb = {26,7}; mem_rsvd = {33,31}; } perf_mem_data_src_mt.__index = function(self, key) local kr = perf_mem_data_src_mt.bitfield_ranges[key] if not kr then return nil; end return shared.extractbits64(self.val, kr[1], kr[2]); end perf_mem_data_src_mt.__newindex = function(self, key, value) --print("perf_event_attr, setting field value: ", key, value) local kr = perf_mem_data_src_mt.bitfield_ranges[key] if not kr then return nil; end self.val = shared.setbits64(self.val, kr[1], kr[2], value); end ffi.metatype(perf_mem_data_src, perf_mem_data_src_mt); -- type of opcode (load/store/prefetch,code) exports.PERF_MEM_OP_NA = 0x01 -- not available exports.PERF_MEM_OP_LOAD = 0x02 -- load instruction exports.PERF_MEM_OP_STORE = 0x04 -- store instruction exports.PERF_MEM_OP_PFETCH = 0x08 -- prefetch exports.PERF_MEM_OP_EXEC = 0x10 -- code (execution) exports.PERF_MEM_OP_SHIFT = 0 -- memory hierarchy (memory level, hit or miss) exports.PERF_MEM_LVL_NA = 0x01 -- not available exports.PERF_MEM_LVL_HIT = 0x02 -- hit level exports.PERF_MEM_LVL_MISS = 0x04 -- miss level exports.PERF_MEM_LVL_L1 = 0x08 -- L1 exports.PERF_MEM_LVL_LFB = 0x10 -- Line Fill Buffer exports.PERF_MEM_LVL_L2 = 0x20 -- L2 exports.PERF_MEM_LVL_L3 = 0x40 -- L3 exports.PERF_MEM_LVL_LOC_RAM = 0x80 -- Local DRAM exports.PERF_MEM_LVL_REM_RAM1 = 0x100 -- Remote DRAM (1 hop) exports.PERF_MEM_LVL_REM_RAM2 = 0x200 -- Remote DRAM (2 hops) exports.PERF_MEM_LVL_REM_CCE1 = 0x400 -- Remote Cache (1 hop) exports.PERF_MEM_LVL_REM_CCE2 = 0x800 -- Remote Cache (2 hops) exports.PERF_MEM_LVL_IO = 0x1000 -- I/O memory exports.PERF_MEM_LVL_UNC = 0x2000 -- Uncached memory exports.PERF_MEM_LVL_SHIFT = 5 -- snoop mode exports.PERF_MEM_SNOOP_NA = 0x01 -- not available exports.PERF_MEM_SNOOP_NONE = 0x02 -- no snoop exports.PERF_MEM_SNOOP_HIT = 0x04 -- snoop hit exports.PERF_MEM_SNOOP_MISS = 0x08 -- snoop miss exports.PERF_MEM_SNOOP_HITM = 0x10 -- snoop hit modified exports.PERF_MEM_SNOOP_SHIFT = 19 -- locked instruction exports.PERF_MEM_LOCK_NA = 0x01 -- not available exports.PERF_MEM_LOCK_LOCKED = 0x02 -- locked transaction exports.PERF_MEM_LOCK_SHIFT = 24 -- TLB access exports.PERF_MEM_TLB_NA = 0x01 -- not available exports.PERF_MEM_TLB_HIT = 0x02 -- hit level exports.PERF_MEM_TLB_MISS = 0x04 -- miss level exports.PERF_MEM_TLB_L1 = 0x08 -- L1 exports.PERF_MEM_TLB_L2 = 0x10 -- L2 exports.PERF_MEM_TLB_WK = 0x20 -- Hardware Walker exports.PERF_MEM_TLB_OS = 0x40 -- OS fault handler exports.PERF_MEM_TLB_SHIFT = 26 local function PERF_MEM_S(a, s) --(((u64)PERF_MEM_##a##_##s) << PERF_MEM_##a##_SHIFT) local id = string.format("PERF_MEM_%s_%s", a, s) local shift = string.format("PERF_MEM_%s_SHIFT", a) return lshift(exports[id], exports[shift]) end return exports
local SheetInfo = {} SheetInfo.sheet = {} function SheetInfo:getSheet() return self.sheet; end return SheetInfo
local playerPlayback = {} playerPlayback.name = "playbackTutorial" playerPlayback.depth = 0 playerPlayback.justification = {0.5, 1.0} playerPlayback.texture = "characters/player/sitDown00" playerPlayback.color = {0.8, 0.2, 0.2, 0.75} playerPlayback.nodeLineRenderType = "line" playerPlayback.nodeLimits = {0, 2} playerPlayback.placements = { name = "playback", data = { tutorial = "" } } return playerPlayback
SILE = require("core.sile") local icu = require("justenoughicu") describe("SILE.linebreak", function() local chars = { 0x10000, 0x10001, 0x10002 } local utf8string = "" for i = 1,#chars do utf8string = utf8string .. luautf8.char(chars[i]) end it("should be the right length in UTF8", function() assert.is.equal(#utf8string, 12) end) it("should be the right length from ICU", function() local res = icu.bidi_runs(utf8string, "LTR") assert.is.equal(res.length, 3) end) end)
--variables DONT CHANGE THESE MouseX = myPlayer.x MouseY = myPlayer.y direction = 1 local squareSize = 20 --making the camera cube in between the player and the mouse + settings giving it X and Y value at the start camera = display.newRect(5, 5 , squareSize, squareSize) camera.alpha = 0 camera.x = myPlayer.x camera.y = myPlayer.y --grapple location grapplepos = display.newImageRect("graphics/crosshair/crosshairstyle4.png",30,30) -- change value of the image from 1-5 to change crosshair grapplepos.alpha = 1 grapplepos.x = myPlayer.x grapplepos.y = myPlayer.y --enemyCount initialised enemyCount = 0 enemyCountDisplay = display.newText(enemyCount , 40 , 40, native.systemFont, 30) enemyCountTextDisplay = display.newText("Enemies Left: " , 40 , 40, native.systemFont, 30) -- splits the screen into the shape X so we know on which quadrant the cursor is at the moment local function onMouseEvent( event ) --sets current cursors x and y values MouseX = event.x MouseY = event.y --top triangle if(event.x > event.y and ((event.x+event.y)<=1200 and event.y < 640)) then direction = 1 --right trangle elseif(event.x > event.y and ((event.x+event.y)>=1200 and event.x > 640)) then direction = 2 --bottom triangle elseif(event.x < event.y and ((event.x+event.y)>=1200 and event.y> 640)) then direction = 3 --left triangle elseif(event.x < event.y and ((event.x+event.y)<=1200 and event.x < 640)) then direction = 4 end return direction end --display level number roomNumber = "Tutorial Room" displayRoom = display.newText( roomNumber, 0, 0, native.systemFont, 40 ) --display inventory / make body static local sheetOptions1 = { width = 198, height = 96, numFrames = 8, sheetContentWidth = 1584, sheetContentHeight = 96, } local inventorySheet = graphics.newImageSheet( "graphics/UI/uiWeaponsItems.png", sheetOptions1 ) local sequenceData = { {name = "idle", frames = { 1}, time = 0, loopCount = 0}, {name = "UI", frames = { 2,3,4,5,6,7,8}, time = 3700, loopCount = 0}, } inventory = display.newSprite(inventorySheet, sequenceData ) inventory.alpha = 1 inventory:setSequence( "idle" ) inventory:setFrame( 1 ) --weapons on the UI local sheetOptions2 = { width = 64, height = 64, numFrames = 2, sheetContentWidth = 64, sheetContentHeight = 128, } local weaponSheet = graphics.newImageSheet( "graphics/items/weapons.png", sheetOptions2 ) local sequenceData = { name = "UI", frames = { 1, 2}, time = 0, loopCount = 0 } weapon = display.newSprite(weaponSheet, sequenceData ) weapon.alpha = 1 weapon:setFrame( 1 ) --display health / make body static local sheetOptions3 = { width = 480, height = 48, numFrames = 11, sheetContentWidth = 480, sheetContentHeight = 528, } local healthSheet = graphics.newImageSheet( "graphics/UI/myPlayerHealth.png", sheetOptions3 ) local sequenceData2 = { name = "UI", frames = { 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, time = 0, loopCount = 0 } health = display.newSprite(healthSheet, sequenceData2 ) health:setFrame( 1 ) health.alpha = 1 --updates the UI with a timer local function CameraTimedReset ( event ) camera.x = ((myPlayer.x)+ (MouseX/3)) - 215 --camera x value camera.y = ((myPlayer.y)+ (MouseY/3)) - 230 --camera y value grapplepos.x = ((myPlayer.x) + (MouseX + MouseX/3) - 855 ) -- cursor positon from the myPlayer grapplepos.y = ((myPlayer.y) + (MouseY + MouseY/3 ) - 870) -- cursor positon from the myPlayer inventory.x = camera.x - 520 -- inventory on bottom inventory.y = camera.y + 350 -- inventory on bottom displayRoom.x = camera.x -- displays room number displayRoom.y = camera.y - 350 -- displays room number weapon.x = camera.x - 570 --inventory on bottom weapon.y = camera.y + 350 --inventory on bottom health.x = camera.x - 360 --inventory on bottom health.y = camera.y - 500 --inventory on bottom enemyCountDisplay.x = camera.x + 500 enemyCountDisplay.y = camera.y - 500 enemyCountTextDisplay.x = camera.x + 370 enemyCountTextDisplay.y = camera.y - 500 health:setFrame( playerHP +1 ) grapplepos:toFront() --so the crosshair is always ontop of the screen --player alpha goes back to 1 after it lowers if(myPlayer.alpha ~= 1)then myPlayer.alpha = myPlayer.alpha + 0.02 else myPlayer:setFillColor( 255) end --room display dissapears after it shows when you enter a new room if(displayRoom.alpha>0)then displayRoom.alpha = displayRoom.alpha - 0.01 end end cameraReset = timer.performWithDelay(1, CameraTimedReset , 0) Runtime:addEventListener( "mouse" , onMouseEvent )
--[[ -- 作者:Steven -- 日期:2017-02-26 -- 文件名:file_apis.lua -- 版权说明:南京正溯网络科技有限公司.版权所有©copy right. -- 文件上传下载的接口封装文件,用户文件管理方案的接口定义 --]] --[[ -- 上传文件基础功能文件,用于其他需要上传系统的调用,调用完成之后,将文件存储到系统中,大文件通过hadoop存储, -- 小文件通过Haystack系统存储 -- 上传之后需要计算md5和sha1编码,同时生成唯一文件编号,写入数据库和redis系统中,写数据库和redis注意分布式存储 -- 一切处理完成之后,系统将文件唯一编号返回给系统,失败返回nil -- 首先客户端将上传文件传送到本地址,根据客户端上传上来的文件的sha1 和 md5 判断是否存在该文件,如果存在则直接返回 -- 如果没有则存储到系统中,生成 -- example --]] local cjson = require "cjson" local resty_md5 = require "resty.md5" local uuid = require "resty.uuid" local resty_sha1 = require "resty.sha1" local upload = require "resty.upload" local str = require "resty.string" local db_help = require "db.lua_db_help" local api_data = require "common.api_data_help" local file_help = require "files.common.file_help" local _M = {} --[[ -- 将 文件信息写入数据库,同时写入redis 该信息为基础的文件信息 -- example local -- @param file_code 文件唯一编码code -- @param md5_code 文件md5码 -- @param sha1_code 文件sha1码 --]] function _M.insert_new_file( file_code,sha1_code) -- 首先从redis中查询一次是否存在该文件 local redis_cli = file_db:new_redis(); local resRedis = redis_cli:hgetall(sha1_code) if resRedis then return file_code; end --insert into mysql -- body local mysql_cli = file_db:new_mysql(); if not mysql_cli then return nil,1041; end local str = string.format("insert into t_file_records(file_code,sha1_code)values('%s','%s');", file_code,sha1_code) local res, err, errcode, sqlstate = mysql_cli:query(str) if not res then ngx.log(ngx.ERR,"bad result: ".. err.. ": ".. errcode.. ": ".. sqlstate.. "."); if(errcode == 1062) then return file_code,errcode; end return nil,errcode; end -- inser into redis if not redis_cli then ngx.log(ngx.ERR,zs_error_code.REDIS_CRE_CLI_ERROR); else res = redis_cli:hmset(sha1_code,"file_code",file_code) if not res then ngx.log(ngx.ERR,"redis_cli.hset error "..sha1_code); end end return file_code,errcode; end --[[ -- 将 查询是否存在指定文件sha1编码的文件存在 redis 中存储格式为hmap key:sha1 subkey: file_code value: filecodeimpl subkey: md5_code value: md5 -- example -- @param sha1_code 文件sha1码 --]] function _M.find_file_by_sha1(sha1_code) -- 从redis中查询,如果不存在则在mysql中查询 local redis_cli = file_db:new_redis(); if not redis_cli then ngx.log(ngx.ERR,ZS_ERROR_CODE.REDIS_CRE_CLI_ERROR); else local res = redis_cli:hgetall(sha1_code) if not res then ngx.log(ngx.ERR,ZS_ERROR_CODE.REDIS_NO_DATA); else --ngx.log(ngx.ERR,zs_error_code.REDIS_CRE_CLI_ERROR); --ngx.say("redis 结果:"..cjson.encode(res)) return table.array2record(res); end end --从数据库中查询 local mysql_cli = file_db:new_mysql(); if not mysql_cli then return nil,1041; end local str = string.format("select * from t_file_records where sha1_code='%s'", sha1_code) local res, err, errcode, sqlstate = mysql_cli:query(str) if not res then ngx.log(ngx.ERR,"bad result: ", err, ": ", errcode, ": ", sqlstate, "."); return nil,errcode; end -- inser into redis if redis_cli then local fileRec = res[1]; if fileRec then redis_cli:hmset(fileRec["sha1_code"],"file_code",fileRec["file_code"]); end end return res,errcode; end --[[ -- 搜索用户的存储文件,主要用于文件的查询 -- example local srcSql = " select * from t_user_files " local db_help = require "db.lua_db_help" local param = db_help.new_param(); param.user_code_fk="user_code_1" param.file_name="file" local start_index = args["start_index"] and args["start_index"] or 0; local offset = args["offset"] and args["offset"] or 20; local strsql = db_help.select_help(srcSql,param,"and") -- @param srcSql sql 前半部分语句 -- @param param 用户需要组装的数据参数表,其中record 的元素信息必须为key=value的格式 key为表的字段名 -- @param condition 搜索语句的条件,主要表现为字符串 -- @param start_index,offset 用于分页查询 该参数可优化 --]] function _M.find_user_files(srcSql,param,condition,start_index,offset) --从数据库中查询 local mysql_cli = file_db:new_mysql(); if not mysql_cli then return nil,1041; end local sql = db_help.select_help(srcSql,param,condition,start_index,offset) local res, err, errcode, sqlstate = mysql_cli:query(sql) if not res then ngx.log(ngx.ERR,"bad result: ", err, ": ", errcode, ": ", sqlstate, "."); return nil,errcode; end return res,errcode; end --[[ 本地将解释一下 post 上传数据包括以下几种方式 1, application/x-www-form-urlencoded 这应该是最常见的 POST 提交数据的方式了。 浏览器的原生 <form> 表单,如果不设置 enctype 属性, 那么最终就会以 application/x-www-form-urlencoded 方式提交数据。 请求类似于下面这样(无关的请求头在本文中都省略掉了): BASHPOST http://www.example.com HTTP/1.1 Content-Type: application/x-www-form-urlencoded;charset=utf-8 title=test&sub%5B%5D=1&sub%5B%5D=2&sub%5B%5D=3 首先,Content-Type 被指定为 application/x-www-form-urlencoded; 其次,提交的数据按照 key1=val1&key2=val2 的方式进行编码,key 和 val 都进行了 URL 转码。 大部分服务端语言都对这种方式有很好的支持。例如 PHP 中,$_POST['title'] 可以获取到 title 的值,$_POST['sub'] 可以得到 sub 数组。 很多时候,我们用 Ajax 提交数据时,也是使用这种方式。 例如 JQuery 和 QWrap 的 Ajax,Content-Type 默认值都是「application/x-www-form-urlencoded;charset=utf-8」。 2,multipart/form-data 这又是一个常见的 POST 数据提交的方式。我们使用表单上传文件时,必须让 <form> 表单的 enctyped 等于 multipart/form-data。 直接来看一个请求示例: 3,application/json 该模式主要直接封装成json进行上传 ]] function get_filename(res) local filename = ngx.re.match(res,'(.+)filename="(.+)"(.*)') if filename then return filename[2] end end function get_uploadmsg(res) local get_uploadmsg = ngx.re.match(res,'(.+)name="uploadmsg"(.*)') if get_uploadmsg then return get_uploadmsg[2] end end function get_postmsg(res) local get_uploadmsg = ngx.re.match(res,'(.+)name="(.*)') if get_uploadmsg then return get_uploadmsg[2] end end --[[ -- _M.exsit_file_help( filesTable ) 该函数主要用于判断系统中是否存在指定的文件, -- 如果不存在指定文件,将结果加入返回的数据表中 -- example -- @param filesTable 存储文件信息的数组,该数组中包含指定的字段sha1_code 字段 --]] function _M.file_exsit_help( filesTable ) -- body if not filesTable then return nil end local len = table.getn(filesTable) local desTable = {} ; if len == 0 then return nil end local desIndex = 1; for i=1,len,1 do local fileInfo = filesTable[i]; local res,err = _M.find_file_by_sha1(fileInfo.sha1_code) if not table.isnull(res) then -- 没查找指定sha1码的文件 desTable[desIndex] = table.clone(fileInfo); desIndex = desIndex + 1; end end return desTable; end --[[ -- _M.pre_uploading(_usercode) 文件上传主函数,客户端上传文件的保存与存储 -- 由于可能存在多个文件上传,所以系统将上传之后的状态也会返回到客户端中 -- example local file_help = require "files.common.file_apis" -- 系统需要预处理一次,即一个用户只能上传一个或指定的多个文件 -- @param _usercode 用户唯一编号 --]] function _M.pre_uploading( _usercode ) local chunk_size = 500*1024 local form, err = upload:new(chunk_size) if not form then ngx.log(ngx.ERR, "failed to new upload: ", err) return api_data.new_failed(); end local upload_msg = nil; local upload_msg_body = nil; -- 用于更进一步的访问限制,减少系统被攻击的几率,在access接入的时候进行一次加密解密处理基本可以杜绝 -- 如果有必要 可以再一次进行判断 --local upload_msg_index = 0; while true do local typ, res, err = form:read() if not typ then ngx.log(ngx.ERR, "failed to read: ", err) return api_data.new_failed(); end if typ == "header" then upload_msg = get_uploadmsg(res[2]) --upload_msg_index = upload_msg_index+1; elseif typ == "body" then if upload_msg then upload_msg_body = res; break; end elseif typ == "part_end" then -- do nothing elseif typ == "eof" then break else -- do nothing end end -- 根据获取的msg信息处理需要上传的文件 if not upload_msg_body then return api_data.new_failed(); end local filesTable = cjson.decode(upload_msg_body); -- 生成唯一编码 -- 随机生成uuid 通过md5进行唯一编码 local md5 = resty_sha1:new() -- 生成唯一uuid local file_id = uuid.generate() -- 通过md5 编码一次 md5:update(file_id) local md5_sum = md5:final() md5:reset() local data = api_data.new_success(); data.tokenex = str.to_hex(md5_sum); -- 写入redis local redis_cli = file_db:new_redis(); if not redis_cli then ngx.log(ngx.ERR,ZS_ERROR_CODE.REDIS_CRE_CLI_ERROR); return api_data.new_failed(); else local file_token_ex = "files_token_ex_".._usercode; local res = redis_cli:set(file_token_ex,data.tokenex ) if not res then ngx.log(ngx.ERR,ZS_ERROR_CODE.REDIS_SET_ERROR); return api_data.new_failed(); else -- 设置超时 5 秒 -- local res = redis_cli:pexpire(file_token_ex,5000); if not res then ngx.log(ngx.ERR,ZS_ERROR_CODE.REDIS_PEXPIRE_ERROR); return api_data.new_failed(); end end end data.data = _M.file_exsit_help( filesTable ) return data; end --[[ -- _M.handle_uploading(token_ex) 文件上传主函数,客户端上传文件的保存与存储 -- 由于可能存在多个文件上传,所以系统将上传之后的状态也会返回到客户端中 -- example local file_help = require "files.common.file_apis" -- 系统需要预处理一次,即一个用户只能上传一个或指定的多个文件 -- 由于用户并发可能同时上传多个文件,系统第一期默认将所有的文件存储到本地 -- 然后将文件通过sha1写入用户记录数据表和文件记录表 --]] local dst_dir = "." function _M.handle_uploading() local chunk_size = 500*1024 local form, err = upload:new(chunk_size) if not form then ngx.log(ngx.ERR, "failed to new upload: ", err) return nil; end local sha1 = resty_sha1:new() local uuid_name; local file = nil local post_key = nil; local extend_info = {}; local files_info = {}; while true do local typ, res, err = form:read() if not typ then ngx.log(ngx.ERR, "failed to read: ", err) return api_data.new_failed(); end if typ == "header" then local file_name = get_filename(res[2]) if file_name then uuid_name = uuid.generate_time()..'.'..file_help.getExtension(file_name); file = io.open(dst_dir .. "/" .. uuid_name , "wb") if not file then ngx.log(ngx.ERR, "failed to open file ", uuid_name) return api_data.new_failed(); end else post_key = get_postmsg(res[2]) end elseif typ == "body" then if file then file:write(res) sha1:update(res) elseif post_key then extend_info[post_key] = res; -- 可能存在bug!!!!!!!-------------- end elseif typ == "part_end" then local sha1_sum = sha1:final() sha1:reset() if file then file:close() file = nil files_info[uuid_name] = {sha1_code=str.to_hex(sha1_sum)}; end elseif typ == "eof" then break else -- do nothing end end local data = api_data.new_success(); data.data = files_info; return data; end return _M
-- Colorscheme name: nord.nvim -- Description: Port of articicestudio's nord theme for neovim -- Author: https://github.com/shaunsingh local util = require('nord.util') -- Load the theme local set = function () util.load() end return { set = set }
local w = display.contentWidth for i=0,w do local sin = 400 - math.sin(math.rad(i)) * 100 local cos = 700 - math.cos(math.rad(i)) * 100 -- display.newCircle(i, sin, 2) -- display.newCircle(i, cos, 2) local line = display.newLine(i, sin, i, cos) line:setStrokeColor(1-(i/w),i/w,0) end print(math.deg(math.pi)) print(math.exp(1)) print(math.pow(2,3))
--!A cross-platform build utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific package governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2018, TBOOX Open Source Group. -- -- @author ruki -- @file package.lua -- -- define module local package = package or {} local _instance = _instance or {} -- load modules local os = require("base/os") local io = require("base/io") local path = require("base/path") local utils = require("base/utils") local table = require("base/table") local global = require("base/global") local interpreter = require("base/interpreter") local sandbox = require("sandbox/sandbox") local config = require("project/config") local platform = require("platform/platform") local sandbox = require("sandbox/sandbox") local sandbox_os = require("sandbox/modules/os") local sandbox_module = require("sandbox/modules/import/core/sandbox/module") -- new an instance function _instance.new(name, info, rootdir) -- new an instance local instance = table.inherit(_instance) -- parse name .e.g vendor.name local nameinfo = name:split("%.") -- init instance instance._FULLNAME = name instance._NAME = nameinfo[2] or name instance._VENDOR = nameinfo[1] instance._INFO = info instance._ROOTDIR = rootdir -- ok return instance end -- get the package configure function _instance:get(name) -- the info local info = self._INFO -- get if from info first local value = info[name] if value ~= nil then return value end end -- get the package full name with vendor function _instance:fullname() return self._FULLNAME end -- get the package name without vendor function _instance:name() return self._NAME end -- get the package alias function _instance:alias() local requireinfo = self:requireinfo() if requireinfo then return requireinfo.alias end end -- get the package vendor function _instance:vendor() return self._VENDOR end -- get urls function _instance:urls() return self._URLS or table.wrap(self:get("urls")) end -- get urls function _instance:urls_set(urls) self._URLS = urls end -- get the alias of url, @note need raw url function _instance:url_alias(url) local urls_extra = self:get("__extra_urls") if urls_extra then local urlextra = urls_extra[url] if urlextra then return urlextra.alias end end end -- get deps function _instance:deps() return self._DEPS end -- get order deps function _instance:orderdeps() return self._ORDERDEPS end -- get sha256 of the url_alias@version_str function _instance:sha256(url_alias) -- get sha256 local versions = self:get("versions") local version_str = self:version_str() if versions and version_str then local sha256 = nil if url_alias then sha256 = versions[url_alias .. ":" ..version_str] end if not sha256 then sha256 = versions[version_str] end -- ok? return sha256 end end -- this package is from system/local/global? -- -- @param kind the from kind -- -- system: from the system directories (.e.g /usr/local) -- local: from the local project package directories (.e.g projectdir/.xmake/packages) -- global: from the global package directories (.e.g ~/.xmake/packages) -- function _instance:from(kind) return self._FROMKIND == kind end -- get the package kind, binary or nil(static, shared) function _instance:kind() return self:get("kind") end -- get the build directory of this package function _instance:buildir() return path.join(self:cachedir(), "build") end -- get the cached directory of this package function _instance:cachedir() return path.join(package.cachedir(), self:fullname(), self:version_str()) end -- get the installed directory of this package function _instance:installdir() -- only be a system package without urls, no installdir if self:from("system") then return end -- make install directory return path.join(package.installdir(self:from("global")), self:fullname(), self:version_str()) end -- get versions function _instance:versions() -- make versions if self._VERSIONS == nil then -- get versions local versions = {} for version, _ in pairs(table.wrap(self:get("versions"))) do -- remove the url alias prefix if exists local pos = version:find(':', 1, true) if pos then version = version:sub(pos + 1, -1) end table.insert(versions, version) end -- remove repeat self._VERSIONS = table.unique(versions) end return self._VERSIONS end -- get the version function _instance:version() return self._VERSION or {} end -- get the version string function _instance:version_str() return self:version().raw or self:version().version end -- the verson from tags, branches or versions? function _instance:version_from(...) -- from source? for _, source in ipairs({...}) do if self:version().source == source then return true end end end -- set the version function _instance:version_set(version, source) -- init package version if type(version) == "string" then version = {version = version, source = source} else version.source = source end -- save version self._VERSION = version end -- get the require info function _instance:requireinfo() return self._REQUIREINFO end -- set the require info function _instance:requireinfo_set(requireinfo) self._REQUIREINFO = requireinfo end -- get xxx_script function _instance:script(name, generic) -- get script local script = self:get(name) local result = nil if type(script) == "function" then result = script elseif type(script) == "table" then -- match script for special plat and arch local plat = (config.get("plat") or "") local pattern = plat .. '|' .. (config.get("arch") or "") for _pattern, _script in pairs(script) do if not _pattern:startswith("__") and pattern:find('^' .. _pattern .. '$') then result = _script break end end -- match script for special plat if result == nil then for _pattern, _script in pairs(script) do if not _pattern:startswith("__") and plat:find('^' .. _pattern .. '$') then result = _script break end end end -- get generic script result = result or script["__generic__"] or generic end -- only generic script result = result or generic -- imports some modules first if result and result ~= generic then local scope = getfenv(result) if scope then for _, modulename in ipairs(table.wrap(self:get("imports"))) do scope[sandbox_module.name(modulename)] = sandbox_module.import(modulename, {anonymous = true}) end end end -- ok return result end -- fetch package info from the local packages -- -- @return {packageinfo}, fetchfrom (.e.g local/global/system) -- function _instance:fetch(force) -- attempt to get it from cache local fetchfrom = self._FETCHFROM local fetchinfo = self._FETCHINFO if not force and fetchinfo then return fetchinfo, fetchfrom end -- fetch binary tool? fetchinfo = nil fetchfrom = nil if self:kind() == "binary" then -- import find_tool self._find_tool = self._find_tool or sandbox_module.import("lib.detect.find_tool", {anonymous = true}) -- fetch it from the system directories fetchinfo = self._find_tool(self:name(), {force = force}) if fetchinfo then fetchfrom = "system" -- ignore self:requireinfo().system end else -- import find_package self._find_package = self._find_package or sandbox_module.import("lib.detect.find_package", {anonymous = true}) -- fetch it from the package directories first local installdir = self:installdir() if not fetchinfo and installdir then fetchinfo = self._find_package(self:name(), {packagedirs = installdir, system = false, cachekey = "package:fetch", force = force}) if fetchinfo then fetchfrom = self._FROMKIND end end -- fetch it from the system directories if not fetchinfo then local system = self:requireinfo().system if system == nil then -- find system package by default system = true end if system then fetchinfo = self._find_package(self:name(), {force = force}) if fetchinfo then fetchfrom = "system" end end end end -- save to cache self._FETCHINFO = fetchinfo self._FETCHFROM = fetchfrom -- ok return fetchinfo, fetchfrom end -- exists this package in local function _instance:exists() return self._FETCHINFO end -- the interpreter function package._interpreter() -- the interpreter has been initialized? return it directly if package._INTERPRETER then return package._INTERPRETER end -- init interpreter local interp = interpreter.new() assert(interp) -- define apis interp:api_define(package.apis()) -- save interpreter package._INTERPRETER = interp -- ok? return interp end -- get package apis function package.apis() return { values = { -- package.set_xxx "package.set_urls" , "package.set_kind" , "package.set_homepage" , "package.set_description" -- package.add_xxx , "package.add_deps" , "package.add_urls" , "package.add_imports" } , script = { -- package.on_xxx "package.on_build" , "package.on_install" , "package.on_test" -- package.before_xxx , "package.before_build" , "package.before_install" , "package.before_test" -- package.before_xxx , "package.after_build" , "package.after_install" , "package.after_test" } , dictionary = { -- package.add_xxx "package.add_versions" } } end -- get install directory function package.installdir(is_global) -- get directory if is_global then return path.join(global.directory(), "packages") else return path.join(config.directory(), "packages") end end -- the cache directory function package.cachedir() return path.join(global.directory(), "cache", "packages") end -- load the package from the package url function package.load_from_url(packagename, packageurl) -- make a temporary package file local packagefile = os.tmpfile() .. ".lua" -- make package description local packagedata = string.format([[ package("%s") set_urls("%s") ]], packagename, packageurl) -- write a temporary package description to file local ok, errors = io.writefile(packagefile, packagedata) if not ok then return nil, errors end -- load package instance local instance, errors = package.load_from_repository(packagename, false, nil, packagefile) -- remove the package file os.rm(packagefile) -- ok? return instance, errors end -- load the package from the system directories function package.load_from_system(packagename) -- get it directly from cache first package._PACKAGES = package._PACKAGES or {} if package._PACKAGES[packagename] then return package._PACKAGES[packagename] end -- new an empty instance local instance, errors = _instance.new(packagename, {}, package._interpreter():rootdir()) if not instance then return nil, errors end -- mark as system package instance._FROMKIND = "system" -- save instance to the cache package._PACKAGES[packagename] = instance -- ok return instance end -- load the package from the project file function package.load_from_project(packagename, project) -- get it directly from cache first package._PACKAGES = package._PACKAGES or {} if package._PACKAGES[packagename] then return package._PACKAGES[packagename] end -- load packages (with cache) local packages, errors = project.packages() if not packages then return nil, errors end -- get interpreter local interp = project.interpreter() or package._interpreter() -- not found? if not packages[packagename] then return end -- new an instance local instance, errors = _instance.new(packagename, packages[packagename], interp:rootdir()) if not instance then return nil, errors end -- mark as local package instance._FROMKIND = "local" -- save instance to the cache package._PACKAGES[packagename] = instance -- ok return instance end -- load the package from the package directory or package description file function package.load_from_repository(packagename, is_global, packagedir, packagefile) -- get it directly from cache first package._PACKAGES = package._PACKAGES or {} if package._PACKAGES[packagename] then return package._PACKAGES[packagename] end -- find the package script path local scriptpath = packagefile if not packagefile and packagedir then scriptpath = path.join(packagedir, "xmake.lua") end if not scriptpath or not os.isfile(scriptpath) then return nil, string.format("the package %s not found!", packagename) end -- load package and disable filter, we will process filter after a while local results, errors = package._interpreter():load(scriptpath, "package", true, false) if not results and os.isfile(scriptpath) then return nil, errors end -- get the package info local packageinfo = nil for name, info in pairs(results) do packagename = name -- use the real package name in package() definition packageinfo = info break end -- check this package if not packageinfo then return nil, string.format("%s: the package %s not found!", scriptpath, packagename) end -- new an instance local instance, errors = _instance.new(packagename, packageinfo, package._interpreter():rootdir()) if not instance then return nil, errors end -- mark as global/project package? instance._FROMKIND = utils.ifelse(is_global, "global", "local") -- save instance to the cache package._PACKAGES[packagename] = instance -- ok return instance end -- return module return package
-- # abcd.lua -- -- ## Compute classifier performance measures -- -- To use this code: -- -- 1. Create an `ABCD` object. -- 2. Run your classifier on a test suite. Take the `predicted` and -- `actual` classification and throw it a `ABCD1`. -- 3. After that, get a report using `ABCDReport`. -- -- For example suppose: -- -- - Six times, `yes` objects are predicted to be `yes`; -- - Twice, a `no` obect is rpedicted to be `no`; -- - Five times, `maybe`s are called `maybe`s; -- - And once, a `maybe` is called `no`. -- -- After all that, `abcd:report()` would print: -- -- db | rx | num | a | b | c | d | acc | pre | pd | pf | f | g | class -- ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- |----- -- data | rx | 14 | 11 | | 1 | 2 | 0.93 | 0.67 | 1.00 | 0.08 | 0.80 | 0.96 | no -- data | rx | 14 | 8 | | | 6 | 0.93 | 1.00 | 1.00 | 0.00 | 1.00 | 1.00 | yes -- data | rx | 14 | 8 | 1 | | 5 | 0.93 | 1.00 | 0.83 | 0.00 | 0.91 | 0.91 | maybe -- local _,the = require"tricks", require"the" local class,fmt,inc,lines,new = _.class, _.fmt, _.inc, _.lines, _.new local o,oo,push,slots = _.o, _.oo, _.push, _.slots -- ## Class local ABCD = class"ABCD" function ABCD:new(data,rx) return new({data= data or "data", rx= rx or "rx",known={}, a={}, b={}, c={}, d={}, yes=0, no=0}, ABCD) end function ABCD.exists(i,x, new) new = not i.known[x] inc(i.known,x) if new then i.a[x]=i.yes + i.no; i.b[x]=0; i.c[x]=0; i.d[x]=0 end end function ABCD.add(i,want,got) i:exists(want) i:exists(got) if want==got then i.yes=i.yes+1 else i.no=i.no+1 end for x,_ in pairs(i.known) do if want == x then inc(want == got and i.d or i.b, x) else inc(got == x and i.c or i.a, x) end end end function ABCD.report(i, p,out,a,b,c,d,pd,pf,pn,f,acc,g,prec) p = function (z) return math.floor(100*z + 0.5) end out= {} for x,_ in pairs( i.known ) do pd,pf,pn,prec,g,f,acc = 0,0,0,0,0,0,0 a= (i.a[x] or 0); b= (i.b[x] or 0); c= (i.c[x] or 0); d= (i.d[x] or 0); if b+d > 0 then pd = d / (b+d) end if a+c > 0 then pf = c / (a+c) end if a+c > 0 then pn = (b+d) / (a+c) end if c+d > 0 then prec = d / (c+d) end if 1-pf+pd > 0 then g=2*(1-pf) * pd / (1-pf+pd) end if prec+pd > 0 then f=2*prec*pd / (prec + pd) end if i.yes + i.no > 0 then acc= i.yes / (i.yes + i.no) end out[x] = { data=i.data, rx=i.rx, num = i.yes+i.no, a=a, b=b,c=c,d=d, acc=p(acc), prec=p(prec), pd=p(pd), pf=p(pf), f=p(f), g=p(g), class=x} end return out end function ABCD.show(i,report, s,d,t) print"" d,s = "---", "%10s | %10s | %4s | %4s | %4s | %4s | %3s | %3s| %3s | %4s | %3s | %3s |" print(fmt(s,"db","rx","a","b","c","d","acc","pd","pf","prec","f","g")) print(fmt(s,d,d,d,d,d,d,d,d,d,d,d,d)) report = report or i:report() for _,x in pairs(slots(report)) do t = report[x] print(fmt(s.." %s", t.data,t.rx,t.a, t.b, t.c, t.d,t.acc, t.pd, t.pf, t.prec, t.f, t.g, x)) end end return ABCD
local VariableFactory = require 'factory'() function VariableFactory:build(name, min, max, discrete_points) self.name = name or '' self.min = min or 0.0 self.max = max or 10.0 self.terms = {} self.range = self.max - self.min self.disc = discrete_points or self.range + 1 self.step = self.range / (self.disc - 1) end function VariableFactory:add_term(term) self.terms[term.name] = term return self end function VariableFactory:__tostring() local s = { ('variable %q'):format(self.name), ('range: [%d-%d]'):format(self.min, self.max), } for _, term in pairs(self.terms) do table.insert(s, ('%s'):format(term)) end return table.concat(s, '\n') end return VariableFactory
local a=module('_core','libs/Tunnel')local b=module('_core','libs/Proxy')APICKF=b.getInterface('API')cAPI=a.getInterface('cAPI')hpp={}a.bindInterface("hpp_contraband",hpp)Citizen.CreateThread(function()while true do Citizen.Wait(5*60*1000)collectgarbage("count")collectgarbage("collect")end end)function hpp.tryBuyItem(c,d)local e=source;local f=APICKF.getUserFromSource(e)if f then local g=f:getCharacter()if g then local h=g.id;local i=g.Inventory:getCapacity()-g.Inventory:getWeight()local j=APICKF.getItemDataFromId(c)local k=parseInt(j:getWeight())if g:getMoney()<parseInt(d)then return{error=true,reason="Dinheiro insuficiente!"}end;if i<k then return{error=true,reason="Espaço insuficiente!"}end;g:removeItem("generic_money",parseInt(d))g:addItem(c,1)TriggerClientEvent("Notify",e,"sucesso","Você comprou x1 "..j.name.."")return{error=false}end end end
-- =========================================================================== -- Base File -- =========================================================================== include("DiplomacyRibbon"); include("DiplomacyRibbon_CQUI.lua");
--[[ frame.lua A specialized version of the bagnon frame for void storage --]] local MODULE = ... local ADDON, Addon = MODULE:match('[^_]+'), _G[MODULE:match('[^_]+')] local Frame = Addon:NewClass('VaultFrame', 'Frame', Addon.Frame) Frame.Title = LibStub('AceLocale-3.0'):GetLocale(ADDON).TitleVault Frame.ItemFrame = Addon.VaultItemFrame Frame.MoneyFrame = Addon.TransferButton Frame.Bags = {'vault'} Frame.OpenSound = SOUNDKIT.UI_ETHEREAL_WINDOW_OPEN Frame.CloseSound = SOUNDKIT.UI_ETHEREAL_WINDOW_CLOSE Frame.MoneySpacing = 30 Frame.BrokerSpacing = 2 --[[ Modifications ]]-- function Frame:New(id) local f = Addon.Frame.New(self, id) f.deposit = self.ItemFrame:New(f, {DEPOSIT}, DEPOSIT) f.deposit:SetPoint('TOPLEFT', 10, -55) f.deposit:Hide() f.withdraw = self.ItemFrame:New(f, {WITHDRAW}, WITHDRAW) f.withdraw:SetPoint('TOPLEFT', f.deposit, 'BOTTOMLEFT', 0, -5) f.withdraw:Hide() return f end function Frame:RegisterSignals() Addon.Frame.RegisterSignals(self) self:RegisterFrameSignal('TRANFER_TOGGLED', 'OnTransferToggled') end function Frame:OnHide() Addon.Frame.OnHide(self) CloseVoidStorageFrame() end function Frame:OnTransferToggled(_, transfering) self.deposit:SetShown(transfering) self.withdraw:SetShown(transfering) self.itemFrame:SetShown(not transfering) if transfering then StaticPopup_Show(ADDON .. 'COMFIRM_TRANSFER').data = self else StaticPopup_Hide(ADDON .. 'COMFIRM_TRANSFER') end end --[[ Properties ]]-- function Frame:GetItemInfo(bag, slot) if bag == 'vault' then return Addon.Frame:GetItemInfo(bag, slot) else local get = bag == DEPOSIT and GetVoidTransferDepositInfo or GetVoidTransferWithdrawalInfo local item = {} for i = 1,9 do if get(i) then slot = slot - 1 if slot == 0 then item.id, item.icon, item._, item.recent, item.filtered, item.quality = get(i) return item end end end return item end end function Frame:IsBagFrameShown() end function Frame:HasSortButton() end function Frame:HasBagToggle() end function Frame:HasMoneyFrame() return true end
--- moneybox.lua --- -- This is an example how to create an importable archetype, -- that any DSB dungeon can then load via dsb_import_arch(file, root_name). -- All you have to distribute is this single Lua file, and any -- bitmaps that the new object needs. -- -- The names used by the data structures created here should be -- dynamically generated, using the ROOT_NAME variable that -- will be defined by the engine when this file is parsed. -- This helps to prevent name collisions if the dungeon designer -- wants to use several similarly named items. -- Load any graphics that your custom object will need. -- Temporary bitmaps should be declared local so the garbage collector -- will be able to take care of them. -- gfx[ROOT_NAME] = dsb_get_bitmap("MONEYBOX") gfx[ROOT_NAME .. "_icon"] = dsb_get_bitmap("MONEYBOX_ICON") gfx[ROOT_NAME .. "_alticon"] = dsb_get_bitmap("MONEYBOX_ALTICON") gfx[ROOT_NAME .. "_inside"] = dsb_get_bitmap("MONEYBOX_INSIDE") -- -- Now define any functions that your custom object will need. -- function moneybox_click(id, zone, mouseobj) local self = dsb_find_arch(id) local targarch = obj[self.zone_obj[zone+1]] local mousearch = nil if (mouseobj) then mousearch = dsb_find_arch(mouseobj) end if (mousearch and mousearch ~= targarch) then return false end if (mouseobj) then dsb_move(dsb_pop_mouse(), IN_OBJ, id, VARIABLE, 0) else local iobj for iobj in dsb_in_obj(id) do local iarch = dsb_find_arch(iobj) if (iarch == targarch) then dsb_push_mouse(iobj) return true end end end end function moneybox_subrenderer(self, id) local zcs = { {x = 34, y = 4}, {x = 94, y = 4}, {x =154, y = 4}, {x = 34, y =74}, {x = 94, y =74}, {x =154, y =74} } local ninside = { 0, 0, 0, 0, 0, 0 } local sr = dsb_subrenderer_target() use_exvar(id) if (not exvar[id].draw_seed) then exvar[id].draw_seed = dsb_rand(8, 1023) end local ds = exvar[id].draw_seed dsb_bitmap_clear(sr, base_background) dsb_bitmap_draw(self.inside_gfx, sr, 30, 0, false) local iobj for iobj in dsb_in_obj(id) do local iarch = dsb_find_arch(iobj) local i if (iarch.class == "COIN" or iarch.class == "GEM") then for i=1,6 do if (obj[self.zone_obj[i]] == iarch) then ninside[i] = ninside[i] + 1 end end end end local i for i=1,6 do local x = zcs[i].x local y = zcs[i].y dsb_msgzone(sr, id, i-1, zcs[i].x, zcs[i].y, 58, 68, M_NEXTTICK) while (ninside[i] > 0) do local tx = (ds + 8 * ninside[i]) % 26 local ty = (ds/2 + 16 * ninside[i]) % 36 dsb_bitmap_draw(obj[self.zone_obj[i]].icon, sr, x + tx, y + ty, false) ninside[i] = ninside[i] - 1 end end end -- -- Finally, declare the new arch into the object table, using the -- dynamic name assigned by the dungeon designer. -- obj[ROOT_NAME] = { name="MONEY BOX", type="THING", class="CONTAINER", mass=11, dungeon=gfx[ROOT_NAME], icon=gfx[ROOT_NAME .. "_icon"], alt_icon=gfx[ROOT_NAME .. "_alticon"], inside_gfx=gfx[ROOT_NAME .. "_inside"], msg_handler = { [M_NEXTTICK] = moneybox_click }, zone_obj = { "gem_blue", "gem_orange", "gem_green", "coin_gold", "coin_silver", "coin_copper" }, subrenderer = moneybox_subrenderer, to_r_hand = alticon, from_r_hand = normicon, max_throw_power=30 }
local _module_0 = { } local find, sub, match = string.find, string.sub, string.match local sanitize sanitize = function(input) if "string" == type(input) then return input:gsub("[%(%)%.%%%+%-%*%?%[%]%^%$]", "%%%0") else return input end end local trim trim = function(input) do local n = find(input, "%S") if n then return match(input, ".*%S", n) else return "" end end end local lines lines = function(s) local res, pos = { }, 1 while true do local lep = string.find(s, "[\r\n]", pos) if not lep then break end local le = sub(s, lep, lep) if (le == "\r") and ((sub(s, lep + 1, lep + 1)) == "\n") then le = "\r\n" end local ln = sub(s, pos, lep - 1) res[#res + 1] = ln pos = lep + #le end if pos <= #s then res[#res + 1] = sub(s, pos) end return res end local lconcat lconcat = function(ta, tb) local tc = { } for _index_0 = 1, #ta do local elem = ta[_index_0] tc[#tc + 1] = elem end for _index_0 = 1, #tb do local elem = tb[_index_0] tc[#tc + 1] = elem end return tc end local extract extract = function(input, language, options) if input == nil then input = "" end if language == nil then language = { } end if options == nil then options = { } end local lt = lines(input) local comments = { } local comment = { content = { } } local tracking = { multi = false, ignore = false } if options.patterns == nil then options.patterns = false end if options.ignore == nil then options.ignore = "///" end if options.merge == nil then options.merge = true end if options.paragraphs == nil then options.paragraphs = true end local igstring = options.patterns and options.ignore or sanitize(options.ignore) local single, multis, multie if options.patterns then single = language.single or "" local _obj_0 = language.multi if _obj_0 ~= nil then multis = _obj_0[1] end local _obj_1 = language.multi if _obj_1 ~= nil then multie = _obj_1[2] end else single = (sanitize(language.single or "")) multis = (sanitize((function() local _obj_0 = language.multi if _obj_0 ~= nil then return _obj_0[1] end return nil end)() or false)) multie = (sanitize((function() local _obj_0 = language.multi if _obj_0 ~= nil then return _obj_0[2] end return nil end)() or false)) end for lc = 1, #lt do local _continue_0 = false repeat local line = lt[lc] if match(line, "^" .. tostring(single) .. tostring(igstring)) then tracking.ignore = not tracking.ignore elseif tracking.ignore then _continue_0 = true break elseif tracking.multi and multie and match(line, tostring(multie)) then tracking.multi = false comment["end"] = lc comment.content[#comment.content] = match(line, "^(.-)" .. tostring(multie)) comments[#comments + 1] = comment comment = { content = { } } elseif tracking.multi then comment.content[#comment.content] = line elseif multis and match(line, "^" .. tostring(multis)) then tracking.multi = true comment.start = lc comment.content[#comment.content] = match(line, "^" .. tostring(multis) .. "(.+)") elseif single and match(line, "^" .. tostring(single)) then comment.start, comment["end"] = lc, lc comment.content[1] = match(line, "^" .. tostring(single) .. "(.-)$") comments[#comments + 1] = comment comment = { content = { } } end _continue_0 = true until true if not _continue_0 then break end end if options.merge then comments[0] = { type = false, start = 0, ["end"] = -1 } for i = #comments, 1, -1 do local _continue_0 = false repeat local curr = comments[i] local prev = comments[i - 1] if not (curr.start == prev["end"] + 1) then _continue_0 = true break end comments[i - 1] = { content = (lconcat(prev.content, curr.content)), start = prev.start, ["end"] = curr["end"] } table.remove(comments, i) _continue_0 = true until true if not _continue_0 then break end end comments[0] = nil end local lastcomments = { } if options.paragraphs then for _index_0 = 1, #comments do local comment = comments[_index_0] local parts = { } local part = { start = 1 } for lc = 1, #comment.content do if comment.content[lc] == "" then part["end"] = lc - 1 parts[#parts + 1] = part part = { start = lc + 1 } else part[#part + 1] = comment.content[lc] end end part["end"] = #comment.content parts[#parts + 1] = part for _index_1 = 1, #parts do local part = parts[_index_1] lastcomments[#lastcomments + 1] = { start = comment.start + part.start - 1, ["end"] = comment.start + part["end"] - 1, content = (function() local _accum_0 = { } local _len_0 = 1 for _index_2 = 1, #part do local l = part[_index_2] _accum_0[_len_0] = l _len_0 = _len_0 + 1 end return _accum_0 end)() } end end comments = lastcomments end return comments end _module_0["extract"] = extract return _module_0
function string.trim(s) return string.gsub(s, "^%s*(.-)%s*$", "%1") end function string.split(inputstr, sep) if string.len(inputstr) == 0 then return {} end sep = sep or "%s" local t = {} for field, s in string.gmatch(inputstr, "([^" .. sep .. "]*)(" .. sep .. "?)") do table.insert(t, field) if s == "" then return t end end return t end function string.start_with(str1, str2) return string.sub(str1, 1, #str2) == str2 end
-- Generated By protoc-gen-lua Do not Edit local protobuf = require "protobuf" module('FriendInfo_pb', package.seeall) local FRIENDINFO = protobuf.Descriptor(); FRIENDINFO.name = "FriendInfo" FRIENDINFO.full_name = ".com.xinqihd.sns.gameserver.proto.FriendInfo" FRIENDINFO.nested_types = {} FRIENDINFO.enum_types = {} FRIENDINFO.fields = {} FRIENDINFO.is_extendable = false FRIENDINFO.extensions = {} FriendInfo = protobuf.Message(FRIENDINFO) _G.FRIENDINFO_PB_FRIENDINFO = FRIENDINFO
--[[ This module holds all complex mathematical formulas used to work out game values --]] local f = {} --[[-------------------------------------- Stats --]]-------------------------------------- f.stats = {} f.stats[1] = {} f.stats[3] = {} -- Returns the HP value in gen I f.stats[1].hp = function(iv, base, ev, level) return math.floor(level / 100 * ((base + iv) * 2 + math.floor(math.ceil(math.sqrt(ev)) / 4))) + level + 10 end f.stats[1].Hp, f.stats[1].HP = f.stats[1].hp, f.stats[1].hp -- Returns the value of any other stat in gen I f.stats[1].anyOther = function(iv, base, ev, level) return math.floor(level / 100 * ((base + iv) * 2 + math.floor(math.ceil(math.sqrt(ev)) / 4))) + 5 end f.stats[1].anyother, f.stats[1].any_other = f.stats[1].anyOther, f.stats[1].anyOther -- Stats calculation is the same in gen I and gen II f.stats[2] = f.stats[1] -- Returns the HP value in gen III f.stats[3].hp = function(iv, base, ev, level) return math.floor(level / 100 * (2 * base + iv + math.floor(ev / 4))) + level + 10 end f.stats[3].Hp, f.stats[3].HP = f.stats[3].hp, f.stats[3].hp -- Returns the value of any other stat in gen III f.stats[3].anyOther = function(iv, base, ev, level, nature) return math.floor(nature * (5 + math.floor( level / 100 * (2 * base + iv + math.floor( ev / 4))))) end f.stats[3].anyother, f.stats[3].any_other = f.stats[3].anyOther, f.stats[3].anyOther -- Stats calculation stays the same since gen III f.stats[4], f.stats[5], f.stats[6], f.stats[7], f.stats[8] = f.stats[3], f.stats[3], f.stats[3], f.stats[3], f.stats[3] return f
local prometheus = require "kong.plugins.prometheus.exporter" local kong = kong prometheus.init() local PrometheusHandler = { PRIORITY = 13, VERSION = "1.2.1", } function PrometheusHandler.init_worker() prometheus.init_worker() end function PrometheusHandler.log(self, conf) local message = kong.log.serialize() local serialized = {} if conf.per_consumer and message.consumer ~= nil then serialized.consumer = message.consumer.username end prometheus.log(message, serialized) end return PrometheusHandler
local isBleeding = 0 local bleedTickTimer, advanceBleedTimer = 0, 0 local fadeOutTimer, blackoutTimer = 0, 0 local onPainKiller = 0 local wasOnPainKillers = false local onDrugs = 0 local wasOnDrugs = false local legCount = 0 local armcount = 0 local headCount = 0 local playerHealth = nil local playerArmour = nil local limbNotifId = 'MHOS_LIMBS' local bleedNotifId = 'MHOS_BLEED' local bleedMoveNotifId = 'MHOS_BLEEDMOVE' local BodyParts = { ['HEAD'] = { label = 'Head', causeLimp = false, isDamaged = false, severity = 0 }, ['NECK'] = { label = 'Neck', causeLimp = false, isDamaged = false, severity = 0 }, ['SPINE'] = { label = 'Spine', causeLimp = true, isDamaged = false, severity = 0 }, ['UPPER_BODY'] = { label = 'Upper Body', causeLimp = false, isDamaged = false, severity = 0 }, ['LOWER_BODY'] = { label = 'Lower Body', causeLimp = true, isDamaged = false, severity = 0 }, ['LARM'] = { label = 'Left Arm', causeLimp = false, isDamaged = false, severity = 0 }, ['LHAND'] = { label = 'Left Hand', causeLimp = false, isDamaged = false, severity = 0 }, ['LFINGER'] = { label = 'Left Hand Fingers', causeLimp = false, isDamaged = false, severity = 0 }, ['LLEG'] = { label = 'Left Leg', causeLimp = true, isDamaged = false, severity = 0 }, ['LFOOT'] = { label = 'Left Foot', causeLimp = true, isDamaged = false, severity = 0 }, ['RARM'] = { label = 'Right Arm', causeLimp = false, isDamaged = false, severity = 0 }, ['RHAND'] = { label = 'Right Hand', causeLimp = false, isDamaged = false, severity = 0 }, ['RFINGER'] = { label = 'Right Hand Fingers', causeLimp = false, isDamaged = false, severity = 0 }, ['RLEG'] = { label = 'Right Leg', causeLimp = true, isDamaged = false, severity = 0 }, ['RFOOT'] = { label = 'Right Foot', causeLimp = true, isDamaged = false, severity = 0 }, } local injured = {} function IsInjuryCausingLimp() for k, v in pairs(BodyParts) do if v.causeLimp and v.isDamaged then return true end end return false end function IsInjuredOrBleeding() if isBleeding > 0 then return true else for k, v in pairs(BodyParts) do if v.isDamaged then return true end end end return false end function GetDamagingWeapon(ped) for k, v in pairs(Config.Weapons) do if HasPedBeenDamagedByWeapon(ped, k, 0) then ClearEntityLastDamageEntity(ped) return v end end return nil end function ProcessRunStuff(ped) if IsInjuryCausingLimp() and not (onPainKiller > 0) then RequestAnimSet("move_m@injured") while not HasAnimSetLoaded("move_m@injured") do Citizen.Wait(0) end SetPedMovementClipset(ped, "move_m@injured", 1 ) local level = 0 for k, v in pairs(injured) do if v.severity > level then level = v.severity end end SetPedMoveRateOverride(ped, Config.MovementRate[level]) if wasOnPainKillers then SetPedToRagdoll(ped, 1500, 2000, 3, true, true, false) wasOnPainKillers = false TriggerEvent('DoLongHudText', 'You Suddenly Black Out', 5000) TriggerEvent('DoLongHudText', 'You\'ve Realized Doing Drugs Does Not Fix All Your Problems', 5000) end else SetPedMoveRateOverride(ped, 1.0) ResetPedMovementClipset(ped, 1.0) if not wasOnPainKillers and (onPainKiller > 0) then wasOnPainKillers = true end if onPainKiller > 0 then onPainKiller = onPainKiller - 1 end end end function ProcessDamage(ped) if not IsEntityDead(ped) or not (onDrugs > 0) then for k, v in pairs(injured) do if (v.part == 'LLEG' and v.severity > 1) or (v.part == 'RLEG' and v.severity > 1) or (v.part == 'LFOOT' and v.severity > 2) or (v.part == 'RFOOT' and v.severity > 2) then if legCount >= Config.LegInjuryTimer then if not IsPedRagdoll(ped) and IsPedOnFoot(ped) then local chance = math.random(100) if (IsPedRunning(ped) or IsPedSprinting(ped)) then if chance <= Config.LegInjuryChance.Running then TriggerEvent('DoLongHudText', 'You\'re Having A Hard Time Running', 5000) ShakeGameplayCam('SMALL_EXPLOSION_SHAKE', 0.08) -- change this float to increase/decrease camera shake SetPedToRagdollWithFall(ped, 1500, 2000, 1, GetEntityForwardVector(ped), 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) end else if chance <= Config.LegInjuryChance.Walking then TriggerEvent('DoLongHudText', 'You\'re Having A Hard Using Your Legs', 5000) ShakeGameplayCam('SMALL_EXPLOSION_SHAKE', 0.08) -- change this float to increase/decrease camera shake SetPedToRagdollWithFall(ped, 1500, 2000, 1, GetEntityForwardVector(ped), 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) end end end legCount = 0 else legCount = legCount + 1 end elseif (v.part == 'LARM' and v.severity > 1) or (v.part == 'LHAND' and v.severity > 1) or (v.part == 'LFINGER' and v.severity > 2) or (v.part == 'RARM' and v.severity > 1) or (v.part == 'RHAND' and v.severity > 1) or (v.part == 'RFINGER' and v.severity > 2) then if armcount >= Config.ArmInjuryTimer then local chance = math.random(100) if (v.part == 'LARM' and v.severity > 1) or (v.part == 'LHAND' and v.severity > 1) or (v.part == 'LFINGER' and v.severity > 2) then local isDisabled = 15 Citizen.CreateThread(function() while isDisabled > 0 do if IsPedInAnyVehicle(ped, true) then DisableControlAction(0, 63, true) -- veh turn left end if IsPlayerFreeAiming(PlayerId()) then DisablePlayerFiring(PlayerId(), true) -- Disable weapon firing end isDisabled = isDisabled - 1 Citizen.Wait(1) end end) else local isDisabled = 15 Citizen.CreateThread(function() while isDisabled > 0 do if IsPedInAnyVehicle(ped, true) then DisableControlAction(0, 63, true) -- veh turn left end if IsPlayerFreeAiming(PlayerId()) then DisableControlAction(0, 25, true) -- Disable weapon firing end isDisabled = isDisabled - 1 Citizen.Wait(1) end end) end armcount = 0 else armcount = armcount + 1 end elseif (v.part == 'HEAD' and v.severity > 2) then if headCount >= Config.HeadInjuryTimer then local chance = math.random(100) if chance <= Config.HeadInjuryChance then TriggerEvent('DoLongHudText', 'You Suddenly Black Out', 5000) --TriggerEvent('DoLongHudText', 'You Suddenly Black Out', 5000) SetFlash(0, 0, 100, 10000, 100) DoScreenFadeOut(100) while not IsScreenFadedOut() do Citizen.Wait(0) end if not IsPedRagdoll(ped) and IsPedOnFoot(ped) and not IsPedSwimming(ped) then ShakeGameplayCam('SMALL_EXPLOSION_SHAKE', 0.08) -- change this float to increase/decrease camera shake SetPedToRagdoll(ped, 5000, 1, 2) end Citizen.Wait(5000) DoScreenFadeIn(250) end headCount = 0 else headCount = headCount + 1 end end end if wasOnDrugs then SetPedToRagdoll(ped, 1500, 2000, 3, true, true, false) wasOnDrugs = false TriggerEvent('DoLongHudText', 'You\'ve Realized Doing Drugs Does Not Fix All Your Problems', 5000) end else onDrugs = onDrugs - 1 if not wasOnDrugs then wasOnDrugs = true end end end function CheckDamage(ped, bone, weapon) if weapon == nil then return end if Config.Bones[bone] ~= nil then if not BodyParts[Config.Bones[bone]].isDamaged then BodyParts[Config.Bones[bone]].isDamaged = true BodyParts[Config.Bones[bone]].severity = 1 --TriggerEvent('DoLongHudText', 'Your ' .. BodyParts[Config.Bones[bone]].label .. ' feels ' .. Config.WoundStates[BodyParts[Config.Bones[bone]].severity], 155) if weapon == Config.WeaponClasses['SMALL_CALIBER'] or weapon == Config.WeaponClasses['MEDIUM_CALIBER'] or weapon == Config.WeaponClasses['CUTTING'] or weapon == Config.WeaponClasses['WILDLIFE'] or weapon == Config.WeaponClasses['OTHER'] or weapon == Config.WeaponClasses['LIGHT_IMPACT'] then if (Config.Bones[bone] == 'UPPER_BODY' or Config.Bones[bone] == 'LOWER_BODY' or Config.Bones[bone] == 'SPINE') and (weapon == Config.WeaponClasses['SMALL_CALIBER'] or weapon == Config.WeaponClasses['MEDIUM_CALIBER']) then if GetPedArmour(ped) > 0 then local chance = math.random(100) if chance <= math.ceil(Config.BodyArmorStaggerChance / 2) then SetPedToRagdoll(ped, 1500, 2000, 2, true, true, false) end else if Config.Bones[bone] == 'SPINE' then SetPedToRagdoll(ped, 1500, 2000, 2, true, true, false) end ApplyBleed(1) end else ApplyBleed(1) end elseif weapon == Config.WeaponClasses['HIGH_CALIBER'] or weapon == Config.WeaponClasses['HEAVY_IMPACT'] or weapon == Config.WeaponClasses['SHOTGUN'] or weapon == Config.WeaponClasses['EXPLOSIVE'] then if (Config.Bones[bone] == 'UPPER_BODY' or Config.Bones[bone] == 'LOWER_BODY' or Config.Bones[bone] == 'SPINE') and (weapon == Config.WeaponClasses['HIGH_CALIBER'] or weapon == Config.WeaponClasses['SHOTGUN']) then if GetPedArmour(ped) > 0 then local chance = math.random(100) if chance <= math.ceil(Config.BodyArmorStaggerChance) then SetPedToRagdoll(ped, 1500, 2000, 3, true, true, false) end if isBleeding < 1 then local chance = math.random(100) if chance <= math.ceil(Config.AmorHighCalBleedChance) then ApplyBleed(1) end end else if Config.Bones[bone] == 'SPINE' then SetPedToRagdoll(ped, 1500, 2000, 3, true, true, false) end ApplyBleed(2) end else ApplyBleed(2) end end table.insert(injured, { part = Config.Bones[bone], label = BodyParts[Config.Bones[bone]].label, severity = BodyParts[Config.Bones[bone]].severity }) TriggerServerEvent('npc-hospital:server:SyncInjuries', { limbs = BodyParts, isBleeding = tonumber(isBleeding) }) ProcessRunStuff(ped) DoLimbAlert() DoBleedAlert() else if weapon == Config.WeaponClasses['SMALL_CALIBER'] or weapon == Config.WeaponClasses['MEDIUM_CALIBER'] or weapon == Config.WeaponClasses['CUTTING'] or weapon == Config.WeaponClasses['WILDLIFE'] or weapon == Config.WeaponClasses['OTHER'] or weapon == Config.WeaponClasses['LIGHT_IMPACT'] then if (Config.Bones[bone] == 'UPPER_BODY' or Config.Bones[bone] == 'LOWER_BODY' or Config.Bones[bone] == 'SPINE') and (weapon == Config.WeaponClasses['SMALL_CALIBER'] or weapon == Config.WeaponClasses['MEDIUM_CALIBER']) then if GetPedArmour(ped) > 0 then local chance = math.random(100) if chance <= math.ceil(Config.BodyArmorStaggerChance / 2) then SetPedToRagdoll(ped, 1500, 2000, 2, true, true, false) end else if Config.Bones[bone] == 'SPINE' then SetPedToRagdoll(ped, 1500, 2000, 2, true, true, false) end ApplyBleed(1) end else ApplyBleed(1) end elseif weapon == Config.WeaponClasses['HIGH_CALIBER'] or weapon == Config.WeaponClasses['HEAVY_IMPACT'] or weapon == Config.WeaponClasses['SHOTGUN'] or weapon == Config.WeaponClasses['EXPLOSIVE'] then if (Config.Bones[bone] == 'UPPER_BODY' or Config.Bones[bone] == 'LOWER_BODY' or Config.Bones[bone] == 'SPINE') and (weapon == Config.WeaponClasses['HIGH_CALIBER'] or weapon == Config.WeaponClasses['SHOTGUN']) then if GetPedArmour(ped) > 0 then local chance = math.random(100) if chance <= math.ceil(Config.BodyArmorStaggerChance) then SetPedToRagdoll(PlayerPedId(), 1500, 2000, 3, true, true, false) end if isBleeding < 1 then local chance = math.random(100) if chance <= math.ceil(Config.AmorHighCalBleedChance) then ApplyBleed(1) end end else if Config.Bones[bone] == 'SPINE' then SetPedToRagdoll(PlayerPedId(), 1500, 2000, 3, true, true, false) end ApplyBleed(2) end else ApplyBleed(2) end end if BodyParts[Config.Bones[bone]].severity < 4 then BodyParts[Config.Bones[bone]].severity = BodyParts[Config.Bones[bone]].severity + 1 TriggerServerEvent('npc-hospital:server:SyncInjuries', { limbs = BodyParts, isBleeding = tonumber(isBleeding) }) for k, v in pairs(injured) do if v.part == Config.Bones[bone] then v.severity = BodyParts[Config.Bones[bone]].severity end end end ProcessRunStuff(ped) DoLimbAlert() DoBleedAlert() end else end end function ApplyBleed(level) if isBleeding ~= 4 then if isBleeding + level > 4 then isBleeding = 4 else isBleeding = isBleeding + level end end end function DoLimbAlert() local player = PlayerPedId() if not IsEntityDead(player) then if #injured > 0 then local limbDamageMsg = '' if #injured > 1 and #injured < 3 then for k, v in pairs(injured) do limbDamageMsg = limbDamageMsg .. 'Your ' .. v.label .. ' feels ' .. Config.WoundStates[v.severity] if k < #injured then limbDamageMsg = limbDamageMsg .. ' | ' end end elseif #injured > 2 then limbDamageMsg = 'You Feel Multiple Pains' else limbDamageMsg = 'Your ' .. injured[1].label .. ' feels ' .. Config.WoundStates[injured[1].severity] end TriggerEvent('DoLongHudText', limbDamageMsg, 155) else Citizen.Wait(1) end else Citizen.Wait(1) end end function DoBleedAlert() local player = PlayerPedId() if not IsEntityDead(player) and isBleeding > 0 then TriggerEvent("evidence:bleeding") TriggerEvent('DoLongHudText', 'You Have ' .. Config.BleedingStates[isBleeding]) else Citizen.Wait(1) end end RegisterNetEvent('npc-hospital:client:SyncBleed') AddEventHandler('npc-hospital:client:SyncBleed', function(bleedStatus) isBleeding = tonumber(bleedStatus) DoBleedAlert() end) RegisterNetEvent('npc-hospital:client:FieldTreatLimbs') AddEventHandler('npc-hospital:client:FieldTreatLimbs', function() for k, v in pairs(BodyParts) do v.isDamaged = false v.severity = 1 end for k, v in pairs(injured) do if v.part == Config.Bones[bone] then v.severity = BodyParts[Config.Bones[bone]].severity end end TriggerServerEvent('npc-hospital:server:SyncInjuries', { limbs = BodyParts, isBleeding = tonumber(isBleeding) }) ProcessRunStuff(PlayerPedId()) DoLimbAlert() end) RegisterNetEvent('npc-hospital:client:FieldTreatBleed') AddEventHandler('npc-hospital:client:FieldTreatBleed', function() if isBleeding > 1 then isBleeding = tonumber(isBleeding) - 1 TriggerServerEvent('npc-hospital:server:SyncInjuries', { limbs = BodyParts, isBleeding = tonumber(isBleeding) }) ProcessRunStuff(PlayerPedId()) DoBleedAlert() end end) RegisterNetEvent('npc-hospital:client:ReduceBleed') AddEventHandler('npc-hospital:client:ReduceBleed', function() if isBleeding > 0 then isBleeding = tonumber(isBleeding) - 1 TriggerServerEvent('npc-hospital:server:SyncInjuries', { limbs = BodyParts, isBleeding = tonumber(isBleeding) }) ProcessRunStuff(PlayerPedId()) DoBleedAlert() end end) RegisterNetEvent('npc-hospital:client:ResetLimbs') AddEventHandler('npc-hospital:client:ResetLimbs', function() for k, v in pairs(BodyParts) do v.isDamaged = false v.severity = 0 end injured = {} TriggerServerEvent('npc-hospital:server:SyncInjuries', { limbs = BodyParts, isBleeding = tonumber(isBleeding) }) ProcessRunStuff(PlayerPedId()) DoLimbAlert() end) RegisterNetEvent('npc-hospital:client:RemoveBleed') AddEventHandler('npc-hospital:client:RemoveBleed', function() for k, v in pairs(BodyParts) do v.isDamaged = false v.severity = 0 end isBleeding = 0 TriggerServerEvent('npc-hospital:server:SyncInjuries', { limbs = BodyParts, isBleeding = tonumber(isBleeding) }) ProcessRunStuff(PlayerPedId()) DoBleedAlert() end) RegisterNetEvent('npc-hospital:client:UsePainKiller') AddEventHandler('npc-hospital:client:UsePainKiller', function(tier) if tier < 4 then onPainKiller = 90 * tier end TriggerEvent('DoLongHudText', 'You feel the pain subside temporarily', 5000) ProcessRunStuff(PlayerPedId()) end) RegisterNetEvent('npc-hospital:client:UseAdrenaline') AddEventHandler('npc-hospital:client:UseAdrenaline', function(tier) if tier < 4 then onDrugs = 180 * tier end TriggerEvent('DoLongHudText', 'You\'re Able To Ignore Your Body Failing', 5000) ProcessRunStuff(PlayerPedId()) end) local prevPos = nil Citizen.CreateThread(function() prevPos = GetEntityCoords(PlayerPedId(), true) while true do local player = PlayerPedId() if bleedTickTimer >= Config.BleedTickRate then if not IsEntityDead(player) then if isBleeding > 0 then if isBleeding == 1 then SetFlash(0, 0, 100, 100, 100) elseif isBleeding == 2 then SetFlash(0, 0, 100, 250, 100) elseif isBleeding == 3 then SetFlash(0, 0, 100, 500, 100) --Function.Call(Hash.SET_FLASH, 0, 0, 100, 500, 100); elseif isBleeding == 4 then SetFlash(0, 0, 100, 500, 100) --Function.Call(Hash.SET_FLASH, 0, 0, 100, 500, 100); end if fadeOutTimer % Config.FadeOutTimer == 0 then if blackoutTimer >= Config.BlackoutTimer then TriggerEvent('DoLongHudText', 'You Suddenly Black Out', 5000) SetFlash(0, 0, 100, 7000, 100) DoScreenFadeOut(500) while not IsScreenFadedOut() do Citizen.Wait(0) end if not IsPedRagdoll(player) and IsPedOnFoot(player) and not IsPedSwimming(player) then ShakeGameplayCam('SMALL_EXPLOSION_SHAKE', 0.08) -- change this float to increase/decrease camera shake SetPedToRagdollWithFall(PlayerPedId(), 7500, 9000, 1, GetEntityForwardVector(player), 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) end Citizen.Wait(1500) DoScreenFadeIn(1000) blackoutTimer = 0 else DoScreenFadeOut(2000) while not IsScreenFadedOut() do Citizen.Wait(0) end DoScreenFadeIn(2000) if isBleeding > 3 then blackoutTimer = blackoutTimer + 2 else blackoutTimer = blackoutTimer + 1 end fadeOutTimer = 0 end else fadeOutTimer = fadeOutTimer + 1 end --TriggerEvent('DoLongHudText', 'You Have ' .. Config.BleedingStates[isBleeding], 25000) local bleedDamage = tonumber(isBleeding) * Config.BleedTickDamage ApplyDamageToPed(player, bleedDamage, false) playerHealth = playerHealth - bleedDamage if advanceBleedTimer >= Config.AdvanceBleedTimer then ApplyBleed(1) DoBleedAlert() advanceBleedTimer = 0 end end end bleedTickTimer = 0 else if math.floor(bleedTickTimer % (Config.BleedTickRate / 10)) == 0 then local currPos = GetEntityCoords(player, true) local moving = #(vector2(prevPos.x, prevPos.y) - vector2(currPos.x, currPos.y)) if (moving > 1) and isBleeding > 2 then TriggerEvent('DoLongHudText', 'You notice blood oozing from your wounds faster when you\'re moving', 155) advanceBleedTimer = advanceBleedTimer + Config.BleedMovementAdvance bleedTickTimer = bleedTickTimer + Config.BleedMovementTick prevPos = currPos else advanceBleedTimer = advanceBleedTimer + 1 bleedTickTimer = bleedTickTimer + 1 end else end bleedTickTimer = bleedTickTimer + 1 end Citizen.Wait(1000) end end) Citizen.CreateThread(function() while true do local ped = PlayerPedId() local health = GetEntityHealth(ped) local armor = GetPedArmour(ped) if not playerHealth then playerHealth = health end if not playerArmor then playerArmor = armor end local armorDamaged = (playerArmor ~= armor and armor < (playerArmor - Config.ArmorDamage) and armor > 0) -- Players armor was damaged local healthDamaged = (playerHealth ~= health and health < (playerHealth - Config.HealthDamage)) -- Players health was damaged if armorDamaged or healthDamaged then local hit, bone = GetPedLastDamageBone(ped) local bodypart = Config.Bones[bone] if hit and bodypart ~= 'NONE' then local checkDamage = true local weapon = GetDamagingWeapon(ped) if weapon ~= nil then if armorDamaged and (bodypart == 'SPINE' or bodypart == 'LOWER_BODY') and weapon <= Config.WeaponClasses['LIGHT_IMPACT'] and weapon ~= Config.WeaponClasses['NOTHING'] then checkDamage = false -- Don't check damage if the it was a body shot and the weapon class isn't that strong end if checkDamage then CheckDamage(ped, bone, weapon) end end end end playerHealth = health playerArmor = armor Citizen.Wait(500) ProcessDamage(ped) Citizen.Wait(500) end end) --[[ Player Died Events ]]-- RegisterNetEvent('baseevents:onPlayerKilled') AddEventHandler('baseevents:onPlayerKilled', function(killedBy, data) TriggerEvent('npc-hospital:client:ResetLimbs') TriggerEvent('npc-hospital:client:RemoveBleed') end) RegisterNetEvent('baseevents:onPlayerDied') AddEventHandler('baseevents:onPlayerDied', function(killedBy, pos) TriggerEvent('npc-hospital:client:ResetLimbs') TriggerEvent('npc-hospital:client:RemoveBleed') end) Citizen.CreateThread(function() while true do Citizen.Wait(0) SetPlayerHealthRechargeMultiplier(PlayerId(), 0.0) end end)
local tag = "theater" local reload = theater and theater.Screen theater = { Screen = reload } theater.Locations = { gm_bluehills_test3 = { offset = Vector(0, 0, 0), angle = Angle(-90, 90, 0), height = 352, width = 704, mins = Vector(353, 81, -35), maxs = Vector(1184, 1184, 434), mpos = Vector(416.03125, 1175.3011474609, 351.95498657227), mang = Angle(0, -90, 0), }, ["gm_abstraction_ex-sunset"] = { offset = Vector(0, 0, 0), angle = Angle(-90, 90, 0), height = 200, width = 320, mins = Vector(-764, -2142, 0), maxs = Vector(-145, -1507, 914), mpos = Vector(-720, -2080, 249), mang = Angle(0, 0, 0), }, redream_waterlands = { offset = Vector(0, 0, 0), angle = Angle(-90, -90, 0), height = 232, width = 412, mins = Vector(4752.1904296875, 9023.96875, -160.29290771484), maxs = Vector(5320.71875, 8122.2255859375, -661.05981445312), mpos = Vector(4822.17578125, 9022.96875, -168.15637207031), mang = Angle(180, 90, 0), }, } theater.Locations["gm_abstraction_ex-night"] = theater.Locations["gm_abstraction_ex-sunset"] local l for map, _ in next, theater.Locations do local match = game.GetMap():match(map) if match and (not l or #l < #match) then l = match end end l = theater.Locations[l] if not l then theater.Spawn = function() ErrorNoHalt("No theater location for this map! " .. game.GetMap() .. "\n") end return end local ENT = {} ENT.ClassName = "theater_screen" ENT.PrintName = "Theater Screen" ENT.Spawnable = true ENT.AdminOnly = true ENT.Base = "mediaplayer_base" ENT.Type = "point" ENT.PlayerConfig = l ENT.IsMediaPlayerEntity = true if SERVER then local box = ents.FindInBox function ENT:Initialize() local mp = self:InstallMediaPlayer("entity") function mp:UpdateListeners() local listeners = {} for _, v in ipairs(box(l.mins, l.maxs)) do if v:IsPlayer() then listeners[#listeners + 1] = v end end self:SetListeners(listeners) end end end scripted_ents.Register(ENT, ENT.ClassName) local i = 0 if CLIENT then hook.Add("GetMediaPlayer", "theater", function() local ply = LocalPlayer() if ply:GetPos():WithinBox(l.mins, l.maxs) then local ent = ents.FindByClass("theater_screen")[1] if ent then return MediaPlayer.GetByObject(ent) end end end) else function theater.Spawn() if IsValid(theater.Screen) then theater.Screen:Remove() end theater.Screen = ents.Create("theater_screen") local screen = theater.Screen local pos, ang = l.mpos, l.mang pos = pos + ang:Forward() * 1 screen:SetPos(pos) screen:SetAngles(ang) screen:SetMoveType(MOVETYPE_NONE) screen:Spawn() screen:Activate() return screen end local function Hook() theater.Spawn() -- DON'T RETURN end if reload then theater.Spawn() end hook.Add("InitPostEntity", "theater", Hook) hook.Add("PostCleanupMap", "theater", Hook) end
-- 12Gauge_Nick -- 12/10/2021 --[[ In the values below this script you need to enter your ClientId, ClientSecret, and YOUR account username! This API WILL LOGIN into your account! - DO NOT GIVE OUT YOUR CLIENT SECRET KEY! ]] local module = {} local OAuthCode = require(script.GetOAuth)() local ClientId = script.ClientId.Value local ClientSecret = script.ClientSecret.Value local ClientAccountName = script.ClientAccountName.Value local HttpService = game:GetService("HttpService") local GetTwitchData = function(Request) return HttpService:JSONDecode(Request.Body).data[1] end local DoChannelSearch = function(ChannelName) ChannelName = ChannelName:lower() if not ChannelName then ChannelName = ClientAccountName end local Request = HttpService:RequestAsync({Url = "https://api.twitch.tv/helix/search/channels?query="..ChannelName,Method = "GET",Headers = {["client-id"] = ClientId,["Authorization"] = "Bearer "..OAuthCode,["Content-Type"] = "application/json"}}) if Request.StatusCode == 200 then return Request else warn("[Helix]:",Request.StatusCode,Request.Body) return false end end local GetAdvancedStreamData = function(ChannelName) ChannelName = ChannelName:lower() if not ChannelName then ChannelName = ClientAccountName end local Request = HttpService:RequestAsync({Url = "https://api.twitch.tv/helix/streams?user_login="..ChannelName,Method = "GET",Headers = {["client-id"] = ClientId,["client-secret"] = ClientSecret,["Authorization"] = "Bearer "..OAuthCode,["Content-Type"] = "application/json"}}) if Request.StatusCode == 200 then return GetTwitchData(Request) else warn("[Helix]:",Request.StatusCode,Request.Body) return {} end end local GetGameIdByName = function(GameName) local Request = HttpService:RequestAsync({Url = "https://api.twitch.tv/helix/games?name="..GameName,Method = "GET",Headers = {["client-id"] = ClientId,["Authorization"] = "Bearer "..OAuthCode,["Content-Type"] = "application/json"}}) if Request.StatusCode == 200 then return GetTwitchData(Request) end return 493057 end local GetTopGameByGame = function(GameName) local GameId = GetGameIdByName(GameName).id local Request = HttpService:RequestAsync({Url = "https://api.twitch.tv/helix/streams?game_id="..GameId,Method = "GET",Headers = {["client-id"] = ClientId,["Authorization"] = "Bearer "..OAuthCode,["Content-Type"] = "application/json"}}) if Request.StatusCode == 200 then local TwitchData = GetTwitchData(Request) return{thumbnail_url = TwitchData.thumbnail_url,user_name = TwitchData.user_name,title = TwitchData.title,started_at = TwitchData.started_at,game_name = TwitchData.game_name,viewer_count = TwitchData.viewer_count,} else warn("[Helix]:",Request.StatusCode,Request.Body) return {} end end function module.GetGameInfo(GameName: string) return GetGameIdByName(GameName) end function module.GetTopGameStreamer(GameName: string) return GetTopGameByGame(GameName) end function module.GetRawStreamData(ChannelName: string) return GetAdvancedStreamData(ChannelName) end function module.DoChannelSearch(ChannelName: string) return DoChannelSearch(ChannelName) end function module.GetCurrentGame(ChannelName: string) return GetAdvancedStreamData(ChannelName).game_name end function module.GetViewership(ChannelName: string) return GetAdvancedStreamData(ChannelName).viewer_count end function module.GetLiveStatus(ChannelName: string) local isLive = GetAdvancedStreamData(ChannelName) if isLive == nil or isLive.type ~= "live" then return false end return true end function module.GetTitle(ChannelName: string) return GetAdvancedStreamData(ChannelName).title end function module.GetThumbnail(ChannelName: string) return GetAdvancedStreamData(ChannelName).thumbnail_url end return module
return {'bsc'}
MpR = {} MpR["max_h"] = 32*5 MpR["max_w"] = 0 local function get_start_load_size() local from_x = math.floor((Tiles.x)/ Tiles.tile_size.w) local from_y = math.floor((Tiles.y)/ (Tiles.tile_size.h/2) +1) return from_x,from_y end local function get_end_load_size() local machine = get_game_machine() local screen_w,screen_h = machine.canvas:get_size() return math.floor((screen_w)/Tiles.tile_size.w+2 + MpR.max_w/Tiles.tile_size.w), math.floor((screen_h)/(Tiles.tile_size.h/2)+1 +2 + MpR.max_h/Tiles.tile_size.h)+4 end function MpR.initialize(screen_map) local max_w, max_h = get_end_load_size() MpR["lightField"] = {} MpR["screen_map"] = screen_map end function MpR.set_element(x,y,element,layer) if MpR.fields[y] == nil then MpR.fields[y] = {} end if layer == nil then MpR.fields[y][x] = 0 return end if MpR.fields[y] then if MpR.fields[y][x] == nil or MpR.fields[y][x] == 0 then MpR.fields[y][x] = {0,0,0} end MpR.fields[y][x][layer] = element end end function MpR.set_empty(x,y,layer) if MpR.fields[y] == nil then MpR.fields[y] = {} end if layer == nil or layer == 0 then MpR.fields[y][x] = 0 else MpR.fields[y][x][layer] = 0 end end function MpR.get_elements(x,y) if MpR.fields[y] and MpR.fields[y][x] ~= 0 then return MpR.fields[y][x] end end function MpR.get_element(x,y,layer) if MpR.fields[y] == nil or MpR.fields[y][x] == nil then return end if MpR.fields[y] and MpR.fields[y][x] ~= 0 then return MpR.fields[y][x][layer] end return 0 end function MpR.remove_element(x,y,layer) if MpR.fields[y] and MpR.fields[y][x] ~= 0 and MpR.fields[y][x][layer] then local tmp = MpR.fields[y][x][layer] MpR.fields[y][x][layer] = 0 local stop_rem for k,v in ipairs(MpR.fields[y][x]) do if v ~= 0 then stop_rem = true break end end if stop_rem == nil then MpR.fields[y][x] = 0 end return tmp end return 0 end function MpR.removeLightElement(x,y) MpR.lightField[y][x] = nil end function MpR.setLightElement(x,y, element) if MpR.lightField[y] ~= nil then MpR.lightField[y][x] = element end end function MpR.getLightElement(x,y) if MpR.lightField[y] ~= nil then return MpR.lightField[y][x] end end function MpR.make_map(w,h) local field = {} local lightField = {} local iter = 1 for iter_y=1,h do for iter_x = 1, w do if field[iter_y] == nil then field[iter_y] = {} end if lightField[iter_y] == nil then lightField[iter_y] = {} end field[iter_y][iter_x] = 0 lightField[iter_y][iter_x] = nil end end MpR["fields"] = field MpR["lightField"] = lightField end function MpR.load_map(path, stop_iter, folder) local field = {} local folder = folder or PATH_MAPS local gm = get_game_machine() dofile(folder .. path .. ".3map") local input = assert(io.open(folder .. path .. ".2map","rb")) local x = HelpFce.bytes_to_num(input:read(1),input:read(1)) local y = HelpFce.bytes_to_num(input:read(1),input:read(1)) local field2 ={} local sizeOfLayers = 3 local count = 0 MpR.fields = {} for iter_y=1,y do for iter_x = 1, x do if field[iter_y] == nil then field[iter_y] = {} end if MpR.lightField[iter_y] == nil then MpR.lightField[iter_y] = {} end MpR.lightField[iter_y][iter_x] = nil local read = {} local is = nil for k=1,sizeOfLayers do read[k] = HelpFce.bytes_to_int(input:read(1), input:read(1),input:read(1), input:read(1)) if read[k] ~= 0 then is = true end end if is then for k,v in ipairs(read) do if v ~= 0 then local d_obj = _LObjects[v] local obj if d_obj.type == "static" then obj = SObj.load_object(d_obj.name,iter_x,iter_y,d_obj.slot) MpR.set_element(iter_x,iter_y, obj,k) elseif d_obj.type == "dynamic" then if gm.client == nil then obj = DObj.load_object(d_obj, iter_x,iter_y, true) if stop_iter then obj:stop_iter() end end elseif d_obj.type == "SimpleObject" then local obj = SO.make() obj:load(d_obj) end end end else MpR.set_empty(iter_x,iter_y) end end end input:close() end local function get_intersect_lines(line1, line2) end local function check_transparency(v2) local line_y = BasicMath.get_position_h2(v2.bound_box.y,v2.bound_box.h,Tiles.tile_size.h) local coord = {["x"] = v2.bound_box.x + Map.x, ["y"] = v2.bound_box.y + Map.y, ["w"] = v2.bound_box.w, ["h"] = v2.bound_box.h} local offset = 0 if v2.move_x then offset = v2.move_x end coord["x"] = coord["x"] + offset local result_transparency = BasicMath.get_intersect_rect(coord, Map.get_transparency_box()) local box = Map.get_transparency_box() if Map.y+line_y-(Map.tile_size.h+box[4]) < BasicMath.get_position_h2(box[2],box[4], Map.tile_size.h) then result_transparency = nil end return result_transparency end function MpR.make_object_render() local machine = get_game_machine() local screen_w,screen_h = machine.canvas:get_size() local map = MpR.fields MpR.last_position = {Tiles.x, Tiles.y} local move_y = Tiles.y local x,y = get_start_load_size() local w,h = get_end_load_size() local n,p = Tiles.tile_to_point(1,h) local base= Tiles.x-Tiles.tile_size.w local base_h = Tiles.y local tmp_line = {} local copy_line = {} Map.line_free() for k=y,y+h do local tmp = math.floor(Tiles.point_collumn_to_tile(Tiles.x-Tiles.tile_size.w,base_h)) tmp_line = Tiles.get_line(Tiles.x-Tiles.tile_size.w,base_h, nil,w+tmp,MpR.get_element) if tmp_line and #tmp_line > 0 then for k,v in ipairs(tmp_line) do v = create_obj_l_c(v) if v then copy_line[#copy_line + 1 ] = v end end Map.insert_line(copy_line, BasicMath.get_position_h2(copy_line[1].bound_box.y, copy_line[1].bound_box.h, Tiles.tile_size.h)) end base_h = base_h + Tiles.tile_size.h/2 copy_line = {} end end function MpR.set_to_layer(static_objects) local machine = get_game_machine() local objects = MpR.make_object_render() MpR["objects"] = objects -- machine:replace_layer(SObj.objects, 2) end function MpR.save( path, folder ) local w, h = Map.size_map[1], Map.size_map[2] local size_map = Map.size_map local id = 0 local dump_objs = {} local folder = folder or PATH_MAPS output = assert(io.open(folder .. path .. ".2map", "wb")) output:write(bytes(size_map[1])) output:write(bytes(size_map[2])) for y = 1, h do for x=1, w do local num = MpR.get_elements(x,y) if num == nil or num == 0 then output:write(write_int(0)) output:write(write_int(0)) output:write(write_int(0)) else for k,v in ipairs(num) do if v == 0 or v[1] == 1 or (type(v) == "table" and v[1] == 1 or v[1] == 0) then if type(v) == "table" and v[1] == 1 then MpR.set_element(x,y,v[2],2) end output:write(write_int(0)) else local dump = v:dump() id = id + 1 dump_objs[#dump_objs + 1] = dump output:write(write_int(id)) if v.render_points then if #v.render_points >= 4 then for k,v1 in ipairs(v.render_points) do if (v1.x == x and v1.y ==y) == false then local tmp = MpR.get_element(v1.x,v1.y,2) MpR.set_element(v1.x,v1.y,{1,tmp},2) end end end end end end end end end output:close() output = assert(io.open(folder .. path .. ".3map", "w")) output:write("_LObjects = {") for k,v in ipairs(dump_objs) do Serialization.serialize(v,output) output:write(",") end output:write("}") output:close() end return MpR
DEBUG_PROTOTYPES = false require("lualib.functions") require("config") require("prototypes.categories.fuel-category") require("prototypes.items.item-groups") require("prototypes.items.items") require("prototypes.recipes.processing") require("prototypes.recipes.fuel-cell") require("prototypes.recipes.nuclear-fuel") require("prototypes.recipes.atomic-bombs") require("prototypes.technology.technology") if MULTICOLOR_REACTOR then require("colors") require("prototypes.items.reactor-mask") require("prototypes.entity.reactor-mask") end
GUIEditor = { gridlist = {}, tab = {}, tabpanel = {}, label = {} } GUIEditor.tabpanel[1] = guiCreateTabPanel(5, 5, 715, 414, false) GUIEditor.tab[1] = guiCreateTab("Your team", GUIEditor.tabpanel[1]) GUIEditor.label[1] = guiCreateLabel(46, 22, 634, 55, "Create your own team! You will be able to set a team name, tag, colour, welcome message and invite players to your team. Teams expire after 30/60 days, but everyone in the team can refresh the team duration (Up to 60 days). You can only own one team or be in one team.", false, GUIEditor.tab[1]) guiLabelSetHorizontalAlign(GUIEditor.label[1], "left", true) GUIEditor.btnBuyTeam = guiCreateButton(46, 263, 165, 50, "Create team\n2500 GC / 20 days", false, GUIEditor.tab[1]) guiSetProperty(GUIEditor.btnBuyTeam, "Disabled", "True") guiSetProperty(GUIEditor.btnBuyTeam, "NormalTextColour", "FFAAAAAA") GUIEditor.label[2] = guiCreateLabel(46, 111, 73, 28, "Team name", false, GUIEditor.tab[1]) guiLabelSetVerticalAlign(GUIEditor.label[2], "center") GUIEditor.teamname = guiCreateEdit(145, 111, 228, 28, "", false, GUIEditor.tab[1]) guiSetProperty(GUIEditor.teamname, "Disabled", "True") GUIEditor.label[3] = guiCreateLabel(46, 149, 73, 28, "Team tag", false, GUIEditor.tab[1]) guiLabelSetVerticalAlign(GUIEditor.label[3], "center") GUIEditor.teamtag = guiCreateEdit(145, 149, 74, 28, "", false, GUIEditor.tab[1]) guiSetProperty(GUIEditor.teamtag, "Disabled", "True") GUIEditor.label[4] = guiCreateLabel(46, 187, 73, 28, "Team colour", false, GUIEditor.tab[1]) guiLabelSetVerticalAlign(GUIEditor.label[4], "center") GUIEditor.teamcolour = guiCreateEdit(145, 187, 74, 28, "#FFFFFF", false, GUIEditor.tab[1]) guiSetProperty(GUIEditor.teamcolour, "Disabled", "True") GUIEditor.teammsg = guiCreateEdit(145, 225, 228, 28, "", false, GUIEditor.tab[1]) guiSetProperty(GUIEditor.teammsg, "Disabled", "True") GUIEditor.chkIgnore = guiCreateCheckBox(46, 335, 204, 29, " Don't show me team invites", false, false, GUIEditor.tab[1]) guiSetProperty(GUIEditor.chkIgnore, "Disabled", "True") GUIEditor.gridMembers = guiCreateGridList(419, 107, 261, 202, false, GUIEditor.tab[1]) guiGridListAddColumn(GUIEditor.gridMembers, "Members", 0.9) guiSetProperty(GUIEditor.gridMembers, "SortSettingEnabled", "False") GUIEditor.btnInvite = guiCreateButton(419, 332, 114, 32, "Invite player", false, GUIEditor.tab[1]) guiSetProperty(GUIEditor.btnInvite, "Disabled", "True") guiSetProperty(GUIEditor.btnInvite, "NormalTextColour", "FFAAAAAA") GUIEditor.btnLeave = guiCreateButton(566, 332, 114, 32, "Leave team", false, GUIEditor.tab[1]) guiSetProperty(GUIEditor.btnLeave, "Disabled", "True") guiSetProperty(GUIEditor.btnLeave, "NormalTextColour", "FFAAAAAA") GUIEditor.label[5] = guiCreateLabel(46, 225, 83, 28, "Welcome msg", false, GUIEditor.tab[1]) guiLabelSetVerticalAlign(GUIEditor.label[5], "center") GUIEditor.tab[2] = guiCreateTab("Teams", GUIEditor.tabpanel[1]) GUIEditor.gridlist[1] = guiCreateGridList(48, 40, 608, 304, false, GUIEditor.tab[2]) guiGridListAddColumn(GUIEditor.gridlist[1], "Team", 0.5) guiGridListAddColumn(GUIEditor.gridlist[1], "Member", 0.5)
local packer_load = nil local cmd = vim.api.nvim_command local fmt = string.format local function verify_conditions(conds, name) if conds == nil then return true end for _, cond in ipairs(conds) do local success, result if type(cond) == 'boolean' then success, result = true, cond elseif type(cond) == 'function' then success, result = pcall(cond) elseif type(cond) == 'string' then success, result = pcall(loadstring(cond)) end if not success then vim.schedule(function() vim.api.nvim_notify( 'packer.nvim: Error running cond for ' .. name .. ': ' .. result, vim.log.levels.ERROR, {} ) end) return false end if result == false then return false end end return true end local function loader_clear_loaders(plugin) if plugin.commands then for _, del_cmd in ipairs(plugin.commands) do cmd('silent! delcommand ' .. del_cmd) end end if plugin.keys then for _, key in ipairs(plugin.keys) do cmd(fmt('silent! %sunmap %s', key[1], key[2])) end end end local function loader_apply_config(plugin, name) if plugin.config then for _, config_line in ipairs(plugin.config) do local success, err if type(config_line) == 'function' then success, err = pcall(config_line, name, plugin) else success, err = pcall(loadstring(config_line), name, plugin) end if not success then vim.schedule(function() vim.api.nvim_notify('packer.nvim: Error running config for ' .. name .. ': ' .. err, vim.log.levels.ERROR, {}) end) end end end end local function loader_apply_wants(plugin, plugins) if plugin.wants then for _, wanted_name in ipairs(plugin.wants) do packer_load({ wanted_name }, {}, plugins) end end end local function loader_apply_after(plugin, plugins, name) if plugin.after then for _, after_name in ipairs(plugin.after) do local after_plugin = plugins[after_name] after_plugin.load_after[name] = nil if next(after_plugin.load_after) == nil then packer_load({ after_name }, {}, plugins) end end end end local function apply_cause_side_effcts(cause) if cause.cmd then local lines = cause.l1 == cause.l2 and '' or (cause.l1 .. ',' .. cause.l2) cmd(fmt('%s %s%s%s %s', cause.mods or '', lines, cause.cmd, cause.bang, cause.args)) elseif cause.keys then local extra = '' while true do local c = vim.fn.getchar(0) if c == 0 then break end extra = extra .. vim.fn.nr2char(c) end if cause.prefix then local prefix = vim.v.count ~= 0 and vim.v.count or '' prefix = prefix .. '"' .. vim.v.register .. cause.prefix if vim.fn.mode 'full' == 'no' then if vim.v.operator == 'c' then prefix = '' .. prefix end prefix = prefix .. vim.v.operator end vim.fn.feedkeys(prefix, 'n') end local escaped_keys = vim.api.nvim_replace_termcodes(cause.keys .. extra, true, true, true) vim.api.nvim_feedkeys(escaped_keys, 'm', true) elseif cause.event then cmd(fmt('doautocmd <nomodeline> %s', cause.event)) elseif cause.ft then cmd(fmt('doautocmd <nomodeline> %s FileType %s', 'filetypeplugin', cause.ft)) cmd(fmt('doautocmd <nomodeline> %s FileType %s', 'filetypeindent', cause.ft)) cmd(fmt('doautocmd <nomodeline> %s FileType %s', 'syntaxset', cause.ft)) end end packer_load = function(names, cause, plugins, force) local some_unloaded = false local needs_bufread = false local num_names = #names for i = 1, num_names do local plugin = plugins[names[i]] if not plugin then local err_message = 'Error: attempted to load ' .. names[i] .. ' which is not present in plugins table!' vim.notify(err_message, vim.log.levels.ERROR, { title = 'packer.nvim' }) error(err_message) end if not plugin.loaded then loader_clear_loaders(plugin) if force or verify_conditions(plugin.cond, names[i]) then -- Set the plugin as loaded before config is run in case something in the config tries to load -- this same plugin again plugin.loaded = true some_unloaded = true needs_bufread = needs_bufread or plugin.needs_bufread loader_apply_wants(plugin, plugins) cmd('packadd ' .. names[i]) if plugin.after_files then for _, file in ipairs(plugin.after_files) do cmd('silent source ' .. file) end end loader_apply_config(plugin, names[i]) loader_apply_after(plugin, plugins, names[i]) end end end if not some_unloaded then return end if needs_bufread then cmd 'doautocmd BufRead' end -- Retrigger cmd/keymap... apply_cause_side_effcts(cause) end local function load_wrapper(names, cause, plugins, force) local success, err_msg = pcall(packer_load, names, cause, plugins, force) if not success then vim.cmd 'echohl ErrorMsg' vim.cmd('echomsg "Error in packer_compiled: ' .. vim.fn.escape(err_msg, '"') .. '"') vim.cmd 'echomsg "Please check your config for correctness"' vim.cmd 'echohl None' end end return load_wrapper