Полезные сниппеты и функции

SR_team

like pancake
Автор темы
BH Team
4,707
6,347
Описание: Ищет маркер на карте.
Использование: local result, x, y, z = SearchMarker(posX, posY, posZ, radius, isRace)
Код:
Lua:
function SearchMarker(posX, posY, posZ, radius, isRace)
    local ret_posX = 0.0
    local ret_posY = 0.0
    local ret_posZ = 0.0
    local isFind = false

    for id = 0, 31 do
        local MarkerStruct = 0
        if isRace then MarkerStruct = 0xC7F168 + id * 56
        else MarkerStruct = 0xC7DD88 + id * 160 end
        local MarkerPosX = representIntAsFloat(readMemory(MarkerStruct + 0, 4, false))
        local MarkerPosY = representIntAsFloat(readMemory(MarkerStruct + 4, 4, false))
        local MarkerPosZ = representIntAsFloat(readMemory(MarkerStruct + 8, 4, false))

        if MarkerPosX ~= 0.0 or MarkerPosY ~= 0.0 or MarkerPosZ ~= 0.0 then
            if getDistanceBetweenCoords3d(MarkerPosX, MarkerPosY, MarkerPosZ, posX, posY, posZ) < radius then
                ret_posX = MarkerPosX
                ret_posY = MarkerPosY
                ret_posZ = MarkerPosZ
                isFind = true
                radius = getDistanceBetweenCoords3d(MarkerPosX, MarkerPosY, MarkerPosZ, posX, posY, posZ)
            end
        end
    end

    return isFind, ret_posX, ret_posY, ret_posZ
end

Пример:
Lua:
script_dependencies("CLEO", "SAMP", "SAMPFUNCS")

---------------------------------------------------------------------------

require "lib.moonloader"
require "lib.sampfuncs"

---------------------------------------------------------------------------

function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    sampRegisterChatCommand("mycmd", cmd)

    while true do wait(0) end
end

function cmd(param)
    if isPlayerPlaying(playerHandle) then
        local posX, posY, posZ = getCharCoordinates(playerPed)
        local res, x, y, z = SearchMarker(posX, posY, posZ, 50.0, false)
        if res then
            sampAddChatMessage(string.format("Найден обычный маркер в координатах %.2f %.2f %.2f", x, y, z), -1)
        else
            res, x, y, z = SearchMarker(posX, posY, posZ, 50.0, true)
            if res then
                sampAddChatMessage(string.format("Найден гоночный маркер в координатах %.2f %.2f %.2f", x, y, z), -1)
            else
                sampAddChatMessage("Маркер не найден", -1)
            end
        end
    end
end

function SearchMarker(posX, posY, posZ, radius, isRace)
    local ret_posX = 0.0
    local ret_posY = 0.0
    local ret_posZ = 0.0
    local isFind = false

    for id = 0, 31 do
        local MarkerStruct = 0
        if isRace then MarkerStruct = 0xC7F168 + id * 56
        else MarkerStruct = 0xC7DD88 + id * 160 end
        local MarkerPosX = representIntAsFloat(readMemory(MarkerStruct + 0, 4, false))
        local MarkerPosY = representIntAsFloat(readMemory(MarkerStruct + 4, 4, false))
        local MarkerPosZ = representIntAsFloat(readMemory(MarkerStruct + 8, 4, false))

        if MarkerPosX ~= 0.0 or MarkerPosY ~= 0.0 or MarkerPosZ ~= 0.0 then
            if getDistanceBetweenCoords3d(MarkerPosX, MarkerPosY, MarkerPosZ, posX, posY, posZ) < radius then
                ret_posX = MarkerPosX
                ret_posY = MarkerPosY
                ret_posZ = MarkerPosZ
                isFind = true
                radius = getDistanceBetweenCoords3d(MarkerPosX, MarkerPosY, MarkerPosZ, posX, posY, posZ)
            end
        end
    end

    return isFind, ret_posX, ret_posY, ret_posZ
end
 
Последнее редактирование:

SR_team

like pancake
Автор темы
BH Team
4,707
6,347
Описание: Ищет 3D текст на карте.
Использование: local result, text, color, x, y, z, distance, ignoreWalls, player, vehicle = Search3Dtext(posX, posY, posZ, radius, patern)
--patern - часть строки или регулярное выражение
Код:
Lua:
function Search3Dtext(x, y, z, radius, patern)
    local text = ""
    local color = 0
    local posX = 0.0
    local posY = 0.0
    local posZ = 0.0
    local distance = 0.0
    local ignoreWalls = false
    local player = -1
    local vehicle = -1
    local result = false

    for id = 0, 2048 do
        if sampIs3dTextDefined(id) then
            local text2, color2, posX2, posY2, posZ2, distance2, ignoreWalls2, player2, vehicle2 = sampGet3dTextInfoById(id)
            if getDistanceBetweenCoords3d(x, y, z, posX2, posY2, posZ2) < radius then
                if string.len(patern) ~= 0 then
                    if string.match(text2, patern, 0) ~= nil then result = true end
                else
                    result = true
                end
                if result then
                    text = text2
                    color = color2
                    posX = posX2
                    posY = posY2
                    posZ = posZ2
                    distance = distance2
                    ignoreWalls = ignoreWalls2
                    player = player2
                    vehicle = vehicle2
                    radius = getDistanceBetweenCoords3d(x, y, z, posX, posY, posZ)
                end
            end
        end
    end

    return result, text, color, posX, posY, posZ, distance, ignoreWalls, player, vehicle
end

Пример:
Lua:
script_dependencies("CLEO", "SAMP", "SAMPFUNCS")

---------------------------------------------------------------------------

require "lib.moonloader"
require "lib.sampfuncs"

---------------------------------------------------------------------------

function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    sampRegisterChatCommand("mycmd", cmd)

    while true do wait(0) end
end

function cmd(param)
    if isPlayerPlaying(playerHandle) then
        local posX, posY, posZ = getCharCoordinates(playerPed)
        local res, text, color, x, y, z, distance, ignoreWalls, player, vehicle = Search3Dtext(posX, posY, posZ, 50.0, "")
        if res then
            sampAddChatMessage(string.format("Найден 3D текст \"%s\" в координатах %.2f %.2f %.2f, дистанция %.2f, id игрока %d, id транспорта %d", text, x, y, z, distance, player, vehicle), color)
        end
    end
end

function Search3Dtext(x, y, z, radius, patern)
    local text = ""
    local color = 0
    local posX = 0.0
    local posY = 0.0
    local posZ = 0.0
    local distance = 0.0
    local ignoreWalls = false
    local player = -1
    local vehicle = -1
    local result = false

    for id = 0, 2048 do
        if sampIs3dTextDefined(id) then
            local text2, color2, posX2, posY2, posZ2, distance2, ignoreWalls2, player2, vehicle2 = sampGet3dTextInfoById(id)
            if getDistanceBetweenCoords3d(x, y, z, posX2, posY2, posZ2) < radius then
                if string.len(patern) ~= 0 then
                    if string.match(text2, patern, 0) ~= nil then result = true end
                else
                    result = true
                end
                if result then
                    text = text2
                    color = color2
                    posX = posX2
                    posY = posY2
                    posZ = posZ2
                    distance = distance2
                    ignoreWalls = ignoreWalls2
                    player = player2
                    vehicle = vehicle2
                    radius = getDistanceBetweenCoords3d(x, y, z, posX, posY, posZ)
                end
            end
        end
    end

    return result, text, color, posX, posY, posZ, distance, ignoreWalls, player, vehicle
end
 
Последнее редактирование:

ZeroXruS

Новичок
17
9
Описание: рисует кнопку на экране
Использование:
bool
isClicked= renderDrawButton([Font], Title, posX, posY, sizeX, sizeY, targetX, targetY, boxColor, targetBoxColor, textColor, targetTextColor)
или
bool isClicked= renderDrawButtonA([Font], Title, posX, posY, targetX, targetY, boxColor, targetBoxColor, textColor, targetTextColor)
Код:

Lua:
function renderDrawButtonA(d3dFont, Title, posX, posY, targetX, targetY, boxColor, targetBoxColor, textColor, targetTextColor) return renderDrawButton(d3dFont, Title, posX, posY, renderGetFontDrawTextLength(d3dFont, Title), renderGetFontDrawHeight(d3dFont), targetX, targetY, boxColor, targetBoxColor, textColor, targetTextColor) end
function renderDrawButton(d3dFont, Title, posX, posY, sizeX, sizeY, targetX, targetY, boxColor, targetBoxColor, textColor, targetTextColor)
    local bool= false
    local currentBoxColor= boxColor
    local currentTextColor= textColor

    if targetX > posX and targetX < posX + sizeX and targetY > posY and targetY < posY + sizeY then
        currentBoxColor= targetBoxColor
        currentTextColor= targetTextColor
        if isKeyJustPressed(VK_LBUTTON) then bool= true end
    end

    renderDrawBox(posX, posY, sizeX + 2, sizeY, currentBoxColor)
    renderFontDrawText(d3dFont, Title, posX, posY, currentTextColor)
    return bool
end
 
  • Нравится
Реакции: deleted-user-164854

4el0ve4ik

Известный
Всефорумный модератор
1,548
1,338
Описание: поиск пикапа по его модели
Использование:
Код:
function main()
if isKeyDown(66) and isKeyJustPressed(72) then
while isKeyDown(66) or isKeyDown(72) do
    wait(10)
end
pickupid()
end
if resultpick then
--body
end
end
Код:
Lua:
function pickupid(model)
   local poolPtr = sampGetPickupPoolPtr()
   local ptwo = readMemory(poolPtr, 4, 0)
   if ptwo > 0 then
     ptwo = poolPtr + 0x4
     local pthree = poolPtr + 0xF004
     for id = 1, 4096 do
       local pfive = readMemory(ptwo + id * 4, 4, false)
       if pfive < 0 or pfive > 0 then
         pfive = readMemory(pthree + id * 20, 4, false)
         if pfive == model then
           return id
         end
       end
     end
   end
end
 
Последнее редактирование:

FYP

Известный
Администратор
1,757
5,684
Описание: разбивает на составляющие цвет, представленный в виде целого (alpha, red, green, blue)
Код:
Lua:
function explode_argb(argb)
  local a = bit.band(bit.rshift(argb, 24), 0xFF)
  local r = bit.band(bit.rshift(argb, 16), 0xFF)
  local g = bit.band(bit.rshift(argb, 8), 0xFF)
  local b = bit.band(argb, 0xFF)
  return a, r, g, b
end

Описание: обратная операция - конвертирует цвет alpha, red, green, blue в целое
Код:
Lua:
function join_argb(a, r, g, b)
  local argb = b  -- b
  argb = bit.bor(argb, bit.lshift(g, 8))  -- g
  argb = bit.bor(argb, bit.lshift(r, 16)) -- r
  argb = bit.bor(argb, bit.lshift(a, 24)) -- a
  return argb
end

Пример:
Lua:
-- функция преобразует цвет ARGB, представленный в виде целого в RGBA в виде целого
function argb_to_rgba(argb)
  local a, r, g, b = explode_argb(argb)
  return join_argb(r, g, b, a)
end

print(bit.tohex(argb_to_rgba(0x11223344)))
-- будет выведено 0x22334411
 
Последнее редактирование:

FYP

Известный
Администратор
1,757
5,684
Возвращает название оружия по иду оружия.
Использование: namegun = getweaponname(weapon)
Lua:
function getweaponname(weapon)
  local namegun
  if weapon == 0 then
    namegun = "Fist"
  end
  if weapon == 1 then
     namegun = "Brass Knuckles"
  end
  if weapon == 2 then
     namegun = "Golf Club"
  end
  if weapon == 3 then
     namegun = "Nightstick"
  end
  if weapon == 4 then
     namegun = "Knife"
  end
  if weapon == 5 then
     namegun = "Baseball Bat"
  end
  if weapon == 6 then
     namegun = "Shovel"
  end
  if weapon == 7 then
     namegun = "Pool Cue"
  end
  if weapon == 8 then
     namegun = "Katana"
  end
  if weapon == 9 then
     namegun = "Chainsaw"
  end
  if weapon == 10 then
     namegun = "Purple Dildo"
  end
  if weapon == 11 then
     namegun = "Dildo"
  end
  if weapon == 12 then
     namegun = "Vibrator"
  end
  if weapon == 13 then
     namegun = "Silver Vibrator"
  end
  if weapon == 14 then
     namegun = "Flowers"
  end
  if weapon == 15 then
     namegun = "Cane"
  end
  if weapon == 16 then
     namegun = "Grenade"
  end
  if weapon == 17 then
     namegun = "Tear Gas"
  end
  if weapon == 18 then
     namegun = "Molotov Cocktail"
  end
  if weapon == 22 then
     namegun = "9mm"
  end
  if weapon == 23 then
     namegun = "Silenced 9mm"
  end
  if weapon == 24 then
     namegun = "Desert Eagle"
  end
  if weapon == 25 then
     namegun = "Shotgun"
  end
  if weapon == 26 then
     namegun = "Sawnoff Shotgun"
  end
  if weapon == 27 then
     namegun = "Combat Shotgun"
  end
  if weapon == 28 then
     namegun = "Micro SMG/Uzi"
  end
  if weapon == 29 then
     namegun = "MP5"
  end
  if weapon == 30 then
     namegun = "AK-47"
  end
  if weapon == 31 then
     namegun = "M4"
  end
  if weapon == 32 then
     namegun = "Tec-9"
  end
  if weapon == 33 then
     namegun = "Country Rifle"
  end
  if weapon == 34 then
     namegun = "Sniper Rifle"
  end
  if weapon == 35 then
     namegun = "RPG"
  end
  if weapon == 36 then
     namegun = "HS Rocket"
  end
  if weapon == 37 then
     namegun = "Flamethrower"
  end
  if weapon == 38 then
     namegun = "Minigun"
  end
  if weapon == 39 then
     namegun = "Satchel Charge"
  end
  if weapon == 40 then
     namegun = "Detonator"
  end
  if weapon == 41 then
     namegun = "Spraycan"
  end
  if weapon == 42 then
     namegun = "Fire Extinguisher"
  end
  if weapon == 43 then
     namegun = "Camera"
  end
  if weapon == 44 then
     namegun = "Night Vis Goggles"
  end
  if weapon == 45 then
     namegun = "Thermal Goggles"
  end
  if weapon == 46 then
     namegun = "Parachute"
  end
  return namegun
end
UPD новый, правильный способ:
Lua:
local weapons = require 'game.weapons'

weapons.get_name(id)
Lua:
function getweaponname(weapon)
  local names = {
  [0] = "Fist",
  [1] = "Brass Knuckles",
  [2] = "Golf Club",
  [3] = "Nightstick",
  [4] = "Knife",
  [5] = "Baseball Bat",
  [6] = "Shovel",
  [7] = "Pool Cue",
  [8] = "Katana",
  [9] = "Chainsaw",
  [10] = "Purple Dildo",
  [11] = "Dildo",
  [12] = "Vibrator",
  [13] = "Silver Vibrator",
  [14] = "Flowers",
  [15] = "Cane",
  [16] = "Grenade",
  [17] = "Tear Gas",
  [18] = "Molotov Cocktail",
  [22] = "9mm",
  [23] = "Silenced 9mm",
  [24] = "Desert Eagle",
  [25] = "Shotgun",
  [26] = "Sawnoff Shotgun",
  [27] = "Combat Shotgun",
  [28] = "Micro SMG/Uzi",
  [29] = "MP5",
  [30] = "AK-47",
  [31] = "M4",
  [32] = "Tec-9",
  [33] = "Country Rifle",
  [34] = "Sniper Rifle",
  [35] = "RPG",
  [36] = "HS Rocket",
  [37] = "Flamethrower",
  [38] = "Minigun",
  [39] = "Satchel Charge",
  [40] = "Detonator",
  [41] = "Spraycan",
  [42] = "Fire Extinguisher",
  [43] = "Camera",
  [44] = "Night Vis Goggles",
  [45] = "Thermal Goggles",
  [46] = "Parachute" }
  return names[weapon]
end
))
 
Последнее редактирование:

4el0ve4ik

Известный
Всефорумный модератор
1,548
1,338
Функция позволяет узнать сколько патронов в обойме.
Lua:
function getAmmoInClip()
    local pointer = getCharPointer(playerPed)
    local weapon = getCurrentCharWeapon(playerPed)
    local slot = getWeapontypeSlot(weapon)
    local cweapon = pointer + 0x5A0
    local current_cweapon = cweapon + slot * 0x1C
    return memory.getuint32(current_cweapon + 0x8)
end
Использование:
local ammoinclip = getAmmoInClip()
P.S.
Lua:
local memory = require "memory"
в начало кода пропишите.
 

hnnssy

Известный
Друг
2,684
2,744
Получение серийника логического диска.
Lua:
local ffi = require("ffi")
ffi.cdef[[
int __stdcall GetVolumeInformationA(
    const char* lpRootPathName,
    char* lpVolumeNameBuffer,
    uint32_t nVolumeNameSize,
    uint32_t* lpVolumeSerialNumber,
    uint32_t* lpMaximumComponentLength,
    uint32_t* lpFileSystemFlags,
    char* lpFileSystemNameBuffer,
    uint32_t nFileSystemNameSize
);
]]
local serial = ffi.new("unsigned long[1]", 0)
ffi.C.GetVolumeInformationA(nil, nil, 0, serial, nil, nil, nil, 0)
serial = serial[0]
 

hnnssy

Известный
Друг
2,684
2,744
Описание: Рисует полосу и числовое значение с указанными параметрами. (как бары в hCHUD, например)
Использование: drawBar(posX, posY, sizeX, sizeY, color1, color2, borderThickness, font, value)
Код:
Lua:
function drawBar(posX, posY, sizeX, sizeY, color1, color2, borderThickness, font, value)
   renderDrawBoxWithBorder(posX, posY, sizeX, sizeY, color2, borderThickness, 0xFF000000)
   renderDrawBox(posX + borderThickness, posY + borderThickness, sizeX / 100 * value - (borderThickness * 2), sizeY - (2 * borderThickness), color1)
   local textLenght = renderGetFontDrawTextLength(font, tostring(value))
   local textHeight = renderGetFontDrawHeight(font)
   renderFontDrawText(font, tostring(value), posX + (sizeX / 2) - (textLenght / 2), posY + (sizeY / 2) - (textHeight / 2), 0xFFFFFFFF)
end

Пример:
HPbar
 

hnnssy

Известный
Друг
2,684
2,744
Описание: Рисует кликабельный текст (как в hClickCommands).
Использование: if drawClickableText(font, text, posX, posY, color, colorA) then -- colorA - цвет текста при наведении курсора
Код:
Lua:
function drawClickableText(font, text, posX, posY, color, colorA)
   renderFontDrawText(font, text, posX, posY, color)
   local textLenght = renderGetFontDrawTextLength(font, text)
   local textHeight = renderGetFontDrawHeight(font)
   local curX, curY = getCursorPos()
   if curX >= posX and curX <= posX + textLenght and curY >= posY and curY <= posY + textHeight then
     renderFontDrawText(font, text, posX, posY, colorA)
     if wasKeyPressed(1) then
       return true
     end
   end
end

Пример: (возле игроков рисует 2 кликлинка для отправки сообщения и репорта)
https://pp.vk.me/c836537/v836537950/22914/kn-I3j-c5Uk.jpg

Lua:
script_name("drawClickableText")
script_description("example of using drawClickableText function")
script_version_number(1)
script_version("v.001")
script_authors("hnnssy")

local ffi = require "ffi"
local getBonePosition = ffi.cast("int (__thiscall*)(void*, float*, int, bool)", 0x5E4280)

function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(100) end
    local font = renderCreateFont("Tahoma", 8, 5)
    while true do
        wait(0)
        if not isPauseMenuActive() and isPlayerPlaying(playerHandle) then
            if wasKeyPressed(90) then
                while isKeyDown(90) do
                    wait(0)
                    sampToggleCursor(1)
                    for id = 0, sampGetMaxPlayerId(true) do
                         if sampIsPlayerConnected(id) then
                        local exists, handle = sampGetCharHandleBySampPlayerId(id)
                            if exists and isCharOnScreen(handle) then
                                plX, plY, plZ = getBodyPartCoordinates(8, handle)
                                local plsX, plsY = convert3DCoordsToScreen(plX, plY, plZ)
                                if drawClickableText(font, "send message", plsX + 25, plsY, 0xFFFFFFFF, 0xFFFF0000) then
                                    sendMessage(id)
                                end
                                if drawClickableText(font, "send report", plsX + 25, plsY + 15, 0xFFFFFFFF, 0xFFFF0000) then
                                    sendReport(id)
                                end
                            end
                        end
                    end
                end
                if wasKeyReleased(90) then sampSetCursorMode(0) end
            end
        end
    end
end

function sendMessage(id)
sampSetChatInputEnabled(1)
sampSetChatInputText("/pm " .. id .. " ")
end

function sendReport(id)
sampSetChatInputEnabled(1)
sampSetChatInputText("/report " .. id .. " ")
end

function getBodyPartCoordinates(id, handle)
  local pedptr = getCharPointer(handle)
  local vec = ffi.new("float[3]")
  getBonePosition(ffi.cast("void*", pedptr), vec, id, true)
  return vec[0], vec[1], vec[2]
end

function drawClickableText(font, text, posX, posY, color, colorA)
    renderFontDrawText(font, text, posX, posY, color)
    local textLenght = renderGetFontDrawTextLength(font, text)
    local textHeight = renderGetFontDrawHeight(font)
    local curX, curY = getCursorPos()
      if curX >= posX and curX <= posX + textLenght and curY >= posY and curY <= posY + textHeight then
        renderFontDrawText(font, text, posX, posY, colorA)
        if wasKeyPressed(1) then
            return true
        end
    end
end
 
Последнее редактирование:

im0rg

Известный
Друг
587
214
Описание: Расстояние между точки "А" в 3D пространстве до точки "B"
Lua:
distance= math.sqrt( ((posX-pedX)^2) + ((posY-pedY)^2) + ((posZ-pedZ)^2))
Пример использования:
Lua:
posX,posY,posZ = 0,0,0
pedX,pedY,pedZ = getCharCoordinates(playerPed)
distance= math.sqrt( ((posX-pedX)^2) + ((posY-pedY)^2) + ((posZ-pedZ)^2))
print(distance)
Знаю что это простая математическая формула. Ну вдруг кому пригодится
 

Losyash1337

Новичок
16
16
Описание: нахождения расстояния между двумя точками на плоскости без math.sqrt с погрешностью 5%.
Код:
Lua:
local function getDistance2d(x1, y1, x2, y2)
    x1 = x1 - x2 -- Далее воспринимаем x1, как dx
    y1 = y1 - y2 -- Далее воспринимаем y1, как dy

    if x1 < 0 then x1 = -x1 end -- Модуль dx
    if y1 < 0 then y1 = -y1 end -- Модуль dy

    -- Если честно, то тут я что-то недопонимаю,
    -- но работает с погрешнстью .05
    if x1 < y1 then
        return (123 * y1 + 51 * x1) / 128 end
    return (123 * x1 + 51 * y1) / 128
end

Описание: нахождения расстояния между двумя точками в пространстве с погрешностью 10%
Код:
Lua:
local function getDistance3d(x1, y1, z1, x2, y2, z2)
    return getDistance2d(z1, z2, getDistance2d(x1, y1, x2, y2), 0)
end

Источник: http://www.gamedev.ru/tip/?id=41
PS: Да, это простая формула, списанная с чьего-то сайтика, но вдруг кому пригодится.
 
  • Нравится
Реакции: Carl_Henderson

SR_team

like pancake
Автор темы
BH Team
4,707
6,347
Описание: нахождения расстояния между двумя точками на плоскости без math.sqrt с погрешностью 5%.
Код:
Lua:
local function getDistance2d(x1, y1, x2, y2)
    x1 = x1 - x2 -- Далее воспринимаем x1, как dx
    y1 = y1 - y2 -- Далее воспринимаем y1, как dy

    if x1 < 0 then x1 = -x1 end -- Модуль dx
    if y1 < 0 then y1 = -y1 end -- Модуль dy

    -- Если честно, то тут я что-то недопонимаю,
    -- но работает с погрешнстью .05
    if x1 < y1 then
        return (123 * y1 + 51 * x1) / 128 end
    return (123 * x1 + 51 * y1) / 128
end

Описание:
нахождения расстояния между двумя точками в пространстве с погрешностью 10%
Код:
Lua:
local function getDistance3d(x1, y1, z1, x2, y2, z2)
    return getDistance2d(z1, z2, getDistance2d(x1, y1, x2, y2), 0)
end

Источник:
http://www.gamedev.ru/tip/?id=41
PS: Да, это простая формула, списанная с чьего-то сайтика, но вдруг кому пригодится.
На сколько я понял, ноги растут из рядов тейлора, а значит 123+51/128 должно быть равно корню из 2. Однако тут немного меньше. Если использовать вместо 123 число 106, а вместо 51 число 74, то погрешность будет меньше. Проверенно на квадрате (dx == dy) с координатами Т1(1;1) и Т2(4;4), где Т1 - первая точка, а Т2 - вторая точка.

Посчитал. Для квадратов погрешность 0.5%, а для не квадратов менее 2%

UPD 2020:
Вспомнил про пост когда его лайкнули, и минут 10 сидел тупил в него, пытаясь вспомнить, что за Тейлор и какие у него там ряды. Немного погуглив частично разобрался, и считаю, что эту инфу стоит прописать тут.

Начинается все с такой не очень сложной фигни, как степенной ряд
1605667644635.png


Значек похожий на букву E - означает, что по тому, что справа надо пройти циклом типа такого:
C++:
auto result = 0;
for (int k = 0; k < INFINITY; ++k){
    result = a[k] * pow(x2 - x1, k);
}

В ряде Тейлора в качестве a[] используется функция, которую можно бесконечно дифференцировать в точке x1 (брать производную), и ряд тейлора выглядит так:
1605668369462.png

Восклицательный знак означает факториал - он встречается практически в каждом Hello World по рекурсии, пример на языке богов:
C++:
int fact(int i){
    if (!i) return 1;
    return fact(i - 1) * i;
}

Но вот, в чем я со своими остатками знаний так и не смог разобраться:
  1. почему делим на 128? Факториал от 5 = 120, а от 6 = 720. Дробное число? Гамма-в-рот-ее-ебать-функция???
  2. Каким хуем я умудрился это еще и оптимизировать? Почему 123 и 51 подходят меньше, чем 106 и 74, не тупой перебор же? А сумма у них 180 - это как-то связанно с углами? Мб тогда и 120 будет правельнее 128?
Кароче мне пора обратно в ВУЗ, а то тупею пиздец

UPD: Вопрос 2 отпадает, точность выше, только когда точки рядом, но чем они дальше, тем меньше точность с моими правками, видимо и правда на угад ебашил
 
Последнее редактирование:

FYP

Известный
Администратор
1,757
5,684
Описание: Универсальная функция для удобной отправки данных синхронизации. Умеет копировать данные локального игрока и игрока по иду. Требует SAMP.Lua.
Lua:
function samp_create_sync_data(sync_type, copy_from_player)
    local ffi = require 'ffi'
    local sampfuncs = require 'sampfuncs'
    -- from SAMP.Lua
    local raknet = require 'samp.raknet'
    require 'samp.synchronization'

    copy_from_player = copy_from_player or true
    local sync_traits = {
        player = {'PlayerSyncData', raknet.PACKET.PLAYER_SYNC, sampStorePlayerOnfootData},
        vehicle = {'VehicleSyncData', raknet.PACKET.VEHICLE_SYNC, sampStorePlayerIncarData},
        passenger = {'PassengerSyncData', raknet.PACKET.PASSENGER_SYNC, sampStorePlayerPassengerData},
        aim = {'AimSyncData', raknet.PACKET.AIM_SYNC, sampStorePlayerAimData},
        trailer = {'TrailerSyncData', raknet.PACKET.TRAILER_SYNC, sampStorePlayerTrailerData},
        unoccupied = {'UnoccupiedSyncData', raknet.PACKET.UNOCCUPIED_SYNC, nil},
        bullet = {'BulletSyncData', raknet.PACKET.BULLET_SYNC, nil},
        spectator = {'SpectatorSyncData', raknet.PACKET.SPECTATOR_SYNC, nil}
    }
    local sync_info = sync_traits[sync_type]
    local data_type = 'struct ' .. sync_info[1]
    local data = ffi.new(data_type, {})
    local raw_data_ptr = tonumber(ffi.cast('uintptr_t', ffi.new(data_type .. '*', data)))
    -- copy player's sync data to the allocated memory
    if copy_from_player then
        local copy_func = sync_info[3]
        if copy_func then
            local _, player_id
            if copy_from_player == true then
                _, player_id = sampGetPlayerIdByCharHandle(PLAYER_PED)
            else
                player_id = tonumber(copy_from_player)
            end
            copy_func(player_id, raw_data_ptr)
        end
    end
    -- function to send packet
    local func_send = function()
        local bs = raknetNewBitStream()
        raknetBitStreamWriteInt8(bs, sync_info[2])
        raknetBitStreamWriteBuffer(bs, raw_data_ptr, ffi.sizeof(data))
        raknetSendBitStreamEx(bs, sampfuncs.HIGH_PRIORITY, sampfuncs.UNRELIABLE_SEQUENCED, 1)
        raknetDeleteBitStream(bs)
    end
    -- metatable to access sync data and 'send' function
    local mt = {
        __index = function(t, index)
            return data[index]
        end,
        __newindex = function(t, index, value)
            data[index] = value
        end
    }
    return setmetatable({send = func_send}, mt)
end
Примеры использования:
Lua:
-- отправка фейковой позиции
local data = samp_create_sync_data('player')
data.position.x = 1337
data.position.y = 1488
data.position.z = 42
data.send()

-- отправка синхронизации транспорта по иду с изменением здоровья
local _, id = sampGetVehicleIdByCarHandle(car)
local data = samp_create_sync_data('vehicle')
data.vehicleId = id
data.position.x, data.position.y, data.position.z = getCarCoordinates(car)
data.vehicleHealth = 0
data.send()

-- фейковый выстрел
local data = samp_create_sync_data('bullet', false)
data.targetType = 1
data.targetId = any_player_id
data.origin.x, data.origin.y, data.origin.z = getActiveCameraCoordinates()
data.target.x, data.target.y, data.target.z = target_x, target_y, target_z
data.weaponId = getCurrentCharWeapon(PLAYER_PED)
data.send()
 
Последнее редактирование: