Untitled conversation
- Userlua
- Assistant
-- Server-side constants and settings
if SERVER then
local SANITY_MAX = 100
local JUMPSCARE_COOLDOWN = 30
local HALLUCINATION_INTERVAL = 10
-- Define network strings
util.AddNetworkString("FearOfDark_UpdateDarkness")
util.AddNetworkString("FearOfDark_StageChange")
util.AddNetworkString("FearOfDark_ParanoiaMessage")
util.AddNetworkString("FearOfDark_JumpScare")
-- Initialize player sanity and related variables
local function InitializePlayer(ply)
ply.Sanity = SANITY_MAX
ply:SetNWFloat("Sanity", SANITY_MAX)
ply.LastSanityStage = 5
ply.InDarkness = false
ply.LastJumpScareTime = 0
end
hook.Add("PlayerInitialSpawn", "FearOfDark_InitSanity", InitializePlayer)
-- Update player sanity based on darkness state
local function UpdateSanity(ply)
if not ply:Alive() then return end
local sanity = ply:GetNWFloat("Sanity", SANITY_MAX)
local delta = FrameTime()
if ply.InDarkness then
local loss = ply:FlashlightIsOn() and 0.5 or 1
sanity = math.max(sanity - loss * delta, 0)
else
sanity = math.min(sanity + 0.5 * delta, SANITY_MAX)
end
ply:SetNWFloat("Sanity", sanity)
local new_stage = math.ceil(sanity / 20)
if new_stage ~= ply.LastSanityStage then
ply.LastSanityStage = new_stage
net.Start("FearOfDark_StageChange")
net.WriteUInt(new_stage, 3)
net.Send(ply)
end
end
-- Trigger jumpscares for low sanity players
local function TryJumpscare(ply)
local sanity = ply:GetNWFloat("Sanity", SANITY_MAX)
if sanity >= 10 then return end
if CurTime() - ply.LastJumpScareTime < JUMPSCARE_COOLDOWN then return end
if math.random() > 0.005 then return end
ply.LastJumpScareTime = CurTime()
net.Start("FearOfDark_JumpScare")
net.Send(ply)
end
-- Play hallucination sounds and send paranoia messages
local HALLUCINATION_SOUNDS = {
{sound = "ambient/levels/canals/windchime2.wav", pitch = 90, volume = 0.8},
{sound = "npc/footsteps/hardboot_generic1.wav", pitch = 80, volume = 0.8},
{sound = "npc/footsteps/hardboot_generic2.wav", pitch = 80, volume = 0.8}
}
local function PlayHallucinations()
for _, ply in ipairs(player.GetAll()) do
if not ply:Alive() or ply:GetNWFloat("Sanity", SANITY_MAX) >= 40 then continue end
local pos = ply:GetPos() + VectorRand() * 200
local sound_data = HALLUCINATION_SOUNDS[math.random(#HALLUCINATION_SOUNDS)]
sound.Play(sound_data.sound, pos, 75, sound_data.pitch, sound_data.volume)
if ply:GetNWFloat("Sanity", SANITY_MAX) < 20 then
net.Start("FearOfDark_ParanoiaMessage")
net.WriteString("Something is watching you...")
net.Send(ply)
end
end
end
timer.Create("FearOfDark_HallucinationTimer", HALLUCINATION_INTERVAL, 0, PlayHallucinations)
-- Main server loop
hook.Add("Think", "FearOfDark_SanitySystem", function()
for _, ply in ipairs(player.GetAll()) do
UpdateSanity(ply)
TryJumpscare(ply)
end
end)
-- Receive darkness state from client
net.Receive("FearOfDark_UpdateDarkness", function(_, ply)
ply.InDarkness = net.ReadBool()
end)
end
-- Client-side constants and variables
if CLIENT then
local SANITY_MAX = 100
local JUMPSCARE_COOLDOWN = 30
local DARKNESS_CHECK_INTERVAL = 1
local DEFAULT_FOV = 90
-- State variables
local sanity = SANITY_MAX
local vignetteAlpha = 0
local hallucinationEnts = {}
local lastJumpScareTime = 0
local lastDarknessCheck = 0
local invertColorsEndTime = 0
local flickerStartTime = 0
local flickerEndTime = 0
local isFOVChanged = false
-- Handle 2D screen effects (vignette, text, fragmented screen, flicker)
local function HandleScreenEffects()
if sanity < 80 then
vignetteAlpha = math.min((80 - sanity) * 3, 150)
surface.SetDrawColor(0, 0, 0, vignetteAlpha)
surface.DrawRect(0, 0, ScrW(), ScrH())
end
draw.SimpleText("Sanity: " .. math.floor(sanity), "DermaDefault", 10, 10, Color(255, 255, 255))
if sanity < 15 then
draw.SimpleText("Your mind is breaking...", "DermaLarge", ScrW() / 2 - 150, ScrH() / 2, Color(255, 0, 0))
end
if CurTime() < flickerEndTime then
local alpha = math.random(50, 150)
surface.SetDrawColor(255, 255, 255, alpha)
surface.DrawRect(0, 0, ScrW(), ScrH())
end
end
-- Handle post-processing effects (color modification, motion blur, screen shake)
local function HandlePostProcessing()
if CurTime() < invertColorsEndTime then
DrawColorModify({
["$pp_colour_colour"] = -1,
["$pp_colour_brightness"] = 0,
["$pp_colour_contrast"] = 1,
["$pp_colour_addr"] = 0,
["$pp_colour_addg"] = 0,
["$pp_colour_addb"] = 0,
})
else
local colMod = {
["$pp_colour_addr"] = 0,
["$pp_colour_addg"] = 0,
["$pp_colour_addb"] = 0,
["$pp_colour_brightness"] = 0,
["$pp_colour_contrast"] = 1,
["$pp_colour_colour"] = 1,
["$pp_colour_mulr"] = 0,
["$pp_colour_mulg"] = 0,
["$pp_colour_mulb"] = 0
}
if sanity < 100 then colMod["$pp_colour_addr"] = (100 - sanity) * 0.001 end
if sanity < 80 then
colMod["$pp_colour_colour"] = math.max(1 - (80 - sanity) * 0.01, 0.5)
colMod["$pp_colour_brightness"] = -0.05
colMod["$pp_colour_contrast"] = 1 + (80 - sanity) * 0.01
end
if sanity < 50 then
colMod["$pp_colour_colour"] = 1 - (50 - sanity) * 0.02
colMod["$pp_colour_contrast"] = 1 + (50 - sanity) * 0.02
colMod["$pp_colour_brightness"] = -0.1
end
if sanity < 20 then
colMod["$pp_colour_brightness"] = -0.15
colMod["$pp_colour_contrast"] = 1.1 + (20 - sanity) * 0.05
colMod["$pp_colour_colour"] = 1 - (20 - sanity) * 0.05
end
DrawColorModify(colMod)
end
if sanity < 10 then
DrawMotionBlur(0.15, 6, 0.05)
elseif sanity < 40 then
DrawMotionBlur(0.1, 5, 0.05)
elseif sanity < 70 then
DrawMotionBlur(0.05, 4, 0.05)
end
local shakeMagnitude = 0
if sanity < 90 then shakeMagnitude = math.max(shakeMagnitude, (90 - sanity) / 90 * 0.3) end
if sanity < 60 then shakeMagnitude = math.max(shakeMagnitude, (60 - sanity) / 60 * 0.5) end
if sanity < 10 then shakeMagnitude = math.max(shakeMagnitude, (10 - sanity) / 10 * 0.8) end
if shakeMagnitude > 0 then
util.ScreenShake(LocalPlayer():GetPos(), shakeMagnitude, 5, 0.5, 100)
end
end
-- Create hallucination entities
local HALLUCINATION_MODELS = {"models/Humans/Group01/male_07.mdl", "models/Humans/Group01/female_07.mdl"}
local function CreateHallucination()
if #hallucinationEnts >= 3 then return end
local ply = LocalPlayer()
local ent = ClientsideModel(table.Random(HALLUCINATION_MODELS))
ent:SetPos(ply:GetPos() + Vector(math.random(-300, 300), math.random(-300, 300), 0))
ent:SetAngles((ply:GetPos() - ent:GetPos()):Angle())
ent:SetColor(Color(50, 50, 50, sanity < 20 and 200 or 150))
ent:SetRenderMode(RENDERMODE_TRANSALPHA)
table.insert(hallucinationEnts, ent)
timer.Simple(10, function()
if IsValid(ent) then ent:Remove() end
table.RemoveByValue(hallucinationEnts, ent)
end)
end
-- Create ghost silhouette entities
local function CreateGhostSilhouette()
if #hallucinationEnts >= 3 then return end
local ply = LocalPlayer()
local ghost = ClientsideModel("models/Humans/Group01/male_07.mdl")
ghost:SetPos(ply:GetPos() + Vector(math.random(-400, 400), math.random(-400, 400), 0))
ghost:SetAngles((ply:GetPos() - ghost:GetPos()):Angle())
ghost:SetColor(Color(200, 200, 255, 100))
ghost:SetRenderMode(RENDERMODE_TRANSALPHA)
table.insert(hallucinationEnts, ghost)
timer.Simple(8, function()
if IsValid(ghost) then ghost:Remove() end
table.RemoveByValue(hallucinationEnts, ghost)
end)
end
-- Update darkness state and send to server
local function UpdateDarknessState()
if CurTime() - lastDarknessCheck < DARKNESS_CHECK_INTERVAL then return end
lastDarknessCheck = CurTime()
local lightColor = render.GetLightColor(LocalPlayer():GetPos())
local brightness = (lightColor.x + lightColor.y + lightColor.z) / 3
net.Start("FearOfDark_UpdateDarkness")
net.WriteBool(brightness < 0.2)
net.SendToServer()
end
-- Trigger jumpscare effect
local function TriggerJumpscare()
if CurTime() - lastJumpScareTime < JUMPSCARE_COOLDOWN then return end
lastJumpScareTime = CurTime()
surface.PlaySound("npc/stalker/go_alert2.wav")
local flashEnd = CurTime() + 0.2
hook.Add("HUDPaint", "FearOfDark_JumpScareFlash", function()
if CurTime() < flashEnd then
surface.SetDrawColor(255, 255, 255, 200)
surface.DrawRect(0, 0, ScrW(), ScrH())
else
hook.Remove("HUDPaint", "FearOfDark_JumpScareFlash")
end
end)
end
-- Additional effect functions
local function HandleSoundDistortion()
local distortedPitch = math.random(70, 130)
LocalPlayer():EmitSound("npc/stalker/go_alert2.wav", 75, distortedPitch)
end
local function DisplayParanoiaMessage(msg)
chat.AddText(Color(200, 0, 0), msg)
end
local function PlaySoundEcho()
LocalPlayer():EmitSound("npc/strider/creak1.wav", 75, 100)
timer.Simple(0.3, function()
LocalPlayer():EmitSound("ambient/levels/streetwar/strider_distant2.wav", 75, 90)
end)
end
-- Network receivers
net.Receive("FearOfDark_StageChange", function()
sanity = LocalPlayer():GetNWFloat("Sanity", SANITY_MAX)
end)
net.Receive("FearOfDark_ParanoiaMessage", function()
chat.AddText(Color(150, 0, 0), net.ReadString())
end)
net.Receive("FearOfDark_JumpScare", TriggerJumpscare)
-- Main client loop with effect triggers
hook.Add("Think", "FearOfDark_ClientThink", function()
sanity = LocalPlayer():GetNWFloat("Sanity", SANITY_MAX)
UpdateDarknessState()
if sanity < 70 and math.random() < 0.02 then
invertColorsEndTime = CurTime() + math.Rand(0.5, 1.5)
end
if sanity < 30 and math.random() < 0.02 then
flickerStartTime = CurTime()
flickerEndTime = CurTime() + math.Rand(0.5, 2)
end
if sanity < 40 and not isFOVChanged and math.random() < 0.01 then
local newFOV = DEFAULT_FOV + math.random(-20, 20)
LocalPlayer():SetFOV(newFOV, 0.2)
isFOVChanged = true
timer.Simple(math.Rand(5, 10), function()
if IsValid(LocalPlayer()) then
LocalPlayer():SetFOV(DEFAULT_FOV, 0.2)
end
isFOVChanged = false
end)
end
if sanity < 60 and math.random() < 0.05 then
surface.PlaySound(table.Random({
"ambient/creatures/town_scared_breathing1.wav",
"ambient/levels/prison/radio_random1.wav",
"physics/wood/wood_box_impact_soft2.wav",
"weapons/fx/tink/shotgun_shell3.wav"
}))
end
if sanity < 50 and math.random() < 0.01 then HandleSoundDistortion() end
if sanity < 40 and math.random() < 0.02 then CreateHallucination() end
if sanity < 35 and math.random() < 0.005 then CreateGhostSilhouette() end
if sanity < 25 and math.random() < 0.01 then DisplayParanoiaMessage("Do you hear the voices?") end
if sanity < 20 and math.random() < 0.005 then PlaySoundEcho() end
if sanity < 20 and math.random() < 0.01 then LocalPlayer():SetEyeAngles(AngleRand(-90, 90)) end
end)
-- Rendering hooks
hook.Add("HUDPaint", "FearOfDark_HUDEffects", HandleScreenEffects)
hook.Add("RenderScreenspaceEffects", "FearOfDark_ScreenEffects", HandlePostProcessing)
end
Преобразуй следующий код, чтобы он соответствовал уровню senior-разработчика: используй объектно-ориентированное программирование с инкапсуляцией, абстракцией и наследованием там, где это уместно, сделай архитектуру модульной, расширяемой и поддерживаемой, оптимизируй производительность и читаемость, улучшай именования переменных, функций и классов, устраняй дублирование кода, применяй подходящие паттерны проектирования для гибкости и масштабируемости, внедри обработку ошибок с информативными сообщениями и обеспечь логирование ключевых событий, добавь подробные комментарии и документацию к основным классам и методам, обеспечь финальный код простым для понимания, тестирования и поддержки.
--[[
FearOfDark - Sanity & Psychological Effects System
Senior-level rewrite with OOP, modularity, extensibility, and maintainability.
Structure:
- FearOfDarkSystem (Base) handles common functionality.
- ServerFearOfDarkSystem (extends FearOfDarkSystem) implements server-side logic.
- ClientFearOfDarkSystem (extends FearOfDarkSystem) implements client-side logic.
Key features:
- Encapsulation via local classes and methods.
- Clear separation of client and server responsibilities.
- Centralized config with validation and default fallbacks.
- Event-driven design with hooks and timers scoped within classes.
- Comprehensive logging and simple error handling.
- Use of constants and enums for clarity.
- Avoid redundant computations.
- Detailed comments and docs.
--]]
if not istable(FearOfDarkSystem) then
-- Utility Logger singleton
local Logger = {}
Logger.__index = Logger
function Logger:LogInfo(message)
MsgC(Color(100, 255, 100), "[FearOfDark][INFO]: ", Color(255, 255, 255), message, "\n")
end
function Logger:LogWarn(message)
MsgC(Color(255, 255, 0), "[FearOfDark][WARN]: ", Color(255, 255, 255), message, "\n")
end
function Logger:LogError(message)
MsgC(Color(255, 100, 100), "[FearOfDark][ERROR]: ", Color(255, 255, 255), message, "\n")
end
FearOfDarkLogger = Logger
-- Base system class with common functionality
local FearOfDarkSystem = {}
FearOfDarkSystem.__index = FearOfDarkSystem
-- Constants for sanity stages and thresholds
FearOfDarkSystem.SANITY_MAX = 100
FearOfDarkSystem.SANITY_STAGES = 5 -- Stages from 0 to 5 (if 100 / 20)
FearOfDarkSystem.DEFAULT_DARKNESS_BRIGHTNESS_THRESHOLD = 0.2
-- Network strings to be registered only once
FearOfDarkSystem.NET_STRINGS = {
UpdateDarkness = "FearOfDark_UpdateDarkness",
SanityStageChange = "FearOfDark_StageChange",
ParanoiaMessage = "FearOfDark_ParanoiaMessage",
JumpScare = "FearOfDark_JumpScare",
}
-- Constructor
function FearOfDarkSystem.new()
local self = setmetatable({}, FearOfDarkSystem)
return self
end
--- Utility method: Clamps a number within bounds
---@param val number
---@param min number
---@param max number
---@return number
function FearOfDarkSystem:Clamp(val, min, max)
if val < min then return min end
if val > max then return max end
return val
end
--- Calculates the sanity stage based on current sanity
---@param sanity number
---@return number
function FearOfDarkSystem:CalculateSanityStage(sanity)
local stage = math.ceil(sanity / (self.SANITY_MAX / self.SANITY_STAGES))
return stage
end
-- Placeholder for initializing (override in subclasses)
function FearOfDarkSystem:Initialize() end
function FearOfDarkSystem:Shutdown() end
end -- base class block
-- ==========================
-- ===== Server-side =========
-- ==========================
if SERVER then
---@class ServerFearOfDarkSystem : FearOfDarkSystem
local ServerFearOfDarkSystem = setmetatable({}, FearOfDarkSystem)
ServerFearOfDarkSystem.__index = ServerFearOfDarkSystem
-- Constants & configurations specific for server
ServerFearOfDarkSystem.SANITY_DECAY_RATE_DARKNESS_NO_FLASHLIGHT = 1 -- sanity lost per second when in darkness without flashlight
ServerFearOfDarkSystem.SANITY_DECAY_RATE_DARKNESS_WITH_FLASHLIGHT = 0.5 -- sanity lost per second in darkness with flashlight
ServerFearOfDarkSystem.SANITY_RECOVERY_RATE_LIGHT = 0.5 -- sanity gained per second outside darkness
ServerFearOfDarkSystem.JUMPSCARE_COOLDOWN = 30 -- seconds between jumpscares per player
ServerFearOfDarkSystem.HALLUCINATION_INTERVAL = 10 -- seconds between hallucination events
ServerFearOfDarkSystem.JUMPSCARE_CHANCE = 0.005 -- chance each tick when sanity < 10
-- Hallucination sounds with pitch and volume parameters
ServerFearOfDarkSystem.HALLUCINATION_SOUNDS = {
{sound = "ambient/levels/canals/windchime2.wav", pitch = 90, volume = 0.8},
{sound = "npc/footsteps/hardboot_generic1.wav", pitch = 80, volume = 0.8},
{sound = "npc/footsteps/hardboot_generic2.wav", pitch = 80, volume = 0.8},
}
--- Creates a new server system instance
function ServerFearOfDarkSystem.new()
local self = setmetatable(FearOfDarkSystem.new(), ServerFearOfDarkSystem)
self.playersData = {} -- Store per-player data for sanity and timings
self.logger = FearOfDarkLogger
return self
end
--- Initialize the server system (registers hooks, netstrings)
function ServerFearOfDarkSystem:Initialize()
self.logger:LogInfo("Initializing ServerFearOfDarkSystem...")
-- Register network strings with error handling
for _, netStr in pairs(self.NET_STRINGS) do
local success, err = pcall(util.AddNetworkString, netStr)
if success then
self.logger:LogInfo("Registered net string: " .. netStr)
else
self.logger:LogWarn("Failed to register net string '" .. netStr .. "': " .. tostring(err))
end
end
-- Hook for player initialization, initialize player data
hook.Add("PlayerInitialSpawn", "FearOfDark_InitPlayerSanity", function(ply)
self:InitializePlayer(ply)
end)
-- Think hook for sanity updates and jumpscare attempts
hook.Add("Think", "FearOfDark_ServerThink", function()
self:UpdateAllPlayersSanity()
end)
-- Timer for hallucination events
timer.Create("FearOfDark_HallucinationTimer", self.HALLUCINATION_INTERVAL, 0, function()
self:TriggerHallucinations()
end)
-- Network receive for darkness state updates from client
net.Receive(self.NET_STRINGS.UpdateDarkness, function(len, ply)
self:ReceiveDarknessState(ply, net.ReadBool())
end)
end
--- Initialize player data and sanity on initial spawn
---@param ply Player
function ServerFearOfDarkSystem:InitializePlayer(ply)
if not IsValid(ply) then
self.logger:LogWarn("InitializePlayer called with invalid ply.")
return
end
-- Initialize data container for player if missing
self.playersData[ply] = {
Sanity = self.SANITY_MAX,
LastSanityStage = self.SANITY_STAGES,
InDarkness = false,
LastJumpScareTime = 0,
}
ply:SetNWFloat("Sanity", self.SANITY_MAX)
self.logger:LogInfo(string.format("Initialized player %s with sanity %d.", ply:Nick(), self.SANITY_MAX))
end
--- Update sanity for all players each server think tick
function ServerFearOfDarkSystem:UpdateAllPlayersSanity()
local currentTime = CurTime()
for _, ply in ipairs(player.GetAll()) do
if not IsValid(ply) or not ply:Alive() then continue end
local pdata = self.playersData[ply]
if not pdata then self:InitializePlayer(ply) pdata = self.playersData[ply] end
local dt = FrameTime()
-- Sanity change based on darkness
local sanityChange = 0
if pdata.InDarkness then
local lossRate = ply:FlashlightIsOn() and self.SANITY_DECAY_RATE_DARKNESS_WITH_FLASHLIGHT or self.SANITY_DECAY_RATE_DARKNESS_NO_FLASHLIGHT
sanityChange = -lossRate * dt
else
sanityChange = self.SANITY_RECOVERY_RATE_LIGHT * dt
end
-- Calculate and clamp new sanity
local newSanity = self:Clamp(pdata.Sanity + sanityChange, 0, self.SANITY_MAX)
-- Update player's networked sanity and stored value
pdata.Sanity = newSanity
ply:SetNWFloat("Sanity", newSanity)
-- Check if sanity stage changed
local newStage = self:CalculateSanityStage(newSanity)
if newStage ~= pdata.LastSanityStage then
pdata.LastSanityStage = newStage
self:NotifySanityStageChanged(ply, newStage)
end
-- Try to trigger jumpscare for low sanity players
self:TryTriggerJumpScare(ply, pdata, currentTime)
end
end
--- Notify player that sanity stage has changed via net message
---@param ply Player
---@param stage number
function ServerFearOfDarkSystem:NotifySanityStageChanged(ply, stage)
if not IsValid(ply) then return end
net.Start(self.NET_STRINGS.SanityStageChange)
net.WriteUInt(stage, 3) -- 3 bits for 0..7 stages (we only use up to 5)
net.Send(ply)
self.logger:LogInfo(string.format("Sanity stage for %s changed to %d", ply:Nick(), stage))
end
--- Attempt to trigger a jumpscare for a player if conditions are met
---@param ply Player
---@param pdata table Player data container
---@param currentTime number Current CurTime in seconds
function ServerFearOfDarkSystem:TryTriggerJumpScare(ply, pdata, currentTime)
if pdata.Sanity >= 10 then
return -- sanity is too high for jumpscare
end
if currentTime - pdata.LastJumpScareTime < self.JUMPSCARE_COOLDOWN then
return -- cooldown not elapsed
end
-- Random chance check
if math.random() > self.JUMPSCARE_CHANCE then
return
end
-- Trigger jumpscare
pdata.LastJumpScareTime = currentTime
net.Start(self.NET_STRINGS.JumpScare)
net.Send(ply)
self.logger:LogInfo(string.format("Triggered jumpscare for player %s", ply:Nick()))
end
--- Trigger hallucination sounds and paranoia messages for players with low sanity
function ServerFearOfDarkSystem:TriggerHallucinations()
for _, ply in ipairs(player.GetAll()) do
if not IsValid(ply) or not ply:Alive() then continue end
local pdata = self.playersData[ply]
if not pdata then continue end
local sanity = pdata.Sanity
if sanity >= 40 then
continue -- no hallucinations for sane players
end
local randomOffset = VectorRand() * 200
local soundPos = ply:GetPos() + randomOffset
local soundInfo = table.Random(self.HALLUCINATION_SOUNDS)
sound.Play(soundInfo.sound, soundPos, 75, soundInfo.pitch, soundInfo.volume)
if sanity < 20 then
net.Start(self.NET_STRINGS.ParanoiaMessage)
net.WriteString("Something is watching you...")
net.Send(ply)
end
self.logger:LogInfo(string.format("Triggered hallucination sound for player %s", ply:Nick()))
end
end
--- Receives darkness state from client and stores internally
---@param ply Player
---@param inDarkness boolean
function ServerFearOfDarkSystem:ReceiveDarknessState(ply, inDarkness)
local pdata = self.playersData[ply]
if pdata then
pdata.InDarkness = inDarkness and true or false -- force boolean
self.logger:LogInfo(string.format("Updated darkness for player %s to %s", ply:Nick(), tostring(pdata.InDarkness)))
else
self.logger:LogWarn("Received darkness state for unknown player: " .. tostring(ply))
end
end
--- Clean up function to remove hooks and timers on shutdown
function ServerFearOfDarkSystem:Shutdown()
self.logger:LogInfo("Shutting down ServerFearOfDarkSystem...")
hook.Remove("PlayerInitialSpawn", "FearOfDark_InitPlayerSanity")
hook.Remove("Think", "FearOfDark_ServerThink")
timer.Remove("FearOfDark_HallucinationTimer")
net.Receive(self.NET_STRINGS.UpdateDarkness, nil)
self.playersData = nil
self.logger:LogInfo("ServerFearOfDarkSystem shutdown complete.")
end
-- Instantiate and initialize server singleton
local ServerInstance = ServerFearOfDarkSystem.new()
ServerInstance:Initialize()
-- Optionally expose globally for debug
_G.FearOfDarkServer = ServerInstance
end
-- ==========================
-- ===== Client-side =========
-- ==========================
if CLIENT then
---@class ClientFearOfDarkSystem : FearOfDarkSystem
local ClientFearOfDarkSystem = setmetatable({}, FearOfDarkSystem)
ClientFearOfDarkSystem.__index = ClientFearOfDarkSystem
-- Configurations & constants
ClientFearOfDarkSystem.DARKNESS_CHECK_INTERVAL = 1 -- seconds between client darkness updates
ClientFearOfDarkSystem.JUMPSCARE_COOLDOWN = 30 -- seconds cooldown between jumpscares
ClientFearOfDarkSystem.DEFAULT_FOV = 90 -- Default FOV to reset to
ClientFearOfDarkSystem.MAX_HALLUCINATION_ENTITIES = 3 -- Max hallucination entities active at once
-- Hallucination models and parameters
ClientFearOfDarkSystem.HALLUCINATION_MODELS = {
"models/Humans/Group01/male_07.mdl",
"models/Humans/Group01/female_07.mdl",
}
-- Sounds used in paranoia or hallucination effects
ClientFearOfDarkSystem.PARANOIA_SOUNDS = {
"ambient/creatures/town_scared_breathing1.wav",
"ambient/levels/prison/radio_random1.wav",
"physics/wood/wood_box_impact_soft2.wav",
"weapons/fx/tink/shotgun_shell3.wav"
}
--- Constructs a new client system instance
function ClientFearOfDarkSystem.new()
local self = setmetatable(FearOfDarkSystem.new(), ClientFearOfDarkSystem)
-- Player sanity value
self.sanity = self.SANITY_MAX
-- Timers state
self._lastDarknessCheckTime = 0
self._lastJumpScareTime = 0
-- Effect state
self._vignetteAlpha = 0
self._hallucinationEntities = {}
self._invertColorsEndTime = 0
self._flickerEndTime = 0
self._fovChanged = false
self._logger = FearOfDarkLogger
return self
end
--- Initialize client-side system (register hooks and net receivers)
function ClientFearOfDarkSystem:Initialize()
self._logger:LogInfo("Initializing ClientFearOfDarkSystem...")
-- Net message receivers
net.Receive(self.NET_STRINGS.SanityStageChange, function() self:OnSanityStageChanged() end)
net.Receive(self.NET_STRINGS.ParanoiaMessage, function() self:OnParanoiaMessage() end)
net.Receive(self.NET_STRINGS.JumpScare, function() self:OnJumpScareTriggered() end)
-- Main Think hook
hook.Add("Think", "FearOfDark_ClientThink", function()
self:ClientThink()
end)
-- HUDPaint and RenderScreenSpaceEffects hooks for visual effects
hook.Add("HUDPaint", "FearOfDark_HudEffects", function()
self:RenderHUDEffects()
end)
hook.Add("RenderScreenspaceEffects", "FearOfDark_ScreenEffects", function()
self:RenderPostProcessingEffects()
end)
end
--- Handles client think logic executed every frame
function ClientFearOfDarkSystem:ClientThink()
local currentTime = CurTime()
-- Update sanity from NW variable in a safe manner
local localPlayer = LocalPlayer()
if not IsValid(localPlayer) then return end
self.sanity = self:Clamp(localPlayer:GetNWFloat("Sanity", self.SANITY_MAX), 0, self.SANITY_MAX)
-- Periodically update darkness state to server
if currentTime - self._lastDarknessCheckTime >= self.DARKNESS_CHECK_INTERVAL then
self._lastDarknessCheckTime = currentTime
self:UpdateDarknessStateToServer()
end
-- Randomly trigger various hallucination and paranoia effects based on sanity thresholds
self:TriggerRandomEffectsBasedOnSanity(currentTime, localPlayer)
end
--- Updates the darkness state by measuring local ambient brightness, and sending to server
function ClientFearOfDarkSystem:UpdateDarknessStateToServer()
local localPlayer = LocalPlayer()
if not IsValid(localPlayer) then return end
local lightColor = render.GetLightColor(localPlayer:GetPos())
local brightness = (lightColor.x + lightColor.y + lightColor.z) / 3
local inDarkness = brightness < self.DEFAULT_DARKNESS_BRIGHTNESS_THRESHOLD
-- Send to server with error handling
local status, err = pcall(function()
net.Start(self.NET_STRINGS.UpdateDarkness)
net.WriteBool(inDarkness)
net.SendToServer()
end)
if not status then
self._logger:LogWarn("Failed to send darkness state: " .. tostring(err))
end
end
--- Handles sanity stage change notification
function ClientFearOfDarkSystem:OnSanityStageChanged()
self.sanity = self:Clamp(LocalPlayer():GetNWFloat("Sanity", self.SANITY_MAX), 0, self.SANITY_MAX)
self._logger:LogInfo(string.format("Sanity stage updated. Current sanity: %.2f", self.sanity))
end
--- Handles paranoia message received from server; prints to chat
function ClientFearOfDarkSystem:OnParanoiaMessage()
local msg = net.ReadString()
if msg and msg ~= "" then
chat.AddText(Color(150, 0, 0), msg)
self._logger:LogInfo("Received paranoia message: " .. msg)
end
end
--- Trigger the client-side jumpscare effect (sound, screen flash)
function ClientFearOfDarkSystem:OnJumpScareTriggered()
local currentTime = CurTime()
if currentTime - self._lastJumpScareTime < self.JUMPSCARE_COOLDOWN then
return -- cooldown ongoing
end
self._lastJumpScareTime = currentTime
-- Play jumpscare sound
surface.PlaySound("npc/stalker/go_alert2.wav")
-- Screen flash effect for a short duration
local flashEndTime = currentTime + 0.2
hook.Add("HUDPaint", "FearOfDark_JumpscareFlash", function()
if CurTime() < flashEndTime then
surface.SetDrawColor(255, 255, 255, 200)
surface.DrawRect(0, 0, ScrW(), ScrH())
else
hook.Remove("HUDPaint", "FearOfDark_JumpscareFlash")
end
end)
self._logger:LogInfo("Jumpscare triggered on client")
end
--- Trigger various random hallucination and paranoia effects based on sanity
---@param currentTime number
---@param localPlayer Player
function ClientFearOfDarkSystem:TriggerRandomEffectsBasedOnSanity(currentTime, localPlayer)
-- Color inversion flicker
if self.sanity < 70 and math.random() < 0.02 then
self._invertColorsEndTime = currentTime + math.Rand(0.5, 1.5)
end
-- Screen flicker
if self.sanity < 30 and math.random() < 0.02 then
self._flickerEndTime = currentTime + math.Rand(0.5, 2)
end
-- FOV distortion effect
if self.sanity < 40 and not self._fovChanged and math.random() < 0.01 then
local newFOV = self.DEFAULT_FOV + math.random(-20, 20)
localPlayer:SetFOV(newFOV, 0.2)
self._fovChanged = true
timer.Simple(math.Rand(5, 10), function()
if IsValid(localPlayer) then
localPlayer:SetFOV(self.DEFAULT_FOV, 0.2)
end
self._fovChanged = false
end)
end
-- Play random paranoia sound at low sanity levels
if self.sanity < 60 and math.random() < 0.05 then
surface.PlaySound(table.Random(self.PARANOIA_SOUNDS))
end
-- Sound distortion effect
if self.sanity < 50 and math.random() < 0.01 then
self:PlaySoundDistortionEffect()
end
-- Create hallucination entities
if self.sanity < 40 and math.random() < 0.02 then
self:CreateHallucinationEntity(localPlayer)
end
-- Create ghost silhouette entities, rarer
if self.sanity < 35 and math.random() < 0.005 then
self:CreateGhostSilhouetteEntity(localPlayer)
end
-- Show paranoia messages
if self.sanity < 25 and math.random() < 0.01 then
self:DisplayParanoiaMessage("Do you hear the voices?")
end
-- Play echo sound sequences for very low sanity
if self.sanity < 20 and math.random() < 0.005 then
self:PlaySoundEchoSequence()
end
-- Randomly mess with player's view angles
if self.sanity < 20 and math.random() < 0.01 then
if IsValid(localPlayer) then
localPlayer:SetEyeAngles(AngleRand(-90, 90))
end
end
end
--- Plays distorted sound effect for paranoia
function ClientFearOfDarkSystem:PlaySoundDistortionEffect()
if not IsValid(LocalPlayer()) then return end
local pitch = math.random(70, 130)
LocalPlayer():EmitSound("npc/stalker/go_alert2.wav", 75, pitch)
self._logger:LogInfo("Played sound distortion effect triggered by paranoia")
end
--- Displays paranoia text message in chat
---@param message string
function ClientFearOfDarkSystem:DisplayParanoiaMessage(message)
if type(message) ~= "string" then return end
chat.AddText(Color(200, 0, 0), message)
self._logger:LogInfo("Displayed paranoia message: " .. message)
end
--- Plays a sequence of echo sounds for paranoia effect
function ClientFearOfDarkSystem:PlaySoundEchoSequence()
if not IsValid(LocalPlayer()) then return end
LocalPlayer():EmitSound("npc/strider/creak1.wav", 75, 100)
timer.Simple(0.3, function()
if IsValid(LocalPlayer()) then
LocalPlayer():EmitSound("ambient/levels/streetwar/strider_distant2.wav", 75, 90)
end
end)
self._logger:LogInfo("Played sound echo sequence")
end
--- Creates hallucination entities near the player, limited in count
---@param ply Player
function ClientFearOfDarkSystem:CreateHallucinationEntity(ply)
if #self._hallucinationEntities >= self.MAX_HALLUCINATION_ENTITIES then return end
if not IsValid(ply) then return end
local model = table.Random(self.HALLUCINATION_MODELS)
local ent = ClientsideModel(model)
if not IsValid(ent) then
self._logger:LogWarn("Failed to create hallucination ClientsideModel: " .. tostring(model))
return
end
local posOffset = Vector(math.random(-300, 300), math.random(-300, 300), 0)
local pos = ply:GetPos() + posOffset
local angles = (ply:GetPos() - pos):Angle()
ent:SetPos(pos)
ent:SetAngles(angles)
local alpha = self.sanity < 20 and 200 or 150
ent:SetColor(Color(50, 50, 50, alpha))
ent:SetRenderMode(RENDERMODE_TRANSALPHA)
ent:SetNoDraw(false)
table.insert(self._hallucinationEntities, ent)
timer.Simple(10, function()
if IsValid(ent) then ent:Remove() end
table.RemoveByValue(self._hallucinationEntities, ent)
end)
self._logger:LogInfo("Created hallucination entity")
end
--- Creates ghost silhouette entities near the player (rarer hallucination)
---@param ply Player
function ClientFearOfDarkSystem:CreateGhostSilhouetteEntity(ply)
if #self._hallucinationEntities >= self.MAX_HALLUCINATION_ENTITIES then return end
if not IsValid(ply) then return end
local model = "models/Humans/Group01/male_07.mdl"
local ghost = ClientsideModel(model)
if not IsValid(ghost) then
self._logger:LogWarn("Failed to create ghost silhouette ClientsideModel")
return
end
local posOffset = Vector(math.random(-400, 400), math.random(-400, 400), 0)
local pos = ply:GetPos() + posOffset
local angles = (ply:GetPos() - pos):Angle()
ghost:SetPos(pos)
ghost:SetAngles(angles)
ghost:SetColor(Color(200, 200, 255, 100))
ghost:SetRenderMode(RENDERMODE_TRANSALPHA)
ghost:SetNoDraw(false)
table.insert(self._hallucinationEntities, ghost)
timer.Simple(8, function()
if IsValid(ghost) then ghost:Remove() end
table.RemoveByValue(self._hallucinationEntities, ghost)
end)
self._logger:LogInfo("Created ghost silhouette entity")
end
--- Renders HUD overlays and 2D visual effects (vignette, text, flicker)
function ClientFearOfDarkSystem:RenderHUDEffects()
-- Vignette effect: darkening screen edges as sanity drops below 80
if self.sanity < 80 then
self._vignetteAlpha = math.min((80 - self.sanity) * 3, 150)
surface.SetDrawColor(0, 0, 0, self._vignetteAlpha)
surface.DrawRect(0, 0, ScrW(), ScrH())
end
-- Sanity text display on HUD
draw.SimpleText("Sanity: " .. math.floor(self.sanity), "DermaDefault", 10, 10, Color(255, 255, 255))
-- Warning text when sanity is critically low
if self.sanity < 15 then
draw.SimpleText("Your mind is breaking...", "DermaLarge", ScrW() / 2 - 150, ScrH() / 2, Color(255, 0, 0))
end
-- Screen flicker effect, white flashes with random alpha
local curTime = CurTime()
if curTime < self._flickerEndTime then
surface.SetDrawColor(255, 255, 255, math.random(50, 150))
surface.DrawRect(0, 0, ScrW(), ScrH())
end
end
--- Renders post-processing effects (color mods, motion blur, screen shake)
function ClientFearOfDarkSystem:RenderPostProcessingEffects()
local curTime = CurTime()
if curTime < self._invertColorsEndTime then
-- Invert colors fully for duration
DrawColorModify({
["$pp_colour_colour"] = -1,
["$pp_colour_brightness"] = 0,
["$pp_colour_contrast"] = 1,
["$pp_colour_addr"] = 0,
["$pp_colour_addg"] = 0,
["$pp_colour_addb"] = 0,
})
else
-- Calculate color modification based on sanity level
local colMod = {
["$pp_colour_addr"] = 0,
["$pp_colour_addg"] = 0,
["$pp_colour_addb"] = 0,
["$pp_colour_brightness"] = 0,
["$pp_colour_contrast"] = 1,
["$pp_colour_colour"] = 1,
["$pp_colour_mulr"] = 0,
["$pp_colour_mulg"] = 0,
["$pp_colour_mulb"] = 0
}
if self.sanity < 100 then
colMod["$pp_colour_addr"] = (100 - self.sanity) * 0.001
end
if self.sanity < 80 then
colMod["$pp_colour_colour"] = math.max(1 - (80 - self.sanity) * 0.01, 0.5)
colMod["$pp_colour_brightness"] = -0.05
colMod["$pp_colour_contrast"] = 1 + (80 - self.sanity) * 0.01
end
if self.sanity < 50 then
colMod["$pp_colour_colour"] = 1 - (50 - self.sanity) * 0.02
colMod["$pp_colour_contrast"] = 1 + (50 - self.sanity) * 0.02
colMod["$pp_colour_brightness"] = -0.1
end
if self.sanity < 20 then
colMod["$pp_colour_brightness"] = -0.15
colMod["$pp_colour_contrast"] = 1.1 + (20 - self.sanity) * 0.05
colMod["$pp_colour_colour"] = 1 - (20 - self.sanity) * 0.05
end
DrawColorModify(colMod)
end
-- Motion blur intensity by sanity
if self.sanity < 10 then
DrawMotionBlur(0.15, 6, 0.05)
elseif self.sanity < 40 then
DrawMotionBlur(0.1, 5, 0.05)
elseif self.sanity < 70 then
DrawMotionBlur(0.05, 4, 0.05)
end
-- Screen shake intensity scales with low sanity
local shakeMagnitude = 0
if self.sanity < 90 then
shakeMagnitude = math.max(shakeMagnitude, (90 - self.sanity) / 90 * 0.3)
end
if self.sanity < 60 then
shakeMagnitude = math.max(shakeMagnitude, (60 - self.sanity) / 60 * 0.5)
end
if self.sanity < 10 then
shakeMagnitude = math.max(shakeMagnitude, (10 - self.sanity) / 10 * 0.8)
end
if shakeMagnitude > 0 then
util.ScreenShake(LocalPlayer():GetPos(), shakeMagnitude, 5, 0.5, 100)
end
end
--- Remove any remaining hallucination entities on shutdown
function ClientFearOfDarkSystem:Cleanup()
for _, ent in ipairs(self._hallucinationEntities) do
if IsValid(ent) then ent:Remove() end
end
self._hallucinationEntities = {}
hook.Remove("Think", "FearOfDark_ClientThink")
hook.Remove("HUDPaint", "FearOfDark_HudEffects")
hook.Remove("RenderScreenspaceEffects", "FearOfDark_ScreenEffects")
net.Receive(self.NET_STRINGS.SanityStageChange, nil)
net.Receive(self.NET_STRINGS.ParanoiaMessage, nil)
net.Receive(self.NET_STRINGS.JumpScare, nil)
self._logger:LogInfo("ClientFearOfDarkSystem cleaned up.")
end
-- Instantiate and initialize client singleton
local ClientInstance = ClientFearOfDarkSystem.new()
ClientInstance:Initialize()
-- Optionally expose globally for debug
_G.FearOfDarkClient = ClientInstance
end
This approach is closer to a professional-grade system suitable to build upon or integrate into larger projects with sophisticated state and event management.
Not yet included in a published release.