Certainly! Below is the optimized and restructured version of your Lua script. The improvements include:
- Consistent Naming Conventions: Adopted
camelCase for function and variable names to maintain consistency.
- Enhanced Readability: Added comments for better understanding and organized the code into logical sections.
- Performance Optimizations:
- Reduced repeated calculations by precomputing frequently used values.
- Utilized
local declarations where appropriate to enhance performance.
- Modular Structure: Grouped related functionalities together and separated concerns for better maintainability.
local Vector3D = require('vector3d')
local SphereLibrary = {}
local spheres = {}
-- Constants
local mathRad = math.rad
local TWO_PI, PI = mathRad(360), mathRad(180)
-- Utility Functions
--- Updates the position of the sphere if it follows a player.
-- @param sphere The sphere to update.
local function updatePosition(sphere)
if sphere.followPlayer then
sphere.center = Vector3D(getCharCoordinates(sphere.playerPed))
end
end
--- Calculates a point on the sphere based on spherical coordinates.
-- @param sphere The sphere for which the point is calculated.
-- @param phi The polar angle in radians.
-- @param theta The azimuthal angle in radians.
-- @return The calculated Vector3D point.
local function calculatePoint(sphere, phi, theta)
local sinPhi = math.sin(phi)
local x = sphere.radius * sinPhi * math.cos(theta)
local y = sphere.radius * sinPhi * math.sin(theta)
local z = sphere.radius * math.cos(phi)
return Vector3D(x, y, z) + sphere.center
end
--- Renders a line between two 3D points on the screen.
-- @param point1 The starting Vector3D point.
-- @param point2 The ending Vector3D point.
-- @param width The width of the line.
-- @param color The color of the line.
local function renderLine(point1, point2, width, color)
local visible1, screenX1, screenY1 = convert3DCoordsToScreenEx(point1.x, point1.y, point1.z)
local visible2, screenX2, screenY2 = convert3DCoordsToScreenEx(point2.x, point2.y, point2.z)
if visible1 and visible2 then
renderDrawLine(screenX1, screenY1, screenX2, screenY2, width, color)
end
end
--- Renders the sphere by drawing lines between calculated points.
-- @param sphere The sphere to render.
local function renderSphere(sphere)
local stepTheta = TWO_PI / sphere.detailLevel
local stepPhi = PI / sphere.detailLevel
for theta = 0, TWO_PI, stepTheta do
for phi = stepPhi, PI - stepPhi, stepPhi do
local point1 = calculatePoint(sphere, phi, theta)
local point2 = calculatePoint(sphere, phi, theta + stepTheta)
local point3 = calculatePoint(sphere, phi + stepPhi, theta)
renderLine(point1, point2, 1, sphere.color)
renderLine(point1, point3, 1, sphere.color)
end
end
end
--- Checks if a given point is inside a sphere.
-- @param point The Vector3D point to check.
-- @param center The center Vector3D of the sphere.
-- @param radius The radius of the sphere.
-- @return True if the point is inside the sphere, false otherwise.
local function isPointInSphere(point, center, radius)
if type(point.x) ~= "number" or type(center.x) ~= "number" then
return false
end
local dx, dy, dz = point.x - center.x, point.y - center.y, point.z - center.z
return (dx * dx + dy * dy + dz * dz) <= (radius * radius)
end
--- Collects entities that are inside the specified sphere.
-- @param sphereId The ID of the sphere to check against.
-- @return A table containing objects, players, and cars inside the sphere.
function SphereLibrary.collectEntitiesInSphere(sphereId)
local sphere = spheres[sphereId]
if not sphere then return nil end
local entities = { objects = {}, players = {}, cars = {} }
--- Helper function to add entities to the list if they are inside the sphere.
-- @param getAllEntities Function to retrieve all entities.
-- @param getCoords Function to get coordinates of an entity.
-- @param getId Function to get the ID of an entity.
-- @param entityKey The key under which to store the entity IDs.
local function addEntities(getAllEntities, getCoords, getId, entityKey)
for _, entity in ipairs(getAllEntities()) do
if isPointInSphere(Vector3D(getCoords(entity)), sphere.center, sphere.radius) then
local _, entityId = getId(entity)
table.insert(entities[entityKey], entityId)
end
end
end
addEntities(getAllObjects, getObjectCoordinates, sampGetObjectSampIdByHandle, 'objects')
addEntities(getAllChars, getCharCoordinates, sampGetPlayerIdByCharHandle, 'players')
addEntities(getAllVehicles, getCarCoordinates, sampGetVehicleIdByCarHandle, 'cars')
return entities
end
--- Creates a new sphere and adds it to the spheres list.
-- @param playerPed The player ped to follow (if any).
-- @param radius The radius of the sphere.
-- @param followPlayer Boolean indicating if the sphere should follow the player.
-- @param centerX The X-coordinate of the sphere's center (default 0).
-- @param centerY The Y-coordinate of the sphere's center (default 0).
-- @param centerZ The Z-coordinate of the sphere's center (default 0).
-- @param detailLevel The detail level for rendering (default 5).
-- @param color The color of the sphere (default -1).
-- @return The ID of the created sphere.
function SphereLibrary.createSphere(playerPed, radius, followPlayer, centerX, centerY, centerZ, detailLevel, color)
local sphereId = #spheres + 1
spheres[sphereId] = {
playerPed = playerPed,
radius = radius,
followPlayer = followPlayer,
center = Vector3D(centerX or 0, centerY or 0, centerZ or 0),
detailLevel = detailLevel or 5,
color = color or -1
}
return sphereId
end
--- Updates and renders all spheres.
function SphereLibrary.updateRender()
for _, sphere in ipairs(spheres) do
updatePosition(sphere)
if isPointOnScreen(sphere.center.x, sphere.center.y, sphere.center.z) then
renderSphere(sphere)
end
end
end
return SphereLibrary
Key Improvements Explained
-
Naming Conventions:
- Functions: Converted function names to
camelCase for consistency (crtSph → createSphere, updRndr → updateRender, etc.).
- Variables: Renamed variables for clarity (
sphs → spheres, sph → sphere, ctr → center, etc.).
-
Code Structure:
- Sections: Organized the code into sections like Constants, Utility Functions, and Library Functions.
- Helper Functions: Created a helper function
addEntities inside collectEntitiesInSphere to avoid repetition.
-
Performance Optimizations:
- Local Variables: Improved the use of
local variables to reduce global namespace pollution and slightly increase performance.
- Precomputed Steps: Calculated
stepTheta and stepPhi once per sphere render instead of recalculating inside loops.
- Early Returns: Added an early return in
isPointInSphere if the point or center doesn't have numerical coordinates, preventing unnecessary calculations.
-
Error Handling:
- Validation: Added checks in
isPointInSphere to ensure that the points have numerical coordinates before performing calculations.
- Nil Checks: Returned
nil if the sphere with the given ID does not exist in collectEntitiesInSphere.
-
Documentation:
- Comments: Added
--- comments to describe the purpose and parameters of functions, enhancing readability and maintainability.
-
Functionality Preservation:
- Ensured that all original functionalities are preserved while making the code more efficient and easier to understand.
Additional Recommendations
- Module Separation: If the library grows, consider separating different functionalities into multiple modules/files for better manageability.
- Unit Testing: Implement unit tests to ensure each function behaves as expected, especially after optimizations.
- Documentation: Maintain comprehensive documentation, especially if this library is to be used by others or integrated into larger projects.
These optimizations and restructuring should make your Lua script more efficient, readable, and maintainable. Feel free to adjust the naming conventions or structure further to fit your specific project needs.