-- Техническое задание для функции calculateSteeringInputs
-- Цель функции:
-- Функция предназначена для вычисления управляющих воздействий (m_fLeftRightSkid, m_fSteeringUpDown, m_fSteeringLeftRight) для управления самолетом, чтобы направить его к заданной цельной позиции в пространстве. Управление должно быть ограничено диапазоном значений от -255 до 255 для каждой оси.
-- Входные параметры:
-- currentPosition: Текущая позиция самолета в пространстве (vec3), характеризующаяся координатами (x, y, z).
-- currentRotation: Текущее вращение самолета, представленное в виде кватерниона (quat).
-- targetPosition: Целевая позиция в пространстве (vec3), к которой должен направляться самолет.
-- Выходные данные:
-- Вектор воздействий (vec3), содержащий три компонента, которые представляют собой величины управления по оси скольжения, тангажа и крена, соответственно.
local maf = require 'maf'
local vec3 = maf.vec3
local quat = maf.quat
local function calculateSteeringInputs(currentPosition, currentRotation, targetPosition)
return pitchInput, yawInput, rollInput
end
-- Основная функция Lua
function main()
-- Ожидание, пока игрок не начнет игру
while not isPlayerPlaying(PLAYER_HANDLE) do wait(100) end
wait(100)
-- Основной игровой цикл
while true do wait(0)
if isCharInAnyCar(playerPed) then
-- Получение объекта транспортного средства
local car = storeCarCharIsInNoSave(playerPed)
-- Получение ориентации и позиции транспортного средства
local rotX, rotY, rotZ, rotW = getVehicleQuaternion(car)
local positionX, positionY, positionZ = getCarCoordinates(car)
-- Расчет целевой позиции, основываясь на центре экрана (камера)
local resX, resY = getScreenResolution()
local cameraX, cameraY, cameraZ = convertScreenCoordsToWorld3D(resX / 2, resY / 2, 100)
-- Создание векторов для текущей и целевой позиции
local currentPosition = vec3(positionX, positionY, positionZ)
local currentRotation = quat(rotX, rotY, rotZ, rotW)
local targetPosition = vec3(cameraX, cameraY, cameraZ)
-- Вычисление управляющих воздействий для управления самолётом
local pitchInput, yawInput, rollInput = calculateSteeringInputs(currentPosition, currentRotation, targetPosition)
print("Steering Inputs: ", pitchInput, yawInput, rollInput)
-- Проверка, существует ли транспортное средство
if doesVehicleExist(car) then
local carPointer = getCarPointer(car)
local vehicle = samem.cast("CVehicle *", carPointer)
-- Регистрация управления самолётом, если это самолёт
if vehicle ~= samem.nullptr and vehicle.nVehicleClass == 0 then -- VEHICLE_TYPE_AUTOMOBILE = 0
local plane = samem.cast('CPlane *', vehicle)
plane.field_988 = 0
plane.field_98C = pitchInput * 1065353213
plane.field_990 = rollInput * 1065353213
print('UpDown Input: ', plane.field_98C / 1065353213)
print('LeftRight Input: ', plane.field_990 / 1065353213)
end
end
end
end
Assistant
User
там нет никакого inverse
Assistant
User
и Conjugate нету
Assistant
User
[ML] (error) (^^)temporary.lua: ...\username\Desktop\GTA San Andreas\moonloader\lib\maf.lua:27: vec3s can only be multiplied by vec3s and numbers
stack traceback:
Assistant
User
инпут должен быть от -1 до 1*
там небольшая ошибка
__add = function(v, u) return v:add(u, vec3()) end,
__sub = function(v, u) return v:sub(u, vec3()) end,
__mul = function(v, u)
if vec3.isvec3(u) then return v:mul(u, vec3())
elseif type(u) == 'number' then return v:scale(u, vec3())
else error('vec3s can only be multiplied by vec3s and numbers') end
end,
__div = function(v, u)
if vec3.isvec3(u) then return v:div(u, vec3())
elseif type(u) == 'number' then return v:scale(1 / u, vec3())
else error('vec3s can only be divided by vec3s and numbers') end
end,
__unm = function(v) return v:scale(-1) end,
__len = function(v) return v:length() end,
__index = {
isvec3 = function(x)
return ffi and ffi.istype('vec3', x) or getmetatable(x) == vec3
end,
clone = function(v)
return vec3(v.x, v.y, v.z)
end,
unpack = function(v)
return v.x, v.y, v.z
end,
set = function(v, x, y, z)
if vec3.isvec3(x) then x, y, z = x.x, x.y, x.z end
v.x = x
v.y = y
v.z = z
return v
end,
add = function(v, u, out)
out = out or v
out.x = v.x + u.x
out.y = v.y + u.y
out.z = v.z + u.z
return out
end,
sub = function(v, u, out)
out = out or v
out.x = v.x - u.x
out.y = v.y - u.y
out.z = v.z - u.z
return out
end,
mul = function(v, u, out)
out = out or v
out.x = v.x * u.x
out.y = v.y * u.y
out.z = v.z * u.z
return out
end,
div = function(v, u, out)
out = out or v
out.x = v.x / u.x
out.y = v.y / u.y
out.z = v.z / u.z
return out
end,
scale = function(v, s, out)
out = out or v
out.x = v.x * s
out.y = v.y * s
out.z = v.z * s
return out
end,
length = function(v)
return math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z)
end,
normalize = function(v, out)
out = out or v
local len = v:length()
return len == 0 and v or v:scale(1 / len, out)
end,
distance = function(v, u)
return vec3.sub(v, u, vtmp1):length()
end,
angle = function(v, u)
return math.acos(v:dot(u) / (v:length() + u:length()))
end,
dot = function(v, u)
return v.x * u.x + v.y * u.y + v.z * u.z
end,
cross = function(v, u, out)
out = out or v
local a, b, c = v.x, v.y, v.z
out.x = b * u.z - c * u.y
out.y = c * u.x - a * u.z
out.z = a * u.y - b * u.x
return out
end,
lerp = function(v, u, t, out)
out = out or v
out.x = v.x + (u.x - v.x) * t
out.y = v.y + (u.y - v.y) * t
out.z = v.z + (u.z - v.z) * t
return out
end,
project = function(v, u, out)
out = out or v
local unorm = vtmp1
u:normalize(unorm)
local dot = v:dot(unorm)
out.x = unorm.x * dot
out.y = unorm.y * dot
out.z = unorm.z * dot
return out
end,
rotate = function(v, q, out)
out = out or v
local u, c, o = vtmp1, vtmp2, out
u.x, u.y, u.z = q.x, q.y, q.z
o.x, o.y, o.z = v.x, v.y, v.z
u:cross(v, c)
local uu = u:dot(u)
local uv = u:dot(v)
o:scale(q.w * q.w - uu)
u:scale(2 * uv)
c:scale(2 * q.w)
return o:add(u:add(c))
end
}
}
quat = {
__call = function(_, x, y, z, w)
return setmetatable({ x = x, y = y, z = z, w = w }, quat)
end,
Target selfTarget;
Plane targetPlane;
Vector3 lastInput;
bool isRecoveringSpeed;
float missileDelayTimer;
float missileCooldownTimer;
bool cannonFiring;
float cannonBurstTimer;
float cannonCooldownTimer;
struct ControlInput {
public float time;
public Vector3 targetPosition;
}
Queue<ControlInput> inputQueue;
bool dodging;
Vector3 lastDodgePoint;
List<Vector3> dodgeOffsets;
const float dodgeUpdateInterval = 0.25f;
float dodgeTimer;
void Start() {
selfTarget = plane.GetComponent<Target>();
if (plane.Target != null) {
targetPlane = plane.Target.GetComponent<Plane>();
}
dodgeOffsets = new List<Vector3>();
inputQueue = new Queue<ControlInput>();
}
Vector3 AvoidGround() {
//roll level and pull up
var roll = plane.Rigidbody.rotation.eulerAngles.z;
if (roll > 180f) roll -= 360f;
return new Vector3(-1, 0, Mathf.Clamp(-roll * rollFactor, -1, 1));
}
Vector3 RecoverSpeed() {
//roll and pitch level
var roll = plane.Rigidbody.rotation.eulerAngles.z;
var pitch = plane.Rigidbody.rotation.eulerAngles.x;
if (roll > 180f) roll -= 360f;
if (pitch > 180f) pitch -= 360f;
return new Vector3(Mathf.Clamp(-pitch, -1, 1), 0, Mathf.Clamp(-roll * rollFactor, -1, 1));
}
Vector3 GetTargetPosition() {
if (plane.Target == null) {
return plane.Rigidbody.position;
}
var targetPosition = plane.Target.Position;
if (Vector3.Distance(targetPosition, plane.Rigidbody.position) < cannonRange) {
return Utilities.FirstOrderIntercept(plane.Rigidbody.position, plane.Rigidbody.velocity, bulletSpeed, targetPosition, plane.Target.Velocity);
}
return targetPosition;
}
Vector3 CalculateSteering(float dt, Vector3 targetPosition) {
if (plane.Target != null && targetPlane.Health == 0) {
return new Vector3();
}
var error = targetPosition - plane.Rigidbody.position;
error = Quaternion.Inverse(plane.Rigidbody.rotation) * error; //transform into local space
var errorDir = error.normalized;
var pitchError = new Vector3(0, error.y, error.z).normalized;
var rollError = new Vector3(error.x, error.y, 0).normalized;
var yawError = new Vector3(error.x, 0, error.z).normalized;
var targetInput = new Vector3();
var pitch = Vector3.SignedAngle(Vector3.forward, pitchError, Vector3.right);
if (-pitch < pitchUpThreshold) pitch += 360f;
targetInput.x = pitch;
if (Vector3.Angle(Vector3.forward, errorDir) < fineSteeringAngle) {
var yaw = Vector3.SignedAngle(Vector3.forward, yawError, Vector3.up);
targetInput.y = yaw * yawFactor;
} else {
var roll = Vector3.SignedAngle(Vector3.up, rollError, Vector3.forward);
targetInput.z = roll * rollFactor;
}
targetInput.x = Mathf.Clamp(targetInput.x, -1, 1);
targetInput.y = Mathf.Clamp(targetInput.y, -1, 1);
targetInput.z = Mathf.Clamp(targetInput.z, -1, 1);
var input = Vector3.MoveTowards(lastInput, targetInput, steeringSpeed * dt);
lastInput = input;
return input;
}
Vector3 GetMissileDodgePosition(float dt, Missile missile) {
dodgeTimer = Mathf.Max(0, dodgeTimer - dt);
var missilePos = missile.Rigidbody.position;
var dist = Mathf.Max(minMissileDodgeDistance, Vector3.Distance(missilePos, plane.Rigidbody.position));
//calculate dodge points
if (dodgeTimer == 0) {
var missileForward = missile.Rigidbody.rotation * Vector3.forward;
dodgeOffsets.Clear();
//4 dodge points: up, down, left, right
dodgeOffsets.Add(new Vector3(0, dist, 0));
dodgeOffsets.Add(new Vector3(0, -dist, 0));
dodgeOffsets.Add(Vector3.Cross(missileForward, Vector3.up) * dist);
dodgeOffsets.Add(Vector3.Cross(missileForward, Vector3.up) * -dist);
dodgeTimer = dodgeUpdateInterval;
}
//select nearest dodge point
float min = float.PositiveInfinity;
Vector3 minDodge = missilePos + dodgeOffsets[0];
foreach (var offset in dodgeOffsets) {
var dodgePosition = missilePos + offset;
var offsetDist = Vector3.Distance(dodgePosition, lastDodgePoint);
if (offsetDist < min) {
minDodge = dodgePosition;
min = offsetDist;
}
}
lastDodgePoint = minDodge;
return minDodge;
}
float CalculateThrottle(float minSpeed, float maxSpeed) {
float input = 0;
if (plane.LocalVelocity.z < minSpeed) {
input = 1;
} else if (plane.LocalVelocity.z > maxSpeed) {
input = -1;
}
return input;
}
void CalculateWeapons(float dt) {
if (plane.Target == null) return;
if (canUseMissiles) {
CalculateMissiles(dt);
}
if (canUseCannon) {
CalculateCannon(dt);
}
}
void CalculateMissiles(float dt) {
missileDelayTimer = Mathf.Max(0, missileDelayTimer - dt);
missileCooldownTimer = Mathf.Max(0, missileCooldownTimer - dt);
var error = plane.Target.Position - plane.Rigidbody.position;
var range = error.magnitude;
var targetDir = error.normalized;
var targetAngle = Vector3.Angle(targetDir, plane.Rigidbody.rotation * Vector3.forward);
if (!plane.MissileLocked || !(targetAngle < missileMaxFireAngle || (180f - targetAngle) < missileMaxFireAngle)) {
//don't fire if not locked or target is too off angle
//can fire if angle is close to 0 (chasing) or 180 (head on)
missileDelayTimer = missileLockFiringDelay;
}
if (range < missileMaxRange && range > missileMinRange && missileDelayTimer == 0 && missileCooldownTimer == 0) {
plane.TryFireMissile();
missileCooldownTimer = missileFiringCooldown;
}
}
void CalculateCannon(float dt) {
if (targetPlane.Health == 0) {
cannonFiring = false;
return;
}
if (cannonFiring) {
cannonBurstTimer = Mathf.Max(0, cannonBurstTimer - dt);
if (cannonBurstTimer == 0) {
cannonFiring = false;
cannonCooldownTimer = cannonBurstCooldown;
plane.SetCannonInput(false);
}
} else {
cannonCooldownTimer = Mathf.Max(0, cannonCooldownTimer - dt);
var targetPosition = Utilities.FirstOrderIntercept(plane.Rigidbody.position, plane.Rigidbody.velocity, bulletSpeed, plane.Target.Position, plane.Target.Velocity);
var error = targetPosition - plane.Rigidbody.position;
var range = error.magnitude;
var targetDir = error.normalized;
var targetAngle = Vector3.Angle(targetDir, plane.Rigidbody.rotation * Vector3.forward);
if (range < cannonRange && targetAngle < cannonMaxFireAngle && cannonCooldownTimer == 0) {
cannonFiring = true;
cannonBurstTimer = cannonBurstLength;
plane.SetCannonInput(true);
}
}
}
void SteerToTarget(float dt, Vector3 planePosition) {
bool foundTarget = false;
Vector3 steering = Vector3.zero;
Vector3 targetPosition = Vector3.zero;
var delay = reactionDelayMax;
if (Vector3.Distance(planePosition, plane.Rigidbody.position) < reactionDelayDistance) {
delay = reactionDelayMin;
}
while (inputQueue.Count > 0) {
var input = inputQueue.Peek();
if (input.time + delay <= Time.time) {
targetPosition = input.targetPosition;
inputQueue.Dequeue();
foundTarget = true;
} else {
break;
}
}
if (foundTarget) {
steering = CalculateSteering(dt, targetPosition);
}
plane.SetControlInput(steering);
}
void FixedUpdate() {
if (plane.Dead) return;
var dt = Time.fixedDeltaTime;
Vector3 steering = Vector3.zero;
float throttle;
bool emergency = false;
Vector3 targetPosition = plane.Target.Position;
var velocityRot = Quaternion.LookRotation(plane.Rigidbody.velocity.normalized);
var ray = new Ray(plane.Rigidbody.position, velocityRot * Quaternion.Euler(groundAvoidanceAngle, 0, 0) * Vector3.forward);
if (Physics.Raycast(ray, groundCollisionDistance + plane.LocalVelocity.z, groundCollisionMask.value)) {
steering = AvoidGround();
throttle = CalculateThrottle(groundAvoidanceMinSpeed, groundAvoidanceMaxSpeed);
emergency = true;
} else {
var incomingMissile = selfTarget.GetIncomingMissile();
if (incomingMissile != null) {
if (dodging == false) {
//start dodging
dodging = true;
lastDodgePoint = plane.Rigidbody.position;
dodgeTimer = 0;
}
var dodgePosition = GetMissileDodgePosition(dt, incomingMissile);
steering = CalculateSteering(dt, dodgePosition);
emergency = true;
} else {
dodging = false;
targetPosition = GetTargetPosition();
}
if (incomingMissile == null && (plane.LocalVelocity.z < recoverSpeedMin || isRecoveringSpeed)) {
isRecoveringSpeed = plane.LocalVelocity.z < recoverSpeedMax;
steering = RecoverSpeed();
throttle = 1;
emergency = true;
} else {
throttle = CalculateThrottle(minSpeed, maxSpeed);
}
}
inputQueue.Enqueue(new ControlInput {
time = Time.time,
targetPosition = targetPosition,
});
plane.SetThrottleInput(throttle);
if (emergency) {
if (isRecoveringSpeed) {
//reduce steering strength while recovering speed
steering.x = Mathf.Clamp(steering.x, -0.5f, 0.5f);
}
plane.SetControlInput(steering);
} else {
SteerToTarget(dt, plane.Target.Position);
}
CalculateWeapons(dt);
}
}
To create the calculateSteeringInputs function using the maf library as detailed in the Lua example, we need to calculate pitch, yaw, and roll adjustments to steer the plane towards a target position. Below you'll find a solution that adheres to the principles outlined in the provided Lua and C# examples.
The key idea is to transform the difference vector between the current position and the target position (error vector) into the plane's local coordinate space. The steering inputs are then calculated based on the orientation difference in this space. Here's how you can implement this:
local function calculateSteeringInputs(currentPosition, currentRotation, targetPosition)
-- Calculate the error vector (target direction)
local errorVector = targetPosition - currentPosition
-- Transform the error vector to local space of the plane using the inverse of the current quaternion rotation
local localErrorVector = currentRotation:inverse() * errorVector
-- Normalize the error direction
local normalizedError = localErrorVector:normalize()
-- For pitch input: project the error on the xz-plane and find angle deviation from the local forward direction
local pitchError = vec3(0, normalizedError.y, normalizedError.z):normalize()
local pitchInput = math.deg(math.asin(pitchError.y))
-- For roll input: project the error on the xy-plane and calculate roll angle needed to align vertically
local rollError = vec3(normalizedError.x, normalizedError.y, 0):normalize()
local rollInput = math.deg(math.asin(rollError.x))
-- For yaw input: project the error on the xz-plane and calculate the yaw needed to steer left/right
local yawError = vec3(normalizedError.x, 0, normalizedError.z):normalize()
local yawInput = math.deg(math.asin(yawError.x))
-- Clamp values to ensure they are within the control range of [-255, 255]
pitchInput = math.min(math.max(pitchInput * 2.55, -255), 255)
rollInput = math.min(math.max(rollInput * 2.55, -255), 255)
yawInput = math.min(math.max(yawInput * 2.55, -255), 255)
return pitchInput, yawInput, rollInput
end
Explanation:
Error Vector: This is the vector from the current position of the plane to the target. It represents the direction in which the plane should be steered.
Local Transformation: We transform this vector into the plane's local coordinate system (aligned to the forward vector of the plane), which helps in determining how to steer the plane.
Pitch, Roll, Yaw Calculations: We project the error vector onto respective plane coordinate planes (xz, xy, and yz planes). Calculating the angle gives us the required input adjustment to make the plane align towards the target.
Clamp and Scale Inputs: We ensure the computed inputs are within the acceptable range of [-255, 255], which simulates the range expected by the controlling system.
This function can be adapted and expanded based on additional nuances or controls specific to your simulation or game environment, such as accommodating for more complex flight dynamics.
Apologies for the confusion. Let's adjust the implementation to avoid using a specific inverse function if that functionality isn't provided directly by the maf library. We can achieve the desired transformation by using the properties of unit quaternions. Here's an adjusted version of the calculateSteeringInputs function:
local function calculateSteeringInputs(currentPosition, currentRotation, targetPosition)
-- Calculate the error vector (target direction)
local errorVector = targetPosition - currentPosition
-- Convert the quaternion into its conjugate (equivalent to inverse for unit quaternions)
local conjRotation = quat(-currentRotation.x, -currentRotation.y, -currentRotation.z, currentRotation.w)
-- Transform the error vector to the local space of the plane
local localErrorVector = conjRotation * errorVector * currentRotation
-- Normalize the error direction
local normalizedError = localErrorVector:normalize()
-- For pitch input: project the error on the xz-plane and find angle deviation from the local forward direction
local pitchError = vec3(0, normalizedError.y, normalizedError.z):normalize()
local pitchInput = math.deg(math.asin(pitchError.y))
-- For roll input: project the error on the xy-plane and calculate roll angle needed to align vertically
local rollError = vec3(normalizedError.x, normalizedError.y, 0):normalize()
local rollInput = math.deg(math.asin(rollError.x))
-- For yaw input: project the error on the xz-plane and calculate the yaw needed to steer left/right
local yawError = vec3(normalizedError.x, 0, normalizedError.z):normalize()
local yawInput = math.deg(math.asin(yawError.x))
-- Clamp values to ensure they are within the control range of [-255, 255]
pitchInput = math.min(math.max(pitchInput * 2.55, -255), 255)
rollInput = math.min(math.max(rollInput * 2.55, -255), 255)
yawInput = math.min(math.max(yawInput * 2.55, -255), 255)
return pitchInput, yawInput, rollInput
end
Key Points:
Using the Conjugate Quaternion: A quaternion conjugate is used to apply inverse rotation because quaternions representing rotation have unit length, so the conjugate serves the same purpose as an inverse for our needs.
Transform the Error Vector: The error vector is multiplied by the quaternion's conjugate to transform it into the local space of the plane. This operation re-orients the error vector to consider the plane's current rotation, ensuring steering is computed relative to the plane's orientation.
Compute and Clamp Inputs: The remaining computational principles for deriving pitch, roll, and yaw inputs remain similar, including clamping the final calculated steering inputs to the desired control range.
Note that this function assumes that multiplication of a quaternion by a vector (currentRotation * errorVector) and a quaternion by another quaternion (for the conjugate operation) is defined and behaves as expected in the maf library. If not, further adjustment to the quaternion handling in this function might be required.
If the maf library doesn't provide a direct method for calculating the quaternion inverse or conjugate, we can manually perform the mathematical operation. For unit quaternions, the inverse is the conjugate, and it can be calculated by negating the vector part (x, y, z) of the quaternion while keeping the scalar part (w) the same.
Here's a revised version of the calculateSteeringInputs function that implements quaternion inverse using this approach:
local function calculateSteeringInputs(currentPosition, currentRotation, targetPosition)
-- Calculate the error vector (target direction)
local errorVector = targetPosition - currentPosition
-- Compute the conjugate (inverse for unit quaternion) of the current rotation
local invRotation = quat(-currentRotation.x, -currentRotation.y, -currentRotation.z, currentRotation.w)
-- Transform the error vector to the local space of the plane using the inverse rotation
-- Note: Quaternion vector rotation is q * v * q^-1
local rotatedErrorVector = invRotation * vec3(errorVector.x, errorVector.y, errorVector.z) * currentRotation
-- Normalize the error direction
local normalizedError = rotatedErrorVector:normalize()
-- For pitch input: take angle deviation in the y/z plane
local pitchError = vec3(0, normalizedError.y, normalizedError.z):normalize()
local pitchInput = math.deg(math.asin(math.max(-1, math.min(1, pitchError.y))))
-- For roll input: consider deviation in the y/x plane
local rollError = vec3(normalizedError.x, normalizedError.y, 0):normalize()
local rollInput = math.deg(math.asin(math.max(-1, math.min(1, rollError.x))))
-- For yaw input: examine x/z plane deviation
local yawError = vec3(normalizedError.x, 0, normalizedError.z):normalize()
local yawInput = math.deg(math.asin(math.max(-1, math.min(1, yawError.x))))
-- Clamp values to ensure they are within the control range of [-255, 255]
pitchInput = math.min(math.max(pitchInput * 2.55, -255), 255)
rollInput = math.min(math.max(rollInput * 2.55, -255), 255)
yawInput = math.min(math.max(yawInput * 2.55, -255), 255)
return pitchInput, yawInput, rollInput
end
Key Adjustments:
Quaternion Calculation: I manually negated the x, y, and z components of the quaternion to find the conjugate, which acts as the inverse when the quaternion is a unit quaternion.
Vector Rotation: To transform the error vector into the plane's local coordinate system, I multiplied it by the inverse quaternion (conjugate) and then by the original quaternion. This operation reorients the vector based on the current plane orientation.
Trigonometry Safeguarding: I used math.max and math.min to constrain the asin function's argument, ensuring it remains within the valid range of [-1, 1] as a safe-guard against floating-point precision issues.
This solution assumes quaternion-vector and quaternion-quaternion multiplications are handled as described. If the maf library doesn't directly support these operations, you might need to implement quaternion-vector multiplication manually or use another suitable library for these operations.
The error message you're seeing indicates that the multiplication operation in your code is attempting to multiply a vec3 object by a quaternion, which isn't directly supported by the maf library. The calculations involving vector rotations using quaternions typically involve specialized logic and are not simply vector-quaternion multiplications.
To rotate a vector by a quaternion in a 3D space, you can manually implement the necessary quaternion-vector multiplication. This involves using some of the quaternion mathematics, as follows:
Quaternion-to-Vector Rotation: To rotate a vector using a quaternion, the formula is v' = q * v * q⁻¹, where q is the quaternion and v is the vector represented as a quaternion (with a 0 scalar).
Implement Vector Rotation: Let's manually implement the rotation.
Here is the corrected code with vector rotation logic integrated without relying on unsupported operations:
local function rotateVectorByQuaternion(v, q)
-- Convert the vector into a quaternion with w = 0
local qv = quat(v.x, v.y, v.z, 0)
-- Calculate q * v * q⁻¹ (essentially rotating vector v by quaternion q)
local qConjugate = quat(-q.x, -q.y, -q.z, q.w)
local rotatedQ = q * qv * qConjugate
-- Return the vector part of the result
return vec3(rotatedQ.x, rotatedQ.y, rotatedQ.z)
end
local function calculateSteeringInputs(currentPosition, currentRotation, targetPosition)
-- Calculate the error vector (target direction)
local errorVector = targetPosition - currentPosition
-- Transform the error vector to the local space of the plane
local localErrorVector = rotateVectorByQuaternion(errorVector, currentRotation)
-- Normalize the error direction
local normalizedError = localErrorVector:normalize()
-- Calculate the different input values
local pitchError = vec3(0, normalizedError.y, normalizedError.z):normalize()
local pitchInput = math.deg(math.asin(math.max(-1, math.min(1, pitchError.y))))
local rollError = vec3(normalizedError.x, normalizedError.y, 0):normalize()
local rollInput = math.deg(math.asin(math.max(-1, math.min(1, rollError.x))))
local yawError = vec3(normalizedError.x, 0, normalizedError.z):normalize()
local yawInput = math.deg(math.asin(math.max(-1, math.min(1, yawError.x))))
-- Clamp values to ensure they are within the control range of [-255, 255]
pitchInput = math.min(math.max(pitchInput * 2.55, -255), 255)
rollInput = math.min(math.max(rollInput * 2.55, -255), 255)
yawInput = math.min(math.max(yawInput * 2.55, -255), 255)
return pitchInput, yawInput, rollInput
end
Explanation:
Quaternion to Vector Rotation: We manually rotate the vector using quaternion mathematics by constructing a quaternion from the vector and applying the standard quaternion rotation formula.
Vector Rotation Method: We added a helper function, rotateVectorByQuaternion, which performs the essential quaternion-rotation arithmetic to apply the rotation to the vector.
This approach should handle the vector rotation correctly using the quaternion's properties and avoid unsupported operations in the maf library. Make sure the operations within this logic are aligned with how your specific library handles quaternion algebra.
Thank you for pointing that out. Let's correct the implementation so that the inputs are clamped between -1 and 1 rather than scaled to the range of -255 to 255.
Here's the updated version of the calculateSteeringInputs function with the correct clamping range applied:
local function rotateVectorByQuaternion(v, q)
-- Convert the vector into a quaternion with w = 0
local qv = quat(v.x, v.y, v.z, 0)
-- Calculate q * v * q⁻¹ (essentially rotating vector v by quaternion q)
local qConjugate = quat(-q.x, -q.y, -q.z, q.w)
local rotatedQ = q * qv * qConjugate
-- Return the vector part of the result
return vec3(rotatedQ.x, rotatedQ.y, rotatedQ.z)
end
local function calculateSteeringInputs(currentPosition, currentRotation, targetPosition)
-- Calculate the error vector (target direction)
local errorVector = targetPosition - currentPosition
-- Transform the error vector to the local space of the plane
local localErrorVector = rotateVectorByQuaternion(errorVector, currentRotation)
-- Normalize the error direction
local normalizedError = localErrorVector:normalize()
-- Calculate the different input values
local pitchError = vec3(0, normalizedError.y, normalizedError.z):normalize()
local pitchInput = math.asin(math.max(-1, math.min(1, pitchError.y)))
local rollError = vec3(normalizedError.x, normalizedError.y, 0):normalize()
local rollInput = math.asin(math.max(-1, math.min(1, rollError.x)))
local yawError = vec3(normalizedError.x, 0, normalizedError.z):normalize()
local yawInput = math.asin(math.max(-1, math.min(1, yawError.x)))
-- Convert from radians to meaningful control input (range [-1, 1])
pitchInput = math.min(math.max(pitchInput / (math.pi / 2), -1), 1)
rollInput = math.min(math.max(rollInput / (math.pi / 2), -1), 1)
yawInput = math.min(math.max(yawInput / (math.pi / 2), -1), 1)
return pitchInput, yawInput, rollInput
end
Key Changes:
Normalization and Conversion: The returned steering inputs are clamped to the range [-1, 1]. This is done by dividing the angle obtained from asin (which returns in radians) by π/2 to normalize the range to [-1, 1].
Input Constraints: By applying math.min and math.max, we ensure that the inputs remain within this [-1, 1] range, suitable for control inputs typically required by game or simulation environments.
This should provide you with normalized control inputs suitable for smoothly controlling your plane's motion towards the target. Adjust these transformations according to your specific dynamics or control sensitivity if required.
Not yet included in a published release.
--]] -- Техническое задание для функции… · The Chat Archive