MegiRicky

rangefinderStablizerV2.lua

Apr 20th, 2026
22
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.33 KB | None | 0 0
  1. radar = peripheral.find("sp_radar")
  2.  
  3. local cannons = {}
  4. local foundNames = {}
  5. local k = 1
  6.  
  7. local directions = {"top", "bottom", "left", "right", "front", "back"}
  8. for _, side in ipairs(directions) do
  9. if peripheral.isPresent(side) then
  10. local name = peripheral.getType(side)
  11. if name == "createbigcannons:cannon_mount" or name == "cbcmodernwarfare:compact_mount" then
  12. local cannon = peripheral.wrap(side)
  13. if cannon then
  14. cannons[k] = cannon
  15. foundNames[peripheral.getName(cannon)] = true
  16. print("Found direct cannon on side: " .. side)
  17. k = k + 1
  18. end
  19. end
  20. end
  21. end
  22.  
  23. local i = 0
  24. local nilCount = 0
  25. local maxNilTolerance = 200
  26.  
  27. while nilCount < maxNilTolerance do
  28. local addr1 = "createbigcannons:cannon_mount_" .. i
  29. local addr2 = "cbcmodernwarfare:compact_mount_" .. i
  30.  
  31. local cannon = peripheral.wrap(addr1)
  32. if not cannon then
  33. cannon = peripheral.wrap(addr2)
  34. end
  35.  
  36. if cannon then
  37. local name = peripheral.getName(cannon)
  38. if not foundNames[name] then
  39. cannons[k] = cannon
  40. foundNames[name] = true
  41. print("Found network cannon: " .. name)
  42. k = k + 1
  43. end
  44. nilCount = 0
  45. else
  46. nilCount = nilCount + 1
  47. end
  48.  
  49. i = i + 1
  50. end
  51.  
  52. print("Total cannons found: " .. #cannons)
  53. cannons[1].assemble()
  54.  
  55. -- Cooldown variables
  56. local cooldownTime = 0.3 -- Cooldown time in seconds
  57. local lastTriggerTime = 0 -- Time when the script was last triggered
  58. local verticalSensitivity = 0.5
  59. redstoneSides = {
  60. laserRangeFinder = "front",
  61. cannonUpInput = "top",
  62. cannonDownInput = "bottom"
  63. }
  64.  
  65. -- Normalize a vector
  66. local function normalizeVector(v)
  67. local length = math.sqrt(v[1]^2 + v[2]^2 + v[3]^2)
  68. if length == 0 then
  69. return {0, 0, 0}
  70. end
  71. return {v[1] / length, v[2] / length, v[3] / length}
  72. end
  73.  
  74. -- Normalize the rotation matrix
  75. local function normalizeRotationMatrix(rotMatrix)
  76. local normalizedMatrix = {}
  77. for i = 1, #rotMatrix do
  78. normalizedMatrix[i] = normalizeVector(rotMatrix[i])
  79. end
  80. return normalizedMatrix
  81. end
  82.  
  83. -- Get the pitch of the ship
  84. local function getPitch()
  85. local rotMatrix = ship.getTransformationMatrix()
  86. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  87. return math.asin(normalizedMatrix[2][3]) -- Extract pitch from the matrix
  88. end
  89. --pitch = math.deg(math.asin(ship.getTransformationMatrix()[2][3]))
  90. -- Get the yaw of the ship
  91. local function getYaw()
  92. local rotMatrix = ship.getTransformationMatrix()
  93. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  94. return math.atan2(-normalizedMatrix[3][1], -normalizedMatrix[3][3]) -- Extract yaw from the matrix
  95. end
  96.  
  97. -- Get the roll of the ship
  98. local function getRoll()
  99. local rotMatrix = ship.getTransformationMatrix()
  100. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  101. return math.atan2(normalizedMatrix[2][1], normalizedMatrix[2][2]) -- Extract roll from the matrix
  102. end
  103.  
  104. local function yawPitchToLookVec(yawDeg, pitchDeg)
  105. local yaw = math.rad(yawDeg)
  106. local pitch = math.rad(pitchDeg)
  107.  
  108. local x = math.sin(yaw) * math.cos(pitch)
  109. local y = math.sin(pitch)
  110. local z = -math.cos(yaw) * math.cos(pitch)
  111.  
  112. return { x = x, y = y, z = z }
  113. end
  114.  
  115.  
  116.  
  117. local function setPitchYaw(targetPitch, targetYaw)
  118. local tasks = {} -- Table to store each cannon's task
  119.  
  120. for index, cannon in pairs(cannons) do
  121. -- Define the function for this cannon's pitch/yaw adjustment
  122. local function adjustCannon()
  123. cannon.setPitch(targetPitch)
  124. cannon.setYaw(targetYaw)
  125. end
  126. -- Add this task to the tasks table
  127. table.insert(tasks, adjustCannon)
  128. end
  129.  
  130. -- Execute all tasks in parallel
  131. parallel.waitForAll(table.unpack(tasks))
  132. end
  133.  
  134. local function askUser(prompt, defaultValue)
  135. print(prompt .. " (default: " .. defaultValue .. ")")
  136. local input = io.read()
  137. if input == "" then
  138. return defaultValue
  139. else
  140. return input
  141. end
  142. end
  143.  
  144. local projectileSpeed = askUser("Enter the projectileSpeed","240")
  145. local g = askUser("Enter the g","0.02")
  146. local cd =askUser("Enter the cd","0.995")
  147. local enableLaserRangeFinder = askUser("Enable laserRangeFinder?","yes")
  148. print("enableVeticalStablizer?")
  149. local enableVerticalStablizer = askUser("Enable vertical stablizer?","yes")
  150. if enableVerticalStablizer == "yes" then
  151. enableVerticalStablizer = true
  152. else
  153. enableVerticalStablizer = false
  154. end
  155. if enableVerticalStablizer and pitchMotor then
  156. print("pitch motor operational, vertical stab on")
  157. else
  158. print("pitch motor offline, vertical stab are off")
  159. enableVerticalStablizer = false
  160. end
  161.  
  162. if enableVerticalStablizer then
  163. verticalDriveRPM = askUser("enter the vertical drive maximum RPM","7.4")
  164. verticalMaxAngularVelocity = verticalDriveRPM / 60 * 360 / 8
  165. end
  166. local vm
  167.  
  168. local localCannonYaw, localCannonPitch = cannons[1].getYaw(), cannons[1].getPitch()
  169. if localCannonYaw == 0 then
  170. shipPitch = math.deg(getPitch())
  171. elseif localCannonYaw == 90 then
  172. shipPitch = -math.deg(getRoll())
  173. elseif localCannonYaw == 180 then
  174. shipPitch = -math.deg(getPitch())
  175. elseif localCannonYaw == 270 then
  176. shipPitch = math.deg(getRoll())
  177. else
  178. error("Yaw offseted, cannon process")
  179. end
  180.  
  181. local function findRelativeAngle(targetYaw,targetPitch)
  182. rot = ship.getQuaternion()
  183. cacheYaw = math.pi - math.rad(targetYaw)
  184. cachePitch = - math.rad(targetPitch)
  185. rotMatAdj11 = 1 - 2*(rot.x^2 + rot.y^2)
  186. rotMatAdj12 = 2*(rot.z * rot.x + rot.y * rot.w)
  187. rotMatAdj13 = 2*(rot.z * rot.y - rot.x * rot.w)
  188. rotMatAdj21 = 2*(rot.z * rot.x - rot.y * rot.w)
  189. rotMatAdj22 = 1 - 2*(rot.z^2 + rot.y^2)
  190. rotMatAdj23 = 2*(rot.x * rot.y + rot.z * rot.w)
  191. rotMatAdj31 = 2*(rot.z * rot.y + rot.x * rot.w)
  192. rotMatAdj32 = 2*(rot.x * rot.y - rot.z * rot.w)
  193. rotMatAdj33 = 1 - 2*(rot.z^2 + rot.x^2)
  194.  
  195. rotMatTGT11 = math.cos(cacheYaw) * math.cos(cachePitch)
  196. rotMatTGT21 = math.sin(cacheYaw) * math.cos(cachePitch)
  197. rotMatTGT31 = - math.sin(cachePitch)
  198.  
  199. rotMatRSLT11 = rotMatAdj11 * rotMatTGT11 + rotMatAdj12 * rotMatTGT21 + rotMatAdj13 * rotMatTGT31
  200. rotMatRSLT21 = rotMatAdj21 * rotMatTGT11 + rotMatAdj22 * rotMatTGT21 + rotMatAdj23 * rotMatTGT31
  201. rotMatRSLT31 = rotMatAdj31 * rotMatTGT11 + rotMatAdj32 * rotMatTGT21 + rotMatAdj33 * rotMatTGT31
  202.  
  203. turretYaw = math.atan2(rotMatRSLT21, rotMatRSLT11)
  204. barrelPitch = math.asin(-rotMatRSLT31)
  205. return math.deg(-turretYaw),math.deg(-barrelPitch)
  206. end
  207.  
  208. local function findBestPitch(distance, initialVelocity, g, cd, c_est, projectileSpeed)
  209. function calculateRange(angle, u, cd, g, c_est, projectileSpeed)
  210. local radians = math.rad(angle)
  211. local u = projectileSpeed / 20
  212. local part1 = u * math.cos(radians) / math.log(cd)
  213. local part2 = ((g * cd) / (g * cd + (1 - cd) * u * math.sin(radians))) ^ (2 + c_est * projectileSpeed * math.sin(radians)) - 1
  214. local XR = part1 * part2
  215. return XR
  216. end
  217. local bestLowPitch = nil
  218. local bestHighPitch = nil
  219. local bestLowDistance = math.huge
  220. local bestHighDistance = math.huge
  221. local targetDistance = distance
  222.  
  223. for pitch = 0, 30, 0.01 do
  224. local calculatedRange = calculateRange(pitch, initialVelocity, cd, g, c_est, projectileSpeed)
  225. local distanceDifference = math.abs(calculatedRange - targetDistance)
  226.  
  227. if pitch <= 30 then
  228. if distanceDifference < bestLowDistance then
  229. bestLowDistance = distanceDifference
  230. bestLowPitch = pitch
  231. end
  232. elseif pitch > 30 then
  233. if distanceDifference < bestHighDistance then
  234. bestHighDistance = distanceDifference
  235. bestHighPitch = pitch
  236. end
  237. end
  238. end
  239.  
  240. if settings.useHighPitch and bestHighPitch and bestHighDistance < 2 then
  241. return bestHighPitch
  242. else
  243. return bestLowPitch
  244. end
  245. end
  246.  
  247. local function aimCannonDirect(targetPos, source)
  248. local dx = targetPos.x - source.x
  249. local dy = targetPos.y - source.y
  250. local dz = targetPos.z - source.z
  251.  
  252. -- yaw geometric
  253. local yaw = math.deg(math.atan2(-dx, dz))
  254. yaw = (yaw + 180) % 360
  255. --geometric pitch
  256. local horizontalDistance = math.sqrt(dx * dx + dz * dz)
  257. local pitch = math.deg(math.atan2(dy, horizontalDistance))
  258. -- ballistic pitch
  259. local distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  260. local ballisticPitch = findBestPitch(distance, projectileSpeed, g, cd, 0.0028, projectileSpeed)
  261. --print("ballisticPitch: "..ballisticPitch)
  262. if pitch > 60 then
  263. pitch = pitch
  264. else
  265. pitch = pitch + ballisticPitch
  266. end
  267. print("pitch: "..pitch.." yaw: "..yaw)
  268. requiredRelativeYaw, requiredRelativePitch = findRelativeAngle(yaw, pitch)
  269.  
  270. return requiredRelativeYaw, requiredRelativePitch, yaw, pitch
  271. end
  272.  
  273. local function laserRangeFinderMain()
  274. while true do
  275. if enableLaserRangeFinder then
  276. local currentTime = os.clock()
  277.  
  278. if currentTime - lastTriggerTime >= cooldownTime then
  279. if redstone.getInput(redstoneSides.laserRangeFinder) then
  280. local cannonPitch = cannons[1].getPitch()
  281. local shipPos = ship.getWorldspacePosition()
  282. local shipYawDeg = math.deg(getYaw())
  283.  
  284. print("Cannon Pitch: " .. cannonPitch .. ", Yaw: " .. shipYawDeg)
  285.  
  286. if radar then
  287. local targets = radar.scanForShips(2000)
  288.  
  289. local lv = yawPitchToLookVec(shipYawDeg, cannonPitch)
  290. local lvLen = math.sqrt(lv.x * lv.x + lv.y * lv.y + lv.z * lv.z)
  291.  
  292. local rx, ry, rz = shipPos.x + lv.x * 30, shipPos.y + lv.y * 30, shipPos.z + lv.z * 30
  293. print(rx,ry,rz)
  294.  
  295. if lvLen ~= 0 then
  296. local lnx, lny, lnz = lv.x / lvLen, lv.y / lvLen, lv.z / lvLen
  297. local coneCos = math.cos(math.rad(10))
  298.  
  299. local bestScore = -math.huge
  300. local bestDist = nil
  301. local bestTarget = nil
  302.  
  303. for _, target in ipairs(targets) do
  304. if target.pos and target.velocity
  305. and target.pos.x and target.pos.y and target.pos.z
  306. and target.velocity.x and target.velocity.y and target.velocity.z then
  307.  
  308. local dx = target.pos.x - shipPos.x
  309. local dy = target.pos.y - shipPos.y
  310. local dz = target.pos.z - shipPos.z
  311.  
  312. local dist = math.sqrt(dx * dx + dy * dy + dz * dz)
  313.  
  314. if dist > 50 then
  315. local ndx, ndy, ndz = dx / dist, dy / dist, dz / dist
  316. local cosAng = ndx * lnx + ndy * lny + ndz * lnz
  317. --print("Distance > 50")
  318. print(cosAng)
  319. if cosAng >= coneCos then
  320. local vx, vy, vz = target.velocity.x, target.velocity.y, target.velocity.z
  321. local speed = math.sqrt(vx * vx + vy * vy + vz * vz)
  322.  
  323. local centered = (cosAng - coneCos) / (1 - coneCos)
  324. local distScore = 1 / (dist + 1)
  325. local speedScore = (speed > 1) and 1 or 0
  326.  
  327. local score = centered * 3.0 + distScore * 0.5 + speedScore * 1
  328.  
  329. if score > bestScore then
  330. bestScore = score
  331. bestDist = dist
  332. bestTarget = target
  333. end
  334. end
  335. end
  336. end
  337. end
  338.  
  339. if bestTarget then
  340. print("target distance: " .. bestDist)
  341. local requiredRelativeYaw, requiredRelativePitch, yaw, pitch = aimCannonDirect(bestTarget.pos, shipPos)
  342. setPitchYaw(requiredRelativePitch, localCannonYaw)
  343. else
  344. print("No valid target in cone")
  345. end
  346. else
  347. print("Invalid look vector")
  348. end
  349. else
  350. print("No radar detected")
  351. end
  352.  
  353. lastTriggerTime = currentTime
  354. end
  355. end
  356. end
  357. sleep()
  358. end
  359. end
  360.  
  361. --
  362. --Vertical stab
  363. --
  364. lastLoopTime = os.clock()
  365. lastPitch = math.deg(getPitch())
  366. globalPitch = shipPitch + localCannonPitch
  367. local globalYaw, requiredLocalPitch, localCannonYaw
  368. pitchMotor = peripheral.find("Create_RotationSpeedController")
  369. sleep(0.2)
  370.  
  371. local currentTargetPitch = 0 -- Initialize once at the top
  372. local maxPitchStepPerFrame = 1 -- degrees max change per frame
  373.  
  374. local function verticalStabilizerMain()
  375. while true do
  376. if enableVerticalStablizer then
  377. local currentTime = os.clock()
  378. local dt = currentTime - lastLoopTime
  379. if dt < 0.001 then dt = 0.001 end
  380. lastLoopTime = currentTime
  381.  
  382. -- Compute ship pitch angular velocity
  383. local currentPitch = math.deg(getPitch())
  384. local pitchAngularVelocity = (currentPitch - lastPitch) / dt
  385. lastPitch = currentPitch
  386.  
  387. -- User input
  388. local cannonInput = 0
  389. if redstone.getInput(redstoneSides.cannonUpInput) then
  390. cannonInput = redstone.getAnalogInput(redstoneSides.cannonUpInput) * verticalSensitivity
  391. elseif redstone.getInput(redstoneSides.cannonDownInput) then
  392. cannonInput = -redstone.getAnalogInput(redstoneSides.cannonDownInput) * verticalSensitivity
  393. end
  394.  
  395. -- Stabilizer desired correction
  396. local desiredCannonSpeed = -pitchAngularVelocity
  397. local stabilizerOutput = desiredCannonSpeed * 60 / 360 * 8
  398.  
  399. -- Combine
  400. local finalCommand = cannonInput + stabilizerOutput
  401. finalCommand = math.min(math.max(-finalCommand, -256), 256)
  402. pitchMotor.setTargetSpeed(finalCommand)
  403.  
  404. -- Set pitch for accurate but SMOOTH angle
  405. local localCannonYaw, localCannonPitch = cannons[1].getYaw(), cannons[1].getPitch()
  406. if localCannonYaw == 0 then
  407. shipPitch = math.deg(getPitch())
  408. elseif localCannonYaw == 90 then
  409. shipPitch = -math.deg(getRoll())
  410. elseif localCannonYaw == 180 then
  411. shipPitch = -math.deg(getPitch())
  412. elseif localCannonYaw == 270 then
  413. shipPitch = math.deg(getRoll())
  414. else
  415. error("Yaw offseted, cannon process")
  416. end
  417.  
  418. deltaPitch = cannonInput/60*360/8*dt
  419. --print("deltaPitch: "..deltaPitch)
  420. globalPitch = globalPitch + deltaPitch
  421.  
  422. _, requiredLocalPitch = findRelativeAngle(localCannonYaw + math.deg(getYaw()), globalPitch)
  423.  
  424. -- Smooth the setPitchYaw:
  425. local pitchError = requiredLocalPitch - currentTargetPitch
  426.  
  427. -- Wrap pitch error to -180..180
  428. if pitchError > 180 then pitchError = pitchError - 360 end
  429. if pitchError < -180 then pitchError = pitchError + 360 end
  430.  
  431. -- Limit step per frame
  432. local pitchStep = math.max(math.min(pitchError, maxPitchStepPerFrame), -maxPitchStepPerFrame)
  433.  
  434. -- Update target pitch gradually
  435. currentTargetPitch = currentTargetPitch + pitchStep
  436.  
  437. -- Finally set it
  438. --setPitchYaw(currentTargetPitch, localCannonYaw)
  439.  
  440. -- Debug print
  441. --print(string.format("PitchVel=%.2f | UserInput=%.2f | StabilizerOut=%.2f | Final=%.2f | currentTargetPitch=%.2f",
  442. -- pitchAngularVelocity, cannonInput, stabilizerOutput, finalCommand, currentTargetPitch))
  443. end
  444.  
  445. sleep()
  446. end
  447. end
  448.  
  449. local function PIDController(Kp, Ki, Kd, error, integral, prevError, dt)
  450. -- Calculate the proportional, integral, and derivative components
  451. local proportional = Kp * error
  452. integral = integral + error * dt
  453. derivative = (error - prevError) / dt
  454.  
  455. -- Calculate output
  456. local output = proportional + (Ki * integral) + (Kd * derivative)
  457.  
  458. -- Return the PID output and updated integral and previous error
  459. return output, integral, error
  460. end
  461.  
  462. parallel.waitForAny(
  463. laserRangeFinderMain,
  464. verticalStabilizerMain
  465. )
Advertisement
Add Comment
Please, Sign In to add comment