repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278
values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15
values |
|---|---|---|---|---|---|
DeinFreund/Zero-K | LuaUI/Widgets/camera_recorder.lua | 17 | 8831 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "CameraRecorder",
desc = "v0.011 Record positions of the camera to a file and repath those positions when loading the replay.",
author = "CarRepairer",
date = "2011-07-04",
license = "GNU GPL, v2 or later",
layer = 1002,
enabled = false,
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--[[
HOW TO USE:
Start a game (such as a replay).
Type /luaui reload
Push Settings > Camera > Recording > Record
Move your camera around.
Push Record again to stop.
End game.
Start a replay of that game you just recorded the camera in.
Type /luaui reload
Push Settings > Camera > Recording > Play
The camera will follow the path you recorded.
Notes:
For some reason the Game.gameID constant doesn't work until you type /luaui reload
The camera positions are saved to a file based on the gameID. If you don't
reload luaui it will save to (or read from) the file camrec_AAAAAAAAAAAAAAAAAAAAAA==.txt
--]]
options_path = 'Settings/Camera/Recording'
--options_order = { }
local OverviewAction = function() end
options = {
record = {
name = "Record",
desc = "Record now",
type = 'button',
-- OnChange defined later
},
play = {
name = "Play",
desc = "Play now",
type = 'button',
-- OnChange defined later
},
help = {
name = 'Help',
type = 'text',
value = [[
* Start a game (such as a replay).
* Type /luaui reload
* Push Settings > Camera > Recording > Record
* Move your camera around.
* Push Record again to stop.
* End game.
* Start a replay of that game you just recorded the camera in.
* Type /luaui reload
* Push Settings > Camera > Recording > Play
* The camera will follow the path you recorded.
]],
}
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--config
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local spGetCameraState = Spring.GetCameraState
local spGetCameraVectors = Spring.GetCameraVectors
local spGetModKeyState = Spring.GetModKeyState
local spGetMouseState = Spring.GetMouseState
local spIsAboveMiniMap = Spring.IsAboveMiniMap
local spSendCommands = Spring.SendCommands
local spSetCameraState = Spring.SetCameraState
local spSetMouseCursor = Spring.SetMouseCursor
local spTraceScreenRay = Spring.TraceScreenRay
local spWarpMouse = Spring.WarpMouse
local spGetCameraDirection = Spring.GetCameraDirection
local abs = math.abs
local min = math.min
local max = math.max
local sqrt = math.sqrt
local sin = math.sin
local cos = math.cos
local echo = Spring.Echo
local KF_FRAMES = 1
local recording = false
local recData = {}
local filename
local ranInit = false
Spring.Utilities = Spring.Utilities or {}
VFS.Include("LuaRules/Utilities/base64.lua")
options.record.OnChange = function()
recording = not recording
echo (recording and '<Camera Recording> Recording begun.' or '<Camera Recording> Recording stopped.')
end
options.play.OnChange = function()
playing = not playing
echo (playing and '<Camera Recording> Playback begun.' or '<Camera Recording> Playback stopped.')
end
local CAMERA_STATE_FORMATS = {
fps = {
"px", "py", "pz",
"dx", "dy", "dz",
"rx", "ry", "rz",
"oldHeight",
},
free = {
"px", "py", "pz",
"dx", "dy", "dz",
"rx", "ry", "rz",
"fov",
"gndOffset",
"gravity",
"slide",
"scrollSpeed",
"velTime",
"avelTime",
"autoTilt",
"goForward",
"invertAlt",
"gndLock",
"vx", "vy", "vz",
"avx", "avy", "avz",
},
OrbitController = {
"px", "py", "pz",
"tx", "ty", "tz",
},
ta = {
"px", "py", "pz",
"dx", "dy", "dz",
"height",
"zscale",
"flipped",
},
ov = {
"px", "py", "pz",
},
rot = {
"px", "py", "pz",
"dx", "dy", "dz",
"rx", "ry", "rz",
"oldHeight",
},
sm = {
"px", "py", "pz",
"dx", "dy", "dz",
"height",
"zscale",
"flipped",
},
tw = {
"px", "py", "pz",
"rx", "ry", "rz",
},
}
local CAMERA_NAMES = {
"fps",
"free",
"OrbitController",
"ta",
"ov",
"rot",
"sm",
"tw",
}
local CAMERA_IDS = {}
for i=1, #CAMERA_NAMES do
CAMERA_IDS[CAMERA_NAMES[i]] = i
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function explode(div,str)
if (div=='') then return false end
local pos,arr = 0,{}
-- for each divider found
for st,sp in function() return string.find(str,div,pos,true) end do
table.insert(arr,string.sub(str,pos,st-1)) -- Attach chars left of current divider
pos = sp + 1 -- Jump past current divider
end
table.insert(arr,string.sub(str,pos)) -- Attach chars right of last divider
return arr
end
local function CameraStateToString(frame, cs)
local name = cs.name
local stateFormat = CAMERA_STATE_FORMATS[name]
local cameraID = CAMERA_IDS[name]
if not stateFormat or not cameraID then return nil end
local result = frame .. '|' .. cameraID .. '|' .. cs.mode
for i=1, #stateFormat do
local num = cs[stateFormat[i]]
if not num then return nil end
result = result .. '|' .. num
end
return result
end
local function StringToCameraState(str)
local s_arr = explode('|', str)
local frame = s_arr[1]
local cameraID = s_arr[2]
local mode = s_arr[3]
local name = CAMERA_NAMES[cameraID+0]
local stateFormat = CAMERA_STATE_FORMATS[name]
if not (cameraID and mode and name and stateFormat) then
--echo ('ISSUE', cameraID , mode , name , stateFormat)
return nil
end
local result = {
frame = frame,
name = name,
mode = mode,
}
for i=1, #stateFormat do
local num = s_arr[i+3]
if not num then return nil end
result[stateFormat[i]] = num
end
return result
end
local function IsKeyframe(frame)
return frame % KF_FRAMES == 0
end
local function RecordFrame(frame)
--echo ('<camrec> recording frame', frame)
local str = CameraStateToString( frame, spGetCameraState() )
local out = assert(io.open(filename, "a+"), "Unable to save camera recording file to "..filename)
out:write(str .. "\n")
assert(out:close())
end
local function FileToData(filename)
--local file = assert(io.open(filename,'r'), "Unable to load camera recording file from "..filename)
local file = io.open(filename,'r')
if not file then
echo('<Camrec> No such file ' .. filename )
return {}
end
local recData = {}
local prevkey = 0
while true do
line = file:read()
if not line then
break
end
--echo ('<camrec> opening line ', line)
local data = StringToCameraState( line )
--recData[ data.frame ] = data
if prevkey ~= 0 then
--echo('<camrec> adding data', prevkey )
recData[ prevkey+0 ] = data
end
prevkey = data.frame
end
return recData
end
local function RunInit()
if ranInit then
return true
end
local gameID = Game.gameID
--echo ('gameid=', gameID)
if not gameID or gameID == '' then
return false
end
ranInit = true
local gameID_enc = Spring.Utilities.Base64Encode( gameID )
--echo( '<camrec>', gameID, gameID_enc )
local gameID_dec = Spring.Utilities.Base64Decode( gameID_enc )
--echo( '<camrec>','equal?', gameID_dec == gameID )
filename = 'camrec_' .. gameID_enc .. '.txt'
--echo ('<camrec>',filename)
recData = FileToData( filename )
return true
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GameFrame()
local frame = Spring.GetGameFrame()
if frame < 1 then return end
if not RunInit() then return end
if recording then
if IsKeyframe(frame) then
RecordFrame(frame)
end
end
if playing then
if recData[frame] then
--echo ('playing frame', frame)
spSetCameraState(recData[frame], KF_FRAMES / 32)
end
end
end
function widget:Initialize()
end
--------------------------------------------------------------------------------
| gpl-2.0 |
DeinFreund/Zero-K | units/damagesink.lua | 6 | 1118 | unitDef = {
unitname = [[damagesink]],
name = [[Damage Sink thing]],
description = [[Does not care if you shoot at it.]],
acceleration = 0,
autoHeal = 500000,
buildCostMetal = 10,
builder = false,
buildingGroundDecalType = [[zenith_aoplane.dds]],
buildPic = [[zenith.png]],
category = [[SINK GUNSHIP]],
energyUse = 0,
footprintX = 2,
footprintZ = 2,
iconType = [[mahlazer]],
idleAutoHeal = 5,
idleTime = 1800,
maxDamage = 500000,
maxSlope = 18,
maxVelocity = 0,
maxWaterDepth = 0,
minCloakDistance = 150,
objectName = [[zenith.s3o]],
script = [[nullscript.lua]],
sightDistance = 660,
turnRate = 0,
useBuildingGroundDecal = true,
workerTime = 0,
yardMap = [[yyyy]],
}
return lowerkeys({ damagesink = unitDef })
| gpl-2.0 |
thess/OpenWrt-luci | applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/rrdtool.lua | 46 | 3168 | -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
m = Map("luci_statistics",
translate("RRDTool Plugin Configuration"),
translate(
"The rrdtool plugin stores the collected data in rrd database " ..
"files, the foundation of the diagrams.<br /><br />" ..
"<strong>Warning: Setting the wrong values will result in a very " ..
"high memory consumption in the temporary directory. " ..
"This can render the device unusable!</strong>"
))
-- collectd_rrdtool config section
s = m:section( NamedSection, "collectd_rrdtool", "luci_statistics" )
-- collectd_rrdtool.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 1
-- collectd_rrdtool.datadir (DataDir)
datadir = s:option( Value, "DataDir", translate("Storage directory") )
datadir.default = "/tmp"
datadir.rmempty = true
datadir.optional = true
datadir:depends( "enable", 1 )
-- collectd_rrdtool.stepsize (StepSize)
stepsize = s:option( Value, "StepSize",
translate("RRD step interval"), translate("Seconds") )
stepsize.default = 30
stepsize.isinteger = true
stepsize.rmempty = true
stepsize.optional = true
stepsize:depends( "enable", 1 )
-- collectd_rrdtool.heartbeat (HeartBeat)
heartbeat = s:option( Value, "HeartBeat",
translate("RRD heart beat interval"), translate("Seconds") )
heartbeat.default = 60
heartbeat.isinteger = true
heartbeat.rmempty = true
heartbeat.optional = true
heartbeat:depends( "enable", 1 )
-- collectd_rrdtool.rrasingle (RRASingle)
rrasingle = s:option( Flag, "RRASingle",
translate("Only create average RRAs"), translate("reduces rrd size") )
rrasingle.default = true
rrasingle.rmempty = true
rrasingle.optional = true
rrasingle:depends( "enable", 1 )
-- collectd_rrdtool.rratimespans (RRATimespan)
rratimespans = s:option( Value, "RRATimespans",
translate("Stored timespans"), translate("seconds; multiple separated by space") )
rratimespans.default = "600 86400 604800 2678400 31622400"
rratimespans.rmempty = true
rratimespans.optional = true
rratimespans:depends( "enable", 1 )
-- collectd_rrdtool.rrarows (RRARows)
rrarows = s:option( Value, "RRARows", translate("Rows per RRA") )
rrarows.isinteger = true
rrarows.default = 100
rrarows.rmempty = true
rrarows.optional = true
rrarows:depends( "enable", 1 )
-- collectd_rrdtool.xff (XFF)
xff = s:option( Value, "XFF", translate("RRD XFiles Factor") )
xff.default = 0.1
xff.isnumber = true
xff.rmempty = true
xff.optional = true
xff:depends( "enable", 1 )
-- collectd_rrdtool.cachetimeout (CacheTimeout)
cachetimeout = s:option( Value, "CacheTimeout",
translate("Cache collected data for"), translate("Seconds") )
cachetimeout.isinteger = true
cachetimeout.default = 100
cachetimeout.rmempty = true
cachetimeout.optional = true
cachetimeout:depends( "enable", 1 )
-- collectd_rrdtool.cacheflush (CacheFlush)
cacheflush = s:option( Value, "CacheFlush",
translate("Flush cache after"), translate("Seconds") )
cacheflush.isinteger = true
cacheflush.default = 100
cacheflush.rmempty = true
cacheflush.optional = true
cacheflush:depends( "enable", 1 )
return m
| apache-2.0 |
resetnow/premake-core | src/actions/vstudio/vs2005.lua | 7 | 3087 | --
-- actions/vstudio/vs2005.lua
-- Add support for the Visual Studio 2005 project formats.
-- Copyright (c) 2008-2015 Jason Perkins and the Premake project
--
premake.vstudio.vs2005 = {}
local p = premake
local vs2005 = p.vstudio.vs2005
local vstudio = p.vstudio
---
-- Register a command-line action for Visual Studio 2006.
---
function vs2005.generateSolution(wks)
p.indent("\t")
p.eol("\r\n")
p.escaper(vs2005.esc)
premake.generate(wks, ".sln", vstudio.sln2005.generate)
if _ACTION >= "vs2010" then
-- Skip generation of empty NuGet packages.config files
if p.workspace.hasProject(wks, function(prj) return #prj.nuget > 0 end) then
premake.generate(
{
location = path.join(wks.location, "packages.config"),
workspace = wks
},
nil,
vstudio.nuget2010.generatePackagesConfig
)
end
end
end
function vs2005.generateProject(prj)
p.indent(" ")
p.eol("\r\n")
p.escaper(vs2005.esc)
if premake.project.isdotnet(prj) then
premake.generate(prj, ".csproj", vstudio.cs2005.generate)
-- Skip generation of empty user files
local user = p.capture(function() vstudio.cs2005.generateUser(prj) end)
if #user > 0 then
p.generate(prj, ".csproj.user", function() p.outln(user) end)
end
elseif premake.project.iscpp(prj) then
premake.generate(prj, ".vcproj", vstudio.vc200x.generate)
-- Skip generation of empty user files
local user = p.capture(function() vstudio.vc200x.generateUser(prj) end)
if #user > 0 then
p.generate(prj, ".vcproj.user", function() p.outln(user) end)
end
end
end
---
-- Apply XML escaping on a value to be included in an
-- exported project file.
---
function vs2005.esc(value)
value = string.gsub(value, '&', "&")
value = value:gsub('"', """)
value = value:gsub("'", "'")
value = value:gsub('<', "<")
value = value:gsub('>', ">")
value = value:gsub('\r', "
")
value = value:gsub('\n', "
")
return value
end
---
-- Define the Visual Studio 2005 export action.
---
newaction {
-- Metadata for the command line and help system
trigger = "vs2005",
shortname = "Visual Studio 2005",
description = "Generate Visual Studio 2005 project files",
-- Visual Studio always uses Windows path and naming conventions
os = "windows",
-- The capabilities of this action
valid_kinds = { "ConsoleApp", "WindowedApp", "StaticLib", "SharedLib", "Makefile", "None" },
valid_languages = { "C", "C++", "C#" },
valid_tools = {
cc = { "msc" },
dotnet = { "msnet" },
},
-- Workspace and project generation logic
onWorkspace = vstudio.vs2005.generateSolution,
onProject = vstudio.vs2005.generateProject,
onCleanWorkspace = vstudio.cleanSolution,
onCleanProject = vstudio.cleanProject,
onCleanTarget = vstudio.cleanTarget,
-- This stuff is specific to the Visual Studio exporters
vstudio = {
csprojSchemaVersion = "2.0",
productVersion = "8.0.50727",
solutionVersion = "9",
versionName = "2005",
}
}
| bsd-3-clause |
AresTao/darkstar | scripts/zones/Quicksand_Caves/mobs/Princeps_IV-XLV.lua | 16 | 1428 | -----------------------------------
-- Area: Quicksand Caves
-- MOB: Princeps IV-XLV
-- Pops in Bastok mission 8-1 "The Chains that Bind Us"
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Quicksand_Caves/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobDeath Action
-----------------------------------
function onMobDeath(mob,killer)
if (killer:getCurrentMission(BASTOK) == THE_CHAINS_THAT_BIND_US) and (killer:getVar("MissionStatus") == 1) then
SetServerVariable("Bastok8-1LastClear", os.time());
end
end;
-----------------------------------
-- onMobEngaged Action
-----------------------------------
function onMobEngaged(mob, target)
end;
-----------------------------------
-- onMobDisengage Action
-----------------------------------
function onMobDisengage(mob)
local self = mob:getID();
DespawnMob(self, 120);
end;
-----------------------------------
-- onMobDespawn Action
-----------------------------------
function onMobDespawn(mob)
local mobsup = GetServerVariable("BastokFight8_1");
SetServerVariable("BastokFight8_1",mobsup - 1);
if (GetServerVariable("BastokFight8_1") == 0) then
local npc = GetNPCByID(17629734); -- qm6
npc:setStatus(0); -- Reappear
end
end;
| gpl-3.0 |
DeinFreund/Zero-K | LuaRules/Configs/StartBoxes/TheHunters-v3.lua | 17 | 1313 | return {
[0] = {
startpoints = {
{860,451},
},
boxes = {
{
{819,410},
{901,410},
{901,492},
{819,492},
},
},
},
[1] = {
startpoints = {
{7496,7578},
},
boxes = {
{
{7455,7537},
{7537,7537},
{7537,7619},
{7455,7619},
},
},
},
[2] = {
startpoints = {
{7414,532},
},
boxes = {
{
{7373,492},
{7455,492},
{7455,573},
{7373,573},
},
},
},
[3] = {
startpoints = {
{778,7414},
},
boxes = {
{
{737,7373},
{819,7373},
{819,7455},
{737,7455},
},
},
},
[4] = {
startpoints = {
{614,3236},
},
boxes = {
{
{573,3195},
{655,3195},
{655,3277},
{573,3277},
},
},
},
[5] = {
startpoints = {
{7496,5202},
},
boxes = {
{
{7455,5161},
{7537,5161},
{7537,5243},
{7455,5243},
},
},
},
[6] = {
startpoints = {
{4219,7660},
},
boxes = {
{
{4178,7619},
{4260,7619},
{4260,7700},
{4178,7700},
},
},
},
[7] = {
startpoints = {
{4628,614},
},
boxes = {
{
{4588,573},
{4669,573},
{4669,655},
{4588,655},
},
},
},
[8] = {
startpoints = {
{4055,4055},
},
boxes = {
{
{3277,3277},
{4833,3277},
{4833,4833},
{3277,4833},
},
},
},
}
| gpl-2.0 |
ld-test/prosody | plugins/mod_time.lua | 3 | 1335 | -- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local st = require "util.stanza";
local datetime = require "util.datetime".datetime;
local legacy = require "util.datetime".legacy;
-- XEP-0202: Entity Time
module:add_feature("urn:xmpp:time");
local function time_handler(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "get" then
origin.send(st.reply(stanza):tag("time", {xmlns="urn:xmpp:time"})
:tag("tzo"):text("+00:00"):up() -- TODO get the timezone in a platform independent fashion
:tag("utc"):text(datetime()));
return true;
end
end
module:hook("iq/bare/urn:xmpp:time:time", time_handler);
module:hook("iq/host/urn:xmpp:time:time", time_handler);
-- XEP-0090: Entity Time (deprecated)
module:add_feature("jabber:iq:time");
local function legacy_time_handler(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "get" then
origin.send(st.reply(stanza):tag("query", {xmlns="jabber:iq:time"})
:tag("utc"):text(legacy()));
return true;
end
end
module:hook("iq/bare/jabber:iq:time:query", legacy_time_handler);
module:hook("iq/host/jabber:iq:time:query", legacy_time_handler);
| mit |
DeinFreund/Zero-K | LuaRules/Gadgets/unit_priority.lua | 5 | 25161 | -- $Id$
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
--
-- Copyright (C) 2009.
-- Licensed under the terms of the GNU GPL, v2 or later.
--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if (not gadgetHandler:IsSyncedCode()) then
return
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "UnitPriority",
desc = "Adds controls to change spending priority on constructions/repairs etc",
author = "Licho",
date = "19.4.2009", --24.2.2013
license = "GNU GPL, v2 or later",
-- Must start before unit_morph.lua gadget to register GG.AddMiscPriority() first.
-- Must be before mex_overdrive
layer = -5,
enabled = true
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
include("LuaRules/Configs/customcmds.h.lua")
include("LuaRules/Configs/constants.lua")
local TooltipsA = {
' Low.',
' Normal.',
' High.',
}
local TooltipsB = {
[CMD_PRIORITY] = 'Construction Priority',
[CMD_MISC_PRIORITY] = 'Morph&Stock Priority',
}
local DefaultState = 1
local CommandOrder = 123456
local CommandDesc = {
id = CMD_PRIORITY,
type = CMDTYPE.ICON_MODE,
name = 'Construction Priority',
action = 'priority',
tooltip = 'Construction Priority' .. TooltipsA[DefaultState + 1],
params = {DefaultState, 'Low','Normal','High'}
}
local MiscCommandOrder = 123457
local MiscCommandDesc = {
id = CMD_MISC_PRIORITY,
type = CMDTYPE.ICON_MODE,
name = 'Morph&Stock Priority',
action = 'miscpriority',
tooltip = 'Morph&Stock Priority' .. TooltipsA[DefaultState + 1],
params = {DefaultState, 'Low','Normal','High'}
}
local StateCount = #CommandDesc.params-1
local UnitPriority = {} -- UnitPriority[unitID] = 0,1,2 priority of the unit
local UnitMiscPriority = {} -- UnitMiscPriority[unitID] = 0,1,2 priority of the unit
local TeamPriorityUnits = {} -- TeamPriorityUnits[TeamID][UnitID] = 0,2 which units are low/high priority builders
local teamMiscPriorityUnits = {} -- teamMiscPriorityUnits[TeamID][UnitID] = 0,2 which units are low/high priority builders
local TeamScale = {} -- TeamScale[TeamID] = {0, 0.4, 1} how much to scale resourcing at different incomes
local TeamScaleEnergy = {} -- TeamScaleEnergy[TeamID] = {0, 0.4, 1} how much to scale energy only resourcing
local TeamMetalReserved = {} -- how much metal is reserved for high priority in each team
local TeamEnergyReserved = {} -- ditto for energy
local effectiveTeamMetalReserved = {} -- Takes max storage into account
local effectiveTeamEnergyReserved = {} -- ditto for energy
local LastUnitFromFactory = {} -- LastUnitFromFactory[FactoryUnitID] = lastUnitID
local UnitOnlyEnergy = {} -- UnitOnlyEnergy[unitID] = true if the unit does not try to drain metal
local checkOnlyEnergy = false -- becomes true onces every second to check for repairers
-- Derandomization of resource allocation. Remembers the portion of resources allocated to the unit and gives access
-- when they have a full chunk.
local UnitConPortion = {}
local UnitMiscPortion = {}
local miscResourceDrain = {} -- metal drain for custom unit added thru GG. function
local miscTeamPriorityUnits = {} --unit that need priority handling
local MiscUnitOnlyEnergy = {} -- MiscUnitOnlyEnergy[unitID] for misc drain
local priorityTypes = {
[CMD_PRIORITY] = {id = CMD_PRIORITY, param = "buildpriority", unitTable = UnitPriority},
[CMD_MISC_PRIORITY] = {id = CMD_MISC_PRIORITY, param = "miscpriority", unitTable = UnitMiscPriority},
}
local ALLY_ACCESS = {allied = true}
local debugTeam = false
local debugOnUnits = false
--------------------------------------------------------------------------------
-- COMMON
--------------------------------------------------------------------------------
local function isFactory(UnitDefID)
return UnitDefs[UnitDefID].isFactory or false
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local max = math.max
local spGetTeamList = Spring.GetTeamList
local spGetTeamResources = Spring.GetTeamResources
local spGetPlayerInfo = Spring.GetPlayerInfo
local spGetUnitDefID = Spring.GetUnitDefID
local spGetUnitHealth = Spring.GetUnitHealth
local spFindUnitCmdDesc = Spring.FindUnitCmdDesc
local spEditUnitCmdDesc = Spring.EditUnitCmdDesc
local spInsertUnitCmdDesc = Spring.InsertUnitCmdDesc
local spRemoveUnitCmdDesc = Spring.RemoveUnitCmdDesc
local spSetUnitRulesParam = Spring.SetUnitRulesParam
local spGetUnitRulesParam = Spring.GetUnitRulesParam
local spSetTeamRulesParam = Spring.SetTeamRulesParam
local spGetUnitIsStunned = Spring.GetUnitIsStunned
local spGetTeamRulesParam = Spring.GetTeamRulesParam
local alliedTable = {allied = true}
local function SetMetalReserved(teamID, value)
TeamMetalReserved[teamID] = value or 0
Spring.SetTeamRulesParam(teamID, "metalReserve", value or 0, alliedTable)
end
local function SetEnergyReserved(teamID, value)
TeamEnergyReserved[teamID] = value or 0
Spring.SetTeamRulesParam(teamID, "energyReserve", value or 0, alliedTable)
end
local function SetPriorityState(unitID, state, prioID)
local cmdDescID = spFindUnitCmdDesc(unitID, prioID)
if (cmdDescID) then
CommandDesc.params[1] = state
spEditUnitCmdDesc(unitID, cmdDescID, { params = CommandDesc.params, tooltip = TooltipsB[prioID] .. TooltipsA[1 + state%StateCount]})
spSetUnitRulesParam(unitID, priorityTypes[prioID].param, state, ALLY_ACCESS)
end
priorityTypes[prioID].unitTable[unitID] = state
end
function PriorityCommand(unitID, cmdID, cmdParams, cmdOptions)
local state = cmdParams[1] or 1
if cmdOptions and (cmdOptions.right) then
state = state - 2
end
state = state % StateCount
SetPriorityState(unitID, state, cmdID)
local lastUnitID = LastUnitFromFactory[unitID]
if lastUnitID ~= nil then
local _, _, _, _, progress = spGetUnitHealth(lastUnitID)
if (progress ~= nil and progress < 1) then -- we are building some unit ,set its priority too
SetPriorityState(lastUnitID, state, cmdID)
end
end
end
function gadget:AllowCommand_GetWantedCommand()
return {[CMD_PRIORITY] = true, [CMD_MISC_PRIORITY] = true}
end
function gadget:AllowCommand_GetWantedUnitDefID()
return true
end
function gadget:AllowCommand(unitID, unitDefID, teamID,
cmdID, cmdParams, cmdOptions)
if (cmdID == CMD_PRIORITY or cmdID == CMD_MISC_PRIORITY) then
PriorityCommand(unitID, cmdID, cmdParams, cmdOptions)
return false -- command was used
end
return true -- command was not used
end
function gadget:CommandFallback(unitID, unitDefID, teamID,
cmdID, cmdParams, cmdOptions)
if (cmdID ~= CMD_PRIORITY) then
return false -- command was not used
end
PriorityCommand(unitID, cmdParams, cmdOptions)
return true, true -- command was used, remove it
end
-- Misc Priority tasks can get their reduced build rate directly.
-- The external gadget is then trusted to obey the proportion which
-- they are allocated.
local function GetMiscPrioritySpendScale(unitID, teamID, onlyEnergy)
if (teamMiscPriorityUnits[teamID] == nil) then
teamMiscPriorityUnits[teamID] = {}
end
local scale
if onlyEnergy then
scale = TeamScaleEnergy[teamID]
else
scale = TeamScale[teamID]
end
local priorityLevel = (UnitMiscPriority[unitID] or 1) + 1
teamMiscPriorityUnits[teamID][unitID] = priorityLevel
if scale and scale[priorityLevel] then
return scale[priorityLevel]
end
return 1 -- Units have full spending if they do not know otherwise.
end
local function CheckReserveResourceUse(teamID, onlyEnergy, resTable)
local energyReserve = effectiveTeamEnergyReserved[teamID] or 0
if energyReserve ~= 0 then
local eCurr = spGetTeamResources(teamID, "energy")
if eCurr <= energyReserve - ((resTable and resTable.e) or 0) then
return false
end
end
if onlyEnergy then
return true
end
local metalReserve = effectiveTeamMetalReserved[teamID] or 0
if metalReserve ~= 0 then
local mCurr = spGetTeamResources(teamID, "metal")
if mCurr <= metalReserve - ((resTable and resTable.m) or 0) then
return false
end
end
return true
end
-- This is the other way that Misc Priority tasks can build at the correct rate.
-- It is quite like AllowUnitBuildStep.
local function AllowMiscPriorityBuildStep(unitID, teamID, onlyEnergy, resTable)
local conAmount = UnitMiscPortion[unitID] or math.random()
if (teamMiscPriorityUnits[teamID] == nil) then
teamMiscPriorityUnits[teamID] = {}
end
local scale
if onlyEnergy then
scale = TeamScaleEnergy[teamID]
else
scale = TeamScale[teamID]
end
local priorityLevel = (UnitMiscPriority[unitID] or 1) + 1
teamMiscPriorityUnits[teamID][unitID] = priorityLevel
if scale and scale[priorityLevel] then
conAmount = conAmount + scale[priorityLevel]
if conAmount >= 1 then
UnitMiscPortion[unitID] = conAmount - 1
return priorityLevel == 3 or CheckReserveResourceUse(teamID, onlyEnergy, resTable)
else
UnitMiscPortion[unitID] = conAmount
return false
end
end
return true
end
function gadget:AllowUnitBuildStep(builderID, teamID, unitID, unitDefID, step)
if (step<=0) then
--// Reclaiming and null buildpower (waited cons) aren't prioritized
return true
end
local conAmount = UnitConPortion[builderID] or math.random()
if (TeamPriorityUnits[teamID] == nil) then
TeamPriorityUnits[teamID] = {}
end
local scale
if UnitOnlyEnergy[builderID] then
scale = TeamScaleEnergy[teamID]
else
scale = TeamScale[teamID]
end
if checkOnlyEnergy then
local _,_,inBuild = spGetUnitIsStunned(unitID)
if inBuild then
UnitOnlyEnergy[builderID] = false
else
UnitOnlyEnergy[builderID] = (spGetUnitRulesParam(unitID, "repairRate") or 1)
end
end
local priorityLevel
if (UnitPriority[unitID] == 0 or (UnitPriority[builderID] == 0 and (UnitPriority[unitID] or 1) == 1 )) then
priorityLevel = 1
elseif (UnitPriority[unitID] == 2 or (UnitPriority[builderID] == 2 and (UnitPriority[unitID] or 1) == 1)) then
priorityLevel = 3
else
priorityLevel = 2
end
TeamPriorityUnits[teamID][builderID] = priorityLevel
if scale and scale[priorityLevel] then
-- scale is a ratio between available-resource and desired-spending.
conAmount = conAmount + scale[priorityLevel]
if conAmount >= 1 then
UnitConPortion[builderID] = conAmount - 1
return priorityLevel == 3 or CheckReserveResourceUse(teamID, UnitOnlyEnergy[builderID])
else
UnitConPortion[builderID] = conAmount
return false
end
end
return true
end
function gadget:GameFrame(n)
if n % TEAM_SLOWUPDATE_RATE == 1 then
local prioUnits, miscPrioUnits
local debugMode
local teams = spGetTeamList()
for i=1,#teams do
local teamID = teams[i]
debugMode = debugTeam and debugTeam[teamID]
prioUnits = TeamPriorityUnits[teamID] or {}
miscPrioUnits = teamMiscPriorityUnits[teamID] or {}
local spending = {0,0,0}
local energySpending = {0,0,0}
local realEnergyOnlyPull = 0
local scaleEnergy = TeamScaleEnergy[teamID]
if debugMode then
Spring.Echo("====== Frame " .. n .. " ======")
if scaleEnergy then
Spring.Echo("team " .. i .. " Initial energy only scale",
"High", scaleEnergy[3],
"Med", scaleEnergy[2],
"Low", scaleEnergy[1]
)
end
end
for unitID, pri in pairs(prioUnits) do --add construction priority spending
local unitDefID = spGetUnitDefID(unitID)
if unitDefID ~= nil then
if UnitOnlyEnergy[unitID] then
local buildSpeed = spGetUnitRulesParam(unitID, "buildSpeed") or UnitDefs[unitDefID].buildSpeed
energySpending[pri] = energySpending[pri] + buildSpeed*UnitOnlyEnergy[unitID]
if scaleEnergy and scaleEnergy[pri] then
realEnergyOnlyPull = realEnergyOnlyPull + buildSpeed*UnitOnlyEnergy[unitID]*scaleEnergy[pri]
if debugMode and debugOnUnits then
GG.UnitEcho(unitID, "Energy Priority: " .. pri ..
", BP: " .. buildSpeed ..
", Pull: " .. buildSpeed*UnitOnlyEnergy[unitID]*scaleEnergy[pri]
)
end
end
else
local buildSpeed = spGetUnitRulesParam(unitID, "buildSpeed") or UnitDefs[unitDefID].buildSpeed
spending[pri] = spending[pri] + buildSpeed
if debugMode and debugOnUnits then
GG.UnitEcho(unitID, "Priority: " .. pri ..
", BP: " .. buildSpeed
)
end
end
end
end
for unitID, miscData in pairs(miscResourceDrain) do --add misc priority spending
local unitDefID = spGetUnitDefID(unitID)
local pri = miscPrioUnits[unitID]
if unitDefID ~= nil and pri then
for index, drain in pairs(miscData) do
if MiscUnitOnlyEnergy[unitID][index] then
energySpending[pri] = energySpending[pri] + drain
if scaleEnergy and scaleEnergy[pri] then
realEnergyOnlyPull = realEnergyOnlyPull + drain*scaleEnergy[pri]
if debugMode and debugOnUnits then
GG.UnitEcho(unitID, "Misc Energy Priority " .. index .. ": " .. pri ..
", BP: " .. drain ..
", Pull: " .. realEnergyOnlyPull + drain*scaleEnergy[pri]
)
end
end
else
spending[pri] = spending[pri] + drain
if debugMode and debugOnUnits then
GG.UnitEcho(unitID, "Misc Priority " .. index .. ": " .. pri ..
", BP: " .. drain
)
end
end
end
end
end
--SendToUnsynced("PriorityStats", teamID, prioSpending, lowPrioSpending, n)
local level, mStor, fakeMetalPull, income, expense, _, _, recieved = spGetTeamResources(teamID, "metal", true)
local elevel, eStor, fakeEnergyPull, eincome, eexpense, _, _, erecieved = spGetTeamResources(teamID, "energy", true)
eincome = eincome + (spGetTeamRulesParam(teamID, "OD_energyIncome") or 0)
effectiveTeamMetalReserved[teamID] = math.min(mStor - HIDDEN_STORAGE, TeamMetalReserved[teamID] or 0)
effectiveTeamEnergyReserved[teamID] = math.min(eStor - HIDDEN_STORAGE, TeamEnergyReserved[teamID] or 0)
-- Take away the constant income which was gained this frame (innate, reclaim)
-- This is to ensure that level + total income is exactly what will be gained in the next second (if nothing is spent).
local lumpIncome = (spGetTeamRulesParam(teamID, "OD_metalBase") or 0) +
(spGetTeamRulesParam(teamID, "OD_metalOverdrive") or 0) + (spGetTeamRulesParam(teamID, "OD_metalMisc") or 0)
level = level - (income - lumpIncome)/30
-- Make sure the misc resoucing is constantly pulling the same value regardless of whether resources are spent
-- If AllowUnitBuildStep returns false the constructor does not add the attempt to pull. This makes pull incorrect.
-- The following calculations get the useful type of pull.
local metalPull = spending[1] + spending[2] + spending[3]
local energyPull = fakeEnergyPull + metalPull - fakeMetalPull + energySpending[1] + energySpending[2] + energySpending[3] - realEnergyOnlyPull
spSetTeamRulesParam(teamID, "extraMetalPull", metalPull - fakeMetalPull, ALLY_ACCESS)
spSetTeamRulesParam(teamID, "extraEnergyPull", energyPull - fakeEnergyPull, ALLY_ACCESS)
if debugMode then
if spending then
Spring.Echo("team " .. i .. " Pull",
"High", spending[3],
"Med", spending[2],
"Low", spending[1]
)
end
end
if debugMode then
if energySpending then
Spring.Echo("team " .. i .. " Energy Only Pull",
"High", energySpending[3],
"Med", energySpending[2],
"Low", energySpending[1]
)
end
end
if debugMode then
Spring.Echo("team " .. i .. " old resource levels:")
if scaleEnergy then
Spring.Echo("nextMetalLevel: " .. (level or "nil"))
Spring.Echo("nextEnergyLevel: " .. (elevel or "nil"))
end
end
-- How much of each resource there is to spend in the next second.
local nextMetalLevel = (income + recieved + level)
local nextEnergyLevel = (eincome + erecieved + elevel)
if debugMode then
Spring.Echo("team " .. i .. " new resource levels:")
if scaleEnergy then
Spring.Echo("nextMetalLevel: " .. (nextMetalLevel or "nil"))
Spring.Echo("nextEnergyLevel: " .. (nextEnergyLevel or "nil"))
end
end
TeamScale[teamID] = {}
TeamScaleEnergy[teamID] = {}
for pri = 3, 1, -1 do
local metalDrain = spending[pri]
local energyDrain = spending[pri] + energySpending[pri]
--if i == 1 then
-- Spring.Echo(pri .. " energyDrain " .. energyDrain)
-- Spring.Echo(pri .. " nextEnergyLevel " .. nextEnergyLevel)
--end
if metalDrain > 0 and energyDrain > 0 and (nextMetalLevel <= metalDrain or nextEnergyLevel <= energyDrain) then
-- both these values are positive and at least one is less than 1
local mRatio = max(0,nextMetalLevel)/metalDrain
local eRatio = max(0,nextEnergyLevel)/energyDrain
local spare
if mRatio < eRatio then
-- mRatio is lower so we are stalling metal harder.
-- Set construction scale limited by metal.
TeamScale[teamID][pri] = mRatio
nextEnergyLevel = nextEnergyLevel - nextMetalLevel
nextMetalLevel = 0
-- Use leftover energy for energy-only tasks.
energyDrain = energySpending[pri]
if energyDrain > 0 and nextEnergyLevel <= energyDrain then
eRatio = nextEnergyLevel/energyDrain
TeamScaleEnergy[teamID][pri] = eRatio
nextEnergyLevel = 0
else
TeamScaleEnergy[teamID][pri] = 1
nextEnergyLevel = nextEnergyLevel - energyDrain
end
else
-- eRatio is lower so we are stalling energy harder.
-- Set scale for build and repair equally and limit by energy.
TeamScale[teamID][pri] = eRatio
TeamScaleEnergy[teamID][pri] = eRatio
nextMetalLevel = nextMetalLevel - nextEnergyLevel
nextEnergyLevel = 0
end
elseif energyDrain > 0 and nextEnergyLevel <= energyDrain then
local eRatio = max(0,nextEnergyLevel)/energyDrain
-- Set scale for build and repair equally and limit by energy.
TeamScale[teamID][pri] = eRatio
TeamScaleEnergy[teamID][pri] = eRatio
nextMetalLevel = nextMetalLevel - nextEnergyLevel
nextEnergyLevel = 0
else
TeamScale[teamID][pri] = 1
TeamScaleEnergy[teamID][pri] = 1
nextMetalLevel = nextMetalLevel - metalDrain
nextEnergyLevel = nextEnergyLevel - energyDrain
end
if pri == 3 then
nextMetalLevel = nextMetalLevel - effectiveTeamMetalReserved[teamID]
nextEnergyLevel = nextEnergyLevel - effectiveTeamEnergyReserved[teamID]
end
end
if debugMode then
if TeamScale[teamID] then
Spring.Echo("team " .. i .. " Scale",
"High", TeamScale[teamID][3],
"Med", TeamScale[teamID][2],
"Low", TeamScale[teamID][1]
)
end
end
if debugMode then
if TeamScaleEnergy[teamID] then
Spring.Echo("team " .. i .. " Energy Only Scale",
"High", TeamScaleEnergy[teamID][3],
"Med", TeamScaleEnergy[teamID][2],
"Low", TeamScaleEnergy[teamID][1]
)
end
end
end
teamMiscPriorityUnits = {} --reset priority list
TeamPriorityUnits = {} --reset builder priority list (will be checked every n%32==15 th frame)
checkOnlyEnergy = false
end
if n % TEAM_SLOWUPDATE_RATE == 0 then
checkOnlyEnergy = true
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Misc priority unit handling
function AddMiscPriorityUnit(unitID) --remotely add a priority command.
if not UnitMiscPriority[unitID] then
local unitDefID = Spring.GetUnitDefID(unitID)
local ud = UnitDefs[unitDefID]
spInsertUnitCmdDesc(unitID, MiscCommandOrder, MiscCommandDesc)
SetPriorityState(unitID, DefaultState, CMD_MISC_PRIORITY)
end
end
function StartMiscPriorityResourcing(unitID, drain, energyOnly, key) --remotely add a priority command.
if not UnitMiscPriority[unitID] then
AddMiscPriorityUnit(unitID)
end
if not miscResourceDrain[unitID] then
miscResourceDrain[unitID] = {}
MiscUnitOnlyEnergy[unitID] = {}
end
key = key or 1
miscResourceDrain[unitID][key] = drain
MiscUnitOnlyEnergy[unitID][key] = energyOnly
end
function StopMiscPriorityResourcing(unitID, key) --remotely remove a forced priority command.
if miscResourceDrain[unitID] then
key = key or 1
miscResourceDrain[unitID][key] = nil
MiscUnitOnlyEnergy[unitID][key] = nil
end
end
function RemoveMiscPriorityUnit(unitID) --remotely remove a forced priority command.
if UnitMiscPriority[unitID] then
if miscResourceDrain[unitID] then
miscResourceDrain[unitID] = nil
MiscUnitOnlyEnergy[unitID] = nil
end
local unitDefID = Spring.GetUnitDefID(unitID)
local ud = UnitDefs[unitDefID]
local cmdDescID = spFindUnitCmdDesc(unitID, CMD_MISC_PRIORITY)
if (cmdDescID) then
spRemoveUnitCmdDesc(unitID, cmdDescID)
spSetUnitRulesParam(unitID, "miscpriority", 1) --reset to normal priority so that overhead icon doesn't show wrench
end
end
end
function gadget:UnitTaken(unitID, unitDefID, oldTeamID, teamID)
if miscResourceDrain[unitID] then
StopMiscPriorityResourcing(unitID)
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Debug
local function toggleDebug(cmd, line, words, player)
if not Spring.IsCheatingEnabled() then
return
end
local teamID = tonumber(words[1])
Spring.Echo("Debug priority for team " .. (teamID or "nil"))
if teamID then
if not debugTeam then
debugTeam = {}
end
if debugTeam[teamID] then
debugTeam[teamID] = nil
if #debugTeam == 0 then
debugTeam = {}
end
Spring.Echo("Disabled")
else
debugTeam[teamID] = true
Spring.Echo("Enabled")
end
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Unit Handling
function gadget:Initialize()
GG.AllowMiscPriorityBuildStep = AllowMiscPriorityBuildStep
GG.GetMiscPrioritySpendScale = GetMiscPrioritySpendScale
GG.AddMiscPriorityUnit = AddMiscPriorityUnit
GG.StartMiscPriorityResourcing = StartMiscPriorityResourcing
GG.StopMiscPriorityResourcing = StopMiscPriorityResourcing
GG.RemoveMiscPriorityUnit = RemoveMiscPriorityUnit
gadgetHandler:RegisterCMDID(CMD_PRIORITY)
gadgetHandler:RegisterCMDID(CMD_MISC_PRIORITY)
for _, unitID in ipairs(Spring.GetAllUnits()) do
local teamID = Spring.GetUnitTeam(unitID)
spInsertUnitCmdDesc(unitID, CommandOrder, CommandDesc)
end
--toggleDebug(nil, nil, {"0"}, nil)
gadgetHandler:AddChatAction("debugpri", toggleDebug, "Debugs priority.")
end
function gadget:RecvLuaMsg(msg, playerID)
if msg:find("mreserve:",1,true) then
local _,_,spec,teamID = spGetPlayerInfo(playerID)
local amount = tonumber(msg:sub(10))
if spec or (not teamID) or (not amount) then
return
end
SetMetalReserved(teamID, amount)
end
if msg:find("ereserve:",1,true) then
local _,_,spec,teamID = spGetPlayerInfo(playerID)
local amount = tonumber(msg:sub(10))
if spec or (not teamID) or (not amount) then
return
end
SetEnergyReserved(teamID, amount)
end
end
function gadget:UnitCreated(UnitID, UnitDefID, TeamID, builderID)
local prio = DefaultState
if (builderID ~= nil) then
local unitDefID = spGetUnitDefID(builderID)
if (unitDefID ~= nil and UnitDefs[unitDefID].isFactory) then
prio = UnitPriority[builderID] or DefaultState -- inherit priorty from factory
LastUnitFromFactory[builderID] = UnitID
end
end
UnitPriority[UnitID] = prio
CommandDesc.params[1] = prio
spInsertUnitCmdDesc(UnitID, CommandOrder, CommandDesc)
end
function gadget:UnitFinished(unitID, unitDefID, teamID)
local ud = UnitDefs[unitDefID]
if ((ud.isFactory or ud.isBuilder) and (ud.buildSpeed > 0 and not ud.customParams.nobuildpower)) then
SetPriorityState(unitID, DefaultState, CMD_PRIORITY)
else -- not a builder priority makes no sense now
UnitPriority[unitID] = nil
local cmdDescID = spFindUnitCmdDesc(unitID, CMD_PRIORITY)
if (cmdDescID) then
spRemoveUnitCmdDesc(unitID, cmdDescID)
end
end
end
function gadget:UnitDestroyed(unitID, unitDefID, teamID)
UnitPriority[unitID] = nil
LastUnitFromFactory[unitID] = nil
if UnitMiscPriority[unitID] then
RemoveMiscPriorityUnit(unitID)
end
end
| gpl-2.0 |
AresTao/darkstar | scripts/zones/Pashhow_Marshlands/npcs/Cavernous_Maw.lua | 29 | 1512 | -----------------------------------
-- Area: Pashhow Marshlands
-- NPC: Cavernous Maw
-- @pos 418 25 27 109
-- Teleports Players to Pashhow Marshlands [S]
-----------------------------------
package.loaded["scripts/zones/Pashhow_Marshlands/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/teleports");
require("scripts/globals/campaign");
require("scripts/zones/Pashhow_Marshlands/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (ENABLE_WOTG == 1 and player:hasKeyItem(PURE_WHITE_FEATHER) and hasMawActivated(player,4)) then
player:startEvent(0x0389);
else
player:messageSpecial(NOTHING_HAPPENS);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0389 and option == 1) then
toMaw(player,15);
end
end; | gpl-3.0 |
DeinFreund/Zero-K | scripts/pw_dropfac.lua | 5 | 1466 | include "constants.lua"
local spGetUnitTeam = Spring.GetUnitTeam
--pieces
local base = piece("base")
local nano1, nano2 = piece("nano1", "nano2")
local build = piece("build")
--local vars
local nanoPieces = {nano1, nano2}
local nanoIdx = 1
local smokePiece = {base}
--opening animation
local function Open()
SetUnitValue(COB.BUGGER_OFF, 1)
SetUnitValue(COB.INBUILDSTANCE, 1)
end
--closing animation of the factory
local function Close()
SetUnitValue(COB.BUGGER_OFF, 0)
SetUnitValue(COB.INBUILDSTANCE, 0)
end
function script.Create()
StartThread(SmokeUnit, smokePiece)
Spring.SetUnitNanoPieces(unitID, nanoPieces)
end
function script.QueryBuildInfo()
return build
end
function script.QueryNanoPiece()
nanoIdx = nanoIdx + 1
if (nanoIdx > #nanoPieces) then
nanoIdx = 1
end
local nano = nanoPieces[nanoIdx]
--// send to LUPS
GG.LUPS.QueryNanoPiece(unitID,unitDefID,spGetUnitTeam(unitID),nano)
return nano
end
function script.QueryLandingPads()
return { build }
end
function script.Activate()
if Spring.GetUnitRulesParam(unitID, "planetwarsDisable") == 1 or GG.applyPlanetwarsDisable then
return
end
StartThread(Open)
end
function script.Deactivate()
StartThread(Close)
end
--death and wrecks
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage / maxHealth
if (severity <= .25) then
return 1 -- corpsetype
elseif (severity <= .5) then
return 1 -- corpsetype
else
return 2 -- corpsetype
end
end | gpl-2.0 |
AresTao/darkstar | scripts/zones/Chamber_of_Oracles/bcnms/through_the_quicksand_caves.lua | 17 | 1880 | -----------------------------------
-- Area: Qu'Bia Arena
-- Name: Zilart Mission 6
-- @pos -221 -24 19 206
-----------------------------------
package.loaded["scripts/zones/Sacrificial_Chamber/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Sacrificial_Chamber/TextIDs");
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
-- print("leave code "..leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
if (player:getCurrentMission(ZILART) == THROUGH_THE_QUICKSAND_CAVES) then
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0);
else
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1);
end
elseif (leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
if (csid == 0x7d01) then
if (player:getCurrentMission(ZILART) == THROUGH_THE_QUICKSAND_CAVES) then
player:completeMission(ZILART,THROUGH_THE_QUICKSAND_CAVES);
player:addMission(ZILART,THE_CHAMBER_OF_ORACLES);
end
end
end; | gpl-3.0 |
AresTao/darkstar | scripts/globals/mobskills/Tail_Crush.lua | 25 | 1026 | ---------------------------------------------
-- Tail Crush
--
-- Description: Smashes a single target with its tail. Additional effect: Poison
-- Type: Physical
-- Utsusemi/Blink absorb: 1 shadow
-- Range: Melee
-- Notes:
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 1;
local accmod = 1;
local dmgmod = 2.5;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded);
local typeEffect = EFFECT_POISON;
local power = mob:getMainLvl()/10 + 10;
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, power, 3, 60);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
u-stone/vlc | share/lua/modules/simplexml.lua | 103 | 3732 | --[==========================================================================[
simplexml.lua: Lua simple xml parser wrapper
--[==========================================================================[
Copyright (C) 2010 Antoine Cellerier
$Id$
Authors: Antoine Cellerier <dionoea at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]==========================================================================]
module("simplexml",package.seeall)
--[[ Returns the xml tree structure
-- Each node is of one of the following types:
-- { name (string), attributes (key->value map), children (node array) }
-- text content (string)
--]]
local function parsexml(stream, errormsg)
if not stream then return nil, errormsg end
local xml = vlc.xml()
local reader = xml:create_reader(stream)
local tree
local parents = {}
local nodetype, nodename = reader:next_node()
while nodetype > 0 do
if nodetype == 1 then
local node = { name= nodename, attributes= {}, children= {} }
local attr, value = reader:next_attr()
while attr ~= nil do
node.attributes[attr] = value
attr, value = reader:next_attr()
end
if tree then
table.insert(tree.children, node)
table.insert(parents, tree)
end
tree = node
elseif nodetype == 2 then
if #parents > 0 then
local tmp = {}
while nodename ~= tree.name do
if #parents == 0 then
error("XML parser error/faulty logic")
end
local child = tree
tree = parents[#parents]
table.remove(parents)
table.remove(tree.children)
table.insert(tmp, 1, child)
for i, node in pairs(child.children) do
table.insert(tmp, i+1, node)
end
child.children = {}
end
for _, node in pairs(tmp) do
table.insert(tree.children, node)
end
tree = parents[#parents]
table.remove(parents)
end
elseif nodetype == 3 then
table.insert(tree.children, nodename)
end
nodetype, nodename = reader:next_node()
end
if #parents > 0 then
error("XML parser error/Missing closing tags")
end
return tree
end
function parse_url(url)
return parsexml(vlc.stream(url))
end
function parse_string(str)
return parsexml(vlc.memory_stream(str))
end
function add_name_maps(tree)
tree.children_map = {}
for _, node in pairs(tree.children) do
if type(node) == "table" then
if not tree.children_map[node.name] then
tree.children_map[node.name] = {}
end
table.insert(tree.children_map[node.name], node)
add_name_maps(node)
end
end
end
| gpl-2.0 |
inoc603/my-vim | lua/config/explorer.lua | 1 | 1190 | local use = require("packer").use
use {
'kyazdani42/nvim-tree.lua',
requires = { 'kyazdani42/nvim-web-devicons' },
config = function()
require("nvim-tree").setup {
filters = {
custom = { '^.git' }
},
renderer = {
highlight_git = true,
},
actions = {
open_file = {
window_picker = {
enable = false,
},
}
},
}
local function keymap(mode, opts)
return function(key, f)
vim.keymap.set(mode, key, f, opts)
end
end
local nnoremap = keymap("n", { noremap = true, silent = true })
nnoremap("<c-\\>", require("nvim-tree.api").tree.toggle)
end
}
use {
'kazhala/close-buffers.nvim',
config = function()
local close_buffers = require("close_buffers")
close_buffers.setup({})
-- :Bdi to wipe all hidden buffer
vim.api.nvim_create_user_command('Bdi', function()
close_buffers.wipe({ type = 'hidden' })
end, { force = true })
end
}
| mit |
AresTao/darkstar | scripts/zones/Southern_San_dOria_[S]/npcs/Raustigne.lua | 16 | 1506 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Raustigne
-- @zone 80
-- @pos 4 -2 44
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil;
require("scripts/zones/Southern_San_dOria_[S]/TextIDs");
require("scripts/globals/quests");
require("scripts/globals/settings");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(CRYSTAL_WAR, CLAWS_OF_THE_GRIFFON) == QUEST_COMPLETED and player:getVar("BoyAndTheBeast") == 0) then
if (player:getCurrentMission(WOTG) == CAIT_SITH or player:hasCompletedMission(WOTG, CAIT_SITH)) then
player:startEvent(0x0037);
end
else
player:startEvent(0x0025E);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0037) then
player:setVar("BoyAndTheBeast",1);
end
end; | gpl-3.0 |
AresTao/darkstar | scripts/zones/Rabao/npcs/Porter_Moogle.lua | 41 | 1509 | -----------------------------------
-- Area: Rabao
-- NPC: Porter Moogle
-- Type: Storage Moogle
-- @zone 247
-- @pos TODO
-----------------------------------
package.loaded["scripts/zones/Rabao/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Rabao/TextIDs");
require("scripts/globals/porter_moogle_util");
local e =
{
TALK_EVENT_ID = 136,
STORE_EVENT_ID = 137,
RETRIEVE_EVENT_ID = 138,
ALREADY_STORED_ID = 139,
MAGIAN_TRIAL_ID = 140
};
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
porterMoogleTrade(player, trade, e);
end
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- No idea what the params are, other than event ID and gil.
player:startEvent(e.TALK_EVENT_ID, 0x6FFFFF, 0x01, 0x06DD, 0x27, 0x7C7E, 0x15, player:getGil(), 0x03E8);
end
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
porterEventUpdate(player, csid, option, e.RETRIEVE_EVENT_ID, RETRIEVE_DIALOG_ID, ITEM_CANNOT_BE_OBTAINED);
end
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
porterEventFinish(player, csid, option, e.TALK_EVENT_ID, ITEM_CANNOT_BE_OBTAINED, ITEM_OBTAINED, NOT_HAVE_ENOUGH_GIL);
end | gpl-3.0 |
duncanc/packland | lua/denzquix/packland/formats/ags-room.lua | 1 | 39221 |
local ffi = require 'ffi'
local bit = require 'bit'
local R = require 'denzquix.packland.reader'
require 'denzquix.packland.data.ags.read'
-------------------------------------------------------------------------------
local format = {}
local reader_proto = {}
-------------------------------------------------------------------------------
local kRoomVersion_pre114_2 = 2 -- exact version unknown
local kRoomVersion_pre114_3 = 3 -- exact version unknown
local kRoomVersion_pre114_4 = 4 -- exact version unknown
local kRoomVersion_pre114_5 = 5 -- exact version unknown
local kRoomVersion_pre114_6 = 6 -- exact version unknown
local kRoomVersion_pre114_7 = 7 -- exact version unknown
local kRoomVersion_114 = 8
local kRoomVersion_200_alpha = 9
local kRoomVersion_200_alpha7 = 10
local kRoomVersion_200_final = 11
local kRoomVersion_208 = 12
local kRoomVersion_214 = 13
local kRoomVersion_240 = 14
local kRoomVersion_241 = 15
local kRoomVersion_250a = 16
local kRoomVersion_250b = 17
local kRoomVersion_251 = 18
local kRoomVersion_253 = 19
local kRoomVersion_255a = 20
local kRoomVersion_255b = 21
local kRoomVersion_261 = 22
local kRoomVersion_262 = 23
local kRoomVersion_270 = 24
local kRoomVersion_272 = 25
local kRoomVersion_300a = 26
local kRoomVersion_300b = 27
local kRoomVersion_303a = 28
local kRoomVersion_303b = 29
local tested_versions = {
[kRoomVersion_pre114_2] = true;
[kRoomVersion_pre114_3] = true;
[kRoomVersion_pre114_4] = true;
[kRoomVersion_pre114_5] = true;
[kRoomVersion_pre114_6] = true;
[kRoomVersion_pre114_7] = true;
[kRoomVersion_114] = true;
-- NOT kRoomVersion_200_alpha
[kRoomVersion_200_alpha7] = true;
[kRoomVersion_200_final] = true;
[kRoomVersion_208] = true;
[kRoomVersion_214] = true;
[kRoomVersion_240] = true;
-- NOT kRoomVersion_241
-- NOT kRoomVersion_250a
[kRoomVersion_250b] = true;
[kRoomVersion_251] = true;
[kRoomVersion_253] = true;
-- NOT kRoomVersion_255a
[kRoomVersion_255b] = true;
[kRoomVersion_261] = true;
[kRoomVersion_262] = true;
[kRoomVersion_270] = true;
[kRoomVersion_272] = true;
[kRoomVersion_300a] = true;
[kRoomVersion_300b] = true;
[kRoomVersion_303a] = true;
[kRoomVersion_303b] = true;
}
-------------------------------------------------------------------------------
local BLOCKTYPE_MAIN = 1
local BLOCKTYPE_SCRIPT = 2
local BLOCKTYPE_COMPSCRIPT = 3
local BLOCKTYPE_COMPSCRIPT2 = 4
local BLOCKTYPE_OBJECTNAMES = 5
local BLOCKTYPE_ANIMBKGRND = 6
local BLOCKTYPE_COMPSCRIPT3 = 7
local BLOCKTYPE_PROPERTIES = 8
local BLOCKTYPE_OBJECTSCRIPTNAMES = 9
local BLOCKTYPE_EOF = 0xFF
-------------------------------------------------------------------------------
function format.dbinit(db)
assert(db:exec [[
CREATE TABLE IF NOT EXISTS bitmap (
dbid INTEGER PRIMARY KEY,
pixel_format TEXT,
pixel_data BLOB,
palette BLOB,
width INTEGER,
height INTEGER
);
CREATE TABLE IF NOT EXISTS room (
dbid INTEGER PRIMARY KEY,
background_image_dbid INTEGER,
hotspot_map_dbid INTEGER,
walkbehind_map_dbid INTEGER,
wall_map_dbid INTEGER,
walk_zone_map_dbid INTEGER,
shadow_map_dbid INTEGER,
region_map_dbid INTEGER,
top_edge_y INTEGER,
bottom_edge_y INTEGER,
left_edge_x INTEGER,
right_edge_x INTEGER,
width INTEGER,
height INTEGER,
resolution TEXT,
game_id INTEGER,
FOREIGN KEY (background_image_dbid) REFERENCES bitmap(dbid),
FOREIGN KEY (hotspot_map_dbid) REFERENCES bitmap(dbid),
FOREIGN KEY (walkbehind_map_dbid) REFERENCES bitmap(dbid),
FOREIGN KEY (wall_map_dbid) REFERENCES bitmap(dbid),
FOREIGN KEY (walk_zone_map_dbid) REFERENCES bitmap(dbid),
FOREIGN KEY (shadow_map_dbid) REFERENCES bitmap(dbid),
FOREIGN KEY (region_map_dbid) REFERENCES bitmap(dbid)
);
CREATE TABLE IF NOT EXISTS room_walkbehind (
dbid INTEGER PRIMARY KEY,
room_dbid INTEGER NOT NULL,
idx INTEGER,
baseline INTEGER,
FOREIGN KEY (room_dbid) REFERENCES room(dbid)
);
CREATE TABLE IF NOT EXISTS room_object (
dbid INTEGER PRIMARY KEY,
room_dbid INTEGER NOT NULL,
idx INTEGER,
sprite_idx INTEGER,
x INTEGER,
y INTEGER,
is_visible INTEGER,
baseline INTEGER,
is_clickable INTEGER,
ignores_walkbehinds INTEGER,
has_tint INTEGER,
ignores_region_tint INTEGER,
ignores_scaling INTEGER,
is_solid INTEGER,
is_deleted INTEGER,
display_name TEXT,
script_name TEXT,
FOREIGN KEY (room_dbid) REFERENCES room(dbid)
);
CREATE TABLE IF NOT EXISTS room_hotspot (
dbid INTEGER PRIMARY KEY,
room_dbid INTEGER NOT NULL,
idx INTEGER,
display_name TEXT,
script_name TEXT,
FOREIGN KEY (room_dbid) REFERENCES room(dbid)
);
CREATE TABLE IF NOT EXISTS message (
dbid INTEGER PRIMARY KEY,
room_dbid INTEGER,
idx INTEGER,
content TEXT,
continues_to_next INTEGER,
is_removed_after_timeout INTEGER,
is_shown_as_speech INTEGER,
FOREIGN KEY (room_dbid) REFERENCES room(dbid)
);
CREATE TABLE IF NOT EXISTS room_anim (
dbid INTEGER PRIMARY KEY,
room_dbid INTEGER,
idx INTEGER,
FOREIGN KEY (room_dbid) REFERENCES room(dbid)
);
CREATE TABLE IF NOT EXISTS room_anim_stage (
dbid INTEGER PRIMARY KEY,
anim_dbid INTEGER,
idx INTEGER,
x INTEGER,
y INTEGER,
data INTEGER,
object INTEGER,
speed INTEGER,
action INTEGER,
wait INTEGER,
FOREIGN KEY (anim_dbid) REFERENCES room_anim(dbid)
);
CREATE TABLE IF NOT EXISTS room_shadow_layer (
dbid INTEGER PRIMARY KEY,
room_dbid INTEGER,
idx INTEGER,
view_idx INTEGER,
FOREIGN KEY (room_dbid) REFERENCES room(dbid)
);
CREATE TABLE IF NOT EXISTS room_walk_zone (
dbid INTEGER PRIMARY KEY,
room_dbid INTEGER,
idx INTEGER,
scale_top INTEGER,
scale_top_y INTEGER,
scale_bottom INTEGER,
scale_bottom_y INTEGER,
FOREIGN KEY (room_dbid) REFERENCES room(dbid)
);
CREATE TABLE IF NOT EXISTS events2002_variable (
dbid INTEGER PRIMARY KEY,
room_dbid INTEGER,
idx INTEGER,
display_name TEXT,
type TEXT,
value INTEGER,
FOREIGN KEY (room_dbid) REFERENCES room(dbid)
);
CREATE TABLE IF NOT EXISTS room_region (
dbid INTEGER PRIMARY KEY,
room_dbid INTEGER,
idx INTEGER,
light_level INTEGER,
tint_level INTEGER,
FOREIGN KEY (room_dbid) REFERENCES room(dbid)
);
]])
end
function format.todb(intype, inpath, db, context)
assert(intype == 'file', 'input must be a file (got ' .. intype .. ')')
local reader = assert(R.fromfile(inpath))
reader:inject('bindata')
reader:inject(reader_proto)
local filename = inpath:match('[^\\/]*$'):lower()
local number
if filename:match('intro') then
number = 0
else
number = tonumber(filename:lower():match('room(%d+)'))
end
format.dbinit(db)
local room = {}
reader:room(room)
local exec_add_bitmap = assert(db:prepare [[
INSERT INTO bitmap (
pixel_format,
pixel_data,
palette,
width,
height
)
VALUES (
:pixel_format,
:pixel_data,
:palette,
:width,
:height
)
]])
local cached_bitmap_dbids = {}
local function add_bitmap(bitmap)
if bitmap == nil then
return nil
end
local cached = cached_bitmap_dbids[bitmap]
if cached then
return cached
end
assert( exec_add_bitmap:bind_text(':pixel_format', 'p8') )
assert( exec_add_bitmap:bind_blob(':pixel_data', bitmap.pixel_data) )
assert( exec_add_bitmap:bind_blob(':palette', bitmap.palette) )
assert( exec_add_bitmap:bind_int(':width', bitmap.width) )
assert( exec_add_bitmap:bind_int(':height', bitmap.height) )
assert( assert( exec_add_bitmap:step() ) == 'done' )
assert( exec_add_bitmap:reset() )
local dbid = db:last_insert_rowid()
cached_bitmap_dbids[bitmap] = dbid
return dbid
end
local background_image_dbid = add_bitmap(room.background_image)
local hotspot_map_dbid = add_bitmap(room.hotspot_map)
local walkbehind_map_dbid = add_bitmap(room.walkbehind_map)
local wall_map_dbid = add_bitmap(room.wall_map)
local walk_zone_map_dbid = add_bitmap(room.walk_zone_map)
local shadow_map_dbid = add_bitmap(room.shadow_map)
local region_map_dbid = add_bitmap(room.region_map)
assert( exec_add_bitmap:finalize() )
local exec_add_room = assert(db:prepare [[
INSERT INTO room (
background_image_dbid,
hotspot_map_dbid,
walkbehind_map_dbid,
walk_zone_map_dbid,
wall_map_dbid,
shadow_map_dbid,
region_map_dbid,
top_edge_y,
bottom_edge_y,
left_edge_x,
right_edge_x,
width,
height,
resolution,
game_id
)
VALUES (
:background_image_dbid,
:hotspot_map_dbid,
:walkbehind_map_dbid,
:walk_zone_map_dbid,
:wall_map_dbid,
:shadow_map_dbid,
:region_map_dbid,
:top_edge_y,
:bottom_edge_y,
:left_edge_x,
:right_edge_x,
:width,
:height,
:resolution,
:game_id
)
]])
assert( exec_add_room:bind_int64(':background_image_dbid', background_image_dbid) )
assert( exec_add_room:bind_int64(':hotspot_map_dbid', hotspot_map_dbid ) )
assert( exec_add_room:bind_int64(':walkbehind_map_dbid', walkbehind_map_dbid ) )
if wall_map_dbid == nil then
assert( exec_add_room:bind_null(':wall_map_dbid') )
else
assert( exec_add_room:bind_int64(':wall_map_dbid', wall_map_dbid ) )
end
if walk_zone_map_dbid == nil then
assert( exec_add_room:bind_null(':walk_zone_map_dbid') )
else
assert( exec_add_room:bind_int64(':walk_zone_map_dbid', walk_zone_map_dbid ) )
end
if shadow_map_dbid == nil then
assert( exec_add_room:bind_null(':shadow_map_dbid') )
else
assert( exec_add_room:bind_int64(':shadow_map_dbid', shadow_map_dbid ) )
end
if region_map_dbid == nil then
assert( exec_add_room:bind_null(':region_map_dbid') )
else
assert( exec_add_room:bind_int64(':region_map_dbid', region_map_dbid ) )
end
assert( exec_add_room:bind_int(':top_edge_y', room.top_edge) )
assert( exec_add_room:bind_int(':bottom_edge_y', room.bottom_edge) )
assert( exec_add_room:bind_int(':left_edge_x', room.left_edge) )
assert( exec_add_room:bind_int(':right_edge_x', room.right_edge) )
if room.width == nil then
assert( exec_add_room:bind_null(':width') )
assert( exec_add_room:bind_null(':height') )
else
assert( exec_add_room:bind_int(':width', room.width) )
assert( exec_add_room:bind_int(':height', room.height) )
end
assert( exec_add_room:bind_text(':resolution', room.resolution) )
if room.game_id == nil then
assert( exec_add_room:bind_null(':game_id') )
else
assert( exec_add_room:bind_int(':game_id', room.game_id) )
end
assert( assert( exec_add_room:step() ) == 'done' )
assert( exec_add_room:finalize() )
local room_dbid = db:last_insert_rowid()
if room.objects[1] then
local exec_add_object = assert(db:prepare [[
INSERT INTO room_object (
room_dbid,
idx,
sprite_idx,
x,
y,
is_visible,
script_name,
display_name,
is_clickable,
ignores_walkbehinds,
has_tint,
ignores_region_tint,
ignores_scaling,
is_solid,
is_deleted,
baseline
)
VALUES (
:room_dbid,
:idx,
:sprite_idx,
:x,
:y,
:is_visible,
:script_name,
:display_name,
:is_clickable,
:ignores_walkbehinds,
:has_tint,
:ignores_region_tint,
:ignores_scaling,
:is_solid,
:is_deleted,
:baseline
)
]])
assert( exec_add_object:bind_int64(':room_dbid', room_dbid) )
for _, object in ipairs(room.objects) do
assert( exec_add_object:bind_int(':idx', object.id) )
assert( exec_add_object:bind_int(':sprite_idx', object.sprite_idx) )
assert( exec_add_object:bind_int(':x', object.x) )
assert( exec_add_object:bind_int(':y', object.y) )
assert( exec_add_object:bind_bool(':is_visible', object.on) )
assert( exec_add_object:bind_text(':display_name', object.display_name) )
assert( exec_add_object:bind_text(':script_name', object.script_name) )
assert( exec_add_object:bind_bool(':is_clickable', object.is_clickable) )
assert( exec_add_object:bind_bool(':ignores_walkbehinds', object.ignores_walkbehinds) )
assert( exec_add_object:bind_bool(':has_tint', object.has_tint) )
assert( exec_add_object:bind_bool(':ignores_region_tint', object.ignores_region_tint) )
assert( exec_add_object:bind_bool(':ignores_scaling', object.ignores_scaling) )
assert( exec_add_object:bind_bool(':is_solid', object.is_solid) )
assert( exec_add_object:bind_bool(':is_deleted', object.is_deleted) )
if object.baseline == nil then
assert( exec_add_object:bind_null(':baseline') )
else
assert( exec_add_object:bind_int(':baseline', object.baseline) )
end
assert( assert( exec_add_object:step() ) == 'done' )
assert( exec_add_object:reset() )
end
assert( exec_add_object:finalize() )
end
if room.walkbehinds[1] then
local exec_add_walkbehind = assert(db:prepare [[
INSERT INTO room_walkbehind (
room_dbid,
idx,
baseline
)
VALUES (
:room_dbid,
:idx,
:baseline
)
]])
assert( exec_add_walkbehind:bind_int64(':room_dbid', room_dbid) )
for _, walkbehind in ipairs(room.walkbehinds) do
assert( exec_add_walkbehind:bind_int(':idx', walkbehind.id) )
if walkbehind.baseline == nil then
assert( exec_add_walkbehind:bind_null(':baseline') )
else
assert( exec_add_walkbehind:bind_int(':baseline', walkbehind.baseline) )
end
assert( assert( exec_add_walkbehind:step() ) == 'done' )
assert( exec_add_walkbehind:reset() )
end
assert( exec_add_walkbehind:finalize() )
end
if room.messages[1] then
local exec_add_message = assert(db:prepare [[
INSERT INTO message (
room_dbid,
idx,
content,
continues_to_next,
is_removed_after_timeout,
is_shown_as_speech
)
VALUES (
:room_dbid,
:idx,
:content,
:continues_to_next,
:is_removed_after_timeout,
:is_shown_as_speech
)
]])
assert( exec_add_message:bind_int64(':room_dbid', room_dbid) )
for _, message in ipairs(room.messages) do
assert( exec_add_message:bind_int(':idx', message.id) )
assert( exec_add_message:bind_text(':content', message.text) )
assert( exec_add_message:bind_bool(':continues_to_next', message.continues_to_next) )
assert( exec_add_message:bind_bool(':is_removed_after_timeout', message.is_removed_after_timeout) )
assert( exec_add_message:bind_bool(':is_shown_as_speech', message.is_shown_as_speech) )
assert( assert( exec_add_message:step() ) == 'done' )
assert( exec_add_message:reset() )
end
assert( exec_add_message:finalize() )
end
if room.hotspots[1] then
local exec_add_hotspot = assert(db:prepare [[
INSERT INTO room_hotspot (
room_dbid,
idx,
display_name,
script_name
)
VALUES (
:room_dbid,
:idx,
:display_name,
:script_name
)
]])
assert( exec_add_hotspot:bind_int64(':room_dbid', room_dbid) )
for _, hotspot in ipairs(room.hotspots) do
assert( exec_add_hotspot:bind_int(':idx', hotspot.id) )
assert( exec_add_hotspot:bind_text(':display_name', hotspot.name) )
assert( exec_add_hotspot:bind_text(':script_name', hotspot.script_name) )
assert( assert( exec_add_hotspot:step() ) == 'done' )
assert( exec_add_hotspot:reset() )
end
assert( exec_add_hotspot:finalize() )
end
if room.anims and room.anims[1] then
local exec_add_anim = assert(db:prepare [[
INSERT INTO room_anim (
room_dbid,
idx
)
values (
:room_dbid,
:idx
)
]])
assert( exec_add_anim:bind_int64(':room_dbid', room_dbid) )
local exec_add_stage = assert(db:prepare [[
INSERT INTO room_anim_stage (
anim_dbid,
idx,
x,
y,
data,
object,
speed,
action,
wait
)
VALUES (
:anim_dbid,
:idx,
:x,
:y,
:data,
:object,
:speed,
:action,
:wait
)
]])
for _, anim in ipairs(room.anims) do
assert( exec_add_anim:bind_int(':idx', anim.id) )
assert( assert( exec_add_anim:step() ) == 'done' )
assert( exec_add_anim:reset() )
local anim_dbid = db:last_insert_rowid()
assert( exec_add_stage:bind_int64(':anim_dbid', anim_dbid) )
for _, stage in ipairs(anim.stages) do
assert( exec_add_stage:bind_int(':idx', stage.id) )
assert( exec_add_stage:bind_int(':x', stage.x) )
assert( exec_add_stage:bind_int(':y', stage.y) )
assert( exec_add_stage:bind_int(':data', stage.data) )
assert( exec_add_stage:bind_int(':object', stage.object) )
assert( exec_add_stage:bind_int(':speed', stage.speed) )
assert( exec_add_stage:bind_int(':action', stage.action) )
assert( exec_add_stage:bind_int(':wait', stage.wait) )
assert( assert( exec_add_stage:step() ) == 'done' )
assert( exec_add_stage:reset() )
end
end
assert( exec_add_anim:finalize() )
assert( exec_add_stage:finalize() )
end
if room.shadow_layers and room.shadow_layers[1] then
local exec_add_shadow = assert(db:prepare [[
INSERT INTO room_shadow_layer (
room_dbid,
idx,
view_idx
)
VALUES (
:room_dbid,
:idx,
:view_idx
)
]])
assert( exec_add_shadow:bind_int64(':room_dbid', room_dbid) )
for _, shadow in ipairs(room.shadow_layers) do
assert( exec_add_shadow:bind_int(':idx', shadow.id) )
assert( exec_add_shadow:bind_int(':view_idx', shadow.view_idx) )
assert( assert(exec_add_shadow:step()) == 'done' )
assert( exec_add_shadow:reset() )
end
assert( exec_add_shadow:finalize() )
end
if room.walk_zones and room.walk_zones[1] then
local exec_add_walk_zone = assert(db:prepare [[
INSERT INTO room_walk_zone (
room_dbid,
idx,
scale_top,
scale_top_y,
scale_bottom,
scale_bottom_y
)
VALUES (
:room_dbid,
:idx,
:scale_top,
:scale_top_y,
:scale_bottom,
:scale_bottom_y
)
]])
assert( exec_add_walk_zone:bind_int64(':room_dbid', room_dbid) )
for _, walk_zone in ipairs(room.walk_zones) do
assert( exec_add_walk_zone:bind_int(':idx', walk_zone.id) )
assert( exec_add_walk_zone:bind_int(':scale_top', walk_zone.scale_top) )
assert( exec_add_walk_zone:bind_int(':scale_bottom', walk_zone.scale_bottom) )
if walk_zone.scale_top_y == nil then
assert( exec_add_walk_zone:bind_null(':scale_top_y') )
assert( exec_add_walk_zone:bind_null(':scale_bottom_y') )
else
assert( exec_add_walk_zone:bind_int(':scale_top_y', walk_zone.scale_top_y) )
assert( exec_add_walk_zone:bind_int(':scale_bottom_y', walk_zone.scale_bottom_y) )
end
assert( assert( exec_add_walk_zone:step() ) == 'done' )
assert( exec_add_walk_zone:reset() )
end
assert( exec_add_walk_zone:finalize() )
end
if room.v3_local_vars and room.v3_local_vars[1] then
local exec_add_var = assert(db:prepare [[
INSERT INTO events2002_variable (
room_dbid,
idx,
display_name,
type,
value
)
VALUES (
:room_dbid,
:idx,
:display_name,
:type,
:value
)
]])
assert( exec_add_var:bind_int64(':room_dbid', room_dbid) )
for _, local_var in ipairs(room.v3_local_vars) do
assert( exec_add_var:bind_int(':idx', local_var.id) )
assert( exec_add_var:bind_text(':display_name', local_var.name) )
assert( exec_add_var:bind_text(':type', local_var.type) )
assert( exec_add_var:bind_int(':value', local_var.value) )
assert( assert( exec_add_var:step() ) == 'done' )
assert( exec_add_var:reset() )
end
assert( exec_add_var:finalize() )
end
if room.regions and room.regions[1] then
local exec_add_region = assert(db:prepare [[
INSERT INTO room_region (
room_dbid,
idx,
light_level,
tint_level
)
VALUES (
:room_dbid,
:idx,
:light_level,
:tint_level
)
]])
assert( exec_add_region:bind_int64(':room_dbid', room_dbid) )
for _, region in ipairs(room.regions) do
assert( exec_add_region:bind_int(':idx', region.id) )
assert( exec_add_region:bind_int(':light_level', region.light_level) )
assert( exec_add_region:bind_int(':tint_level', region.tint_level) )
assert( assert( exec_add_region:step() ) == 'done' )
assert( exec_add_region:reset() )
end
assert( exec_add_region:finalize() )
end
end
function reader_proto:room(room)
local version = self:int16le()
assert(tested_versions[version], 'unsupported room data version')
if version <= kRoomVersion_pre114_4 then
self.v = version
self:room_main(room)
return
end
while true do
local chunk_id = self:uint8()
if chunk_id == BLOCKTYPE_EOF then
break
end
local chunk_length = self:int32le()
if chunk_id == BLOCKTYPE_MAIN then
local chunk_reader = R.fromstring( self:blob( chunk_length ) )
chunk_reader:inject 'bindata'
chunk_reader:inject(reader_proto)
chunk_reader.v = version
chunk_reader:room_main(room)
elseif chunk_id == BLOCKTYPE_SCRIPT then
room.source_code = self:masked_blob('+', 'Avis Durgan', chunk_length)
elseif chunk_id == BLOCKTYPE_COMPSCRIPT then
room.compiled_code_v1 = self:blob( chunk_length )
elseif chunk_id == BLOCKTYPE_COMPSCRIPT2 then
room.compiled_code_v2 = self:blob( chunk_length )
elseif chunk_id == BLOCKTYPE_COMPSCRIPT3 then
room.compiled_code_v3 = self:blob( chunk_length )
elseif chunk_id == BLOCKTYPE_OBJECTNAMES then
local end_pos = self:pos() + chunk_length
assert(self:uint8() == #room.objects, 'inconsistent object count for names')
for _, object in ipairs(room.objects) do
object.display_name = self:nullTerminated(30)
if object.display_name == '' then
object.display_name = nil
end
end
assert(self:pos() == end_pos, 'object name length has changed')
elseif chunk_id == BLOCKTYPE_ANIMBKGRND then
local end_pos = self:pos() + chunk_length
room.background_animation_frames = list( self:uint8() )
room.background_animation_speed = self:uint8()
if version >= kRoomVersion_255a then
for _, frame in ipairs(room.background_animation_frames) do
frame.shared = self:int8()
end
end
local pos = self:pos()
for i, frame in ipairs(room.background_animation_frames) do
if i == 1 then
frame.image = room.background_image
else
frame.image = {}
self:lzw_bitmap(frame.image)
end
end
assert(self:pos() == end_pos, 'unexpected length of animated background block')
elseif chunk_id == BLOCKTYPE_PROPERTIES then
local end_pos = self:pos() + chunk_length
if self:int32le() ~= 1 then
error 'invalid properties data'
end
room.properties = {}
self:properties(room.properties)
for _, hotspot in ipairs(room.hotspots) do
hotspot.properties = {}
self:properties(hotspot.properties)
end
for _, object in ipairs(room.objects) do
object.properties = {}
self:properties(object.properties)
end
assert(self:pos() == end_pos, 'unexpected length of properties block')
elseif chunk_id == BLOCKTYPE_OBJECTSCRIPTNAMES then
local end_pos = self:pos() + chunk_length
assert(self:uint8() == #room.objects, 'inconsistent object count for script names')
for _, object in ipairs(room.objects) do
object.script_name = self:nullTerminated(20)
if object.script_name == '' then
object.script_name = nil
end
end
assert(self:pos() == end_pos, 'unexpected length of object script names block')
else
error('unknown room data chunk: ' .. chunk_id)
end
end
end
function reader_proto:properties(properties)
if self:int32le() ~= 1 then
error 'invalid properties data'
end
for i = 1, self:int32le() do
local name = self:nullTerminated()
local value = self:nullTerminated()
properties[name] = value
end
end
local function list(length)
local t = {byId={}}
for i = 1, length do
local id = i-1
local el = {id = id}
t[i] = el
t.byId[id] = el
end
return t
end
function reader_proto:masked_blob(op, mask, n)
local buf = {}
if op == '+' then
for i = 1, n do
local b = self:uint8()
local mb = mask:byte(((i-1) % #mask) + 1)
buf[i] = string.char(bit.band(0xFF, b + mb))
end
elseif op == '-' then
for i = 1, n do
local b = self:uint8()
local mb = mask:byte(((i-1) % #mask) + 1)
buf[i] = string.char(bit.band(0xFF, b - mb))
end
else
error('unsupported mask op', 2)
end
return table.concat(buf)
end
function reader_proto:room_main(room)
local max_hotspots, max_objects, max_walk_zones
if self.v >= kRoomVersion_272 then
max_hotspots = 50
max_objects = 10
max_walk_zones = 16
elseif self.v >= kRoomVersion_262 then
max_hotspots = 30
max_objects = 10
max_walk_zones = 16
elseif self.v >= kRoomVersion_200_alpha then
max_hotspots = 20
max_objects = 10
max_walk_zones = 16
else
max_hotspots = 16
max_objects = 10
end
local max_shadow_layers
if self.v >= kRoomVersion_114 then
max_shadow_layers = 16
end
if max_shadow_layers then
room.shadow_layers = list(max_shadow_layers)
end
if self.v >= kRoomVersion_208 then
local bpp = self:int32le()
if bpp == 1 then
room.pixel_format = 'p8'
elseif bpp == 2 then
room.pixel_format = 'r5g6b5'
elseif bpp == 3 then
room.pixel_format = 'r8g8b8'
elseif bpp == 4 then
room.pixel_format = 'r8g8b8x8'
else
error('unsupported bits-per-pixel value: ' .. bpp)
end
else
room.pixel_format = 'p8'
end
room.walkbehinds = list(self:uint16le())
for _, walkbehind in ipairs(room.walkbehinds) do
walkbehind.baseline = self:int16le()
if walkbehind.baseline == -1 then
walkbehind.baseline = nil
end
end
if self.v >= kRoomVersion_200_alpha then
-- to trim room.hotspots later
room.used_hotspots = self:int32le()
if room.used_hotspots == 0 then
room.used_hotspots = nil
end
end
room.hotspots = list(max_hotspots)
self:inject 'ags:interactions'
if self.v >= kRoomVersion_200_alpha and self.v <= kRoomVersion_240 then
for _, hotspot in ipairs(room.hotspots) do
hotspot.interactions_v2 = {}
self:interactions_v2(hotspot.interactions_v2)
end
room.objects = list(max_objects)
for _, object in ipairs(room.objects) do
object.interactions_v2 = {}
self:interactions_v2(object.interactions_v2)
end
room.interactions_v2 = {}
self:interactions_v2(room.interactions_v2)
end
if room.used_hotspots then
for i = room.used_hotspots+1, max_hotspots do
room.hotspots[i] = nil
end
end
if self.v >= kRoomVersion_200_alpha then
for _, hotspot in ipairs(room.hotspots) do
hotspot.walk_to_x = self:int16le()
hotspot.walk_to_y = self:int16le()
end
end
if self.v >= kRoomVersion_303a then
for _, hotspot in ipairs(room.hotspots) do
hotspot.name = self:nullTerminated()
end
elseif self.v >= kRoomVersion_200_alpha then
for _, hotspot in ipairs(room.hotspots) do
hotspot.name = self:nullTerminated(30)
end
end
if self.v >= kRoomVersion_270 then
for _, hotspot in ipairs(room.hotspots) do
hotspot.script_name = self:nullTerminated(20):match('^.+$')
end
end
if self.v >= kRoomVersion_200_alpha then
room.walls = list( self:int32le() )
for _, wall in ipairs(room.walls) do
wall.points = list(30)
for _, point in ipairs(wall.points) do
point.x = self:int32le()
end
for _, point in ipairs(wall.points) do
point.y = self:int32le()
end
for i = self:int32le() + 1, #wall.points do
wall.points[i] = nil
end
end
end
if self.v <= kRoomVersion_pre114_6 then
room.interactions_v1 = {events = list(125)}
self:interactions_v1(room.interactions_v1)
elseif self.v <= kRoomVersion_114 then
room.interactions_v1 = {events = list(127)}
self:interactions_v1(room.interactions_v1)
end
room.top_edge = self:int16le()
room.bottom_edge = self:int16le()
room.left_edge = self:int16le()
room.right_edge = self:int16le()
local used_object_count = self:uint16le()
if room.objects then
for i = used_object_count + 1, max_objects do
room.objects[i] = nil
end
else
room.objects = list(used_object_count)
end
for _, object in ipairs(room.objects) do
self:room_object(object)
end
if self.v >= kRoomVersion_253 then
room.v3_local_vars = list( self:int32le() )
for _, local_var in ipairs(room.v3_local_vars) do
self:v3_local_var(local_var)
end
end
if self.v >= kRoomVersion_241 and self.v < kRoomVersion_300a then
for _, hotspot in ipairs(room.hotspots) do
hotspot.interactions_v3 = {}
self:interactions_v3(hotspot.interactions_v3)
end
for _, object in ipairs(room.objects) do
object.interactions_v3 = {}
self:interactions_v3(object.interactions_v3)
end
room.interactions_v3 = {}
self:interactions_v3(room.interactions_v3)
end
if self.v >= kRoomVersion_255b then
room.regions = list( self:int32le() )
end
if self.v >= kRoomVersion_255b and self.v < kRoomVersion_300a then
for _, region in ipairs(room.regions) do
region.interactions_v3 = {}
self:interactions_v3(region.interactions_v3)
end
end
if self.v >= kRoomVersion_300a then
room.interactions_v4 = {}
self:interactions_v4(room.interactions_v4)
for _, hotspot in ipairs(room.hotspots) do
hotspot.interactions_v4 = {}
self:interactions_v4(hotspot.interactions_v4)
end
for _, object in ipairs(room.objects) do
object.interactions_v4 = {}
self:interactions_v4(object.interactions_v4)
end
for _, region in ipairs(room.regions) do
region.interactions_v4 = {}
self:interactions_v4(region.interactions_v4)
end
end
if self.v >= kRoomVersion_200_alpha then
for _, object in ipairs(room.objects) do
object.baseline = self:int32le()
if object.baseline == -1 then
object.baseline = nil
end
end
room.width = self:int16le()
room.height = self:int16le()
end
if self.v >= kRoomVersion_262 then
for _, object in ipairs(room.objects) do
object.flags = self:int16le()
end
end
for _, object in ipairs(room.objects) do
local flags = object.flags or 0
object.is_clickable = 0 == bit.band(flags, 1)
object.ignores_walkbehinds = 0 ~= bit.band(flags, 2)
object.has_tint = 0 ~= bit.band(flags, 4)
object.ignores_region_tint = 0 == bit.band(flags, 8)
object.ignores_scaling = 0 == bit.band(flags, 0x10)
object.is_solid = 0 ~= bit.band(flags, 0x20)
object.is_deleted = 0 ~= bit.band(flags, 0x40)
end
if self.v >= kRoomVersion_200_final then
room.resolution = self:int16le()
if room.resolution == 1 then
room.resolution = 'low'
elseif room.resolution == 2 then
room.resolution = 'high'
else
room.resolution = tostring(room.resolution)
end
end
if self.v >= kRoomVersion_240 then
local walk_zone_count = self:int32le()
if walk_zone_count == 0 then
walk_zone_count = max_walk_zones - 1
end
room.walk_zones = list(walk_zone_count + 1)
elseif self.v >= kRoomVersion_200_alpha7 then
room.walk_zones = list(max_walk_zones)
end
if room.walk_zones then
table.remove(room.walk_zones, 1)
room.walk_zones.byId[0] = nil
end
if self.v >= kRoomVersion_200_alpha7 then
for _, walk_zone in ipairs(room.walk_zones) do
walk_zone.scale_top = self:int16le()
walk_zone.scale_bottom = walk_zone.scale_top
end
end
if self.v >= kRoomVersion_255b then
-- we now have regions, so the old walk zone light-level is no longer used
-- it still exists in the room data, but just gets ignored
self:skip( 2 * #room.walk_zones )
elseif self.v >= kRoomVersion_214 then
-- regions are duplicated from walk zones, with light level applied
room.regions = list( #room.walk_zones )
for _, region in ipairs(room.regions) do
region.light_level = self:int16le()
region.tint_level = 0
end
end
if self.v >= kRoomVersion_251 then
for _, walk_zone in ipairs(room.walk_zones) do
walk_zone.scale_bottom = self:int16le()
end
for _, walk_zone in ipairs(room.walk_zones) do
walk_zone.scale_top_y = self:int16le()
end
for _, walk_zone in ipairs(room.walk_zones) do
walk_zone.scale_bottom_y = self:int16le()
end
end
if self.v >= kRoomVersion_200_alpha then
room.password = self:masked_blob('+', 'Avis Durgan', 11)
else
room.password = self:masked_blob('+', '\60', 11)
end
room.password = string.match(room.password, '^%Z+')
room.startup_music = self:uint8()
room.allows_save_load = self:bool8()
room.hides_player_character = self:bool8()
room.player_special_view = self:uint8()
if room.player_special_view == 0 then
room.player_special_view = nil
end
room.music_volume = self:int8() -- 0 normal, -3 quietest, 5 loudest (but 3 highest setting in editor)
self:skip(5) -- 5 unused room options
room.messages = list(self:uint16le())
if self.v >= kRoomVersion_272 then
room.game_id = self:int32le()
end
-- TODO: check about message flags pre-v3?
for _, message in ipairs(room.messages) do
message.is_shown_as_speech = self:bool8()
local flags = self:uint8()
if 0 ~= bit.band(1, flags) then
message.continues_to_next = true
end
if 0 ~= bit.band(2, flags) then
message.is_removed_after_timeout = true
end
end
if self.v >= kRoomVersion_261 then
for _, message in ipairs(room.messages) do
message.text = self:masked_blob('-', 'Avis Durgan', self:int32le())
end
else
for _, message in ipairs(room.messages) do
message.text = self:nullTerminated()
end
end
for _, message in ipairs(room.messages) do
if message.text:sub(-1) == '\200' then
message.text = message.text:sub(1, -2)
message.continues_to_next = true
end
end
if self.v >= kRoomVersion_pre114_6 then
room.anims = list( self:int16le() )
for _, anim in ipairs(room.anims) do
self:room_anim(anim)
end
end
-- graphical script
if self.v >= kRoomVersion_pre114_4 and self.v <= kRoomVersion_241 then
assert( self:int32le() == 1, 'invalid script configuration version' )
room.script_vars = list( self:int32le() )
for _, script_var in ipairs(room.script_vars) do
script_var.name = self:blob( self:uint8() )
end
room.scripts = {}
while true do
local ct = self:int32le()
if ct == -1 or ct == nil then
break
end
room.scripts[#room.scripts+1] = {idx=ct, code=self:blob( self:int32le() )}
end
end
if self.v >= kRoomVersion_114 then
for _, shadow in ipairs(room.shadow_layers) do
shadow.view_idx = self:int16le()
end
for i = #room.shadow_layers, 1, -1 do
if room.shadow_layers[i].view_idx == 0 then
table.remove(room.shadow_layers, i)
end
end
end
if self.v >= kRoomVersion_255b then
for _, region in ipairs(room.regions) do
region.light_level = self:int16le()
end
for _, region in ipairs(room.regions) do
region.tint_level = self:int32le()
end
end
room.background_image = {}
if self.v >= kRoomVersion_pre114_5 then
self:lzw_bitmap(room.background_image, room.pixel_format)
else
self:allegro_bitmap(room.background_image)
end
if self.v >= kRoomVersion_255b then
room.region_map = {}
self:allegro_bitmap(room.region_map)
elseif self.v >= kRoomVersion_200_alpha then
-- ignored!
-- shadow map instead gets copied from walk zone map (see below)
self:allegro_bitmap({ })
elseif self.v >= kRoomVersion_114 then
room.shadow_map = {}
self:allegro_bitmap(room.shadow_map)
end
if self.v >= kRoomVersion_200_alpha then
room.walk_zone_map = {}
self:allegro_bitmap(room.walk_zone_map)
else
room.wall_map = {}
self:allegro_bitmap(room.wall_map)
end
if self.v >= kRoomVersion_214 and self.v < kRoomVersion_255b then
-- region map is just walk zone map (using the old walk zone light-level)
room.region_map = room.walk_zone_map
end
if self.v >= kRoomVersion_200_alpha then
room.shadow_map = room.walk_zone_map
end
room.walkbehind_map = {}
self:allegro_bitmap(room.walkbehind_map)
room.hotspot_map = {}
self:allegro_bitmap(room.hotspot_map)
end
function reader_proto:room_object(object)
object.sprite_idx = self:int16le()
object.x = self:int16le()
object.y = self:int16le()
object.room = self:int16le()
object.on = self:bool16()
end
function reader_proto:room_anim(anim)
anim.stages = list(10)
for _, stage in ipairs(anim.stages) do
self:anim_stage(stage)
end
for i = self:int32le() + 1, #anim.stages do
anim.stages.byId[anim.stages[i].id] = nil
anim.stages[i] = nil
end
end
function reader_proto:anim_stage(stage)
local base = self:pos()
stage.x = self:int32le()
stage.y = self:int32le()
stage.data = self:int32le()
stage.object = self:int32le()
stage.speed = self:int32le()
stage.action = self:uint8()
stage.wait = self:uint8()
self:align(4, base)
end
function reader_proto:allegro_bitmap(bitmap)
local width = self:int16le()
local height = self:int16le()
local buf = {}
local left = width * height
repeat
local bytes
local cx = self:int8()
if cx == -128 then
bytes = self:blob(1)
elseif cx < 0 then
bytes = string.rep(self:blob(1), 1 - cx)
else
bytes = self:blob(1 + cx)
end
buf[#buf+1] = bytes
left = left - #bytes
until left == 0
bitmap.width = width
bitmap.height = height
bitmap.pixel_data = table.concat(buf)
bitmap.pixel_format = 'p8'
bitmap.palette_pixel_format = 'r8g8b8'
local palbuf = {}
for i = 1, 256 do
local b = self:uint8()
local g = self:uint8()
local r = self:uint8()
palbuf[i] = string.char(
bit.bor(bit.lshift(r, 2), bit.rshift(r, 4)),
bit.bor(bit.lshift(g, 2), bit.rshift(g, 4)),
bit.bor(bit.lshift(b, 2), bit.rshift(b, 4)))
end
bitmap.palette = table.concat(palbuf)
end
local function bytes_per_pixel(pixel_format)
local bitcount = 0
for bits in pixel_format:gmatch('%d+') do
bitcount = bitcount + tonumber(bits)
end
return math.ceil(bitcount / 8)
end
function reader_proto:lzw_bitmap(bitmap, pixel_format)
local palbuf = {}
for i = 1, 256 do
local r = self:uint8()
local g = self:uint8()
local b = self:uint8()
self:skip(1)
palbuf[i] = string.char(
bit.bor(bit.lshift(r, 2), bit.rshift(r, 4)),
bit.bor(bit.lshift(g, 2), bit.rshift(g, 4)),
bit.bor(bit.lshift(b, 2), bit.rshift(b, 4)))
end
bitmap.palette_pixel_format = 'r8g8b8'
bitmap.palette = table.concat(palbuf)
local max_size = self:int32le()
local uncomp_size = self:int32le()
local end_pos = self:pos() + uncomp_size
local lzbuffer = ffi.new('uint8_t[4096]')
local ix = 0x1000 - 0x10
local pixbuf = {}
local written = 0
repeat
local bits = self:uint8()
for bitpos = 0, 7 do
if 0 ~= bit.band(bits, bit.lshift(1, bitpos)) then
local jx = self:int16le()
local len = bit.band(bit.rshift(jx, 12), 0xF) + 3
jx = bit.band(ix - jx - 1, 0xFFF)
for _ = 1, len do
pixbuf[#pixbuf+1] = string.char(lzbuffer[jx])
lzbuffer[ix] = lzbuffer[jx]
jx = (jx + 1) % 0x1000
ix = (ix + 1) % 0x1000
end
written = written + len
else
local ch = self:uint8()
lzbuffer[ix] = ch
pixbuf[#pixbuf+1] = string.char(ch)
ix = (ix + 1) % 0x1000
written = written + 1
end
if written >= max_size then
break
end
end
until written >= max_size
assert(self:pos() == end_pos)
bitmap.pixel_data = table.concat(pixbuf)
bitmap.pixel_format = pixel_format
local size_reader = R.fromstring(bitmap.pixel_data:sub(1,8))
size_reader:inject 'bindata'
bitmap.width = size_reader:int32le() / bytes_per_pixel(pixel_format)
bitmap.height = size_reader:int32le()
bitmap.pixel_data = bitmap.pixel_data:sub(9)
end
return format
| mit |
AresTao/darkstar | scripts/globals/items/anthos_xiphos.lua | 41 | 1078 | -----------------------------------------
-- ID: 17750
-- Item: Anthos Xiphos
-- Additional Effect: Water Damage
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 10;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(4,11);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_WATER, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_WATER,0);
dmg = adjustForTarget(target,dmg,ELE_WATER);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_WATER,dmg);
local message = MSGBASIC_ADD_EFFECT_DMG;
if (dmg < 0) then
message = MSGBASIC_ADD_EFFECT_HEAL;
end
return SUBEFFECT_WATER_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
DeinFreund/Zero-K | LuaRules/Gadgets/unit_terraform.lua | 1 | 130296 | -- $Id: unit_terraform.lua 4610 2009-05-12 13:03:32Z google frog $
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "Terraformers",
desc = "Terraforming script for lasso based area/line terraform, also ramp",
author = "Google Frog",
date = "Nov, 2009",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true -- loaded by default?
}
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
if gadgetHandler:IsSyncedCode() then
--------------------------------------------------------------------------------
-- SYNCED
--------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local USE_TERRAIN_TEXTURE_CHANGE = true -- (Spring.GetModOptions() or {}).terratex == "1"
-- Speedups
local cos = math.cos
local floor = math.floor
local abs = math.abs
local pi = math.pi
local ceil = math.ceil
local sqrt = math.sqrt
local pow = math.pow
local random = math.random
local max = math.max
local spAdjustHeightMap = Spring.AdjustHeightMap
local spGetGroundHeight = Spring.GetGroundHeight
local spGetGroundOrigHeight = Spring.GetGroundOrigHeight
local spGetGroundNormal = Spring.GetGroundNormal
local spLevelHeightMap = Spring.LevelHeightMap
local spGetUnitBuildFacing = Spring.GetUnitBuildFacing
local spGetCommandQueue = Spring.GetCommandQueue
local spValidUnitID = Spring.ValidUnitID
local spGetGameFrame = Spring.GetGameFrame
local spGiveOrderToUnit = Spring.GiveOrderToUnit
local spInsertUnitCmdDesc = Spring.InsertUnitCmdDesc
local spTestBuildOrder = Spring.TestBuildOrder
local spSetHeightMap = Spring.SetHeightMap
local spSetHeightMapFunc = Spring.SetHeightMapFunc
local spRevertHeightMap = Spring.RevertHeightMap
local spEditUnitCmdDesc = Spring.EditUnitCmdDesc
local spFindUnitCmdDesc = Spring.FindUnitCmdDesc
local spGetActiveCommand = Spring.GetActiveCommand
local spSpawnCEG = Spring.SpawnCEG
local spCreateUnit = Spring.CreateUnit
local spDestroyUnit = Spring.DestroyUnit
local spGetAllyTeamList = Spring.GetAllyTeamList
local spSetUnitLosMask = Spring.SetUnitLosMask
local spGetTeamInfo = Spring.GetTeamInfo
local spGetUnitHealth = Spring.GetUnitHealth
local spSetUnitHealth = Spring.SetUnitHealth
local spGetCommandQueue = Spring.GetCommandQueue
local spGetUnitTeam = Spring.GetUnitTeam
local spGetUnitAllyTeam = Spring.GetUnitAllyTeam
local spAddHeightMap = Spring.AddHeightMap
local spGetUnitPosition = Spring.GetUnitPosition
local spSetUnitPosition = Spring.SetUnitPosition
local spSetUnitSensorRadius = Spring.SetUnitSensorRadius
local spGetAllUnits = Spring.GetAllUnits
local spGetUnitIsDead = Spring.GetUnitIsDead
local spSetUnitRulesParam = Spring.SetUnitRulesParam
local mapWidth = Game.mapSizeX
local mapHeight = Game.mapSizeZ
local CMD_OPT_RIGHT = CMD.OPT_RIGHT
local CMD_OPT_SHIFT = CMD.OPT_SHIFT
local CMD_OPT_ALT = CMD.OPT_ALT
local CMD_STOP = CMD.STOP
local CMD_REPAIR = CMD.REPAIR
local CMD_INSERT = CMD.INSERT
local checkCoord = {
{x = -8, z = 0},
{x = 8, z = 0},
{x = 0, z = -8},
{x = 0, z = 8},
}
local invRoot2 = 1/sqrt(2)
local terraUnitHP = 1000000 --hp of terraunit, must be the same as on unitdef
--------------------------------------------------------------------------------
-- Configuration
--------------------------------------------------------------------------------
local bumpyMap = {}
for i = 0, 64, 8 do
bumpyMap[i] = {}
for j = 0, 64, 8 do
bumpyMap[i][j] = 32 - max(abs(i-32), abs(j-32))
end
end
local maxAreaSize = 2000 -- max X or Z bound of area terraform
local areaSegMaxSize = 200 -- max width and height of terraform squares
local maxWallPoints = 700 -- max points that can makeup a wall
local wallSegmentLength = 14 -- how many points are part of a wall segment (points are seperated 8 elmos orthagonally)
local maxRampWidth = 200 -- maximun width of ramp segment
local maxRampLegth = 200 -- maximun length of ramp segment
local maxHeightDifference = 30 -- max difference of height around terraforming, Makes Shraka Pyramids
local maxRampGradient = 5
local volumeCost = 0.0128
local pointExtraAreaCost = 0 -- 0.027
local pointExtraAreaCostDepth = 6
local pointExtraPerimeterCost = 0.1
local pointExtraPerimeterCostDepth = 6
local baseTerraunitCost = 12
local inbuiltCostMult = 0.5
local perimeterEdgeCost = {
[0] = 0,
[1] = 1,
[2] = 1.4,
[3] = 1,
[4] = 1,
}
-- cost of a point = volumeCost*diffHeight + extraCost*(extraCostDepth < diffHeight and diffHeight or extraCostDepth)
-- cost of shraka pyramid point = volumeCost*diffHeight
--ramp dimensions
local maxTotalRampLength = 3000
local maxTotalRampWidth = 800
local minTotalRampLength = 40
local minTotalRampWidth = 24
local checkLoopFrames = 1200 -- how many frames it takes to check through all cons
local terraformDecayFrames = 1800 -- how many frames a terrablock can survive for without a repair command
local decayCheckFrequency = 90 -- frequency of terraform decay checks
local structureCheckLoopFrames = 300 -- frequency of slow update for building deformation check
local terraUnitLimit = 250 -- limit on terraunits per player
local terraUnitLeash = 100 -- how many elmos a terraunit is allowed to roam
local costMult = 1
local modOptions = Spring.GetModOptions()
if modOptions.terracostmult then
costMult = modOptions.terracostmult
end
volumeCost = volumeCost * costMult * inbuiltCostMult
pointExtraPerimeterCost = pointExtraPerimeterCost * costMult * inbuiltCostMult
pointExtraAreaCost = pointExtraAreaCost * costMult * inbuiltCostMult
--------------------------------------------------------------------------------
-- Arrays
--------------------------------------------------------------------------------
local drawPositions = {count = 0, data = {}}
local drawPosMap = {}
local steepnessMarkers = {inner = {count = 0, data = {}, frame = 0}}
local structure = {}
local structureTable = {}
local structureCount = 0
local structureAreaMap = {}
local structureCheckFrame = {}
local currentCheckFrame = 0
local terraformUnit = {}
local terraformUnitTable = {}
local terraformUnitCount = 0
local terraformOrder = {}
local terraformOrders = 0
local constructor = {}
local constructorTable = {}
local constructors = 0
local currentCon = 0
local checkInterval = 0
-- Performance
local MIN_UPDATE_PERIOD = 3
local MAX_UPDATE_PERIOD = 30
local updatePeriod = 15 -- how many frames to update
local terraformOperations = 0 -- tracks how many operations. Used to prevent slowdown.
local nextUpdateCheck = 0 -- Time at which to check performance
-- Map terraform commands given by teamID and tag.
local fallbackCommands = {}
local terraunitDefID = UnitDefNames["terraunit"].id
local shieldscoutDefID = UnitDefNames["shieldscout"].id
--local novheavymineDefID = UnitDefNames["novheavymine"].id
local exceptionArray = {
[UnitDefNames["shipcarrier"].id] = true,
}
local terraformUnitDefIDs = {}
for i = 1, #UnitDefs do
local ud = UnitDefs[i]
if ud and ud.isBuilder and not ud.isFactory and not exceptionArray[i] then
terraformUnitDefIDs[i] = true
end
end
local REPAIR_ORDER_PARAMS = {0, CMD_REPAIR, CMD_OPT_RIGHT, 0} -- static because only the 4th parameter changes
local workaround_recursion_in_cmd_fallback = {}
local workaround_recursion_in_cmd_fallback_needed = false
--------------------------------------------------------------------------------
-- Custom Commands
--------------------------------------------------------------------------------
include("LuaRules/Configs/customcmds.h.lua")
local rampCmdDesc = {
id = CMD_RAMP,
type = CMDTYPE.ICON_MAP,
name = 'Ramp',
cursor = 'Ramp',
action = 'rampground',
tooltip = 'Build a Ramp - Click and drag between two positions.',
}
local levelCmdDesc = {
id = CMD_LEVEL,
type = CMDTYPE.ICON_AREA,
name = 'Level',
cursor = 'Level',
action = 'levelground',
tooltip = 'Level the terrain - Click and drag a line or closed shape.',
}
local raiseCmdDesc = {
id = CMD_RAISE,
type = CMDTYPE.ICON_AREA,
name = 'Raise',
cursor = 'Raise',
action = 'raiseground',
tooltip = 'Raises/Lower terrain - - Click and drag a line or closed shape.',
}
local smoothCmdDesc = {
id = CMD_SMOOTH,
type = CMDTYPE.ICON_AREA,
name = 'Smooth',
cursor = 'Smooth',
action = 'smoothground',
tooltip = 'Smooth the terrain - Click and drag a line or closed shape.',
}
local restoreCmdDesc = {
id = CMD_RESTORE,
type = CMDTYPE.ICON_AREA,
name = 'Restore2',
cursor = 'Restore2',
action = 'restoreground',
tooltip = 'Restore the terrain to its original shape - Click and drag a line or closed shape.',
}
local bumpyCmdDesc = {
id = CMD_BUMPY,
type = CMDTYPE.ICON_AREA,
name = 'Bumpify',
cursor = 'Repair',
action = 'bumpifyground',
tooltip = 'Makes the ground bumpy',
}
local fallbackableCommands = {
[CMD_RAMP] = true,
[CMD_LEVEL] = true,
[CMD_RAISE] = true,
[CMD_SMOOTH] = true,
[CMD_RESTORE] = true,
}
local wantedCommands = {
[CMD_RAMP] = true,
[CMD_LEVEL] = true,
[CMD_RAISE] = true,
[CMD_SMOOTH] = true,
[CMD_RESTORE] = true,
[CMD_TERRAFORM_INTERNAL] = true,
}
local cmdDescsArray = {
rampCmdDesc,
levelCmdDesc,
raiseCmdDesc,
smoothCmdDesc,
restoreCmdDesc,
--bumpyCmdDesc,
}
if (not Game.mapDamage) then -- map has "notDeformable = true", or "disablemapdamage = 1" modoption was set in the startscript
include("LuaRules/colors.h.lua")
local disabledText = '\n' .. RedStr .. "DISABLED" .. PinkStr .. " (map not deformable)"
for _, cmdDesc in ipairs(cmdDescsArray) do
cmdDesc.disabled = true
dDesc.tooltip = cmdDesc.tooltip .. disabledText
end
elseif modOptions.terrarestoreonly == "1" then
include("LuaRules/colors.h.lua")
local disabledText = '\n' .. RedStr .. "DISABLED" .. PinkStr .. " (only restore allowed)"
for _, cmdDesc in ipairs(cmdDescsArray) do
if cmdDesc ~= restoreCmdDesc then
cmdDesc.disabled = true
cmdDesc.tooltip = cmdDesc.tooltip .. disabledText
end
end
end
--------------------------------------------------------------------------------
-- New Functions
--------------------------------------------------------------------------------
local function IsBadNumber(value, thingToSay)
local isBad = (string.find(tostring(value), "n") and true) or false
if isBad then
Spring.Echo("Terraform bad number detected", thingToSay, value)
end
return isBad
end
local function SetTooltip(unitID, spent, estimatedCost)
Spring.SetUnitRulesParam(unitID, "terraform_spent", spent, {allied = true})
if IsBadNumber(estimatedCost, "SetTooltip") then
estimatedCost = 100 -- the estimate is for widgets only so better to have wrong data than to crash
end
Spring.SetUnitRulesParam(unitID, "terraform_estimate", estimatedCost, {allied = true})
end
--------------------------------------------------------------------------------
-- Terraform Calculation Functions
--------------------------------------------------------------------------------
local function linearEquation(x,m,x1,y1)
return m*(x-x1)+y1
end
local function distance(x1,y1,x2,y2)
return ((x1-x2)^2+(y1-y2)^2)^0.5
end
local function pointHeight(xs, ys, zs, x, z, m, h, xdis)
local xInt = (z-zs+m*xs+x/m)/(m+1/m)
local ratio = abs(xInt-xs)/xdis
return ratio*h+ys
end
local function bumpyFunc(x,z,bumpyType)
local sign = pow(-1,((x - x%64)/64 + (z - z%64)/64))
--return pow(-1,((x - x%8)/8 + (z - z%8)/8))*3*(bumpyType + 1)
return bumpyMap[x%64][z%64]*sign*(bumpyType + 1)
end
local function checkPointCreation(terraform_type, volumeSelection, orHeight, newHeight, startHeight, x, z)
if terraform_type == 6 then
local _, ny, _ = spGetGroundNormal(x,z)
if ny > select(2,spGetGroundNormal(x+8,z)) then
ny = select(2,spGetGroundNormal(x+8,z))
end
if ny > select(2,spGetGroundNormal(x-8,z)) then
ny = select(2,spGetGroundNormal(x-8,z))
end
if ny > select(2,spGetGroundNormal(x,z+8)) then
ny = select(2,spGetGroundNormal(x,z+8))
end
if ny > select(2,spGetGroundNormal(x,z-8)) then
ny = select(2,spGetGroundNormal(x,z-8))
end
--if (volumeSelection == 1 and ny > 0.595) or ny > 0.894 then
-- Spring.MarkerAddLine(x,0,z,x+8,0,z+8)
-- Spring.MarkerAddLine(x+8,0,z,x,0,z+8)
--end
return (volumeSelection == 1 and ny > 0.595) or ny > 0.894
end
if volumeSelection == 0 or terraform_type == 2 then
return true
end
if abs(orHeight-newHeight) == 0 then
return false
end
if terraform_type == 5 then
return (volumeSelection == 1 and orHeight < startHeight) or (volumeSelection == 2 and orHeight > startHeight)
else
return (volumeSelection == 1 and orHeight < newHeight) or (volumeSelection == 2 and orHeight > newHeight)
end
end
local function updateBorderWithPoint(border, x, z)
if x < border.left then
border.left = x
end
if x > border.right then
border.right = x
end
if z < border.top then
border.top = z
end
if z > border.bottom then
border.bottom = z
end
end
local function getPointInsideMap(x,z)
if x < 1 then
x = 1
end
if x > mapWidth-1 then
x = mapWidth-1
end
if z < 1 then
z = 1
end
if z > mapHeight-1 then
z = mapHeight-1
end
return x, z
end
local function setupTerraunit(unitID, team, x, y, z)
local y = y or CallAsTeam(team, function () return spGetGroundHeight(x,z) end)
Spring.MoveCtrl.Enable(unitID)
Spring.MoveCtrl.SetPosition(unitID, x, y or 0, z)
Spring.MoveCtrl.Disable(unitID)
spSetUnitSensorRadius(unitID,"los",0) -- REMOVE IN 0.83
spSetUnitSensorRadius(unitID,"airLos",0) -- REMOVE IN 0.83
local allyTeamList = spGetAllyTeamList()
local _,_,_,_,_,unitAllyTeam = spGetTeamInfo(team)
for i=1, #allyTeamList do
local allyID = allyTeamList[i]
if allyID ~= unitAllyTeam then
spSetUnitLosMask(unitID, allyID, {los=true, radar=true, prevLos=true, contRadar=true } )
end
end
spSetUnitHealth(unitID, {
health = 0.01,
build = 0
})
end
local function AddFallbackCommand(teamID, commandTag, terraunits, terraunitList, commandX, commandZ)
fallbackCommands[teamID] = fallbackCommands[teamID] or {}
fallbackCommands[teamID][commandTag] = {
terraunits = terraunits,
terraunitList = terraunitList,
commandX = commandX,
commandZ = commandZ,
}
end
local function GetUnitAveragePosition(unit, units)
if not unit then
return
end
local unitsX = 0
local unitsZ = 0
local i = 1
while i <= units do
if (spValidUnitID(unit[i])) then
local x,_,z = spGetUnitPosition(unit[i])
unitsX = unitsX + x
unitsZ = unitsZ + z
i = i + 1
else
unit[i] = unit[units]
unit[units] = nil
units = units - 1
end
end
if units == 0 then
return
end
return unitsX/units, unitsZ/units
end
local function TerraformRamp(x1, y1, z1, x2, y2, z2, terraform_width, unit, units, team, volumeSelection, shift, commandX, commandZ, commandTag, disableForceCompletion)
--** Initial constructor processing **
local unitsX, unitsZ = GetUnitAveragePosition(unit, units)
if not unitsX then
unitsX, unitsZ = commandX, commandZ
end
--calculate equations of the 3 lines, left, right and mid
local border = {}
if abs(x1 - x2) < 0.1 then
x2 = x1 + 0.1
end
if abs(z1 - z2) < 0.1 then
z2 = z1 + 0.1
end
local dis = distance(x1,z1,x2,z2)
if dis < minTotalRampLength-0.05 or dis > maxTotalRampLength+0.05 then
return
end
if terraform_width < minTotalRampWidth or terraform_width > maxTotalRampWidth*2 then
return
end
local xdis = abs(x1-x2)
local heightDiff = y2-y1
if heightDiff/dis > maxRampGradient then
heightDiff = maxRampGradient*dis
elseif heightDiff/dis < -maxRampGradient then
heightDiff = -maxRampGradient*dis
end
-- Due to previous checks, m is not 0 or infinity.
local m = (z1-z2)/(x1-x2)
local segmentsAlong = ceil(dis/maxRampLegth)
local segmentsAcross = ceil(terraform_width/maxRampWidth)
local segLength = dis/segmentsAlong
local segWidth = terraform_width/segmentsAcross
local widthScale = terraform_width/dis
local lengthScale = segLength/dis
local add = {x = (x2-x1)*lengthScale, z = (z2-z1)*lengthScale}
local addPerp = {x = (z1-z2)*segWidth/dis, z = -(x1-x2)*segWidth/dis}
local mid = {x = (x1-x2)*widthScale/2, z = (z1-z2)*widthScale/2}
local leftRot = {x = mid.z+x1, z = -mid.x+z1}
local rightRot = {x = -mid.z+x1, z = mid.x+z1}
--Spring.MarkerAddPoint(leftRot.x,0,leftRot.z,"L")
--Spring.MarkerAddPoint(rightRot.x,0,rightRot.z,"R")
--Spring.MarkerAddPoint(rightRot.x+add.x,0,rightRot.z+add.z,"R + A")
--Spring.MarkerAddPoint(rightRot.x+addPerp.x,0,rightRot.z+addPerp.z,"R + AP")
local topleftGrad
local botleftGrad
local toppoint
local botpoint
local leftpoint
local rightpoint
--** Store the 4 points of each segment diamond, changes with quadrant **
if x1 < x2 then
if z1 < z2 then
-- bottom right
topleftGrad = -1/m
botleftGrad = m
toppoint = rightRot
leftpoint = {x = rightRot.x+addPerp.x, z = rightRot.z+addPerp.z}
rightpoint = {x = toppoint.x+add.x, z = toppoint.z+add.z}
botpoint = {x = leftpoint.x+add.x, z = leftpoint.z+add.z}
border = {left = leftRot.x, right = rightRot.x-x1+x2, top = rightRot.z, bottom = leftRot.z-z1+z2}
else
-- top right
topleftGrad = m
botleftGrad = -1/m
leftpoint = rightRot
botpoint = {x = rightRot.x+addPerp.x, z = rightRot.z+addPerp.z}
rightpoint = {x = botpoint.x+add.x, z = botpoint.z+add.z}
toppoint = {x = rightRot.x+add.x, z = rightRot.z+add.z}
border = {left = rightRot.x, right = leftRot.x-x1+x2, top = rightRot.z-z1+z2, bottom = leftRot.z}
end
else
if z1 < z2 then
-- bottom left
topleftGrad = m
botleftGrad = -1/m
rightpoint = rightRot
toppoint = {x = rightRot.x+addPerp.x, z = rightRot.z+addPerp.z}
botpoint = {x = rightRot.x+add.x, z = rightRot.z+add.z}
leftpoint = {x = toppoint.x+add.x, z = toppoint.z+add.z}
border = {left = leftRot.x-x1+x2, right = rightRot.x, top = rightRot.z-z1+z2, bottom = leftRot.z}
else
-- top left
topleftGrad = -1/m
botleftGrad = m
botpoint = rightRot
rightpoint = {x = rightRot.x+addPerp.x, z = rightRot.z+addPerp.z}
toppoint = {x = rightpoint.x+add.x, z = rightpoint.z+add.z}
leftpoint = {x = rightRot.x+add.x, z = rightRot.z+add.z}
border = {left = rightRot.x-x1+x2, right = leftRot.x, top = leftRot.z-z1+z2, bottom = rightRot.z}
end
end
-- check it's all working
--[[
Spring.MarkerAddPoint( border.left,0,border.top,"topleft")
Spring.MarkerAddPoint( border.right,0,border.bottom,"botright")
Spring.MarkerAddPoint( x1,y1,z1, "start")
Spring.MarkerAddPoint( x2,y2,z2, "end")
Spring.MarkerAddPoint( leftpoint.x,y1,leftpoint.z, "leftP")
Spring.MarkerAddPoint( toppoint.x,y1,toppoint.z, "topP")
Spring.MarkerAddPoint( botpoint.x,y1,botpoint.z, "botP")
Spring.MarkerAddPoint( leftpoint.x,y1,toppoint.z, "topleft")
Spring.MarkerAddPoint( rightpoint.x,y1,botpoint.z, "botright")
Spring.MarkerAddLine(toppoint.x,y1,toppoint.z,leftpoint.x,y1,leftpoint.z)
Spring.MarkerAddLine(botpoint.x,y1,botpoint.z,leftpoint.x,y1,leftpoint.z)
Spring.MarkerAddLine(toppoint.x,y1,toppoint.z,rightpoint.x,y1,rightpoint.z)
Spring.MarkerAddLine(botpoint.x,y1,botpoint.z,rightpoint.x,y1,rightpoint.z)
Spring.MarkerAddLine(leftpoint.x,y1,toppoint.z,rightpoint.x,y1,toppoint.z)
Spring.MarkerAddLine(rightpoint.x,y1,toppoint.z,rightpoint.x,y1,botpoint.z)
Spring.MarkerAddLine(leftpoint.x,y1,toppoint.z,leftpoint.x,y1,botpoint.z)
Spring.MarkerAddLine(leftpoint.x,y1,botpoint.z,rightpoint.x,y1,botpoint.z)
--]]
--** Split the ramp into segments and calculate the points within each one**
local otherTerraformUnitCount = terraformUnitCount
local segment = {}
local n = 1
local i = 0
while i < segmentsAlong do
local j = 0
while j < segmentsAcross do
local middleSegment = (i > 0) and (j > 0) and (i < segmentsAlong - 1) and (j < segmentsAcross - 1)
local offset = (middleSegment and 8) or 0
segment[n] = {}
segment[n].along = i
segment[n].point = {}
segment[n].area = {}
segment[n].border = {
left = floor((leftpoint.x+add.x*i+addPerp.x*j)/8)*8 - offset,
right = ceil((rightpoint.x+add.x*i+addPerp.x*j)/8)*8 + offset,
top = floor((toppoint.z+add.z*i+addPerp.z*j)/8)*8 - offset,
bottom = ceil((botpoint.z+add.z*i+addPerp.z*j)/8)*8 + offset
}
-- end of segment
--segment[n].position = {x = (rightRot.x-4+add.x*i+addPerp.x*(j+0.5)-16*(x2-x1)/dis), z = (rightRot.z-4+add.z*i+addPerp.z*(j+0.5)-16*(z2-z1)/dis)}
-- middle of segment
segment[n].position = {x = rightRot.x+add.x*(i+0.5)+addPerp.x*(j+0.5), z = rightRot.z+add.z*(i+0.5)+addPerp.z*(j+0.5)}
local pc = 1
local topline1 = {x = leftpoint.x+add.x*i+addPerp.x*j - offset, z = leftpoint.z+add.z*i+addPerp.z*j - offset, m = topleftGrad}
local topline2 = {x = toppoint.x+add.x*i+addPerp.x*j + offset, z = toppoint.z+add.z*i+addPerp.z*j - offset, m = botleftGrad}
local botline1 = {x = leftpoint.x+add.x*i+addPerp.x*j - offset, z = leftpoint.z+add.z*i+addPerp.z*j + offset, m = botleftGrad}
local botline2 = {x = botpoint.x+add.x*i+addPerp.x*j + offset, z = botpoint.z+add.z*i+addPerp.z*j + offset, m = topleftGrad}
local topline = topline1
local botline = botline1
local lx = segment[n].border.left - offset
while lx <= segment[n].border.right + offset do
segment[n].area[lx] = {}
local zmin = linearEquation(lx,topline.m,topline.x,topline.z)
local zmax = linearEquation(lx,botline.m,botline.x,botline.z)
local lz = segment[n].border.top
while lz <= zmax do
if zmin <= lz then
local h = pointHeight(x1, y1, z1, lx, lz, m, heightDiff, xdis)
local orHeight = spGetGroundHeight(lx,lz)
if checkPointCreation(4, volumeSelection, orHeight, h, 0, lx, lz) then
segment[n].point[pc] = {x = lx, y = h ,z = lz, orHeight = orHeight, prevHeight = spGetGroundHeight(lx,lz)}
pc = pc + 1
end
end
lz = lz+8
end
lx = lx+8
if topline == topline1 and topline2.x < lx then
topline = topline2
end
if botline == botline1 and botline2.x < lx then
botline = botline2
end
end
if pc ~= 1 then
segment[n].points = pc - 1
n = n + 1
end
j = j+1
end
i = i+1
end
--** Detect potentially overlapping buildings**
local localStructure = {}
local localStructureCount = 0
for i = 1, structureCount do
local s = structure[structureTable[i] ]
if (border.left < s.maxx and
border.right > s.minx and
border.top < s.maxz and
border.bottom > s.minz) then
localStructureCount = localStructureCount + 1
localStructure[localStructureCount] = i
end
end
--** Creates terraform building and assigns each one segment data **
local block = {}
local blocks = 0
terraformOrders = terraformOrders + 1
terraformOrder[terraformOrders] = {border = border, index = {}, indexes = 0}
local rampLevels = {count = 0, data = {[0] = {along = false}}}
local frame = spGetGameFrame()
for i = 1,n-1 do
-- detect overlapping buildings
segment[i].structure = {}
segment[i].structureCount = 0
segment[i].structureArea = {}
for j = 1, localStructureCount do
local s = structure[structureTable[localStructure[j]]]
if (segment[i].border.left < s.maxx and
segment[i].border.right > s.minx and
segment[i].border.top < s.maxz and
segment[i].border.bottom > s.minz) then
segment[i].structureCount = segment[i].structureCount + 1
segment[i].structure[segment[i].structureCount] = {id = s}
s.checkAtDeath = true
for lx = s.minx, s.maxx, 8 do
if not segment[i].structureArea[lx] then
segment[i].structureArea[lx] = {}
end
for lz = s.minz,s.maxz, 8 do
segment[i].structureArea[lx][lz] = true
end
end
end
end
-- calculate cost
local totalCost = 0
local areaCost = 0
local perimeterCost = 0
for j = 1, segment[i].points do
if not segment[i].area[segment[i].point[j].x] then
segment[i].area[segment[i].point[j].x] = {}
end
local currHeight = segment[i].point[j].orHeight
segment[i].point[j].aimHeight = segment[i].point[j].y
if segment[i].structureArea[segment[i].point[j].x] and segment[i].structureArea[segment[i].point[j].x][segment[i].point[j].z] then
segment[i].point[j].diffHeight = 0.0001
segment[i].point[j].structure = true
--segment[i].area[segment[i].point[j].x][segment[i].point[j].z] = {orHeight = segment[i].point[j].orHeight,diffHeight = segment[i].point[j].diffHeight, building = true}
else
segment[i].point[j].diffHeight = segment[i].point[j].aimHeight-currHeight
segment[i].area[segment[i].point[j].x][segment[i].point[j].z] = {orHeight = segment[i].point[j].orHeight,diffHeight = segment[i].point[j].diffHeight, building = false}
end
totalCost = totalCost + abs(segment[i].point[j].diffHeight)
areaCost = areaCost + (pointExtraAreaCostDepth > abs(segment[i].point[j].diffHeight) and abs(segment[i].point[j].diffHeight) or pointExtraAreaCostDepth)
end
-- Perimeter Cost
local pyramidCostEstimate = 0
for j = 1, segment[i].points do
local x = segment[i].point[j].x
local z = segment[i].point[j].z
if segment[i].area[x] and segment[i].area[x][z] then
local edgeCount = 0
if (not segment[i].area[x+8]) or (not segment[i].area[x+8][z]) then
edgeCount = edgeCount + 1
end
if (not segment[i].area[x-8]) or (not segment[i].area[x-8][z]) then
edgeCount = edgeCount + 1
end
if (not segment[i].area[x][z+8]) then
edgeCount = edgeCount + 1
end
if (not segment[i].area[x][z-8]) then
edgeCount = edgeCount + 1
end
if perimeterEdgeCost[edgeCount] > 0 then
perimeterCost = perimeterCost + perimeterEdgeCost[edgeCount]*(pointExtraPerimeterCostDepth > abs(segment[i].point[j].diffHeight) and abs(segment[i].point[j].diffHeight) or pointExtraPerimeterCostDepth)
end
if edgeCount > 0 then
local height = abs(segment[i].point[j].diffHeight)
if height > 30 then
pyramidCostEstimate = pyramidCostEstimate + ((height - height%maxHeightDifference)*(floor(height/maxHeightDifference)-1)*0.5 + floor(height/maxHeightDifference)*(height%maxHeightDifference))*volumeCost
end
end
end
end
if totalCost ~= 0 then
local baseCost = areaCost*pointExtraAreaCost + perimeterCost*pointExtraPerimeterCost + baseTerraunitCost
totalCost = totalCost*volumeCost + baseCost
--Spring.Echo(totalCost .. "\t" .. baseCost)
local pos = segment[i].position
local vx, vz = unitsX - segment[i].position.x, unitsZ - segment[i].position.z
local scale = terraUnitLeash/sqrt(vx^2 + vz^2)
local terraunitX, terraunitZ = segment[i].position.x + scale*vx, segment[i].position.z + scale*vz
local teamY = CallAsTeam(team, function () return spGetGroundHeight(segment[i].position.x,segment[i].position.z) end)
local id = spCreateUnit(terraunitDefID, terraunitX, teamY or 0, terraunitZ, 0, team, true)
spSetUnitHealth(id, 0.01)
if id then
if segment[i].along ~= rampLevels.data[rampLevels.count].along then
rampLevels.count = rampLevels.count + 1
rampLevels.data[rampLevels.count] = {along = segment[i].along, count = 0, data = {}}
end
rampLevels.data[rampLevels.count].count = rampLevels.data[rampLevels.count].count + 1
rampLevels.data[rampLevels.count].data[rampLevels.data[rampLevels.count].count] = id
terraunitX, terraunitZ = getPointInsideMap(terraunitX,terraunitZ)
setupTerraunit(id, team, terraunitX, false, terraunitZ)
spSetUnitRulesParam(id, "terraformType", 4) --ramp
blocks = blocks + 1
block[blocks] = id
terraformUnitCount = terraformUnitCount + 1
terraformOrder[terraformOrders].indexes = terraformOrder[terraformOrders].indexes + 1
terraformUnit[id] = {
positionAnchor = segment[i].position,
position = {x = terraunitX, z = terraunitZ},
progress = 0,
lastUpdate = 0,
totalSpent = 0,
baseCostSpent = 0,
cost = totalCost,
baseCost = baseCost,
totalCost = totalCost,
pyramidCostEstimate = pyramidCostEstimate,
point = segment[i].point,
points = segment[i].points,
area = segment[i].area,
border = segment[i].border,
smooth = false,
intercepts = 0,
intercept = {},
interceptMap = {},
decayTime = frame + terraformDecayFrames,
allyTeam = unitAllyTeam,
team = team,
order = terraformOrders,
orderIndex = terraformOrder[terraformOrders].indexes,
fullyInitialised = false,
lastProgress = 0,
lastHealth = 0,
disableForceCompletion = disableForceCompletion,
}
terraformUnitTable[terraformUnitCount] = id
terraformOrder[terraformOrders].index[terraformOrder[terraformOrders].indexes] = terraformUnitCount
SetTooltip(id, 0, pyramidCostEstimate + totalCost)
end
end
end
--** Give repair order for each block to all selected units **
if rampLevels.count == 0 then
return
end
local orderList = {data = {}, count = 0}
local zig = 0
if linearEquation(unitsX,m,x1,z1) < unitsZ then
zig = 1
end
for i = 1, rampLevels.count do
for j = 1 + rampLevels.data[i].count*zig, (rampLevels.data[i].count-1)*(1-zig) + 1, 1-zig*2 do
orderList.count = orderList.count + 1
orderList.data[orderList.count] = rampLevels.data[i].data[j]
end
zig = 1-zig
end
if orderList.count == 0 then
return
end
AddFallbackCommand(team, commandTag, orderList.count, orderList.data, commandX, commandZ)
end
local function TerraformWall(terraform_type, mPoint, mPoints, terraformHeight, unit, units, team, volumeSelection, shift, commandX, commandZ, commandTag, disableForceCompletion)
local border = {left = mapWidth, right = 0, top = mapHeight, bottom = 0}
--** Initial constructor processing **
local unitsX, unitsZ = GetUnitAveragePosition(unit, units)
if not unitsX then
unitsX, unitsZ = commandX, commandZ
end
--** Convert Mouse Points to a Closed Loop on a Grid **
-- points interpolated from mouse points
local point = {}
local points = 1
mPoint[1].x = floor((mPoint[1].x+8)/16)*16
mPoint[1].z = floor((mPoint[1].z+8)/16)*16
point[1] = mPoint[1]
updateBorderWithPoint(border, point[points].x, point[points].z)
for i = 2, mPoints, 1 do
mPoint[i].x = floor((mPoint[i].x+8)/16)*16
mPoint[i].z = floor((mPoint[i].z+8)/16)*16
local diffX = mPoint[i].x - mPoint[i-1].x
local diffZ = mPoint[i].z - mPoint[i-1].z
local a_diffX = abs(diffX)
local a_diffZ = abs(diffZ)
if a_diffX <= 16 and a_diffZ <= 16 then
points = points + 1
point[points] = {x = mPoint[i].x, z = mPoint[i].z}
updateBorderWithPoint(border, point[points].x, point[points].z)
else
-- interpolate between far apart points to prevent wall holes.
if a_diffX > a_diffZ then
local m = diffZ/diffX
local sign = diffX/a_diffX
for j = 0, a_diffX, 16 do
points = points + 1
point[points] = {x = mPoint[i-1].x + j*sign, z = floor((mPoint[i-1].z + j*m*sign)/16)*16}
updateBorderWithPoint(border, point[points].x, point[points].z)
end
else
local m = diffX/diffZ
local sign = diffZ/a_diffZ
for j = 0, a_diffZ, 16 do
points = points + 1
point[points] = {x = floor((mPoint[i-1].x + j*m*sign)/16)*16, z = mPoint[i-1].z + j*sign}
updateBorderWithPoint(border, point[points].x, point[points].z)
end
end
end
end
border.left = border.left - 16
border.top = border.top - 16
border.right = border.right + 16
border.bottom = border.bottom + 16
if points > maxWallPoints then
-- cancel command if the wall is too big, anti-slowdown
return false
end
--** Split the mouse points into segments **
-- area checks for overlap
local area = {}
for i = border.left,border.right,8 do
area[i] = {}
end
local segment = {}
local n = 1
local count = 0
local continue = true
while continue do
if count*wallSegmentLength+1 <= points then
segment[n] = {}
segment[n].point = {}
segment[n].area = {}
segment[n].border = {left = mapWidth, right = 0, top = mapHeight, bottom = 0}
segment[n].position = {x = point[count*wallSegmentLength+1].x, z = point[count*wallSegmentLength+1].z}
local averagePosition = {x = 0, z = 0, n = 0}
local pc = 1
for j = count*wallSegmentLength+1, (count+1)*wallSegmentLength do
if j > points then
continue = false
break
else
averagePosition.x = averagePosition.x + point[j].x
averagePosition.z = averagePosition.z + point[j].z
averagePosition.n = averagePosition.n + 1
for lx = -16,16,8 do
for lz = -16,16,8 do
-- lx/lz steps through the points around the mousePoint
if not area[point[j].x+lx][point[j].z+lz] then
-- check if the point will be terraformed be a previous block
segment[n].point[pc] = {x = point[j].x+lx, z = point[j].z+lz}
area[point[j].x+lx][point[j].z+lz] = true
-- update border
updateBorderWithPoint(segment[n].border, segment[n].point[pc].x, segment[n].point[pc].z)
--[[if segment[n].point[pc].x-16 < .left then
segment[n].border.left = segment[n].point[pc].x-16
end
if segment[n].point[pc].x+16 > segment[n].border.right then
segment[n].border.right = segment[n].point[pc].x+16
end
if segment[n].point[pc].z-16 < segment[n].border.top then
segment[n].border.top = segment[n].point[pc].z-16
end
if segment[n].point[pc].z+16 > segment[n].border.bottom then
segment[n].border.bottom = segment[n].point[pc].z+16
end--]]
local currHeight = spGetGroundHeight(segment[n].point[pc].x, segment[n].point[pc].z)
segment[n].point[pc].orHeight = currHeight
segment[n].point[pc].prevHeight = currHeight
if checkPointCreation(terraform_type, volumeSelection, currHeight, terraformHeight,
spGetGroundOrigHeight(segment[n].point[pc].x, segment[n].point[pc].z),segment[n].point[pc].x, segment[n].point[pc].z) then
pc = pc + 1
end
end
end
end
end
end
-- discard segments with no new terraforming
if pc ~= 1 then
segment[n].position = {x = averagePosition.x/averagePosition.n, z = averagePosition.z/averagePosition.n}
segment[n].points = pc - 1
n = n + 1
end
count = count + 1
else
continue = false
end
end
--** Detect potentially overlapping buildings**
local localStructure = {}
local localStructureCount = 0
for i = 1, structureCount do
local s = structure[structureTable[i]]
if (border.left < s.maxx and
border.right > s.minx and
border.top < s.maxz and
border.bottom > s.minz) then
localStructureCount = localStructureCount + 1
localStructure[localStructureCount] = i
end
end
--** Creates terraform building and assigns each one segment data **
local block = {}
local blocks = 0
terraformOrders = terraformOrders + 1
terraformOrder[terraformOrders] = {border = border, index = {}, indexes = 0}
local otherTerraformUnitCount = terraformUnitCount
local frame = spGetGameFrame()
for i = 1,n-1 do
-- detect overlapping buildings
segment[i].structure = {}
segment[i].structureCount = 0
segment[i].structureArea = {}
for j = 1, localStructureCount do
local s = structure[structureTable[localStructure[j]]]
if (segment[i].border.left < s.maxx and
segment[i].border.right > s.minx and
segment[i].border.top < s.maxz and
segment[i].border.bottom > s.minz) then
segment[i].structureCount = segment[i].structureCount + 1
segment[i].structure[segment[i].structureCount] = {id = s}
s.checkAtDeath = true
for lx = s.minx, s.maxx, 8 do
if not segment[i].structureArea[lx] then
segment[i].structureArea[lx] = {}
end
for lz = s.minz,s.maxz, 8 do
segment[i].structureArea[lx][lz] = true
end
end
end
end
-- calculate cost
local totalCost = 0
local areaCost = 0
local perimeterCost = 0
if terraform_type == 1 then
for j = 1, segment[i].points do
if not segment[i].area[segment[i].point[j].x] then
segment[i].area[segment[i].point[j].x] = {}
end
currHeight = segment[i].point[j].orHeight
segment[i].point[j].aimHeight = terraformHeight
if segment[i].structureArea[segment[i].point[j].x] and segment[i].structureArea[segment[i].point[j].x][segment[i].point[j].z] then
segment[i].point[j].diffHeight = 0.0001
segment[i].point[j].structure = true
--segment[i].area[segment[i].point[j].x][segment[i].point[j].z] = {orHeight = segment[i].point[j].orHeight,diffHeight = segment[i].point[j].diffHeight, building = true}
else
segment[i].point[j].diffHeight = segment[i].point[j].aimHeight-currHeight
segment[i].area[segment[i].point[j].x][segment[i].point[j].z] = {orHeight = segment[i].point[j].orHeight,diffHeight = segment[i].point[j].diffHeight, building = false}
end
totalCost = totalCost + abs(segment[i].point[j].diffHeight)
areaCost = areaCost + (pointExtraAreaCostDepth > abs(segment[i].point[j].diffHeight) and abs(segment[i].point[j].diffHeight) or pointExtraAreaCostDepth)
if not segment[i].area[segment[i].point[j].x] then
segment[i].area[segment[i].point[j].x] = {}
end
end
elseif terraform_type == 2 then
for j = 1, segment[i].points do
if not segment[i].area[segment[i].point[j].x] then
segment[i].area[segment[i].point[j].x] = {}
end
currHeight = segment[i].point[j].orHeight
segment[i].point[j].aimHeight = terraformHeight+currHeight
if segment[i].structureArea[segment[i].point[j].x] and segment[i].structureArea[segment[i].point[j].x][segment[i].point[j].z] then
segment[i].point[j].diffHeight = 0.0001
segment[i].point[j].structure = true
--segment[i].area[segment[i].point[j].x][segment[i].point[j].z] = {orHeight = segment[i].point[j].orHeight,diffHeight = segment[i].point[j].diffHeight, building = true}
else
segment[i].point[j].diffHeight = terraformHeight
segment[i].area[segment[i].point[j].x][segment[i].point[j].z] = {orHeight = segment[i].point[j].orHeight,diffHeight = segment[i].point[j].diffHeight, building = false}
end
totalCost = totalCost + abs(terraformHeight)
areaCost = areaCost + (pointExtraAreaCostDepth > abs(segment[i].point[j].diffHeight) and abs(segment[i].point[j].diffHeight) or pointExtraAreaCostDepth)
if not segment[i].area[segment[i].point[j].x] then
segment[i].area[segment[i].point[j].x] = {}
end
end
elseif terraform_type == 3 then
for j = 1, segment[i].points do
local totalHeight = 0
for lx = -16, 16,8 do
for lz = -16, 16,8 do
totalHeight = totalHeight + spGetGroundHeight(segment[i].point[j].x+lx, segment[i].point[j].z+lz)
end
end
if not segment[i].area[segment[i].point[j].x] then
segment[i].area[segment[i].point[j].x] = {}
end
currHeight = segment[i].point[j].orHeight
segment[i].point[j].aimHeight = totalHeight/25
if segment[i].structureArea[segment[i].point[j].x] and segment[i].structureArea[segment[i].point[j].x][segment[i].point[j].z] then
segment[i].point[j].diffHeight = 0.0001
segment[i].point[j].structure = true
--segment[i].area[segment[i].point[j].x][segment[i].point[j].z] = {orHeight = segment[i].point[j].orHeight,diffHeight = segment[i].point[j].diffHeight, building = true}
else
segment[i].point[j].diffHeight = segment[i].point[j].aimHeight-currHeight
segment[i].area[segment[i].point[j].x][segment[i].point[j].z] = {orHeight = segment[i].point[j].orHeight,diffHeight = segment[i].point[j].diffHeight, building = false}
end
totalCost = totalCost + abs(segment[i].point[j].diffHeight)
areaCost = areaCost + (pointExtraAreaCostDepth > abs(segment[i].point[j].diffHeight) and abs(segment[i].point[j].diffHeight) or pointExtraAreaCostDepth)
if not segment[i].area[segment[i].point[j].x] then
segment[i].area[segment[i].point[j].x] = {}
end
end
elseif terraform_type == 5 then
for j = 1, segment[i].points do
if not segment[i].area[segment[i].point[j].x] then
segment[i].area[segment[i].point[j].x] = {}
end
currHeight = segment[i].point[j].orHeight
segment[i].point[j].aimHeight = spGetGroundOrigHeight(segment[i].point[j].x, segment[i].point[j].z)
if segment[i].structureArea[segment[i].point[j].x] and segment[i].structureArea[segment[i].point[j].x][segment[i].point[j].z] then
segment[i].point[j].diffHeight = 0.0001
segment[i].point[j].structure = true
--segment[i].area[segment[i].point[j].x][segment[i].point[j].z] = {orHeight = segment[i].point[j].orHeight,diffHeight = segment[i].point[j].diffHeight, building = true}
else
segment[i].point[j].diffHeight = segment[i].point[j].aimHeight-currHeight
segment[i].area[segment[i].point[j].x][segment[i].point[j].z] = {orHeight = segment[i].point[j].orHeight,diffHeight = segment[i].point[j].diffHeight, building = false}
end
totalCost = totalCost + abs(segment[i].point[j].diffHeight)
areaCost = areaCost + (pointExtraAreaCostDepth > abs(segment[i].point[j].diffHeight) and abs(segment[i].point[j].diffHeight) or pointExtraAreaCostDepth)
end
elseif terraform_type == 6 then
for j = 1, segment[i].points do
if not segment[i].area[segment[i].point[j].x] then
segment[i].area[segment[i].point[j].x] = {}
end
currHeight = segment[i].point[j].orHeight
segment[i].point[j].aimHeight = currHeight + bumpyFunc(segment[i].point[j].x,segment[i].point[j].z,volumeSelection)
if segment[i].structureArea[segment[i].point[j].x] and segment[i].structureArea[segment[i].point[j].x][segment[i].point[j].z] then
segment[i].point[j].diffHeight = 0.0001
segment[i].point[j].structure = true
--segment[i].area[segment[i].point[j].x][segment[i].point[j].z] = {orHeight = segment[i].point[j].orHeight,diffHeight = segment[i].point[j].diffHeight, building = true}
else
segment[i].point[j].diffHeight = segment[i].point[j].aimHeight-currHeight
segment[i].area[segment[i].point[j].x][segment[i].point[j].z] = {orHeight = segment[i].point[j].orHeight,diffHeight = segment[i].point[j].diffHeight, building = false}
end
totalCost = totalCost + abs(segment[i].point[j].diffHeight)
areaCost = areaCost + (pointExtraAreaCostDepth > abs(segment[i].point[j].diffHeight) and abs(segment[i].point[j].diffHeight) or pointExtraAreaCostDepth)
end
end
-- Perimeter Cost
local pyramidCostEstimate = 0
for j = 1, segment[i].points do
local x = segment[i].point[j].x
local z = segment[i].point[j].z
if segment[i].area[x] and segment[i].area[x][z] then
local edgeCount = 0
if (not segment[i].area[x+8]) or (not segment[i].area[x+8][z]) then
edgeCount = edgeCount + 1
end
if (not segment[i].area[x-8]) or (not segment[i].area[x-8][z]) then
edgeCount = edgeCount + 1
end
if (not segment[i].area[x][z+8]) then
edgeCount = edgeCount + 1
end
if (not segment[i].area[x][z-8]) then
edgeCount = edgeCount + 1
end
if perimeterEdgeCost[edgeCount] > 0 then
perimeterCost = perimeterCost + perimeterEdgeCost[edgeCount]*(pointExtraPerimeterCostDepth > abs(segment[i].point[j].diffHeight) and abs(segment[i].point[j].diffHeight) or pointExtraPerimeterCostDepth)
end
if edgeCount > 0 then
local height = abs(segment[i].point[j].diffHeight)
if height > 30 then
pyramidCostEstimate = pyramidCostEstimate + ((height - height%maxHeightDifference)*(floor(height/maxHeightDifference)-1)*0.5 + floor(height/maxHeightDifference)*(height%maxHeightDifference))*volumeCost
end
end
end
end
if totalCost ~= 0 then
local baseCost = areaCost*pointExtraAreaCost + perimeterCost*pointExtraPerimeterCost + baseTerraunitCost
totalCost = totalCost*volumeCost + baseCost
--Spring.Echo(totalCost .. "\t" .. baseCost)
local pos = segment[i].position
local vx, vz = unitsX - segment[i].position.x, unitsZ - segment[i].position.z
local scale = terraUnitLeash/sqrt(vx^2 + vz^2)
local terraunitX, terraunitZ = segment[i].position.x + scale*vx, segment[i].position.z + scale*vz
local teamY = CallAsTeam(team, function () return spGetGroundHeight(segment[i].position.x,segment[i].position.z) end)
local id = spCreateUnit(terraunitDefID, terraunitX, teamY or 0, terraunitZ, 0, team, true)
spSetUnitHealth(id, 0.01)
if id then
terraunitX, terraunitZ = getPointInsideMap(terraunitX,terraunitZ)
setupTerraunit(id, team, terraunitX, false, terraunitZ)
spSetUnitRulesParam(id, "terraformType", terraform_type)
blocks = blocks + 1
block[blocks] = id
terraformUnitCount = terraformUnitCount + 1
terraformOrder[terraformOrders].indexes = terraformOrder[terraformOrders].indexes + 1
terraformUnit[id] = {
positionAnchor = segment[i].position,
position = {x = terraunitX, z = terraunitZ},
progress = 0,
lastUpdate = 0,
totalSpent = 0,
baseCostSpent = 0,
cost = totalCost,
baseCost = baseCost,
totalCost = totalCost,
pyramidCostEstimate = pyramidCostEstimate,
point = segment[i].point,
points = segment[i].points,
area = segment[i].area,
border = segment[i].border,
smooth = false,
intercepts = 0,
intercept = {},
interceptMap = {},
decayTime = frame + terraformDecayFrames,
allyTeam = unitAllyTeam,
team = team,
order = terraformOrders,
orderIndex = terraformOrder[terraformOrders].indexes,
fullyInitialised = false,
lastProgress = 0,
lastHealth = 0,
disableForceCompletion = disableForceCompletion,
}
terraformUnitTable[terraformUnitCount] = id
terraformOrder[terraformOrders].index[terraformOrder[terraformOrders].indexes] = terraformUnitCount
SetTooltip(id, 0, pyramidCostEstimate + totalCost)
end
end
end
AddFallbackCommand(team, commandTag, blocks, block, commandX, commandZ)
end
local function TerraformArea(terraform_type, mPoint, mPoints, terraformHeight, unit, units, team, volumeSelection, shift, commandX, commandZ, commandTag, disableForceCompletion)
local border = {left = mapWidth, right = 0, top = mapHeight, bottom = 0} -- border for the entire area
--** Initial constructor processing **
local unitsX, unitsZ = GetUnitAveragePosition(unit, units)
if not unitsX then
unitsX, unitsZ = commandX, commandZ
end
--** Convert Mouse Points to a Closed Loop on a Grid **
-- close the mouse points loop
mPoints = mPoints + 1
mPoint[mPoints] = mPoint[1]
-- points interpolated from mouse points
local point = {}
local points = 1
-- snap mouse to grid
mPoint[1].x = floor(mPoint[1].x/16)*16
mPoint[1].z = floor(mPoint[1].z/16)*16
point[1] = mPoint[1]
updateBorderWithPoint(border, point[points].x, point[points].z)
for i = 2, mPoints, 1 do
-- snap mouse to grid
mPoint[i].x = floor(mPoint[i].x/16)*16
mPoint[i].z = floor(mPoint[i].z/16)*16
local diffX = mPoint[i].x - mPoint[i-1].x
local diffZ = mPoint[i].z - mPoint[i-1].z
local a_diffX = abs(diffX)
local a_diffZ = abs(diffZ)
-- do not add another points of the same coordinates
if a_diffX <= 16 and a_diffZ <= 16 then
points = points + 1
point[points] = {x = mPoint[i].x, z = mPoint[i].z}
updateBorderWithPoint(border, point[points].x, point[points].z)
else
-- interpolate between far apart points to prevent loop holes.
if a_diffX > a_diffZ then
local m = diffZ/diffX
local sign = diffX/a_diffX
for j = 0, a_diffX, 16 do
points = points + 1
point[points] = {x = mPoint[i].x - j*sign, z = floor((mPoint[i].z - j*m*sign)/16)*16}
updateBorderWithPoint(border, point[points].x, point[points].z)
end
else
local m = diffX/diffZ
local sign = diffZ/a_diffZ
for j = 0, a_diffZ, 16 do
points = points + 1
point[points] = {x = floor((mPoint[i].x - j*m*sign)/16)*16, z = mPoint[i].z - j*sign}
updateBorderWithPoint(border, point[points].x, point[points].z)
end
end
end
end
if border.right-border.left > maxAreaSize or border.bottom-border.top > maxAreaSize then
-- cancel command if the area is too big, anti-slowdown
return false
end
--** Compute which points are on the inside of the Loop **
-- Uses Floodfill, a faster algorithm is possible?
local area = {}
-- 2D array
for i = border.left-16,border.right+16,16 do
area[i] = {}
end
-- set loop edge points to 2. 2 cannot be flooded
for i = 1, points do
area[point[i].x][point[i].z] = 2
end
-- set all other array points to 1. 1 is vunerable
for i = border.left,border.right,16 do
for j = border.top,border.bottom,16 do
if area[i][j] ~= 2 then
area[i][j] = 1
end
end
end
-- set the points on the border of the array to -1. -1 is the 'flood'
for i = border.left,border.right,16 do
if area[i][border.top] ~= 2 then
area[i][border.top] = -1
end
if area[i][border.bottom] ~= 2 then
area[i][border.bottom] = -1
end
end
for i = border.top,border.bottom,16 do
if area[border.left][i] ~= 2 then
area[border.left][i] = -1
end
if area[border.right][i] ~= 2 then
area[border.right][i] = -1
end
end
-- floodfill algorithm turning 1s into -1s. -1s turn to false
local continue = true
while continue do
continue = false
for i = border.left,border.right,16 do
for j = border.top,border.bottom,16 do
if area[i][j] == -1 then
if area[i+16][j] == 1 then
area[i+16][j] = -1
continue = true
end
if area[i-16][j] == 1 then
area[i-16][j] = -1
continue = true
end
if area[i][j+16] == 1 then
area[i][j+16] = -1
continue = true
end
if area[i][j-16] == 1 then
area[i][j-16] = -1
continue = true
end
area[i][j] = false
end
end
end
end
--** Break the area into segments to be individually terraformed **
border.right = border.right + 16
border.bottom = border.bottom + 16
local width = (border.right-border.left)/ceil((border.right-border.left)/areaSegMaxSize)
local height = (border.bottom-border.top)/ceil((border.bottom-border.top)/areaSegMaxSize)
-- width and height are the witdh and height of segments. They must be squished to all be the same size
local segment = {}
local otherTerraformUnitCount = terraformUnitCount
local wCount = ceil((border.right-border.left)/areaSegMaxSize) - 1
local hCount = ceil((border.bottom-border.top)/areaSegMaxSize) - 1
-- w/hCount is the number of segments that fit into the width/height
local addX = 0
-- addX and addZ prevent overlap
local n = 1 -- segment count
for i = 0, wCount do
local addZ = 0
for j = 0, hCount do
-- i and j step through possible segments based on splitting the rectangular area into rectangles
segment[n] = {}
segment[n].grid = {x = i, z = j}
segment[n].point = {}
segment[n].area = {}
segment[n].border = {left = mapWidth, right = 0, top = mapHeight, bottom = 0}
local totalX = 0
local totalZ = 0
-- totalX/Z is used to find the average position of the segment
local m = 1 -- number of points in the segment
for lx = border.left + floor(width * i/8)*8 + addX, border.left + floor(width * (i+1)/8)*8, 16 do
for lz = border.top + floor(height * j/8)*8 + addZ, border.top + floor(height * (j+1)/8)*8, 16 do
-- lx/lz steps though all 16x16 points
if area[floor(lx/16)*16][floor(lz/16)*16] then
--Spring.MarkerAddLine(floor(lx/16)*16-2,0,floor(lz/16)*16-2, floor(lx/16)*16+2,0,floor(lz/16)*16+2)
--Spring.MarkerAddLine(floor(lx/16)*16-2,0,floor(lz/16)*16+2, floor(lx/16)*16+2,0,floor(lz/16)*16-2)
-- fill in the top, left and middle
for x = lx, lx+8, 8 do
for z = lz, lz+8, 8 do
local currHeight = spGetGroundHeight(x, z)
if checkPointCreation(terraform_type, volumeSelection, currHeight, terraformHeight,spGetGroundOrigHeight(x, z), x, z) then
segment[n].point[m] = {x = x, z = z, orHeight = currHeight, prevHeight = currHeight}
m = m + 1
totalX = totalX + x
totalZ = totalZ + z
updateBorderWithPoint(segment[n].border, x, z)
end
end
end
local right = not area[floor(lx/16)*16+16][floor(lz/16)*16]
local bottom = not area[floor(lx/16)*16][floor(lz/16)*16+16]
-- fill in bottom right if it is missing
if right and bottom then
local currHeight = spGetGroundHeight(lx+16, lz+16)
if checkPointCreation(terraform_type, volumeSelection, currHeight, terraformHeight,spGetGroundOrigHeight(lx+16, lz+16), lx+16, lz+16) then
segment[n].point[m] = {x = lx+16, z = lz+16, orHeight = currHeight, prevHeight = currHeight}
m = m + 1
totalX = totalX + lx+16
totalZ = totalZ + lz+16
updateBorderWithPoint(segment[n].border, lx+16, lz+16)
end
end
if right then
for z = lz, lz+8, 8 do
local currHeight = spGetGroundHeight(lx+16, z)
if checkPointCreation(terraform_type, volumeSelection, currHeight, terraformHeight,spGetGroundOrigHeight(lx+16, z), lx+16, z) then
segment[n].point[m] = {x = lx+16, z = z, orHeight = currHeight, prevHeight = currHeight}
m = m + 1
totalX = totalX + lx+16
totalZ = totalZ + z
updateBorderWithPoint(segment[n].border, lx+16, z)
end
end
end
if bottom then
for x = lx, lx+8, 8 do
local currHeight = spGetGroundHeight(x, lz+16)
if checkPointCreation(terraform_type, volumeSelection, currHeight, terraformHeight,spGetGroundOrigHeight(x, lz+16), x, lz+16) then
segment[n].point[m] = {x = x, z = lz+16, orHeight = currHeight, prevHeight = currHeight}
m = m + 1
totalX = totalX + x
totalZ = totalZ + lz+16
updateBorderWithPoint(segment[n].border, x, lz+16)
end
end
end
end
end
end
addZ = 8
-- if there are no points in the segment the segment is discarded
if m ~= 1 then
segment[n].points = m - 1
segment[n].position = {x = totalX/(m-1), z = totalZ/(m-1)}
n = n + 1
end
end
addX = 8
end
--** Detect potentially overlapping buildings**
local localStructure = {}
local localStructureCount = 0
for i = 1, structureCount do
local s = structure[structureTable[i]]
if (border.left < s.maxx and
border.right > s.minx and
border.top < s.maxz and
border.bottom > s.minz) then
localStructureCount = localStructureCount + 1
localStructure[localStructureCount] = i
end
end
--** Creates terraform building and assigns each one segment data **
local block = {}
local blocks = 0
terraformOrders = terraformOrders + 1
terraformOrder[terraformOrders] = {border = border, index = {}, indexes = 0}
local frame = spGetGameFrame()
local unitIdGrid = {}
local aveX = 0
local aveZ = 0
for i = 1,n-1 do
-- detect overlapping buildings
segment[i].structure = {}
segment[i].structureCount = 0
segment[i].structureArea = {}
for j = 1, localStructureCount do
local s = structure[structureTable[localStructure[j]]]
if (segment[i].border.left < s.maxx and
segment[i].border.right > s.minx and
segment[i].border.top < s.maxz and
segment[i].border.bottom > s.minz) then
segment[i].structureCount = segment[i].structureCount + 1
segment[i].structure[segment[i].structureCount] = {id = s}
s.checkAtDeath = true
for lx = s.minx, s.maxx, 8 do
if not segment[i].structureArea[lx] then
segment[i].structureArea[lx] = {}
end
for lz = s.minz,s.maxz, 8 do
segment[i].structureArea[lx][lz] = true
end
end
end
end
--calculate cost of terraform
local totalCost = 0
local areaCost = 0
local perimeterCost = 0
if terraform_type == 1 then
for j = 1, segment[i].points do
if not segment[i].area[segment[i].point[j].x] then
segment[i].area[segment[i].point[j].x] = {}
end
local currHeight = segment[i].point[j].orHeight
segment[i].point[j].aimHeight = terraformHeight
if segment[i].structureArea[segment[i].point[j].x] and segment[i].structureArea[segment[i].point[j].x][segment[i].point[j].z] then
segment[i].point[j].diffHeight = 0.0001
segment[i].point[j].structure = true
--segment[i].area[segment[i].point[j].x][segment[i].point[j].z] = {orHeight = segment[i].point[j].orHeight,diffHeight = segment[i].point[j].diffHeight, building = true}
else
segment[i].point[j].diffHeight = segment[i].point[j].aimHeight-currHeight
segment[i].area[segment[i].point[j].x][segment[i].point[j].z] = {orHeight = segment[i].point[j].orHeight,diffHeight = segment[i].point[j].diffHeight, building = false}
end
totalCost = totalCost + abs(segment[i].point[j].diffHeight)
areaCost = areaCost + (pointExtraAreaCostDepth > abs(segment[i].point[j].diffHeight) and abs(segment[i].point[j].diffHeight) or pointExtraAreaCostDepth)
end
elseif terraform_type == 2 then
for j = 1, segment[i].points do
if not segment[i].area[segment[i].point[j].x] then
segment[i].area[segment[i].point[j].x] = {}
end
local currHeight = segment[i].point[j].orHeight
segment[i].point[j].aimHeight = terraformHeight+currHeight
if segment[i].structureArea[segment[i].point[j].x] and segment[i].structureArea[segment[i].point[j].x][segment[i].point[j].z] then
segment[i].point[j].diffHeight = 0.0001
segment[i].point[j].structure = true
--segment[i].area[segment[i].point[j].x][segment[i].point[j].z] = {orHeight = segment[i].point[j].orHeight,diffHeight = segment[i].point[j].diffHeight, building = true}
else
segment[i].point[j].diffHeight = terraformHeight
segment[i].area[segment[i].point[j].x][segment[i].point[j].z] = {orHeight = segment[i].point[j].orHeight,diffHeight = segment[i].point[j].diffHeight, building = false}
end
totalCost = totalCost + abs(segment[i].point[j].diffHeight)
areaCost = areaCost + (pointExtraAreaCostDepth > abs(segment[i].point[j].diffHeight) and abs(segment[i].point[j].diffHeight) or pointExtraAreaCostDepth)
end
elseif terraform_type == 3 then
for j = 1, segment[i].points do
local totalHeight = 0
for lx = -16, 16,8 do
for lz = -16, 16,8 do
totalHeight = totalHeight + spGetGroundHeight(segment[i].point[j].x+lx, segment[i].point[j].z+lz)
end
end
if not segment[i].area[segment[i].point[j].x] then
segment[i].area[segment[i].point[j].x] = {}
end
local currHeight = segment[i].point[j].orHeight
segment[i].point[j].aimHeight = totalHeight/25
if segment[i].structureArea[segment[i].point[j].x] and segment[i].structureArea[segment[i].point[j].x][segment[i].point[j].z] then
segment[i].point[j].diffHeight = 0.0001
segment[i].point[j].structure = true
--segment[i].area[segment[i].point[j].x][segment[i].point[j].z] = {orHeight = segment[i].point[j].orHeight,diffHeight = segment[i].point[j].diffHeight, building = true}
else
segment[i].point[j].diffHeight = segment[i].point[j].aimHeight-currHeight
segment[i].area[segment[i].point[j].x][segment[i].point[j].z] = {orHeight = segment[i].point[j].orHeight,diffHeight = segment[i].point[j].diffHeight, building = false}
end
totalCost = totalCost + abs(segment[i].point[j].diffHeight)
areaCost = areaCost + (pointExtraAreaCostDepth > abs(segment[i].point[j].diffHeight) and abs(segment[i].point[j].diffHeight) or pointExtraAreaCostDepth)
end
elseif terraform_type == 5 then
for j = 1, segment[i].points do
if not segment[i].area[segment[i].point[j].x] then
segment[i].area[segment[i].point[j].x] = {}
end
local currHeight = segment[i].point[j].orHeight
segment[i].point[j].aimHeight = spGetGroundOrigHeight(segment[i].point[j].x, segment[i].point[j].z)
if segment[i].structureArea[segment[i].point[j].x] and segment[i].structureArea[segment[i].point[j].x][segment[i].point[j].z] then
segment[i].point[j].diffHeight = 0.0001
segment[i].point[j].structure = true
--segment[i].area[segment[i].point[j].x][segment[i].point[j].z] = {orHeight = segment[i].point[j].orHeight,diffHeight = segment[i].point[j].diffHeight, building = true}
else
segment[i].point[j].diffHeight = segment[i].point[j].aimHeight-currHeight
segment[i].area[segment[i].point[j].x][segment[i].point[j].z] = {orHeight = segment[i].point[j].orHeight,diffHeight = segment[i].point[j].diffHeight, building = false}
end
totalCost = totalCost + abs(segment[i].point[j].diffHeight)
areaCost = areaCost + (pointExtraAreaCostDepth > abs(segment[i].point[j].diffHeight) and abs(segment[i].point[j].diffHeight) or pointExtraAreaCostDepth)
end
elseif terraform_type == 6 then
for j = 1, segment[i].points do
if not segment[i].area[segment[i].point[j].x] then
segment[i].area[segment[i].point[j].x] = {}
end
local currHeight = segment[i].point[j].orHeight
segment[i].point[j].aimHeight = currHeight + bumpyFunc(segment[i].point[j].x,segment[i].point[j].z,volumeSelection)
if segment[i].structureArea[segment[i].point[j].x] and segment[i].structureArea[segment[i].point[j].x][segment[i].point[j].z] then
segment[i].point[j].diffHeight = 0.0001
segment[i].point[j].structure = true
--segment[i].area[segment[i].point[j].x][segment[i].point[j].z] = {orHeight = segment[i].point[j].orHeight,diffHeight = segment[i].point[j].diffHeight, building = true}
else
segment[i].point[j].diffHeight = segment[i].point[j].aimHeight-currHeight
segment[i].area[segment[i].point[j].x][segment[i].point[j].z] = {orHeight = segment[i].point[j].orHeight,diffHeight = segment[i].point[j].diffHeight, building = false}
end
totalCost = totalCost + abs(segment[i].point[j].diffHeight)
areaCost = areaCost + (pointExtraAreaCostDepth > abs(segment[i].point[j].diffHeight) and abs(segment[i].point[j].diffHeight) or pointExtraAreaCostDepth)
end
end
-- Perimeter Cost
local pyramidCostEstimate = 0 -- just for UI
for j = 1, segment[i].points do
local x = segment[i].point[j].x
local z = segment[i].point[j].z
if segment[i].area[x] and segment[i].area[x][z] then
local edgeCount = 0
if (not segment[i].area[x+8]) or (not segment[i].area[x+8][z]) then
edgeCount = edgeCount + 1
end
if (not segment[i].area[x-8]) or (not segment[i].area[x-8][z]) then
edgeCount = edgeCount + 1
end
if (not segment[i].area[x][z+8]) then
edgeCount = edgeCount + 1
end
if (not segment[i].area[x][z-8]) then
edgeCount = edgeCount + 1
end
if perimeterEdgeCost[edgeCount] > 0 then
perimeterCost = perimeterCost + perimeterEdgeCost[edgeCount]*(pointExtraPerimeterCostDepth > abs(segment[i].point[j].diffHeight) and abs(segment[i].point[j].diffHeight) or pointExtraPerimeterCostDepth)
end
if edgeCount > 0 then
local height = abs(segment[i].point[j].diffHeight)
if height > 30 then
pyramidCostEstimate = pyramidCostEstimate + ((height - height%maxHeightDifference)*(floor(height/maxHeightDifference)-1)*0.5 + floor(height/maxHeightDifference)*(height%maxHeightDifference))*volumeCost
end
end
end
end
if totalCost ~= 0 then
local baseCost = areaCost*pointExtraAreaCost + perimeterCost*pointExtraPerimeterCost + baseTerraunitCost
totalCost = totalCost*volumeCost + baseCost
--Spring.Echo("Total Cost", totalCost, "Area Cost", areaCost*pointExtraAreaCost, "Perimeter Cost", perimeterCost*pointExtraPerimeterCost)
local pos = segment[i].position
local vx, vz = unitsX - segment[i].position.x, unitsZ - segment[i].position.z
local scale = terraUnitLeash/sqrt(vx^2 + vz^2)
local terraunitX, terraunitZ = segment[i].position.x + scale*vx, segment[i].position.z + scale*vz
local teamY = CallAsTeam(team, function () return spGetGroundHeight(segment[i].position.x,segment[i].position.z) end)
local id = spCreateUnit(terraunitDefID, terraunitX, teamY or 0, terraunitZ, 0, team, true)
spSetUnitHealth(id, 0.01)
if id then
unitIdGrid[segment[i].grid.x] = unitIdGrid[segment[i].grid.x] or {}
unitIdGrid[segment[i].grid.x][segment[i].grid.z] = id
aveX = aveX + segment[i].position.x
aveZ = aveZ + segment[i].position.z
terraunitX, terraunitZ = getPointInsideMap(terraunitX,terraunitZ)
setupTerraunit(id, team, terraunitX, false, terraunitZ)
spSetUnitRulesParam(id, "terraformType", terraform_type)
blocks = blocks + 1
block[blocks] = id
terraformUnitCount = terraformUnitCount + 1
terraformOrder[terraformOrders].indexes = terraformOrder[terraformOrders].indexes + 1
terraformUnit[id] = {
positionAnchor = segment[i].position,
position = {x = terraunitX, z = terraunitZ},
progress = 0,
lastUpdate = 0,
totalSpent = 0,
baseCostSpent = 0,
cost = totalCost,
baseCost = baseCost,
totalCost = totalCost,
pyramidCostEstimate = pyramidCostEstimate,
point = segment[i].point,
points = segment[i].points,
area = segment[i].area,
border = segment[i].border,
smooth = false,
intercepts = 0,
intercept = {},
interceptMap = {},
decayTime = frame + terraformDecayFrames,
allyTeam = unitAllyTeam,
team = team,
order = terraformOrders,
orderIndex = terraformOrder[terraformOrders].indexes,
fullyInitialised = false,
lastProgress = 0,
lastHealth = 0,
disableForceCompletion = disableForceCompletion,
}
terraformUnitTable[terraformUnitCount] = id
terraformOrder[terraformOrders].index[terraformOrder[terraformOrders].indexes] = terraformUnitCount
SetTooltip(id, 0, pyramidCostEstimate + totalCost)
end
end
end
--** Give repair order for each block to all selected units **
if terraformOrder[terraformOrders].indexes == 0 then
return
end
aveX = aveX/terraformOrder[terraformOrders].indexes
aveZ = aveZ/terraformOrder[terraformOrders].indexes
local orderList = {data = {}, count = 0}
if unitsX < unitsZ - aveZ + aveX then -- left or top
if unitsX < -unitsZ + aveZ + aveX then -- left
local zig = 0
if unitsZ > aveZ then -- 4th octant
zig = 1
end
for gx = 0, wCount do
for gz = 0 + hCount*zig, hCount*(1-zig), 1-zig*2 do
if unitIdGrid[gx] and unitIdGrid[gx][gz] then
orderList.count = orderList.count + 1
orderList.data[orderList.count] = unitIdGrid[gx][gz]
end
end
zig = 1 - zig
end
else -- top
local zig = 0
if unitsX > aveX then -- 2nd octant
zig = 1
end
for gz = hCount, 0, -1 do
for gx = 0 + wCount*zig, wCount*(1-zig), 1-zig*2 do
if unitIdGrid[gx] and unitIdGrid[gx][gz] then
orderList.count = orderList.count + 1
orderList.data[orderList.count] = unitIdGrid[gx][gz]
end
end
zig = 1 - zig
end
end
else -- bottom or right
if unitsX < -unitsZ + aveZ + aveX then -- bottom
local zig = 0
if unitsX > aveX then -- 7th octant
zig = 1
end
for gz = 0, hCount do
for gx = 0 + wCount*zig, wCount*(1-zig), 1-zig*2 do
if unitIdGrid[gx] and unitIdGrid[gx][gz] then
orderList.count = orderList.count + 1
orderList.data[orderList.count] = unitIdGrid[gx][gz]
end
end
zig = 1 - zig
end
else -- right
local zig = 0
if unitsZ > aveZ then -- 1st octant
zig = 1
end
for gx = wCount, 0, -1 do
for gz = 0 + hCount*zig, hCount*(1-zig), 1-zig*2 do
if unitIdGrid[gx] and unitIdGrid[gx][gz] then
orderList.count = orderList.count + 1
orderList.data[orderList.count] = unitIdGrid[gx][gz]
end
end
zig = 1 - zig
end
end
end
if orderList.count == 0 then
return
end
AddFallbackCommand(team, commandTag, orderList.count, orderList.data, commandX, commandZ)
end
--------------------------------------------------------------------------------
-- Recieve Terraform command from UI widget
--------------------------------------------------------------------------------
function gadget:AllowCommand_GetWantedCommand()
return wantedCommands
end
function gadget:AllowCommand_GetWantedUnitDefID()
return true
end
function gadget:AllowCommand(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions)
-- Don't allow non-constructors to queue terraform fallback.
if fallbackableCommands[cmdID] and not terraformUnitDefIDs[unitDefID] then
return false
end
if (cmdID == CMD_TERRAFORM_INTERNAL) then
if GG.terraformRequiresUnlock and not GG.terraformUnlocked[teamID] then
return false
end
local terraform_type = cmdParams[1]
local teamID = cmdParams[2]
local commandX = cmdParams[3]
local commandZ = cmdParams[4]
local commandTag = cmdParams[5]
local loop = cmdParams[6]
local terraformHeight = cmdParams[7]
local pointCount = cmdParams[8]
local constructorCount = cmdParams[9]
local volumeSelection = cmdParams[10]
--level or raise or smooth or restore or bumpify
if terraform_type == 1 or terraform_type == 2 or terraform_type == 3 or terraform_type == 5 then --or terraform_type == 6 then
local point = {}
local unit = {}
local i = 11
for j = 1, pointCount do
point[j] = {x = cmdParams[i], z = cmdParams[i+1]}
i = i + 2
end
for j = 1, constructorCount do
unit[j] = cmdParams[i]
i = i + 1
end
if loop == 0 then
TerraformWall(terraform_type, point, pointCount, terraformHeight, unit, constructorCount, teamID, volumeSelection, cmdOptions.shift, commandX, commandZ, commandTag)
else
TerraformArea(terraform_type, point, pointCount, terraformHeight, unit, constructorCount, teamID, volumeSelection, cmdOptions.shift, commandX, commandZ, commandTag)
end
return false
elseif terraform_type == 4 then --ramp
local point = {}
local unit = {}
local i = 11
for j = 1, pointCount do
point[j] = {x = cmdParams[i], y = cmdParams[i+1],z = cmdParams[i+2]}
i = i + 3
end
for j = 1, constructorCount do
unit[j] = cmdParams[i]
i = i + 1
end
TerraformRamp(point[1].x,point[1].y,point[1].z,point[2].x,point[2].y,point[2].z,terraformHeight*2,unit, constructorCount,teamID, volumeSelection, cmdOptions.shift, commandX, commandZ, commandTag)
return false
end
end
return true -- allowed
end
--------------------------------------------------------------------------------
-- Sudden Death Mode
--------------------------------------------------------------------------------
function GG.Terraform_RaiseWater(raiseAmount)
for i = 1, structureCount do
local s = structure[structureTable[i]]
s.h = s.h - raiseAmount
end
for i = 1, terraformUnitCount do
local id = terraformUnitTable[i]
for j = 1, terraformUnit[id].points do
local point = terraformUnit[id].point[j]
point.orHeight = point.orHeight - raiseAmount
point.aimHeight = point.aimHeight - raiseAmount
end
end
--[[ move commands looks as though it will be messy
local allUnits = spGetAllUnits()
local allUnitsCount = #allUnits
for i = 1, allUnitsCount do
if spValidUnitID(allUnits[i]) then
local x,y,z = spGetUnitPosition(allUnits[i])
spSetUnitPosition(x,y-raiseAmount,z)
local commands = spGetCommandQueue(allUnits[i])
local commandsCount = #commands
for j = 1, commandsCount do
end
end
end
--]]
spAdjustHeightMap(0, 0, mapWidth, mapHeight, -raiseAmount)
Spring.SetGameRulesParam("waterLevelModifier", raiseAmount)
local features = Spring.GetAllFeatures()
for i = 1, #features do
local featureID = features[i]
local fx, fy, fz = Spring.GetFeaturePosition(featureID)
if featureID and fy then
Spring.SetFeaturePosition(featureID, fx, fy - raiseAmount, fz, true)
end
end
end
--------------------------------------------------------------------------------
-- Handle terraunit
--------------------------------------------------------------------------------
local function deregisterTerraformUnit(id,terraformIndex,origin)
if not terraformUnit[id] then
Spring.Log(gadget:GetInfo().name, LOG.ERROR, "Terraform:")
Spring.Log(gadget:GetInfo().name, LOG.ERROR, "Attempted to remove nil terraform ID")
Spring.Log(gadget:GetInfo().name, LOG.ERROR, "Error Tpye " .. origin)
Spring.Log(gadget:GetInfo().name, LOG.ERROR, "Tell Google Frog")
return
end
--Removed Intercept Check
--if not terraformUnit[id].intercepts then
-- Spring.Echo("Terraform:")
-- Spring.Echo("Attempted to index terraformUnit with wrong id")
-- Spring.Echo("Tell Google Frog")
-- return
--end
----Spring.MarkerAddPoint(terraformUnit[id].position.x,0,terraformUnit[id].position.z,"Spent " .. terraformUnit[id].totalSpent)
--
-- remove from intercepts tables
--for j = 1, terraformUnit[id].intercepts do -- CRASH ON THIS LINE -- not for a while though
-- local oid = terraformUnit[id].intercept[j].id
-- local oindex = terraformUnit[id].intercept[j].index
-- if oindex < terraformUnit[oid].intercepts then
-- terraformUnit[terraformUnit[oid].intercept[terraformUnit[oid].intercepts].id].intercept[terraformUnit[oid].intercept[terraformUnit[oid].intercepts].index].index = oindex
-- terraformUnit[oid].intercept[oindex] = terraformUnit[oid].intercept[terraformUnit[oid].intercepts]
-- end
-- terraformUnit[oid].intercept[terraformUnit[oid].intercepts] = nil
-- terraformUnit[oid].intercepts = terraformUnit[oid].intercepts - 1
-- terraformUnit[oid].interceptMap[id] = nil
--end
-- remove from order table
local to = terraformOrder[terraformUnit[id].order]
if terraformUnit[id].orderIndex ~= to.indexes then
to.index[terraformUnit[id].orderIndex] = to.index[to.indexes]
terraformUnit[terraformUnitTable[to.index[to.indexes]]].orderIndex = terraformUnit[id].orderIndex
end
to.indexes = to.indexes - 1
-- remove order table if it is now emty
if to.indexes < 1 then
if terraformOrders ~= terraformUnit[id].order then
terraformOrder[terraformUnit[id].order] = terraformOrder[terraformOrders]
for i = 1, terraformOrder[terraformOrders].indexes do
terraformUnit[terraformUnitTable[terraformOrder[terraformOrders].index[i]]].order = terraformUnit[id].order
end
end
terraformOrders = terraformOrders - 1
end
-- remove from terraform table
terraformUnit[id] = nil
if terraformIndex ~= terraformUnitCount then
terraformUnitTable[terraformIndex] = terraformUnitTable[terraformUnitCount]
local t = terraformUnit[terraformUnitTable[terraformUnitCount]]
terraformOrder[t.order].index[t.orderIndex] = terraformIndex
end
terraformUnitCount = terraformUnitCount - 1
end
local function updateTerraformEdgePoints(id)
for i = 1, terraformUnit[id].points do
local point = terraformUnit[id].point[i]
if point.structure then
point.edges = nil
else
local x = point.x
local z = point.z
local area = terraformUnit[id].area
local edges = 0
local edge = {}
local spots = {top = false, bot = false, left = false, right = false}
if (not area[x-8]) or (not area[x-8][z]) then
spots.left = true
end
if (not area[x+8]) or (not area[x+8][z]) then
spots.right = true
end
if not area[x][z-8] then
spots.top = true
end
if not area[x][z+8] then
spots.bot = true
end
if spots.left then
edges = edges + 1
edge[edges] = {x = x-8, z = z, check = {count = 1, pos = {[1] = {x = -8, z = 0}, } } }
if spots.top then
edge[edges].check.count = edge[edges].check.count + 1
edge[edges].check.pos[edge[edges].check.count] = {x = 0, z = -8}
end
if spots.bot then
edge[edges].check.count = edge[edges].check.count + 1
edge[edges].check.pos[edge[edges].check.count] = {x = 0, z = 8}
end
end
if spots.right then
edges = edges + 1
edge[edges] = {x = x+8, z = z, check = {count = 1, pos = {[1] = {x = 8, z = 0}, } } }
if spots.top then
edge[edges].check.count = edge[edges].check.count + 1
edge[edges].check.pos[edge[edges].check.count] = {x = 0, z = -8}
end
if spots.bot then
edge[edges].check.count = edge[edges].check.count + 1
edge[edges].check.pos[edge[edges].check.count] = {x = 0, z = 8}
end
end
if spots.top then
edges = edges + 1
edge[edges] = {x = x, z = z-8, check = {count = 1, pos = {[1] = {x = 0, z = -8}, } } }
if spots.left then
edge[edges].check.count = edge[edges].check.count + 1
edge[edges].check.pos[edge[edges].check.count] = {x = -8, z = 0}
end
if spots.right then
edge[edges].check.count = edge[edges].check.count + 1
edge[edges].check.pos[edge[edges].check.count] = {x = 8, z = 0}
end
end
if spots.bot then
edges = edges + 1
edge[edges] = {x = x, z = z+8, check = {count = 1, pos = {[1] = {x = 0, z = 8}, } } }
if spots.left then
edge[edges].check.count = edge[edges].check.count + 1
edge[edges].check.pos[edge[edges].check.count] = {x = -8, z = 0}
end
if spots.right then
edge[edges].check.count = edge[edges].check.count + 1
edge[edges].check.pos[edge[edges].check.count] = {x = 8, z = 0}
end
end
if edges ~= 0 then
point.edges = edges
point.edge = edge
else
point.edges = nil
end
end
end
end
local function CheckThickness(x, z, area)
-- This function returns whether the terraform point has sufficient nearby points
-- for the terraform to not be considered too thin.
if x%16 == 8 then
if z%16 == 8 then
local north = area[x] and (area[x][z-16] ~= nil)
local northEast = area[x+16] and (area[x+16][z-16] ~= nil)
local east = area[x+16] and (area[x+16][z] ~= nil)
if north and northEast and east then
return true
end
local southEast = area[x+16] and (area[x+16][z+16] ~= nil)
if northEast and east and southEast then
return true
end
local south = area[x] and (area[x][z+16] ~= nil)
if east and southEast and south then
return true
end
local southWest = area[x-16] and (area[x-16][z+16] ~= nil)
if southEast and south and southWest then
return true
end
local west = area[x-16] and (area[x-16][z] ~= nil)
if south and southWest and west then
return true
end
local northWest = area[x-16] and (area[x-16][z-16] ~= nil)
if southWest and west and northWest then
return true
end
if west and northWest and north then
return true
end
if northWest and north and northEast then
return true
end
else
return (area[x] and (area[x][z-8] ~= nil)) or (area[x] and (area[x][z+8] ~= nil))
end
elseif z%16 == 8 then
return (area[x-8] and (area[x-8][z] ~= nil)) or (area[x+8] and (area[x+8][z] ~= nil))
else
if area[x-8] and (area[x-8][z-8] ~= nil) then
return true
end
if area[x-8] and (area[x-8][z+8] ~= nil) then
return true
end
if area[x+8] and (area[x+8][z-8] ~= nil) then
return true
end
if area[x+8] and (area[x+8][z+8] ~= nil) then
return true
end
end
return false
end
local function updateTerraformCost(id)
local terra = terraformUnit[id]
local checkAreaRemoved = true
local areaRemoved = false
while checkAreaRemoved do
checkAreaRemoved = false
for i = 1, terra.points do
local point = terra.point[i]
if not point.structure then
local x = point.x
local z = point.z
if not CheckThickness(x, z, terra.area) then
if terra.area[x] and terra.area[x][z] then
terra.area[x][z] = nil
end
point.structure = 1
areaRemoved = true
checkAreaRemoved = true
end
end
end
end
if areaRemoved then
updateTerraformEdgePoints(id)
end
local volume = 0
for i = 1, terra.points do
local point = terra.point[i]
local x = point.x
local z = point.z
local height = spGetGroundHeight(x,z)
point.orHeight = height
if point.structure == 1 then
point.diffHeight = 0
elseif point.structure then
point.diffHeight = 0
else
point.diffHeight = point.aimHeight - height
end
volume = volume + abs(point.diffHeight)
end
spSetUnitHealth(id, {
health = 0,
build = 0
})
if volume < 0.0001 then
-- Destroying the terraform here would enable structure-detecting maphax.
volume = 0.0001
terra.toRemove = true
end
terra.lastProgress = 0
terra.lastHealth = 0
terra.progress = 0
terra.cost = volume*volumeCost
terra.totalCost = terra.cost + terra.baseCost
return true
end
local function checkTerraformIntercepts(id)
for i = 1, terraformOrders do
--Spring.MarkerAddLine(terraformOrder[i].border.left,0,terraformOrder[i].border.top,terraformOrder[i].border.right,0,terraformOrder[i].border.top)
--Spring.MarkerAddLine(terraformOrder[i].border.left,0,terraformOrder[i].border.bottom,terraformOrder[i].border.right,0,terraformOrder[i].border.bottom)
--Spring.MarkerAddLine(terraformOrder[i].border.left,0,terraformOrder[i].border.top,terraformOrder[i].border.left,0,terraformOrder[i].border.bottom)
--Spring.MarkerAddLine(terraformOrder[i].border.right,0,terraformOrder[i].border.top,terraformOrder[i].border.right,0,terraformOrder[i].border.bottom)
if (terraformOrder[i].border.left <= terraformOrder[terraformUnit[id].order].border.right and
terraformOrder[i].border.right >= terraformOrder[terraformUnit[id].order].border.left and
terraformOrder[i].border.top <= terraformOrder[terraformUnit[id].order].border.bottom and
terraformOrder[i].border.bottom >= terraformOrder[terraformUnit[id].order].border.top) then
for j = 1, terraformOrder[i].indexes do
local oid = terraformUnitTable[terraformOrder[i].index[j]]
if oid ~= id and not terraformUnit[id].interceptMap[oid] and terraformUnit[oid].fullyInitialised then
if (terraformUnit[id].border.left <= terraformUnit[oid].border.right and
terraformUnit[id].border.right >= terraformUnit[oid].border.left and
terraformUnit[id].border.top <= terraformUnit[oid].border.bottom and
terraformUnit[id].border.bottom >= terraformUnit[oid].border.top) then
terraformUnit[oid].intercepts = terraformUnit[oid].intercepts + 1
terraformUnit[id].intercepts = terraformUnit[id].intercepts + 1
terraformUnit[oid].intercept[terraformUnit[oid].intercepts] = {index = terraformUnit[id].intercepts, id = id}
terraformUnit[id].intercept[terraformUnit[id].intercepts] = {index = terraformUnit[oid].intercepts, id = oid}
terraformUnit[oid].interceptMap[id] = true
terraformUnit[id].interceptMap[oid] = true
end
end
end
end
end
end
local function updateTerraformBorder(id,x,z) -- updates border for edge point x,z
local change = false
if x < terraformUnit[id].border.left then
terraformUnit[id].border.left = x
change = true
end
if x > terraformUnit[id].border.right then
terraformUnit[id].border.right = x
change = true
end
if z < terraformUnit[id].border.top then
terraformUnit[id].border.top = z
change = true
end
if z > terraformUnit[id].border.bottom then
terraformUnit[id].border.bottom = z
change = true
end
if change then
local border = terraformOrder[terraformUnit[id].order].border
if x < border.left then
border.left = x
end
if x > border.right then
border.right = x
end
if z < border.top then
border.top = z
end
if z > border.bottom then
border.bottom = z
end
checkTerraformIntercepts(id)
end
end
local function finishInitialisingTerraformUnit(id)
--checkTerraformIntercepts(id) --Removed Intercept Check
updateTerraformEdgePoints(id)
updateTerraformCost(id)
--Spring.MarkerAddPoint(terraformUnit[id].position.x,0,terraformUnit[id].position.z,"Base " .. terraformUnit[id].baseCost)
--Spring.MarkerAddPoint(terraformUnit[id].position.x,0,terraformUnit[id].position.z,"Cost " .. terraformUnit[id].cost)
--Spring.MarkerAddPoint(terraformUnit[id].position.x,0,terraformUnit[id].position.z,"Points " .. terraformUnit[id].points)
terraformUnit[id].fullyInitialised = true
end
local function addSteepnessMarker(team, x, z)
local n = spGetGameFrame()
if steepnessMarkers.inner.frame ~= n then
steepnessMarkers.inner = {count = 0, data = {}, frame = n}
end
Spring.Echo(steepnessMarkers.inner.frame)
steepnessMarkers.inner.count = steepnessMarkers.inner.count+1
steepnessMarkers.inner.data[steepnessMarkers.inner.count] = {team = team, x = x, z = z}
end
local function updateTerraform(health,id,arrayIndex,costDiff)
local terra = terraformUnit[id]
if terra.toRemove and (costDiff > 0.1 or terra.baseCostSpent > 0.1) then
-- Removing terraform too early enables structure-detecting maphax.
deregisterTerraformUnit(id,arrayIndex,2)
spDestroyUnit(id, false, true)
return 0
end
if terra.baseCostSpent then
if costDiff < terra.baseCost-terra.baseCostSpent then
terra.baseCostSpent = terra.baseCostSpent + costDiff
local newBuild = terra.baseCostSpent/terra.totalCost
spSetUnitHealth(id, {
health = newBuild*terraUnitHP,
build = newBuild
})
terra.lastHealth = newBuild*terraUnitHP
terra.lastProgress = newBuild
return 1
else
costDiff = costDiff - (terra.baseCost-terra.baseCostSpent)
terra.baseCostSpent = false
--[[ naive ground drawing
local drawingList = {}
for i = 1, terra.points do
local x = terra.point[i].x
local z = terra.point[i].z
drawingList[#drawingList+1] = {x = x, z = z, tex = 1}
end
GG.Terrain_Texture_changeBlockList(drawingList)
--]]
--[[
something pertaining to drawing would go here
for i = 1, terra.points do
local x = terra.point[i].x
local z = terra.point[i].z
if terra.area[x+8] and terra.area[x+8][z+8] then
if drawPosMap[x] and drawPosMap[x][z] then
drawPositions.data[drawPosMap[x][z] ].r = 0.5
drawPositions.data[drawPosMap[x][z] ].g = 0
drawPositions.data[drawPosMap[x][z] ].b = 0
drawPositions.data[drawPosMap[x][z] ].a = 0.5
else
drawPositions.count = drawPositions.count + 1
drawPositions.data[drawPositions.count] = {x1 = x, z1 = z, x2 = x+8, z2 = z+8, r = 0.5, g = 0, b = 0, a = 0.5}
drawPosMap[x] = drawPosMap[x] or {}
drawPosMap[x][z] = drawPositions.count
end
end
end--]]
end
end
for i = 1, terra.points do
local heightDiff = terra.point[i].prevHeight - spGetGroundHeight(terra.point[i].x, terra.point[i].z)
if heightDiff ~= 0 then
updateTerraformCost(id)
break
-- There must be a nicer way to update costs, below is an unstable attempt.
--local change = ((1-terra.progress)*terra.point[i].diffHeight + heightDiff)/((1-terra.progress)*terra.point[i].diffHeight)
--Spring.Echo(change)
--local costChange = (abs(change * terra.point[i].diffHeight) - abs(terra.point[i].diffHeight))*volumeCost
--terra.point[i].diffHeight = change * terra.point[i].diffHeight
--terra.point[i].orHeight = terra.point[i].aimHeight - terra.point[i].diffHeight
--terraformUnit[id].cost = terraformUnit[id].cost + costChange
--terraformUnit[id].totalCost = terraformUnit[id].totalCost + costChange
end
end
local newProgress = terra.progress + costDiff/terra.totalCost
if newProgress> 1 then
newProgress = 1
end
local addedCost = 0
local extraPoint = {}
local extraPoints = 0
local extraPointArea = {}
--[[
for i = 1, terra.points do
if terra.point[i].edges then
for j = 1, terra.point[i].edges do
local x = terra.point[i].edge[j].x
local z = terra.point[i].edge[j].z
Spring.MarkerAddLine(x-2,0,z-2, x+2,0,z+2)
Spring.MarkerAddLine(x-2,0,z+2, x+2,0,z-2)
end
end
end
--]]
for i = 1, terra.points do
if terra.point[i].edges then
local newHeight = terra.point[i].orHeight+(terra.point[i].aimHeight-terra.point[i].orHeight)*newProgress
local up = terra.point[i].aimHeight-terra.point[i].orHeight > 0
for j = 1, terra.point[i].edges do
local x = terra.point[i].edge[j].x
local z = terra.point[i].edge[j].z
local groundHeight = spGetGroundHeight(x, z)
local edgeHeight = groundHeight
local overlap = false
local overlapCost = 0
if extraPointArea[x] and extraPointArea[x][z] then
overlap = extraPointArea[x][z]
edgeHeight = extraPoint[overlap].orHeight + extraPoint[overlap].heightDiff
overlapCost = extraPoint[overlap].cost
end
local diffHeight = newHeight - edgeHeight
if diffHeight > maxHeightDifference and up then
local index = extraPoints + 1
if overlap then
if not extraPoint[overlap].pyramid then
addSteepnessMarker(terra.team, terra.position.x,terra.position.z)
deregisterTerraformUnit(id,arrayIndex,2)
spDestroyUnit(id, false, true)
return 0
end
index = overlap
else
extraPoints = extraPoints + 1
end
extraPoint[index] = {
x = x, z = z,
orHeight = groundHeight,
heightDiff = newHeight - maxHeightDifference - groundHeight,
cost = (newHeight - maxHeightDifference - groundHeight),
supportX = terra.point[i].x,
supportZ = terra.point[i].z,
supportH = newHeight,
supportID = i,
check = terra.point[i].edge[j].check,
pyramid = true, -- pyramid = rising up, not pyramid = ditch
}
--updateTerraformBorder(id,x,z) --Removed Intercept Check
if structureAreaMap[x] and structureAreaMap[x][z] then
if terra.area[terra.point[i].x] and terra.area[terra.point[i].x][terra.point[i].z] then
terra.area[terra.point[i].x][terra.point[i].z] = false
end
terra.point[i].diffHeight = 0.0001
terra.point[i].structure = 1
return -1
end
addedCost = addedCost + extraPoint[index].cost - overlapCost
if not extraPointArea[x] then
extraPointArea[x] = {}
end
extraPointArea[x][z] = index
elseif diffHeight < -maxHeightDifference and not up then
local index = extraPoints + 1
if overlap then
if extraPoint[overlap].pyramid then
addSteepnessMarker(terra.team, terra.position.x,terra.position.z)
deregisterTerraformUnit(id,arrayIndex,2)
spDestroyUnit(id, false, true)
return 0
end
index = overlap
else
extraPoints = extraPoints + 1
end
extraPoint[index] = {
x = x,
z = z,
orHeight = groundHeight,
heightDiff = newHeight + maxHeightDifference - groundHeight,
cost = -(newHeight + maxHeightDifference - groundHeight),
supportX = terra.point[i].x,
supportZ = terra.point[i].z,
supportH = newHeight,
supportID = i,
check = terra.point[i].edge[j].check,
pyramid = false, -- pyramid = rising up, not pyramid = ditch
}
--updateTerraformBorder(id,x,z) --Removed Intercept Check
if structureAreaMap[x] and structureAreaMap[x][z] then
if terra.area[terra.point[i].x] and terra.area[terra.point[i].x][terra.point[i].z] then
terra.area[terra.point[i].x][terra.point[i].z] = false
end
terra.point[i].diffHeight = 0.0001
terra.point[i].structure = 1
return -1
end
addedCost = addedCost + extraPoint[index].cost - overlapCost
if not extraPointArea[x] then
extraPointArea[x] = {}
end
extraPointArea[x][z] = index
end
end
end
end
local i = 1
while i <= extraPoints do
local newHeight = extraPoint[i].supportH
-- diamond pyramids
--local maxHeightDifferenceLocal = (abs(extraPoint[i].x-extraPoint[i].supportX) + abs(extraPoint[i].z-extraPoint[i].supportZ))*maxHeightDifference/8+maxHeightDifference
-- circular pyramids
local maxHeightDifferenceLocal = sqrt((extraPoint[i].x-extraPoint[i].supportX)^2 + (extraPoint[i].z-extraPoint[i].supportZ)^2)*maxHeightDifference/8+maxHeightDifference
for j = 1, extraPoint[i].check.count do
local x = extraPoint[i].check.pos[j].x + extraPoint[i].x
local z = extraPoint[i].check.pos[j].z + extraPoint[i].z
--and not (extraPointArea[x] and extraPointArea[x][z])
if not (terra.area[x] and terra.area[x][z]) then
local groundHeight = spGetGroundHeight(x, z)
local edgeHeight = groundHeight
local overlap = false
local overlapCost = 0
if extraPointArea[x] and extraPointArea[x][z] then
overlap = extraPointArea[x][z]
edgeHeight = extraPoint[overlap].orHeight + extraPoint[overlap].heightDiff
overlapCost = extraPoint[overlap].cost
end
local diffHeight = newHeight - edgeHeight
if diffHeight > maxHeightDifferenceLocal and extraPoint[i].pyramid then
local index = extraPoints + 1
if overlap then
if not extraPoint[overlap].pyramid then
addSteepnessMarker(terra.team, terra.position.x,terra.position.z)
deregisterTerraformUnit(id,arrayIndex,2)
spDestroyUnit(id, false, true)
return 0
end
index = overlap
else
extraPoints = extraPoints + 1
end
extraPoint[index] = {
x = x,
z = z,
orHeight = groundHeight,
heightDiff = newHeight - maxHeightDifferenceLocal - groundHeight,
cost = (newHeight - maxHeightDifferenceLocal - groundHeight),
supportX = extraPoint[i].supportX,
supportZ = extraPoint[i].supportZ,
supportH = extraPoint[i].supportH,
supportID = extraPoint[i].supportID,
check = extraPoint[i].check,
pyramid = true, -- pyramid = rising up, not pyramid = ditch
}
--updateTerraformBorder(id,x,z) --Removed Intercept Check
if structureAreaMap[x] and structureAreaMap[x][z] then
if terra.area[extraPoint[index].supportX] and terra.area[extraPoint[index].supportX][extraPoint[index].supportZ] then
terra.area[extraPoint[index].supportX][extraPoint[index].supportZ] = false
end
terra.point[extraPoint[i].supportID].diffHeight = 0.0001
terra.point[extraPoint[i].supportID].structure = 1
return -1
end
addedCost = addedCost + extraPoint[index].cost - overlapCost
if not extraPointArea[x] then
extraPointArea[x] = {}
end
extraPointArea[x][z] = index
elseif diffHeight < -maxHeightDifferenceLocal and not extraPoint[i].pyramid then
local index = extraPoints + 1
if overlap then
if extraPoint[overlap].pyramid then
addSteepnessMarker(terra.team, terra.position.x,terra.position.z)
deregisterTerraformUnit(id,arrayIndex,2)
spDestroyUnit(id, false, true)
return 0
end
index = overlap
else
extraPoints = extraPoints + 1
end
extraPoint[index] = {
x = x,
z = z,
orHeight = groundHeight,
heightDiff = newHeight + maxHeightDifferenceLocal - groundHeight,
cost = -(newHeight + maxHeightDifferenceLocal - groundHeight),
supportX = extraPoint[i].supportX,
supportZ = extraPoint[i].supportZ,
supportH = extraPoint[i].supportH,
supportID = extraPoint[i].supportID,
check = extraPoint[i].check,
pyramid = false, -- pyramid = rising up, not pyramid = ditch
}
--updateTerraformBorder(id,x,z) --Removed Intercept Check
if structureAreaMap[x] and structureAreaMap[x][z] then
if terra.area[extraPoint[index].supportX] and terra.area[extraPoint[index].supportX][extraPoint[index].supportZ] then
terra.area[extraPoint[index].supportX][extraPoint[index].supportZ] = false -- false for edge-derived problems
end
terra.point[extraPoint[i].supportID].diffHeight = 0.0001
terra.point[extraPoint[i].supportID].structure = 1
return -1
end
addedCost = addedCost + extraPoint[index].cost - overlapCost
if not extraPointArea[x] then
extraPointArea[x] = {}
end
extraPointArea[x][z] = index
end
end
end
if extraPoints > 9000 then
Spring.Log(gadget:GetInfo().name, LOG.WARNING, "spire wall break")
break -- safty
end
i = i + 1
end
terraformOperations = terraformOperations + extraPoints
local oldCostDiff = costDiff
local edgeTerraMult = 1
if costDiff ~= 0 then
if addedCost == 0 then
terra.progress = terra.progress + costDiff/terra.totalCost
else
local extraCost = 0
if terra.progress + costDiff/terra.cost > 1 then
extraCost = costDiff - terra.cost*(1 - terra.progress)
costDiff = (1 - terra.progress)*terra.cost
end
addedCost = addedCost*volumeCost
local edgeTerraCost = (costDiff*addedCost/(costDiff+addedCost))
terra.progress = terra.progress + (costDiff-edgeTerraCost)/terra.cost
edgeTerraMult = edgeTerraCost/addedCost
if extraCost > 0 then
edgeTerraCost = edgeTerraCost + extraCost
if edgeTerraCost > addedCost then
terra.progress = terra.progress + (edgeTerraCost - addedCost)/terra.cost
edgeTerraMult = 1
else
edgeTerraMult = edgeTerraCost/addedCost
end
end
end
end
if edgeTerraMult > 1 then
Spring.Log(gadget:GetInfo().name, LOG.ERROR, "Terraform:")
Spring.Log(gadget:GetInfo().name, LOG.ERROR, "edgeTerraMult > 1 THIS IS VERY BAD")
Spring.Log(gadget:GetInfo().name, LOG.ERROR, "Tell Google Frog")
end
local progress = terra.progress
if terra.progress > 1 then
progress = 1
edgeTerraMult = 1
end
local newBuild = terra.progress
spSetUnitHealth(id, {
health = newBuild*terraUnitHP,
build = newBuild
})
terra.lastHealth = newBuild*terraUnitHP
terra.lastProgress = newBuild
-- Bug Safety
for i = 1, extraPoints do
if abs(extraPoint[i].orHeight + extraPoint[i].heightDiff*edgeTerraMult) > 3000 then
Spring.Log(gadget:GetInfo().name, LOG.WARNING, "Terraform:")
Spring.Log(gadget:GetInfo().name, LOG.WARNING, "Strange pyramid construction")
Spring.Log(gadget:GetInfo().name, LOG.WARNING, "Destroying Terraform Unit")
deregisterTerraformUnit(id,arrayIndex,2)
spDestroyUnit(id, false, true)
return 0
end
end
local func = function()
for i = 1, terra.points do
local height = terra.point[i].orHeight+terra.point[i].diffHeight*progress
spSetHeightMap(terra.point[i].x,terra.point[i].z, height)
terra.point[i].prevHeight = height
end
for i = 1, extraPoints do
spSetHeightMap(extraPoint[i].x,extraPoint[i].z,extraPoint[i].orHeight + extraPoint[i].heightDiff*edgeTerraMult)
end
end
spSetHeightMapFunc(func)
-- Draw the changes
if USE_TERRAIN_TEXTURE_CHANGE then
local drawingList = {}
for i = 1, terra.points do
local x = terra.point[i].x
local z = terra.point[i].z
local freeLeft = not (terra.area[x-8] and terra.area[x-8][z]) and not (extraPointArea[x-8] and extraPointArea[x-8][z])
local freeUp = not (terra.area[x] and terra.area[x][z-8]) and not (extraPointArea[x] and extraPointArea[x][z-8])
local freeRight = not (terra.area[x+8] and terra.area[x+8][z]) and not (extraPointArea[x+8] and extraPointArea[x+8][z])
local freeDown = not (terra.area[x] and terra.area[x][z+8]) and not (extraPointArea[x] and extraPointArea[x][z+8])
drawingList[#drawingList+1] = {x = x, z = z, tex = 1, edge = freeRight or freeDown}
if freeLeft then
drawingList[#drawingList+1] = {x = x-8, z = z, tex = 1, edge = true}
end
if freeUp then
drawingList[#drawingList+1] = {x = x, z = z-8, tex = 1, edge = true}
if freeLeft then
drawingList[#drawingList+1] = {x = x-8, z = z-8, tex = 1, edge = true}
end
end
end
for i = 1, extraPoints do
local x = extraPoint[i].x
local z = extraPoint[i].z
local freeLeft = not (extraPointArea[x-8] and extraPointArea[x-8][z])
local freeUp = not (terra.area[x] and terra.area[x][z-8]) and not (extraPointArea[x] and extraPointArea[x][z-8])
drawingList[#drawingList+1] = {x = x, z = z, tex = 2}
if freeLeft then
drawingList[#drawingList+1] = {x = x-8, z = z, tex = 2}
end
if freeUp then
drawingList[#drawingList+1] = {x = x, z = z-8, tex = 2}
if freeLeft then
drawingList[#drawingList+1] = {x = x-8, z = z-8, tex = 2}
end
end
end
for i = 1, #drawingList do
local x = drawingList[i].x+4
local z = drawingList[i].z+4
local edge = drawingList[i].edge
drawingList[i].edge = nil -- don't sent to other gadget to send to unsynced
-- edge exists because raised walls have passability at higher normal than uniform ramps
local oHeight = spGetGroundOrigHeight(x,z)
local height = spGetGroundHeight(x,z)
if abs(oHeight-height) < 1 then
drawingList[i].tex = 0
else
local normal = select(2,Spring.GetGroundNormal(x,z))
if (edge and normal > 0.8) or (not edge and normal > 0.892) then
drawingList[i].tex = 1
elseif (edge and normal > 0.41) or (not edge and normal > 0.585) then
drawingList[i].tex = 2
else
drawingList[i].tex = 3
end
end
end
GG.Terrain_Texture_changeBlockList(drawingList)
end
--Removed Intercept Check
--if terraformUnit[id].intercepts ~= 0 then
-- local i = 1
-- while i <= terra.intercepts do
-- local test = updateTerraformCost(terra.intercept[i].id)
-- if test then
-- i = i + 1
-- end
-- end
--end
if terra.progress > 1 then
deregisterTerraformUnit(id,arrayIndex,2)
spDestroyUnit(id, false, true)
return 0
end
return 1
end
local function DoTerraformUpdate(n, forceCompletion)
local i = 1
while i <= terraformUnitCount do
local id = terraformUnitTable[i]
if (spValidUnitID(id)) then
local force = (forceCompletion and not terraformUnit[id].disableForceCompletion)
local health = spGetUnitHealth(id)
local diffProgress = health/terraUnitHP - terraformUnit[id].progress
if diffProgress == 0 then
if (not forceCompletion) and (n % decayCheckFrequency == 0 and terraformUnit[id].decayTime < n) then
deregisterTerraformUnit(id,i,3)
spDestroyUnit(id, false, true)
else
i = i + 1
end
else
if not terraformUnit[id].fullyInitialised then
finishInitialisingTerraformUnit(id,i)
end
if force or (n - terraformUnit[id].lastUpdate >= updatePeriod) then
local costDiff = health - terraformUnit[id].lastHealth
if force then
costDiff = costDiff + 100000 -- enough?
end
terraformUnit[id].totalSpent = terraformUnit[id].totalSpent + costDiff
SetTooltip(id, terraformUnit[id].totalSpent, terraformUnit[id].pyramidCostEstimate + terraformUnit[id].totalCost)
if GG.Awards and GG.Awards.AddAwardPoints then
GG.Awards.AddAwardPoints('terra', terraformUnit[id].team, costDiff)
end
local updateVar = updateTerraform(health,id,i,costDiff)
while updateVar == -1 do
if updateTerraformCost(id) then
updateTerraformEdgePoints(id)
updateVar = updateTerraform(health,id,i,costDiff)
else
updateVar = 0
end
end
if updateVar == 1 then
if n then
terraformUnit[id].lastUpdate = n
end
i = i + 1
end
else
i = i + 1
end
end
else
-- remove if the unit is no longer valid
deregisterTerraformUnit(id,i,4)
end
end
end
function gadget:GameFrame(n)
if workaround_recursion_in_cmd_fallback_needed then
for unitID, terraID in pairs(workaround_recursion_in_cmd_fallback) do
REPAIR_ORDER_PARAMS[4] = terraID
spGiveOrderToUnit(unitID, CMD_INSERT, REPAIR_ORDER_PARAMS, CMD_OPT_ALT)
end
workaround_recursion_in_cmd_fallback = {}
workaround_recursion_in_cmd_fallback_needed = false
end
--if n % 300 == 0 then
-- GG.Terraform_RaiseWater(-20)
--end
if n >= nextUpdateCheck then
updatePeriod = math.max(MIN_UPDATE_PERIOD, math.min(MAX_UPDATE_PERIOD, terraformOperations/60))
--Spring.Echo("Terraform operations", terraformOperations, updatePeriod)
terraformOperations = 0
nextUpdateCheck = n + updatePeriod
end
DoTerraformUpdate(n)
--check constrcutors that are repairing terraform blocks
if constructors ~= 0 then
if n % checkInterval == 0 then
-- only check 1 con per cycle
currentCon = currentCon + 1
if currentCon > constructors then
currentCon = 1
end
local cQueue = spGetCommandQueue(constructorTable[currentCon], -1)
if cQueue then
local ncq = #cQueue
for i = 1, ncq do
if cQueue[i].id == CMD_REPAIR then
if #cQueue[i].params == 1 then
-- target unit command
if terraformUnit[cQueue[i].params[1]] then
terraformUnit[cQueue[i].params[1]].decayTime = n + terraformDecayFrames
end
-- bring terraunit towards con
if i == 1 and spValidUnitID(cQueue[i].params[1]) and terraformUnit[cQueue[i].params[1] ] then
local cx, _, cz = spGetUnitPosition(constructorTable[currentCon])
local team = spGetUnitTeam(constructorTable[currentCon])
if cx and team then
local tpos = terraformUnit[cQueue[i].params[1] ].positionAnchor
local vx, vz = cx - tpos.x, cz - tpos.z
local scale = terraUnitLeash/sqrt(vx^2 + vz^2)
local x,z = tpos.x + scale*vx, tpos.z + scale*vz
local y = CallAsTeam(team, function () return spGetGroundHeight(x,z) end)
x, z = getPointInsideMap(x,z)
terraformUnit[cQueue[i].params[1] ].position = {x = x, z = z}
spSetUnitPosition(cQueue[i].params[1], x, y , z)
--Spring.MoveCtrl.Enable(cQueue[i].params[1])
--Spring.MoveCtrl.SetPosition(cQueue[i].params[1], x, y , z)
--Spring.MoveCtrl.Disable(cQueue[i].params[1])
end
end
elseif #cQueue[i].params == 4 then -- there is a command with 5 params that I do not want
-- area command
local radSQ = cQueue[i].params[4]^2
local cX, _, cZ = cQueue[i].params[1],cQueue[i].params[2],cQueue[i].params[3]
if constructor[constructorTable[currentCon]] and constructor[constructorTable[currentCon]].allyTeam then
local allyTeam = constructor[constructorTable[currentCon]].allyTeam
for j = 1, terraformUnitCount do
local terra = terraformUnit[terraformUnitTable[j]]
if terra.allyTeam == allyTeam then
local disSQ = (terra.position.x - cX)^2 + (terra.position.z - cZ)^2
if disSQ < radSQ then
--Spring.MarkerAddPoint(terra.position.x,0,terra.position.z,"saved " .. cX)
terra.decayTime = n + terraformDecayFrames
end
end
end
end
end
end
end
end
end
end
--check structures for terrain deformation
local struc = structureCheckFrame[n % structureCheckLoopFrames]
if struc then
local i = 1
while i <= struc.count do
local unit = structure[struc.unit[i]]
if unit then
local height = spGetGroundHeight(unit.x, unit.z)
if height ~= unit.h then
spLevelHeightMap(unit.minx,unit.minz,unit.maxx,unit.maxz,unit.h)
end
else
end
i = i + 1
end
end
end
function gadget:CommandFallback(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions)
if not fallbackableCommands[cmdID] then
return false
end
if not fallbackCommands[teamID] then
return false
end
if not (cmdParams and cmdParams[4]) then
return false
end
local command = fallbackCommands[teamID][cmdParams[4]]
if not command then
return false
end
if not terraformUnitDefIDs[unitDefID] then
return false, true
end
local ux,_,uz = spGetUnitPosition(unitID)
local closestID
local closestDistance
for i = 1, command.terraunits do
local terraID = command.terraunitList[i]
if (Spring.ValidUnitID(terraID) and Spring.GetUnitDefID(terraID) == terraunitDefID) then
local tx,_,tz = spGetUnitPosition(terraID)
local distance = (tx-ux)*(tx-ux) + (tz-uz)*(tz-uz)
if (not closestDistance) or (distance < closestDistance) then
closestID = terraID
closestDistance = distance
end
end
end
if closestID then
--[[ Recursion not allowed.
REPAIR_ORDER_PARAMS[4] = closestID
spGiveOrderToUnit(unitID, CMD_INSERT, REPAIR_ORDER_PARAMS, CMD_OPT_ALT)
]]
workaround_recursion_in_cmd_fallback[unitID] = closestID
workaround_recursion_in_cmd_fallback_needed = true
return true, false
end
fallbackCommands[teamID][cmdParams[4]] = nil
return false
end
function gadget:UnitPreDamaged(unitID, unitDefID, unitTeam, damage, paralyzer,
weaponID, attackerID, attackerDefID, attackerTeam)
if unitDefID == terraunitDefID then
return 0 -- terraunit starts on 0 HP. If a unit is damaged and has 0 HP it dies
end
return damage
end
--------------------------------------------------------------------------------
-- Weapon Terraform
--------------------------------------------------------------------------------
local wantedList = {}
local SeismicWeapon = {}
local DEFAULT_SMOOTH = 0.5
local HEIGHT_FUDGE_FACTOR = 10
local HEIGHT_RAD_MULT = 0.8
local MIN_SMOOTH_RAD = 20
for i=1,#WeaponDefs do
local wd = WeaponDefs[i]
if wd.customParams and wd.customParams.smoothradius or wd.customParams.smoothmult then
wantedList[#wantedList + 1] = wd.id
Script.SetWatchWeapon(wd.id,true)
SeismicWeapon[wd.id] = {
smooth = wd.customParams.smoothmult or DEFAULT_SMOOTH,
smoothradius = wd.customParams.smoothradius or wd.craterAreaOfEffect*0.5,
gatherradius = wd.customParams.gatherradius or wd.craterAreaOfEffect*0.75,
detachmentradius = wd.customParams.detachmentradius
}
end
end
local function makeTerraChangedPointsPyramidAroundStructures(posX,posY,posZ,posCount)
--local found = {count = 0, data = {}}
for i = 1, posCount do
if structureAreaMap[posX[i]] and structureAreaMap[posX[i]][posZ[i]] then
posY[i] = 0
--found.count = found.count + 1
--found.data[found.count] = {x = posX[i], z = posZ[i]}
end
end
--[[
if found.count == 0 then
return posY
end
for i = 1, posCount do
local x = posX[i]
local z = posZ[i]
for j = 1, found.count do
local fx = found.data[j].x
local fz = found.data[j].z
local maxChange = sqrt((fx-x)^2 + (fz-z)^2)*maxHeightDifference/64
if abs(posY[i]) > maxChange then
posY[i] = abs(posY[i])/posY[i]*maxChange
end
end
end
--]]
return posY
end
function gadget:Explosion_GetWantedWeaponDef()
return wantedList
end
function gadget:Explosion(weaponID, x, y, z, owner)
if SeismicWeapon[weaponID] then
local height = spGetGroundHeight(x,z)
local smoothradius = SeismicWeapon[weaponID].smoothradius
local gatherradius = SeismicWeapon[weaponID].gatherradius
local detachmentradius = SeismicWeapon[weaponID].detachmentradius
local maxSmooth = SeismicWeapon[weaponID].smooth
if y > height + HEIGHT_FUDGE_FACTOR then
local factor = 1 - ((y - height - HEIGHT_FUDGE_FACTOR)/smoothradius*HEIGHT_RAD_MULT)^2
if factor > 0 then
smoothradius = smoothradius*factor
gatherradius = gatherradius*factor
maxSmooth = maxSmooth*factor
else
return
end
end
local smoothradiusSQ = smoothradius^2
local gatherradiusSQ = gatherradius^2
smoothradius = smoothradius + (8 - smoothradius%8)
gatherradius = gatherradius + (8 - gatherradius%8)
local sx = floor((x+4)/8)*8
local sz = floor((z+4)/8)*8
local groundPoints = 0
local groundHeight = 0
local origHeight = {} -- just to not read the heightmap twice
for i = sx-gatherradius, sx+gatherradius,8 do
origHeight[i] = {}
for j = sz-gatherradius, sz+gatherradius,8 do
local disSQ = (i - x)^2 + (j - z)^2
if disSQ <= gatherradiusSQ then
origHeight[i][j] = spGetGroundHeight(i,j)
groundPoints = groundPoints + 1
groundHeight = groundHeight + origHeight[i][j]
end
end
end
local biggestChange = 0
if groundPoints > 0 then
groundHeight = groundHeight/groundPoints
local posX, posY, posZ = {}, {}, {}
local posCount = 0
for i = sx-smoothradius, sx+smoothradius,8 do
for j = sz-smoothradius, sz+smoothradius,8 do
local disSQ = (i - x)^2 + (j - z)^2
if disSQ <= smoothradiusSQ then
if not origHeight[i] then
origHeight[i] = {}
end
if not origHeight[i][j] then
origHeight[i][j] = spGetGroundHeight(i,j)
end
local newHeight = (groundHeight - origHeight[i][j]) * maxSmooth * (1 - disSQ/smoothradiusSQ)^2
posCount = posCount + 1
posX[posCount] = i
posY[posCount] = newHeight
posZ[posCount] = j
local absChange = math.abs(newHeight)
if biggestChange and absChange > biggestChange then
if absChange > 0.5 then
biggestChange = false
else
biggestChange = absChange
end
end
end
end
end
local posY = makeTerraChangedPointsPyramidAroundStructures(posX,posY,posZ,posCount)
if (not biggestChange) or (math.random() < biggestChange/2) then
spSetHeightMapFunc(
function(x,z,h)
for i = 1, #x, 1 do
spAddHeightMap(x[i],z[i],h[i])
end
end,
posX,
posZ,
posY
)
end
end
if detachmentradius then
local GRAVITY = Game.gravity
local units = Spring.GetUnitsInCylinder(sx,sz,detachmentradius)
for i = 1, #units do
local hitUnitID = units[i]
GG.DetatchFromGround(hitUnitID, 1, 0.25, 0.002*GRAVITY)
end
end
end
end
--------------------------------------------------------------------------------
-- Death Explosion Terraform
--------------------------------------------------------------------------------
local function deregisterStructure(unitID)
if structure[unitID].checkAtDeath then
for i = 1, terraformOrders do
if (structure[unitID].minx < terraformOrder[i].border.right and
structure[unitID].maxx > terraformOrder[i].border.left and
structure[unitID].minz < terraformOrder[i].border.bottom and
structure[unitID].maxz> terraformOrder[i].border.top) then
for j = 1, terraformOrder[i].indexes do
local oid = terraformUnitTable[terraformOrder[i].index[j]]
if (structure[unitID].minx < terraformUnit[oid].border.right and
structure[unitID].maxx > terraformUnit[oid].border.left and
structure[unitID].minz < terraformUnit[oid].border.bottom and
structure[unitID].maxz > terraformUnit[oid].border.top) then
local recalc = false
for k = 1, terraformUnit[oid].points do
if structure[unitID].area[terraformUnit[oid].point[k].x] then
if structure[unitID].area[terraformUnit[oid].point[k].x][terraformUnit[oid].point[k].z] then
terraformUnit[oid].point[k].structure = false
terraformUnit[oid].area[terraformUnit[oid].point[k].x][terraformUnit[oid].point[k].z] = true
recalc = true
end
end
if terraformUnit[oid].point[k].structure == 1 then
terraformUnit[oid].point[k].structure = false
terraformUnit[oid].area[terraformUnit[oid].point[k].x][terraformUnit[oid].point[k].z] = true
recalc = true
end
end
if recalc then
updateTerraformEdgePoints(oid)
updateTerraformCost(oid)
end
end
end
end
end
end
for i = structure[unitID].minx, structure[unitID].maxx, 8 do
if not structureAreaMap[i] then
structureAreaMap[i] = {}
end
for j = structure[unitID].minz, structure[unitID].maxz, 8 do
structureAreaMap[i][j] = structureAreaMap[i][j] - 1
if structureAreaMap[i][j] < 1 then
structureAreaMap[i][j] = nil
end
end
end
local f = structureCheckFrame[structure[unitID].frame]
if f.count ~= structure[unitID].frameIndex then
structureCheckFrame[structure[unitID].frame].unit[structure[unitID].frameIndex] = structureCheckFrame[structure[unitID].frame].unit[f.count]
end
if structureCheckFrame[structure[unitID].frame].count == 1 then
structureCheckFrame[structure[unitID].frame] = nil
else
structureCheckFrame[structure[unitID].frame].count = structureCheckFrame[structure[unitID].frame].count - 1
end
if structure[unitID].index ~= structureCount then
structureTable[structure[unitID].index] = structureTable[structureCount]
structure[structureTable[structureCount]].index = structure[unitID].index
end
structureCount = structureCount - 1
structure[unitID] = nil
end
function gadget:UnitDestroyed(unitID, unitDefID)
if (unitDefID == shieldscoutDefID) then
local _,_,_,_,build = spGetUnitHealth(unitID)
if build == 1 then
local ux, uy, uz = spGetUnitPosition(unitID)
ux = floor((ux+8)/16)*16
uz = floor((uz+8)/16)*16
local posCount = 57
local posX =
{ux-8,ux,ux+8,
ux-16,ux-8,ux,ux+8,ux+16,
ux-24,ux-16,ux-8,ux,ux+8,ux+16,ux+24,
ux-32,ux-24,ux-16,ux-8,ux,ux+8,ux+16,ux+24,ux+32,
ux-32,ux-24,ux-16,ux-8,ux,ux+8,ux+16,ux+24,ux+32,
ux-32,ux-24,ux-16,ux-8,ux,ux+8,ux+16,ux+24,ux+32,
ux-24,ux-16,ux-8,ux,ux+8,ux+16,ux+24,
ux-16,ux-8,ux,ux+8,ux+16,
ux-8,ux,ux+8}
local posZ =
{uz-32,uz-32,uz-32,
uz-24,uz-24,uz-24,uz-24,uz-24,
uz-16,uz-16,uz-16,uz-16,uz-16,uz-16,uz-16,
uz-8 ,uz-8 ,uz-8 ,uz-8 ,uz-8 ,uz-8 ,uz-8 ,uz-8 ,uz-8 ,
uz ,uz ,uz ,uz ,uz ,uz ,uz ,uz ,uz ,
uz+8 ,uz+8 ,uz+8 ,uz+8 ,uz+8 ,uz+8 ,uz+8 ,uz+8 ,uz+8 ,
uz+16,uz+16,uz+16,uz+16,uz+16,uz+16,uz+16,
uz+24,uz+24,uz+24,uz+24,uz+24,
uz+32,uz+32,uz+32}
-- {0 ,0 ,0 ,
-- 1 ,3 ,5 ,3 ,1 ,
-- 1 ,7 ,14,17,14,7 ,1 ,
--0 ,3 ,14,26,31,26,14,3 ,0 ,
--0 ,5 ,17,31,36,31,17,5 ,0 ,
--0 ,3 ,14,26,31,26,14,3 ,0 ,
-- 1 ,7 ,14,17,14,7 ,1 ,
-- 1 ,3 ,5 ,3 ,1 ,
-- 0 ,0 ,0 }
local posY =
{2 ,3 ,2 ,
2 ,3 ,7 ,3 ,2 ,
2 ,5 ,20,21,20,4 ,2 ,
2 ,3 ,20,25,26,25,20,3 ,2 ,
3 ,7 ,21,26,28,26,21,7 ,3 ,
2 ,3 ,20,25,26,25,20,3 ,2 ,
2 ,4 ,20,21,20,5 ,2 ,
2,3 ,7 ,3 ,2 ,
2 ,3 ,2 }
posY = makeTerraChangedPointsPyramidAroundStructures(posX,posY,posZ,posCount)
spSetHeightMapFunc(
function(x,z,h)
for i = 1, #x, 1 do
spAddHeightMap(x[i],z[i],h[i])
end
end,
posX,
posZ,
posY
)
local units = Spring.GetUnitsInCylinder(ux,uz,40)
for i = 1, #units do
local hitUnitID = units[i]
if hitUnitID ~= unitID then
GG.AddGadgetImpulseRaw(hitUnitID, 0, 0.3, 0, true, true)
end
end
end
--spAdjustHeightMap(ux-64, uz-64, ux+64, uz+64 , 0)
end
--[[
if (unitDefID == novheavymineDefID) then
local _,_,_,_,build = spGetUnitHealth(unitID)
if build == 1 then
local ux, uy, uz = spGetUnitPosition(unitID)
ux = ceil(ux/8)*8-4
uz = ceil(uz/8)*8-4
local heightChange = -30
local size = 48
local heightMap = {}
for ix = ux-size-8, ux+size+8, 8 do
heightMap[ix] = {}
for iz = uz-size-8, uz+size+8, 8 do
heightMap[ix][iz] = spGetGroundHeight(ix, iz)
end
end
local point = {}
local points = 0
for ix = ux-size, ux+size, 8 do
for iz = uz-size, uz+size, 8 do
local newHeight = heightMap[ix][iz] + heightChange
local maxDiff = heightMap[ix-8][iz]-newHeight
if heightMap[ix+8][iz]-newHeight > maxDiff then
maxDiff = heightMap[ix+8][iz]-newHeight
end
if heightMap[ix][iz-8]-newHeight > maxDiff then
maxDiff = heightMap[ix][iz-8]-newHeight
end
if heightMap[ix][iz+8]-newHeight > maxDiff then
maxDiff = heightMap[ix][iz+8]-newHeight
end
if maxDiff < maxHeightDifference then
points = points + 1
point[points] = {x = ix, y = newHeight, z = iz}
elseif maxDiff < maxHeightDifference*2 then
points = points + 1
point[points] = {x = ix, y = newHeight+maxDiff-maxHeightDifference, z = iz}
end
end
end
local func = function()
for i = 1, points do
spSetHeightMap(point[i].x,point[i].z,point[i].y)
end
end
spSetHeightMapFunc(func)
end
--spAdjustHeightMap(ux-64, uz-64, ux+64, uz+64 , 0)
end
--]]
if constructor[unitID] then
local index = constructor[unitID].index
if index ~= constructors then
constructorTable[index] = constructorTable[constructors]
end
constructorTable[constructors] = nil
constructors = constructors - 1
constructor[unitID] = nil
if constructors ~= 0 then
checkInterval = ceil(checkLoopFrames/constructors)
if checkInterval <= 1 then
checkLoopFrames = checkLoopFrames * 2
end
checkInterval = ceil(checkLoopFrames/constructors)
end
end
if structure[unitID] then
deregisterStructure(unitID)
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:UnitCreated(unitID, unitDefID, teamID)
if spGetUnitIsDead(unitID) then
return
end
local ud = UnitDefs[unitDefID]
-- add terraform commands to builders
if terraformUnitDefIDs[unitDefID] and not(GG.terraformRequiresUnlock and not GG.terraformUnlocked[teamID]) then
for _, cmdDesc in ipairs(cmdDescsArray) do
spInsertUnitCmdDesc(unitID, cmdDesc)
end
local aTeam = spGetUnitAllyTeam(unitID)
constructors = constructors + 1
constructorTable[constructors] = unitID
constructor[unitID] = {allyTeam = aTeam, index = constructors}
checkInterval = ceil(checkLoopFrames/constructors)
end
-- add structure to structure table
if (ud.isBuilding == true or ud.maxAcc == 0) and (not ud.customParams.mobilebuilding) then
local ux, uy, uz = spGetUnitPosition(unitID)
ux = floor((ux+4)/8)*8
uz = floor((uz+4)/8)*8
local face = spGetUnitBuildFacing(unitID)
local xsize = ud.xsize*4
local ysize = (ud.zsize or ud.ysize)*4
structureCount = structureCount + 1
if ((face == 0) or(face == 2)) then
structure[unitID] = { x = ux, z = uz , h = spGetGroundHeight(ux, uz), def = ud,
minx = ux-xsize, minz = uz-ysize, maxx = ux+xsize, maxz = uz+ysize, area = {}, index = structureCount}
else
structure[unitID] = { x = ux, z = uz , h = spGetGroundHeight(ux, uz), def = ud,
minx = ux-ysize, minz = uz-xsize, maxx = ux+ysize, maxz = uz+xsize, area = {}, index = structureCount}
end
for i = structure[unitID].minx, structure[unitID].maxx, 8 do
structure[unitID].area[i] = {}
if not structureAreaMap[i] then
structureAreaMap[i] = {}
end
for j = structure[unitID].minz, structure[unitID].maxz, 8 do
structure[unitID].area[i][j] = true
if structureAreaMap[i][j] then
structureAreaMap[i][j] = structureAreaMap[i][j] + 1
else
structureAreaMap[i][j] = 1
end
end
end
structureTable[structureCount] = unitID
-- slow update for terrain checking
if not structureCheckFrame[currentCheckFrame] then
structureCheckFrame[currentCheckFrame] = {count = 0, unit = {}}
end
structureCheckFrame[currentCheckFrame].count = structureCheckFrame[currentCheckFrame].count + 1
structureCheckFrame[currentCheckFrame].unit[structureCheckFrame[currentCheckFrame].count] = unitID
structure[unitID].frame = currentCheckFrame
structure[unitID].frameIndex = structureCheckFrame[currentCheckFrame].count
currentCheckFrame = currentCheckFrame + 1
if currentCheckFrame > structureCheckLoopFrames then
currentCheckFrame = 0
end
-- check if the building is on terraform
for i = 1, terraformOrders do
if (structure[unitID].minx < terraformOrder[i].border.right and
structure[unitID].maxx > terraformOrder[i].border.left and
structure[unitID].minz < terraformOrder[i].border.bottom and
structure[unitID].maxz> terraformOrder[i].border.top) then
for j = 1, terraformOrder[i].indexes do
local oid = terraformUnitTable[terraformOrder[i].index[j]]
if (structure[unitID].minx < terraformUnit[oid].border.right and
structure[unitID].maxx > terraformUnit[oid].border.left and
structure[unitID].minz < terraformUnit[oid].border.bottom and
structure[unitID].maxz > terraformUnit[oid].border.top) then
structure[unitID].checkAtDeath = true
local recalc = false
local area = terraformUnit[oid].area
for k = 1, terraformUnit[oid].points do
local point = terraformUnit[oid].point[k]
local x, z = point.x, point.z
if structure[unitID].area[x] and structure[unitID].area[x][z] then
terraformUnit[oid].point[k].diffHeight = 0.0001
terraformUnit[oid].point[k].structure = true
if area[x] and area[x][z] then
area[x][z] = nil
end
recalc = true
end
end
if recalc then
updateTerraformCost(oid)
updateTerraformEdgePoints(oid)
end
end
end
end
end
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Initialise, check modoptions and register command
local TerraformFunctions = {}
function TerraformFunctions.ForceTerraformCompletion(pregame)
DoTerraformUpdate(Spring.GetGameFrame(), true)
if pregame then
-- gadget:UnsyncedHeightMapUpdate seems to not be called pregame.
GG.TerrainTexture.UpdateAll()
end
end
function TerraformFunctions.TerraformArea(terraform_type, point, pointCount, terraformHeight, unit, constructorCount, teamID, volumeSelection, shift, commandX, commandZ, commandTag, disableForceCompletion)
TerraformArea(terraform_type, point, pointCount, terraformHeight, unit, constructorCount, teamID, volumeSelection, shift, commandX, commandZ, commandTag, disableForceCompletion)
end
function TerraformFunctions.TerraformWall(terraform_type, point, pointCount, terraformHeight, unit, constructorCount, teamID, volumeSelection, shift, commandX, commandZ, commandTag, disableForceCompletion)
TerraformWall(terraform_type, point, pointCount, terraformHeight, unit, constructorCount, teamID, volumeSelection, shift, commandX, commandZ, commandTag, disableForceCompletion)
end
function TerraformFunctions.TerraformRamp(startX, startY, startZ, endX, endY, endZ, width, unit, constructorCount,teamID, volumeSelection, shift, commandX, commandZ, commandTag, disableForceCompletion)
TerraformRamp(startX, startY, startZ, endX, endY, endZ, width, unit, constructorCount,teamID, volumeSelection, shift, commandX, commandZ, commandTag, disableForceCompletion)
end
function TerraformFunctions.SetStructureHeight(unitID, height)
if structure[unitID] then
structure[unitID].h = height
end
end
function gadget:Initialize()
gadgetHandler:RegisterCMDID(CMD_TERRAFORM_INTERNAL)
local terraformColor = {0.7, 0.75, 0, 0.7}
Spring.SetCustomCommandDrawData(CMD_RAMP, "Ramp", terraformColor, false)
Spring.SetCustomCommandDrawData(CMD_LEVEL, "Level", terraformColor, false)
Spring.SetCustomCommandDrawData(CMD_RAISE, "Raise", terraformColor, false)
Spring.SetCustomCommandDrawData(CMD_SMOOTH, "Smooth", terraformColor, false)
Spring.SetCustomCommandDrawData(CMD_RESTORE, "Restore2", terraformColor, false)
Spring.AssignMouseCursor("Ramp", "cursorRamp", true, true)
Spring.AssignMouseCursor("Level", "cursorLevel", true, true)
Spring.AssignMouseCursor("Raise", "cursorRaise", true, true)
Spring.AssignMouseCursor("Smooth", "cursorSmooth", true, true)
Spring.AssignMouseCursor("Restore2", "cursorRestore2", true, true)
gadgetHandler:RegisterCMDID(CMD_RAMP)
gadgetHandler:RegisterCMDID(CMD_LEVEL)
gadgetHandler:RegisterCMDID(CMD_RAISE)
gadgetHandler:RegisterCMDID(CMD_SMOOTH)
gadgetHandler:RegisterCMDID(CMD_RESTORE)
GG.Terraform = TerraformFunctions
for _, unitID in ipairs(Spring.GetAllUnits()) do
local unitDefID = Spring.GetUnitDefID(unitID)
local teamID = spGetUnitTeam(unitID)
gadget:UnitCreated(unitID, unitDefID, teamID)
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Save/Load
function gadget:Load(zip)
for _, unitID in ipairs(Spring.GetAllUnits()) do
if Spring.GetUnitDefID(unitID) == terraunitDefID then
spDestroyUnit(unitID)
end
end
end
--------------------------------------------------------------------------------
-- SYNCED
--------------------------------------------------------------------------------
else
--------------------------------------------------------------------------------
-- UNSYNCED
--------------------------------------------------------------------------------
local terraunitDefID = UnitDefNames["terraunit"].id
local terraUnits = {}
function gadget:Initialize()
for _, unitID in ipairs(Spring.GetAllUnits()) do
local unitDefID = Spring.GetUnitDefID(unitID)
local teamID = Spring.GetUnitTeam(unitID)
gadget:UnitCreated(unitID, unitDefID, teamID)
end
end
function gadget:UnitCreated(unitID, unitDefID, teamID)
if unitDefID == terraunitDefID then
terraUnits[unitID] = true
Spring.UnitRendering.SetUnitLuaDraw(unitID, true)
end
end
function gadget:UnitDestroyed(unitID, unitDefID)
if terraUnits[unitID] then
terraUnits[unitID] = nil
end
end
function gadget:DrawUnit(unitID, drawMode)
if terraUnits[unitID] then
return true --suppress engine drawing
end
end
--------------------------------------------------------------------------------
-- UNSYNCED
--------------------------------------------------------------------------------
end | gpl-2.0 |
AresTao/darkstar | scripts/zones/Ilrusi_Atoll/npcs/Treasure_Coffer.lua | 17 | 1898 | -----------------------------------
-- Area:
-- NPC: Treasure Coffer
-- @zone illrusi atoll
-- @pos
-----------------------------------
package.loaded["scripts/zones/Ilrusi_Atoll/TextIDs"] = nil;
package.loaded["scripts/globals/bcnm"] = nil;
-------------------------------------
require("scripts/globals/bcnm");
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Ilrusi_Atoll/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(CHEST);
local npcID = npc:getID();
local correctcofferID = GetServerVariable("correctcoffer");
print(npcID);
print(correctcofferID);
if (npcID == correctcofferID) then --correct coffer ??
player:messageSpecial( GOLDEN);
if (player:getCurrentMission(ASSAULT)==GOLDEN_SALVAGE) then
player:completeMission(ASSAULT,GOLDEN_SALVAGE);
end
GetNPCByID(17002654):setStatus(0);--spawn Ancient_Lockbox
local ID;
for ID=17002505,17002516,1 do
if (GetMobAction(ID) > 0) then DespawnMob(npcID);printf("mobdespawn: %u",ID); end--despawn mimic
end
GetNPCByID(npcID):setAnimation(89);--coffer open anim
else
SpawnMob(npcID);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
AresTao/darkstar | scripts/zones/West_Sarutabaruta/npcs/Stone_Monument.lua | 32 | 1299 | -----------------------------------
-- Area: West Sarutabaruta
-- NPC: Stone Monument
-- Involved in quest "An Explorer's Footsteps"
-- @pos -205.593 -23.210 -119.670 115
-----------------------------------
package.loaded["scripts/zones/West_Sarutabaruta/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/West_Sarutabaruta/TextIDs");
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0384);
end;
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 1 and trade:hasItemQty(571,1)) then
player:tradeComplete();
player:addItem(570);
player:messageSpecial(ITEM_OBTAINED,570);
player:setVar("anExplorer-CurrentTablet",0x00400);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
hsk81/google-diff-match-patch | lua/diff_match_patch.lua | 265 | 73869 | --[[
* Diff Match and Patch
*
* Copyright 2006 Google Inc.
* http://code.google.com/p/google-diff-match-patch/
*
* Based on the JavaScript implementation by Neil Fraser.
* Ported to Lua by Duncan Cross.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
--]]
--[[
-- Lua 5.1 and earlier requires the external BitOp library.
-- This library is built-in from Lua 5.2 and later as 'bit32'.
require 'bit' -- <http://bitop.luajit.org/>
local band, bor, lshift
= bit.band, bit.bor, bit.lshift
--]]
local band, bor, lshift
= bit32.band, bit32.bor, bit32.lshift
local type, setmetatable, ipairs, select
= type, setmetatable, ipairs, select
local unpack, tonumber, error
= unpack, tonumber, error
local strsub, strbyte, strchar, gmatch, gsub
= string.sub, string.byte, string.char, string.gmatch, string.gsub
local strmatch, strfind, strformat
= string.match, string.find, string.format
local tinsert, tremove, tconcat
= table.insert, table.remove, table.concat
local max, min, floor, ceil, abs
= math.max, math.min, math.floor, math.ceil, math.abs
local clock = os.clock
-- Utility functions.
local percentEncode_pattern = '[^A-Za-z0-9%-=;\',./~!@#$%&*%(%)_%+ %?]'
local function percentEncode_replace(v)
return strformat('%%%02X', strbyte(v))
end
local function tsplice(t, idx, deletions, ...)
local insertions = select('#', ...)
for i = 1, deletions do
tremove(t, idx)
end
for i = insertions, 1, -1 do
-- do not remove parentheses around select
tinsert(t, idx, (select(i, ...)))
end
end
local function strelement(str, i)
return strsub(str, i, i)
end
local function indexOf(a, b, start)
if (#b == 0) then
return nil
end
return strfind(a, b, start, true)
end
local htmlEncode_pattern = '[&<>\n]'
local htmlEncode_replace = {
['&'] = '&', ['<'] = '<', ['>'] = '>', ['\n'] = '¶<br>'
}
-- Public API Functions
-- (Exported at the end of the script)
local diff_main,
diff_cleanupSemantic,
diff_cleanupEfficiency,
diff_levenshtein,
diff_prettyHtml
local match_main
local patch_make,
patch_toText,
patch_fromText,
patch_apply
--[[
* The data structure representing a diff is an array of tuples:
* {{DIFF_DELETE, 'Hello'}, {DIFF_INSERT, 'Goodbye'}, {DIFF_EQUAL, ' world.'}}
* which means: delete 'Hello', add 'Goodbye' and keep ' world.'
--]]
local DIFF_DELETE = -1
local DIFF_INSERT = 1
local DIFF_EQUAL = 0
-- Number of seconds to map a diff before giving up (0 for infinity).
local Diff_Timeout = 1.0
-- Cost of an empty edit operation in terms of edit characters.
local Diff_EditCost = 4
-- At what point is no match declared (0.0 = perfection, 1.0 = very loose).
local Match_Threshold = 0.5
-- How far to search for a match (0 = exact location, 1000+ = broad match).
-- A match this many characters away from the expected location will add
-- 1.0 to the score (0.0 is a perfect match).
local Match_Distance = 1000
-- When deleting a large block of text (over ~64 characters), how close do
-- the contents have to be to match the expected contents. (0.0 = perfection,
-- 1.0 = very loose). Note that Match_Threshold controls how closely the
-- end points of a delete need to match.
local Patch_DeleteThreshold = 0.5
-- Chunk size for context length.
local Patch_Margin = 4
-- The number of bits in an int.
local Match_MaxBits = 32
function settings(new)
if new then
Diff_Timeout = new.Diff_Timeout or Diff_Timeout
Diff_EditCost = new.Diff_EditCost or Diff_EditCost
Match_Threshold = new.Match_Threshold or Match_Threshold
Match_Distance = new.Match_Distance or Match_Distance
Patch_DeleteThreshold = new.Patch_DeleteThreshold or Patch_DeleteThreshold
Patch_Margin = new.Patch_Margin or Patch_Margin
Match_MaxBits = new.Match_MaxBits or Match_MaxBits
else
return {
Diff_Timeout = Diff_Timeout;
Diff_EditCost = Diff_EditCost;
Match_Threshold = Match_Threshold;
Match_Distance = Match_Distance;
Patch_DeleteThreshold = Patch_DeleteThreshold;
Patch_Margin = Patch_Margin;
Match_MaxBits = Match_MaxBits;
}
end
end
-- ---------------------------------------------------------------------------
-- DIFF API
-- ---------------------------------------------------------------------------
-- The private diff functions
local _diff_compute,
_diff_bisect,
_diff_halfMatchI,
_diff_halfMatch,
_diff_cleanupSemanticScore,
_diff_cleanupSemanticLossless,
_diff_cleanupMerge,
_diff_commonPrefix,
_diff_commonSuffix,
_diff_commonOverlap,
_diff_xIndex,
_diff_text1,
_diff_text2,
_diff_toDelta,
_diff_fromDelta
--[[
* Find the differences between two texts. Simplifies the problem by stripping
* any common prefix or suffix off the texts before diffing.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean} opt_checklines Has no effect in Lua.
* @param {number} opt_deadline Optional time when the diff should be complete
* by. Used internally for recursive calls. Users should set DiffTimeout
* instead.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
--]]
function diff_main(text1, text2, opt_checklines, opt_deadline)
-- Set a deadline by which time the diff must be complete.
if opt_deadline == nil then
if Diff_Timeout <= 0 then
opt_deadline = 2 ^ 31
else
opt_deadline = clock() + Diff_Timeout
end
end
local deadline = opt_deadline
-- Check for null inputs.
if text1 == nil or text1 == nil then
error('Null inputs. (diff_main)')
end
-- Check for equality (speedup).
if text1 == text2 then
if #text1 > 0 then
return {{DIFF_EQUAL, text1}}
end
return {}
end
-- LUANOTE: Due to the lack of Unicode support, Lua is incapable of
-- implementing the line-mode speedup.
local checklines = false
-- Trim off common prefix (speedup).
local commonlength = _diff_commonPrefix(text1, text2)
local commonprefix
if commonlength > 0 then
commonprefix = strsub(text1, 1, commonlength)
text1 = strsub(text1, commonlength + 1)
text2 = strsub(text2, commonlength + 1)
end
-- Trim off common suffix (speedup).
commonlength = _diff_commonSuffix(text1, text2)
local commonsuffix
if commonlength > 0 then
commonsuffix = strsub(text1, -commonlength)
text1 = strsub(text1, 1, -commonlength - 1)
text2 = strsub(text2, 1, -commonlength - 1)
end
-- Compute the diff on the middle block.
local diffs = _diff_compute(text1, text2, checklines, deadline)
-- Restore the prefix and suffix.
if commonprefix then
tinsert(diffs, 1, {DIFF_EQUAL, commonprefix})
end
if commonsuffix then
diffs[#diffs + 1] = {DIFF_EQUAL, commonsuffix}
end
_diff_cleanupMerge(diffs)
return diffs
end
--[[
* Reduce the number of edits by eliminating semantically trivial equalities.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function diff_cleanupSemantic(diffs)
local changes = false
local equalities = {} -- Stack of indices where equalities are found.
local equalitiesLength = 0 -- Keeping our own length var is faster.
local lastequality = nil
-- Always equal to diffs[equalities[equalitiesLength]][2]
local pointer = 1 -- Index of current position.
-- Number of characters that changed prior to the equality.
local length_insertions1 = 0
local length_deletions1 = 0
-- Number of characters that changed after the equality.
local length_insertions2 = 0
local length_deletions2 = 0
while diffs[pointer] do
if diffs[pointer][1] == DIFF_EQUAL then -- Equality found.
equalitiesLength = equalitiesLength + 1
equalities[equalitiesLength] = pointer
length_insertions1 = length_insertions2
length_deletions1 = length_deletions2
length_insertions2 = 0
length_deletions2 = 0
lastequality = diffs[pointer][2]
else -- An insertion or deletion.
if diffs[pointer][1] == DIFF_INSERT then
length_insertions2 = length_insertions2 + #(diffs[pointer][2])
else
length_deletions2 = length_deletions2 + #(diffs[pointer][2])
end
-- Eliminate an equality that is smaller or equal to the edits on both
-- sides of it.
if lastequality
and (#lastequality <= max(length_insertions1, length_deletions1))
and (#lastequality <= max(length_insertions2, length_deletions2)) then
-- Duplicate record.
tinsert(diffs, equalities[equalitiesLength],
{DIFF_DELETE, lastequality})
-- Change second copy to insert.
diffs[equalities[equalitiesLength] + 1][1] = DIFF_INSERT
-- Throw away the equality we just deleted.
equalitiesLength = equalitiesLength - 1
-- Throw away the previous equality (it needs to be reevaluated).
equalitiesLength = equalitiesLength - 1
pointer = (equalitiesLength > 0) and equalities[equalitiesLength] or 0
length_insertions1, length_deletions1 = 0, 0 -- Reset the counters.
length_insertions2, length_deletions2 = 0, 0
lastequality = nil
changes = true
end
end
pointer = pointer + 1
end
-- Normalize the diff.
if changes then
_diff_cleanupMerge(diffs)
end
_diff_cleanupSemanticLossless(diffs)
-- Find any overlaps between deletions and insertions.
-- e.g: <del>abcxxx</del><ins>xxxdef</ins>
-- -> <del>abc</del>xxx<ins>def</ins>
-- e.g: <del>xxxabc</del><ins>defxxx</ins>
-- -> <ins>def</ins>xxx<del>abc</del>
-- Only extract an overlap if it is as big as the edit ahead or behind it.
pointer = 2
while diffs[pointer] do
if (diffs[pointer - 1][1] == DIFF_DELETE and
diffs[pointer][1] == DIFF_INSERT) then
local deletion = diffs[pointer - 1][2]
local insertion = diffs[pointer][2]
local overlap_length1 = _diff_commonOverlap(deletion, insertion)
local overlap_length2 = _diff_commonOverlap(insertion, deletion)
if (overlap_length1 >= overlap_length2) then
if (overlap_length1 >= #deletion / 2 or
overlap_length1 >= #insertion / 2) then
-- Overlap found. Insert an equality and trim the surrounding edits.
tinsert(diffs, pointer,
{DIFF_EQUAL, strsub(insertion, 1, overlap_length1)})
diffs[pointer - 1][2] =
strsub(deletion, 1, #deletion - overlap_length1)
diffs[pointer + 1][2] = strsub(insertion, overlap_length1 + 1)
pointer = pointer + 1
end
else
if (overlap_length2 >= #deletion / 2 or
overlap_length2 >= #insertion / 2) then
-- Reverse overlap found.
-- Insert an equality and swap and trim the surrounding edits.
tinsert(diffs, pointer,
{DIFF_EQUAL, strsub(deletion, 1, overlap_length2)})
diffs[pointer - 1] = {DIFF_INSERT,
strsub(insertion, 1, #insertion - overlap_length2)}
diffs[pointer + 1] = {DIFF_DELETE,
strsub(deletion, overlap_length2 + 1)}
pointer = pointer + 1
end
end
pointer = pointer + 1
end
pointer = pointer + 1
end
end
--[[
* Reduce the number of edits by eliminating operationally trivial equalities.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function diff_cleanupEfficiency(diffs)
local changes = false
-- Stack of indices where equalities are found.
local equalities = {}
-- Keeping our own length var is faster.
local equalitiesLength = 0
-- Always equal to diffs[equalities[equalitiesLength]][2]
local lastequality = nil
-- Index of current position.
local pointer = 1
-- The following four are really booleans but are stored as numbers because
-- they are used at one point like this:
--
-- (pre_ins + pre_del + post_ins + post_del) == 3
--
-- ...i.e. checking that 3 of them are true and 1 of them is false.
-- Is there an insertion operation before the last equality.
local pre_ins = 0
-- Is there a deletion operation before the last equality.
local pre_del = 0
-- Is there an insertion operation after the last equality.
local post_ins = 0
-- Is there a deletion operation after the last equality.
local post_del = 0
while diffs[pointer] do
if diffs[pointer][1] == DIFF_EQUAL then -- Equality found.
local diffText = diffs[pointer][2]
if (#diffText < Diff_EditCost) and (post_ins == 1 or post_del == 1) then
-- Candidate found.
equalitiesLength = equalitiesLength + 1
equalities[equalitiesLength] = pointer
pre_ins, pre_del = post_ins, post_del
lastequality = diffText
else
-- Not a candidate, and can never become one.
equalitiesLength = 0
lastequality = nil
end
post_ins, post_del = 0, 0
else -- An insertion or deletion.
if diffs[pointer][1] == DIFF_DELETE then
post_del = 1
else
post_ins = 1
end
--[[
* Five types to be split:
* <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
* <ins>A</ins>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<ins>C</ins>
* <ins>A</del>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<del>C</del>
--]]
if lastequality and (
(pre_ins+pre_del+post_ins+post_del == 4)
or
(
(#lastequality < Diff_EditCost / 2)
and
(pre_ins+pre_del+post_ins+post_del == 3)
)) then
-- Duplicate record.
tinsert(diffs, equalities[equalitiesLength],
{DIFF_DELETE, lastequality})
-- Change second copy to insert.
diffs[equalities[equalitiesLength] + 1][1] = DIFF_INSERT
-- Throw away the equality we just deleted.
equalitiesLength = equalitiesLength - 1
lastequality = nil
if (pre_ins == 1) and (pre_del == 1) then
-- No changes made which could affect previous entry, keep going.
post_ins, post_del = 1, 1
equalitiesLength = 0
else
-- Throw away the previous equality.
equalitiesLength = equalitiesLength - 1
pointer = (equalitiesLength > 0) and equalities[equalitiesLength] or 0
post_ins, post_del = 0, 0
end
changes = true
end
end
pointer = pointer + 1
end
if changes then
_diff_cleanupMerge(diffs)
end
end
--[[
* Compute the Levenshtein distance; the number of inserted, deleted or
* substituted characters.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {number} Number of changes.
--]]
function diff_levenshtein(diffs)
local levenshtein = 0
local insertions, deletions = 0, 0
for x, diff in ipairs(diffs) do
local op, data = diff[1], diff[2]
if (op == DIFF_INSERT) then
insertions = insertions + #data
elseif (op == DIFF_DELETE) then
deletions = deletions + #data
elseif (op == DIFF_EQUAL) then
-- A deletion and an insertion is one substitution.
levenshtein = levenshtein + max(insertions, deletions)
insertions = 0
deletions = 0
end
end
levenshtein = levenshtein + max(insertions, deletions)
return levenshtein
end
--[[
* Convert a diff array into a pretty HTML report.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} HTML representation.
--]]
function diff_prettyHtml(diffs)
local html = {}
for x, diff in ipairs(diffs) do
local op = diff[1] -- Operation (insert, delete, equal)
local data = diff[2] -- Text of change.
local text = gsub(data, htmlEncode_pattern, htmlEncode_replace)
if op == DIFF_INSERT then
html[x] = '<ins style="background:#e6ffe6;">' .. text .. '</ins>'
elseif op == DIFF_DELETE then
html[x] = '<del style="background:#ffe6e6;">' .. text .. '</del>'
elseif op == DIFF_EQUAL then
html[x] = '<span>' .. text .. '</span>'
end
end
return tconcat(html)
end
-- ---------------------------------------------------------------------------
-- UNOFFICIAL/PRIVATE DIFF FUNCTIONS
-- ---------------------------------------------------------------------------
--[[
* Find the differences between two texts. Assumes that the texts do not
* have any common prefix or suffix.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean} checklines Has no effect in Lua.
* @param {number} deadline Time when the diff should be complete by.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @private
--]]
function _diff_compute(text1, text2, checklines, deadline)
if #text1 == 0 then
-- Just add some text (speedup).
return {{DIFF_INSERT, text2}}
end
if #text2 == 0 then
-- Just delete some text (speedup).
return {{DIFF_DELETE, text1}}
end
local diffs
local longtext = (#text1 > #text2) and text1 or text2
local shorttext = (#text1 > #text2) and text2 or text1
local i = indexOf(longtext, shorttext)
if i ~= nil then
-- Shorter text is inside the longer text (speedup).
diffs = {
{DIFF_INSERT, strsub(longtext, 1, i - 1)},
{DIFF_EQUAL, shorttext},
{DIFF_INSERT, strsub(longtext, i + #shorttext)}
}
-- Swap insertions for deletions if diff is reversed.
if #text1 > #text2 then
diffs[1][1], diffs[3][1] = DIFF_DELETE, DIFF_DELETE
end
return diffs
end
if #shorttext == 1 then
-- Single character string.
-- After the previous speedup, the character can't be an equality.
return {{DIFF_DELETE, text1}, {DIFF_INSERT, text2}}
end
-- Check to see if the problem can be split in two.
do
local
text1_a, text1_b,
text2_a, text2_b,
mid_common = _diff_halfMatch(text1, text2)
if text1_a then
-- A half-match was found, sort out the return data.
-- Send both pairs off for separate processing.
local diffs_a = diff_main(text1_a, text2_a, checklines, deadline)
local diffs_b = diff_main(text1_b, text2_b, checklines, deadline)
-- Merge the results.
local diffs_a_len = #diffs_a
diffs = diffs_a
diffs[diffs_a_len + 1] = {DIFF_EQUAL, mid_common}
for i, b_diff in ipairs(diffs_b) do
diffs[diffs_a_len + 1 + i] = b_diff
end
return diffs
end
end
return _diff_bisect(text1, text2, deadline)
end
--[[
* Find the 'middle snake' of a diff, split the problem in two
* and return the recursively constructed diff.
* See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} deadline Time at which to bail if not yet complete.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @private
--]]
function _diff_bisect(text1, text2, deadline)
-- Cache the text lengths to prevent multiple calls.
local text1_length = #text1
local text2_length = #text2
local _sub, _element
local max_d = ceil((text1_length + text2_length) / 2)
local v_offset = max_d
local v_length = 2 * max_d
local v1 = {}
local v2 = {}
-- Setting all elements to -1 is faster in Lua than mixing integers and nil.
for x = 0, v_length - 1 do
v1[x] = -1
v2[x] = -1
end
v1[v_offset + 1] = 0
v2[v_offset + 1] = 0
local delta = text1_length - text2_length
-- If the total number of characters is odd, then
-- the front path will collide with the reverse path.
local front = (delta % 2 ~= 0)
-- Offsets for start and end of k loop.
-- Prevents mapping of space beyond the grid.
local k1start = 0
local k1end = 0
local k2start = 0
local k2end = 0
for d = 0, max_d - 1 do
-- Bail out if deadline is reached.
if clock() > deadline then
break
end
-- Walk the front path one step.
for k1 = -d + k1start, d - k1end, 2 do
local k1_offset = v_offset + k1
local x1
if (k1 == -d) or ((k1 ~= d) and
(v1[k1_offset - 1] < v1[k1_offset + 1])) then
x1 = v1[k1_offset + 1]
else
x1 = v1[k1_offset - 1] + 1
end
local y1 = x1 - k1
while (x1 <= text1_length) and (y1 <= text2_length)
and (strelement(text1, x1) == strelement(text2, y1)) do
x1 = x1 + 1
y1 = y1 + 1
end
v1[k1_offset] = x1
if x1 > text1_length + 1 then
-- Ran off the right of the graph.
k1end = k1end + 2
elseif y1 > text2_length + 1 then
-- Ran off the bottom of the graph.
k1start = k1start + 2
elseif front then
local k2_offset = v_offset + delta - k1
if k2_offset >= 0 and k2_offset < v_length and v2[k2_offset] ~= -1 then
-- Mirror x2 onto top-left coordinate system.
local x2 = text1_length - v2[k2_offset] + 1
if x1 > x2 then
-- Overlap detected.
return _diff_bisectSplit(text1, text2, x1, y1, deadline)
end
end
end
end
-- Walk the reverse path one step.
for k2 = -d + k2start, d - k2end, 2 do
local k2_offset = v_offset + k2
local x2
if (k2 == -d) or ((k2 ~= d) and
(v2[k2_offset - 1] < v2[k2_offset + 1])) then
x2 = v2[k2_offset + 1]
else
x2 = v2[k2_offset - 1] + 1
end
local y2 = x2 - k2
while (x2 <= text1_length) and (y2 <= text2_length)
and (strelement(text1, -x2) == strelement(text2, -y2)) do
x2 = x2 + 1
y2 = y2 + 1
end
v2[k2_offset] = x2
if x2 > text1_length + 1 then
-- Ran off the left of the graph.
k2end = k2end + 2
elseif y2 > text2_length + 1 then
-- Ran off the top of the graph.
k2start = k2start + 2
elseif not front then
local k1_offset = v_offset + delta - k2
if k1_offset >= 0 and k1_offset < v_length and v1[k1_offset] ~= -1 then
local x1 = v1[k1_offset]
local y1 = v_offset + x1 - k1_offset
-- Mirror x2 onto top-left coordinate system.
x2 = text1_length - x2 + 1
if x1 > x2 then
-- Overlap detected.
return _diff_bisectSplit(text1, text2, x1, y1, deadline)
end
end
end
end
end
-- Diff took too long and hit the deadline or
-- number of diffs equals number of characters, no commonality at all.
return {{DIFF_DELETE, text1}, {DIFF_INSERT, text2}}
end
--[[
* Given the location of the 'middle snake', split the diff in two parts
* and recurse.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} x Index of split point in text1.
* @param {number} y Index of split point in text2.
* @param {number} deadline Time at which to bail if not yet complete.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @private
--]]
function _diff_bisectSplit(text1, text2, x, y, deadline)
local text1a = strsub(text1, 1, x - 1)
local text2a = strsub(text2, 1, y - 1)
local text1b = strsub(text1, x)
local text2b = strsub(text2, y)
-- Compute both diffs serially.
local diffs = diff_main(text1a, text2a, false, deadline)
local diffsb = diff_main(text1b, text2b, false, deadline)
local diffs_len = #diffs
for i, v in ipairs(diffsb) do
diffs[diffs_len + i] = v
end
return diffs
end
--[[
* Determine the common prefix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the start of each
* string.
--]]
function _diff_commonPrefix(text1, text2)
-- Quick check for common null cases.
if (#text1 == 0) or (#text2 == 0) or (strbyte(text1, 1) ~= strbyte(text2, 1))
then
return 0
end
-- Binary search.
-- Performance analysis: http://neil.fraser.name/news/2007/10/09/
local pointermin = 1
local pointermax = min(#text1, #text2)
local pointermid = pointermax
local pointerstart = 1
while (pointermin < pointermid) do
if (strsub(text1, pointerstart, pointermid)
== strsub(text2, pointerstart, pointermid)) then
pointermin = pointermid
pointerstart = pointermin
else
pointermax = pointermid
end
pointermid = floor(pointermin + (pointermax - pointermin) / 2)
end
return pointermid
end
--[[
* Determine the common suffix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of each string.
--]]
function _diff_commonSuffix(text1, text2)
-- Quick check for common null cases.
if (#text1 == 0) or (#text2 == 0)
or (strbyte(text1, -1) ~= strbyte(text2, -1)) then
return 0
end
-- Binary search.
-- Performance analysis: http://neil.fraser.name/news/2007/10/09/
local pointermin = 1
local pointermax = min(#text1, #text2)
local pointermid = pointermax
local pointerend = 1
while (pointermin < pointermid) do
if (strsub(text1, -pointermid, -pointerend)
== strsub(text2, -pointermid, -pointerend)) then
pointermin = pointermid
pointerend = pointermin
else
pointermax = pointermid
end
pointermid = floor(pointermin + (pointermax - pointermin) / 2)
end
return pointermid
end
--[[
* Determine if the suffix of one string is the prefix of another.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of the first
* string and the start of the second string.
* @private
--]]
function _diff_commonOverlap(text1, text2)
-- Cache the text lengths to prevent multiple calls.
local text1_length = #text1
local text2_length = #text2
-- Eliminate the null case.
if text1_length == 0 or text2_length == 0 then
return 0
end
-- Truncate the longer string.
if text1_length > text2_length then
text1 = strsub(text1, text1_length - text2_length + 1)
elseif text1_length < text2_length then
text2 = strsub(text2, 1, text1_length)
end
local text_length = min(text1_length, text2_length)
-- Quick check for the worst case.
if text1 == text2 then
return text_length
end
-- Start by looking for a single character match
-- and increase length until no match is found.
-- Performance analysis: http://neil.fraser.name/news/2010/11/04/
local best = 0
local length = 1
while true do
local pattern = strsub(text1, text_length - length + 1)
local found = strfind(text2, pattern, 1, true)
if found == nil then
return best
end
length = length + found - 1
if found == 1 or strsub(text1, text_length - length + 1) ==
strsub(text2, 1, length) then
best = length
length = length + 1
end
end
end
--[[
* Does a substring of shorttext exist within longtext such that the substring
* is at least half the length of longtext?
* This speedup can produce non-minimal diffs.
* Closure, but does not reference any external variables.
* @param {string} longtext Longer string.
* @param {string} shorttext Shorter string.
* @param {number} i Start index of quarter length substring within longtext.
* @return {?Array.<string>} Five element Array, containing the prefix of
* longtext, the suffix of longtext, the prefix of shorttext, the suffix
* of shorttext and the common middle. Or nil if there was no match.
* @private
--]]
function _diff_halfMatchI(longtext, shorttext, i)
-- Start with a 1/4 length substring at position i as a seed.
local seed = strsub(longtext, i, i + floor(#longtext / 4))
local j = 0 -- LUANOTE: do not change to 1, was originally -1
local best_common = ''
local best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b
while true do
j = indexOf(shorttext, seed, j + 1)
if (j == nil) then
break
end
local prefixLength = _diff_commonPrefix(strsub(longtext, i),
strsub(shorttext, j))
local suffixLength = _diff_commonSuffix(strsub(longtext, 1, i - 1),
strsub(shorttext, 1, j - 1))
if #best_common < suffixLength + prefixLength then
best_common = strsub(shorttext, j - suffixLength, j - 1)
.. strsub(shorttext, j, j + prefixLength - 1)
best_longtext_a = strsub(longtext, 1, i - suffixLength - 1)
best_longtext_b = strsub(longtext, i + prefixLength)
best_shorttext_a = strsub(shorttext, 1, j - suffixLength - 1)
best_shorttext_b = strsub(shorttext, j + prefixLength)
end
end
if #best_common * 2 >= #longtext then
return {best_longtext_a, best_longtext_b,
best_shorttext_a, best_shorttext_b, best_common}
else
return nil
end
end
--[[
* Do the two texts share a substring which is at least half the length of the
* longer text?
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {?Array.<string>} Five element Array, containing the prefix of
* text1, the suffix of text1, the prefix of text2, the suffix of
* text2 and the common middle. Or nil if there was no match.
* @private
--]]
function _diff_halfMatch(text1, text2)
if Diff_Timeout <= 0 then
-- Don't risk returning a non-optimal diff if we have unlimited time.
return nil
end
local longtext = (#text1 > #text2) and text1 or text2
local shorttext = (#text1 > #text2) and text2 or text1
if (#longtext < 4) or (#shorttext * 2 < #longtext) then
return nil -- Pointless.
end
-- First check if the second quarter is the seed for a half-match.
local hm1 = _diff_halfMatchI(longtext, shorttext, ceil(#longtext / 4))
-- Check again based on the third quarter.
local hm2 = _diff_halfMatchI(longtext, shorttext, ceil(#longtext / 2))
local hm
if not hm1 and not hm2 then
return nil
elseif not hm2 then
hm = hm1
elseif not hm1 then
hm = hm2
else
-- Both matched. Select the longest.
hm = (#hm1[5] > #hm2[5]) and hm1 or hm2
end
-- A half-match was found, sort out the return data.
local text1_a, text1_b, text2_a, text2_b
if (#text1 > #text2) then
text1_a, text1_b = hm[1], hm[2]
text2_a, text2_b = hm[3], hm[4]
else
text2_a, text2_b = hm[1], hm[2]
text1_a, text1_b = hm[3], hm[4]
end
local mid_common = hm[5]
return text1_a, text1_b, text2_a, text2_b, mid_common
end
--[[
* Given two strings, compute a score representing whether the internal
* boundary falls on logical boundaries.
* Scores range from 6 (best) to 0 (worst).
* @param {string} one First string.
* @param {string} two Second string.
* @return {number} The score.
* @private
--]]
function _diff_cleanupSemanticScore(one, two)
if (#one == 0) or (#two == 0) then
-- Edges are the best.
return 6
end
-- Each port of this function behaves slightly differently due to
-- subtle differences in each language's definition of things like
-- 'whitespace'. Since this function's purpose is largely cosmetic,
-- the choice has been made to use each language's native features
-- rather than force total conformity.
local char1 = strsub(one, -1)
local char2 = strsub(two, 1, 1)
local nonAlphaNumeric1 = strmatch(char1, '%W')
local nonAlphaNumeric2 = strmatch(char2, '%W')
local whitespace1 = nonAlphaNumeric1 and strmatch(char1, '%s')
local whitespace2 = nonAlphaNumeric2 and strmatch(char2, '%s')
local lineBreak1 = whitespace1 and strmatch(char1, '%c')
local lineBreak2 = whitespace2 and strmatch(char2, '%c')
local blankLine1 = lineBreak1 and strmatch(one, '\n\r?\n$')
local blankLine2 = lineBreak2 and strmatch(two, '^\r?\n\r?\n')
if blankLine1 or blankLine2 then
-- Five points for blank lines.
return 5
elseif lineBreak1 or lineBreak2 then
-- Four points for line breaks.
return 4
elseif nonAlphaNumeric1 and not whitespace1 and whitespace2 then
-- Three points for end of sentences.
return 3
elseif whitespace1 or whitespace2 then
-- Two points for whitespace.
return 2
elseif nonAlphaNumeric1 or nonAlphaNumeric2 then
-- One point for non-alphanumeric.
return 1
end
return 0
end
--[[
* Look for single edits surrounded on both sides by equalities
* which can be shifted sideways to align the edit to a word boundary.
* e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function _diff_cleanupSemanticLossless(diffs)
local pointer = 2
-- Intentionally ignore the first and last element (don't need checking).
while diffs[pointer + 1] do
local prevDiff, nextDiff = diffs[pointer - 1], diffs[pointer + 1]
if (prevDiff[1] == DIFF_EQUAL) and (nextDiff[1] == DIFF_EQUAL) then
-- This is a single edit surrounded by equalities.
local diff = diffs[pointer]
local equality1 = prevDiff[2]
local edit = diff[2]
local equality2 = nextDiff[2]
-- First, shift the edit as far left as possible.
local commonOffset = _diff_commonSuffix(equality1, edit)
if commonOffset > 0 then
local commonString = strsub(edit, -commonOffset)
equality1 = strsub(equality1, 1, -commonOffset - 1)
edit = commonString .. strsub(edit, 1, -commonOffset - 1)
equality2 = commonString .. equality2
end
-- Second, step character by character right, looking for the best fit.
local bestEquality1 = equality1
local bestEdit = edit
local bestEquality2 = equality2
local bestScore = _diff_cleanupSemanticScore(equality1, edit)
+ _diff_cleanupSemanticScore(edit, equality2)
while strbyte(edit, 1) == strbyte(equality2, 1) do
equality1 = equality1 .. strsub(edit, 1, 1)
edit = strsub(edit, 2) .. strsub(equality2, 1, 1)
equality2 = strsub(equality2, 2)
local score = _diff_cleanupSemanticScore(equality1, edit)
+ _diff_cleanupSemanticScore(edit, equality2)
-- The >= encourages trailing rather than leading whitespace on edits.
if score >= bestScore then
bestScore = score
bestEquality1 = equality1
bestEdit = edit
bestEquality2 = equality2
end
end
if prevDiff[2] ~= bestEquality1 then
-- We have an improvement, save it back to the diff.
if #bestEquality1 > 0 then
diffs[pointer - 1][2] = bestEquality1
else
tremove(diffs, pointer - 1)
pointer = pointer - 1
end
diffs[pointer][2] = bestEdit
if #bestEquality2 > 0 then
diffs[pointer + 1][2] = bestEquality2
else
tremove(diffs, pointer + 1, 1)
pointer = pointer - 1
end
end
end
pointer = pointer + 1
end
end
--[[
* Reorder and merge like edit sections. Merge equalities.
* Any edit section can move as long as it doesn't cross an equality.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function _diff_cleanupMerge(diffs)
diffs[#diffs + 1] = {DIFF_EQUAL, ''} -- Add a dummy entry at the end.
local pointer = 1
local count_delete, count_insert = 0, 0
local text_delete, text_insert = '', ''
local commonlength
while diffs[pointer] do
local diff_type = diffs[pointer][1]
if diff_type == DIFF_INSERT then
count_insert = count_insert + 1
text_insert = text_insert .. diffs[pointer][2]
pointer = pointer + 1
elseif diff_type == DIFF_DELETE then
count_delete = count_delete + 1
text_delete = text_delete .. diffs[pointer][2]
pointer = pointer + 1
elseif diff_type == DIFF_EQUAL then
-- Upon reaching an equality, check for prior redundancies.
if count_delete + count_insert > 1 then
if (count_delete > 0) and (count_insert > 0) then
-- Factor out any common prefixies.
commonlength = _diff_commonPrefix(text_insert, text_delete)
if commonlength > 0 then
local back_pointer = pointer - count_delete - count_insert
if (back_pointer > 1) and (diffs[back_pointer - 1][1] == DIFF_EQUAL)
then
diffs[back_pointer - 1][2] = diffs[back_pointer - 1][2]
.. strsub(text_insert, 1, commonlength)
else
tinsert(diffs, 1,
{DIFF_EQUAL, strsub(text_insert, 1, commonlength)})
pointer = pointer + 1
end
text_insert = strsub(text_insert, commonlength + 1)
text_delete = strsub(text_delete, commonlength + 1)
end
-- Factor out any common suffixies.
commonlength = _diff_commonSuffix(text_insert, text_delete)
if commonlength ~= 0 then
diffs[pointer][2] =
strsub(text_insert, -commonlength) .. diffs[pointer][2]
text_insert = strsub(text_insert, 1, -commonlength - 1)
text_delete = strsub(text_delete, 1, -commonlength - 1)
end
end
-- Delete the offending records and add the merged ones.
if count_delete == 0 then
tsplice(diffs, pointer - count_insert,
count_insert, {DIFF_INSERT, text_insert})
elseif count_insert == 0 then
tsplice(diffs, pointer - count_delete,
count_delete, {DIFF_DELETE, text_delete})
else
tsplice(diffs, pointer - count_delete - count_insert,
count_delete + count_insert,
{DIFF_DELETE, text_delete}, {DIFF_INSERT, text_insert})
end
pointer = pointer - count_delete - count_insert
+ (count_delete>0 and 1 or 0) + (count_insert>0 and 1 or 0) + 1
elseif (pointer > 1) and (diffs[pointer - 1][1] == DIFF_EQUAL) then
-- Merge this equality with the previous one.
diffs[pointer - 1][2] = diffs[pointer - 1][2] .. diffs[pointer][2]
tremove(diffs, pointer)
else
pointer = pointer + 1
end
count_insert, count_delete = 0, 0
text_delete, text_insert = '', ''
end
end
if diffs[#diffs][2] == '' then
diffs[#diffs] = nil -- Remove the dummy entry at the end.
end
-- Second pass: look for single edits surrounded on both sides by equalities
-- which can be shifted sideways to eliminate an equality.
-- e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
local changes = false
pointer = 2
-- Intentionally ignore the first and last element (don't need checking).
while pointer < #diffs do
local prevDiff, nextDiff = diffs[pointer - 1], diffs[pointer + 1]
if (prevDiff[1] == DIFF_EQUAL) and (nextDiff[1] == DIFF_EQUAL) then
-- This is a single edit surrounded by equalities.
local diff = diffs[pointer]
local currentText = diff[2]
local prevText = prevDiff[2]
local nextText = nextDiff[2]
if strsub(currentText, -#prevText) == prevText then
-- Shift the edit over the previous equality.
diff[2] = prevText .. strsub(currentText, 1, -#prevText - 1)
nextDiff[2] = prevText .. nextDiff[2]
tremove(diffs, pointer - 1)
changes = true
elseif strsub(currentText, 1, #nextText) == nextText then
-- Shift the edit over the next equality.
prevDiff[2] = prevText .. nextText
diff[2] = strsub(currentText, #nextText + 1) .. nextText
tremove(diffs, pointer + 1)
changes = true
end
end
pointer = pointer + 1
end
-- If shifts were made, the diff needs reordering and another shift sweep.
if changes then
-- LUANOTE: no return value, but necessary to use 'return' to get
-- tail calls.
return _diff_cleanupMerge(diffs)
end
end
--[[
* loc is a location in text1, compute and return the equivalent location in
* text2.
* e.g. 'The cat' vs 'The big cat', 1->1, 5->8
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @param {number} loc Location within text1.
* @return {number} Location within text2.
--]]
function _diff_xIndex(diffs, loc)
local chars1 = 1
local chars2 = 1
local last_chars1 = 1
local last_chars2 = 1
local x
for _x, diff in ipairs(diffs) do
x = _x
if diff[1] ~= DIFF_INSERT then -- Equality or deletion.
chars1 = chars1 + #diff[2]
end
if diff[1] ~= DIFF_DELETE then -- Equality or insertion.
chars2 = chars2 + #diff[2]
end
if chars1 > loc then -- Overshot the location.
break
end
last_chars1 = chars1
last_chars2 = chars2
end
-- Was the location deleted?
if diffs[x + 1] and (diffs[x][1] == DIFF_DELETE) then
return last_chars2
end
-- Add the remaining character length.
return last_chars2 + (loc - last_chars1)
end
--[[
* Compute and return the source text (all equalities and deletions).
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} Source text.
--]]
function _diff_text1(diffs)
local text = {}
for x, diff in ipairs(diffs) do
if diff[1] ~= DIFF_INSERT then
text[#text + 1] = diff[2]
end
end
return tconcat(text)
end
--[[
* Compute and return the destination text (all equalities and insertions).
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} Destination text.
--]]
function _diff_text2(diffs)
local text = {}
for x, diff in ipairs(diffs) do
if diff[1] ~= DIFF_DELETE then
text[#text + 1] = diff[2]
end
end
return tconcat(text)
end
--[[
* Crush the diff into an encoded string which describes the operations
* required to transform text1 into text2.
* E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'.
* Operations are tab-separated. Inserted text is escaped using %xx notation.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} Delta text.
--]]
function _diff_toDelta(diffs)
local text = {}
for x, diff in ipairs(diffs) do
local op, data = diff[1], diff[2]
if op == DIFF_INSERT then
text[x] = '+' .. gsub(data, percentEncode_pattern, percentEncode_replace)
elseif op == DIFF_DELETE then
text[x] = '-' .. #data
elseif op == DIFF_EQUAL then
text[x] = '=' .. #data
end
end
return tconcat(text, '\t')
end
--[[
* Given the original text1, and an encoded string which describes the
* operations required to transform text1 into text2, compute the full diff.
* @param {string} text1 Source string for the diff.
* @param {string} delta Delta text.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @throws {Errorend If invalid input.
--]]
function _diff_fromDelta(text1, delta)
local diffs = {}
local diffsLength = 0 -- Keeping our own length var is faster
local pointer = 1 -- Cursor in text1
for token in gmatch(delta, '[^\t]+') do
-- Each token begins with a one character parameter which specifies the
-- operation of this token (delete, insert, equality).
local tokenchar, param = strsub(token, 1, 1), strsub(token, 2)
if (tokenchar == '+') then
local invalidDecode = false
local decoded = gsub(param, '%%(.?.?)',
function(c)
local n = tonumber(c, 16)
if (#c ~= 2) or (n == nil) then
invalidDecode = true
return ''
end
return strchar(n)
end)
if invalidDecode then
-- Malformed URI sequence.
error('Illegal escape in _diff_fromDelta: ' .. param)
end
diffsLength = diffsLength + 1
diffs[diffsLength] = {DIFF_INSERT, decoded}
elseif (tokenchar == '-') or (tokenchar == '=') then
local n = tonumber(param)
if (n == nil) or (n < 0) then
error('Invalid number in _diff_fromDelta: ' .. param)
end
local text = strsub(text1, pointer, pointer + n - 1)
pointer = pointer + n
if (tokenchar == '=') then
diffsLength = diffsLength + 1
diffs[diffsLength] = {DIFF_EQUAL, text}
else
diffsLength = diffsLength + 1
diffs[diffsLength] = {DIFF_DELETE, text}
end
else
error('Invalid diff operation in _diff_fromDelta: ' .. token)
end
end
if (pointer ~= #text1 + 1) then
error('Delta length (' .. (pointer - 1)
.. ') does not equal source text length (' .. #text1 .. ').')
end
return diffs
end
-- ---------------------------------------------------------------------------
-- MATCH API
-- ---------------------------------------------------------------------------
local _match_bitap, _match_alphabet
--[[
* Locate the best instance of 'pattern' in 'text' near 'loc'.
* @param {string} text The text to search.
* @param {string} pattern The pattern to search for.
* @param {number} loc The location to search around.
* @return {number} Best match index or -1.
--]]
function match_main(text, pattern, loc)
-- Check for null inputs.
if text == nil or pattern == nil or loc == nil then
error('Null inputs. (match_main)')
end
if text == pattern then
-- Shortcut (potentially not guaranteed by the algorithm)
return 1
elseif #text == 0 then
-- Nothing to match.
return -1
end
loc = max(1, min(loc, #text))
if strsub(text, loc, loc + #pattern - 1) == pattern then
-- Perfect match at the perfect spot! (Includes case of null pattern)
return loc
else
-- Do a fuzzy compare.
return _match_bitap(text, pattern, loc)
end
end
-- ---------------------------------------------------------------------------
-- UNOFFICIAL/PRIVATE MATCH FUNCTIONS
-- ---------------------------------------------------------------------------
--[[
* Initialise the alphabet for the Bitap algorithm.
* @param {string} pattern The text to encode.
* @return {Object} Hash of character locations.
* @private
--]]
function _match_alphabet(pattern)
local s = {}
local i = 0
for c in gmatch(pattern, '.') do
s[c] = bor(s[c] or 0, lshift(1, #pattern - i - 1))
i = i + 1
end
return s
end
--[[
* Locate the best instance of 'pattern' in 'text' near 'loc' using the
* Bitap algorithm.
* @param {string} text The text to search.
* @param {string} pattern The pattern to search for.
* @param {number} loc The location to search around.
* @return {number} Best match index or -1.
* @private
--]]
function _match_bitap(text, pattern, loc)
if #pattern > Match_MaxBits then
error('Pattern too long.')
end
-- Initialise the alphabet.
local s = _match_alphabet(pattern)
--[[
* Compute and return the score for a match with e errors and x location.
* Accesses loc and pattern through being a closure.
* @param {number} e Number of errors in match.
* @param {number} x Location of match.
* @return {number} Overall score for match (0.0 = good, 1.0 = bad).
* @private
--]]
local function _match_bitapScore(e, x)
local accuracy = e / #pattern
local proximity = abs(loc - x)
if (Match_Distance == 0) then
-- Dodge divide by zero error.
return (proximity == 0) and 1 or accuracy
end
return accuracy + (proximity / Match_Distance)
end
-- Highest score beyond which we give up.
local score_threshold = Match_Threshold
-- Is there a nearby exact match? (speedup)
local best_loc = indexOf(text, pattern, loc)
if best_loc then
score_threshold = min(_match_bitapScore(0, best_loc), score_threshold)
-- LUANOTE: Ideally we'd also check from the other direction, but Lua
-- doesn't have an efficent lastIndexOf function.
end
-- Initialise the bit arrays.
local matchmask = lshift(1, #pattern - 1)
best_loc = -1
local bin_min, bin_mid
local bin_max = #pattern + #text
local last_rd
for d = 0, #pattern - 1, 1 do
-- Scan for the best match; each iteration allows for one more error.
-- Run a binary search to determine how far from 'loc' we can stray at this
-- error level.
bin_min = 0
bin_mid = bin_max
while (bin_min < bin_mid) do
if (_match_bitapScore(d, loc + bin_mid) <= score_threshold) then
bin_min = bin_mid
else
bin_max = bin_mid
end
bin_mid = floor(bin_min + (bin_max - bin_min) / 2)
end
-- Use the result from this iteration as the maximum for the next.
bin_max = bin_mid
local start = max(1, loc - bin_mid + 1)
local finish = min(loc + bin_mid, #text) + #pattern
local rd = {}
for j = start, finish do
rd[j] = 0
end
rd[finish + 1] = lshift(1, d) - 1
for j = finish, start, -1 do
local charMatch = s[strsub(text, j - 1, j - 1)] or 0
if (d == 0) then -- First pass: exact match.
rd[j] = band(bor((rd[j + 1] * 2), 1), charMatch)
else
-- Subsequent passes: fuzzy match.
-- Functions instead of operators make this hella messy.
rd[j] = bor(
band(
bor(
lshift(rd[j + 1], 1),
1
),
charMatch
),
bor(
bor(
lshift(bor(last_rd[j + 1], last_rd[j]), 1),
1
),
last_rd[j + 1]
)
)
end
if (band(rd[j], matchmask) ~= 0) then
local score = _match_bitapScore(d, j - 1)
-- This match will almost certainly be better than any existing match.
-- But check anyway.
if (score <= score_threshold) then
-- Told you so.
score_threshold = score
best_loc = j - 1
if (best_loc > loc) then
-- When passing loc, don't exceed our current distance from loc.
start = max(1, loc * 2 - best_loc)
else
-- Already passed loc, downhill from here on in.
break
end
end
end
end
-- No hope for a (better) match at greater error levels.
if (_match_bitapScore(d + 1, loc) > score_threshold) then
break
end
last_rd = rd
end
return best_loc
end
-- -----------------------------------------------------------------------------
-- PATCH API
-- -----------------------------------------------------------------------------
local _patch_addContext,
_patch_deepCopy,
_patch_addPadding,
_patch_splitMax,
_patch_appendText,
_new_patch_obj
--[[
* Compute a list of patches to turn text1 into text2.
* Use diffs if provided, otherwise compute it ourselves.
* There are four ways to call this function, depending on what data is
* available to the caller:
* Method 1:
* a = text1, b = text2
* Method 2:
* a = diffs
* Method 3 (optimal):
* a = text1, b = diffs
* Method 4 (deprecated, use method 3):
* a = text1, b = text2, c = diffs
*
* @param {string|Array.<Array.<number|string>>} a text1 (methods 1,3,4) or
* Array of diff tuples for text1 to text2 (method 2).
* @param {string|Array.<Array.<number|string>>} opt_b text2 (methods 1,4) or
* Array of diff tuples for text1 to text2 (method 3) or undefined (method 2).
* @param {string|Array.<Array.<number|string>>} opt_c Array of diff tuples for
* text1 to text2 (method 4) or undefined (methods 1,2,3).
* @return {Array.<_new_patch_obj>} Array of patch objects.
--]]
function patch_make(a, opt_b, opt_c)
local text1, diffs
local type_a, type_b, type_c = type(a), type(opt_b), type(opt_c)
if (type_a == 'string') and (type_b == 'string') and (type_c == 'nil') then
-- Method 1: text1, text2
-- Compute diffs from text1 and text2.
text1 = a
diffs = diff_main(text1, opt_b, true)
if (#diffs > 2) then
diff_cleanupSemantic(diffs)
diff_cleanupEfficiency(diffs)
end
elseif (type_a == 'table') and (type_b == 'nil') and (type_c == 'nil') then
-- Method 2: diffs
-- Compute text1 from diffs.
diffs = a
text1 = _diff_text1(diffs)
elseif (type_a == 'string') and (type_b == 'table') and (type_c == 'nil') then
-- Method 3: text1, diffs
text1 = a
diffs = opt_b
elseif (type_a == 'string') and (type_b == 'string') and (type_c == 'table')
then
-- Method 4: text1, text2, diffs
-- text2 is not used.
text1 = a
diffs = opt_c
else
error('Unknown call format to patch_make.')
end
if (diffs[1] == nil) then
return {} -- Get rid of the null case.
end
local patches = {}
local patch = _new_patch_obj()
local patchDiffLength = 0 -- Keeping our own length var is faster.
local char_count1 = 0 -- Number of characters into the text1 string.
local char_count2 = 0 -- Number of characters into the text2 string.
-- Start with text1 (prepatch_text) and apply the diffs until we arrive at
-- text2 (postpatch_text). We recreate the patches one by one to determine
-- context info.
local prepatch_text, postpatch_text = text1, text1
for x, diff in ipairs(diffs) do
local diff_type, diff_text = diff[1], diff[2]
if (patchDiffLength == 0) and (diff_type ~= DIFF_EQUAL) then
-- A new patch starts here.
patch.start1 = char_count1 + 1
patch.start2 = char_count2 + 1
end
if (diff_type == DIFF_INSERT) then
patchDiffLength = patchDiffLength + 1
patch.diffs[patchDiffLength] = diff
patch.length2 = patch.length2 + #diff_text
postpatch_text = strsub(postpatch_text, 1, char_count2)
.. diff_text .. strsub(postpatch_text, char_count2 + 1)
elseif (diff_type == DIFF_DELETE) then
patch.length1 = patch.length1 + #diff_text
patchDiffLength = patchDiffLength + 1
patch.diffs[patchDiffLength] = diff
postpatch_text = strsub(postpatch_text, 1, char_count2)
.. strsub(postpatch_text, char_count2 + #diff_text + 1)
elseif (diff_type == DIFF_EQUAL) then
if (#diff_text <= Patch_Margin * 2)
and (patchDiffLength ~= 0) and (#diffs ~= x) then
-- Small equality inside a patch.
patchDiffLength = patchDiffLength + 1
patch.diffs[patchDiffLength] = diff
patch.length1 = patch.length1 + #diff_text
patch.length2 = patch.length2 + #diff_text
elseif (#diff_text >= Patch_Margin * 2) then
-- Time for a new patch.
if (patchDiffLength ~= 0) then
_patch_addContext(patch, prepatch_text)
patches[#patches + 1] = patch
patch = _new_patch_obj()
patchDiffLength = 0
-- Unlike Unidiff, our patch lists have a rolling context.
-- http://code.google.com/p/google-diff-match-patch/wiki/Unidiff
-- Update prepatch text & pos to reflect the application of the
-- just completed patch.
prepatch_text = postpatch_text
char_count1 = char_count2
end
end
end
-- Update the current character count.
if (diff_type ~= DIFF_INSERT) then
char_count1 = char_count1 + #diff_text
end
if (diff_type ~= DIFF_DELETE) then
char_count2 = char_count2 + #diff_text
end
end
-- Pick up the leftover patch if not empty.
if (patchDiffLength > 0) then
_patch_addContext(patch, prepatch_text)
patches[#patches + 1] = patch
end
return patches
end
--[[
* Merge a set of patches onto the text. Return a patched text, as well
* as a list of true/false values indicating which patches were applied.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @param {string} text Old text.
* @return {Array.<string|Array.<boolean>>} Two return values, the
* new text and an array of boolean values.
--]]
function patch_apply(patches, text)
if patches[1] == nil then
return text, {}
end
-- Deep copy the patches so that no changes are made to originals.
patches = _patch_deepCopy(patches)
local nullPadding = _patch_addPadding(patches)
text = nullPadding .. text .. nullPadding
_patch_splitMax(patches)
-- delta keeps track of the offset between the expected and actual location
-- of the previous patch. If there are patches expected at positions 10 and
-- 20, but the first patch was found at 12, delta is 2 and the second patch
-- has an effective expected position of 22.
local delta = 0
local results = {}
for x, patch in ipairs(patches) do
local expected_loc = patch.start2 + delta
local text1 = _diff_text1(patch.diffs)
local start_loc
local end_loc = -1
if #text1 > Match_MaxBits then
-- _patch_splitMax will only provide an oversized pattern in
-- the case of a monster delete.
start_loc = match_main(text,
strsub(text1, 1, Match_MaxBits), expected_loc)
if start_loc ~= -1 then
end_loc = match_main(text, strsub(text1, -Match_MaxBits),
expected_loc + #text1 - Match_MaxBits)
if end_loc == -1 or start_loc >= end_loc then
-- Can't find valid trailing context. Drop this patch.
start_loc = -1
end
end
else
start_loc = match_main(text, text1, expected_loc)
end
if start_loc == -1 then
-- No match found. :(
results[x] = false
-- Subtract the delta for this failed patch from subsequent patches.
delta = delta - patch.length2 - patch.length1
else
-- Found a match. :)
results[x] = true
delta = start_loc - expected_loc
local text2
if end_loc == -1 then
text2 = strsub(text, start_loc, start_loc + #text1 - 1)
else
text2 = strsub(text, start_loc, end_loc + Match_MaxBits - 1)
end
if text1 == text2 then
-- Perfect match, just shove the replacement text in.
text = strsub(text, 1, start_loc - 1) .. _diff_text2(patch.diffs)
.. strsub(text, start_loc + #text1)
else
-- Imperfect match. Run a diff to get a framework of equivalent
-- indices.
local diffs = diff_main(text1, text2, false)
if (#text1 > Match_MaxBits)
and (diff_levenshtein(diffs) / #text1 > Patch_DeleteThreshold) then
-- The end points match, but the content is unacceptably bad.
results[x] = false
else
_diff_cleanupSemanticLossless(diffs)
local index1 = 1
local index2
for y, mod in ipairs(patch.diffs) do
if mod[1] ~= DIFF_EQUAL then
index2 = _diff_xIndex(diffs, index1)
end
if mod[1] == DIFF_INSERT then
text = strsub(text, 1, start_loc + index2 - 2)
.. mod[2] .. strsub(text, start_loc + index2 - 1)
elseif mod[1] == DIFF_DELETE then
text = strsub(text, 1, start_loc + index2 - 2) .. strsub(text,
start_loc + _diff_xIndex(diffs, index1 + #mod[2] - 1))
end
if mod[1] ~= DIFF_DELETE then
index1 = index1 + #mod[2]
end
end
end
end
end
end
-- Strip the padding off.
text = strsub(text, #nullPadding + 1, -#nullPadding - 1)
return text, results
end
--[[
* Take a list of patches and return a textual representation.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @return {string} Text representation of patches.
--]]
function patch_toText(patches)
local text = {}
for x, patch in ipairs(patches) do
_patch_appendText(patch, text)
end
return tconcat(text)
end
--[[
* Parse a textual representation of patches and return a list of patch objects.
* @param {string} textline Text representation of patches.
* @return {Array.<_new_patch_obj>} Array of patch objects.
* @throws {Error} If invalid input.
--]]
function patch_fromText(textline)
local patches = {}
if (#textline == 0) then
return patches
end
local text = {}
for line in gmatch(textline, '([^\n]*)') do
text[#text + 1] = line
end
local textPointer = 1
while (textPointer <= #text) do
local start1, length1, start2, length2
= strmatch(text[textPointer], '^@@ %-(%d+),?(%d*) %+(%d+),?(%d*) @@$')
if (start1 == nil) then
error('Invalid patch string: "' .. text[textPointer] .. '"')
end
local patch = _new_patch_obj()
patches[#patches + 1] = patch
start1 = tonumber(start1)
length1 = tonumber(length1) or 1
if (length1 == 0) then
start1 = start1 + 1
end
patch.start1 = start1
patch.length1 = length1
start2 = tonumber(start2)
length2 = tonumber(length2) or 1
if (length2 == 0) then
start2 = start2 + 1
end
patch.start2 = start2
patch.length2 = length2
textPointer = textPointer + 1
while true do
local line = text[textPointer]
if (line == nil) then
break
end
local sign; sign, line = strsub(line, 1, 1), strsub(line, 2)
local invalidDecode = false
local decoded = gsub(line, '%%(.?.?)',
function(c)
local n = tonumber(c, 16)
if (#c ~= 2) or (n == nil) then
invalidDecode = true
return ''
end
return strchar(n)
end)
if invalidDecode then
-- Malformed URI sequence.
error('Illegal escape in patch_fromText: ' .. line)
end
line = decoded
if (sign == '-') then
-- Deletion.
patch.diffs[#patch.diffs + 1] = {DIFF_DELETE, line}
elseif (sign == '+') then
-- Insertion.
patch.diffs[#patch.diffs + 1] = {DIFF_INSERT, line}
elseif (sign == ' ') then
-- Minor equality.
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, line}
elseif (sign == '@') then
-- Start of next patch.
break
elseif (sign == '') then
-- Blank line? Whatever.
else
-- WTF?
error('Invalid patch mode "' .. sign .. '" in: ' .. line)
end
textPointer = textPointer + 1
end
end
return patches
end
-- ---------------------------------------------------------------------------
-- UNOFFICIAL/PRIVATE PATCH FUNCTIONS
-- ---------------------------------------------------------------------------
local patch_meta = {
__tostring = function(patch)
local buf = {}
_patch_appendText(patch, buf)
return tconcat(buf)
end
}
--[[
* Class representing one patch operation.
* @constructor
--]]
function _new_patch_obj()
return setmetatable({
--[[ @type {Array.<Array.<number|string>>} ]]
diffs = {};
--[[ @type {?number} ]]
start1 = 1; -- nil;
--[[ @type {?number} ]]
start2 = 1; -- nil;
--[[ @type {number} ]]
length1 = 0;
--[[ @type {number} ]]
length2 = 0;
}, patch_meta)
end
--[[
* Increase the context until it is unique,
* but don't let the pattern expand beyond Match_MaxBits.
* @param {_new_patch_obj} patch The patch to grow.
* @param {string} text Source text.
* @private
--]]
function _patch_addContext(patch, text)
if (#text == 0) then
return
end
local pattern = strsub(text, patch.start2, patch.start2 + patch.length1 - 1)
local padding = 0
-- LUANOTE: Lua's lack of a lastIndexOf function results in slightly
-- different logic here than in other language ports.
-- Look for the first two matches of pattern in text. If two are found,
-- increase the pattern length.
local firstMatch = indexOf(text, pattern)
local secondMatch = nil
if (firstMatch ~= nil) then
secondMatch = indexOf(text, pattern, firstMatch + 1)
end
while (#pattern == 0 or secondMatch ~= nil)
and (#pattern < Match_MaxBits - Patch_Margin - Patch_Margin) do
padding = padding + Patch_Margin
pattern = strsub(text, max(1, patch.start2 - padding),
patch.start2 + patch.length1 - 1 + padding)
firstMatch = indexOf(text, pattern)
if (firstMatch ~= nil) then
secondMatch = indexOf(text, pattern, firstMatch + 1)
else
secondMatch = nil
end
end
-- Add one chunk for good luck.
padding = padding + Patch_Margin
-- Add the prefix.
local prefix = strsub(text, max(1, patch.start2 - padding), patch.start2 - 1)
if (#prefix > 0) then
tinsert(patch.diffs, 1, {DIFF_EQUAL, prefix})
end
-- Add the suffix.
local suffix = strsub(text, patch.start2 + patch.length1,
patch.start2 + patch.length1 - 1 + padding)
if (#suffix > 0) then
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, suffix}
end
-- Roll back the start points.
patch.start1 = patch.start1 - #prefix
patch.start2 = patch.start2 - #prefix
-- Extend the lengths.
patch.length1 = patch.length1 + #prefix + #suffix
patch.length2 = patch.length2 + #prefix + #suffix
end
--[[
* Given an array of patches, return another array that is identical.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @return {Array.<_new_patch_obj>} Array of patch objects.
--]]
function _patch_deepCopy(patches)
local patchesCopy = {}
for x, patch in ipairs(patches) do
local patchCopy = _new_patch_obj()
local diffsCopy = {}
for i, diff in ipairs(patch.diffs) do
diffsCopy[i] = {diff[1], diff[2]}
end
patchCopy.diffs = diffsCopy
patchCopy.start1 = patch.start1
patchCopy.start2 = patch.start2
patchCopy.length1 = patch.length1
patchCopy.length2 = patch.length2
patchesCopy[x] = patchCopy
end
return patchesCopy
end
--[[
* Add some padding on text start and end so that edges can match something.
* Intended to be called only from within patch_apply.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @return {string} The padding string added to each side.
--]]
function _patch_addPadding(patches)
local paddingLength = Patch_Margin
local nullPadding = ''
for x = 1, paddingLength do
nullPadding = nullPadding .. strchar(x)
end
-- Bump all the patches forward.
for x, patch in ipairs(patches) do
patch.start1 = patch.start1 + paddingLength
patch.start2 = patch.start2 + paddingLength
end
-- Add some padding on start of first diff.
local patch = patches[1]
local diffs = patch.diffs
local firstDiff = diffs[1]
if (firstDiff == nil) or (firstDiff[1] ~= DIFF_EQUAL) then
-- Add nullPadding equality.
tinsert(diffs, 1, {DIFF_EQUAL, nullPadding})
patch.start1 = patch.start1 - paddingLength -- Should be 0.
patch.start2 = patch.start2 - paddingLength -- Should be 0.
patch.length1 = patch.length1 + paddingLength
patch.length2 = patch.length2 + paddingLength
elseif (paddingLength > #firstDiff[2]) then
-- Grow first equality.
local extraLength = paddingLength - #firstDiff[2]
firstDiff[2] = strsub(nullPadding, #firstDiff[2] + 1) .. firstDiff[2]
patch.start1 = patch.start1 - extraLength
patch.start2 = patch.start2 - extraLength
patch.length1 = patch.length1 + extraLength
patch.length2 = patch.length2 + extraLength
end
-- Add some padding on end of last diff.
patch = patches[#patches]
diffs = patch.diffs
local lastDiff = diffs[#diffs]
if (lastDiff == nil) or (lastDiff[1] ~= DIFF_EQUAL) then
-- Add nullPadding equality.
diffs[#diffs + 1] = {DIFF_EQUAL, nullPadding}
patch.length1 = patch.length1 + paddingLength
patch.length2 = patch.length2 + paddingLength
elseif (paddingLength > #lastDiff[2]) then
-- Grow last equality.
local extraLength = paddingLength - #lastDiff[2]
lastDiff[2] = lastDiff[2] .. strsub(nullPadding, 1, extraLength)
patch.length1 = patch.length1 + extraLength
patch.length2 = patch.length2 + extraLength
end
return nullPadding
end
--[[
* Look through the patches and break up any which are longer than the maximum
* limit of the match algorithm.
* Intended to be called only from within patch_apply.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
--]]
function _patch_splitMax(patches)
local patch_size = Match_MaxBits
local x = 1
while true do
local patch = patches[x]
if patch == nil then
return
end
if patch.length1 > patch_size then
local bigpatch = patch
-- Remove the big old patch.
tremove(patches, x)
x = x - 1
local start1 = bigpatch.start1
local start2 = bigpatch.start2
local precontext = ''
while bigpatch.diffs[1] do
-- Create one of several smaller patches.
local patch = _new_patch_obj()
local empty = true
patch.start1 = start1 - #precontext
patch.start2 = start2 - #precontext
if precontext ~= '' then
patch.length1, patch.length2 = #precontext, #precontext
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, precontext}
end
while bigpatch.diffs[1] and (patch.length1 < patch_size-Patch_Margin) do
local diff_type = bigpatch.diffs[1][1]
local diff_text = bigpatch.diffs[1][2]
if (diff_type == DIFF_INSERT) then
-- Insertions are harmless.
patch.length2 = patch.length2 + #diff_text
start2 = start2 + #diff_text
patch.diffs[#(patch.diffs) + 1] = bigpatch.diffs[1]
tremove(bigpatch.diffs, 1)
empty = false
elseif (diff_type == DIFF_DELETE) and (#patch.diffs == 1)
and (patch.diffs[1][1] == DIFF_EQUAL)
and (#diff_text > 2 * patch_size) then
-- This is a large deletion. Let it pass in one chunk.
patch.length1 = patch.length1 + #diff_text
start1 = start1 + #diff_text
empty = false
patch.diffs[#patch.diffs + 1] = {diff_type, diff_text}
tremove(bigpatch.diffs, 1)
else
-- Deletion or equality.
-- Only take as much as we can stomach.
diff_text = strsub(diff_text, 1,
patch_size - patch.length1 - Patch_Margin)
patch.length1 = patch.length1 + #diff_text
start1 = start1 + #diff_text
if (diff_type == DIFF_EQUAL) then
patch.length2 = patch.length2 + #diff_text
start2 = start2 + #diff_text
else
empty = false
end
patch.diffs[#patch.diffs + 1] = {diff_type, diff_text}
if (diff_text == bigpatch.diffs[1][2]) then
tremove(bigpatch.diffs, 1)
else
bigpatch.diffs[1][2]
= strsub(bigpatch.diffs[1][2], #diff_text + 1)
end
end
end
-- Compute the head context for the next patch.
precontext = _diff_text2(patch.diffs)
precontext = strsub(precontext, -Patch_Margin)
-- Append the end context for this patch.
local postcontext = strsub(_diff_text1(bigpatch.diffs), 1, Patch_Margin)
if postcontext ~= '' then
patch.length1 = patch.length1 + #postcontext
patch.length2 = patch.length2 + #postcontext
if patch.diffs[1]
and (patch.diffs[#patch.diffs][1] == DIFF_EQUAL) then
patch.diffs[#patch.diffs][2] = patch.diffs[#patch.diffs][2]
.. postcontext
else
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, postcontext}
end
end
if not empty then
x = x + 1
tinsert(patches, x, patch)
end
end
end
x = x + 1
end
end
--[[
* Emulate GNU diff's format.
* Header: @@ -382,8 +481,9 @@
* @return {string} The GNU diff string.
--]]
function _patch_appendText(patch, text)
local coords1, coords2
local length1, length2 = patch.length1, patch.length2
local start1, start2 = patch.start1, patch.start2
local diffs = patch.diffs
if length1 == 1 then
coords1 = start1
else
coords1 = ((length1 == 0) and (start1 - 1) or start1) .. ',' .. length1
end
if length2 == 1 then
coords2 = start2
else
coords2 = ((length2 == 0) and (start2 - 1) or start2) .. ',' .. length2
end
text[#text + 1] = '@@ -' .. coords1 .. ' +' .. coords2 .. ' @@\n'
local op
-- Escape the body of the patch with %xx notation.
for x, diff in ipairs(patch.diffs) do
local diff_type = diff[1]
if diff_type == DIFF_INSERT then
op = '+'
elseif diff_type == DIFF_DELETE then
op = '-'
elseif diff_type == DIFF_EQUAL then
op = ' '
end
text[#text + 1] = op
.. gsub(diffs[x][2], percentEncode_pattern, percentEncode_replace)
.. '\n'
end
return text
end
-- Expose the API
local _M = {}
_M.DIFF_DELETE = DIFF_DELETE
_M.DIFF_INSERT = DIFF_INSERT
_M.DIFF_EQUAL = DIFF_EQUAL
_M.diff_main = diff_main
_M.diff_cleanupSemantic = diff_cleanupSemantic
_M.diff_cleanupEfficiency = diff_cleanupEfficiency
_M.diff_levenshtein = diff_levenshtein
_M.diff_prettyHtml = diff_prettyHtml
_M.match_main = match_main
_M.patch_make = patch_make
_M.patch_toText = patch_toText
_M.patch_fromText = patch_fromText
_M.patch_apply = patch_apply
-- Expose some non-API functions as well, for testing purposes etc.
_M.diff_commonPrefix = _diff_commonPrefix
_M.diff_commonSuffix = _diff_commonSuffix
_M.diff_commonOverlap = _diff_commonOverlap
_M.diff_halfMatch = _diff_halfMatch
_M.diff_bisect = _diff_bisect
_M.diff_cleanupMerge = _diff_cleanupMerge
_M.diff_cleanupSemanticLossless = _diff_cleanupSemanticLossless
_M.diff_text1 = _diff_text1
_M.diff_text2 = _diff_text2
_M.diff_toDelta = _diff_toDelta
_M.diff_fromDelta = _diff_fromDelta
_M.diff_xIndex = _diff_xIndex
_M.match_alphabet = _match_alphabet
_M.match_bitap = _match_bitap
_M.new_patch_obj = _new_patch_obj
_M.patch_addContext = _patch_addContext
_M.patch_splitMax = _patch_splitMax
_M.patch_addPadding = _patch_addPadding
_M.settings = settings
return _M
| apache-2.0 |
Raybird/google-diff-match-patch | lua/diff_match_patch.lua | 265 | 73869 | --[[
* Diff Match and Patch
*
* Copyright 2006 Google Inc.
* http://code.google.com/p/google-diff-match-patch/
*
* Based on the JavaScript implementation by Neil Fraser.
* Ported to Lua by Duncan Cross.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
--]]
--[[
-- Lua 5.1 and earlier requires the external BitOp library.
-- This library is built-in from Lua 5.2 and later as 'bit32'.
require 'bit' -- <http://bitop.luajit.org/>
local band, bor, lshift
= bit.band, bit.bor, bit.lshift
--]]
local band, bor, lshift
= bit32.band, bit32.bor, bit32.lshift
local type, setmetatable, ipairs, select
= type, setmetatable, ipairs, select
local unpack, tonumber, error
= unpack, tonumber, error
local strsub, strbyte, strchar, gmatch, gsub
= string.sub, string.byte, string.char, string.gmatch, string.gsub
local strmatch, strfind, strformat
= string.match, string.find, string.format
local tinsert, tremove, tconcat
= table.insert, table.remove, table.concat
local max, min, floor, ceil, abs
= math.max, math.min, math.floor, math.ceil, math.abs
local clock = os.clock
-- Utility functions.
local percentEncode_pattern = '[^A-Za-z0-9%-=;\',./~!@#$%&*%(%)_%+ %?]'
local function percentEncode_replace(v)
return strformat('%%%02X', strbyte(v))
end
local function tsplice(t, idx, deletions, ...)
local insertions = select('#', ...)
for i = 1, deletions do
tremove(t, idx)
end
for i = insertions, 1, -1 do
-- do not remove parentheses around select
tinsert(t, idx, (select(i, ...)))
end
end
local function strelement(str, i)
return strsub(str, i, i)
end
local function indexOf(a, b, start)
if (#b == 0) then
return nil
end
return strfind(a, b, start, true)
end
local htmlEncode_pattern = '[&<>\n]'
local htmlEncode_replace = {
['&'] = '&', ['<'] = '<', ['>'] = '>', ['\n'] = '¶<br>'
}
-- Public API Functions
-- (Exported at the end of the script)
local diff_main,
diff_cleanupSemantic,
diff_cleanupEfficiency,
diff_levenshtein,
diff_prettyHtml
local match_main
local patch_make,
patch_toText,
patch_fromText,
patch_apply
--[[
* The data structure representing a diff is an array of tuples:
* {{DIFF_DELETE, 'Hello'}, {DIFF_INSERT, 'Goodbye'}, {DIFF_EQUAL, ' world.'}}
* which means: delete 'Hello', add 'Goodbye' and keep ' world.'
--]]
local DIFF_DELETE = -1
local DIFF_INSERT = 1
local DIFF_EQUAL = 0
-- Number of seconds to map a diff before giving up (0 for infinity).
local Diff_Timeout = 1.0
-- Cost of an empty edit operation in terms of edit characters.
local Diff_EditCost = 4
-- At what point is no match declared (0.0 = perfection, 1.0 = very loose).
local Match_Threshold = 0.5
-- How far to search for a match (0 = exact location, 1000+ = broad match).
-- A match this many characters away from the expected location will add
-- 1.0 to the score (0.0 is a perfect match).
local Match_Distance = 1000
-- When deleting a large block of text (over ~64 characters), how close do
-- the contents have to be to match the expected contents. (0.0 = perfection,
-- 1.0 = very loose). Note that Match_Threshold controls how closely the
-- end points of a delete need to match.
local Patch_DeleteThreshold = 0.5
-- Chunk size for context length.
local Patch_Margin = 4
-- The number of bits in an int.
local Match_MaxBits = 32
function settings(new)
if new then
Diff_Timeout = new.Diff_Timeout or Diff_Timeout
Diff_EditCost = new.Diff_EditCost or Diff_EditCost
Match_Threshold = new.Match_Threshold or Match_Threshold
Match_Distance = new.Match_Distance or Match_Distance
Patch_DeleteThreshold = new.Patch_DeleteThreshold or Patch_DeleteThreshold
Patch_Margin = new.Patch_Margin or Patch_Margin
Match_MaxBits = new.Match_MaxBits or Match_MaxBits
else
return {
Diff_Timeout = Diff_Timeout;
Diff_EditCost = Diff_EditCost;
Match_Threshold = Match_Threshold;
Match_Distance = Match_Distance;
Patch_DeleteThreshold = Patch_DeleteThreshold;
Patch_Margin = Patch_Margin;
Match_MaxBits = Match_MaxBits;
}
end
end
-- ---------------------------------------------------------------------------
-- DIFF API
-- ---------------------------------------------------------------------------
-- The private diff functions
local _diff_compute,
_diff_bisect,
_diff_halfMatchI,
_diff_halfMatch,
_diff_cleanupSemanticScore,
_diff_cleanupSemanticLossless,
_diff_cleanupMerge,
_diff_commonPrefix,
_diff_commonSuffix,
_diff_commonOverlap,
_diff_xIndex,
_diff_text1,
_diff_text2,
_diff_toDelta,
_diff_fromDelta
--[[
* Find the differences between two texts. Simplifies the problem by stripping
* any common prefix or suffix off the texts before diffing.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean} opt_checklines Has no effect in Lua.
* @param {number} opt_deadline Optional time when the diff should be complete
* by. Used internally for recursive calls. Users should set DiffTimeout
* instead.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
--]]
function diff_main(text1, text2, opt_checklines, opt_deadline)
-- Set a deadline by which time the diff must be complete.
if opt_deadline == nil then
if Diff_Timeout <= 0 then
opt_deadline = 2 ^ 31
else
opt_deadline = clock() + Diff_Timeout
end
end
local deadline = opt_deadline
-- Check for null inputs.
if text1 == nil or text1 == nil then
error('Null inputs. (diff_main)')
end
-- Check for equality (speedup).
if text1 == text2 then
if #text1 > 0 then
return {{DIFF_EQUAL, text1}}
end
return {}
end
-- LUANOTE: Due to the lack of Unicode support, Lua is incapable of
-- implementing the line-mode speedup.
local checklines = false
-- Trim off common prefix (speedup).
local commonlength = _diff_commonPrefix(text1, text2)
local commonprefix
if commonlength > 0 then
commonprefix = strsub(text1, 1, commonlength)
text1 = strsub(text1, commonlength + 1)
text2 = strsub(text2, commonlength + 1)
end
-- Trim off common suffix (speedup).
commonlength = _diff_commonSuffix(text1, text2)
local commonsuffix
if commonlength > 0 then
commonsuffix = strsub(text1, -commonlength)
text1 = strsub(text1, 1, -commonlength - 1)
text2 = strsub(text2, 1, -commonlength - 1)
end
-- Compute the diff on the middle block.
local diffs = _diff_compute(text1, text2, checklines, deadline)
-- Restore the prefix and suffix.
if commonprefix then
tinsert(diffs, 1, {DIFF_EQUAL, commonprefix})
end
if commonsuffix then
diffs[#diffs + 1] = {DIFF_EQUAL, commonsuffix}
end
_diff_cleanupMerge(diffs)
return diffs
end
--[[
* Reduce the number of edits by eliminating semantically trivial equalities.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function diff_cleanupSemantic(diffs)
local changes = false
local equalities = {} -- Stack of indices where equalities are found.
local equalitiesLength = 0 -- Keeping our own length var is faster.
local lastequality = nil
-- Always equal to diffs[equalities[equalitiesLength]][2]
local pointer = 1 -- Index of current position.
-- Number of characters that changed prior to the equality.
local length_insertions1 = 0
local length_deletions1 = 0
-- Number of characters that changed after the equality.
local length_insertions2 = 0
local length_deletions2 = 0
while diffs[pointer] do
if diffs[pointer][1] == DIFF_EQUAL then -- Equality found.
equalitiesLength = equalitiesLength + 1
equalities[equalitiesLength] = pointer
length_insertions1 = length_insertions2
length_deletions1 = length_deletions2
length_insertions2 = 0
length_deletions2 = 0
lastequality = diffs[pointer][2]
else -- An insertion or deletion.
if diffs[pointer][1] == DIFF_INSERT then
length_insertions2 = length_insertions2 + #(diffs[pointer][2])
else
length_deletions2 = length_deletions2 + #(diffs[pointer][2])
end
-- Eliminate an equality that is smaller or equal to the edits on both
-- sides of it.
if lastequality
and (#lastequality <= max(length_insertions1, length_deletions1))
and (#lastequality <= max(length_insertions2, length_deletions2)) then
-- Duplicate record.
tinsert(diffs, equalities[equalitiesLength],
{DIFF_DELETE, lastequality})
-- Change second copy to insert.
diffs[equalities[equalitiesLength] + 1][1] = DIFF_INSERT
-- Throw away the equality we just deleted.
equalitiesLength = equalitiesLength - 1
-- Throw away the previous equality (it needs to be reevaluated).
equalitiesLength = equalitiesLength - 1
pointer = (equalitiesLength > 0) and equalities[equalitiesLength] or 0
length_insertions1, length_deletions1 = 0, 0 -- Reset the counters.
length_insertions2, length_deletions2 = 0, 0
lastequality = nil
changes = true
end
end
pointer = pointer + 1
end
-- Normalize the diff.
if changes then
_diff_cleanupMerge(diffs)
end
_diff_cleanupSemanticLossless(diffs)
-- Find any overlaps between deletions and insertions.
-- e.g: <del>abcxxx</del><ins>xxxdef</ins>
-- -> <del>abc</del>xxx<ins>def</ins>
-- e.g: <del>xxxabc</del><ins>defxxx</ins>
-- -> <ins>def</ins>xxx<del>abc</del>
-- Only extract an overlap if it is as big as the edit ahead or behind it.
pointer = 2
while diffs[pointer] do
if (diffs[pointer - 1][1] == DIFF_DELETE and
diffs[pointer][1] == DIFF_INSERT) then
local deletion = diffs[pointer - 1][2]
local insertion = diffs[pointer][2]
local overlap_length1 = _diff_commonOverlap(deletion, insertion)
local overlap_length2 = _diff_commonOverlap(insertion, deletion)
if (overlap_length1 >= overlap_length2) then
if (overlap_length1 >= #deletion / 2 or
overlap_length1 >= #insertion / 2) then
-- Overlap found. Insert an equality and trim the surrounding edits.
tinsert(diffs, pointer,
{DIFF_EQUAL, strsub(insertion, 1, overlap_length1)})
diffs[pointer - 1][2] =
strsub(deletion, 1, #deletion - overlap_length1)
diffs[pointer + 1][2] = strsub(insertion, overlap_length1 + 1)
pointer = pointer + 1
end
else
if (overlap_length2 >= #deletion / 2 or
overlap_length2 >= #insertion / 2) then
-- Reverse overlap found.
-- Insert an equality and swap and trim the surrounding edits.
tinsert(diffs, pointer,
{DIFF_EQUAL, strsub(deletion, 1, overlap_length2)})
diffs[pointer - 1] = {DIFF_INSERT,
strsub(insertion, 1, #insertion - overlap_length2)}
diffs[pointer + 1] = {DIFF_DELETE,
strsub(deletion, overlap_length2 + 1)}
pointer = pointer + 1
end
end
pointer = pointer + 1
end
pointer = pointer + 1
end
end
--[[
* Reduce the number of edits by eliminating operationally trivial equalities.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function diff_cleanupEfficiency(diffs)
local changes = false
-- Stack of indices where equalities are found.
local equalities = {}
-- Keeping our own length var is faster.
local equalitiesLength = 0
-- Always equal to diffs[equalities[equalitiesLength]][2]
local lastequality = nil
-- Index of current position.
local pointer = 1
-- The following four are really booleans but are stored as numbers because
-- they are used at one point like this:
--
-- (pre_ins + pre_del + post_ins + post_del) == 3
--
-- ...i.e. checking that 3 of them are true and 1 of them is false.
-- Is there an insertion operation before the last equality.
local pre_ins = 0
-- Is there a deletion operation before the last equality.
local pre_del = 0
-- Is there an insertion operation after the last equality.
local post_ins = 0
-- Is there a deletion operation after the last equality.
local post_del = 0
while diffs[pointer] do
if diffs[pointer][1] == DIFF_EQUAL then -- Equality found.
local diffText = diffs[pointer][2]
if (#diffText < Diff_EditCost) and (post_ins == 1 or post_del == 1) then
-- Candidate found.
equalitiesLength = equalitiesLength + 1
equalities[equalitiesLength] = pointer
pre_ins, pre_del = post_ins, post_del
lastequality = diffText
else
-- Not a candidate, and can never become one.
equalitiesLength = 0
lastequality = nil
end
post_ins, post_del = 0, 0
else -- An insertion or deletion.
if diffs[pointer][1] == DIFF_DELETE then
post_del = 1
else
post_ins = 1
end
--[[
* Five types to be split:
* <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
* <ins>A</ins>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<ins>C</ins>
* <ins>A</del>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<del>C</del>
--]]
if lastequality and (
(pre_ins+pre_del+post_ins+post_del == 4)
or
(
(#lastequality < Diff_EditCost / 2)
and
(pre_ins+pre_del+post_ins+post_del == 3)
)) then
-- Duplicate record.
tinsert(diffs, equalities[equalitiesLength],
{DIFF_DELETE, lastequality})
-- Change second copy to insert.
diffs[equalities[equalitiesLength] + 1][1] = DIFF_INSERT
-- Throw away the equality we just deleted.
equalitiesLength = equalitiesLength - 1
lastequality = nil
if (pre_ins == 1) and (pre_del == 1) then
-- No changes made which could affect previous entry, keep going.
post_ins, post_del = 1, 1
equalitiesLength = 0
else
-- Throw away the previous equality.
equalitiesLength = equalitiesLength - 1
pointer = (equalitiesLength > 0) and equalities[equalitiesLength] or 0
post_ins, post_del = 0, 0
end
changes = true
end
end
pointer = pointer + 1
end
if changes then
_diff_cleanupMerge(diffs)
end
end
--[[
* Compute the Levenshtein distance; the number of inserted, deleted or
* substituted characters.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {number} Number of changes.
--]]
function diff_levenshtein(diffs)
local levenshtein = 0
local insertions, deletions = 0, 0
for x, diff in ipairs(diffs) do
local op, data = diff[1], diff[2]
if (op == DIFF_INSERT) then
insertions = insertions + #data
elseif (op == DIFF_DELETE) then
deletions = deletions + #data
elseif (op == DIFF_EQUAL) then
-- A deletion and an insertion is one substitution.
levenshtein = levenshtein + max(insertions, deletions)
insertions = 0
deletions = 0
end
end
levenshtein = levenshtein + max(insertions, deletions)
return levenshtein
end
--[[
* Convert a diff array into a pretty HTML report.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} HTML representation.
--]]
function diff_prettyHtml(diffs)
local html = {}
for x, diff in ipairs(diffs) do
local op = diff[1] -- Operation (insert, delete, equal)
local data = diff[2] -- Text of change.
local text = gsub(data, htmlEncode_pattern, htmlEncode_replace)
if op == DIFF_INSERT then
html[x] = '<ins style="background:#e6ffe6;">' .. text .. '</ins>'
elseif op == DIFF_DELETE then
html[x] = '<del style="background:#ffe6e6;">' .. text .. '</del>'
elseif op == DIFF_EQUAL then
html[x] = '<span>' .. text .. '</span>'
end
end
return tconcat(html)
end
-- ---------------------------------------------------------------------------
-- UNOFFICIAL/PRIVATE DIFF FUNCTIONS
-- ---------------------------------------------------------------------------
--[[
* Find the differences between two texts. Assumes that the texts do not
* have any common prefix or suffix.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean} checklines Has no effect in Lua.
* @param {number} deadline Time when the diff should be complete by.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @private
--]]
function _diff_compute(text1, text2, checklines, deadline)
if #text1 == 0 then
-- Just add some text (speedup).
return {{DIFF_INSERT, text2}}
end
if #text2 == 0 then
-- Just delete some text (speedup).
return {{DIFF_DELETE, text1}}
end
local diffs
local longtext = (#text1 > #text2) and text1 or text2
local shorttext = (#text1 > #text2) and text2 or text1
local i = indexOf(longtext, shorttext)
if i ~= nil then
-- Shorter text is inside the longer text (speedup).
diffs = {
{DIFF_INSERT, strsub(longtext, 1, i - 1)},
{DIFF_EQUAL, shorttext},
{DIFF_INSERT, strsub(longtext, i + #shorttext)}
}
-- Swap insertions for deletions if diff is reversed.
if #text1 > #text2 then
diffs[1][1], diffs[3][1] = DIFF_DELETE, DIFF_DELETE
end
return diffs
end
if #shorttext == 1 then
-- Single character string.
-- After the previous speedup, the character can't be an equality.
return {{DIFF_DELETE, text1}, {DIFF_INSERT, text2}}
end
-- Check to see if the problem can be split in two.
do
local
text1_a, text1_b,
text2_a, text2_b,
mid_common = _diff_halfMatch(text1, text2)
if text1_a then
-- A half-match was found, sort out the return data.
-- Send both pairs off for separate processing.
local diffs_a = diff_main(text1_a, text2_a, checklines, deadline)
local diffs_b = diff_main(text1_b, text2_b, checklines, deadline)
-- Merge the results.
local diffs_a_len = #diffs_a
diffs = diffs_a
diffs[diffs_a_len + 1] = {DIFF_EQUAL, mid_common}
for i, b_diff in ipairs(diffs_b) do
diffs[diffs_a_len + 1 + i] = b_diff
end
return diffs
end
end
return _diff_bisect(text1, text2, deadline)
end
--[[
* Find the 'middle snake' of a diff, split the problem in two
* and return the recursively constructed diff.
* See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} deadline Time at which to bail if not yet complete.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @private
--]]
function _diff_bisect(text1, text2, deadline)
-- Cache the text lengths to prevent multiple calls.
local text1_length = #text1
local text2_length = #text2
local _sub, _element
local max_d = ceil((text1_length + text2_length) / 2)
local v_offset = max_d
local v_length = 2 * max_d
local v1 = {}
local v2 = {}
-- Setting all elements to -1 is faster in Lua than mixing integers and nil.
for x = 0, v_length - 1 do
v1[x] = -1
v2[x] = -1
end
v1[v_offset + 1] = 0
v2[v_offset + 1] = 0
local delta = text1_length - text2_length
-- If the total number of characters is odd, then
-- the front path will collide with the reverse path.
local front = (delta % 2 ~= 0)
-- Offsets for start and end of k loop.
-- Prevents mapping of space beyond the grid.
local k1start = 0
local k1end = 0
local k2start = 0
local k2end = 0
for d = 0, max_d - 1 do
-- Bail out if deadline is reached.
if clock() > deadline then
break
end
-- Walk the front path one step.
for k1 = -d + k1start, d - k1end, 2 do
local k1_offset = v_offset + k1
local x1
if (k1 == -d) or ((k1 ~= d) and
(v1[k1_offset - 1] < v1[k1_offset + 1])) then
x1 = v1[k1_offset + 1]
else
x1 = v1[k1_offset - 1] + 1
end
local y1 = x1 - k1
while (x1 <= text1_length) and (y1 <= text2_length)
and (strelement(text1, x1) == strelement(text2, y1)) do
x1 = x1 + 1
y1 = y1 + 1
end
v1[k1_offset] = x1
if x1 > text1_length + 1 then
-- Ran off the right of the graph.
k1end = k1end + 2
elseif y1 > text2_length + 1 then
-- Ran off the bottom of the graph.
k1start = k1start + 2
elseif front then
local k2_offset = v_offset + delta - k1
if k2_offset >= 0 and k2_offset < v_length and v2[k2_offset] ~= -1 then
-- Mirror x2 onto top-left coordinate system.
local x2 = text1_length - v2[k2_offset] + 1
if x1 > x2 then
-- Overlap detected.
return _diff_bisectSplit(text1, text2, x1, y1, deadline)
end
end
end
end
-- Walk the reverse path one step.
for k2 = -d + k2start, d - k2end, 2 do
local k2_offset = v_offset + k2
local x2
if (k2 == -d) or ((k2 ~= d) and
(v2[k2_offset - 1] < v2[k2_offset + 1])) then
x2 = v2[k2_offset + 1]
else
x2 = v2[k2_offset - 1] + 1
end
local y2 = x2 - k2
while (x2 <= text1_length) and (y2 <= text2_length)
and (strelement(text1, -x2) == strelement(text2, -y2)) do
x2 = x2 + 1
y2 = y2 + 1
end
v2[k2_offset] = x2
if x2 > text1_length + 1 then
-- Ran off the left of the graph.
k2end = k2end + 2
elseif y2 > text2_length + 1 then
-- Ran off the top of the graph.
k2start = k2start + 2
elseif not front then
local k1_offset = v_offset + delta - k2
if k1_offset >= 0 and k1_offset < v_length and v1[k1_offset] ~= -1 then
local x1 = v1[k1_offset]
local y1 = v_offset + x1 - k1_offset
-- Mirror x2 onto top-left coordinate system.
x2 = text1_length - x2 + 1
if x1 > x2 then
-- Overlap detected.
return _diff_bisectSplit(text1, text2, x1, y1, deadline)
end
end
end
end
end
-- Diff took too long and hit the deadline or
-- number of diffs equals number of characters, no commonality at all.
return {{DIFF_DELETE, text1}, {DIFF_INSERT, text2}}
end
--[[
* Given the location of the 'middle snake', split the diff in two parts
* and recurse.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} x Index of split point in text1.
* @param {number} y Index of split point in text2.
* @param {number} deadline Time at which to bail if not yet complete.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @private
--]]
function _diff_bisectSplit(text1, text2, x, y, deadline)
local text1a = strsub(text1, 1, x - 1)
local text2a = strsub(text2, 1, y - 1)
local text1b = strsub(text1, x)
local text2b = strsub(text2, y)
-- Compute both diffs serially.
local diffs = diff_main(text1a, text2a, false, deadline)
local diffsb = diff_main(text1b, text2b, false, deadline)
local diffs_len = #diffs
for i, v in ipairs(diffsb) do
diffs[diffs_len + i] = v
end
return diffs
end
--[[
* Determine the common prefix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the start of each
* string.
--]]
function _diff_commonPrefix(text1, text2)
-- Quick check for common null cases.
if (#text1 == 0) or (#text2 == 0) or (strbyte(text1, 1) ~= strbyte(text2, 1))
then
return 0
end
-- Binary search.
-- Performance analysis: http://neil.fraser.name/news/2007/10/09/
local pointermin = 1
local pointermax = min(#text1, #text2)
local pointermid = pointermax
local pointerstart = 1
while (pointermin < pointermid) do
if (strsub(text1, pointerstart, pointermid)
== strsub(text2, pointerstart, pointermid)) then
pointermin = pointermid
pointerstart = pointermin
else
pointermax = pointermid
end
pointermid = floor(pointermin + (pointermax - pointermin) / 2)
end
return pointermid
end
--[[
* Determine the common suffix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of each string.
--]]
function _diff_commonSuffix(text1, text2)
-- Quick check for common null cases.
if (#text1 == 0) or (#text2 == 0)
or (strbyte(text1, -1) ~= strbyte(text2, -1)) then
return 0
end
-- Binary search.
-- Performance analysis: http://neil.fraser.name/news/2007/10/09/
local pointermin = 1
local pointermax = min(#text1, #text2)
local pointermid = pointermax
local pointerend = 1
while (pointermin < pointermid) do
if (strsub(text1, -pointermid, -pointerend)
== strsub(text2, -pointermid, -pointerend)) then
pointermin = pointermid
pointerend = pointermin
else
pointermax = pointermid
end
pointermid = floor(pointermin + (pointermax - pointermin) / 2)
end
return pointermid
end
--[[
* Determine if the suffix of one string is the prefix of another.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of the first
* string and the start of the second string.
* @private
--]]
function _diff_commonOverlap(text1, text2)
-- Cache the text lengths to prevent multiple calls.
local text1_length = #text1
local text2_length = #text2
-- Eliminate the null case.
if text1_length == 0 or text2_length == 0 then
return 0
end
-- Truncate the longer string.
if text1_length > text2_length then
text1 = strsub(text1, text1_length - text2_length + 1)
elseif text1_length < text2_length then
text2 = strsub(text2, 1, text1_length)
end
local text_length = min(text1_length, text2_length)
-- Quick check for the worst case.
if text1 == text2 then
return text_length
end
-- Start by looking for a single character match
-- and increase length until no match is found.
-- Performance analysis: http://neil.fraser.name/news/2010/11/04/
local best = 0
local length = 1
while true do
local pattern = strsub(text1, text_length - length + 1)
local found = strfind(text2, pattern, 1, true)
if found == nil then
return best
end
length = length + found - 1
if found == 1 or strsub(text1, text_length - length + 1) ==
strsub(text2, 1, length) then
best = length
length = length + 1
end
end
end
--[[
* Does a substring of shorttext exist within longtext such that the substring
* is at least half the length of longtext?
* This speedup can produce non-minimal diffs.
* Closure, but does not reference any external variables.
* @param {string} longtext Longer string.
* @param {string} shorttext Shorter string.
* @param {number} i Start index of quarter length substring within longtext.
* @return {?Array.<string>} Five element Array, containing the prefix of
* longtext, the suffix of longtext, the prefix of shorttext, the suffix
* of shorttext and the common middle. Or nil if there was no match.
* @private
--]]
function _diff_halfMatchI(longtext, shorttext, i)
-- Start with a 1/4 length substring at position i as a seed.
local seed = strsub(longtext, i, i + floor(#longtext / 4))
local j = 0 -- LUANOTE: do not change to 1, was originally -1
local best_common = ''
local best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b
while true do
j = indexOf(shorttext, seed, j + 1)
if (j == nil) then
break
end
local prefixLength = _diff_commonPrefix(strsub(longtext, i),
strsub(shorttext, j))
local suffixLength = _diff_commonSuffix(strsub(longtext, 1, i - 1),
strsub(shorttext, 1, j - 1))
if #best_common < suffixLength + prefixLength then
best_common = strsub(shorttext, j - suffixLength, j - 1)
.. strsub(shorttext, j, j + prefixLength - 1)
best_longtext_a = strsub(longtext, 1, i - suffixLength - 1)
best_longtext_b = strsub(longtext, i + prefixLength)
best_shorttext_a = strsub(shorttext, 1, j - suffixLength - 1)
best_shorttext_b = strsub(shorttext, j + prefixLength)
end
end
if #best_common * 2 >= #longtext then
return {best_longtext_a, best_longtext_b,
best_shorttext_a, best_shorttext_b, best_common}
else
return nil
end
end
--[[
* Do the two texts share a substring which is at least half the length of the
* longer text?
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {?Array.<string>} Five element Array, containing the prefix of
* text1, the suffix of text1, the prefix of text2, the suffix of
* text2 and the common middle. Or nil if there was no match.
* @private
--]]
function _diff_halfMatch(text1, text2)
if Diff_Timeout <= 0 then
-- Don't risk returning a non-optimal diff if we have unlimited time.
return nil
end
local longtext = (#text1 > #text2) and text1 or text2
local shorttext = (#text1 > #text2) and text2 or text1
if (#longtext < 4) or (#shorttext * 2 < #longtext) then
return nil -- Pointless.
end
-- First check if the second quarter is the seed for a half-match.
local hm1 = _diff_halfMatchI(longtext, shorttext, ceil(#longtext / 4))
-- Check again based on the third quarter.
local hm2 = _diff_halfMatchI(longtext, shorttext, ceil(#longtext / 2))
local hm
if not hm1 and not hm2 then
return nil
elseif not hm2 then
hm = hm1
elseif not hm1 then
hm = hm2
else
-- Both matched. Select the longest.
hm = (#hm1[5] > #hm2[5]) and hm1 or hm2
end
-- A half-match was found, sort out the return data.
local text1_a, text1_b, text2_a, text2_b
if (#text1 > #text2) then
text1_a, text1_b = hm[1], hm[2]
text2_a, text2_b = hm[3], hm[4]
else
text2_a, text2_b = hm[1], hm[2]
text1_a, text1_b = hm[3], hm[4]
end
local mid_common = hm[5]
return text1_a, text1_b, text2_a, text2_b, mid_common
end
--[[
* Given two strings, compute a score representing whether the internal
* boundary falls on logical boundaries.
* Scores range from 6 (best) to 0 (worst).
* @param {string} one First string.
* @param {string} two Second string.
* @return {number} The score.
* @private
--]]
function _diff_cleanupSemanticScore(one, two)
if (#one == 0) or (#two == 0) then
-- Edges are the best.
return 6
end
-- Each port of this function behaves slightly differently due to
-- subtle differences in each language's definition of things like
-- 'whitespace'. Since this function's purpose is largely cosmetic,
-- the choice has been made to use each language's native features
-- rather than force total conformity.
local char1 = strsub(one, -1)
local char2 = strsub(two, 1, 1)
local nonAlphaNumeric1 = strmatch(char1, '%W')
local nonAlphaNumeric2 = strmatch(char2, '%W')
local whitespace1 = nonAlphaNumeric1 and strmatch(char1, '%s')
local whitespace2 = nonAlphaNumeric2 and strmatch(char2, '%s')
local lineBreak1 = whitespace1 and strmatch(char1, '%c')
local lineBreak2 = whitespace2 and strmatch(char2, '%c')
local blankLine1 = lineBreak1 and strmatch(one, '\n\r?\n$')
local blankLine2 = lineBreak2 and strmatch(two, '^\r?\n\r?\n')
if blankLine1 or blankLine2 then
-- Five points for blank lines.
return 5
elseif lineBreak1 or lineBreak2 then
-- Four points for line breaks.
return 4
elseif nonAlphaNumeric1 and not whitespace1 and whitespace2 then
-- Three points for end of sentences.
return 3
elseif whitespace1 or whitespace2 then
-- Two points for whitespace.
return 2
elseif nonAlphaNumeric1 or nonAlphaNumeric2 then
-- One point for non-alphanumeric.
return 1
end
return 0
end
--[[
* Look for single edits surrounded on both sides by equalities
* which can be shifted sideways to align the edit to a word boundary.
* e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function _diff_cleanupSemanticLossless(diffs)
local pointer = 2
-- Intentionally ignore the first and last element (don't need checking).
while diffs[pointer + 1] do
local prevDiff, nextDiff = diffs[pointer - 1], diffs[pointer + 1]
if (prevDiff[1] == DIFF_EQUAL) and (nextDiff[1] == DIFF_EQUAL) then
-- This is a single edit surrounded by equalities.
local diff = diffs[pointer]
local equality1 = prevDiff[2]
local edit = diff[2]
local equality2 = nextDiff[2]
-- First, shift the edit as far left as possible.
local commonOffset = _diff_commonSuffix(equality1, edit)
if commonOffset > 0 then
local commonString = strsub(edit, -commonOffset)
equality1 = strsub(equality1, 1, -commonOffset - 1)
edit = commonString .. strsub(edit, 1, -commonOffset - 1)
equality2 = commonString .. equality2
end
-- Second, step character by character right, looking for the best fit.
local bestEquality1 = equality1
local bestEdit = edit
local bestEquality2 = equality2
local bestScore = _diff_cleanupSemanticScore(equality1, edit)
+ _diff_cleanupSemanticScore(edit, equality2)
while strbyte(edit, 1) == strbyte(equality2, 1) do
equality1 = equality1 .. strsub(edit, 1, 1)
edit = strsub(edit, 2) .. strsub(equality2, 1, 1)
equality2 = strsub(equality2, 2)
local score = _diff_cleanupSemanticScore(equality1, edit)
+ _diff_cleanupSemanticScore(edit, equality2)
-- The >= encourages trailing rather than leading whitespace on edits.
if score >= bestScore then
bestScore = score
bestEquality1 = equality1
bestEdit = edit
bestEquality2 = equality2
end
end
if prevDiff[2] ~= bestEquality1 then
-- We have an improvement, save it back to the diff.
if #bestEquality1 > 0 then
diffs[pointer - 1][2] = bestEquality1
else
tremove(diffs, pointer - 1)
pointer = pointer - 1
end
diffs[pointer][2] = bestEdit
if #bestEquality2 > 0 then
diffs[pointer + 1][2] = bestEquality2
else
tremove(diffs, pointer + 1, 1)
pointer = pointer - 1
end
end
end
pointer = pointer + 1
end
end
--[[
* Reorder and merge like edit sections. Merge equalities.
* Any edit section can move as long as it doesn't cross an equality.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function _diff_cleanupMerge(diffs)
diffs[#diffs + 1] = {DIFF_EQUAL, ''} -- Add a dummy entry at the end.
local pointer = 1
local count_delete, count_insert = 0, 0
local text_delete, text_insert = '', ''
local commonlength
while diffs[pointer] do
local diff_type = diffs[pointer][1]
if diff_type == DIFF_INSERT then
count_insert = count_insert + 1
text_insert = text_insert .. diffs[pointer][2]
pointer = pointer + 1
elseif diff_type == DIFF_DELETE then
count_delete = count_delete + 1
text_delete = text_delete .. diffs[pointer][2]
pointer = pointer + 1
elseif diff_type == DIFF_EQUAL then
-- Upon reaching an equality, check for prior redundancies.
if count_delete + count_insert > 1 then
if (count_delete > 0) and (count_insert > 0) then
-- Factor out any common prefixies.
commonlength = _diff_commonPrefix(text_insert, text_delete)
if commonlength > 0 then
local back_pointer = pointer - count_delete - count_insert
if (back_pointer > 1) and (diffs[back_pointer - 1][1] == DIFF_EQUAL)
then
diffs[back_pointer - 1][2] = diffs[back_pointer - 1][2]
.. strsub(text_insert, 1, commonlength)
else
tinsert(diffs, 1,
{DIFF_EQUAL, strsub(text_insert, 1, commonlength)})
pointer = pointer + 1
end
text_insert = strsub(text_insert, commonlength + 1)
text_delete = strsub(text_delete, commonlength + 1)
end
-- Factor out any common suffixies.
commonlength = _diff_commonSuffix(text_insert, text_delete)
if commonlength ~= 0 then
diffs[pointer][2] =
strsub(text_insert, -commonlength) .. diffs[pointer][2]
text_insert = strsub(text_insert, 1, -commonlength - 1)
text_delete = strsub(text_delete, 1, -commonlength - 1)
end
end
-- Delete the offending records and add the merged ones.
if count_delete == 0 then
tsplice(diffs, pointer - count_insert,
count_insert, {DIFF_INSERT, text_insert})
elseif count_insert == 0 then
tsplice(diffs, pointer - count_delete,
count_delete, {DIFF_DELETE, text_delete})
else
tsplice(diffs, pointer - count_delete - count_insert,
count_delete + count_insert,
{DIFF_DELETE, text_delete}, {DIFF_INSERT, text_insert})
end
pointer = pointer - count_delete - count_insert
+ (count_delete>0 and 1 or 0) + (count_insert>0 and 1 or 0) + 1
elseif (pointer > 1) and (diffs[pointer - 1][1] == DIFF_EQUAL) then
-- Merge this equality with the previous one.
diffs[pointer - 1][2] = diffs[pointer - 1][2] .. diffs[pointer][2]
tremove(diffs, pointer)
else
pointer = pointer + 1
end
count_insert, count_delete = 0, 0
text_delete, text_insert = '', ''
end
end
if diffs[#diffs][2] == '' then
diffs[#diffs] = nil -- Remove the dummy entry at the end.
end
-- Second pass: look for single edits surrounded on both sides by equalities
-- which can be shifted sideways to eliminate an equality.
-- e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
local changes = false
pointer = 2
-- Intentionally ignore the first and last element (don't need checking).
while pointer < #diffs do
local prevDiff, nextDiff = diffs[pointer - 1], diffs[pointer + 1]
if (prevDiff[1] == DIFF_EQUAL) and (nextDiff[1] == DIFF_EQUAL) then
-- This is a single edit surrounded by equalities.
local diff = diffs[pointer]
local currentText = diff[2]
local prevText = prevDiff[2]
local nextText = nextDiff[2]
if strsub(currentText, -#prevText) == prevText then
-- Shift the edit over the previous equality.
diff[2] = prevText .. strsub(currentText, 1, -#prevText - 1)
nextDiff[2] = prevText .. nextDiff[2]
tremove(diffs, pointer - 1)
changes = true
elseif strsub(currentText, 1, #nextText) == nextText then
-- Shift the edit over the next equality.
prevDiff[2] = prevText .. nextText
diff[2] = strsub(currentText, #nextText + 1) .. nextText
tremove(diffs, pointer + 1)
changes = true
end
end
pointer = pointer + 1
end
-- If shifts were made, the diff needs reordering and another shift sweep.
if changes then
-- LUANOTE: no return value, but necessary to use 'return' to get
-- tail calls.
return _diff_cleanupMerge(diffs)
end
end
--[[
* loc is a location in text1, compute and return the equivalent location in
* text2.
* e.g. 'The cat' vs 'The big cat', 1->1, 5->8
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @param {number} loc Location within text1.
* @return {number} Location within text2.
--]]
function _diff_xIndex(diffs, loc)
local chars1 = 1
local chars2 = 1
local last_chars1 = 1
local last_chars2 = 1
local x
for _x, diff in ipairs(diffs) do
x = _x
if diff[1] ~= DIFF_INSERT then -- Equality or deletion.
chars1 = chars1 + #diff[2]
end
if diff[1] ~= DIFF_DELETE then -- Equality or insertion.
chars2 = chars2 + #diff[2]
end
if chars1 > loc then -- Overshot the location.
break
end
last_chars1 = chars1
last_chars2 = chars2
end
-- Was the location deleted?
if diffs[x + 1] and (diffs[x][1] == DIFF_DELETE) then
return last_chars2
end
-- Add the remaining character length.
return last_chars2 + (loc - last_chars1)
end
--[[
* Compute and return the source text (all equalities and deletions).
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} Source text.
--]]
function _diff_text1(diffs)
local text = {}
for x, diff in ipairs(diffs) do
if diff[1] ~= DIFF_INSERT then
text[#text + 1] = diff[2]
end
end
return tconcat(text)
end
--[[
* Compute and return the destination text (all equalities and insertions).
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} Destination text.
--]]
function _diff_text2(diffs)
local text = {}
for x, diff in ipairs(diffs) do
if diff[1] ~= DIFF_DELETE then
text[#text + 1] = diff[2]
end
end
return tconcat(text)
end
--[[
* Crush the diff into an encoded string which describes the operations
* required to transform text1 into text2.
* E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'.
* Operations are tab-separated. Inserted text is escaped using %xx notation.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} Delta text.
--]]
function _diff_toDelta(diffs)
local text = {}
for x, diff in ipairs(diffs) do
local op, data = diff[1], diff[2]
if op == DIFF_INSERT then
text[x] = '+' .. gsub(data, percentEncode_pattern, percentEncode_replace)
elseif op == DIFF_DELETE then
text[x] = '-' .. #data
elseif op == DIFF_EQUAL then
text[x] = '=' .. #data
end
end
return tconcat(text, '\t')
end
--[[
* Given the original text1, and an encoded string which describes the
* operations required to transform text1 into text2, compute the full diff.
* @param {string} text1 Source string for the diff.
* @param {string} delta Delta text.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @throws {Errorend If invalid input.
--]]
function _diff_fromDelta(text1, delta)
local diffs = {}
local diffsLength = 0 -- Keeping our own length var is faster
local pointer = 1 -- Cursor in text1
for token in gmatch(delta, '[^\t]+') do
-- Each token begins with a one character parameter which specifies the
-- operation of this token (delete, insert, equality).
local tokenchar, param = strsub(token, 1, 1), strsub(token, 2)
if (tokenchar == '+') then
local invalidDecode = false
local decoded = gsub(param, '%%(.?.?)',
function(c)
local n = tonumber(c, 16)
if (#c ~= 2) or (n == nil) then
invalidDecode = true
return ''
end
return strchar(n)
end)
if invalidDecode then
-- Malformed URI sequence.
error('Illegal escape in _diff_fromDelta: ' .. param)
end
diffsLength = diffsLength + 1
diffs[diffsLength] = {DIFF_INSERT, decoded}
elseif (tokenchar == '-') or (tokenchar == '=') then
local n = tonumber(param)
if (n == nil) or (n < 0) then
error('Invalid number in _diff_fromDelta: ' .. param)
end
local text = strsub(text1, pointer, pointer + n - 1)
pointer = pointer + n
if (tokenchar == '=') then
diffsLength = diffsLength + 1
diffs[diffsLength] = {DIFF_EQUAL, text}
else
diffsLength = diffsLength + 1
diffs[diffsLength] = {DIFF_DELETE, text}
end
else
error('Invalid diff operation in _diff_fromDelta: ' .. token)
end
end
if (pointer ~= #text1 + 1) then
error('Delta length (' .. (pointer - 1)
.. ') does not equal source text length (' .. #text1 .. ').')
end
return diffs
end
-- ---------------------------------------------------------------------------
-- MATCH API
-- ---------------------------------------------------------------------------
local _match_bitap, _match_alphabet
--[[
* Locate the best instance of 'pattern' in 'text' near 'loc'.
* @param {string} text The text to search.
* @param {string} pattern The pattern to search for.
* @param {number} loc The location to search around.
* @return {number} Best match index or -1.
--]]
function match_main(text, pattern, loc)
-- Check for null inputs.
if text == nil or pattern == nil or loc == nil then
error('Null inputs. (match_main)')
end
if text == pattern then
-- Shortcut (potentially not guaranteed by the algorithm)
return 1
elseif #text == 0 then
-- Nothing to match.
return -1
end
loc = max(1, min(loc, #text))
if strsub(text, loc, loc + #pattern - 1) == pattern then
-- Perfect match at the perfect spot! (Includes case of null pattern)
return loc
else
-- Do a fuzzy compare.
return _match_bitap(text, pattern, loc)
end
end
-- ---------------------------------------------------------------------------
-- UNOFFICIAL/PRIVATE MATCH FUNCTIONS
-- ---------------------------------------------------------------------------
--[[
* Initialise the alphabet for the Bitap algorithm.
* @param {string} pattern The text to encode.
* @return {Object} Hash of character locations.
* @private
--]]
function _match_alphabet(pattern)
local s = {}
local i = 0
for c in gmatch(pattern, '.') do
s[c] = bor(s[c] or 0, lshift(1, #pattern - i - 1))
i = i + 1
end
return s
end
--[[
* Locate the best instance of 'pattern' in 'text' near 'loc' using the
* Bitap algorithm.
* @param {string} text The text to search.
* @param {string} pattern The pattern to search for.
* @param {number} loc The location to search around.
* @return {number} Best match index or -1.
* @private
--]]
function _match_bitap(text, pattern, loc)
if #pattern > Match_MaxBits then
error('Pattern too long.')
end
-- Initialise the alphabet.
local s = _match_alphabet(pattern)
--[[
* Compute and return the score for a match with e errors and x location.
* Accesses loc and pattern through being a closure.
* @param {number} e Number of errors in match.
* @param {number} x Location of match.
* @return {number} Overall score for match (0.0 = good, 1.0 = bad).
* @private
--]]
local function _match_bitapScore(e, x)
local accuracy = e / #pattern
local proximity = abs(loc - x)
if (Match_Distance == 0) then
-- Dodge divide by zero error.
return (proximity == 0) and 1 or accuracy
end
return accuracy + (proximity / Match_Distance)
end
-- Highest score beyond which we give up.
local score_threshold = Match_Threshold
-- Is there a nearby exact match? (speedup)
local best_loc = indexOf(text, pattern, loc)
if best_loc then
score_threshold = min(_match_bitapScore(0, best_loc), score_threshold)
-- LUANOTE: Ideally we'd also check from the other direction, but Lua
-- doesn't have an efficent lastIndexOf function.
end
-- Initialise the bit arrays.
local matchmask = lshift(1, #pattern - 1)
best_loc = -1
local bin_min, bin_mid
local bin_max = #pattern + #text
local last_rd
for d = 0, #pattern - 1, 1 do
-- Scan for the best match; each iteration allows for one more error.
-- Run a binary search to determine how far from 'loc' we can stray at this
-- error level.
bin_min = 0
bin_mid = bin_max
while (bin_min < bin_mid) do
if (_match_bitapScore(d, loc + bin_mid) <= score_threshold) then
bin_min = bin_mid
else
bin_max = bin_mid
end
bin_mid = floor(bin_min + (bin_max - bin_min) / 2)
end
-- Use the result from this iteration as the maximum for the next.
bin_max = bin_mid
local start = max(1, loc - bin_mid + 1)
local finish = min(loc + bin_mid, #text) + #pattern
local rd = {}
for j = start, finish do
rd[j] = 0
end
rd[finish + 1] = lshift(1, d) - 1
for j = finish, start, -1 do
local charMatch = s[strsub(text, j - 1, j - 1)] or 0
if (d == 0) then -- First pass: exact match.
rd[j] = band(bor((rd[j + 1] * 2), 1), charMatch)
else
-- Subsequent passes: fuzzy match.
-- Functions instead of operators make this hella messy.
rd[j] = bor(
band(
bor(
lshift(rd[j + 1], 1),
1
),
charMatch
),
bor(
bor(
lshift(bor(last_rd[j + 1], last_rd[j]), 1),
1
),
last_rd[j + 1]
)
)
end
if (band(rd[j], matchmask) ~= 0) then
local score = _match_bitapScore(d, j - 1)
-- This match will almost certainly be better than any existing match.
-- But check anyway.
if (score <= score_threshold) then
-- Told you so.
score_threshold = score
best_loc = j - 1
if (best_loc > loc) then
-- When passing loc, don't exceed our current distance from loc.
start = max(1, loc * 2 - best_loc)
else
-- Already passed loc, downhill from here on in.
break
end
end
end
end
-- No hope for a (better) match at greater error levels.
if (_match_bitapScore(d + 1, loc) > score_threshold) then
break
end
last_rd = rd
end
return best_loc
end
-- -----------------------------------------------------------------------------
-- PATCH API
-- -----------------------------------------------------------------------------
local _patch_addContext,
_patch_deepCopy,
_patch_addPadding,
_patch_splitMax,
_patch_appendText,
_new_patch_obj
--[[
* Compute a list of patches to turn text1 into text2.
* Use diffs if provided, otherwise compute it ourselves.
* There are four ways to call this function, depending on what data is
* available to the caller:
* Method 1:
* a = text1, b = text2
* Method 2:
* a = diffs
* Method 3 (optimal):
* a = text1, b = diffs
* Method 4 (deprecated, use method 3):
* a = text1, b = text2, c = diffs
*
* @param {string|Array.<Array.<number|string>>} a text1 (methods 1,3,4) or
* Array of diff tuples for text1 to text2 (method 2).
* @param {string|Array.<Array.<number|string>>} opt_b text2 (methods 1,4) or
* Array of diff tuples for text1 to text2 (method 3) or undefined (method 2).
* @param {string|Array.<Array.<number|string>>} opt_c Array of diff tuples for
* text1 to text2 (method 4) or undefined (methods 1,2,3).
* @return {Array.<_new_patch_obj>} Array of patch objects.
--]]
function patch_make(a, opt_b, opt_c)
local text1, diffs
local type_a, type_b, type_c = type(a), type(opt_b), type(opt_c)
if (type_a == 'string') and (type_b == 'string') and (type_c == 'nil') then
-- Method 1: text1, text2
-- Compute diffs from text1 and text2.
text1 = a
diffs = diff_main(text1, opt_b, true)
if (#diffs > 2) then
diff_cleanupSemantic(diffs)
diff_cleanupEfficiency(diffs)
end
elseif (type_a == 'table') and (type_b == 'nil') and (type_c == 'nil') then
-- Method 2: diffs
-- Compute text1 from diffs.
diffs = a
text1 = _diff_text1(diffs)
elseif (type_a == 'string') and (type_b == 'table') and (type_c == 'nil') then
-- Method 3: text1, diffs
text1 = a
diffs = opt_b
elseif (type_a == 'string') and (type_b == 'string') and (type_c == 'table')
then
-- Method 4: text1, text2, diffs
-- text2 is not used.
text1 = a
diffs = opt_c
else
error('Unknown call format to patch_make.')
end
if (diffs[1] == nil) then
return {} -- Get rid of the null case.
end
local patches = {}
local patch = _new_patch_obj()
local patchDiffLength = 0 -- Keeping our own length var is faster.
local char_count1 = 0 -- Number of characters into the text1 string.
local char_count2 = 0 -- Number of characters into the text2 string.
-- Start with text1 (prepatch_text) and apply the diffs until we arrive at
-- text2 (postpatch_text). We recreate the patches one by one to determine
-- context info.
local prepatch_text, postpatch_text = text1, text1
for x, diff in ipairs(diffs) do
local diff_type, diff_text = diff[1], diff[2]
if (patchDiffLength == 0) and (diff_type ~= DIFF_EQUAL) then
-- A new patch starts here.
patch.start1 = char_count1 + 1
patch.start2 = char_count2 + 1
end
if (diff_type == DIFF_INSERT) then
patchDiffLength = patchDiffLength + 1
patch.diffs[patchDiffLength] = diff
patch.length2 = patch.length2 + #diff_text
postpatch_text = strsub(postpatch_text, 1, char_count2)
.. diff_text .. strsub(postpatch_text, char_count2 + 1)
elseif (diff_type == DIFF_DELETE) then
patch.length1 = patch.length1 + #diff_text
patchDiffLength = patchDiffLength + 1
patch.diffs[patchDiffLength] = diff
postpatch_text = strsub(postpatch_text, 1, char_count2)
.. strsub(postpatch_text, char_count2 + #diff_text + 1)
elseif (diff_type == DIFF_EQUAL) then
if (#diff_text <= Patch_Margin * 2)
and (patchDiffLength ~= 0) and (#diffs ~= x) then
-- Small equality inside a patch.
patchDiffLength = patchDiffLength + 1
patch.diffs[patchDiffLength] = diff
patch.length1 = patch.length1 + #diff_text
patch.length2 = patch.length2 + #diff_text
elseif (#diff_text >= Patch_Margin * 2) then
-- Time for a new patch.
if (patchDiffLength ~= 0) then
_patch_addContext(patch, prepatch_text)
patches[#patches + 1] = patch
patch = _new_patch_obj()
patchDiffLength = 0
-- Unlike Unidiff, our patch lists have a rolling context.
-- http://code.google.com/p/google-diff-match-patch/wiki/Unidiff
-- Update prepatch text & pos to reflect the application of the
-- just completed patch.
prepatch_text = postpatch_text
char_count1 = char_count2
end
end
end
-- Update the current character count.
if (diff_type ~= DIFF_INSERT) then
char_count1 = char_count1 + #diff_text
end
if (diff_type ~= DIFF_DELETE) then
char_count2 = char_count2 + #diff_text
end
end
-- Pick up the leftover patch if not empty.
if (patchDiffLength > 0) then
_patch_addContext(patch, prepatch_text)
patches[#patches + 1] = patch
end
return patches
end
--[[
* Merge a set of patches onto the text. Return a patched text, as well
* as a list of true/false values indicating which patches were applied.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @param {string} text Old text.
* @return {Array.<string|Array.<boolean>>} Two return values, the
* new text and an array of boolean values.
--]]
function patch_apply(patches, text)
if patches[1] == nil then
return text, {}
end
-- Deep copy the patches so that no changes are made to originals.
patches = _patch_deepCopy(patches)
local nullPadding = _patch_addPadding(patches)
text = nullPadding .. text .. nullPadding
_patch_splitMax(patches)
-- delta keeps track of the offset between the expected and actual location
-- of the previous patch. If there are patches expected at positions 10 and
-- 20, but the first patch was found at 12, delta is 2 and the second patch
-- has an effective expected position of 22.
local delta = 0
local results = {}
for x, patch in ipairs(patches) do
local expected_loc = patch.start2 + delta
local text1 = _diff_text1(patch.diffs)
local start_loc
local end_loc = -1
if #text1 > Match_MaxBits then
-- _patch_splitMax will only provide an oversized pattern in
-- the case of a monster delete.
start_loc = match_main(text,
strsub(text1, 1, Match_MaxBits), expected_loc)
if start_loc ~= -1 then
end_loc = match_main(text, strsub(text1, -Match_MaxBits),
expected_loc + #text1 - Match_MaxBits)
if end_loc == -1 or start_loc >= end_loc then
-- Can't find valid trailing context. Drop this patch.
start_loc = -1
end
end
else
start_loc = match_main(text, text1, expected_loc)
end
if start_loc == -1 then
-- No match found. :(
results[x] = false
-- Subtract the delta for this failed patch from subsequent patches.
delta = delta - patch.length2 - patch.length1
else
-- Found a match. :)
results[x] = true
delta = start_loc - expected_loc
local text2
if end_loc == -1 then
text2 = strsub(text, start_loc, start_loc + #text1 - 1)
else
text2 = strsub(text, start_loc, end_loc + Match_MaxBits - 1)
end
if text1 == text2 then
-- Perfect match, just shove the replacement text in.
text = strsub(text, 1, start_loc - 1) .. _diff_text2(patch.diffs)
.. strsub(text, start_loc + #text1)
else
-- Imperfect match. Run a diff to get a framework of equivalent
-- indices.
local diffs = diff_main(text1, text2, false)
if (#text1 > Match_MaxBits)
and (diff_levenshtein(diffs) / #text1 > Patch_DeleteThreshold) then
-- The end points match, but the content is unacceptably bad.
results[x] = false
else
_diff_cleanupSemanticLossless(diffs)
local index1 = 1
local index2
for y, mod in ipairs(patch.diffs) do
if mod[1] ~= DIFF_EQUAL then
index2 = _diff_xIndex(diffs, index1)
end
if mod[1] == DIFF_INSERT then
text = strsub(text, 1, start_loc + index2 - 2)
.. mod[2] .. strsub(text, start_loc + index2 - 1)
elseif mod[1] == DIFF_DELETE then
text = strsub(text, 1, start_loc + index2 - 2) .. strsub(text,
start_loc + _diff_xIndex(diffs, index1 + #mod[2] - 1))
end
if mod[1] ~= DIFF_DELETE then
index1 = index1 + #mod[2]
end
end
end
end
end
end
-- Strip the padding off.
text = strsub(text, #nullPadding + 1, -#nullPadding - 1)
return text, results
end
--[[
* Take a list of patches and return a textual representation.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @return {string} Text representation of patches.
--]]
function patch_toText(patches)
local text = {}
for x, patch in ipairs(patches) do
_patch_appendText(patch, text)
end
return tconcat(text)
end
--[[
* Parse a textual representation of patches and return a list of patch objects.
* @param {string} textline Text representation of patches.
* @return {Array.<_new_patch_obj>} Array of patch objects.
* @throws {Error} If invalid input.
--]]
function patch_fromText(textline)
local patches = {}
if (#textline == 0) then
return patches
end
local text = {}
for line in gmatch(textline, '([^\n]*)') do
text[#text + 1] = line
end
local textPointer = 1
while (textPointer <= #text) do
local start1, length1, start2, length2
= strmatch(text[textPointer], '^@@ %-(%d+),?(%d*) %+(%d+),?(%d*) @@$')
if (start1 == nil) then
error('Invalid patch string: "' .. text[textPointer] .. '"')
end
local patch = _new_patch_obj()
patches[#patches + 1] = patch
start1 = tonumber(start1)
length1 = tonumber(length1) or 1
if (length1 == 0) then
start1 = start1 + 1
end
patch.start1 = start1
patch.length1 = length1
start2 = tonumber(start2)
length2 = tonumber(length2) or 1
if (length2 == 0) then
start2 = start2 + 1
end
patch.start2 = start2
patch.length2 = length2
textPointer = textPointer + 1
while true do
local line = text[textPointer]
if (line == nil) then
break
end
local sign; sign, line = strsub(line, 1, 1), strsub(line, 2)
local invalidDecode = false
local decoded = gsub(line, '%%(.?.?)',
function(c)
local n = tonumber(c, 16)
if (#c ~= 2) or (n == nil) then
invalidDecode = true
return ''
end
return strchar(n)
end)
if invalidDecode then
-- Malformed URI sequence.
error('Illegal escape in patch_fromText: ' .. line)
end
line = decoded
if (sign == '-') then
-- Deletion.
patch.diffs[#patch.diffs + 1] = {DIFF_DELETE, line}
elseif (sign == '+') then
-- Insertion.
patch.diffs[#patch.diffs + 1] = {DIFF_INSERT, line}
elseif (sign == ' ') then
-- Minor equality.
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, line}
elseif (sign == '@') then
-- Start of next patch.
break
elseif (sign == '') then
-- Blank line? Whatever.
else
-- WTF?
error('Invalid patch mode "' .. sign .. '" in: ' .. line)
end
textPointer = textPointer + 1
end
end
return patches
end
-- ---------------------------------------------------------------------------
-- UNOFFICIAL/PRIVATE PATCH FUNCTIONS
-- ---------------------------------------------------------------------------
local patch_meta = {
__tostring = function(patch)
local buf = {}
_patch_appendText(patch, buf)
return tconcat(buf)
end
}
--[[
* Class representing one patch operation.
* @constructor
--]]
function _new_patch_obj()
return setmetatable({
--[[ @type {Array.<Array.<number|string>>} ]]
diffs = {};
--[[ @type {?number} ]]
start1 = 1; -- nil;
--[[ @type {?number} ]]
start2 = 1; -- nil;
--[[ @type {number} ]]
length1 = 0;
--[[ @type {number} ]]
length2 = 0;
}, patch_meta)
end
--[[
* Increase the context until it is unique,
* but don't let the pattern expand beyond Match_MaxBits.
* @param {_new_patch_obj} patch The patch to grow.
* @param {string} text Source text.
* @private
--]]
function _patch_addContext(patch, text)
if (#text == 0) then
return
end
local pattern = strsub(text, patch.start2, patch.start2 + patch.length1 - 1)
local padding = 0
-- LUANOTE: Lua's lack of a lastIndexOf function results in slightly
-- different logic here than in other language ports.
-- Look for the first two matches of pattern in text. If two are found,
-- increase the pattern length.
local firstMatch = indexOf(text, pattern)
local secondMatch = nil
if (firstMatch ~= nil) then
secondMatch = indexOf(text, pattern, firstMatch + 1)
end
while (#pattern == 0 or secondMatch ~= nil)
and (#pattern < Match_MaxBits - Patch_Margin - Patch_Margin) do
padding = padding + Patch_Margin
pattern = strsub(text, max(1, patch.start2 - padding),
patch.start2 + patch.length1 - 1 + padding)
firstMatch = indexOf(text, pattern)
if (firstMatch ~= nil) then
secondMatch = indexOf(text, pattern, firstMatch + 1)
else
secondMatch = nil
end
end
-- Add one chunk for good luck.
padding = padding + Patch_Margin
-- Add the prefix.
local prefix = strsub(text, max(1, patch.start2 - padding), patch.start2 - 1)
if (#prefix > 0) then
tinsert(patch.diffs, 1, {DIFF_EQUAL, prefix})
end
-- Add the suffix.
local suffix = strsub(text, patch.start2 + patch.length1,
patch.start2 + patch.length1 - 1 + padding)
if (#suffix > 0) then
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, suffix}
end
-- Roll back the start points.
patch.start1 = patch.start1 - #prefix
patch.start2 = patch.start2 - #prefix
-- Extend the lengths.
patch.length1 = patch.length1 + #prefix + #suffix
patch.length2 = patch.length2 + #prefix + #suffix
end
--[[
* Given an array of patches, return another array that is identical.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @return {Array.<_new_patch_obj>} Array of patch objects.
--]]
function _patch_deepCopy(patches)
local patchesCopy = {}
for x, patch in ipairs(patches) do
local patchCopy = _new_patch_obj()
local diffsCopy = {}
for i, diff in ipairs(patch.diffs) do
diffsCopy[i] = {diff[1], diff[2]}
end
patchCopy.diffs = diffsCopy
patchCopy.start1 = patch.start1
patchCopy.start2 = patch.start2
patchCopy.length1 = patch.length1
patchCopy.length2 = patch.length2
patchesCopy[x] = patchCopy
end
return patchesCopy
end
--[[
* Add some padding on text start and end so that edges can match something.
* Intended to be called only from within patch_apply.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @return {string} The padding string added to each side.
--]]
function _patch_addPadding(patches)
local paddingLength = Patch_Margin
local nullPadding = ''
for x = 1, paddingLength do
nullPadding = nullPadding .. strchar(x)
end
-- Bump all the patches forward.
for x, patch in ipairs(patches) do
patch.start1 = patch.start1 + paddingLength
patch.start2 = patch.start2 + paddingLength
end
-- Add some padding on start of first diff.
local patch = patches[1]
local diffs = patch.diffs
local firstDiff = diffs[1]
if (firstDiff == nil) or (firstDiff[1] ~= DIFF_EQUAL) then
-- Add nullPadding equality.
tinsert(diffs, 1, {DIFF_EQUAL, nullPadding})
patch.start1 = patch.start1 - paddingLength -- Should be 0.
patch.start2 = patch.start2 - paddingLength -- Should be 0.
patch.length1 = patch.length1 + paddingLength
patch.length2 = patch.length2 + paddingLength
elseif (paddingLength > #firstDiff[2]) then
-- Grow first equality.
local extraLength = paddingLength - #firstDiff[2]
firstDiff[2] = strsub(nullPadding, #firstDiff[2] + 1) .. firstDiff[2]
patch.start1 = patch.start1 - extraLength
patch.start2 = patch.start2 - extraLength
patch.length1 = patch.length1 + extraLength
patch.length2 = patch.length2 + extraLength
end
-- Add some padding on end of last diff.
patch = patches[#patches]
diffs = patch.diffs
local lastDiff = diffs[#diffs]
if (lastDiff == nil) or (lastDiff[1] ~= DIFF_EQUAL) then
-- Add nullPadding equality.
diffs[#diffs + 1] = {DIFF_EQUAL, nullPadding}
patch.length1 = patch.length1 + paddingLength
patch.length2 = patch.length2 + paddingLength
elseif (paddingLength > #lastDiff[2]) then
-- Grow last equality.
local extraLength = paddingLength - #lastDiff[2]
lastDiff[2] = lastDiff[2] .. strsub(nullPadding, 1, extraLength)
patch.length1 = patch.length1 + extraLength
patch.length2 = patch.length2 + extraLength
end
return nullPadding
end
--[[
* Look through the patches and break up any which are longer than the maximum
* limit of the match algorithm.
* Intended to be called only from within patch_apply.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
--]]
function _patch_splitMax(patches)
local patch_size = Match_MaxBits
local x = 1
while true do
local patch = patches[x]
if patch == nil then
return
end
if patch.length1 > patch_size then
local bigpatch = patch
-- Remove the big old patch.
tremove(patches, x)
x = x - 1
local start1 = bigpatch.start1
local start2 = bigpatch.start2
local precontext = ''
while bigpatch.diffs[1] do
-- Create one of several smaller patches.
local patch = _new_patch_obj()
local empty = true
patch.start1 = start1 - #precontext
patch.start2 = start2 - #precontext
if precontext ~= '' then
patch.length1, patch.length2 = #precontext, #precontext
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, precontext}
end
while bigpatch.diffs[1] and (patch.length1 < patch_size-Patch_Margin) do
local diff_type = bigpatch.diffs[1][1]
local diff_text = bigpatch.diffs[1][2]
if (diff_type == DIFF_INSERT) then
-- Insertions are harmless.
patch.length2 = patch.length2 + #diff_text
start2 = start2 + #diff_text
patch.diffs[#(patch.diffs) + 1] = bigpatch.diffs[1]
tremove(bigpatch.diffs, 1)
empty = false
elseif (diff_type == DIFF_DELETE) and (#patch.diffs == 1)
and (patch.diffs[1][1] == DIFF_EQUAL)
and (#diff_text > 2 * patch_size) then
-- This is a large deletion. Let it pass in one chunk.
patch.length1 = patch.length1 + #diff_text
start1 = start1 + #diff_text
empty = false
patch.diffs[#patch.diffs + 1] = {diff_type, diff_text}
tremove(bigpatch.diffs, 1)
else
-- Deletion or equality.
-- Only take as much as we can stomach.
diff_text = strsub(diff_text, 1,
patch_size - patch.length1 - Patch_Margin)
patch.length1 = patch.length1 + #diff_text
start1 = start1 + #diff_text
if (diff_type == DIFF_EQUAL) then
patch.length2 = patch.length2 + #diff_text
start2 = start2 + #diff_text
else
empty = false
end
patch.diffs[#patch.diffs + 1] = {diff_type, diff_text}
if (diff_text == bigpatch.diffs[1][2]) then
tremove(bigpatch.diffs, 1)
else
bigpatch.diffs[1][2]
= strsub(bigpatch.diffs[1][2], #diff_text + 1)
end
end
end
-- Compute the head context for the next patch.
precontext = _diff_text2(patch.diffs)
precontext = strsub(precontext, -Patch_Margin)
-- Append the end context for this patch.
local postcontext = strsub(_diff_text1(bigpatch.diffs), 1, Patch_Margin)
if postcontext ~= '' then
patch.length1 = patch.length1 + #postcontext
patch.length2 = patch.length2 + #postcontext
if patch.diffs[1]
and (patch.diffs[#patch.diffs][1] == DIFF_EQUAL) then
patch.diffs[#patch.diffs][2] = patch.diffs[#patch.diffs][2]
.. postcontext
else
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, postcontext}
end
end
if not empty then
x = x + 1
tinsert(patches, x, patch)
end
end
end
x = x + 1
end
end
--[[
* Emulate GNU diff's format.
* Header: @@ -382,8 +481,9 @@
* @return {string} The GNU diff string.
--]]
function _patch_appendText(patch, text)
local coords1, coords2
local length1, length2 = patch.length1, patch.length2
local start1, start2 = patch.start1, patch.start2
local diffs = patch.diffs
if length1 == 1 then
coords1 = start1
else
coords1 = ((length1 == 0) and (start1 - 1) or start1) .. ',' .. length1
end
if length2 == 1 then
coords2 = start2
else
coords2 = ((length2 == 0) and (start2 - 1) or start2) .. ',' .. length2
end
text[#text + 1] = '@@ -' .. coords1 .. ' +' .. coords2 .. ' @@\n'
local op
-- Escape the body of the patch with %xx notation.
for x, diff in ipairs(patch.diffs) do
local diff_type = diff[1]
if diff_type == DIFF_INSERT then
op = '+'
elseif diff_type == DIFF_DELETE then
op = '-'
elseif diff_type == DIFF_EQUAL then
op = ' '
end
text[#text + 1] = op
.. gsub(diffs[x][2], percentEncode_pattern, percentEncode_replace)
.. '\n'
end
return text
end
-- Expose the API
local _M = {}
_M.DIFF_DELETE = DIFF_DELETE
_M.DIFF_INSERT = DIFF_INSERT
_M.DIFF_EQUAL = DIFF_EQUAL
_M.diff_main = diff_main
_M.diff_cleanupSemantic = diff_cleanupSemantic
_M.diff_cleanupEfficiency = diff_cleanupEfficiency
_M.diff_levenshtein = diff_levenshtein
_M.diff_prettyHtml = diff_prettyHtml
_M.match_main = match_main
_M.patch_make = patch_make
_M.patch_toText = patch_toText
_M.patch_fromText = patch_fromText
_M.patch_apply = patch_apply
-- Expose some non-API functions as well, for testing purposes etc.
_M.diff_commonPrefix = _diff_commonPrefix
_M.diff_commonSuffix = _diff_commonSuffix
_M.diff_commonOverlap = _diff_commonOverlap
_M.diff_halfMatch = _diff_halfMatch
_M.diff_bisect = _diff_bisect
_M.diff_cleanupMerge = _diff_cleanupMerge
_M.diff_cleanupSemanticLossless = _diff_cleanupSemanticLossless
_M.diff_text1 = _diff_text1
_M.diff_text2 = _diff_text2
_M.diff_toDelta = _diff_toDelta
_M.diff_fromDelta = _diff_fromDelta
_M.diff_xIndex = _diff_xIndex
_M.match_alphabet = _match_alphabet
_M.match_bitap = _match_bitap
_M.new_patch_obj = _new_patch_obj
_M.patch_addContext = _patch_addContext
_M.patch_splitMax = _patch_splitMax
_M.patch_addPadding = _patch_addPadding
_M.settings = settings
return _M
| apache-2.0 |
AresTao/darkstar | scripts/zones/Garlaige_Citadel/TextIDs.lua | 7 | 1860 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6538; -- You cannot obtain the item <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6542; -- Obtained: <item>.
GIL_OBTAINED = 6543; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6545; -- Obtained key item: <keyitem>.
-- Treasure Coffer/Chest Dialog
CHEST_UNLOCKED = 7316; -- You unlock the chest!
CHEST_FAIL = 7317; -- Fails to open the chest.
CHEST_TRAP = 7318; -- The chest was trapped!
CHEST_WEAK = 7319; -- You cannot open the chest when you are in a weakened state.
CHEST_MIMIC = 7320; -- The chest was a mimic!
CHEST_MOOGLE = 7321; -- You cannot open the chest while participating in the moogle event.
CHEST_ILLUSION = 7322; -- The chest was but an illusion...
CHEST_LOCKED = 7323; -- The chest appears to be locked.
-- Dialog Texts
SENSE_OF_FOREBODING = 6557; -- You are suddenly overcome with a sense of foreboding...
YOU_FIND_NOTHING = 7284; -- You find nothing special.
PRESENCE_FROM_CEILING = 7286; -- You sense a presence from in the ceiling.?Prompt?
HEAT_FROM_CEILING = 7287; -- You feel a terrible heat from the ceiling.
-- Door dialog
A_GATE_OF_STURDY_STEEL = 7262; -- A gate of sturdy steel.
OPEN_WITH_THE_RIGHT_KEY = 7268; -- You might be able to open it with the right key.
BANISHING_GATES = 7277; -- The first banishing gate begins to open...
BANISHING_GATES_CLOSING = 7280; -- The first banishing gate starts to close.
-- Other
NOTHING_OUT_OF_THE_ORDINARY = 6556; -- There is nothing out of the ordinary here.
-- conquest Base
CONQUEST_BASE = 0;
-- Strange Apparatus
DEVICE_NOT_WORKING = 7224; -- The device is not working.
SYS_OVERLOAD = 7233; -- arning! Sys...verload! Enterin...fety mode. ID eras...d
YOU_LOST_THE = 7238; -- You lost the #.
| gpl-3.0 |
AresTao/darkstar | scripts/zones/Beaucedine_Glacier/npcs/Luck_Rune.lua | 34 | 1089 | -----------------------------------
-- Area: Beaucedine Glacier
-- NPC: Luck Rune
-- Involved in Quest: Mhaura Fortune
-- @pos 70.736 -37.778 149.624 111
-----------------------------------
package.loaded["scripts/zones/Beaucedine_Glacier/TextIDs"] = nil;
-------------------------------------
require("scripts/zones/Beaucedine_Glacier/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_THE_ORDINARY);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
AresTao/darkstar | scripts/zones/Lower_Jeuno/npcs/_l08.lua | 36 | 1561 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Streetlamp
-- Involved in Quests: Community Service
-- @zone 245
-- @pos -32.897 0 -28.521
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local hour = VanadielHour();
if (hour >= 18 and hour < 21) then
if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_ACCEPTED) then
if (player:getVar("cService") == 3) then
player:setVar("cService",4);
end
elseif (hour >= 18 and hour < 21) then
if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED) then
if (player:getVar("cService") == 16) then
player:setVar("cService",17);
end
end
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
prosody-modules/import | mod_couchdb/couchdb/couchapi.lib.lua | 32 | 2213 |
local setmetatable = setmetatable;
local pcall = pcall;
local type = type;
local t_concat = table.concat;
local print = print;
local socket_url = require "socket.url";
local http = require "socket.http";
local ltn12 = require "ltn12";
--local json = require "json";
local json = module:require("couchdb/json");
--module("couchdb")
local _M = {};
local function urlcat(url, path)
return url:gsub("/*$", "").."/"..path:gsub("^/*", "");
end
local doc_mt = {};
doc_mt.__index = doc_mt;
function doc_mt:get()
return self.db:get(socket_url.escape(self.id));
end
function doc_mt:put(val)
return self.db:put(socket_url.escape(self.id), val);
end
function doc_mt:__tostring()
return "couchdb.doc("..self.url..")";
end
local db_mt = {};
db_mt.__index = db_mt;
function db_mt:__tostring()
return "couchdb.db("..self.url..")";
end
function db_mt:doc(id)
local url = urlcat(self.url, socket_url.escape(id));
return setmetatable({ url = url, db = self, id = id }, doc_mt);
end
function db_mt:get(id)
local url = urlcat(self.url, id);
local a,b = http.request(url);
local r,x = pcall(json.decode, a);
if r then a = x; end
return a,b;
end
function db_mt:put(id, value)
local url = urlcat(self.url, id);
if type(value) == "table" then
value = json.encode(value);
elseif value ~= nil and type(value) ~= "string" then
return nil, "Invalid type";
end
local t = {};
local a,b = http.request {
url = url,
sink = ltn12.sink.table(t),
source = ltn12.source.string(value),
method = "PUT",
headers = {
["Content-Length"] = #value,
["Content-Type"] = "application/json"
}
};
a = t_concat(t);
local r,x = pcall(json.decode, a);
if r then a = x; end
return a,b;
end
local server_mt = {};
server_mt.__index = server_mt;
function server_mt:db(name)
local url = urlcat(self.url, socket_url.escape(name));
return setmetatable({ url = url }, db_mt);
end
function server_mt:__tostring()
return "couchdb.server("..self.url..")";
end
function _M.server(url)
return setmetatable({ url = url }, server_mt);
end
function _M.db(url)
return setmetatable({ url = url }, db_mt);
end
return _M;
| mit |
AresTao/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Milazahn.lua | 34 | 1033 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Milazahn
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0252);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
AresTao/darkstar | scripts/globals/spells/bluemagic/magic_fruit.lua | 18 | 1794 | -----------------------------------------
-- Spell: Magic Fruit
-- Restores HP for the target party member
-- Spell cost: 72 MP
-- Monster Type: Beasts
-- Spell Type: Magical (Light)
-- Blue Magic Points: 3
-- Stat Bonus: CHR+1 HP+5
-- Level: 58
-- Casting Time: 3.5 seconds
-- Recast Time: 6 seconds
--
-- Combos: Resist Sleep
-----------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local minCure = 250;
local divisor = 0.6666;
local constant = 130;
local power = getCurePowerOld(caster);
local final = getCureFinal(caster,spell,getBaseCureOld(power,divisor,constant),minCure,true);
local diff = (target:getMaxHP() - target:getHP());
if (power > 559) then
divisor = 2.8333;
constant = 391.2
elseif (power > 319) then
divisor = 1;
constant = 210;
end
final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100));
if (target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == TYPE_PC or target:getObjType() == TYPE_MOB)) then
--Applying server mods....
final = final * CURE_POWER;
end
if (final > diff) then
final = diff;
end
target:addHP(final);
target:wakeUp();
caster:updateEnmityFromCure(target,final);
spell:setMsg(7);
return final;
end; | gpl-3.0 |
Jmainguy/docker_images | prosody/prosody/lib/luarocks/rocks/luasocket/3.0rc1-1/test/ltn12test.lua | 12 | 8625 | local ltn12 = require("ltn12")
dofile("testsupport.lua")
local function format(chunk)
if chunk then
if chunk == "" then return "''"
else return string.len(chunk) end
else return "nil" end
end
local function show(name, input, output)
local sin = format(input)
local sout = format(output)
io.write(name, ": ", sin, " -> ", sout, "\n")
end
local function chunked(length)
local tmp
return function(chunk)
local ret
if chunk and chunk ~= "" then
tmp = chunk
end
ret = string.sub(tmp, 1, length)
tmp = string.sub(tmp, length+1)
if not chunk and ret == "" then ret = nil end
return ret
end
end
local function named(f, name)
return function(chunk)
local ret = f(chunk)
show(name, chunk, ret)
return ret
end
end
--------------------------------
local function split(size)
local buffer = ""
local last_out = ""
local last_in = ""
local function output(chunk)
local part = string.sub(buffer, 1, size)
buffer = string.sub(buffer, size+1)
last_out = (part ~= "" or chunk) and part
last_in = chunk
return last_out
end
return function(chunk, done)
if done then
return not last_in and not last_out
end
-- check if argument is consistent with state
if not chunk then
if last_in and last_in ~= "" and last_out ~= "" then
error("nil chunk following data chunk", 2)
end
if not last_out then error("extra nil chunk", 2) end
return output(chunk)
elseif chunk == "" then
if last_out == "" then error('extra "" chunk', 2) end
if not last_out then error('"" chunk following nil return', 2) end
if not last_in then error('"" chunk following nil chunk', 2) end
return output(chunk)
else
if not last_in then error("data chunk following nil chunk", 2) end
if last_in ~= "" and last_out ~= "" then
error("data chunk following data chunk", 2)
end
buffer = chunk
return output(chunk)
end
end
end
--------------------------------
local function format(chunk)
if chunk then
if chunk == "" then return "''"
else return string.len(chunk) end
else return "nil" end
end
--------------------------------
local function merge(size)
local buffer = ""
local last_out = ""
local last_in = ""
local function output(chunk)
local part
if string.len(buffer) >= size or not chunk then
part = buffer
buffer = ""
else
part = ""
end
last_out = (part ~= "" or chunk) and part
last_in = chunk
return last_out
end
return function(chunk, done)
if done then
return not last_in and not last_out
end
-- check if argument is consistent with state
if not chunk then
if last_in and last_in ~= "" and last_out ~= "" then
error("nil chunk following data chunk", 2)
end
if not last_out then error("extra nil chunk", 2) end
return output(chunk)
elseif chunk == "" then
if last_out == "" then error('extra "" chunk', 2) end
if not last_out then error('"" chunk following nil return', 2) end
if not last_in then error('"" chunk following nil chunk', 2) end
return output(chunk)
else
if not last_in then error("data chunk following nil chunk", 2) end
if last_in ~= "" and last_out ~= "" then
error("data chunk following data chunk", 2)
end
buffer = buffer .. chunk
return output(chunk)
end
end
end
--------------------------------
io.write("testing sink.table: ")
local sink, t = ltn12.sink.table()
local s, c = "", ""
for i = 0, 10 do
c = string.rep(string.char(i), i)
s = s .. c
assert(sink(c), "returned error")
end
assert(sink(nil), "returned error")
assert(table.concat(t) == s, "mismatch")
print("ok")
--------------------------------
io.write("testing sink.chain (with split): ")
sink, t = ltn12.sink.table()
local filter = split(3)
sink = ltn12.sink.chain(filter, sink)
s = "123456789012345678901234567890"
assert(sink(s), "returned error")
assert(sink(s), "returned error")
assert(sink(nil), "returned error")
assert(table.concat(t) == s .. s, "mismatch")
assert(filter(nil, 1), "filter not empty")
print("ok")
--------------------------------
io.write("testing sink.chain (with merge): ")
sink, t = ltn12.sink.table()
filter = merge(10)
sink = ltn12.sink.chain(filter, sink)
s = string.rep("123", 30)
s = s .. string.rep("4321", 30)
for i = 1, 30 do
assert(sink("123"), "returned error")
end
for i = 1, 30 do
assert(sink("4321"), "returned error")
end
assert(sink(nil), "returned error")
assert(filter(nil, 1), "filter not empty")
assert(table.concat(t) == s, "mismatch")
print("ok")
--------------------------------
io.write("testing source.string and pump.all: ")
local source = ltn12.source.string(s)
sink, t = ltn12.sink.table()
assert(ltn12.pump.all(source, sink), "returned error")
assert(table.concat(t) == s, "mismatch")
print("ok")
--------------------------------
io.write("testing source.chain (with split): ")
source = ltn12.source.string(s)
filter = split(5)
source = ltn12.source.chain(source, filter)
sink, t = ltn12.sink.table()
assert(ltn12.pump.all(source, sink), "returned error")
assert(table.concat(t) == s, "mismatch")
assert(filter(nil, 1), "filter not empty")
print("ok")
--------------------------------
io.write("testing source.chain (with split) and sink.chain (with merge): ")
source = ltn12.source.string(s)
filter = split(5)
source = ltn12.source.chain(source, filter)
local filter2 = merge(13)
sink, t = ltn12.sink.table()
sink = ltn12.sink.chain(filter2, sink)
assert(ltn12.pump.all(source, sink), "returned error")
assert(table.concat(t) == s, "mismatch")
assert(filter(nil, 1), "filter not empty")
assert(filter2(nil, 1), "filter2 not empty")
print("ok")
--------------------------------
io.write("testing filter.chain (and sink.chain, with split, merge): ")
source = ltn12.source.string(s)
filter = split(5)
filter2 = merge(13)
local chain = ltn12.filter.chain(filter, filter2)
sink, t = ltn12.sink.table()
sink = ltn12.sink.chain(chain, sink)
assert(ltn12.pump.all(source, sink), "returned error")
assert(table.concat(t) == s, "mismatch")
assert(filter(nil, 1), "filter not empty")
assert(filter2(nil, 1), "filter2 not empty")
print("ok")
--------------------------------
io.write("testing filter.chain (and sink.chain, a bunch): ")
source = ltn12.source.string(s)
filter = split(5)
filter2 = merge(13)
local filter3 = split(7)
local filter4 = merge(11)
local filter5 = split(10)
chain = ltn12.filter.chain(filter, filter2, filter3, filter4, filter5)
sink, t = ltn12.sink.table()
sink = ltn12.sink.chain(chain, sink)
assert(ltn12.pump.all(source, sink))
assert(table.concat(t) == s, "mismatch")
assert(filter(nil, 1), "filter not empty")
assert(filter2(nil, 1), "filter2 not empty")
assert(filter3(nil, 1), "filter3 not empty")
assert(filter4(nil, 1), "filter4 not empty")
assert(filter5(nil, 1), "filter5 not empty")
print("ok")
--------------------------------
io.write("testing filter.chain (and source.chain, with split, merge): ")
source = ltn12.source.string(s)
filter = split(5)
filter2 = merge(13)
local chain = ltn12.filter.chain(filter, filter2)
sink, t = ltn12.sink.table()
source = ltn12.source.chain(source, chain)
assert(ltn12.pump.all(source, sink), "returned error")
assert(table.concat(t) == s, "mismatch")
assert(filter(nil, 1), "filter not empty")
assert(filter2(nil, 1), "filter2 not empty")
print("ok")
--------------------------------
io.write("testing filter.chain (and source.chain, a bunch): ")
source = ltn12.source.string(s)
filter = split(5)
filter2 = merge(13)
local filter3 = split(7)
local filter4 = merge(11)
local filter5 = split(10)
chain = ltn12.filter.chain(filter, filter2, filter3, filter4, filter5)
sink, t = ltn12.sink.table()
source = ltn12.source.chain(source, chain)
assert(ltn12.pump.all(source, sink))
assert(table.concat(t) == s, "mismatch")
assert(filter(nil, 1), "filter not empty")
assert(filter2(nil, 1), "filter2 not empty")
assert(filter3(nil, 1), "filter3 not empty")
assert(filter4(nil, 1), "filter4 not empty")
assert(filter5(nil, 1), "filter5 not empty")
print("ok")
| gpl-2.0 |
AresTao/darkstar | scripts/globals/items/dish_of_spaghetti_nero_di_seppia_+1.lua | 36 | 1731 | -----------------------------------------
-- ID: 5202
-- Item: Dish of Spaghetti Nero Di Seppia +1
-- Food Effect: 60 Mins, All Races
-----------------------------------------
-- HP % 17 (cap 140)
-- Dexterity 3
-- Vitality 2
-- Agility -1
-- Mind -2
-- Charisma -1
-- Double Attack 1
-- Store TP 6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5202);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 17);
target:addMod(MOD_FOOD_HP_CAP, 140);
target:addMod(MOD_DEX, 3);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_AGI, -1);
target:addMod(MOD_MND, -2);
target:addMod(MOD_CHR, -1);
target:addMod(MOD_DOUBLE_ATTACK, 1);
target:addMod(MOD_STORETP, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 17);
target:delMod(MOD_FOOD_HP_CAP, 140);
target:delMod(MOD_DEX, 3);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_AGI, -1);
target:delMod(MOD_MND, -2);
target:delMod(MOD_CHR, -1);
target:delMod(MOD_DOUBLE_ATTACK, 1);
target:delMod(MOD_STORETP, 6);
end;
| gpl-3.0 |
NREL/api-umbrella | src/api-umbrella/proxy/middleware/api_key_validator.lua | 1 | 1729 | local get_user = require("api-umbrella.proxy.user_store").get
return function(settings)
-- Retrieve the API key found in the resolve_api_key middleware.
local api_key = ngx.ctx.api_key
if not api_key then
if settings and settings["disable_api_key"] then
return nil
else
return nil, "api_key_missing"
end
end
-- Look for the api key in the user database.
local user = get_user(api_key)
if not user then
return nil, "api_key_invalid"
end
-- Store the api key on the user object for easier access (the user object
-- doesn't contain it directly, to save memory storage in the lookup table).
user["api_key"] = api_key
-- Store user details for logging.
ngx.ctx.user_id = user["id"]
ngx.ctx.user_email = user["email"]
ngx.ctx.user_registration_source = user["registration_source"]
-- Check to make sure the user isn't disabled.
if user["disabled_at"] then
return nil, "api_key_disabled"
end
-- Check if this API requires the user's API key be verified in some fashion
-- (for example, if they must verify their e-mail address during signup).
if settings and settings["api_key_verification_level"] then
local verification_level = settings["api_key_verification_level"]
if verification_level == "required_email" then
if not user["email_verified"] then
return nil, "api_key_unverified"
end
elseif verification_level == "transition_email" then
local transition_start_at = settings["_api_key_verification_transition_start_at"]
if user["created_at"] and user["created_at"] >= transition_start_at and not user["email_verified"] then
return nil, "api_key_unverified"
end
end
end
return user
end
| mit |
Milkyway-at-home/milkywayathome_client | nbody/tests/NBodyTesting.lua | 1 | 12977 | --
-- Copyright (C) 2011 Matthew Arsenault
--
-- This file is part of Milkway@Home.
--
-- Milkyway@Home is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Milkyway@Home is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with Milkyway@Home. If not, see <http://www.gnu.org/licenses/>.
--
--
require "persistence"
require "curry"
-- Utility for helping get errors from printf/eprintf only with error reported at actual use site
local function stringFormatCatchError(...)
local args = { ... }
-- trap the errors from string.format so we can tell where the error actually comes from
local success, str = pcall(function() return string.format(unpack(args)) end)
if success then
return str
else
io.stderr:write(str .. "\n") -- str is the error from string.format
error(str, 3) -- call level is not here, and then above printf/eprintf
end
end
function printf(...)
io.stdout:write(stringFormatCatchError(...))
end
function eprintf(...)
io.stderr:write(stringFormatCatchError(...))
end
-- Given a function of an arbitrary number of arguments, and a number
-- of lists corresponding to that number of arguments, returns that
-- function applied to every combination of arguments from the lists.
function buildAllCombinations(f, ...)
-- Apply each function in fs to each value in tbl
local function mapApply(fs, tbl)
return foldl(function(acc, f)
return foldl(function(acc, v)
acc[#acc + 1] = f(v)
return acc
end,
acc,
tbl)
end,
{ },
fs)
end
return foldl(mapApply, { curry(f, #{...}) }, {...})
end
function getKeyNames(t)
local keys = { }
local i = 1
for k, _ in pairs(t) do
keys[i] = k
i = i + 1
end
return keys
end
function printTable(tbl)
assert(type(tbl) == "table", "Expected table to print")
io.stderr:write("------------------------------\n" .. tostring(tbl) .. "\n")
local function printTableMain(t, level)
for k, v in pairs(t) do
local prefix = ""
for i = 0, level do
prefix = prefix .. " "
end
io.stderr:write(prefix .. tostring(k) .. " = " .. tostring(v) .. "\n")
if type(v) == "table" then
printTableMain(v, level + 1)
io.stderr:write("\n")
end
end
end
printTableMain(tbl, 0)
io.stderr:write("------------------------------\n")
end
function deepcopy(object)
local lookup_table = {}
local function _copy(object)
if type(object) ~= "table" then
return object
elseif lookup_table[object] then
return lookup_table[object]
end
local new_table = {}
lookup_table[object] = new_table
for index, value in pairs(object) do
new_table[_copy(index)] = _copy(value)
end
return setmetatable(new_table, getmetatable(object))
end
return _copy(object)
end
function mergeTables(m1, ...)
local i = #m1
for _, m in ipairs({...}) do
for _, v in ipairs(m) do
i = i + 1
m1[i] = v
end
end
return m1
end
function runTest(t)
local status, fatal = "NBODY_SUCCESS", false -- 0 steps is OK
--eprintf("TEST - Before getTestNBodyState\n")
local ctx, st = getTestNBodyState(t)
--eprintf("TEST - Before Step Loop\n")
for i = 1, t.nSteps do
--eprintf("TEST - Before State Step\n")
status = st:step(ctx)
--eprintf("TEST - Before Status Check\n")
fatal = statusIsFatal(status)
if fatal then
assert(false, string.format("Fatal Context after %d steps: %s\n", i, tostring(ctx)))
break
end
end
--eprintf("TEST - Before Sort Bodies\n")
local res = st:hashSortBodies()
--eprintf("TEST - After\n")
return res, status, fatal
end
function runTestSet(tests, resultTable)
resultTable.hashtable = { }
local i = 1
for _, t in ipairs(tests) do
print("Running test ", i, 100 * i / #tests)
printResult(t)
--eprintf("TESTSET - Before runTest\n")
local resultHash, status, failed = runTest(t)
--eprintf("TESTSET - Before hashNBodyTest\n")
local testHash = hashNBodyTest(t)
--eprintf("TESTSET - Before resultTable assignments\n")
resultTable.hashtable[testHash] = t
resultTable.hashtable[testHash].result = resultHash
resultTable.hashtable[testHash].status = status
resultTable.hashtable[testHash].failed = failed
i = i + 1
--eprintf("TESTSET - After\n")
end
return resultTable
end
function generateResultsToFile(tests, resultTable, file)
resultTable = runTestSet(tests, resultTable)
persistence.store(file, resultTable)
end
function loadResultsFromFile(file)
return assert(persistence.load(file), "Failed to load results from file " .. file)
end
function findTestResult(result, resultTable)
local key, foundResult
assert(type(resultTable) == "table", "Expected result table to be a table")
assert(type(result) == "table", "Expected result to look up to be a table")
key = hashNBodyTest(result)
foundResult = resultTable.hashtable[key]
if foundResult == nil then
io.stderr:write("Result for test not found in result table\n")
end
return foundResult
end
function printResult(t)
local fmt =
[[
{
theta = %.15f,
treeRSize = %.15f,
seed = %u,
nbody = %u,
allowIncest = %s,
nSteps = %u,
criterion = "%s",
potential = "%s",
doublePrec = %s,
model = "%s",
useQuad = %s,
LMC = %s,
LMCDynaFric = %s
]]
local str
str = string.format(fmt,
t.theta,
t.treeRSize,
t.seed,
t.nbody,
tostring(t.allowIncest),
t.nSteps,
t.criterion,
t.potential,
tostring(t.doublePrec),
t.model,
tostring(t.useQuad),
tostring(t.LMC),
tostring(t.LMCDynaFric))
local resultFmt =
[[
result = "%s",
status = "%s",
failed = %s
]]
if (t.result ~= nil) then
str = str .. string.format(resultFmt, t.result, tostring(t.status), tostring(t.failed))
end
str = str .. "}\n"
print(str)
end
function checkTestResult(test, resultTable)
local expected = findTestResult(test, resultTable)
if expected == nil then
error("Test result not in result table")
end
assert(expected.result ~= nil, "Hash missing from expected result")
assert(expected.status ~= nil, "Status missing from expected result")
assert(expected.failed ~= nil, "Failed status missing from expected result")
local doesNotMatch = false
local hash, status, failed = runTest(test)
if hash ~= expected.result then
io.stderr:write("Hash does not match expected:\n")
doesNotMatch = true
end
if status ~= expected.status then
io.stderr:write("Status does not match expected:\n")
doesNotMatch = true
end
if failed ~= expected.failed then
io.stderr:write("Failed status does not match expected:\n")
doesNotMatch = true
end
if doesNotMatch then
io.stderr:write("Failing test:\n")
io.stderr:write(string.format("Got hash = %s, status = %s, failed = %s\nExpected:\n",
hash, status, tostring(failed)))
printResult(test)
end
return doesNotMatch
end
-- Marshal between a table with "x" "y" and "z" and the userdata
-- Vector type since persistence can't handle userdata
function vectorToTable(v)
local vTable = { }
vTable.x = v.x
vTable.y = v.y
vTable.z = v.z
return vTable
end
function tableToVector(vTable)
return Vector.create(vTable.x, vTable.y, vTable.z)
end
function os.readProcess(bin, ...)
local args, cmd
args = table.concat({...}, " ")
-- Redirect stderr to stdout, since popen only gets stdout
cmd = table.concat({ bin, args, "2>&1" }, " ")
local f, rc = assert(io.popen(cmd, "r"))
local s = assert(f:read('*a'))
f:close()
return s, rc
end
function getExtraNBodyFlags()
nbodyFlags = os.getenv("NBODY_FLAGS")
if nbodyFlags == nil then
nbodyFlags = ""
end
return nbodyFlags
end
function calcMean(table)
local total = 0.0
assert(type(table) == "table")
if #table == 0 then
return 0.0
end
for k, v in ipairs(table) do
total = total + v
end
return total / #table
end
function calcStddev(table, mean)
local total = 0.0
-- Bad things happen if this ends up nan
if #table == 0 then
return 0.0
end
if mean == nil then
mean = calcMean(table)
end
for k, v in ipairs(table) do
total = total + sqr(v - mean)
end
return sqrt(total / (#table - 1))
end
function calcStats(table)
local avg = calcMean(table)
return avg, calcStddev(table, avg)
end
function randomSeed()
return math.random(0, 32767)
end
function findMin(table)
assert(type(table) == "table" and #table > 0)
local low = table[1]
for _, i in ipairs(table) do
if i < low then
low = i
end
end
return low
end
function findMinMax(table)
assert(type(table) == "table" and #table > 0)
local low = table[1]
local high = table[1]
for _, i in ipairs(table) do
if i < low then
low = i
end
if i > high then
high = i
end
end
return low, high
end
function runSimple(arg)
return os.readProcess(arg.nbodyBin or "milkyway_nbody",
"--checkpoint-interval=-1",
"--debug-boinc",
"-t",
"-f", arg.input,
table.concat(arg.extraArgs, " ")
)
end
function runFullTest(arg)
local testPath, histogramPath = arg.testName, arg.histogram
if arg.testDir then
testPath = string.format("%s/%s.lua", arg.testDir, arg.testName)
histogramPath = string.format("%s/%s", arg.testDir, arg.histogram)
else
testPath = arg.testName .. ".lua"
end
mkdir(".checkpoints")
local cpFlag = string.format("--no-clean-checkpoint -c %s/%s__%d",
".checkpoints",
arg.testName,
arg.seed)
if not arg.cached then
cpFlag = cpFlag .. " --ignore-checkpoint"
end
-- eprintf("Running command line:\n %s\n --checkpoint-interval=-1\n -g\n -t\n -f %s\n -h %s\n --seed %s\n %s\n %s\n %s\n",
-- tostring(arg.nbodyBin),
-- tostring(testPath),
-- tostring(histogramPath),
-- tostring(arg.seed),
-- tostring(cpFlag),
-- tostring(getExtraNBodyFlags()),
-- tostring(table.concat(arg.extraArgs, " ")))
return os.readProcess(arg.nbodyBin or "milkyway_nbody",
"--checkpoint-interval=-1", -- Disable checkpointing
"-g", -- Prevent stderr from getting consumed with BOINC
"-t",
"-f", testPath,
"-h", histogramPath,
"--seed", arg.seed,
cpFlag,
getExtraNBodyFlags(),
table.concat(arg.extraArgs, " ")
)
end
-- Find the likelihood from the output of the process
function findNumber(str, name)
local pattern = string.format("<%s>(.+)</%s>", name, name)
local m = str:match(pattern)
local lineSep = string.rep("-", 80) .. "\n"
if m == nil then
eprintf("Didn't match '%s' in output\nOffending output:\n%s\n%s%s",
name,
lineSep,
str,
lineSep
)
return nil
else
return tonumber(m)
end
end
function findLikelihood(str, emd)
if emd then
name = "emd"
else
name = "search_likelihood"
end
-- likelihood is negated
return -findNumber(str, name)
end
| gpl-3.0 |
chanko08/Ludum-Dare-33 | lib/tiny.lua | 3 | 23223 | --[[
Copyright (c) 2015 Calvin Rose
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.
]]
--- @module tiny-ecs
-- @author Calvin Rose
-- @license MIT
-- @copyright 2015
local tiny = { _VERSION = "1.1-7" }
-- Local versions of standard lua functions
local tinsert = table.insert
local tremove = table.remove
local tsort = table.sort
local pairs = pairs
local setmetatable = setmetatable
local type = type
local select = select
-- Local versions of the library functions
local tiny_manageEntities
local tiny_manageSystems
local tiny_addEntity
local tiny_addSystem
local tiny_add
local tiny_removeEntity
local tiny_removeSystem
local tiny_remove
--- Filter functions.
-- A Filter is a function that selects which Entities apply to a System.
-- Filters take two parameters, the System and the Entity, and return a boolean
-- value indicating if the Entity should be processed by the System.
--
-- Filters must be added to Systems by setting the `filter` field of the System.
-- Filter's returned by tiny-ecs's Filter functions are immutable and can be
-- used by multiple Systems.
--
-- local f1 = tiny.requireAll("position", "velocity", "size")
-- local f2 = tiny.requireAny("position", "velocity", "size")
--
-- local e1 = {
-- position = {2, 3},
-- velocity = {3, 3},
-- size = {4, 4}
-- }
--
-- local entity2 = {
-- position = {4, 5},
-- size = {4, 4}
-- }
--
-- local e3 = {
-- position = {2, 3},
-- velocity = {3, 3}
-- }
--
-- print(f1(nil, e1), f1(nil, e2), f1(nil, e3)) -- prints true, false, false
-- print(f2(nil, e1), f2(nil, e2), f2(nil, e3)) -- prints true, true, true
--
-- Filters can also be passed as arguments to other Filter constructors. This is
-- a powerful way to create complex, custom Filters that select a very specific
-- set of Entities.
--
-- -- Selects Entities with an "image" Component, but not Entities with a
-- -- "Player" or "Enemy" Component.
-- filter = tiny.requireAll("image", tiny.rejectAny("Player", "Enemy"))
--
-- @section Filter
--- Makes a Filter that selects Entities with all specified Components and
-- Filters.
function tiny.requireAll(...)
local components = {...}
local len = #components
return function(system, e)
local c
for i = 1, len do
c = components[i]
if type(c) == 'function' then
if not c(system, e) then
return false
end
elseif e[c] == nil then
return false
end
end
return true
end
end
--- Makes a Filter that selects Entities with at least one of the specified
-- Components and Filters.
function tiny.requireAny(...)
local components = {...}
local len = #components
return function(system, e)
local c
for i = 1, len do
c = components[i]
if type(c) == 'function' then
if c(system, e) then
return true
end
elseif e[c] ~= nil then
return true
end
end
return false
end
end
--- Makes a Filter that rejects Entities with all specified Components and
-- Filters, and selects all other Entities.
function tiny.rejectAll(...)
local components = {...}
local len = #components
return function(system, e)
local c
for i = 1, len do
c = components[i]
if type(c) == 'function' then
if not c(system, e) then
return true
end
elseif e[c] == nil then
return true
end
end
return false
end
end
--- Makes a Filter that rejects Entities with at least one of the specified
-- Components and Filters, and selects all other Entities.
function tiny.rejectAny(...)
local components = {...}
local len = #components
return function(system, e)
local c
for i = 1, len do
c = components[i]
if type(c) == 'function' then
if c(system, e) then
return false
end
elseif e[c] ~= nil then
return false
end
end
return true
end
end
--- System functions.
-- A System is a wrapper around function callbacks for manipulating Entities.
-- Systems are implemented as tables that contain at least one method;
-- an update function that takes parameters like so:
--
-- * `function system:update(dt)`.
--
-- There are also a few other optional callbacks:
--
-- * `function system:filter(entity)` - Returns true if this System should
-- include this Entity, otherwise should return false. If this isn't specified,
-- no Entities are included in the System.
-- * `function system:onAdd(entity)` - Called when an Entity is added to the
-- System.
-- * `function system:onRemove(entity)` - Called when an Entity is removed
-- from the System.
-- * `function system:onModify(dt)` - Called when the System is modified by
-- adding or removing Entities from the System.
--
-- For Filters, it is convenient to use `tiny.requireAll` or `tiny.requireAny`,
-- but one can write their own filters as well. Set the Filter of a System like
-- so:
-- system.filter = tiny.requireAll("a", "b", "c")
-- or
-- function system:filter(entity)
-- return entity.myRequiredComponentName ~= nil
-- end
--
-- All Systems also have a few important fields that are initialized when the
-- system is added to the World. A few are important, and few should be less
-- commonly used.
--
-- * The `world` field points to the World that the System belongs to. Useful
-- for adding and removing Entities from the world dynamically via the System.
-- * The `active` flag is whether or not the System is updated automatically.
-- Inactive Systems should be updated manually or not at all via
-- `system:update(dt)`. Defaults to true.
-- * The `entities` field is an ordered list of Entities in the System. This
-- list can be used to quickly iterate through all Entities in a System.
-- * The `interval` field is an optional field that makes Systems update at
-- certain intervals using buffered time, regardless of World update frequency.
-- For example, to make a System update once a second, set the System's interval
-- to 1.
-- * The `index` field is the System's index in the World. Lower indexed
-- Systems are processed before higher indices. The `index` is a read only
-- field; to set the `index`, use `tiny.setSystemIndex(world, system)`.
-- * The `indices` field is a table of Entity keys to their indices in the
-- `entities` list. Most Systems can ignore this.
-- * The `modified` flag is an indicator if the System has been modified in
-- the last update. If so, the `onModify` callback will be called on the System
-- in the next update, if it has one. This is usually managed by tiny-ecs, so
-- users should mostly ignore this, too.
--
-- @section System
-- Use an empty table as a key for identifying Systems. Any table that contains
-- this key is considered a System rather than an Entity.
local systemTableKey = { "SYSTEM_TABLE_KEY" }
-- Checks if a table is a System.
local function isSystem(table)
return table[systemTableKey]
end
-- Update function for all Processing Systems.
local function processingSystemUpdate(system, dt)
local entities = system.entities
local preProcess = system.preProcess
local process = system.process
local postProcess = system.postProcess
local entity
if preProcess then
preProcess(system, dt)
end
if process then
local len = #entities
for i = 1, len do
entity = entities[i]
process(system, entity, dt)
end
end
if postProcess then
postProcess(system, dt)
end
end
-- Sorts Systems by a function system.sort(entity1, entity2) on modify.
local function sortedSystemOnModify(system, dt)
local entities = system.entities
local indices = system.indices
local sortDelegate = system.sortDelegate
if not sortDelegate then
local compare = system.compare
sortDelegate = function(e1, e2)
return compare(system, e1, e2)
end
system.sortDelegate = sortDelegate
end
tsort(entities, sortDelegate)
for i = 1, #entities do
local entity = entities[i]
indices[entity] = i
end
end
--- Creates a new System or System class from the supplied table. If `table` is
-- nil, creates a new table.
function tiny.system(table)
table = table or {}
table[systemTableKey] = true
return table
end
--- Creates a new Processing System or Processing System class. Processing
-- Systems process each entity individual, and are usually what is needed.
-- Processing Systems have three extra callbacks besides those inheritted from
-- vanilla Systems.
--
-- function system:preProcess(entities, dt) -- Called before iteration.
-- function system:process(entities, dt) -- Process each entity.
-- function system:postProcess(entity, dt) -- Called after iteration.
--
-- Processing Systems have their own `update` method, so don't implement a
-- a custom `update` callback for Processing Systems.
-- @see system
function tiny.processingSystem(table)
table = table or {}
table[systemTableKey] = true
table.update = processingSystemUpdate
return table
end
--- Creates a new Sorted System or Sorted System class. Sorted Systems sort
-- their Entities according to a user-defined method, `system:compare(e1, e2)`,
-- which should return true if `e1` should come before `e2` and false otherwise.
-- Sorted Systems also override the default System's `onModify` callback, so be
-- careful if defining a custom callback. However, for processing the sorted
-- entities, consider `tiny.sortedProcessingSystem(table)`.
-- @see system
function tiny.sortedSystem(table)
table = table or {}
table[systemTableKey] = true
table.onModify = sortedSystemOnModify
return table
end
--- Creates a new Sorted Processing System or Sorted Processing System class.
-- Sorted Processing Systems have both the aspects of Processing Systems and
-- Sorted Systems.
-- @see system
-- @see processingSystem
-- @see sortedSystem
function tiny.sortedProcessingSystem(table)
table = table or {}
table[systemTableKey] = true
table.update = processingSystemUpdate
table.onModify = sortedSystemOnModify
return table
end
--- World functions.
-- A World is a container that manages Entities and Systems. Typically, a
-- program uses one World at a time.
--
-- For all World functions except `tiny.world(...)`, object-oriented syntax can
-- be used instead of the documented syntax. For example,
-- `tiny.add(world, e1, e2, e3)` is the same as `world:add(e1, e2, e3)`.
-- @section World
-- Forward declaration
local worldMetaTable
--- Creates a new World.
-- Can optionally add default Systems and Entities. Returns the new World along
-- with default Entities and Systems.
function tiny.world(...)
local ret = {
-- List of Entities to add
entitiesToAdd = {},
-- List of Entities to remove
entitiesToRemove = {},
-- List of Entities to add
systemsToAdd = {},
-- List of Entities to remove
systemsToRemove = {},
-- Set of Entities
entities = {},
-- Number of Entities in World
entityCount = 0,
-- List of Systems
systems = {}
}
tiny_add(ret, ...)
tiny_manageSystems(ret)
tiny_manageEntities(ret)
return setmetatable(ret, worldMetaTable), ...
end
--- Adds an Entity to the world.
-- Also call this on Entities that have changed Components such that they
-- match different Filters. Returns the Entity.
function tiny.addEntity(world, entity)
local e2a = world.entitiesToAdd
e2a[#e2a + 1] = entity
if world.entities[entity] then
tiny_removeEntity(world, entity)
end
return entity
end
tiny_addEntity = tiny.addEntity
--- Adds a System to the world. Returns the System.
function tiny.addSystem(world, system)
local s2a = world.systemsToAdd
s2a[#s2a + 1] = system
return system
end
tiny_addSystem = tiny.addSystem
--- Shortcut for adding multiple Entities and Systems to the World. Returns all
-- added Entities and Systems.
function tiny.add(world, ...)
local obj
for i = 1, select("#", ...) do
obj = select(i, ...)
if obj then
if isSystem(obj) then
tiny_addSystem(world, obj)
else -- Assume obj is an Entity
tiny_addEntity(world, obj)
end
end
end
return ...
end
tiny_add = tiny.add
--- Removes an Entity to the World. Returns the Entity.
function tiny.removeEntity(world, entity)
local e2r = world.entitiesToRemove
e2r[#e2r + 1] = entity
return entity
end
tiny_removeEntity = tiny.removeEntity
--- Removes a System from the world. Returns the System.
function tiny.removeSystem(world, system)
local s2r = world.systemsToRemove
s2r[#s2r + 1] = system
return system
end
tiny_removeSystem = tiny.removeSystem
--- Shortcut for removing multiple Entities and Systems from the World. Returns
-- all removed Systems and Entities
function tiny.remove(world, ...)
local obj
for i = 1, select("#", ...) do
obj = select(i, ...)
if obj then
if isSystem(obj) then
tiny_removeSystem(world, obj)
else -- Assume obj is an Entity
tiny_removeEntity(world, obj)
end
end
end
return ...
end
tiny_remove = tiny.remove
-- Adds and removes Systems that have been marked from the World.
function tiny_manageSystems(world)
local s2a, s2r = world.systemsToAdd, world.systemsToRemove
-- Early exit
if #s2a == 0 and #s2r == 0 then
return
end
local entities = world.entities
local systems = world.systems
local system, index, filter
local entityList, entityIndices, entityIndex, onRemove, onAdd
-- Remove Systems
for i = 1, #s2r do
system = s2r[i]
index = system.index
if system.world == world then
onRemove = system.onRemove
if onRemove then
entityList = system.entities
for j = 1, #entityList do
onRemove(system, entityList[j])
end
end
tremove(systems, index)
for j = index, #systems do
systems[j].index = j
end
end
s2r[i] = nil
-- Clean up System
system.world = nil
system.entities = nil
system.indices = nil
system.index = nil
end
-- Add Systems
for i = 1, #s2a do
system = s2a[i]
if systems[system.index] ~= system then
entityList = {}
entityIndices = {}
system.entities = entityList
system.indices = entityIndices
if system.active == nil then
system.active = true
end
system.modified = true
system.world = world
index = #systems + 1
system.index = index
systems[index] = system
-- Try to add Entities
onAdd = system.onAdd
filter = system.filter
if filter then
for entity in pairs(entities) do
if filter(system, entity) then
entityIndex = #entityList + 1
entityList[entityIndex] = entity
entityIndices[entity] = entityIndex
if onAdd then
onAdd(system, entity)
end
end
end
end
end
s2a[i] = nil
end
end
-- Adds and removes Entities that have been marked.
function tiny_manageEntities(world)
local e2a, e2r = world.entitiesToAdd, world.entitiesToRemove
-- Early exit
if #e2a == 0 and #e2r == 0 then
return
end
local entities = world.entities
local systems = world.systems
local entityCount = world.entityCount
local entity, system, index
local onRemove, onAdd, ses, seis, filter, tmpEntity
-- Remove Entities
for i = 1, #e2r do
entity = e2r[i]
if entities[entity] then
entities[entity] = nil
entityCount = entityCount - 1
for j = 1, #systems do
system = systems[j]
ses = system.entities
seis = system.indices
index = seis[entity]
if index then
system.modified = true
tmpEntity = ses[#ses]
ses[index] = tmpEntity
seis[tmpEntity] = index
seis[entity] = nil
ses[#ses] = nil
onRemove = system.onRemove
if onRemove then
onRemove(system, entity)
end
end
end
end
e2r[i] = nil
end
-- Add Entities
for i = 1, #e2a do
entity = e2a[i]
if not entities[entity] then
entities[entity] = true
entityCount = entityCount + 1
for j = 1, #systems do
system = systems[j]
ses = system.entities
seis = system.indices
filter = system.filter
if filter and filter(system, entity) then
system.modified = true
index = #ses + 1
ses[index] = entity
seis[entity] = index
onAdd = system.onAdd
if onAdd then
onAdd(system, entity)
end
end
end
end
e2a[i] = nil
end
-- Update Entity count
world.entityCount = entityCount
end
--- Manages Entities and Systems marked for deletion or addition. Call this
-- before modifying Systems and Entities outside of a call to `tiny.update`.
-- Do not call this within a call to `tiny.update`.
function tiny.refresh(world)
tiny_manageSystems(world)
tiny_manageEntities(world)
end
--- Updates the World by dt (delta time). Takes an optional parameter, `filter`,
-- which is a Filter that selects Systems from the World, and updates only those
-- Systems. If `filter` is not supplied, all Systems are updated. Put this
-- function in your main loop.
function tiny.update(world, dt, filter)
tiny_manageSystems(world)
tiny_manageEntities(world)
local systems = world.systems
local system, update, interval, onModify
-- Iterate through Systems IN ORDER
for i = 1, #systems do
system = systems[i]
if system.active and ((not filter) or filter(world, system)) then
-- Call the modify callback on Systems that have been modified.
onModify = system.onModify
if onModify and system.modified then
onModify(system, dt)
end
-- Update Systems that have an update method (most Systems)
update = system.update
if update then
interval = system.interval
if interval then
local bufferedTime = (system.bufferedTime or 0) + dt
while bufferedTime >= interval do
bufferedTime = bufferedTime - interval
if update then
update(system, interval)
end
end
system.bufferedTime = bufferedTime
else
update(system, dt)
end
end
system.modified = false
end
end
end
--- Removes all Entities from the World.
function tiny.clearEntities(world)
for e in pairs(world.entities) do
tiny_removeEntity(world, e)
end
end
--- Removes all Systems from the World.
function tiny.clearSystems(world)
local systems = world.systems
for i = #systems, 1, -1 do
tiny_removeSystem(world, systems[i])
end
end
--- Gets number of Entities in the World.
function tiny.getEntityCount(world)
return world.entityCount
end
--- Gets number of Systems in World.
function tiny.getSystemCount(world)
return #(world.systems)
end
--- Gets the index of the System in the World.
-- A simpler alternative is `system.index`.
function tiny.getSystemIndex(world, system)
return system.index
end
--- Sets the index of a System in the World, and returns the old index. Changes
-- the order in which they Systems processed, because lower indexed Systems are
-- processed first. Returns the old system.index.
function tiny.setSystemIndex(world, system, index)
local oldIndex = system.index
local systems = world.systems
tremove(systems, oldIndex)
tinsert(systems, index, system)
for i = oldIndex, index, index >= oldIndex and 1 or -1 do
systems[i].index = i
end
return oldIndex
end
-- Construct world metatable.
worldMetaTable = {
__index = {
add = tiny.add,
addEntity = tiny.addEntity,
addSystem = tiny.addSystem,
remove = tiny.remove,
removeEntity = tiny.removeEntity,
removeSystem = tiny.removeSystem,
refresh = tiny.refresh,
update = tiny.update,
clearEntities = tiny.clearEntities,
clearSystems = tiny.clearSystems,
getEntityCount = tiny.getEntityCount,
getSystemCount = tiny.getSystemCount,
getSystemIndex = tiny.getSystemIndex,
setSystemIndex = tiny.setSystemIndex
}
}
return tiny
| mit |
AresTao/darkstar | scripts/zones/AlTaieu/Zone.lua | 17 | 2407 | -----------------------------------
--
-- Zone: AlTaieu (33)
--
-----------------------------------
package.loaded["scripts/zones/AlTaieu/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/AlTaieu/TextIDs");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-25,-1 ,-620 ,33);
end
if (player:getCurrentMission(COP) == GARDEN_OF_ANTIQUITY and player:getVar("PromathiaStatus")==0) then
cs=0x0001;
elseif (player:getCurrentMission(COP) == DAWN and player:getVar("PromathiaStatus")==0) then
cs=0x00A7;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0001) then
player:setVar("PromathiaStatus",1);
player:addKeyItem(LIGHT_OF_ALTAIEU);
player:messageSpecial(KEYITEM_OBTAINED,LIGHT_OF_ALTAIEU);
player:addTitle(SEEKER_OF_THE_LIGHT);
elseif (csid == 0x00A7) then
player:setVar("PromathiaStatus",1);
end
end;
| gpl-3.0 |
AresTao/darkstar | scripts/globals/items/hellsteak.lua | 35 | 1725 | -----------------------------------------
-- ID: 5609
-- Item: hellsteak
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Health 20
-- Strength 6
-- Intelligence -2
-- Health Regen While Healing 2
-- Attack % 19
-- Ranged ATT % 19
-- Dragon Killer 5
-- Demon Killer 5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5609);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 20);
target:addMod(MOD_STR, 6);
target:addMod(MOD_INT, -2);
target:addMod(MOD_HPHEAL, 2);
target:addMod(MOD_ATTP, 19);
target:addMod(MOD_RATTP, 19);
target:addMod(MOD_DRAGON_KILLER, 5);
target:addMod(MOD_DEMON_KILLER, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 20);
target:delMod(MOD_STR, 6);
target:delMod(MOD_INT, -2);
target:delMod(MOD_HPHEAL, 2);
target:delMod(MOD_ATTP, 19);
target:delMod(MOD_RATTP, 19);
target:delMod(MOD_DRAGON_KILLER, 5);
target:delMod(MOD_DEMON_KILLER, 5);
end;
| gpl-3.0 |
Guard13007/LightWorld-Editor | src/lib/LoveFrames/objects/internal/scrollable/scrollarea.lua | 12 | 5719 | --[[------------------------------------------------
-- Love Frames - A GUI library for LOVE --
-- Copyright (c) 2012-2014 Kenny Shields --
--]]------------------------------------------------
-- get the current require path
local path = string.sub(..., 1, string.len(...) - string.len(".objects.internal.scrollable.scrollarea"))
local loveframes = require(path .. ".libraries.common")
-- scrollarea class
local newobject = loveframes.NewObject("scrollarea", "loveframes_object_scrollarea", true)
--[[---------------------------------------------------------
- func: initialize()
- desc: initializes the object
--]]---------------------------------------------------------
function newobject:initialize(parent, bartype)
self.type = "scroll-area"
self.bartype = bartype
self.parent = parent
self.x = 0
self.y = 0
self.scrolldelay = 0
self.delayamount = 0.05
self.down = false
self.internal = true
self.internals = {}
table.insert(self.internals, loveframes.objects["scrollbar"]:new(self, bartype))
-- apply template properties to the object
loveframes.templates.ApplyToObject(self)
end
--[[---------------------------------------------------------
- func: update(deltatime)
- desc: updates the object
--]]---------------------------------------------------------
function newobject:update(dt)
local visible = self.visible
local alwaysupdate = self.alwaysupdate
if not visible then
if not alwaysupdate then
return
end
end
self:CheckHover()
local base = loveframes.base
local parent = self.parent
local pinternals = parent.internals
local button = pinternals[2]
local bartype = self.bartype
local time = love.timer.getTime()
local x, y = love.mouse.getPosition()
local listo = parent.parent
local down = self.down
local scrolldelay = self.scrolldelay
local delayamount = self.delayamount
local internals = self.internals
local bar = internals[1]
local hover = self.hover
local update = self.Update
if button then
if bartype == "vertical" then
self.staticx = 0
self.staticy = button.height - 1
self.width = parent.width
self.height = parent.height - button.height*2 + 2
elseif bartype == "horizontal" then
self.staticx = button.width - 1
self.staticy = 0
self.width = parent.width - button.width*2 + 2
self.height = parent.height
end
end
-- move to parent if there is a parent
if parent ~= base then
self.x = parent.x + self.staticx
self.y = parent.y + self.staticy
end
if down then
if scrolldelay < time then
self.scrolldelay = time + delayamount
if self.bartype == "vertical" then
if y > bar.y then
bar:Scroll(bar.height)
else
bar:Scroll(-bar.height)
end
elseif self.bartype == "horizontal" then
if x > bar.x then
bar:Scroll(bar.width)
else
bar:Scroll(-bar.width)
end
end
end
if not hover then
self.down = false
end
end
for k, v in ipairs(internals) do
v:update(dt)
end
if update then
update(self, dt)
end
end
--[[---------------------------------------------------------
- func: draw()
- desc: draws the object
--]]---------------------------------------------------------
function newobject:draw()
local visible = self.visible
if not visible then
return
end
local internals = self.internals
local skins = loveframes.skins.available
local skinindex = loveframes.config["ACTIVESKIN"]
local defaultskin = loveframes.config["DEFAULTSKIN"]
local selfskin = self.skin
local skin = skins[selfskin] or skins[skinindex]
local drawfunc = skin.DrawScrollArea or skins[defaultskin].DrawScrollArea
local draw = self.Draw
local drawcount = loveframes.drawcount
-- set the object's draw order
self:SetDrawOrder()
if draw then
draw(self)
else
drawfunc(self)
end
for k, v in ipairs(internals) do
v:draw()
end
end
--[[---------------------------------------------------------
- func: mousepressed(x, y, button)
- desc: called when the player presses a mouse button
--]]---------------------------------------------------------
function newobject:mousepressed(x, y, button)
local visible = self.visible
if not visible then
return
end
local listo = self.parent.parent
local time = love.timer.getTime()
local internals = self.internals
local bar = internals[1]
local hover = self.hover
local delayamount = self.delayamount
if hover and button == "l" then
self.down = true
self.scrolldelay = time + delayamount + 0.5
local baseparent = self:GetBaseParent()
if baseparent and baseparent.type == "frame" then
baseparent:MakeTop()
end
if self.bartype == "vertical" then
if y > self.internals[1].y then
bar:Scroll(bar.height)
else
bar:Scroll(-bar.height)
end
elseif self.bartype == "horizontal" then
if x > bar.x then
bar:Scroll(bar.width)
else
bar:Scroll(-bar.width)
end
end
loveframes.downobject = self
end
for k, v in ipairs(internals) do
v:mousepressed(x, y, button)
end
end
--[[---------------------------------------------------------
- func: mousereleased(x, y, button)
- desc: called when the player releases a mouse button
--]]---------------------------------------------------------
function newobject:mousereleased(x, y, button)
local visible = self.visible
if not visible then
return
end
local internals = self.internals
if button == "l" then
self.down = false
end
for k, v in ipairs(internals) do
v:mousereleased(x, y, button)
end
end
--[[---------------------------------------------------------
- func: GetBarType()
- desc: gets the object's bar type
--]]---------------------------------------------------------
function newobject:GetBarType()
return self.bartype
end
| mit |
prosody-modules/import | mod_bidi/mod_bidi.lua | 32 | 4894 | -- Bidirectional Server-to-Server Connections
-- http://xmpp.org/extensions/xep-0288.html
-- Copyright (C) 2013 Kim Alvefur
--
-- This file is MIT/X11 licensed.
--
local add_filter = require "util.filters".add_filter;
local st = require "util.stanza";
local jid_split = require"util.jid".prepped_split;
local core_process_stanza = prosody.core_process_stanza;
local traceback = debug.traceback;
local hosts = hosts;
local xmlns_bidi_feature = "urn:xmpp:features:bidi"
local xmlns_bidi = "urn:xmpp:bidi";
local secure_only = module:get_option_boolean("secure_bidi_only", true);
local disable_bidi_for = module:get_option_set("no_bidi_with", { });
local bidi_sessions = module:shared"sessions-cache";
local function handleerr(err) log("error", "Traceback[s2s]: %s: %s", tostring(err), traceback()); end
local function handlestanza(session, stanza)
if stanza.attr.xmlns == "jabber:client" then --COMPAT: Prosody pre-0.6.2 may send jabber:client
stanza.attr.xmlns = nil;
end
-- stanza = session.filter("stanzas/in", stanza);
if stanza then
return xpcall(function () return core_process_stanza(session, stanza) end, handleerr);
end
end
local function new_bidi(origin)
if origin.type == "s2sin" then -- then we create an "outgoing" bidirectional session
local conflicting_session = hosts[origin.to_host].s2sout[origin.from_host]
if conflicting_session then
conflicting_session.log("info", "We already have an outgoing connection to %s, closing it...", origin.from_host);
conflicting_session:close{ condition = "conflict", text = "Replaced by bidirectional stream" }
end
bidi_sessions[origin.from_host] = origin;
origin.is_bidi = true;
elseif origin.type == "s2sout" then -- handle incoming stanzas correctly
local bidi_session = {
type = "s2sin"; direction = "incoming";
is_bidi = true; orig_session = origin;
to_host = origin.from_host;
from_host = origin.to_host;
hosts = {};
}
origin.bidi_session = bidi_session;
setmetatable(bidi_session, { __index = origin });
module:fire_event("s2s-authenticated", { session = bidi_session, host = origin.to_host });
local remote_host = origin.to_host;
add_filter(origin, "stanzas/in", function(stanza)
if stanza.attr.xmlns ~= nil then return stanza end
local _, host = jid_split(stanza.attr.from);
if host ~= remote_host then return stanza end
handlestanza(bidi_session, stanza);
end, 1);
end
end
module:hook("route/remote", function(event)
local from_host, to_host, stanza = event.from_host, event.to_host, event.stanza;
if from_host ~= module.host then return end
local to_session = bidi_sessions[to_host];
if not to_session or to_session.type ~= "s2sin" then return end
if to_session.sends2s(stanza) then return true end
end, -2);
-- Incoming s2s
module:hook("s2s-stream-features", function(event)
local origin, features = event.origin, event.features;
if not origin.is_bidi and not origin.bidi_session and not origin.do_bidi
and not hosts[module.host].s2sout[origin.from_host]
and not disable_bidi_for:contains(origin.from_host)
and (not secure_only or (origin.cert_chain_status == "valid"
and origin.cert_identity_status == "valid")) then
module:log("debug", "Announcing support for bidirectional streams");
features:tag("bidi", { xmlns = xmlns_bidi_feature }):up();
end
end);
module:hook("stanza/urn:xmpp:bidi:bidi", function(event)
local origin = event.session or event.origin;
if not origin.is_bidi and not origin.bidi_session
and not disable_bidi_for:contains(origin.from_host)
and (not secure_only or origin.cert_chain_status == "valid"
and origin.cert_identity_status == "valid") then
module:log("debug", "%s requested bidirectional stream", origin.from_host);
origin.do_bidi = true;
return true;
end
end);
-- Outgoing s2s
module:hook("stanza/http://etherx.jabber.org/streams:features", function(event)
local origin = event.session or event.origin;
if not ( origin.bidi_session or origin.is_bidi or origin.do_bidi)
and not disable_bidi_for:contains(origin.to_host)
and event.stanza:get_child("bidi", xmlns_bidi_feature)
and (not secure_only or origin.cert_chain_status == "valid"
and origin.cert_identity_status == "valid") then
module:log("debug", "%s supports bidirectional streams", origin.to_host);
origin.sends2s(st.stanza("bidi", { xmlns = xmlns_bidi }));
origin.do_bidi = true;
end
end, 160);
function enable_bidi(event)
local session = event.session;
if session.do_bidi and not ( session.is_bidi or session.bidi_session ) then
session.do_bidi = nil;
new_bidi(session);
end
end
module:hook("s2sin-established", enable_bidi);
module:hook("s2sout-established", enable_bidi);
function disable_bidi(event)
local session = event.session;
if session.type == "s2sin" then
bidi_sessions[session.from_host] = nil;
end
end
module:hook("s2sin-destroyed", disable_bidi);
module:hook("s2sout-destroyed", disable_bidi);
| mit |
AresTao/darkstar | scripts/zones/Uleguerand_Range/npcs/HomePoint#2.lua | 19 | 1189 | -----------------------------------
-- Area: Uleguerand_Range
-- NPC: HomePoint#2
-- @pos
-----------------------------------
package.loaded["scripts/zones/Uleguerand_Range/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Uleguerand_Range/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fd, 77);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fd) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
chanko08/Ludum-Dare-33 | systems/animation.lua | 2 | 1851 | local animation = {}
animation.system = tiny.processingSystem()
animation.system.filter = tiny.requireAll('animations')
function animation.system:process(entity, dt)
entity.current_animation:update(dt)
end
animation.renderer = tiny.processingSystem()
animation.renderer.draw = true
animation.renderer.with_camera = true
animation.renderer.filter = tiny.requireAll('animations')
function animation.renderer:process(entity, dt)
entity.current_animation:draw(
entity.current_sprite,
entity.pos.x,
entity.pos.y
)
end
function animation.switch(ent, animation_id, mirror)
if ent.animations[animation_id] then
if not mirror then
ent.current_animation = ent.animations[animation_id].animation
else
ent.current_animation = ent.animations[animation_id].mirror
end
ent.current_sprite = ent.animations[animation_id].sprite
end
end
function animation.new(assets, ent)
ent.animations = {}
for asset_name, a in pairs(assets) do
if not love.filesystem.exists(a.path) then
error('picture file does not exist: ' .. a.path)
end
if not love.filesystem.isFile(a.path) then
error('filepath to picture is for a directory: ' .. a.path)
end
local img = love.graphics.newImage(a.path)
local g = anim8.newGrid(
a.frame_width,
img:getHeight(),
img:getWidth(),
img:getHeight()
)
local anim = anim8.newAnimation(g(a.frames,1), 1/10.0)
local mirr = anim:clone()
mirr:flipH()
ent.animations[asset_name] = {
animation = anim,
sprite = img,
mirror = mirr
}
end
local start_animation = ent.animations['default'] or _.first(_.values(ent.animations))
ent.current_animation = start_animation.animation
ent.current_sprite = start_animation.sprite
return ent
end
return animation
| mit |
AresTao/darkstar | scripts/zones/Bhaflau_Remnants/Zone.lua | 36 | 1125 | -----------------------------------
--
-- Zone: Bhaflau_Remnants
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Bhaflau_Remnants/TextIDs"] = nil;
require("scripts/zones/Bhaflau_Remnants/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
AresTao/darkstar | scripts/zones/Southern_San_dOria/npcs/Raimbroy.lua | 17 | 3329 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Raimbroy
-- Starts and Finishes Quest: The Sweetest Things
-- @zone 230
-- @pos
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
-- "The Sweetest Things" quest status var
theSweetestThings = player:getQuestStatus(SANDORIA,THE_SWEETEST_THINGS);
if (theSweetestThings ~= QUEST_AVAILABLE) then
if (trade:hasItemQty(4370,5) and trade:getItemCount() == 5) then
player:startEvent(0x0217,GIL_RATE*400);
else
player:startEvent(0x020a);
end
end
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
theSweetestThings = player:getQuestStatus(SANDORIA, THE_SWEETEST_THINGS);
-- "The Sweetest Things" Quest Dialogs
if (player:getFameLevel(SANDORIA) >= 2 and theSweetestThings == QUEST_AVAILABLE) then
theSweetestThingsVar = player:getVar("theSweetestThings");
if (theSweetestThingsVar == 1) then
player:startEvent(0x0215);
elseif (theSweetestThingsVar == 2) then
player:startEvent(0x0216);
else
player:startEvent(0x0214);
end
elseif (theSweetestThings == QUEST_ACCEPTED) then
player:startEvent(0x0218);
elseif (theSweetestThings == QUEST_COMPLETED) then
player:startEvent(0x0219);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
-- "The Sweetest Things" ACCEPTED
if (csid == 0x0214) then
player:setVar("theSweetestThings", 1);
elseif (csid == 0x0215) then
if (option == 0) then
player:addQuest(SANDORIA,THE_SWEETEST_THINGS);
player:setVar("theSweetestThings", 0);
else
player:setVar("theSweetestThings", 2);
end
elseif (csid == 0x0216 and option == 0) then
player:addQuest(SANDORIA, THE_SWEETEST_THINGS);
player:setVar("theSweetestThings", 0);
elseif (csid == 0x0217) then
player:tradeComplete();
player:addTitle(APIARIST);
player:addGil(GIL_RATE*400);
if (player:getQuestStatus(SANDORIA, THE_SWEETEST_THINGS) == QUEST_ACCEPTED) then
player:addFame(SANDORIA,SAN_FAME*30);
player:completeQuest(SANDORIA, THE_SWEETEST_THINGS);
else
player:addFame(SANDORIA, SAN_FAME*5);
end
end
end; | gpl-3.0 |
DeinFreund/Zero-K | gamedata/explosions_post.lua | 17 | 1247 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- Load CA's effects from ./effects and not ./gamedata/explosions
--
local luaFiles = VFS.DirList('effects', '*.lua', '*.tdf')
--couldn't be arsed to convert to lua since there is no real benefit for CEG's -Zement/DOT
for _, filename in ipairs(luaFiles) do
local edEnv = {}
edEnv._G = edEnv
edEnv.Shared = Shared
edEnv.GetFilename = function() return filename end
setmetatable(edEnv, { __index = system })
local success, eds = pcall(VFS.Include, filename, edEnv)
if (not success) then
Spring.Log("explosions_post.lua", "error", 'Error parsing ' .. filename .. ': ' .. eds)
elseif (eds == nil) then
Spring.Log("explosions_post.lua", "error", 'Missing return table from: ' .. filename)
else
for edName, ed in pairs(eds) do
if ((type(edName) == 'string') and (type(ed) == 'table')) then
ed.filename = filename
ExplosionDefs[edName] = ed
end
end
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| gpl-2.0 |
AresTao/darkstar | scripts/globals/items/galette_des_rois.lua | 39 | 1322 | -----------------------------------------
-- ID: 5875
-- Item: Galette Des Rois
-- Food Effect: 180 Min, All Races
-----------------------------------------
-- MP % 1
-- Intelligence +2
-- Random Jewel
-----------------------------------------
require("scripts/globals/status");
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD)) then
result = 246;
end
if (target:getFreeSlotsCount() == 0) then
result = 308;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5875);
local rand = math.random(784,815);
target:addItem(rand); -- Random Jewel
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MPP, 1);
target:addMod(MOD_INT, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MPP, 1);
target:delMod(MOD_INT, 2);
end;
| gpl-3.0 |
AresTao/darkstar | scripts/zones/Lower_Jeuno/npcs/Domenic.lua | 34 | 1998 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Domenic
-- BCNM/KSNM Teleporter
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Lower_Jeuno/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/teleports");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasCompleteQuest(JEUNO,BEYOND_INFINITY) == true) then
player:startEvent(0x2783,player:getGil());
else
player:startEvent(0x2784);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x2783) then
if (option == 1 and player:getGil() >= 750) then
player:delGil(750);
toGhelsba(player);
elseif (option == 2 and player:getGil() >= 750) then
player:delGil(750);
player:setPos(0, 0, 0, 0, 139);
elseif (option == 3 and player:getGil() >= 750) then
player:delGil(750);
player:setPos(0, 0, 0, 0, 144);
elseif (option == 4 and player:getGil() >= 750) then
player:delGil(750);
player:setPos(0, 0, 0, 0, 146);
elseif (option == 5 and player:getGil() >= 1000) then
player:delGil(1000);
player:setPos(0, 0, 0, 0, 206);
end
end
end; | gpl-3.0 |
DeinFreund/Zero-K | scripts/corcom_alt.lua | 16 | 8793 | include "constants.lua"
local spSetUnitShieldState = Spring.SetUnitShieldState
--------------------------------------------------------------------------------
-- pieces
--------------------------------------------------------------------------------
local torso = piece 'torso'
local lfirept = piece 'lfirept'
local rbigflash = piece 'rbigflash'
local nanospray = piece 'nanospray'
local nanolathe = piece 'nanolathe'
local luparm = piece 'luparm'
local ruparm = piece 'ruparm'
local pelvis = piece 'pelvis'
local rthigh = piece 'rthigh'
local lthigh = piece 'lthigh'
local biggun = piece 'biggun'
local lleg = piece 'lleg'
local l_foot = piece 'l_foot'
local rleg = piece 'rleg'
local r_foot = piece 'r_foot'
local head = piece 'head'
local smokePiece = {torso}
local nanoPieces = {nanospray}
--------------------------------------------------------------------------------
-- constants
--------------------------------------------------------------------------------
local SIG_WALK = 1
local SIG_LASER = 2
local SIG_DGUN = 4
local SIG_RESTORE_LASER = 8
local SIG_RESTORE_DGUN = 16
local TORSO_SPEED_YAW = math.rad(300)
local ARM_SPEED_PITCH = math.rad(180)
local PACE = 1.6
local BASE_VELOCITY = UnitDefNames.corcom1.speed or 1.25*30
local VELOCITY = UnitDefs[unitDefID].speed or BASE_VELOCITY
PACE = PACE * VELOCITY/BASE_VELOCITY
local THIGH_FRONT_ANGLE = -math.rad(40)
local THIGH_FRONT_SPEED = math.rad(60) * PACE
local THIGH_BACK_ANGLE = math.rad(20)
local THIGH_BACK_SPEED = math.rad(60) * PACE
local SHIN_FRONT_ANGLE = math.rad(35)
local SHIN_FRONT_SPEED = math.rad(90) * PACE
local SHIN_BACK_ANGLE = math.rad(5)
local SHIN_BACK_SPEED = math.rad(90) * PACE
local ARM_FRONT_ANGLE = -math.rad(15)
local ARM_FRONT_SPEED = math.rad(22.5) * PACE
local ARM_BACK_ANGLE = math.rad(5)
local ARM_BACK_SPEED = math.rad(22.5) * PACE
local ARM_PERPENDICULAR = math.rad(90)
--[[
local FOREARM_FRONT_ANGLE = -math.rad(15)
local FOREARM_FRONT_SPEED = math.rad(40) * PACE
local FOREARM_BACK_ANGLE = -math.rad(10)
local FOREARM_BACK_SPEED = math.rad(40) * PACE
]]--
local TORSO_ANGLE_MOTION = math.rad(8)
local TORSO_SPEED_MOTION = math.rad(15)*PACE
local RESTORE_DELAY_LASER = 4000
local RESTORE_DELAY_DGUN = 2500
--------------------------------------------------------------------------------
-- vars
--------------------------------------------------------------------------------
local isMoving, isLasering, isDgunning, gunLockOut, shieldOn = false, false, false, false, true
local restoreHeading, restorePitch = 0, 0
local flamers = {}
local starBLaunchers = {}
local wepTable = UnitDefs[unitDefID].weapons
wepTable.n = nil
for index, weapon in pairs(wepTable) do
local weaponDef = WeaponDefs[weapon.weaponDef]
if weaponDef.type == "Flame" or (weaponDef.customParams and weaponDef.customParams.flamethrower) then
flamers[index] = true
elseif weaponDef.type == "StarburstLauncher" then
starBLaunchers[index] = true
--Spring.Echo("sbl found")
end
end
wepTable = nil
--------------------------------------------------------------------------------
-- funcs
--------------------------------------------------------------------------------
local function Walk()
Signal(SIG_WALK)
SetSignalMask(SIG_WALK)
while true do
--left leg up, right leg back
Turn(lthigh, x_axis, THIGH_FRONT_ANGLE, THIGH_FRONT_SPEED)
Turn(lleg, x_axis, SHIN_FRONT_ANGLE, SHIN_FRONT_SPEED)
Turn(rthigh, x_axis, THIGH_BACK_ANGLE, THIGH_BACK_SPEED)
Turn(rleg, x_axis, SHIN_BACK_ANGLE, SHIN_BACK_SPEED)
if not(isLasering or isDgunning) then
--left arm back, right arm front
Turn(torso, y_axis, TORSO_ANGLE_MOTION, TORSO_SPEED_MOTION)
Turn(luparm, x_axis, ARM_BACK_ANGLE, ARM_BACK_SPEED)
Turn(ruparm, x_axis, ARM_FRONT_ANGLE, ARM_FRONT_SPEED)
end
WaitForTurn(lthigh, x_axis)
Sleep(0)
--right leg up, left leg back
Turn(lthigh, x_axis, THIGH_BACK_ANGLE, THIGH_BACK_SPEED)
Turn(lleg, x_axis, SHIN_BACK_ANGLE, SHIN_BACK_SPEED)
Turn(rthigh, x_axis, THIGH_FRONT_ANGLE, THIGH_FRONT_SPEED)
Turn(rleg, x_axis, SHIN_FRONT_ANGLE, SHIN_FRONT_SPEED)
if not(isLasering or isDgunning) then
--left arm front, right arm back
Turn(torso, y_axis, -TORSO_ANGLE_MOTION, TORSO_SPEED_MOTION)
Turn(luparm, x_axis, ARM_FRONT_ANGLE, ARM_FRONT_SPEED)
Turn(ruparm, x_axis, ARM_BACK_ANGLE, ARM_BACK_SPEED)
end
WaitForTurn(rthigh, x_axis)
Sleep(0)
end
end
local function RestoreLegs()
Signal(SIG_WALK)
SetSignalMask(SIG_WALK)
Move(pelvis, y_axis, 0, 1)
Turn(rthigh, x_axis, 0, math.rad(200))
Turn(rleg, x_axis, 0, math.rad(200))
Turn(lthigh, x_axis, 0, math.rad(200))
Turn(lleg, x_axis, 0, math.rad(200))
end
function script.Create()
Hide(lfirept)
Hide(rbigflash)
Hide(nanospray)
Turn(luparm, x_axis, math.rad(30))
Turn(ruparm, x_axis, math.rad(-10))
Turn(biggun, x_axis, math.rad(41))
Turn(nanolathe, x_axis, math.rad(36))
StartThread(SmokeUnit, smokePiece)
Spring.SetUnitNanoPieces(unitID, nanoPieces)
end
function script.StartMoving()
isMoving = true
StartThread(Walk)
end
function script.StopMoving()
isMoving = false
StartThread(RestoreLegs)
end
function script.AimFromWeapon(num)
return torso
end
function script.QueryWeapon(num)
if num == 3 then
return rbigflash
elseif num == 2 or num == 4 then
return torso
else
return lfirept
end
end
function script.FireWeapon(num)
if num == 5 then
EmitSfx(lfirept, 1024)
elseif num == 3 then
EmitSfx(rbigflash, 1026)
end
end
function script.Shot(num)
if num == 5 then
EmitSfx(lfirept, 1025)
elseif num == 3 then
EmitSfx(rbigflash, 1027)
end
if flamers[num] then
--GG.LUPS.FlameShot(unitID, unitDefID, _, num)
end
end
local function RestoreLaser()
Signal(SIG_RESTORE_LASER)
SetSignalMask(SIG_RESTORE_LASER)
Sleep(RESTORE_DELAY_LASER)
isLasering = false
Turn(luparm, x_axis, 0, ARM_SPEED_PITCH)
Turn(biggun, x_axis, math.rad(41), ARM_SPEED_PITCH)
if not isDgunning then
Turn(torso, y_axis, restoreHeading, TORSO_SPEED_YAW)
end
end
local function RestoreDgun()
Signal(SIG_RESTORE_DGUN)
SetSignalMask(SIG_RESTORE_DGUN)
Sleep(RESTORE_DELAY_DGUN)
isDgunning = false
Turn(ruparm, x_axis, restorePitch, ARM_SPEED_PITCH)
Turn(nanolathe, x_axis, math.rad(36), ARM_SPEED_PITCH)
if not isLasering then
Turn(torso, y_axis, restoreHeading, TORSO_SPEED_YAW)
end
end
function script.AimWeapon(num, heading, pitch)
if num >= 5 then
Signal(SIG_LASER)
SetSignalMask(SIG_LASER)
isLasering = true
if not isDgunning then
Turn(torso, y_axis, heading, TORSO_SPEED_YAW)
end
Turn(luparm, x_axis, math.rad(0) - pitch, ARM_SPEED_PITCH)
Turn(nanolathe, x_axis, math.rad(0), ARM_SPEED_PITCH)
WaitForTurn(torso, y_axis)
WaitForTurn(luparm, x_axis)
StartThread(RestoreLaser)
return true
elseif num == 3 then
if starBLaunchers[num] then
pitch = ARM_PERPENDICULAR
end
Signal(SIG_DGUN)
SetSignalMask(SIG_DGUN)
isDgunning = true
Turn(torso, y_axis, heading, TORSO_SPEED_YAW)
Turn(ruparm, x_axis, math.rad(0) - pitch, ARM_SPEED_PITCH)
Turn(biggun, x_axis, math.rad(0), ARM_SPEED_PITCH)
WaitForTurn(torso, y_axis)
WaitForTurn(ruparm, x_axis)
StartThread(RestoreDgun)
return true
elseif num == 2 or num == 4 then
Sleep(100)
return (shieldOn)
end
return false
end
function script.StopBuilding()
SetUnitValue(COB.INBUILDSTANCE, 0)
restoreHeading, restorePitch = 0, 0
StartThread(RestoreLaser)
end
function script.StartBuilding(heading, pitch)
Turn(ruparm, x_axis, math.rad(-30) - pitch, ARM_SPEED_PITCH)
if not (isDgunning) then Turn(torso, y_axis, heading, TORSO_SPEED_YAW) end
restoreHeading, restorePitch = heading, pitch
SetUnitValue(COB.INBUILDSTANCE, 1)
end
function script.QueryNanoPiece()
GG.LUPS.QueryNanoPiece(unitID,unitDefID,Spring.GetUnitTeam(unitID),rbigflash)
return rbigflash
end
function script.Activate()
--spSetUnitShieldState(unitID, 2, true)
end
function script.Deactivate()
--spSetUnitShieldState(unitID, 2, false)
end
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage/maxHealth
if severity < 0.5 then
Explode(torso, sfxNone)
Explode(luparm, sfxNone)
Explode(ruparm, sfxNone)
Explode(pelvis, sfxNone)
Explode(lthigh, sfxNone)
Explode(rthigh, sfxNone)
Explode(nanospray, sfxNone)
Explode(biggun, sfxNone)
Explode(lleg, sfxNone)
Explode(rleg, sfxNone)
return 1
else
Explode(torso, sfxShatter)
Explode(luparm, sfxSmoke + sfxFire + sfxExplode)
Explode(ruparm, sfxSmoke + sfxFire + sfxExplode)
Explode(pelvis, sfxShatter)
Explode(lthigh, sfxShatter)
Explode(rthigh, sfxShatter)
Explode(nanospray, sfxSmoke + sfxFire + sfxExplode)
Explode(biggun, sfxSmoke + sfxFire + sfxExplode)
Explode(lleg, sfxShatter)
Explode(rleg, sfxShatter)
Explode(head, sfxSmoke + sfxFire)
return 2
end
end
| gpl-2.0 |
AresTao/darkstar | scripts/zones/FeiYin/TextIDs.lua | 7 | 2354 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6558; -- You cannot obtain the item <item> come back again after sorting your inventory
ITEM_OBTAINED = 6562; -- Obtained: <item>
GIL_OBTAINED = 6563; -- Obtained <number> gil
KEYITEM_OBTAINED = 6565; -- Obtained key item: <keyitem>
FISHING_MESSAGE_OFFSET = 7219; -- You can't fish here
HOMEPOINT_SET = 10674; -- Home point set!
-- Treasure Coffer/Chest Dialog
CHEST_UNLOCKED = 7344; -- You unlock the chest!
CHEST_FAIL = 7345; -- Fails to open the chest.
CHEST_TRAP = 7346; -- The chest was trapped!
CHEST_WEAK = 7347; -- You cannot open the chest when you are in a weakened state.
CHEST_MIMIC = 7348; -- The chest was a mimic!
CHEST_MOOGLE = 7349; -- You cannot open the chest while participating in the moogle event.
CHEST_ILLUSION = 7350; -- The chest was but an illusion...
CHEST_LOCKED = 7351; -- The chest appears to be locked.
-- Other Dialog
SENSE_OF_FOREBODING = 6577; -- You are suddenly overcome with a sense of foreboding...
NOTHING_OUT_OF_ORDINARY = 6576; -- There is nothing out of the ordinary here.
-- ACP mission
MARK_OF_SEED_HAS_VANISHED = 7487; -- The Mark of Seed has vanished without a trace...
MARK_OF_SEED_IS_ABOUT_TO_DISSIPATE = 7486; -- The Mark of Seed is about to dissipate entirely! Only a faint outline remains...
MARK_OF_SEED_GROWS_FAINTER = 7485; -- The Mark of Seed grows fainter still. Before long, it will fade away entirely...
MARK_OF_SEED_FLICKERS = 7484; -- The glow of the Mark of Seed flickers and dims ever so slightly...
SCINTILLATING_BURST_OF_LIGHT = 7475; -- As you extend your hand, there is a scintillating burst of light!
YOU_REACH_FOR_THE_LIGHT = 7474; -- You reach for the light, but there is no discernable effect...
EVEN_GREATER_INTENSITY = 7473; -- The emblem on your hand glows with even greater intensity!
THE_LIGHT_DWINDLES = 7472; -- However, the light dwindles and grows dim almost at once...
YOU_REACH_OUT_TO_THE_LIGHT = 7471; -- You reach out to the light, and one facet of a curious seed-shaped emblem materializes on the back of your hand.
SOFTLY_SHIMMERING_LIGHT = 7470; -- You see a softly shimmering light...
-- conquest Base
CONQUEST_BASE = 3;
| gpl-3.0 |
DeinFreund/Zero-K | units/cloakskirm.lua | 1 | 3804 | unitDef = {
unitname = [[cloakskirm]],
name = [[Ronin]],
description = [[Skirmisher Bot (Direct-Fire)]],
acceleration = 0.3,
brakeRate = 0.2,
buildCostMetal = 90,
buildPic = [[cloakskirm.png]],
canGuard = true,
canMove = true,
canPatrol = true,
category = [[LAND]],
collisionVolumeOffsets = [[0 -5 0]],
collisionVolumeScales = [[26 39 26]],
collisionVolumeType = [[CylY]],
corpse = [[DEAD]],
customParams = {
modelradius = [[18]],
midposoffset = [[0 6 0]],
reload_move_penalty = 0.75,
},
explodeAs = [[BIG_UNITEX]],
footprintX = 2,
footprintZ = 2,
iconType = [[kbotskirm]],
idleAutoHeal = 5,
idleTime = 1800,
leaveTracks = true,
maxDamage = 420,
maxSlope = 36,
maxVelocity = 2.3,
maxWaterDepth = 20,
minCloakDistance = 75,
movementClass = [[KBOT2]],
noChaseCategory = [[TERRAFORM FIXEDWING SUB]],
objectName = [[sphererock.s3o]],
script = "cloakskirm.lua",
selfDestructAs = [[BIG_UNITEX]],
sfxtypes = {
explosiongenerators = {
[[custom:rockomuzzle]],
},
},
sightDistance = 523,
trackOffset = 0,
trackStrength = 8,
trackStretch = 1,
trackType = [[ComTrack]],
trackWidth = 18,
turnRate = 2200,
upright = true,
weapons = {
{
def = [[BOT_ROCKET]],
badTargetCategory = [[FIXEDWING]],
onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]],
},
},
weaponDefs = {
BOT_ROCKET = {
name = [[Rocket]],
areaOfEffect = 48,
burnblow = true,
cegTag = [[missiletrailredsmall]],
craterBoost = 0,
craterMult = 0,
customParams = {
light_camera_height = 1600,
light_color = [[0.90 0.65 0.30]],
light_radius = 250,
reload_move_mod_time = 3,
},
damage = {
default = 180,
subs = 9,
},
fireStarter = 70,
flightTime = 2.45,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 2,
model = [[wep_m_ajax.s3o]],
noSelfDamage = true,
predictBoost = 1,
range = 455,
reloadtime = 3.5,
smokeTrail = true,
soundHit = [[weapon/missile/sabot_hit]],
soundHitVolume = 8,
soundStart = [[weapon/missile/sabot_fire]],
soundStartVolume = 7,
startVelocity = 200,
texture2 = [[darksmoketrail]],
tracks = false,
turret = true,
weaponAcceleration = 200,
weaponType = [[MissileLauncher]],
weaponVelocity = 200,
},
},
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 2,
footprintZ = 2,
object = [[rocko_d.dae]],
},
HEAP = {
blocking = false,
footprintX = 2,
footprintZ = 2,
object = [[debris2x2c.s3o]],
},
},
}
return lowerkeys({ cloakskirm = unitDef })
| gpl-2.0 |
ld-test/prosody | util/prosodyctl.lua | 1 | 6365 | -- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local config = require "core.configmanager";
local encodings = require "util.encodings";
local stringprep = encodings.stringprep;
local storagemanager = require "core.storagemanager";
local usermanager = require "core.usermanager";
local signal = require "util.signal";
local set = require "util.set";
local lfs = require "lfs";
local pcall = pcall;
local type = type;
local nodeprep, nameprep = stringprep.nodeprep, stringprep.nameprep;
local io, os = io, os;
local print = print;
local tostring, tonumber = tostring, tonumber;
local CFG_SOURCEDIR = _G.CFG_SOURCEDIR;
local _G = _G;
local prosody = prosody;
-- UI helpers
local function show_message(msg, ...)
print(msg:format(...));
end
local function show_usage(usage, desc)
print("Usage: ".._G.arg[0].." "..usage);
if desc then
print(" "..desc);
end
end
local function getchar(n)
local stty_ret = os.execute("stty raw -echo 2>/dev/null");
local ok, char;
if stty_ret == 0 then
ok, char = pcall(io.read, n or 1);
os.execute("stty sane");
else
ok, char = pcall(io.read, "*l");
if ok then
char = char:sub(1, n or 1);
end
end
if ok then
return char;
end
end
local function getline()
local ok, line = pcall(io.read, "*l");
if ok then
return line;
end
end
local function getpass()
local stty_ret = os.execute("stty -echo 2>/dev/null");
if stty_ret ~= 0 then
io.write("\027[08m"); -- ANSI 'hidden' text attribute
end
local ok, pass = pcall(io.read, "*l");
if stty_ret == 0 then
os.execute("stty sane");
else
io.write("\027[00m");
end
io.write("\n");
if ok then
return pass;
end
end
local function show_yesno(prompt)
io.write(prompt, " ");
local choice = getchar():lower();
io.write("\n");
if not choice:match("%a") then
choice = prompt:match("%[.-(%U).-%]$");
if not choice then return nil; end
end
return (choice == "y");
end
local function read_password()
local password;
while true do
io.write("Enter new password: ");
password = getpass();
if not password then
show_message("No password - cancelled");
return;
end
io.write("Retype new password: ");
if getpass() ~= password then
if not show_yesno [=[Passwords did not match, try again? [Y/n]]=] then
return;
end
else
break;
end
end
return password;
end
local function show_prompt(prompt)
io.write(prompt, " ");
local line = getline();
line = line and line:gsub("\n$","");
return (line and #line > 0) and line or nil;
end
-- Server control
local function adduser(params)
local user, host, password = nodeprep(params.user), nameprep(params.host), params.password;
if not user then
return false, "invalid-username";
elseif not host then
return false, "invalid-hostname";
end
local host_session = prosody.hosts[host];
if not host_session then
return false, "no-such-host";
end
storagemanager.initialize_host(host);
local provider = host_session.users;
if not(provider) or provider.name == "null" then
usermanager.initialize_host(host);
end
local ok, errmsg = usermanager.create_user(user, password, host);
if not ok then
return false, errmsg or "creating-user-failed";
end
return true;
end
local function user_exists(params)
local user, host, password = nodeprep(params.user), nameprep(params.host), params.password;
storagemanager.initialize_host(host);
local provider = prosody.hosts[host].users;
if not(provider) or provider.name == "null" then
usermanager.initialize_host(host);
end
return usermanager.user_exists(user, host);
end
local function passwd(params)
if not user_exists(params) then
return false, "no-such-user";
end
return adduser(params);
end
local function deluser(params)
if not user_exists(params) then
return false, "no-such-user";
end
local user, host = nodeprep(params.user), nameprep(params.host);
return usermanager.delete_user(user, host);
end
local function getpid()
local pidfile = config.get("*", "pidfile");
if not pidfile then
return false, "no-pidfile";
end
if type(pidfile) ~= "string" then
return false, "invalid-pidfile";
end
local modules_enabled = set.new(config.get("*", "modules_disabled"));
if prosody.platform ~= "posix" or modules_enabled:contains("posix") then
return false, "no-posix";
end
local file, err = io.open(pidfile, "r+");
if not file then
return false, "pidfile-read-failed", err;
end
local locked, err = lfs.lock(file, "w");
if locked then
file:close();
return false, "pidfile-not-locked";
end
local pid = tonumber(file:read("*a"));
file:close();
if not pid then
return false, "invalid-pid";
end
return true, pid;
end
local function isrunning()
local ok, pid, err = getpid();
if not ok then
if pid == "pidfile-read-failed" or pid == "pidfile-not-locked" then
-- Report as not running, since we can't open the pidfile
-- (it probably doesn't exist)
return true, false;
end
return ok, pid;
end
return true, signal.kill(pid, 0) == 0;
end
local function start()
local ok, ret = isrunning();
if not ok then
return ok, ret;
end
if ret then
return false, "already-running";
end
if not CFG_SOURCEDIR then
os.execute("./prosody");
else
os.execute(CFG_SOURCEDIR.."/../../bin/prosody");
end
return true;
end
local function stop()
local ok, ret = isrunning();
if not ok then
return ok, ret;
end
if not ret then
return false, "not-running";
end
local ok, pid = getpid()
if not ok then return false, pid; end
signal.kill(pid, signal.SIGTERM);
return true;
end
local function reload()
local ok, ret = isrunning();
if not ok then
return ok, ret;
end
if not ret then
return false, "not-running";
end
local ok, pid = getpid()
if not ok then return false, pid; end
signal.kill(pid, signal.SIGHUP);
return true;
end
return {
show_message = show_message;
show_warning = show_message;
show_usage = show_usage;
getchar = getchar;
getline = getline;
getpass = getpass;
show_yesno = show_yesno;
read_password = read_password;
show_prompt = show_prompt;
adduser = adduser;
user_exists = user_exists;
passwd = passwd;
deluser = deluser;
getpid = getpid;
isrunning = isrunning;
start = start;
stop = stop;
reload = reload;
};
| mit |
roboxt/fik | plugins/Badwords.lua | 8 | 2478 | local function addword(msg, name)
local hash = 'chat:'..msg.to.id..':badword'
redis:hset(hash, name, 'newword')
return "کلمه جدید به فیلتر کلمات اضافه شد\n>"..name
end
local function get_variables_hash(msg)
return 'chat:'..msg.to.id..':badword'
end
local function list_variablesbad(msg)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = 'لیست کلمات غیرمجاز :\n\n'
for i=1, #names do
text = text..'> '..names[i]..'\n'
end
return text
else
return
end
end
function clear_commandbad(msg, var_name)
--Save on redis
local hash = get_variables_hash(msg)
redis:del(hash, var_name)
return 'پاک شدند'
end
local function list_variables2(msg, value)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = ''
for i=1, #names do
if string.match(value, names[i]) and not is_momod(msg) then
if msg.to.type == 'channel' then
delete_msg(msg.id,ok_cb,false)
else
kick_user(msg.from.id, msg.to.id)
end
return
end
--text = text..names[i]..'\n'
end
end
end
local function get_valuebad(msg, var_name)
local hash = get_variables_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if not value then
return
else
return value
end
end
end
function clear_commandsbad(msg, cmd_name)
--Save on redis
local hash = get_variables_hash(msg)
redis:hdel(hash, cmd_name)
return ''..cmd_name..' پاک شد'
end
local function run(msg, matches)
if matches[2] == 'addword' then
if not is_momod(msg) then
return 'only for moderators'
end
local name = string.sub(matches[3], 1, 50)
local text = addword(msg, name)
return text
end
if matches[2] == 'badwords' then
return list_variablesbad(msg)
elseif matches[2] == 'clearbadwords' then
if not is_momod(msg) then return '_|_' end
local asd = '1'
return clear_commandbad(msg, asd)
elseif matches[2] == 'remword' or matches[2] == 'rw' then
if not is_momod(msg) then return '_|_' end
return clear_commandsbad(msg, matches[3])
else
local name = user_print_name(msg.from)
return list_variables2(msg, matches[1])
end
end
return {
patterns = {
"^([!/#])(rw) (.*)$",
"^([!/#])(addword) (.*)$",
"^([!/#])(remword) (.*)$",
"^([!/#])(badwords)$",
"^([!/#])(clearbadwords)$",
"^(.+)$",
},
run = run
}
| gpl-2.0 |
AresTao/darkstar | scripts/zones/Metalworks/Zone.lua | 28 | 1683 | -----------------------------------
--
-- Zone: Metalworks (237)
--
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/zone");
require("scripts/globals/settings");
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(-9.168,0,0.001,128);
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
openium/overthebox-feeds | luci-mod-admin-full/luasrc/model/cbi/admin_network/wifi_add.lua | 50 | 4887 | -- Copyright 2009 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local fs = require "nixio.fs"
local nw = require "luci.model.network"
local fw = require "luci.model.firewall"
local uci = require "luci.model.uci".cursor()
local http = require "luci.http"
local iw = luci.sys.wifi.getiwinfo(http.formvalue("device"))
local has_firewall = fs.access("/etc/config/firewall")
if not iw then
luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless"))
return
end
m = SimpleForm("network", translate("Join Network: Settings"))
m.cancel = translate("Back to scan results")
m.reset = false
function m.on_cancel()
local dev = http.formvalue("device")
http.redirect(luci.dispatcher.build_url(
dev and "admin/network/wireless_join?device=" .. dev
or "admin/network/wireless"
))
end
nw.init(uci)
fw.init(uci)
m.hidden = {
device = http.formvalue("device"),
join = http.formvalue("join"),
channel = http.formvalue("channel"),
mode = http.formvalue("mode"),
bssid = http.formvalue("bssid"),
wep = http.formvalue("wep"),
wpa_suites = http.formvalue("wpa_suites"),
wpa_version = http.formvalue("wpa_version")
}
if iw and iw.mbssid_support then
replace = m:field(Flag, "replace", translate("Replace wireless configuration"),
translate("An additional network will be created if you leave this unchecked."))
function replace.cfgvalue() return "1" end
else
replace = m:field(DummyValue, "replace", translate("Replace wireless configuration"))
replace.default = translate("The hardware is not multi-SSID capable and the existing " ..
"configuration will be replaced if you proceed.")
function replace.formvalue() return "1" end
end
if http.formvalue("wep") == "1" then
key = m:field(Value, "key", translate("WEP passphrase"),
translate("Specify the secret encryption key here."))
key.password = true
key.datatype = "wepkey"
elseif (tonumber(m.hidden.wpa_version) or 0) > 0 and
(m.hidden.wpa_suites == "PSK" or m.hidden.wpa_suites == "PSK2")
then
key = m:field(Value, "key", translate("WPA passphrase"),
translate("Specify the secret encryption key here."))
key.password = true
key.datatype = "wpakey"
--m.hidden.wpa_suite = (tonumber(http.formvalue("wpa_version")) or 0) >= 2 and "psk2" or "psk"
end
newnet = m:field(Value, "_netname_new", translate("Name of the new network"),
translate("The allowed characters are: <code>A-Z</code>, <code>a-z</code>, " ..
"<code>0-9</code> and <code>_</code>"
))
newnet.default = m.hidden.mode == "Ad-Hoc" and "mesh" or "wwan"
newnet.datatype = "uciname"
if has_firewall then
fwzone = m:field(Value, "_fwzone",
translate("Create / Assign firewall-zone"),
translate("Choose the firewall zone you want to assign to this interface. Select <em>unspecified</em> to remove the interface from the associated zone or fill out the <em>create</em> field to define a new zone and attach the interface to it."))
fwzone.template = "cbi/firewall_zonelist"
fwzone.default = m.hidden.mode == "Ad-Hoc" and "mesh" or "wan"
end
function newnet.parse(self, section)
local net, zone
if has_firewall then
local zval = fwzone:formvalue(section)
zone = fw:get_zone(zval)
if not zone and zval == '-' then
zval = m:formvalue(fwzone:cbid(section) .. ".newzone")
if zval and #zval > 0 then
zone = fw:add_zone(zval)
end
end
end
local wdev = nw:get_wifidev(m.hidden.device)
wdev:set("disabled", false)
wdev:set("channel", m.hidden.channel)
if replace:formvalue(section) then
local n
for _, n in ipairs(wdev:get_wifinets()) do
wdev:del_wifinet(n)
end
end
local wconf = {
device = m.hidden.device,
ssid = m.hidden.join,
mode = (m.hidden.mode == "Ad-Hoc" and "adhoc" or "sta")
}
if m.hidden.wep == "1" then
wconf.encryption = "wep-open"
wconf.key = "1"
wconf.key1 = key and key:formvalue(section) or ""
elseif (tonumber(m.hidden.wpa_version) or 0) > 0 then
wconf.encryption = (tonumber(m.hidden.wpa_version) or 0) >= 2 and "psk2" or "psk"
wconf.key = key and key:formvalue(section) or ""
else
wconf.encryption = "none"
end
if wconf.mode == "adhoc" or wconf.mode == "sta" then
wconf.bssid = m.hidden.bssid
end
local value = self:formvalue(section)
net = nw:add_network(value, { proto = "dhcp" })
if not net then
self.error = { [section] = "missing" }
else
wconf.network = net:name()
local wnet = wdev:add_wifinet(wconf)
if wnet then
if zone then
fw:del_network(net:name())
zone:add_network(net:name())
end
uci:save("wireless")
uci:save("network")
uci:save("firewall")
luci.http.redirect(wnet:adminlink())
end
end
end
if has_firewall then
function fwzone.cfgvalue(self, section)
self.iface = section
local z = fw:get_zone_by_network(section)
return z and z:name()
end
end
return m
| gpl-3.0 |
DeinFreund/Zero-K | LuaUI/Widgets/api_cluster_detection.lua | 17 | 26408 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "Cluster Detection",
desc = "Unit cluster detection API",
author = "msafwan",
date = "2011.10.22",
license = "GNU GPL, v2 or later",
layer = -math.huge,
enabled = true,
api = true,
alwaysStart = true,
}
end
local echoOutCalculationTime = false
---------------------------------------------------------------------------------
-----------C L U S T E R D E T E C T I O N T O O L --------------------------
---------------------------------------------------------------------------------
--Note: maintained by msafwan (xponen)
--Positional Functions------------------------------------------------------------
-- 3 function.
local searchCount = 0
local function BinarySearchNaturalOrder(position, orderedList)
local prevCount = os.clock()
local startPos = 1
local endPos = #orderedList
local span = endPos - startPos
local midPos = math.modf((span/2) + startPos + 0.5) --round to nearest integer
local found = false
while (span > 1) do
local difference = position - orderedList[midPos][2]
if difference < 0 then
endPos = midPos
elseif difference > 0 then
startPos = midPos
else
found=true
break;
end
span = endPos - startPos
midPos = math.modf((span/2) + startPos + 0.5) --round to nearest integer
end
if not found then
if(math.abs(position - orderedList[startPos][2]) < math.abs(position - orderedList[endPos][2])) then
midPos = startPos
else
midPos = endPos
end
end
searchCount = searchCount + (os.clock() - prevCount)
return midPos
end
local distCount = 0
local function GetDistanceSQ(unitID1, unitID2,receivedUnitList)
local prevClock = os.clock()
local x1,x2 = receivedUnitList[unitID1][1],receivedUnitList[unitID2][1]
local z1,z2 = receivedUnitList[unitID1][3],receivedUnitList[unitID2][3]
local distanceSQ = ((x1-x2)^2 + (z1-z2)^2)
distCount = distCount + (os.clock() - prevClock)
return distanceSQ
end
local intersectionCount = 0
local function GetUnitsInSquare(x,z,distance,posListX)
local unitIndX = BinarySearchNaturalOrder(x, posListX)
local unitsX = {}
for i = unitIndX, 1, -1 do --go left
if x - posListX[i][2] > distance then
break
end
unitsX[#unitsX+1]=posListX[i]
end
for i = unitIndX+1, #posListX, 1 do --go right
if posListX[i][2]-x > distance then
break
end
unitsX[#unitsX+1]=posListX[i]
end
if #unitsX == 0 then
return unitsX
end
local prevClock = os.clock()
local unitsInBox = {}
for i=1, #unitsX, 1 do
if (math.abs(unitsX[i][3]-z) <= distance) then
unitsInBox[#unitsInBox+1] = unitsX[i][1]
end
end
intersectionCount = intersectionCount + (os.clock()-prevClock)
return unitsInBox
end
--GetNeigbors--------------------------------------------------------------------
-- 1 function.
local getunitCount = 0
local function GetNeighbor (unitID, myTeamID, neighborhoodRadius, receivedUnitList,posListX) --//return the unitIDs of specific units around a center unit
local prevCount = os.clock()
local x,z = receivedUnitList[unitID][1],receivedUnitList[unitID][3]
local tempList = GetUnitsInSquare(x,z,neighborhoodRadius,posListX) --Get neighbor. Ouput: unitID + my units
getunitCount = getunitCount + (os.clock() - prevCount)
return tempList
end
--Pre-SORTING function----------------------------------------------------------------
--3 function
local function InsertAtOrder(posList, newObject,compareFunction) --//stack big values at end of table, and tiny values at start of table.
local insertionIndex = #posList + 1 --//insert data just below that big value
for i = #posList, 1, -1 do
if compareFunction(posList[i],newObject) then-- posList[i] < newObject will sort in ascending order, while posList[i] > newObject will sort in descending order
break
end
insertionIndex=i
end
--//shift table content
local buffer1 = posList[insertionIndex] --backup content of current index
posList[insertionIndex] = newObject --replace current index with new value. eg: {unitID = objects.unitID , x = objects.x, z = objects.z }
for j = insertionIndex, #posList, 1 do --shift content for content less-or-equal-to table lenght
local buffer2 = posList[j+1] --save content of next index
posList[j+1] = buffer1 --put backup value into next index
buffer1 = buffer2 --use saved content as next backup, then repeat process
end
return posList
end
local insertCount = 0
local function InsertOrderSeed (orderSeed, unitID_to_orderSeedMeta, unitID, objects) --//stack tiny values at end of table, and big values at start of table.
local prevClock = os.clock()
local orderSeedLenght = #orderSeed or 0 --//code below can handle both: table of lenght 0 and >1
local insertionIndex = orderSeedLenght + 1 --//insert data just above that big value
for i = orderSeedLenght, 1, -1 do
if orderSeed[i].content.reachability_distance >= objects[unitID].reachability_distance then --//if existing value is abit bigger than to-be-inserted value: break
break
end
insertionIndex=i
end
--//shift table content
local buffer1 = orderSeed[insertionIndex] --backup content of current index
orderSeed[insertionIndex] = {unitID = unitID , content = objects[unitID]} --replace current index with new value
unitID_to_orderSeedMeta[unitID]=insertionIndex --update meta table
for j = insertionIndex, orderSeedLenght, 1 do --shift content for content less-or-equal-to table lenght
local buffer2 = orderSeed[j+1] --save content of next index
orderSeed[j+1] = buffer1 --put backup value into next index
unitID_to_orderSeedMeta[buffer1.unitID]=j+1 -- update meta table
buffer1 = buffer2 --use saved content as next backup, then repeat process
end
insertCount = insertCount + (os.clock() - prevClock)
return orderSeed, unitID_to_orderSeedMeta
end
local shiftCount = 0
local function ShiftOrderSeed (orderSeed, unitID_to_orderSeedMeta, unitID, objects) --//move values to end of table, and shift big values to beginning of of table.
local prevClock = os.clock()
local oldPosition = unitID_to_orderSeedMeta[unitID]
local newPosition = oldPosition
for i = oldPosition+1, #orderSeed, 1 do
if orderSeed[i].content.reachability_distance < objects[unitID].reachability_distance then --//if existing value is abit lower than to-be-inserted value: add behind it and break
break
end
newPosition = i
end
if newPosition == oldPosition then
orderSeed[oldPosition]={unitID = unitID , content = objects[unitID]}
else
local buffer1 = orderSeed[newPosition] --//backup content of current index
orderSeed[newPosition] = {unitID = unitID , content = objects[unitID]} --//replace current index with new value
unitID_to_orderSeedMeta[unitID]=newPosition --//update meta table
orderSeed[oldPosition] = nil --//delete old position
for j = newPosition-1, oldPosition, -1 do --//shift values toward beginning of table
local buffer2 = orderSeed[j] --//save content of current index
orderSeed[j] = buffer1 --//put backup value into previous index
unitID_to_orderSeedMeta[buffer1.unitID]=j --// update meta table
buffer1 = buffer2 --//use saved content as the following backup, then repeat process
end
end
shiftCount = shiftCount + (os.clock() - prevClock)
return orderSeed, unitID_to_orderSeedMeta
end
--Merge-SORTING function----------------------------------------------------------------
--2 function. Reference: http://www.algorithmist.com/index.php/Merge_sort.c
local function merge(left, right, CompareFunction)
local result ={} --var list result
local leftProgress, rightProgress = 1,1
while leftProgress <= #left or rightProgress <= #right do --while length(left) > 0 or length(right) > 0
local leftNotFinish = leftProgress <= #left
local rightNotFinish = rightProgress <= #right
if leftNotFinish and rightNotFinish then --if length(left) > 0 and length(right) > 0
if CompareFunction(left[leftProgress],right[rightProgress]) then --if first(left) < first(right), sort ascending. if first(left) > first(right), sort descending.
result[#result+1] =left[leftProgress]--append first(left) to result
leftProgress = leftProgress + 1 --left = rest(left)
else
result[#result+1] =right[rightProgress]--append first(right) to result
rightProgress = rightProgress + 1 --right = rest(right)
end
elseif leftNotFinish then --else if length(left) > 0
result[#result+1] =left[leftProgress] --append first(left) to result
leftProgress = leftProgress + 1 --left = rest(left)
elseif rightNotFinish then --else if length(right) > 0
result[#result+1] =right[rightProgress] --append first(right) to result
rightProgress = rightProgress + 1 --right = rest(right)
end
end --end while
return result
end
local function merge_sort(m,CompareFunction)
--// if list size is 1, consider it sorted and return it
if #m <=1 then--if length(m) <= 1
return m
end
--// else list size is > 1, so split the list into two sublists
local left, right = {}, {} --var list left, right
local middle = math.modf((#m/2)+0.5) --var integer middle = length(m) / 2
for i= 1, middle, 1 do --for each x in m up to middle
left[#left+1] = m[i] --add x to left
end
for j= #m, middle+1, -1 do--for each x in m after or equal middle
right[(j-middle)] = m[j]--add x to right
end
--// recursively call merge_sort() to further split each sublist
--// until sublist size is 1
left = merge_sort(left,CompareFunction)
right = merge_sort(right,CompareFunction)
--// merge the sublists returned from prior calls to merge_sort()
--// and return the resulting merged sublist
return merge(left, right,CompareFunction)
end
--OPTICS function----------------------------------------------------------------
--5 function
local useMergeSorter_gbl = true --//constant: experiment with merge sorter (slower)
local orderseedCount = 0
local function OrderSeedsUpdate(neighborsID, currentUnitID,objects, orderSeed,unitID_to_orderSeedMeta,receivedUnitList)
local prevCount = os.clock()
local c_dist = objects[currentUnitID].core_distance
for i=1, #neighborsID do
local neighborUnitID = neighborsID[i]
objects[neighborUnitID]=objects[neighborUnitID] or {unitID=neighborUnitID,}
if (objects[neighborUnitID].processed~=true) then
local new_r_dist = math.max(c_dist, GetDistanceSQ(currentUnitID, neighborUnitID,receivedUnitList))
if objects[neighborUnitID].reachability_distance==nil then
objects[neighborUnitID].reachability_distance = new_r_dist
if useMergeSorter_gbl then
orderSeed[#orderSeed+1] = {unitID = neighborUnitID, content = objects[neighborUnitID]}
unitID_to_orderSeedMeta[neighborUnitID] = #orderSeed
else
orderSeed, unitID_to_orderSeedMeta = InsertOrderSeed (orderSeed, unitID_to_orderSeedMeta, neighborUnitID,objects)
end
else --// object already in OrderSeeds
if new_r_dist< objects[neighborUnitID].reachability_distance then
objects[neighborUnitID].reachability_distance = new_r_dist
if useMergeSorter_gbl then
local oldPosition = unitID_to_orderSeedMeta[neighborUnitID]
orderSeed[oldPosition] = {unitID = neighborUnitID, content = objects[neighborUnitID]} -- update values
else
orderSeed, unitID_to_orderSeedMeta = ShiftOrderSeed(orderSeed, unitID_to_orderSeedMeta, neighborUnitID, objects)
end
end
end
end
end
if useMergeSorter_gbl then
-- orderSeed = merge_sort(orderSeed, function(a,b) return a.content.reachability_distance > b.content.reachability_distance end ) --really slow
table.sort(orderSeed, function(a,b) return a.content.reachability_distance > b.content.reachability_distance end) --abit slow
for i= 1, #orderSeed do
unitID_to_orderSeedMeta[orderSeed[i].unitID] = i
end
end
orderseedCount = orderseedCount + (os.clock() - prevCount)
return orderSeed, objects, unitID_to_orderSeedMeta
end
local setcoreCount =0
local function SetCoreDistance(neighborsID, minimumNeighbor, unitID,receivedUnitList)
if (#neighborsID >= minimumNeighbor) then
local neighborsDist= {} --//table to list down neighbor's distance.
for i=1, #neighborsID do
-- local distance = spGetUnitSeparation (unitID, neighborsID[i])
local distanceSQ = GetDistanceSQ(unitID,neighborsID[i],receivedUnitList)
neighborsDist[i]= distanceSQ --//add distance value
end
local prevCount = os.clock()
table.sort(neighborsDist, function(a,b) return a < b end)
-- neighborsDist = merge_sort(neighborsDist, true)
setcoreCount = setcoreCount + (os.clock()-prevCount)
return neighborsDist[minimumNeighbor] --//return the distance of the minimumNeigbor'th unit with respect to the center unit.
else
return nil
end
end
local function ExtractDBSCAN_Clustering (unitID, currentClusterID, cluster, noiseIDList, object, neighborhoodRadius_alt)
local reachabilityDist = (object.reachability_distance and math.sqrt(object.reachability_distance)) or 9999
--// Precondition: neighborhoodRadius_alt <= generating dist neighborhoodRadius for Ordered Objects
if reachabilityDist > neighborhoodRadius_alt then --// UNDEFINED > neighborhoodRadius. ie: Not reachable from outside
local coreDistance = (object.core_distance and math.sqrt(object.core_distance)) or 9999
if coreDistance <= neighborhoodRadius_alt then --//has neighbor
currentClusterID = currentClusterID + 1 --//create new cluster
cluster[currentClusterID] = cluster[currentClusterID] or {} --//initialize array
local arrayIndex = #cluster[currentClusterID] + 1
cluster[currentClusterID][arrayIndex] = unitID --//add to new cluster
-- Spring.Echo("CREATE CLUSTER")
else --//if has no neighbor
local arrayIndex = #noiseIDList +1
noiseIDList[arrayIndex]= unitID --//add to noise list
end
else --// object.reachability_distance <= neighborhoodRadius_alt. ie:reachable
local arrayIndex = #cluster[currentClusterID] + 1
cluster[currentClusterID][arrayIndex] = unitID--//add to current cluster
end
return cluster, noiseIDList, currentClusterID
end
local function ExpandClusterOrder(orderedObjects,receivedUnitList, unitID, neighborhoodRadius, minimumNeighbor, objects,posListX)
local neighborsID = GetNeighbor (unitID, myTeamID, neighborhoodRadius, receivedUnitList,posListX)
objects[unitID].processed = true
objects[unitID].reachability_distance = nil
objects[unitID].core_distance = SetCoreDistance(neighborsID, minimumNeighbor, unitID,receivedUnitList)
orderedObjects[#orderedObjects+1]=objects[unitID]
if objects[unitID].core_distance ~= nil then --//it have neighbor
local orderSeed ={}
local unitID_to_orderSeedMeta = {}
orderSeed, objects, unitID_to_orderSeedMeta = OrderSeedsUpdate(neighborsID, unitID, objects, orderSeed,unitID_to_orderSeedMeta,receivedUnitList)
while #orderSeed > 0 do
local currentUnitID = orderSeed[#orderSeed].unitID
objects[currentUnitID] = orderSeed[#orderSeed].content
orderSeed[#orderSeed]=nil
local neighborsID_ne = GetNeighbor (currentUnitID, myTeamID, neighborhoodRadius, receivedUnitList,posListX)
objects[currentUnitID].processed = true
objects[currentUnitID].core_distance = SetCoreDistance(neighborsID_ne, minimumNeighbor, currentUnitID,receivedUnitList)
orderedObjects[#orderedObjects+1]=objects[currentUnitID]
if objects[currentUnitID].core_distance~=nil then
orderSeed, objects,unitID_to_orderSeedMeta = OrderSeedsUpdate(neighborsID_ne, currentUnitID, objects, orderSeed, unitID_to_orderSeedMeta,receivedUnitList)
end
end
end
return orderedObjects,objects
end
function WG.OPTICS_cluster (receivedUnitList, neighborhoodRadius, minimumNeighbor, _, neighborhoodRadius_alt) --//OPTIC_cluster function are accessible globally
local objects={}
local orderedObjects = {}
local cluster = {}
local noiseIDList = {}
local currentClusterID = 0
local posListX= {}
local osClock1 = os.clock()
--//SORTING unit list by X axis for easier searching, for getting unit in a box thru GetUnitInSquare()
neighborhoodRadius = math.max(neighborhoodRadius_alt,neighborhoodRadius)
for unitID,pos in pairs(receivedUnitList) do
posListX[#posListX+1] = {unitID,pos[1],pos[3]}
-- posListX = InsertAtOrder(posListX, {unitID,pos[1],pos[3]},function(a,b) return a[2]<b[2] end) --abit slow
end
table.sort(posListX, function(a,b) return a[2]<b[2] end) --//stack ascending
if echoOutCalculationTime then
distCount,shiftCount,insertCount = 0,0,0
setcoreCount,getunitCount,searchCount = 0,0,0
orderseedCount,intersectionCount = 0,0
Spring.Echo("SPEED")
Spring.Echo("Initial sorting: ".. os.clock() - osClock1)
osClock1 = os.clock()
end
--//SORTING unit list by connections, for extracting cluster information later using ExtractDBSCAN_Clustering()
for unitID,_ in pairs(receivedUnitList) do --//go thru the un-ordered list
objects[unitID] = objects[unitID] or {unitID=unitID,}
if (objects[unitID].processed ~= true) then
orderedObjects, objects = ExpandClusterOrder(orderedObjects,receivedUnitList,unitID, neighborhoodRadius,minimumNeighbor,objects,posListX)
end
end
if echoOutCalculationTime then
Spring.Echo("OPTICs: ".. os.clock() - osClock1)
Spring.Echo(" Distance calculation: ".. distCount)
Spring.Echo(" OrderSeed calc: " .. orderseedCount)
Spring.Echo(" Insert calculation: " .. insertCount)
Spring.Echo(" Shift calculation: " .. shiftCount)
Spring.Echo(" SetCore sort calc: " .. setcoreCount)
Spring.Echo(" GetUnitBox calc: " .. getunitCount)
Spring.Echo(" BinarySearch: " .. searchCount)
Spring.Echo(" Intersection: " .. intersectionCount)
osClock1 = os.clock()
end
--//CREATE cluster based on desired density (density == neighborhoodRadius_alt).
--//Note: changing cluster view to different density is really cheap when using this function as long as the initial neighborhoodRadius is greater than the new density.
--//if new density (neighborhoodRadius_alt) is greater than initial neighborhoodRadius, then you must recalculate the connections using bigger neighborhoodRadius which incur greater cost.
for i=1, #orderedObjects do
local unitID = orderedObjects[i].unitID
cluster, noiseIDList, currentClusterID = ExtractDBSCAN_Clustering (unitID, currentClusterID, cluster, noiseIDList, orderedObjects[i], neighborhoodRadius_alt)
end
if echoOutCalculationTime then
Spring.Echo("Extract Cluster: ".. os.clock() - osClock1)
end
return cluster, noiseIDList
end
function WG.Run_OPTIC(receivedUnitList, neighborhoodRadius, minimumNeighbor) --//OPTIC_cluster function are accessible globally
local objects={}
local orderedObjects = {}
local posListX= {}
--//SORTING unit list by X axis for easier searching, for getting unit in a box thru GetUnitInSquare()
for unitID,pos in pairs(receivedUnitList) do
posListX[#posListX+1] = {unitID,pos[1],pos[3]}
-- posListX = InsertAtOrder(posListX, {unitID,pos[1],pos[3]},function(a,b) return a[2]<b[2] end) --abit slow
end
table.sort(posListX, function(a,b) return a[2]<b[2] end) --//stack ascending
--//SORTING unit list by connections, for extracting cluster information later using ExtractDBSCAN_Clustering()
for unitID,_ in pairs(receivedUnitList) do --//go thru the un-ordered list
objects[unitID] = objects[unitID] or {unitID=unitID,}
if (objects[unitID].processed ~= true) then
orderedObjects, objects = ExpandClusterOrder(orderedObjects,receivedUnitList,unitID, neighborhoodRadius,minimumNeighbor,objects,posListX)
end
end
return orderedObjects
end
function WG.Extract_Cluster (orderedObjects,neighborhoodRadius_alt )
local cluster = {}
local noiseIDList = {}
local currentClusterID = 0
--//CREATE cluster based on desired density (density == neighborhoodRadius_alt).
--//Note: changing cluster view to different density is really cheap when using this function as long as the initial neighborhoodRadius is greater than the new density.
--//if new density (neighborhoodRadius_alt) is greater than initial neighborhoodRadius, then you must recalculate the connections using bigger neighborhoodRadius which incur greater cost.
for i=1, #orderedObjects do
local unitID = orderedObjects[i].unitID
cluster, noiseIDList, currentClusterID = ExtractDBSCAN_Clustering (unitID, currentClusterID, cluster, noiseIDList, orderedObjects[i], neighborhoodRadius_alt)
end
return cluster, noiseIDList
end
function WG.Convert_To_Circle (cluster, noiseIDList,receivedUnitList)
--// extract cluster information and add mapMarker.
local circlePosition = {}
for index=1 , #cluster do
local sumX, sumY,sumZ, unitCount,meanX, meanY, meanZ = 0,0 ,0 ,0 ,0,0,0
local maxX, minX, maxZ, minZ, radiiX, radiiZ, avgRadii = 0,99999,0,99999, 0,0,0
for unitIndex=1, #cluster[index] do
local unitID = cluster[index][unitIndex]
local x,y,z= receivedUnitList[unitID][1],receivedUnitList[unitID][2],receivedUnitList[unitID][3] --// get stored unit position
sumX= sumX+x
sumY = sumY+y
sumZ = sumZ+z
if x> maxX then
maxX= x
end
if x<minX then
minX=x
end
if z> maxZ then
maxZ= z
end
if z<minZ then
minZ=z
end
unitCount=unitCount+1
end
meanX = sumX/unitCount --//calculate center of cluster
meanY = sumY/unitCount
meanZ = sumZ/unitCount
radiiX = ((maxX - meanX)+ (meanX - minX))/2
radiiZ = ((maxZ - meanZ)+ (meanZ - minZ))/2
avgRadii = (radiiX + radiiZ) /2
circlePosition[#circlePosition+1] = {meanX,0,meanZ,avgRadii+100,#cluster[index]}
end
if #noiseIDList>0 then --//IF outlier list is not empty
for j= 1 ,#noiseIDList do
local unitID = noiseIDList[j]
local x,y,z= receivedUnitList[unitID][1],receivedUnitList[unitID][2],receivedUnitList[unitID][3] --// get stored unit position
circlePosition[#circlePosition+1] = {x,0,z,100,1}
end
end
return circlePosition
end
--DBSCAN function----------------------------------------------------------
--1 function. BUGGY (Not yet debugged)
function WG.DBSCAN_cluster(receivedUnitList,neighborhoodRadius,minimumNeighbor)
local unitID_to_clusterMeta = {}
local visitedUnitID = {}
local currentCluster_global=1
local cluster = {}
local unitIDNoise = {}
local posListX = {}
for unitID,pos in pairs(receivedUnitList) do
posListX[#posListX+1] = {unitID,pos[1],pos[3]}
-- posListX = InsertAtOrder(posListX, {unitID,pos[1],pos[3]},function(a,b) return a[2]<b[2] end) --abit slow
end
table.sort(posListX, function(a,b) return a[2]<b[2] end) --//stack ascending
for unitID,_ in pairs(receivedUnitList) do --//go thru the un-ordered list
if visitedUnitID[unitID] ~= true then --//skip if already visited
visitedUnitID[unitID] = true
local neighborUnits = GetNeighbor (unitID, myTeamID, neighborhoodRadius, receivedUnitList,posListX)
if #neighborUnits ~= nil then
if #neighborUnits <= minimumNeighbor then --//if surrounding units is less-or-just-equal to minimum neighbor then mark current unit as noise or 'outliers'
local noiseIDLenght = #unitIDNoise or 0 --// if table is empty then make sure return table-lenght as 0 (zero) instead of 'nil'
unitIDNoise[noiseIDLenght +1] = unitID
else
--local clusterIndex = #cluster+1 --//lenght of previous cluster table plus 1 new cluster
cluster[currentCluster_global]={} --//initialize new cluster with an empty table for unitID
local unitClusterLenght = #cluster[currentCluster_global] or 0 --// if table is empty then make sure return table-lenght as 0 (zero) instead of 'nil'
cluster[currentCluster_global][unitClusterLenght +1] = unitID --//lenght of the table-in-table containing unit list plus 1 new unit
unitID_to_clusterMeta[unitID] = currentCluster_global
for l=1, #neighborUnits do
local unitID_ne = neighborUnits[l]
if visitedUnitID[unitID_ne] ~= true then --//skip if already visited
visitedUnitID[unitID_ne] = true
local neighborUnits_ne = GetNeighbor (unitID_ne, myTeamID, neighborhoodRadius, receivedUnitList,posListX)
if #neighborUnits_ne ~= nil then
if #neighborUnits_ne > minimumNeighbor then
for m=1, #neighborUnits_ne do
local duplicate = false
for n=1, #neighborUnits do
if neighborUnits[n] == neighborUnits_ne[m] then
duplicate = true
break
end
end
if duplicate== false then
neighborUnits[#neighborUnits +1]=neighborUnits_ne[m]
end
end --//for m=1, m<= #neighborUnits_ne, 1
end --// if #neighborUnits_ne > minimumNeighbor
end --//if #neighborUnits_ne ~= nil
if unitID_to_clusterMeta[unitID_ne] ~= currentCluster_global then
local unitIndex_ne = #cluster[currentCluster_global] +1 --//lenght of the table-in-table containing unit list plus 1 new unit
cluster[currentCluster_global][unitIndex_ne] = unitID_ne
unitID_to_clusterMeta[unitID_ne] = currentCluster_global
end
end --//if visitedUnitID[unitID_ne] ~= true
end --//for l=1, l <= #neighborUnits, 1
currentCluster_global= currentCluster_global + 1
end --//if #neighborUnits <= minimumNeighbor, else
end --//if #neighborUnits ~= nil
end --//if visitedUnitID[unitID] ~= true
end --//for i=1, i <= #receivedUnitList,1
return cluster, unitIDNoise
end
--brief: a clustering algorithm
--algorithm source: Ordering Points To Identify the Clustering Structure (OPTICS) by Mihael Ankerst, Markus M. Breunig, Hans-Peter Kriegel and Jörg Sander
--algorithm source: density-based spatial clustering of applications with noise (DBSCAN) by Martin Ester, Hans-Peter Kriegel, Jörg Sander and Xiaowei Xu
--Reference:
--http://en.wikipedia.org/wiki/OPTICS_algorithm ;pseudocode
--http://en.wikipedia.org/wiki/DBSCAN ;pseudocode
--http://codingplayground.blogspot.com/2009/11/dbscan-clustering-algorithm.html ;C++ sourcecode
--http://www.google.com.my/search?q=optics%3A+Ordering+Points+To+Identify+the+Clustering+Structure ;article & pseudocode on OPTICS
---------------------------------------------------------------------------------
---------------------------------E N D ------------------------------------------
--------------------------------------------------------------------------------- | gpl-2.0 |
small-Wood/FlappyBird | runtime/linux/Resources/src/main.lua | 3 | 1713 |
-- cclog
cclog = function(...)
print(string.format(...))
end
-- for CCLuaEngine traceback
function __G__TRACKBACK__(msg)
cclog("----------------------------------------")
cclog("LUA ERROR: " .. tostring(msg) .. "\n")
cclog(debug.traceback())
cclog("----------------------------------------")
end
-- run a scene
function runScene(_scene)
if cc.Director:getInstance():getRunningScene() then
cc.Director:getInstance():replaceScene(_scene)
else
cc.Director:getInstance():runWithScene(_scene)
end
end
-- static var
visibleSize = cc.Director:getInstance():getVisibleSize()
origin = cc.Director:getInstance():getVisibleOrigin()
local function loadCocosLib()
require "Cocos2d"
require "Cocos2dConstants"
require "Resource"
require("AudioEngine")
require("extern")
require("AtlasLoader")
require("BirdSprite")
end
local function main()
collectgarbage("collect")
-- avoid memory leak
collectgarbage("setpause", 100)
collectgarbage("setstepmul", 5000)
local targetPlatform = cc.Application:getInstance():getTargetPlatform()
if targetPlatform == cc.PLATFORM_OS_WINDOWS then
cc.FileUtils:getInstance():addSearchResolutionsOrder("res/sounds/wav")
EFFECT_FORMAT = ".wav"
else
cc.FileUtils:getInstance():addSearchResolutionsOrder("res/sounds/ogg")
end
cc.FileUtils:getInstance():addSearchResolutionsOrder("src")
cc.FileUtils:getInstance():addSearchResolutionsOrder("res/fonts")
cc.FileUtils:getInstance():addSearchResolutionsOrder("res/image")
loadCocosLib()
local ls = require("LoadingScene")
runScene(ls.createScene())
end
xpcall(main, __G__TRACKBACK__)
| gpl-2.0 |
AresTao/darkstar | scripts/globals/spells/huton_san.lua | 17 | 1612 | -----------------------------------------
-- Spell: Huton: San
-- Deals wind damage to an enemy and lowers its resistance against ice.
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
--doNinjutsuNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus)
local duration = 15 + caster:getMerit(MERIT_HUTON_EFFECT) -- T1 bonus debuff duration
local bonusAcc = 0;
local bonusMab = caster:getMerit(MERIT_HUTON_EFFECT) + caster:getMod(MOD_NIN_NUKE_BONUS); -- T1 mag atk + "enhances Ninjustu damage" mod
if(caster:getMerit(MERIT_HUTON_SAN) ~= 0) then -- T2 mag atk/mag acc, don't want to give a penalty to entities that can cast this without merits
bonusMab = bonusMab + caster:getMerit(MERIT_HUTON_SAN) - 5; -- merit gives 5 power but no bonus with one invest, thus subtract 5
bonusAcc = bonusAcc + caster:getMerit(MERIT_HUTON_SAN) - 5;
end;
if (caster:isBehind(target,15) and caster:hasStatusEffect(EFFECT_INNIN)) then -- Innin mag atk bonus from behind, guesstimating angle at 15 degrees
bonusMab = bonusMab + caster:getStatusEffect(EFFECT_INNIN):getPower();
end
local dmg = doNinjutsuNuke(134,1,caster,spell,target,false,bonusAcc,bonusMab);
handleNinjutsuDebuff(caster,target,spell,30,duration,MOD_ICERES);
return dmg;
end; | gpl-3.0 |
ld-test/prosody | tools/migration/migrator/prosody_sql.lua | 3 | 6351 |
local assert = assert;
local have_DBI, DBI = pcall(require,"DBI");
local print = print;
local type = type;
local next = next;
local pairs = pairs;
local t_sort = table.sort;
local json = require "util.json";
local mtools = require "migrator.mtools";
local tostring = tostring;
local tonumber = tonumber;
if not have_DBI then
error("LuaDBI (required for SQL support) was not found, please see http://prosody.im/doc/depends#luadbi", 0);
end
module "prosody_sql"
local function create_table(connection, params)
local create_sql = "CREATE TABLE `prosody` (`host` TEXT, `user` TEXT, `store` TEXT, `key` TEXT, `type` TEXT, `value` TEXT);";
if params.driver == "PostgreSQL" then
create_sql = create_sql:gsub("`", "\"");
elseif params.driver == "MySQL" then
create_sql = create_sql:gsub("`value` TEXT", "`value` MEDIUMTEXT");
end
local stmt = connection:prepare(create_sql);
if stmt then
local ok = stmt:execute();
local commit_ok = connection:commit();
if ok and commit_ok then
local index_sql = "CREATE INDEX `prosody_index` ON `prosody` (`host`, `user`, `store`, `key`)";
if params.driver == "PostgreSQL" then
index_sql = index_sql:gsub("`", "\"");
elseif params.driver == "MySQL" then
index_sql = index_sql:gsub("`([,)])", "`(20)%1");
end
local stmt, err = connection:prepare(index_sql);
local ok, commit_ok, commit_err;
if stmt then
ok, err = assert(stmt:execute());
commit_ok, commit_err = assert(connection:commit());
end
elseif params.driver == "MySQL" then -- COMPAT: Upgrade tables from 0.8.0
-- Failed to create, but check existing MySQL table here
local stmt = connection:prepare("SHOW COLUMNS FROM prosody WHERE Field='value' and Type='text'");
local ok = stmt:execute();
local commit_ok = connection:commit();
if ok and commit_ok then
if stmt:rowcount() > 0 then
local stmt = connection:prepare("ALTER TABLE prosody MODIFY COLUMN `value` MEDIUMTEXT");
local ok = stmt:execute();
local commit_ok = connection:commit();
if ok and commit_ok then
print("Database table automatically upgraded");
end
end
repeat until not stmt:fetch();
end
end
end
end
local function serialize(value)
local t = type(value);
if t == "string" or t == "boolean" or t == "number" then
return t, tostring(value);
elseif t == "table" then
local value,err = json.encode(value);
if value then return "json", value; end
return nil, err;
end
return nil, "Unhandled value type: "..t;
end
local function deserialize(t, value)
if t == "string" then return value;
elseif t == "boolean" then
if value == "true" then return true;
elseif value == "false" then return false; end
elseif t == "number" then return tonumber(value);
elseif t == "json" then
return json.decode(value);
end
end
local function decode_user(item)
local userdata = {
user = item[1][1].user;
host = item[1][1].host;
stores = {};
};
for i=1,#item do -- loop over stores
local result = {};
local store = item[i];
for i=1,#store do -- loop over store data
local row = store[i];
local k = row.key;
local v = deserialize(row.type, row.value);
if k and v then
if k ~= "" then result[k] = v; elseif type(v) == "table" then
for a,b in pairs(v) do
result[a] = b;
end
end
end
userdata.stores[store[1].store] = result;
end
end
return userdata;
end
function reader(input)
local dbh = assert(DBI.Connect(
assert(input.driver, "no input.driver specified"),
assert(input.database, "no input.database specified"),
input.username, input.password,
input.host, input.port
));
assert(dbh:ping());
local stmt = assert(dbh:prepare("SELECT * FROM prosody"));
assert(stmt:execute());
local keys = {"host", "user", "store", "key", "type", "value"};
local f,s,val = stmt:rows(true);
-- get SQL rows, sorted
local iter = mtools.sorted {
reader = function() val = f(s, val); return val; end;
filter = function(x)
for i=1,#keys do
if not x[keys[i]] then return false; end -- TODO log error, missing field
end
if x.host == "" then x.host = nil; end
if x.user == "" then x.user = nil; end
if x.store == "" then x.store = nil; end
return x;
end;
sorter = function(a, b)
local a_host, a_user, a_store = a.host or "", a.user or "", a.store or "";
local b_host, b_user, b_store = b.host or "", b.user or "", b.store or "";
return a_host > b_host or (a_host==b_host and a_user > b_user) or (a_host==b_host and a_user==b_user and a_store > b_store);
end;
};
-- merge rows to get stores
iter = mtools.merged(iter, function(a, b)
return (a.host == b.host and a.user == b.user and a.store == b.store);
end);
-- merge stores to get users
iter = mtools.merged(iter, function(a, b)
return (a[1].host == b[1].host and a[1].user == b[1].user);
end);
return function()
local x = iter();
return x and decode_user(x);
end;
end
function writer(output, iter)
local dbh = assert(DBI.Connect(
assert(output.driver, "no output.driver specified"),
assert(output.database, "no output.database specified"),
output.username, output.password,
output.host, output.port
));
assert(dbh:ping());
create_table(dbh, output);
local stmt = assert(dbh:prepare("SELECT * FROM prosody"));
assert(stmt:execute());
local stmt = assert(dbh:prepare("DELETE FROM prosody"));
assert(stmt:execute());
local insert_sql = "INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)";
if output.driver == "PostgreSQL" then
insert_sql = insert_sql:gsub("`", "\"");
end
local insert = assert(dbh:prepare(insert_sql));
return function(item)
if not item then assert(dbh:commit()) return dbh:close(); end -- end of input
local host = item.host or "";
local user = item.user or "";
for store, data in pairs(item.stores) do
-- TODO transactions
local extradata = {};
for key, value in pairs(data) do
if type(key) == "string" and key ~= "" then
local t, value = assert(serialize(value));
local ok, err = assert(insert:execute(host, user, store, key, t, value));
else
extradata[key] = value;
end
end
if next(extradata) ~= nil then
local t, extradata = assert(serialize(extradata));
local ok, err = assert(insert:execute(host, user, store, "", t, extradata));
end
end
end;
end
return _M;
| mit |
NeoRaider/luci | protocols/luci-proto-ppp/luasrc/model/cbi/admin_network/proto_pppoe.lua | 47 | 3729 | -- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local map, section, net = ...
local username, password, ac, service
local ipv6, defaultroute, metric, peerdns, dns,
keepalive_failure, keepalive_interval, demand, mtu
username = section:taboption("general", Value, "username", translate("PAP/CHAP username"))
password = section:taboption("general", Value, "password", translate("PAP/CHAP password"))
password.password = true
ac = section:taboption("general", Value, "ac",
translate("Access Concentrator"),
translate("Leave empty to autodetect"))
ac.placeholder = translate("auto")
service = section:taboption("general", Value, "service",
translate("Service Name"),
translate("Leave empty to autodetect"))
service.placeholder = translate("auto")
if luci.model.network:has_ipv6() then
ipv6 = section:taboption("advanced", ListValue, "ipv6")
ipv6:value("auto", translate("Automatic"))
ipv6:value("0", translate("Disabled"))
ipv6:value("1", translate("Manual"))
ipv6.default = "auto"
end
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
peerdns = section:taboption("advanced", Flag, "peerdns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
peerdns.default = peerdns.enabled
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("peerdns", "")
dns.datatype = "ipaddr"
dns.cast = "string"
keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure",
translate("LCP echo failure threshold"),
translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures"))
function keepalive_failure.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^(%d+)[ ,]+%d+") or v)
end
end
keepalive_failure.placeholder = "0"
keepalive_failure.datatype = "uinteger"
keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval",
translate("LCP echo interval"),
translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold"))
function keepalive_interval.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^%d+[ ,]+(%d+)"))
end
end
function keepalive_interval.write(self, section, value)
local f = tonumber(keepalive_failure:formvalue(section)) or 0
local i = tonumber(value) or 5
if i < 1 then i = 1 end
if f > 0 then
m:set(section, "keepalive", "%d %d" %{ f, i })
else
m:del(section, "keepalive")
end
end
keepalive_interval.remove = keepalive_interval.write
keepalive_failure.write = keepalive_interval.write
keepalive_failure.remove = keepalive_interval.write
keepalive_interval.placeholder = "5"
keepalive_interval.datatype = "min(1)"
demand = section:taboption("advanced", Value, "demand",
translate("Inactivity timeout"),
translate("Close inactive connection after the given amount of seconds, use 0 to persist connection"))
demand.placeholder = "0"
demand.datatype = "uinteger"
mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU"))
mtu.placeholder = "1500"
mtu.datatype = "max(9200)"
| apache-2.0 |
DIVIY/TG-Bot | data/config.lua | 1 | 1319 | --DIVIY_IQ--
do local _ = {
about_text = "🚩Welcome to TH3BOSS V6 For more information Subscribe to the channel @llDEV1lln\n https://github.com/moody2020/TH3BOSS\n\n🚩Dev @TH3BOSS\n\n🚩 Dev Bot @ll60Kllbot\n\n 🚩channel @llDEV1ll",
enabled_plugins = {
"badword",
"admin",
"ingroup",
"stats",
"anti_spam",
"owners",
"arabic_lock",
"set",
"get",
"invite",
"all",
"leave_ban",
"setwelcome",
"msg_checks",
"hello",
"isup",
"onservice",
"supergroup",
"banhammer",
"broadcast",
"badword",
"addsudo",
"insta",
"info",
"textphoto",
"lock_bot",
"lock_fwd",
"me",
"plugins",
"image",
"sticker",
"map",
"voice",
"getlink",
"getfile",
"TH3BOSS",
"VIRSON",
"TH3BOSS1",
"TH3BOSS2",
"TH3BOSS3",
"TH3BOSS4",
"TH3BOSS5",
"TH3BOSS6",
"TH3BOSS7",
"newgroup",
"replay",
"help",
"stats",
"lock_media",
"decoration",
"nedme",
"writer",
"@TH3BOSS",
"kickall",
"run",
"delete",
"Serverinfo",
"leave_bot",
"kickme",
},
help_text = "",
help_text_realm = "",
help_text_super = "",
moderation = {
data = "data/moderation.json"
},
sudo_users = {
226861861,
}
}
return _
end
| gpl-2.0 |
prosody-modules/import | mod_listusers/mod_listusers.lua | 34 | 2522 | function module.command(args)
local action = table.remove(args, 1);
if not action then -- Default, list registered users
local data_path = CFG_DATADIR or "data";
if not pcall(require, "luarocks.loader") then
pcall(require, "luarocks.require");
end
local lfs = require "lfs";
function decode(s)
return s:gsub("%%([a-fA-F0-9][a-fA-F0-9])", function (c)
return string.char(tonumber("0x"..c));
end);
end
for host in lfs.dir(data_path) do
local accounts = data_path.."/"..host.."/accounts";
if lfs.attributes(accounts, "mode") == "directory" then
for user in lfs.dir(accounts) do
if user:sub(1,1) ~= "." then
print(decode(user:gsub("%.dat$", "")).."@"..decode(host));
end
end
end
end
elseif action == "--connected" then -- List connected users
local socket = require "socket";
local default_local_interfaces = { };
if socket.tcp6 and config.get("*", "use_ipv6") ~= false then
table.insert(default_local_interfaces, "::1");
end
if config.get("*", "use_ipv4") ~= false then
table.insert(default_local_interfaces, "127.0.0.1");
end
local console_interfaces = config.get("*", "console_interfaces")
or config.get("*", "local_interfaces")
or default_local_interfaces
console_interfaces = type(console_interfaces)~="table"
and {console_interfaces} or console_interfaces;
local console_ports = config.get("*", "console_ports") or 5582
console_ports = type(console_ports) ~= "table" and { console_ports } or console_ports;
local st, conn = pcall(assert,socket.connect(console_interfaces[1], console_ports[1]));
if (not st) then print("Error"..(conn and ": "..conn or "")); return 1; end
local banner = config.get("*", "console_banner");
if (
(not banner) or
(
(type(banner) == "string") and
(banner:match("^| (.+)$"))
)
) then
repeat
local rec_banner = conn:receive()
until
rec_banner == "" or
rec_banner == nil; -- skip banner
end
conn:send("c2s:show()\n");
conn:settimeout(1); -- Only hit in case of failure
repeat local line = conn:receive()
if not line then break; end
local jid = line:match("^| (.+)$");
if jid then
jid = jid:gsub(" %- (%w+%(%d+%))$", "\t%1");
print(jid);
elseif line:match("^| OK:") then
return 0;
end
until false;
end
return 0;
end
| mit |
AresTao/darkstar | scripts/zones/Nashmau/npcs/Pipiroon.lua | 34 | 1224 | -----------------------------------
-- Area: Nashmau
-- NPC: Pipiroon
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Nashmau/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Nashmau/TextIDs");
require("scripts/globals/shop");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,PIPIROON_SHOP_DIALOG);
stock = {0x43A1,1204, -- Grenade
0x43A3,6000, -- Riot Grenade
0x03A0,515, -- Bomb Ash
0x0b39,10000} -- Nashmau Waystone
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
DeinFreund/Zero-K | LuaUI/Widgets/gfx_sun_and_atmosphere.lua | 5 | 5793 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "Sun and Atmosphere Handler.",
desc = "Overrides sun and atmosphere for maps with poor settings",
author = "GoogleFrog",
date = "June 8, 2016",
license = "GNU GPL, v2 or later",
layer = 100000000,
enabled = true -- loaded by default?
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
VFS.Include("LuaRules/Utilities/versionCompare.lua")
local devCompatibility = Spring.Utilities.IsCurrentVersionNewerThan(100, 0)
local OVERRIDE_DIR = LUAUI_DIRNAME .. 'Configs/MapSettingsOverride/'
local MAP_FILE = (Game.mapName or "") .. ".lua"
local OVERRIDE_FILE = OVERRIDE_DIR .. MAP_FILE
local OVERRIDE_CONFIG = VFS.FileExists(OVERRIDE_FILE) and VFS.Include(OVERRIDE_FILE) or false
local initialized = false
local skip = {
["enable_fog"] = true,
["save_map_settings"] = true,
["load_map_settings"] = true,
}
local function GetOptionsTable(pathMatch)
local retTable = {}
for i = 1, #options_order do
local name = options_order[i]
if not skip[name] then
local option = options[name]
if option.path == pathMatch then
retTable[name] = option.value
end
end
end
return retTable
end
local function SaveSettings()
local writeTable = {
sun = GetOptionsTable('Settings/Graphics/Sun and Fog/Sun'),
fog = GetOptionsTable('Settings/Graphics/Sun and Fog/Fog')
}
WG.SaveTable(writeTable, OVERRIDE_DIR, MAP_FILE, nil, {concise = true, prefixReturn = true, endOfFile = true})
end
local function LoadSunAndFogSettings()
if not OVERRIDE_CONFIG then
return
end
local sun = OVERRIDE_CONFIG.sun
if sun then
Spring.SetSunLighting(sun)
for name, value in pairs(sun) do
options[name].value = value
end
end
local fog = OVERRIDE_CONFIG.fog
if fog then
Spring.SetAtmosphere(fog)
for name, value in pairs(fog) do
options[name].value = value
end
end
local water = OVERRIDE_CONFIG.water
if water then
Spring.SetWaterParams(water)
end
end
local function LoadMinimapSettings()
if (not OVERRIDE_CONFIG) or (not OVERRIDE_CONFIG.minimap) then
return
end
local minimap = OVERRIDE_CONFIG.minimap
Spring.Echo("Setting minimap brightness")
Spring.SetSunLighting(minimap)
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function GetOptions()
local fogPath = 'Settings/Graphics/Sun and Fog/Fog'
local sunPath = 'Settings/Graphics/Sun and Fog/Sun'
local options = {}
local options_order = {}
local function AddOption(name, option)
options[name] = option
options_order[#options_order + 1] = name
end
local function AddColorOption(name, humanName, path, ColorFunction)
options[name] = {
name = humanName,
type = 'colors',
value = { 0.8, 0.8, 0.8, 1},
OnChange = function (self)
if initialized then
Spring.Echo("ColorFunction")
Spring.Utilities.TableEcho(self.value, name)
ColorFunction({[name] = self.value})
end
end,
advanced = true,
developmentOnly = true,
path = path
}
options_order[#options_order + 1] = name
end
local function AddNumberOption(name, humanName, path, NumberFunction)
options[name] = {
name = humanName,
type = 'number',
value = 0,
min = -5, max = 5, step = 0.01,
OnChange = function (self)
if initialized then
Spring.Echo("NumberFunction", name, self.value)
NumberFunction({[name] = self.value})
end
end,
advanced = true,
developmentOnly = true,
path = path
}
options_order[#options_order + 1] = name
end
local sunThings = {"ground", "unit"}
local sunColors = {"Ambient", "Diffuse", "Specular"}
for _, thing in ipairs(sunThings) do
for _, color in ipairs(sunColors) do
AddColorOption(thing .. color .. "Color", thing .. " " .. color .. "Color", sunPath, Spring.SetSunLighting)
end
end
AddNumberOption("specularExponent", "Specular Exponent", sunPath, Spring.SetSunLighting)
local fogThings = {"sun", "sky", "cloud", "fog"}
for _, thing in ipairs(fogThings) do
AddColorOption(thing .. "Color", thing .. " Color", fogPath, Spring.SetAtmosphere)
end
AddNumberOption("fogStart", "Fog Start", fogPath, Spring.SetAtmosphere)
AddNumberOption("fogEnd", "Fog End", fogPath, Spring.SetAtmosphere)
AddOption("save_map_settings", {
name = 'Save Settings',
type = 'button',
desc = "Save settings to infolog.",
OnChange = SaveSettings,
advanced = true
})
AddOption("load_map_settings", {
name = 'Load Settings',
type = 'button',
desc = "Load the settings, if the map has a config.",
OnChange = LoadSunAndFogSettings,
advanced = true
})
return options, options_order
end
options_path = 'Settings/Graphics/Sun and Fog'
options, options_order = GetOptions()
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:Initialize()
if not devCompatibility then
widgetHandler:RemoveWidget()
return
end
if Spring.SetSunLighting then
-- See Mantis https://springrts.com/mantis/view.php?id=5280
Spring.Echo("SetSunLighting")
Spring.SetSunLighting({groundSpecularColor = {0,0,0,0}})
end
if Spring.GetGameFrame() < 1 then
LoadMinimapSettings()
end
end
local updates = 0
function widget:Update()
initialized = true
updates = updates + 1
if updates > 4 then
LoadSunAndFogSettings()
widgetHandler:RemoveCallIn("Update")
end
end | gpl-2.0 |
NeoRaider/luci | applications/luci-app-ddns/luasrc/model/cbi/ddns/hints.lua | 1 | 6833 | -- Copyright 2014-2016 Christian Schoenebeck <christian dot schoenebeck at gmail dot com>
-- Licensed to the public under the Apache License 2.0.
local DISP = require "luci.dispatcher"
local SYS = require "luci.sys"
local CTRL = require "luci.controller.ddns" -- this application's controller
local DDNS = require "luci.tools.ddns" -- ddns multiused functions
-- html constants
font_red = [[<font color="red">]]
font_off = [[</font>]]
bold_on = [[<strong>]]
bold_off = [[</strong>]]
-- cbi-map definition -- #######################################################
m = Map("ddns")
m.title = CTRL.app_title_back()
m.description = CTRL.app_description()
m.redirect = DISP.build_url("admin", "services", "ddns")
-- SimpleSection definition -- #################################################
-- show Hints to optimize installation and script usage
s = m:section( SimpleSection,
translate("Hints"),
translate("Below a list of configuration tips for your system to run Dynamic DNS updates without limitations") )
-- ddns_scripts needs to be updated for full functionality
if not CTRL.service_ok() then
local so = s:option(DummyValue, "_update_needed")
so.titleref = DISP.build_url("admin", "system", "packages")
so.rawhtml = true
so.title = font_red .. bold_on ..
translate("Software update required") .. bold_off .. font_off
so.value = translate("The currently installed 'ddns-scripts' package did not support all available settings.") ..
"<br />" ..
translate("Please update to the current version!")
end
-- DDNS Service disabled
if not SYS.init.enabled("ddns") then
local se = s:option(DummyValue, "_not_enabled")
se.titleref = DISP.build_url("admin", "system", "startup")
se.rawhtml = true
se.title = bold_on ..
translate("DDNS Autostart disabled") .. bold_off
se.value = translate("Currently DDNS updates are not started at boot or on interface events." .. "<br />" ..
"This is the default if you run DDNS scripts by yourself (i.e. via cron with force_interval set to '0')" )
end
-- No IPv6 support
if not DDNS.has_ipv6 then
local v6 = s:option(DummyValue, "_no_ipv6")
v6.titleref = 'http://www.openwrt.org" target="_blank'
v6.rawhtml = true
v6.title = bold_on ..
translate("IPv6 not supported") .. bold_off
v6.value = translate("IPv6 is currently not (fully) supported by this system" .. "<br />" ..
"Please follow the instructions on OpenWrt's homepage to enable IPv6 support" .. "<br />" ..
"or update your system to the latest OpenWrt Release")
end
-- No HTTPS support
if not DDNS.has_ssl then
local sl = s:option(DummyValue, "_no_https")
sl.titleref = DISP.build_url("admin", "system", "packages")
sl.rawhtml = true
sl.title = bold_on ..
translate("HTTPS not supported") .. bold_off
sl.value = translate("Neither GNU Wget with SSL nor cURL installed to support updates via HTTPS protocol.") ..
"<br />- " ..
translate("You should install GNU Wget with SSL (prefered) or cURL package.") ..
"<br />- " ..
translate("In some versions cURL/libcurl in OpenWrt is compiled without proxy support.")
end
-- No bind_network
if not DDNS.has_bindnet then
local bn = s:option(DummyValue, "_no_bind_network")
bn.titleref = DISP.build_url("admin", "system", "packages")
bn.rawhtml = true
bn.title = bold_on ..
translate("Binding to a specific network not supported") .. bold_off
bn.value = translate("Neither GNU Wget with SSL nor cURL installed to select a network to use for communication.") ..
"<br />- " ..
translate("You should install GNU Wget with SSL or cURL package.") ..
"<br />- " ..
translate("GNU Wget will use the IP of given network, cURL will use the physical interface.") ..
"<br />- " ..
translate("In some versions cURL/libcurl in OpenWrt is compiled without proxy support.")
end
-- currently only cURL possibly without proxy support
if not DDNS.has_proxy then
local px = s:option(DummyValue, "_no_proxy")
px.titleref = DISP.build_url("admin", "system", "packages")
px.rawhtml = true
px.title = bold_on ..
translate("cURL without Proxy Support") .. bold_off
px.value = translate("cURL is installed, but libcurl was compiled without proxy support.") ..
"<br />- " ..
translate("You should install GNU Wget with SSL or replace libcurl.") ..
"<br />- " ..
translate("In some versions cURL/libcurl in OpenWrt is compiled without proxy support.")
end
-- "Force IP Version not supported"
if not DDNS.has_forceip then
local fi = s:option(DummyValue, "_no_force_ip")
fi.titleref = DISP.build_url("admin", "system", "packages")
fi.rawhtml = true
fi.title = bold_on ..
translate("Force IP Version not supported") .. bold_off
local value = translate("BusyBox's nslookup and Wget do not support to specify " ..
"the IP version to use for communication with DDNS Provider!")
if not (DDNS.has_wgetssl or DDNS.has_curl) then
value = value .. "<br />- " ..
translate("You should install GNU Wget with SSL (prefered) or cURL package.")
end
if not (DDNS.has_bindhost or DDNS.has_hostip) then
value = value .. "<br />- " ..
translate("You should install BIND host or hostip package for DNS requests.")
end
fi.value = value
end
-- "DNS requests via TCP not supported"
if not DDNS.has_bindhost then
local dt = s:option(DummyValue, "_no_dnstcp")
dt.titleref = DISP.build_url("admin", "system", "packages")
dt.rawhtml = true
dt.title = bold_on ..
translate("DNS requests via TCP not supported") .. bold_off
dt.value = translate("BusyBox's nslookup and hostip do not support to specify to use TCP " ..
"instead of default UDP when requesting DNS server!") ..
"<br />- " ..
translate("You should install BIND host package for DNS requests.")
end
-- nslookup compiled with musl produce problems when using
if not DDNS.has_dnsserver then
local ds = s:option(DummyValue, "_no_dnsserver")
ds.titleref = DISP.build_url("admin", "system", "packages")
ds.rawhtml = true
ds.title = bold_on ..
translate("Using specific DNS Server not supported") .. bold_off
ds.value = translate("BusyBox's nslookup in the current compiled version " ..
"does not handle given DNS Servers correctly!") ..
"<br />- " ..
translate("You should install BIND host or hostip package, " ..
"if you need to specify a DNS server to detect your registered IP.")
end
-- certificates installed
if DDNS.has_ssl and not DDNS.has_cacerts then
local ca = s:option(DummyValue, "_no_certs")
ca.titleref = DISP.build_url("admin", "system", "packages")
ca.rawhtml = true
ca.title = bold_on ..
translate("No certificates found") .. bold_off
ca.value = translate("If using secure communication you should verify server certificates!") ..
"<br />- " ..
translate("Install ca-certificates package or needed certificates " ..
"by hand into /etc/ssl/certs default directory")
end
return m
| apache-2.0 |
AresTao/darkstar | scripts/globals/mobskills/Calcifying_Deluge.lua | 25 | 1064 | ---------------------------------------------
-- Calcifying Deluge
--
-- Description: Delivers a threefold ranged attack to targets in an area of effect. Additional effect: Petrification
-- Type: Physical
-- Utsusemi/Blink absorb: 2-3 shadows
-- Range: Unknown
-- Notes: Used only by Medusa.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 1;
local accmod = 1;
local dmgmod = 2;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_PIERCE,MOBPARAM_3_SHADOW);
target:delHP(dmg);
local typeEffect = EFFECT_PETRIFICATION;
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 120);
return dmg;
end;
| gpl-3.0 |
AresTao/darkstar | scripts/globals/items/bowl_of_delicious_puls.lua | 35 | 1320 | -----------------------------------------
-- ID: 4533
-- Item: Bowl of Delicious Puls
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Dexterity -1
-- Vitality 3
-- Health Regen While Healing 5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,4533);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, -1);
target:addMod(MOD_VIT, 3);
target:addMod(MOD_HPHEAL, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, -1);
target:delMod(MOD_VIT, 3);
target:delMod(MOD_HPHEAL, 5);
end;
| gpl-3.0 |
AresTao/darkstar | scripts/zones/Bastok_Mines/npcs/Sieglinde.lua | 24 | 1809 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Sieglinde
-- Alchemy Synthesis Image Support
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local guildMember = isGuildMember(player,1);
local SkillCap = getCraftSkillCap(player,SKILL_SMITHING);
local SkillLevel = player:getSkillLevel(SKILL_SMITHING);
if (guildMember == 1) then
if (player:hasStatusEffect(EFFECT_ALCHEMY_IMAGERY) == false) then
player:startEvent(0x007C,SkillCap,SkillLevel,2,201,player:getGil(),0,4095,0);
else
player:startEvent(0x007C,SkillCap,SkillLevel,2,201,player:getGil(),7009,4095,0);
end
else
player:startEvent(0x007C);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x007C and option == 1) then
player:messageSpecial(ALCHEMY_SUPPORT,0,7,2);
player:addStatusEffect(EFFECT_ALCHEMY_IMAGERY,1,0,120);
end
end; | gpl-3.0 |
AresTao/darkstar | scripts/commands/giveitem.lua | 27 | 1612 | ---------------------------------------------------------------------------------------------------
-- func: @giveitem <player> <itemId> <amount> <aug1> <v1> <aug2> <v2> <aug3> <v3> <aug4> <v4>
-- desc: Gives an item to the target player.
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "siiiiiiiiii"
};
function onTrigger(player, target, itemId, amount, aug0, aug0val, aug1, aug1val, aug2, aug2val, aug3, aug3val)
if (target == nil or itemId == nil) then
player:PrintToPlayer("You must enter a valid player name and item ID.");
return;
end
local targ = GetPlayerByName( target );
if (targ == nil) then
player:PrintToPlayer( string.format( "Player named '%s' not found!", target ) );
return;
end
-- Load needed text ids for players current zone..
local TextIDs = "scripts/zones/" .. targ:getZoneName() .. "/TextIDs";
package.loaded[TextIDs] = nil;
require(TextIDs);
-- Attempt to give the target the item..
if (targ:getFreeSlotsCount() == 0) then
targ:messageSpecial( ITEM_CANNOT_BE_OBTAINED, itemId );
player:PrintToPlayer( string.format( "Player '%s' does not have free space for that item!", target ) );
else
targ:addItem( itemId, amount, aug0, aug0val, aug1, aug1val, aug2, aug2val, aug3, aug3val );
targ:messageSpecial( ITEM_OBTAINED, itemId );
player:PrintToPlayer( string.format( "Gave player Item with ID of '%u' ", itemId ) );
end
end; | gpl-3.0 |
NREL/api-umbrella | src/api-umbrella/proxy/jobs/elasticsearch_setup.lua | 1 | 4778 | local config = require "api-umbrella.proxy.models.file_config"
local elasticsearch = require "api-umbrella.utils.elasticsearch"
local elasticsearch_templates = require "api-umbrella.proxy.elasticsearch_templates_data"
local icu_date = require "icu-date-ffi"
local interval_lock = require "api-umbrella.utils.interval_lock"
local elasticsearch_query = elasticsearch.query
local delay = 3600 -- in seconds
local _M = {}
function _M.wait_for_elasticsearch()
local elasticsearch_alive = false
local wait_time = 0
local sleep_time = 0.5
local max_time = 60
repeat
local res, err = elasticsearch_query("/_cluster/health")
if err then
ngx.log(ngx.NOTICE, "failed to fetch cluster health from elasticsearch (this is expected if elasticsearch is starting up at the same time): ", err)
elseif res.body_json and res.body_json["status"] == "yellow" or res.body_json["status"] == "green" then
elasticsearch_alive = true
end
if not elasticsearch_alive then
ngx.sleep(sleep_time)
wait_time = wait_time + sleep_time
end
until elasticsearch_alive or wait_time > max_time
if elasticsearch_alive then
return true, nil
else
return false, "elasticsearch was not ready within " .. max_time .."s"
end
end
function _M.create_templates()
-- Template creation only needs to be run once on startup or reload.
local created = ngx.shared.active_config:get("elasticsearch_templates_created")
if created then return end
if elasticsearch_templates then
for _, template in ipairs(elasticsearch_templates) do
local _, err = elasticsearch_query("/_template/" .. template["id"], {
method = "PUT",
body = template["template"],
})
if err then
ngx.log(ngx.ERR, "failed to update elasticsearch template: ", err)
end
end
end
local set_ok, set_err = ngx.shared.active_config:safe_set("elasticsearch_templates_created", true)
if not set_ok then
ngx.log(ngx.ERR, "failed to set 'elasticsearch_templates_created' in 'active_config' shared dict: ", set_err)
end
end
function _M.create_aliases()
local date = icu_date.new({ zone_id = "UTC" })
local today = date:format(elasticsearch.partition_date_format)
date:add(icu_date.fields.DATE, 1)
local tomorrow = date:format(elasticsearch.partition_date_format)
local aliases = {
{
alias = config["elasticsearch"]["index_name_prefix"] .. "-logs-" .. today,
index = config["elasticsearch"]["index_name_prefix"] .. "-logs-v" .. config["elasticsearch"]["template_version"] .. "-" .. today,
},
{
alias = config["elasticsearch"]["index_name_prefix"] .. "-logs-write-" .. today,
index = config["elasticsearch"]["index_name_prefix"] .. "-logs-v" .. config["elasticsearch"]["template_version"] .. "-" .. today,
},
}
-- Create the aliases needed for the next day if we're at the end of the
-- month.
if tomorrow ~= today then
table.insert(aliases, {
alias = config["elasticsearch"]["index_name_prefix"] .. "-logs-" .. tomorrow,
index = config["elasticsearch"]["index_name_prefix"] .. "-logs-v" .. config["elasticsearch"]["template_version"] .. "-" .. tomorrow,
})
table.insert(aliases, {
alias = config["elasticsearch"]["index_name_prefix"] .. "-logs-write-" .. tomorrow,
index = config["elasticsearch"]["index_name_prefix"] .. "-logs-v" .. config["elasticsearch"]["template_version"] .. "-" .. tomorrow,
})
end
for _, alias in ipairs(aliases) do
-- Only create aliases if they don't already exist.
local exists_res, exists_err = elasticsearch_query("/_alias/" .. alias["alias"], {
method = "HEAD",
})
if exists_err then
ngx.log(ngx.ERR, "failed to check elasticsearch index alias: ", exists_err)
elseif exists_res.status == 404 then
-- Make sure the index exists.
local _, create_err = elasticsearch_query("/" .. alias["index"], {
method = "PUT",
})
if create_err then
ngx.log(ngx.ERR, "failed to create elasticsearch index: ", create_err)
end
-- Create the alias for the index.
local _, alias_err = elasticsearch_query("/" .. alias["index"] .. "/_alias/" .. alias["alias"], {
method = "PUT",
})
if alias_err then
ngx.log(ngx.ERR, "failed to create elasticsearch index alias: ", alias_err)
end
end
end
end
local function setup()
local _, err = _M.wait_for_elasticsearch()
if not err then
_M.create_templates()
_M.create_aliases()
else
ngx.log(ngx.ERR, "timed out waiting for eleasticsearch before setup, rerunning...")
ngx.sleep(5)
setup()
end
end
function _M.spawn()
interval_lock.repeat_with_mutex('elasticsearch_index_setup', delay, setup)
end
return _M
| mit |
DeinFreund/Zero-K | LuaUI/Widgets/gui_chili_vote.lua | 1 | 8891 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "Chili Vote Display",
desc = "GUI for votes",
author = "KingRaptor",
date = "May 04, 2008",
license = "GNU GPL, v2 or later",
layer = -9,
enabled = true -- loaded by default?
}
end
--//version +0.3;
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local Chili
local Button
local Label
local Window
local Panel
local TextBox
local Image
local Progressbar
local Control
local Font
-- elements
local window, panel_main, label_title
local panel_vote, label_vote, button_vote, progress_vote = {}, {}, {}, {}
local button_end, button_end_image
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local voteCount, voteMax = {}, {}
local pollActive = false
local hidePoll = false
local votingForceStart = false
local string_success = "END:SUCCESS"
local string_fail = "END:FAILED"
local string_vote = {"!y=", "!n="}
local string_titleStart = "Poll: "
local string_endvote = " poll cancelled"
local string_titleEnd = "?"
local string_noVote = "There is no poll going on, start some first"
local string_votemove = "Do you want to join"
local springieName = Spring.GetModOptions().springiename or ''
--local voteAntiSpam = false
local VOTE_SPAM_DELAY = 1 --seconds
--[[
local index_votesHave = 14
local index_checkDoubleDigits = 17
local index_votesNeeded = 18
local index_voteTitle = 15
]]--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function GetVotes(line)
for i=1, 2 do
local index_init = line:find(string_vote[i])
local index_votesHave = line:find("%d[%d/]", index_init)
local index_votesHaveEnd = line:find("/", index_votesHave) - 1
local index_votesNeeded = index_votesHaveEnd + 2
local index_votesNeededEnd = ( line:find("[,]", index_votesNeeded) or line:find("\]", index_votesNeeded) ) - 1
local numVotes = tonumber(line:sub(index_votesHave, index_votesHaveEnd))
local maxVotes = tonumber(line:sub(index_votesNeeded, index_votesNeededEnd))
voteCount[i] = numVotes
voteMax[i] = maxVotes
progress_vote[i]:SetCaption(voteCount[i]..'/'..voteMax[i])
progress_vote[i]:SetValue(voteCount[i]/voteMax[i])
end
end
local lastClickTimestamp = 0
local function CheckForVoteSpam (currentTime) --// function return "true" if not a voteSpam
local elapsedTimeFromLastClick = currentTime - lastClickTimestamp
if elapsedTimeFromLastClick < VOTE_SPAM_DELAY then
return false
else
lastClickTimestamp= currentTime
return true
end
end
local function RemoveWindow()
pollActive = false
screen0:RemoveChild(window)
for i=1,2 do
voteCount[i] = 0
voteMax[i] = 1 -- protection against div0
--progress_vote[i]:SetCaption('?/?')
progress_vote[i]:SetValue(0)
button_vote[i]:Show()
end
end
function widget:AddConsoleMessage(msg)
local line = msg.text
if votingForceStart and line:sub(1,7) == "GameID:" then
RemoveWindow()
votingForceStart = false
end
if msg.msgtype ~= "autohost" then -- no spoofing messages
return false
end
if line:find(string_success) or line:find(string_fail) or line:find(string_endvote) or line:find(string_noVote) or ((not Spring.GetSpectatingState()) and line:find(string_votemove)) then --terminate existing vote
RemoveWindow()
votingForceStart = false
elseif line:find(string_titleStart) and line:find(string_vote[1]) and line:find(string_vote[2]) then --start new vote
--if pollActive then --//close previous windows in case Springie started a new vote without terminating the last one.
-- RemoveWindow()
-- votingForceStart = false
--end
if not pollActive then -- new poll was called
pollActive = true
hidePoll = false
screen0:AddChild(window)
end
if not hidePoll then -- only draw when X button was not pressed
local indexStart = select(2, line:find(string_titleStart))
local indexEnd = line:find(string_titleEnd)
if not (indexStart and indexEnd) then
-- malformed poll line
Spring.Log(widget:GetInfo().name, LOG.ERROR, "malformed poll notification text")
return
end
local title = line:sub(indexStart, indexEnd - 1)
if title:find("Resign team ") then
local allyTeamID = string.match(title, '%d+') - 1
local teamName = Spring.GetGameRulesParam("allyteam_long_name_" .. allyTeamID)
if allyTeamID ~= Spring.GetLocalAllyTeamID() or Spring.GetSpectatingState() then
title = teamName .. " voting on resign..."
button_vote[1]:Hide()
button_vote[2]:Hide()
else
title = "Vote: resign?"
end
else
title = "Vote: " .. title .. "?"
votingForceStart = ((title:find("force game"))~=nil)
end
label_title:SetCaption(title)
--elseif line:find(string_vote1) or line:find(string_vote2) then --apply a vote
GetVotes(line)
end
end
return false
end
--[[
local timer = 0
function widget:Update(dt)
if not voteAntiSpam then
return
end
timer = timer + dt
if timer < VOTE_SPAM_DELAY then
return
end
voteAntiSpam = false
timer = 0
end
--]]
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:Initialize()
-- setup Chili
Chili = WG.Chili
Button = Chili.Button
Label = Chili.Label
Colorbars = Chili.Colorbars
Window = Chili.Window
Panel = Chili.Panel
Image = Chili.Image
Progressbar = Chili.Progressbar
Control = Chili.Control
screen0 = Chili.Screen0
--create main Chili elements
local screenWidth,screenHeight = Spring.GetWindowGeometry()
local height = tostring(math.floor(screenWidth/screenHeight*0.35*0.35*100)) .. "%"
local y = tostring(math.floor((1-screenWidth/screenHeight*0.35*0.35)*100)) .. "%"
local labelHeight = 24
local fontSize = 16
window = Window:New{
--parent = screen0,
name = 'votes';
color = {0, 0, 0, 0},
width = 300;
height = 120;
right = 2;
y = "45%";
dockable = true;
dockableSavePositionOnly = true,
draggable = true,
resizable = false,
tweakDraggable = true,
tweakResizable = true,
minWidth = MIN_WIDTH,
minHeight = MIN_HEIGHT,
padding = {0, 0, 0, 0},
--itemMargin = {0, 0, 0, 0},
}
panel_main = Panel:New{
parent = window,
resizeItems = true;
orientation = "vertical";
height = "100%";
width = "100%";
padding = {0, 0, 0, 0},
itemMargin = {0, 0, 0, 0},
backgroundColor = {0, 0, 0, 0},
}
label_title = Label:New{
parent = panel_main,
autosize=false;
align="center";
valign="top";
caption = '';
height = 16,
width = "100%";
}
for i=1,2 do
panel_vote[i] = Panel:New{
parent = panel_main,
resizeItems = true;
orientation = "horizontal";
y = (40*(i-1))+15 ..'%',
height = "40%";
width = "100%";
padding = {0, 0, 0, 0},
itemMargin = {0, 0, 0, 0},
backgroundColor = {0, 0, 0, 0},
}
--[[
label_vote[i] = Label:New{
parent = panel_vote[i],
autosize=false;
align="left";
valign="center";
caption = (i==1) and 'Yes' or 'No',
height = 16,
width = "100%";
}
]]--
progress_vote[i] = Progressbar:New{
parent = panel_vote[i],
x = "0%",
width = "80%";
height = "100%",
max = 1;
caption = "?/?";
color = (i == 1 and {0.2,0.9,0.3,1}) or {0.9,0.15,0.2,1};
}
button_vote[i] = Button:New{
parent = panel_vote[i],
x = "80%",
width = "20%",
height = "100%",
classname = "overlay_button",
caption = (i==1) and 'Yes' or 'No',
OnClick = { function ()
--if voteAntiSpam then return end
--voteAntiSpam = true
local notSpam = CheckForVoteSpam (os.clock())
if notSpam then
Spring.SendCommands({'say !vote '..i})
end
end},
padding = {1,1,1,1},
--keepAspect = true,
}
progress_vote[i]:SetValue(0)
voteCount[i] = 0
voteMax[i] = 1 -- protection against div0
end
button_end = Button:New {
width = 20,
height = 20,
y = 0,
right = 0,
classname = "overlay_button_tiny",
parent=window;
padding = {0, 0, 0,0},
margin = {0, 0, 0, 0},
caption="";
tooltip = "Hide this vote";
OnClick = {function()
screen0:RemoveChild(window)
hidePoll = true
end}
}
button_end_image = Image:New {
width = 16,
height = 16,
x = 2,
y = 2,
keepAspect = false,
file = "LuaUI/Images/closex_16.png";
parent = button_end;
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| gpl-2.0 |
AresTao/darkstar | scripts/zones/Windurst_Waters_[S]/npcs/Mhoti_Pyiahrs.lua | 38 | 1045 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Mhoti Pyiahrs
-- Type: Allegiance
-- @zone: 94
-- @pos 6.356 -2 26.677
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0002);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
DeinFreund/Zero-K | LuaUI/Widgets/gfx_color_blindness_correction.lua | 5 | 4004 | function widget:GetInfo()
return {
name = "Color Blindness Correction",
version = 1.0,
desc = "Corrects a screen colors for color-blinded people",
author = "ivand",
date = "2017",
license = "GPL",
layer = math.huge, --wanna draw last
enabled = true
}
end
options_path = "Settings/Accessibility"
options_order = { "cbcType", "cbcMethod", "cbcOnlySim" }
options = {
cbcType = {
name = "Color Blindness Type",
type = "radioButton",
value = "none",
items = {
{key = "none", name = "None"},
{key = "protanopia", name="Protanopia - missing RED"},
{key = "deuteranopia", name="Deuteranopia - missing GREEN"},
{key = "tritanopia", name="Tritanopia - missing BLUE"},
},
simpleMode = true,
everyMode = true,
},
cbcMethod = {
name = "Color Blindness Correction Method",
type = "number",
value = 2,
min = 1, max = 2, step = 1,
simpleMode = true,
everyMode = true,
},
cbcOnlySim = {
name = 'Only simulate color blindness',
type = 'bool',
value = false,
advanced = true,
},
}
---------------------------------------------------------------------------
local cbcShader = nil
local fragment_body = nil
local vsx, vsy = nil
local screenTex = nil
---------------------------------------------------------------------------
local function CleanShader()
if (gl.DeleteShader and cbcShader) then
gl.DeleteShader(cbcShader)
end
cbcShader = nil
end
local function CreateShader()
local fragment_complete =
"#define "..string.upper(options.cbcType.value).."\n" ..
"#define METHOD"..tostring(options.cbcMethod.value).."\n" ..
((options.cbcOnlySim.value and "#define CORRECT") or "").."\n" ..
fragment_body
cbcShader = gl.CreateShader({
fragment = fragment_complete,
uniformInt = {screenTex = 0}
})
if cbcShader == nil then
Spring.Log(widget:GetInfo().name, LOG.ERROR, "cbcShader: shader error: "..gl.GetShaderLog())
end
end
local function SetupCBCOptions()
CleanShader()
if options.cbcType.value ~= "none" then
CreateShader()
end
end
---------------------------------------------------------------------------
function widget:Initialize()
if (gl.CreateShader == nil) then
Spring.Log(widget:GetInfo().name, LOG.ERROR, "removing widget, no shader support")
widgetHandler:RemoveWidget()
return
end
fragment_body = VFS.LoadFile("LuaUI\\Widgets\\Shaders\\cbc.fs", VFS.ZIP)
if (fragment_body == nil) then
Spring.Log(widget:GetInfo().name, LOG.ERROR, "removing widget, no shader code found")
widgetHandler:RemoveWidget()
return
end
options.cbcType.OnChange = SetupCBCOptions
options.cbcMethod.OnChange = SetupCBCOptions
options.cbcOnlySim.OnChange = SetupCBCOptions
if (widgetHandler.DrawScreenPost ~= nil) then
widgetHandler:RemoveCallIn("DrawScreenEffects")
end
SetupCBCOptions()
widget:ViewResize()
end
local function CleanTextures()
if screenTex then
gl.DeleteTexture(screenTex)
screenTex = nil
end
end
local function CreateTextures()
screenTex = gl.CreateTexture(vsx, vsy, {
--TODO figure out what it means
fbo = true, min_filter = GL.LINEAR, mag_filter = GL.LINEAR,
wrap_s = GL.CLAMP, wrap_t = GL.CLAMP,
})
if screenTex == nil then
Spring.Log(widget:GetInfo().name, LOG.ERROR, "screenTex texture error")
end
end
function widget:ViewResize()
vsx, vsy = gl.GetViewSizes()
CleanTextures()
CreateTextures()
end
local function PerformDraw()
if cbcShader then
gl.CopyToTexture(screenTex, 0, 0, 0, 0, vsx, vsy)
gl.Texture(0, screenTex)
gl.UseShader(cbcShader)
gl.TexRect(0,vsy,vsx,0)
gl.Texture(0, false)
gl.UseShader(0)
end
end
-- Adds partial compatibility with spring versions, which don't support "DrawScreenPost", remove this later.
-- This call is removed in widget:Initialize() if DrawScreenPost is present
function widget:DrawScreenEffects(vsx, vsy)
PerformDraw()
end
function widget:DrawScreenPost(vsx, vsy)
PerformDraw()
end
function widget:Shutdown()
CleanShader()
CleanTextures()
fragment_body = nil
end | gpl-2.0 |
Jmainguy/docker_images | prosody/prosody/lib/prosody/modules/mod_time.lua | 4 | 1336 | -- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local st = require "util.stanza";
local datetime = require "util.datetime".datetime;
local legacy = require "util.datetime".legacy;
-- XEP-0202: Entity Time
module:add_feature("urn:xmpp:time");
local function time_handler(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "get" then
origin.send(st.reply(stanza):tag("time", {xmlns="urn:xmpp:time"})
:tag("tzo"):text("+00:00"):up() -- TODO get the timezone in a platform independent fashion
:tag("utc"):text(datetime()));
return true;
end
end
module:hook("iq/bare/urn:xmpp:time:time", time_handler);
module:hook("iq/host/urn:xmpp:time:time", time_handler);
-- XEP-0090: Entity Time (deprecated)
module:add_feature("jabber:iq:time");
local function legacy_time_handler(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "get" then
origin.send(st.reply(stanza):tag("query", {xmlns="jabber:iq:time"})
:tag("utc"):text(legacy()));
return true;
end
end
module:hook("iq/bare/jabber:iq:time:query", legacy_time_handler);
module:hook("iq/host/jabber:iq:time:query", legacy_time_handler);
| gpl-2.0 |
DeinFreund/Zero-K | LuaUI/Widgets/gui_persistent_build_height.lua | 1 | 12525 | function widget:GetInfo()
return {
name = "Persistent Build Height",
desc = "Persistent UI for setting Skydust height.",
author = "Google Frog",
version = "v1",
date = "7th June, 2016",
license = "GNU GPL, v2 or later",
layer = math.huge,
enabled = true,
handler = true,
}
end
--------------------------------------------------------------------------------
-- Speedups
--------------------------------------------------------------------------------
local spGetActiveCommand = Spring.GetActiveCommand
local spSetActiveCommand = Spring.SetActiveCommand
local spGetMouseState = Spring.GetMouseState
local spTraceScreenRay = Spring.TraceScreenRay
local spGetGroundHeight = Spring.GetGroundHeight
local spGetSelectedUnits = Spring.GetSelectedUnits
local spGetModKeyState = Spring.GetModKeyState
local GL_LINE_STRIP = GL.LINE_STRIP
local GL_LINES = GL.LINES
local glVertex = gl.Vertex
local glLineWidth = gl.LineWidth
local glColor = gl.Color
local glBeginEnd = gl.BeginEnd
local floor = math.floor
local ceil = math.ceil
---------------------------------
-- Epic Menu
---------------------------------
options_path = 'Settings/Interface/Building Placement'
options_order = { 'enterSetHeightWithB', 'altMouseToSetHeight'}
options = {
enterSetHeightWithB = {
name = "Toggle set height with B",
type = "bool",
value = true,
noHotkey = true,
desc = "Press B while placing a structure to set the height of the structure. Keys C and V increase or decrease height."
},
altMouseToSetHeight = {
name = "Alt mouse wheel to set height",
type = "bool",
value = true,
noHotkey = true,
desc = "Hold Alt and mouse wheel to set height."
},
}
--------------------------------------------------------------------------------
-- Config
--------------------------------------------------------------------------------
include("keysym.h.lua")
VFS.Include("LuaRules/Configs/customcmds.h.lua")
local mexDefID = UnitDefNames["staticmex"].id
local INCREMENT_SIZE = 20
local heightIncrease = KEYSYMS.C
local heightDecrease = KEYSYMS.V
local toggleHeight = KEYSYMS.B
-- Colours used during height choosing for level and raise
local negVolume = {1, 0, 0, 0.1} -- negative volume
local posVolume = {0, 1, 0, 0.1} -- posisive volume
local groundGridColor = {0.3, 0.2, 1, 0.8} -- grid representing new ground height
-- colour of lasso during drawing
local lassoColor = {0.2, 1.0, 0.2, 0.8}
local edgeColor = {0.2, 1.0, 0.2, 0.4}
local SQUARE_BUILDABLE = 2 -- magic constant returned by TestBuildOrder
--------------------------------------------------------------------------------
-- Local Vars
--------------------------------------------------------------------------------
local defaultBuildHeight = 40
local buildHeight = {}
local buildingPlacementID = false
local buildingPlacementHeight = 0
local toggleEnabled = false
local floating = false
local pointX = 0
local pointY = 0
local pointZ = 0
local sizeX = 0
local sizeZ = 0
local oddX = 0
local oddZ = 0
local facing = 0
local corner = {
[1] = {[1] = 0, [-1] = 0},
[-1] = {[1] = 0, [-1] = 0},
}
--------------------------------------------------------------------------------
-- Height Handling
--------------------------------------------------------------------------------
local function CheckEnabled()
if options.enterSetHeightWithB.value then
return toggleEnabled
end
return true
end
local function SendCommand()
local constructor = spGetSelectedUnits()
if #constructor == 0 then
return
end
-- Snap mex to metal spots
if buildingPlacementID == mexDefID and WG.GetClosestMetalSpot then
local pos = WG.GetClosestMetalSpot(pointX, pointZ)
if pos then
pointX, pointZ = pos.x, pos.z
local height = spGetGroundHeight(pointX, pointZ)
if height < 0 then
height = 0
if buildingPlacementHeight == 0 then
pointY = 2
else
pointY = height + buildingPlacementHeight
end
else
pointY = height + buildingPlacementHeight
end
end
end
-- Setup parameters for terraform command
local team = Spring.GetUnitTeam(constructor[1]) or Spring.GetMyTeamID()
local commandTag = WG.Terraform_GetNextTag()
local params = {}
params[1] = 1 -- terraform type = level
params[2] = team
params[3] = pointX
params[4] = pointZ
params[5] = commandTag
params[6] = 1 -- Loop parameter
params[7] = pointY -- Height parameter of terraform
params[8] = 5 -- Five points in the terraform
params[9] = #constructor -- Number of constructors with the command
params[10] = 0 -- Ordinary volume selection
-- Rectangle of terraform
params[11] = pointX + sizeX
params[12] = pointZ + sizeZ
params[13] = pointX + sizeX
params[14] = pointZ - sizeZ
params[15] = pointX - sizeX
params[16] = pointZ - sizeZ
params[17] = pointX - sizeX
params[18] = pointZ + sizeZ
params[19] = pointX + sizeX
params[20] = pointZ + sizeZ
-- Set constructors
local i = 21
for j = 1, #constructor do
params[i] = constructor[j]
i = i + 1
end
local a,c,m,s = spGetModKeyState()
Spring.GiveOrderToUnit(constructor[1], CMD_TERRAFORM_INTERNAL, params, 0)
-- if global build command is active, check if it wants to handle the orders before giving units any commands.
if not WG.GlobalBuildCommand or not WG.GlobalBuildCommand.CommandNotifyRaiseAndBuild(constructor, -buildingPlacementID, pointX, pointY, pointZ, facing, s) then
if not s then
spSetActiveCommand(-1)
end
local cmdOpts = {coded = 0}
if s then
cmdOpts.shift = true
cmdOpts.coded = cmdOpts.coded + CMD.OPT_SHIFT
end
if m then
cmdOpts.meta = true
cmdOpts.coded = cmdOpts.coded + CMD.OPT_META
end
local height = Spring.GetGroundHeight(pointX, pointZ)
WG.CommandInsert(CMD_LEVEL, {pointX, height, pointZ, commandTag}, cmdOpts)
WG.CommandInsert(-buildingPlacementID, {pointX, height, pointZ, facing}, cmdOpts, 1)
end
end
function widget:KeyPress(key, mods)
local _,activeCommand = spGetActiveCommand()
if (not activeCommand) or (activeCommand >= 0) then
return false
end
if key == toggleHeight and options.enterSetHeightWithB.value then
toggleEnabled = not toggleEnabled
return true
end
if ((key ~= heightIncrease) and (key ~= heightDecrease)) then
return false
end
-- Return true during structure placement to block C and V for integral menu.
if (not buildingPlacementID) then
return true
end
if key == heightIncrease then
buildingPlacementHeight = (buildingPlacementHeight or 0) + INCREMENT_SIZE
elseif key == heightDecrease then
buildingPlacementHeight = (buildingPlacementHeight or 0) - INCREMENT_SIZE
end
buildHeight[buildingPlacementID] = buildingPlacementHeight
widgetHandler:UpdateWidgetCallIn("DrawWorld", self)
return true
end
function widget:Update(dt)
if not CheckEnabled() then
buildingPlacementID = false
return
end
local _,activeCommand = spGetActiveCommand()
if (not activeCommand) or (activeCommand >= 0) then
if buildingPlacementID then
buildingPlacementID = false
toggleEnabled = false
end
return
end
if buildingPlacementID ~= -activeCommand then
buildingPlacementID = -activeCommand
buildingPlacementHeight = (buildHeight[buildingPlacementID] or defaultBuildHeight)
facing = Spring.GetBuildFacing()
local offFacing = (facing == 1 or facing == 3)
local ud = UnitDefs[buildingPlacementID]
local footX = ud.xsize/2
local footZ = ud.zsize/2
if offFacing then
footX, footZ = footZ, footX
end
oddX = (footX%2)*8
oddZ = (footZ%2)*8
sizeX = footX * 8 - 0.1
sizeZ = footZ * 8 - 0.1
widgetHandler:UpdateWidgetCallIn("DrawWorld", self)
end
local ud = buildingPlacementID and UnitDefs[buildingPlacementID]
if not ud then
return
end
local mx,my = spGetMouseState()
-- Should not ignore water if the structure can float. See https://springrts.com/mantis/view.php?id=5390
local _, pos = spTraceScreenRay(mx, my, true, false, false, not Spring.Utilities.BlueprintFloat(ud))
if pos then
pointX = floor((pos[1] + 8 - oddX)/16)*16 + oddX
pointZ = floor((pos[3] + 8 - oddZ)/16)*16 + oddZ
local height = spGetGroundHeight(pointX, pointZ)
if ud.floatOnWater and height < 0 then
if buildingPlacementHeight == 0 and not floating then
-- Callin may have been removed
widgetHandler:UpdateWidgetCallIn("DrawWorld", self)
end
height = 0
floating = true
if buildingPlacementHeight == 0 then
pointY = 2
else
pointY = height + buildingPlacementHeight
end
else
floating = false
pointY = height + buildingPlacementHeight
end
for i = -1, 1, 2 do
for j = -1, 1, 2 do
corner[i][j] = spGetGroundHeight(pointX + sizeX*i, pointZ + sizeZ*j)
end
end
else
pointX = false
end
end
function widget:MouseWheel(up, value)
if not options.altMouseToSetHeight.value then
return
end
local _,activeCommand = spGetActiveCommand()
if (not activeCommand) or (activeCommand > 0) then
return false
end
local alt, ctrl, meta, shift = Spring.GetModKeyState()
if not alt then
return
end
toggleEnabled = true
buildingPlacementHeight = (buildingPlacementHeight or 0) + INCREMENT_SIZE*value
buildHeight[buildingPlacementID] = buildingPlacementHeight
widgetHandler:UpdateWidgetCallIn("DrawWorld", self)
return true
end
function widget:MousePress(mx, my, button)
if button == 2 and options.altMouseToSetHeight.value then
local alt, ctrl, meta, shift = Spring.GetModKeyState()
if not alt then
return
end
local _,activeCommand = spGetActiveCommand()
if (not activeCommand) or (activeCommand > 0) then
return
end
toggleEnabled = not toggleEnabled
if toggleEnabled then
widgetHandler:UpdateWidgetCallIn("DrawWorld", self)
else
buildingPlacementID = false
end
return true
end
if not buildingPlacementID then
return
end
local unbuildableTerrain = (Spring.TestBuildOrder(buildingPlacementID, pointX, 0, pointZ, Spring.GetBuildFacing()) ~= SQUARE_BUILDABLE)
if not ((floating or buildingPlacementHeight ~= 0 or (buildingPlacementHeight == 0 and unbuildableTerrain)) and button == 1 and pointX) then
return
end
SendCommand()
return true
end
--------------------------------------------------------------------------------
-- Drawing
--------------------------------------------------------------------------------
local function DrawRectangleLine()
glVertex(pointX + sizeX, pointY, pointZ + sizeZ)
glVertex(pointX + sizeX, pointY, pointZ - sizeZ)
glVertex(pointX - sizeX, pointY, pointZ - sizeZ)
glVertex(pointX - sizeX, pointY, pointZ + sizeZ)
glVertex(pointX + sizeX, pointY, pointZ + sizeZ)
end
local function DrawRectangleCorners()
glVertex(pointX + sizeX, pointY, pointZ + sizeZ)
glVertex(pointX + sizeX, corner[1][1], pointZ + sizeZ)
glVertex(pointX + sizeX, pointY, pointZ - sizeZ)
glVertex(pointX + sizeX, corner[1][-1], pointZ - sizeZ)
glVertex(pointX - sizeX, pointY, pointZ - sizeZ)
glVertex(pointX - sizeX, corner[-1][-1], pointZ - sizeZ)
glVertex(pointX - sizeX, pointY, pointZ + sizeZ)
glVertex(pointX - sizeX, corner[-1][1], pointZ + sizeZ)
end
function widget:DrawWorld()
if not buildingPlacementID then
widgetHandler:RemoveWidgetCallIn("DrawWorld", self)
return
end
if pointX then
--// draw the lines
glLineWidth(2.0)
glColor(edgeColor)
glBeginEnd(GL_LINES, DrawRectangleCorners)
glLineWidth(3.0)
glColor(lassoColor)
glBeginEnd(GL_LINE_STRIP, DrawRectangleLine)
glColor(1, 1, 1, 1)
glLineWidth(1.0)
end
end
function widget:Shutdown()
if (volumeDraw) then
gl.DeleteList(volumeDraw); volumeDraw=nil
gl.DeleteList(mouseGridDraw); mouseGridDraw=nil
end
if (groundGridDraw) then
gl.DeleteList(groundGridDraw); groundGridDraw=nil
end
end
--------------------------------------------------------------------------------
-- Persistent Config
--------------------------------------------------------------------------------
function widget:GetConfigData()
local heightByName = {}
for unitDefID, spacing in pairs(buildHeight) do
local name = UnitDefs[unitDefID] and UnitDefs[unitDefID].name
if name then
heightByName[name] = spacing
end
end
return {buildHeight = heightByName}
end
function widget:SetConfigData(data)
local heightByName = data.buildHeight or {}
for name, spacing in pairs(heightByName) do
local unitDefID = UnitDefNames[name] and UnitDefNames[name].id
if unitDefID then
buildHeight[unitDefID] = spacing
end
end
end
| gpl-2.0 |
AresTao/darkstar | scripts/globals/weaponskills/atonement.lua | 18 | 4766 | -----------------------------------
-- Atonement
-- TODO: This needs to be reworked, as this weapon skill does damage based on current enmity, not based on stat modifiers. http://wiki.ffxiclopedia.org/wiki/Atonement http://www.bg-wiki.com/bg/Atonement
-- Sword weapon skill
-- Skill Level: N/A
-- Delivers a Twofold attack. Damage varies with TP. Conqueror: Aftermath effect varies with TP.
-- Available only after completing the Unlocking a Myth (Paladin) quest.
-- Aligned with the Aqua Gorget, Flame Gorget & Light Gorget.
-- Aligned with the Aqua Belt, Flame Belt & Light Belt.
-- Element: None
-- Modifiers: STR:40% VIT:50%
-- 100%TP 200%TP 300%TP
-- 1.00 1.25 1.50
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 2;
params.ftp100 = 1; params.ftp200 = 1.25; params.ftp300 = 1.5;
params.str_wsc = 0.4; params.dex_wsc = 0.0; params.vit_wsc = 0.5; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 1; params.ftp200 = 1.5; params.ftp300 = 2.0;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
if ((player:getEquipID(SLOT_MAIN) == 18997) and (player:getMainJob() == JOB_PLD)) then
if (damage > 0) then
-- AFTERMATH LEVEL 1
if ((player:getTP() >= 100) and (player:getTP() <= 110)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 10, 0, 180, 0, 1);
elseif ((player:getTP() >= 111) and (player:getTP() <= 120)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 11, 0, 180, 0, 1);
elseif ((player:getTP() >= 121) and (player:getTP() <= 130)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 12, 0, 180, 0, 1);
elseif ((player:getTP() >= 131) and (player:getTP() <= 140)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 13, 0, 180, 0, 1);
elseif ((player:getTP() >= 141) and (player:getTP() <= 150)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 14, 0, 180, 0, 1);
elseif ((player:getTP() >= 151) and (player:getTP() <= 160)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 15, 0, 180, 0, 1);
elseif ((player:getTP() >= 161) and (player:getTP() <= 170)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 16, 0, 180, 0, 1);
elseif ((player:getTP() >= 171) and (player:getTP() <= 180)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 17, 0, 180, 0, 1);
elseif ((player:getTP() >= 181) and (player:getTP() <= 190)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 18, 0, 180, 0, 1);
elseif ((player:getTP() >= 191) and (player:getTP() <= 199)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 19, 0, 180, 0, 1);
-- AFTERMATH LEVEL 2
elseif ((player:getTP() >= 200) and (player:getTP() <= 210)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 24, 0, 180, 0, 1);
elseif ((player:getTP() >= 211) and (player:getTP() <= 219)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 28, 0, 180, 0, 1);
elseif ((player:getTP() >= 221) and (player:getTP() <= 229)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 32, 0, 180, 0, 1);
elseif ((player:getTP() >= 231) and (player:getTP() <= 239)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 36, 0, 180, 0, 1);
elseif ((player:getTP() >= 241) and (player:getTP() <= 249)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 40, 0, 180, 0, 1);
elseif ((player:getTP() >= 251) and (player:getTP() <= 259)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 44, 0, 180, 0, 1);
elseif ((player:getTP() >= 261) and (player:getTP() <= 269)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 48, 0, 180, 0, 1);
elseif ((player:getTP() >= 271) and (player:getTP() <= 279)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 52, 0, 180, 0, 1);
elseif ((player:getTP() >= 281) and (player:getTP() <= 289)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 56, 0, 180, 0, 1);
elseif ((player:getTP() >= 291) and (player:getTP() <= 299)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 59, 0, 180, 0, 1);
-- AFTERMATH LEVEL 3
elseif ((player:getTP() == 300)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV3, 45, 0, 120, 0, 1);
end
end
end
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
thess/OpenWrt-luci | applications/luci-app-olsr/luasrc/model/cbi/olsr/olsrd6.lua | 68 | 16296 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2010 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
require("luci.tools.webadmin")
local fs = require "nixio.fs"
local util = require "luci.util"
local ip = require "luci.ip"
local has_ipip = fs.glob("/etc/modules.d/[0-9]*-ipip")()
m = Map("olsrd6", translate("OLSR Daemon"),
translate("The OLSR daemon is an implementation of the Optimized Link State Routing protocol. "..
"As such it allows mesh routing for any network equipment. "..
"It runs on any wifi card that supports ad-hoc mode and of course on any ethernet device. "..
"Visit <a href='http://www.olsr.org'>olsrd.org</a> for help and documentation."))
function m.on_parse()
local has_defaults = false
m.uci:foreach("olsrd6", "InterfaceDefaults",
function(s)
has_defaults = true
return false
end)
if not has_defaults then
m.uci:section("olsrd6", "InterfaceDefaults")
end
end
function write_float(self, section, value)
local n = tonumber(value)
if n ~= nil then
return Value.write(self, section, "%.1f" % n)
end
end
s = m:section(TypedSection, "olsrd6", translate("General settings"))
s.anonymous = true
s:tab("general", translate("General Settings"))
s:tab("lquality", translate("Link Quality Settings"))
s:tab("smartgw", translate("SmartGW"), not has_ipip and translate("Warning: kmod-ipip is not installed. Without kmod-ipip SmartGateway will not work, please install it."))
s:tab("advanced", translate("Advanced Settings"))
poll = s:taboption("advanced", Value, "Pollrate", translate("Pollrate"),
translate("Polling rate for OLSR sockets in seconds. Default is 0.05."))
poll.optional = true
poll.datatype = "ufloat"
poll.placeholder = "0.05"
nicc = s:taboption("advanced", Value, "NicChgsPollInt", translate("Nic changes poll interval"),
translate("Interval to poll network interfaces for configuration changes (in seconds). Default is \"2.5\"."))
nicc.optional = true
nicc.datatype = "ufloat"
nicc.placeholder = "2.5"
tos = s:taboption("advanced", Value, "TosValue", translate("TOS value"),
translate("Type of service value for the IP header of control traffic. Default is \"16\"."))
tos.optional = true
tos.datatype = "uinteger"
tos.placeholder = "16"
fib = s:taboption("general", ListValue, "FIBMetric", translate("FIB metric"),
translate ("FIBMetric controls the metric value of the host-routes OLSRd sets. "..
"\"flat\" means that the metric value is always 2. This is the preferred value "..
"because it helps the linux kernel routing to clean up older routes. "..
"\"correct\" uses the hopcount as the metric value. "..
"\"approx\" use the hopcount as the metric value too, but does only update the hopcount if the nexthop changes too. "..
"Default is \"flat\"."))
fib:value("flat")
fib:value("correct")
fib:value("approx")
lql = s:taboption("lquality", ListValue, "LinkQualityLevel", translate("LQ level"),
translate("Link quality level switch between hopcount and cost-based (mostly ETX) routing.<br />"..
"<b>0</b> = do not use link quality<br />"..
"<b>2</b> = use link quality for MPR selection and routing<br />"..
"Default is \"2\""))
lql:value("2")
lql:value("0")
lqage = s:taboption("lquality", Value, "LinkQualityAging", translate("LQ aging"),
translate("Link quality aging factor (only for lq level 2). Tuning parameter for etx_float and etx_fpm, smaller values "..
"mean slower changes of ETX value. (allowed values are between 0.01 and 1.0)"))
lqage.optional = true
lqage:depends("LinkQualityLevel", "2")
lqa = s:taboption("lquality", ListValue, "LinkQualityAlgorithm", translate("LQ algorithm"),
translate("Link quality algorithm (only for lq level 2).<br />"..
"<b>etx_float</b>: floating point ETX with exponential aging<br />"..
"<b>etx_fpm</b> : same as etx_float, but with integer arithmetic<br />"..
"<b>etx_ff</b> : ETX freifunk, an etx variant which use all OLSR traffic (instead of only hellos) for ETX calculation<br />"..
"<b>etx_ffeth</b>: incompatible variant of etx_ff that allows ethernet links with ETX 0.1.<br />"..
"Defaults to \"etx_ff\""))
lqa.optional = true
lqa:value("etx_ff")
lqa:value("etx_fpm")
lqa:value("etx_float")
lqa:value("etx_ffeth")
lqa:depends("LinkQualityLevel", "2")
lqa.optional = true
lqfish = s:taboption("lquality", Flag, "LinkQualityFishEye", translate("LQ fisheye"),
translate("Fisheye mechanism for TCs (checked means on). Default is \"on\""))
lqfish.default = "1"
lqfish.optional = true
hyst = s:taboption("lquality", Flag, "UseHysteresis", translate("Use hysteresis"),
translate("Hysteresis for link sensing (only for hopcount metric). Hysteresis adds more robustness to the link sensing "..
"but delays neighbor registration. Defaults is \"yes\""))
hyst.default = "yes"
hyst.enabled = "yes"
hyst.disabled = "no"
hyst:depends("LinkQualityLevel", "0")
hyst.optional = true
hyst.rmempty = true
port = s:taboption("general", Value, "OlsrPort", translate("Port"),
translate("The port OLSR uses. This should usually stay at the IANA assigned port 698. It can have a value between 1 and 65535."))
port.optional = true
port.default = "698"
port.rmempty = true
mainip = s:taboption("general", Value, "MainIp", translate("Main IP"),
translate("Sets the main IP (originator ip) of the router. This IP will NEVER change during the uptime of olsrd. "..
"Default is ::, which triggers usage of the IP of the first interface."))
mainip.optional = true
mainip.rmempty = true
mainip.datatype = "ipaddr"
mainip.placeholder = "::"
sgw = s:taboption("smartgw", Flag, "SmartGateway", translate("Enable"), translate("Enable SmartGateway. If it is disabled, then " ..
"all other SmartGateway parameters are ignored. Default is \"no\"."))
sgw.default="no"
sgw.enabled="yes"
sgw.disabled="no"
sgw.rmempty = true
sgwnat = s:taboption("smartgw", Flag, "SmartGatewayAllowNAT", translate("Allow gateways with NAT"), translate("Allow the selection of an outgoing ipv4 gateway with NAT"))
sgwnat:depends("SmartGateway", "yes")
sgwnat.default="yes"
sgwnat.enabled="yes"
sgwnat.disabled="no"
sgwnat.optional = true
sgwnat.rmempty = true
sgwuplink = s:taboption("smartgw", ListValue, "SmartGatewayUplink", translate("Announce uplink"), translate("Which kind of uplink is exported to the other mesh nodes. " ..
"An uplink is detected by looking for a local HNA6 ::ffff:0:0/96 or 2000::/3. Default setting is \"both\"."))
sgwuplink:value("none")
sgwuplink:value("ipv4")
sgwuplink:value("ipv6")
sgwuplink:value("both")
sgwuplink:depends("SmartGateway", "yes")
sgwuplink.default="both"
sgwuplink.optional = true
sgwuplink.rmempty = true
sgwulnat = s:taboption("smartgw", Flag, "SmartGatewayUplinkNAT", translate("Uplink uses NAT"), translate("If this Node uses NAT for connections to the internet. " ..
"Default is \"yes\"."))
sgwulnat:depends("SmartGatewayUplink", "ipv4")
sgwulnat:depends("SmartGatewayUplink", "both")
sgwulnat.default="yes"
sgwulnat.enabled="yes"
sgwulnat.disabled="no"
sgwnat.optional = true
sgwnat.rmempty = true
sgwspeed = s:taboption("smartgw", Value, "SmartGatewaySpeed", translate("Speed of the uplink"), translate("Specifies the speed of "..
"the uplink in kilobits/s. First parameter is upstream, second parameter is downstream. Default is \"128 1024\"."))
sgwspeed:depends("SmartGatewayUplink", "ipv4")
sgwspeed:depends("SmartGatewayUplink", "ipv6")
sgwspeed:depends("SmartGatewayUplink", "both")
sgwspeed.optional = true
sgwspeed.rmempty = true
sgwprefix = s:taboption("smartgw", Value, "SmartGatewayPrefix", translate("IPv6-Prefix of the uplink"), translate("This can be used " ..
"to signal the external IPv6 prefix of the uplink to the clients. This might allow a client to change it's local IPv6 address to " ..
"use the IPv6 gateway without any kind of address translation. The maximum prefix length is 64 bits. " ..
"Default is \"::/0\" (no prefix)."))
sgwprefix:depends("SmartGatewayUplink", "ipv6")
sgwprefix:depends("SmartGatewayUplink", "both")
sgwprefix.optional = true
sgwprefix.rmempty = true
willingness = s:taboption("advanced", ListValue, "Willingness", translate("Willingness"),
translate("The fixed willingness to use. If not set willingness will be calculated dynamically based on battery/power status. Default is \"3\"."))
for i=0,7 do
willingness:value(i)
end
willingness.optional = true
willingness.default = "3"
natthr = s:taboption("advanced", Value, "NatThreshold", translate("NAT threshold"),
translate("If the route to the current gateway is to be changed, the ETX value of this gateway is "..
"multiplied with this value before it is compared to the new one. "..
"The parameter can be a value between 0.1 and 1.0, but should be close to 1.0 if changed.<br />"..
"<b>WARNING:</b> This parameter should not be used together with the etx_ffeth metric!<br />"..
"Defaults to \"1.0\"."))
for i=1,0.1,-0.1 do
natthr:value(i)
end
natthr:depends("LinkQualityAlgorithm", "etx_ff")
natthr:depends("LinkQualityAlgorithm", "etx_float")
natthr:depends("LinkQualityAlgorithm", "etx_fpm")
natthr.default = "1.0"
natthr.optional = true
natthr.write = write_float
i = m:section(TypedSection, "InterfaceDefaults", translate("Interfaces Defaults"))
i.anonymous = true
i.addremove = false
i:tab("general", translate("General Settings"))
i:tab("addrs", translate("IP Addresses"))
i:tab("timing", translate("Timing and Validity"))
mode = i:taboption("general", ListValue, "Mode", translate("Mode"),
translate("Interface Mode is used to prevent unnecessary packet forwarding on switched ethernet interfaces. "..
"valid Modes are \"mesh\" and \"ether\". Default is \"mesh\"."))
mode:value("mesh")
mode:value("ether")
mode.optional = true
mode.rmempty = true
weight = i:taboption("general", Value, "Weight", translate("Weight"),
translate("When multiple links exist between hosts the weight of interface is used to determine the link to use. "..
"Normally the weight is automatically calculated by olsrd based on the characteristics of the interface, "..
"but here you can specify a fixed value. Olsrd will choose links with the lowest value.<br />"..
"<b>Note:</b> Interface weight is used only when LinkQualityLevel is set to 0. "..
"For any other value of LinkQualityLevel, the interface ETX value is used instead."))
weight.optional = true
weight.datatype = "uinteger"
weight.placeholder = "0"
lqmult = i:taboption("general", DynamicList, "LinkQualityMult", translate("LinkQuality Multiplicator"),
translate("Multiply routes with the factor given here. Allowed values are between 0.01 and 1.0. "..
"It is only used when LQ-Level is greater than 0. Examples:<br />"..
"reduce LQ to fd91:662e:3c58::1 by half: fd91:662e:3c58::1 0.5<br />"..
"reduce LQ to all nodes on this interface by 20%: default 0.8"))
lqmult.optional = true
lqmult.rmempty = true
lqmult.cast = "table"
lqmult.placeholder = "default 1.0"
function lqmult.validate(self, value)
for _, v in pairs(value) do
if v ~= "" then
local val = util.split(v, " ")
local host = val[1]
local mult = val[2]
if not host or not mult then
return nil, translate("LQMult requires two values (IP address or 'default' and multiplicator) seperated by space.")
end
if not (host == "default" or ip.IPv6(host)) then
return nil, translate("Can only be a valid IPv6 address or 'default'")
end
if not tonumber(mult) or tonumber(mult) > 1 or tonumber(mult) < 0.01 then
return nil, translate("Invalid Value for LQMult-Value. Must be between 0.01 and 1.0.")
end
if not mult:match("[0-1]%.[0-9]+") then
return nil, translate("Invalid Value for LQMult-Value. You must use a decimal number between 0.01 and 1.0 here.")
end
end
end
return value
end
ip6m = i:taboption("addrs", Value, "IPv6Multicast", translate("IPv6 multicast"),
translate("IPv6 multicast address. Default is \"FF02::6D\", the manet-router linklocal multicast."))
ip6m.optional = true
ip6m.datatype = "ip6addr"
ip6m.placeholder = "FF02::6D"
ip6s = i:taboption("addrs", Value, "IPv6Src", translate("IPv6 source"),
translate("IPv6 src prefix. OLSRd will choose one of the interface IPs which matches the prefix of this parameter. "..
"Default is \"0::/0\", which triggers the usage of a not-linklocal interface IP."))
ip6s.optional = true
ip6s.datatype = "ip6addr"
ip6s.placeholder = "0::/0"
hi = i:taboption("timing", Value, "HelloInterval", translate("Hello interval"))
hi.optional = true
hi.datatype = "ufloat"
hi.placeholder = "5.0"
hi.write = write_float
hv = i:taboption("timing", Value, "HelloValidityTime", translate("Hello validity time"))
hv.optional = true
hv.datatype = "ufloat"
hv.placeholder = "40.0"
hv.write = write_float
ti = i:taboption("timing", Value, "TcInterval", translate("TC interval"))
ti.optional = true
ti.datatype = "ufloat"
ti.placeholder = "2.0"
ti.write = write_float
tv = i:taboption("timing", Value, "TcValidityTime", translate("TC validity time"))
tv.optional = true
tv.datatype = "ufloat"
tv.placeholder = "256.0"
tv.write = write_float
mi = i:taboption("timing", Value, "MidInterval", translate("MID interval"))
mi.optional = true
mi.datatype = "ufloat"
mi.placeholder = "18.0"
mi.write = write_float
mv = i:taboption("timing", Value, "MidValidityTime", translate("MID validity time"))
mv.optional = true
mv.datatype = "ufloat"
mv.placeholder = "324.0"
mv.write = write_float
ai = i:taboption("timing", Value, "HnaInterval", translate("HNA interval"))
ai.optional = true
ai.datatype = "ufloat"
ai.placeholder = "18.0"
ai.write = write_float
av = i:taboption("timing", Value, "HnaValidityTime", translate("HNA validity time"))
av.optional = true
av.datatype = "ufloat"
av.placeholder = "108.0"
av.write = write_float
ifs = m:section(TypedSection, "Interface", translate("Interfaces"))
ifs.addremove = true
ifs.anonymous = true
ifs.extedit = luci.dispatcher.build_url("admin/services/olsrd6/iface/%s")
ifs.template = "cbi/tblsection"
function ifs.create(...)
local sid = TypedSection.create(...)
luci.http.redirect(ifs.extedit % sid)
end
ign = ifs:option(Flag, "ignore", translate("Enable"))
ign.enabled = "0"
ign.disabled = "1"
ign.rmempty = false
function ign.cfgvalue(self, section)
return Flag.cfgvalue(self, section) or "0"
end
network = ifs:option(DummyValue, "interface", translate("Network"))
network.template = "cbi/network_netinfo"
mode = ifs:option(DummyValue, "Mode", translate("Mode"))
function mode.cfgvalue(...)
return Value.cfgvalue(...) or m.uci:get_first("olsrd6", "InterfaceDefaults", "Mode", "mesh")
end
hello = ifs:option(DummyValue, "_hello", translate("Hello"))
function hello.cfgvalue(self, section)
local i = tonumber(m.uci:get("olsrd6", section, "HelloInterval")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "HelloInterval", 5))
local v = tonumber(m.uci:get("olsrd6", section, "HelloValidityTime")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "HelloValidityTime", 40))
return "%.01fs / %.01fs" %{ i, v }
end
tc = ifs:option(DummyValue, "_tc", translate("TC"))
function tc.cfgvalue(self, section)
local i = tonumber(m.uci:get("olsrd6", section, "TcInterval")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "TcInterval", 2))
local v = tonumber(m.uci:get("olsrd6", section, "TcValidityTime")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "TcValidityTime", 256))
return "%.01fs / %.01fs" %{ i, v }
end
mid = ifs:option(DummyValue, "_mid", translate("MID"))
function mid.cfgvalue(self, section)
local i = tonumber(m.uci:get("olsrd6", section, "MidInterval")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "MidInterval", 18))
local v = tonumber(m.uci:get("olsrd6", section, "MidValidityTime")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "MidValidityTime", 324))
return "%.01fs / %.01fs" %{ i, v }
end
hna = ifs:option(DummyValue, "_hna", translate("HNA"))
function hna.cfgvalue(self, section)
local i = tonumber(m.uci:get("olsrd6", section, "HnaInterval")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "HnaInterval", 18))
local v = tonumber(m.uci:get("olsrd6", section, "HnaValidityTime")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "HnaValidityTime", 108))
return "%.01fs / %.01fs" %{ i, v }
end
return m
| apache-2.0 |
NeoRaider/luci | applications/luci-app-olsr/luasrc/model/cbi/olsr/olsrd6.lua | 68 | 16296 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2010 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
require("luci.tools.webadmin")
local fs = require "nixio.fs"
local util = require "luci.util"
local ip = require "luci.ip"
local has_ipip = fs.glob("/etc/modules.d/[0-9]*-ipip")()
m = Map("olsrd6", translate("OLSR Daemon"),
translate("The OLSR daemon is an implementation of the Optimized Link State Routing protocol. "..
"As such it allows mesh routing for any network equipment. "..
"It runs on any wifi card that supports ad-hoc mode and of course on any ethernet device. "..
"Visit <a href='http://www.olsr.org'>olsrd.org</a> for help and documentation."))
function m.on_parse()
local has_defaults = false
m.uci:foreach("olsrd6", "InterfaceDefaults",
function(s)
has_defaults = true
return false
end)
if not has_defaults then
m.uci:section("olsrd6", "InterfaceDefaults")
end
end
function write_float(self, section, value)
local n = tonumber(value)
if n ~= nil then
return Value.write(self, section, "%.1f" % n)
end
end
s = m:section(TypedSection, "olsrd6", translate("General settings"))
s.anonymous = true
s:tab("general", translate("General Settings"))
s:tab("lquality", translate("Link Quality Settings"))
s:tab("smartgw", translate("SmartGW"), not has_ipip and translate("Warning: kmod-ipip is not installed. Without kmod-ipip SmartGateway will not work, please install it."))
s:tab("advanced", translate("Advanced Settings"))
poll = s:taboption("advanced", Value, "Pollrate", translate("Pollrate"),
translate("Polling rate for OLSR sockets in seconds. Default is 0.05."))
poll.optional = true
poll.datatype = "ufloat"
poll.placeholder = "0.05"
nicc = s:taboption("advanced", Value, "NicChgsPollInt", translate("Nic changes poll interval"),
translate("Interval to poll network interfaces for configuration changes (in seconds). Default is \"2.5\"."))
nicc.optional = true
nicc.datatype = "ufloat"
nicc.placeholder = "2.5"
tos = s:taboption("advanced", Value, "TosValue", translate("TOS value"),
translate("Type of service value for the IP header of control traffic. Default is \"16\"."))
tos.optional = true
tos.datatype = "uinteger"
tos.placeholder = "16"
fib = s:taboption("general", ListValue, "FIBMetric", translate("FIB metric"),
translate ("FIBMetric controls the metric value of the host-routes OLSRd sets. "..
"\"flat\" means that the metric value is always 2. This is the preferred value "..
"because it helps the linux kernel routing to clean up older routes. "..
"\"correct\" uses the hopcount as the metric value. "..
"\"approx\" use the hopcount as the metric value too, but does only update the hopcount if the nexthop changes too. "..
"Default is \"flat\"."))
fib:value("flat")
fib:value("correct")
fib:value("approx")
lql = s:taboption("lquality", ListValue, "LinkQualityLevel", translate("LQ level"),
translate("Link quality level switch between hopcount and cost-based (mostly ETX) routing.<br />"..
"<b>0</b> = do not use link quality<br />"..
"<b>2</b> = use link quality for MPR selection and routing<br />"..
"Default is \"2\""))
lql:value("2")
lql:value("0")
lqage = s:taboption("lquality", Value, "LinkQualityAging", translate("LQ aging"),
translate("Link quality aging factor (only for lq level 2). Tuning parameter for etx_float and etx_fpm, smaller values "..
"mean slower changes of ETX value. (allowed values are between 0.01 and 1.0)"))
lqage.optional = true
lqage:depends("LinkQualityLevel", "2")
lqa = s:taboption("lquality", ListValue, "LinkQualityAlgorithm", translate("LQ algorithm"),
translate("Link quality algorithm (only for lq level 2).<br />"..
"<b>etx_float</b>: floating point ETX with exponential aging<br />"..
"<b>etx_fpm</b> : same as etx_float, but with integer arithmetic<br />"..
"<b>etx_ff</b> : ETX freifunk, an etx variant which use all OLSR traffic (instead of only hellos) for ETX calculation<br />"..
"<b>etx_ffeth</b>: incompatible variant of etx_ff that allows ethernet links with ETX 0.1.<br />"..
"Defaults to \"etx_ff\""))
lqa.optional = true
lqa:value("etx_ff")
lqa:value("etx_fpm")
lqa:value("etx_float")
lqa:value("etx_ffeth")
lqa:depends("LinkQualityLevel", "2")
lqa.optional = true
lqfish = s:taboption("lquality", Flag, "LinkQualityFishEye", translate("LQ fisheye"),
translate("Fisheye mechanism for TCs (checked means on). Default is \"on\""))
lqfish.default = "1"
lqfish.optional = true
hyst = s:taboption("lquality", Flag, "UseHysteresis", translate("Use hysteresis"),
translate("Hysteresis for link sensing (only for hopcount metric). Hysteresis adds more robustness to the link sensing "..
"but delays neighbor registration. Defaults is \"yes\""))
hyst.default = "yes"
hyst.enabled = "yes"
hyst.disabled = "no"
hyst:depends("LinkQualityLevel", "0")
hyst.optional = true
hyst.rmempty = true
port = s:taboption("general", Value, "OlsrPort", translate("Port"),
translate("The port OLSR uses. This should usually stay at the IANA assigned port 698. It can have a value between 1 and 65535."))
port.optional = true
port.default = "698"
port.rmempty = true
mainip = s:taboption("general", Value, "MainIp", translate("Main IP"),
translate("Sets the main IP (originator ip) of the router. This IP will NEVER change during the uptime of olsrd. "..
"Default is ::, which triggers usage of the IP of the first interface."))
mainip.optional = true
mainip.rmempty = true
mainip.datatype = "ipaddr"
mainip.placeholder = "::"
sgw = s:taboption("smartgw", Flag, "SmartGateway", translate("Enable"), translate("Enable SmartGateway. If it is disabled, then " ..
"all other SmartGateway parameters are ignored. Default is \"no\"."))
sgw.default="no"
sgw.enabled="yes"
sgw.disabled="no"
sgw.rmempty = true
sgwnat = s:taboption("smartgw", Flag, "SmartGatewayAllowNAT", translate("Allow gateways with NAT"), translate("Allow the selection of an outgoing ipv4 gateway with NAT"))
sgwnat:depends("SmartGateway", "yes")
sgwnat.default="yes"
sgwnat.enabled="yes"
sgwnat.disabled="no"
sgwnat.optional = true
sgwnat.rmempty = true
sgwuplink = s:taboption("smartgw", ListValue, "SmartGatewayUplink", translate("Announce uplink"), translate("Which kind of uplink is exported to the other mesh nodes. " ..
"An uplink is detected by looking for a local HNA6 ::ffff:0:0/96 or 2000::/3. Default setting is \"both\"."))
sgwuplink:value("none")
sgwuplink:value("ipv4")
sgwuplink:value("ipv6")
sgwuplink:value("both")
sgwuplink:depends("SmartGateway", "yes")
sgwuplink.default="both"
sgwuplink.optional = true
sgwuplink.rmempty = true
sgwulnat = s:taboption("smartgw", Flag, "SmartGatewayUplinkNAT", translate("Uplink uses NAT"), translate("If this Node uses NAT for connections to the internet. " ..
"Default is \"yes\"."))
sgwulnat:depends("SmartGatewayUplink", "ipv4")
sgwulnat:depends("SmartGatewayUplink", "both")
sgwulnat.default="yes"
sgwulnat.enabled="yes"
sgwulnat.disabled="no"
sgwnat.optional = true
sgwnat.rmempty = true
sgwspeed = s:taboption("smartgw", Value, "SmartGatewaySpeed", translate("Speed of the uplink"), translate("Specifies the speed of "..
"the uplink in kilobits/s. First parameter is upstream, second parameter is downstream. Default is \"128 1024\"."))
sgwspeed:depends("SmartGatewayUplink", "ipv4")
sgwspeed:depends("SmartGatewayUplink", "ipv6")
sgwspeed:depends("SmartGatewayUplink", "both")
sgwspeed.optional = true
sgwspeed.rmempty = true
sgwprefix = s:taboption("smartgw", Value, "SmartGatewayPrefix", translate("IPv6-Prefix of the uplink"), translate("This can be used " ..
"to signal the external IPv6 prefix of the uplink to the clients. This might allow a client to change it's local IPv6 address to " ..
"use the IPv6 gateway without any kind of address translation. The maximum prefix length is 64 bits. " ..
"Default is \"::/0\" (no prefix)."))
sgwprefix:depends("SmartGatewayUplink", "ipv6")
sgwprefix:depends("SmartGatewayUplink", "both")
sgwprefix.optional = true
sgwprefix.rmempty = true
willingness = s:taboption("advanced", ListValue, "Willingness", translate("Willingness"),
translate("The fixed willingness to use. If not set willingness will be calculated dynamically based on battery/power status. Default is \"3\"."))
for i=0,7 do
willingness:value(i)
end
willingness.optional = true
willingness.default = "3"
natthr = s:taboption("advanced", Value, "NatThreshold", translate("NAT threshold"),
translate("If the route to the current gateway is to be changed, the ETX value of this gateway is "..
"multiplied with this value before it is compared to the new one. "..
"The parameter can be a value between 0.1 and 1.0, but should be close to 1.0 if changed.<br />"..
"<b>WARNING:</b> This parameter should not be used together with the etx_ffeth metric!<br />"..
"Defaults to \"1.0\"."))
for i=1,0.1,-0.1 do
natthr:value(i)
end
natthr:depends("LinkQualityAlgorithm", "etx_ff")
natthr:depends("LinkQualityAlgorithm", "etx_float")
natthr:depends("LinkQualityAlgorithm", "etx_fpm")
natthr.default = "1.0"
natthr.optional = true
natthr.write = write_float
i = m:section(TypedSection, "InterfaceDefaults", translate("Interfaces Defaults"))
i.anonymous = true
i.addremove = false
i:tab("general", translate("General Settings"))
i:tab("addrs", translate("IP Addresses"))
i:tab("timing", translate("Timing and Validity"))
mode = i:taboption("general", ListValue, "Mode", translate("Mode"),
translate("Interface Mode is used to prevent unnecessary packet forwarding on switched ethernet interfaces. "..
"valid Modes are \"mesh\" and \"ether\". Default is \"mesh\"."))
mode:value("mesh")
mode:value("ether")
mode.optional = true
mode.rmempty = true
weight = i:taboption("general", Value, "Weight", translate("Weight"),
translate("When multiple links exist between hosts the weight of interface is used to determine the link to use. "..
"Normally the weight is automatically calculated by olsrd based on the characteristics of the interface, "..
"but here you can specify a fixed value. Olsrd will choose links with the lowest value.<br />"..
"<b>Note:</b> Interface weight is used only when LinkQualityLevel is set to 0. "..
"For any other value of LinkQualityLevel, the interface ETX value is used instead."))
weight.optional = true
weight.datatype = "uinteger"
weight.placeholder = "0"
lqmult = i:taboption("general", DynamicList, "LinkQualityMult", translate("LinkQuality Multiplicator"),
translate("Multiply routes with the factor given here. Allowed values are between 0.01 and 1.0. "..
"It is only used when LQ-Level is greater than 0. Examples:<br />"..
"reduce LQ to fd91:662e:3c58::1 by half: fd91:662e:3c58::1 0.5<br />"..
"reduce LQ to all nodes on this interface by 20%: default 0.8"))
lqmult.optional = true
lqmult.rmempty = true
lqmult.cast = "table"
lqmult.placeholder = "default 1.0"
function lqmult.validate(self, value)
for _, v in pairs(value) do
if v ~= "" then
local val = util.split(v, " ")
local host = val[1]
local mult = val[2]
if not host or not mult then
return nil, translate("LQMult requires two values (IP address or 'default' and multiplicator) seperated by space.")
end
if not (host == "default" or ip.IPv6(host)) then
return nil, translate("Can only be a valid IPv6 address or 'default'")
end
if not tonumber(mult) or tonumber(mult) > 1 or tonumber(mult) < 0.01 then
return nil, translate("Invalid Value for LQMult-Value. Must be between 0.01 and 1.0.")
end
if not mult:match("[0-1]%.[0-9]+") then
return nil, translate("Invalid Value for LQMult-Value. You must use a decimal number between 0.01 and 1.0 here.")
end
end
end
return value
end
ip6m = i:taboption("addrs", Value, "IPv6Multicast", translate("IPv6 multicast"),
translate("IPv6 multicast address. Default is \"FF02::6D\", the manet-router linklocal multicast."))
ip6m.optional = true
ip6m.datatype = "ip6addr"
ip6m.placeholder = "FF02::6D"
ip6s = i:taboption("addrs", Value, "IPv6Src", translate("IPv6 source"),
translate("IPv6 src prefix. OLSRd will choose one of the interface IPs which matches the prefix of this parameter. "..
"Default is \"0::/0\", which triggers the usage of a not-linklocal interface IP."))
ip6s.optional = true
ip6s.datatype = "ip6addr"
ip6s.placeholder = "0::/0"
hi = i:taboption("timing", Value, "HelloInterval", translate("Hello interval"))
hi.optional = true
hi.datatype = "ufloat"
hi.placeholder = "5.0"
hi.write = write_float
hv = i:taboption("timing", Value, "HelloValidityTime", translate("Hello validity time"))
hv.optional = true
hv.datatype = "ufloat"
hv.placeholder = "40.0"
hv.write = write_float
ti = i:taboption("timing", Value, "TcInterval", translate("TC interval"))
ti.optional = true
ti.datatype = "ufloat"
ti.placeholder = "2.0"
ti.write = write_float
tv = i:taboption("timing", Value, "TcValidityTime", translate("TC validity time"))
tv.optional = true
tv.datatype = "ufloat"
tv.placeholder = "256.0"
tv.write = write_float
mi = i:taboption("timing", Value, "MidInterval", translate("MID interval"))
mi.optional = true
mi.datatype = "ufloat"
mi.placeholder = "18.0"
mi.write = write_float
mv = i:taboption("timing", Value, "MidValidityTime", translate("MID validity time"))
mv.optional = true
mv.datatype = "ufloat"
mv.placeholder = "324.0"
mv.write = write_float
ai = i:taboption("timing", Value, "HnaInterval", translate("HNA interval"))
ai.optional = true
ai.datatype = "ufloat"
ai.placeholder = "18.0"
ai.write = write_float
av = i:taboption("timing", Value, "HnaValidityTime", translate("HNA validity time"))
av.optional = true
av.datatype = "ufloat"
av.placeholder = "108.0"
av.write = write_float
ifs = m:section(TypedSection, "Interface", translate("Interfaces"))
ifs.addremove = true
ifs.anonymous = true
ifs.extedit = luci.dispatcher.build_url("admin/services/olsrd6/iface/%s")
ifs.template = "cbi/tblsection"
function ifs.create(...)
local sid = TypedSection.create(...)
luci.http.redirect(ifs.extedit % sid)
end
ign = ifs:option(Flag, "ignore", translate("Enable"))
ign.enabled = "0"
ign.disabled = "1"
ign.rmempty = false
function ign.cfgvalue(self, section)
return Flag.cfgvalue(self, section) or "0"
end
network = ifs:option(DummyValue, "interface", translate("Network"))
network.template = "cbi/network_netinfo"
mode = ifs:option(DummyValue, "Mode", translate("Mode"))
function mode.cfgvalue(...)
return Value.cfgvalue(...) or m.uci:get_first("olsrd6", "InterfaceDefaults", "Mode", "mesh")
end
hello = ifs:option(DummyValue, "_hello", translate("Hello"))
function hello.cfgvalue(self, section)
local i = tonumber(m.uci:get("olsrd6", section, "HelloInterval")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "HelloInterval", 5))
local v = tonumber(m.uci:get("olsrd6", section, "HelloValidityTime")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "HelloValidityTime", 40))
return "%.01fs / %.01fs" %{ i, v }
end
tc = ifs:option(DummyValue, "_tc", translate("TC"))
function tc.cfgvalue(self, section)
local i = tonumber(m.uci:get("olsrd6", section, "TcInterval")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "TcInterval", 2))
local v = tonumber(m.uci:get("olsrd6", section, "TcValidityTime")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "TcValidityTime", 256))
return "%.01fs / %.01fs" %{ i, v }
end
mid = ifs:option(DummyValue, "_mid", translate("MID"))
function mid.cfgvalue(self, section)
local i = tonumber(m.uci:get("olsrd6", section, "MidInterval")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "MidInterval", 18))
local v = tonumber(m.uci:get("olsrd6", section, "MidValidityTime")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "MidValidityTime", 324))
return "%.01fs / %.01fs" %{ i, v }
end
hna = ifs:option(DummyValue, "_hna", translate("HNA"))
function hna.cfgvalue(self, section)
local i = tonumber(m.uci:get("olsrd6", section, "HnaInterval")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "HnaInterval", 18))
local v = tonumber(m.uci:get("olsrd6", section, "HnaValidityTime")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "HnaValidityTime", 108))
return "%.01fs / %.01fs" %{ i, v }
end
return m
| apache-2.0 |
AresTao/darkstar | scripts/globals/weaponskills/burning_blade.lua | 30 | 1294 | -----------------------------------
-- Burning Blade
-- Sword weapon skill
-- Skill Level: 30
-- Desription: Deals Fire elemental damage to enemy. Damage varies with TP.
-- Aligned with the Flame Gorget.
-- Aligned with the Flame Belt.
-- Element: Fire
-- Modifiers: STR:20% ; INT:20%
-- 100%TP 200%TP 300%TP
-- 1.00 2.00 2.50
-----------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.ftp100 = 1; params.ftp200 = 2; params.ftp300 = 2.5;
params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.2; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.ele = ELE_FIRE;
params.skill = SKILL_SWD;
params.includemab = true;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp200 = 2.1; params.ftp300 = 3.4;
params.str_wsc = 0.4; params.int_wsc = 0.4;
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
qlee001/lua-rbtree | test.lua | 1 | 7321 | local rb = require "rbtree"
local function test_insert()
local size = 1024
local tree, err = rb.new(size)
assert(tree and not err, "new rbtree failed")
local t = {}
local index = 1
while index <= size do
local num = math.random(10240000)
if not t[num] then
local res, err = tree:insert(num, "Num-" .. tostring(num))
assert(res and not err, "insert failed")
t[num] = true
index = index + 1
end
end
for k, _ in pairs(t) do
local res, err = tree:find(k)
assert(res and not err, "insert but not found")
end
for i = 1, size do
local num = math.random(10240000)
if not t[num] then
local res, err = tree:find(num)
assert(not res)
res, err = tree:insert(num, "Num-" .. tostring(num))
assert(not res and err == "full")
else
local res, err = tree:find(num)
assert((res == "Num-" .. tostring(num)) and not err)
end
end
return
end
local function test_delete()
local size = 1024
local tree, err = rb.new(size)
assert(tree and not err, "new rbtree failed")
local t = {}
local index = 1
while index <= size do
local num = math.random(10240000)
if not t[num] then
local res, err = tree:insert(num, "Num-" .. tostring(num))
assert(res and not err, "insert failed")
t[num] = true
index = index + 1
end
end
for k, _ in pairs(t) do
local res, err = tree:find(k)
assert(res and not err, "insert but not found")
end
for k, v in pairs(t) do
local res = tree:find(k)
assert(res and res == "Num-" .. tostring(k), "not found")
local res, err = tree:delete(k)
assert(res and not err, "delete failed")
res = tree:find(k)
assert(not res, "delete but found")
end
for k, _ in pairs(t) do
local res = tree:find(k)
assert(not res, "insert but not found")
end
return
end
local function test_insert_and_delete1()
local size = 10240
local tree, err = rb.new(size)
assert(tree and not err, "new rbtree failed")
local t = {}
for i = 1, 10 do
local index = 1
while index <= size do
local num = math.random(10240000)
if not t[num] then
local res, err = tree:insert(num, "Num-" .. tostring(num))
assert(res and not err, "insert failed")
t[num] = true
index = index + 1
end
end
for k, _ in pairs(t) do
local res, err = tree:find(k)
assert(res and not err, "insert but not found")
end
for k, v in pairs(t) do
local res = tree:find(k)
assert(res and res == "Num-" .. tostring(k), "not found")
local res, err = tree:delete(k)
assert(res and not err, "delete failed")
res = tree:find(k)
assert(not res, "delete but found")
t[k] = nil
end
for k, v in pairs(t) do
assert(not k and not v, "not empty")
end
end
return
end
local function test_insert_and_delete2()
local size = 10240
local tree, err = rb.new(size * 2)
assert(tree and not err, "new rbtree failed")
local t = {}
for i = 1, 10 do
local index = 1
while index <= size do
local num = math.random(10240000)
if not t[num] then
local res, err = tree:insert(num, "Num-" .. tostring(num))
assert(res and not err, "insert failed")
t[num] = true
index = index + 1
end
end
for k, _ in pairs(t) do
local res, err = tree:find(k)
assert(res and not err, "insert but not found")
end
index = 0
for k, v in pairs(t) do
local res = tree:find(k)
assert(res and res == "Num-" .. tostring(k), "not found")
local res, err = tree:delete(k)
assert(res and not err, "delete failed")
res = tree:find(k)
assert(not res, "delete but found")
t[k] = nil
index = index + 1
if index >= size / 10 * 9 then
break
end
end
end
for k, v in pairs(t) do
local res = tree:find(k)
assert(res and res == "Num-" .. tostring(k), "not found")
end
for i = 1, size do
local num = math.random(10240000)
if not t[num] then
local res, err = tree:find(num)
assert(not res)
else
local res, err = tree:find(num)
assert((res == "Num-" .. tostring(num)) and not err)
end
end
for k, v in pairs(t) do
local res, err = tree:delete(k)
assert(res and not err, "delete failed")
t[k] = nil
end
for k, v in pairs(t) do
assert(not k and not v, "not empty")
end
return
end
math.randomseed(os.clock())
test_insert()
test_delete()
test_insert_and_delete1()
test_insert_and_delete2()
--[[
local size = 1024
local tree, err = rb.new(size)
if not tree then
print('err:', err)
end
for iiiii = 1, 10 do
local t = {}
--tree:all()
local count = 0
while count <= size do
local num = math.random(10240000)
local val = 'Num-' .. tostring(num)
if not t[num] then
local res , err = tree:insert(num, val)
if not res then
print('insert:',err)
break
end
t[num] = true
count = count + 1
else
-- print('dulplicate, key:', num)
end
end
--tree:all()
for k, v in pairs(t) do
local res = tree:find(k)
if not res or res ~= ('Num-' .. tostring(k)) then
print('fatal error, not found')
else
-- print('successful, key:', k, ' val:', res)
end
end
--[[
for i = 1, 102400 do
local num = math.random(10240000)
local res = tree:find(num)
local exist
if not res or res ~= ('Num-' .. tostring(num)) then
exist = false
else
exist = true
end
if (not t[num] and exist) or (t[num] and not exist)then
print('error key:', num, ' val:', res, ' t.num:', t[num])
end
end
--return
--[[
for k, v in pairs(t) do
local res = tree:delete(k)
if not res then
return
end
end
for k, v in pairs(t) do
local res = tree:find(k)
if not res then
--print('successful, key:', k, ' val:', res)
else
print('fatal error not delete, res:', res, ' k:', k)
end
end
]]--
--[[
tree:insert(4, 'First')
tree:insert(443, 'Second')
tree:insert(453, 'Third')
tree:insert(4344312, 'Num-4344312')
tree:insert(434312, 'Num-434312')
tree:insert(34312, 'Num-34312')
tree:insert(34352, 'Num-34352')
tree:insert(3352, 'Num-3352')
]]--
--[[
local res = tree:find(5)
print('find 5 res:', res)
res = tree:find(4)
print('find 4 res:', res)
res = tree:find(444)
print('find 444 res:', res)
res = tree:find(443)
print('find 443 res:', res)
res = tree:find(453)
print('find 453 res:', res)
tree:delete(4)
res = tree:find(4)
print('find 4 res:', res)
]]--
| mit |
ignacio/route66 | unittest/run.lua | 1 | 5116 | package.path = [[C:\LuaRocks\1.0\lua\?.lua;C:\LuaRocks\1.0\lua\?\init.lua;]] .. package.path
require "luarocks.require"
local Runner = require "siteswap.runner"
local Test = require "siteswap.test"
local event_emitter = require "luanode.event_emitter"
local Class = require "luanode.class"
local route66 = require "route66"
local runner = Runner()
local router = route66.new()
--
-- The router to be used in the tests
--
router:get("/hello/(.+)", function(req, res, word)
res:writeHead(200, { ["Content-Type"] = "text/plain"})
res:finish("received " .. word)
end)
router:get("hola", "que", "tal", function(req, res)
end)
router:post("/postit", function(req, res)
assert(#req:listeners("data") > 0, "A 'data' listener should have been added")
res:writeHead(200, { ["Content-Type"] = "text/plain"})
res:finish(req.body)
end)
router:raw_post("/raw_post", function(req, res)
-- no data listener was added
assert(#req:listeners("data") == 0, "No 'data' listener should have been added")
req._incoming_data = {}
req:on("data", function (self, data)
req._incoming_data[#req._incoming_data + 1] = data
end)
req:on("end", function()
req.body = table.concat(req._incoming_data)
req._incoming_data = nil
res:writeHead(200, { ["Content-Type"] = "text/plain"})
res:finish(req.body)
end)
end)
--
-- A fake webserver
--
local server = event_emitter()
server:on("request", function(self, req, res)
router.not_found(req, res)
end)
router:bindServer(server)
--
-- Fake requests and responses
--
local Request = Class.InheritsFrom(event_emitter)
function Request:finish (data)
if data then
table.insert(self.body, data)
end
self.body = table.concat(self.body)
self:emit("data", self.body)
self:emit("end")
end
local function make_request ()
return Request({ body = {} })
end
local Response = Class.InheritsFrom(event_emitter)
function Response:writeHead (status, headers)
self.status = status
self.headers = headers
end
function Response:finish (data)
if data then
table.insert(self.body, data)
end
self.body = table.concat(self.body)
end
local function make_response ()
return Response({ body = {} })
end
---
-- Valid GET. Must reply 200.
--
runner:AddTest("GET", function(test)
local req, res = make_request(), make_response()
req.url = "/hello/world"
req.method = "GET"
req.headers = {Accept = "*/*", Foo = "bar"}
server:emit("request", req, res)
test:assert_equal(200, res.status)
test:assert_equal("received world", res.body)
test:Done()
end)
---
-- GET not found. Must reply 404.
--
runner:AddTest("GET not found", function(test)
local req, res = make_request(), make_response()
req.url = "/not_found"
req.method = "GET"
req.headers = {Accept = "*/*"}
server:emit("request", req, res)
test:assert_equal(404, res.status)
test:assert_equal("Not Found\n", res.body)
test:Done()
end)
---
-- Valid POST. Must reply 200.
--
runner:AddTest("POST", function(test)
local req, res = make_request(), make_response()
req.url = "/postit"
req.method = "POST"
req.headers = {Accept = "*/*", Foo = "bar", ["Content-Length"] = 10}
server:emit("request", req, res)
req:finish("0123456789")
test:assert_equal(200, res.status)
test:assert_equal("0123456789", res.body)
test:Done()
end)
---
-- A request is performed and there is no handler for it.
-- We use a HEAD request for the simple reason we didn't register any handlers for it.
--
runner:AddTest("Method with no handler", function(test)
local req, res = make_request(), make_response()
req.url = "/hello/world"
req.method = "HEAD"
req.headers = {Accept = "*/*", Foo = "bar"}
server:emit("request", req, res)
test:assert_equal(405, res.status)
test:Done()
end)
---
-- Checks that when the method is allowed (there are handlers for it) but no pattern
-- matches, a 404 is returned.
--
runner:AddTest("Allowed method but no match", function(test)
local req, res = make_request(), make_response()
req.url = "/foo"
req.method = "GET"
req.headers = {Accept = "*/*", Foo = "bar"}
server:emit("request", req, res)
test:assert_equal(404, res.status)
test:Done()
end)
---
-- Unknown method. Must reply 405.
--
runner:AddTest("Unknown method", function(test)
local req, res = make_request(), make_response()
req.url = "/who_cares"
req.method = "unknown_method"
req.headers = {Accept = "*/*"}
server:emit("request", req, res)
test:assert_equal(405, res.status)
test:Done()
end)
---
-- Raw POST. Must reply 200.
--
runner:AddTest("RAW POST", function(test)
local req, res = make_request(), make_response()
req.url = "/raw_post"
req.method = "POST"
req.headers = {Accept = "*/*", Foo = "bar", ["Content-Length"] = 10}
server:emit("request", req, res)
req:finish("0123456789")
test:assert_equal(200, res.status)
test:assert_equal("0123456789", res.body)
test:Done()
end)
runner:Run()
process:loop()
| mit |
AresTao/darkstar | scripts/zones/LaLoff_Amphitheater/npcs/qm0_1.lua | 35 | 1154 | -----------------------------------
-- Area: LaLoff_Amphitheater
-- NPC: qm0 (warp player outside after they win fight)
-------------------------------------
package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil;
-------------------------------------
require("scripts/zones/LaLoff_Amphitheater/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0C);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdate CSID: %u",csid);
-- printf("onUpdate RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("onFinish CSID: %u",csid);
--printf("onFinish RESULT: %u",option);
if (csid == 0x0C and option == 1) then
player:setPos(291.459,-42.088,-401.161,163,130);
end
end; | gpl-3.0 |
openium/overthebox-feeds | luci-mod-admin-full/luasrc/model/cbi/admin_network/network.lua | 4 | 2603 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Copyright 2015 OVH <OverTheBox@ovh.net>
-- Licensed to the public under the Apache License 2.0.
local fs = require "nixio.fs"
m = Map("network", translate("Interfaces"))
m.pageaction = false
m:section(SimpleSection).template = "admin_network/iface_overview"
-- Show ATM bridge section if we have the capabilities
if fs.access("/usr/sbin/br2684ctl") then
atm = m:section(TypedSection, "atm-bridge", translate("ATM Bridges"),
translate("ATM bridges expose encapsulated ethernet in AAL5 " ..
"connections as virtual Linux network interfaces which can " ..
"be used in conjunction with DHCP or PPP to dial into the " ..
"provider network."))
atm.addremove = true
atm.anonymous = true
atm.create = function(self, section)
local sid = TypedSection.create(self, section)
local max_unit = -1
m.uci:foreach("network", "atm-bridge",
function(s)
local u = tonumber(s.unit)
if u ~= nil and u > max_unit then
max_unit = u
end
end)
m.uci:set("network", sid, "unit", max_unit + 1)
m.uci:set("network", sid, "atmdev", 0)
m.uci:set("network", sid, "encaps", "llc")
m.uci:set("network", sid, "payload", "bridged")
m.uci:set("network", sid, "vci", 35)
m.uci:set("network", sid, "vpi", 8)
return sid
end
atm:tab("general", translate("General Setup"))
atm:tab("advanced", translate("Advanced Settings"))
vci = atm:taboption("general", Value, "vci", translate("ATM Virtual Channel Identifier (VCI)"))
vpi = atm:taboption("general", Value, "vpi", translate("ATM Virtual Path Identifier (VPI)"))
encaps = atm:taboption("general", ListValue, "encaps", translate("Encapsulation mode"))
encaps:value("llc", translate("LLC"))
encaps:value("vc", translate("VC-Mux"))
atmdev = atm:taboption("advanced", Value, "atmdev", translate("ATM device number"))
unit = atm:taboption("advanced", Value, "unit", translate("Bridge unit number"))
payload = atm:taboption("advanced", ListValue, "payload", translate("Forwarding mode"))
payload:value("bridged", translate("bridged"))
payload:value("routed", translate("routed"))
m.pageaction = true
end
local network = require "luci.model.network"
if fs.access("/proc/sys/net/mptcp") then
local s = m:section(NamedSection, "globals", "globals", translate("Global network options"))
local mtcp = s:option(ListValue, "multipath", translate("Multipath TCP"))
mtcp:value("enable", translate("enable"))
mtcp:value("disable", translate("disable"))
m.pageaction = true
end
return m
| gpl-3.0 |
thess/OpenWrt-luci | applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/processes.lua | 57 | 1951 | -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
module("luci.statistics.rrdtool.definitions.processes", package.seeall)
function rrdargs( graph, plugin, plugin_instance, dtype )
return {
{
title = "%H: Processes",
vlabel = "Processes/s",
data = {
instances = {
ps_state = {
"sleeping", "running", "paging", "blocked", "stopped", "zombies"
}
},
options = {
ps_state_sleeping = { color = "0000ff" },
ps_state_running = { color = "008000" },
ps_state_paging = { color = "ffff00" },
ps_state_blocked = { color = "ff5000" },
ps_state_stopped = { color = "555555" },
ps_state_zombies = { color = "ff0000" }
}
}
},
{
title = "%H: CPU time used by %pi",
vlabel = "Jiffies",
data = {
sources = {
ps_cputime = { "syst", "user" }
},
options = {
ps_cputime__user = {
color = "0000ff",
overlay = true
},
ps_cputime__syst = {
color = "ff0000",
overlay = true
}
}
}
},
{
title = "%H: Threads and processes belonging to %pi",
vlabel = "Count",
detail = true,
data = {
sources = {
ps_count = { "threads", "processes" }
},
options = {
ps_count__threads = { color = "00ff00" },
ps_count__processes = { color = "0000bb" }
}
}
},
{
title = "%H: Page faults in %pi",
vlabel = "Pagefaults",
detail = true,
data = {
sources = {
ps_pagefaults = { "minflt", "majflt" }
},
options = {
ps_pagefaults__minflt = { color = "ff0000" },
ps_pagefaults__majflt = { color = "ff5500" }
}
}
},
{
title = "%H: Virtual memory size of %pi",
vlabel = "Bytes",
detail = true,
number_format = "%5.1lf%sB",
data = {
types = { "ps_rss" },
options = {
ps_rss = { color = "0000ff" }
}
}
}
}
end
| apache-2.0 |
AresTao/darkstar | scripts/zones/Port_Windurst/npcs/Pyo_Nzon.lua | 36 | 2750 | -----------------------------------
-- Area: Port Windurst
-- NPC: Pyo Nzon
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
TruthJusticeOnionWay = player:getQuestStatus(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY);
KnowOnesOnions = player:getQuestStatus(WINDURST,KNOW_ONE_S_ONIONS);
InspectorsGadget = player:getQuestStatus(WINDURST,INSPECTOR_S_GADGET);
OnionRings = player:getQuestStatus(WINDURST,ONION_RINGS);
CryingOverOnions = player:getQuestStatus(WINDURST,CRYING_OVER_ONIONS);
ThePromise = player:getQuestStatus(WINDURST,THE_PROMISE);
if (ThePromise == QUEST_COMPLETED) then
Message = math.random(0,1)
if (Message == 1) then
player:startEvent(0x021b);
else
player:startEvent(0x020f);
end
elseif (ThePromise == QUEST_ACCEPTED) then
player:startEvent(0x0205);
elseif (CryingOverOnions == QUEST_COMPLETED) then
player:startEvent(0x01fe);
elseif (CryingOverOnions == QUEST_ACCEPTED) then
player:startEvent(0x01f6);
elseif (OnionRings == QUEST_COMPLETED) then
player:startEvent(0x01bb);
elseif (OnionRings == QUEST_ACCEPTED ) then
player:startEvent(0x01b5);
elseif (InspectorsGadget == QUEST_COMPLETED) then
player:startEvent(0x01aa);
elseif (InspectorsGadget == QUEST_ACCEPTED) then
player:startEvent(0x01a2);
elseif (KnowOnesOnions == QUEST_COMPLETED) then
player:startEvent(0x0199);
elseif (KnowOnesOnions == QUEST_ACCEPTED) then
KnowOnesOnionsVar = player:getVar("KnowOnesOnions");
if (KnowOnesOnionsVar == 2) then
player:startEvent(0x0198);
else
player:startEvent(0x018c);
end
elseif (TruthJusticeOnionWay == QUEST_COMPLETED) then
player:startEvent(0x017e);
elseif (TruthJusticeOnionWay == QUEST_ACCEPTED) then
player:startEvent(0x0177);
else
player:startEvent(0x016e);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
AresTao/darkstar | scripts/globals/abilities/equanimity.lua | 28 | 1166 | -----------------------------------
-- Ability: Equanimity
-- Your next black magic spell will generate less enmity.
-- Obtained: Scholar Level 75
-- Recast Time: Stratagem Charge
-- Duration: 1 black magic spell or 60 seconds, whichever occurs first
--
-- Level |Charges |Recharge Time per Charge
-- ----- -------- ---------------
-- 10 |1 |4:00 minutes
-- 30 |2 |2:00 minutes
-- 50 |3 |1:20 minutes
-- 70 |4 |1:00 minute
-- 90 |5 |48 seconds
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if player:hasStatusEffect(EFFECT_EQUANIMITY) then
return MSGBASIC_EFFECT_ALREADY_ACTIVE, 0;
end
return 0,0;
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
player:addStatusEffect(EFFECT_EQUANIMITY,player:getMerit(MERIT_EQUANIMITY),0,60);
return EFFECT_EQUANIMITY;
end; | gpl-3.0 |
sandrinr/XCSoar | Data/Lua/gestures.lua | 4 | 2791 | -- Gestures -------------------------------------------------------------------
xcsoar.input_event.new("gesture_U",
function(e)
xcsoar.fire_legacy_event("Zoom","in");
e:cancel();
end
)
xcsoar.input_event.new("gesture_D",
function(e)
xcsoar.fire_legacy_event("Zoom","out");
end
)
xcsoar.input_event.new("gesture_UD",
function(e)
xcsoar.fire_legacy_event("Zoom","auto on");
xcsoar.fire_legacy_event("Zoom","auto show");
end
)
xcsoar.input_event.new("gesture_R",
function(e)
xcsoar.fire_legacy_event("ScreenModes","previous");
end
)
xcsoar.input_event.new("gesture_L",
function(e)
xcsoar.fire_legacy_event("ScreenModes","next");
end
)
xcsoar.input_event.new("gesture_DR",
function(e)
xcsoar.fire_legacy_event("WaypointDetails","select");
end
)
xcsoar.input_event.new("gesture_DL",
function(e)
xcsoar.fire_legacy_event("Setup","Alternates");
end
)
xcsoar.input_event.new("gesture_DU",
function(e)
xcsoar.fire_legacy_event("Mode","Menu");
end
)
xcsoar.input_event.new("gesture_RD",
function(e)
xcsoar.fire_legacy_event("Calculator");
end
)
xcsoar.input_event.new("gesture_URD",
function(e)
xcsoar.fire_legacy_event("Analysis");
end
)
xcsoar.input_event.new("gesture_LDR",
function(e)
xcsoar.fire_legacy_event("Checklist");
end
)
xcsoar.input_event.new("gesture_URDL",
function(e)
xcsoar.fire_legacy_event("Pan", "on");
end
)
xcsoar.input_event.new("gesture_LDRDL",
function(e)
xcsoar.fire_legacy_event("Status", "all");
end
)
| gpl-2.0 |
DeinFreund/Zero-K | LuaUI/Widgets/gui_chili_crudeplayerlist.lua | 1 | 29769 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "Chili Crude Player List",
desc = "v1.327 Chili Crude Player List.",
author = "CarRepairer",
date = "2011-01-06",
license = "GNU GPL, v2 or later",
layer = 50,
enabled = false,
}
end
if Spring.GetModOptions().singleplayercampaignbattleid then
return
end
VFS.Include ("LuaRules/Utilities/lobbyStuff.lua")
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local Chili
local Image
local Button
local Checkbox
local Window
local ScrollPanel
local StackPanel
local Label
local screen0
local color2incolor
local incolor2color
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local window_cpl, scroll_cpl
local colorNames = {}
local colors = {}
local showWins = false
local wins_width = 0
local green = ''
local red = ''
local orange = ''
local yellow = ''
local cyan = ''
local white = ''
local function IsFFA()
local allyteams = Spring.GetAllyTeamList()
local gaiaT = Spring.GetGaiaTeamID()
local gaiaAT = select(6, Spring.GetTeamInfo(gaiaT))
local numAllyTeams = 0
for i=1,#allyteams do
if allyteams[i] ~= gaiaAT then
local teams = Spring.GetTeamList(allyteams[i])
if #teams > 0 then
numAllyTeams = numAllyTeams + 1
end
end
end
return numAllyTeams > 2
end
local cf = (not Spring.FixedAllies()) and IsFFA()
if not WG.rzones then
WG.rzones = {
rZonePlaceMode = false
}
end
local x_wins = 0
local x_icon_country = x_wins + 20
local x_icon_rank = x_icon_country + 20
local x_icon_clan = x_icon_rank + 16
local x_cf = x_icon_clan + 16
local x_team = x_cf + 20
local x_name = x_team + 16
local x_share = x_name + 140
local x_cpu = x_share + 16
local x_ping = x_cpu + 16
local x_postwins = x_ping + 16
local UPDATE_FREQUENCY = 0.8 -- seconds
local wantsNameRefresh = {} -- unused
local cfCheckBoxes = {}
local allyTeams = {} -- [id] = {team1, team2, ...}
local teams = {} -- [id] = {leaderName = name, roster = {entity1, entity2, ...}}
-- entity = player (including specs) or bot
-- ordered list; contains isAI, isSpec, playerID, teamID, name, namelabel, cpuImg, pingImg
local entities = {}
local pingMult = 2/3 -- lower = higher ping needed to be red
pingCpuColors = {
{0, 1, 0, 1},
{0.7, 1, 0, 1},
{1, 1, 0, 1},
{1, 0.6, 0, 1},
{1, 0, 0, 1}
}
local sharePic = ":n:"..LUAUI_DIRNAME.."Images/playerlist/share.png"
local cpuPic = ":n:"..LUAUI_DIRNAME.."Images/playerlist/cpu.png"
local pingPic = ":n:"..LUAUI_DIRNAME.."Images/playerlist/ping.png"
--local show_spec = false
local localTeam = 0
local localAlliance = 0
include("keysym.h.lua")
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function SetupPlayerNames() end
options_path = 'Settings/HUD Panels/Player List'
options_order = {'text_height', 'backgroundOpacity', 'reset_wins', 'inc_wins_1', 'inc_wins_2','alignToTop','showSpecs','allyTeamPerTeam','debugMessages','mousewheel','win_show_condition'}
options = {
text_height = {
name = 'Font Size (10-18)',
type = 'number',
value = 13,
min = 10, max = 18, step = 1,
OnChange = function() SetupPlayerNames() end,
advanced = true
},
backgroundOpacity = {
name = "Background opacity",
type = "number",
value = 0, min = 0, max = 1, step = 0.01,
OnChange = function(self)
scroll_cpl.backgroundColor = {1,1,1,self.value}
scroll_cpl.borderColor = {1,1,1,self.value}
scroll_cpl:Invalidate()
end,
},
reset_wins = {
name = "Reset Wins",
desc = "Reset the win counts of all players",
type = 'button',
OnChange = function()
if WG.WinCounter_Reset ~= nil then
WG.WinCounter_Reset()
SetupPlayerNames()
end
end,
},
inc_wins_1 = {
name = "Increment Team 1 Wins",
desc = "",
type = 'button',
OnChange = function()
if WG.WinCounter_Increment ~= nil then
local allyTeams = Spring.GetAllyTeamList()
WG.WinCounter_Increment(allyTeams[1])
SetupPlayerNames()
end
end,
advanced = true
},
inc_wins_2 = {
name = "Increment Team 2 Wins",
desc = "",
type = 'button',
OnChange = function()
if WG.WinCounter_Increment ~= nil then
local allyTeams = Spring.GetAllyTeamList()
WG.WinCounter_Increment(allyTeams[2])
SetupPlayerNames()
end
end,
advanced = true
},
win_show_condition = {
name = 'Show Wins',
type = 'radioButton',
value = 'whenRelevant',
items = {
{key ='always', name='Always'},
{key ='whenRelevant', name='When someone has wins'},
{key ='never', name='Never'},
},
OnChange = function() SetupPlayerNames() end,
},
alignToTop = {
name = "Align to top",
type = 'bool',
value = false,
desc = "Align list entries to top (i.e. don't push to bottom)",
OnChange = function() SetupPlayerNames() end,
},
showSpecs = {
name = "Show spectators",
type = 'bool',
value = false,
desc = "Show spectators in main window (rather than confining them to tooltip. Note: tooltip might block mouse click in some cases)",
OnChange = function() SetupPlayerNames() end,
},
allyTeamPerTeam = {
name = "Display team for each player",
type = 'bool',
value = true,
desc = "Write the team number next to each player's name (rather than only for first player)",
OnChange = function() SetupPlayerNames() end,
},
debugMessages = {
name = "Enable debug messages",
type = 'bool',
value = false,
desc = "Enables some debug messages (disable if it starts flooding console)",
},
mousewheel = {
name = "Scroll with mousewheel",
type = 'bool',
value = true,
OnChange = function(self)
scroll_cpl.ignoreMouseWheel = not self.value;
end,
},
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function CheckShowWins()
return WG.WinCounter_currentWinTable ~= nil and (WG.WinCounter_currentWinTable.hasWins and options.win_show_condition.value == "whenRelevant") or options.win_show_condition.value == "always"
end
local function ShareUnits(playername, team)
local selcnt = Spring.GetSelectedUnitsCount()
if selcnt > 0 then
Spring.SendCommands("say a: I gave "..selcnt.." units to "..playername..".")
-- no point spam, thx
--[[local su = Spring.GetSelectedUnits()
for _,uid in ipairs(su) do
local ux,uy,uz = Spring.GetUnitPosition(uid)
Spring.MarkerAddPoint(ux,uy,uz)
end]]
Spring.ShareResources(team, "units")
else
Spring.Echo('Player List: No units selected to share.')
end
end
local function PingTimeOut(pingTime)
if pingTime < 1 then
return (math.floor(pingTime*1000) ..'ms')
elseif pingTime > 999 then
return ('' .. (math.floor(pingTime*100/60)/100)):sub(1,4) .. 'min'
end
--return (math.floor(pingTime*100))/100
return ('' .. (math.floor(pingTime*100)/100)):sub(1,4) .. 's' --needed due to rounding errors.
end
-- makes a color char from a color table
-- explanation for string.char: http://springrts.com/phpbb/viewtopic.php?f=23&t=24952
local function GetColorChar(colorTable)
if colorTable == nil then return string.char(255,255,255,255) end
local col = {}
for i=1,4 do
col[i] = math.ceil(colorTable[i]*255)
end
return string.char(col[4],col[1],col[2],col[3])
end
--[[
local function GetColorStr(colorTable)
if colorTable == nil then return "\255\255\255\255" end
end
]]--
-- ceasefire button tooltip
local function CfTooltip(allyTeam)
local tooltip = ''
if Spring.GetGameRulesParam('cf_' .. localAlliance .. '_' .. allyTeam) == 1 then
tooltip = tooltip .. green .. 'Ceasefire in effect.' .. white
else
local theyOffer = Spring.GetGameRulesParam('cf_offer_' .. localAlliance .. '_' .. allyTeam) == 1
local youOffer = Spring.GetGameRulesParam('cf_offer_' .. allyTeam.. '_' .. localAlliance) == 1
if theyOffer then
tooltip = tooltip .. yellow .. 'They have offered a ceasefire.' .. white .. '\n'
end
if youOffer then
tooltip = tooltip .. cyan .. 'Your team has offered a ceasefire.' .. white .. '\n'
end
tooltip = tooltip .. red .. 'No ceasefire in effect.' .. white
end
tooltip = tooltip .. '\n\n'
tooltip = tooltip .. 'Your team\'s votes: \n'
local teamList = Spring.GetTeamList(localAlliance)
for _,teamID in ipairs(teamList) do
local _,playerID = Spring.GetTeamInfo(teamID)
local name = Spring.GetPlayerInfo(playerID) or '-'
local vote = Spring.GetTeamRulesParam(teamID, 'cf_vote_' ..allyTeam)==1 and green..'Y'..white or red..'N'..white
local teamColor = color2incolor(Spring.GetTeamColor(teamID))
tooltip = tooltip .. teamColor .. ' <' .. name .. '> ' .. white.. vote ..'\n'
end
tooltip = tooltip .. '\n'
tooltip = tooltip .. 'Check this box to vote for a ceasefire with '.. yellow ..'<Team ' .. (allyTeam+1) .. '>'..white..'. \n\n'
..'If everyone votes Yes, an offer will be made. If there is a ceasefire, '
..'unchecking the box will break it.'
return tooltip
end
-- spectator tooltip
-- not shown if they're in playerlist as well
local function MakeSpecTooltip()
if options.showSpecs.value then
scroll_cpl.tooltip = nil
return
end
local players = Spring.GetPlayerList()
local specsSorted = {}
for i = 1, #players do
local name, active, spectator, teamID, allyTeamID, pingTime, cpuUsage = Spring.GetPlayerInfo(players[i])
if spectator and active then
specsSorted[#specsSorted + 1] = {name = name, ping = pingTime, cpu = math.min(cpuUsage,1)}
--specsSorted[#specsSorted + 1] = {name = name, ping = pingTime, cpu = cpuUsage}
end
end
table.sort(specsSorted, function(a,b)
return a.name:lower() < b.name:lower()
end)
local windowTooltip = "SPECTATORS"
for i=1,#specsSorted do
local cpuCol = pingCpuColors[ math.ceil( specsSorted[i].cpu * 5 ) ]
cpuCol = GetColorChar(cpuCol)
local pingCol = pingCpuColors[ math.ceil( math.min(specsSorted[i].ping*pingMult,1) * 5 ) ]
pingCol = GetColorChar(pingCol)
local cpu = math.round(specsSorted[i].cpu*100)
windowTooltip = windowTooltip .. "\n\t"..specsSorted[i].name.."\t"..cpuCol..(cpu)..'%\008' .. "\t"..pingCol..PingTimeOut(specsSorted[i].ping).."\008"
end
scroll_cpl.tooltip = windowTooltip --tooltip in display region only (window_cpl have soo much waste space)
end
-- updates ping and CPU for all players; name if needed
local function UpdatePlayerInfo()
for i = 1, #entities do
if not entities[i].isAI then
local playerID = entities[i].playerID
local name, active, spectator, teamID, allyTeamID, pingTime, cpuUsage = Spring.GetPlayerInfo(playerID)
--Spring.Echo("Player Update", playerID, name, active, spectator, teamID, allyTeamID, pingTime, cpuUsage, #(Spring.GetPlayerList(teamID, true)))
local name_out = name or ''
if name_out == '' or #(Spring.GetPlayerList(teamID, true)) == 0 or (spectator and not entities[i].isSpec) or Spring.GetTeamRulesParam(teamID, "isDead") == 1 then
if Spring.GetGameSeconds() < 0.1 or cpuUsage > 1 then
name_out = "<Waiting> " ..(name or '')
elseif Spring.GetTeamUnitCount(teamID) > 0 then
name_out = "<Aband. units> " .. (name or '')
else
name_out = "<Dead> " .. (name or '')
end
end
if entities[i].nameLabel then
entities[i].nameLabel:SetCaption(name_out)
end
if ((not spectator) or options.showSpecs.value) then
-- update ping and CPU
pingTime = pingTime or 0
cpuUsage = cpuUsage or 0
local min_pingTime = math.min(pingTime, 1)
local min_cpuUsage = math.min(cpuUsage, 1)
local cpuColIndex = math.ceil( min_cpuUsage * 5 )
local pingColIndex = math.ceil( min_pingTime * 5 )
local pingTime_readable = PingTimeOut(pingTime)
local blank = not active
local cpuImg = entities[i].cpuImg
if cpuImg then
cpuImg.tooltip = (blank and nil or 'CPU: ' .. math.round(cpuUsage*100) .. '%')
if cpuColIndex ~= entities[i].cpuIndexOld then
entities[i].cpuIndexOld = cpuColIndex
cpuImg.color = pingCpuColors[cpuColIndex]
cpuImg:Invalidate()
end
end
local pingImg = entities[i].pingImg
if pingImg then
pingImg.tooltip = (blank and nil or 'Ping: ' .. pingTime_readable)
if pingColIndex ~= entities[i].pingIndexOld then
entities[i].pingIndexOld = pingColIndex
pingImg.color = pingCpuColors[pingColIndex]
pingImg:Invalidate()
end
end
end
local wins = 0
if name ~= nil and WG.WinCounter_currentWinTable ~= nil and WG.WinCounter_currentWinTable[name] ~= nil then
wins = WG.WinCounter_currentWinTable[name].wins
end
if entities[i].winsLabel then
entities[i].winsLabel:SetCaption(wins)
end
end -- if not isAI
end -- for entities
MakeSpecTooltip()
for allyTeam, cb in pairs(cfCheckBoxes) do
cb.tooltip = CfTooltip(allyTeam)
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function AddCfCheckbox(allyTeam)
local fontsize = options.text_height.value
if cf and allyTeam ~= -1 and allyTeam ~= localAlliance then
local cfCheck = Checkbox:New{
x=x_cf,y=(fontsize+1) * row + 3,width=20,
caption='',
checked = Spring.GetTeamRulesParam(localTeam, 'cf_vote_' ..allyTeam)==1,
tooltip = CfTooltip(allyTeam),
OnChange = { function(self)
Spring.SendLuaRulesMsg('ceasefire:'.. (self.checked and 'n' or 'y') .. ':' .. allyTeam)
self.tooltip = CfTooltip(allyTeam)
end },
}
scroll_cpl:AddChild(cfCheck)
cfCheckBoxes[allyTeam] = cfCheck
end
end
local function WriteAllyTeamNumbers(allyTeam)
local fontsize = options.text_height.value
local aCol = {1,0,0,1}
if allyTeam == -1 then
aCol = {1,1,1,1}
elseif allyTeam == localAlliance then
aCol = {0,1,1,1}
elseif Spring.GetGameRulesParam('cf_' .. localAlliance .. '_' .. allyTeam) == 1 then
aCol = {0,1,0,1}
elseif Spring.GetGameRulesParam('cf_offer_' .. localAlliance .. '_' .. allyTeam) == 1 then
aCol = {1,0.5,0,1}
end
-- allyteam number
scroll_cpl:AddChild(
Label:New{
x=x_team,
y=(fontsize+1) * row,
caption = (allyTeam == -1 and 'S' or allyTeam+1),
textColor = aCol,
fontsize = fontsize,
fontShadow = true,
autosize = false,
}
)
end
-- adds all the entity information
local function AddEntity(entity, teamID, allyTeamID)
local fontsize = options.text_height.value
local deadTeam = false
if entity == nil then
entity = {}
deadTeam = true
end
local name,active,spectator,pingTime,cpuUsage,country,_, customKeys
local playerID = entity.playerID or teams[teamID].leader
if playerID then
name,active,spectator,_,_,pingTime,cpuUsage,country,_, customKeys = Spring.GetPlayerInfo(playerID)
end
--Spring.Echo("Entity with team ID " .. teamID .. " is " .. (active and '' or "NOT ") .. "active")
if not active then deadTeam = true end
pingTime = pingTime or 0
cpuUsage = cpuUsage or 0
local name_out = entity.name or ''
if (name_out == '' or deadTeam or (spectator and teamID >= 0)) and not entity.isAI then
if Spring.GetGameSeconds() < 0.1 or cpuUsage > 1 then
name_out = "<Waiting> " ..(name or '')
elseif Spring.GetTeamUnitCount(teamID) > 0 then
name_out = "<Aband. units> " ..(name or '')
else
name_out = "<Dead> " ..(name or '')
end
end
local icon = nil
local icRank = nil
local icCountry = country and country ~= '' and "LuaUI/Images/flags/" .. (country) .. ".png" or nil
-- clan/faction emblems, level, country
if (not entity.isAI and customKeys ~= nil) then
if (customKeys.clan~=nil and customKeys.clan~="") then
icon = "LuaUI/Configs/Clans/" .. customKeys.clan ..".png"
elseif (customKeys.faction~=nil and customKeys.faction~="") then
icon = "LuaUI/Configs/Factions/" .. customKeys.faction ..".png"
end
icRank = "LuaUI/Images/LobbyRanks/" .. (customKeys.icon or "0_0") .. ".png"
end
local min_pingTime = math.min(pingTime, 1)
local min_cpuUsage = math.min(cpuUsage, 1)
local cpuCol = pingCpuColors[ math.ceil( min_cpuUsage * 5 ) ]
local pingCol = pingCpuColors[ math.ceil( min_pingTime * 5 ) ]
local pingTime_readable = PingTimeOut(pingTime)
local wins = 0
if name ~= nil and WG.WinCounter_currentWinTable ~= nil and WG.WinCounter_currentWinTable[name] ~= nil then wins = WG.WinCounter_currentWinTable[name].wins end
if not entity.isAI then
-- flag
if icCountry ~= nil then
scroll_cpl:AddChild(
Chili.Image:New{
file=icCountry;
width= fontsize + 3;
height=fontsize + 3;
x=x_icon_country,
y=(fontsize+1) * row,
}
)
end
-- level-based rank
if icRank ~= nil then
scroll_cpl:AddChild(
Chili.Image:New{
file=icRank;
width= fontsize + 3;
height=fontsize + 3;
x=x_icon_rank,
y=(fontsize+1) * row,
}
)
end
-- clan icon
if icon ~= nil then
scroll_cpl:AddChild(
Chili.Image:New{
file=icon;
width= fontsize + 3;
height=fontsize + 3;
x=x_icon_clan,
y=(fontsize+1) * row,
}
)
end
end
-- name
local nameLabel = Label:New{
x=x_name,
y=(fontsize+1) * row,
width=150,
autosize=false,
--caption = (spectator and '' or ((teamID+1).. ') ') ) .. name, --do not remove, will add later as option
caption = name_out,
realText = name_out,
textColor = teamID and {Spring.GetTeamColor(teamID)} or {1,1,1,1},
fontsize = fontsize,
fontShadow = true,
}
entity.nameLabel = nameLabel
scroll_cpl:AddChild(nameLabel)
-- because for some goddamn stupid reason the names won't show otherwise
nameLabel:UpdateLayout()
nameLabel:Invalidate()
-- share button
if active and allyTeamID == localAlliance and teamID ~= localTeam then
scroll_cpl:AddChild(
Button:New{
x=x_share,
y=(fontsize+1) * (row+0.5)-2.5,
height = fontsize,
width = fontsize,
tooltip = 'Double click to share selected units to ' .. name,
caption = '',
padding ={0,0,0,0},
OnDblClick = { function(self) ShareUnits(name, teamID) end, },
children = {
Image:New{
x=0,y=0,
height='100%',
width='100%',
file = sharePic,
},
},
}
)
end
-- CPU, ping
if not (entity.isAI) then
local cpuImg = Image:New{
x=x_cpu,
y=(fontsize+1) * row,
height = (fontsize+3),
width = (fontsize+3)*10/16,
tooltip = 'CPU: ' .. math.round(cpuUsage*100) .. '%',
file = cpuPic,
keepAspect = false,
}
function cpuImg:HitTest(x,y) return self end
entity.cpuImg = cpuImg
scroll_cpl:AddChild(cpuImg)
local pingImg = Image:New{
x=x_ping,
y=(fontsize+1) * row,
height = (fontsize+3),
width = (fontsize+3)*10/16,
tooltip = 'Ping: ' .. pingTime_readable,
file = pingPic,
keepAspect = false,
}
function pingImg:HitTest(x,y) return self end
entity.pingImg = pingImg
scroll_cpl:AddChild(pingImg)
if showWins and WG.WinCounter_currentWinTable ~= nil and WG.WinCounter_currentWinTable[name] ~= nil then
local winsLabel = Label:New{
x=x_wins,
y=(fontsize+1) * row,
width=20,
autosize=false,
--caption = (spectator and '' or ((teamID+1).. ') ') ) .. name, --do not remove, will add later as option
caption = wins,
realText = wins,
textColor = teamID and {Spring.GetTeamColor(teamID)} or {1,1,1,1},
fontsize = fontsize,
fontShadow = true,
}
scroll_cpl:AddChild(winsLabel)
end
end
row = row + 1
end
-- adds: ally team number if applicable
local function AddTeam(teamID, allyTeamID)
if options.allyTeamPerTeam.value then
WriteAllyTeamNumbers(allyTeamID)
end
-- add each entity in the team
local count = #teams[teamID].roster
if count == 0 then
AddEntity(nil, teamID, allyTeamID)
return
end
for i=1,count do
AddEntity(teams[teamID].roster[i], teamID, allyTeamID)
end
end
-- adds: ally team number if applicable, ceasefire button
local function AddAllyTeam(allyTeamID)
if #(allyTeams[allyTeamID] or {}) == 0 then
return
end
-- sort teams by leader name, putting own team at top
--table.sort(allyTeams[allyTeamID], function(a,b)
-- if a == localTeam then return true
-- elseif b == localTeam then return false end
-- return a.name:lower() < b.name:lower()
-- end)
if not options.allyTeamPerTeam.value then
WriteAllyTeamNumbers(allyTeamID)
end
AddCfCheckbox(allyTeamID)
-- add each team in the allyteam
for i=1,#allyTeams[allyTeamID] do
AddTeam(allyTeams[allyTeamID][i], allyTeamID)
end
end
local function AlignScrollPanel()
--push things to bottom of window if needed
local height = math.ceil(row * (options.text_height.value+1.5) + 10)
if height < window_cpl.height then
scroll_cpl.height = height
scroll_cpl.verticalScrollbar = false
else
scroll_cpl.height = window_cpl.height
scroll_cpl.verticalScrollbar = true
end
if not (options.alignToTop.value) then
scroll_cpl.y = (window_cpl.height) - scroll_cpl.height - 2
else
scroll_cpl.y = 0
end
end
SetupPlayerNames = function()
showWins = CheckShowWins()
if options.debugMessages.value then
Spring.Echo("Generating playerlist")
end
entities = {}
teams = {}
allyTeams = {}
local specTeam = {roster = {}}
local fontsize = options.text_height.value
scroll_cpl:ClearChildren()
scroll_cpl:AddChild( Label:New{ x=x_team, caption = 'T', fontShadow = true, fontsize = fontsize, } )
if cf then
scroll_cpl:AddChild( Label:New{ x=x_cf, caption = 'CF', fontShadow = true, fontsize = fontsize, } )
end
scroll_cpl:AddChild( Label:New{ x=x_name, caption = 'Name', fontShadow = true, fontsize = fontsize,} )
scroll_cpl:AddChild( Label:New{ x=x_cpu, caption = 'C', fontShadow = true, fontsize = fontsize,} )
scroll_cpl:AddChild( Label:New{ x=x_ping, caption = 'P', fontShadow = true, fontsize = fontsize,} )
if showWins then scroll_cpl:AddChild( Label:New{ x=x_wins, caption = 'W', fontShadow = true, fontsize = fontsize,} ) end
local playerlist = Spring.GetPlayerList()
local teamsSorted = Spring.GetTeamList()
local allyTeamsSorted = Spring.GetAllyTeamList()
local myID = Spring.GetMyPlayerID()
local myName = Spring.GetPlayerInfo(myID)
localTeam = Spring.GetMyTeamID()
localAlliance = Spring.GetMyAllyTeamID()
-- register any AIs as entities, assign teams to allyTeams
for i = 1, #teamsSorted do
local teamID = teamsSorted[i]
if teamID ~= Spring.GetGaiaTeamID() then
teams[teamID] = teams[teamID] or {roster = {}}
local _,leader,isDead,isAI,_,allyTeamID = Spring.GetTeamInfo(teamID)
if isAI then
local skirmishAIID, name, hostingPlayerID, shortName, version, options = Spring.GetAIInfo(teamID)
name = '<'.. name ..'> '.. shortName
local entityID = #entities + 1
entities[entityID] = {name = name, teamID = teamID, isAI = true}
local index = #teams[teamID].roster + 1
teams[teamID].roster[index] = entities[entityID]
end
teams[teamID].leader = leader
allyTeams[allyTeamID] = allyTeams[allyTeamID] or {}
allyTeams[allyTeamID][#allyTeams[allyTeamID]+1] = teamID
end --if teamID ~= Spring.GetGaiaTeamID()
end --for each team
-- go through all players, register as entities, assign to teams
for i = 1, #playerlist do
local playerID = playerlist[i]
local name, active, spectator, teamID, allyTeamID, pingTime, cpuUsage, country = Spring.GetPlayerInfo(playerID)
local isSpec = (teamID == 0 and spectator and (not Spring.GetGameRulesParam("initiallyPlayingPlayer_" .. playerID)))
local entityID = #entities + 1
entities[entityID] = {name = name, isSpec = isSpec, playerID = playerID, teamID = teamID}--(not spectator) and teamID or nil}
if not isSpec then
local index = #teams[teamID].roster + 1
teams[teamID].roster[index] = entities[entityID]
end
if active and spectator then
specTeam.roster[#(specTeam.roster) + 1] = entities[entityID]
end
end
-- sort allyteams: own at top, others in order
table.sort(allyTeamsSorted,
function(a,b)
if a == localAlliance then return true
elseif b == localAlliance then return false end
return a < b
end
)
row = 1
for i = 1, #allyTeamsSorted do
AddAllyTeam(allyTeamsSorted[i])
end
if options.showSpecs.value and #specTeam.roster ~= 0 then
teams[-1] = specTeam
allyTeams[-1] = {-1}
AddAllyTeam(-1)
else
MakeSpecTooltip()
end
--[[
scroll_cpl:AddChild( Checkbox:New{
x=5, y=fontsize * (row + 0.5),
height=fontsize * 1.5, width=160,
caption = 'Show Spectators',
checked = show_spec,
OnChange = { function(self) show_spec = not self.checked; SetupPlayerNames(); end },
} )
row = row + 1
]]--
-- ceasefire: restricted zones button
if cf then
scroll_cpl:AddChild( Checkbox:New{
x=5, y=(fontsize+1) * (row + 0.5),
height=fontsize * 1.5, width=160,
caption = 'Place Restricted Zones',
checked = WG.rzones.rZonePlaceMode,
OnChange = { function(self) WG.rzones.rZonePlaceMode = not WG.rzones.rZonePlaceMode; end },
} )
row = row + 1.5
end
AlignScrollPanel()
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:Shutdown()
Spring.SendCommands({"info 1"})
end
local timer = 0
local lastSizeX
local lastSizeY
function widget:Update(s)
timer = timer + s
if timer > UPDATE_FREQUENCY then
timer = 0
if (window_cpl.hidden) then --//don't update when window is hidden.
return
end
if (lastSizeX ~= window_cpl.width or lastSizeY ~= window_cpl.height) then --//if user resize the player-list OR if the simple-color state have changed, then refresh the player list.
AlignScrollPanel()
lastSizeX = window_cpl.width
lastSizeY = window_cpl.height
else
if showWins ~= CheckShowWins() then
SetupPlayerNames()
end
UpdatePlayerInfo()
end
end
end
function widget:PlayerChanged(playerID)
SetupPlayerNames()
end
function widget:PlayerAdded(playerID)
SetupPlayerNames()
end
function widget:PlayerRemoved(playerID)
SetupPlayerNames()
end
function widget:TeamDied(teamID)
SetupPlayerNames()
end
function widget:TeamChanged(teamID)
SetupPlayerNames()
end
-- workaround for stupidity
function widget:GameStart()
SetupPlayerNames()
end
-----------------------------------------------------------------------
function widget:Initialize()
if not WG.Chili then
widgetHandler:RemoveWidget()
return
end
Chili = WG.Chili
Image = Chili.Image
Button = Chili.Button
Checkbox = Chili.Checkbox
Window = Chili.Window
ScrollPanel = Chili.ScrollPanel
StackPanel = Chili.StackPanel
Label = Chili.Label
screen0 = Chili.Screen0
color2incolor = Chili.color2incolor
incolor2color = Chili.incolor2color
green = color2incolor(0,1,0,1)
red = color2incolor(1,0,0,1)
orange = color2incolor(1,0.4,0,1)
yellow = color2incolor(1,1,0,1)
cyan = color2incolor(0,1,1,1)
white = color2incolor(1,1,1,1)
-- Set the size for the default settings.
local screenWidth,screenHeight = Spring.GetWindowGeometry()
local x_bound = 310
window_cpl = Window:New{
dockable = true,
name = "Player List",
color = {0,0,0,0},
right = 0,
bottom = 0,
width = x_bound,
height = 150,
padding = {8, 2, 2, 2};
--autosize = true;
parent = screen0,
draggable = false,
resizable = false,
tweakDraggable = true,
tweakResizable = true,
parentWidgetName = widget:GetInfo().name, --for gui_chili_docking.lua (minimize function)
minWidth = x_bound,
}
scroll_cpl = ScrollPanel:New{
parent = window_cpl,
width = "100%",
maxWidth = x_bound, --in case window_cpl is upsized to ridiculous size
--height = "100%",
backgroundColor = {1,1,1,options.backgroundOpacity.value},
borderColor = {1,1,1,options.backgroundOpacity.value},
--padding = {0, 0, 0, 0},
--autosize = true,
scrollbarSize = 6,
horizontalScrollbar = false,
ignoreMouseWheel = not options.mousewheel.value,
NCHitTest = function(self,x,y)
local alt,ctrl, meta,shift = Spring.GetModKeyState()
local _,_,lmb,mmb,rmb = Spring.GetMouseState()
if (shift or ctrl or alt) or (mmb or rmb) or ((not self.tooltip or self.tooltip=="") and not (meta and lmb)) then --hover over window will intercept mouse, pressing right-mouse or middle-mouse or shift or ctrl or alt will stop intercept
return false
end
return self --mouse over panel
end,
OnMouseDown={ function(self)
local alt, ctrl, meta, shift = Spring.GetModKeyState()
if not meta then return false end
WG.crude.OpenPath(options_path)
WG.crude.ShowMenu()
return true
end },
}
function scroll_cpl:IsAboveVScrollbars(x, y) -- this override default Scrollpanel's HitTest. It aim to: reduce chance of click stealing. It exclude any modifier key (shift,alt,ctrl, except spacebar which is used for Space+click shortcut), and only allow left-click to reposition the vertical scrollbar
local alt,ctrl, meta,shift = Spring.GetModKeyState()
if (x< self.width - self.scrollbarSize) or (shift or ctrl or alt) or (not select(3,Spring.GetMouseState())) then
return false
end
return self
end
SetupPlayerNames()
Spring.SendCommands({"info 0"})
lastSizeX = window_cpl.width
lastSizeY = window_cpl_height
WG.LocalColor = WG.LocalColor or {}
WG.LocalColor.listeners = WG.LocalColor.listeners or {}
WG.LocalColor.listeners["Chili Crude Playerlist"] = SetupPlayerNames
end
function widget:Shutdown()
if WG.LocalColor and WG.LocalColor.listeners then
WG.LocalColor.listeners["Chili Crude Playerlist"] = nil
end
end
| gpl-2.0 |
AresTao/darkstar | scripts/globals/items/quus.lua | 18 | 1314 | -----------------------------------------
-- ID: 5793
-- Item: quus
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 2
-- Mind -4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 7) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5793);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 2);
target:addMod(MOD_MND, -4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 2);
target:delMod(MOD_MND, -4);
end;
| gpl-3.0 |
DeinFreund/Zero-K | scripts/pw_wormhole.lua | 5 | 1839 | include "constants.lua"
local base = piece('base')
local panel1, panel2 = piece('pannel1', 'pannel2')
local slider1, slider2, focal1, focal2 = piece('slider1', 'slider2', 'focal1', 'focal2')
local wheel1, wheel2 = piece('wheel1', 'wheel2')
local turret, cylinder, cannon, cannonbase = piece('turret', 'cylinder', 'canon', 'canonbase')
local drone = piece('drone')
local spin = math.rad(60)
local function SliderAnim(piece, reverse)
local dist = 9 * (reverse and -1 or 1)
while true do
Move(piece, z_axis, dist, 4)
WaitForMove(piece, z_axis)
Move(piece, z_axis, -dist, 4)
WaitForMove(piece, z_axis)
end
end
function script.Create()
if Spring.GetUnitRulesParam(unitID, "planetwarsDisable") == 1 or GG.applyPlanetwarsDisable then
return
end
Spin(wheel1, x_axis, spin)
Spin(wheel2, x_axis, spin)
--StartThread(SliderAnim, slider1)
--StartThread(SliderAnim, slider2)
Spin(focal1, y_axis, spin)
Spin(focal2, y_axis, -spin)
end
function script.AimFromWeapon(num)
return drone
end
-- fake weapon, do not fire
function script.AimWeapon(num)
return false
end
function script.QueryWeapon(num)
return drone
end
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage/maxHealth
if severity < .5 then
Explode(base, sfxNone)
Explode(wheel1, sfxNone)
Explode(wheel2, sfxNone)
Explode(slider1, sfxNone)
Explode(slider2, sfxNone)
--Explode(focal1, sfxFall)
--Explode(focal2, sfxFall)
--Explode(panel1, sfxFall)
--Explode(panel2, sfxFall)
return 1
else
Explode(base, sfxShatter)
Explode(wheel1, sfxShatter)
Explode(wheel2, sfxShatter)
Explode(slider1, sfxFall + sfxSmoke + sfxFire)
Explode(slider2, sfxFall + sfxSmoke + sfxFire)
Explode(panel1, sfxFall + sfxSmoke + sfxFire)
Explode(panel2, sfxFall + sfxSmoke + sfxFire)
return 2
end
end | gpl-2.0 |
AresTao/darkstar | scripts/globals/abilities/celerity.lua | 28 | 1156 | -----------------------------------
-- Ability: Celerity
-- Reduces the casting time and the recast time of your next white magic spell by 50%.
-- Obtained: Scholar Level 25
-- Recast Time: Stratagem Charge
-- Duration: 1 white magic spell or 60 seconds, whichever occurs first.
--
-- Level |Charges |Recharge Time per Charge
-- ----- -------- ---------------
-- 10 |1 |4:00 minutes
-- 30 |2 |2:00 minutes
-- 50 |3 |1:20 minutes
-- 70 |4 |1:00 minute
-- 90 |5 |48 seconds
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if player:hasStatusEffect(EFFECT_CELERITY) then
return MSGBASIC_EFFECT_ALREADY_ACTIVE, 0;
end
return 0,0;
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
player:addStatusEffect(EFFECT_CELERITY,1,0,60);
return EFFECT_CELERITY;
end; | gpl-3.0 |
AresTao/darkstar | scripts/zones/Rabao/npcs/HomePoint#1.lua | 17 | 1235 | -----------------------------------
-- Area: Rabao
-- NPC: HomePoint#1
-- @pos -29.276 0.001 -76.585 247
-----------------------------------
package.loaded["scripts/zones/Rabao/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Rabao/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 42);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
AresTao/darkstar | scripts/zones/East_Ronfaure_[S]/npcs/Logging_Point.lua | 29 | 1113 | -----------------------------------
-- Area: East Ronfaure [S]
-- NPC: Logging Point
-----------------------------------
package.loaded["scripts/zones/East_Ronfaure_[S]/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/logging");
require("scripts/zones/East_Ronfaure_[S]/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
startLogging(player,player:getZoneID(),npc,trade,0x0385);
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(LOGGING_IS_POSSIBLE_HERE,1021);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
soroushwilson/soroush | plugins/stickermarker.lua | 28 | 2159 | local function run(msg, matches)
local text = URL.escape(matches[1])
local color = 'blue'
if matches[2] == 'red' then
color = 'red'
elseif matches[2] == 'black' then
color = 'black'
elseif matches[2] == 'blue' then
color = 'blue'
elseif matches[2] == 'green' then
color = 'green'
elseif matches[2] == 'yellow' then
color = 'yellow'
elseif matches[2] == 'pink' then
color = 'magenta'
elseif matches[2] == 'orange' then
color = 'Orange'
elseif matches[2] == 'brown' then
color = 'DarkOrange'
end
local font = 'mathrm'
if matches[3] == 'bold' then
font = 'mathbf'
elseif matches[3] == 'italic' then
font = 'mathit'
elseif matches[3] == 'fun' then
font = 'mathfrak'
elseif matches[1] == 'arial' then
font = 'mathrm'
end
local size = '700'
if matches[4] == 'small' then
size = '300'
elseif matches[4] == 'larg' then
size = '700'
end
local url = 'http://latex.codecogs.com/png.latex?'..'\\dpi{'..size..'}%20\\huge%20\\'..font..'{{\\color{'..color..'}'..text..'}}'
local file = download_to_file(url,'file.webp')
if msg.to.type == 'channel' then
send_document('channel#id'..msg.to.id,file,ok_cb,false)
else
send_document('chat#id'..msg.to.id,file,ok_cb,false)
end
end
return {
patterns = {
"^[/!#]sticker (.*) ([^%s]+) (.*) (small)$",
"^[/!#]sticker (.*) ([^%s]+) (.*) (larg)$",
"^[/!#]sticker (.*) ([^%s]+) (bold)$",
"^[/!#]sticker (.*) (bold)$",
"^[/!#]sticker (.*) ([^%s]+) (italic)$",
"^[/!#]sticker (.*) ([^%s]+) (fun)$",
"^[/!#]sticker (.*) ([^%s]+) (arial)$",
"^[/!#]sticker (.*) (red)$",
"[/!#]sticker (.*) (black)$",
"^[/!#]sticker (.*) (blue)$",
"^[/!#]sticker (.*) (green)$",
"^[/!#]sticker (.*) (yellow)$",
"^[/!#]sticker (.*) (pink)$",
"^[/!#]sticker (.*) (orange)$",
"^[/!#]sticker (.*) (brown)$",
"^[/!#]sticker +(.*)$",
},
run = run
}
| gpl-2.0 |
AresTao/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Iruki-Waraki.lua | 38 | 2851 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Iruki-Waraki
-- Type: Standard NPC
-- Involved in quest: No Strings Attached
-- @pos 101.329 -6.999 -29.042 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local NoStringsAttached = player:getQuestStatus(AHT_URHGAN,NO_STRINGS_ATTACHED);
local NoStringsAttachedProgress = player:getVar("NoStringsAttachedProgress");
if (NoStringsAttached == 1 and NoStringsAttachedProgress == 1) then
player:startEvent(0x0104); -- he tells u to get him an automaton
elseif (NoStringsAttached == 1 and NoStringsAttachedProgress == 2) then
player:startEvent(0x0105); -- reminder to get an automaton
elseif (NoStringsAttached == 1 and NoStringsAttachedProgress == 6) then
player:startEvent(0x010a); -- you bring him the automaton
elseif (NoStringsAttached == 2) then
player:startEvent(0x010b); -- asking you how are you doing with your automaton
-- In case a player completed the quest before unlocking attachments was implemented (no harm in doing this repeatedly)
player:unlockAttachment(8224); --Harlequin Frame
player:unlockAttachment(8193); --Harlequin Head
else
player:startEvent(0x0103); -- Leave him alone
end;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0104) then
player:setVar("NoStringsAttachedProgress",2);
elseif (csid == 0x010a) then
if (player:getFreeSlotsCount() ~= 0) then
player:completeQuest(AHT_URHGAN,NO_STRINGS_ATTACHED);
player:addTitle(PROUD_AUTOMATON_OWNER);
player:unlockJob(18);
player:addItem(17859);
player:messageSpecial(ITEM_OBTAINED,17859); -- animator
player:messageSpecial(5699); -- "You can now become a puppetmaster."
player:setVar("NoStringsAttachedProgress",0);
player:setPetName(PETTYPE_AUTOMATON, option+118);
player:unlockAttachment(8224); --Harlequin Frame
player:unlockAttachment(8193); --Harlequin Head
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17859);
end;
end;
end;
| gpl-3.0 |
AresTao/darkstar | scripts/zones/RuAun_Gardens/Zone.lua | 28 | 15340 | -----------------------------------
--
-- Zone: RuAun_Gardens (130)
--
-----------------------------------
package.loaded["scripts/zones/RuAun_Gardens/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/missions");
require("scripts/globals/conquest");
require("scripts/zones/RuAun_Gardens/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
local manuals = {17310100,17310101,17310102,17310103,17310104,17310105};
SetFieldManual(manuals);
-- Blue portal timers (2 minutes)
-- counterclockwise
SetServerVariable("Main-to-Seiryu-BlueTeleport",0);
SetServerVariable("Seiryu-to-Genbu-BlueTeleport",0);
SetServerVariable("Genbu-to-Byakko-BlueTeleport",0);
SetServerVariable("Byakko-to-Suzaku-BlueTeleport",0);
SetServerVariable("Suzaku-to-Main-BlueTeleport",0);
-- clockwise
SetServerVariable("Main-to-Suzaku-BlueTeleport",0);
SetServerVariable("Suzaku-to-Byakko-BlueTeleport",0);
SetServerVariable("Byakko-to-Genbu-BlueTeleport",0);
SetServerVariable("Genbu-to-Seiryu-BlueTeleport",0);
SetServerVariable("Seiryu-to-Main-BlueTeleport",0);
------------------------------
-- Red teleports
------------------------------
zone:registerRegion(1,-3,-54,-583,1,-50,-579);
zone:registerRegion(2,147,-26,-449,151,-22,-445);
zone:registerRegion(3,186,-43,-405,190,-39,-401);
zone:registerRegion(4,272,-42,-379,276,-38,-375);
zone:registerRegion(5,306,-39,-317,310,-35,-313);
zone:registerRegion(6,393,-39,193,397,-35,197);
zone:registerRegion(7,62,-39,434,66,-35,438);
zone:registerRegion(8,-2,-42,464,2,-38,468);
zone:registerRegion(9,-65,-39,434,-61,-35,438);
zone:registerRegion(10,-397,-39,193,-393,-35,197);
zone:registerRegion(11,-445,-42,142,-441,-38,146);
zone:registerRegion(12,-276,-42,-379,-272,-38,-375);
zone:registerRegion(13,-191,-43,-405,-187,-39,-401);
zone:registerRegion(14,-151,-26,-449,-147,-22,-445);
zone:registerRegion(15,543,-73,-19,547,-69,-15);
zone:registerRegion(16,182,-73,511,186,-69,515);
zone:registerRegion(17,-432,-73,332,-428,-69,336);
zone:registerRegion(18,-453,-73,-308,-449,-69,-304);
zone:registerRegion(19,-436,-39,71,-432,-35,75);
zone:registerRegion(20,-310,-39,-317,-306,-35,-313);
zone:registerRegion(21,441,-42,142,445,-38,146);
zone:registerRegion(22,432,-39,71,436,-35,75);
------------------------------
-- Blue teleports
------------------------------
zone:registerRegion(23,162.5,-31,-353.5,168.5,-30,-347.5); -- Main To Seriyu
zone:registerRegion(24,374.5,-25,61.5,380.5,-24,67.5); -- Seriyu to Genbu
zone:registerRegion(25,52.5,-25,376.5,58.5,-24,382.5); -- Genbu to Byakko
zone:registerRegion(26,-346.5,-25,166.5,-340.5,-24,172.5); -- Byakko to Suzaku
zone:registerRegion(27,-270.5,-25,-277.5,-264.5,-24,-271.5); -- Suzaku to Main
zone:registerRegion(28,-170,-31,-354.4,-162,-30,-347.2); -- Main to Suzaku
zone:registerRegion(29,-381,-25,61.5,-374.5,-24,67.5); -- Suzaku to Byakko
zone:registerRegion(30,-58,-25,376.5,-52,-24,382.5); -- Byakko to Genbu
zone:registerRegion(31,340.5,-25,166.5,346.5,-24,172.5); --Genbu to Seriyu
zone:registerRegion(32,264.5,-25,-277.5,270.5,-24,-271.5); -- Seriyu to Main
------------------------------
-- Yellow teleports
------------------------------
zone:registerRegion(33,454,-5,-149,456,-3,-147);
zone:registerRegion(34,278,-5,383,281,-3,386);
zone:registerRegion(35,-283,-5,386,-280,-3,389);
zone:registerRegion(36,-456,-5,-149,-454,-3,-147);
---432,-72,335,-429,-70,333
------------------------------
-- Green teleports
------------------------------
zone:registerRegion(37,-145,-41,-156,-142,-39,-153);
zone:registerRegion(38,142,-41,-156,145,-39,-153 );
UpdateTreasureSpawnPoint(17310020);
SetRegionalConquestOverseers(zone:getRegionID())
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(333.017,-44.896,-458.35,164);
end
if (player:getCurrentMission(ZILART) == THE_GATE_OF_THE_GODS and player:getVar("ZilartStatus") == 1) then
cs = 0x0033;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
switch (region:GetRegionID()): caseof
{
---------------------------------
[1] = function (x) -- Portal --
---------------------------------
player:startEvent(0x0000);
end,
---------------------------------
[2] = function (x) -- Portal --
---------------------------------
player:startEvent(0x0001);
end,
---------------------------------
[3] = function (x) -- Portal --
---------------------------------
player:startEvent(0x0002);
end,
---------------------------------
[4] = function (x) -- Portal --
---------------------------------
if (math.random(0,1) == 0) then
player:startEvent(0x0004);
else
player:startEvent(0x0005);
end
end,
---------------------------------
[5] = function (x) -- Portal --
---------------------------------
player:startEvent(0x0006);
end,
---------------------------------
[6] = function (x) -- Portal --
---------------------------------
player:startEvent(0x0009);
end,
---------------------------------
[7] = function (x) -- Portal --
---------------------------------
player:startEvent(0x0010);
end,
---------------------------------
[8] = function (x) -- Portal --
---------------------------------
if (math.random(0,1) == 0) then
player:startEvent(0x0012);
else
player:startEvent(0x0013);
end
end,
---------------------------------
[9] = function (x) -- Portal --
---------------------------------
player:startEvent(0x0014);
end,
---------------------------------
[10] = function (x) -- Portal --
---------------------------------
player:startEvent(0x0017);
end,
---------------------------------
[11] = function (x) -- Portal --
---------------------------------
if (math.random(0,1) == 0) then
player:startEvent(0x0019);
else
player:startEvent(0x001A);
end
end,
---------------------------------
[12] = function (x) -- Portal --
---------------------------------
if (math.random(0,1) == 0) then
player:startEvent(0x0020);
else
player:startEvent(0x0021);
end
end,
---------------------------------
[13] = function (x) -- Portal --
---------------------------------
player:startEvent(0x0022);
end,
---------------------------------
[14] = function (x) -- Portal --
---------------------------------
player:startEvent(0x0024);
end,
---------------------------------
[15] = function (x) -- Portal --
---------------------------------
player:startEvent(0x0025);
end,
---------------------------------
[16] = function (x) -- Portal --
---------------------------------
player:startEvent(0x0026);
end,
---------------------------------
[17] = function (x) -- Portal --
---------------------------------
player:startEvent(0x0027);
end,
---------------------------------
[18] = function (x) -- Portal --
---------------------------------
player:startEvent(0x0028);
end,
---------------------------------
[19] = function (x) -- Portal --
---------------------------------
player:startEvent(0x001B);
end,
---------------------------------
[20] = function (x) -- Portal --
---------------------------------
player:startEvent(0x001E);
end,
---------------------------------
[21] = function (x) -- Portal --
---------------------------------
if (math.random(0,1) == 0) then
player:startEvent(0x000B);
else
player:startEvent(0x000C);
end
end,
---------------------------------
[22] = function (x) -- Portal --
---------------------------------
player:startEvent(0x0009);
end,
----------- BLUE portals --------------
---------------------------------
[23] = function (x) -- Portal -- Main To Seriyu
---------------------------------
if (GetNPCByID(17310054):getAnimation() == 8) then
player:startEvent(0x0003);
end
end,
---------------------------------
[24] = function (x) -- Portal -- Seriyu to Genbu
---------------------------------
if (GetNPCByID(17310057):getAnimation() == 8) then
player:startEvent(0x000A);
end
end,
---------------------------------
[25] = function (x) -- Portal -- Genbu to Byakko
---------------------------------
if (GetNPCByID(17310060):getAnimation() == 8) then
player:startEvent(0x0011);
end
end,
---------------------------------
[26] = function (x) -- Portal -- Byakko to Suzaku
---------------------------------
if (GetNPCByID(17310063):getAnimation() == 8) then
player:startEvent(0x0018);
end
end,
---------------------------------
[27] = function (x) -- Portal -- Suzaku to Main
---------------------------------
if (GetNPCByID(17310066):getAnimation() == 8) then
player:startEvent(0x001F);
end
end,
---------------------------------
[28] = function (x) -- Portal -- Main to Suzaku
---------------------------------
if (GetNPCByID(17310067):getAnimation() == 8) then
player:startEvent(0x0023);
end
end,
---------------------------------
[29] = function (x) -- Portal -- Suzaku to Byakko
---------------------------------
if (GetNPCByID(17310064):getAnimation() == 8) then
player:startEvent(0x001C);
end
end,
---------------------------------
[30] = function (x) -- Portal -- Byakko to Genbu
---------------------------------
if (GetNPCByID(17310061):getAnimation() == 8) then
player:startEvent(0x0015);
end
end,
---------------------------------
[31] = function (x) -- Portal -- Genbu to Seriyu
---------------------------------
if (GetNPCByID(17310058):getAnimation() == 8) then
player:startEvent(0x000E);
end
end,
---------------------------------
[32] = function (x) -- Portal -- Seriyu to Main
---------------------------------
if (GetNPCByID(17310055):getAnimation() == 8) then
player:startEvent(0x0007);
end
end,
---------------------------------
[33] = function (x) -- Seiryu's Portal --
---------------------------------
player:startEvent(0x0008);
end,
---------------------------------
[34] = function (x) -- Genbu's Portal --
---------------------------------
player:startEvent(0x000f);
end,
---------------------------------
[35] = function (x) -- Byakko's Portal --
---------------------------------
player:startEvent(0x0016);
end,
---------------------------------
[36] = function (x) -- Suzaku's Portal --
---------------------------------
player:startEvent(0x001d);
end,
---------------------------------
[37] = function (x)
---------------------------------
if (player:getVar("skyShortcut") == 1) then
player:startEvent(0x002a);
else
title = player:getTitle();
if (title == 401) then
player:startEvent(0x0029,title);
else
player:startEvent(0x002b,title);
end
end
end,
---------------------------------
[38] = function (x)
---------------------------------
if (player:getVar("skyShortcut") == 1) then
player:startEvent(0x002a);
else
title = player:getTitle();
if (title == 401) then
player:startEvent(0x0029,title);
else
player:startEvent(0x002b,title);
end
end
end,
default = function (x)
end,
}
end;
-----------------------------------
-- onRegionLeave
-----------------------------------
function onRegionLeave(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0029 and option ~= 0) then
player:setVar("skyShortcut",1);
elseif (csid == 0x0033) then
player:setVar("ZilartStatus",0);
player:completeMission(ZILART,THE_GATE_OF_THE_GODS);
player:addMission(ZILART,ARK_ANGELS);
end
end; | gpl-3.0 |
AresTao/darkstar | scripts/globals/abilities/pets/frost_breath.lua | 25 | 1248 | ---------------------------------------------------
-- Frost Breath
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0;
end;
function onPetAbility(target, pet, skill, master)
---------- Deep Breathing ----------
-- 0 for none
-- 1 for first merit
-- 0.25 for each merit after the first
-- TODO: 0.1 per merit for augmented AF2 (10663 *w/ augment*)
local deep = 1;
if (pet:hasStatusEffect(EFFECT_MAGIC_ATK_BOOST) == true) then
deep = deep + 1 + (master:getMerit(MERIT_DEEP_BREATHING)-1)*0.25;
pet:delStatusEffect(EFFECT_MAGIC_ATK_BOOST);
end
local gear = master:getMod(MOD_WYVERN_BREATH)/256; -- Master gear that enhances breath
local dmgmod = MobBreathMove(pet, target, 0.185, pet:getMainLvl()*15, ELE_ICE); -- Works out to (hp/6) + 15, as desired
dmgmod = (dmgmod * (1+gear))*deep;
local dmg = MobFinalAdjustments(dmgmod,pet,skill,target,MOBSKILL_MAGICAL,MOBPARAM_ICE,MOBPARAM_IGNORE_SHADOWS);
target:delHP(dmg);
return dmg;
end | gpl-3.0 |
AresTao/darkstar | scripts/zones/Misareaux_Coast/npcs/_0p3.lua | 34 | 1082 | -----------------------------------
-- Area: Misareaux Coast
-- NPC: Dilapidated Gate
-- Notes: Entrance to Misareaux Coast
-----------------------------------
package.loaded["scripts/zones/Misareaux_Coast/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Misareaux_Coast/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0229);
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
AresTao/darkstar | scripts/zones/Carpenters_Landing/mobs/Birdtrap.lua | 23 | 1306 | -----------------------------------
-- Area: Carpenters' Landing
-- Mob: Birdtrap
-- Note: Placeholder Orctrap
-----------------------------------
require("scripts/zones/Carpenters_Landing/MobIDs");
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
-- Get Birdtrap ID and check if it is a PH of Orctrap
mob = mob:getID();
-- Check if Birdtrap is within the Orctrap_PH table
if (Orctrap_PH[mob] ~= nil) then
-- printf("%u is a PH",mob);
-- Get Orctrap previous ToD
Orctrap_ToD = GetServerVariable("[POP]Orctrap");
-- Check if Orctrap window is open, and there is not an Orctrap popped already(ACTION_NONE = 0)
if (Orctrap_ToD <= os.time(t) and GetMobAction(Orctrap) == 0) then
-- printf("Orctrap window open");
-- Give Birdtrap 5 percent chance to pop Orctrap
if (math.random(1,20) == 5) then
-- printf("Orctrap will pop");
UpdateNMSpawnPoint(Orctrap);
GetMobByID(Orctrap):setRespawnTime(GetMobRespawnTime(mob));
SetServerVariable("[PH]Orctrap", mob);
DeterMob(mob, true);
end
end
end
end; | gpl-3.0 |
AresTao/darkstar | scripts/zones/Nashmau/npcs/Leleroon.lua | 17 | 3000 | -----------------------------------
-- Area: Nashmau
-- NPC: Leleroon
-- Standard Info NPC -- Corsair SideQuests
-- @pos -14.687 0.000 25.114 53
-----------------------------------
package.loaded["scripts/zones/Nashmau/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Nashmau/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(AHT_URHGAN,NAVIGATING_THE_UNFRIENDLY_SEAS) == QUEST_ACCEPTED and player:getVar("NavigatingtheUnfriendlySeas") <= 2) then
if (trade:hasItemQty(2341,1) and trade:getItemCount() == 1) then -- Trade Hydrogauage
player:startEvent(0x11B);
player:setVar("NavigatingtheUnfriendlySeas",2);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local mJob = player:getMainJob();
local mLvl = player:getMainLvl();
if (player:getVar("AgainstAllOddsSideQuests") == 1 and mJob == 17 and mLvl >= AF3_QUEST_LEVEL) then
player:startEvent(0x11A); -- CS with 3 Options
else
player:startEvent(0x0108); -- Basic Dialog
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (option == 0) then
elseif (option == 1) then
if (player:hasKeyItem(LELEROONS_LETTER_RED) or player:hasKeyItem(LELEROONS_LETTER_BLUE) or player:hasKeyItem(LELEROONS_LETTER_GREEN) == false) then --
player:addKeyItem(LELEROONS_LETTER_GREEN);
player:messageSpecial(KEYITEM_OBTAINED,LELEROONS_LETTER_GREEN)
player:setVar("LeleroonsLetterGreen",1);
player:setVar("AgainstAllOddsSideQuests",2);
end
elseif (option == 2) then
if (player:hasKeyItem(LELEROONS_LETTER_RED) or player:hasKeyItem(LELEROONS_LETTER_BLUE) or player:hasKeyItem(LELEROONS_LETTER_GREEN) == false) then --
player:addKeyItem(LELEROONS_LETTER_BLUE);
player:messageSpecial(KEYITEM_OBTAINED,LELEROONS_LETTER_BLUE)
player:setVar("LeleroonsLetterBlue",1);
player:setVar("AgainstAllOddsSideQuests",2);
end
elseif (option == 3) then
if (player:hasKeyItem(LELEROONS_LETTER_RED) or player:hasKeyItem(LELEROONS_LETTER_BLUE) or player:hasKeyItem(LELEROONS_LETTER_GREEN) == false) then --
player:addKeyItem(LELEROONS_LETTER_RED);
player:messageSpecial(KEYITEM_OBTAINED,LELEROONS_LETTER_RED)
player:setVar("LeleroonsLetterRed",1);
player:setVar("AgainstAllOddsSideQuests",2);
end
end
end;
| gpl-3.0 |
AresTao/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Somnolent_Rooster.lua | 34 | 1042 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Somnolent Rooster
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00E7);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
AresTao/darkstar | scripts/zones/Northern_San_dOria/npcs/Danngogg.lua | 36 | 1427 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Danngogg
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x021c);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
AresTao/darkstar | scripts/zones/Spire_of_Mea/npcs/_0l3.lua | 51 | 1321 | -----------------------------------
-- Area: Spire_of_Mea
-- NPC: web of regret
-----------------------------------
package.loaded["scripts/zones/Spire_of_Mea/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/bcnm");
require("scripts/zones/Spire_of_Mea/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (TradeBCNM(player,player:getZoneID(),trade,npc)) then
return;
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (EventTriggerBCNM(player,npc)) then
return 1;
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("onUpdate CSID: %u",csid);
--printf("onUpdate RESULT: %u",option);
if (EventUpdateBCNM(player,csid,option)) then
return;
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("onFinish CSID: %u",csid);
--printf("onFinish RESULT: %u",option);
if (EventFinishBCNM(player,csid,option)) then
return;
end
end; | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.