hexsha
stringlengths 40
40
| size
int64 5
129k
| content
stringlengths 5
129k
| avg_line_length
float64 4
98.3
| max_line_length
int64 5
660
| alphanum_fraction
float64 0.25
0.98
|
---|---|---|---|---|---|
bc8ac2d50eda11c97d34db805135817ac8207561 | 483 | export modinfo = {
type: "command"
desc: "Teleport"
alias: {"tp"}
func: (Msg,Speaker) ->
Split = Msg\find(ConfigSystem("Get", "Blet"))
From = GetPlayers(Msg\sub(1,Split-1),Speaker)
To = GetPlayers(Msg\sub(Split+1),Speaker)[1]
Current = 0
for i=-(180),180,360/#From
Current = Current + 1
pcall ->
if From[Current] ~= To
From[Current].Character.Torso.CFrame = To.Character.Torso.CFrame * CFrame.Angles(0,math.rad(i),0) * CFrame.new(0,0,5 + (#From*1.1))
} | 32.2 | 136 | 0.635611 |
df731ae3503b86c8582f8911d4223a96bc62dd67 | 7,548 | ATT_HOSTILE = 0
ATT_NEUTRAL = 1
delta_to_cmd = (dx, dy) ->
d2v = {
[-1]: {
[-1]: "CMD_MOVE_UP_LEFT"
[0]: "CMD_MOVE_LEFT"
[1]: "CMD_MOVE_DOWN_LEFT"
}
[0]: {
[-1]: "CMD_MOVE_UP"
[0]: "CMD_WAIT"
[1]: "CMD_MOVE_DOWN"
}
[1]: {
[-1]: "CMD_MOVE_UP_RIGHT"
[0]: "CMD_MOVE_RIGHT"
[1]: "CMD_MOVE_DOWN_RIGHT"
}
}
return d2v[dx][dy]
sign = (a) ->
return a > 0 and 1 or a < 0 and -1 or 0
abs = (a) ->
return a * sign(a)
choose_move_towards = (ax, ay, bx, by, square_func) ->
los_radius = you.los()
move = nil
dx = bx - ax
dy = by - ay
try_move = (mx, my) ->
if mx == 0 and my == 0
return nil
elseif abs(ax+mx) > los_radius or abs(ay+my) > los_radius
return nil
elseif square_func(ax+mx, ay+my)
return {mx,my}
else
return nil
if abs(dx) > abs(dy)
if abs(dy) == 1
move = try_move(sign(dx), 0)
if move == nil then move = try_move(sign(dx), sign(dy))
if move == nil then move = try_move(sign(dx), 0)
if move == nil and abs(dx) > abs(dy)+1
move = try_move(sign(dx), 1)
if move == nil and abs(dx) > abs(dy)+1
move = try_move(sign(dx), -1)
if move == nil then move = try_move(0, sign(dy))
elseif abs(dx) == abs(dy)
move = try_move(sign(dx), sign(dy))
if move == nil then move = try_move(sign(dx), 0)
if move == nil then move = try_move(0, sign(dy))
else
if abs(dx) == 1
move = try_move(0, sign(dy))
if move == nil then move = try_move(sign(dx), sign(dy))
if move == nil then move = try_move(0, sign(dy))
if move == nil and abs(dy) > abs(dx)+1
move = try_move(1, sign(dy))
if move == nil and abs(dy) > abs(dx)+1
move = try_move(-1, sign(dy))
if move == nil then move = try_move(sign(dx), 0)
return move
can_move_maybe = (dx, dy) ->
if view.feature_at(dx,dy) ~= "unseen" and view.is_safe_square(dx,dy)
m = monster.get_monster_at(dx, dy)
if not m or not m\is_firewood()
return true
return false
have_reaching = () ->
wp = items.equipped_at("weapon")
return wp and wp.reach_range == 2 and not wp.is_melded
will_tab = (ax, ay, bx, by) ->
if abs(bx-ax) <= 1 and abs(by-ay) <= 1 or abs(bx-ax) <= 2 and abs(by-ay) <= 2 and have_reaching()
return true
move = choose_move_towards(ax, ay, bx, by, can_move_maybe)
if move == nil
return false
return will_tab(ax+move[1], ay+move[2], bx, by)
have_ranged = () ->
wp = items.equipped_at("weapon")
return wp and wp.is_ranged and not wp.is_melded
have_throwing = (no_move) ->
return (AUTOFIGHT_THROW or no_move and AUTOFIGHT_THROW_NOMOVE) and items.fired_item() ~= nil
get_monster_info = (dx,dy,no_move) ->
m = monster.get_monster_at(dx,dy)
name = m\name()
if not m
return nil
info = {}
info.name = name
info.distance = (if abs(dx) > abs(dy) then -abs(dx) else -abs(dy))
if have_ranged()
info.attack_type = you.see_cell_no_trans(dx, dy) and 3 or 0
elseif not have_reaching()
info.attack_type = (if -info.distance < 2 then 2 else 0)
else
if -info.distance > 2
info.attack_type = 0
elseif -info.distance < 2
info.attack_type = 2
else
info.attack_type = (if view.can_reach(dx, dy) then 1 else 0)
if info.attack_type == 0 and have_throwing(no_move) and you.see_cell_no_trans(dx, dy)
info.attack_type = 3
if info.attack_type == 0 and not will_tab(0,0,dx,dy)
info.attack_type = -1
info.can_attack = (if info.attack_type > 0 then 1 else info.attack_type)
info.safe = m\is_safe() and -1 or 0
info.constricting_you = (if m\is_constricting_you() then 1 else 0)
-- Only prioritize good stabs\ sleep and paralysis.
info.very_stabbable = (if m\stabbability() >= 1 then 1 else 0)
info.injury = m\damage_level()
info.threat = m\threat()
info.orc_priest_wizard = (if name == "orc priest" or name == "orc wizard" then 1 else 0)
return info
flag_order = {"threat", "can_attack", "safe", "distance", "constricting_you", "very_stabbable", "injury", "orc_priest_wizard"}
compare_monster_info = (m1, m2) ->
-- flag_order = autofight_flag_order
-- if flag_order == nil
-- flag_order = {"can_attack", "safe", "distance", "constricting_you", "very_stabbable", "injury", "threat", "orc_priest_wizard"}
for i,flag in ipairs(flag_order)
if m1[flag] > m2[flag]
return true
elseif m1[flag] < m2[flag]
return false
return false
is_candidate_for_attack = (x,y) ->
m = monster.get_monster_at(x, y)
if not m or m\attitude() ~= ATT_HOSTILE
return false
if m\name() == "butterfly" or m\name() == "orb of destruction"
return false
if m\is_firewood()
if string.find(m\name(), "ballistomycete")
return true
return false
return true
get_target = (no_move) ->
local x, y, bestx, besty, best_info, new_info
los_radius = you.los()
bestx = 0
besty = 0
best_info = nil
for x = -los_radius,los_radius
for y = -los_radius,los_radius
if is_candidate_for_attack(x, y)
new_info = get_monster_info(x, y, no_move)
if (not best_info) or compare_monster_info(new_info, best_info)
bestx = x
besty = y
best_info = new_info
return bestx, besty, best_info
should_confirm_move = (cmd_name, dx, dy) ->
bestx, besty, best_info = get_target(true)
if not best_info
-- Can move freely, no enemies
return false
if best_info.threat < 2
return false
return true, "#{best_info.name} has threat #{best_info.threat}. Do you do the move #{cmd_name}? [y/n]"
is_safe_or_confirmed_move = (cmd_name, dx, dy) ->
should_confirm, msg = should_confirm_move(cmd_name, dx, dy)
if should_confirm
return crawl.yesno(msg)
return true
for {func_name, cmd_name, dx, dy} in *{
{"safe_up", "up", 0, -1}
{"safe_down", "down", 0, 1}
{"safe_left", "left", -1, 0}
{"safe_right", "right", 1, 0}
{"safe_wait", "to the same square", 0, 0}
{"safe_up_left", "up-left", -1, -1}
{"safe_up_right", "up-right", 1, -1}
{"safe_down_left", "down-left", -1, 1}
{"safe_down_right", "down-right", 1, 1}
}
_G[func_name] = () ->
-- We want to detect these cases...
-- 1) Confirm running from a fast monster
-- 2) Confirm moving towards a strong monster
-- 3) Confirm moving towards enough damage to deal 50% of my health
-- 4) Confirm moving in range of throwing enemies
-- 5) Doing ANYTHING while slow
if not is_safe_or_confirmed_move(cmd_name, dx, dy)
crawl.mpr("Not moving #{cmd_name}! Think a bit!")
else
crawl.do_commands({delta_to_cmd(dx, dy)})
prev_hit_closest = hit_closest
_G.hit_closest = () ->
bestx, besty, best_info = get_target(true)
if best_info and best_info.threat >= 2 and not crawl.yesno("Attack monster #{best_info.name} with threat #{best_info.threat}? [y/n]")
crawl.mpr("Not autoattacking, think!")
return
prev_hit_closest()
_G.show_safety = () ->
bestx, besty, best_info = get_target(true)
crawl.mpr("Target: ".. tostring(best_info.threat))
| 34.153846 | 137 | 0.588368 |
7557cc9fa2c163dfadc1dfaf1627db062b6fc304 | 2,690 | utility = require('shared.utility')
-- A process measure regularly sends update events.
-- If a specific process is being monitored, then that process' state is updated.
-- Else the statuses of the various supported platforms' client processes are updated.
class Process
new: () =>
@monitoring = false
@commandMeasure = SKIN\GetMeasure('Command')
@currentGame = nil
@startingTime = nil
@duration = 0
getGame: () => @currentGame
registerPlatforms: (platforms) =>
log('Registering platform processes')
@platformProcesses = {}
@platformStatuses = {}
for platform in *platforms
if platform\isEnabled()
id = platform\getPlatformID()
process = platform\getPlatformProcess()
if process ~= nil
@platformProcesses[id] = process
@platformStatuses[id] = false
log(('- %d = %s')\format(id, tostring(process)))
update: (running) =>
if @monitoring
log('Updating game process status')
if running and not @gameStatus
@gameStatus = true
@duration = 0
@startingTime = os.time()
GameProcessStarted(@currentGame)
return true
elseif not running and @gameStatus
@stopMonitoring()
else
log('Game is still running')
return false
utility.runCommand('tasklist /fo csv /nh', '', 'UpdatePlatformProcesses', {}, 'Hide', 'UTF8')
return true
updatePlatforms: () =>
return {} if @platformProcesses == nil
log('Updating platform client process statuses')
output = @commandMeasure\GetStringValue()
for id, process in pairs(@platformProcesses)
@platformStatuses[id] = if output\match(process) ~= nil then true else false
log(('- %d = %s')\format(id, tostring(@platformStatuses[id])))
return @platformStatuses
monitor: (game) =>
assert(type(game) == 'table', 'main.process.Process.monitor')
@currentGame = game
process = game\getProcess()
log('Monitoring process', process)
@duration = 0
@startingTime = os.time()
return if process == nil
@gameStatus = false
@monitoring = true
assert(type(process) == 'string', 'main.process.Process.monitor')
SKIN\Bang(('[!SetOption "Process" "ProcessName" "%s"]')\format(process))
SKIN\Bang('[!SetOption "Process" "UpdateDivider" "63"]')
stopMonitoring: () =>
return if @currentGame == nil
@gameStatus = false
@monitoring = false
@duration = os.time() - @startingTime
@startingTime = nil
GameProcessTerminated(@currentGame)
@currentGame = nil
SKIN\Bang('[!SetOption "Process" "UpdateDivider" "630"]')
getDuration: () => return @duration
isRunning: () => return @gameStatus
isPlatformRunning: (platformID) =>
return false if @platformProcesses == nil
return @platformStatuses[platformID] == true
return Process
| 30.224719 | 95 | 0.69145 |
92a2692c05d694b1303898efcd7ba7336dc862e9 | 3,314 | {:cimport, :internalize, :eq, :neq, :ffi, :lib, :cstr, :to_cstr} = require 'test.unit.helpers'
path = lib
ffi.cdef [[
typedef enum file_comparison {
kEqualFiles = 1, kDifferentFiles = 2, kBothFilesMissing = 4, kOneFileMissing = 6, kEqualFileNames = 7
} FileComparison;
FileComparison path_full_compare(char_u *s1, char_u *s2, int checkname);
char_u *path_tail(char_u *fname);
char_u *path_tail_with_sep(char_u *fname);
char_u *path_next_component(char_u *fname);
]]
-- import constants parsed by ffi
{:kEqualFiles, :kDifferentFiles, :kBothFilesMissing, :kOneFileMissing, :kEqualFileNames} = path
NULL = ffi.cast 'void*', 0
describe 'path function', ->
describe 'path_full_compare', ->
path_full_compare = (s1, s2, cn) ->
s1 = to_cstr s1
s2 = to_cstr s2
path.path_full_compare s1, s2, cn or 0
f1 = 'f1.o'
f2 = 'f2.o'
before_each ->
-- create the three files that will be used in this spec
(io.open f1, 'w').close!
(io.open f2, 'w').close!
after_each ->
os.remove f1
os.remove f2
it 'returns kEqualFiles when passed the same file', ->
eq kEqualFiles, (path_full_compare f1, f1)
it 'returns kEqualFileNames when files that dont exist and have same name', ->
eq kEqualFileNames, (path_full_compare 'null.txt', 'null.txt', true)
it 'returns kBothFilesMissing when files that dont exist', ->
eq kBothFilesMissing, (path_full_compare 'null.txt', 'null.txt')
it 'returns kDifferentFiles when passed different files', ->
eq kDifferentFiles, (path_full_compare f1, f2)
eq kDifferentFiles, (path_full_compare f2, f1)
it 'returns kOneFileMissing if only one does not exist', ->
eq kOneFileMissing, (path_full_compare f1, 'null.txt')
eq kOneFileMissing, (path_full_compare 'null.txt', f1)
describe 'path_tail', ->
path_tail = (file) ->
res = path.path_tail (to_cstr file)
neq NULL, res
ffi.string res
it 'returns the tail of a given file path', ->
eq 'file.txt', path_tail 'directory/file.txt'
it 'returns an empty string if file ends in a slash', ->
eq '', path_tail 'directory/'
describe 'path_tail_with_sep', ->
path_tail_with_sep = (file) ->
res = path.path_tail_with_sep (to_cstr file)
neq NULL, res
ffi.string res
it 'returns the tail of a file together with its seperator', ->
eq '///file.txt', path_tail_with_sep 'directory///file.txt'
it 'returns an empty string when given an empty file name', ->
eq '', path_tail_with_sep ''
it 'returns only the seperator if there is a traling seperator', ->
eq '/', path_tail_with_sep 'some/directory/'
it 'cuts a leading seperator', ->
eq 'file.txt', path_tail_with_sep '/file.txt'
eq '', path_tail_with_sep '/'
it 'returns the whole file name if there is no seperator', ->
eq 'file.txt', path_tail_with_sep 'file.txt'
describe 'path_next_component', ->
path_next_component = (file) ->
res = path.path_next_component (to_cstr file)
neq NULL, res
ffi.string res
it 'returns', ->
eq 'directory/file.txt', path_next_component 'some/directory/file.txt'
it 'returns empty string if given file contains no seperator', ->
eq '', path_next_component 'file.txt'
| 32.811881 | 103 | 0.667471 |
86b03cd6a07c68b8d911e2e87601a83c942bb80d | 1,567 | class List
new: =>
@__list = {}
-- Add an item to the end of the list
push: (value) => @__list[@len! + 1] = value
-- Remove an item from the end of the list
pop: => table.remove @__list, @len!
-- Look at the item at the end of the list
peek: => @__list[@len!]
-- The last item in the list
last: => @peek!
-- Add an item to the begining of the list
unshift: (value) => table.insert @__list, 1, value
-- Remove an item from the begining of the list
shift: => table.remove @__list, 1
-- Remove an item at any point
remove: (i) => table.remove @__list, i
-- Look at the item at the begining of the list
first: => @__list[1]
len: => #@__list
__len: => @len!
__tostring: => string.format "{ %s }", table.concat @__list, ", "
index: (i) => @__list[i]
-- Iterate over the list
-- Removing items during iteration may cause unexpected results
pairs: =>
n, len = 0, @len!
->
n += 1
return nil if n > len
@__list[n]
-- Reverse iterate over the list
-- Removing items during iteration may cause unexpected results
rpairs: =>
n = @len! + 1
->
n -= 1
return nil if n < 1
@__list[n]
-- Iterate over the list returning the index as well
-- Removing items during iteration may cause unexpected results
ipairs: =>
n, len = 0, @len!
->
n += 1
return nil if n > len
n, @__list[n]
-- Reverse iterate over the list returning the index as well
-- Removing items during iteration may cause unexpected results
ripairs: =>
n = @len! + 1
->
n -= 1
return nil if n < 1
n, @__list[n]
{ :List }
| 21.465753 | 66 | 0.62157 |
32820d418ec1b607eee3886c6ee299534e8543d7 | 592 | import Point from require "LunoPunk.geometry.Point"
-- TODO
class atlasdata
new: =>
create: (source) ->
atlasdata!
-- Creates a new AtlasRegion
-- @param rect Defines the rectangle of the tile on the tilesheet
-- @param center Positions the local center point to pivot on
--
-- @return The new AtlasRegion object.
createRegion: (rect, center) =>
r = rect\clone!
p = Point center.x, center.y unless center != nil
-- tileIndex = @__tilesheet\addTileRect r, p
AtlasRegion @, tileIndex, rect
width: => @__width
height: => @__height
AtlasData = atlasdata!
{ :AtlasData }
| 21.925926 | 66 | 0.695946 |
69e0df34b302e9577ddc463a3c8ea2e0ab3449a8 | 379 | export modinfo = {
type: "function"
id: "getDoMultiPlayersFunction"
func: (Number, SubFunction) ->
(Msg, Speaker) ->
currentTable = {}
for i = 1, Number do
currentTable[i] = GetPlayers(Split(Msg)[i], Speaker)[1]
if currentTable[i] == nil then
error string.format("%s gave no results", tostring(Split(Msg)[i]))
SubFunction currentTable, Msg, Speaker
}
| 27.071429 | 71 | 0.662269 |
b2be23fa8a28bf7ca97a1df8e10610a725f0aee8 | 20 | require "lapis.flow" | 20 | 20 | 0.8 |
a287c9cf7355e2413e1e52a76c2b49490f85da10 | 2,823 | --
-- Provide req.session and user capabilities (req.context)
--
import sub, match, format from require 'string'
import date, time from require 'os'
import encrypt, uncrypt, sign from require 'crypto'
JSON = require 'json'
expires_in = (ttl) -> date '%c', time() + ttl
serialize = (secret, obj) ->
str = JSON.stringify obj
str_enc = encrypt secret, str
timestamp = time()
hmac_sig = sign secret, timestamp .. str_enc
result = hmac_sig .. timestamp .. str_enc
result
deserialize = (secret, ttl, str) ->
hmac_signature = sub str, 1, 40
timestamp = tonumber sub(str, 41, 50), 10
data = sub str, 51
hmac_sig = sign secret, timestamp .. data
return nil if hmac_signature != hmac_sig or timestamp + ttl <= time()
data = uncrypt secret, data
data = JSON.parse data
data = nil if data == JSON.null
data
read_session = (key, secret, ttl, req) ->
cookie = type(req) == 'string' and req or req.headers.cookie
if cookie
cookie = match cookie, '%s*;*%s*' .. key .. '=(%w*)'
if cookie and cookie != ''
return deserialize secret, ttl, cookie
nil
--
-- we keep sessions safely in encrypted and signed cookies.
-- inspired by caolan/cookie-sessions
--
return (options = {}) ->
-- defaults
key = options.key or 'sid'
ttl = options.ttl or 15 * 24 * 60 * 60 * 1000
secret = options.secret
context = options.context or {}
-- handler
return (req, res, continue) ->
-- read session data from request and store it in req.session
req.session = read_session key, secret, ttl, req
-- patch response to support writing cookies
-- TODO: is there a lighter method?
_write_head = res.write_head
res.write_head = (self, code, headers, callback) ->
cookie = nil
if not req.session
if req.headers.cookie
cookie = format '%s=;expires=%s;httponly;path=/', key, expires_in(0)
else
cookie = format '%s=%s;expires=%s;httponly;path=/', key, serialize(secret, req.session), expires_in(ttl)
-- Set-Cookie
if cookie
self\add_header 'Set-Cookie', cookie
_write_head self, code, headers, callback
-- always create a session if options.default_session specified
if options.default_session and not req.session
req.session = options.default_session
-- use authorization callback if specified
if options.authorize
-- given current session, setup request context
options.authorize req.session, (context) ->
req.context = context or {}
continue()
-- assign static request context
else
-- default is guest request context
req.context = context.guest or {}
-- user authenticated?
if req.session and req.session.uid and context.user
-- provide user request context
req.context = context.user
continue()
| 31.021978 | 112 | 0.657457 |
b733c7455429791aff04754a6b2535e521ccc70a | 744 | export modinfo = {
type: "command"
desc: "Rirakkusu"
alias: {"rirak"}
func: getDoPlayersFunction (v) ->
t=v.Character.Torso
ls=t['Left Shoulder']
rs=t['Right Shoulder']
lh=t['Left Hip']
rh=t['Right Hip']
n=t.Neck
v.Character.Animate.Disabled=true
for i=1,180
ls.C0 = ls.C0 *CFrame.Angles(0,0,math.rad(-(1)))
rs.C0 = rs.C0 *CFrame.Angles(0,0,math.rad(1))
for i=1,35
lh.C0 = lh.C0 *CFrame.new(0,0.01,0) *CFrame.Angles(math.rad(-(1.2)),0,0)
rh.C0 = rh.C0 *CFrame.new(0,0.01,0) *CFrame.Angles(math.rad(-(1.2)),0,0)
t.Parent\MoveTo(t.Position+Vector3.new(0,5,0))
t.Anchored=true
v.Character.Head.Anchored=true
s = CreateInstance"Smoke"{
Parent: t
Opacity: 0.5
RiseVelocity: -(25)
Size: 0.1
}
} | 26.571429 | 75 | 0.63172 |
4e1a2cf0b3e2068fea354e4b3f0424fb26d8e3e6 | 1,212 | lapisconfig=require "lapis.config"
import config from lapisconfig
config "development", ->
set "envmode","development"
config {"test","production"}, ->
set "envmode","production"
config {"development","test","production"},->
set "appname", "please set the appname in config.moon"
session_name "please set the session name in config.moon"
secret "please set the secret in config.moon"
set "env_lua_path", (os.getenv "LUA_PATH")\gsub "%;", "\\;"
set "env_lua_cpath", (os.getenv "LUA_CPATH")\gsub "%;", "\\;"
set "env_moon_path", (os.getenv "MOON_PATH")\gsub "%;", "\\;"
modules {}
postgres ->
database "please set the database in config.moon"
password "please set the password in config.moon"
host "127.0.0.1"
port "5432"
user "postgres"
backend "pgmoon"
config {"development","test"}, ->
port 8080
enable_console true
enable_web_migration true
page_cache_size "1m"
num_workers 1
code_cache "off"
run_daemon "off"
measure_performance true
config "production", ->
port 8081
enable_console false
enable_web_migration false
page_cache_size "30m"
num_workers 4
code_cache "on"
run_daemon "on"
measure_performance false
return lapisconfig | 26.933333 | 63 | 0.69967 |
b5cfbe759f5ec0ac1db0be6612b17af38d408640 | 4,857 | ---------------------------------------------------------------------------
-- Environment ------------------------------------------------------------
---------------------------------------------------------------------------
hs = require 'hs'
import tostring from _G
import find from string
colors = require 'colors'
{ :rect } = require 'hs.geometry'
log = require('log').get 'console'
import leftClick from require 'hs.eventtap'
import focusedWindow from require 'hs.window'
{ new:Toolbar } = require 'hs.webview.toolbar'
import partial, partialr, once from require 'fn'
import styledtext, console, settings, hotkey, application from hs
{ :istable, :ishex, :isfunction, sigcheck:T } = require 'typecheck'
import copy, sort, join, merge, reduce, eachk from require 'fn.table'
import getAbsolutePosition, setAbsolutePosition from require 'hs.mouse'
---------------------------------------------------------------------------
-- Implementation ---------------------------------------------------------
---------------------------------------------------------------------------
self = merge {
theme: nil
completions: nil
}, console
printc = (color, v) ->
color = if istable color then color
elseif ishex color then colors.hex color
else colors.name color
console.print styledtext.new(tostring v, {
:color,
font: console.consoleFont()
})
buildcompletions = (modpairs) ->
result = {}
for n, m in pairs modpairs
for k, v in pairs m
comp = result[k]
newcomp = n .. '.' .. (isfunction(v) and k .. '()' or k)
if comp
comp[#comp + 1] = newcomp
result[k] = comp
else result[k] = { newcomp }
return result
autocomplete = (kw, completions, handler) ->
result = {}
for k, t in pairs completions
join result, t if k\find kw, nil, true
default = handler kw
switch #result
when 1 then default
when 1
if #default == 0
result[#result + 1] = 'dummy'
result
else
default[#default + 1] = result[1]
default
else
sort(result)
join default, result
init = (options) ->
with options
-- Window behavior
if .behavior
@.behavior .behavior
-- Toggle hot key
if .toggleHotKey
@_hotkey = hotkey.bind .toggleHotKey[1], .toggleHotKey[2], @toggle
if not .titleVisible
@.titleVisibility 'hidden'
-- initialize theme.
if .themes
theme = require 'console.theme'
current = .themes.current
if current then .themes.current = nil
elseif saved = settings.get 'console.theme'
current = saved if .themes[saved]
theme.init(.themes, current)
@theme = theme
-- initialize toolbar.
if .toolbar
toolbar = Toolbar .toolbar.name, .toolbar.items
if globalCallback = .toolbar.callback
toolbar\setCallback globalCallback
if setup = .toolbar.setup
eachk setup, (k, v) -> toolbar[k] toolbar, v
@.toolbar toolbar
-- build auto-completion handler.
if .autocompletion
completions = buildcompletions .autocompletion
_completion = hs.completionsForInputString
hs.completionsForInputString = partialr autocomplete, completions, _completion
@_completions = completions
log.debugf 'Auto-completion table built with %d entries.', reduce(completions, 0, (r, t) -> r + #t) if log.debug
-- apply saved settings.
alpha = settings.get 'console.alpha'
@.alpha alpha if alpha != nil
frame = settings.get 'console.frame'
if frame and settings.get 'hs.reloaded'
@.open!
if window = @.hswindow!
log.debug 'Restoring to previous window frame : ' .. tostring(frame) if log.debug
window\setFrame rect frame._x, frame._y, frame._w, frame._h
stop = () ->
settings.set 'console.alpha', @.alpha!
settings.set 'console.theme', @.theme.get! if @.theme
if window = @.hswindow! then settings.set 'console.frame', window\frame!
toggle = (focusTextField) ->
win = @.window!
if win
win\close!
else
@.open!
if focusTextField
win = @.window!
mousePosition = getAbsolutePosition!
frame = win\frame!
leftClick { x: frame._x + frame._w - 30, y: frame._y + frame._h - 30 }
setAbsolutePosition mousePosition
return
window = () -> application.get('org.hammerspoon.Hammerspoon')\findWindow('Hammerspoon Console')
---------------------------------------------------------------------------
-- Interface --------------------------------------------------------------
---------------------------------------------------------------------------
merge self, {
printc: T 'color, any', printc
init: T 'table', once(init)
toggle: T '?boolean', toggle
:stop, :window
-- rename
open: hs.openConsole
hswindow: window
alwaysOnTop: hs.consoleOnTop
setContent: console.setConsole,
getContent: console.getConsole
}
| 31.538961 | 118 | 0.572576 |
6541847e43f6664b4d5e9528da8c8e98daac4e95 | 460 | class MP4 extends Format
new: =>
@displayName = "MP4 (h264/AAC)"
@supportsTwopass = true
@videoCodec = "libx264"
@audioCodec = "aac"
@outputExtension = "mp4"
@acceptsBitrate = true
formats["mp4"] = MP4!
class MP4NVENC extends Format
new: =>
@displayName = "MP4 (h264-NVENC/AAC)"
@supportsTwopass = true
@videoCodec = "h264_nvenc"
@audioCodec = "aac"
@outputExtension = "mp4"
@acceptsBitrate = true
formats["mp4-nvenc"] = MP4NVENC!
| 20.909091 | 39 | 0.671739 |
b0011972932144ad2926eb3258f7f6d565257927 | 2,635 | ffi = require "ffi"
ffi_istype = ffi.istype
ffi_metatype = ffi.metatype
bit = require "bit"
bit_xor = bit.bxor
bit_lshift = bit.lshift
bit_rshift = bit.rshift
math = require "math"
sqrt = math.sqrt
atan2 = math.atan2
local *
is_number = (n) -> type(n) == "number"
is_vector2 = (n) -> ffi_istype vector2, n
hashxy = (x, y) ->
-- the easier the better
x * 1e7 + y
index_mt = {
clone: (v) ->
vector2 v.x, v.y
euclidean: (v) ->
vector2 v\len!, atan2(v.x, v.y)
ieuclidean: (v) ->
v.x = v\len!
v.y = atan2(v.x, v.y)
polar: (v) ->
vector2 v.x * cos(v.y), v.x * sin(v.y)
ipolar: (v) ->
v.x = v.x * cos(v.y)
v.y = v.x * sin(v.y)
set: (a, b) ->
a.x = b.x
a.y = b.y
setxy: (v, x, y) ->
v.x = x
v.y = y
unpack: (v) ->
v.x, v.y
hash: (v) ->
hashxy v.x, v.y
length: (v) ->
sqrt v.x^2 + v.y^2
length2: (v) ->
v.x^2 + v.y^2
dot: (a, b) ->
a.x*b.x + a.y*b.y
cross: (a, b) ->
a.x*b.y - a.y*b.x
distance: (a, b) ->
sqrt (a.x-b.x)^2 + (a.y-b.y)^2
distance2: (a, b) ->
(a.x-b.x)^2 + (a.y-b.y)^2
normalize: (v) ->
l = v\length!
assert l>0, "Vec2: trying to normalize (0,0)."
vector2 v.x/l, v.y/l
inormalize: (v) ->
l = v\length!
assert l>0, "Vec2: trying to normalize (0,0)."
v.x /= l
v.y /= l
add: (a, b) ->
vector2 a.x+b.x, a.y+b.y
sub: (a, b) ->
vector2 a.x-b.x, a.y-b.y
mul: (a, b) ->
if is_number a
vector2 a * b.x, a * b.y
elseif is_number b
vector2 a.x * b, a.y * b
else
error "Vec2: please use 'dot(a,b)'."
div: (a, b) ->
assert is_number(b), "Vec2: can only divide by number."
vector2 a.x/b, a.y/b
unm: (v) ->
vector2 -v.x, -v.y
eq: (a, b) ->
is_vector2(a) and
is_vector2(b) and
a.x == b.x and a.y == b.y
tostring: (v) ->
"(#{v.x},#{v.y})"
iadd: (a, b) ->
a.x += b.x
a.y += b.y
isub: (a, b) ->
a.x -= b.x
a.y -= b.y
imul: (a, b) ->
a.x *= b
a.y *= b
idiv: (a, b) ->
a.x /= b
a.y /= b
iunm: (v) ->
v.x = -v.x
v.y = -v.y
}
mt = {
__add: index_mt.add
__sub: index_mt.sub
__mul: index_mt.mul
__div: index_mt.div
__unm: index_mt.unm
__eq: index_mt.eq
__tostring: index_mt.tostring
__index: index_mt
}
vector2 = ffi_metatype "struct { double x, y; }", mt
setmetatable {
ctype: vector2
zero: -> vector2 0, 0
identity: (n=1) -> vector2 n, n
from_polar: (d, angle) ->
vector2 d * cos(angle), d * sin(angle)
is_a: is_vector2
hashxy: hashxy
}, {
__call: (_, ...) -> vector2 ...
__index: index_mt
} | 19.81203 | 59 | 0.494118 |
119d9a58cc94b65354e28c1343306e9561413804 | 1,088 | export class Keyboard extends Input
new: => super @@keys
key_down: (key) =>
@keys[key] = axel.now
key_up: (key) =>
@keys[key] = -axel.now
@keys: {
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
"t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", " ",
"!", "\"", "#", "$", "&", "'", "(", ")", "*", ",", ".", "/", ":", ";", "<", "=", ">", "?", "@",
"[", "\\", "]", "^", "_", "`", "kp0", "kp1", "kp2", "kp3", "kp4", "kp5", "kp6", "kp7", "kp8",
"kp9", "kp.", "kp,", "kp/", "kp*", "kp-", "kp+", "kpenter", "kp=", "up", "down", "right", "left",
"home", "end", "pageup", "pagedown", "insert", "backspace", "tab", "clear", "return", "delete",
"f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15",
"f16", "f17", "f18", "numlock", "capslock", "scrolllock", "rshift", "lshift", "rctrl", "lctrl",
"ralt", "lalt", "rgui", "lgui", "mode", "pause", "escape", "help", "printscreen", "sysreq",
"menu", "application", "power", "currencyunit", "undo"
} | 51.809524 | 99 | 0.398897 |
b9a6f33828eba537457bca909e7071276a05391d | 799 | -- Rainbow Arena, a game by Mirrexagon.
--
-- The code is under the MIT license (see `LICENSE-MIT`).
--
-- Sounds, music, and graphics are under the Creative Commons CC-BY 4.0 license (see `LICENSE-CC-BY-4.0`).
-- - Sound effects made with Bfxr (http://www.bfxr.net) and Audacity (http://www.audacityteam.org).
-- - Music made by me; see https://lmirx.net
--
-- Note that parts NOT made by me remain the property of their respective authors; these parts include:
-- - lib/hump is HUMP by vrld (https://github.com/vrld/hump)
-- - lib/tiny.lua is tiny-ecs by bakpakin (https://github.com/bakpakin/tiny-ecs)
love.load = ->
love.update = (dt) ->
print dt
love.draw = ->
love.graphics.setColor 1, 1, 1
love.graphics.circle "line", 300, 300, 30
love.graphics.print "Potato", 100, 100
| 33.291667 | 106 | 0.680851 |
610dbad7a5916adcc5afe68dfc061f60cb1c3527 | 482 | M = {}
__ = ...
TK = require "PackageToolkit"
case1 = TK.module.initimport __, "_case1"
case2 = TK.module.initimport __, "_case2"
case3 = TK.module.initimport __, "_case3"
M.main = () ->
case2.run "case 2"
case1.run "case 1"
-- test module.ipath
if (TK.module.ipath __, "m1") == __ .. ".m1"
print (TK.module.ipath __, "m1")
print "module.ipath verified!"
else
print "module.ipath not working!"
case3.run "test module.path"
return M | 24.1 | 48 | 0.607884 |
64d3e1a203cb4c33f2101d103888f773ee220bda | 365 | -- 0-based 2D array
Array = require (PILE_OF_CODE_BASE or '') .. "ds.Array"
class Array2D
-- not auto init
new: (@width, @height) =>
@size = width * height
@data = Array @size
index: (x, y) =>
x + @width * y
get: (x, y) =>
@data[@index(x, y)]
set: (x, y, value) =>
@data[@index(x, y)] = value
__tostring: =>
tostring @data
| 16.590909 | 55 | 0.531507 |
20aee5d29b5dac3e2e45b79f20c44051edaa75a1 | 476 | describe "user bugs", ->
parse = require('lush').parse
-- https://github.com/rktjmp/lush.nvim/commit/7103ea77d738ef48c983491b22ae2ca4f797dbbc#r47924319
-- https://github.com/kunzaatko/nord.nvim/issues/2
it "gives better warning if inherit isn't a table", ->
spec = -> {
A { fg: "a_fg", bg: "a_bg", "inverse"}
}
e = assert.error(-> parse(spec))
assert.matches("target_not_lush_type", e.code)
assert.not.matches("No message avaliable", e.msg)
| 36.615385 | 98 | 0.668067 |
97a7539b7d0a729b413d50d4693145ead31bea93 | 161 | export class Stairs extends Entity
new: (x, y) =>
sprite = sprites.stairs
x = x - sprite.width / 2
y = y - sprite.height / 2
super x, y, sprite | 26.833333 | 34 | 0.596273 |
dd055563f94c473cde78b44a2a439d3d980d11e1 | 4,955 | --- Copyright 2012-2018 The Howl Developers
--- License: MIT (see LICENSE.md at the top-level directory of the distribution)
{:app, :dispatch, :interact, :sys} = howl
{:StyledText} = howl.ui
{:File} = howl.io
{:file_list, :get_dir_and_leftover} = howl.util.paths
available_commands = ->
commands = {}
-- load commands in a separate coroutine using async becuase this can take a while sometimes
dispatch.launch ->
for path in sys.env.PATH\gmatch '[^:]+'
dir = File path
if dir.exists
for child in *dir.children_async
-- show command name in the first column and parent_dir in the second
table.insert commands, {child.basename, child.parent.short_path}
return commands
looks_like_path = (text) ->
return unless text
for p in *{
'^%s*%./',
'^%s*%.%./',
'^%s*/',
'^%s*~/',
}
if text\umatch p
return true
files_under = (path) ->
return {} unless path
file_list path.children, path
directories_under = (path) ->
dirs = [child for child in *path.children when child.is_directory]
rows = file_list dirs, path
if path.parent
table.insert rows, 1, {StyledText('../', 'directory'), file: path.parent}
table.insert rows, 1, {StyledText('./', 'directory'), file: path}
return rows
normalized_relative_path = (from_path, to_path) ->
relative = ''
parent = from_path
while parent
if to_path\is_below parent
return relative .. to_path\relative_to_parent parent
else
parent = parent.parent
relative ..= '../'
class ExternalCommandConsole
new: (@dir) =>
error 'no dir specified for external command' unless @dir
@dir = File(@dir) if type(@dir) == 'string'
@available_commands = available_commands!
display_prompt: => "[#{@dir.short_path}] $ "
display_title: => "Command"
complete: (text) =>
-- parse into an array of {word:, trailing_spaces:} objects
words = @_parse text
if #words == 0 or (#words == 1 and words[1].word != 'cd' and not looks_like_path words[1].word)
-- trying to auto complete a command
match_text = if words[1] then words[1].word else ''
return {
name: 'command'
completions: @available_commands
:match_text
columns: {{style: 'string'}, {style: 'comment'}}
}
elseif words[1].word == 'cd' and not words[1].trailing_spaces.is_empty
path = if words[2] then words[2].word else ''
matched_dir, match_text = @_parse_path path
return name: 'cd', completions: directories_under(matched_dir), :match_text, auto_show: true
elseif looks_like_path words[#words].word
-- try to complete the last word
path = words[#words].word
matched_dir, match_text = @_parse_path path
words[#words] = nil
prefix = table.concat ["#{w.word}#{w.trailing_spaces}" for w in *words]
return name: 'filepath', :prefix, completions: files_under(matched_dir), :match_text
back: =>
if @dir.parent
@dir = @dir.parent
_parse: (text) =>
[:word, :trailing_spaces for word, trailing_spaces in text\gmatch '([^%s]+)([%s]*)']
_parse_path: (path) =>
if path\starts_with '~' .. File.separator
path = tostring(File.home_dir) .. path\sub 2
local matched_dir, match_text
if path.is_blank or path == '.' or path == '..'
matched_dir = @dir
match_text = path
elseif path\ends_with File.separator
matched_dir = @dir / path
return unless matched_dir.exists and matched_dir.is_directory
match_text = ''
else
matched_dir, match_text = get_dir_and_leftover tostring(@dir / path)
return matched_dir, match_text
_join: (words) =>
parts = {}
for w in *words
table.insert parts, w.word
table.insert parts, w.trailing_spaces
return table.join parts
select: (text, item, completion_opts) =>
unless item
return @run text
if completion_opts.name == 'cd'
if tostring(item[1]) == './'
@dir = item.file
return text: ''
else
relpath = normalized_relative_path @dir, item.file
return text: "cd #{relpath}/"
if completion_opts.name == 'command'
-- commands are {commmand, parent_dir} tables
return text: item[1] .. ' '
if completion_opts.name == 'filepath'
relpath = normalized_relative_path @dir, item.file
return text: completion_opts.prefix .. relpath
run: (text) =>
words = @_parse text
if words[1].word == 'cd' and words[2]
new_dir = @dir / words[2].word
if new_dir.is_directory
@dir = new_dir
return text: ''
else
error 'No directory ' .. new_dir
return result: {working_directory: @dir, cmd: text}
interact.register
name: 'get_external_command'
description: ''
handler: (opts={}) ->
console_view = howl.ui.ConsoleView ExternalCommandConsole opts.path or howl.io.File.home_dir
app.window.command_panel\run console_view, text: opts.text
| 30.96875 | 99 | 0.642583 |
d9a6275745fa9836e3721518c7b247f186041616 | 96 | export modinfo = {
type: "command"
desc: "Nyan"
alias: {"nyan"}
func: ->
SetSky 55987937
} | 13.714286 | 18 | 0.614583 |
81b995943ae9a85a96d0d32945876a441db49d78 | 7,881 | -- Copyright 2012-2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import Settings from howl
append = table.insert
local scopes
layer_defs = {'default': {}}
defs = {}
watchers = {}
saved_scopes = {''}
predefined_types =
boolean: {
options: { true, false }
convert: (value) ->
return value if type(value) == 'boolean'
return true if value == 'true'
return false if value == 'false'
value
},
number: {
convert: (value) -> tonumber(value) or tonumber(tostring(value)) or value
validate: (value) -> type(value) == 'number'
},
positive_number: {
convert: (value) -> tonumber(value) or tonumber(tostring(value)) or value
validate: (value) -> type(value) == 'number' and value >= 0
},
string: {
convert: (value) -> tostring value
}
string_list: {
convert: (value) ->
what = type(value)
if what == 'table'
[tostring(v) for v in *value]
elseif what == 'string' and value\contains ','
[v.stripped for v in value\gmatch '[^,]+']
elseif what == 'string' and value.is_blank
{}
else
{ tostring value }
validate: (value) -> type(value) == 'table'
tostring: (value) ->
type(value) == 'table' and table.concat(value, ', ') or tostring value
}
broadcast = (name, value, is_local) ->
callbacks = watchers[name]
if callbacks
for callback in *callbacks
status, ret = pcall callback, name, value, is_local
if not status
log.error 'Error invoking config watcher: ' .. ret
get_def = (name) ->
def = defs[name]
error 'Undefined variable "' .. name .. '"', 2 if not def
def
validate = (def, value) ->
return if value == nil
def_valid = def.validate and def.validate(value)
if def_valid != nil
if not def_valid
error "Illegal option '#{value}' for '#{def.name}'"
else
return true
if def.options
options = type(def.options) == 'table' and def.options or def.options!
for option in *options
option = option[1] if type(option) == 'table'
return if option == value
error "Illegal option '#{value}' for '#{def.name}'"
convert = (def, value) ->
if def.convert
new_value = def.convert(value)
return new_value if new_value != nil
value
definitions = setmetatable {},
__index: (_, k) -> defs[k]
__newindex: -> error 'Attempt to write to read-only table `.definitions`'
__pairs: -> pairs defs
define = (var = {}) ->
for field in *{'name', 'description'}
error '`' .. field .. '` missing', 2 if not var[field]
if var.scope and var.scope != 'local' and var.scope != 'global'
error 'Unknown scope "' .. var.scope .. '"', 2
if var.type_of
var = moon.copy var
predef = predefined_types[var.type_of]
error('Unknown type"' .. var.type_of .. '"', 2) if not predef
for k,v in pairs predef
var[k] = v unless var[k] != nil
defs[var.name] = var
broadcast var.name, var.default, false
define_layer = (name, def={}) ->
error 'defaults not allowed' if def.defaults
layer_defs[name] = moon.copy(def)
layer_defs[name].defaults = {}
define
name: 'persist_config'
description: 'Whether to save the configuration values'
type: 'boolean'
default: true
define
name: 'save_config_on_exit'
description: 'Whether to automatically save the current configuration on exit'
type: 'boolean'
default: false
scope: 'global'
load_config = (force=false, dir=nil) ->
return if scopes and not force
settings = Settings dir
scopes = settings\load_system('config') or {}
local get
save_config = (dir=nil) ->
return unless scopes
settings = Settings dir
scopes_copy = {}
for scope, values in *saved_scopes
values = scopes[scope]
continue unless values
persisted_values = nil
if get 'persist_config', scope
persisted_values = values
else
persisted_values = {'persist_config': values['persist_config']}
empty = not next persisted_values
if persisted_values and not empty
scopes_copy[scope] = persisted_values
settings\save_system('config', scopes_copy)
set = (name, value, scope='', layer='default') ->
load_config! unless scopes
def = get_def name
error "Unknown layer '#{layer}'" if not layer_defs[layer]
if def.scope
if def.scope == 'local' and scope == ''
error 'Attempt to set a global value for local variable "' .. name .. '"', 2
if def.scope == 'global' and scope != ''
error 'Attempt to set a local value for global variable "' .. name .. '"', 2
value = convert def, value
validate def, value
unless scopes[scope]
scopes[scope] = {}
unless scopes[scope][name]
scopes[scope][name] = {}
scopes[scope][name][layer] = value
broadcast name, value, (scope != '' or layer != 'default')
set_default = (name, value, layer='default') ->
def = get_def name
error "Unknown layer '#{layer}'" if not layer_defs[layer]
value = convert def, value
validate def, value
layer_defs[layer].defaults[name] = value
broadcast name, value, true
get_default = (name, layer='default') ->
if layer_defs[layer].defaults
return layer_defs[layer].defaults[name]
parent = (scope) ->
pos = scope\rfind('/')
return '' unless pos
return scope\sub(1, pos - 1)
local _get
_get = (name, scope, layers) ->
values = scopes[scope] and scopes[scope][name]
values = {} if values == nil
if scope == ''
for _layer in *layers
value = values[_layer]
return value if value != nil
value = get_default name, _layer
return value if value != nil
else
for _layer in *layers
value = values[_layer]
return value if value != nil
if scope != ''
return _get(name, parent(scope), layers)
def = defs[name]
return def.default if def
get = (name, scope='', layer='default') ->
load_config! unless scopes
current_layer = layer
layers = {layer}
while current_layer
current_layer = layer_defs[current_layer].parent
append layers, current_layer
if layers[#layers] != 'default'
append layers, 'default'
_get name, scope, layers
reset = ->
scopes = {}
for _, layer_def in pairs layer_defs
layer_def.defaults = {}
watch = (name, callback) ->
list = watchers[name]
if not list
list = {}
watchers[name] = list
append list, callback
proxy_mt = {
__index: (proxy, key) -> get(key, proxy._scope, proxy._read_layer)
__newindex: (proxy, key, value) -> set(key, value, proxy._scope, proxy._write_layer)
}
local proxy
proxy = (scope, write_layer='default', read_layer=write_layer) ->
_proxy = {
clear: => scopes[@_scope] = {}
for_layer: (layer) -> proxy scope, layer
_scope: scope
_write_layer: write_layer
_read_layer: read_layer
}
setmetatable _proxy, proxy_mt
scope_for_file = (file) -> 'file'..file
for_file = (file) -> proxy scope_for_file file
for_layer = (layer) -> proxy '', layer
merge = (scope, target_scope) ->
if scopes[scope]
scopes[target_scope] or= {}
target = scopes[target_scope]
source = scopes[scope]
for layer, layer_config in pairs source
if target[layer]
for name, value in pairs layer_config
target[layer][name] = value
else
target[layer] = moon.copy layer_config
replace = (scope, target_scope) ->
scopes[target_scope] = {}
merge scope, target_scope
delete = (scope) ->
error 'Cannot delete global scope' if scope == ''
scopes[scope] = nil
config = {
:definitions
:load_config
:save_config
:define
:define_layer
:set
:set_default
:get
:watch
:reset
:proxy
:scope_for_file
:for_file
:for_layer
:replace
:merge
:delete
}
return setmetatable config, {
__index: (t, k) -> rawget(config, k) or get k
__newindex: (t, k, v) ->
if rawget config, k
config[k] = v
else
set k, v
}
| 24.783019 | 86 | 0.642431 |
30eff9f282ad740dfbe95e1ca7de112800eda76c | 1,731 | class
new: (@x, @y, @w, @h) =>
@acc = 14
@dx = 0
@dy = 0
@frc_x = 0.35
@frc_y = 2
@gravity = 30
@grounded = false
@jump_force = 8
@keys = {
"right": "right"
"left": "left"
"jump": "space"
}
@wall = 0
@wall_jump = {
x: 8
y: 7
}
update: (dt) =>
with love.keyboard
if .isDown @keys["right"]
@dx += @acc * dt
if .isDown @keys["left"]
@dx -= @acc * dt
@dx -= (@dx / @frc_x) * dt
@dy -= (@dy / @frc_y) * dt
@x, @y, @cols = world\move @, @x + @dx, @y + @dy
@grounded = false
@wall = 0
for c in *@cols
with c.normal
unless .y == 0
if .y == -1
@grounded = true
@dy = 0
unless .x == 0
@dx = 0
@wall = .x unless @grounded
dx, dy = c.other.apply! if c.other.apply
@dx = dx or @dx
@dy = dy or @dy
----------------------------------
-- noob
----------------------------------
if game.noob
@dx -= @wall * dt * 0.5
@dy += @gravity * 0.75 * dt
else
@dy += @gravity * dt
@dx -= @wall * dt * 0.05
with game
ww, wy, ww, wh = .camera\getWorld!
.camera.x = math.lerp .camera.x, @x + @dx, dt * 2
.camera.y = math.lerp .camera.y, @y + @dy, dt * 2
.camera.angle = math.lerp .camera.angle, -@dx * 0.015, dt * 5
press: (key) =>
if key == @keys["jump"]
if @grounded
@dy = -@jump_force
else
@dx = @wall_jump.x * @wall unless @wall == 0
@dy = -@wall_jump.y unless @wall == 0
draw: =>
with lg
.setColor 255, 255, 255
.draw game.sprites.player[0], @x, @y
| 19.449438 | 67 | 0.410168 |
dc6f615224498036310dd12eccd9b0d78b90a4a8 | 11,866 | Dorothy!
EditorView = require "View.Control.Trigger.Editor"
ExprEditor = require "Control.Trigger.ExprEditor"
SelectionItem = require "Control.Basic.SelectionItem"
ExprChooser = require "Control.Trigger.ExprChooser"
SelectionPanel = require "Control.Basic.SelectionPanel"
InputBox = require "Control.Basic.InputBox"
MessageBox = require "Control.Basic.MessageBox"
TriggerDef = require "Data.TriggerDef"
import Expressions,ToEditText from TriggerDef
import CompareTable,Path from require "Lib.Utils"
TriggerScope = Class
__initc:=>
@scrollArea = nil
@panel = nil
@triggerBtn = nil
@changeTrigger = (button)->
if @triggerBtn
@triggerBtn.checked = false
@panel\removeChild @triggerBtn.exprEditor,false
@triggerBtn = if button and button.checked then button else nil
if @triggerBtn
if not @triggerBtn.exprEditor
{width:panelW,height:panelH} = @panel
listMenuW = @scrollArea.width
exprEditor = with ExprEditor {
type:"Action"
x:panelW/2+listMenuW/2
y:panelH/2
width:panelW-listMenuW
height:panelH-20
}
\loadExpr @triggerBtn.file
if @editor.localScope.currentGroup == "Built-In"
.triggerMenu.enabled = false
@triggerBtn.exprEditor = exprEditor
@triggerBtn\slot "Cleanup",->
parent = exprEditor.parent
if parent
parent\removeChild exprEditor
else
exprEditor\cleanup!
@panel\addChild @triggerBtn.exprEditor
__init:(menu,path,prefix)=>
@_menu = menu
@_path = path
@_prefix = prefix
@_currentGroup = ""
@_groups = nil
@_groupOffset = {}
@items = {}
@files = {}
@_menu\slot "Cleanup",->
for _,item in pairs @items
item\cleanup! unless item.parent
updateItems:=>
path = @path
prefix = @prefix
defaultFolder = path.."Default"
oContent\mkdir defaultFolder unless oContent\exist defaultFolder
@_groups = Path.getFolders path
table.sort @_groups
table.insert @_groups,1,"Built-In"
files = Path.getAllFiles path,"action"
for i = 1,#files
files[i] = prefix..files[i]
for builtinFile in *Path.getAllFiles editor.builtinActionPath,"action"
table.insert files,editor.builtinActionPath.."/"..builtinFile
filesToAdd,filesToDel = CompareTable @files,files
allItemsUpdated = #filesToDel == #@files
@files = files
for file in *filesToAdd
appendix = Path.getFilename file
group = file\sub(1,-#appendix-2)\match "([^\\/]*)$"
item = with SelectionItem {
text:Path.getName file
width:@_menu.width-20
height:35
}
.file = file
.group = group
\slot "Tapped",@@changeTrigger
@items[file] = item
for file in *filesToDel
item = @items[file]
if @@triggerBtn == item
@@triggerBtn = nil
if item.parent
item.parent\removeChild item
else
item\cleanup!
@items[file] = nil
@currentGroup = (@_currentGroup == "" or allItemsUpdated) and "Default" or @_currentGroup
currentGroup:property => @_currentGroup,
(group)=>
@_groupOffset[@_currentGroup] = @@scrollArea.offset
@_currentGroup = group
groupItems = for _,item in pairs @items
continue if item.group ~= group
item
table.sort groupItems,(itemA,itemB)-> itemA.text < itemB.text
with @_menu
\removeAllChildrenWithCleanup false
for item in *groupItems
\addChild item
@@scrollArea.offset = oVec2.zero
@@scrollArea.viewSize = \alignItems!
@@scrollArea.offset = @_groupOffset[@_currentGroup] or oVec2.zero
if group == "Built-In"
for button in *{@@editor.newBtn,@@editor.addBtn,@@editor.delBtn}
button.enabled = false
button\perform CCSequence {
oScale 0.3,0,0,oEase.OutQuad
CCHide!
}
else
for button in *{@@editor.newBtn,@@editor.addBtn,@@editor.delBtn}
if not button.enabled
button.enabled = true
button\perform CCSequence {
CCShow!
oScale 0.3,1,1,oEase.OutQuad
}
menuItems:property => @_menu.children
groups:property => @_groups
prefix:property => editor[@_prefix]
path:property => editor[@_path]
menu:property => @_menu
Class
__partial:=>
EditorView title:"Action Editor", scope:false
__init:(args)=>
{width:panelW,height:panelH} = @panel
@firstDisplay = true
TriggerScope.editor = @
TriggerScope.scrollArea = @listScrollArea
TriggerScope.panel = @panel
@localScope = TriggerScope @localListMenu,
"actionFullPath",
"actionFolder"
@listScrollArea\setupMenuScroll @localListMenu
@listScrollArea.viewSize = @localListMenu\alignItems!
lastGroupListOffset = oVec2.zero
@groupBtn\slot "Tapped",->
scope = @localScope
groups = for group in *scope.groups
continue if group == "Default" or group == scope.currentGroup
group
table.insert groups,1,"Default" if scope.currentGroup ~= "Default"
table.insert groups,"<NEW>"
table.insert groups,"<DEL>"
with SelectionPanel {
title:"Current Group"
subTitle:scope.currentGroup
width:180
items:groups
itemHeight:40
fontSize:20
}
.scrollArea.offset = lastGroupListOffset
.menu.children[#.menu.children-1].color = ccColor3 0x80ff00
.menu.children.last.color = ccColor3 0xff0080
\slot "Selected",(item)->
return unless item
lastGroupListOffset = .scrollArea.offset
switch item
when "<NEW>"
with InputBox text:"New Group Name"
\slot "Inputed",(result)->
return unless result
if not result\match("^[_%a][_%w]*$")
MessageBox text:"Invalid Name!",okOnly:true
elseif oContent\exist scope.prefix..result
MessageBox text:"Group Exist!",okOnly:true
else
oContent\mkdir scope.path..result
scope\updateItems!
scope.currentGroup = result
@groupBtn.text = result
when "<DEL>"
text = if scope.currentGroup == "Default"
"Delete Actions\nBut Keep Group\n#{scope.currentGroup}"
else
"Delete Group\n#{scope.currentGroup}\nWith Actions"
with MessageBox text:text
\slot "OK",(result)->
return unless result
Path.removeFolder scope.path..scope.currentGroup.."/"
scope\updateItems!
scope.currentGroup = "Default"
@groupBtn.text = scope.currentGroup
else
scope.currentGroup = item
@groupBtn.text = item
@newBtn\slot "Tapped",->
with InputBox text:"New Action Name"
\slot "Inputed",(result)->
return unless result
if not result\match("^[_%a][_%w]*$")
MessageBox text:"Invalid Name!",okOnly:true
else
scope = @localScope
triggerFullPath = scope.path..scope.currentGroup.."/"..result..".action"
if oContent\exist triggerFullPath
MessageBox text:"Action Exist!",okOnly:true
else
trigger = Expressions.UnitAction\Create!
trigger[2][2] = result
oContent\saveToFile triggerFullPath,ToEditText trigger
codeFile = Path.getPath(triggerFullPath)..Path.getName(triggerFullPath)..".lua"
triggerCode = TriggerDef.ToCodeText trigger
oContent\saveToFile codeFile,triggerCode
scope\updateItems!
triggerFile = scope.prefix..scope.currentGroup.."/"..result..".action"
for item in *scope.menu.children
if item.file == triggerFile
item\emit "Tapped",item
break
@addBtn\slot "Tapped",->
MessageBox text:"Place Actions In\nFolders Under\n/Logic/Action/",okOnly:true
@delBtn\slot "Tapped",->
triggerBtn = TriggerScope.triggerBtn
if triggerBtn
with MessageBox text:"Delete Action\n#{triggerBtn.text}"
\slot "OK",(result)->
return unless result
filename = editor.gameFullPath..triggerBtn.file
oContent\remove filename
oContent\remove Path.getPath(filename)..Path.getName(filename)..".lua"
@localScope\updateItems!
else
MessageBox text:"No Action Selected!",okOnly:true
with @copyBtn
.copying = false
.targetFile = nil
.targetData = nil
\slot "Tapped",->
triggerBtn = TriggerScope.triggerBtn
if not triggerBtn
MessageBox text:"No Action Selected!",okOnly:true
return
if @copyBtn.copying and @localScope.currentGroup == "Built-In"
MessageBox text:"Can`t Add Action\nHere!",okOnly:true
return
@copyBtn.copying = not @copyBtn.copying
if @copyBtn.copying
@copyBtn.text = "Paste"
@copyBtn.color = ccColor3 0xff0080
@copyBtn.targetFile = triggerBtn.file
@copyBtn.targetData = triggerBtn.exprEditor.exprData
else
@copyBtn.text = "Copy"
@copyBtn.color = ccColor3 0x00ffff
targetFilePath = [email protected]
triggerName = Path.getName(targetFilePath).."Copy"
scope = @localScope
newPath = scope.path..scope.currentGroup.."/"..triggerName
count = 0
filename = newPath..".action"
while oContent\exist filename
count += 1
filename = newPath..tostring(count)..".action"
triggerName ..= tostring count if count > 1
exprData = @copyBtn.targetData
oldName = exprData[2][2]
exprData[2][2] = triggerName
oContent\saveToFile filename,ToEditText(exprData)
exprData[2][2] = oldName
scope\updateItems!
@copyBtn.targetFile = nil
@copyBtn.targetData = nil
@closeBtn\slot "Tapped",->
if @localScope.menuItems
for item in *@localScope.menuItems
exprEditor = item.exprEditor
if exprEditor and exprEditor.modified
exprEditor.modified = false
exprEditor\save!
@hide!
@gslot "Scene.Action.ChangeName",(triggerName)->
TriggerScope.triggerBtn.text = triggerName
file = TriggerScope.triggerBtn.file
TriggerScope.triggerBtn.file = Path.getPath(file)..triggerName..".action"
@closeEvent = @gslot "Scene.Action.Close",-> @hide!
currentAction:property =>
if TriggerScope.triggerBtn
TriggerScope.triggerBtn.file
else
nil,
(value)=>
item = @localScope.items[value]
if item
@localScope.currentGroup = item.group
if item
item\emit "Tapped",item
if editor.startupData and editor.startupData.actionLine
item.exprEditor.targetLine = editor.startupData.actionLine
currentLine:property =>
if TriggerScope.triggerBtn and TriggerScope.triggerBtn.exprEditor
TriggerScope.triggerBtn.exprEditor.selectedLine
else
nil
show:=>
@closeEvent.enabled = true
@panel\schedule once ->
@localScope\updateItems!
@groupBtn.text = @localScope.currentGroup
if @firstDisplay
@firstDisplay = false
if editor.startupData and editor.startupData.action
@currentAction = editor.startupData.action
@visible = true
@closeBtn.scaleX = 0
@closeBtn.scaleY = 0
@closeBtn\perform oScale 0.3,1,1,oEase.OutBack
@panel.opacity = 0
@panel\perform CCSequence {
oOpacity 0.3,1,oEase.OutQuad
CCCall ->
@listScrollArea.touchEnabled = true
@localListMenu.enabled = true
@editMenu.enabled = true
@opMenu.enabled = true
for control in *editor.children
if control ~= @ and control.__class ~= ExprChooser
control.visibleState = control.visible
control.visible = false
}
hide:=>
@closeEvent.enabled = false
for control in *editor.children
if control ~= @ and control.__class ~= ExprChooser
control.visible = control.visibleState
@listScrollArea.touchEnabled = false
@localListMenu.enabled = false
@editMenu.enabled = false
@opMenu.enabled = false
@closeBtn\perform oScale 0.3,0,0,oEase.InBack
@panel\perform oOpacity 0.3,0,oEase.OutQuad
@perform CCSequence {
CCDelay 0.3
CCHide!
}
| 32.244565 | 92 | 0.660964 |
c1784293293750775a380f4e93b83c9bb56e5b4f | 228 | config = require "lapis.cmd.nginx.templates.config"
import compile_config from require "lapis.cmd.nginx"
env = setmetatable {}, __index: (key) => "<%- #{key\lower!} %>"
compile_config config, env, os_env: false, header: false
| 32.571429 | 63 | 0.714912 |
88ff4ce91cf3fda1e0bbad48eee23082abe2d045 | 2,275 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import app, interact from howl
class SearchInteraction
run: (@finish, @operation, @type, opts={}) =>
@searcher = app.editor.searcher
@keymap = moon.copy @keymap
for keystroke in *opts.backward_keys
@keymap[keystroke] = -> @searcher\previous!
for keystroke in *opts.forward_keys
@keymap[keystroke] = -> @searcher\next!
app.window.command_line.title = opts.title
on_update: (text) =>
@searcher[@operation] @searcher, text, @type
help: {
{
key: 'up'
action: 'Select previous match'
}
{
key: 'down'
action: 'Select next match'
}
}
keymap:
up: => @searcher\previous!
down: => @searcher\next!
enter: => self.finish true
escape: => self.finish false
interact.register
name: 'search'
description: ''
factory: SearchInteraction
interact.register
name: 'forward_search'
description: ''
handler: ->
interact.search 'forward_to', 'plain'
title: 'Forward Search'
forward_keys: howl.bindings.keystrokes_for('buffer-search-forward', 'editor')
backward_keys: howl.bindings.keystrokes_for('buffer-search-backward', 'editor')
interact.register
name: 'backward_search'
description: ''
handler: ->
interact.search 'backward_to', 'plain'
title: 'Backward Search'
forward_keys: howl.bindings.keystrokes_for('buffer-search-forward', 'editor')
backward_keys: howl.bindings.keystrokes_for('buffer-search-backward', 'editor')
interact.register
name: 'forward_search_word'
description: ''
handler: ->
interact.search 'forward_to', 'word',
title: 'Forward Word Search'
forward_keys: howl.bindings.keystrokes_for('buffer-search-word-forward', 'editor')
backward_keys: howl.bindings.keystrokes_for('buffer-search-word-backward', 'editor')
interact.register
name: 'backward_search_word'
description: ''
handler: ->
interact.search 'backward_to', 'word',
title: 'Backward Word Search',
forward_keys: howl.bindings.keystrokes_for('buffer-search-word-forward', 'editor')
backward_keys: howl.bindings.keystrokes_for('buffer-search-word-backward', 'editor')
| 29.934211 | 90 | 0.686593 |
ccb189e9ec2da74473ce43df93a0600466908939 | 9,690 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
GFile = require 'ljglibs.gio.file'
GFileInfo = require 'ljglibs.gio.file_info'
glib = require 'ljglibs.glib'
{:park, :resume, :resume_with_error, :wait} = howl.dispatch
import PropertyObject from howl.util.moon
append = table.insert
file_types = {
[tonumber GFileInfo.TYPE_DIRECTORY]: 'directory',
[tonumber GFileInfo.TYPE_SYMBOLIC_LINK]: 'symlink',
[tonumber GFileInfo.TYPE_SPECIAL]: 'special',
[tonumber GFileInfo.TYPE_REGULAR]: 'regular',
[tonumber GFileInfo.TYPE_MOUNTABLE]: 'mountable',
[tonumber GFileInfo.TYPE_UNKNOWN]: 'unknown',
}
class File extends PropertyObject
TYPE_DIRECTORY: GFileInfo.TYPE_DIRECTORY
TYPE_SYMBOLIC_LINK: GFileInfo.TYPE_SYMBOLIC_LINK
TYPE_SPECIAL: GFileInfo.TYPE_SPECIAL
TYPE_REGULAR: GFileInfo.TYPE_REGULAR
TYPE_MOUNTABLE: GFileInfo.TYPE_MOUNTABLE
TYPE_UNKNOWN: GFileInfo.TYPE_UNKNOWN
@async: false
tmpfile: ->
file = File assert os.tmpname!
file.touch if not file.exists
file
tmpdir: ->
with File os.tmpname!
\delete! if .exists
\mkdir!
with_tmpfile: (f) ->
file = File.tmpfile!
result = { pcall f, file }
file\delete_all! if file.exists
if result[1]
table.unpack result, 2
else
error result[2]
is_absolute: (path) ->
(path\match('^/') or path\match('^%a:\\\\')) != nil
expand_path: (path) ->
expanded_home = File.home_dir.path .. File.separator
res = path\gsub ".+#{File.separator}~#{File.separator}", expanded_home
res\gsub "^~#{File.separator}", expanded_home
separator: jit.os == 'Windows' and '\\' or '/'
new: (target, cwd, opts) =>
error "missing parameter #1 for File()", 3 unless target
t = typeof target
if t == 'File'
@gfile = target.gfile
@path = target.path
else
if t == 'string'
if cwd and not self.is_absolute target
target = GFile(tostring cwd)\get_child(target).path
@gfile = GFile tostring target
else
@gfile = target
@path = @gfile.path
if opts
@_ft = opts.type
super!
@property basename: get: => @gfile.basename
@property display_name: get: =>
base = @basename
@is_directory and "#{base}#{File.separator}" or base
@property extension: get: => @basename\match('%.([^.]+)$')
@property uri: get: => @gfile.uri
@property is_directory: get: => @_has_file_type GFileInfo.TYPE_DIRECTORY
@property is_link: get: => @_has_file_type GFileInfo.TYPE_SYMBOLIC_LINK
@property is_special: get: => @_has_file_type GFileInfo.TYPE_SPECIAL
@property is_regular: get: => @_has_file_type GFileInfo.TYPE_REGULAR
@property is_mountable: get: => @_has_file_type GFileInfo.TYPE_MOUNTABLE
@property is_hidden: get: => @exists and @_info!.is_hidden
@property is_backup: get: => @exists and @_info!.is_backup
@property size: get: => @_info!.size
@property exists: get: => @gfile.exists
@property readable: get: => @exists and @_info('access')\get_attribute_boolean 'access::can-read'
@property etag: get: => @exists and @_info('etag').etag
@property modified_at: get: => @exists and @_info('time')\get_attribute_uint64 'time::modified'
@property short_path: get: =>
return "~" if @path == File.home_dir.path
@path\gsub "^#{File.home_dir.path}#{File.separator}", '~/'
@property root_dir:
get: =>
file = @
while file.parent
file = file.parent
return file
@property writeable: get: =>
if @exists
return @_info('access')\get_attribute_boolean 'access::can-write'
else
return @parent.exists and @parent.writeable
@property file_type: get: => file_types[tonumber @_file_type]
@property contents:
get: => @gfile\load_contents!
set: (contents) =>
with @_assert io.open @path, 'wb'
\write tostring contents
\close!
@property parent:
get: =>
parent = @gfile.parent
return if parent then File(parent) else nil
@property children:
get: =>
File.async and @children_async or @children_sync
@property children_sync:
get: =>
files = {}
enum = @gfile\enumerate_children 'standard::name,standard::type', GFile.QUERY_INFO_NONE
while true
info = enum\next_file!
unless info
enum\close!
return files
append files, File(enum\get_child(info), nil, type: info.filetype)
@property children_async:
get: =>
handle = park 'enumerate-children-async'
@gfile\enumerate_children_async 'standard::name,standard::type', nil, nil, (status, ret, err_code) ->
if status
resume handle, ret
else
resume_with_error handle, "#{ret} (#{err_code})"
enum = wait handle
files = {}
while true
info = enum\next_file!
unless info
enum\close!
return files
append files, File(enum\get_child(info), nil, type: info.filetype)
open: (mode = 'r', func) =>
fh = assert io.open @path, mode
if func
ret = table.pack pcall func, fh
fh\close!
error ret[2] unless ret[1]
return table.unpack ret, 2, ret.n
fh
read: (...) =>
args = {...}
@open 'r', (fh) -> fh\read table.unpack args
join: (...) =>
root = @gfile
root = root\get_child(tostring child) for child in *{...}
File root
relative_to_parent: (parent) =>
parent.gfile\get_relative_path @gfile
is_below: (dir) => @relative_to_parent(dir) != nil
mkdir: => @gfile\make_directory!
mkdir_p: => @gfile\make_directory_with_parents!
delete: => @gfile\delete!
delete_all: =>
if @is_directory
entries = @find!
entry\delete! for entry in *entries when not entry.is_directory
directories = [f for f in *entries when f.is_directory]
table.sort directories, (a,b) -> a.path > b.path
dir\delete! for dir in *directories
@delete!
touch: => @contents = '' if not @exists
find: (options = {}) =>
error "Can't invoke find on a non-directory", 1 if not @is_directory
filters = {}
if options.filter then append filters, options.filter
filter = (entry) -> for f in *filters do return true if f entry
files = {}
directories = {}
dir = self
on_enter = options.on_enter
while dir
if on_enter and 'break' == on_enter(dir, files)
return files, true
ok, children = pcall -> dir.children
unless ok
dir = table.remove directories
append(files, dir) if dir
continue
if options.sort then table.sort children, (a,b) -> a.basename < b.basename
for entry in *children
continue if filter entry
if entry.is_directory
append directories, 1, entry
else
append files, entry
dir = table.remove directories
append(files, dir) if dir
files, false
find_paths: (opts = {}) =>
separator = File.separator
exclude_directories = opts.exclude_directories
exclude_non_directories = opts.exclude_non_directories
get_children = if File.async then
(dir) ->
handle = park 'enumerate-children-async'
dir\enumerate_children_async 'standard::name,standard::type', nil, nil, (status, ret, err_code) ->
if status
resume handle, ret
else
resume handle, nil
wait handle
else
(dir) ->
dir\enumerate_children 'standard::name,standard::type', GFile.QUERY_INFO_NONE
filter = opts.filter
on_enter = opts.on_enter
scan_dir = (dir, base, list = {}, depth=1) ->
return if opts.max_depth and depth > opts.max_depth
enum = get_children dir
return unless enum
while true
info = enum\next_file!
unless info
enum\close!
break
if info.filetype == GFileInfo.TYPE_DIRECTORY
f = enum\get_child info
path = "#{base}#{info.name}#{separator}"
continue if filter and filter(path)
if on_enter and 'break' == on_enter(path, list)
return true
append list, path unless exclude_directories
scan_dir f, path, list, depth + 1
else
path = "#{base}#{info.name}"
continue if filter and filter(path)
append list, path unless exclude_non_directories
error "Can't invoke find on a non-directory", 1 if not @is_directory
paths = {}
if on_enter and 'break' == on_enter(".#{separator}", paths)
return paths, true
partial = scan_dir GFile(@path), '', paths
paths, partial
copy: (dest, flags) =>
@gfile\copy File(dest).gfile, flags, nil, nil
tostring: => tostring @path or @uri
_info: (namespace = 'standard') =>
@gfile\query_info "#{namespace}::*", GFile.QUERY_INFO_NONE
@property _file_type: get: =>
@_ft or= @_info!.filetype
@_ft
_has_file_type: (t) =>
return @_ft == t if @_ft != nil
return false unless @exists
@_ft = @_info!.filetype
@_ft == t
@meta {
__tostring: => @tostring!
__div: (op) => @join op
__concat: (op1, op2) ->
if op1.__class == File
op1\join(op2)
else
tostring(op1) .. tostring(op2)
__eq: (op1, op2) -> op1\tostring! == op2\tostring!
__lt: (op1, op2) -> op1\tostring! < op2\tostring!
__le: (op1, op2) -> op1\tostring! <= op2\tostring!
}
_assert: (...) =>
status, msg = ...
error @tostring! .. ': ' .. msg, 3 if not status
...
File.home_dir = File glib.get_home_dir!
File.__base.rm = File.delete
File.__base.unlink = File.delete
File.__base.rm_r = File.delete_all
return File
| 28.00578 | 108 | 0.630547 |
e37f4d9ef9d8d6c3f906c1309528647e21168ff9 | 1,297 | import Model, enum from require "lapis.db.cassandra.model"
import types, create_table from require "lapis.db.cassandra.schema"
import drop_tables, truncate_tables from require "lapis.spec.db"
class Users extends Model
@create_table: =>
drop_tables @
create_table @table_name!, {
{"id", types.integer primary_key: true}
{"name", types.varchar}
}
@truncate: =>
truncate_tables @
class Posts extends Model
@timestamp: true
@create_table: =>
drop_tables @
create_table @table_name!, {
{"id", types.id}
{"user_id", types.integer}
{"title", types.varchar}
{"body", types.varchar}
{"created_at", types.timestamp}
{"updated_at", types.timestamp}
}
@truncate: =>
truncate_tables @
class Likes extends Model
@primary_key: {"user_id", "post_id"}
@timestamp: true
@relations: {
{"user", belongs_to: "Users"}
{"post", belongs_to: "Posts"}
}
@create_table: =>
drop_tables @
create_table @table_name!, {
{"user_id", types.integer}
{"post_id", types.integer}
{"count", types.integer}
{"created_at", types.timestamp}
{"updated_at", types.timestamp}
"PRIMARY KEY (user_id, post_id)"
}
@truncate: =>
truncate_tables @
{:Users, :Posts, :Likes}
| 22.362069 | 67 | 0.632999 |
ec55d4607cf4b5a619923a2545a1e60fc5da1e40 | 12,500 | -- Copyright 2013-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
ffi = require 'ffi'
ffi.cdef [[
typedef char gchar;
typedef long glong;
typedef unsigned long gulong;
typedef int gint;
typedef unsigned int guint;
typedef int8_t gint8;
typedef int16_t gint16;
typedef int32_t gint32;
typedef int64_t gint64;
typedef uint8_t guint8;
typedef uint16_t guint16;
typedef uint32_t guint32;
typedef uint64_t guint64;
typedef gint gboolean;
typedef unsigned long gsize;
typedef signed long gssize;
typedef void * gpointer;
typedef int32_t GQuark;
typedef guint32 gunichar;
typedef guint64 guint64;
typedef gint64 goffset;
typedef double gdouble;
typedef float gfloat;
typedef const void * gconstpointer;
typedef int GPid;
/* version definitions */
extern const guint glib_major_version;
extern const guint glib_minor_version;
extern const guint glib_micro_version;
extern const guint glib_binary_age;
extern const guint glib_interface_age;
const gchar * glib_check_version (guint required_major,
guint required_minor,
guint required_micro);
/* GError definitions */
typedef struct {
GQuark domain;
gint code;
gchar * message;
} GError;
void g_error_free (GError *error);
/* utf8 helper functions */
glong g_utf8_pointer_to_offset(const gchar *str, const gchar *pos);
gchar * g_utf8_offset_to_pointer(const gchar *str, glong offset);
gchar * g_utf8_find_next_char (const gchar *p, const gchar *end);
glong g_utf8_strlen(const gchar *str, gssize len);
gchar * g_utf8_strdown(const gchar *str, gssize len);
gchar * g_utf8_strup(const gchar *str, gssize len);
gchar * g_utf8_strreverse(const gchar *str, gssize len);
gint g_utf8_collate(const gchar *str1, const gchar *str2);
gchar * g_utf8_substring(const gchar *str, glong start_pos, glong end_pos);
gboolean g_utf8_validate (const gchar *str, gssize max_len, const gchar **end);
gchar * g_utf8_make_valid (const gchar *str, gssize len);
gint g_unichar_to_utf8(gunichar c, gchar *outbuf);
gchar * g_strndup(const gchar *str, gssize n);
/* Callback definitions */
typedef void (*GCallback) (void);
typedef void (*GVCallback1) (gpointer);
typedef void (*GVCallback2) (gpointer, gpointer);
typedef void (*GVCallback3) (gpointer, gpointer, gpointer);
typedef void (*GVCallback4) (gpointer, gpointer, gpointer, gpointer);
typedef void (*GVCallback5) (gpointer, gpointer, gpointer, gpointer, gpointer);
typedef void (*GVCallback6) (gpointer, gpointer, gpointer, gpointer, gpointer, gpointer);
typedef void (*GVCallback7) (gpointer, gpointer, gpointer, gpointer, gpointer, gpointer, gpointer);
typedef gboolean (*GBCallback1) (gpointer);
typedef gboolean (*GBCallback2) (gpointer, gpointer);
typedef gboolean (*GBCallback3) (gpointer, gpointer, gpointer);
typedef gboolean (*GBCallback4) (gpointer, gpointer, gpointer, gpointer);
typedef gboolean (*GBCallback5) (gpointer, gpointer, gpointer, gpointer, gpointer);
typedef gboolean (*GBCallback6) (gpointer, gpointer, gpointer, gpointer, gpointer, gpointer);
typedef gboolean (*GBCallback7) (gpointer, gpointer, gpointer, gpointer, gpointer, gpointer, gpointer);
typedef gboolean (*GCallback1) (gpointer);
typedef gboolean (*GCallback2) (gpointer, gpointer);
typedef gboolean (*GCallback3) (gpointer, gpointer, gpointer);
typedef gboolean (*GCallback4) (gpointer, gpointer, gpointer, gpointer);
/* main loop */
typedef GCallback1 GSourceFunc;
typedef GCallback1 GDestroyNotify;
typedef void (*GChildWatchFunc) (GPid pid, gint status, gpointer user_data);
typedef gpointer GMainContext;
GMainContext g_main_context_default(void);
gboolean g_main_context_iteration(GMainContext *context, gboolean may_block);
guint g_idle_add_full(gint priority,
GSourceFunc function,
gpointer data,
GDestroyNotify notify);
guint g_timeout_add_full(gint priority,
guint interval,
GSourceFunc function,
gpointer data,
GDestroyNotify notify);
gboolean g_source_remove (guint tag);
guint g_child_watch_add (GPid pid, GChildWatchFunc function, gpointer data);
enum GPriority {
G_PRIORITY_HIGH = -100,
G_PRIORITY_DEFAULT = 0,
G_PRIORITY_HIGH_IDLE = 100,
G_PRIORITY_DEFAULT_IDLE = 200,
G_PRIORITY_LOW = 300
};
/* GRegex */
typedef enum {
G_REGEX_CASELESS = 1 << 0,
G_REGEX_MULTILINE = 1 << 1,
G_REGEX_DOTALL = 1 << 2,
G_REGEX_EXTENDED = 1 << 3,
G_REGEX_ANCHORED = 1 << 4,
G_REGEX_DOLLAR_ENDONLY = 1 << 5,
G_REGEX_UNGREEDY = 1 << 9,
G_REGEX_RAW = 1 << 11,
G_REGEX_NO_AUTO_CAPTURE = 1 << 12,
G_REGEX_OPTIMIZE = 1 << 13,
G_REGEX_FIRSTLINE = 1 << 18,
G_REGEX_DUPNAMES = 1 << 19,
G_REGEX_NEWLINE_CR = 1 << 20,
G_REGEX_NEWLINE_LF = 1 << 21,
G_REGEX_NEWLINE_CRLF = G_REGEX_NEWLINE_CR | G_REGEX_NEWLINE_LF,
G_REGEX_NEWLINE_ANYCRLF = G_REGEX_NEWLINE_CR | 1 << 22,
G_REGEX_BSR_ANYCRLF = 1 << 23,
G_REGEX_JAVASCRIPT_COMPAT = 1 << 25
} GRegexCompileFlags;
typedef enum {
G_REGEX_MATCH_ANCHORED = 1 << 4,
G_REGEX_MATCH_NOTBOL = 1 << 7,
G_REGEX_MATCH_NOTEOL = 1 << 8,
G_REGEX_MATCH_NOTEMPTY = 1 << 10,
G_REGEX_MATCH_PARTIAL = 1 << 15,
G_REGEX_MATCH_NEWLINE_CR = 1 << 20,
G_REGEX_MATCH_NEWLINE_LF = 1 << 21,
G_REGEX_MATCH_NEWLINE_CRLF = G_REGEX_MATCH_NEWLINE_CR | G_REGEX_MATCH_NEWLINE_LF,
G_REGEX_MATCH_NEWLINE_ANY = 1 << 22,
G_REGEX_MATCH_NEWLINE_ANYCRLF = G_REGEX_MATCH_NEWLINE_CR | G_REGEX_MATCH_NEWLINE_ANY,
G_REGEX_MATCH_BSR_ANYCRLF = 1 << 23,
G_REGEX_MATCH_BSR_ANY = 1 << 24,
G_REGEX_MATCH_PARTIAL_SOFT = G_REGEX_MATCH_PARTIAL,
G_REGEX_MATCH_PARTIAL_HARD = 1 << 27,
G_REGEX_MATCH_NOTEMPTY_ATSTART = 1 << 28
} GRegexMatchFlags;
typedef struct {} GMatchInfo;
gint g_match_info_get_match_count (const GMatchInfo *match_info);
gboolean g_match_info_matches (const GMatchInfo *match_info);
gboolean g_match_info_next (GMatchInfo *match_info, GError **error);
gchar * g_match_info_fetch (const GMatchInfo *match_info, gint match_num);
void g_match_info_unref (GMatchInfo *match_info);
void g_match_info_free (GMatchInfo *match_info);
gboolean g_match_info_fetch_pos (const GMatchInfo *match_info,
gint match_num,
gint *start_pos,
gint *end_pos);
gboolean g_match_info_is_partial_match (const GMatchInfo *match_info);
typedef struct {} GRegex;
GRegex * g_regex_new (const gchar *pattern,
GRegexCompileFlags compile_options,
GRegexMatchFlags match_options,
GError **error);
void g_regex_unref (GRegex *regex);
const gchar * g_regex_get_pattern (const GRegex *regex);
gint g_regex_get_capture_count (const GRegex *regex);
gboolean g_regex_match (const GRegex *regex,
const gchar *string,
GRegexMatchFlags match_options,
GMatchInfo **match_info);
gboolean g_regex_match_full (const GRegex *regex,
const gchar *string,
gssize string_len,
gint start_position,
GRegexMatchFlags match_options,
GMatchInfo **match_info,
GError **error);
gchar * g_regex_escape_string (const gchar *string, gint length);
/* GList */
typedef struct {} GList;
GList * g_list_append (GList *list, gpointer data);
GList * g_list_prepend (GList *list, gpointer data);
GList * g_list_insert (GList *list, gpointer data, gint position);
GList * g_list_remove (GList *list, gconstpointer data);
GList * g_list_remove_all (GList *list, gconstpointer data);
void g_list_free (GList *list);
guint g_list_length (GList *list);
GList * g_list_nth (GList *list, guint n);
gpointer g_list_nth_data (GList *list, guint n);
/* GBytes */
typedef struct {} GBytes;
GBytes * g_bytes_new_static (gconstpointer data, gsize size);
GBytes * g_bytes_new (gconstpointer data, gsize size);
gsize g_bytes_get_size (GBytes *bytes);
gconstpointer g_bytes_get_data (GBytes *bytes, gsize *size);
GBytes * g_bytes_ref (GBytes *bytes);
void g_bytes_unref (GBytes *bytes);
/* Utility functions */
const gchar * g_get_home_dir (void);
gchar * g_get_current_dir (void);
gchar * g_strndup (const gchar *str, gsize n);
gpointer g_malloc0 (gsize n_bytes);
void g_free(gpointer mem);
void g_strfreev (gchar **str_array);
gpointer g_slice_alloc (gsize block_size);
gpointer g_slice_alloc0 (gsize block_size);
void g_slice_free1 (gsize block_size, gpointer mem_block);
/* Process spawning */
typedef enum {
G_SPAWN_DEFAULT = 0,
G_SPAWN_LEAVE_DESCRIPTORS_OPEN = 1 << 0,
G_SPAWN_DO_NOT_REAP_CHILD = 1 << 1,
/* look for argv[0] in the path i.e. use execvp() */
G_SPAWN_SEARCH_PATH = 1 << 2,
/* Dump output to /dev/null */
G_SPAWN_STDOUT_TO_DEV_NULL = 1 << 3,
G_SPAWN_STDERR_TO_DEV_NULL = 1 << 4,
G_SPAWN_CHILD_INHERITS_STDIN = 1 << 5,
G_SPAWN_FILE_AND_ARGV_ZERO = 1 << 6,
G_SPAWN_SEARCH_PATH_FROM_ENVP = 1 << 7
} GSpawnFlags;
typedef void (*GSpawnChildSetupFunc) (gpointer user_data);
gboolean g_spawn_async_with_pipes (const gchar *working_directory,
gchar **argv,
gchar **envp,
GSpawnFlags flags,
GSpawnChildSetupFunc child_setup,
gpointer user_data,
GPid *child_pid,
gint *standard_input,
gint *standard_output,
gint *standard_error,
GError **error);
void g_spawn_close_pid (GPid pid);
/* Shell-related Utilities */
gboolean g_shell_parse_argv (const gchar *command_line,
gint *argcp,
gchar ***argvp,
GError **error);
gchar * g_shell_quote (const gchar *unquoted_string);
gchar * g_shell_unquote (const gchar *quoted_string, GError **error);
/* Environment utilities */
const gchar * g_getenv (const gchar *variable);
gboolean g_setenv (const gchar *variable,
const gchar *value,
gboolean overwrite);
void g_unsetenv (const gchar *variable);
gchar ** g_listenv (void);
/* File utilities */
typedef enum {
G_FILE_TEST_IS_REGULAR = 1 << 0,
G_FILE_TEST_IS_SYMLINK = 1 << 1,
G_FILE_TEST_IS_DIR = 1 << 2,
G_FILE_TEST_IS_EXECUTABLE = 1 << 3,
G_FILE_TEST_EXISTS = 1 << 4
} GFileTest;
gboolean g_file_test (const gchar *filename,
GFileTest test);
gint64 g_get_monotonic_time (void);
gint64 g_get_real_time (void);
typedef struct {} GMappedFile;
GMappedFile * g_mapped_file_new (const gchar *filename,
gboolean writable,
GError **error);
void g_mapped_file_unref (GMappedFile *file);
gsize g_mapped_file_get_length (GMappedFile *file);
gchar * g_mapped_file_get_contents (GMappedFile *file);
]]
| 40.849673 | 105 | 0.616 |
aa7e585e6c3c52685faa2042097d6fb7978daae9 | 1,441 |
---
-- Luminary Console: Proxy for the modified version of lapis-console included
-- with the Luminary package (luminary.console).
--
-- This module should be required in your main lapis application (usually
-- web.moon) to provide a POST-only interface for the modified lapis-console
-- to direct it's AJAX requests.
--
-- TODO: Enable/disable this Application via lapis config file
-- TODO: Enable respond_to "GET" if enabled in lapis config file
--
import Application, respond_to, capture_errors_json, assert_error, yield_error
from require "lapis.application"
import assert_valid from require "lapis.validate"
import run, make from require "lapis.console"
class LuminaryRoutes extends Application
@path: "/luminary"
@name: "luminary_"
-- A path is needed for the console's AJAX to poke
[console: "/console"]: respond_to {
GET: make!
POST: capture_errors_json =>
@params.lang or= "moonscript"
@params.code or= ""
assert_valid @params, {
{ "lang", one_of: {"lua", "moonscript"} }
}
if @params.lang == "moonscript"
moonscript = require "moonscript.base"
fn, err = moonscript.loadstring @params.code
if err
{ json: { error: err } }
else
lines, queries = run @, fn
if lines
{ json: { :lines, :queries } }
else
{ json: { error: queries } }
}
| 29.408163 | 78 | 0.632894 |
d26961c1082d969abd34fbed0c3d7a621420b621 | 4,494 | db = require "lapis.db"
import escape_literal from db
import concat from table
append_all = (t, ...) ->
for i=1, select "#", ...
t[#t + 1] = select i, ...
extract_options = (cols) ->
options = {}
cols = for col in *cols
if type(col) == "table" and col[1] != "raw"
for k,v in pairs col
options[k] = v
continue
col
cols, options
entity_exists = (name) ->
name = db.escape_literal name
res = unpack db.select "COUNT(*) as c from pg_class where relname = #{name}"
res.c > 0
gen_index_name = (...) ->
parts = for p in *{...}
switch type(p)
when "string"
p
when "table"
if p[1] == "raw"
p[2]\gsub("[^%w]+$", "")\gsub("[^%w]+", "_")
else
continue
else
continue
concat(parts, "_") .. "_idx"
create_table = (name, columns) ->
buffer = {"CREATE TABLE IF NOT EXISTS #{db.escape_identifier name} ("}
add = (...) -> append_all buffer, ...
for i, c in ipairs columns
add "\n "
if type(c) == "table"
name, kind = unpack c
add db.escape_identifier(name), " ", tostring kind
else
add c
add "," unless i == #columns
add "\n" if #columns > 0
add ");"
db.query concat buffer
create_index = (tname, ...) ->
index_name = gen_index_name tname, ...
return if entity_exists index_name
columns, options = extract_options {...}
buffer = {"CREATE"}
append_all buffer, " UNIQUE" if options.unique
append_all buffer, " INDEX ",
db.escape_identifier(index_name),
" ON ", db.escape_identifier tname
if options.method
append_all buffer, " USING ", options.method
append_all buffer, " ("
for i, col in ipairs columns
append_all buffer, db.escape_identifier(col)
append_all buffer, ", " unless i == #columns
append_all buffer, ")"
if options.tablespace
append_all buffer, " TABLESPACE ", options.tablespace
if options.where
append_all buffer, " WHERE ", options.where
append_all buffer, ";"
db.query concat buffer
drop_index = (...) ->
index_name = gen_index_name ...
db.query "DROP INDEX IF EXISTS #{db.escape_identifier index_name}"
drop_table = (tname) ->
db.query "DROP TABLE IF EXISTS #{db.escape_identifier tname};"
add_column = (tname, col_name, col_type) ->
tname = db.escape_identifier tname
col_name = db.escape_identifier col_name
db.query "ALTER TABLE #{tname} ADD COLUMN #{col_name} #{col_type}"
drop_column = (tname, col_name) ->
tname = db.escape_identifier tname
col_name = db.escape_identifier col_name
db.query "ALTER TABLE #{tname} DROP COLUMN #{col_name}"
rename_column = (tname, col_from, col_to) ->
tname = db.escape_identifier tname
col_from = db.escape_identifier col_from
col_to = db.escape_identifier col_to
db.query "ALTER TABLE #{tname} RENAME COLUMN #{col_from} TO #{col_to}"
rename_table = (tname_from, tname_to) ->
tname_from = db.escape_identifier tname_from
tname_to = db.escape_identifier tname_to
db.query "ALTER TABLE #{tname_from} RENAME TO #{tname_to}"
class ColumnType
default_options: { null: false }
new: (@base, @default_options) =>
__call: (opts) =>
out = @base
for k,v in pairs @default_options
opts[k] = v unless opts[k] != nil
unless opts.null
out ..= " NOT NULL"
if opts.default != nil
out ..= " DEFAULT " .. escape_literal opts.default
if opts.unique
out ..= " UNIQUE"
if opts.primary_key
out ..= " PRIMARY KEY"
out
__tostring: => @__call @default_options
class TimeType extends ColumnType
__tostring: ColumnType.__tostring
__call: (opts) =>
base = @base
@base = base .. " with time zone" if opts.timezone
with ColumnType.__call @, opts
@base = base
C = ColumnType
T = TimeType
types = setmetatable {
serial: C "serial"
varchar: C "character varying(255)"
text: C "text"
time: T "timestamp"
date: C "date"
integer: C "integer", null: false, default: 0
numeric: C "numeric", null: false, default: 0
real: C "real", null: false, default: 0
double: C "double precision", null: false, default: 0
boolean: C "boolean", null: false, default: false
foreign_key: C "integer"
}, __index: (key) =>
error "Don't know column type `#{key}`"
{
:types, :create_table, :drop_table, :create_index, :drop_index, :add_column,
:drop_column, :rename_column, :rename_table, :entity_exists, :gen_index_name
}
| 24.692308 | 78 | 0.630841 |
3348b9c5e41797a5cda9a9c61531582b44160f2d | 1,558 | -- type checking for classes
_type = type
export type = (v) ->
base = _type v
if base == "table"
cls = v.__class
return cls.__name if cls
base
sauce3.console = require "sauce3/core/console"
sauce3.java = require "sauce3/core/java"
sauce3.File = require "sauce3/utils/File"
sauce3.Font = require "sauce3/utils/Font"
sauce3.Image = require "sauce3/utils/Image"
sauce3.Quad = require "sauce3/utils/Quad"
sauce3.file_system = require "sauce3/core/file_system"
sauce3.timer = require "sauce3/core/timer"
sauce3.graphics = require "sauce3/core/graphics"
sauce3.console = require "sauce3/core/console"
sauce3.system = require "sauce3/core/system"
sauce3.timer = require "sauce3/core/timer"
sauce3.audio = require "sauce3/core/audio"
import key_codes, button_codes from require "sauce3/wrappers"
sauce3._key_pressed = (key) ->
(sauce3.key_pressed key_codes[key]) if sauce3.key_pressed
sauce3._key_released = (key) ->
(sauce3.key_released key_codes[key]) if sauce3.key_released
sauce3._mouse_pressed = (x, y, button) ->
(sauce3.mouse_pressed button_codes[button]) if sauce3.mouse_pressed
sauce3._mouse_released = (x, y, button) ->
(sauce3.mouse_released button_codes[button]) if sauce3.mouse_released
sauce3._quit = ->
if sauce3.quit then sauce3.quit!
sauce3.audio.stop_all!
sauce3.run = ->
dt = sauce3.timer.get_delta!
sauce3.update(dt) if sauce3.update
sauce3.graphics.clear!
sauce3.graphics.origin!
sauce3.draw! if sauce3.draw
sauce3.graphics.present!
require "main"
| 27.333333 | 71 | 0.723363 |
0b781893d7c625c5b6403e03ec9e017d503311a4 | 7,457 |
import concat, insert from table
_G = _G
import type, pairs, ipairs, tostring, getfenv, setfenv from _G
import locked_fn, release_fn from require "lapis.util.functions"
punct = "[%^$()%.%[%]*+%-?]"
escape_patt = (str) ->
(str\gsub punct, (p) -> "%"..p)
html_escape_entities = {
['&']: '&'
['<']: '<'
['>']: '>'
['"']: '"'
["'"]: '''
}
html_unescape_entities = {}
for key,value in pairs html_escape_entities
html_unescape_entities[value] = key
html_escape_pattern = "[" .. concat([escape_patt char for char in pairs html_escape_entities]) .. "]"
escape = (text) ->
(text\gsub html_escape_pattern, html_escape_entities)
unescape = (text) ->
(text\gsub "(&[^&]-;)", (enc) ->
decoded = html_unescape_entities[enc]
decoded if decoded else enc)
strip_tags = (html) ->
html\gsub "<[^>]+>", ""
void_tags = {
"area"
"base"
"br"
"col"
"command"
"embed"
"hr"
"img"
"input"
"keygen"
"link"
"meta"
"param"
"source"
"track"
"wbr"
}
for tag in *void_tags
void_tags[tag] = true
------------------
element_attributes = (buffer, t) ->
return unless type(t) == "table"
for k,v in pairs t
if type(k) == "string" and not k\match "^__"
buffer\write " ", k, "=", '"', escape(tostring(v)), '"'
nil
element = (buffer, name, attrs, ...) ->
with buffer
\write "<", name
element_attributes(buffer, attrs)
if void_tags[name]
-- check if it has content
has_content = false
for thing in *{attrs, ...}
t = type thing
switch t
when "string"
has_content = true
break
when "table"
if thing[1]
has_content = true
break
unless has_content
\write "/>"
return buffer
\write ">"
\write_escaped attrs, ...
\write "</", name, ">"
class Buffer
builders: {
html_5: (...) ->
raw '<!DOCTYPE HTML>'
if type((...)) == "table"
html ...
else
html lang: "en", ...
}
new: (@buffer) =>
@old_env = {}
@i = #@buffer
@make_scope!
with_temp: (fn) =>
old_i, old_buffer = @i, @buffer
@i = 0
@buffer = {}
fn!
with @buffer
@i, @buffer = old_i, old_buffer
make_scope: =>
@scope = setmetatable { [Buffer]: true }, {
__index: (scope, name) ->
handler = switch name
when "widget"
@\render_widget
when "render"
@\render
when "capture"
(fn) -> table.concat @with_temp fn
when "element"
(...) -> element @, ...
when "text"
@\write_escaped
when "raw"
@\write
unless handler
default = @old_env[name]
return default unless default == nil
unless handler
builder = @builders[name]
unless builder == nil
handler = (...) -> @call builder, ...
unless handler
handler = (...) -> element @, name, ...
scope[name] = handler
handler
}
render: (mod_name) =>
widget = require mod_name
@render_widget widget!
render_widget: (w) =>
if current = @widget
w\_inherit_helpers current
w\render @
call: (fn, ...) =>
env = getfenv fn
if env == @scope
return fn!
before = @old_env
@old_env = env
clone = locked_fn fn
setfenv clone, @scope
out = {clone ...}
release_fn clone
@old_env = before
unpack out
write_escaped: (thing, next_thing, ...) =>
switch type thing
when "string"
@write escape thing
when "table"
for chunk in *thing
@write_escaped chunk
else
@write thing
if next_thing -- keep the tail call
@write_escaped next_thing, ...
write: (thing, next_thing, ...) =>
switch type thing
when "string"
@i += 1
@buffer[@i] = thing
when "number"
@write tostring thing
when "nil"
nil -- ignore
when "table"
for chunk in *thing
@write chunk
when "function"
@call thing
else
error "don't know how to handle: " .. type(thing)
if next_thing -- keep tail call
@write next_thing, ...
html_writer = (fn) ->
(buffer) -> Buffer(buffer)\write fn
render_html = (fn) ->
buffer = {}
html_writer(fn) buffer
concat buffer
helper_key = setmetatable {}, __tostring: -> "::helper_key::"
-- ensures that all methods are called in the buffer's scope
class Widget
@__inherited: (cls) =>
cls.__base.__call = (...) => @render ...
@include: (other_cls) =>
import mixin_class from require "lapis.util"
other_cls = require other_cls if type(other_cls) == "string"
mixin_class @, other_cls
new: (opts) =>
-- copy in options
if opts
for k,v in pairs opts
if type(k) == "string"
@[k] = v
_set_helper_chain: (chain) => rawset @, helper_key, chain
_get_helper_chain: => rawget @, helper_key
_find_helper: (name) =>
if chain = @_get_helper_chain!
for h in *chain
helper_val = h[name]
if helper_val != nil
-- call functions in scope of helper
value = if type(helper_val) == "function"
(w, ...) -> helper_val h, ...
else
helper_val
return value
_inherit_helpers: (other) =>
@_parent = other
-- add helpers from parents
if other_helpers = other\_get_helper_chain!
for helper in *other_helpers
@include_helper helper
-- insert table onto end of helper_chain
include_helper: (helper) =>
if helper_chain = @[helper_key]
insert helper_chain, helper
else
@_set_helper_chain { helper }
nil
content_for: (name, val) =>
if val
if helper = @_get_helper_chain![1]
helper.layout_opts[name] = if type(val) == "string"
escape val
else
getfenv(val).capture val
else
@_buffer\write @[name]
has_content_for: (name) =>
not not @[name]
content: => -- implement me
render_to_string: (...) =>
buffer = {}
@render buffer, ...
concat buffer
render: (buffer, ...) =>
@_buffer = if buffer.__class == Buffer
buffer
else
Buffer buffer
old_widget = @_buffer.widget
@_buffer.widget = @
meta = getmetatable @
index = meta.__index
index_is_fn = type(index) == "function"
seen_helpers = {}
scope = setmetatable {}, {
__tostring: meta.__tostring
__index: (scope, key) ->
value = if index_is_fn
index scope, key
else
index[key]
-- run method in buffer scope
if type(value) == "function"
wrapped = if Widget.__base[key] and key != "content"
value
else
(...) -> @_buffer\call value, ...
scope[key] = wrapped
return wrapped
-- look for helper
if value == nil and not seen_helpers[key]
helper_value = @_find_helper key
seen_helpers[key] = true
if helper_value != nil
scope[key] = helper_value
return helper_value
value
}
setmetatable @, __index: scope
@content ...
setmetatable @, meta
@_buffer.widget = old_widget
nil
{ :Widget, :Buffer, :html_writer, :render_html, :escape, :unescape }
| 21.99705 | 101 | 0.544723 |
f30f058e0389103f32f9108816e7fa89a5e5beec | 346 | html = require "lapis.html"
class Layout extends html.Widget
content: =>
html_5 ->
head ->
title @title
body ->
h1 @title
if @errors
div class: "errors", ->
ul ->
for e in *@errors
li e
div class: "content", ->
@content_for "inner"
| 19.222222 | 33 | 0.450867 |
638413f84fcea30b655c3697a891d53b89ab49ac | 2,387 | require "love.timer"
import thread, timer from love
http = require "socket.http"
check = (data) ->
send = thread.getChannel data.thread_channel or "itchy"
exponential_backoff = 1
while true
result = {}
if data.url
result.body, result.status = http.request data.url
elseif data.proxy
unless data.target
result.message = "'target' or 'url' must be defined!"
send\push result
return false
result.body, result.status = http.request "#{data.proxy}/get/https://itch.io/api/1/x/wharf/latest?target=#{data.target}&channel_name=#{data.channel}"
unless result.body
result.message = "socket.http.request error: #{result.status}"
send\push result
return false
result.version = result.body\match '%s*{%s*"latest"%s*:%s*"(.+)"%s*}%s*'
result.version = tonumber(result.version) or result.version
result.latest = if data.version
result.version == data.version
if result.status != 200 and (not result.version)
result.message = "unknown, error getting latest version: HTTP #{result.status}, trying again in #{exponential_backoff} seconds"
send\push result
timer.sleep exponential_backoff
exponential_backoff *= 2
exponential_backoff = 10 * 60 if exponential_backoff > 10 * 60 -- maximum backoff is 10 minutes
continue
elseif result.latest != nil
if result.latest
result.message = "#{result.version}, you have the latest version"
else
result.message = "#{result.version}, there is a newer version available!"
else
result.message = result.version
send\push result
return true
-- data should be a table of information
start = (data) ->
data.proxy = "http://45.55.113.149:16343" unless data.proxy or data.url
-- channel can be autodetected if not specified
unless data.channel
require "love.system"
os = love.system.getOS!
switch os
when "OS X"
data.channel = "osx"
when "Windows"
data.channel = "win32"
when "Linux"
data.channel = "linux"
when "Android"
data.channel = "android"
when "iOS"
data.channel = "ios"
else
data.channel = os
check data
-- if we should check again every x seconds, wait, and do so
if data.interval
while true
timer.sleep data.interval
check data
start(...)
| 29.8375 | 155 | 0.648513 |
7ec8035bef078e173bc52fb4c87aa22eed8fc2cf | 10,772 | json = require "json"
DownloadManager = require "DM.DownloadManager"
DependencyControl = nil
Logger = require "l0.DependencyControl.Logger"
Common = require "l0.DependencyControl.Common"
defaultLogger = Logger fileBaseName: "DepCtrl.UpdateFeed"
class ScriptUpdateRecord extends Common
msgs = {
errors: {
noActiveChannel: "No active channel."
}
changelog: {
header: "Changelog for %s v%s (released %s):"
verTemplate: "v %s:"
msgTemplate: " • %s"
}
}
new: (@namespace, @data, @config = {c:{}}, scriptType, autoChannel = true, @logger = defaultLogger) =>
DependencyControl or= require "l0.DependencyControl"
@moduleName = scriptType == @@ScriptType.Module and @namespace
@[k] = v for k, v in pairs data
@setChannel! if autoChannel
getChannels: =>
channels, default = {}
for name, channel in pairs @data.channels
channels[#channels+1] = name
if channel.default and not default
default = name
return channels, default
setChannel: (channelName = @config.c.activeChannel) =>
with @config.c
.channels, default = @getChannels!
.lastChannel or= channelName or default
channelData = @data.channels[.lastChannel]
@activeChannel = .lastChannel
return false, @activeChannel unless channelData
@[k] = v for k, v in pairs channelData
@files = @files and [file for file in *@files when not file.platform or file.platform == @@platform] or {}
return true, @activeChannel
checkPlatform: =>
@logger\assert @activeChannel, msgs.errors.noActiveChannel
return not @platforms or ({p,true for p in *@platforms})[@@platform], @@platform
getChangelog: (versionRecord, minVer = 0) =>
return "" unless "table" == type @changelog
maxVer = DependencyControl\parseVersion @version
minVer = DependencyControl\parseVersion minVer
changelog = {}
for ver, entry in pairs @changelog
ver = DependencyControl\parseVersion ver
verStr = DependencyControl\getVersionString ver
if ver >= minVer and ver <= maxVer
changelog[#changelog+1] = {ver, verStr, entry}
return "" if #changelog == 0
table.sort changelog, (a,b) -> a[1]>b[1]
msg = {msgs.changelog.header\format @name, DependencyControl\getVersionString(@version), @released or "<no date>"}
for chg in *changelog
chg[3] = {chg[3]} if type(chg[3]) ~= "table"
if #chg[3] > 0
msg[#msg+1] = @logger\format msgs.changelog.verTemplate, 1, chg[2]
msg[#msg+1] = @logger\format(msgs.changelog.msgTemplate, 1, entry) for entry in *chg[3]
return table.concat msg, "\n"
class UpdateFeed extends Common
templateData = {
maxDepth: 7,
templates: {
feedName: {depth: 1, order: 1, key: "name" }
baseUrl: {depth: 1, order: 2, key: "baseUrl" }
feed: {depth: 1, order: 3, key: "knownFeeds", isHashTable: true }
namespace: {depth: 3, order: 1, parentKeys: {macros:true, modules:true} }
namespacePath: {depth: 3, order: 2, parentKeys: {macros:true, modules:true}, repl:"%.", to: "/" }
scriptName: {depth: 3, order: 3, key: "name" }
channel: {depth: 5, order: 1, parentKeys: {channels:true} }
version: {depth: 5, order: 2, key: "version" }
platform: {depth: 7, order: 1, key: "platform" }
fileName: {depth: 7, order: 2, key: "name" }
-- rolling templates
fileBaseUrl: {key: "fileBaseUrl", rolling: true }
}
sourceAt: {}
}
msgs = {
trace: {
usingCached: "Using cached feed."
downloaded: "Downloaded feed to %s."
}
errors: {
downloadAdd: "Couldn't initiate download of %s to %s (%s)."
downloadFailed: "Download of feed %s to %s failed (%s)."
cantOpen: "Can't open downloaded feed for reading (%s)."
parse: "Error parsing feed."
}
}
@defaultConfig = {
downloadPath: aegisub.decode_path "?temp/l0.#{@@__name}_feedCache"
dumpExpanded: false
}
@cache = {}
fileBaseName = "l0.#{@@__name}_"
fileMatchTemplate = "l0.#{@@__name}_%x%x%x%x.*%.json"
feedsHaveBeenTrimmed = false
-- precalculate some tables for the templater
templateData.rolling = {n, true for n,t in pairs templateData.templates when t.rolling}
templateData.sourceKeys = {t.key, t.depth for n,t in pairs templateData.templates when t.key}
with templateData
for i=1,.maxDepth
.sourceAt[i], j = {}, 1
for name, tmpl in pairs .templates
if tmpl.depth==i and not tmpl.rolling
.sourceAt[i][j] = name
j += 1
table.sort .sourceAt[i], (a,b) -> return .templates[a].order < .templates[b].order
new: (@url, autoFetch = true, fileName, @config = {}, @logger = defaultLogger) =>
DependencyControl or= require "l0.DependencyControl"
-- fill in missing config values
@config[k] = v for k, v in pairs @@defaultConfig when @config[k] == nil
-- delete old feeds
feedsHaveBeenTrimmed or= Logger(fileMatchTemplate: fileMatchTemplate, logDir: @config.downloadPath, maxFiles: 20)\trimFiles!
@fileName = fileName or table.concat {@config.downloadPath, fileBaseName, "%04X"\format(math.random 0, 16^4-1), ".json"}
if @@cache[@url]
@logger\trace msgs.trace.usingCached
@data = @@cache[@url]
elseif autoFetch
@fetch!
@downloadManager = DownloadManager aegisub.decode_path @config.downloadPath
getKnownFeeds: =>
return {} unless @data
return [url for _, url in pairs @data.knownFeeds]
-- TODO: maybe also search all requirements for feed URLs
fetch: (fileName) =>
@fileName = fileName if fileName
dl, err = @downloadManager\addDownload @url, @fileName
unless dl
return false, msgs.errors.downloadAdd\format @url, @fileName, err
@downloadManager\waitForFinish -> true
if dl.error
return false, msgs.errors.downloadFailed\format @url, @fileName, dl.error
@logger\trace msgs.trace.downloaded, @fileName
handle, err = io.open @fileName
unless handle
return false, msgs.errors.cantOpen\format err
decoded, data = pcall json.decode, handle\read "*a"
unless decoded and data
-- luajson errors are useless dumps of whatever, no use to pass them on to the user
return false, msgs.errors.parse
data[key] = {} for key in *{ @@ScriptType.name.legacy[@@ScriptType.Automation],
@@ScriptType.name.legacy[@@ScriptType.Module],
"knownFeeds"} when not data[key]
@data, @@cache[@url] = data, data
@expand!
return @data
expand: =>
{:templates, :maxDepth, :sourceAt, :rolling, :sourceKeys} = templateData
vars, rvars = {}, {i, {} for i=0, maxDepth}
expandTemplates = (val, depth, rOff=0) ->
return switch type val
when "string"
val = val\gsub "@{(.-):(.-)}", (name, key) ->
if type(vars[name]) == "table" or type(rvars[depth+rOff]) == "table"
vars[name][key] or rvars[depth+rOff][name][key]
val\gsub "@{(.-)}", (name) -> vars[name] or rvars[depth+rOff][name]
when "table"
{k, expandTemplates v, depth, rOff for k, v in pairs val}
else val
recurse = (obj, depth = 1, parentKey = "", upKey = "") ->
-- collect regular template variables first
for name in *sourceAt[depth]
with templates[name]
if not .key
-- template variables are not expanded if they are keys
vars[name] = parentKey if .parentKeys[upKey]
elseif .key and obj[.key]
-- expand other templates used in template variable
obj[.key] = expandTemplates obj[.key], depth
vars[name] = obj[.key]
vars[name] = vars[name]\gsub(.repl, .to) if .repl
-- update rolling template variables last
for name,_ in pairs rolling
rvars[depth][name] = obj[templates[name].key] or rvars[depth-1][name] or ""
rvars[depth][name] = expandTemplates rvars[depth][name], depth, -1
obj[templates[name].key] and= rvars[depth][name]
-- expand variables in non-template strings and recurse tables
for k,v in pairs obj
if sourceKeys[k] ~= depth and not rolling[k]
switch type v
when "string"
obj[k] = expandTemplates obj[k], depth
when "table"
recurse v, depth+1, k, parentKey
-- invalidate template variables created at depth+1
vars[name] = nil for name in *sourceAt[depth+1]
rvars[depth+1] = {}
recurse @data
if @dumpExpanded
handle = io.open @fileName\gsub(".json$", ".exp.json"), "w"
handle\write(json.encode @data)\close!
return @data
getScript: (namespace, scriptType, config, autoChannel) =>
section = @@ScriptType.name.legacy[scriptType]
scriptData = @data[section][namespace]
return false unless scriptData
ScriptUpdateRecord namespace, scriptData, config, scriptType, autoChannel, @logger
getMacro: (namespace, config, autoChannel) =>
@getScript namespace, false, config, autoChannel
getModule: (namespace, config, autoChannel) =>
@getScript namespace, true, config, autoChannel | 43.088 | 132 | 0.54029 |
8a28a03d39dc5300a938289cbf89c9e236181aeb | 1,107 | #!amulet
local *
class Game
score: 0
timer: 10
playing: true
new: (win, player, food) =>
@win = win
@player = player
@food = food
connect: (t) =>
t.score.text = tostring @score
t.timer.text = "%.1f"\format @timer
gameover: =>
return with gameover = @timer <= 0
if @playing and gameover
@playing = false
@win.scene\action am.play "resources/gameover.ogg"
update: (dt) =>
with @win
return \close! if \key_pressed"escape"
if \key_released"enter" or \key_released"f5"
@playing = true
@timer = 10
@score = 0
@player.pos = vec2 0
@player.speed = vec2 0
@food\start!
return
@timer -= dt
@timer = math.clamp @timer, 0, 10
if math.distance(@player.pos, @food.pos) < 64
@win.scene\action am.play "resources/eaten.ogg"
@food\start!
@score += 1
@timer = 100 / (9 + @score)
| 23.553191 | 66 | 0.469738 |
97cfc67a7ca8314a11060c96488d7b1636dd1689 | 30 | theme_load('theme-defs') true
| 15 | 29 | 0.766667 |
c8301a6375b0b59c91038e6120aa130125f311c2 | 1,742 |
one_of = (state, arguments) ->
{ input, expected } = arguments
for e in *expected
return true if input == e
false
s = require "say"
assert = require "luassert"
s\set "assertion.one_of.positive",
"Expected %s to be one of:\n%s"
s\set "assertion.one_of.negative",
"Expected property %s to not be in:\n%s"
assert\register "assertion",
"one_of", one_of, "assertion.one_of.positive", "assertion.one_of.negative"
with_query_fn = (q, run, db=require "lapis.db.postgres") ->
old_query = db.get_raw_query!
db.set_raw_query q
if not run
-> db.set_raw_query old_query
else
with run!
db.set_raw_query old_query
assert_queries = (expected, result) ->
assert #expected == #result, "number of expected queries does not match number received"
for i, q in ipairs expected
if type(q) == "table"
assert.one_of result[i], q
else
assert.same q, result[i]
stub_queries = ->
import setup, teardown, before_each from require "busted"
local queries, query_mock
get_queries = -> queries
mock_query = (pattern, result) ->
query_mock[pattern] = result
show_queries = os.getenv("LAPIS_SHOW_QUERIES")
local restore
setup ->
_G.ngx = { null: nil }
restore = with_query_fn (q) ->
if show_queries
require("lapis.logging").query q
table.insert queries, (q\gsub("%s+", " ")\gsub("[\n\t]", " "))
-- try to find a mock
for k,v in pairs query_mock
if q\match k
return if type(v) == "function"
v!
else
v
{}
teardown ->
_G.ngx = nil
restore!
before_each ->
queries = {}
query_mock = {}
get_queries, mock_query
{ :with_query_fn, :assert_queries, :stub_queries }
| 21.775 | 90 | 0.630884 |
5245136bf318b5f877a0352592c7a161f99ed966 | 1,852 | lapis = require "lapis"
db = require "lapis.db"
import Model from require "lapis.db.model"
import config from require "lapis.config"
import insert from table
import sort from table
import random from math
class Fortune extends Model
class World extends Model
class Benchmark extends lapis.Application
"/": =>
json: {message: "Hello, World!"}
"/db": =>
num_queries = tonumber(@params.queries) or 1
if num_queries < 2
w = World\find random(1, 10000)
return json: {id:w.id,randomNumber:w.randomnumber}
worlds = {}
for i = 1, num_queries
w = World\find random(1, 10000)
insert worlds, {id:w.id,randomNumber:w.randomnumber}
json: worlds
"/fortunes": =>
@fortunes = Fortune\select ""
insert @fortunes, {id:0, message:"Additional fortune added at request time."}
sort @fortunes, (a, b) -> a.message < b.message
layout:false, @html ->
raw '<!DOCTYPE HTML>'
html ->
head ->
title "Fortunes"
body ->
element "table", ->
tr ->
th ->
text "id"
th ->
text "message"
for fortune in *@fortunes
tr ->
td ->
text fortune.id
td ->
text fortune.message
"/update": =>
num_queries = tonumber(@params.queries) or 1
if num_queries == 0
num_queries = 1
worlds = {}
for i = 1, num_queries
wid = random(1, 10000)
world = World\find wid
world.randomnumber = random(1, 10000)
world\update "randomnumber"
insert worlds, {id:world.id,randomNumber:world.randomnumber}
if num_queries < 2
return json: worlds[1]
json: worlds
"/plaintext": =>
content_type:"text/plain", layout: false, "Hello, World!"
| 26.084507 | 81 | 0.568575 |
38c8d69390bb1a2ee52495c3617743fcfb433770 | 8,139 | import UTIL from require "ZF.util.util"
import MATH from require "ZF.util.math"
import TABLE from require "ZF.util.table"
import TAGS from require "ZF.text.tags"
import TEXT from require "ZF.text.text"
class FBF
version: "1.0.2"
new: (l, start_time = l.start_time, end_time = l.end_time) =>
-- copys line
@line = TABLE(l)\copy!
-- set line times
@lstart = start_time
@lend = end_time
@ldur = end_time - start_time
-- converts time values in milliseconds to frames
@sframe = aegisub.frame_from_ms start_time
@eframe = aegisub.frame_from_ms end_time
@dframe = @eframe - @sframe
@iframe = -1 + aegisub.ms_from_frame 0
@s, @e, @d = 0, end_time, end_time - start_time
-- gets the transformation "t" through a time interval
getTimeInInterval = (t1, t2, accel = 1, t) ->
u = @s - @lstart
if u < t1
t = 0
elseif u >= t2
t = 1
else
t = (u - t1) ^ accel / (t2 - t1) ^ accel
return t
-- libass functions
@util = {
-- https://github.com/libass/libass/blob/0e0f9da2edc8eead93f9bf0ac4ef0336ad646ea7/libass/ass_parse.c#L633
transform: (...) ->
args, t1, t2, accel = {...}, 0, @ldur, 1
if #args == 3
{t1, t2, accel} = args
elseif #args == 2
{t1, t2} = args
elseif #args == 1
{accel} = args
return getTimeInInterval t1, t2, accel
-- https://github.com/libass/libass/blob/0e0f9da2edc8eead93f9bf0ac4ef0336ad646ea7/libass/ass_parse.c#L452
move: (x1, y1, x2, y2, t1, t2) ->
if t1 and t2
if t1 > t2
t1, t2 = t2, t1
else
t1, t2 = 0, 0
if t1 <= 0 and t2 <= 0
t1, t2 = 0, @ldur
t = getTimeInInterval t1, t2
x = MATH\round (1 - t) * x1 + t * x2, 3
y = MATH\round (1 - t) * y1 + t * y2, 3
return x, y
-- https://github.com/libass/libass/blob/0e0f9da2edc8eead93f9bf0ac4ef0336ad646ea7/libass/ass_parse.c#L585
fade: (dec, ...) ->
-- https://github.com/libass/libass/blob/0e0f9da2edc8eead93f9bf0ac4ef0336ad646ea7/libass/ass_parse.c#L196
interpolate_alpha = (now, t1, t2, t3, t4, a1, a2, a3, a = a3) ->
if now < t1
a = a1
elseif now < t2
cf = (now - t1) / (t2 - t1)
a = a1 * (1 - cf) + a2 * cf
elseif now < t3
a = a2
elseif now < t4
cf = (now - t3) / (t4 - t3)
a = a2 * (1 - cf) + a3 * cf
return a
args, a1, a2, a3, t1, t2, t3, t4 = {...}
if #args == 2
-- 2-argument version (\fad, according to specs)
a1 = 255
a2 = 0
a3 = 255
t1 = 0
{t2, t3} = args
t4 = @ldur
t3 = t4 - t3
elseif #args == 7
-- 7-argument version (\fade)
{a1, a2, a3, t1, t2, t3, t4} = args
else
return ""
return ass_alpha interpolate_alpha @s - @lstart, t1, t2, t3, t4, a1, dec or a2, a3
}
-- gets frame duration
frameDur: (dec = 0) =>
msa, msb = aegisub.ms_from_frame(1), aegisub.ms_from_frame(101)
return MATH\round msb and (msb - msa) / 100 or 41.708, dec
-- solves the transformations related to the \t tag
solveTransformation: (tags) =>
if tags\match "\\t%b()"
split = TAGS\splitTags tags
for tag in *split
if tag.name == "t"
t = @util.transform tag.ts, tag.te, tag.ac
for trs in *tag.value
-- initial and final value
a, b = 0, trs.value
if fag = TAGS\tagsContainsTag split, trs.name
a = fag.value
unless trs.name == "clip" or trs.name == "iclip"
trs.value = UTIL\interpolation t, nil, a, b
if type(trs.value) == "number"
trs.value = MATH\round trs.value
else
-- if is a rectangular clip
if type(a) == "table" and type(b) == "table"
{a1, b1, c1, d1} = a
{a2, b2, c2, d2} = b
a3 = MATH\round UTIL\interpolation t, "number", a1, a2
b3 = MATH\round UTIL\interpolation t, "number", b1, b2
c3 = MATH\round UTIL\interpolation t, "number", c1, c2
d3 = MATH\round UTIL\interpolation t, "number", d1, d2
trs.value = {a3, b3, c3, d3}
else
-- if is a vector clip --> yes it works
trs.value = UTIL\interpolation t, nil, a, b
tags = TAGS\removeTag tags, tag.name, TAGS\remBarces tag.value.__tostring!
break
return tags
-- solves the transformations related to the \move tag
solveMove: (tags) =>
if tags\match "\\move%b()"
for tag in *TAGS\splitTags tags
if tag.name == "move"
px, py = @util.move unpack tag.value
tags = TAGS\removeTag tags, tag.name, "\\pos(#{px},#{py})"
break
return tags
-- solves the transformations related to the \fad or \fade tag
solveFade: (tags, dec = 0) =>
if tags\match "\\fade?%b()"
for tag in *TAGS\splitTags tags
if tag.name == "fad" or tag.name == "fade"
fade = @util.fade dec, unpack tag.value
tags = TAGS\removeTags tags, tag.name, {"alpha", "\\alpha#{fade}"}
break
return tags
-- performs all transformations on the frame
perform: (split) =>
split = type(split) == "table" and split or TAGS\splitTextByTags split, false
for i = 1, #split.tags
tags, alpha = split.tags[i], nil
-- performs \move tag transformation if \move is on the first tag layer
if i == 1
tags = @solveMove tags
-- performs \t tag transformation one at a time
while tags\match "\\t%b()"
tags = @solveTransformation tags
-- gets the alpha value contained in the frame and convert it to a number
if alpha = TAGS\getTagInTags tags, "alpha"
alpha = tonumber alpha\match("&?[hH](%x%x)&?"), 16
-- performs \fad or \fade tag transformation
tags = @solveFade tags, alpha
-- removes style values that are contained on the frame
split.tags[i] = TAGS\clearStyleValues @line, tags, true
-- removes equal values that are contained on the frame
return TAGS\clearEqualTags split.__tostring!
-- iterate frame by frame
iter: (step = 1, i = 0) =>
{:sframe, :eframe, :dframe, :iframe} = @
->
i += (i == 0 and 1 or step)
if i <= dframe -- i <= total frames
add = i + step
if add > dframe
while add > dframe + 1
add -= 1
@s = iframe + aegisub.ms_from_frame sframe + i
@e = iframe + aegisub.ms_from_frame sframe + add
@d = @e - @s
return @s, @e, @d, i, dframe
{:FBF} | 43.292553 | 121 | 0.454724 |
c7fe1a5cb4b2f3c1df6a1498757093350715eed4 | 1,297 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
_G = _G
import table, tostring, print from _G
import config from howl
append = table.insert
config.define
name: 'max_log_entries'
description: 'Maximum number of log entries to keep in memory'
default: 1000
type_of: 'number'
log = {}
setfenv 1, log
essentials_of = (s) ->
first_line = s\match '[^\n\r]*'
essentials = first_line\match '^%[[^]]+%]:%d+: (.+)'
essentials or first_line
dispatch = (level, message) ->
entry = :message, :level
append entries, entry
window = _G.howl.app.window
if window and window.visible
status = window.status
command_line = window.command_line
essentials = essentials_of message
status[level] status, essentials
command_line\notify essentials, level if command_line.showing
else
print message if not _G.os.getenv('BUSTED')
while #entries > config.max_log_entries and #entries > 0
table.remove entries, 1
entry
export *
entries = {}
last_error = nil
info = (message) -> dispatch 'info', message
warning = (message) -> dispatch 'warning', message
warn = warning
error = (message) -> last_error = dispatch 'error', message
clear = ->
entries = {}
last_error = nil
return log
| 23.581818 | 79 | 0.700077 |
43894759d03e97f10e7b379d31d6e3c55bc2f4fe | 987 | config = require 'lapis.config'
path = require "lapis.cmd.path"
local leda
class Leda
paths: {
"/usr/local/bin"
"/usr/bin"
}
find_bin: =>
return @bin if @bin
bin = "leda"
paths = [p for p in *@paths]
table.insert paths, os.getenv "LAPIS_LEDA"
for to_check in *paths
to_check ..= "/#{bin}"
if path.exists to_check
@bin = to_check
return @bin
nil, "failed to find leda installation"
start: (environment) =>
assert @find_bin!
port = config.get!.port
host = config.get!.host or 'localhost'
print "starting server on #{host}:#{port} in environment #{environment}. Press Ctrl-C to exit"
env = ""
if environment == 'development'
env = "LEDA_DEBUG=1"
execute = "#{env} #{@bin} --execute='require(\"lapis\").serve(\"app\")'"
os.execute execute
leda = Leda!
find_leda = ->
leda\find_bin!
start_leda = (environment) ->
leda\start environment
{ :find_leda, :start_leda }
| 18.277778 | 98 | 0.604863 |
0f16807a2ec1763c9b278f401ed3d3593fc4dc35 | 3,475 | math.randomseed os.time!
fill = (width, height) ->
map = {}
for x = 0, width
row = {}
for y = 0, height
row[y] = 1 -- wall/background
map[x] = row
map
clone = (map) ->
nmap = fill #map, #map[0]
for x = 0, #map
for y = 0, #map[0]
nmap[x][y] = map[x][y] == 2 and 1 or map[x][y]
nmap
mapper = {}
mapper.automata = (map, config) ->
nmap = {}
with config
nmap = clone map
auto = (x, y) ->
sum = 0
for ix = -1, 1
for iy = -1, 1
unless (ix == 0 and iy == 0)
sum += map[x + ix][y + iy]
switch map[x][y]
when 0
if sum > config.ca.spawn_threshold
nmap[x][y] = 1 unless x == game.start_x and y == game.start_y
when 1
if sum < config.ca.die_threshold
nmap[x][y] = 0
for x = 1, #nmap - 1
for y = 1, #nmap[0] - 1
auto x, y
nmap
mapper.add_walls = (map, config) ->
nmap = {}
with config
nmap = clone map
for x = 0, #nmap
for y = 0, #nmap[0]
sum = 0
flag = false
for ix = -1, 1
for iy = -1, 1
if x + ix < 0 or x + ix >= #nmap or y + iy < 0 or y + iy >= #nmap[0]
sum += 1
flag = true
continue
unless (ix == 0 and iy == 0)
sum += map[x + ix][y + iy]
if nmap[x][y] == 1
if sum < 8
nmap[x][y] = 2 -- solid
elseif flag
nmap[x][y] = 2 -- solid
nmap -- the new map
mapper.fraction_of = (map, t) ->
sum = 0
for x = 0, #map
for y = 0, #map[0]
sum += 1 if map[x][y] == t
sum / (#map * #map[0])
mapper.gen = (config) ->
start = os.time!
map = {}
with config
worm =
x: math.floor .width / 2
y: math.floor .height / 2
r: math.random 0, 3 -- clocwize 0..3
map = fill .width, .height
player_set = false
while .floor >= mapper.fraction_of map, 0
if os.time! - start > 1
return mapper.gen config
last_r = worm.r
while worm.r == last_r
worm.r = math.random 0, 3
switch worm.r
when 0
worm.y -= 1
when 1
worm.x += 1
when 2
worm.y += 1
when 3
worm.x -= 1
if map[worm.x] and map[worm.x][worm.y]
map[worm.x][worm.y] = 0 -- floor
unless player_set
game.start_x = worm.x
game.start_y = worm.y
if worm.r == 0 or worm.r == 2
if map[worm.x] and map[worm.x][worm.y + 1]
map[worm.x][worm.y + 1] = 0
else
if map[worm.x + 1] and map[worm.x + 1][worm.y]
map[worm.x + 1][worm.y] = 0
else
worm.x = math.floor .width / 2
worm.y = math.floor .height / 2
map
mapper | 25 | 92 | 0.364317 |
ae315aff4dbf5d888f247c425179a530b2a22f75 | 951 | -- Template used by Spritemap to define animations.
-- Don't create these yourself, instead you can fetch them with Spritemap.add.
class Animation
-- @param name Animation name.
-- @param frames Array of frame indices to animate.
-- @param frameRate Animation speed.
-- @param loop If the animation should loop.
new: (name, frames, frameRate = 0, loop = true, parent = nil) =>
@__name = name
@__frames = frames
@__frameRate = frameRate
@__loop = loop
-- Plays the animation.
--
-- @param reset If the animation should force-restart if it is already playing.
-- @param reverse If the animation should play in reverse.
play: (reset = false, reverse = false) =>
-- Amount of frames in the animation.
frameCount: => #@__frames
-- Animation speed.
frameRate: => @__frameRate
-- Array of frame indices to animate.
frames: => @__frames
-- If the animation loops.
loop: => @__loop
-- Name of the animation.
name: => @__name
| 27.171429 | 80 | 0.695058 |
1980bf468394f94aa91c2fdce56a573c7727a57e | 1,557 | [[
joli-lune
small framework for love2d
MIT License (see licence file)
]]
System = require "src.systems.system"
class MenuElement extends System
__tostring: => return "menuelement"
onCreate: (data, menu) =>
@menu = menu
@nexts = {}
for property,value in pairs data
@[property] = value
@width = @width or 1
@height = @height or 1
@entity\addSystem "Renderer"
if type(data.renderers) == "table"
with @entity.renderer
for i, renderer in pairs data.renderers
\add "menu_element_" .. i, unpack(renderer)
if data.sprite
@entity.renderer\add "menu_element_sprite", data.sprite, data.anim
if type(@label) == "string"
@entity.renderer\add "menu_element_text", @label, data.style, data.width, data.align
with @entity\addSystem "SoundSet"
if data.navsound
\addSource "nav", data.navsound
if data.actsound
\addSource "act", data.actsound
add: (key, element) => table.insert @nexts,{:key, :element}
remove: =>
table.remove @menu.list, table.index_of @menu.list, @
@entity\destroy!
@menu\setNexts!
activate: =>
if type(@method)=="function"
if @entity.soundset
if @entity.soundset.sources.act
@entity.soundset.sources.act\play!
@method @
updateElement: (dt,menu) =>
for n in *@nexts
if @input\pressed n.key
if n.element
menu\setCurrent menu.list[n.element]
break
if @activationKey and @input\pressed @activationKey
@\activate!
clickable: (system) =>
with @entity
\addSystem "Collider",@width,@height
\addSystem system
return MenuElement | 21.929577 | 87 | 0.680796 |
e643a6251a44edaa9e17d4c0df01e3ab9ccd439b | 2,296 | class Line extends Base
new: (arg0, arg1, arg2, arg3, arg4) =>
asVector = false
if arguments_.length >= 4
@_px = arg0
@_py = arg1
@_vx = arg2
@_vy = arg3
asVector = arg4
else
@_px = arg0.x
@_py = arg0.y
@_vx = arg1.x
@_vy = arg1.y
asVector = arg2
if !asVector
@_vx -= @_px
@_vy -= @_py
getPoint: =>
Point(@_px, @_py)
getVector: =>
Point(@_vx, @_vy)
intersect: (line, isInfinite) =>
Line\intersect @_px, @_py, @_vx, @_vy, line._px, line._py, line._vx, line._vy, true, isInfinite
getSide: (point) =>
Line\getSide @_px, @_py, @_vx, @_vy, point.x, point.y, true
getDistance: (point) =>
math.abs Line\getSignedDistance(@_px, @_py, @_vx, @_vy, point.x, point.y, true)
@intersect: (apx, apy, avx, avy, bpx, bpy, bvx, bvy, asVector, isInfinite) ->
-- Convert 2nd points to vectors if they are not specified as such.
if !asVector
avx -= apx
avy -= apy
bvx -= bpx
bvy -= bpy
cross = bvy * avx - bvx * avy
-- Avoid divisions by 0, and errors when getting too close to 0
if !Numerical\isZero(cross)
dx = apx - bpx
dy = apy - bpy
ta = (bvx * dy - bvy * dx) / cross
tb = (avx * dy - avy * dx) / cross
-- Check the ranges of t parameters if the line is not allowed
-- to extend beyond the definition points.
Point(apx + ta * avx, apy + ta * avy) if (isInfinite or 0 <= ta and ta <= 1) and (isInfinite or 0 <= tb and tb <= 1)
@getSide: (px, py, vx, vy, x, y, asVector) ->
if !asVector
vx -= px
vy -= py
v2x = x - px
v2y = y - py
ccw = v2x * vy - v2y * vx
if ccw is 0
ccw = v2x * vx + v2y * vy
if ccw > 0
v2x -= vx
v2y -= vy
ccw = v2x * vx + v2y * vy
ccw = 0 if ccw < 0
(if ccw < 0 then -1 else (if ccw > 0 then 1 else 0))
@getSignedDistance: (px, py, vx, vy, x, y, asVector) ->
if !asVector
vx -= px
vy -= py
-- Cache these values since they're used heavily in fatline code
m = vy / vx -- slope
b = py - m * px -- y offset
-- Distance to the linear equation
(y - (m * x) - b) / Math.sqrt(m * m + 1) | 26.697674 | 121 | 0.517422 |
467b329e1b16e6b5055dc7decfadd07a3737612a | 5,741 | class Matrix
new: (a, c, b, d, tx, ty) =>
@_a = a
@_c = c
@_b = b
@_d = d
@_tx = tx
@_ty = ty
equals: (mx) =>
mx is @ or mx and @_a is mx._a and @_b is mx._b and @_c is mx._c and @_d is mx._d and @_tx is mx._tx and @_ty is mx._ty or false
reset: =>
@_a = @_d = 1
@_c = @_b = @_tx = @_ty = 0
scale: (scale, center) ->
_scale = Point\read(arg)
_center = Point\read(arg, 0, 0, true)
@translate(_center) if _center
@_a *= _scale.x
@_c *= _scale.x
@_b *= _scale.y
@_d *= _scale.y
@translate(_center\negate()) if _center
translate: (point) =>
point = Point\read(arg)
x = point.x
y = point.y
@_tx += x * @_a + y * @_b
@_ty += x * @_c + y * @_d
rotate: (angle, center) =>
center = Point.read(arg, 1)
angle = angle * math.pi / 180
-- Concatenate rotation matrix into this one
x = center.x
y = center.y
cos = math.cos(angle)
sin = math.sin(angle)
tx = x - x * cos + y * sin
ty = y - x * sin - y * cos
a = @_a
b = @_b
c = @_c
d = @_d
@_a = cos * a + sin * b
@_b = -sin * a + cos * b
@_c = cos * c + sin * d
@_d = -sin * c + cos * d
@_tx += tx * a + ty * b
@_ty += tx * c + ty * d
shear: (point, center) ->
-- Do not modify point, center, since that would arguments of which
-- we're reading from!
_point = Point.read(arguments_)
_center = Point.read(arguments_, 0, 0, true)
@translate _center if _center
a = @_a
c = @_c
@_a += _point.y * @_b
@_c += _point.y * @_d
@_b += _point.x * a
@_d += _point.x * c
@translate _center.negate() if _center
isIdentity: =>
@_a is 1 and @_c is 0 and @_b is 0 and @_d is 1 and @_tx is 0 and @_ty is 0
isInvertible: =>
!!@_getDeterminant()
isSingular: =>
not @_getDeterminant()
concatenate: (mx) =>
a = @_a
b = @_b
c = @_c
d = @_d
@_a = mx._a * a + mx._c * b
@_b = mx._b * a + mx._d * b
@_c = mx._a * c + mx._c * d
@_d = mx._b * c + mx._d * d
@_tx += mx._tx * a + mx._ty * b
@_ty += mx._tx * c + mx._ty * d
preConcatenate: (mx) =>
a = @_a
b = @_b
c = @_c
d = @_d
tx = @_tx
ty = @_ty
@_a = mx._a * a + mx._b * c
@_b = mx._a * b + mx._b * d
@_c = mx._c * a + mx._d * c
@_d = mx._c * b + mx._d * d
@_tx = mx._a * tx + mx._b * ty + mx._tx
@_ty = mx._c * tx + mx._d * ty + mx._ty
transform: (src, srcOff, dst, dstOff, numPts) =>
(if arg.length < 5 then @_transformPoint(Point\read(arg)) else @_transformCoordinates(src, srcOff, dst, dstOff, numPts))
_transformPoint: (point, dest, dontNotify) =>
x = point.x
y = point.y
dest = Base\create(Point) if !dest
dest\set x * @_a + y * @_b + @_tx, x * @_c + y * @_d + @_ty, dontNotify
_transformCoordinates: (src, srcOff, dst, dstOff, numPts) =>
i = srcOff
j = dstOff
srcEnd = srcOff + 2 * numPts
while i < srcEnd
x = src[i++]
y = src[i++]
dst[j++] = x * @_a + y * @_b + @_tx
dst[j++] = x * @_c + y * @_d + @_ty
dst
_transformCorners: (rect) =>
x1 = rect.x
y1 = rect.y
x2 = x1 + rect.width
y2 = y1 + rect.height
coords = [x1, y1, x2, y1, x2, y2, x1, y2]
@_transformCoordinates coords, 0, coords, 0, 4
_transformBounds: (bounds, dest, dontNotify) =>
coords = @_transformCorners(bounds)
min = coords.slice(0, 2)
max = coords.slice()
i = 2
while i < 8
val = coords[i]
j = i & 1
if val < min[j]
min[j] = val
else max[j] = val if val > max[j]
i++
dest = Base\create(Rectangle) if !dest
dest\set min[0], min[1], max[0] - min[0], max[1] - min[1], dontNotify
inverseTransform: (point) =>
@_inverseTransform Point\read(arg)
_getDeterminant: =>
det = @_a * @_d - @_b * @_c
(if @isFinite(det) and not Numerical\isZero(det) and @isFinite(@_tx) and @isFinite(@_ty) then det else null)
_inverseTransform: (point, dest, dontNotify) =>
det = @_getDeterminant()
return nil if det
x = point.x - @_tx
y = point.y - @_ty
dest = Base\create(Point) if !dest
dest\set (x * @_d - y * @_b) / det, (y * @_a - x * @_c) / det, dontNotify
decompose: ->
-- http://dev.w3.org/csswg/css3-2d-transforms/#matrix-decomposition
-- http://stackoverflow.com/questions/4361242/
-- https://github.com/wisec/DOMinator/blob/master/layout/style/nsStyleAnimation.cpp#L946
a = @_a
b = @_b
c = @_c
d = @_d
return nil if Numerical\isZero(a * d - b * c)
scaleX = Math\sqrt(a * a + b * b)
a /= scaleX
b /= scaleX
shear = a * c + b * d
c -= a * shear
d -= b * shear
scaleY = Math\sqrt(c * c + d * d)
c /= scaleY
d /= scaleY
shear /= scaleY
-- a * d - b * c should now be 1 or -1
if a * d < b * c
a = -a
b = -b
-- We don't need c & d anymore, but if we did, we'd have to do this:
-- c = -c;
-- d = -d;
shear = -shear
scaleX = -scaleX
translation: @getTranslation()
scaling: Point(scaleX, scaleY)
rotation: -math.atan2(b, a) * 180 / math.PI
shearing: shear
getValues: =>
[@_a, @_c, @_b, @_d, @_tx, @_ty]
getTranslation: =>
-- No decomposition is required to extract translation, so treat this
Point(@_tx, @_ty)
getScaling: =>
(@decompose() or {}).scaling
getRotation: =>
(@decompose() or {}).rotation
inverted: =>
det = @_getDeterminant()
det and Matrix(@_d / det, -@_c / det, -@_b / det, @_a / det, (@_b * @_ty - @_d * @_tx) / det, (@_c * @_tx - @_a * @_ty) / det)
shiftless: =>
Matrix(@_a, @_c, @_b, @_d, 0, 0)
| 23.432653 | 132 | 0.516461 |
34b7d72e0db98ba1e91432ed9c044548c2a01384 | 1,872 | export class ImageSet extends Image
new: (filename, frameWidth, frameHeight) =>
super(filename)
@frame = width: frameWidth, height: frameHeight
@quad = love.graphics.newQuad(0, 0, @frame.width, @frame.height, @texture\getDimensions!)
@frameCount =
columns: math.floor(@texture\getWidth! / @frame.width)
rows: math.floor(@texture\getHeight! / @frame.height)
@totalFrames = @frameCount.columns * @frameCount.rows
@currentFrameId = 1
@isLooping = false
@isPlaying = false
@clock = 0
@frameDuration = 0
-- callbacks
@callbacks = {
onEnd: -> return
}
update: (dt) =>
super(dt)
if (not @isPlaying)
return false
@clock += dt
if (@clock >= @frameDuration)
@clock = 0
@currentFrameId += 1
if (@currentFrameId > @totalFrames)
if (@isLooping)
@currentFrameId = 1
@callbacks.onEnd!
return true
else
@stop!
@callbacks.onEnd!
return true
@_updateFrame!
return false
play: (forceReset=true) =>
if (forceReset)
@currentFrameId = 1
@clock = 0
@isPlaying = true
@_updateFrame!
stop: =>
@isPlaying = false
setFrame: (frameId) =>
@clock = 0
@currentFrameId = frameId
@_updateFrame!
_updateFrame: =>
id = @currentFrameId - 1
fX = id % @frameCount.columns
fY = math.floor(id / @frameCount.columns)
@quad\setViewport(fX * @frame.width, fY * @frame.height, @frame.width, @frame.height)
| 27.130435 | 98 | 0.487714 |
192b00b8d31e41d9adb21b11267f80e6fbb2312a | 507 | import config from require "lapis.config"
_appname = "badakhshan"
_session_name = _appname .. "_session"
config "development", ->
appname _appname
session_name _session_name
port 8080
num_workers 1
secret "dev-secret"
lua_code_cache "off"
redis ->
host "127.0.0.1"
port 6379
config "production", ->
appname _appname
session_name _session_name
port 80
num_workers 4
secret assert os.getenv "LAPIS_SECRET"
lua_code_cache "on"
redis ->
host "127.0.0.1"
port 6379
| 18.777778 | 41 | 0.706114 |
1d54a218aa6aaa1fcafb03b90f3d45ef3a648176 | 289 | Entity = require "Lutron/Entity/Entity"
class ColoredEntity extends Entity
new: (x = 0, y = 0, width = 1, height = 1, r = 255, g = 255, b = 255, a = 255) =>
super x, y, width, height
@r = r
@g = g
@b = b
@a = a
draw: =>
lutro.graphics.setColor @r, @g, @b, @a
| 22.230769 | 83 | 0.529412 |
e280d90155b612edd3498cb099604914dbb71c80 | 6,604 | Dorothy!
AITreeViewView = require "View.Control.AI.AITreeView"
MenuItem = require "Control.AI.MenuItem"
TriggerDef = require "Data.TriggerDef"
ExprChooser = require "Control.Trigger.ExprChooser"
import Path from require "Lib.Utils"
MenuW = 200
MenuH = 40
Class AITreeViewView,
__init:(args)=>
@type = "AITree"
@extension = ".tree"
@exprData = nil
@items = nil
@modified = false
@filename = nil
@setupMenuScroll @treeMenu
@_selectedExprItem = nil
@changeExprItem = (button)->
@_selectedExprItem.checked = false if @_selectedExprItem
@_selectedExprItem = button.checked and button or nil
if button.checked
@editMenu.visible = true
{:expr,:parentExpr,:index} = button
isRoot = index == nil
isParentRoot = parentExpr == @exprData
isLeaf = switch expr[1]
when "Con","Act" then true
else false
@addBtn.text = isLeaf and "Append" or "Add"
edit = not isRoot
insert = not isRoot
add = true
del = not isRoot
up = index and ((isParentRoot and index > 3) or (not isParentRoot and index > 2))
down = index and index < #parentExpr
buttons = for v,k in pairs {:edit,:insert,:add,:del,:up,:down}
if k then v
else continue
@showEditButtons buttons
else
@editMenu.visible = false
@editBtn\slot "Tapped",->
selectedExprItem = @_selectedExprItem
if selectedExprItem
{:expr,:parentExpr,:index} = selectedExprItem
with ExprChooser {
valueType:"AINode"
expr:expr
parentExpr:parentExpr
owner:@
}
.backBtn.visible = false
\slot "Result",(newExpr)->
oldExpr = parentExpr[index]
parentExpr[index] = newExpr
selectedExprItem.expr = newExpr
if oldExpr ~= newExpr
@loadExpr @exprData
@.changeExprItem with @items[newExpr]
.checked = true
else
@alignNodes!
@notifyEdit!
@addBtn\slot "Tapped",->
selectedExprItem = @_selectedExprItem
{:expr,:parentExpr,:index} = selectedExprItem
with ExprChooser {
valueType:"AINode"
parentExpr:expr
owner:@
}
.backBtn.visible = false
\slot "Result",(newExpr)->
return unless newExpr
switch expr[1]
when "Con","Act"
table.insert parentExpr,index+1,newExpr
else
table.insert expr,newExpr
@alignNodes!
@.changeExprItem with @items[newExpr]
.checked = true
@notifyEdit!
@insertBtn\slot "Tapped",->
selectedExprItem = @_selectedExprItem
{:expr,:parentExpr,:index} = selectedExprItem
with ExprChooser {
valueType:"AINode"
parentExpr:expr
owner:@
}
.previewItem.visible = false
.backBtn.visible = false
\slot "Result",(newExpr)->
return unless newExpr
table.insert parentExpr,index,newExpr
@alignNodes!
@.changeExprItem with @items[newExpr]
.checked = true
@notifyEdit!
@delBtn\slot "Tapped",->
selectedExprItem = @_selectedExprItem
{:expr,:parentExpr,:index} = selectedExprItem
table.remove parentExpr,index
@loadExpr @exprData
@.changeExprItem with @items[parentExpr]
.checked = true
@notifyEdit!
@upBtn\slot "Tapped",->
selectedExprItem = @_selectedExprItem
{:expr,:parentExpr,:index} = selectedExprItem
if (parentExpr == @exprData and index > 3) or index > 2
parentExpr[index] = parentExpr[index-1]
parentExpr[index-1] = expr
@alignNodes!
@_selectedExprItem = nil
@.changeExprItem selectedExprItem
@notifyEdit!
@downBtn\slot "Tapped",->
selectedExprItem = @_selectedExprItem
{:expr,:parentExpr,:index} = selectedExprItem
if index < #parentExpr
parentExpr[index] = parentExpr[index+1]
parentExpr[index+1] = expr
@alignNodes!
@_selectedExprItem = nil
@.changeExprItem selectedExprItem
@notifyEdit!
notifyEdit:=>
@modified = true
emit "Scene.#{ @type }.Edited",@filename
loadExpr:(arg)=>
offset = @offset
@offset = oVec2.zero
@treeMenu\removeAllChildrenWithCleanup!
@drawNode = with CCDrawNode!
.anchor = oVec2.zero
.contentSize = @treeMenu.contentSize
@treeMenu\addChild @drawNode
@items = {}
@exprData = switch type arg
when "table" then arg
when "string"
@filename = arg
TriggerDef.SetExprMeta dofile arg
@alignNodes!
@offset = offset
alignNodes:=>
return unless @exprData
{positionX:rootX, positionY:rootY} = @treeMenu.children[1]
drawNode = @drawNode
drawNode\clear!
right,bottom = rootX,rootY
white = ccColor4!
drawLink = (x,y,startY)->
start = oVec2 x-MenuW/2+20,startY+MenuH/2+10
mid = oVec2 start.x,y
stop = oVec2 start.x+20,y
drawNode\drawSegment start,mid,0.5,white
drawNode\drawSegment mid,stop,0.5,white
nextNode = (parentExpr,index,x,y)->
expr = index and parentExpr[index] or parentExpr
return unless "table" == type expr
right = math.max x,right
bottom = math.min y,bottom
node = @items[expr]
if not node
node = with MenuItem {
expr:expr
index:index
parentExpr:parentExpr
width:MenuW
height:MenuH
}
\slot "Tapped",@changeExprItem
@treeMenu\addChild node
@items[expr] = node
switch expr[1]
when "AIRoot"
node.position = oVec2 x,y
y -= (MenuH+10)
startY = y
yCount = 1
for i = 3, #expr
drawLink x,y,startY
yLevel = nextNode expr,i,x+40,y
yCount += yLevel
y -= (MenuH+10)*yLevel
return yCount
when "Con","Act"
node.position = oVec2 x,y
return 1
else
node.position = oVec2 x,y
y -= (MenuH+10)
startY = y
yCount = 1
for i = 2, #expr
drawLink x,y,startY
yLevel = nextNode expr,i,x+40,y
yCount += yLevel
y -= (MenuH+10)*yLevel
return yCount
nextNode @exprData,nil,10+MenuW/2,@treeMenu.height-10-MenuH/2
@viewSize = CCSize right-rootX+MenuW+20,rootY-bottom+MenuH+20
save:=>
triggerText = TriggerDef.ToEditText @exprData
oContent\saveToFile editor.gameFullPath..@filename,triggerText
if not @isCodeHasError
codeFile = editor.gameFullPath..@filename
codeFile = Path.getPath(codeFile)..Path.getName(codeFile)..".lua"
triggerCode = TriggerDef.ToCodeText @exprData
oContent\saveToFile codeFile,triggerCode
showEditButtons:(names)=>
buttonSet = {@["#{ name }Btn"],true for name in *names}
posY = @editMenu.height-35
for i = 1,#@editMenu.children
child = @editMenu.children[i]
if buttonSet[child]
child.positionY = posY
child.visible = true
with child.face
.scaleX = 0
.scaleY = 0
\perform child.scaleAction
posY -= 60
else
child.visible = false
| 27.065574 | 85 | 0.658389 |
b7561db2a79a0e866f8386b2c8e6e5bf5094acfa | 802 |
import assert_env from require "lapis.environment"
truncate_tables = (...) ->
db = require "lapis.db"
assert_env "test", for: "truncate_tables"
tables = for t in *{...}
switch type(t)
when "table"
t\table_name!
when "nil"
error "nil passed to truncate tables, perhaps a bad reference?"
else
t
-- truncate is slow, so delete is used instead
-- db.truncate unpack tables
for table in *tables
db.delete table
drop_tables = (...) ->
db = require "lapis.db"
assert_env "test", for: "drop_tables"
names = for t in *{...}
db.escape_identifier if type(t) == "table"
t\table_name!
else
t
return unless next names
db.query "drop table if exists " .. table.concat names, ", "
{ :truncate_tables, :drop_tables }
| 21.675676 | 71 | 0.619701 |
65834ece04cfc0e79b5b91d0b8ac708034cdfcce | 477 | -- x, y, scale x, scale y, rotation: returns camera
make = (x, y, sx, sy, r) ->
cam =
:x, :y
:sx, :sy
:r
cam.move = (dx, dy) =>
@x += dx
@y += dy
@
cam.set = =>
with love.graphics
.push!
.translate .getWidth! / 2 - @x, .getHeight! / 2 - @y
.scale @sx, @sy
.rotate @r
@
cam.unset = =>
love.graphics.pop!
@
cam
{
:make
} | 15.9 | 64 | 0.366876 |
e46be12ce6292bd6fe70e401dcba0f245ce0a34f | 519 | -- get the app content
util = require "mooncrafts.util"
import path_sanitize from util
engage = (__sitename=ngx.var.__sitename) ->
-- ensure sitename is saniized
__sitename = path_sanitize(__sitename)
ngx.var.__sitename = __sitename
router = router_cache.resolve(__sitename)
ngx.log(ngx.ERR, __sitename) if router == nil
return router\handleRequest(ngx) if router
ngx.status = 500
ngx.say("Unexpected error while handling request, this should be a 404")
ngx.exit(ngx.status)
{ :engage }
| 24.714286 | 74 | 0.728324 |
68713baccd2961cf0a5b1cfac63818194e96a75c | 2,425 | class Vector
new: (@content = {}) =>
@type = "vector"
__add: (other) =>
switch other.type
when "vector"
assert #@content == #other.content, "Can't operate vectors of different dimensions!"
Vector [@content[i] + o for i, o in ipairs other.content]
when "matrix"
assert @cols == #other.content, "Can't operate vector and matrix with wrong dimensions!"
pass = {}
for i = 1, #other.content / other.cols
p = 0
for n = 1, other.cols
p += other.content[(i * other.cols) + n - 2] + @content[n]
pass[#pass + 1] = p
Vector pass
__sub: (other) =>
switch other.type
when "vector"
assert #@content == #other.content, "Can't operate vectors of different dimensions!"
Vector [@content[i] - o for i, o in ipairs other.content]
when "matrix"
assert @cols == #other.content, "Can't operate vector and matrix with wrong dimensions!"
pass = {}
for i = 1, #other.content / other.cols
p = 0
for n = 1, other.cols
p += other.content[(i * other.cols) + n - 2] - @content[n]
pass[#pass + 1] = p
Vector pass
__mul: (other) =>
switch other.type
when "vector"
assert #@content == #other.content, "Can't operate vectors of different dimensions!"
Vector [@content[i] * o for i, o in ipairs other.content]
when "matrix"
assert @cols == #other.content, "Can't operate vector and matrix with wrong dimensions!"
pass = {}
for i = 1, #other.content / other.cols
p = 0
for n = 1, other.cols
p += other.content[(i * other.cols) + n - 2] * @content[n]
pass[#pass + 1] = p
Vector pass
__div: (other) =>
switch other.type
when "vector"
assert #@content == #other.content, "Can't operate vectors of different dimensions!"
Vector [@content[i] / o for i, o in ipairs other.content]
when "matrix"
assert @cols == #other.content, "Can't operate vector and matrix with wrong dimensions!"
pass = {}
for i = 1, #other.content / other.cols
p = 0
for n = 1, other.cols
p += other.content[(i * other.cols) + n - 2] / @content[n]
pass[#pass + 1] = p
Vector pass
__neg: =>
Vector [-o for i, o in ipairs @content]
| 30.3125 | 96 | 0.545567 |
0cc61de22e9f07088fea624af3d6269ba50a22f6 | 1,549 | lapis = require "lapis"
util = require "lapis.util"
import assert_valid from require "lapis.validate"
import Model from require "lapis.db.model"
import
capture_errors
respond_to
from require "lapis.application"
class Address extends Model
class Estate extends Model
lapis.serve class extends lapis.Application
layout: require "views.lamutib"
handle_404: =>
"404 not found", status: 404
[estates: "/"]: =>
@title = "estates"
@estates = Estate\select!
render: true
[estate: "/estate/:code"]: =>
@e = Estate\find code: @params.code
return "estate not found", status: 404 unless @e
@a = Address\find @e.address_id
@title = "estate " .. @e.code
render: true
[new_estate: "/estate"]: respond_to {
GET: =>
@title = "create an estate"
render: true
POST: capture_errors =>
assert_valid @params, {
{ "code", exists: true, min_length: 3, max_length: 17 }
{ "build", optional: true, is_integer: true }
{ "comment", optional: true, min_length: 3, max_length: 37 }
{ "street", min_length: 3, max_length: 17 }
{ "zipcode", min_length: 5, max_length: 5 }
{ "city", min_length: 3, max_length: 17 }
}
a = Address\create
street: @params.street
zipcode: @params.zipcode
city: @params.city
country: @params.country
Estate\create
address_id: a.id
code: @params.code
build: @params.build
comment: @params.comment
redirect_to: @url_for "estates"
}
| 26.254237 | 68 | 0.619109 |
dfe3afdbf077e53aa51091c702e099fb65ac513a | 2,531 | niceatan = (y,x) ->
a = math.atan2(y,x)
if a < 0
a = -a
else
a = math.pi + math.pi - a
return a
niceAngle = (a) ->
if a > 2*math.pi or a <0
a = a%(2*math.pi)
return a
between = (a,b,c) ->
return (a >= c and c <= b) or (a <= c and c >= b )
class Boat
SPEED = 1000
ROWSIZE = 50
new: =>
@body = love.physics.newBody(world, 650/2, 650/2, "dynamic")
--@shape = love.physics.newCircleShape(20)
@shape = love.physics.newRectangleShape(50, 70)
--@shape = love.physics.newPolygonShape(-50,-50,50,25,50,-50)
@fixture = love.physics.newFixture(@body, @shape, 1)
@body\setLinearDamping(1)
@body\setAngularDamping(1)
@joystick = love.joystick.getJoysticks![1]
assert(@joystick, "no joystick found")
@rowleft = {0,0}
@rowright = {0,0}
update: (dt) =>
ax,ay,_,ax2,ay2 = @joystick\getAxes!
@\moveRow(dt,1,ax,ay)
@\moveRow(dt,2,ax2,ay2)
--@rowleft[1], @rowleft[2] = ax,ay
--@rowright[1], @rowright[2] = ax2,ay2
--@body\applyForce(SPEED*ax*dt,SPEED*ay*dt)
draw: =>
bx,by = @body\getX!, @body\getY!
--love.graphics.circle("fill", @body\getX(), @body\getY(), @shape\getRadius())
love.graphics.polygon("fill", @body\getWorldPoints(@shape\getPoints()))
@drawRow(@rowleft)
@drawRow(@rowright)
moveRow: (dt,rown,x,y) =>
a = niceatan(y,x)
bd = niceAngle(@body\getAngle!)
local row,d,l
if rown == 1 then
row = @rowleft
d = 1
if x < 0 then
l = math.sqrt(math.pow(x,2) + math.pow(y,2))
else
l = 0
elseif rown == 2 then
row = @rowright
d = -1
if x > 0
l = math.sqrt(math.pow(x,2) + math.pow(y,2))
else
l = 0
mod = (a, n) -> a - math.floor(a/n) * n
da = row[1] - a
da = mod((da + math.pi), 2*math.pi) - math.pi
da = da
c = SPEED*da*l
fpi = math.pi/2
--@body\applyForce(@body\getLocalVector(0,SPEED*da*l))
if row == @rowright
@body\applyForce(-math.cos(bd+fpi)*c, -math.sin(bd+fpi)*c)
@body\applyTorque(5000*da*l*d)
else
@body\applyForce(math.cos(bd+fpi)*c, math.sin(bd+fpi)*c)
@body\applyTorque(-5000*da*l*d)
row[1],row[2] = a,l
drawRow: (row) =>
bx,by = @body\getX!, @body\getY!
bd = @body\getAngle!
--a = math.atan2(row[2],row[1])
--l = math.min(2,1/math.sqrt(math.pow(row[1],2) + math.pow(row[2],2)))
a,l = row[1],row[2]
love.graphics.line(bx,by,bx+ ROWSIZE*l*math.cos(a-bd), by-ROWSIZE*l*math.sin(a-bd))
return Boat
| 25.565657 | 87 | 0.557487 |
9484d9f2d3b1150205915999f72f41dadca4861c | 1,582 | -- Copyright 2016 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
{:bundle} = howl
{:File} = howl.io
{:env} = howl.sys
describe 'bundle.ruby.util', ->
local util
setup ->
bundle.load_by_name 'ruby'
util = _G.bundles.ruby.util
teardown -> bundle.unload 'ruby'
describe 'ruby_version_for(path)', ->
it 'supports .ruby-version files', ->
with_tmpdir (dir) ->
ruby_version = dir / '.ruby-version'
ruby_version.contents = '2.3\n'
root_file = dir / 'root.rb'
root_file\touch!
sub_file = dir\join('sub/below.rb')
sub_file\mkdir_p!
for path in *{root_file, sub_file, dir}
assert.equal '2.3', util.ruby_version_for path
it 'returns nil if no particular version is found', ->
with_tmpdir (dir) ->
assert.is_nil util.ruby_version_for dir\join('sub.rb')
assert.is_nil util.ruby_version_for dir
describe 'ruby_command_for(path)', ->
REAL_HOME = env.HOME
describe 'with a .ruby-version file present', ->
local dir
before_each ->
dir = File.tmpdir!
ruby_version = dir / '.ruby-version'
ruby_version.contents = '2.3\n'
env.HOME = dir.path
after_each ->
env.HOME = REAL_HOME
dir\delete_all! if dir.exists
it 'returns a matching executable from the rvm rubies if possible', ->
exec = with dir\join('.rvm/wrappers/ruby-2.3.0/ruby')
\mkdir_p!
\touch!
assert.equals exec.path, util.ruby_command_for dir
| 28.25 | 79 | 0.620733 |
621ca95f038a6bc696891f9960b5aeaa83f975aa | 12,235 | require "imgui"
lunajson = require "lunajson"
filename = ""
mode = "idle"
waypoints = {}
selected = 0
next_waypoint = 1
runways = {}
next_runway = 1
selected_runway = 0
selected_runway_point = 0
local runway_drag_offset
local font
dimensions = {50, 50}
love.load = ->
font = love.graphics.newFont('3270Medium.ttf', 20)
love.graphics.setFont(font)
love.window.setMode(0, 0)
love.update = ->
imgui.NewFrame!
love.draw = ->
imgui.Begin('Main')
_, filename = imgui.InputText("Filename", filename, 64)
_, dimensions[1], dimensions[2] = imgui.DragFloat2(
"Boundary Dimensions", dimensions[1], dimensions[2])
if dimensions[1] < 0.0
dimensions[1] = 0.0
if dimensions[2] < 0.0
dimensions[2] = 0.0
if imgui.Button('Export')
f = io.open(filename, 'w')
io.output(f)
io.write(lunajson.encode({
width: dimensions[1],
height: dimensions[2],
waypoints: [{
name: wp.name,
x: wp.x,
y: dimensions[2] - wp.y
} for _, wp in pairs waypoints]
runways: [{
names: rw.names,
points: [{x: point.x, y: dimensions[2] - point.y} for _, point in ipairs rw.points]
} for _, rw in pairs runways]
}))
io.close(f)
if imgui.Button('Load')
f = io.open(filename, 'r')
io.input(f)
obj = lunajson.decode(io.read("*all"))
dimensions = {obj.width, obj.height}
waypoints = [{
name: wp.name,
x: wp.x,
y: dimensions[2] - wp.y
} for _, wp in pairs obj.waypoints]
runways = [{
names: rw.names,
points: [{x: point.x, y: dimensions[2] - point.y} for _, point in ipairs rw.points]
} for _, rw in pairs obj.runways]
io.close(f)
imgui.End!
if selected != 0
wp = waypoints[selected]
imgui.Begin('Edit Waypoint')
_, wp.name = imgui.InputText("Name", wp.name, 8)
if imgui.Button('Delete Waypoint')
waypoints[selected] = nil
selected = 0
imgui.End!
if selected_runway != 0
rw = runways[selected_runway]
imgui.Begin('Edit Runway')
for i, name in ipairs rw.names
_, name.name = imgui.InputText("Name "..i, name.name, 8)
_, name.offset.angle = imgui.DragFloat("Name "..i.." Angle", name.offset.angle)
_, name.distance = imgui.DragFloat("Name "..i.." Distance", name.distance)
name.offset.x = name.distance * math.cos(name.offset.angle)
name.offset.y = name.distance * math.sin(name.offset.angle)
if imgui.Button('Delete Runway')
runways[selected_runway] = nil
selected_runway = 0
imgui.End!
love.graphics.clear(89, 142, 111, 255)
for id, wp in pairs waypoints
love.graphics.setColor(16, 71, 20)
love.graphics.circle("fill", wp.x, wp.y, 10, 50)
if selected == id
love.graphics.setColor(208, 232, 210)
else
love.graphics.setColor(100, 153, 107)
love.graphics.setLineWidth(2)
love.graphics.circle("line", wp.x, wp.y, 10, 50)
for _, wp in pairs waypoints
love.graphics.setColor(16, 71, 20)
love.graphics.print(wp.name, wp.x + 10, wp.y + 10)
for id, rw in pairs runways
love.graphics.setLineWidth(3)
love.graphics.setColor(16, 71, 20)
love.graphics.line(rw.points[1].x, rw.points[1].y, rw.points[2].x, rw.points[2].y)
if id == selected_runway
love.graphics.setColor(208, 232, 210)
for i, name in ipairs rw.names
love.graphics.printf(name.name,
rw.points[i].x + name.offset.x - 200,
rw.points[i].y + name.offset.y - font\getHeight() / 2,
400,
'center')
love.graphics.setLineWidth(3)
love.graphics.setColor(208, 232, 210)
love.graphics.rectangle("line", 2, 2, dimensions[1], dimensions[2])
love.graphics.setLineWidth(2)
love.graphics.setColor(0, 0, 0)
y = love.graphics.getHeight()
love.graphics.line(20, y - 20, 20 + 100, y - 20)
love.graphics.print("5 km", 20, y - 40)
love.graphics.setColor(255, 255, 255, 255)
imgui.Render()
love.quit = ->
imgui.ShutDown!
love.textinput = (t) ->
imgui.TextInput(t)
love.keypressed = (k) ->
imgui.KeyPressed(k)
love.keyreleased = (k) ->
imgui.KeyReleased(k)
snap = (x, y, sx, sy) ->
dx = x - sx
dy = y - sy
if math.sqrt(dx * dx + dy * dy) < 8
return sx, sy
return x, y
snapRunway = (x, y, i) ->
sel = runways[selected_runway]
dx = sel.points[i].x - x
dy = sel.points[i].y - y
dist = math.sqrt(dx * dx + dy * dy)
sqrt2 = math.sqrt(2) / 2
--90 deg
x, y = snap(x, y, x, sel.points[i].y)
x, y = snap(x, y, sel.points[i].x, y)
--45 deg
x, y = snap(x, y, sel.points[i].x + dist * sqrt2, sel.points[i].y + dist * sqrt2)
x, y = snap(x, y, sel.points[i].x - dist * sqrt2, sel.points[i].y + dist * sqrt2)
x, y = snap(x, y, sel.points[i].x + dist * sqrt2, sel.points[i].y - dist * sqrt2)
x, y = snap(x, y, sel.points[i].x - dist * sqrt2, sel.points[i].y - dist * sqrt2)
for id, rw in pairs runways
if id != selected_runway
--parallel
dx = rw.points[2].x - rw.points[1].x
dy = rw.points[2].y - rw.points[1].y
len = math.sqrt(dx * dx + dy * dy)
dx /= len
dy /= len
x, y = snap(x, y, sel.points[i].x + dist * dx, sel.points[i].y + dist * dy)
x, y = snap(x, y, sel.points[i].x - dist * dx, sel.points[i].y - dist * dy)
x, y = snap(x, y, sel.points[i].x + dist * dy, sel.points[i].y - dist * dx)
x, y = snap(x, y, sel.points[i].x - dist * dy, sel.points[i].y + dist * dx)
return x, y
snapWaypoint = (x, y) ->
for id, rw in pairs runways
--colinear
rx1, ry1 = rw.points[1].x, rw.points[1].y
rx2, ry2 = rw.points[2].x, rw.points[2].y
dx = rx2 - rx1
dy = ry2 - ry1
dx2, dy2 = -dy, dx
x2 = x + dx2
y2 = y + dy2
xi = ((rx1 * ry2 - ry1 * rx2) * (x - x2) - (rx1 - rx2) * (x * y2 - y * x2)) /
((rx1 - rx2) * (y - y2) - (x - x2) * (ry1 - ry2))
yi = ((rx1 * ry2 - ry1 * rx2) * (y - y2) - (ry1 - ry2) * (x * y2 - y * x2)) /
((rx1 - rx2) * (y - y2) - (x - x2) * (ry1 - ry2))
x, y = snap(x, y, xi, yi)
return x, y
love.mousemoved = (x, y) ->
imgui.MouseMoved(x, y)
if not imgui.GetWantCaptureMouse!
switch mode
when "dragging"
x, y = snapWaypoint(x, y)
waypoints[selected].x = x
waypoints[selected].y = y
when "placing_runway"
x, y = snapRunway(x, y, 1)
runways[selected_runway].points[2].x = x
runways[selected_runway].points[2].y = y
when "editing_runway"
x, y = snapRunway(x, y, if selected_runway_point == 1 then 2 else 1)
runways[selected_runway].points[selected_runway_point].x = x
runways[selected_runway].points[selected_runway_point].y = y
when "dragging_runway"
runways[selected_runway].points[2].x = x + runway_drag_offset.x +
runways[selected_runway].points[2].x - runways[selected_runway].points[1].x
runways[selected_runway].points[2].y = y + runway_drag_offset.y +
runways[selected_runway].points[2].y - runways[selected_runway].points[1].y
runways[selected_runway].points[1].x = x + runway_drag_offset.x
runways[selected_runway].points[1].y = y + runway_drag_offset.y
love.mousepressed = (x, y, button) ->
imgui.MousePressed(button)
if not imgui.GetWantCaptureMouse!
switch mode
when "placing_runway"
mode = "idle"
when "editing_runway"
mode = "idle"
when "dragging_runway"
mode = "idle"
when "idle"
for id, wp in pairs waypoints
dx = x - wp.x
dy = y - wp.y
if math.sqrt(dx * dx + dy * dy) < 10
if button == 2
if selected == id
selected = 0
waypoints[id] = nil
else
selected = id
mode = "dragging"
return
for id, rw in pairs runways
x1, y1 = rw.points[1].x, rw.points[1].y
x2, y2 = rw.points[2].x, rw.points[2].y
dx, dy = x - x1, y - y1
if math.sqrt(dx * dx + dy * dy) < 10
selected_runway = id
selected_runway_point = 1
mode = "editing_runway"
dx, dy = x - x2, y - y2
if math.sqrt(dx * dx + dy * dy) < 10
selected_runway = id
selected_runway_point = 2
mode = "editing_runway"
px = x2 - x1
py = y2 - y1
lsq = px * px + py * py
u = ((x - x1) * px + (y - y1) * py) / lsq
if u > 1
u = 1
if u < 0
u = 0
xx = x1 + u * px
yy = y1 + u * py
dx = x - xx
dy = y - yy
dist = math.sqrt(dx * dx + dy * dy)
if dist < 12
selected_runway = id
mode = "dragging_runway"
runway_drag_offset = {
x: rw.points[1].x - x
y: rw.points[1].y - y
}
return
if button == 1
if love.keyboard.isDown("lshift")
runways[next_runway] =
names: {
{
name: "1C"
distance: 20
offset: {
angle: 0
x: 10
y: 0
}
},
{
name: "1C"
distance: 20
offset: {
angle: 0
x: 10
y: 0
}
}
}
points: {
{
x: x
y: y
},
{
x: x
y: y
}
}
selected_runway = next_runway
selected = 0
next_runway += 1
mode = "placing_runway"
else
x, y = snapWaypoint(x, y)
waypoints[next_waypoint] =
x: x
y: y
name: "NWPT"
selected = next_waypoint
next_waypoint += 1
love.mousereleased = (x, y, button) ->
imgui.MouseReleased(button)
switch mode
when "dragging"
mode = "idle"
love.wheelmoved = (x, y) ->
imgui.WheelMoved(y)
| 35.985294 | 99 | 0.440049 |
86b33547d11882087babaf3a60fc8819d6c2cf93 | 130 |
-- insert all moon library functions into requiring scope
export moon
moon = moon or {}
moon.inject = true
require "moon.init"
| 14.444444 | 57 | 0.738462 |
546843a89b4ef214a6833558c48af0ba37e86e84 | 9,002 | -- dev/bgfxgen.moon
--
-- generate bgfx auxilliary files
-- assumes truss has been built into "../build/"
sutil = require "util/string.t"
argparse = require "util/argparse.t"
genconstants = require "dev/genconstants.t"
BGFX_PATH = "/bgfx_EXTERNAL-prefix/src/bgfx_EXTERNAL"
os_exec = (cmd) ->
f = io.popen cmd, "r"
ret = f\read "*all"
f\close!
ret
os_copy = (srcfn, destfn) ->
cmd = if truss.os == "Windows"
"copy \"#{srcfn\gsub("/", "\\")}\" \"#{destfn\gsub("/", "\\")}\" /y"
else
"cp \"#{srcfn}\" \"#{destfn}\""
print cmd
print os_exec cmd
copy_files = (buildpath) ->
srcpath = "#{buildpath}#{BGFX_PATH}"
os_copy "#{srcpath}/include/bgfx/defines.h", "include/bgfxdefines.h"
os_copy "#{srcpath}/examples/common/shaderlib.sh", "shaders/raw/common/shaderlib.sh"
os_copy "#{srcpath}/src/bgfx_shader.sh", "shaders/raw/common/bgfx_shader.sh"
os_copy "#{srcpath}/src/bgfx_compute.sh", "shaders/raw/common/bgfx_compute.sh"
rawload = (fn) -> (io.open fn, "rt")\read "*a"
DEFINE_PATT = "^#define%s*([%w_]*)[^%(%w_]"
get_define_names = () ->
-- assumes `defines.h` has been copied to `include/bgfxdefines.h`
defnames = {}
for line in *(sutil.split_lines rawload "include/bgfxdefines.h")
name = line\match DEFINE_PATT
if name and name != ""
table.insert defnames, name
defnames
get_constants = () -> genconstants.gen_constants_file get_define_names!
to_snake_case = (s) ->
s_first = s\sub(1,1)\upper!
s_rem = s\sub 2, -1
s = s_first .. s_rem
table.concat [v\lower! for v in s\gmatch "[%u%d]+%l*"], "_"
lower_snake = (s) -> (to_snake_case s)\lower!
upper_snake = (s) -> (to_snake_case s)\upper!
remove_comment = (s) ->
fpos = s\find "%-%-"
if fpos
s = s\sub 1, fpos-1
sutil.strip s
fix5p1 = (data) ->
lines = sutil.split_lines data
outlines = {}
cur_enum = nil
for linepos = 1, #lines
curline = remove_comment sutil.strip lines[linepos]
if (curline\sub 1,4) == "enum"
cur_enum = curline\sub 5,-1
elseif cur_enum and curline == ""
if (outlines[#outlines]\sub -2,-1) != "()"
print("Enum missing function call: #{cur_enum}")
outlines[#outlines] = outlines[#outlines] .. "()"
cur_enum = nil
if (curline\sub 1,2) == "()"
outlines[#outlines] = outlines[#outlines] .. curline
else
outlines[#outlines+1] = curline
temp = io.open "bleh.lua", "wt"
temp\write table.concat outlines, "\n"
temp\close!
table.concat outlines, "\n"
_flatten = (dest, list) ->
for v in *list
if type(v) == 'table' then
_flatten dest, v
else
dest[#dest+1] = v
dest
flatten = (lists) -> _flatten {}, lists
conflatten = (lists) -> table.concat (flatten lists), "\n"
ordered_concat = (t, keyorder, sep) ->
table.concat [t[k] for k in *keyorder], (sep or "\n\n")
key_sorted_concat = (t, sep) ->
sorted_keys = [k for k, v in pairs t]
table.sort sorted_keys
ordered_concat t, sorted_keys, sep
exec_in = (env, fn) ->
src = fix5p1 rawload fn
chunk, err = loadstring src
if not chunk
truss.error "Error parsing #{fn}: #{err}"
setfenv chunk, env
chunk! or env
load_idl = (buildpath) ->
env = truss.extend_table {}, truss.clean_subenv
path = buildpath .. BGFX_PATH
print "Loading IDL from [#{path}]"
idl = exec_in env, "#{path}/scripts/idl.lua"
exec_in idl, "#{path}/scripts/bgfx.idl"
BANNED_TYPES = {"va_list"}
is_api_func = (line) ->
parts = sutil.split " ", line
if parts[1] != "BGFX_C_API" then return nil
api_key = (parts[2] != "const" and parts[3]) or parts[4] or line
api_key = (sutil.split "%(", api_key)[1]
signature = table.concat [p for p in *parts[2,]], " "
for bad_type in *BANNED_TYPES
if line\find bad_type
signature = "//" .. signature
signature, api_key
get_functions = (buildpath) ->
-- generating function signatures from the IDL is too much of a pain
-- instead just read them from the C-api header
path = "#{buildpath}#{BGFX_PATH}/include/bgfx/c99/bgfx.h"
api_funcs = {}
for line in *(sutil.split_lines rawload path)
api_line, api_order_key = is_api_func line
if api_line then api_funcs[api_order_key] = api_line
key_sorted_concat api_funcs, "\n"
gen_enum = (e) ->
format_val = if e.underscore
(v) -> upper_snake v
else
(v) -> v\upper!
name = "bgfx_#{lower_snake e.name}"
conflatten {
"typedef enum #{name} {",
(table.concat [" #{name\upper!}_#{format_val v.name}" for v in *e.enum], ",\n") .. ",",
" #{name\upper!}_COUNT",
"} #{name}_t;"
}
gen_enums = (idl) ->
enums = {t.name, gen_enum t for t in *idl.types when t.enum}
key_sorted_concat enums, "\n\n"
gen_handle = (handle) ->
name = "bgfx_#{lower_snake handle.name}"
"typedef struct #{name} { uint16_t idx; } #{name}_t;"
gen_handles = (idl) ->
handles = {t.name, gen_handle t for t in *idl.types when t.handle}
key_sorted_concat handles, "\n"
is_pointer = (s) -> ((s\sub -1) == "*") and (s\sub 1, -2)
is_const = (s) -> ((s\sub 1, 5) == "const") and (s\sub 7)
is_enum = (s) ->
parts = sutil.split "::", s
if #parts == 2 and (parts[2]\sub 1, 4) == "Enum"
parts[1]
else
false
is_array = (s) ->
array_start = s\find "%["
if not array_start then return nil, nil
return (s\sub 1, array_start-1), (s\sub array_start+1, -2)
FIXED_TYPES = {
"float": "float"
"double": "double"
"char": "char"
"bool": "bool"
"CallbackI": "bgfx_callback_interface_t"
"bx::AllocatorI": "bgfx_allocator_interface_t"
"void": "void"
}
for itype in *{8, 16, 32, 64}
for qualifier in *{"uint", "int"}
tname = "#{qualifier}#{itype}_t"
FIXED_TYPES[tname] = tname
format_count = (count) ->
parts = sutil.split "::", count
if #parts == 2 -- assume ::Count
"BGFX_#{upper_snake parts[1]}_COUNT"
else
count
namespaced_structs = {}
format_type = (t, parent) ->
subtype, count = is_array t
if subtype
(format_type subtype, parent), (format_count count)
else
pointer_type = is_pointer t
if pointer_type
t = pointer_type
const_type = is_const t
if const_type
t = const_type
res = ""
if FIXED_TYPES[t]
res = FIXED_TYPES[t]
else
res = lower_snake ((is_enum t) or t)
if parent and namespaced_structs["#{parent}_#{res}"]
res = "#{parent}_#{res}"
res = "bgfx_" .. res .. "_t"
if pointer_type
res = res .. "*"
if const_type
res = "const " .. res
res
format_field = (f, parent) ->
argtype, argcount = format_type f.fulltype, parent
name = f.name
if argcount
name = "#{name}[#{argcount}]"
" #{argtype} #{name};"
gen_struct = (struct) ->
name = lower_snake struct.name
if struct.namespace
name = "#{lower_snake struct.namespace}_#{name}"
namespaced_structs[name] = true
if #struct.struct == 0
return name, "typedef struct bgfx_#{name}_s bgfx_#{name}_t;"
name, conflatten {
"typedef struct bgfx_#{name}_s {",
[format_field f, name for f in *struct.struct]
"} bgfx_#{name}_t;"
}
gen_structs = (idl) ->
structs = {}
for t in *idl.types
if not t.struct then continue
name, struct = gen_struct t
table.insert structs, struct
table.concat structs, "\n\n"
PREAMBLE = [[
/*
* BGFX Copyright 2011-2021 Branimir Karadzic. All rights reserved.
* License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
*
* This header is slightly modified to make it easier for Terra
* to digest; it is automatically generated from the 'real' BGFX
* headers and IDL by `dev/bgfxgen.moon`.
*/
#ifndef BGFX_C99_H_HEADER_GUARD
#define BGFX_C99_H_HEADER_GUARD
//#include <stdarg.h> // va_list
#include <stdbool.h> // bool
#include <stdint.h> // uint32_t
#include <stdlib.h> // size_t
#undef UINT32_MAX
#define UINT32_MAX 4294967295
#define BGFX_UINT32_MAX 4294967295
#define BGFX_INVALID_HANDLE 0xffff
typedef uint16_t bgfx_view_id_t;
typedef struct bgfx_interface_vtbl bgfx_interface_vtbl_t;
typedef struct bgfx_callback_interface bgfx_callback_interface_t;
typedef struct bgfx_callback_vtbl bgfx_callback_vtbl_t;
typedef struct bgfx_allocator_interface bgfx_allocator_interface_t;
typedef struct bgfx_allocator_vtbl bgfx_allocator_vtbl_t;
typedef void (*bgfx_release_fn_t)(void* _ptr, void* _userData);
]]
gen_header = (buildpath) ->
idl = load_idl buildpath
conflatten {
PREAMBLE,
"\n\n/* Enums: */\n",
gen_enums idl,
"\n\n/* Handle types: */\n",
gen_handles idl,
"\n\n/* Structs: */\n",
gen_structs idl,
"\n\n/* Functions: */\n",
get_functions buildpath,
"\n",
"#endif // BGFX_C99_H_HEADER_GUARD"
}
export init = ->
bpath = truss.args[3] or "../build"
print "Copying files from #{bpath}"
copy_files bpath
print "Generating include/bgfx_truss.c99.h"
truss.save_string "include/bgfx_truss.c99.h", (gen_header bpath)
print "Generating scripts/gfx/bgfx_constants.t"
truss.save_string "scripts/gfx/bgfx_constants.t", get_constants!
print "Done."
truss.quit!
export update = ->
truss.quit! | 27.783951 | 94 | 0.64719 |
b0fb175281d42dca3c085bdaba30c91fd8b7d521 | 1,592 | import Widget from require "lapis.html"
class DefaultLayout extends Widget
content: =>
html_5 ->
head ->
meta charset:"UTF-8"
title @title or "IceShard"
link -- Bootstrap CSS (4.2.1)
rel: 'stylesheet'
href: 'https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css'
integrity: 'sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS'
crossorigin: 'anonymous'
script -- JQuery Slim (3.3.1)
src: 'https://code.jquery.com/jquery-3.3.1.slim.min.js'
integrity: 'sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo'
crossorigin: 'anonymous'
script -- Bootstrap JS (4.2.1)
src: 'https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js'
integrity: 'sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k'
crossorigin: 'anonymous'
script -- Popper (1.14.6)
src: 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js'
integrity: 'sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut'
crossorigin: 'anonymous'
body ->
@content_for 'navbar' if @has_content_for 'navbar'
if @has_content_for 'jumbotron'
@content_for 'jumbotron'
@content_for 'inner'
else
div class:'container-fluid pt-5', ->
@content_for 'inner'
@content_for 'footer' if @has_content_for 'footer'
| 38.829268 | 95 | 0.631281 |
a8f19de074f5538e4d050b5c43843f84678211c8 | 15,277 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
{:BufferContext, :BufferLines, :BufferMarkers, :Chunk, :config, :mode, :signal, :sys} = howl
{:PropertyObject} = howl.util.moon
{:File} = howl.io
{:utf8} = howl.util
aullar = require 'aullar'
ffi = require 'ffi'
ffi_string, ffi_new = ffi.string, ffi.new
append = table.insert
min = math.min
buffer_id = 0
next_id = ->
buffer_id += 1
return buffer_id
class Buffer extends PropertyObject
new: (b_mode = {}) =>
super!
@id = next_id!
@_buffer = aullar.Buffer!
@markers = BufferMarkers @_buffer
@completers = {}
@inspectors = {}
@mode = b_mode
@_set_config!
@config\clear!
@properties = {}
@data = {}
@_eol = '\n'
@viewers = 0
@_modified = false
@sync_revision_id = @_buffer\get_revision_id true
@last_changed = sys.time!
@_buffer\add_listener
on_inserted: self\_on_text_inserted
on_deleted: self\_on_text_deleted
on_changed: self\_on_text_changed
@property file:
get: => @_file
set: (file) =>
@_associate_with_file file
modified = false
if file.exists
contents = file.contents
contents, changed = utf8.clean_string(contents)
if changed > 0
log.info "cleaned up '#{file}', now #{#contents} bytes"
modified = true
@_buffer.text = contents
@sync_etag = file.etag
-- update EOL from loaded file if possible
first_line = @_buffer\get_line 1
if first_line and first_line.has_eol
eol = @_buffer\sub first_line.size + 1, first_line.end_offset
@eol = eol
else
@text = ''
@sync_etag = nil
@can_undo = false
@_modified = modified
@sync_revision_id = @_buffer\get_revision_id true
@property mode:
get: => @_mode
set: (new_mode = {}) =>
old_mode = @_mode
@_mode = new_mode
if new_mode.lexer
@_buffer.lexer = (text) -> new_mode.lexer text, @
else
@_buffer.lexer = nil
@_set_config!
signal.emit 'buffer-mode-set', buffer: self, mode: new_mode, :old_mode
@property title:
get: => @_title or (@file and @file.basename) or 'Untitled'
set: (title) =>
@_title = title
signal.emit 'buffer-title-set', buffer: self
@property text:
get: => @_buffer.text
set: (text) =>
@_buffer.text = utf8.clean_string(text)
@property modified:
get: => @_modified
set: (status) =>
if status
notify = not @_modified
@_modified = true
if notify
signal.emit 'buffer-modified', buffer: self
else
@_modified = false
@property can_undo:
get: => @_buffer.can_undo
set: (value) => @_buffer\clear_revisions! if not value
@property collect_revisions:
get: => @_buffer.collect_revisions
set: (v) => @_buffer.collect_revisions = v
@property size: get: => @_buffer.size
@property length: get: => @_buffer.length
@property lines: get: => BufferLines self, @_buffer
@property eol:
get: => @_eol
set: (eol) =>
if eol != '\n' and eol != '\r' and eol != '\r\n'
error 'Unknown eol mode'
@_eol = eol
@property showing: get: => @viewers > 0
@property last_shown:
get: => @viewers > 0 and sys.time! or @_last_shown
set: (timestamp) => @_last_shown = timestamp
@property multibyte: get: =>
@_buffer.multibyte
@property modified_on_disk: get: =>
return false if not @file or not @file.exists
@file and @file.etag != @sync_etag
@property read_only:
get: => @_buffer.read_only
set: (v) => @_buffer.read_only = v
@property _config_scope:
get: => @_file and config.scope_for_file(@_file.path) or ('buffer/' .. @id)
chunk: (start_pos, end_pos) => Chunk self, start_pos, end_pos
context_at: (pos) => BufferContext self, pos
delete: (start_pos, end_pos) =>
return if start_pos > end_pos
b_start, b_end = @byte_offset(start_pos), @byte_offset(end_pos + 1)
@_buffer\delete b_start, b_end - b_start
insert: (text, pos) =>
b_pos = @byte_offset pos
text = utf8.clean_string(text)
@_buffer\insert b_pos, text
pos + text.ulen
append: (text) =>
text = utf8.clean_string(text)
@_buffer\insert @_buffer.size + 1, text
@length + 1
replace: (pattern, replacement) =>
matches = {}
pos = 1
text = @text
while pos <= @length
start_pos, end_pos, match = text\ufind pattern, pos
break unless start_pos
-- only replace the match within pattern if present
end_pos = match and (start_pos + #match - 1) or end_pos
append matches, start_pos
append matches, end_pos
pos = end_pos + 1
return if #matches == 0
if @multibyte
matches = [@_buffer\byte_offset(p) for p in *matches]
offset = matches[1]
count = matches[#matches] - offset + 1
replacement = utf8.clean_string(replacement)
@_buffer\change offset, count, ->
for i = #matches, 1, -2
start_pos = matches[i - 1]
end_pos = matches[i]
@_buffer\replace start_pos, (end_pos - start_pos) + 1, replacement
#matches / 2
change: (start_pos, end_pos, changer) =>
b_start, b_end = @byte_offset(start_pos), @byte_offset(end_pos + 1)
@_buffer\change b_start, b_end - b_start, ->
changer @
save: =>
if @file
if @_mode.before_save
success, ret = pcall @_mode.before_save, @_mode, @
log.error "Error invoking #{@_mode.name} mode before_save #{ret}" unless success
if @config.strip_trailing_whitespace
ws = '[\t ]'
@replace "(#{ws}+)#{@eol}", ''
@replace "(#{ws}+)#{@eol}?$", ''
if @config.ensure_newline_at_eof and not @text\match "#{@eol}$"
@append @eol
local backup
if @config.backup_files and @file.exists
file_stem = "#{@file.basename}::#{ffi.C.getpid!}::#{@file.etag}"
backup_directory = File @config.backup_directory or howl.app.settings.backupdir
backup = backup_directory / file_stem
status, err = pcall @file\copy, backup, {'COPY_OVERWRITE', 'COPY_ALL_METADATA'}
if not status
log.error "Failed to write backup file #{backup} for #{@file}: #{err}"
backup = nil
@file.contents = @text
@_modified = false
@sync_etag = @file.etag
@sync_revision_id = @_buffer\get_revision_id true
if backup
status, err = pcall backup\delete
if not status
log.warn "Failed to delete backup file #{backup} for #{@file}: #{err}"
signal.emit 'buffer-saved', buffer: self
save_as: (file) =>
@_associate_with_file file
@save!
as_one_undo: (f) => @_buffer\as_one_undo f
undo: =>
@_buffer\undo!
@_modified = @_buffer\get_revision_id! != @sync_revision_id
redo: =>
@_buffer\redo!
@_modified = @_buffer\get_revision_id! != @sync_revision_id
char_offset: (byte_offset) =>
@_buffer\char_offset byte_offset
byte_offset: (char_offset) =>
@_buffer\byte_offset char_offset
sub: (start_pos, end_pos = -1) =>
len = @length
start_pos += len + 1 if start_pos < 0
end_pos += len + 1 if end_pos < 0
start_pos = 1 if start_pos < 1
end_pos = len if end_pos > len
byte_start_pos = @byte_offset(start_pos)
-- we find the start of the next character
-- to include the last byte in a multibyte character
byte_end_pos = min @byte_offset(end_pos + 1), @_buffer.size + 1
byte_size = byte_end_pos - byte_start_pos
return '' if byte_size <= 0
ffi_string @_buffer\get_ptr(byte_start_pos, byte_size), byte_size
get_ptr: (start_pos, end_pos) =>
if end_pos < start_pos
return ffi_new('const char[1]', 0), 0
len = @length
if not start_pos or start_pos < 1 or start_pos > len or
not end_pos or end_pos < 1 or end_pos > len
error "Buffer.get_ptr(): Illegal span: (#{start_pos}, #{end_pos} for buffer with length #{len}", 2
byte_start_pos = @byte_offset(start_pos)
byte_end_pos = min @byte_offset(end_pos + 1), @_buffer.size + 1
count = byte_end_pos - byte_start_pos
@_buffer\get_ptr(byte_start_pos, count), count
find: (search, init = 1) =>
if init < 0
init = @length + init + 1
if init < 1 or init > @length
return nil
byte_start_pos, byte_end_pos = @text\find search, @byte_offset(init), true
if byte_start_pos
start_pos = @char_offset byte_start_pos
end_pos = @char_offset(byte_end_pos + 1) - 1
return start_pos, end_pos
nil
rfind: (search, init = @length) =>
if init < 0
init = @length + init + 1
if init < 1 or init > @length
return nil
-- use byte offset of last byte of char at init
byte_start_pos = @text\rfind search, @byte_offset(init + 1) - 1
if byte_start_pos
start_pos = @char_offset byte_start_pos
return start_pos, start_pos + search.ulen - 1
nil
reload: (force = false) =>
error "Cannot reload buffer '#{self}': no associated file", 2 unless @file
return false if @_modified and not force
@file = @file
signal.emit 'buffer-reloaded', buffer: self
true
lex: (end_pos = @size) =>
if @_mode.lexer
b_end_pos = @byte_offset end_pos
@_buffer\ensure_styled_to pos: b_end_pos
mode_at: (pos) =>
b_pos = @byte_offset pos
mode_name = @_buffer.styling\get_mode_name_at b_pos
-- Returns @mode if there's no marker or the requested mode doesn't exist.
mode_name and mode.by_name(mode_name) or @mode
config_at: (pos) =>
mode_at = @mode_at pos
return @config if mode_at == @mode
return config.proxy @_config_scope, mode_at.config_layer
resolve_span: (span, line_nr = nil) =>
{:start_pos, :end_pos} = span
local line, l_start_pos, l_b_start_offset
-- resolve start pos as needed
unless start_pos
if span.byte_start_pos
start_pos = @char_offset span.byte_start_pos
elseif line_nr or span.line_nr
line = @lines[line_nr or span.line_nr]
start_pos = line.start_pos
l_start_pos = line.start_pos
if span.start_column
start_pos = l_start_pos + span.start_column - 1
elseif span.byte_start_column
l_b_start_offset = line.byte_start_pos
start_pos = @char_offset l_b_start_offset + span.byte_start_column - 1
-- resolve end pos as needed
unless end_pos
if span.byte_end_pos
end_pos = @char_offset span.byte_end_pos
elseif span.count
end_pos = start_pos + span.count
elseif line_nr or span.line_nr
line or= @lines[line_nr or span.line_nr]
end_pos = line.end_pos
if span.end_column
l_start_pos or= line.start_pos
end_pos = l_start_pos + span.end_column - 1
elseif span.byte_end_column
l_b_start_offset or= line.byte_start_pos
end_pos = @char_offset l_b_start_offset + span.byte_end_column - 1
unless start_pos and end_pos
error "Invalid span: Failed to determine both start and end", 2
return start_pos, end_pos
add_view_ref: =>
@viewers += 1
remove_view_ref: (view) =>
@viewers -= 1
_associate_with_file: (file) =>
scope = @_config_scope
@_file = file
config.merge scope, @_config_scope
config.delete scope
@_set_config!
@title = file and file.basename or 'Untitled'
_set_config: =>
@config = config.proxy @_config_scope, 'default', @mode.config_layer
_on_text_inserted: (_, _, args) =>
@_on_buffer_modification 'text-inserted', args
_on_text_deleted: (_, _, args) =>
@_on_buffer_modification 'text-deleted', args
_on_text_changed: (_, _, args) =>
@_on_buffer_modification 'text-changed', args
_on_buffer_modification: (what, args) =>
@_modified = true
@last_changed = sys.time!
args = {
buffer: self,
at_pos: @char_offset(args.offset),
part_of_revision: args.part_of_revision,
text: args.text
prev_text: args.prev_text
}
signal.emit what, args
signal.emit 'buffer-modified', buffer: self
@meta {
__len: => @length
__tostring: => @title
}
-- Config variables
with config
.define
name: 'strip_trailing_whitespace'
description: 'Whether trailing whitespace will be removed upon save'
default: true
type_of: 'boolean'
.define
name: 'ensure_newline_at_eof'
description: 'Whether to ensure a trailing newline is present at eof upon save'
default: true
type_of: 'boolean'
.define
name: 'backup_files'
description: 'Whether or not to make temporary backups of files while saving'
default: false
type_of: 'boolean'
.define
name: 'backup_directory'
description: "The directory to backup files while saving"
type_of: 'string'
-- Signals
with signal
.register 'buffer-saved',
description: 'Signaled right after a buffer was saved',
parameters:
buffer: 'The buffer that was saved'
.register 'text-inserted',
description: [[
Signaled right after text has been inserted into a buffer. No additional
modifications may be done within the signal handler.
]]
parameters:
buffer: 'The buffer for which the text was inserted'
at_pos: 'The start position of the inserted text'
text: 'The text that was inserted'
part_of_revision: 'The text was inserted as part of an undo or redo operation'
.register 'text-deleted',
description: [[
Signaled right after text was deleted from a buffer. No additional
modifications may be done within the signal handler.
]]
parameters:
buffer: 'The buffer for which the text was deleted'
at_pos: 'The start position of the deleted text'
text: 'The text that was deleted'
part_of_revision: 'The text was deleted as part of an undo or redo operation'
.register 'text-changed',
description: [[
Signaled right after text was changed in a buffer. No additional
modifications may be done within the signal handler.
]]
parameters:
buffer: 'The buffer for which the text was deleted'
at_pos: 'The start position of the deleted text'
text: 'The new text that was inserted'
prev_text: 'The text that was removed'
part_of_revision: 'The text was changed as part of an undo or redo operation'
.register 'buffer-modified',
description: 'Signaled right after a buffer was modified',
parameters:
buffer: 'The buffer that was modified'
as_undo: 'The buffer was modified as the result of an undo operation'
as_redo: 'The buffer was modified as the result of a redo operation'
.register 'buffer-reloaded',
description: 'Signaled right after a buffer was reloaded',
parameters:
buffer: 'The buffer that was reloaded'
.register 'buffer-mode-set',
description: 'Signaled right after a buffer had its mode set',
parameters:
buffer: 'The target buffer'
mode: 'The new mode that was set'
old_mode: 'The old mode if any'
.register 'buffer-title-set',
description: 'Signaled right after a buffer had its title set',
parameters:
buffer: 'The buffer receiving the new title'
return Buffer
| 28.770245 | 104 | 0.648295 |
f98a8f9deb281694d3f615c0b62916b79f7b4ea8 | 1,067 | require 'luarocks.loader'
ffi = require 'ffi'
C = ffi.C
sdl = require 'sdl2'
socket = require 'socket'
import cdef_BF_FRAME from require 'bitflut_cdefs'
ffi.cdef cdef_BF_FRAME
server = assert socket.udp6!
assert server\setsockname '::', 54321
server\settimeout 1
sdl.init sdl.INIT_VIDEO
window = sdl.createWindow "BitFlut", sdl.WINDOWPOS_CENTERED, sdl.WINDOWPOS_CENTERED, 512, 512, sdl.WINDOW_SHOWN
renderer = sdl.createRenderer window, -1, sdl.RENDERER_ACCELERATED
sdl.setRenderDrawColor renderer, 0, 0, 0, 0
sdl.renderClear renderer
sdl.renderPresent renderer
fsize=ffi.sizeof 'struct BF_FRAME'
running = true
event = ffi.new('SDL_Event')
while running
frame=server\receive fsize
if frame
frame=ffi.cast 'struct BF_FRAME *', frame
if ffi.string(frame.magic,4)=='BFPX'
sdl.setRenderDrawColor renderer, frame.r, frame.g, frame.b, frame.a
sdl.renderDrawPoint renderer, frame.x, frame.y
while sdl.pollEvent(event) ~= 0
if event.type == sdl.QUIT
running = false
sdl.renderPresent renderer
sdl.destroyWindow window
sdl.quit!
| 26.02439 | 111 | 0.75164 |
49665e742f83cf8a724800dd9f9f935b4076b859 | 464 | lapis = require "lapis"
lfs = require "lfs"
-- Load all applications
root = "applications"
all_apps = {}
for entity in lfs.dir(root) do
if entity ~= "." and entity ~= ".." and string.sub(entity, -4) == ".lua" then
app = string.sub(entity, 0, -5)
all_apps[#all_apps + 1] = app
class extends lapis.Application
@enable "etlua"
for _, app in pairs all_apps
@include root .. "." ..app
[index: "/"]: =>
render: "home"
| 23.2 | 81 | 0.579741 |
25d484cabd8a03d3434aad1942c1d5fc60f70b19 | 7,990 | import Buffer from howl
import Editor, highlight from howl.ui
describe 'Searcher', ->
buffer = nil
editor = Editor Buffer {}
searcher = editor.searcher
cursor = editor.cursor
before_each ->
buffer = Buffer howl.mode.by_name 'default'
editor.buffer = buffer
after_each -> searcher\cancel!
describe 'forward_to(string)', ->
it 'moves the cursor to the next occurrence of <string>', ->
buffer.text = 'hellö\nworld!'
cursor.pos = 1
searcher\forward_to 'l'
assert.equal 3, cursor.pos
searcher\forward_to 'ld'
assert.equal 10, cursor.pos
it 'highlights the match with "search"', ->
buffer.text = 'hellö\nworld!'
cursor.pos = 1
searcher\forward_to 'lö'
assert.same { 'search' }, highlight.at_pos buffer, 4
assert.same { 'search' }, highlight.at_pos buffer, 5
assert.not_same { 'search' }, highlight.at_pos buffer, 6
it 'matches at the current position', ->
buffer.text = 'no means no'
cursor.pos = 1
searcher\forward_to 'no'
assert.equal 1, cursor.pos
it 'handles growing match from empty', ->
buffer.text = 'no means no'
cursor.pos = 1
searcher\forward_to ''
assert.equal 1, cursor.pos
searcher\forward_to 'n'
assert.equal 1, cursor.pos
searcher\forward_to 'no'
assert.equal 1, cursor.pos
it 'does not move the cursor when there is no match', ->
buffer.text = 'hello!'
cursor.pos = 1
searcher\forward_to 'foo'
assert.equal 1, cursor.pos
describe 'next()', ->
it 'moves to the next match', ->
buffer.text = 'aaaa'
cursor.pos = 1
searcher\forward_to 'a'
assert.equal 1, cursor.pos
searcher\next!
assert.equal 2, cursor.pos
searcher\next!
assert.equal 3, cursor.pos
describe 'previous()', ->
it 'moves to the previous match', ->
buffer.text = 'aaaa'
cursor.pos = 4
searcher\forward_to 'a'
assert.equal 4, cursor.pos
searcher\previous!
assert.equal 3, cursor.pos
searcher\previous!
assert.equal 2, cursor.pos
describe 'backward_to(string)', ->
it 'moves the cursor to the previous occurrence of <string>', ->
buffer.text = 'hellö\nworld!'
cursor.pos = 11
searcher\backward_to 'l'
assert.equal 10, cursor.pos
searcher\backward_to 'lö'
assert.equal 4, cursor.pos
it 'handles search term growing from empty', ->
buffer.text = 'aaaaaaaa'
cursor.pos = 5
searcher\backward_to ''
assert.equal 5, cursor.pos
searcher\backward_to 'a'
assert.equal 4, cursor.pos
searcher\backward_to 'aa'
assert.equal 4, cursor.pos
it 'skips any matches at the current position by default', ->
buffer.text = 'aaaaaaaa'
cursor.pos = 5
searcher\backward_to 'a'
assert.equal 4, cursor.pos
it 'finds matches that overlap with cursor', ->
buffer.text = 'ababababa'
cursor.pos = 4
searcher\backward_to 'baba'
assert.equal 2, cursor.pos
it 'does not skip any matches at the current position if the searcher is active', ->
buffer.text = 'abaaaaab'
cursor.pos = 8
searcher\backward_to 'a'
assert.equal 7, cursor.pos
searcher\backward_to 'ab'
assert.equal 7, cursor.pos
it 'does not move the cursor when there is no match', ->
buffer.text = 'hello!'
cursor.pos = 3
searcher\backward_to 'f'
assert.equal 3, cursor.pos
describe 'next()', ->
it 'moves to the next match', ->
buffer.text = 'aaaa'
cursor.pos = 4
searcher\backward_to 'a'
searcher\next!
assert.equal 4, cursor.pos
describe 'previous()', ->
it 'moves to the previous match', ->
buffer.text = 'aaaa'
cursor.pos = 3
searcher\backward_to 'a'
searcher\next!
searcher\previous!
assert.equal 2, cursor.pos
describe 'forward_to(string, "word")', ->
it 'moves the cursor to the start of the current word', ->
buffer.text = 'hello helloo hello'
cursor.pos = 2
searcher\forward_to 'hello', 'word'
assert.equal 1, cursor.pos
it 'highlights current word with "search" and other word matches with "search_secondary"', ->
buffer.text = 'hello hola hello hola hello'
cursor.pos = 13
searcher\forward_to 'hello', 'word'
assert.same { 'search' }, highlight.at_pos buffer, 12
assert.same { 'search' }, highlight.at_pos buffer, 16
assert.same { 'search_secondary' }, highlight.at_pos buffer, 1
assert.same { 'search_secondary' }, highlight.at_pos buffer, 23
it 'highlights overlapping matches correctly', ->
buffer.text = 'aaa'
cursor.pos = 2
searcher\forward_to 'aa'
assert.equal 2, cursor.pos
assert.same { 'search_secondary' }, highlight.at_pos buffer, 1
assert.same { 'search_secondary', 'search' }, highlight.at_pos buffer, 2
assert.same { 'search' }, highlight.at_pos buffer, 3
it 'does not move the cursor when there is no match', ->
buffer.text = 'hello!'
cursor.pos = 1
searcher\forward_to 'foo', 'word'
assert.equal 1, cursor.pos
describe 'next()', ->
it 'moves to the next word match', ->
buffer.text = 'hello helloo hello'
cursor.pos = 1
searcher\forward_to 'hello', 'word'
searcher\next!
assert.equal 14, cursor.pos
describe 'previous()', ->
it 'moves to the previous word match', ->
buffer.text = 'hello helloo hello'
cursor.pos = 1
searcher\forward_to 'hello', 'word'
searcher\next!
searcher\previous!
assert.equal 1, cursor.pos
describe 'backward_to(string, "word")', ->
it 'moves the cursor to the previous occurrence of word match <string>', ->
buffer.text = 'hello helloo hello'
cursor.pos = 14
searcher\backward_to 'hello', 'word'
assert.equal 1, cursor.pos
it 'skips match at the current position by default', ->
buffer.text = 'no means no'
cursor.pos = 9
searcher\backward_to 'no', 'word'
assert.equal 1, cursor.pos
it 'does not move the cursor when there is no match', ->
buffer.text = 'hello!'
cursor.pos = 2
searcher\backward_to 'foo', 'word'
assert.equal 2, cursor.pos
it 'handles substring match at start of file gracefully', ->
buffer.text = 'abcd abc'
cursor.pos = 6
searcher\backward_to 'abc', 'word'
assert.equal 7, cursor.pos
describe 'next()', ->
it 'moves to the next word match', ->
buffer.text = 'hello helloo hello'
cursor.pos = 14
searcher\backward_to 'hello', 'word'
searcher\next!
assert.equal 14, cursor.pos
describe 'previous()', ->
it 'moves to the previous word match', ->
buffer.text = 'hello helloo hello'
cursor.pos = 14
searcher\backward_to 'hello', 'word'
searcher\next!
searcher\previous!
assert.equal 1, cursor.pos
it 'cancel() moves the cursor back to the original position', ->
buffer.text = 'hello!'
cursor.pos = 1
searcher\forward_to 'll'
searcher\cancel!
assert.equal 1, cursor.pos
it 'repeat_last() repeats the last search in the last direction', ->
buffer.text = 'hellö wörld'
cursor.pos = 1
searcher\forward_to 'ö'
searcher\commit!
assert.equal 5, cursor.pos
searcher\repeat_last!
assert.equal 8, cursor.pos
cursor.pos = 11
searcher\backward_to 'ö'
searcher\commit!
assert.equal 8, cursor.pos
searcher\repeat_last!
assert.equal 5, cursor.pos
it '.active is true if the searcher is currently active', ->
assert.is_false searcher.active
searcher\forward_to 'o'
assert.is_true searcher.active
searcher\cancel!
assert.is_false searcher.active
| 30.849421 | 97 | 0.619274 |
a86e5d8544f3ed854f09cf646845ceac722e948d | 355 | class ElmMode
new: =>
@lexer = bundle_load 'elm_lexer'
@completers = {'elm_completer', 'in_buffer'}
comment_syntax: '--'
default_config:
complete: 'manual'
auto_pairs:
'(': ')'
'[': ']'
'{': '}'
'"': '"'
indentation: {
more_after: {
r'\\b(let|in|of|then|else)\\b\\s*(.*)$'
'=%s*(--.*)$'
}
}
| 15.434783 | 48 | 0.464789 |
e8b58c30d12e9e6dd05f4f957bef33228509fbd2 | 142 | describe 'package.path', ->
it 'should be set correctly', ->
path = './?.lua;./?/init.lua'
assert.equal path, package.path\sub(1, #path)
| 28.4 | 47 | 0.626761 |
3417301530f77ab971eb58616e3c4ed4224cd77e | 1,334 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import app, interact from howl
import Window from howl.ui
match = require 'luassert.match'
require 'howl.interactions.search'
require 'howl.interactions.select'
describe 'search', ->
local command_line, searcher
before_each ->
app.window = Window!
app.window\realize!
command_line = app.window.command_line
searcher = {}
app.editor = :searcher
it "registers interactions", ->
assert.not_nil interact.forward_search
assert.not_nil interact.backward_search
assert.not_nil interact.forward_search_word
assert.not_nil interact.backward_search_word
describe 'interact.forward_search', ->
it 'searches forward for typed text', ->
searcher.forward_to = spy.new -> true
within_activity interact.forward_search, ->
command_line\write 'tw'
assert.spy(searcher.forward_to).was_called_with match.is_ref(searcher), 'tw', 'plain'
describe 'interact.forward_search_word', ->
it 'searches forward for typed word', ->
searcher.forward_to = spy.new -> true
within_activity interact.forward_search_word, ->
command_line\write 'tw'
assert.spy(searcher.forward_to).was_called_with match.is_ref(searcher), 'tw', 'word'
| 32.536585 | 91 | 0.727136 |
a1c685a9aefaff3ff7a1e65e083dda0f526a411b | 175 | M = {}
T = (require "PackageToolkit").module
runmodule = (T.import ..., "_runmodule").runmodule
M.call = (modules, ...) ->
return runmodule modules, false, ...
return M
| 19.444444 | 50 | 0.628571 |
6dfd896acc4a8f73cf1cd123df131d9702e855d1 | 6,998 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import config from howl
import highlight from howl.ui
highlight.define_default 'search', {
style: highlight.ROUNDBOX,
color: '#ffffff'
outline_alpha: 100
}
highlight.define_default 'search_secondary', {
style: highlight.ROUNDBOX,
color: '#ffffff'
alpha: 0
outline_alpha: 150
}
with config
.define
name: 'search_wraps'
description: 'Whether searches wrap around to top or bottom when there are no more matches'
default: true
type_of: 'boolean'
class Searcher
lineStart: nil
lineEnd: nil
new: (editor) =>
@editor = editor
@last_search = nil
@last_direction = nil
@last_type = nil
forward_to: (search, type = 'plain', match_at_cursor = true, line_search = false) =>
@jump_to search, direction: 'forward', type: type, match_at_cursor: match_at_cursor, line_search: line_search
backward_to: (search, type = 'plain', match_at_cursor = @active, line_search = false) =>
@jump_to search, direction: 'backward', type: type, match_at_cursor: match_at_cursor, line_search: line_search
jump_to: (search, opts = {}) =>
@_clear_highlights!
return if search.is_empty
direction = opts.direction or 'forward'
ensure_word = opts.type == 'word'
match_at_cursor = opts.match_at_cursor or false
search_engine = @_find_match unless opts.line_search
search_engine = @_find_match_line if opts.line_search
unless @active
@_init!
if direction == 'forward' and ensure_word
-- back up to start of current word
@editor.cursor.pos = @editor.current_context.word.start_pos
init = @editor.cursor.pos
if direction == 'forward'
if not match_at_cursor
init += 1
else
init += search.ulen - 2
if match_at_cursor
init += 1
start_pos, end_pos = search_engine self, search, init, direction, ensure_word
if start_pos
@end_pos = end_pos+1
@editor.cursor.pos = start_pos
@_highlight_matches search, start_pos, ensure_word
else
if ensure_word
log.error "No word matches found for '#{search}'"
else
log.error "No matches found for '#{search}'"
@last_search = search
@last_direction = direction
@last_type = opts.type
repeat_last: =>
@_init!
if @last_direction == 'forward'
@next!
else
@previous!
@commit!
next: (line_search = false) =>
if @last_search
if @last_type == 'word'
log.info "Next match for word '#{@last_search}'"
else
log.info "Next match for'#{@last_search}'"
@forward_to @last_search, @last_type, false, line_search
previous: (line_search = false) =>
if @last_search
if @last_type == 'word'
log.info "Previous match for word '#{@last_search}'"
else
log.info "Previous match for '#{@last_search}'"
@backward_to @last_search, @last_type, false, line_search
commit: =>
@buffer = nil
@start_pos = nil
@active = false
@startPos = nil
@endPos = nil
if @end_pos
@editor.cursor.pos = @end_pos
cancel: =>
@startPos = nil
@endPos = nil
@_clear_highlights!
if @active
@editor.cursor.pos = @start_pos
@commit!
_find_match: (search, init, direction, ensure_word) =>
finder = nil
wrap_pos = nil
wrap_msg = ''
if direction == 'forward'
finder = @buffer.find
wrap_pos = 1
wrap_msg = 'Search hit BOTTOM, continuing at TOP'
else
finder = @buffer.rfind
wrap_pos = -1
wrap_msg = 'Search hit TOP, continuing at BOTTOM'
wrapped = false
while true
start_pos, end_pos = finder @buffer, search, init
if start_pos
if not ensure_word or @_is_word(start_pos, search)
return start_pos, end_pos
-- the match wasn't a word, continue searching
if direction == 'forward'
init = end_pos + 1
else
init = start_pos - 1
else
if wrapped or init == wrap_pos
-- already wrapped, or no need to wrap
return
else
init = wrap_pos
log.info wrap_msg
wrapped = true
_find_match_line: (search, init, direction, ensure_word) =>
if not @lineStart and not @lineEnd
@lineStart = @buffer\begin_line init
@lineEnd = @buffer\end_line init
finder = nil
wrap_pos = nil
wrap_msg = ''
if direction == 'forward'
finder = @buffer.find_line
wrap_pos = @lineStart
wrap_msg = 'Search hit BOTTOM, continuing at TOP'
else
finder = @buffer.rfind_line
wrap_pos = -1
wrap_msg = 'Search hit TOP, continuing at BOTTOM'
wrapped = false
while true
start_pos, end_pos = finder @buffer, search, init, @lineEnd, @lineStart
if start_pos
if not ensure_word or @_is_word(start_pos, search)
return start_pos, end_pos
-- the match wasn't a word, continue searching
if direction == 'forward'
init = end_pos + 1
else
init = start_pos - 1
else
if wrapped or init == wrap_pos
-- already wrapped, or no need to wrap
return
else
init = wrap_pos
log.info wrap_msg
wrapped = true
_is_word: (match_pos, word) =>
match_ctx = @editor.buffer\context_at match_pos
return match_ctx.word.text == word
_highlight_matches: (search, match_pos, ensure_word) =>
return unless search
buffer = @editor.buffer
-- scan the displayed lines and a few more for good measure
start_boundary = buffer.lines[math.max(1, @editor.line_at_top - 5)].start_pos
end_boundary = buffer.lines[math.min(#buffer.lines, @editor.line_at_bottom + 5)].end_pos
-- match at match_pos gets a different highlight than other matches
for start_pos, end_pos in @_find_matches search, start_boundary, end_boundary
if not ensure_word or @_is_word(start_pos, search)
if start_pos != match_pos
highlight.apply 'search_secondary', buffer, start_pos, end_pos - start_pos + 1
highlight.apply 'search', buffer, match_pos, search.ulen
_find_matches: (search, start_boundary, end_boundary) =>
match_start_pos = nil
match_end_pos = nil
text = @buffer\sub start_boundary, end_boundary
init = 1
return ->
while true
if init > #text
return
match_start_pos, match_end_pos = text\ufind search, init, true
return if not match_start_pos
init = match_end_pos + 1
return match_start_pos + start_boundary - 1, match_end_pos + start_boundary - 1
_clear_highlights: =>
@lineStart = nil
@lineEnd = nil
highlight.remove_all 'search', @editor.buffer
highlight.remove_all 'search_secondary', @editor.buffer
_init: =>
@start_pos = @editor.cursor.pos
@buffer = @editor.buffer
@active = true
| 27.880478 | 114 | 0.643184 |
88d03ce1782666ae97a21cee7c9364a6a012d29e | 205 | buildings = {}
buildings["Command Center"] = {
cost: {
'rubidium': 0
},
ent: "command_center"
}
buildings["Firegun factory"] = {
cost: {
'iron':100
},
ent: "firegun_factory"
}
{ :buildings } | 10.789474 | 32 | 0.595122 |
b0e5b12a2e1eb025c0abd24a18f2b67c162eb2b1 | 10,823 | mp = require "MessagePack"
C = require "const"
string = string
table = table
ngx = ngx
type = type
ipairs = ipairs
error = error
string = string
socket = nil
decode_base64 = nil
sha1_bin = nil
crypto = nil
-- Use non NGINX modules
-- requires: luasock (implicit), lua-resty-socket, sha1
openssl_sha1_hash = (msg) ->
crypto.digest('sha1', msg, true)
if not ngx then
socket = require("socket")
socket.unix = require("socket.unix")
mime = require("mime")
decode_base64 = mime.unb64
crypto = require("crypto")
if crypto.sha1
print "This version of SHA1 is text only and is not supported"
else
sha1_bin = openssl_sha1_hash
else
socket = ngx.socket
decode_base64 = ngx.decode_base64
sha1_bin = ngx.sha1_bin
mp.set_integer('unsigned')
_prepare_request = (h, b) ->
header = mp.pack(h)
body = mp.pack(b)
len = mp.pack(string.len(header) + string.len(body))
len .. header .. body
_xor = (str_a, str_b) ->
_bxor = (a, b) ->
r = 0
for i = 0, 31 do
x = a / 2 + b / 2
if x ~= math.floor(x)
r = r + 2^i
a = math.floor(a / 2)
b = math.floor(b / 2)
return r
result = ''
if string.len(str_a) != string.len(str_b) then
return
for i = 1, string.len(str_a) do
result = result .. string.char(_bxor(string.byte(str_a, i), string.byte(str_b, i)))
result
_prepare_key = (value) ->
if type(value) == 'table'
return value
elseif value == nil
return { }
else
return { value }
class Tarantool
new: (params) =>
@meta = {
host: C.HOST,
port: C.PORT,
user: C.USER,
password: C.PASSWORD,
socket_timeout: C.SOCKET_TIMEOUT,
connect_now: C.CONNECT_NOW
_lookup_spaces: true
_lookup_indexes: true
_spaces: {}
_indexes: {}
}
if params and type(params) == 'table'
for key, value in pairs(@meta) do
if params[key] != nil then
@meta[key] = params[key]
self[key] = @meta[key]
sock, err = socket.tcp()
if not sock
@err = err
return
if @socket_timeout
sock\settimeout(@socket_timeout)
@sock = sock
if not ngx
@unix = socket.unix()
if @connect_now
ok, err = @connect()
if not ok
print(err)
@err = err
enable_lookups: () =>
@_lookup_spaces = true
@_lookup_indexes = true
disable_lookups: () =>
@_lookup_spaces = false
@_lookup_indexes = false
@_spaces = {}
@_indexes = {}
_wraperr: (err) =>
if err then
err .. ', server: ' .. @host .. ':' .. @port
else
"Internal error"
connect: (host, port) =>
if not @sock
return nil, "No socket created"
@host = host or @host
@port = tonumber(port or @port)
ok = nil
err = nil
if string.find(@host, 'unix:/')
if ngx
ok, err = @sock\connect(@host)
else
ok, err = @unix\connect(string.match(@host, 'unix:(.+)'))
if ok
@sock = @unix
else
ok, err = @sock\connect(@host, @port)
if not ok then
return ok, @_wraperr(err)
return @_handshake()
disconnect: () =>
if not @sock
return nil, "no socket created"
return @sock\close()
set_keepalive: () =>
if not @sock
return nil, "no socket created"
ok, err = @sock\setkeepalive()
if not ok then
@disconnect()
return nil, err
return ok
select: (space, index, key, opts) =>
if opts == nil
opts = {}
spaceno, err = @_resolve_space(space)
if not spaceno
return nil, err
indexno, err = @_resolve_index(spaceno, index or "primary")
if not indexno
return nil, err
body = {
[C.SPACE_ID]: spaceno,
[C.INDEX_ID]: indexno,
[C.KEY]: _prepare_key(key)
}
if opts.limit != nil
body[C.LIMIT] = tonumber(opts.limit)
else
body[C.LIMIT] = C.MAX_LIMIT
if opts.offset != nil then
body[C.OFFSET] = tonumber(opts.offset)
else
body[C.OFFSET] = 0
if type(opts.iterator) == 'number' then
body[C.ITERATOR] = opts.iterator
response, err = @_request({ [ C.TYPE ]: C.SELECT }, body )
if err
return nil, err
elseif response and response.code != C.OK
return nil, @_wraperr(response.error)
else
return response.data
insert: (space, tuple) =>
spaceno, err = @_resolve_space(space)
if not spaceno
return nil, err
response, err = @_request({ [C.TYPE]: C.INSERT }, { [C.SPACE_ID]: spaceno, [C.TUPLE]: tuple })
if err
return nil, err
elseif response and response.code != C.OK
return nil, @_wraperr(response.error)
else
return response.data
replace: (space, tuple) =>
spaceno, err = @_resolve_space(space)
if not spaceno
return nil, err
response, err = @_request({ [C.TYPE]: C.REPLACE }, { [C.SPACE_ID]: spaceno, [C.TUPLE]: tuple })
if err
return nil, err
elseif response and response.code != C.OK then
return nil, @_wraperr(response.error)
else
return response.data
delete: (space, key) =>
spaceno, err = @_resolve_space(space)
if not spaceno
return nil, err
response, err = @_request({ [C.TYPE]: C.DELETE }, { [C.SPACE_ID]: spaceno, [C.KEY]: _prepare_key(key) })
if err
return nil, err
elseif response and response.code != C.OK
return nil, @_wraperr(response.error)
else
return response.data
update: (index, key, oplist) =>
spaceno, err = @_resolve_space(space)
if not spaceno
return nil, err
indexno, err = @_resolve_index(spaceno, index)
if not indexno
return nil, err
response, err = @_request({ [C.TYPE]: C.UPDATE }, {
[C.SPACE_ID]: spaceno,
[C.INDEX_ID]: indexno,
[C.KEY]: _prepare_key(key),
[C.TUPLE]: oplist,
})
if err
return nil, err
elseif response and response.code != C.OK
return nil, @_wraperr(response.error)
else
return response.data
upsert: (space, tuple, oplist) =>
spaceno, err = @_resolve_space(space)
if not spaceno
return nil, err
response, err = @_request({ [C.TYPE]: C.UPSERT }, {
[C.SPACE_ID]: spaceno,
[C.TUPLE]: tuple,
[C.OPS]: oplist,
})
if err
return nil, err
elseif response and response.code != C.OK
return nil, @_wraperr(response.error)
else
return response.data
ping: () =>
response, err = @_request({ [ C.TYPE ]: C.PING }, {} )
if err
return nil, err
elseif response and response.code != C.OK
return nil, @_wraperr(response.error)
else
return "PONG"
call: (proc, args) =>
response, err = @_request({ [ C.TYPE ]: C.CALL }, { [C.FUNCTION_NAME]: proc, [C.TUPLE]: args } )
if err
return nil, err
elseif response and response.code != C.OK
return nil, @_wraperr(response.error)
else
return unpack(response.data)
_resolve_space: (space) =>
if type(space) == 'number' then
return space
elseif type(space) == 'string' then
if @_lookup_spaces and @_spaces[space] then
return @_spaces[space]
else
return nil, 'Invalid space identificator: ' .. space
data, err = @select(C.VIEW_SPACE, C.INDEX_SPACE_NAME, space)
if not data or not data[1] or not data[1][1] or err then
return nil, (err or 'Can\'t find space with identifier: ' .. space)
newspace = data[1][1]
if @_lookup_spaces
@_spaces[space] = newspace
return newspace
_resolve_index: (space, index) =>
if type(index) == 'number' then
return index
elseif type(index) == 'string'
if @lookup_indexes and @_indexes[index]
return @_indexes[index]
else
return nil, 'Invalid index identifier: ' .. index
spaceno, err = @_resolve_space(space)
if not spaceno
return nil, err
data, err = @select(C.VIEW_INDEX, C.INDEX_INDEX_NAME, { spaceno, index })
if not data or not data[1] or not data[1][2] or err
return nil, (err or 'Can\'t find index with identifier: ' .. index)
newindex = data[1][2]
if @_lookup_indexes
@_indexes[index] = newindex
return newindex
_handshake: () =>
greeting = nil
greeting_err = nil
if not @_salt
greeting, greeting_err = @sock\receive(C.GREETING_SIZE)
if not greeting or greeting_err
@sock\close()
return nil, @_wraperr(greeting_err)
@_salt = string.sub(greeting, C.GREETING_SALT_OFFSET + 1)
@_salt = string.sub(decode_base64(@_salt), 1, 20)
@authenticated, err = @_authenticate()
return @authenticated, err
return true
_authenticate: () =>
if not @user then
return true
rbody = { [C.USER_NAME]: @user, [C.TUPLE]: { } }
password = @password or ''
if password != ''
step_1 = sha1_bin(@password)
step_2 = sha1_bin(step_1)
step_3 = sha1_bin(@_salt .. step_2)
scramble = _xor(step_1, step_3)
rbody[C.TUPLE] = { "chap-sha1", scramble }
response, err = @_request({ [C.TYPE]: C.AUTH }, rbody)
if err
return nil, err
elseif response and response.code != C.OK
return nil, @_wraperr(response.error)
else
return true
_request: (header, body) =>
sock = @sock
if type(header) != 'table'
return nil, 'invlid request header'
@sync_num = ((@sync_num or 0) + 1) % C.REQUEST_PER_CONNECTION
if not header[C.SYNC]
header[C.SYNC] = @sync_num
else
@sync_num = header[C.SYNC]
request = _prepare_request(header, body)
bytes, err = sock\send(request)
if bytes == nil then
sock\close()
return nil, @_wraperr("Failed to send request: " .. err)
size, err = sock\receive(C.HEAD_BODY_LEN_SIZE)
if not size
sock\close()
return nil, @_wraperr("Failed to get response size: " .. err)
size = mp.unpack(size)
if not size
sock\close()
return nil, @_wraperr("Client get response invalid size")
header_and_body, err = sock\receive(size)
if not header_and_body
sock\close()
return nil, @_wraperr("Failed to get response header and body: " .. err)
iterator = mp.unpacker(header_and_body)
value, res_header = iterator()
if type(res_header) != 'table' then
return nil, @_wraperr("Invalid header: " .. type(res_header) .. " (table expected)")
if res_header[C.SYNC] != @sync_num then
return nil, @_wraperr("Invalid header SYNC: request: " .. @sync_num .. " response: " .. res_header[C.SYNC])
value, res_body = iterator()
if type(res_body) != 'table'
res_body = {}
return { code: res_header[C.TYPE], data: res_body[C.DATA], error: res_body[C.ERROR] }
| 25.707838 | 113 | 0.592534 |
7c51a82409ac075fed658ed9fbf3de76aaeb3c8b | 197 | {
graphics: lg,
keyboard: lk,
mouse: lm,
audio: la,
event: le
} = love
love.load = () ->
require("src.demo")
t = DemoClass()
print(t.val)
love.update = (dt) ->
| 10.944444 | 23 | 0.497462 |
4206b62bb13678e5b5bd3b8f05c1524d9eb493b7 | 553 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
ffi = require 'ffi'
jit = require 'jit'
require 'ljglibs.cdefs.gtk'
core = require 'ljglibs.core'
gobject = require 'ljglibs.gobject'
require 'ljglibs.gtk.widget'
gc_ptr = gobject.gc_ptr
C = ffi.C
jit.off true, true
core.define 'GtkSpinner < GtkWidget', {
properties: {
active: 'gboolean'
}
new: -> gc_ptr C.gtk_spinner_new!
start: => C.gtk_spinner_start @
stop: => C.gtk_spinner_stop @
}, (spec) -> spec.new!
| 21.269231 | 79 | 0.699819 |
f422063c1b15e9c8e8cda2a96cc6b85517fa8433 | 3,057 | export class SeedBullet extends Enemy
new: =>
super(9999)
@canTakeDamage = false
with @graphic = ImageSet("#{Settings.folders.graphics}/bulletseed.png", 8, 5)
.origin.x = 4
.origin.y = 3
.frameDuration = .130
\play!
@attackRange = {}
with @movement = @addComponent(Movement(800, 800, 1500, 1500))
.callbacks.onEndMove = ->
print "end move"
@finishTurn!
-- attack
@damage = 1
@attacked = nil
@attackDirection = x: 0, y: 0
-- attack tween
@attackTween = nil
@playingAttackTween = false
@attackMoveDistance = 14
sceneAdded: (scene) =>
super(scene)
Lume.push(@attackRange, { @attackDirection.x, @attackDirection.y })
if (@attackDirection.x > 0)
@turnTo("right")
elseif (@attackDirection.x < 0)
@turnTo("left")
elseif (@attackDirection.y > 0)
@turnTo("down")
@graphic.orientation = math.rad(90)
elseif (@attackDirection.y < 0)
@turnTo("up")
@graphic.orientation = math.rad(-90)
update: (dt) =>
super(dt)
if (not @isAlive)
return
if (@playingAttackTween)
if (@attackTween\update(dt))
@playingAttackTween = false
if (@attacked != nil)
switch (@attacked.__class.__name)
when "Player"
@attacked\takeDamage(@damage)
when "SeedBullet"
@attacked\die!
@die!
@finishTurn!
-- health
onDeath: =>
super!
@removeSelf!
startTurn: (turn) =>
super(turn)
-- planning
plan: (time) =>
super(time)
@hasFinishedPlanning = true
onThink: (dt) =>
super(dt)
executePlan: =>
super!
if (not @attack!)
@move(@attackDirection.x, @attackDirection.y)
-- attack
attack: =>
attackedCell = @neighborCell(@attackDirection.x, @attackDirection.y)
if (attackedCell == nil)
return false
if (attackedCell.thing != nil or not attackedCell.walkable)
@attacked = attackedCell.thing
@currentCell!.thing = nil
attackX = @x + @attackDirection.x * @attackMoveDistance
attackY = @y + @attackDirection.y * @attackMoveDistance
@attackTween = Tween.new(.1, @, { x: attackX, y: attackY }, "inCubic")
@playingAttackTween = true
return true
return false
-- collision
onCollideThing: (thing) =>
switch (thing.__class.__parent.__name)
when "Player"
-- attack
@attack!
return true
return true
| 26.815789 | 86 | 0.479555 |
5a4e50a5d868c5023e7d01262fca3bf64a0df81f | 399 | {
order: 'acfv',
kinds: {
v: { group: 'neotags_VariableTag' },
a: { group: 'neotags_PreProcTag' },
c: {
group: 'neotags_PreProcTag',
prefix: [[\(\(^\|\s\):\?\)\@<=]],
suffix: [[\(!\?\(\s\|$\)\)\@=]],
},
f: {
group: 'neotags_FunctionTag',
prefix: [[\%(\%(g\|s\|l\):\)\=]],
},
}
}
| 23.470588 | 45 | 0.338346 |
1fcaec12ce5598785ca03e21b23cb46aa4930f01 | 5,593 | AddCSLuaFile!
Moonpanel.Canvas.Sockets = {}
class Moonpanel.Canvas.Sockets.BaseSocket
new: (@__canvas, @__id) =>
__setCoordinates: (width) =>
data = @__canvas\GetData!
@__x = ((@__id - 1) % width) + 1
@__y = math.floor((@__id - 1) / width) + 1
SetEntity: (entity, postPopulate = true) =>
pathNodes = @__canvas\GetPathNodes!
if @__entity
dirty = true
@__entity\CleanUpPathNodes pathNodes
if CLIENT and @__entity.Render
@__canvas\RemoveRenderable @__entity
with @__entity = entity or @__class.BaseEntity
\SetSocket @
\PopulatePathNodes pathNodes
\PostPopulatePathNodes pathNodes if postPopulate
if CLIENT and .Render
@__canvas\AddRenderable @__entity
@__canvas\RebuildPathFinderCache!
GetEntity: => @__entity
GetCanvas: => @__canvas
SetY: (@__y) =>
GetY: => @__y
SetX: (@__x) =>
GetX: => @__x
GetSocketType: => @__class.SocketType
IsTraced: => @__canvas\IsTraced @
class Moonpanel.Canvas.Sockets.IntersectionSocket extends Moonpanel.Canvas.Sockets.BaseSocket
@SocketType = Moonpanel.Canvas.SocketType.Intersection
@BaseEntity = Moonpanel.Canvas.Entities.BaseIntersection
new: (canvas, id) =>
super canvas, id
data = canvas\GetData!
@__setCoordinates data.Meta.Width + 1
SetPathNode: (@__pathNode) =>
GetPathNode: => @__pathNode
ExportData: =>
className = @__class.__name
if className ~= "BaseIntersection"
{ Type: className }
GetRenderOrigin: =>
return @__cachedRenderOrigin if @__cachedRenderOrigin
node = @GetPathNode!
@__cachedRenderOrigin = Vector node.screenX, node.screenY
@__cachedRenderOrigin
GetAbove: => @__canvas\GetVPathSocketAt @__x , @__y - 1
GetBelow: => @__canvas\GetVPathSocketAt @__x , @__y
GetLeft: => @__canvas\GetHPathSocketAt @__x - 1 , @__y
GetRight: => @__canvas\GetHPathSocketAt @__x , @__y
GetRadius: =>
data = @__canvas\GetData!
return 0.5 * 1.5 * Moonpanel.Canvas.Resolution * (data.Dim.BarWidth / 100)
CanClick: (x, y) =>
ro = @GetRenderOrigin!
distSqr = (x - ro.x)^2 + (y - ro.y)^2
radius = @GetRadius!
return radius * radius > distSqr
class Moonpanel.Canvas.Sockets.CellSocket extends Moonpanel.Canvas.Sockets.BaseSocket
@SocketType = Moonpanel.Canvas.SocketType.Cell
@BaseEntity = Moonpanel.Canvas.Entities.BaseCell
new: (canvas, id) =>
super canvas, id
data = canvas\GetData!
@__setCoordinates data.Meta.Width
GetRenderOrigin: =>
return @__cachedRenderOrigin if @__cachedRenderOrigin
left = @GetLeft!\GetRenderOrigin!
right = @GetRight!\GetRenderOrigin!
@__cachedRenderOrigin = (left + right) / 2
@__cachedRenderOrigin
GetAbove: => @__canvas\GetHPathSocketAt @__x , @__y
GetBelow: => @__canvas\GetHPathSocketAt @__x , @__y + 1
GetLeft: => @__canvas\GetVPathSocketAt @__x , @__y
GetRight: => @__canvas\GetVPathSocketAt @__x + 1 , @__y
GetHitBox: =>
return @__cachedHitBox if @__cachedHitBox
ro = @GetRenderOrigin!
data = @__canvas\GetData!
barLength = @GetCanvas!\GetBarLength!
barWidth = @GetCanvas!\GetBarWidth!
size = barLength - barWidth
@__cachedHitBox = Moonpanel.Rect ro.x - size/2, ro.y - size/2,
size, size
@__cachedHitBox
CanClick: (x, y) =>
return @GetHitBox!\Contains x, y
class Moonpanel.Canvas.Sockets.PathSocket extends Moonpanel.Canvas.Sockets.BaseSocket
@SocketType = Moonpanel.Canvas.SocketType.Path
@BaseEntity = Moonpanel.Canvas.Entities.BasePath
SetHorizontal: (@__horizontal) =>
data = @__canvas\GetData!
@__setCoordinates data.Meta.Width + (@__horizontal and 0 or 1)
IsHorizontal: => @__horizontal
IsVertical: => not @__horizontal
GetRenderOrigin: =>
return @__cachedRenderOrigin if @__cachedRenderOrigin
nodeA, nodeB = if @__horizontal
@GetLeft!, @GetRight!
else
@GetAbove!, @GetBelow!
@__cachedRenderOrigin = (nodeA\GetRenderOrigin! + nodeB\GetRenderOrigin!) / 2
@__cachedRenderOrigin
GetAbove: =>
if @__horizontal
@__canvas\GetCellSocketAt @__x, @__y - 1
else
@__canvas\GetIntersectionSocketAt @__x, @__y
GetBelow: =>
if @__horizontal
@__canvas\GetCellSocketAt @__x, @__y
else
@__canvas\GetIntersectionSocketAt @__x, @__y + 1
GetLeft: =>
if @__horizontal
@__canvas\GetIntersectionSocketAt @__x, @__y
else
@__canvas\GetCellSocketAt @__x - 1, @__y
GetRight: =>
if @__horizontal
@__canvas\GetIntersectionSocketAt @__x + 1, @__y
else
@__canvas\GetCellSocketAt @__x, @__y
GetHitBox: =>
return @__cachedHitBox if @__cachedHitBox
ro = @GetRenderOrigin!
data = @__canvas\GetData!
barLength = @GetCanvas!\GetBarLength!
barWidth = @GetCanvas!\GetBarWidth!
@__cachedHitBox = Moonpanel.Rect if @__horizontal
ro.x - barLength/2, ro.y - barWidth/2, barLength, barWidth
else
ro.x - barWidth/2, ro.y - barLength/2, barWidth, barLength
@__cachedHitBox
CanClick: (x, y) =>
return @GetHitBox!\Contains x, y
| 28.535714 | 93 | 0.619167 |
f0275634828dc8fb75568dad935f6b195a761001 | 2,565 | export RUN_TESTS = false
if RUN_TESTS
print('Running tests')
utility = nil
export LOCALIZATION = nil
STATE = {
PATHS: {
RESOURCES: nil
}
STACK: false
}
COMPONENTS = {
STATUS: nil
}
export HideStatus = () -> COMPONENTS.STATUS\hide()
-- TODO: Have a look at the possibility of being able to use Lua patterns (square brackets seem to cause issues, but dot works just fine)
export Initialize = () ->
SKIN\Bang('[!Hide]')
STATE.PATHS.RESOURCES = SKIN\GetVariable('@')
dofile(('%s%s')\format(STATE.PATHS.RESOURCES, 'lib\\rainmeter_helpers.lua'))
COMPONENTS.STATUS = require('shared.status')()
success, err = pcall(
() ->
require('shared.enums')
utility = require('shared.utility')
utility.createJSONHelpers()
COMPONENTS.SETTINGS = require('shared.settings')()
export log = if COMPONENTS.SETTINGS\getLogging() == true then (...) -> print(...) else () -> return
log('Initializing Search config')
export LOCALIZATION = require('shared.localization')(COMPONENTS.SETTINGS)
SKIN\Bang(('[!SetOption "WindowTitle" "Text" "%s"]')\format(LOCALIZATION\get('search_window_all_title', 'Search')))
COMPONENTS.STATUS\hide()
SKIN\Bang('[!CommandMeasure "Script" "HandshakeSearch()" "#ROOTCONFIG#"]')
)
return COMPONENTS.STATUS\show(err, true) unless success
export Update = () ->
return
export Handshake = (stack) ->
success, err = pcall(
() ->
if stack
SKIN\Bang(('[!SetOption "WindowTitle" "Text" "%s"]')\format(LOCALIZATION\get('search_window_current_title', 'Search (current games)')))
STATE.STACK = stack
meter = SKIN\GetMeter('WindowShadow')
skinWidth = meter\GetW()
skinHeight = meter\GetH()
mainConfig = utility.getConfig(SKIN\GetVariable('ROOTCONFIG'))
monitorIndex = nil
if mainConfig ~= nil
monitorIndex = utility.getConfigMonitor(mainConfig) or 1
else
monitorIndex = 1
x, y = utility.centerOnMonitor(skinWidth, skinHeight, monitorIndex)
SKIN\Bang(('[!Move "%d" "%d"]')\format(x, y))
SKIN\Bang('[!ZPos 1][!Show]')
SKIN\Bang('[!CommandMeasure "Input" "ExecuteBatch 1"]')
)
return COMPONENTS.STATUS\show(err, true) unless success
export SetInput = (str) ->
success, err = pcall(
() ->
SKIN\Bang(('[!CommandMeasure "Script" "Search(\'%s\', %s)" "#ROOTCONFIG#"]')\format(str\sub(1, -2), tostring(STATE.STACK)))
SKIN\Bang('[!DeactivateConfig]')
)
return COMPONENTS.STATUS\show(err, true) unless success
export CancelInput = () ->
success, err = pcall(
() ->
SKIN\Bang('[!DeactivateConfig]')
)
return COMPONENTS.STATUS\show(err, true) unless success
| 31.280488 | 139 | 0.681481 |
f41bfb99538d184d72675c2fc4483f18534cb03a | 1,004 | require "axel.util.enums"
require "axel.util.axel_utils"
require "axel.util.directional_set"
require "axel.util.timer"
require "axel.util.timer_set"
require "axel.base.point"
require "axel.base.rectangle"
require "axel.base.vector"
require "axel.base.entity"
require "axel.base.group"
require "axel.state.state"
require "axel.state.state_stack"
require "axel.camera.camera"
require "axel.camera.camera_effect"
require "axel.camera.fade_camera_effect"
require "axel.render.color"
require "axel.sprite.quad_set"
require "axel.sprite.animation"
require "axel.sprite.animation_set"
require "axel.sprite.sprite"
require "axel.input.input"
require "axel.input.keyboard"
require "axel.input.mouse"
require "axel.tilemap.tile"
require "axel.tilemap.tilemap"
require "axel.collision.collider"
require "axel.collision.group_collider"
require "axel.collision.grid_collider"
require "axel.text.text"
require "axel.util.debugger"
require "axel.render.particle_system"
require "axel.render.emitter"
require "axel.axel" | 30.424242 | 40 | 0.804781 |
80a078dadc103d74bb5c0096501f203dfe6491f3 | 359 | require('src/debug')
hug = require('vendor/hug')
export _ = hug._
export math = hug.math
scenes = require('vendor/hump/gamestate')
TitleScene = require('lib/scenes/title')
love.load = () ->
love.graphics.setNewFont(12)
love.graphics.setBackgroundColor(0 ,0, 0)
love.graphics.setColor(255, 255, 255)
scenes.registerEvents()
scenes.switch(TitleScene())
| 22.4375 | 42 | 0.727019 |
4ed4d0f35119c98a66cf42d85630d6e3f0a649db | 566 | System = require "lib.concord.system"
Position = require "src.components.Position"
Rectangle = require "src.components.Rectangle"
filter = {
Position,
Rectangle
}
RectangleRenderer = System filter
RectangleRenderer.draw = () =>
for _, entity in ipairs self.pool.objects
position = entity\get Position
rectangle = entity\get Rectangle
-- Draw a rectangle at the center of the position
love.graphics.rectangle "fill",
position.x - (rectangle.width / 2),
position.y - (rectangle.height / 2),
rectangle.width,
rectangle.height
RectangleRenderer | 25.727273 | 51 | 0.740283 |
797365b5fdfdca073ac06888b4ffc4da9fdd69d4 | 453 | M = {}
name1 = "strings"
name2 = "batch_format"
TK = require("PackageToolkit")
FX = require("FunctionalX")
M.case = (input1, input2, solution, msg="") ->
print TK.ui.dashed_line 80, '-'
print string.format "test %s.%s()", name1, name2
print msg
result = FX[name1][name2] input1, input2
print "Result: ", unpack result
assert TK.test.equal_lists result, solution
print "VERIFIED!"
print TK.ui.dashed_line 80, '-'
return M | 30.2 | 52 | 0.653422 |
4acfad969b59c6642a0d47f8b16e84ff3cf80a37 | 929 | path = (...)\gsub("[^%.]*$", "")
M = require(path .. 'master')
local Vec2
Vec2 = M.class {
__init: (x=0, y=0) => self.x, self.y = x, y
__add: (u, v) ->
Vec2(u.x + v.x, u.y + v.y)
__sub: (u, v) ->
Vec2(u.x - v.x, u.y - v.y)
__unm: => Vec2(-self.x, -self.y)
__mul: (a, b) ->
if type(a) == "number"
Vec2(a*b.x, a*b.y)
elseif type(b) == "number"
Vec2(b*a.x, b*a.y)
else error("attempt to multiply a vector with a non-scalar value", 2)
__div: (a) => @@(self.x/a, self.y/a)
__eq: (u, v) -> u.x == v.x and u.y == v.y
__tostring: (v) -> "(#{v.x}, #{v.y})"
__index: (key) =>
key == 1 and @x or key == 2 and @y or nil
dot: (u, v) -> u.x*v.x + u.y*v.y
wedge: (u, v) -> u.x*v.y - u.y*v.x
lenS: (v) ->
Vec2.dot(v, v)
len: => math.sqrt(self\lenS())
unpack: => self.x, self.y
}
M.Vec2 = Vec2 | 21.604651 | 77 | 0.4338 |
97699a3dbbba0eeee9c82e9f57ffb4c8264c60c3 | 18,413 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import Window, Editor, theme from howl.ui
import Buffer, Settings, mode, breadcrumbs, bundle, bindings, keymap, signal, interact, timer, clipboard, config from howl
import File, Process from howl.io
import PropertyObject from howl.util.moon
Gtk = require 'ljglibs.gtk'
callbacks = require 'ljglibs.callbacks'
{:get_monotonic_time} = require 'ljglibs.glib'
{:C} = require('ffi')
bit = require 'bit'
append = table.insert
coro_create, coro_status = coroutine.create, coroutine.status
non_idle_dispatches = {
'^signal motion%-',
'^signal key%-press%-event',
'^signal button%-',
}
is_idle_dispatch = (desc) ->
for p in *non_idle_dispatches
return false if desc\find(p) != nil
true
last_activity = get_monotonic_time!
dispatcher = (f, description, ...) ->
unless is_idle_dispatch(description)
last_activity = get_monotonic_time!
co = coro_create (...) -> f ...
status, ret = coroutine.resume co, ...
if status
if coro_status(co) == 'dead'
return ret
else
error ret
false
sort_buffers = (buffers, current_buffer=nil) ->
table.sort buffers, (a, b) ->
if current_buffer == a return true
if current_buffer == b return false
return true if a.showing and not b.showing
return false if b.showing and not a.showing
-- if none of the buffers are showing, we compare the last shown time
unless a.showing
ls_a = a.last_shown or 0
ls_b = b.last_shown or 0
return ls_a > ls_b if ls_a != ls_b
a.title < b.title
parse_path_args = (paths, cwd=nil) ->
files = {}
hints = {}
for path in *paths
local file
line, col = 1, 1
e_path, s_line, s_col = path\match '^(.+):(%d+):(%d+)$'
if e_path
file = e_path
line = tonumber s_line
col = s_col
else
e_path, s_line = path\match '^(.+):(%d+)$'
if e_path
file = e_path
line = tonumber s_line
else
file = path
files[#files + 1] = File(file, cwd).gfile
hints[#hints + 1] = "#{line}:#{col}"
files, hints
class Application extends PropertyObject
title: 'Howl'
new: (@root_dir, @args) =>
@windows = {}
@_editors = {}
@_buffers = {}
@_recently_closed = {}
bundle.dirs = { @root_dir / 'bundles' }
@_load_base!
bindings.push keymap
@window = nil
@editor = nil
callbacks.configure {
:dispatcher,
on_error: _G.log.error
}
signal.connect 'log-entry-appended', (entry) ->
level = entry.level
message = entry.message
return if level == 'traceback'
if @window and @window.visible
essentials = entry.essentials
status = @window.status
command_line = @window.command_line
status[level] status, essentials
command_line\notify essentials, level if command_line.showing
elseif not @args.spec
print message
super!
@property idle: get: =>
tonumber(get_monotonic_time! - last_activity) / 1000 / 1000
@property buffers: get: =>
buffers = { table.unpack @_buffers }
sort_buffers buffers, (@editor and @editor.buffer)
buffers
@property recently_closed: get: => moon.copy @_recently_closed
@property editors: get: => @_editors
@property next_buffer: get: =>
return @new_buffer! if #@_buffers == 0
sort_buffers @_buffers
hidden_buffers = [b for b in *@_buffers when not b.showing]
return #hidden_buffers > 0 and hidden_buffers[1] or @_buffers[1]
new_window: (properties = {}) =>
props = title: @title
props[k] = v for k, v in pairs(properties)
window = Window props
window\set_default_size 800, 640
window\on_delete_event ->
if #@windows == 1
modified = [b for b in *@_buffers when b.modified]
if #modified > 0
-- postpone the quit check, since we really need to prevent
-- the close right away by returning true
timer.asap -> @quit!
else
@quit!
true
window\on_destroy (destroy_window) ->
@windows = [w for w in *@windows when w\to_gobject! != destroy_window]
@g_app\add_window window\to_gobject!
append @windows, window
@window = window if #@windows == 1
window
new_editor: (opts = {}) =>
editor = Editor opts.buffer or @next_buffer
(opts.window or @window)\add_view editor, opts.placement or 'right_of'
append @_editors, editor
editor\grab_focus!
editor
editor_for_buffer: (buffer) =>
for visible_editor in *@_editors
if visible_editor.buffer == buffer
return visible_editor
nil
new_buffer: (buffer_mode) =>
buffer_mode or= mode.by_name 'default'
buffer = Buffer buffer_mode
@_append_buffer buffer
buffer
add_buffer: (buffer, show = true) =>
for b in *@buffers
return if b == buffer
@_append_buffer buffer
if show and @editor
breadcrumbs.drop!
@editor.buffer = buffer
@editor
close_buffer: (buffer, force = false) =>
unless force
local prompt
if buffer.modified
prompt = "Buffer is modified, close anyway? "
elseif buffer.activity and buffer.activity\is_running!
prompt = "Buffer has a running activity (#{buffer.activity.name}), close anyway? "
if prompt
return unless interact.yes_or_no :prompt
@_buffers = [b for b in *@_buffers when b != buffer]
if buffer.file
@_add_recently_closed buffer
if buffer.showing
for editor in *@editors
if editor.buffer == buffer
if editor == @editor -- if showing in the current editor
breadcrumbs.drop! -- we drop a crumb here
editor.buffer = @next_buffer
signal.emit 'buffer-closed', :buffer
open_file: (file, editor = @editor) =>
@open :file, editor
open: (loc, editor) =>
return unless loc
unless loc.buffer or loc.file
error "Malformed loc: either .buffer or .file must be set", 2
file = loc.file
buffer = loc.buffer or @_buffer_for_file(file)
if buffer
@add_buffer buffer
else
-- open the file specified
buffer = @new_buffer mode.for_file file
status, err = pcall -> buffer.file = file
if not status
@close_buffer buffer
error "Failed to open #{file}: #{err}"
@_recently_closed = [file_info for file_info in *@_recently_closed when file_info.file != buffer.file]
signal.emit 'file-opened', :file, :buffer
-- all right, now we got a buffer, let's get an editor if needed
unless editor
editor = @editor_for_buffer(loc.buffer) or @editor
editor or= @new_editor buffer
-- buffer and editor in place, drop a crumb and show the location
breadcrumbs.drop {
buffer: editor.buffer,
pos: editor.cursor.pos,
line_at_top: editor.line_at_top
}
editor.buffer = buffer
if loc.line_nr
editor.line_at_center = loc.line_nr
opts = line: loc.line_nr
if loc.column
opts.column = loc.column
elseif loc.column_index
opts.column_index = loc.column_index
editor.cursor\move_to opts
if loc.highlights
for hl in *loc.highlights
editor\highlight hl, loc.line_nr
-- drop another breadcrumb at the new location
breadcrumbs.drop!
buffer, editor
save_all: =>
for b in *@buffers
if b.modified
unless b.file
log.error "No file associated with modified buffer '#{b}'"
return false
b\save!
true
synchronize: =>
clipboard.synchronize!
reload_count = 0
changed_count = 0
for b in *@_buffers
if b.modified_on_disk
changed_count += 1
unless b.modified
b\reload!
reload_count += 1
if changed_count > 0
msg = "Files modified on disk: #{reload_count} buffer(s) reloaded"
stale_count = changed_count - reload_count
if stale_count > 0
log.warn "#{msg}, #{stale_count} modified buffer(s) left"
else
log.info msg
run: =>
jit.off true, true
args = @args
app_base = 'io.howl.Editor'
flags = bit.bor(
Gtk.Application.HANDLES_OPEN,
Gtk.Application.HANDLES_COMMAND_LINE
)
@g_app = Gtk.Application app_base, flags
@g_app\register!
-- by default we'll not open files in the same instance,
-- but this can be toggled via the --reuse command line parameter
if @g_app.is_remote and not @args.reuse
@g_app = Gtk.Application "#{app_base}-#{os.time!}", bit.bor(
flags,
Gtk.Application.NON_UNIQUE
)
@g_app\register!
@g_app\on_activate ->
@_load!
@g_app\on_open (_, files, hint) ->
hints = [h for h in hint\gmatch '[^,]+']
@_load files, hints
@g_app\on_command_line (app, command_line) ->
paths = [v for v in *command_line.arguments[2, ] when not v\match('^-')]
files, hints = parse_path_args paths, command_line.cwd
if #files > 0
app\open files, table.concat(hints, ',')
else
app\activate!
signal.connect 'window-focused', self\synchronize
signal.connect 'editor-destroyed', (s_args) ->
@_editors = [e for e in *@_editors when e != s_args.editor]
breadcrumbs.init!
@g_app\run args
quit: (force = false) =>
if force or not @_should_abort_quit!
unless #@args > 1
@save_session!
if config.save_config_on_exit
unless pcall config.save_config
print 'Error saving config'
for _, process in pairs Process.running
process\send_signal 'KILL'
for win in * moon.copy @windows
win.command_line\abort_all!
win\destroy!
howl.clipboard.store!
save_session: =>
return if @args.no_profile or #@args > 1
session = {
version: 1
buffers: {}
recently_closed: {}
window: {
maximized: @window.maximized
fullscreen: @window.fullscreen
}
}
for b in *@buffers
continue unless b.file
append session.buffers, {
file: b.file.path
last_shown: b.last_shown
properties: b.properties
}
for f in *@_recently_closed
append session.recently_closed, {
file: f.file.path
last_shown: f.last_shown
}
@settings\save_system 'session', session
pump_mainloop: (max_count = 100) =>
jit.off true, true
count = 0
ctx = C.g_main_context_default!
while count < max_count and C.g_main_context_iteration(ctx, false) != 0
count += 1
_append_buffer: (buffer) =>
if config.autoclose_single_buffer and #@_buffers == 1
present = @_buffers[1]
if not present.file and not present.modified and present.length == 0
@_buffers[1] = buffer
return
append @_buffers, buffer
_buffer_for_file: (file) =>
for b in *@buffers
return b if b.file == file
nil
_load: (files = {}, hints = {}) =>
local window
-- bootstrap if we're booting up
unless @_loaded
@settings = Settings!
@_load_core!
if @settings.dir and not @args.no_profile
append bundle.dirs, @settings.dir\join 'bundles'
fonts_dir = @settings.dir\join('fonts')
if fonts_dir.exists
C.FcConfigAppFontAddDir(nil, fonts_dir.path)
if howl.sys.info.is_flatpak
append bundle.dirs, File '/app/bundles'
bundle.load_all!
unless @args.no_profile
status, ret = pcall @settings.load_user, @settings
unless status
log.error "Failed to load user settings: #{ret}"
theme.apply!
@_load_application_icon!
signal.connect 'mode-registered', self\_on_mode_registered
signal.connect 'mode-unregistered', self\_on_mode_unregistered
window = @new_window!
howl.janitor.start!
-- load files from command line
loaded_buffers = {}
for i = 1, #files
file = File files[i]
buffer = @_buffer_for_file file
unless buffer
buffer = @new_buffer mode.for_file file
status, ret = pcall -> buffer.file = file
if not status
@close_buffer buffer
buffer = nil
log.error "Failed to open file '#{file}': #{ret}"
if buffer
hint = hints[i]
if hint
nums = [tonumber(v) for v in hint\gmatch('%d+')]
{line, column} = nums
buffer.properties.position = :line, :column
append loaded_buffers, buffer
-- files we've loaded via a --reuse invocation should be shown
if #loaded_buffers > 0 and @_loaded
for i = 1, math.min(#@editors, #loaded_buffers)
@editors[i].buffer = loaded_buffers[i]
-- all loaded files should be considered as having been viewed just now
now = howl.sys.time!
for b in *loaded_buffers
b.last_shown = now
-- restore session properties
unless @_loaded
unless @args.no_profile
@_restore_session window, #files == 0
if #@editors == 0
@editor = @new_editor @_buffers[1] or @new_buffer!
for b in *loaded_buffers
signal.emit 'file-opened', file: b.file, buffer: b
unless @_loaded
window\show_all! if window
@_loaded = true
howl.io.File.async = true
signal.emit 'app-ready'
@_set_initial_status window
_should_abort_quit: =>
modified = [b for b in *@_buffers when b.modified]
if #modified > 0
if not interact.yes_or_no prompt: "Modified buffers exist, close anyway? "
return true
false
_on_mode_registered: (args) =>
-- check if any buffers with default_mode could use this new mode
default_mode = mode.by_name 'default'
for buffer in *@_buffers
if buffer.file and buffer.mode == default_mode
buffer_mode = mode.for_file buffer.file
if mode != default_mode
buffer.mode = buffer_mode
_on_mode_unregistered: (args) =>
-- remove the mode from any buffers that are previously using it
mode_name = args.name
default_mode = mode.by_name 'default'
for buffer in *@_buffers
if buffer.mode.name == mode_name
if buffer.file
buffer.mode = mode.for_file buffer.file
else
buffer.mode = default_mode
_restore_session: (window, restore_buffers) =>
session = @settings\load_system 'session'
if session and session.version == 1
if restore_buffers
for entry in *session.buffers
file = File(entry.file)
continue unless file.exists
status, err = pcall ->
buffer = @new_buffer mode.for_file file
buffer.file = file
buffer.last_shown = entry.last_shown
buffer.properties = entry.properties
signal.emit 'file-opened', :file, :buffer
log.error "Failed to load #{file}: #{err}" unless status
if session.recently_closed
@_recently_closed = [{file: File(file_info.file), last_shown: file_info.last_shown} for file_info in *session.recently_closed]
if session.window
with session.window
window.maximized = .maximized
window.fullscreen = .fullscreen
_set_initial_status: (window) =>
if log.last_error
startup_errors = [e for e in *log.entries when e.level == 'error']
window.status\error "#{log.last_error.message} (#{#startup_errors} startup errors in total)"
else
window.status\info 'Howl ready.'
_load_base: =>
require 'howl.variables.core_variables'
require 'howl.modes'
_load_core: =>
require 'howl.completion.in_buffer_completer'
require 'howl.completion.api_completer'
require 'howl.interactions.basic'
require 'howl.interactions.buffer_selection'
require 'howl.interactions.bundle_selection'
require 'howl.interactions.clipboard'
require 'howl.interactions.external_command'
require 'howl.interactions.file_selection'
require 'howl.interactions.line_selection'
require 'howl.interactions.location_selection'
require 'howl.interactions.mode_selection'
require 'howl.interactions.replacement'
require 'howl.interactions.search'
require 'howl.interactions.select'
require 'howl.interactions.signal_selection'
require 'howl.interactions.text_entry'
require 'howl.interactions.variable_assignment'
require 'howl.commands.file_commands'
require 'howl.commands.app_commands'
require 'howl.commands.ui_commands'
require 'howl.commands.edit_commands'
require 'howl.editing'
require 'howl.ui.icons.font_awesome'
require 'howl.janitor'
require 'howl.inspect'
require 'howl.file_search'
_load_application_icon: =>
dir = @root_dir
while dir
icon = dir\join('share/icons/hicolor/scalable/apps/howl.svg')
if icon.exists
status, err = pcall Gtk.Window.set_default_icon_from_file, icon.path
log.error "Failed to load application icon: #{err}" unless status
return
dir = dir.parent
log.warn "Failed to find application icon"
_add_recently_closed: (buffer) =>
@_recently_closed = [file_info for file_info in *@_recently_closed when file_info.file != buffer.file]
append @_recently_closed, {
file: buffer.file
last_shown: buffer.last_shown
}
count = #@_recently_closed
limit = config.recently_closed_limit
if count > limit
overage = count - limit
@_recently_closed = [@_recently_closed[idx] for idx = 1 + overage, limit + overage]
config.define
name: 'recently_closed_limit'
description: 'The number of files to remember in the recently closed list'
default: 1000
type_of: 'number'
scope: 'global'
config.define
name: 'autoclose_single_buffer'
description: 'When only one, empty buffer is open, automatically close it when another is created'
default: true
type_of: 'boolean'
scope: 'global'
signal.register 'file-opened',
description: 'Signaled right after a file was opened in a buffer',
parameters:
buffer: 'The buffer that the file was opened into'
file: 'The file that was opened'
signal.register 'buffer-closed',
description: 'Signaled right after a buffer was closed',
parameters:
buffer: 'The buffer that was closed'
signal.register 'app-ready',
description: 'Signaled right after the application has completed initialization'
return Application
| 28.19755 | 136 | 0.646608 |
1061f1ae614c6cd0707b118c409f6f09a44a6f10 | 917 | -- x, y, scale x, scale y, rotation: returns camera
make = (x, y, sx, sy, r) ->
cam = {
:x, :y
:sx, :sy
:r
}
cam.move = (dx, dy) =>
@x += dx
@y += dy
cam
cam.set = =>
with love.graphics
.push!
.translate .getWidth! / 2 - @x, .getHeight! / 2 - @y
.scale @sx, @sy
.rotate @r
cam
cam.unset = =>
love.graphics.pop!
cam
--The width of the camera in in-game distance
cam.width = =>
love.graphics.getWidth! / @sx
--The height of the camera in in-game distance
cam.height = =>
love.graphics.getHeight! / @sy
--Position of the left border of the camera in the gameworld
cam.left = =>
@x / @sx - @width!/2
--Position of the right border of the camera in the gameworld
cam.right = =>
@x / @sx + @width!/2
cam.top = =>
@y / @sy - @height!/2
cam.bot = =>
@y / @sy + @height!/2
cam
{
:make
}
| 15.810345 | 63 | 0.522356 |
e4b9a502d6fefe7b9b46500c799bdfe985c92d95 | 12,366 | LOADED_KEY = setmetatable {}, __tostring: => "::loaded_relations::"
assert_model = (primary_model, model_name) ->
with m = primary_model\get_relation_model model_name
error "failed to find model `#{model_name}` for relation" unless m
find_relation = (model, name) ->
return unless model
if rs = model.relations
for relation in *rs
if relation[1] == name
return relation
if p = model.__parent
find_relation p, name
preload_relation = (objects, name, ...) =>
preloader = @relation_preloaders and @relation_preloaders[name]
unless preloader
error "Model #{@__name} doesn't have preloader for #{name}"
preloader @, objects, ...
true
preload_relations = (objects, name, ...) =>
preloader = @relation_preloaders and @relation_preloaders[name]
unless preloader
error "Model #{@__name} doesn't have preloader for #{name}"
preloader @, objects
if ...
@preload_relations objects, ...
else
true
preload_homogeneous = (sub_relations, model, objects, front, ...) ->
import to_json from require "lapis.util"
return unless front
if type(front) == "table"
for key,val in pairs front
relation = type(key) == "string" and key or val
preload_relation model, objects, relation
if type(key) == "string"
r = find_relation model, key
unless r
error "missing relation: #{key}"
sub_relations or= {}
sub_relations[val] or= {}
loaded_objects = sub_relations[val]
if r.has_many or r.fetch and r.many
for obj in *objects
for fetched in *obj[key]
table.insert loaded_objects, fetched
else
for obj in *objects
table.insert loaded_objects, obj[key]
else
preload_relation model, objects, front
if ...
preload_homogeneous sub_relations, model, objects, ...
else
sub_relations
preload = (objects, ...) ->
-- group by type
by_type = {}
for object in *objects
cls = object.__class
unless cls
error "attempting to preload an object that doesn't have a class, are you sure it's a model?"
by_type[cls] or= {}
table.insert by_type[object.__class], object
local sub_relations
for model, model_objects in pairs by_type
sub_relations = preload_homogeneous sub_relations, model, model_objects, ...
if sub_relations
for sub_load, sub_objects in pairs sub_relations
preload sub_objects, sub_load
true
mark_loaded_relations = (items, name) ->
for item in *items
if loaded = item[LOADED_KEY]
loaded[name] = true
else
item[LOADED_KEY] = { [name]: true }
clear_loaded_relation = (item, name) ->
item[name] = nil
if loaded = item[LOADED_KEY]
loaded[name] = nil
true
relation_is_loaded = (item, name) ->
item[name] or item[LOADED_KEY] and item[LOADED_KEY][name]
get_relations_class = (model) ->
parent = model.__parent
unless parent
error "model does not have parent class"
if rawget parent, "_relations_class"
return parent
preloaders = {}
if inherited = parent.relation_preloaders
setmetatable preloaders, __index: inherited
relations_class = class extends model.__parent
@__name: "#{model.__name}Relations"
@_relations_class: true
@relation_preloaders: preloaders
@preload_relations: preload_relations
@preload_relation: preload_relation
clear_loaded_relation: clear_loaded_relation
model.__parent = relations_class
setmetatable model.__base, relations_class.__base
relations_class
fetch = (name, opts) =>
source = opts.fetch
assert type(source) == "function", "Expecting function for `fetch` relation"
get_method = opts.as or "get_#{name}"
@__base[get_method] = =>
existing = @[name]
loaded = @[LOADED_KEY]
return existing if existing != nil or loaded and loaded[name]
if loaded
loaded[name] = true
else
@[LOADED_KEY] = { [name]: true }
with obj = source @
@[name] = obj
if opts.preload
@relation_preloaders[name] = (objects, preload_opts) =>
mark_loaded_relations objects, name
opts.preload objects, preload_opts, @, name
belongs_to = (name, opts) =>
source = opts.belongs_to
assert type(source) == "string", "Expecting model name for `belongs_to` relation"
get_method = opts.as or "get_#{name}"
column_name = opts.key or "#{name}_id"
assert type(column_name) == "string",
"`belongs_to` relation doesn't support composite key, use `has_one` instead"
@__base[get_method] = =>
return nil unless @[column_name]
existing = @[name]
loaded = @[LOADED_KEY]
return existing if existing != nil or loaded and loaded[name]
if loaded
loaded[name] = true
else
@[LOADED_KEY] = { [name]: true }
model = assert_model @@, source
with obj = model\find @[column_name]
@[name] = obj
@relation_preloaders[name] = (objects, preload_opts) =>
model = assert_model @@, source
preload_opts or= {}
preload_opts.as = name
preload_opts.for_relation = name
model\include_in objects, column_name, preload_opts
has_one = (name, opts) =>
source = opts.has_one
model_name = @__name
assert type(source) == "string", "Expecting model name for `has_one` relation"
get_method = opts.as or "get_#{name}"
-- assert opts.local_key, "`has_one` relation `local_key` option deprecated for composite `key`"
@__base[get_method] = =>
existing = @[name]
loaded = @[LOADED_KEY]
return existing if existing != nil or loaded and loaded[name]
if loaded
loaded[name] = true
else
@[LOADED_KEY] = { [name]: true }
model = assert_model @@, source
clause = if type(opts.key) == "table"
out = {}
for k,v in pairs opts.key
key, local_key = if type(k) == "number"
v, v
else
k,v
out[key] = @[local_key] or @@db.NULL
out
else
local_key = opts.local_key
unless local_key
local_key, extra_key = @@primary_keys!
assert extra_key == nil, "Model #{model_name} has composite primary keys, you must specify column mapping directly with `key`"
{
[opts.key or "#{@@singular_name!}_id"]: @[local_key]
}
if where = opts.where
for k,v in pairs where
clause[k] = v
with obj = model\find clause
@[name] = obj
@relation_preloaders[name] = (objects, preload_opts) =>
model = assert_model @@, source
key = if type(opts.key) == "table"
opts.key
else
local_key = opts.local_key
unless local_key
local_key, extra_key = @@primary_keys!
assert extra_key == nil, "Model #{model_name} has composite primary keys, you must specify column mapping directly with `key`"
{
[opts.key or "#{@@singular_name!}_id"]: local_key
}
preload_opts or= {}
preload_opts.for_relation = name
preload_opts.as = name
preload_opts.where or= opts.where
model\include_in objects, key, preload_opts
has_many = (name, opts) =>
source = opts.has_many
assert type(source) == "string", "Expecting model name for `has_many` relation"
get_method = opts.as or "get_#{name}"
get_paginated_method = "#{get_method}_paginated"
build_query = (additional_opts) =>
foreign_key = opts.key or "#{@@singular_name!}_id"
clause = if type(foreign_key) == "table"
out = {}
for k,v in pairs foreign_key
key, local_key = if type(k) == "number"
v, v
else
k,v
out[key] = @[local_key] or @@db.NULL
out
else
{
[foreign_key]: @[opts.local_key or @@primary_keys!]
}
if where = opts.where
for k,v in pairs where
clause[k] = v
if additional_opts and additional_opts.where
for k,v in pairs additional_opts.where
clause[k] = v
clause = "where #{@@db.encode_clause clause}"
if order = additional_opts and additional_opts.order or opts.order
clause ..= " order by #{order}"
clause
@__base[get_method] = =>
existing = @[name]
loaded = @[LOADED_KEY]
return existing if existing != nil or loaded and loaded[name]
if loaded
loaded[name] = true
else
@[LOADED_KEY] = { [name]: true }
model = assert_model @@, source
with res = model\select build_query(@)
@[name] = res
unless opts.pager == false
@__base[get_paginated_method] = (fetch_opts) =>
model = assert_model @@, source
query_opts = if fetch_opts and (fetch_opts.where or fetch_opts.order)
-- ordered paginator can take order
order = unless fetch_opts.ordered
fetch_opts.order
{
where: fetch_opts.where
:order
}
model\paginated build_query(@, query_opts), fetch_opts
@relation_preloaders[name] = (objects, preload_opts) =>
model = assert_model @@, source
foreign_key = opts.key or "#{@@singular_name!}_id"
composite_key = type(foreign_key) == "table"
local_key = unless composite_key
opts.local_key or @@primary_keys!
preload_opts or= {}
unless composite_key
preload_opts.flip = true
preload_opts.many = true
preload_opts.for_relation = name
preload_opts.as = name
preload_opts.local_key = local_key
preload_opts.order or= opts.order
preload_opts.where or= opts.where
model\include_in objects, foreign_key, preload_opts
polymorphic_belongs_to = (name, opts) =>
import enum from require "lapis.db.model"
types = opts.polymorphic_belongs_to
assert type(types) == "table", "missing types"
type_col = "#{name}_type"
id_col = "#{name}_id"
enum_name = "#{name}_types"
model_for_type_method = "model_for_#{name}_type"
type_for_object_method = "#{name}_type_for_object"
type_for_model_method = "#{name}_type_for_model"
get_method = "get_#{name}"
@[enum_name] = enum { assert(v[1], "missing type name"), k for k,v in pairs types}
@relation_preloaders[name] = (objs, preload_opts) =>
fields = preload_opts and preload_opts.fields
for {type_name, model_name} in *types
model = assert_model @@, model_name
filtered = [o for o in *objs when o[type_col] == @@[enum_name][type_name]]
model\include_in filtered, id_col, {
for_relation: name
as: name
fields: fields and fields[type_name]
}
objs
-- TODO: deprecate this for the new `preload_relations` method
@["preload_#{name}s"] = @relation_preloaders[name]
@[model_for_type_method] = (t) =>
type_name = @[enum_name]\to_name t
for {t_name, t_model_name} in *types
if t_name == type_name
return assert_model @@, t_model_name
error "failed to model for type: #{type_name}"
@[type_for_object_method] = (o) =>
@[type_for_model_method] @, assert o.__class, "invalid object, missing class"
@[type_for_model_method] = (m) =>
assert m.__name, "missing class name for model"
model_name = m.__name
for i, {_, t_model_name} in ipairs types
if model_name == t_model_name
return i
error "failed to find type for model: #{model_name}"
@__base[get_method] = =>
existing = @[name]
loaded = @[LOADED_KEY]
return existing if existing != nil or loaded and loaded[name]
if loaded
loaded[name] = true
else
@[LOADED_KEY] = { [name]: true }
if t = @[type_col]
model = @@[model_for_type_method] @@, t
with obj = model\find @[id_col]
@[name] = obj
relation_builders = {
:fetch, :belongs_to, :has_one, :has_many, :polymorphic_belongs_to,
}
-- add_relations, Things, {
-- {"user", has_one: "Users"}
-- {"posts", has_many: "Posts", pager: true, order: "id ASC"}
-- }
add_relations = (relations) =>
cls = get_relations_class @
for relation in *relations
name = assert relation[1], "missing relation name"
built = false
for k in pairs relation
if builder = relation_builders[k]
builder cls, name, relation
built = true
break
continue if built
import flatten_params from require "lapis.logging"
error "don't know how to create relation `#{flatten_params relation}`"
{
:relation_builders, :find_relation, :clear_loaded_relation, :LOADED_KEY
:add_relations, :get_relations_class, :mark_loaded_relations, :relation_is_loaded
:preload
}
| 26.536481 | 134 | 0.650493 |
913168025defbf63a070af7e7add65b8689df480 | 25,580 |
-- Copyright (C) 2017-2020 DBotThePony
-- 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.
-- editor stuffs
gui.ppm2.dxlevel.not_supported = 'Dein DirectX™ Level ist zu niedrig. Mindestens ist 9.0 erforderlich. Wenn Du 8.1 für die Bildrate verwendest,\nDann hast Du entweder eine alte Grafikkarte oder schlechte Treiber.\nDenn die Bildrate in gmod kann nur niedrig sein, weil andere Addons nutzlos hohe CPU-Last erzeugen.\nJa! Diese Meldung wird mehrmals erscheinen, um Dich zu ärgern. Denn, WARUM HAST DU DICH DAN ÜBER FEHLENDE TEXTUREN GEMELDET????'
gui.ppm2.dxlevel.toolow = 'DirectX™ level ist zu niedrig für PPM/2'
gui.ppm2.editor.eyes.separate = 'Getrennte Einstellungen für Augen verwenden'
gui.ppm2.editor.eyes.url = 'Augen URL Textur'
gui.ppm2.editor.eyes.url_desc = 'Bei Verwendung der Augen URL Textur; Die folgenden Optionen haben keine Auswirkung'
gui.ppm2.editor.eyes.lightwarp_desc = 'Lightwarp wirkt nur auf EyeRefract Augen'
gui.ppm2.editor.eyes.lightwarp = "Lightwarp"
gui.ppm2.editor.eyes.desc1 = "Lightwarp textur URL eingabe\nEs muss 256x16 sein!"
gui.ppm2.editor.eyes.desc2 = "Glanzstärke\nDieser Parameter erhöht die Stärke der Echtzeitreflexionen auf das Auge\nUm Änderungen zu sehen, setze ppm2_cl_reflections convar auf 1\nAndere Spieler würden Reflexionen nur sehen, wenn ppm2_cl_reflections auf 1 gesetzt ist\n0 - ist matt; 1 - ist spiegelnd"
for _, {tprefix, prefix} in ipairs {{'def', ''}, {'left', 'Links '}, {'right', 'Rechts '}}
gui.ppm2.editor.eyes[tprefix].lightwarp.shader = "#{prefix}EyeRefract Shader verwenden"
gui.ppm2.editor.eyes[tprefix].lightwarp.cornera = "#{prefix}Eye Cornea diffus verwenden"
gui.ppm2.editor.eyes[tprefix].lightwarp.glossiness = "#{prefix}Glanz"
gui.ppm2.editor.eyes[tprefix].type = "#{prefix}Augentyp"
gui.ppm2.editor.eyes[tprefix].reflection_type = "#{prefix}Augenreflexion typ"
gui.ppm2.editor.eyes[tprefix].lines = "#{prefix}Augenlinien"
gui.ppm2.editor.eyes[tprefix].derp = "#{prefix}Derp Augen"
gui.ppm2.editor.eyes[tprefix].derp_strength = "#{prefix}Derp Augen Stärke"
gui.ppm2.editor.eyes[tprefix].iris_size = "#{prefix}Augengröße"
gui.ppm2.editor.eyes[tprefix].points_inside = "#{prefix}Augenlinien innen"
gui.ppm2.editor.eyes[tprefix].width = "#{prefix}Augenbreite"
gui.ppm2.editor.eyes[tprefix].height = "#{prefix}Augenhöhe"
gui.ppm2.editor.eyes[tprefix].pupil.width = "#{prefix}Pupillenbreite"
gui.ppm2.editor.eyes[tprefix].pupil.height = "#{prefix}Pupillenhöhe"
gui.ppm2.editor.eyes[tprefix].pupil.size = "#{prefix}Pupillengröße"
gui.ppm2.editor.eyes[tprefix].pupil.shift_x = "#{prefix}Pupillen Verschiebung X"
gui.ppm2.editor.eyes[tprefix].pupil.shift_y = "#{prefix}Pupillen Verschiebung Y"
gui.ppm2.editor.eyes[tprefix].pupil.rotation = "#{prefix}Augenrotation"
gui.ppm2.editor.eyes[tprefix].background = "#{prefix}Augenhintergrund"
gui.ppm2.editor.eyes[tprefix].pupil_size = "#{prefix}Pupille"
gui.ppm2.editor.eyes[tprefix].top_iris = "#{prefix}Obere Augeniris"
gui.ppm2.editor.eyes[tprefix].bottom_iris = "#{prefix}Untere Augeniris"
gui.ppm2.editor.eyes[tprefix].line1 = "#{prefix}Augenlinie 1"
gui.ppm2.editor.eyes[tprefix].line2 = "#{prefix}Augenlinie 2"
gui.ppm2.editor.eyes[tprefix].reflection = "#{prefix}Augenreflexionseffekt"
gui.ppm2.editor.eyes[tprefix].effect = "#{prefix}Augeneffekt"
gui.ppm2.editor.generic.title = 'PPM/2 Pony Editor'
gui.ppm2.editor.generic.title_file = '%q - PPM/2 Pony Editor'
gui.ppm2.editor.generic.title_file_unsaved = '%q* - PPM/2 Pony Editor (ungespeicherte Änderungen!)'
gui.ppm2.editor.generic.yes = 'Yas!'
gui.ppm2.editor.generic.no = 'Noh!'
gui.ppm2.editor.generic.ohno = 'Onoh!'
gui.ppm2.editor.generic.okay = 'Okai ;w;'
gui.ppm2.editor.generic.datavalue = '%s\nDatenwert: %q'
gui.ppm2.editor.generic.url = '%s\n\nLink geht zu: %s'
gui.ppm2.editor.generic.url_field = 'URL Feld'
gui.ppm2.editor.generic.spoiler = 'Geheimnisvoller Spoiler'
gui.ppm2.editor.generic.restart.needed = 'Neustart des Editors erforderlich'
gui.ppm2.editor.generic.restart.text = 'Du solltest den Editor neu starten, um die Änderung zu übernehmen.\nJetzt neu starten?\nNicht gespeicherte Daten gehen verloren!'
gui.ppm2.editor.generic.fullbright = 'Volle Helligkeit'
gui.ppm2.editor.generic.wtf = 'Aus irgendeinem Grund hat Dein Player kein NetworkedPonyData. - Nichts zu bearbeiten!\nVersuche ppm2_reload in Deine Konsole einzugeben und versuche es erneut, den Editor zu öffnen.'
gui.ppm2.editor.io.random = 'Randomisieren!'
gui.ppm2.editor.io.newfile.title = 'Neue Datei'
gui.ppm2.editor.io.newfile.confirm = 'Willst Du wirklich eine neue Datei erstellen?'
gui.ppm2.editor.io.newfile.toptext = 'Zurücksetzen'
gui.ppm2.editor.io.delete.confirm = 'Willst Du diese Datei wirklich löschen?\nEs wird für immer weg sein!\n(eine lange Zeit!)'
gui.ppm2.editor.io.delete.title = 'Wirklich löschen?'
gui.ppm2.editor.io.filename = 'Dateiname'
gui.ppm2.editor.io.hint = 'Datei per Doppelklick öffnen'
gui.ppm2.editor.io.reload = 'Dateiliste neu laden'
gui.ppm2.editor.io.failed = 'Import fehlgeschlagen.'
gui.ppm2.editor.io.warn.oldfile = '!!! Es kann funktionieren oder auch nicht. Du wirst zerquetscht werden.'
gui.ppm2.editor.io.warn.text = "Derzeit hast du deine Änderungen nicht angegeben.\nWillst Du wirklich eine andere Datei öffnen?"
gui.ppm2.editor.io.warn.header = 'Nicht gespeicherte Änderungen!'
gui.ppm2.editor.io.save.button = 'Speichern'
gui.ppm2.editor.io.save.text = 'Dateiname ohne ppm2/ und .dat eingeben\nTipp: Um als Autoload zu speichern, schreibe "_current" (ohne ") ein.'
gui.ppm2.editor.io.wear = 'übernehmen (Anziehen)'
gui.ppm2.editor.seq.standing = 'Stehen'
gui.ppm2.editor.seq.move = 'Bewegen'
gui.ppm2.editor.seq.walk = 'Gehen'
gui.ppm2.editor.seq.sit = 'Sitzen'
gui.ppm2.editor.seq.swim = 'Schwimmen'
gui.ppm2.editor.seq.run = 'Laufen'
gui.ppm2.editor.seq.duckwalk = 'Ducken gehen'
gui.ppm2.editor.seq.duck = 'Ducken'
gui.ppm2.editor.seq.jump = 'Springen'
gui.ppm2.editor.misc.race = 'Rasse'
gui.ppm2.editor.misc.weight = 'Gewicht'
gui.ppm2.editor.misc.size = 'Pony Größe'
gui.ppm2.editor.misc.hide_weapons = 'Waffen verstecken'
gui.ppm2.editor.misc.chest = 'Männliche Brust'
gui.ppm2.editor.misc.gender = 'Geschlecht'
gui.ppm2.editor.misc.wings = 'Flügel Typ'
gui.ppm2.editor.misc.flexes = 'Flex steuerung'
gui.ppm2.editor.misc.no_flexes2 = 'Kein Flex beim neuen Modell'
gui.ppm2.editor.misc.no_flexes_desc = 'Du kannst jeden Flex Zustandsregler separat deaktivieren.\nSo können diese Flexe mit Addons von Drittanbietern (wie PAC3) modifiziert werden.'
gui.ppm2.editor.misc.hide_pac3 = 'Entitys ausblenden wenn PAC3 Entity verwendet wird'
gui.ppm2.editor.misc.hide_mane = 'Mähne ausblenden wenn PAC3 Entity verwendet wird'
gui.ppm2.editor.misc.hide_tail = 'Schweif ausblenden wenn PAC3 Entity verwendet wird'
gui.ppm2.editor.misc.hide_socks = 'Socken ausblenden wenn PAC3 Entity verwendet wird'
gui.ppm2.editor.tabs.main = 'Allgemeines'
gui.ppm2.editor.tabs.files = 'Dateien'
gui.ppm2.editor.tabs.old_files = 'Alte Dateien'
gui.ppm2.editor.tabs.cutiemark = 'Schönheitsfleck'
gui.ppm2.editor.tabs.head = 'Kopfanatomie'
gui.ppm2.editor.tabs.eyes = 'Augen'
gui.ppm2.editor.tabs.face = 'Gesicht'
gui.ppm2.editor.tabs.mouth = 'Mund'
gui.ppm2.editor.tabs.left_eye = 'Linkes Auge'
gui.ppm2.editor.tabs.right_eye = 'Rechtes Auge'
gui.ppm2.editor.tabs.mane_horn = 'Mähne und Horn'
gui.ppm2.editor.tabs.mane = 'Mähne'
gui.ppm2.editor.tabs.details = 'Details'
gui.ppm2.editor.tabs.url_details = 'URL Details'
gui.ppm2.editor.tabs.url_separated_details = 'URL Getrennte Details'
gui.ppm2.editor.tabs.ears = 'Ohren'
gui.ppm2.editor.tabs.horn = 'Horn'
gui.ppm2.editor.tabs.back = 'Rücken'
gui.ppm2.editor.tabs.wings = 'Flügel'
gui.ppm2.editor.tabs.left = 'Links'
gui.ppm2.editor.tabs.right = 'Rechts'
gui.ppm2.editor.tabs.neck = 'Hals'
gui.ppm2.editor.tabs.body = 'Pony Körper'
gui.ppm2.editor.tabs.tattoos = 'Tätowierungen'
gui.ppm2.editor.tabs.tail = 'Schweif'
gui.ppm2.editor.tabs.hooves = 'Huf Anatomie'
gui.ppm2.editor.tabs.bottom_hoof = 'Huf unten'
gui.ppm2.editor.tabs.legs = 'Beine'
gui.ppm2.editor.tabs.socks = 'Socken'
gui.ppm2.editor.tabs.newsocks = 'Neue Socken'
gui.ppm2.editor.tabs.about = 'Über'
gui.ppm2.editor.old_tabs.mane_tail = 'Mähne und Schweif'
gui.ppm2.editor.old_tabs.wings_and_horn_details = 'Flügel und Horn Details'
gui.ppm2.editor.old_tabs.wings_and_horn = 'Flügel und Horn'
gui.ppm2.editor.old_tabs.body_details = 'Körper Details'
gui.ppm2.editor.old_tabs.mane_tail_detals = 'Mähne und Schweif URL Details'
gui.ppm2.editor.cutiemark.display = 'Schönheitsfleck anzeigen'
gui.ppm2.editor.cutiemark.type = 'Schönheitsfleck typ'
gui.ppm2.editor.cutiemark.size = 'Schönheitsfleck größe'
gui.ppm2.editor.cutiemark.color = 'Schönheitsfleck Farbe'
gui.ppm2.editor.cutiemark.input = 'Schönheitsfleck URL bild Eingabefeld\nSollte PNG oder JPEG sein (funktioniert wie bei\nPAC3 URL texture)'
gui.ppm2.editor.face.eyelashes = 'Wimpern'
gui.ppm2.editor.face.eyelashes_color = 'Wimpern Farbe'
gui.ppm2.editor.face.eyelashes_phong = 'Wimpern Phong Parameter'
gui.ppm2.editor.face.eyebrows_color = 'Augenbrauen Farbe'
gui.ppm2.editor.face.new_muzzle = 'Neue Schnauze für das männliche Modell nutzen'
gui.ppm2.editor.face.nose = 'Nasenfarbe'
gui.ppm2.editor.face.lips = 'Lippenfarbe'
gui.ppm2.editor.face.eyelashes_separate_phong = 'Separate Wimpern Phong'
gui.ppm2.editor.face.eyebrows_glow = 'leuchtende Augenbrauen'
gui.ppm2.editor.face.eyebrows_glow_strength = 'Augenbrauen Leuchtstärke'
gui.ppm2.editor.face.inherit.lips = 'Erbe Lippen Farbe vom Körper'
gui.ppm2.editor.face.inherit.nose = 'Erbe Nasen Farbe vom Körper'
gui.ppm2.editor.mouth.fangs = 'Fangzähne'
gui.ppm2.editor.mouth.alt_fangs = 'Alternative Fangzähne'
gui.ppm2.editor.mouth.claw = 'Klauenzähne'
gui.ppm2.editor.mouth.teeth = 'Zahnfarbe'
gui.ppm2.editor.mouth.teeth_phong = 'Zahn Phong Parameter'
gui.ppm2.editor.mouth.mouth = 'Mundfarbe'
gui.ppm2.editor.mouth.mouth_phong = 'Mund Phong Parameter'
gui.ppm2.editor.mouth.tongue = 'Zungenfarbe'
gui.ppm2.editor.mouth.tongue_phong = 'Zunge Phong Parameter'
gui.ppm2.editor.mane.type = 'Mähne Typ'
gui.ppm2.editor.mane.phong = 'Trenne Mähne phong Einstellungen vom Körper'
gui.ppm2.editor.mane.mane_phong = 'Mähne Phong Parameter'
gui.ppm2.editor.mane.phong_sep = 'Trenne obere und untere Mähnenfarbe'
gui.ppm2.editor.mane.up.phong = 'Obere Mähne Phong Einstellungen'
gui.ppm2.editor.mane.down.type = 'Untere Mähne Typ'
gui.ppm2.editor.mane.down.phong = 'Untere Mähne Phong Einstellungen'
gui.ppm2.editor.mane.newnotice = 'Die nächsten Optionen wirken sich nur auf das neue Modell aus'
for i = 1, 2
gui.ppm2.editor.mane['color' .. i] = "Mähnefarbe #{i}"
gui.ppm2.editor.mane.up['color' .. i] = "Obere Mähnefarbe #{i}"
gui.ppm2.editor.mane.down['color' .. i] = "Untere Mähnefarbe #{i}"
for i = 1, 6
gui.ppm2.editor.mane['detail_color' .. i] = "Mähne Detail Farbe #{i}"
gui.ppm2.editor.mane.up['detail_color' .. i] = "Obere Mähnefarbe #{i}"
gui.ppm2.editor.mane.down['detail_color' .. i] = "Untere Mähnefarbe #{i}"
gui.ppm2.editor.url_mane['desc' .. i] = "Mähne URL Detail #{i} Eingabefeld"
gui.ppm2.editor.url_mane['color' .. i] = "Mähne URL Detail Farbe #{i}"
gui.ppm2.editor.url_tail['desc' .. i] = "Schweif URL Detail #{i} Eingabefeld"
gui.ppm2.editor.url_tail['color' .. i] = "Schweif URL detail Farbe #{i}"
gui.ppm2.editor.url_mane.sep.up['desc' .. i] = "Obere Mähne URL Detail #{i} Eingabefeld"
gui.ppm2.editor.url_mane.sep.up['color' .. i] = "Obere Mähne URL Detail Farbe #{i}"
gui.ppm2.editor.url_mane.sep.down['desc' .. i] = "Untere Mähne URL Detail #{i} Eingabefeld"
gui.ppm2.editor.url_mane.sep.down['color' .. i] = "Untere Mähne URL Detail Farbe #{i}"
gui.ppm2.editor.ears.bat = 'Bat pony Ohren'
gui.ppm2.editor.ears.size = 'Ohrengröße'
gui.ppm2.editor.horn.detail_color = 'Horn Detailfarbe'
gui.ppm2.editor.horn.glowing_detail = 'Horn leuchten Detail'
gui.ppm2.editor.horn.glow_strength = 'Horn leuchten Stärke'
gui.ppm2.editor.horn.separate_color = 'Trenne Horn Farbe vom Körper'
gui.ppm2.editor.horn.color = 'Horn Farbe'
gui.ppm2.editor.horn.horn_phong = 'Horn Phong Parameter'
gui.ppm2.editor.horn.magic = 'Horn magie Farbe'
gui.ppm2.editor.horn.separate_magic_color = 'Trenne magie Farbe vom Augen Farbe'
gui.ppm2.editor.horn.separate = 'Trenne Horn Farbe vom Körper'
gui.ppm2.editor.horn.separate_phong = 'Trenne Horn phong Einstellungen vom Körper'
for i = 1, 3
gui.ppm2.editor.horn.detail['desc' .. i] = "Horn URL Detail #{i}"
gui.ppm2.editor.horn.detail['color' .. i] = "URL Detail Farbe #{i}"
gui.ppm2.editor.wings.separate_color = 'Trenne Flügel Farbe vom Körper'
gui.ppm2.editor.wings.color = 'Flügelfarbe'
gui.ppm2.editor.wings.wings_phong = 'Flügel Phong Parameter'
gui.ppm2.editor.wings.separate = 'Trenne Flügelfarbe vom Körper'
gui.ppm2.editor.wings.separate_phong = 'Trenne Flügel phong Einstellungen vom Körper'
gui.ppm2.editor.wings.bat_color = 'Bat Flügelfarbe'
gui.ppm2.editor.wings.bat_skin_color = 'Bat Flügel Hautfarbe'
gui.ppm2.editor.wings.bat_skin_phong = 'Bat Flügel Haut Phong Parameter'
gui.ppm2.editor.wings.normal = 'Normale Flügel'
gui.ppm2.editor.wings.bat = 'Bat Flügel'
gui.ppm2.editor.wings.bat_skin = 'Bat Flügel Haut'
gui.ppm2.editor.wings.left.size = 'Linker Flügel Größe'
gui.ppm2.editor.wings.left.fwd = 'Linker Flügel Vorwärts'
gui.ppm2.editor.wings.left.up = 'Linker Flügel Hoch'
gui.ppm2.editor.wings.left.inside = 'Linker Flügel Innen'
gui.ppm2.editor.wings.right.size = 'Rechter Flügel Größe'
gui.ppm2.editor.wings.right.fwd = 'Rechter Flügel Vorwärts'
gui.ppm2.editor.wings.right.up = 'Rechter Flügel Hoch'
gui.ppm2.editor.wings.right.inside = 'Rechter Flügel Innen'
for i = 1, 3
gui.ppm2.editor.wings.details.def['detail' .. i] = "Flügel URL Detail #{i}"
gui.ppm2.editor.wings.details.def['color' .. i] = "URL Detail Farbe #{i}"
gui.ppm2.editor.wings.details.bat['detail' .. i] = "Bat Flügel URL Detail #{i}"
gui.ppm2.editor.wings.details.bat['color' .. i] = "Bat Flügel URL Detail Farbe #{i}"
gui.ppm2.editor.wings.details.batskin['detail' .. i] = "Bat Flügel Haut URL Detail #{i}"
gui.ppm2.editor.wings.details.batskin['color' .. i] = "Bat Flügel Haut URL Detail Farbe #{i}"
gui.ppm2.editor.neck.height = 'Halshöhe'
gui.ppm2.editor.body.suit = 'Körperanzug'
gui.ppm2.editor.body.color = 'Körperfarbe'
gui.ppm2.editor.body.body_phong = 'Körper Phong Parameter'
gui.ppm2.editor.body.spine_length = 'Rückenlänge'
gui.ppm2.editor.body.url_desc = 'Körper Detail URL Bild Eingabefeld\nSollte PNG oder JPEG sein (funktioniert wie bei\nPAC3 URL textur)'
gui.ppm2.editor.body.disable_hoofsteps = 'Hufschritte Deaktivieren'
gui.ppm2.editor.body.disable_wander_sounds = 'Wandergeräusche Deaktivieren'
gui.ppm2.editor.body.disable_new_step_sounds = 'Neue Laufgeräusche Deaktivieren'
gui.ppm2.editor.body.disable_jump_sound = 'Sprung geräusche Deaktivieren'
gui.ppm2.editor.body.disable_falldown_sound = 'Sprung geräusche Deaktivieren'
gui.ppm2.editor.body.call_playerfootstep = 'PlayerFootstep bei jedem Sound aufrufen'
gui.ppm2.editor.body.call_playerfootstep_desc = 'Ruft den PlayerFootstep hook bei jedem tatsächlichen Sound auf, den Du hörst.\nDurch die Verwendung dieser Option können sich andere installierte Addons auf die Immersion von PPM2 verlassen,\ndie den PlayerFootstep hook hören. Dies sollte nur deaktiviert werden, wenn es zu unzuverlässige Ergebnisse von anderen Addons kommt\noder Deine FPS auf niedrige Werte fallen, da eines der installierten Addons schlecht Programmiert wurde.'
for i = 1, PPM2.MAX_BODY_DETAILS
gui.ppm2.editor.body.detail['desc' .. i] = "Detail #{i}"
gui.ppm2.editor.body.detail['color' .. i] = "Detail Farbe #{i}"
gui.ppm2.editor.body.detail['glow' .. i] = "Detail #{i} leuchtet"
gui.ppm2.editor.body.detail['glow_strength' .. i] = "Detail #{i} leuchtkraft"
gui.ppm2.editor.body.detail.url['desc' .. i] = "Detail #{i}"
gui.ppm2.editor.body.detail.url['color' .. i] = "Detail Farbe #{i}"
gui.ppm2.editor.tattoo.edit_keyboard = 'Bearbeiten mit der Tastatur'
gui.ppm2.editor.tattoo.type = 'Typ'
gui.ppm2.editor.tattoo.over = 'Tattoo über Körperdetails'
gui.ppm2.editor.tattoo.glow = 'Tattoo leuchtet'
gui.ppm2.editor.tattoo.glow_strength = 'Tattoo leuchtkraft'
gui.ppm2.editor.tattoo.color = 'Farbe der Tätowierung'
gui.ppm2.editor.tattoo.tweak.rotate = 'Rotation'
gui.ppm2.editor.tattoo.tweak.x = 'X Position'
gui.ppm2.editor.tattoo.tweak.y = 'Y Position'
gui.ppm2.editor.tattoo.tweak.width = 'Breite Skalierung'
gui.ppm2.editor.tattoo.tweak.height = 'Länge Skalierung'
for i = 1, PPM2.MAX_TATTOOS
gui.ppm2.editor.tattoo['layer' .. i] = "Tattooschicht #{i}"
gui.ppm2.editor.tail.type = 'Schweif typ'
gui.ppm2.editor.tail.size = 'Schweif größe'
gui.ppm2.editor.tail.tail_phong = 'Schweif Phong Parameter'
gui.ppm2.editor.tail.separate = 'Trenne Schweif phong Einstellungen vom Körper'
for i = 1, 2
gui.ppm2.editor.tail['color' .. i] = 'Schweiffarbe ' .. i
for i = 1, 6
gui.ppm2.editor.tail['detail' .. i] = "Schweif Detail Farbe #{i}"
gui.ppm2.editor.tail.url['detail' .. i] = "Schweif URL Detail #{i}"
gui.ppm2.editor.tail.url['color' .. i] = "Schweif URL Detail #{i}"
gui.ppm2.editor.hoof.fluffers = 'Huf flausch'
gui.ppm2.editor.legs.height = 'Bein höhe'
gui.ppm2.editor.legs.socks.simple = 'Socken (einfache Textur)'
gui.ppm2.editor.legs.socks.model = 'Socken (als Modell)'
gui.ppm2.editor.legs.socks.color = 'Socken Modell Farbe'
gui.ppm2.editor.legs.socks.socks_phong = 'Socken Phong Parameter'
gui.ppm2.editor.legs.socks.texture = 'Socken Textur'
gui.ppm2.editor.legs.socks.url_texture = 'Socken URL textur'
for i = 1, 6
gui.ppm2.editor.legs.socks['color' .. i] = 'Socken Detail Farbe ' .. i
gui.ppm2.editor.legs.newsocks.model = 'Socken (als neues Modell)'
for i = 1, 3
gui.ppm2.editor.legs.newsocks['color' .. i] = 'Neue Sockenfarbe ' .. i
gui.ppm2.editor.legs.newsocks.url = 'Neue Socken URL textur'
-- shared editor stuffs
gui.ppm2.editor.tattoo.help = "Um den Bearbeitungsmodus zu verlassen, drücke Escape oder klicke irgendwo mit der Maus
Um das Tattoo zu bewegen, verwende WASD
Um höher/niedriger zu skalieren, verwende die Hoch/Runter Pfeiltasten
Um breiter/kleiner zu skalieren, verwende die Rechts/Links Pfeiltasten
Um links/rechts zu Drehen, verwende die Q/E Tasten"
gui.ppm2.editor.reset_value = 'Zurücksetzen %s'
gui.ppm2.editor.phong.info = 'Mehr Infos über Phong im Wiki'
gui.ppm2.editor.phong.exponent = 'Phong Exponent - wie stark die reflektierende Eigenschaft\nvon der Ponyhaut ist\nSetze den Wert nahe Null, um dem Roboterlook zu bekommen\nPonyhaut'
gui.ppm2.editor.phong.exponent_text = 'Phong Exponent'
gui.ppm2.editor.phong.boost.title = 'Phong Verstärkung - multipliziert spiegelnde Kartenreflexionen'
gui.ppm2.editor.phong.boost.boost = 'Phong Verstärkung'
gui.ppm2.editor.phong.tint.title = 'Tönung Farbe - welche Farben reflektieren Spiegelkarte\nWeiß - Reflektiert alle Farben\n(Im weißen Raum - weiße Spiegelkarte)'
gui.ppm2.editor.phong.tint.tint = 'Tönung Farbe - welche Farben reflektieren Spiegelkarte\nWeiß - Reflektiert alle Farben\n(Im weißen Raum - weiße Spiegelkarte)'
gui.ppm2.editor.phong.frensel.front.title = 'Phong Front - Fresnel 0 Grad Reflexionswinkel Multiplikator'
gui.ppm2.editor.phong.frensel.front.front = 'Phong Front'
gui.ppm2.editor.phong.frensel.middle.title = 'Phong Mitte - Fresnel 45 Grad Reflexionswinkel Multiplikator'
gui.ppm2.editor.phong.frensel.middle.front = 'Phong Mitte'
gui.ppm2.editor.phong.frensel.sliding.title = 'Phong Gleitend - Fresnel 45 Grad Reflexionswinkel Multiplikator'
gui.ppm2.editor.phong.frensel.sliding.front = 'Phong Gleitend'
gui.ppm2.editor.phong.lightwarp = 'Lightwarp'
gui.ppm2.editor.phong.url_lightwarp = 'Lightwarp textur URL eingabe\nEs muss 256x16 sein!'
gui.ppm2.editor.phong.bumpmap = 'Bumpmap URL eingabe'
gui.ppm2.editor.info.discord = "Trete DBot's Discord bei!"
gui.ppm2.editor.info.ponyscape = "PPM/2 ist ein Ponyscape projekt"
gui.ppm2.editor.info.creator = "PPM/2 wurde von DBot erstellt und entwickelt"
gui.ppm2.editor.info.newmodels = "Neue Modelle wurden von Durpy erstellt"
gui.ppm2.editor.info.cppmmodels = "CPPM Modelle (einschließlich Ponyhände) gehören zu UnkN', 'http://steamcommunity.com/profiles/76561198084938735"
gui.ppm2.editor.info.oldmodels = "Alte Modelle gehören zu Scentus und den anderen."
gui.ppm2.editor.info.bugs = "Einen Fehler gefunden? Melde es hier!"
gui.ppm2.editor.info.sources = "Quellen findest du hier"
gui.ppm2.editor.info.githubsources = "Oder im GitHub mirror"
gui.ppm2.editor.info.thanks = "Besonderer Dank geht an alle, die kritisiert,\ngeholfen und PPM/2 getestet haben!"
-- other stuff
info.ppm2.fly.pegasus = 'Du musst eine Pegasus oder ein Alicorn sein, um zu fliegen!'
info.ppm2.fly.cannot = 'Du kannst nicht %s im Augenblick.'
gui.ppm2.emotes.sad = 'Traurig'
gui.ppm2.emotes.wild = 'Wild'
gui.ppm2.emotes.grin = 'Grinsen'
gui.ppm2.emotes.angry = 'Wütend'
gui.ppm2.emotes.tongue = ':P'
gui.ppm2.emotes.angrytongue = '>:P'
gui.ppm2.emotes.pff = 'Pffff!'
gui.ppm2.emotes.kitty = ':3'
gui.ppm2.emotes.owo = 'oWo'
gui.ppm2.emotes.ugh = 'Uuugh'
gui.ppm2.emotes.lips = 'Lippen lecken'
gui.ppm2.emotes.scrunch = 'Scrunch'
gui.ppm2.emotes.sorry = 'Entschuldigend'
gui.ppm2.emotes.wink = 'Zwinkern'
gui.ppm2.emotes.right_wink = 'Rechts Zwinkern'
gui.ppm2.emotes.licking = 'Lecken'
gui.ppm2.emotes.suggestive_lips = 'Anzüglich Lippen Lecken'
gui.ppm2.emotes.suggestive_no_tongue = 'Anzüglich ohne Zunge'
gui.ppm2.emotes.gulp = 'Schlucken'
gui.ppm2.emotes.blah = 'Blah blah blah'
gui.ppm2.emotes.happi = 'Glücklich'
gui.ppm2.emotes.happi_grin = 'Glückliches Grinsen'
gui.ppm2.emotes.duck = 'ENTE'
gui.ppm2.emotes.ducks = 'ENTEN WAHNSINN'
gui.ppm2.emotes.quack = 'QUACK'
gui.ppm2.emotes.suggestive = 'Anzüglich mit Zunge'
message.ppm2.emotes.invalid = 'Keine Emotion mit ID: %s'
gui.ppm2.editor.intro.text = "Grüße meinen neuen.... Robochirurgen für Ponys! Es erlaubt Dir....\n" ..
"hmmm... ein Pony zu werden, und ja, dieser Prozess ist UNUMKEHRBAR! Aber mach dir keine Sorgen,\n" ..
"Du verlierst keine deiner Gehirnzellen, in und nach der Operation, weil wir die Operation sehr schonend durchführen...\n\n" ..
"Eigentlich habe ich keine Ahnung, du biologisches Wesen! Seine mechanischen Hände werden dich in die engsten Umarmungen hüllen, die du je bekommen hast!\n" ..
"Und, bitte, sterbe nicht in diesen Prozess, denn dies würde dazu führen DAS ERLÖSCHEN DEINER LEBENSLANGEN GARANTIE... und Du wirst kein Pony sein!\n" ..
"----\n\n\n" ..
"Vorsicht: Nehme den Robochirurgen nicht auseinander.\nLege deine Hände/Hufe nicht in bewegliche Teile des Robochirurgen.\n" ..
"Schalte es während des Betriebs nicht aus..\nVersuche nicht sich seinen Taten zu widersetzen.\n" ..
"Sei immer sanft mit den Robochirurgen.\n" ..
"Schlage den Robochirurgen nie auf sein Interface.\n" ..
"DBot's DLibCo übernimmt keine Verantwortung für Schäden, die durch falsche Verwendung von Robochirurgen entstehen.\n" ..
"Die Garantie erlischt, wenn der Benutzer stirbt.\n" ..
"Keine Rückerstattung."
gui.ppm2.editor.intro.title = 'Willkommen hier, Mensch!'
gui.ppm2.editor.intro.okay = "Ok, ich werde diese Lizenz sowieso nie lesen."
message.ppm2.debug.race_condition = 'Empfange NetworkedPonyData bevor das Entity auf dem Client erstellt wurde! Warten...'
gui.ppm2.spawnmenu.newmodel = 'Spawn neues Modell'
gui.ppm2.spawnmenu.newmodelnj = 'Spawn neues nj Modell'
gui.ppm2.spawnmenu.oldmodel = 'Spawn altes Modell'
gui.ppm2.spawnmenu.oldmodelnj = 'Spawn altes nj Modell'
gui.ppm2.spawnmenu.cppmmodel = 'Spawn CPPM Modell'
gui.ppm2.spawnmenu.cppmmodelnj = 'Spawn CPPM nj Modell'
gui.ppm2.spawnmenu.cleanup = 'Bereinige unbenutzte Modelle'
gui.ppm2.spawnmenu.reload = 'Lokale Daten neu laden'
gui.ppm2.spawnmenu.require = 'Daten vom Server anfordern'
gui.ppm2.spawnmenu.drawhooves = 'Stelle Hufe als Hände dar'
gui.ppm2.spawnmenu.nohoofsounds = 'Keine Hufgeräusche'
gui.ppm2.spawnmenu.noflexes = 'Deaktiviere Gesichtsausdrücke (emotes)'
gui.ppm2.spawnmenu.advancedmode = 'PPM2-Editor Erweiterter Modus aktivieren'
gui.ppm2.spawnmenu.reflections = 'Echtzeit Augenreflexionen aktivieren'
gui.ppm2.spawnmenu.reflections_drawdist = 'Reflexions sichtweite'
gui.ppm2.spawnmenu.reflections_renderdist = 'Reflexions render sichtweite'
gui.ppm2.spawnmenu.doublejump = 'Doppelsprung aktiviert Flug'
gui.ppm2.spawnmenu.vm_magic = 'ViewModel Einhorn ausrichtung'
tip.ppm2.in_editor = 'In PPM/2 Editor'
tip.ppm2.camera = "%s's PPM/2 Kamera"
message.ppm2.queue_notify = '%i Texturen werden in die Warteschlange gestellt, um gerendert zu werden.'
gui.ppm2.editor.body.bump = 'Bumpmap stärke'
| 54.425532 | 480 | 0.763761 |
ca79588ff3495234a6dce9171b0e19df36815967 | 7,677 | path = 'game/'
mapper = require path .. 'map'
camera = require path .. 'camera'
block = require path .. 'block'
export entities = require path .. 'entities'
game =
x: 0
y: 0
start_x: 0
start_y: 0
size: 32
map: {}
player: {} -- we need a reference to the player; enemies etc. need to know what's up
-- non-ECS event-queue
objects: {}
grass: {} -- jush fucking grass, draw it in the background
guns: {} -- guns and bullets
-- for ticking all the animations
animation_loop: {}
-- ECS entity id list
ecs_ids: {}
config:
width: love.graphics.getWidth! / 10
height: love.graphics.getHeight! / 10
floor: 0.1 -- fraction being floor
spin: 0.22 -- probability of spinning the wormy boi
ca:
iterations: 3
spawn_threshold: 4
die_threshold: 5
camera: camera.make love.graphics.getWidth! / 2, love.graphics.getHeight! / 2, 0.75, 0.75, 0
world: {}
sprites: require path .. 'sprites'
game.load = =>
@world = bump.newWorld 64, 64
@new_level!
check_side = (map, x, y, t) ->
if map[x] and map[x][y]
return map[x][y] == t
false
game.animate = (obj, field, a, b, speed) =>
table.insert @animation_loop,
:obj
:field
:a
:b
:speed
time: a
game.remove_animation = (obj, field) =>
for i, a in ipairs @animation_loop
table.remove @animation_loop, i if a.obj == obj and a.field == field
break
game.new_level = =>
@objects = {}
@grass = {}
@guns = {}
cx, cy = @config.width / 2 * game.size, @config.height / 2 * game.size
for id in *@ecs_ids
e.delete(id)
@ecs_ids = {}
for i = 1, 10
id = e.enemy {
position: {x: cx, y: cy}
size: {w: 32, h: 32}
sprite: {src: ""}
enemy:
waypoint: {x:0, y:0}
}
@ecs_ids[#@ecs_ids+1] = id
@world\add id, cx, cy, 32, 32
imap = mapper.gen @config
for i = 0, @config.ca.iterations
imap = mapper.automata imap, @config
@map = mapper.add_walls imap, @config
for x = 0, #@map
for y = 0, #@map[0]
switch @map[x][y]
when 0
b = block.make x * @size, y * @size, game.sprites.stones['0000']
b.sprite = @sprites.floor.grass
@spawn_grass b
if 0 == math.random 0, 3
keys = {}
for k in pairs @sprites.environment
table.insert keys, k
b = block.make x * @size, y * @size, @sprites.environment[keys[math.random #keys]]
@spawn b
when 1 -- wall
b = block.make x * @size, y * @size, game.sprites.stones['0000']
@spawn b
when 2 -- solid block
name = ''
down = check_side @map, x, y + 1, 0
name ..= (check_side @map, x, y - 1, 0) and 1 or 0
name ..= (check_side @map, x + 1, y, 0) and 1 or 0
name ..= down and 1 or 0
name ..= (check_side @map, x - 1, y, 0) and 1 or 0
b = block.make x * @size, y * @size, @sprites.floor.grass
@spawn_grass b
b = block.make x * @size, y * @size, game.sprites.stones[name], down
@world\add b, b.x, b.y, b.w, b.h
@spawn b
@player = entities.player.make @start_x * @size, @start_y * @size
@world\add @player, @player.x, @player.y, 8, 16
@spawn @player
game.spawn = (obj) =>
table.insert @objects, obj
obj\load! if obj.load
obj
game.spawn_grass = (grass) =>
table.insert @grass, grass
game.spawn_gun = (gun) =>
table.insert @guns, gun
gun
game.remove_bullet = (b) =>
for i, v in ipairs @guns
if v == b
table.remove @guns, i
break
@world\remove b
game.update = (dt) =>
for obj in *@objects
continue unless obj
obj\update dt if obj.update
for gun in *@guns
continue unless gun
gun\update dt if gun.update
for an in *@animation_loop
an.time += dt * an.speed
if (math.floor an.time) > an.b
an.time = an.a
an.obj[an.field] = math.floor an.time
game.real_pos_of = (obj) =>
cx = love.graphics.getWidth! / 2
cy = love.graphics.getHeight! / 2
x = obj.x * @camera.sx + cx - @camera.x + obj.w / 2 * @camera.sx
y = obj.y * @camera.sy + cy - @camera.y + obj.h / 2 * @camera.sy
x, y
game.atan2_obj_to_mouse = (obj) =>
x, y = @real_pos_of obj
math.atan2 y - @y, x - @x
game.draw = =>
@camera\set!
with love.graphics
for grass in *@grass
continue unless grass
grass\draw! if grass.draw
for obj in *@objects
continue unless obj
obj\draw! if obj.draw
for gun in *@guns
continue unless gun
gun\draw! if gun.draw
-- for x = 0, #@map
-- for y = 0, #@map[0]
-- if @map[x][y] == 0
-- .setColor 0.5, 1, 0.6
-- .rectangle 'fill', x * @size, y * @size, @size, @size
-- if @map[x][y] == 2
-- .setColor 0.4, 0.7, 0.3
-- .rectangle 'fill', x * @size, y * @size, @size, @size
s!
@camera\unset!
-- cx = love.graphics.getWidth! / 2
-- cy = love.graphics.getHeight! / 2
-- love.graphics.setColor 0, 0, 1
-- love.graphics.line @x, @y, @player.x * @camera.sx + cx - @camera.x + @player.w / 2 * @camera.sx, @player.y * @camera.sy + cy - @camera.y + @player.h / 2 * @camera.sy
love.graphics.setColor 0, 0, 0
love.graphics.print 'layout (enter to change): ' .. @player.controls.current, 10, 60
linecount = 0
newline = ->
result = 90 + 15*linecount
linecount += 1
result
love.graphics.print 'floor (change: 1 and 2): ' .. @config.floor, 10, newline!
love.graphics.print 'spin (change: 3 and 4): ' .. @config.spin, 10, newline!
love.graphics.print 'ca iterations (change: 5 and 6): ' .. @config.ca.iterations, 10, newline!
love.graphics.print 'ca spawn (change: 7 and 8): ' .. @config.ca.die_threshold, 10, newline!
love.graphics.print 'ca die (change: 9 and 0): ' .. @config.ca.spawn_threshold, 10, newline!
-- love.graphics.rectangle 'fill', x, y, 20, 20
game.key_press = (key) =>
switch key
when 'space'
@world = bump.newWorld 64, 64
@new_level!
collectgarbage("count")
when '1'
@config.floor -= 0.02
when '2'
@config.floor += 0.02
when '3'
@config.spin -= 0.02
when '4'
@config.spin += 0.02
when '5'
@config.ca.iterations -= 1
when '6'
@config.ca.iterations += 1
when '7'
@config.ca.die_threshold -= 1
when '8'
@config.ca.die_threshold += 1
when '9'
@config.ca.spawn_threshold -= 1
when '0'
@config.ca.spawn_threshold += 1
for obj in *@objects
obj\key_press key if obj.key_press
game.mouse_moved = (x, y) =>
@x = x
@y = y
game.mouse_press = (mouse, x, y) =>
for obj in *@objects
obj\mouse_press mouse, x, y if obj.mouse_press
game
| 26.842657 | 172 | 0.497981 |
8d29f43e022b6eeaaa1648ea5dbedab5f2ebba23 | 10,580 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import app, dispatch from howl
import Window from howl.ui
require 'howl.ui.icons.font_awesome'
describe 'CommandLine', ->
local command_line, run_as_handler
run_in_coroutine = (f) ->
wrapped = coroutine.wrap -> f!
return wrapped!
before_each ->
app.window = Window!
command_line = app.window.command_line
run_as_handler = (f) ->
command_line\run
name: 'within-activity'
handler: -> f!
after_each ->
ok, result = pcall -> app.window.command_line\abort_all!
if not ok
print result
run_as_handler = nil
command_line = nil
app.window = nil
describe 'command_line', ->
describe '\\run(activity_spec)', ->
it 'errors if handler or factory field not in spec', ->
f = -> command_line\run {}
assert.raises 'requires "name" and one of "handler" or "factory" fields', f
describe 'for activity with handler', ->
it 'calls activity handler', ->
handler = spy.new ->
command_line\run
name: 'run-activity'
handler: handler
assert.spy(handler).was_called 1
it 'passes any extra args to handler', ->
handler = spy.new ->
aspec =
name: 'run-activity'
handler: handler
command_line\run aspec, 'a1', 'a2', 'a3'
assert.spy(handler).was_called_with 'a1', 'a2', 'a3'
it 'returns result of handler', ->
result = command_line\run
name: 'run-activity'
handler: -> return 'r1'
assert.equal 'r1', result
describe 'for activity with factory', ->
it 'instantiates facory, calls run method', ->
handler = spy.new ->
run_in_coroutine ->
command_line\run
name: 'run-factory'
factory: ->
run: handler
assert.spy(handler).was_called 1
it 'passes instantiated object, finish function, extra args to run', ->
local args
obj = run: (...) ->
args = {...}
aspec =
name: 'run-factory'
factory: -> obj
run_in_coroutine ->
command_line\run aspec, 'a1', 'a2'
assert.equal args[1], obj
assert.equal 'function', type(args[2])
assert.equal 'a1', args[3]
assert.equal 'a2', args[4]
it 'returns result passed in finish function', ->
local result
run_in_coroutine ->
result = command_line\run
name: 'run-factory'
factory: ->
run: (finish) => finish('r2')
assert.equal 'r2', result
describe '\\run_after_finish(f)', ->
it 'calls f! immediately after the current activity stack exits', ->
nextf = spy.new ->
command_line\run
name: 'run-activity'
handler: ->
command_line\run_after_finish nextf
assert.spy(nextf).was_called 1
describe '\\switch_to(new_command)', ->
it 'cancels current command and runs new command, preserving text', ->
command_run = howl.command.run
timer_asap = howl.timer.asap
howl.timer.asap = (f) -> f!
new_run = spy.new ->
howl.command.run = new_run
command_line\run
name: 'run-activity'
handler: ->
command_line.text = 'hello arg'
command_line\switch_to 'new-command'
howl.command.run = command_run
howl.timer.asap = timer_asap
assert.spy(new_run).was_called_with 'new-command hello arg'
describe '.text', ->
it 'cannot be set when no running activity', ->
f = -> command_line.text = 'hello'
assert.raises 'no running activity', f
it 'returns nil when no running activity', ->
assert.equals nil, command_line.text
it 'updates the text displayed in the command_widget', ->
run_as_handler ->
command_line.text = 'hello'
assert.equal 'hello', command_line.command_widget.text
command_line.text = 'bye'
assert.equal 'bye', command_line.command_widget.text
it 'returns the text previously set', ->
run_as_handler ->
assert.equal command_line.text, ''
command_line.text = 'hi'
assert.equal 'hi', command_line.text
describe '.prompt', ->
it 'does not work when no running activity', ->
f = -> command_line.prompt = 'hello'
assert.raises 'no running activity', f
it 'updates the prompt displayed in the command_widget', ->
run_as_handler ->
command_line.prompt = 'hello'
assert.equal 'hello', command_line.command_widget.text
command_line.prompt = 'bye'
assert.equal 'bye', command_line.command_widget.text
it 'returns the prompt previously set', ->
run_as_handler ->
command_line.prompt = 'set'
assert.equal 'set', command_line.prompt
describe 'title', ->
it 'is hidden by default', ->
run_as_handler ->
assert.is_false command_line.header\to_gobject!.visible
it 'is shown and updated by setting .title', ->
run_as_handler ->
command_line.title = 'Nice Title'
assert.equal 'Nice Title', command_line.indic_title.label
assert.is_true command_line.header\to_gobject!.visible
it 'is hidden by setting title to empty string', ->
run_as_handler ->
command_line.title = 'Nice Title'
assert.is_true command_line.header\to_gobject!.visible
command_line.title = ''
assert.is_false command_line.header\to_gobject!.visible
it 'is restored to the one set by the current interaction', ->
run_as_handler ->
command_line.title = 'Title 0'
assert.equal 'Title 0', command_line.indic_title.label
run_as_handler ->
command_line.title = 'Title 1'
assert.equal 'Title 1', command_line.indic_title.label
assert.equal 'Title 0', command_line.indic_title.label
describe 'when using both .prompt and .text', ->
it 'the prompt is displayed before the text', ->
run_as_handler ->
command_line.prompt = 'prómpt:'
command_line.text = 'téxt'
assert.equal 'prómpt:téxt', command_line.command_widget.text
it 'preserves text when updating prompt', ->
run_as_handler ->
command_line.prompt = 'héllo:'
command_line.text = 'téxt'
assert.equal 'héllo:téxt', command_line.command_widget.text
command_line.prompt = 'hóla:'
assert.equal 'hóla:téxt', command_line.command_widget.text
it 'preserves prompt when updating téxt ', ->
run_as_handler ->
command_line.prompt = 'héllo:'
command_line.text = 'téxt '
assert.equal 'héllo:téxt ', command_line.command_widget.text
command_line.text = 'hóla'
assert.equal 'héllo:hóla', command_line.command_widget.text
context 'clear()', ->
it 'clears the text only, leaving prompt intact', ->
run_as_handler ->
command_line.prompt = 'héllo:'
command_line.text = 'téxt'
command_line\clear!
assert.equal 'héllo:', command_line.command_widget.text
describe 'when using nested interactions', ->
it 'each interaction has independent prompt and text', ->
run_as_handler ->
command_line.prompt = 'outer:'
command_line.text = '0'
assert.equal 'outer:0', command_line.command_widget.text
run_as_handler ->
command_line.prompt = 'inner:'
command_line.text = '1'
assert.equal 'outer:0inner:1', command_line.command_widget.text
command_line.prompt = 'later:'
assert.equal 'outer:0later:1', command_line.command_widget.text
assert.equal 'outer:0', command_line.command_widget.text
it '.stack_depth returns number of running activities', ->
depths = {}
table.insert depths, command_line.stack_depth
run_as_handler ->
table.insert depths, command_line.stack_depth
run_as_handler ->
table.insert depths, command_line.stack_depth
run_as_handler ->
table.insert depths, command_line.stack_depth
table.insert depths, command_line.stack_depth
table.insert depths, command_line.stack_depth
table.insert depths, command_line.stack_depth
assert.same { 0, 1, 2, 3, 2, 1, 0 }, depths
it '\\abort_all! cancels all running activities', ->
depths = {}
table.insert depths, command_line.stack_depth
run_as_handler ->
table.insert depths, command_line.stack_depth
run_as_handler ->
table.insert depths, command_line.stack_depth
run_as_handler ->
table.insert depths, command_line.stack_depth
command_line\abort_all!
table.insert depths, command_line.stack_depth
assert.same { 0, 1, 2, 3, 0 }, depths
it 'finishing any activity aborts all nested activities', ->
depths = {}
table.insert depths, command_line.stack_depth
run_as_handler ->
dispatch.launch ->
table.insert depths, command_line.stack_depth
p = dispatch.park 'command_line_test'
dispatch.launch ->
run_as_handler -> run_as_handler ->
table.insert depths, command_line.stack_depth
dispatch.resume p
dispatch.wait p
table.insert depths, command_line.stack_depth
assert.same {0, 1, 3, 1}, depths
it '\\clear_all! clears the entire command line and restores on exit', ->
texts = {}
run_as_handler ->
command_line.prompt = 'outér:'
command_line.text = '0'
run_as_handler ->
table.insert texts, command_line.command_widget.text
command_line\clear_all!
table.insert texts, command_line.command_widget.text
command_line.prompt = 'innér:'
command_line.text = '1'
table.insert texts, command_line.command_widget.text
table.insert texts, command_line.command_widget.text
assert.same { 'outér:0', '', 'innér:1', 'outér:0' }, texts
| 35.864407 | 83 | 0.600284 |
db94e342a9e3f1fee3e59103d49317c055f68a52 | 17,331 |
-- Copyright (C) 2017-2019 DBot
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-- of the Software, and to permit persons to whom the Software is furnished to do so,
-- subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all copies
-- or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
-- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
-- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
-- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- DEALINGS IN THE SOFTWARE.
local DISABLE_HOOFSTEP_SOUND_CLIENT
if game.SinglePlayer()
DISABLE_HOOFSTEP_SOUND_CLIENT = CreateConVar('ppm2_cl_no_hoofsound', '0', {FCVAR_ARCHIVE}, 'Disable hoofstep sound play time') if SERVER
else
DISABLE_HOOFSTEP_SOUND_CLIENT = CreateConVar('ppm2_cl_no_hoofsound', '0', {FCVAR_ARCHIVE, FCVAR_USERINFO}, 'Disable hoofstep sound play time') if CLIENT
DISABLE_HOOFSTEP_SOUND = CreateConVar('ppm2_no_hoofsound', '0', {FCVAR_REPLICATED}, 'Disable hoofstep sound play time')
hook.Remove('PlayerStepSoundTime', 'PPM2.Hooks')
hook.Add 'PlayerStepSoundTime', 'PPM2.Hoofstep', (stepType = STEPSOUNDTIME_NORMAL, isWalking = false) =>
return if not @IsPonyCached() or DISABLE_HOOFSTEP_SOUND_CLIENT and DISABLE_HOOFSTEP_SOUND_CLIENT\GetBool() or DISABLE_HOOFSTEP_SOUND\GetBool()
rate = @GetPlaybackRate() * .5
if @Crouching()
switch stepType
when STEPSOUNDTIME_NORMAL
return not isWalking and (300 / rate) or (600 / rate)
when STEPSOUNDTIME_ON_LADDER
return 500 / rate
when STEPSOUNDTIME_WATER_KNEE
return not isWalking and (400 / rate) or (800 / rate)
when STEPSOUNDTIME_WATER_FOOT
return not isWalking and (350 / rate) or (700 / rate)
else
switch stepType
when STEPSOUNDTIME_NORMAL
return not isWalking and (150 / rate) or (300 / rate)
when STEPSOUNDTIME_ON_LADDER
return 500 / rate
when STEPSOUNDTIME_WATER_KNEE
return not isWalking and (250 / rate) or (500 / rate)
when STEPSOUNDTIME_WATER_FOOT
return not isWalking and (175 / rate) or (350 / rate)
net.pool('ppm2_workaround_emitsound') if SERVER
SOUND_STRINGS_POOL = {}
SOUND_STRINGS_POOL_EXCP = {}
SOUND_STRINGS_POOL_INV = {}
AddSoundString = (sound) ->
nextid = #SOUND_STRINGS_POOL_INV + 1
SOUND_STRINGS_POOL[sound] = nextid
SOUND_STRINGS_POOL_INV[nextid] = sound
AddSoundStringEx = (sound) ->
nextid = #SOUND_STRINGS_POOL_INV + 1
SOUND_STRINGS_POOL[sound] = nextid
SOUND_STRINGS_POOL_EXCP[sound] = nextid
SOUND_STRINGS_POOL_INV[nextid] = sound
class PPM2.MaterialSoundEntry
@REGISTRIES = {}
@Ask = (matType = MAT_DEFAULT) =>
for reg in *@REGISTRIES
if reg.material == matType
return reg
return false
new: (name, material, variantsWalk = 0, variantsRun = 0, variantsWander = 0) =>
table.insert(@@REGISTRIES, @)
@name = name
@material = material
@variantsWalk = variantsWalk
@variantsRun = variantsRun
@variantsWander = variantsWander
@variantsLand = 0
@playHoofclap = true
AddSoundString('player/ppm2/' .. @name .. '/' .. @name .. '_walk' .. i .. '.ogg') for i = 1, @variantsWalk
AddSoundString('player/ppm2/' .. @name .. '/' .. @name .. '_run' .. i .. '.ogg') for i = 1, @variantsRun
AddSoundString('player/ppm2/' .. @name .. '/' .. @name .. '_wander' .. i .. '.ogg') for i = 1, @variantsWander
ShouldPlayHoofclap: => @playHoofclap
DisableHoofclap: =>
@playHoofclap = false
return @
GetWalkSound: =>
return 'player/ppm2/' .. @name .. '/' .. @name .. '_walk' .. math.random(1, @variantsWalk) .. '.ogg' if @variantsWalk ~= 0
return 'player/ppm2/' .. @name .. '/' .. @name .. '_run' .. math.random(1, @variantsRun) .. '.ogg' if @variantsRun ~= 0
GetRunSound: =>
return 'player/ppm2/' .. @name .. '/' .. @name .. '_run' .. math.random(1, @variantsRun) .. '.ogg' if @variantsRun ~= 0
return 'player/ppm2/' .. @name .. '/' .. @name .. '_walk' .. math.random(1, @variantsWalk) .. '.ogg' if @variantsWalk ~= 0
GetWanderSound: =>
return 'player/ppm2/' .. @name .. '/' .. @name .. '_wander' .. math.random(1, @variantsWander) .. '.ogg' if @variantsWander ~= 0
GetLandSound: =>
return 'player/ppm2/' .. @name .. '/' .. @name .. '_land' .. math.random(1, @variantsLand) .. '.ogg' if @variantsLand ~= 0
AddLandSounds: (variants) =>
@variantsLand = variants
AddSoundString('player/ppm2/' .. @name .. '/' .. @name .. '_land' .. i .. '.ogg') for i = 1, variants
return @
AddSoundString('player/ppm2/hooves' .. i .. '.ogg') for i = 1, 3
AddSoundString('player/ppm2/falldown.ogg')
AddSoundStringEx('player/ppm2/jump.ogg')
RECALL = false
RecallPlayerFootstep = (ply, pos, foot, sound, volume, filter) ->
RECALL = true
ProtectedCall () -> hook.Run('PlayerFootstep', ply, pos, foot, sound, volume, filter)
RECALL = false
LEmitSound = (ply, name, level = 75, volume = 1, levelIfOnServer = level) ->
return if not IsValid(ply)
if CLIENT
ply\EmitSound(name, level, 100, volume) if not game.SinglePlayer() -- Some mods fix this globally (PAC3 for example)
-- so lets try to avoid problems
return
if game.SinglePlayer()
ply\EmitSound(name, level, 100, volume)
return
error('Tried to play unpooled sound: ' .. name) if not SOUND_STRINGS_POOL[name]
filter = RecipientFilter()
filter\AddPAS(ply\GetPos())
filter\RemovePlayer(ply)
for ply2 in *filter\GetPlayers()
if ply2\GetInfoBool('ppm2_cl_no_hoofsound', false)
filter\RemovePlayer(ply2)
return if filter\GetCount() == 0
net.Start('ppm2_workaround_emitsound')
net.WritePlayer(ply)
net.WriteUInt8(SOUND_STRINGS_POOL[name])
net.WriteUInt8(levelIfOnServer)
net.WriteUInt8((volume * 100)\floor())
net.Send(filter)
return filter
if CLIENT
EntityEmitSound = (data) ->
ply = data.Entity
return if not IsValid(ply) or not ply\IsPlayer()
pdata = ply\GetPonyData()
return if not pdata or not pdata\ShouldMuffleHoosteps()
return if not SOUND_STRINGS_POOL[data.OriginalSoundName] or SOUND_STRINGS_POOL_EXCP[data.OriginalSoundName]
data.DSP = 31
return true
hook.Add 'EntityEmitSound', 'PPM2.Hoofsteps', EntityEmitSound, -2
-- 0 LrigPelvis
-- 1 Lrig_LEG_BL_Femur
-- 2 Lrig_LEG_BL_Tibia
-- 3 Lrig_LEG_BL_LargeCannon
-- 4 Lrig_LEG_BL_PhalanxPrima
-- 5 Lrig_LEG_BL_RearHoof
-- 6 Lrig_LEG_BR_Femur
-- 7 Lrig_LEG_BR_Tibia
-- 8 Lrig_LEG_BR_LargeCannon
-- 9 Lrig_LEG_BR_PhalanxPrima
-- 10 Lrig_LEG_BR_RearHoof
-- 11 LrigSpine1
-- 12 LrigSpine2
-- 13 LrigRibcage
-- 14 Lrig_LEG_FL_Scapula
-- 15 Lrig_LEG_FL_Humerus
-- 16 Lrig_LEG_FL_Radius
-- 17 Lrig_LEG_FL_Metacarpus
-- 18 Lrig_LEG_FL_PhalangesManus
-- 19 Lrig_LEG_FL_FrontHoof
-- 20 Lrig_LEG_FR_Scapula
-- 21 Lrig_LEG_FR_Humerus
-- 22 Lrig_LEG_FR_Radius
-- 23 Lrig_LEG_FR_Metacarpus
-- 24 Lrig_LEG_FR_PhalangesManus
-- 25 Lrig_LEG_FR_FrontHoof
-- 26 LrigNeck1
-- 27 LrigNeck2
-- 28 LrigNeck3
-- 29 LrigScull
-- 30 Jaw
-- 31 Ear_L
-- 32 Ear_R
-- 33 Mane02
-- 34 Mane03
-- 35 Mane03_tip
-- 36 Mane04
-- 37 Mane05
-- 38 Mane06
-- 39 Mane07
-- 40 Mane01
-- 41 Lrigweaponbone
-- 42 right_hand
-- 43 wing_l
-- 44 wing_r
-- 45 Tail01
-- 46 Tail02
-- 47 Tail03
-- 48 wing_l_bat
-- 49 wing_r_bat
-- 50 wing_open_l
-- 51 wing_open_r
class PPM2.PlayerFootstepsListener
@soundBones = {
Vector(8.112172, 3.867798, 0)
Vector(8.111097, -3.863072, 0)
Vector(-14.863633, 4.491844, 0)
Vector(-14.863256, -4.487118, 0)
}
new: (ply) =>
ply.__ppm2_walkc = @
@ply = ply
@walkSpeed = ply\GetWalkSpeed()
@runSpeed = ply\GetRunSpeed()
@playedWanderSound = false
@running = false
@lastVelocity = @ply\GetVelocity()
@initialVel = @ply\GetVelocity()
@lastTrace = @TraceNow()
@onGround = @ply\OnGround()
@Validate() if @onGround
hook.Add 'PlayerFootstep', @, @PlayerFootstep, 8
hook.Add 'Think', @, @Think
@nextWanderPos = 0
@nextWalkPos = 0
@nextRunPos = 0
@lambdaEmitWander = ->
return if not @ply\IsValid()
return if @ParentCall('GetDisableWanderSounds', false)
return if not @onGround
return if not @lastEntry
sound = @lastEntry\GetWanderSound()
return if not sound
filter = @EmitSound(sound, 50, @GetVolume(), 70)
return if not @ParentCall('GetCallPlayerFootstepHook', true)
@nextWanderPos += 1
@nextWanderPos %= 4
RecallPlayerFootstep(@ply, @@GetPosForSide(@nextWanderPos, @ply), @nextWanderPos, sound, @GetVolume(), filter)
@lambdaEmitWalk = ->
return if not @ply\IsValid()
return if not @onGround
if not @lastEntry
if not @ParentCall('GetDisableHoofsteps', false)
sound = @@RandHoof()
filter = @EmitSound(sound, 50, 0.8 * @GetVolume(), 65)
return if not @ParentCall('GetCallPlayerFootstepHook', true)
@nextWalkPos += 1
@nextWalkPos %= 4
RecallPlayerFootstep(@ply, @@GetPosForSide(@nextWalkPos, @ply), @nextWalkPos, sound, 0.8 * @GetVolume(), filter)
return
@EmitSound(@@RandHoof(), 50, 0.8 * @GetVolume(), 65) if @lastEntry\ShouldPlayHoofclap() and not @ParentCall('GetDisableHoofsteps', false)
return if @ParentCall('GetDisableStepSounds', false)
sound = @lastEntry\GetWalkSound()
return if not sound
filter = @EmitSound(sound, 40, 0.8 * @GetVolume(), 55)
return true if not @ParentCall('GetCallPlayerFootstepHook', true)
@nextWalkPos += 1
@nextWalkPos %= 4
RecallPlayerFootstep(@ply, @@GetPosForSide(@nextWalkPos, @ply), @nextWalkPos, sound, 0.8 * @GetVolume(), filter)
return true
@lambdaEmitRun = ->
return if not @ply\IsValid()
return if not @onGround
if not @lastEntry
if not @ParentCall('GetDisableHoofsteps', false)
sound = @@RandHoof()
filter = @EmitSound(sound, 60, @GetVolume(), 70)
return if not @ParentCall('GetCallPlayerFootstepHook', true)
@nextRunPos += 1
@nextRunPos %= 4
RecallPlayerFootstep(@ply, @@GetPosForSide(@nextRunPos, @ply), @nextRunPos, sound, @GetVolume(), filter)
return
@EmitSound(@@RandHoof(), 60, @GetVolume(), 70) if @lastEntry\ShouldPlayHoofclap() and not @ParentCall('GetDisableHoofsteps', false)
return if @ParentCall('GetDisableStepSounds', false)
sound = @lastEntry\GetRunSound()
return if not sound
filter = @EmitSound(sound, 40, 0.7 * @GetVolume(), 60)
return true if not @ParentCall('GetCallPlayerFootstepHook', true)
@nextRunPos += 1
@nextRunPos %= 4
RecallPlayerFootstep(@ply, @@GetPosForSide(@nextRunPos, @ply), @nextRunPos, sound, 0.7 * @GetVolume(), filter)
return true
@GetPosForSide = (side = 0, ply) =>
if data = ply\GetPonyData()
return ply\GetPos() if not @soundBones[side + 1]
return ply\GetPos() + @soundBones[side + 1] * data\GetPonySize()
return ply\GetPos() if not @soundBones[side + 1]
return ply\GetPos() + @soundBones[side + 1]
IsValid: => @ply\IsValid() and not @playedWanderSound
ParentCall: (func, ifNone) =>
if data = @ply\GetPonyData()
return data[func](data)
return ifNone
GetVolume: => @ParentCall('GetHoofstepVolume', 1)
Validate: =>
newMatType = @lastTrace.MatType == 0 and MAT_DEFAULT or @lastTrace.MatType
return if @lastMatType == newMatType
@lastMatType = newMatType
@lastEntry = PPM2.MaterialSoundEntry\Ask(@lastMatType)
@RandHoof: => 'player/ppm2/hooves' .. math.random(1, 3) .. '.ogg'
EmitSound: (name, level = 75, volume = 1, levelIfOnServer = level) => LEmitSound(@ply, name, level, volume, levelIfOnServer)
PlayWalk: =>
timer.Simple 0.13, @lambdaEmitWalk
timer.Simple 0.21, @lambdaEmitWalk
--timer.Simple 0.19, @lambdaEmitWalk
return @lambdaEmitWalk()
PlayWander: =>
@playedWanderSound = true
timer.Simple 0.13, @lambdaEmitWander
timer.Simple 0.17, @lambdaEmitWander
--timer.Simple 0.27, @lambdaEmitWander
@lambdaEmitWander()
PlayRun: =>
timer.Simple 0.18, @lambdaEmitRun
--timer.Simple 0.13, @lambdaEmitRun
--timer.Simple 0.17, @lambdaEmitRun
return @lambdaEmitRun()
TraceNow: => @@TraceNow(@ply)
@TraceNow: (ply, dropToGround) =>
mins, maxs = ply\GetHull()
trData = {
start: ply\GetPos()
endpos: ply\GetPos() - Vector(0, 0, not dropToGround and 5 or 15)
:mins, :maxs
filter: ply
}
return util.TraceHull(trData)
PlayerFootstep: (ply) =>
return if RECALL
return if ply ~= @ply
return true if CLIENT and @ply ~= LocalPlayer()
@lastTrace = @TraceNow()
@Validate()
if @running
return @PlayRun()
else
return @PlayWalk()
Think: =>
@lastVelocity = @ply\GetVelocity()
vlen = @lastVelocity\Length()
@onGround = @ply\OnGround()
@running = vlen >= @runSpeed
if vlen < @walkSpeed * 0.2
@ply.__ppm2_walkc = nil
@PlayWander()
PPM2.MaterialSoundEntry('concrete', MAT_CONCRETE, 11, 11, 5)
PPM2.MaterialSoundEntry('dirt', MAT_DIRT, 11, 11, 5)\AddLandSounds(4)\DisableHoofclap()
PPM2.MaterialSoundEntry('grass', MAT_GRASS, 10, 4, 6)\DisableHoofclap()
PPM2.MaterialSoundEntry('gravel', MAT_DEFAULT, 11, 11, 3)\DisableHoofclap() -- e
PPM2.MaterialSoundEntry('metalbar', MAT_METAL, 11, 11, 6)
PPM2.MaterialSoundEntry('metalbox', MAT_VENT, 10, 9, 4)
PPM2.MaterialSoundEntry('mud', MAT_SLOSH, 10, 9, 4)\DisableHoofclap()
PPM2.MaterialSoundEntry('sand', MAT_SAND, 11, 11, 0)\DisableHoofclap()
PPM2.MaterialSoundEntry('snow', MAT_SNOW, 11, 11, 5)\DisableHoofclap()
PPM2.MaterialSoundEntry('squeakywood', MAT_WOOD, 11, 0, 7)
if CLIENT
net.receive 'ppm2_workaround_emitsound', ->
return if DISABLE_HOOFSTEP_SOUND_CLIENT\GetBool()
ply, sound, level, volume = net.ReadPlayer(), SOUND_STRINGS_POOL_INV[net.ReadUInt8()], net.ReadUInt8(), net.ReadUInt8() / 100
return if not IsValid(ply)
ply\EmitSound(sound, level, 100, volume)
hook.Add 'PlayerFootstep', 'PPM2.Hoofstep', (pos, foot, sound, volume, filter) =>
return if RECALL
return if CLIENT and game.SinglePlayer()
return if not @IsPonyCached() or DISABLE_HOOFSTEP_SOUND_CLIENT and DISABLE_HOOFSTEP_SOUND_CLIENT\GetBool() or DISABLE_HOOFSTEP_SOUND\GetBool()
return if @__ppm2_walkc
return PPM2.PlayerFootstepsListener(@)\PlayerFootstep(@)
LEmitSoundRecall = (sound, level, volume, levelIfOnServer = level, side) =>
return if not @IsValid()
filter = LEmitSound(@, sound, level, volume, levelIfOnServer)
RecallPlayerFootstep(@, PPM2.PlayerFootstepsListener\GetPosForSide(side, @), side, sound, volume, filter)
return filter
ProcessFalldownEvents = (cmd) =>
return if not @IsPonyCached()
return if DISABLE_HOOFSTEP_SOUND_CLIENT and DISABLE_HOOFSTEP_SOUND_CLIENT\GetBool() or DISABLE_HOOFSTEP_SOUND\GetBool()
if @GetMoveType() ~= MOVETYPE_WALK
@__ppm2_jump = false
return
self2 = @GetTable()
ground = @OnGround()
jump = cmd\KeyDown(IN_JUMP)
modifier = 1
disableFalldown = false
disableJumpSound = false
disableHoofsteps = false
disableWalkSounds = false
if data = @GetPonyData()
modifier = data\GetHoofstepVolume()
disableFalldown = data\GetDisableFalldownSound()
disableJumpSound = data\GetDisableJumpSound()
disableHoofsteps = data\GetDisableHoofsteps()
disableWalkSounds = data\GetDisableStepSounds()
if @__ppm2_jump and ground
@__ppm2_jump = false
tr = PPM2.PlayerFootstepsListener\TraceNow(@)
entry = PPM2.MaterialSoundEntry\Ask(tr.MatType == 0 and MAT_DEFAULT or tr.MatType)
if entry
if sound = entry\GetLandSound()
LEmitSound(@, sound, 60, modifier, 75) if not disableFalldown
elseif not @__ppm2_walkc and not disableWalkSounds
if sound = entry\GetWalkSound()
LEmitSoundRecall(@, sound, 45, 0.2 * modifier, 55, 0)
timer.Simple 0.04, -> LEmitSoundRecall(@, sound, 45, 0.3 * modifier, 55, 1)
timer.Simple 0.07, -> LEmitSoundRecall(@, sound, 45, 0.3 * modifier, 55, 2)
timer.Simple 0.1, -> LEmitSoundRecall(@, sound, 45, 0.3 * modifier, 55, 3)
if not entry\ShouldPlayHoofclap()
return
if not disableFalldown
filter = LEmitSound(@, 'player/ppm2/falldown.ogg', 60, 1, 75)
for i = 0, 3
timer.Simple i * 0.1, -> RecallPlayerFootstep(@, PPM2.PlayerFootstepsListener\GetPosForSide(i, @), i, 'player/ppm2/falldown.ogg', 1, filter) if @IsValid()
elseif jump and not ground and not @__ppm2_jump
@__ppm2_jump = true
LEmitSound(@, 'player/ppm2/jump.ogg', 50, 1, 65) if not disableJumpSound
tr = PPM2.PlayerFootstepsListener\TraceNow(@, true)
entry = PPM2.MaterialSoundEntry\Ask(tr.MatType == 0 and MAT_DEFAULT or tr.MatType)
if (not entry or entry\ShouldPlayHoofclap()) and not disableHoofsteps
LEmitSoundRecall(@, PPM2.PlayerFootstepsListener.RandHoof(), 55, 0.4 * modifier, 65, 0)
timer.Simple 0.04, -> LEmitSoundRecall(@, PPM2.PlayerFootstepsListener.RandHoof(), 55, 0.4 * modifier, 65, 1)
timer.Simple 0.07, -> LEmitSoundRecall(@, PPM2.PlayerFootstepsListener.RandHoof(), 55, 0.4 * modifier, 65, 2)
timer.Simple 0.1, -> LEmitSoundRecall(@, PPM2.PlayerFootstepsListener.RandHoof(), 55, 0.4 * modifier, 65, 3)
hook.Add 'StartCommand', 'PPM2.Hoofsteps', ProcessFalldownEvents
| 34.386905 | 158 | 0.706307 |
053dcca322cd5b2ed0dad6e896674413243e4e77 | 134 |
if false
true
true
true
true
print hello
else
true
true
true
true
print "hello world"
print doesnt.exist
| 7.052632 | 21 | 0.626866 |
bc4ef19122a2a20951f80093b02985b713613fbe | 2,889 | int2bin = (n) ->
result = {}
while n ~= 0
if n % 2 == 0
result[#result]
table.concat result
walls = (path) ->
{
'0000': love.graphics.newImage path .. '0000.png'
'0001': love.graphics.newImage path .. '0001.png'
'0010': love.graphics.newImage path .. '0010.png'
'0011': love.graphics.newImage path .. '0011.png'
'0100': love.graphics.newImage path .. '0100.png'
'0101': love.graphics.newImage path .. '0101.png'
'0110': love.graphics.newImage path .. '0110.png'
'0111': love.graphics.newImage path .. '0111.png'
'1000': love.graphics.newImage path .. '1000.png'
'1001': love.graphics.newImage path .. '1001.png'
'1010': love.graphics.newImage path .. '1010.png'
'1011': love.graphics.newImage path .. '1011.png'
'1100': love.graphics.newImage path .. '1100.png'
'1101': love.graphics.newImage path .. '1101.png'
'1110': love.graphics.newImage path .. '1110.png'
'1111': love.graphics.newImage path .. '1111.png'
}
sprites =
stones: walls 'sprites/wall/stone/'
floor:
grass: love.graphics.newImage 'sprites/floor/grass.png'
enemy:
fucker: love.graphics.newImage 'sprites/enemy/fucker.png'
environment:
flower1: love.graphics.newImage 'sprites/environment/flower1.png'
flower2: love.graphics.newImage 'sprites/environment/flower2.png'
flower3: love.graphics.newImage 'sprites/environment/flower3.png'
flower4: love.graphics.newImage 'sprites/environment/flower4.png'
grass1: love.graphics.newImage 'sprites/environment/grass1.png'
grass2: love.graphics.newImage 'sprites/environment/grass2.png'
grass3: love.graphics.newImage 'sprites/environment/grass3.png'
grass4: love.graphics.newImage 'sprites/environment/grass4.png'
grass5: love.graphics.newImage 'sprites/environment/grass5.png'
grass6: love.graphics.newImage 'sprites/environment/grass6.png'
rocks1: love.graphics.newImage 'sprites/environment/rocks1.png'
rocks2: love.graphics.newImage 'sprites/environment/rocks2.png'
rocks3: love.graphics.newImage 'sprites/environment/rocks3.png'
rocks4: love.graphics.newImage 'sprites/environment/rocks4.png'
player:
idle: love.graphics.newImage 'sprites/player/player_idle.png'
walk: {
love.graphics.newImage 'sprites/player/player_walk1.png',
love.graphics.newImage 'sprites/player/player_walk2.png',
love.graphics.newImage 'sprites/player/player_walk3.png',
love.graphics.newImage 'sprites/player/player_walk4.png'
}
gun:
handgun: love.graphics.newImage 'sprites/gun/handgun.png'
bullet:
pill_lg: love.graphics.newImage 'sprites/projectile/pill_large.png'
sprites | 45.140625 | 75 | 0.65559 |
12422ad743d61924ac0c673e5f8d1d96cb48923d | 3,790 |
--
-- Copyright (C) 2017-2020 DBotThePony
-- 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.
net = DLib.net
ALLOW_ONLY_RAGDOLLS = CreateConVar('ppm2_sv_edit_ragdolls_only', '0', {FCVAR_NOTIFY, FCVAR_REPLICATED}, 'Allow to edit only ragdolls')
DISALLOW_PLAYERS = CreateConVar('ppm2_sv_edit_no_players', '1', {FCVAR_NOTIFY, FCVAR_REPLICATED}, 'When unrestricted edit allowed, do not allow to edit players.')
genericUsageCheck = (ply, ent) ->
return false if not IsValid(ply)
return false if not IsValid(ent)
return false if ALLOW_ONLY_RAGDOLLS\GetBool() and ent\GetClass() ~= 'prop_ragdoll'
return false if DISALLOW_PLAYERS\GetBool() and ent\IsPlayer()
return false if not ent\IsPony()
return false if not hook.Run('CanTool', ply, {Entity: ent, HitPos: ent\GetPos(), HitNormal: Vector()}, 'ponydata')
return false if not hook.Run('CanProperty', ply, 'ponydata', ent)
return true
net.ReceiveAntispam('PPM2.RagdollEdit')
net.Receive 'PPM2.RagdollEdit', (len = 0, ply = NULL) ->
ent = net.ReadEntity()
useLocal = net.ReadBool()
return if not genericUsageCheck(ply, ent)
if useLocal
return if not ply\GetPonyData()
data = ent\GetPonyData() or PPM2.NetworkedPonyData(nil, ent)
plydata = ply\GetPonyData()
plydata\ApplyDataToObject(data)
data\Create()
else
data = ent\GetPonyData() or PPM2.NetworkedPonyData(nil, ent)
data\ReadNetworkData(len, ply, false, false)
data\CreateOrNetworkAll()
duplicator.StoreEntityModifier(ent, 'ppm2_ragdolledit', ent\GetPonyData()\NetworkedIterable(false))
net.ReceiveAntispam('PPM2.RagdollEditFlex')
net.Receive 'PPM2.RagdollEditFlex', (len = 0, ply = NULL) ->
ent = net.ReadEntity()
status = net.ReadBool()
return if not genericUsageCheck(ply, ent)
if not ent\GetPonyData()
data = PPM2.NetworkedPonyData(nil, ent)
data = ent\GetPonyData()
data\SetNoFlex(status)
data\Create() if not data\IsNetworked()
net.ReceiveAntispam('PPM2.RagdollEditEmote')
net.Receive 'PPM2.RagdollEditEmote', (len = 0, ply = NULL) ->
ent = net.ReadEntity()
return if not genericUsageCheck(ply, ent)
self = ply
emoteID = net.ReadUInt(8)
return if not PPM2.AVALIABLE_EMOTES[emoteID]
@__ppm2_last_played_emote = @__ppm2_last_played_emote or 0
return if @__ppm2_last_played_emote > RealTimeL()
@__ppm2_last_played_emote = RealTimeL() + 1
net.Start('PPM2.PlayEmote')
net.WriteUInt(emoteID, 8)
net.WriteEntity(ent)
net.WriteBool(false)
net.WriteBool(false)
net.SendOmit(ply)
duplicator.RegisterEntityModifier 'ppm2_ragdolledit', (ply = NULL, ent = NULL, storeddata = {}) ->
return if not IsValid(ent)
if not ent\GetPonyData()
data = PPM2.NetworkedPonyData(nil, ent)
data = ent\GetPonyData()
data["Set#{key}"](data, value, false) for _, {key, value} in ipairs storeddata when data["Set#{key}"]
data\Create()
| 40.319149 | 162 | 0.75277 |
6cb2cb1836e3648aaa539d393c2f31cfe47c8ffe | 1,446 | -- alfons.file
-- Gets the contents of a taskfile
fs = require "filekit"
readMoon = (file) ->
local content
with fs.safeOpen file, "r"
-- check that we could open correctly
if .error
return nil, "Could not open #{file}: #{.error}"
-- read and compile
import to_lua from require "moonscript.base"
content, err = to_lua \read "*a"
-- check that we could compile correctly
unless content
return nil, "Could not read or parse #{file}: #{err}"
\close!
-- return
return content
readLua = (file) ->
local content
with fs.safeOpen file, "r"
-- check that we could open correctly
if .error
return nil, "Could not open #{file}: #{.error}"
-- read and compile
content = \read "*a"
-- check that we could compile correctly
unless content
return nil, "Could not read #{file}: #{content}"
\close!
-- return
return content
readTeal = (file) ->
local content
with fs.safeOpen file, "r"
-- check that we could open correctly
if .error
return nil, "Could not open #{file}: #{.error}"
-- read and compile
import init_env, gen from require "tl"
gwe = init_env true, false -- lax:true, compat:false
content = gen (\read "*a"), gwe
-- check that we could compile correctly
unless content
return nil, "Could not read #{file}: #{content}"
\close!
-- return
return content
{ :readMoon, :readLua, :readTeal } | 27.283019 | 60 | 0.625864 |
36fb897e777cce9f307c66233844bb9bbef7275c | 6,950 | local log
version = '1.0.4'
haveDepCtrl, DependencyControl = pcall require, 'l0.DependencyControl'
if haveDepCtrl
version = DependencyControl {
name: 'TrimHandler'
:version
description: 'A class for encoding video clips.'
author: 'torque'
url: 'https://github.com/TypesettingTools/Aegisub-Motion'
moduleName: 'a-mo.TrimHandler'
feed: 'https://raw.githubusercontent.com/TypesettingTools/Aegisub-Motion/DepCtrl/DependencyControl.json'
{
{ 'a-mo.Log', version: '1.0.0' }
}
}
log = version\requireModules!
else
log = require 'a-mo.Log'
windows = jit.os == "Windows"
class TrimHandler
@version: version
@windows: windows
existingPresets: {
"x264", "ffmpeg"
}
-- Set up encoder presets.
defaults: {
x264: '"#{encbin}" --crf 16 --tune fastdecode -i 250 --fps 23.976 --sar 1:1 --index "#{prefix}/#{index}.index" --seek #{startf} --frames #{lenf} -o "#{prefix}/#{output}[#{startf}-#{endf}].mp4" "#{inpath}/#{input}"'
ffmpeg: '"#{encbin}" -ss #{startt} -an -sn -i "#{inpath}/#{input}" -q:v 1 -frames:v #{lenf} "#{prefix}/#{output}[#{startf}-#{endf}]-%05d.jpg"'
-- avs2pipe: 'echo FFVideoSource("#{inpath}#{input}",cachefile="#{prefix}#{index}.index").trim(#{startf},#{endf}).ConvertToRGB.ImageWriter("#{prefix}/#{output}-[#{startf}-#{endf}]\\",type="png").ConvertToYV12 > "#{temp}/a-mo.encode.avs"\nmkdir "#{prefix}#{output}-[#{startf}-#{endf}]"\n"#{encbin}" video "#{temp}/a-mo.encode.avs"\ndel "#{temp}/a-mo.encode.avs"'
-- vapoursynth:
}
-- Example trimConfig:
-- trimConfig = {
-- -- The prefix is the directory the output will be written to. It
-- -- is passed through aegisub.decode_path.
-- prefix: "?video"
-- -- The name of the built in encoding preset to use. Overridden by
-- -- command if that is neither nil nor an empty string.
-- preset: "x264"
-- -- The path of the executable used to actually do the encoding.
-- -- Full path is recommended as the shell environment may be
-- -- different than expected on non-windows systems.
-- encBin: "C:\x264.exe"
-- -- A custom encoding command that can be used to override the
-- -- built-in defaults. Usable token documentation to come.
-- -- Overrides preset if that is set.
-- command: nil
-- -- Script should attempt to create prefix directory.
-- makePfix: nil
-- -- Script should attempt to log output of the encoding command.
-- writeLog: true
-- }
new: ( trimConfig ) =>
@tokens = { }
if trimConfig.command != nil
trimConfig.command = trimConfig.command\gsub "[\t \r\n]*$", ""
if trimConfig.command != ""
@command = trimConfig.command
else
@command = @defaults[trimConfig.preset]
else
@command = @defaults[trimConfig.preset]
@makePrefix = trimConfig.makePfix
@writeLog = trimConfig.writeLog
with @tokens
.temp = aegisub.decode_path "?temp"
-- For some reason, aegisub appends / to the end of ?temp but not
-- other tokens.
finalTemp = .temp\sub -1, -1
if finalTemp == '\\' or finalTemp == '/'
.temp = .temp\sub 1, -2
.encbin = trimConfig.encBin
.prefix = aegisub.decode_path trimConfig.prefix
.inpath = aegisub.decode_path "?video"
.log = aegisub.decode_path "#{.temp}/a-mo.encode.log"
getVideoName @
getVideoName = =>
with @tokens
video = aegisub.project_properties!.video_file
if video\len! == 0
log.windowError "Aegisub thinks your video is 0 frames long.\nTheoretically it should be impossible to get this error."
if video\match "^?dummy"
log.windowError "I can't encode that dummy video for you."
.input = video\gsub( "^[A-Z]:\\", "", 1 )\gsub ".+[^\\/]-[\\/]", "", 1
.index = .input\match "(.+)%.[^%.]+$"
.output = .index
calculateTrimLength: ( lineCollection ) =>
with @tokens
.startt = lineCollection.startTime / 1000
.endt = lineCollection.endTime / 1000
.lent = .endt - .startt
.startf = lineCollection.startFrame
.endf = lineCollection.endFrame - 1
.lenf = lineCollection.totalFrames
performTrim: =>
with platform = ({
[true]: {
pre: @tokens.temp
ext: ".ps1"
-- This needs to be run from cmd or it will not work.
exec: 'powershell -c iex "$(gc "%s" -en UTF8)"'
preCom: (@makePrefix and "mkdir -Force \"#{@tokens.prefix}\"; & " or "& ")
postCom: (@writeLog and " 2>&1 | Out-File #{@tokens.log} -en UTF8; if($LASTEXITCODE -ne 0) {echo \"If there is no log before this, your encoder is not a working executable or your encoding command is invalid.\" | ac -en utf8 #{@tokens.log}; exit 1}" or "") .. "; exit 0"
execFunc: ( encodeScript ) ->
-- clear out old logfile because it doesn't get overwritten
-- when certain errors occur.
if @writeLog
logFile = io.open @tokens.log, 'wb'
logFile\close! if logFile
success = os.execute encodeScript
if @writeLog and not success
logFile = io.open @tokens.log, 'r'
unless logFile
log.windowError "Could not read log file #{@tokens.log}.\nSomething has gone horribly wrong."
encodeLog = logFile\read '*a'
logFile\close!
log.warn "\nEncoding error:"
log.warn encodeLog
log.windowError "Encoding failed. Log has been printed to progress window."
elseif not success
log.windowError "Encoding seems to have failed but you didn't write a log file."
}
[false]: {
pre: @tokens.temp
ext: ".sh"
exec: 'sh "%s"'
preCom: @makePrefix and "mkdir -p \"#{@tokens.prefix}\"\n" or ""
postCom: " 2>&1; if [[ $? -ne 0 ]]; then echo \"If there is no log before this, your encoder is not a working executable or your encoding command is invalid.\"; false; fi"
execFunc: ( encodeScript ) ->
logFile = io.popen encodeScript, 'r'
encodeLog = logFile\read '*a'
-- When closing a file handle created with io.popen,
-- file:close returns the same values returned by
-- os.execute.
success = logFile\close!
unless success
log.warn "\nEncoding error:"
log.warn encodeLog
log.windowError "Encoding failed. Log has been printed to progress window."
}
})[windows]
-- check encoder binary exists
encoder = io.open @tokens.encbin, "rb"
unless encoder
log.windowError "Encoding binary (#{@tokens.encbin}) does not appear to exist."
encoder\close!
encodeScript = aegisub.decode_path "#{.pre}/a-mo.encode#{.ext}"
encodeScriptFile = io.open encodeScript, "w+"
unless encodeScriptFile
log.windowError "Encoding script could not be written.\nSomething is wrong with your temp dir (#{.pre})."
encodeString = .preCom .. @command\gsub( "#{(.-)}", ( token ) -> @tokens[token] ) .. .postCom
if windows
encodeString = encodeString\gsub "`", "``"
log.debug encodeString
encodeScriptFile\write encodeString
encodeScriptFile\close!
.execFunc .exec\format encodeScript
if haveDepCtrl
return version\register TrimHandler
else
return TrimHandler
| 37.365591 | 363 | 0.648201 |
3b589a8a488a0000354868e34414e445992c448b | 272 | -- check whether the host operating system is windows
M = {}
T = require("PackageToolkit").module
L = T.import ..., "../_lists"
S = T.import ..., "../_strings"
M.windows = () ->
dir_separator = L.head S.split package.config
return dir_separator == '\\'
return M
| 27.2 | 53 | 0.636029 |
a7946b23e4d4f1c6923da83b109b2e962a1916f7 | 334 | class WEBP extends Format
new: =>
@displayName = "WEBP"
@supportsTwopass = false
@videoCodec = "libwebp_anim"
@audioCodec = ""
@outputExtension = "webp"
@acceptsBitrate = false
getFlags: =>
{
"--ofopts-add=loop=0",
"--ovcopts-add=quality=80",
"--ovcopts-add=compression_level=5"
}
formats["webp"] = WEBP!
| 18.555556 | 38 | 0.640719 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.