Untitled conversation
- Userlua
- Assistant
if CLIENT then
-------------------------------------------------------------------
-- FirstPersonView Module
-- Provides a precise first-person camera positioned at the player's head.
-------------------------------------------------------------------
-- Define the FirstPersonView table
local FirstPersonView = {
-- Configuration table with default values. These can be overridden via
-- console variables (ConVars) for dynamic configuration.
config = {
headBoneNames = {
"ValveBiped.Bip01_Head1", -- Priority-ordered list of head bone names
"ValveBiped.Bip01_Neck1",
"ValveBiped.Bip01_EyeLeft",
"ValveBiped.Bip01_EyeRight",
"ValveBiped.Bip01_Mouth"
},
cameraOffset = Vector(0, 0, 0), -- Default camera offset (modifiable via ConVar)
drawLocalPlayer = true, -- Whether to draw the local player model in first-person
spectatorTeam = nil, -- Spectator team identifier (to be set during initialization)
notifyOnError = true, -- Whether to notify the player on errors
cameraCollision = true, -- Whether to enable camera collision detection
maxCameraDistance = 60, -- Maximum camera distance to prevent clipping
hullSize = 2, -- Size for TraceHull (defines the half-size of the box)
},
-- Table to cache head bone indices for the local player
headBoneIndices = {},
-- Flag to ensure single initialization
initialized = false,
-- Rate limiter for error notifications to prevent spam
errorRateLimiter = {
lastErrorTime = 0,
cooldown = 5, -- seconds
},
}
---------------------------------------------------
-- Utility Functions
---------------------------------------------------
-- Utility function to log messages with a prefix
local function Log(message, isError)
if isError then
if FirstPersonView.config.notifyOnError then chat.AddText(Color(255, 0, 0), "[FirstPersonView] " .. message) end
print("[FirstPersonView] " .. message)
else
print("[FirstPersonView] " .. message)
end
end
-- Utility function to check and update the rate limiter
local function CanNotifyError()
local currentTime = CurTime()
if currentTime - FirstPersonView.errorRateLimiter.lastErrorTime >= FirstPersonView.errorRateLimiter.cooldown then
FirstPersonView.errorRateLimiter.lastErrorTime = currentTime
return true
end
return false
end
---------------------------------------------------
-- Configuration Loading and Management
---------------------------------------------------
-- Function to load and apply camera offset from ConVar
local function LoadCameraOffset()
local offsetX = GetConVar("fvp_camera_offset_x"):GetFloat()
local offsetY = GetConVar("fvp_camera_offset_y"):GetFloat()
local offsetZ = GetConVar("fvp_camera_offset_z"):GetFloat()
FirstPersonView.config.cameraOffset = Vector(offsetX, offsetY, offsetZ)
end
-- Function to load head bone names from ConVar (comma-separated)
local function LoadHeadBoneNames()
local boneNamesString = GetConVar("fvp_head_bone_names"):GetString()
local boneNamesRaw = string.Split(boneNamesString, ",")
-- Trim whitespace and ensure uniqueness using a temporary table
local uniqueBoneSet = {}
local uniqueBoneList = {}
for _, name in ipairs(boneNamesRaw) do
local trimmed = string.Trim(name)
if trimmed ~= "" and not uniqueBoneSet[trimmed] then
table.insert(uniqueBoneList, trimmed)
uniqueBoneSet[trimmed] = true
end
end
FirstPersonView.config.headBoneNames = uniqueBoneList
end
-- Function to load spectator team from ConVar
local function LoadSpectatorTeam()
-- Attempt to fetch TEAM_SPECTATOR safely
local spectatorTeam = GetConVar("fvp_spectator_team"):GetInt()
if spectatorTeam <= 0 then
-- Fallback to default if invalid
spectatorTeam = TEAM_SPECTATOR or 8
end
FirstPersonView.config.spectatorTeam = spectatorTeam
end
-- Function to initialize ConVars for dynamic configuration
local function InitializeConVars()
CreateClientConVar("fvp_camera_offset_x", "0", true, false, "FirstPersonView: Camera offset X (forward/backward)")
CreateClientConVar("fvp_camera_offset_y", "0", true, false, "FirstPersonView: Camera offset Y (left/right)")
CreateClientConVar("fvp_camera_offset_z", "0", true, false, "FirstPersonView: Camera offset Z (up/down)")
CreateClientConVar("fvp_head_bone_names", "ValveBiped.Bip01_Head1,ValveBiped.Bip01_Neck1,ValveBiped.Bip01_EyeLeft,ValveBiped.Bip01_EyeRight,ValveBiped.Bip01_Mouth", true, false, "FirstPersonView: Comma-separated list of head bone names")
CreateClientConVar("fvp_spectator_team", tostring(TEAM_SPECTATOR or 8), true, false, "FirstPersonView: Spectator team identifier")
end
-- Function to refresh configuration from ConVars
local function RefreshConfig()
LoadCameraOffset()
LoadHeadBoneNames()
LoadSpectatorTeam()
end
-- Hook to watch for ConVar changes and refresh configuration accordingly
local function SetupConVarChangeHooks()
-- Camera Offset Changes
cvars.AddChangeCallback("fvp_camera_offset_x", LoadCameraOffset, "FirstPersonView_CameraOffsetX")
cvars.AddChangeCallback("fvp_camera_offset_y", LoadCameraOffset, "FirstPersonView_CameraOffsetY")
cvars.AddChangeCallback("fvp_camera_offset_z", LoadCameraOffset, "FirstPersonView_CameraOffsetZ")
-- Head Bone Names Change
cvars.AddChangeCallback("fvp_head_bone_names", LoadHeadBoneNames, "FirstPersonView_HeadBoneNames")
-- Spectator Team Change
cvars.AddChangeCallback("fvp_spectator_team", LoadSpectatorTeam, "FirstPersonView_SpectatorTeam")
end
---------------------------------------------------
-- Bone Caching
---------------------------------------------------
-- Function to cache head bone indices for the local player
function FirstPersonView:CacheHeadBones()
local ply = LocalPlayer()
if not IsValid(ply) then
if CanNotifyError() then Log("Local player is not valid. Cannot cache head bones.", true) end
return
end
local model = ply:GetModel()
if not model or model == "" then
if CanNotifyError() then Log("Local player's model is invalid. Cannot cache head bones.", true) end
return
end
-- Clear existing cached bones
table.Empty(self.headBoneIndices)
-- Iterate through the list of possible head bone names and cache all found bones
for _, boneName in ipairs(self.config.headBoneNames) do
local boneIndex = ply:LookupBone(boneName)
if boneIndex then
table.insert(self.headBoneIndices, boneIndex)
-- Optional: Uncomment the following line to reduce console spam
-- Log("Cached head bone '" .. boneName .. "' (Index: " .. tostring(boneIndex) .. ") for model '" .. model .. "'.", false)
end
end
-- If no head bones found, log warning with rate limiting
if #self.headBoneIndices == 0 and CanNotifyError() then Log("Warning: No valid head bones found for model '" .. model .. "'. Expected bones: " .. table.concat(self.config.headBoneNames, ", "), true) end
end
---------------------------------------------------
-- Camera Positioning
---------------------------------------------------
-- Function to get the head position for the local player
function FirstPersonView:GetHeadPosition()
local ply = LocalPlayer()
if not IsValid(ply) then return nil end
if #self.headBoneIndices == 0 then
-- Attempt to cache head bones if not already cached
self:CacheHeadBones()
if #self.headBoneIndices == 0 then
-- Fallback to eye position if head bones not found
Log("Using eye position as fallback for camera.", true)
return ply:EyePos()
end
end
-- Use the first valid head bone position
local boneIndex = self.headBoneIndices[1]
local bonePos = ply:GetBonePosition(boneIndex)
if bonePos then
return bonePos
else
Log("Failed to get position for head bone index " .. tostring(boneIndex) .. ". Using eye position.", true)
return ply:EyePos()
end
end
-- Variable to store the current view
local currentView = {
origin = Vector(0, 0, 0),
angles = Angle(0, 0, 0),
fov = 0,
drawviewer = false,
}
-- Hook to calculate and set the camera view
function FirstPersonView:CalcView(ply, pos, angles, fov)
if not IsValid(ply) then return end
if ply:Team() == self.config.spectatorTeam then return end
local headPos = self:GetHeadPosition()
if not headPos then return end
-- Use the player's actual view angles to ensure camera aligns with player's view
local playerAngles = ply:EyeAngles()
-- Calculate the desired camera position based on the head position and camera offset
local desiredCameraPos = headPos + playerAngles:Forward() * self.config.cameraOffset.x + playerAngles:Right() * self.config.cameraOffset.y + playerAngles:Up() * self.config.cameraOffset.z
-- Implement camera collision detection to prevent clipping
if self.config.cameraCollision then
local trace = {}
trace.start = headPos
trace.endpos = desiredCameraPos
trace.filter = ply
trace.mask = MASK_SOLID -- Изменено с MASK_VISIBLE_AND_NPCS на MASK_SOLID
trace.min = Vector(-self.config.hullSize, -self.config.hullSize, -self.config.hullSize) -- Минимальные размеры Hull
trace.max = Vector(self.config.hullSize, self.config.hullSize, self.config.hullSize) -- Максимальные размеры Hull
local tr = util.TraceHull(trace) -- Используется TraceHull вместо TraceLine
if tr.Hit then
local distance = tr.HitPos:Distance(headPos)
if distance < self.config.maxCameraDistance then
desiredCameraPos = tr.HitPos
else
-- Ограничьте дистанцию камеры
desiredCameraPos = headPos + playerAngles:Forward() * self.config.maxCameraDistance + playerAngles:Right() * self.config.cameraOffset.y + playerAngles:Up() * self.config.cameraOffset.z
end
end
end
-- Установите позицию камеры и углы без сглаживания
currentView.origin = desiredCameraPos
currentView.angles = playerAngles
currentView.fov = fov
currentView.drawviewer = self.config.drawLocalPlayer
return currentView
end
---------------------------------------------------
-- Local Player Model Rendering
---------------------------------------------------
-- Function to determine whether to draw the local player model
function FirstPersonView:ShouldDrawLocalPlayer()
local ply = LocalPlayer()
if not IsValid(ply) then return true end
-- Do not draw the player model if in spectator mode
if ply:Team() == self.config.spectatorTeam then return false end
return self.config.drawLocalPlayer
end
---------------------------------------------------
-- Bone Manipulation for Head Hiding
---------------------------------------------------
-- Store original bone scales to restore after manipulation
FirstPersonView.originalBoneScales = {}
-- Function to hide the player's head bones
function FirstPersonView:HideHeadBones()
local ply = LocalPlayer()
if not IsValid(ply) then return end
if #self.headBoneIndices == 0 then return end
for _, boneIndex in ipairs(self.headBoneIndices) do
-- Store the original scale if not already stored
if not self.originalBoneScales[boneIndex] then
local originalScale = ply:GetManipulateBoneScale(boneIndex)
if originalScale then
self.originalBoneScales[boneIndex] = originalScale
else
self.originalBoneScales[boneIndex] = Vector(1, 1, 1)
end
end
-- Hide the bone by setting its scale to zero
ply:ManipulateBoneScale(boneIndex, Vector(0, 0, 0))
end
end
-- Function to restore the player's head bones
function FirstPersonView:RestoreHeadBones()
local ply = LocalPlayer()
if not IsValid(ply) then return end
if #self.headBoneIndices == 0 then return end
for _, boneIndex in ipairs(self.headBoneIndices) do
if self.originalBoneScales[boneIndex] then
ply:ManipulateBoneScale(boneIndex, self.originalBoneScales[boneIndex])
self.originalBoneScales[boneIndex] = nil
else
-- If original scale wasn't stored, ensure it's visible
ply:ManipulateBoneScale(boneIndex, Vector(1, 1, 1))
end
end
end
-- Hook to handle pre-player draw
function FirstPersonView:PrePlayerDraw(ply)
if ply ~= LocalPlayer() then return end
self:HideHeadBones()
end
-- Hook to handle post-player draw
function FirstPersonView:PostPlayerDraw(ply)
if ply ~= LocalPlayer() then return end
self:RestoreHeadBones()
end
---------------------------------------------------
-- Event Handlers
---------------------------------------------------
-- Hook to handle player model changes
function FirstPersonView:OnPlayerSetModel(ply)
if ply ~= LocalPlayer() then return end
self:CacheHeadBones()
end
-- Hook to handle player spawn events
function FirstPersonView:OnPlayerSpawn(ply)
if ply ~= LocalPlayer() then return end
-- Delay caching to ensure the model is fully loaded
timer.Simple(0.5, function() if IsValid(ply) then self:CacheHeadBones() end end)
end
-- Hook to handle player disconnection and clean up cache
function FirstPersonView:OnPlayerDisconnected(ply)
if ply ~= LocalPlayer() then return end
-- Clear cached bone indices and restore bone scales if necessary
if #self.headBoneIndices > 0 then
self:RestoreHeadBones()
table.Empty(self.headBoneIndices)
Log("Cleared cached head bones due to player disconnection.", false)
end
end
---------------------------------------------------
-- Initialization and Cleanup
---------------------------------------------------
-- Function to clean up all hooks and cached data
function FirstPersonView:RemoveHooks()
hook.Remove("CalcView", "FirstPersonView_CalcView")
hook.Remove("ShouldDrawLocalPlayer", "FirstPersonView_ShouldDrawLocalPlayer")
hook.Remove("PlayerSetModel", "FirstPersonView_PlayerSetModel")
hook.Remove("PlayerSpawn", "FirstPersonView_PlayerSpawn")
hook.Remove("PrePlayerDraw", "FirstPersonView_PrePlayerDraw")
hook.Remove("PostPlayerDraw", "FirstPersonView_PostPlayerDraw")
hook.Remove("PlayerDisconnected", "FirstPersonView_PlayerDisconnected")
hook.Remove("ShutDown", "FirstPersonView_ShutDown")
-- Restore bone scales if hidden
self:RestoreHeadBones()
-- Clear cached bone indices
table.Empty(self.headBoneIndices)
self.initialized = false
Log("All hooks removed and caches cleared.", false)
end
-- Initialization function
function FirstPersonView:Initialize()
if self.initialized then
Log("Initialization skipped: already initialized.", false)
return
end
self.initialized = true
InitializeConVars()
RefreshConfig()
SetupConVarChangeHooks()
-- Cache head bones for the local player
self:CacheHeadBones()
-- Register hooks
hook.Add("CalcView", "FirstPersonView_CalcView", function(ply, pos, angles, fov) return FirstPersonView:CalcView(ply, pos, angles, fov) end)
hook.Add("ShouldDrawLocalPlayer", "FirstPersonView_ShouldDrawLocalPlayer", function() return FirstPersonView:ShouldDrawLocalPlayer() end)
hook.Add("PlayerSetModel", "FirstPersonView_PlayerSetModel", function(ply) FirstPersonView:OnPlayerSetModel(ply) end)
hook.Add("PlayerSpawn", "FirstPersonView_PlayerSpawn", function(ply) FirstPersonView:OnPlayerSpawn(ply) end)
hook.Add("PrePlayerDraw", "FirstPersonView_PrePlayerDraw", function(ply) FirstPersonView:PrePlayerDraw(ply) end)
hook.Add("PostPlayerDraw", "FirstPersonView_PostPlayerDraw", function(ply) FirstPersonView:PostPlayerDraw(ply) end)
hook.Add("PlayerDisconnected", "FirstPersonView_PlayerDisconnected", function(ply) FirstPersonView:OnPlayerDisconnected(ply) end)
hook.Add("ShutDown", "FirstPersonView_ShutDown", function() FirstPersonView:RemoveHooks() end)
Log("FirstPersonView initialized successfully.", false)
end
---------------------------------------------------
-- Start Initialization if Not Already Initialized
---------------------------------------------------
-- Prevent multiple instances by checking if already initialized
if not FirstPersonView.initialized then
-- Delay initialization to ensure teams and other dependencies are loaded
hook.Add("InitPostEntity", "FirstPersonView_Initialize", function() FirstPersonView:Initialize() end)
end
-------------------------------------------------------------------
-- End of FirstPersonView Module
-------------------------------------------------------------------
end
Найди ошибки, баги, проблемы, утечки и недостатки, напиши их.
The provided Lua script appears to be designed for Garry's Mod (GMod) to create a precise first-person view by positioning the camera at the player's head and optionally hiding the head bones to prevent the model from obstructing the view. While the script is comprehensive and well-structured, several potential issues, bugs, and areas for improvement exist. Below is a detailed analysis of these concerns:
PlayerDisconnected Hook:
PlayerDisconnected hook primarily exists on the server side. On the client side, this hook might not function as intended because the client may not receive this event directly.OnPlayerDisconnected function may never be called on the client, leading to potential resource leaks or improper cleanup of cached data.PlayerDisconnected hook is functional on the client. If not, consider alternative methods such as using networking (net) to notify the client of disconnections or handle cleanup on client-side events like OnRemove for the player entity.ShutDown Hook:
ShutDown hook is typically a server-side event. Its client-side counterpart may not exist or behave differently.RemoveHooks function might not be triggered correctly, preventing proper cleanup when the client shuts down.OnRemove for the player entity or other appropriate client-side events.Client-Side Bone Manipulation:
ManipulateBoneScale are used to hide head bones by scaling them to zero. However, manipulating bones on the client side may not always produce the desired visual effect, especially if the server also controls bone scales or if other client-side scripts manipulate bones.Storing Original Bone Scales:
originalBoneScales) without considering that multiple scripts might modify the same bones.ConVar Change Callbacks Not Cleaned Up:
RemoveHooks).RemoveHooks is called.Default Spectator Team Value:
tostring(TEAM_SPECTATOR or 8). If TEAM_SPECTATOR is undefined, 8 is used, assuming it's the default spectator team.TEAM_SPECTATOR is not 8, the spectator team identification may be incorrect, causing unintended behavior like incorrect player rendering.timer.Simple(0.5, ...) to delay bone caching after a player spawns. This arbitrary delay might not always align with the actual model loading time.Limited Error Information:
Rate Limiting for Error Notifications:
Fixed Hull Size and Mask:
hullSize = 2) and MASK_SOLID. This might not be suitable for all maps or scenarios.Camera Position Clamping:
maxCameraDistance. However, if the collision occurs beyond this distance, the camera might not position correctly relative to the player's view.ValveBiped.Bip01_Head1, etc.) which may not exist in all player models.ShouldDrawLocalPlayer Logic:
ShouldDrawLocalPlayer returns false if the player is on the spectator team, regardless of the drawLocalPlayer configuration.drawLocalPlayer, but spectators always have it hidden. This might not align with user expectations or server configurations.GetHeadPosition function attempts to cache head bones if none are cached each time it's called and fails, which could lead to repeated bone lookups every frame if caching continually fails.CalcView.Incomplete Hook Removal:
RemoveHooks function removes several hooks but does not remove ConVar change callbacks.RemoveHooks function to unregister all ConVar change callbacks.Residual State After Cleanup:
LocalPlayer Validity:
LocalPlayer() is valid but does not account for situations where the local player might not be fully initialized or might change.LocalPlayer() might fail or behave unexpectedly during transitions, such as switching characters or during initial loading.LocalPlayer() is fully initialized before performing operations.timer.Simple for delayed operations introduces concurrency aspects where operations are scheduled independently of the main execution flow.Hard-to-Maintain Configuration Loading:
Lack of Documentation and User Guidance:
LoadHeadBoneNames function splits the ConVar string by commas and trims whitespace but does not handle cases where bone names might contain commas or invalid characters.SetRenderMode to hide specific parts.While the script demonstrates thoughtful structuring and comprehensive functionality for implementing a first-person view in GMod, addressing the aforementioned issues is crucial for ensuring reliability, performance, and a positive user experience. Implementing the recommended changes will help mitigate potential bugs, enhance maintainability, and broaden compatibility with various player models and server configurations.
Not yet included in a published release.