Tonemap Fuse for Fusion based on Timothy Lottes algorithm (Lua) - lua

I'm trying to build a Fuse (Fusion studio plugin) based on the tone mapper by Timothy Lottes : http://32ipi028l5q82yhj72224m8j.wpengine.netdna-cdn.com/wp-content/uploads/2016/03/GdcVdrLottes.pdf
presented in this algorithm: https://github.com/Opioid/tonemapper/blob/master/tonemapper.py#L14-L42
The Fuse is accepted by Fusion, but crashes when I'm trying to use it. Could anyone give me some feedback please at what I am doing wrong?
Thanks
(Fuses are written in Lua)
--[[
Tone Mapper based on
http://32ipi028l5q82yhj72224m8j.wpengine.netdna-cdn.com/wp-content/uploads/2016/03/GdcVdrLottes.pdf
https://github.com/Opioid/tonemapper/blob/master/tonemapper.py#L14-L42
version 2021 01 05 by Pieter Dumoulin
]]--
FuRegisterClass("ToneMapper", CT_SourceTool, {
REGS_Category = "Fuses",
REGS_Name = "Tone Mapper",
REGS_OpIconString = "TM",
REGS_OpDescription = "Tone Mapper",
REG_OpNoMask = true
})
function Create()
InContrast = self:AddInput("Contrast", "Contrast", {
LINKID_DataType = "Number",
INPID_InputControl = "SliderControl",
INP_MinAllowed = 0,
INP_MaxScale = 5,
INP_Default = 1.2,
})
InShoulder = self:AddInput("Shoulder", "Shoulder", {
LINKID_DataType = "Number",
INPID_InputControl = "SliderControl",
INP_MinAllowed = 0,
INP_MaxScale = 5,
INP_Default = 0.97,
})
InMidIn = self:AddInput("Middle Grey In", "mid_in", {
LINKID_DataType = "Number",
INPID_InputControl = "SliderControl",
INP_MinAllowed = 0,
INP_MaxScale = 1,
INP_Default = 0.4,
})
InMidOut = self:AddInput("Middle Grey Out", "mid_out", {
LINKID_DataType = "Number",
INPID_InputControl = "SliderControl",
INP_MinAllowed = 0,
INP_MaxScale = 1,
INP_Default = 0.18,
})
InHdrMax = self:AddInput("HdrMax", "Hdr_Max", {
LINKID_DataType = "Number",
INPID_InputControl = "SliderControl",
INP_MinAllowed = 0,
INP_MaxScale = 100,
INP_Default = 64,
})
InImage = self:AddInput("Input", "Input", {
LINKID_DataType = "Image",
LINK_Main = 1,
})
OutImage = self:AddOutput("Output", "Output", {
LINKID_DataType = "Image",
LINK_Main = 1,
})
end
function maxrgbfunc()
if p.R == p.G == p.B then return p.G
elseif p.G == math.max(p.R, p.B) then return p.G
elseif p.B == math.max(p.G, p.R) then return p.B
elseif p.R == math.max(p.G, p.B) then return p.R
else return math.max(p.R, math.max(p.G, p.B))
end
function tonemapfunc()
local peak = math.min(maxRGB, self_hdr_max)
local curve = (peak ^ self_a) / (((peak ^ self_a) ^ self_d) * self_b + self_c)
return curve
end
function Process(req)
local img = InImage:GetValue(req)
local a = InContrast:GetValue(req).Value
local d = InShoulder:GetValue(req).Value
local mid_in = InMidIn:GetValue(req).Value
local mid_out = InMidOut:GetValue(req).Value
local hdr_max = InHdrMax:GetValue(req).Value
local ad = a * d
local midi_pow_a = mid_in ^ a
local midi_pow_ad = mid_in ^ ad
local hdrm_pow_a = hdr_max ^ a
local hdrm_pow_ad = hdr_max ^ ad
local u = hdrm_pow_ad * mid_out - midi_pow_ad * mid_out
local v = midi_pow_ad * mid_out
local self_a = a
local self_d = d
local self_b = -((-midi_pow_a + (mid_out * (hdrm_pow_ad * midi_pow_a - hdrm_pow_a * v)) / u) / v)
local self_c = (hdrm_pow_ad * midi_pow_a - hdrm_pow_a * v) / u
local self_hdr_max = hdr_max
local out = Image({IMG_Like = img})
self:DoMultiProcess(nil, { In = img, Out = out, MaxRGB = maxrgb }, img.Height, function (y)
local p = Pixel()
for x=0,In.Width-1 do
In:GetPixel(x,y, p)
maxRGB = maxrgbfunc(x, y, p)
local peak = tonemapfunc(maxRGB, self_hdr_max, self_a, self_d, self_b, self_c, x, y, p)
local ratioR = p.R / maxRGB
local ratioG = p.G / maxRGB
local ratioB = p.B / maxRGB
p.R = peak * ratioR
p.G = peak * ratioG
p.B = peak * ratioB
Out:SetPixel(x,y, p)
end
end)
end
OutImage:Set(req,out)
end

Related

What is the problem with my Gradient Descent Algorithm or how its applied?

I've been trying figure out what I have done wrong for many hours, but just can't figure out. I've even looked at other basic Neural Network libraries to make sure that my gradient descent algorithms were correct, but it still isn't working.
I'm trying to teach it XOR but it outputs -
input (0 0) | 0.011441891321516094
input (1 0) | 0.6558508610135193
input (0 1) | 0.6558003273099053
input (1 1) | 0.6563021185296245
after 1000 trainings, so clearly there's something wrong.
The code is written in lua and I created the Neural Network from raw data so you can easily understand how the data is formatted.
- Training code -
math.randomseed(os.time())
local nn = require("NeuralNetwork")
local network = nn.newFromRawData({
["activationFunction"] = "sigmoid",
["learningRate"] = 0.3,
["net"] = {
[1] = {
[1] = {
["value"] = 0
},
[2] = {
["value"] = 0
}
},
[2] = {
[1] = {
["bias"] = 1,
["netInput"] = 0,
["value"] = 0,
["weights"] = {
[1] = 1,
[2] = 1
}
},
[2] = {
["bias"] = 1,
["netInput"] = 0,
["value"] = 0,
["weights"] = {
[1] = 1,
[2] = 1
}
},
[3] = {
["bias"] = 1,
["netInput"] = 0,
["value"] = 0,
["weights"] = {
[1] = 1,
[2] = 1
}
},
[4] = {
["bias"] = 1,
["netInput"] = 0,
["value"] = 0,
["weights"] = {
[1] = 1,
[2] = 1
}
}
},
[3] = {
[1] = {
["bias"] = 1,
["netInput"] = 0,
["value"] = 0,
["weights"] = {
[1] = 1,
[2] = 1,
[3] = 1,
[4] = 1
}
}
}
}
})
attempts = 1000
for i = 1,attempts do
network:backPropagate({0,0},{0})
network:backPropagate({1,0},{1})
network:backPropagate({0,1},{1})
network:backPropagate({1,1},{0})
end
print("Results:")
print("input (0 0) | "..network:feedForward({0,0})[1])
print("input (1 0) | "..network:feedForward({1,0})[1])
print("input (0 1) | "..network:feedForward({0,1})[1])
print("input (1 1) | "..network:feedForward({1,1})[1])
- Library -
local nn = {}
nn.__index = nn
nn.ActivationFunctions = {
sigmoid = function(x) return 1/(1+math.exp(-x/1)) end,
ReLu = function(x) return math.max(0, x) end,
}
nn.Derivatives = {
sigmoid = function(x) return x * (1 - x) end,
ReLu = function(x) return x > 0 and 1 or 0 end,
}
nn.CostFunctions = {
MSE = function(outputs, expected)
local sum = 0
for i = 1, #outputs do
sum += 1/2*(expected[i] - outputs[i])^2
end
return sum/#outputs
end,
}
function nn.new(inputs, outputs, hiddenLayers, neurons, learningRate, activationFunction)
local self = setmetatable({}, nn)
self.learningRate = learningRate or .3
self.activationFunction = activationFunction or "ReLu"
self.net = {}
local net = self.net
local layers = hiddenLayers+2
for i = 1, layers do
net[i] = {}
end
for i = 1, inputs do
net[1][i] = {value = 0}
end
for i = 2, layers-1 do
for x = 1, neurons do
net[i][x] = {netInput = 0, value = 0, bias = math.random()*2-1, weights = {}}
for z = 1, #net[i-1] do
net[i][x].weights[z] = math.random()*2-1
end
end
end
for i = 1, outputs do
net[layers][i] = {netInput = 0, value = 0, bias = math.random()*2-1, weights = {}}
for z = 1, #net[layers-1] do
net[layers][i].weights[z] = math.random()*2-1
end
end
return self
end
function nn.newFromRawData(data)
return setmetatable(data, nn)
end
function nn:feedForward(inputs)
local net = self.net
local activation = self.activationFunction
local layers = #net
local inputLayer = net[1]
local outputLayer = net[layers]
for i = 1, #inputLayer do
inputLayer[i].value = inputs[i]
end
for i = 2, layers do
local layer = net[i]
for x = 1, #layer do
local sum = layer[x].bias
for z = 1, #net[i-1] do
sum += net[i-1][z].value * layer[x].weights[z]
end
layer[x].netInput = sum
layer[x].value = nn.ActivationFunctions[activation](sum)
end
end
local outputs = {}
for i = 1, #outputLayer do
table.insert(outputs, outputLayer[i].value)
end
return outputs
end
function nn:backPropagate(inputs, expected)
local outputs = self:feedForward(inputs)
local net = self.net
local activation = self.activationFunction
local layers = #net
local lr = self.learningRate
local inputLayer = net[1]
local outputLayer = net[layers]
for i = 1, #outputLayer do
local delta = -(expected[i] - outputs[i]) * nn.Derivatives[activation](net[layers][i].value)
outputLayer[i].delta = delta
end
for i = layers-1, 2, -1 do
local layer = net[i]
local nextLayer = net[i+1]
for x = 1, #layer do
local delta = 0
for z = 1, #nextLayer do
delta += nextLayer[z].delta * nextLayer[z].weights[x]
end
layer[x].delta = delta * nn.Derivatives[activation](layer[x].value)
end
end
for i = 2, layers do
local lastLayer = net[i-1]
for x = 1, #net[i] do
net[i][x].bias -= lr * net[i][x].delta
for z = 1, #lastLayer do
net[i][x].weights[z] -= lr * net[i][x].delta * lastLayer[z].value
end
end
end
end
return nn
Any help would be highly appreciated, thanks!
All initial weights must be DIFFERENT numbers, otherwise backpropagation will not work. For example, you can replace 1 with math.random()
Increase number of attempts to 10000
With these modifications, your code works fine:
Results:
input (0 0) | 0.028138230938126
input (1 0) | 0.97809448578087
input (0 1) | 0.97785000216126
input (1 1) | 0.023128477689456

Why does my LOVE2D program keep resetting the score?

So, I'm currently in a problem with updating my Super Mario Bros. Yeah, sure, it works fine, but the problem is this:
Whenever I touch the flagpole at the end, it literally resets my score.
It makes no sense with this program since I made a params for PlayState:enter, and I don't exactly know why my score goes back to 0.
This shows up in PlayState.lua:
function PlayState:enter(params)
self.score = params.score
self.lastLevelWidth = params.lastLevelWidth
if self.lastLevelWidth == 0 then
self.lastLevelWidth = 100
else
self.lastLevelWidth = self.lastLevelWidth + 50
end
self.camX = 0
self.camY = 0
self.level = LevelMaker.generate(100, 10)
self.tileMap = self.level.tileMap
self.background = math.random(3)
self.backgroundX = 0
self.gravityOn = true
self.gravityAmount = 6
self.player = Player({
x = 0, y = 0,
width = 16, height = 20,
texture = 'green-alien',
stateMachine = StateMachine {
['idle'] = function() return PlayerIdleState(self.player) end,
['walking'] = function() return PlayerWalkingState(self.player) end,
['jump'] = function() return PlayerJumpState(self.player, self.gravityAmount) end,
['falling'] = function() return PlayerFallingState(self.player, self.gravityAmount) end
},
map = self.tileMap,
level = self.level,
})
self:spawnEnemies()
self.player:changeState('falling')
end
I used the params to get to a new score, 0, but I don't want it to let it stay like that. This is what I have done in LevelMaker.lua:
keyCollected = false
function LevelMaker.generate(width, height)
local tiles = {}
local entities = {}
local objects = {}
local tileID = TILE_ID_GROUND
-- whether we should draw our tiles with toppers
local topper = true
local tileset = math.random(20)
local topperset = math.random(20)
-- insert blank tables into tiles for later access
for x = 1, height do
table.insert(tiles, {})
end
-- make positions for the lock box and key in the level
local lockBoxPosition = math.random(1, width)
local keyPosition = math.random(1, width)
local keySkin = math.random(1, 4)
-- column by column generation instead of row; sometimes better for platformers
for x = 1, width do
local tileID = TILE_ID_EMPTY
-- lay out the empty space
for y = 1, 6 do
table.insert(tiles[y],
Tile(x, y, tileID, nil, tileset, topperset))
end
-- chance to just be emptiness
if math.random(7) == 1 and x ~= 1 and lockBoxPosition ~= x and keyPosition ~= x then
for y = 7, height do
table.insert(tiles[y],
Tile(x, y, tileID, nil, tileset, topperset))
end
else
tileID = TILE_ID_GROUND
local blockHeight = 4
for y = 7, height do
table.insert(tiles[y],
Tile(x, y, tileID, y == 7 and topper or nil, tileset, topperset))
end
-- chance to generate a pillar
if math.random(8) == 1 then
blockHeight = 2
-- chance to generate bush on pillar
if math.random(8) == 1 then
table.insert(objects,
GameObject {
texture = 'bushes',
x = (x - 1) * TILE_SIZE,
y = (4 - 1) * TILE_SIZE,
width = 16,
height = 16,
-- select random frame from bush_ids whitelist, then random row for variance
frame = BUSH_IDS[math.random(#BUSH_IDS)] + (math.random(4) - 1) * 7
}
)
end
-- pillar tiles
tiles[5][x] = Tile(x, 5, tileID, topper, tileset, topperset)
tiles[6][x] = Tile(x, 6, tileID, nil, tileset, topperset)
tiles[7][x].topper = nil
-- chance to generate bushes
elseif math.random(8) == 1 and keyPosition ~= 1 then
table.insert(objects,
GameObject {
texture = 'bushes',
x = (x - 1) * TILE_SIZE,
y = (6 - 1) * TILE_SIZE,
width = 16,
height = 16,
frame = BUSH_IDS[math.random(#BUSH_IDS)] + (math.random(4) - 1) * 7,
collidable = false
}
)
end
if x == keyPosition then
table.insert(objects,
GameObject {
texture = 'keys-and-locks',
x = (x - 1) * TILE_SIZE,
y = (blockHeight + 1) * TILE_SIZE,
width = 16,
height = 16,
frame = keySkin,
collidable = true,
consumable = true,
solid = false,
onConsume = function(player, object)
gSounds['pickup']:play()
player.score = player.score + 500
keyCollected = true
end
}
)
end
if x == lockBoxPosition then
table.insert(objects,
GameObject {
texture = 'keys-and-locks',
x = (x - 1) * TILE_SIZE,
y = (blockHeight - 1) * TILE_SIZE,
width = 16,
height = 16,
frame = keySkin + 4,
collidable = true,
consumable = true,
hit = false,
solid = true,
lockedBox = false,
objectRemove = false,
onCollide = function(obj)
if not obj.hit then
if keyCollected then
gSounds['pickup']:play()
obj.hit = true
obj.objectRemove = true
obj.consumable = true
local pole = GameObject {
texture = 'poles',
x = (width * TILE_SIZE) - 32,
y = (blockHeight - 1) * TILE_SIZE,
width = 16,
height = 48,
frame = math.random(#POLES),
collidable = true,
consumable = true,
solid = false,
onConsume = function(player, object)
gSounds['pickup']:play()
player.score = player.score + 1000
gStateMachine:change('play', {
score = player.score,
lastLevelWidth = width
})
end
}
local flag = GameObject {
texture = 'flags',
x = (width * TILE_SIZE) - 32 + 6,
y = blockHeight * TILE_SIZE,
width = 16,
height = 10,
frame = 1,
collidable = true,
consumable = true,
solid = false,
onConsume = function(player, object)
gSounds['pickup']:play()
player.score = player.score + 1000
gStateMachine:change('play', {
score = player.score,
lastLevelWidth = width
})
end
}
Timer.tween(2.0 , {
[flag] = {y = ((blockHeight - 1) * TILE_SIZE) + 4}
})
gSounds['powerup-reveal']:play()
table.insert(objects, pole)
table.insert(objects, flag)
end
keyCollected = false
end
gSounds['empty-block']:play()
end
}
)
-- chance to spawn a block
elseif math.random(10) == 1 then
table.insert(objects,
-- jump block
GameObject {
texture = 'jump-blocks',
x = (x - 1) * TILE_SIZE,
y = (blockHeight - 1) * TILE_SIZE,
width = 16,
height = 16,
-- make it a random variant
frame = math.random(#JUMP_BLOCKS),
collidable = true,
hit = false,
solid = true,
-- collision function takes itself
onCollide = function(obj)
-- spawn a gem if we haven't already hit the block
if not obj.hit then
-- chance to spawn gem, not guaranteed
if math.random(5) == 1 then
-- maintain reference so we can set it to nil
local gem = GameObject {
texture = 'gems',
x = (x - 1) * TILE_SIZE,
y = (blockHeight - 1) * TILE_SIZE - 4,
width = 16,
height = 16,
frame = math.random(#GEMS),
collidable = true,
consumable = true,
solid = false,
-- gem has its own function to add to the player's score
onConsume = function(player, object)
gSounds['pickup']:play()
player.score = player.score + 100
end
}
-- make the gem move up from the block and play a sound
Timer.tween(0.1, {
[gem] = {y = (blockHeight - 2) * TILE_SIZE}
})
gSounds['powerup-reveal']:play()
table.insert(objects, gem)
end
obj.hit = true
end
gSounds['empty-block']:play()
end
}
)
end
end
end
local map = TileMap(width, height)
map.tiles = tiles
return GameLevel(entities, objects, map)
end
What's supposed to happen is that when I collected the key and unlocked the lock block, I get a flag, and when I collide with the flag at the end of the map, I get to a new level, with the same score, but not 0. Sadly, everytime I get to a new level, it turns into 0.
I don't know if the problem is in StartState.lua:
function StartState:update(dt)
if love.keyboard.wasPressed('enter') or love.keyboard.wasPressed('return') then
gStateMachine:change('play', {
score = 0,
lastLevelWidth = 0
})
end
end
Any ideas why it's like this?
If you collide with the pole and then change to StartState, then that is the problem. I suggest feeding the score through start with: function StartState:enter(params) self.score = params.score end
Then just pass self.score through to the playstate

Why does unequipping this tool relocates the player to the center of the map in Roblox?

This gear was inserted from the Catalog. It relocates the player to the center of the map when it's unequipped by clicking on the thumbnail. At 1st, I tested in a game I made. Everytime I unequipped it, the player kept falling through the baseplate and dying. I noticed it is the same position over and over. I moved the baseplate's position lower and the player falls down onto the baseplate instead of dying. Then I tested the gear in a new empty baseplate, unequipping it, the player moves to the center, too. I check the position of the both the Handle and the player's Torso, but that axis does not match any position in the script. Can someone point this out for me so that I can change it to the last position that the player stops?
Tool = script.Parent
Handle = Tool:WaitForChild("Handle")
Players = game:GetService("Players")
Debris = game:GetService("Debris")
Assets = require(Tool:WaitForChild("Assets"))
Data = Assets.Data
BaseUrl = Assets.BaseUrl
BasePart = Instance.new("Part")
BasePart.Material = Enum.Material.Plastic
BasePart.Shape = Enum.PartType.Block
BasePart.TopSurface = Enum.SurfaceType.Smooth
BasePart.BottomSurface = Enum.SurfaceType.Smooth
BasePart.FormFactor = Enum.FormFactor.Custom
BasePart.Size = Vector3.new(0.2, 0.2, 0.2)
BasePart.Anchored = false
BasePart.CanCollide = true
BasePart.Locked = true
Animations = {
Hold = {Animation = Tool:WaitForChild("Hold"), FadeTime = nil, Weight = nil, Speed = nil}
}
Sounds = {
Honk = Handle:WaitForChild("Honk"),
Engine = Handle:WaitForChild("Running")
}
Controls = {
Forward = {Key = "w", ByteKey = 17, Mode = false},
Backward = {Key = "s", ByteKey = 18, Mode = false},
Left = {Key = "a", ByteKey = 20, Mode = false},
Right = {Key = "d", ByteKey = 19, Mode = false}
}
Rate = (1 / 60)
Gravity = 196.20
PoseOffset = CFrame.new(0, -1.5125, -0.3) * CFrame.Angles(0, 0, 0) --The offset your character is from the center of the vehicle.
SpeedBoost = {
Allowed = false,
Active = false,
Enabled = true,
Duration = 10,
ReloadTime = 30
}
Special = {
Allowed = false,
Enabled = true,
Active = false,
Duration = 0,
ReloadTime = 60
}
Speed = {
Acceleration = {
Normal = 30,
Boost = 30
},
Deceleration = {
Normal = 30,
Boost = 30
},
MovementSpeed = {
Normal = {Min = 20, Max = 70},
Boost = {Min = 20, Max = 70}
},
TurnSpeed = {
Speed = {Min = 5, Max = 5},
TurnAlpha = 0.30,
AlphaDampening = 0.2
},
}
MaxSpeed = { --Maximum speed which the vehicle can move and turn at.
Movement = Speed.MovementSpeed.Normal,
Turn = Speed.TurnSpeed.Speed,
Acceleration = Speed.Acceleration.Normal,
Deceleration = Speed.Deceleration.Normal
}
CurrentSpeed = { --The speed which the vehicle is moving and turning at.
Movement = 0,
Turn = 0
}
Honk = {
Honking = false,
LastHonk = 0,
ReloadTime = 1
}
Jump = {
Jumping = false,
LastJump = 0,
ReloadTime = 1.25,
JumpForce = 30
}
ToolEquipped = false
ServerControl = (Tool:FindFirstChild("ServerControl") or Instance.new("RemoteFunction"))
ServerControl.Name = "ServerControl"
ServerControl.Parent = Tool
ClientControl = (Tool:FindFirstChild("ClientControl") or Instance.new("RemoteFunction"))
ClientControl.Name = "ClientControl"
ClientControl.Parent = Tool
Tool.Enabled = true
function RayCast(Position, Direction, MaxDistance, IgnoreList)
local IgnoreList = ((type(IgnoreList) == "table" and IgnoreList) or {IgnoreList})
return game:GetService("Workspace"):FindPartOnRayWithIgnoreList(Ray.new(Position, Direction.unit * (MaxDistance or 999.999)), IgnoreList)
end
function GetAllConnectedParts(Object)
local Parts = {}
local function GetConnectedParts(Object)
for i, v in pairs(Object:GetConnectedParts()) do
local Ignore = false
for ii, vv in pairs(Parts) do
if v == vv then
Ignore = true
end
end
if not Ignore then
table.insert(Parts, v)
GetConnectedParts(v)
end
end
end
GetConnectedParts(Object)
return Parts
end
function EnableFirstPersonView()
if not CheckIfAlive() or not ToolEquipped then
return
end
local Limbs = {"LeftHand", "RightHand"}
for i, v in pairs(Limbs) do
local Limb = Character:FindFirstChild(v)
if Limb:IsA("BasePart") then
Spawn(function()
InvokeClient("SetLocalTransparencyModifier", {Object = Limb, Transparency = 0, AutoUpdate = false})
end)
end
end
end
function ThrustUpdater()
for i, v in pairs(CurrentSpeed) do
CurrentSpeed[i] = 0
end
for i, v in pairs(Controls) do
Controls[i].Mode = false
end
while ToolEquipped and Body and Body.Parent and CheckIfAlive() and RotationForce and RotationForce.Parent and ThrustForce and ThrustForce.Parent and TurnGyro and TurnGyro.Parent do
RotationForce.angularvelocity = Vector3.new(0, CurrentSpeed.Turn, 0)
if math.abs(CurrentSpeed.Turn) > Speed.TurnSpeed.AlphaDampening then
CurrentSpeed.Turn = (CurrentSpeed.Turn - (Speed.TurnSpeed.AlphaDampening * (math.abs(CurrentSpeed.Turn) / CurrentSpeed.Turn)))
else
CurrentSpeed.Turn = 0
end
if not Controls.Forward.Mode or Controls.Backward.Mode then --Slow down if not controlling.
CurrentSpeed.Movement = (CurrentSpeed.Movement * 0.99)
end
local MySpeed = Vector3.new(Body.Velocity.X, 0, Body.Velocity.Z).magnitude
local VelocityDifference = math.abs((MySpeed - (ThrustForce.velocity.magnitude)))
if MySpeed > 3 and ThrustForce.velocity.magnitude > 3 and VelocityDifference > (0.7 * ThrustForce.velocity.magnitude) then
CurrentSpeed.Movement = (CurrentSpeed.Movement * 0.9)
end
if Controls.Forward.Mode then --Handle acceleration
CurrentSpeed.Movement = math.min(MaxSpeed.Movement.Max, (CurrentSpeed.Movement + (MaxSpeed.Acceleration * Rate)))
end
if Controls.Backward.Mode then --Handle deceleration, if speed is more than 0, decrease quicker.
CurrentSpeed.Movement = math.max(-MaxSpeed.Movement.Min, (CurrentSpeed.Movement - (MaxSpeed.Deceleration * ((CurrentSpeed.Movement > 0 and 2.8) or 1) * Rate)))
end
if Controls.Left.Mode then --Handle left turn speed
CurrentSpeed.Turn = math.min(Speed.TurnSpeed.Speed.Max, (CurrentSpeed.Turn + (Speed.TurnSpeed.TurnAlpha)))
end
if Controls.Right.Mode then --Handle right turn speed
CurrentSpeed.Turn = math.max(-Speed.TurnSpeed.Speed.Min, (CurrentSpeed.Turn - (Speed.TurnSpeed.TurnAlpha)))
end
local Direction = UpperTorso.CFrame.lookVector
Direction = Vector3.new(Direction.x, 0, Direction.z).unit
local Velocity = (Direction * CurrentSpeed.Movement) --The thrust force which you move.
ThrustForce.velocity = Vector3.new(Velocity.X, ThrustForce.velocity.Y, Velocity.Z)
local LeanAmount = (-CurrentSpeed.Turn * (math.pi / 6) / 4) --Amount your character leans over.
local XZAngle = math.atan2(UpperTorso.CFrame.lookVector.z, 0, UpperTorso.CFrame.lookVector.x) --Handle rotation
TurnGyro.cframe = CFrame.Angles((LeanAmount * Direction.x), 0, (LeanAmount * Direction.z))
--Wheel animation
local DesiredAngle = (999999999 * (-CurrentSpeed.Movement / math.abs(CurrentSpeed.Movement)))
local MaxVelocity = (CurrentSpeed.Movement / 250)
for i, v in pairs({FrontMotor, BackMotor}) do
if v and v.Parent then
v.DesiredAngle = DesiredAngle
v.MaxVelocity = MaxVelocity
end
end
--Smoke exhaust from vehicle running.
for i, v in pairs(ExhaustSmoke) do
if v and v.Parent then
v.Opacity = ((math.min(math.abs(CurrentSpeed.Movement), 10) / 10) * 0.5)
end
end
--Engine running sound which pitch changes while in motion.
Sounds.Engine.Pitch = (1 + (math.abs(CurrentSpeed.Movement / MaxSpeed.Movement.Max) * 1))
wait(Rate)
end
end
function SpawnVehicle()
Handle.Transparency = 1
Spawn(function()
InvokeClient("PlaySound", Sounds.Engine)
InvokeClient("PlayAnimation", Animations.Hold)
end)
Humanoid.PlatformStand = true
local VehicleData = Assets.CreateVehicle()
Body = VehicleData.Vehicle
local ParticleTable = VehicleData.Tables
--FrontMotor = Body.FrontMotor
--BackMotor = Body.BackMotor
ExhaustSmoke = ParticleTable.ExhaustSmoke
Lights = ParticleTable.Lights
Sparkles = ParticleTable.Sparkles
if SpeedBoost.Active then
for i, v in pairs(Sparkles) do
if v and v.Parent then
v.Enabled = true
end
end
end
local UpperTorsoWeld = Instance.new("Weld")
UpperTorsoWeld.C0 = PoseOffset
UpperTorsoWeld.Part0 = UpperTorso
UpperTorsoWeld.Part1 = Body
UpperTorsoWeld.Parent = Body
Body.CanCollide = true
RotationForce = Instance.new("BodyAngularVelocity")
RotationForce.maxTorque = Vector3.new(0, math.huge, 0)
RotationForce.angularvelocity = Vector3.new(0, 0, 0)
RotationForce.Parent = UpperTorso
ThrustForce = Instance.new("BodyVelocity")
ThrustForce.maxForce = Vector3.new(math.huge, 0, math.huge)
ThrustForce.velocity = Vector3.new(0, 0, 0)
ThrustForce.P = 100
ThrustForce.Parent = UpperTorso
TurnGyro = Instance.new("BodyGyro")
TurnGyro.maxTorque = Vector3.new(5000, 0, 5000)
TurnGyro.P = 300
TurnGyro.D = 100
TurnGyro.Parent = UpperTorso
Body.Parent = Tool
local RayHit, RayPos, RayNormal = RayCast(UpperTorso.Position, Vector3.new(0, -1, 0), (UpperTorso.Size.Y * 2), {Character})
if RayHit then
UpperTorso.CFrame = UpperTorso.CFrame + Vector3.new(0, ((Character:GetModelSize().Y / 2) + 1.5), 0)
end
Spawn(ThrustUpdater)
end
function FreezePlayer()
if CheckIfAlive() then
local FreezePart = BasePart:Clone()
FreezePart.Name = "FreezePart"
FreezePart.Transparency = 1
FreezePart.Anchored = true
FreezePart.CanCollide = false
local FreezeWeld = Instance.new("Weld")
FreezeWeld.Part0 = UpperTorso
FreezeWeld.Part1 = FreezePart
FreezeWeld.Parent = FreezePart
Debris:AddItem(FreezePart, 0.125)
FreezePart.Parent = Character
UpperTorso.Velocity = Vector3.new(0, -25, 0)
UpperTorso.RotVelocity = Vector3.new(0, 0, 0)
end
end
function CleanUp()
Handle.Velocity = Vector3.new(0, 0, 0)
Handle.RotVelocity = Vector3.new(0, 0, 0)
for i, v in pairs({}) do
if v then
v:disconnect()
end
end
for i, v in pairs({Body, RotationForce, ThrustForce, TurnGyro}) do
if v and v.Parent then
v:Destroy()
end
end
for i, v in pairs(Tool:GetChildren()) do
if v:IsA("BasePart") and v ~= Handle then
v:Destroy()
end
end
end
function CheckIfAlive()
return (((Character and Character.Parent and Humanoid and Humanoid.Parent and Humanoid.Health > 0 and UpperTorso and UpperTorso.Parent and Player and Player.Parent) and true) or false)
end
function Equipped(Mouse)
Character = Tool.Parent
Player = Players:GetPlayerFromCharacter(Character)
Humanoid = Character:FindFirstChild("Humanoid")
UpperTorso = Character:FindFirstChild("UpperTorso")
if not CheckIfAlive() then
return
end
Spawn(CleanUp)
Spawn(EnableFirstPersonView)
Spawn(SpawnVehicle)
ToolEquipped = true
end
function Unequipped()
Spawn(CleanUp)
Spawn(FreezePlayer)
for i, v in pairs(Sounds) do
v:Stop()
Spawn(function()
InvokeClient("StopSound", v)
end)
end
if CheckIfAlive() then
Humanoid.PlatformStand = false
end
Handle.Transparency = 0
ToolEquipped = false
end
function OnServerInvoke(player, mode, value)
if player == Player and ToolEquipped and value and CheckIfAlive() then
if mode == "KeyPress" then
local Down = value.Down
local Key = value.Key
local ByteKey = string.byte(Key)
for i, v in pairs(Controls) do
if Key == v.Key or ByteKey == v.ByteKey then
Controls[i].Mode = Down
end
end
if Key == " " and Down then --Jump controller
if math.abs(tick() - Jump.LastJump) > Jump.ReloadTime and not Jump.Jumping and ThrustForce and ThrustForce.Parent then
Jump.Jumping = true
local Parts = GetAllConnectedParts(Body)
local Mass = 0
for i, v in pairs(Parts) do
Mass = (Mass + v:GetMass())
end
ThrustForce.maxForce = Vector3.new(ThrustForce.maxForce.X, ((Mass * Gravity) * 100), ThrustForce.maxForce.Z)
ThrustForce.velocity = (Vector3.new(0, 1, 0) * Jump.JumpForce) + Vector3.new(ThrustForce.velocity.X, 0, ThrustForce.velocity.Z)
wait(0.1)
ThrustForce.maxForce = Vector3.new(ThrustForce.maxForce.X, 0, ThrustForce.maxForce.Z)
ThrustForce.velocity = Vector3.new(ThrustForce.velocity.X, 0, ThrustForce.velocity.Z)
Jump.LastJump = tick()
Jump.Jumping = false
end
elseif Key == "x" and Down then --Toggle light(s) on/off.
for i, v in pairs(Lights) do
if v and v.Parent then
v.Enabled = not v.Enabled
end
end
elseif Key == "h" and Down then --Play honk sound.
local Sound = Sounds.Honk
if (tick() - Honk.LastHonk) >= (Sound.TimeLength + Honk.ReloadTime) and not Honk.Honking then
Honk.Honking = true
local TempSound = Sound:Clone()
Debris:AddItem(TempSound, Sound.TimeLength)
TempSound.Parent = Body
TempSound:Play()
Honk.LastHonk = tick()
Honk.Honking = false
end
elseif Key == "q" and Down then --Activate special.
if not Special.Allowed or not Special.Enabled or Special.Active then
return
end
Special.Enabled = false
Special.Active = true
wait(Special.Duration)
Special.Active = false
wait(Special.ReloadTime)
Special.Enabled = true
elseif ByteKey == 48 and Down then --Activate speed boost.
if not SpeedBoost.Allowed or not SpeedBoost.Enabled or SpeedBoost.Active then
return
end
SpeedBoost.Enabled = false
SpeedBoost.Active = true
for i, v in pairs(Sparkles) do
if v and v.Parent then
v.Enabled = true
end
end
MaxSpeed.Acceleration = Speed.Acceleration.Boost
MaxSpeed.Deceleration = Speed.Deceleration.Boost
MaxSpeed.Movement = Speed.MovementSpeed.Boost
wait(SpeedBoost.Duration)
MaxSpeed.Acceleration = Speed.Acceleration.Normal
MaxSpeed.Deceleration = Speed.Deceleration.Normal
MaxSpeed.Movement = Speed.MovementSpeed.Normal
for i, v in pairs(Sparkles) do
if v and v.Parent then
v.Enabled = false
end
end
SpeedBoost.Active = false
wait(SpeedBoost.ReloadTime)
SpeedBoost.Enabled = true
end
end
end
end
function InvokeClient(Mode, Value)
local ClientReturn = nil
pcall(function()
ClientReturn = ClientControl:InvokeClient(Player, Mode, Value)
end)
return ClientReturn
end
Spawn(CleanUp)
ServerControl.OnServerInvoke = OnServerInvoke
Tool.Equipped:connect(Equipped)
Tool.Unequipped:connect(Unequipped)
I found it. Freezingplayer is the culprit. I took out "Spawn(FreezePlayer)" when it is unequipped and it works.
function Unequipped()
Spawn(CleanUp)
---Spawn(FreezePlayer)

Strange LUA Error While Scripting Garry's Mod SWEP

I am currently working on a Garry's Mod SWEP for my friends server. I have been troubleshooting for about 8 hours, when i got this strange error:
line 13: attempt to index global 'SWEP' (a nil value)
stack traceback:
t.lua:13: in main chunk
[C]: ?
not sure what it means, as i am fairly new to LUA.
Here is my whole script (also at codepad):
if SERVER then
SWEP.Weight = 30
SWEP.AutoSwitchTo = true
SWEP.AutoSwitchFrom = true
end
if CLIENT then
SWEP.PrintName = "Bill Nye's Test Weapon"
SWEP.Slot = 4
SWEP.SlotPos = 1
end
SWEP.Base = "weapon_base" -- line 13
SWEP.Category = "Bill Nye's Admin Weapons"
SWEP.Author = "Bill Nye The Russian Spy"
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.ViewModelFlip = true
SWEP.HoldType = "ar2"
SWEP.ViewModel =
{["element_name2"] = { type = "Model", model = "models/XQM/cylinderx2.mdl", bone = "v_weapon.AK47_Parent", rel = "", pos = Vector(0.027, 4.118, 0.518), angle = Angle(-90.025, -4.764, -0.364), size = Vector(0.167, 0.167, 0.167), color = Color(90, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} },
["element_name4"] = { type = "Model", model = "models/props_lab/huladoll.mdl", bone = "v_weapon.AK47_Parent", rel = "", pos = Vector(-0.89, 3.947, 1.452), angle = Angle(-86.752, -1.621, -180), size = Vector(0.273, 0.273, 0.273), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} },
["element_name3"] = { type = "Model", model = "models/props_phx/construct/glass/glass_plate1x1.mdl", bone = "v_weapon.AK47_Parent", rel = "", pos = Vector(0.017, 6.109, 2.431), angle = Angle(0, 0, 0), size = Vector(0.041, 0.041, 0.041), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 3, bodygroup = {} },
["element_name"] = { type = "Model", model = "models/sprops/misc/alphanum/alphanum_plu.mdl", bone = "v_weapon.AK47_Parent", rel = "", pos = Vector(0.067, 6.19, 2.417), angle = Angle(0, -1.17, 87.662), size = Vector(0.107, 0.107, 0.107), color = Color(255, 0, 0, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {}}
}
SWEP.WorldModel =
{["element_name2"] = { type = "Model", model = "models/XQM/cylinderx2.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(4.316, 0.736, -4.292), angle = Angle(0, 0, 0), size = Vector(0.167, 0.167, 0.167), color = Color(90, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} },
["element_name4"] = { type = "Model", model = "models/props_lab/huladoll.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(4.987, 0.634, -5.249), angle = Angle(180, 17.653, 0), size = Vector(0.273, 0.273, 0.273), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} },
["element_name3"] = { type = "Model", model = "models/props_phx/construct/glass/glass_plate1x1.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(12.293, 0.656, -7.63), angle = Angle(88.204, 1.24, 1.22), size = Vector(0.041, 0.041, 0.041), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 3, bodygroup = {} },
["element_name"] = { type = "Model", model = "models/sprops/misc/alphanum/alphanum_plu.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(12.619, 0.646, -7.801), angle = Angle(0, 89.783, 0.244), size = Vector(0.107, 0.107, 0.107), color = Color(255, 0, 0, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {}}
}
SWEP.Primary.Recoil = 0.00
SWEP.Primary.Damage = 1000
SWEP.Primary.NumShots = 1
SWEP.Primary.Spread = 0
SWEP.Primary.Cone = 0
SWEP.Primary.ClipSize = 27
SWEP.Primary.DefaultClip = 100
SWEP.Primary.Ammo = "ar2"
SWEP.Primary.Automatic = true
SWEP.Primary.Delay = 0.1
SWEP.IronSightsPos = Vector(6.099, -13.468, 2.612)
SWEP.IronSightsAng = Vector(3.517, 0, -0)
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = true
SWEP.Secondary.Ammo = "none"
function SWEP:Initialize()
self:SetWeaponHoldType(self.HoldType)
end
function SWEP:PrimaryAttack()
if (self:CanPrimaryAttack()) then
return
end
local Bullet = {}
Bullet.Num = self.Primary.NumShots
Bullet.Src = self.Owner:GetShootPos ()
Bullet.Dir = self.Owner:GetAimVector ()
Bullet.Spread = Vector(self.Primary.Spread, self.Primary.Spread,0)
Bullet.Tracer = 0
Bullet.Damage = self.Primary.Damage
Bullet.AmmoType = self.Primary.Ammo
self:ShootEffects()
self:FireBullets(Bullet)
self:EmitSound ("Weapon_IRifle.Single")
self:TakePrimaryAmmo ( 1 )
self:SetNextPrimaryFire(CurTime() + self.Primary.Delay)
end
function SWEP:SecondaryAttack()
return false
end
It means:
in your t.lua file on line 13 you point to SWEP value, which is a null value.
Did you call: SWEP:initialize()?
function SWEP:Initialize()
self:SetWeaponHoldType(self.HoldType)
end
check if your value is "local" or if your SWEP value has been initialized.
also check if you remove it before like this: SWEP = nil or not.

how to get array value in lua in not using id

i have this array in my lua...
local data = {}
data[1] = {}
data[1].title = "Crazy Song"
data[1].subtitle = "by Bruno Earth"
data[1].image = "note.png"
data[2] = {}
data[2].title = "Enter Sunman"
data[2].subtitle = "by Mentalica"
data[2].image = "note.png"
data[3] = {}
data[3].title = "Bitter Child of Mine"
data[3].subtitle = "by Gunz n bullets"
data[3].image = "note.png"
data[4] = {}
data[4].title = "Missed A thing"
data[4].subtitle = "by Ero-Smith"
data[4].image = "note.png"
data[5] = {}
data[5].title = "Pornstar"
data[5].subtitle = "by Nicklefront"
data[5].image = "note.png"
data[6] = {}
data[6].title = "Burner"
data[6].subtitle = "by Asher"
data[6].image = "note.png"
how can i get the array values by not using id on it. i just want to get the title for my conditional statement?
i try this in my code:
local getTitle = function(event)
print (".................")
print (event.target.id)
print (event.target.title)
end
but i got only this...
touch: began
touch: ended
.................
2
nil
how can i get and print the title of my array?
this is my code:
module(..., package.seeall)
display.setStatusBar( display.HiddenStatusBar )
function new()
local localGroup = display.newGroup()
local tableView = require("tableView")
local ui = require("ui")
--------------------------------------------------------------------------
local screenOffsetW, screenOffsetH = display.contentWidth - display.viewableContentWidth, display.contentHeight - display.viewableContentHeight
local songList
local backBtn
local detailScreenText
local background = display.newRect(0, 0, display.contentWidth, display.contentHeight)
background:setFillColor(0, 0, 0)
localGroup:insert(background)
local data = {}
--iPad: setup a color fill for selected items
local selected = display.newRect(0, 0, 50, 50) --add acolor fill to show the selected item
selected:setFillColor(67,141,241,180) --set the color fill to light blue
selected.isVisible = false --hide color fill until neede
-----------------------------------------------
data[1] = {}
data[1].title = "Crazy Song"
data[1].subtitle = "by Bruno Earth"
data[1].image = "note.png"
data[2] = {}
data[2].title = "Enter Sunman"
data[2].subtitle = "by Mentalica"
data[2].image = "note.png"
data[3] = {}
data[3].title = "Bitter Child of Mine"
data[3].subtitle = "by Gunz n bullets"
data[3].image = "note.png"
data[4] = {}
data[4].title = "Missed A thing"
data[4].subtitle = "by Ero-Smith"
data[4].image = "note.png"
data[5] = {}
data[5].title = "Pornstar"
data[5].subtitle = "by Nicklefront"
data[5].image = "note.png"
data[6] = {}
data[6].title = "Burner"
data[6].subtitle = "by Asher"
data[6].image = "note.png"
local topBoundary = display.screenOriginY + 40
local bottomBoundary = display.screenOriginY + 0
local getTitle = function(event)
print (".................")
print (event.target.id)
print (event.target.title)
end
songList = tableView.newList{
data=data,
default="listItemBg.png",
over="listItemBg_over.png",
onRelease=getTitle,
top=topBoundary,
bottom=bottomBoundary,
callback = function( row )
local g = display.newGroup()
local img = display.newImage(row.image)
g:insert(img)
img.x = math.floor(img.width*0.5 + 6)
img.y = math.floor(img.height*0.5)
local title = display.newText( row.title, 0, 0, native.systemFontBold, 16 )
title:setTextColor(0,0,0)
g:insert(title)
title.x = title.width*0.5 + img.width + 6
title.y = 30
local subtitle = display.newText( row.subtitle, 0, 0, native.systemFont, 14 )
subtitle:setTextColor(80,80,90)
g:insert(subtitle)
subtitle.x = subtitle.width*0.5 + img.width + 6
subtitle.y = title.y + title.height + 6
return g
end
}
localGroup:insert(songList)
local function scrollToTop()
songList:scrollTo(topBoundary-1)
end
local navBar = display.newImage("navBar.png")
navBar.x = display.contentWidth*.5
navBar.y = math.floor(display.screenOriginY + navBar.height*0.5)
localGroup:insert(navBar)
local navHeader = display.newText("Song Lists", 0, 0, native.systemFontBold, 16)
navHeader:setTextColor(255, 255, 255)
navHeader.x = display.contentWidth*.5
navHeader.y = navBar.y
localGroup:insert(navHeader)
--backBtn.alpha = 0
local listBackground = display.newRect( 0, 0, songList.width, songList.height )
listBackground:setFillColor(255,255,255)
songList:insert(1,listBackground)
--Setup the back button
function changeScene(e)
if e.phase == 'ended' then
print ("ok")
director:changeScene(e.target.scene, "fade")
print ("back!")
end
end
backBtn = display.newImage("backButton.png")
backBtn.x = math.floor(backBtn.width/2) + backBtn.width + screenOffsetW
backBtn.y = navBar.y
backBtn.scene = "menu"
backBtn:addEventListener("touch", changeScene)
return localGroup
end
i got it...
i do this
local getTitle = function(event)
print (".................")
local id = event.target.id
print (id)
print (data[id].title)
end

Resources