Untitled conversation
- Userlua
- Assistant
local font = renderCreateFont('Tahoma', 10, 4)
local nodes = {}
local nodeCount = 255
function main()
while not isSampAvailable() do
wait(0)
end
sampRegisterChatCommand('get_node_in_stream', function()
local fx, fy, fz = getCharCoordinates(PLAYER_PED)
nodes = {}
for i = 1, nodeCount do
local nx, ny, nz = getNthClosestCarNode(fx, fy, fz, i)
table.insert(nodes, {nx, ny, nz})
end
local sortedNodes = {}
local currentNode = {fx, fy, fz}
while #nodes > 0 do
local nearestIndex = 1
local nearestDistance = getDistanceBetweenCoords3d(currentNode[1], currentNode[2], currentNode[3], nodes[1][1], nodes[1][2], nodes[1][3])
for i = 2, #nodes do
local distance = getDistanceBetweenCoords3d(currentNode[1], currentNode[2], currentNode[3], nodes[i][1], nodes[i][2], nodes[i][3])
if distance < nearestDistance then
nearestIndex = i
nearestDistance = distance
end
end
table.insert(sortedNodes, nodes[nearestIndex])
currentNode = nodes[nearestIndex]
table.remove(nodes, nearestIndex)
end
nodes = sortedNodes
lua_thread.create(function()
while true do
wait(0)
for i = 1, #nodes do
local result, sx, sy = convert3DCoordsToScreenEx(nodes[i][1], nodes[i][2], nodes[i][3])
if result and isPointOnScreen(nodes[i][1], nodes[i][2], nodes[i][3], 5) then renderFontDrawText(font, 'node #' .. i, sx, sy, 0xFFFFFFFF, 0x90000000) end
end
end
end)
end)
sampRegisterChatCommand('route', function(params)
local nodeIndices = {}
for part in string.gmatch(params, '([^,]+)') do
if string.find(part, '-') then
local startIdx, endIdx = part:match('(%d+)-(%d+)')
startIdx, endIdx = tonumber(startIdx), tonumber(endIdx)
if startIdx and endIdx then
if startIdx < endIdx then
for i = startIdx, endIdx do
table.insert(nodeIndices, i)
end
else
for i = startIdx, endIdx, -1 do
table.insert(nodeIndices, i)
end
end
end
else
local idx = tonumber(part)
if idx then table.insert(nodeIndices, idx) end
end
end
local routeNodes = {}
for _, idx in ipairs(nodeIndices) do
if nodes[idx] then table.insert(routeNodes, nodes[idx]) end
end
if #routeNodes > 0 then
driveAlongNodes(routeNodes)
else
sampAddChatMessage('Перед использованием, соберите информацию о всех нодах: /get_node_in_stream', 0xFFFFFF)
end
end)
while true do
wait(0)
end
end
function driveAlongNodes(routeNodes)
lua_thread.create(function()
local car = getCarCharIsUsing(PLAYER_PED)
for i, node in ipairs(routeNodes) do
local nx, ny, nz = unpack(node)
taskCarDriveToCoord(PLAYER_PED, car, nx, ny, nz, 20.0, 1, nil, 0)
local stuckCounter = 0
local lastDistance = getDistanceBetweenCoords3d(nx, ny, nz, getCarCoordinates(car))
while true do
wait(0)
local currentDistance = getDistanceBetweenCoords3d(nx, ny, nz, getCarCoordinates(car))
if currentDistance < 5.0 then
sampAddChatMessage('Узел #' .. i .. ' достигнут.', 0xFFFFFF)
break
end
if math.abs(currentDistance - lastDistance) < 0.1 then
stuckCounter = stuckCounter + 1
else
stuckCounter = 0
end
if stuckCounter > 100 then
sampAddChatMessage('Застревание на узле #' .. i .. ', переход к следующему.', 0xFFFFFF)
break
end
lastDistance = currentDistance
end
end
clearCharTasksImmediately(PLAYER_PED)
sampAddChatMessage('Маршрут закончен, экспериментально от Tectrex.', 0xFFFFFF)
end)
end
Optimize the code, improve the code, fix possible bugs, errors, glitches
Certainly! Below is the optimized and enhanced version of your Lua script for SAMP (San Andreas Multiplayer). The improvements address performance optimizations, bug fixes, enhanced readability, and better resource management. I've also included comments to highlight the changes and improvements made.
-- Constants for easy configuration and maintenance
local FONT_NAME = 'Tahoma'
local FONT_SIZE = 10
local FONT_FLAGS = 4
local NODE_COUNT = 255
local REPORT_DISTANCE = 20.0
local REACHED_DISTANCE = 5.0
local STUCK_DISTANCE_THRESHOLD = 0.1
local STUCK_LIMIT = 100
-- Messages for user feedback
local ROUTE_FINISHED_MSG = 'Маршрут закончен, экспериментально от Tectrex.'
local NO_NODES_MSG = 'Перед использованием, соберите информацию о всех нодах: /get_node_in_stream'
local NODE_REACHED_MSG = 'Узел #%d достигнут.'
local NODE_STUCK_MSG = 'Застревание на узле #%d, переход к следующему.'
-- Variables to store state
local font = nil
local nodes = {}
local renderingThread = nil -- To prevent multiple rendering threads
-- Utility function to calculate 3D distance
local function getDistance3D(x1, y1, z1, x2, y2, z2)
local dx, dy, dz = x2 - x1, y2 - y1, z2 - z1
return math.sqrt(dx * dx + dy * dy + dz * dz)
end
-- Function to sort nodes based on nearest distance using a more efficient sort
local function sortNodesByDistance(initialX, initialY, initialZ, nodeList)
table.sort(nodeList, function(a, b)
local distA = getDistance3D(initialX, initialY, initialZ, a[1], a[2], a[3])
local distB = getDistance3D(initialX, initialY, initialZ, b[1], b[2], b[3])
return distA < distB
end)
end
-- Function to render nodes on screen
local function startRenderingNodes(nodeList)
if renderingThread and coroutine.status(renderingThread) ~= "dead" then
-- Rendering thread already running
return
end
renderingThread = coroutine.create(function()
while true do
wait(0)
for i, node in ipairs(nodeList) do
local result, sx, sy = convert3DCoordsToScreenEx(node[1], node[2], node[3])
if result and isPointOnScreen(node[1], node[2], node[3], 5) then
renderFontDrawText(font, string.format('node #%d', i), sx, sy, 0xFFFFFFFF, 0x90000000)
end
end
end
end)
coroutine.resume(renderingThread)
end
-- Main function to initialize and register commands
function main()
-- Wait until SAMP is available before proceeding
while not isSampAvailable() do
wait(0)
end
-- Initialize the font after SAMP is available
font = renderCreateFont(FONT_NAME, FONT_SIZE, FONT_FLAGS)
if not font then
sampAddChatMessage("Не удалось создать шрифт для отображения узлов.", 0xFF0000)
return
end
-- Register the '/get_node_in_stream' chat command
sampRegisterChatCommand('get_node_in_stream', function()
local fx, fy, fz = getCharCoordinates(PLAYER_PED)
if not fx or not fy or not fz then
sampAddChatMessage("Не удалось получить координаты игрока.", 0xFF0000)
return
end
nodes = {}
for i = 1, NODE_COUNT do
local nx, ny, nz = getNthClosestCarNode(fx, fy, fz, i)
if nx and ny and nz then
table.insert(nodes, {nx, ny, nz})
else
-- Handle cases where fewer nodes are available
break
end
end
if #nodes == 0 then
sampAddChatMessage("Не удалось собрать узлы.", 0xFF0000)
return
end
-- Sort nodes based on distance from the player's current position
sortNodesByDistance(fx, fy, fz, nodes)
-- Start rendering the sorted nodes on the screen
startRenderingNodes(nodes)
sampAddChatMessage("Узлы успешно собраны и отображаются на экране.", 0x00FF00)
end)
-- Register the '/route' chat command
sampRegisterChatCommand('route', function(params)
if #nodes == 0 then
sampAddChatMessage(NO_NODES_MSG, 0xFFFFFF)
return
end
local nodeIndices = {}
for part in string.gmatch(params, '([^,]+)') do
local startIdx, endIdx = part:match('(%d+)%-(%d+)')
if startIdx and endIdx then
startIdx, endIdx = tonumber(startIdx), tonumber(endIdx)
if startIdx and endIdx then
if startIdx < endIdx then
for i = startIdx, endIdx do
table.insert(nodeIndices, i)
end
else
for i = startIdx, endIdx, -1 do
table.insert(nodeIndices, i)
end
end
end
else
local idx = tonumber(part)
if idx then
table.insert(nodeIndices, idx)
else
sampAddChatMessage(string.format("Неверный формат индекса: %s", part), 0xFF0000)
end
end
end
if #nodeIndices == 0 then
sampAddChatMessage("Не выбраны допустимые индексы узлов.", 0xFF0000)
return
end
local routeNodes = {}
for _, idx in ipairs(nodeIndices) do
if nodes[idx] then
table.insert(routeNodes, nodes[idx])
else
sampAddChatMessage(string.format("Узел с индексом #%d не найден.", idx), 0xFF0000)
end
end
if #routeNodes > 0 then
driveAlongNodes(routeNodes)
else
sampAddChatMessage(NO_NODES_MSG, 0xFFFFFF)
end
end)
-- Keep the main thread alive
while true do
wait(0)
end
end
-- Function to execute the driving along the specified route
function driveAlongNodes(routeNodes)
lua_thread.create(function()
for i, node in ipairs(routeNodes) do
local car = getCarCharIsUsing(PLAYER_PED)
if not car then
sampAddChatMessage("Вы не находитесь в автомобиле.", 0xFF0000)
break
end
local nx, ny, nz = unpack(node)
if not (nx and ny and nz) then
sampAddChatMessage(string.format("Невалидные координаты для узла #%d.", i), 0xFF0000)
goto continue
end
-- Task the car to drive to the node's coordinates
taskCarDriveToCoord(PLAYER_PED, car, nx, ny, nz, REPORT_DISTANCE, 1, nil, 0)
local stuckCounter = 0
local lastDistance = getDistance3D(nx, ny, nz, getCarCoordinates(car))
while true do
wait(0)
if not isCharInAnyCar(PLAYER_PED) then
sampAddChatMessage("Вы вышли из автомобиля. Маршрут остановлен.", 0xFF0000)
return
end
local currentCar = getCarCharIsUsing(PLAYER_PED)
if not currentCar then
sampAddChatMessage("Автомобиль недоступен.", 0xFF0000)
return
end
local currentX, currentY, currentZ = getCarCoordinates(currentCar)
if not (currentX and currentY and currentZ) then
sampAddChatMessage("Не удалось получить координаты автомобиля.", 0xFF0000)
return
end
local currentDistance = getDistance3D(nx, ny, nz, currentX, currentY, currentZ)
if currentDistance < REACHED_DISTANCE then
sampAddChatMessage(string.format(NODE_REACHED_MSG, i), 0x00FF00)
break
end
if math.abs(currentDistance - lastDistance) < STUCK_DISTANCE_THRESHOLD then
stuckCounter = stuckCounter + 1
else
stuckCounter = 0
end
if stuckCounter > STUCK_LIMIT then
sampAddChatMessage(string.format(NODE_STUCK_MSG, i), 0xFFFF00)
break
end
lastDistance = currentDistance
end
::continue::
end
clearCharTasksImmediately(PLAYER_PED)
sampAddChatMessage(ROUTE_FINISHED_MSG, 0xFFFFFF)
end)
end
Constants and Configuration:
Efficient Sorting:
table.sort function, sorting nodes based on their distance from the player's position. This is generally more efficient and simpler.Rendering Thread Management:
renderingThread variable to ensure that only one rendering thread is active at any time, preventing multiple threads from rendering nodes simultaneously if /get_node_in_stream is called multiple times.Enhanced Error Handling:
getCharCoordinates, getNthClosestCarNode, and others return valid data before proceeding.Improved Command Parsing:
/route command to handle invalid inputs gracefully, informing the user if they input incorrect node indices or formats.Drive Function Enhancements:
driveAlongNodes, the script now re-fetches the car each iteration to handle scenarios where the player might switch vehicles during the route.Utility Functions:
getDistance3D utility function to calculate the distance between two 3D points, improving code readability and reusability.sortNodesByDistance function to encapsulate the sorting logic.Code Readability and Maintenance:
Performance Monitoring:
User Interface Enhancements:
Validation and Security:
Extensibility:
By implementing these optimizations and improvements, the script should be more efficient, reliable, and user-friendly. Feel free to further customize the script based on your specific requirements and preferences.
Not yet included in a published release.
Resource Management:
Localization and User Feedback: