MegiRicky

SHARD_Gen1

Jan 23rd, 2026
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 40.77 KB | None | 0 0
  1. local radar = peripheral.find("sp_radar")
  2. local modem = peripheral.find("modem")
  3.  
  4. local friendlyIDs
  5. local friendlyIDFile = "friendly_ids.txt"
  6. local scanInterval = 0.01
  7.  
  8. local mode = "auto" --Auto targeting mode, target the cloeset target
  9. local redstoneTimeout = 30
  10. local cycleIndex = 1
  11. local lastRedstoneInputTime = os.clock()
  12.  
  13. local yawErrorSum = 0
  14. local lastYawError = 0
  15. local pitchErrorSum = 0
  16. local lastPitchError = 0
  17. local yawError = 0
  18. local yawIntegral = 0
  19. local yawPrevError = 0
  20. local pitchError = 0
  21. local pitchIntegral = 0
  22. local pitchPrevError = 0
  23. local lastTime = os.clock()
  24.  
  25. local Kp_yaw = 7
  26. local Ki_yaw = 0
  27. local Kd_yaw = 0.05
  28. local Kp_pitch = 0.5
  29. local Ki_pitch = 0
  30. local Kd_pitch = 0.01
  31. local dt = 0.1
  32. local dt1,dt2
  33. local accelerationFactor = 0.2
  34. local velocityFactor = 1
  35.  
  36. local spreadYawRange = 1 -- Max spread angle for yaw (in degrees)
  37. local spreadPitchRange = 1 -- Max spread angle for pitch (in degrees)
  38.  
  39. local controls = {}
  40.  
  41. local cannon = peripheral.find("cbc_cannon_mount")
  42. if not(cannon) then
  43. cannon = peripheral.find("cbcmf_compact_cannon_mount")
  44. end
  45.  
  46. print("press enter to assemble cannons")
  47. cannon.assemble()
  48.  
  49. local function readFriendlyIDs(filename)
  50. if not fs.exists(filename) then
  51. print("Friendly IDs file '" .. filename .. "' does not exist. Creating it.")
  52. local file = fs.open(filename, "w")
  53. print("Input friendly IDs (player names) separated by commas:")
  54. local ids = io.read()
  55. file.write(ids)
  56. file.close()
  57. else
  58. print("Do you want to edit the friendly player id config? (yes/no),press enter to skip")
  59. local editChoice = io.read()
  60. if editChoice == "" then
  61. editChoice = "no"
  62. end
  63. if editChoice:lower() == "yes" then
  64. if fs.exists(filename) then
  65. fs.delete(filename)
  66. print("Friendly IDs file '" .. filename .. "' does not exist. Creating it.")
  67. local file = fs.open(filename, "w")
  68. print("Input friendly IDs (player names) separated by commas:")
  69. local ids = io.read()
  70. file.write(ids)
  71. file.close()
  72. end
  73. end
  74. end
  75.  
  76. local file = fs.open(filename, "r")
  77. local friendlyIDs = {}
  78. if file then
  79. local line = file.readLine()
  80. while line do
  81. print("Line read: " .. line) -- Debug print for the line
  82.  
  83. -- Split the line by commas and insert each name into the friendlyIDs table
  84. for name in string.gmatch(line, '([^,]+)') do
  85. print("Friendly ID (Name): " .. name) -- Debug print for each name
  86. table.insert(friendlyIDs, name) -- Store the player name
  87. end
  88. line = file.readLine() -- Read the next line
  89. end
  90. file.close()
  91. end
  92. return friendlyIDs
  93. end
  94.  
  95. -- Function to check if a player ID is friendly
  96. local function isFriendly(playerID)
  97. for _, friendlyID in ipairs(friendlyIDs) do
  98. if playerID == friendlyID then
  99. return true
  100. end
  101. end
  102. return false
  103. end
  104.  
  105. -- Read friendly IDs from the file
  106. local function saveSettingsToFile(filename, settings)
  107. local file = fs.open(filename, "w")
  108. if file then
  109. file.write(textutils.serialize(settings))
  110. file.close()
  111. print("Settings saved to '" .. filename .. "'")
  112. else
  113. print("Failed to save settings.")
  114. end
  115. end
  116.  
  117. local function loadSettingsFromFile(filename)
  118. if not fs.exists(filename) then
  119. return nil
  120. end
  121.  
  122. local file = fs.open(filename, "r")
  123. local settings = textutils.unserialize(file.readAll())
  124. file.close()
  125. return settings
  126. end
  127.  
  128. local function askForInput(prompt, defaultValue)
  129. print(prompt .. " (default: " .. defaultValue .. "):")
  130. local input = io.read()
  131. if input == "" then
  132. return defaultValue
  133. else
  134. return tonumber(input) or input
  135. end
  136. end
  137.  
  138. local function createSettings()
  139. local settings = {}
  140. settings.auto = askForInput("Enable auto fire, yes/no note that you need redstone input to anyside of the computer (safetly measure)", "yes") == "yes"
  141. --settings.velocityFactor = askForInput("Input the velocityFactor", 1)
  142. settings.controlChannel = askForInput("Input the control channel",500)
  143. settings.projectileSpeed = askForInput("Input the muzzle velocity number", 160)
  144. settings.g = askForInput("Input the gravity acceleration per tick", 0.025)
  145. settings.cd = askForInput("Input the drag per tick", 0.99)
  146. settings.autoSpread = askForInput("Enable automatic spread, yes/no", "yes") == "yes"
  147. settings.lengthCorrection = askForInput("Enter cannon source ship length correction", 35)
  148. settings.heightCorrection = askForInput("Enter cannon source ship height correction", 5)
  149. settings.widthCorrection = askForInput("Enter the cannon source ship width correction, positive if the ship is at the right side",0)
  150. settings.limitor = askForInput("Enable pitch yaw limiter, yes/no", "yes") == "yes"
  151. settings.pitchLowerLimit = askForInput("Ignore the follwing if no limitr. Input the pitch lower limit, default: -10",-10)
  152. settings.pitchUpperLimit = askForInput("Input the pitch lower limit, default: 90",90)
  153. settings.yawLowerLimit = askForInput("Input the yaw lower limit, default: -120",-120)
  154. settings.yawUpperLimit = askForInput("Input the pitch lower limit, default: 120",120)
  155.  
  156. return settings
  157. end
  158.  
  159. local function createPresetSettings()
  160. local presets = {
  161. {
  162. filename = "ussNJport1CIWS_settings.txt",
  163. settings = {
  164. controlsChannel = 500,
  165. velocityFactor = 1,
  166. projectileSpeed = 160,
  167. g = 0.005,
  168. cd = 0.999999,
  169. autoSpread = true,
  170. lengthCorrection = 17,
  171. heightCorrection = 24,
  172. widthCorrection = -7,
  173. limitor = true,
  174. pitchLowerLimit = -10,
  175. pitchUpperLimit = 90,
  176. yawLowerLimit = -150,
  177. yawUpperLimit = 0,
  178. auto = true
  179. }
  180. },
  181. {
  182. filename = "ussNJstarboard1CIWS_settings.txt",
  183. settings = {
  184. controlsChannel = 500,
  185. velocityFactor = 1,
  186. projectileSpeed = 160,
  187. g = 0.005,
  188. cd = 0.999999,
  189. autoSpread = true,
  190. lengthCorrection = 17,
  191. heightCorrection = 24,
  192. widthCorrection = 7,
  193. limitor = true,
  194. pitchLowerLimit = -10,
  195. pitchUpperLimit = 90,
  196. yawLowerLimit = 0,
  197. yawUpperLimit = 150,
  198. auto = true
  199. }
  200. },
  201. {
  202. filename = "ussNJport2CIWS_settings.txt",
  203. settings = {
  204. controlsChannel = 500,
  205. velocityFactor = 1,
  206. projectileSpeed = 160,
  207. g = 0.005,
  208. cd = 0.999999,
  209. autoSpread = true,
  210. lengthCorrection = -14,
  211. heightCorrection = 21,
  212. widthCorrection = -6,
  213. limitor = true,
  214. pitchLowerLimit = -10,
  215. pitchUpperLimit = 90,
  216. yawLowerLimit = -180,
  217. yawUpperLimit = -20,
  218. auto = true
  219. }
  220. },
  221. {
  222. filename = "ussNJstarboard2CIWS_settings.txt",
  223. settings = {
  224. controlsChannel = 500,
  225. velocityFactor = 1,
  226. projectileSpeed = 160,
  227. g = 0.005,
  228. cd = 0.999999,
  229. autoSpread = true,
  230. lengthCorrection = -14,
  231. heightCorrection = 21,
  232. widthCorrection = 6,
  233. limitor = true,
  234. pitchLowerLimit = -10,
  235. pitchUpperLimit = 90,
  236. yawLowerLimit = 0,
  237. yawUpperLimit = 200,
  238. auto = true
  239. }
  240. },
  241. {
  242. filename = "type55BowCIWS_settings.txt",
  243. settings = {
  244. controlsChannel = 500,
  245. velocityFactor = 1,
  246. projectileSpeed = 200,
  247. g = 0.005,
  248. cd = 0.999999,
  249. autoSpread = true,
  250. lengthCorrection = 34,
  251. heightCorrection = 9,
  252. widthCorrection = 0,
  253. pitchLowerLimit = -10,
  254. pitchUpperLimit = 90,
  255. yawLowerLimit = -120,
  256. yawUpperLimit = 120,
  257. limitor = true,
  258. auto = true
  259. }
  260. },
  261. {
  262. filename = "type55port1_settings.txt",
  263. settings = {
  264. controlsChannel = 500,
  265. velocityFactor = 1,
  266. projectileSpeed = 200,
  267. g = 0.005,
  268. cd = 0.999999,
  269. autoSpread = true,
  270. lengthCorrection = -42,
  271. heightCorrection = 12,
  272. widthCorrection = -8,
  273. pitchLowerLimit = -20,
  274. pitchUpperLimit = 90,
  275. yawLowerLimit = -160,
  276. yawUpperLimit = -20,
  277. limitor = true,
  278. auto = true
  279. }
  280. },
  281. {
  282. filename = "type55port2_settings.txt",
  283. settings = {
  284. controlsChannel = 500,
  285. velocityFactor = 1,
  286. projectileSpeed = 200,
  287. g = 0.005,
  288. cd = 0.999999,
  289. autoSpread = true,
  290. lengthCorrection = -52,
  291. heightCorrection = 12,
  292. widthCorrection = -8,
  293. pitchLowerLimit = -20,
  294. pitchUpperLimit = 90,
  295. yawLowerLimit = -200,
  296. yawUpperLimit = -20,
  297. limitor = true,
  298. auto = true
  299. }
  300. },
  301. {
  302. filename = "type55starboard1_settings.txt",
  303. settings = {
  304. controlsChannel = 500,
  305. velocityFactor = 1,
  306. projectileSpeed = 200,
  307. g = 0.005,
  308. cd = 0.999999,
  309. autoSpread = true,
  310. lengthCorrection = -42,
  311. heightCorrection = 12,
  312. widthCorrection = 8,
  313. pitchLowerLimit = -20,
  314. pitchUpperLimit = 90,
  315. yawLowerLimit = 20,
  316. yawUpperLimit = 160,
  317. limitor = true,
  318. auto = true
  319. }
  320. },
  321. {
  322. filename = "type55starboard2_settings.txt",
  323. settings = {
  324. controlsChannel = 500,
  325. velocityFactor = 1,
  326. projectileSpeed = 200,
  327. g = 0.005,
  328. cd = 0.999999,
  329. autoSpread = true,
  330. lengthCorrection = -52,
  331. heightCorrection = 12,
  332. widthCorrection = 8,
  333. pitchLowerLimit = -20,
  334. pitchUpperLimit = 90,
  335. yawLowerLimit = 20,
  336. yawUpperLimit = 160,
  337. limitor = true,
  338. auto = true
  339. }
  340. },
  341. {
  342. filename = "TuoCChiangCIWS_settings.txt",
  343. settings = {
  344. controlsChannel = 500,
  345. velocityFactor = 1,
  346. projectileSpeed = 120,
  347. g = 0.005,
  348. cd = 0.999999,
  349. autoSpread = true,
  350. lengthCorrection = -10,
  351. heightCorrection = 7,
  352. widthCorrection = 0,
  353. pitchLowerLimit = -20,
  354. pitchUpperLimit = 90,
  355. yawLowerLimit = 60,
  356. yawUpperLimit = 300,
  357. limitor = false,
  358. auto = true
  359. }
  360. },
  361. {
  362. filename = "ZTZ99CIWS_settings.txt",
  363. settings = {
  364. controlsChannel = 500,
  365. velocityFactor = 1,
  366. projectileSpeed = 160,
  367. g = 0.005,
  368. cd = 0.999999,
  369. autoSpread = true,
  370. lengthCorrection = -1,
  371. heightCorrection = 1.5,
  372. widthCorrection = 1,
  373. limitor = true,
  374. pitchLowerLimit = -12,
  375. pitchUpperLimit = 90,
  376. yawLowerLimit = -360,
  377. yawUpperLimit = 360,
  378. auto = true
  379. }
  380. },
  381. {
  382. filename = "YunBao_settings.txt",
  383. settings = {
  384. controlsChannel = 500,
  385. velocityFactor = 1,
  386. projectileSpeed = 160,
  387. g = 0.005,
  388. cd = 0.999999,
  389. autoSpread = true,
  390. lengthCorrection = 0,
  391. heightCorrection = 1.2,
  392. widthCorrection = 1,
  393. limitor = true,
  394. pitchLowerLimit = -8,
  395. pitchUpperLimit = 90,
  396. yawLowerLimit = -360,
  397. yawUpperLimit = 360,
  398. auto = true
  399. }
  400. },
  401. {
  402. filename = "EMBTCIWS_settings.txt",
  403. settings = {
  404. controlsChannel = 2000,
  405. velocityFactor = 1,
  406. projectileSpeed = 160,
  407. g = 0.005,
  408. cd = 0.999999,
  409. autoSpread = true,
  410. lengthCorrection = -0.5,
  411. heightCorrection = 1.5,
  412. widthCorrection = 1,
  413. limitor = true,
  414. pitchLowerLimit = -12,
  415. pitchUpperLimit = 90,
  416. yawLowerLimit = -360,
  417. yawUpperLimit = 360,
  418. auto = true
  419. }
  420. },
  421. {
  422. filename = "CIWStruck_settings.txt",
  423. settings = {
  424. controlsChannel = 500,
  425. velocityFactor = 1,
  426. projectileSpeed = 160,
  427. g = 0.005,
  428. cd = 0.999999,
  429. autoSpread = false,
  430. lengthCorrection = 0,
  431. heightCorrection = 0,
  432. widthCorrection = 0,
  433. limitor = true,
  434. auto = false
  435. }
  436. }
  437. }
  438.  
  439. for _, preset in ipairs(presets) do
  440. if true then
  441. saveSettingsToFile(preset.filename, preset.settings)
  442. print("Created preset settings: " .. preset.filename)
  443. end
  444. end
  445. end
  446.  
  447. local function handleSettings()
  448. print("Checking for existing settings...")
  449. createPresetSettings()
  450.  
  451. -- List available settings
  452. local settingsFiles = fs.list("/")
  453. local settingsFilesFound = false
  454. local settingsFilesList = {}
  455.  
  456. for _, file in ipairs(settingsFiles) do
  457. if string.match(file, "_settings.txt") then
  458. table.insert(settingsFilesList, file)
  459. settingsFilesFound = true
  460. end
  461. end
  462.  
  463. if not settingsFilesFound then
  464. print("No settings found. Please create a new one.")
  465. local filename = askForInput("Enter a name for the new settings file", "example_settings.txt")
  466. local settings = createSettings()
  467. saveSettingsToFile(filename, settings)
  468. return settings
  469. else
  470. print("Available settings:")
  471.  
  472. local pageSize = 10 -- Number of settings to display per page
  473. local totalFiles = #settingsFilesList
  474. local currentPage = 1
  475. local totalPages = math.ceil(totalFiles / pageSize)
  476.  
  477. while currentPage <= totalPages do
  478. local startIdx = (currentPage - 1) * pageSize + 1
  479. local endIdx = math.min(startIdx + pageSize - 1, totalFiles)
  480.  
  481. -- Display a batch of settings files
  482. for i = startIdx, endIdx do
  483. print(i .. ". " .. settingsFilesList[i])
  484. end
  485.  
  486. if currentPage < totalPages then
  487. print("\nPress Enter to see more settings...")
  488. io.read() -- Wait for the user to press Enter
  489. end
  490.  
  491. currentPage = currentPage + 1
  492. end
  493.  
  494. local selection = askForInput("Select an existing setting to load or create a new one (1-" .. totalFiles .. " or new)", "new")
  495.  
  496. if selection == "new" then
  497. local filename = askForInput("Enter a name for the new settings file", "settings.txt")
  498. local settings = createSettings()
  499. saveSettingsToFile(filename, settings)
  500. return settings
  501. else
  502. local filename = settingsFilesList[tonumber(selection)]
  503. local settings = loadSettingsFromFile(filename)
  504. print("Loaded settings from '" .. filename .. "'")
  505.  
  506. local editChoice = askForInput("Do you want to edit this setting? (yes/no)", "no")
  507. if editChoice == "yes" then
  508. local newSettings = createSettings()
  509. saveSettingsToFile(filename, newSettings)
  510. return newSettings
  511. else
  512. return settings
  513. end
  514. end
  515. end
  516. end
  517.  
  518. -- Normalize a vector
  519. local function normalizeVector(v)
  520. local length = math.sqrt(v[1]^2 + v[2]^2 + v[3]^2)
  521. if length == 0 then
  522. return {0, 0, 0}
  523. end
  524. return {v[1] / length, v[2] / length, v[3] / length}
  525. end
  526.  
  527. -- Normalize the rotation matrix
  528. local function normalizeRotationMatrix(rotMatrix)
  529. local normalizedMatrix = {}
  530. for i = 1, #rotMatrix do
  531. normalizedMatrix[i] = normalizeVector(rotMatrix[i])
  532. end
  533. return normalizedMatrix
  534. end
  535.  
  536. -- Get the pitch of the ship
  537. local function getPitch()
  538. local rotMatrix = ship.getTransformationMatrix()
  539. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  540. return math.asin(normalizedMatrix[2][3]) -- Extract pitch from the matrix
  541. end
  542. --pitch = math.deg(math.asin(ship.getTransformationMatrix()[2][3]))
  543. -- Get the yaw of the ship
  544. local function getYaw()
  545. local rotMatrix = ship.getTransformationMatrix()
  546. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  547. return math.atan2(-normalizedMatrix[3][1], -normalizedMatrix[3][3]) -- Extract yaw from the matrix
  548. end
  549.  
  550. -- Get the roll of the ship
  551. local function getRoll()
  552. local rotMatrix = ship.getTransformationMatrix()
  553. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  554. return math.atan2(normalizedMatrix[2][1], normalizedMatrix[2][2]) -- Extract roll from the matrix
  555. end
  556.  
  557. -- Main execution
  558. local settings = handleSettings()
  559.  
  560. -- Use the settings in your code
  561. print("Using settings:")
  562. print(textutils.serialize(settings))
  563. velocityFactor = 1
  564. g = tonumber(settings.g)
  565. lengthCorrection = tonumber(settings.lengthCorrection)
  566. heightCorrection = tonumber(settings.heightCorrection)
  567. widthCorrection = tonumber(settings.widthCorrection)
  568. cd = tonumber(settings.cd)
  569. projectileSpeed = tonumber(settings.projectileSpeed)
  570. auto = settings.auto
  571. limitor = settings.limitor
  572. autoSpread = settings.autoSpread
  573.  
  574. if modem then
  575. modem.open(settings.controlsChannel)
  576. end
  577.  
  578. friendlyIDs = readFriendlyIDs(friendlyIDFile)
  579. print("Friendly IDs: " .. textutils.serialize(friendlyIDs)) -- Debug print
  580.  
  581. if cannon.assemble() then
  582. print("asseble failed, press enter to contiue")
  583. io.read()
  584. end
  585.  
  586. local function PIDController(Kp, Ki, Kd, error, integral, prevError, dt)
  587. -- Calculate the proportional, integral, and derivative components
  588. local proportional = Kp * error
  589. integral = integral + error * dt -- Accumulate the error for the integral term
  590. local derivative = (error - prevError) / dt
  591.  
  592. -- Calculate the PID output
  593. local output = proportional + (Ki * integral) + (Kd * derivative)
  594.  
  595. -- Return the PID output, updated integral, and current error
  596. return output, integral, error
  597. end
  598.  
  599. local function calculateVelocity(pos1, pos2, dt)
  600. local vx = (pos2[1] - pos1[1]) / dt
  601. local vy = (pos2[2] - pos1[2]) / dt
  602. local vz = (pos2[3] - pos1[3]) / dt
  603. return {x=vx, y=0, z=vz}
  604. end
  605.  
  606. local function calculateAcceleration(vel1, vel2, dt)
  607. local ax = (vel2.x - vel1.x) / dt
  608. local ay = (vel2.y - vel1.y) / dt
  609. local az = (vel2.z - vel1.z) / dt
  610. return {x = ax, y = ay, z = az}
  611. end
  612.  
  613. local function estimatePosition(pos, velocity, acceleration, time)
  614. local shipVelocity = ship.getVelocity()
  615. local estX = pos.x + (velocity.x - shipVelocity.x) * velocityFactor * time + 0.5 * acceleration.x * time^2
  616. local estY = pos.y + (velocity.y - shipVelocity.y) * velocityFactor * time + 0.5 * acceleration.y * time^2
  617. local estZ = pos.z + (velocity.z - shipVelocity.z) * velocityFactor * time + 0.5 * acceleration.z * time^2
  618. return {x = estX, y = estY, z = estZ}
  619. end
  620.  
  621. local function findRelativeAngle(targetYaw,targetPitch)
  622. rot = ship.getQuaternion()
  623. cacheYaw = math.pi - math.rad(targetYaw)
  624. cachePitch = - math.rad(targetPitch)
  625. rotMatAdj11 = 1 - 2*(rot.x^2 + rot.y^2)
  626. rotMatAdj12 = 2*(rot.z * rot.x + rot.y * rot.w)
  627. rotMatAdj13 = 2*(rot.z * rot.y - rot.x * rot.w)
  628. rotMatAdj21 = 2*(rot.z * rot.x - rot.y * rot.w)
  629. rotMatAdj22 = 1 - 2*(rot.z^2 + rot.y^2)
  630. rotMatAdj23 = 2*(rot.x * rot.y + rot.z * rot.w)
  631. rotMatAdj31 = 2*(rot.z * rot.y + rot.x * rot.w)
  632. rotMatAdj32 = 2*(rot.x * rot.y - rot.z * rot.w)
  633. rotMatAdj33 = 1 - 2*(rot.z^2 + rot.x^2)
  634.  
  635. rotMatTGT11 = math.cos(cacheYaw) * math.cos(cachePitch)
  636. rotMatTGT21 = math.sin(cacheYaw) * math.cos(cachePitch)
  637. rotMatTGT31 = - math.sin(cachePitch)
  638.  
  639. rotMatRSLT11 = rotMatAdj11 * rotMatTGT11 + rotMatAdj12 * rotMatTGT21 + rotMatAdj13 * rotMatTGT31
  640. rotMatRSLT21 = rotMatAdj21 * rotMatTGT11 + rotMatAdj22 * rotMatTGT21 + rotMatAdj23 * rotMatTGT31
  641. rotMatRSLT31 = rotMatAdj31 * rotMatTGT11 + rotMatAdj32 * rotMatTGT21 + rotMatAdj33 * rotMatTGT31
  642.  
  643. turretYaw = math.atan2(rotMatRSLT21, rotMatRSLT11)
  644. barrelPitch = math.asin(-rotMatRSLT31)
  645. return math.deg(-turretYaw),math.deg(-barrelPitch)
  646. end
  647.  
  648. local function calculateRange(angle, u, cd, g, c_est, projectileSpeed)
  649. local radians = math.rad(angle)
  650. local u = projectileSpeed/20
  651. local part1 = u * math.cos(radians) / math.log(cd)
  652. local part2 = ((g * cd) / (g * cd + (1 - cd) * u * math.sin(radians))) ^ (2 + c_est * projectileSpeed * math.sin(radians)) - 1
  653. local XR = part1 * part2
  654.  
  655. return XR
  656. end
  657.  
  658. local function findBestPitch(targetX, targetY, targetZ, sourceX, sourceY, sourceZ, initialVelocity, g, cd, c_est, projectileSpeed)
  659. local bestLowPitch = nil
  660. local bestHighPitch = nil
  661. local bestLowDistance = math.huge
  662. local bestHighDistance = math.huge
  663. local targetDistance = math.sqrt((targetX - sourceX)^2 + (targetZ - sourceZ)^2)
  664.  
  665. for pitch = 0, 90, 0.1 do -- Iterate over pitch angles
  666. local calculatedRange = calculateRange(pitch, initialVelocity, cd, g, c_est, projectileSpeed)
  667. local distanceDifference = math.abs(calculatedRange - targetDistance)
  668.  
  669. -- Find the low-angle solution
  670. if pitch <= 30 then
  671. if distanceDifference < bestLowDistance then
  672. bestLowDistance = distanceDifference
  673. bestLowPitch = pitch
  674. end
  675. -- Find the high-angle solution
  676. elseif pitch > 30 then
  677. if distanceDifference < bestHighDistance then
  678. bestHighDistance = distanceDifference
  679. bestHighPitch = pitch
  680. end
  681. end
  682. end
  683.  
  684. -- If the target is within 400 blocks, prioritize the low-angle solution
  685. return bestLowPitch
  686. end
  687.  
  688. local function applySpread(targetYaw, targetPitch, distance)
  689. -- Avoid division by zero
  690. if distance < 1 then distance = 1 end
  691.  
  692. -- Adjust angle spread inversely with distance (constant spatial spread)
  693. -- Example: spreadAngle = atan(spreadSize / distance)
  694. -- Let’s assume a constant spread size of 1 block/metre
  695. local spatialSpreadSize = 1 -- change as needed
  696. local effectiveYawSpread = math.deg(math.atan(spatialSpreadSize / distance)) * spreadYawRange
  697. local effectivePitchSpread = math.deg(math.atan(spatialSpreadSize / distance)) * spreadPitchRange
  698.  
  699. -- Apply the adjusted spread
  700. local yawSpread = (math.random() * 2 - 1) * effectiveYawSpread
  701. local pitchSpread = (math.random() * 2 - 1) * effectivePitchSpread
  702.  
  703. local newYaw = targetYaw + yawSpread
  704. local newPitch = targetPitch + pitchSpread
  705.  
  706. return newYaw, newPitch
  707. end
  708.  
  709. local lastTargetPos, lastTargetVelocity, predictedTargetVelocity, predictedTargetAcceleration
  710. local lastTargetAqquireTime = os.clock()
  711.  
  712. local function predictFuturePosition(targetPos, targetVel, sourceX, sourceY, sourceZ)
  713. local currentTime = os.clock()
  714. local dt = currentTime - lastTargetAqquireTime
  715.  
  716. -- Initialize predictedVelocity & predictedAcceleration if needed
  717. if not lastTargetPos then
  718. lastTargetPos = targetPos
  719. lastTargetVelocity = targetVel
  720. predictedTargetVelocity = targetVel
  721. predictedTargetAcceleration = {x = 0, y = 0, z = 0}
  722. lastTargetAqquireTime = currentTime
  723. elseif dt >= 0.5 then
  724. -- Estimate velocity
  725. predictedTargetVelocity = {
  726. x = (targetPos.x - lastTargetPos.x) / dt,
  727. y = (targetPos.y - lastTargetPos.y) / dt,
  728. z = (targetPos.z - lastTargetPos.z) / dt
  729. }
  730.  
  731. -- Estimate acceleration
  732. predictedTargetAcceleration = {
  733. x = (predictedTargetVelocity.x - lastTargetVelocity.x) / dt,
  734. y = (predictedTargetVelocity.y - lastTargetVelocity.y) / dt,
  735. z = (predictedTargetVelocity.z - lastTargetVelocity.z) / dt
  736. }
  737.  
  738. -- Update previous values
  739. lastTargetPos = targetPos
  740. lastTargetVelocity = predictedTargetVelocity
  741. lastTargetAqquireTime = currentTime
  742. end
  743.  
  744. -- Compute initial distance to target
  745. local dx = targetPos.x - sourceX
  746. local dy = targetPos.y - sourceY
  747. local dz = targetPos.z - sourceZ
  748. local distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  749.  
  750. local losLength = math.sqrt(dx^2 + dy^2 + dz^2)
  751. local losUnit = {
  752. x = dx / losLength,
  753. y = dy / losLength,
  754. z = dz / losLength
  755. }
  756.  
  757. -- Compute rate of escape using dot product
  758. local rateOfEscape = predictedTargetVelocity.x * losUnit.x + predictedTargetVelocity.y * losUnit.y + predictedTargetVelocity.z * losUnit.z
  759. rateOfClosure = projectileSpeed - rateOfEscape
  760.  
  761. -- Get ship's velocity
  762. local shipVelocity = ship.getVelocity()
  763.  
  764. -- Initial estimate for travel time
  765. local estimateTime = distance / rateOfClosure + 0.5
  766.  
  767. -- Predict future position using velocity and acceleration
  768. local estimateX = targetPos.x
  769. + (predictedTargetVelocity.x * velocityFactor - shipVelocity.x) * estimateTime
  770. + 0.5 * predictedTargetAcceleration.x * estimateTime * estimateTime
  771.  
  772. local estimateY = targetPos.y
  773. + (predictedTargetVelocity.y * velocityFactor - shipVelocity.y) * estimateTime
  774. + 0.5 * predictedTargetAcceleration.y * estimateTime * estimateTime
  775.  
  776. local estimateZ = targetPos.z
  777. + (predictedTargetVelocity.z * velocityFactor - shipVelocity.z) * estimateTime
  778. + 0.5 * predictedTargetAcceleration.z * estimateTime * estimateTime
  779.  
  780. -- Recalculate distance after initial estimate
  781. dx = estimateX - sourceX
  782. dy = estimateY - sourceY
  783. dz = estimateZ - sourceZ
  784. distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  785.  
  786. -- Refine estimateTime
  787. estimateTime = distance / rateOfClosure + 0.5
  788.  
  789. -- Recompute future position with refined time
  790. estimateX = targetPos.x
  791. + (predictedTargetVelocity.x * velocityFactor - shipVelocity.x) * estimateTime
  792. + 0.5 * predictedTargetAcceleration.x * estimateTime * estimateTime
  793.  
  794. estimateY = targetPos.y
  795. + (predictedTargetVelocity.y * velocityFactor - shipVelocity.y) * estimateTime
  796. + 0.5 * predictedTargetAcceleration.y * estimateTime * estimateTime
  797.  
  798. estimateZ = targetPos.z
  799. + (predictedTargetVelocity.z * velocityFactor - shipVelocity.z) * estimateTime
  800. + 0.5 * predictedTargetAcceleration.z * estimateTime * estimateTime
  801.  
  802. return {x = estimateX, y = estimateY, z = estimateZ}
  803. end
  804.  
  805.  
  806. local requiredRelativePitch,requiredRelativeYaw = 0,0
  807. local function aimCannon(targetPos, targetVel, targetAcc, sourceX, sourceY, sourceZ)
  808. if sourceX and sourceY and sourceZ then
  809. local futurePos = predictFuturePosition(targetPos, targetVel, sourceX, sourceY, sourceZ)
  810. --print(textutils.serialize(futurePos))
  811. -- Calculate the new dx, dy, dz for the predicted future position
  812. dx = futurePos.x - sourceX
  813. dy = futurePos.y - sourceY
  814. dz = futurePos.z - sourceZ
  815.  
  816. local distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  817. local horizontalDistance = math.sqrt(dx * dx + dz * dz)
  818. local pitch = math.deg(math.atan2(dy, horizontalDistance))
  819.  
  820. local yaw = math.deg(math.atan2(-dx, dz))
  821. yaw = (yaw + 180) % 360
  822.  
  823. --Adjust pitch based on distance adjustments
  824. print(projectileSpeed,g,cd,sourceX,pitch)
  825. pitch = pitch + findBestPitch(futurePos.x, futurePos.y, futurePos.z, sourceX, sourceY, sourceZ, projectileSpeed, g, cd, 0.0028, projectileSpeed)
  826. local shipYaw = math.deg(getYaw())
  827. if shipYaw < 0 then shipYaw = shipYaw + 360 end
  828.  
  829. requiredRelativeYaw = yaw - shipYaw
  830. if requiredRelativeYaw > 180 then
  831. requiredRelativeYaw = requiredRelativeYaw - 360
  832. elseif requiredRelativeYaw < -180 then
  833. requiredRelativeYaw = requiredRelativeYaw + 360
  834. end
  835.  
  836. yaw, pitch = applySpread(yaw, pitch, distance)
  837.  
  838. requiredRelativeYaw,requiredRelativePitch = findRelativeAngle(yaw,pitch)
  839. locked = true
  840. if limitor then
  841. if requiredRelativeYaw < settings.yawLowerLimit then
  842. requiredRelativeYaw = settings.yawLowerLimit
  843. locked = false
  844. elseif requiredRelativeYaw > settings.yawUpperLimit then
  845. requiredRelativeYaw = settings.yawUpperLimit
  846. locked = false
  847. end
  848. if requiredRelativePitch < settings.pitchLowerLimit then
  849. requiredRelativePitch = settings.pitchLowerLimit
  850. locked = false
  851. elseif requiredRelativePitch > settings.pitchUpperLimit then
  852. requiredRelativePitch = settings.pitchUpperLimit
  853. locked = false
  854. end
  855. end
  856.  
  857. end
  858. end
  859.  
  860. local function setPitchYaw()
  861. while true do
  862. if requiredRelativeYaw and requiredRelativePitch then
  863. --print("setting angle yaw: "..requiredRelativeYaw.." pitch: "..requiredRelativePitch)
  864. cannon.setPitch(requiredRelativePitch)
  865. cannon.setYaw(requiredRelativeYaw)
  866. end
  867. sleep()
  868. end
  869. end
  870.  
  871. local function calculateSpeed(velocity)
  872. return math.sqrt(velocity.x^2 + velocity.y^2 + velocity.z^2)
  873. end
  874.  
  875. local function calculateAcceleration(vel1, vel2, dt)
  876. local ax = (vel2.x - vel1.x) / dt * accelerationFactor
  877. local ay = (vel2.y - vel1.y) / dt * accelerationFactor
  878. local az = (vel2.z - vel1.z) / dt * accelerationFactor
  879. return {x = ax, y = ay, z = az}
  880. end
  881.  
  882. local function estimatePosition(pos, velocity, acceleration, time)
  883. local estX = pos.x + velocity.x * velocityFactor * time + 0.5 * acceleration.x * time^2
  884. local estY = pos.y + velocity.y * velocityFactor * time + 0.5 * acceleration.y * time^2
  885. local estZ = pos.z + velocity.z * velocityFactor * time + 0.5 * acceleration.z * time^2
  886. return {x = estX, y = estY, z = estZ}
  887. end
  888.  
  889. local function updateMode()
  890. if redstone.getInput("top") or (controls and controls.targetSwitch) then
  891. lastRedstoneInputTime = os.clock()
  892. mode = "cycle"
  893. elseif os.clock() - lastRedstoneInputTime > redstoneTimeout then
  894. mode = "auto"
  895. end
  896. end
  897.  
  898. -- Function to get the closest target (players or ships)
  899. local function getClosestTarget()
  900. local targetScan1 = radar.scanForPlayers(400)
  901. local shipScan1 = radar.scanForShips(400) -- Scan for ships (e.g., missiles) within 1000 units
  902.  
  903. -- Variables to hold the closest target data
  904. local closestTarget = nil
  905. local closestDistance = math.huge
  906. local targetPos1 = nil
  907. local targetInfo = nil
  908. local targets = {}
  909. local highestSpeed = 0
  910.  
  911. for _, player in pairs(targetScan1) do
  912. if player and player.pos then
  913. local dx = player.pos[1] - shipPos.x
  914. local dy = player.pos[2] - shipPos.y
  915. local dz = player.pos[3] - shipPos.z
  916. local distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  917.  
  918. -- If this player is closer than the current closest, update the closest target
  919. if not isFriendly(player.nickname) then
  920. closestDistance = distance
  921. targetPos1 = player.pos
  922.  
  923. table.insert(targets, {type = "player", pos = player.pos, distance = distance, nickname = player.nickname})
  924. end
  925. end
  926. end
  927.  
  928. -- Loop through each ship detected in the first ship scan
  929. local closestDistance = math.huge
  930. for _, ship in pairs(shipScan1) do
  931. if ship and ship.pos then
  932. local dx = ship.pos.x - shipPos.x
  933. local dy = ship.pos.y - shipPos.y
  934. local dz = ship.pos.z - shipPos.z
  935. local CIWSdistance = math.sqrt(dx * dx + dy * dy + dz * dz)
  936.  
  937. -- Calculate speed of the ship
  938. local shipSpeed = calculateSpeed(ship.velocity)
  939.  
  940. --calculate distance with ship source
  941.  
  942. local dx = ship.pos.x - vesselPos.x
  943. local dy = ship.pos.y - vesselPos.y
  944. local dz = ship.pos.z - vesselPos.z
  945. local shipDistance = math.sqrt(dx * dx + dy * dy + dz * dz)
  946.  
  947. --check velocity difference to see if the target is on the same vessel
  948.  
  949. local speedError = math.abs(ship.velocity.x - vesselVelocity.x) + math.abs(ship.velocity.y - vesselVelocity.y) + math.abs(ship.velocity.z - vesselVelocity.z)
  950.  
  951. -- If the ship is moving fast (e.g., a missile), prioritize it
  952. --if shipSpeed > 4 and not( isFriendly(ship.id)) and (CIWSdistance > 15 or shipDistance > 15 ) and speedError > 2 then
  953. if shipSpeed > 4 and not( isFriendly(ship.id)) and (CIWSdistance > 15 or shipDistance > 15 ) and speedError > 2 then
  954. closestDistance = CIWSdistance
  955. highestSpeed = shipSpeed
  956. targetPos1 = ship.pos
  957. table.insert(targets, {type = "ship", pos = ship.pos, distance = distance, velocity = ship.velocity, id = ship.id})
  958. end
  959. end
  960. end
  961.  
  962. table.sort(targets, function(a, b)
  963. if not a.distance or not b.distance then
  964. return false -- Safeguard against nil values
  965. end
  966.  
  967. if a.type == "ship" and b.type == "player" then
  968. return true
  969. elseif a.type == "player" and b.type == "ship" then
  970. return false
  971. else
  972. return a.distance < b.distance
  973. end
  974. end)
  975.  
  976. return targets
  977. end
  978.  
  979. local function main()
  980. while true do
  981. local startTime = os.clock()
  982. shipPos = ship.getWorldspacePosition()
  983. vesselPos = shipPos
  984. vesselVelocity = ship.getVelocity()
  985.  
  986. shipPos.x = shipPos.x + lengthCorrection * math.cos(getYaw() - math.pi/2) + widthCorrection * math.cos(getYaw())
  987. shipPos.y = shipPos.y + heightCorrection
  988. shipPos.z = shipPos.z + lengthCorrection * math.sin(getYaw() - math.pi/2) + widthCorrection * math.sin(getYaw())
  989.  
  990. updateMode()
  991. local firstScanEndTime = os.clock()
  992. local dt1 = firstScanEndTime - startTime
  993.  
  994. -- Get all targets
  995. local targets = getClosestTarget()
  996. print(textutils.serialize(controls))
  997. -- Determine the target based on the mode
  998. local targetInfo
  999. if mode == "auto" then
  1000. -- In auto mode, lock on to the closest target
  1001. if #targets > 0 then
  1002. targetInfo = targets[1]
  1003. end
  1004. cycleIndex = 1
  1005. elseif mode == "cycle" then
  1006. -- In cycle mode, switch to the next target on redstone input
  1007. if redstone.getInput("top") or (controls and controls.targetSwitch) then
  1008. cycleIndex = cycleIndex + 1 -- Cycle to the next target
  1009. print("Cycling to next target.")
  1010. end
  1011. if cycleIndex > #targets then
  1012. cycleIndex = 1
  1013. end
  1014. if #targets > 0 then
  1015. targetInfo = targets[cycleIndex]
  1016. end
  1017. end
  1018. -- Wait for a short period (scanInterval) to perform the second scan
  1019. if targetInfo and targetInfo.pos then
  1020. -- Perform second scan for both players and ships
  1021. if targetInfo.type == "player" then
  1022. sleep(scanInterval)
  1023. local targetScan2 = radar.scanForPlayers(400)
  1024. local targetPos2 = nil
  1025.  
  1026. for _, player in pairs(targetScan2) do
  1027. if player and player.pos and player.nickname == targetInfo.nickname then
  1028. targetPos2 = player.pos
  1029. break
  1030. end
  1031. end
  1032.  
  1033. -- If both positions are available, calculate velocity for the player
  1034. if targetInfo.pos and targetPos2 then
  1035. targetInfo.velocity = calculateVelocity(targetInfo.pos, targetPos2, scanInterval*4)
  1036. targetInfo.pos.x = targetPos2[1]
  1037. targetInfo.pos.y = targetPos2[2]
  1038. targetInfo.pos.z = targetPos2[3]
  1039. else
  1040. targetInfo.velocity = {x=0, y=0, z=0} -- Default velocity if we cannot calculate it
  1041. end
  1042.  
  1043. if targetInfo.pos and targetInfo.pos.x and targetInfo.velocity then
  1044. print("aiming cannon")
  1045. aimCannon(targetInfo.pos, targetInfo.velocity, {x=0,y=0,z=0}, shipPos.x, shipPos.y, shipPos.z)
  1046. else
  1047. locked = false
  1048. redstone.setOutput("back",false)
  1049. end
  1050. elseif targetInfo.type == "ship" then
  1051. sleep(scanInterval)
  1052.  
  1053. local shipScan2 = radar.scanForShips(400)
  1054. local shipPos2, shipVelocity2 = nil, nil
  1055.  
  1056. -- Find the same ship in the second scan based on its ID
  1057. for _, ship in pairs(shipScan2) do
  1058. if ship.id == targetInfo.id then
  1059. shipPos2 = ship.pos
  1060. shipVelocity2 = ship.velocity
  1061. break
  1062. end
  1063. end
  1064.  
  1065. local dt2 = os.clock() - firstScanEndTime
  1066. if targetInfo.velocity and shipVelocity2 then
  1067. -- Calculate acceleration
  1068. local acceleration = calculateAcceleration(targetInfo.velocity, shipVelocity2, dt2)
  1069. -- Update velocity for next scan
  1070. targetInfo.velocity = shipVelocity2
  1071. -- Aim the cannon considering acceleration
  1072. aimCannon(targetInfo.pos, targetInfo.velocity, acceleration, shipPos.x, shipPos.y, shipPos.z)
  1073. else
  1074. locked = false
  1075. end
  1076. else
  1077. locked = false
  1078. redstone.setOutput("back",false)
  1079. end
  1080. else
  1081. locked = false
  1082. redstone.setOutput("back",false)
  1083. end
  1084. os.sleep()
  1085. end
  1086. end
  1087.  
  1088. local function autoFire()
  1089. while true do
  1090. safetyOff = redstone.getInput("left") or redstone.getInput("right") or redstone.getInput("bottom") or redstone.getInput("back") or (controls and controls.fireAutocannon)
  1091. if locked and auto and safetyOff then
  1092. cannon.fire()
  1093. cannon.fire()
  1094. cannon.fire()
  1095. cannon.fire()
  1096. redstone.setOutput("front",true)
  1097. else
  1098. redstone.setOutput("front",false)
  1099. end
  1100. sleep()
  1101. end
  1102. end
  1103.  
  1104. local function modemMessage()
  1105. while true do
  1106. if modem then
  1107. local event, side, channel, replyChannel, message, distance = os.pullEvent("modem_message")
  1108. if channel == settings.controlsChannel then
  1109. controls = message
  1110. end
  1111. else
  1112. sleep()
  1113. end
  1114. end
  1115. end
  1116.  
  1117. parallel.waitForAny(
  1118. main,
  1119. autoFire,
  1120. modemMessage,
  1121. setPitchYaw
  1122. )
Advertisement
Add Comment
Please, Sign In to add comment