getDistanceBetweenCoords3d Помогите мне пожалуйста

saradaken

Участник
Автор темы
56
6
Версия MoonLoader
Другое
Здравствуйте, я хочу задать радиус для перевода текста с исходного языка, но проблема в том, что полученное значение может быть неверным?
*Пояснение
Если игрок находится в позиции, близкой к 3dtext или в пределах 10 метров, он выполнит перевод, если 3dtext будет найден в пределах указанного расстояния.

Спасибо за помощь.


Lua:
function sampev.onCreate3DText(id, color, position, dist, testLOS, attachedPlayerId, attachedVehicleId, text)
    if itdtext.v then
        local X, Y, Z = getCharCoordinates(PLAYER_PED)
        local px, py, pz = position.x, position.y, position.z
        local radius = 50.0
        local distes = getDistanceBetweenCoords3d(X, Y, Z, px, py, pz)

        if dist < radius then
        sampAddChatMessage(string.format("Found 3D text \"%s\" at coordinates %.2f %.2f %.2f, distance %.2f, player id %d, vehicle id %d", text, px, py, pz, dist, attachedPlayerId, attachedVehicleId), color)

            if translatedCache[text] then
                text = translatedCache[text]
            else
                local originalText = text
                loadCache()
                if translatedCache[originalText] then
                    text = translatedCache[originalText]
                else
                    enqueueTranslation(originalText, false, function(otext)
                        if otext then
                            translatedCache[originalText] = otext
                            saveCache()
                            text = otext
                            if sampIs3dTextDefined(id) then
                                local info = {sampGet3dTextInfoById(id)}
                                if #info >= 9 then
                                    local bs = raknetNewBitStream()
                                    raknetBitStreamWriteInt16(bs, id)
                                    raknetBitStreamWriteInt32(bs, color)
                                    raknetBitStreamWriteFloat(bs, info[3])
                                    raknetBitStreamWriteFloat(bs, info[4])
                                    raknetBitStreamWriteFloat(bs, info[5])
                                    raknetBitStreamWriteFloat(bs, info[6])
                                    raknetBitStreamWriteInt8(bs, info[7])
                                    raknetBitStreamWriteInt16(bs, info[8])
                                    raknetBitStreamWriteInt16(bs, info[9])
                                    raknetBitStreamEncodeString(bs, text)
                                    raknetEmulRpcReceiveBitStream(36, bs)
                                    raknetDeleteBitStream(bs)
                                end
                            end
                        end
                    end)
                end
            end
        end
    end

    return {id, color, position, dist, testLOS, attachedPlayerId, attachedVehicleId, text}
end

UP
 
Последнее редактирование:

Byte

Потрачен
119
31
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Здравствуйте, я хочу задать радиус для перевода текста с исходного языка, но проблема в том, что полученное значение может быть неверным?
*Пояснение
Если игрок находится в позиции, близкой к 3dtext или в пределах 10 метров, он выполнит перевод, если 3dtext будет найден в пределах указанного расстояния.

Спасибо за помощь.


Lua:
function sampev.onCreate3DText(id, color, position, dist, testLOS, attachedPlayerId, attachedVehicleId, text)
    if itdtext.v then
        local X, Y, Z = getCharCoordinates(PLAYER_PED)
        local px, py, pz = position.x, position.y, position.z
        local radius = 50.0
        local distes = getDistanceBetweenCoords3d(X, Y, Z, px, py, pz)

        if dist < radius then
        sampAddChatMessage(string.format("Found 3D text \"%s\" at coordinates %.2f %.2f %.2f, distance %.2f, player id %d, vehicle id %d", text, px, py, pz, dist, attachedPlayerId, attachedVehicleId), color)

            if translatedCache[text] then
                text = translatedCache[text]
            else
                local originalText = text
                loadCache()
                if translatedCache[originalText] then
                    text = translatedCache[originalText]
                else
                    enqueueTranslation(originalText, false, function(otext)
                        if otext then
                            translatedCache[originalText] = otext
                            saveCache()
                            text = otext
                            if sampIs3dTextDefined(id) then
                                local info = {sampGet3dTextInfoById(id)}
                                if #info >= 9 then
                                    local bs = raknetNewBitStream()
                                    raknetBitStreamWriteInt16(bs, id)
                                    raknetBitStreamWriteInt32(bs, color)
                                    raknetBitStreamWriteFloat(bs, info[3])
                                    raknetBitStreamWriteFloat(bs, info[4])
                                    raknetBitStreamWriteFloat(bs, info[5])
                                    raknetBitStreamWriteFloat(bs, info[6])
                                    raknetBitStreamWriteInt8(bs, info[7])
                                    raknetBitStreamWriteInt16(bs, info[8])
                                    raknetBitStreamWriteInt16(bs, info[9])
                                    raknetBitStreamEncodeString(bs, text)
                                    raknetEmulRpcReceiveBitStream(36, bs)
                                    raknetDeleteBitStream(bs)
                                end
                            end
                        end
                    end)
                end
            end
        end
    end

    return {id, color, position, dist, testLOS, attachedPlayerId, attachedVehicleId, text}
end
Lua:
function sampev.onCreate3DText(id, color, position, dist, testLOS, attachedPlayerId, attachedVehicleId, text)
    if itdtext.v then
        local X, Y, Z = getCharCoordinates(PLAYER_PED)
        local px, py, pz = position.x, position.y, position.z
        local radius = 10.0
        local distes = getDistanceBetweenCoords3d(X, Y, Z, px, py, pz)

        if distes < radius then
            sampAddChatMessage(string.format("Found 3D text \"%s\" at coordinates %.2f %.2f %.2f, distance %.2f, player id %d, vehicle id %d", text, px, py, pz, distes, attachedPlayerId, attachedVehicleId), color)

            if translatedCache[text] then
                text = translatedCache[text]
            else
                local originalText = text
                loadCache()
                if translatedCache[originalText] then
                    text = translatedCache[originalText]
                else
                    enqueueTranslation(originalText, false, function(otext)
                        if otext then
                            translatedCache[originalText] = otext
                            saveCache()
                            text = otext
                            if sampIs3dTextDefined(id) then
                                local info = {sampGet3dTextInfoById(id)}
                                if #info >= 9 then
                                    local bs = raknetNewBitStream()
                                    raknetBitStreamWriteInt16(bs, id)
                                    raknetBitStreamWriteInt32(bs, color)
                                    raknetBitStreamWriteFloat(bs, info[3])
                                    raknetBitStreamWriteFloat(bs, info[4])
                                    raknetBitStreamWriteFloat(bs, info[5])
                                    raknetBitStreamWriteFloat(bs, info[6])
                                    raknetBitStreamWriteInt8(bs, info[7])
                                    raknetBitStreamWriteInt16(bs, info[8])
                                    raknetBitStreamWriteInt16(bs, info[9])
                                    raknetBitStreamEncodeString(bs, text)
                                    raknetEmulRpcReceiveBitStream(36, bs)
                                    raknetDeleteBitStream(bs)
                                end
                            end
                        end
                    end)
                end
            end
        end
    end

    return {id, color, position, dist, testLOS, attachedPlayerId, attachedVehicleId, text}
end
 
  • Нравится
Реакции: saradaken

saradaken

Участник
Автор темы
56
6
Lua:
function sampev.onCreate3DText(id, color, position, dist, testLOS, attachedPlayerId, attachedVehicleId, text)
    if itdtext.v then
        local X, Y, Z = getCharCoordinates(PLAYER_PED)
        local px, py, pz = position.x, position.y, position.z
        local radius = 10.0
        local distes = getDistanceBetweenCoords3d(X, Y, Z, px, py, pz)

        if distes < radius then
            sampAddChatMessage(string.format("Found 3D text \"%s\" at coordinates %.2f %.2f %.2f, distance %.2f, player id %d, vehicle id %d", text, px, py, pz, distes, attachedPlayerId, attachedVehicleId), color)

            if translatedCache[text] then
                text = translatedCache[text]
            else
                local originalText = text
                loadCache()
                if translatedCache[originalText] then
                    text = translatedCache[originalText]
                else
                    enqueueTranslation(originalText, false, function(otext)
                        if otext then
                            translatedCache[originalText] = otext
                            saveCache()
                            text = otext
                            if sampIs3dTextDefined(id) then
                                local info = {sampGet3dTextInfoById(id)}
                                if #info >= 9 then
                                    local bs = raknetNewBitStream()
                                    raknetBitStreamWriteInt16(bs, id)
                                    raknetBitStreamWriteInt32(bs, color)
                                    raknetBitStreamWriteFloat(bs, info[3])
                                    raknetBitStreamWriteFloat(bs, info[4])
                                    raknetBitStreamWriteFloat(bs, info[5])
                                    raknetBitStreamWriteFloat(bs, info[6])
                                    raknetBitStreamWriteInt8(bs, info[7])
                                    raknetBitStreamWriteInt16(bs, info[8])
                                    raknetBitStreamWriteInt16(bs, info[9])
                                    raknetBitStreamEncodeString(bs, text)
                                    raknetEmulRpcReceiveBitStream(36, bs)
                                    raknetDeleteBitStream(bs)
                                end
                            end
                        end
                    end)
                end
            end
        end
    end

    return {id, color, position, dist, testLOS, attachedPlayerId, attachedVehicleId, text}
end
Даже если значение уменьшено, его все равно нельзя использовать.

up

Здравствуйте, я хочу задать радиус для перевода текста с исходного языка, но проблема в том, что полученное значение может быть неверным?
*Пояснение
Если игрок находится в позиции, близкой к 3dtext или в пределах 10 метров, он выполнит перевод, если 3dtext будет найден в пределах указанного расстояния.

Спасибо за помощь.


Lua:
function sampev.onCreate3DText(id, color, position, dist, testLOS, attachedPlayerId, attachedVehicleId, text)
    if itdtext.v then
        local X, Y, Z = getCharCoordinates(PLAYER_PED)
        local px, py, pz = position.x, position.y, position.z
        local radius = 50.0
        local distes = getDistanceBetweenCoords3d(X, Y, Z, px, py, pz)

        if dist < radius then
        sampAddChatMessage(string.format("Found 3D text \"%s\" at coordinates %.2f %.2f %.2f, distance %.2f, player id %d, vehicle id %d", text, px, py, pz, dist, attachedPlayerId, attachedVehicleId), color)

            if translatedCache[text] then
                text = translatedCache[text]
            else
                local originalText = text
                loadCache()
                if translatedCache[originalText] then
                    text = translatedCache[originalText]
                else
                    enqueueTranslation(originalText, false, function(otext)
                        if otext then
                            translatedCache[originalText] = otext
                            saveCache()
                            text = otext
                            if sampIs3dTextDefined(id) then
                                local info = {sampGet3dTextInfoById(id)}
                                if #info >= 9 then
                                    local bs = raknetNewBitStream()
                                    raknetBitStreamWriteInt16(bs, id)
                                    raknetBitStreamWriteInt32(bs, color)
                                    raknetBitStreamWriteFloat(bs, info[3])
                                    raknetBitStreamWriteFloat(bs, info[4])
                                    raknetBitStreamWriteFloat(bs, info[5])
                                    raknetBitStreamWriteFloat(bs, info[6])
                                    raknetBitStreamWriteInt8(bs, info[7])
                                    raknetBitStreamWriteInt16(bs, info[8])
                                    raknetBitStreamWriteInt16(bs, info[9])
                                    raknetBitStreamEncodeString(bs, text)
                                    raknetEmulRpcReceiveBitStream(36, bs)
                                    raknetDeleteBitStream(bs)
                                end
                            end
                        end
                    end)
                end
            end
        end
    end

    return {id, color, position, dist, testLOS, attachedPlayerId, attachedVehicleId, text}
end
up

up

UP

Здравствуйте, я хочу задать радиус для перевода текста с исходного языка, но проблема в том, что полученное значение может быть неверным?
*Пояснение
Если игрок находится в позиции, близкой к 3dtext или в пределах 10 метров, он выполнит перевод, если 3dtext будет найден в пределах указанного расстояния.

Спасибо за помощь.


Lua:
function sampev.onCreate3DText(id, color, position, dist, testLOS, attachedPlayerId, attachedVehicleId, text)
    if itdtext.v then
        local X, Y, Z = getCharCoordinates(PLAYER_PED)
        local px, py, pz = position.x, position.y, position.z
        local radius = 50.0
        local distes = getDistanceBetweenCoords3d(X, Y, Z, px, py, pz)

        if dist < radius then
        sampAddChatMessage(string.format("Found 3D text \"%s\" at coordinates %.2f %.2f %.2f, distance %.2f, player id %d, vehicle id %d", text, px, py, pz, dist, attachedPlayerId, attachedVehicleId), color)

            if translatedCache[text] then
                text = translatedCache[text]
            else
                local originalText = text
                loadCache()
                if translatedCache[originalText] then
                    text = translatedCache[originalText]
                else
                    enqueueTranslation(originalText, false, function(otext)
                        if otext then
                            translatedCache[originalText] = otext
                            saveCache()
                            text = otext
                            if sampIs3dTextDefined(id) then
                                local info = {sampGet3dTextInfoById(id)}
                                if #info >= 9 then
                                    local bs = raknetNewBitStream()
                                    raknetBitStreamWriteInt16(bs, id)
                                    raknetBitStreamWriteInt32(bs, color)
                                    raknetBitStreamWriteFloat(bs, info[3])
                                    raknetBitStreamWriteFloat(bs, info[4])
                                    raknetBitStreamWriteFloat(bs, info[5])
                                    raknetBitStreamWriteFloat(bs, info[6])
                                    raknetBitStreamWriteInt8(bs, info[7])
                                    raknetBitStreamWriteInt16(bs, info[8])
                                    raknetBitStreamWriteInt16(bs, info[9])
                                    raknetBitStreamEncodeString(bs, text)
                                    raknetEmulRpcReceiveBitStream(36, bs)
                                    raknetDeleteBitStream(bs)
                                end
                            end
                        end
                    end)
                end
            end
        end
    end

    return {id, color, position, dist, testLOS, attachedPlayerId, attachedVehicleId, text}
end

UP
up
 
Последнее редактирование:

Byte

Потрачен
119
31
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
  • Нравится
Реакции: saradaken

saradaken

Участник
Автор темы
56
6
я даже не понимаю что ты хочешь, и что у тебя конкретно не работает.
im so sorry
What I want is I try to find 3dtext near the player's position, if it is within a certain radius, it will translate the text.
I don't understand why it doesn't work.
Мне очень жаль
Я хочу найти 3D-текст рядом с позицией игрока, если он находится в определенном радиусе, он переведет текст.
Я не понимаю, почему это не работает.
I tried searching on the forum but there is nothing.
Я пробовал искать на форуме, но ничего нет.
thank u )
 

RTD

Потужно
Модератор
405
476
Создание 3D-текста происходит сразу во всей области стрима с параметром дистанции показа - решение о том, показывать текст или нет, принимает клиент, а не сервер. Это значит что, то что ты хочешь сделать, нужно реализовывать как минимум не в хуке onCreate3DText
 
  • Влюблен
Реакции: saradaken

Sleash

Известный
89
159
самое простое решение проблемы
Код:
while true do wait(100)
    for i = 0, 2048-1 do
        local text, color, posX, posY, posZ, distance, ignoreWalls, attachedPlayerId, attachedVehicleId = sampGet3dTextInfoById(i)
        if distance <= 20.0 and distance > 0.01 --[[fix bug]] then
            -- ur code
        end
    end
end
На счёт оптимизации можно не задумываться, ей здесь нет
UPD: Если учитывать, что выполнять код надо единожды:

Код:
local label3dtext = {}
while true do wait(100)
    for i = 0, 2048-1 do
        local text, color, posX, posY, posZ, distance, ignoreWalls, attachedPlayerId, attachedVehicleId = sampGet3dTextInfoById(i)
        if distance <= 20.0 and distance > 0.01 --[[fix bug]] and not label3dtext[i] then
            label3dtext[i] = {text, color, posX, posY, posZ, distance, ignoreWalls, attachedPlayerId, attachedVehicleId}
          
            -- ur code
          
        elselabel3dtext[i] = nil end
    end
end
UPD2: Написал что-то похожее на то, что тебе надо, но это очень нестабильный код (могут быть варнинги в чате или краш скрипта через время), но думаю для базы или примера будет нормально
P.S.: Добавил преобразование цвета, потому, что если цвет задаётся в функции, а не в строке на стороне сервера, то он меняется на чёрный
 

Вложения

  • test3d.lua
    6.6 KB · Просмотры: 1
Последнее редактирование:
  • Влюблен
Реакции: saradaken

Sleash

Известный
89
159
@saradaken, все проблемы были из-за потоков, их возможное одновременное выполнение, а так же поток в потоке. Я избавился от всего этого в коде, и сделал всё последовательно (в том числе второй http-запрос на ссылку от переводчика). Скрипт ниже хорошо работает и не крашится.
Активация: /entrans
 

Вложения

  • test3d.lua
    5 KB · Просмотры: 3
Последнее редактирование:
  • Влюблен
Реакции: saradaken

saradaken

Участник
Автор темы
56
6
@saradaken, все проблемы были из-за потоков, их возможное одновременное выполнение, а так же поток в потоке. Я избавился от всего этого в коде, и сделал всё последовательно (в том числе второй http-запрос на ссылку от переводчика). Скрипт ниже хорошо работает и не крашится.
Активация: /entrans

Спасибо за помощь, но у меня, похоже, та же проблема, что и у вас: цветовые значения неверны при переводе из оригинала.
1745293261923.png

1745293919127.png



Здесь отображаются правильные значения цветов. Но, похоже, что он переводит русский-английский-английский (он переводит дважды). Он перетранслирует, потому что \r\n отличается. Вторая проблема, которую я обнаружил, заключается в том, что он не извлекает текст из сохраненного кэша для отображения вместо исходного текста, который является русским.
Lua:
function normalizeText(text)
    return text:gsub("\r\n", "\n"):gsub("\r", "\n"):gsub("[ \t]+$", ""):gsub("\n+", "\n")
end

function sampev.onCreate3DText(id, color, position, distance, testLOS, attachedPlayerId, attachedVehicleId, text)
    if not itdtext.v then return end

    local radius = 10.0
    local px, py, pz = getCharCoordinates(PLAYER_PED)

    for i = 0, 2047 do
        if sampIs3dTextDefined(i) then
            local text2, color2, posX2, posY2, posZ2, distance2, ignoreWalls2, player2, vehicle2 = sampGet3dTextInfoById(i)
            if getDistanceBetweenCoords3d(px, py, pz, posX2, posY2, posZ2) < radius then
                sampAddChatMessage(string.format(
                    'Found 3D text "%s" at coordinates %.2f, %.2f, %.2f, distance %.2f, player id %d, vehicle id %d',
                    text2, posX2, posY2, posZ2, distance2, player2, vehicle2), color2)

                local originalText = normalizeText(text2)

                if translatedCache[originalText] then
                    text2 = translatedCache[originalText] 
                else
                    loadCache()
                    enqueueTranslation(originalText, false, function(otext)
                        if otext then
                            translatedCache[originalText] = otext
                            saveCache()
                            text2 = otext

                            sampDestroy3dText(i)
                            sampCreate3dText(text2, color2, posX2, posY2, posZ2, distance2, ignoreWalls2, player2, vehicle2)
                        end
                    end)
                end
            end
        end
    end
end
 

dmitry.kale

Активный
346
83
Lua:
function normalizeText(text)
    return text:gsub("\r\n", "\n"):gsub("\r", "\n"):gsub("[ \t]+$", ""):gsub("\n+", "\n")
end

function sampev.onCreate3DText(id, color, position, distance, testLOS, attachedPlayerId, attachedVehicleId, text)
    if not itdtext.v then return end
    local radius = 10.0
    local px, py, pz = getCharCoordinates(PLAYER_PED)
    local processedTexts = {}
    for i = 0, 2047 do
        if not sampIs3dTextDefined(i) then goto continue end
        local text2, color2, posX2, posY2, posZ2, distance2, ignoreWalls2, player2, vehicle2 = sampGet3dTextInfoById(i)
        if getDistanceBetweenCoords3d(px, py, pz, posX2, posY2, posZ2) >= radius or processedTexts[text2] then goto continue end
        processedTexts[text2] = true
        sampAddChatMessage(string.format('Found 3D text "%s" at coordinates %.2f, %.2f, %.2f, distance %.2f, player id %d, vehicle id %d',text2, posX2, posY2, posZ2, distance2, player2, vehicle2), color2)
        local originalText = normalizeText(text2)
        if translatedCache[originalText] then
            sampDestroy3dText(i)
            sampCreate3dText(translatedCache[originalText], color2, posX2, posY2, posZ2, distance2, ignoreWalls2, player2, vehicle2)
        else
            loadCache()
            enqueueTranslation(originalText, false, function(translatedText)
                if not translatedText then return end
                translatedCache[originalText] = translatedText
                saveCache()
                if sampIs3dTextDefined(i) then
                    sampDestroy3dText(i)
                    sampCreate3dText(translatedText, color2, posX2, posY2, posZ2, distance2, ignoreWalls2, player2, vehicle2)
                end
            end)
        end
        ::continue::
    end
end
check
 

saradaken

Участник
Автор темы
56
6
Lua:
function normalizeText(text)
    return text:gsub("\r\n", "\n"):gsub("\r", "\n"):gsub("[ \t]+$", ""):gsub("\n+", "\n")
end

function sampev.onCreate3DText(id, color, position, distance, testLOS, attachedPlayerId, attachedVehicleId, text)
    if not itdtext.v then return end
    local radius = 10.0
    local px, py, pz = getCharCoordinates(PLAYER_PED)
    local processedTexts = {}
    for i = 0, 2047 do
        if not sampIs3dTextDefined(i) then goto continue end
        local text2, color2, posX2, posY2, posZ2, distance2, ignoreWalls2, player2, vehicle2 = sampGet3dTextInfoById(i)
        if getDistanceBetweenCoords3d(px, py, pz, posX2, posY2, posZ2) >= radius or processedTexts[text2] then goto continue end
        processedTexts[text2] = true
        sampAddChatMessage(string.format('Found 3D text "%s" at coordinates %.2f, %.2f, %.2f, distance %.2f, player id %d, vehicle id %d',text2, posX2, posY2, posZ2, distance2, player2, vehicle2), color2)
        local originalText = normalizeText(text2)
        if translatedCache[originalText] then
            sampDestroy3dText(i)
            sampCreate3dText(translatedCache[originalText], color2, posX2, posY2, posZ2, distance2, ignoreWalls2, player2, vehicle2)
        else
            loadCache()
            enqueueTranslation(originalText, false, function(translatedText)
                if not translatedText then return end
                translatedCache[originalText] = translatedText
                saveCache()
                if sampIs3dTextDefined(i) then
                    sampDestroy3dText(i)
                    sampCreate3dText(translatedText, color2, posX2, posY2, posZ2, distance2, ignoreWalls2, player2, vehicle2)
                end
            end)
        end
        ::continue::
    end
end
check

Спасибо за ваши комментарии и помощь) Но, к сожалению, это все еще не работает

@saradaken, как я понимаю вы хотите переписать скрипт Server translater под асинхронные запросы?
Да, я попробовал изменить код скрипта перевода сервера, чтобы он работал синхронно так вроде всё стало лучше. Старый вариант, по ощущениям, вызывал фризы в игре. После переделки всё заработало, но осталась проблема с радиусом хочется, чтобы 3D-тексты определялись только рядом, а не где-то далеко.