Cache and entities update

added cache system similar to others that are readily available. Included beginings of reworked rebound entities
This commit is contained in:
gononono64 committed 2025-04-23 14:10:19 -05:00
1 parent b9842eedfe
commit 89858c6d73
16 files changed
+589 -207

No files matched your search

+200
View File
@@ -0,0 +1,200 @@
Utility = Utility or Require("lib/utility/client/utility.lua")
Ids = Ids or Require("lib/utility/shared/ids.lua")
Point = Point or Require("lib/points/client/points.lua")
ClientEntityActions = ClientEntityActions or Require("lib/entities/client/client_entity_actions.lua") -- Added
local Entities = {} -- Stores entity data received from server
ClientEntity = {} -- Renamed from BaseEntity
local function SpawnEntity(entityData)
entityData = entityData and entityData.args
if entityData.spawned and DoesEntityExist(entityData.spawned) then return end -- Already spawned
-- for k, v in pairs(entityData.args) do
-- print(string.format("SpawnEntity %s: %s", k, v))
-- end
local model = entityData.model and type(entityData.model) == 'string' and GetHashKey(entityData.model) or entityData.model
if not Utility.LoadModel(model) then
print(string.format("[ClientEntity] Failed to load model %s for entity %s", entityData.model, entityData.id))
return
end
local entity = nil
local coords = entityData.coords
local rotation = entityData.rotation
if entityData.entityType == 'object' then
entity = CreateObject(model, coords.x, coords.y, coords.z, false, false, false)
SetEntityRotation(entity, rotation.x, rotation.y, rotation.z, 2, true)
elseif entityData.entityType == 'ped' then
entity = CreatePed(4, model, coords.x, coords.y, coords.z, type(rotation) == 'number' and rotation or rotation.z, false, false)
-- Apply ped specific settings from entityData.meta if needed
elseif entityData.entityType == 'vehicle' then
entity = CreateVehicle(model, coords.x, coords.y, coords.z, type(rotation) == 'number' and rotation or rotation.z, false, false)
-- Apply vehicle specific settings from entityData.meta if needed
else
print(string.format("[ClientEntity] Unknown entity type '%s' for entity %s", entityData.entityType, entityData.id))
end
if entity then
entityData.spawned = entity
SetModelAsNoLongerNeeded(model)
SetEntityAsMissionEntity(entity, true, true) -- Keep entity from being deleted by game engine
FreezeEntityPosition(entity, entityData.freeze or false) -- Optional freeze based on meta
if entityData.OnSpawn and type(entityData.OnSpawn) == 'function' then
entityData.OnSpawn(entityData)
end
-- print(string.format("[ClientEntity] Spawned %s entity %s (GameID: %s)", entityData.entityType, entityData.id, entity))
else
SetModelAsNoLongerNeeded(model)
end
end
local function RemoveEntity(entityData)
entityData = entityData and entityData.args
if not entityData then return end -- Added safety check
ClientEntityActions.StopAction(entityData.id) -- Stop any ongoing action before despawning
if entityData.spawned and DoesEntityExist(entityData.spawned) then
local entityHandle = entityData.spawned
entityData.spawned = nil -- Clear handle first
SetEntityAsMissionEntity(entityHandle, false, false) -- Allow game engine to delete if needed, though we delete manually
DeleteEntity(entityHandle)
-- print(string.format("[ClientEntity] Removed %s entity %s (GameID: %s)", entityData.entityType, entityData.id, entityHandle))
end
if entityData.OnRemove and type(entityData.OnRemove) == 'function' then
entityData.OnRemove(entityData)
end
end
--- Registers an entity received from the server and sets up proximity spawning.
-- @param entityData table Data received from the server via 'community_bridge:client:CreateEntity'
function ClientEntity.Register(entityData)
if Entities[entityData.id] then return end -- Already registered
Entities[entityData.id] = entityData
-- print(string.format("[ClientEntity] Registering %s entity %s", entityData.entityType, entityData.id))
-- Use Point system for proximity checks
Point.Register(entityData.id, entityData.coords, entityData.spawnDistance or 50.0, entityData, SpawnEntity, RemoveEntity, function() end)
end
--- Unregisters an entity and removes it from the world if spawned.
-- @param id string|number The ID of the entity to unregister.
function ClientEntity.Unregister(id)
local entityData = Entities[id]
if not entityData then return end
-- print(string.format("[ClientEntity] Unregistering entity %s", id))
Point.Remove(id) -- Remove from proximity checks (this will call RemoveEntity if currently in range)
RemoveEntity(entityData) -- Ensure it's removed even if Point.Remove didn't trigger it
Entities[id] = nil
end
--- Updates the data for a registered entity.
-- @param id string|number The ID of the entity to update.
-- @param data table The data fields to update.
function ClientEntity.Update(id, data)
local entityData = Entities[id]
print(string.format("[ClientEntity] Updating entity %s", id))
if not entityData then return end
local needsPointUpdate = false
for key, value in pairs(data) do
if key == 'coords' and #(entityData.coords - value) > 0.1 then
print(string.format("[ClientEntity] Updating coords for entity %s", id))
needsPointUpdate = true
end
if key == 'spawnDistance' and entityData.spawnDistance ~= value then
needsPointUpdate = true
end
entityData[key] = value
end
-- If entity is currently spawned, apply updates
if entityData.spawned and DoesEntityExist(entityData.spawned) then
if data.coords then
SetEntityCoords(entityData.spawned, entityData.coords.x, entityData.coords.y, entityData.coords.z, false, false, false, true)
end
if data.rotation then
if entityData.entityType == 'object' then
SetEntityRotation(entityData.spawned, entityData.rotation.x, entityData.rotation.y, entityData.rotation.z, 2, true)
else -- Ped/Vehicle heading
SetEntityHeading(entityData.spawned, type(entityData.rotation) == 'number' and entityData.rotation or entityData.rotation.z)
end
end
if data.freeze ~= nil then
FreezeEntityPosition(entityData.spawned, data.freeze)
end
-- Add other updatable properties as needed
end
-- Update Point registration if coords or distance changed
if needsPointUpdate then
Point.Remove(id)
Point.Register(
entityData.id,
entityData.coords,
entityData.spawnDistance or 50.0,
SpawnEntity,
RemoveEntity,
nil,
entityData
)
end
if entityData.OnUpdate and type(entityData.OnUpdate) == 'function' then
entityData.OnUpdate(entityData, data)
end
end
function ClientEntity.Get(id)
return Entities[id]
end
function ClientEntity.GetAll()
return Entities
end
-- Network Event Handlers
RegisterNetEvent("community_bridge:client:CreateEntity", function(entityData)
ClientEntity.Register(entityData)
end)
RegisterNetEvent("community_bridge:client:DeleteEntity", function(id)
ClientEntity.Unregister(id)
end)
RegisterNetEvent("community_bridge:client:UpdateEntity", function(id, data)
ClientEntity.Update(id, data)
end)
-- New handler for entity actions
RegisterNetEvent("community_bridge:client:TriggerEntityAction", function(entityId, actionName, ...)
local entityData = Entities[entityId]
-- Check if entity exists locally AND is currently spawned
if entityData and entityData.spawned and DoesEntityExist(entityData.spawned) then
local actionFunc = ClientEntityActions[actionName]
if actionFunc and type(actionFunc) == 'function' then
-- print(string.format("[ClientEntity] Executing action '%s' for entity %s", actionName, entityId))
actionFunc(entityData, ...) -- Pass entityData and any additional arguments
else
print(string.format("[ClientEntity] Received unknown action '%s' for entity %s", actionName, entityId))
end
-- else
-- Optional: Log if action received but entity not spawned locally
-- print(string.format("[ClientEntity] Received action '%s' for entity %s, but entity not spawned locally.", actionName, entityId))
end
end)
-- Resource Stop Cleanup
AddEventHandler('onResourceStop', function(resourceName)
if resourceName == GetCurrentResourceName() then
for id, entityData in pairs(Entities) do
Point.Remove(id) -- Clean up point registration
RemoveEntity(entityData) -- Clean up spawned game entity
end
Entities = {} -- Clear local cache
end
end)
return ClientEntity
@@ -0,0 +1,101 @@
local LA = LA or Require("lib/utility/shared/la.lua")
local ActionThreads = {} -- Store running action threads { [entityId] = thread }
ClientEntityActions = {}
--- Makes a ped entity walk to specified coordinates.
-- @param entityData table The entity data containing the spawned ped handle.
-- @param coords vector3 The target coordinates.
-- @param speed number Movement speed.
-- @param timeout number Timeout in ms.
function ClientEntityActions.WalkTo(entityData, coords, speed, timeout)
local entity = entityData.spawned
if not entity or not DoesEntityExist(entity) or not IsEntityAPed(entity) then return end
-- Clear any existing task for this entity
if ActionThreads[entityData.id] then
-- Potentially stop the old thread if needed, depending on desired behavior
ClearPedTasks(entity)
end
local thread = CreateThread(function()
TaskGoToCoordAnyMeans(entity, coords.x, coords.y, coords.z, speed or 1.0, 0, false, 786603, timeout or -1)
-- Wait until task is completed or entity is despawned
while GetScriptTaskStatus(entity, 288358301) ~= 7 and entityData.spawned == entity and DoesEntityExist(entity) do
Wait(500)
end
ActionThreads[entityData.id] = nil -- Clear thread reference when done/stopped
end)
ActionThreads[entityData.id] = thread
end
--- Lerps an entity's position over time.
-- @param entityData table The entity data containing the spawned entity handle.
-- @param targetCoords vector3 The target coordinates.
-- @param duration number Duration of the lerp in milliseconds.
-- @param easingType string (Optional) Easing function name from LA library (e.g., "linear", "sine").
-- @param easingDirection string (Optional) "in", "out", or "inout".
function ClientEntityActions.LerpTo(entityData, targetCoords, duration, easingType, easingDirection)
local entity = entityData.spawned
if not entity or not DoesEntityExist(entity) then return end
local startCoords = GetEntityCoords(entity)
local startTime = GetGameTimer()
easingType = easingType or "linear"
easingDirection = easingDirection or "inout"
-- Clear any existing lerp for this entity
if ActionThreads[entityData.id] then
-- Stop the old thread if needed
end
local thread = CreateThread(function()
while GetGameTimer() < startTime + duration do
-- Check if entity still exists and is the same one we started with
if not entityData.spawned or entityData.spawned ~= entity or not DoesEntityExist(entity) then
break -- Stop if entity despawned or changed
end
local elapsed = GetGameTimer() - startTime
local t = LA.Clamp(elapsed / duration, 0.0, 1.0)
local easedT = LA.EaseInOut(t, easingType) -- Default to EaseInOut if direction not specified or invalid
if easingDirection == "in" then
easedT = LA.EaseIn(t, easingType)
elseif easingDirection == "out" then
easedT = LA.EaseOut(t, easingType)
end
local currentPos = LA.LerpVector(startCoords, targetCoords, easedT)
SetEntityCoordsNoOffset(entity, currentPos.x, currentPos.y, currentPos.z, false, false, false)
Wait(0)
end
-- Ensure final position if completed fully
if entityData.spawned == entity and DoesEntityExist(entity) then
SetEntityCoordsNoOffset(entity, targetCoords.x, targetCoords.y, targetCoords.z, false, false, false)
end
ActionThreads[entityData.id] = nil -- Clear thread reference
end)
ActionThreads[entityData.id] = thread
end
--- Stops any ongoing action for a specific entity.
-- @param entityId string|number The ID of the entity.
function ClientEntityActions.StopAction(entityId)
if ActionThreads[entityId] then
-- Stopping Lua threads directly isn't safe/possible.
-- Instead, rely on checks within the thread loops (e.g., entityData.spawned check)
-- For peds, we can clear tasks.
local entityData = ClientEntity.Get(entityId) -- Assumes ClientEntity is accessible or passed in
if entityData and entityData.spawned and DoesEntityExist(entityData.spawned) then
if IsEntityAPed(entityData.spawned) then
ClearPedTasks(entityData.spawned)
end
-- Other entity types might need different stop logic if applicable
end
ActionThreads[entityId] = nil -- Clear reference to let the thread terminate naturally
end
end
return ClientEntityActions
-51
View File
@@ -1,51 +0,0 @@
-- Objects
Utility = Utility or Require("lib/utility/client/utility.lua")
Ids = Ids or Require("lib/utility/shared/ids.lua")
Point = Point or Require("lib/points/client/points.lua")
local Entities = {}
BaseEntity = {}
function BaseEntity.Create(id, model, coords, rotation, meta)
local self = meta or {}
if id and type(id) == "table" then
self = id
self.id = id.id or Ids.CreateUniqueId(Entities)
self.rotation = id.rotation or vector3(0.0, 0.0, 0.0)
else
self.id = id or Ids.CreateUniqueId(Entities)
self.model = model
self.coords = coords
self.rotation = rotation or vector3(0.0, 0.0, 0.0)
end
assert(self.id, "ID Failed to generate")
assert(self.model, "Model is required for entity creation")
assert(self.coords, "Coords are required for entity creation")
self.Spawn = self.Spawn or function() end
self.Remove = self.Remove or function() end
return Point.Register(self.id, self.coords, 50.0, self.Spawn, self.Remove, nil, self)
end
function BaseEntity.GetAll()
return Entities
end
function BaseEntity.Get(id)
return Entities[id]
end
function BaseEntity.Add(self)
Entities[self.id] = self
end
function BaseEntity.Remove(id)
Entities[id] = nil
end
function BaseEntity.LoadModel(model)
return Utility.LoadModel(model)
end
return BaseEntity
-71
View File
@@ -1,71 +0,0 @@
BaseEntity = BaseEntity or Require("lib/entities/client/entity_base.lua")
local Objects = {}
Object = {}
function Object.Create(id, model, coords, rotation, meta)
local base = meta or {}
if id and type(id) == "table" then
base = id
base.id = id.id or Ids.CreateUniqueId(Objects)
base.rotation = id.rotation or vector3(0.0, 0.0, 0.0)
else
base.id = id or Ids.CreateUniqueId(Objects)
base.model = model
base.coords = coords
base.rotation = rotation or vector3(0.0, 0.0, 0.0)
end
assert(base.id, "ID Failed to generate")
assert(base.model, "Model is required for entity creation")
assert(base.coords, "Coords are required for entity creation")
base.Spawn = function(self)
print("Spawning object", self)
if not BaseEntity.LoadModel(self.model) then return end
self.entity = CreateObject(self.model, self.coords.x, self.coords.y, self.coords.z, false, false, false)
SetEntityRotation(self.entity, self.rotation.x, self.rotation.y, self.rotation.z, 2, false)
SetEntityAsMissionEntity(self.entity, true, true)
SetModelAsNoLongerNeeded(self.model)
if self.OnSpawn then self.OnSpawn(self, self.entity, self.coords, self.rotation) end
return self.entity
end
base.Remove = function(self)
DeleteEntity(self.entity)
if self.OnRemove then self.OnRemove(self, self.entity) end
self.entity = nil
end
Object.Add(base)
return BaseEntity.Create(base)
end
function Object.GetAll()
return Objects
end
function Object.Get(id)
return Objects[id]
end
function Object.Add(self)
Objects[self.id] = self
end
function Object.Remove(id)
Objects[id] = nil
end
function Object.SetOnSpawn(id, callback)
local obj = Object.Get(id)
if not obj then return end
obj.OnSpawn = callback
return true
end
function Object.SetOnRemove(id, callback)
local obj = Object.Get(id)
if not obj then return end
obj.OnRemove = callback
return true
end
return Object
-46
View File
@@ -1,46 +0,0 @@
-- Objects
Ids = Ids or Require("lib/utility/shared/ids.lua")
local Entities = {}
EntityRelay = {}
function EntityRelay.Create(id, model, coords, rotation, meta)
local self = meta or {}
if id and type(id) == "table" then
self = id
self.id = id.id or Ids.CreateUniqueId(Entities)
self.rotation = id.rotation or vector3(0.0, 0.0, 0.0)
else
self.id = id or Ids.CreateUniqueId(Entities)
self.model = model
self.coords = coords
self.rotation = rotation or vector3(0.0, 0.0, 0.0)
end
assert(self.id, "ID Failed to generate")
assert(self.model, "Model is required for entity creation")
assert(self.coords, "Coords are required for entity creation")
EntityRelay.Add(self)
TriggerClientEvent(GetCurrentResourceName() .. "client:CreateEntity", -1, self)
end
function EntityRelay.GetAll()
return Entities
end
function EntityRelay.Get(id)
return Entities[id]
end
function EntityRelay.Add(self)
Entities[self.id] = self
end
function EntityRelay.Remove(id)
Entities[id] = nil
end
function EntityRelay.LoadModel(model)
return Utility.LoadModel(model)
end
return EntityRelay
+100
View File
@@ -0,0 +1,100 @@
Ids = Ids or Require("lib/utility/shared/ids.lua")
local Entities = {}
ServerEntity = {} -- Renamed from EntityRelay
--- Creates a server-side representation of an entity and notifies clients.
-- @param entityType string 'object', 'ped', or 'vehicle'
-- @param model string|number
-- @param coords vector3
-- @param rotation vector3|number Heading for peds/vehicles, rotation for objects
-- @param meta table Optional additional data
-- @return table The created entity data
function ServerEntity.Create(id, entityType, model, coords, rotation, meta)
local self = meta or {}
self.id = id or Ids.CreateUniqueId(Entities)
self.entityType = entityType
self.model = model
self.coords = coords
self.rotation = rotation or (entityType == 'object' and vector3(0.0, 0.0, 0.0) or 0.0) -- Default rotation or heading
self.resource = GetInvokingResource()
assert(self.id, "ID Failed to generate")
assert(self.entityType, "EntityType is required")
assert(self.model, "Model is required for entity creation")
assert(self.coords, "Coords are required for entity creation")
ServerEntity.Add(self)
TriggerClientEvent("community_bridge:client:CreateEntity", -1, self)
return self
end
--- Deletes a server-side entity representation and notifies clients.
-- @param id string|number The ID of the entity to delete.
function ServerEntity.Delete(id)
if Entities[id] then
ServerEntity.Remove(id)
TriggerClientEvent("community_bridge:client:DeleteEntity", -1, id)
end
end
--- Updates data for a server-side entity and notifies clients.
-- @param id string|number The ID of the entity to update.
-- @param data table The data fields to update.
function ServerEntity.Update(id, data)
local entity = Entities[id]
print("Updating entity: ", id, entity)
if not entity then return false end
for key, value in pairs(data) do
entity[key] = value
end
TriggerClientEvent("community_bridge:client:UpdateEntity", -1, id, data)
return true
end
--- Triggers a specific action on the client-side entity.
-- Clients will only execute the action if the entity is currently spawned for them.
-- @param entityId string|number The ID of the entity.
-- @param actionName string The name of the action to trigger (must match a function in ClientEntityActions).
-- @param ... any Additional arguments for the action function.
function ServerEntity.TriggerAction(entityId, actionName, ...)
local entity = Entities[entityId]
if not entity then
print(string.format("[ServerEntity] Attempted to trigger action '%s' on non-existent entity %s", actionName, entityId))
return
end
TriggerClientEvent("community_bridge:client:TriggerEntityAction", -1, entityId, actionName, ...)
end
function ServerEntity.GetAll()
return Entities
end
function ServerEntity.Get(id)
return Entities[id]
end
function ServerEntity.Add(self)
Entities[self.id] = self
end
function ServerEntity.Remove(id)
Entities[id] = nil
end
-- Clean up entities associated with a stopped resource
AddEventHandler('onResourceStop', function(resourceName)
local toDelete = {}
for id, entity in pairs(Entities) do
if entity.resource == resourceName then
table.insert(toDelete, id)
end
end
for _, id in pairs(toDelete) do
ServerEntity.Delete(id)
end
end)
return ServerEntity