MegiRicky

NGDWBVRGen4_Artillery

May 19th, 2025 (edited)
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 61.86 KB | None | 0 0
  1. local monitor = peripheral.find("monitor")
  2. local radar = peripheral.find("sp_radar")
  3. local modem = peripheral.wrap("right")
  4. local speaker = peripheral.find("speaker")
  5. local yawMotor = peripheral.find("Create_RotationSpeedController")
  6.  
  7. -- Ensure all required peripherals are connected
  8. if not monitor or not radar or not ship then
  9. error("Required peripherals are not attached")
  10. end
  11.  
  12. monitor.setTextScale(0.5)
  13. monitor.clear()
  14. yawMotor.setTargetSpeed(0)
  15.  
  16. local radarScale = 500
  17. local friendlyID = {289, 232}
  18. local targetPositions = {}
  19. local waypoints = {}
  20. local displayState = "radar" -- Initial display state
  21. local selectedTarget = nil
  22. local lockedTargetId = nil
  23. local lockedWaypoint = nil -- Variable to store the locked waypoint
  24. local projectileSpeed = 320 --m/s
  25. local spreadConstant = 0.3
  26. local requiredRelativeYaw,requiredRelativePitch = 0,0
  27.  
  28. -- Get channel data for cannons
  29. local function getChannelInput(prompt, default)
  30. print(prompt .. ", default: " .. default)
  31. local input = io.read()
  32. if input == "" then
  33. input = default
  34. end
  35. return tonumber(input)
  36. end
  37.  
  38. local waypointChannel = getChannelInput("Input the control channel",1421)
  39. modem.open(waypointChannel)
  40.  
  41. local cannonData = {
  42. port5inch = {hitPosX = nil, hitPosY = nil, hitPosZ = nil, pitch = nil, yaw = nil, source = {} },
  43. starboard5inch = {hitPosX = nil, hitPosY = nil, hitPosZ = nil, pitch = nil, yaw = nil, source = {}},
  44. bow15inch = {hitPosX = nil, hitPosY = nil, hitPosZ = nil, pitch = nil, yaw = nil, source = {}},
  45. stern15inch = {hitPosX = nil, hitPosY = nil, hitPosZ = nil, pitch = nil, yaw = nil, source = {}},
  46. }
  47.  
  48. local cannonTarget = {
  49. port5inch = { type = nil, side = "port", id = nil, x = nil, y = nil, z = nil, yawAdjust = 0, pitchAdjust = 0 },
  50. starboard5inch = { type = nil, side = "starboard", id = nil, x = nil, y = nil, z = nil, yawAdjust = 0, pitchAdjust = 0 },
  51. bow15inch = { type = nil, side = "bow", id = nil, x = nil, y = nil, z = nil, yawAdjust = 0, pitchAdjust = 0},
  52. stern15inch = { type = nil, side = "stern", id = nil, x = nil, y = nil, z = nil, yawAdjust = 0, pitchAdjust = 0},
  53. }
  54.  
  55. local LaunchedMissiles = {}
  56. local missileControls = {
  57. fireMissile = {}
  58. }
  59. local immediateMissileInfo = {}
  60. local AIMInfoList,GBUInfoList,thunderBoltInfoList = {},{},{}
  61. local pendingMissileLaunches = {}
  62. local AIMCount,GBUCount,thunderboltCount = 0,0,0
  63.  
  64. local cannons = {}
  65. local k = 1
  66. local nilCount = 0
  67. local i = 0
  68. while nilCount < 200 do
  69. local cannon = peripheral.wrap("createbigcannons:cannon_mount_"..tostring(i))
  70. if not(cannon) then
  71. cannon = peripheral.wrap("cbcmodernwarfare:compact_mount_"..tostring(i))
  72. end
  73. if cannon then
  74. cannons[k] = cannon
  75. k = k + 1
  76. nilCount = 0
  77. print("found cannon")
  78. else
  79. nilCount = nilCount + 1
  80. end
  81. i = i + 1
  82. end
  83. print("Found "..#cannons.." cannons")
  84. for _, cannon in ipairs(cannons) do
  85. cannon.assemble()
  86. end
  87.  
  88.  
  89. local function checkFriendly(ID)
  90. local friendly = false
  91. for _, id in ipairs(friendlyID) do
  92. if tonumber(ID) == tonumber(id) then
  93. friendly = true
  94. break
  95. end
  96. end
  97. return friendly
  98. end
  99.  
  100. local w, h = monitor.getSize()
  101.  
  102. local function drawControls()
  103. local w, h = monitor.getSize()
  104. monitor.setCursorPos(1, h-1)
  105. monitor.write(" ")
  106. monitor.setCursorPos(1, h)
  107. monitor.write(" ")
  108. monitor.setCursorPos(1, h-1)
  109. monitor.write("Scale: ")
  110. monitor.setCursorPos(8, h-1)
  111. monitor.write("-")
  112. monitor.setCursorPos(10, h-1)
  113. monitor.write("+")
  114. monitor.setCursorPos(1, h-2)
  115. monitor.write("Stop locking")
  116. monitor.setCursorPos(1, h-3)
  117. monitor.write("Fire Cannons")
  118.  
  119. local segmentLength = radarScale / 2
  120. local scaleText
  121. if segmentLength >= 1000 then
  122. scaleText = string.format("%.1f km", segmentLength / 1000)
  123. else
  124. scaleText = string.format("%d m", segmentLength)
  125. end
  126.  
  127. monitor.setCursorPos(1, h)
  128. monitor.write("Segment Length: " .. scaleText)
  129.  
  130. -- Add button to navigate to waypoint page at the bottom right corner
  131. monitor.setCursorPos(w-10, h-1)
  132. monitor.write("Waypoints")
  133.  
  134. -- Add button to navigate to the cannon adjustment page at the top right corner
  135. monitor.setCursorPos(w-13, 1)
  136. monitor.write("Adjust Cannon")
  137. end
  138.  
  139. local function addWaypoint(x, y, z, color)
  140. local newWaypoint = {
  141. x = x,
  142. y = y,
  143. z = z,
  144. color = color or colors.purple
  145. }
  146. table.insert(waypoints, newWaypoint)
  147. end
  148.  
  149. local function deleteWaypointByPos(x, y, z)
  150. for i = #waypoints, 1, -1 do
  151. local wp = waypoints[i]
  152. if wp.x == tonumber(x) and wp.y == tonumber(y) and wp.z == tonumber(z) then
  153. table.remove(waypoints, i)
  154. return true
  155. end
  156. end
  157. return false
  158. end
  159.  
  160. local function normalizeVector(v)
  161. local length = math.sqrt(v[1]^2 + v[2]^2 + v[3]^2)
  162. if length == 0 then
  163. return {0, 0, 0}
  164. end
  165. return {v[1] / length, v[2] / length, v[3] / length}
  166. end
  167.  
  168. -- Normalize the rotation matrix
  169. local function normalizeRotationMatrix(rotMatrix)
  170. local normalizedMatrix = {}
  171. for i = 1, #rotMatrix do
  172. normalizedMatrix[i] = normalizeVector(rotMatrix[i])
  173. end
  174. return normalizedMatrix
  175. end
  176.  
  177. -- Get the pitch of the ship
  178. local function getPitch()
  179. local rotMatrix = ship.getTransformationMatrix()
  180. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  181. return math.asin(normalizedMatrix[2][3]) -- Extract pitch from the matrix
  182. end
  183. --pitch = math.deg(math.asin(ship.getTransformationMatrix()[2][3]))
  184. -- Get the yaw of the ship
  185. local function getYaw()
  186. local rotMatrix = ship.getTransformationMatrix()
  187. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  188. return math.atan2(-normalizedMatrix[3][1], -normalizedMatrix[3][3]) -- Extract yaw from the matrix
  189. end
  190.  
  191. -- Get the roll of the ship
  192. local function getRoll()
  193. local rotMatrix = ship.getTransformationMatrix()
  194. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  195. return math.atan2(normalizedMatrix[2][1], normalizedMatrix[2][2]) -- Extract roll from the matrix
  196. end
  197.  
  198. local function drawWaypointPage()
  199. local w, h = monitor.getSize()
  200. monitor.clear()
  201. monitor.setCursorPos(1, 1)
  202. monitor.write("Waypoint Page")
  203. monitor.setCursorPos(1, 3)
  204. monitor.write("Enter coordinates (x, y, z) and color:")
  205. monitor.setCursorPos(1, 4)
  206. monitor.write("Format: x,y,z,color")
  207. monitor.setCursorPos(1, 5)
  208. monitor.write("Colors: red, yellow, green, blue, purple")
  209. monitor.setCursorPos(1, h-1)
  210. monitor.write("Enter to submit, Back to cancel.")
  211. end
  212.  
  213. local function drawCannonAdjustmentPage()
  214. local w, h = monitor.getSize()
  215. monitor.clear()
  216.  
  217. -- 标题
  218. monitor.setCursorPos(1, 1)
  219. monitor.write("Cannon Adjustment")
  220.  
  221. -- 顶部右上角控制按钮布局起点
  222. local cx = w - 16
  223.  
  224. -- 上移按钮
  225. monitor.setCursorPos(cx, 1)
  226. monitor.write(" [ ]")
  227. monitor.setCursorPos(cx, 2)
  228. monitor.write(" [ + ]")
  229. monitor.setCursorPos(cx, 3)
  230. monitor.write(" [ ]")
  231.  
  232. -- 左右按钮(Yaw)
  233. monitor.setCursorPos(cx, 4)
  234. monitor.write("[ ] [ ]")
  235. monitor.setCursorPos(cx, 5)
  236. monitor.write("[ - ] R [ + ]")
  237. monitor.setCursorPos(cx, 6)
  238. monitor.write("[ ] [ ]")
  239.  
  240. -- 下移按钮
  241. monitor.setCursorPos(cx, 7)
  242. monitor.write(" [ ]")
  243. monitor.setCursorPos(cx, 8)
  244. monitor.write(" [ - ]")
  245. monitor.setCursorPos(cx, 9)
  246. monitor.write(" [ ]")
  247.  
  248. -- Spread 控制(左侧)
  249. monitor.setCursorPos(1, 3)
  250. monitor.write("Spread: [-]"..string.sub(string.format("%.2f", spreadConstant), 1, 3).."[+]")
  251.  
  252. monitor.setCursorPos(1, 5)
  253. monitor.write(string.format("Pitch: %.1f", requiredRelativePitch))
  254. monitor.setCursorPos(1, 6)
  255. monitor.write(string.format("Yaw: %.0f", math.deg(getYaw())))
  256.  
  257. monitor.setCursorPos(1, h-2)
  258. monitor.write("Stop locking")
  259. monitor.setCursorPos(1, h-3)
  260. monitor.write("Fire Cannons")
  261.  
  262. -- 返回按钮
  263. monitor.setCursorPos(1, h)
  264. monitor.write("Back")
  265. end
  266.  
  267. local function drawRadarBackground(centerX, centerY, radius, shipYawRadians)
  268. local aspectRatio = 1.5
  269. local segmentLength = radarScale / 4
  270. local pixelPerSegmentX = w / 4
  271. local pixelPerSegmentY = h / 4
  272.  
  273. -- Draw the grid
  274. for i = 0, w - pixelPerSegmentX, pixelPerSegmentX do
  275. -- Vertical lines
  276. for y = 1, h - 2 do -- Leave space for the scale display at the bottom
  277. monitor.setCursorPos(i, y)
  278. monitor.write("|")
  279. end
  280. end
  281.  
  282. for j = 0, h - pixelPerSegmentY, pixelPerSegmentY do
  283. -- Horizontal lines
  284. for x = 1, w do
  285. monitor.setCursorPos(x, j)
  286. monitor.write("-")
  287. end
  288. end
  289.  
  290. -- Draw the circle
  291. for i = 0, 360, 5 do
  292. local rad = i * (math.pi / 180)
  293. local x = centerX + (radius * math.sin(rad)) * aspectRatio
  294. local y = centerY + radius * math.cos(rad)
  295. monitor.setCursorPos(math.floor(x + 0.5), math.floor(y + 0.5))
  296. monitor.write(".")
  297. end
  298.  
  299. -- Draw the crosshair
  300. for y = centerY - radius, centerY + radius do
  301. monitor.setCursorPos(centerX, y)
  302. monitor.write("|")
  303. end
  304.  
  305. local trueBearing = (math.deg(shipYawRadians) + 360) % 360 - 180
  306. if trueBearing < 0 then
  307. trueBearing = trueBearing + 360
  308. end
  309. local textPos = centerY - radius + 10
  310. if textPos > 0 then
  311. monitor.setCursorPos(centerX - (#tostring(math.floor(trueBearing)) + 2) / 2, textPos)
  312. monitor.write(tostring(math.floor(trueBearing)) .. "°")
  313. end
  314.  
  315. local directions = {"N", "W", "S", "E"}
  316. local dirAngles = {0, 90, 180, 270}
  317.  
  318. for index, dir in ipairs(directions) do
  319. local dirRad = (dirAngles[index] + math.deg(shipYawRadians)) * (math.pi / 180)
  320. local dirX = centerX + (radius * math.sin(dirRad)) * aspectRatio
  321. local dirY = centerY + radius * math.cos(dirRad)
  322. monitor.setCursorPos(math.floor(dirX + 0.5), math.floor(dirY + 0.5))
  323. monitor.write(dir)
  324. end
  325.  
  326. -- Display segment length
  327. monitor.setCursorPos(1, centerY + radius + 2)
  328. monitor.write("Segment Length: " .. segmentLength .. " meters")
  329. end
  330.  
  331. local function drawTargetOnCircle(centerX, centerY, radius, relX, relY, aspectRatio)
  332. local dx = relX - centerX
  333. local dy = relY - centerY
  334. local mag = math.sqrt((dx / aspectRatio)^2 + dy^2)
  335.  
  336. if (mag > radius) then
  337. local intersectX = centerX + ((dx / mag) * radius) * aspectRatio
  338. local intersectY = centerY + (dy / mag) * radius
  339. return intersectX, intersectY
  340. else
  341. return relX, relY
  342. end
  343. end
  344.  
  345. local function drawCannonCrosshair(centerX, centerY, radius, aspectRatio)
  346. local pos = ship.getWorldspacePosition()
  347. local shipYawRadians = math.atan2(-ship.getTransformationMatrix()[1][3], ship.getTransformationMatrix()[3][3])
  348. if shipYawRadians < 0 then shipYawRadians = shipYawRadians + 2 * math.pi end
  349. -- Function to calculate relative yaw in degrees from ship's facing
  350. local function relativeYaw(dx, dz)
  351. local angle = math.atan2(dx, dz)
  352. local relativeAngle = angle + shipYawRadians - math.pi
  353. if relativeAngle < -math.pi then
  354. relativeAngle = relativeAngle + 2 * math.pi
  355. elseif relativeAngle >= math.pi then
  356. relativeAngle = relativeAngle - 2 * math.pi
  357. end
  358. return math.deg(relativeAngle)
  359. end
  360.  
  361. local function drawCrosshairForCannon(cannonData, color)
  362. if cannonData.hitPosX and cannonData.hitPosZ then
  363. local dx = cannonData.hitPosX - pos.x
  364. local dz = cannonData.hitPosZ - pos.z
  365. local cannonYaw = relativeYaw(dx, dz)
  366. local distance = math.sqrt(dx^2 + dz^2)
  367. local scaledDistance = (distance / radarScale) * radius
  368. local relX = centerX + (scaledDistance * math.sin(math.rad(cannonYaw))) * aspectRatio
  369. local relY = centerY + scaledDistance * math.cos(math.rad(cannonYaw))
  370. relX, relY = drawTargetOnCircle(centerX, centerY, radius, relX, relY, aspectRatio)
  371. monitor.setCursorPos(math.floor(relX + 0.5), math.floor(relY + 0.5))
  372. monitor.setBackgroundColor(color)
  373. monitor.write("X")
  374. monitor.setBackgroundColor(colors.black)
  375. return cannonYaw
  376. end
  377. return nil
  378. end
  379.  
  380. -- Draw crosshair and check range for each cannon
  381. local portYaw = drawCrosshairForCannon(cannonData.port5inch, colors.red)
  382. if portYaw and not(portYaw > 225 and portYaw < 330) then
  383. monitor.setCursorPos(1, 1)
  384. monitor.write("Warning: Port cannon may hit the ship!")
  385. end
  386.  
  387. local starboardYaw = drawCrosshairForCannon(cannonData.starboard5inch, colors.blue)
  388. if starboardYaw and not(starboardYaw > 30 and starboardYaw < 135) then
  389. monitor.setCursorPos(1, 2)
  390. monitor.write("Warning: Starboard cannon may hit the ship!")
  391. end
  392.  
  393. local bowYaw = drawCrosshairForCannon(cannonData.bow15inch, colors.green)
  394. if bowYaw and not(bowYaw > 120 and bowYaw < 240) then
  395. monitor.setCursorPos(1, 3)
  396. monitor.write("Warning: Bow cannon may hit the ship!")
  397. end
  398.  
  399. local sternYaw = drawCrosshairForCannon(cannonData.stern15inch, colors.yellow)
  400. if sternYaw and not(sternYaw > 300 or sternYaw < 60) then
  401. monitor.setCursorPos(1, 4)
  402. monitor.write("Warning: Stern cannon may hit the ship!")
  403. end
  404. end
  405.  
  406. local function calculateRelativeAngle(objectAngle, shipYawRadians)
  407. local relativeAngle = objectAngle + shipYawRadians - math.pi
  408. if relativeAngle < -math.pi then
  409. relativeAngle = relativeAngle + 2 * math.pi
  410. elseif relativeAngle >= math.pi then
  411. relativeAngle = relativeAngle - 2 * math.pi
  412. end
  413. return relativeAngle
  414. end
  415.  
  416. local function drawRadarDisplay()
  417. local w, h = monitor.getSize()
  418. local centerX, centerY = math.floor(w / 2), math.floor(h / 2)
  419. local radius = math.min(centerX, centerY) - 1
  420. local aspectRatio = 1.2
  421.  
  422. local matrix = ship.getTransformationMatrix()
  423. local shipYawRadians = math.atan2(-matrix[1][3], matrix[3][3])
  424. if (shipYawRadians < 0) then
  425. shipYawRadians = shipYawRadians + 2 * math.pi
  426. end
  427.  
  428. drawRadarBackground(centerX, centerY, radius, shipYawRadians)
  429. monitor.setCursorPos(centerX, centerY)
  430. monitor.write("+")
  431.  
  432. drawCannonCrosshair(centerX, centerY, radius, aspectRatio)
  433.  
  434. local pos = ship.getWorldspacePosition()
  435. local results = radar.scanForShips(10000)
  436. targetPositions = {}
  437. for _, object in ipairs(results) do
  438. local x = object.pos.x - pos.x
  439. local z = object.pos.z - pos.z
  440. local distance = math.sqrt(x^2 + z^2)
  441. local objectAngle = math.atan2(x, z)
  442. local relativeAngle = calculateRelativeAngle(objectAngle, shipYawRadians)
  443.  
  444. local scaledDistance = (distance / radarScale) * radius
  445. local relX = centerX + (scaledDistance * math.sin(relativeAngle)) * aspectRatio
  446. local relY = centerY + scaledDistance * math.cos(relativeAngle)
  447.  
  448. relX, relY = drawTargetOnCircle(centerX, centerY, radius, relX, relY, aspectRatio)
  449.  
  450. if (object.mass > 2000 and distance > 5) then
  451. if (distance > radarScale) then
  452. monitor.setTextColor(colors.lightBlue)
  453. else
  454. monitor.setTextColor(colors.red)
  455. end
  456. if (checkFriendly(object.id)) then
  457. monitor.setBackgroundColor(colors.blue)
  458. elseif (object.mass > 1000000) then
  459. monitor.setBackgroundColor(colors.orange)
  460. elseif (math.sqrt(object.velocity.x ^ 2 + object.velocity.y ^ 2 + object.velocity.z ^ 2) > 30) then
  461. monitor.setBackgroundColor(colors.red)
  462. else
  463. monitor.setBackgroundColor(colors.yellow)
  464. end
  465. monitor.setCursorPos(math.floor(relX + 0.5), math.floor(relY + 0.5))
  466. monitor.write("o")
  467. monitor.setTextColor(colors.green)
  468. monitor.setBackgroundColor(colors.black)
  469.  
  470. table.insert(targetPositions, {x = math.floor(relX + 0.5), y = math.floor(relY + 0.5), data = object})
  471. end
  472. end
  473.  
  474. -- Draw waypoints
  475. for index, waypoint in ipairs(waypoints) do
  476. local wpX = waypoint.x - pos.x
  477. local wpZ = waypoint.z - pos.z
  478. local distance = math.sqrt(wpX^2 + wpZ^2)
  479. local wpAngle = math.atan2(wpX, wpZ)
  480. local relativeAngle = calculateRelativeAngle(wpAngle, shipYawRadians)
  481.  
  482. local scaledDistance = (distance / radarScale) * radius
  483. local relX = centerX + (scaledDistance * math.sin(relativeAngle)) * aspectRatio
  484. local relY = centerY + scaledDistance * math.cos(relativeAngle)
  485.  
  486. relX, relY = drawTargetOnCircle(centerX, centerY, radius, relX, relY, aspectRatio)
  487.  
  488. monitor.setBackgroundColor(waypoint.color)
  489. monitor.setCursorPos(math.floor(relX + 0.5), math.floor(relY + 0.5))
  490. monitor.write("W")
  491. monitor.setBackgroundColor(colors.black)
  492.  
  493. table.insert(targetPositions, {x = math.floor(relX + 0.5), y = math.floor(relY + 0.5), data = {type = "waypoint", x = waypoint.x,y = waypoint.y, z = waypoint.z, index = index}})
  494. end
  495. end
  496.  
  497. local function displayTargetInfo(target)
  498. local w, h = monitor.getSize()
  499. local pos = ship.getWorldspacePosition()
  500.  
  501. monitor.clear()
  502. monitor.setCursorPos(1, h-13)
  503. monitor.write("Target Info")
  504. monitor.setCursorPos(1, h-12)
  505.  
  506. local targetPosX, targetPosY, targetPosZ
  507. if target.type == "waypoint" then
  508. monitor.write("Type: Waypoint")
  509. targetPosX, targetPosY, targetPosZ = target.x, target.y, target.z
  510. monitor.setCursorPos(1, h-7)
  511. monitor.write("Coordinate: " .. target.x .. ", "..target.y..", ".. target.z)
  512. else
  513. monitor.write("ID: " .. target.id)
  514. targetPosX, targetPosY, targetPosZ = target.pos.x, target.pos.y, target.pos.z
  515. monitor.setCursorPos(1, h-11)
  516. monitor.write("Mass: " .. target.mass)
  517. monitor.setCursorPos(1, h-10)
  518. monitor.write("Velocity: " .. string.format("%.2f, %.2f, %.2f", target.velocity.x, target.velocity.y, target.velocity.z))
  519. monitor.setCursorPos(1, h-9)
  520. monitor.write("Position: " .. string.format("%.2f, %.2f, %.2f", target.pos.x, target.pos.y, target.pos.z))
  521. end
  522.  
  523. local distance = math.sqrt((targetPosX - pos.x)^2 + (targetPosZ - pos.z)^2)
  524. local dx = targetPosX - pos.x
  525. local dz = targetPosZ - pos.z
  526. local bearing = (math.deg(math.atan2(dz, dx)) + 360) % 360 - 270
  527. if bearing < 0 then
  528. bearing = bearing + 360
  529. end
  530.  
  531. monitor.setCursorPos(1, h-8)
  532. monitor.write("Distance: " .. string.format("%.2f", distance) .. " meters")
  533. monitor.setCursorPos(1, h-7)
  534. monitor.write("Bearing: " .. string.format("%.2f", bearing) .. "°")
  535.  
  536. if target.type ~= "waypoint" then
  537. local type = "unknown"
  538. local hostile = "hostile"
  539. if target.mass > 1000000 then
  540. type = "ship"
  541. elseif math.sqrt(target.velocity.x ^ 2 + target.velocity.y ^ 2 + target.velocity.z ^ 2) > 30 then
  542. type = "Flying missile / plane"
  543. else
  544. type = "unknown"
  545. end
  546. if checkFriendly(target.id) then
  547. hostile = "friendly"
  548. else
  549. hostile = "hostile"
  550. end
  551. monitor.setCursorPos(1, h-6)
  552. monitor.write("Type: " .. hostile .. " " .. type)
  553. end
  554.  
  555. monitor.setCursorPos(1, h-5)
  556. monitor.write("[Direct Fire Lock]")
  557. monitor.setCursorPos(1, h-4)
  558. monitor.write("[Indirect Fire Lock]")
  559. monitor.setCursorPos(1, h-3)
  560. monitor.write("[MRIS Lock]")
  561.  
  562. if target.type == "waypoint" then
  563. monitor.setCursorPos(1, h-2)
  564. monitor.write("[Delete Waypoint]")
  565. end
  566.  
  567. monitor.setCursorPos(1, h)
  568. monitor.write("Back")
  569. end
  570.  
  571. local function launchMissile(targetType, targetId, targetPos, missileType)
  572. local currentMissile = nil
  573.  
  574. -- Function to find and remove the first unlaunched missile from a list
  575. local function findUnlaunchedMissile(missileList)
  576. for i = #missileList, 1, -1 do -- Iterate in reverse to avoid index shifting issues
  577. local missile = missileList[i]
  578. if missile.launchState == false then
  579. missile.launchState = true -- Mark missile as launched
  580. table.insert(LaunchedMissiles, missile) -- Move to launched list
  581. return table.remove(missileList, i) -- Remove from available list and return it
  582. end
  583. end
  584. return nil
  585. end
  586.  
  587.  
  588. -- Get the first unlaunched missile of the specified type
  589. if missileType == "AIM-220" then
  590. currentMissile = findUnlaunchedMissile(AIMInfoList)
  591. elseif missileType == "GBU-42" then
  592. currentMissile = findUnlaunchedMissile(GBUInfoList)
  593. elseif missileType == "thunderBolt" then
  594. currentMissile = findUnlaunchedMissile(thunderBoltInfoList)
  595. end
  596.  
  597. -- If no unlaunched missile is found, exit function
  598. if not currentMissile then
  599. print("No available unlaunched missile of type:", missileType)
  600. return
  601. end
  602.  
  603. local currentMissileId = currentMissile.id
  604. print("Launching missile " .. currentMissileId)
  605.  
  606. -- Assign the missile as launched and set target info
  607. if targetType == "ship" then
  608. missileControls.fireMissile[currentMissileId] = {launch = true, type = targetType, id = targetId}
  609. else
  610. missileControls.fireMissile[currentMissileId] = {launch = true, type = targetType, pos = targetPos}
  611. end
  612. end
  613.  
  614. local yawErrorSum = 0
  615. local lastYawError = 0
  616. local pitchErrorSum = 0
  617. local lastPitchError = 0
  618. local yawError = 0
  619. local yawIntegral = 0
  620. local yawPrevError = 0
  621. local pitchError = 0
  622. local pitchIntegral = 0
  623. local pitchPrevError = 0
  624. local lastTime = os.clock()
  625.  
  626. local Kp_yaw = 3.5
  627. local Ki_yaw = 0
  628. local Kd_yaw = 0.1
  629. local Kp_pitch = 0.25
  630. local Ki_pitch = 0.05
  631. local Kd_pitch = 0.012
  632. local dt = 0.1
  633. local function customProportional(error, Kp)
  634. -- Nonlinear proportional scaling
  635. -- Example: Quadratic growth for small errors
  636. local scaleFactor = 0 -- Controls how quickly the value grows for small errors
  637.  
  638. local absError = math.abs(error)
  639. local proportional = Kp * (absError / (1 + scaleFactor * absError)) -- Sigmoid-like growth
  640.  
  641. if error < 0 then
  642. proportional = -proportional -- Preserve the sign of the error
  643. end
  644.  
  645. return math.abs(proportional) * (error < 0 and -1 or 1) -- Cap the value
  646. end
  647.  
  648. local function PIDController(Kp, Ki, Kd, error, integral, prevError, dt)
  649. -- Nonlinear proportional term using the custom function
  650. local proportional = customProportional(error, Kp)
  651.  
  652. -- Integral and derivative components
  653. integral = integral + error * dt
  654. local derivative = (error - prevError) / dt
  655.  
  656. -- Calculate the PID output
  657. local output = proportional + (Ki * integral) + (Kd * derivative)
  658.  
  659. -- Return the PID output, updated integral, and current error
  660. return output, integral, error
  661. end
  662.  
  663. local lastYawTime = os.clock()
  664. -- Yaw control function using PID
  665. local function yawControl(deltaYaw, currentYaw)
  666. local now = os.clock()
  667. local dtThisFrame = now - lastYawTime
  668. lastYawTime = now
  669. if dtThisFrame <= 0 then
  670. dtThisFrame = 0.05
  671. end
  672. -- PID controller for yaw
  673. --print(dtThisFrame)
  674. local yawSpeed, newIntegral, newPrevError = PIDController(Kp_yaw, Ki_yaw, Kd_yaw, deltaYaw, yawIntegral, yawPrevError, dtThisFrame)
  675.  
  676. -- 2) Update global PID state
  677. yawIntegral = newIntegral
  678. yawPrevError = newPrevError
  679.  
  680. -- Constrain the yaw speed to prevent runaway spinning
  681. yawSpeed = math.max(-36, math.min(36, yawSpeed))
  682.  
  683. --print("deltaYaw: " .. deltaYaw)
  684. --print("yawSpeed: " .. yawSpeed)
  685.  
  686. -- Set motor speed based on PID output
  687. yawMotor.setTargetSpeed(-yawSpeed)
  688. end
  689.  
  690. local function findRelativeAngle(targetYaw,targetPitch)
  691. rot = ship.getQuaternion()
  692. cacheYaw = math.pi - math.rad(targetYaw)
  693. cachePitch = - math.rad(targetPitch)
  694. rotMatAdj11 = 1 - 2*(rot.x^2 + rot.y^2)
  695. rotMatAdj12 = 2*(rot.z * rot.x + rot.y * rot.w)
  696. rotMatAdj13 = 2*(rot.z * rot.y - rot.x * rot.w)
  697. rotMatAdj21 = 2*(rot.z * rot.x - rot.y * rot.w)
  698. rotMatAdj22 = 1 - 2*(rot.z^2 + rot.y^2)
  699. rotMatAdj23 = 2*(rot.x * rot.y + rot.z * rot.w)
  700. rotMatAdj31 = 2*(rot.z * rot.y + rot.x * rot.w)
  701. rotMatAdj32 = 2*(rot.x * rot.y - rot.z * rot.w)
  702. rotMatAdj33 = 1 - 2*(rot.z^2 + rot.x^2)
  703.  
  704. rotMatTGT11 = math.cos(cacheYaw) * math.cos(cachePitch)
  705. rotMatTGT21 = math.sin(cacheYaw) * math.cos(cachePitch)
  706. rotMatTGT31 = - math.sin(cachePitch)
  707.  
  708. rotMatRSLT11 = rotMatAdj11 * rotMatTGT11 + rotMatAdj12 * rotMatTGT21 + rotMatAdj13 * rotMatTGT31
  709. rotMatRSLT21 = rotMatAdj21 * rotMatTGT11 + rotMatAdj22 * rotMatTGT21 + rotMatAdj23 * rotMatTGT31
  710. rotMatRSLT31 = rotMatAdj31 * rotMatTGT11 + rotMatAdj32 * rotMatTGT21 + rotMatAdj33 * rotMatTGT31
  711.  
  712. turretYaw = math.atan2(rotMatRSLT21, rotMatRSLT11)
  713. barrelPitch = math.asin(-rotMatRSLT31)
  714. return math.deg(-turretYaw),math.deg(-barrelPitch)
  715. end
  716.  
  717. local lockedTarget = {pos = {x = nil, y = nil, z = nil}, velocity = {x = nil, y = nil, z = nil}, type = nil, lockMode = nil}
  718. local function setPitchYaw()
  719. while true do
  720. if lockedTarget and lockedTarget.lockMode and requiredRelativeYaw and requiredRelativePitch then
  721. local tasks = {} -- Table to store each cannon's task
  722.  
  723. for index, cannon in pairs(cannons) do
  724. -- Define the function for this cannon's pitch/yaw adjustment
  725. local function adjustCannon()
  726. if false then
  727. -- No spread for the first cannon
  728. cannon.setPitch(requiredRelativePitch)
  729. cannon.setYaw(math.min(3,math.max(-3,requiredRelativeYaw)))
  730. --print("Cannon " .. index .. " (Primary) set to pitch: " .. requiredRelativePitch .. " and yaw: " .. requiredRelativeYaw)
  731. else
  732. -- Spread logic for other cannons
  733. local localSpreadConstant = spreadConstant
  734. if requiredRelativePitch < 30 then localSpreadConstant=localSpreadConstant/2 end
  735.  
  736. local pitchVariation = math.random(-2, 2) * localSpreadConstant -- Adjust the range to control the spread
  737. if requiredRelativePitch > 30 then localSpreadConstant = localSpreadConstant*8 end
  738. local yawVariation = math.random(-2, 2) * localSpreadConstant -- Adjust the range to control the spread
  739.  
  740. local adjustedPitch = requiredRelativePitch + pitchVariation
  741. local adjustedYaw = requiredRelativeYaw + yawVariation
  742.  
  743. if lockedTarget.lockMode == "MRSI" or lockedTarget == "indirect" then
  744. cannon.setPitch(adjustedPitch)
  745. cannon.setYaw(math.min(3,math.max(-3,adjustedYaw)))
  746. --print("Cannon " .. index .. " set to pitch: " .. adjustedPitch .. " and yaw: " .. adjustedYaw)
  747. else
  748. cannon.setPitch(requiredRelativePitch)
  749. cannon.setYaw(math.min(3,math.max(-3,requiredRelativeYaw)))
  750. --print("Cannon " .. index .. " set to uniform pitch: " .. requiredRelativePitch .. " and yaw: " .. requiredRelativeYaw)
  751. end
  752. end
  753. end
  754.  
  755. -- Add this task to the tasks table
  756. table.insert(tasks, adjustCannon)
  757. end
  758. -- Execute all tasks in parallel
  759. parallel.waitForAll(table.unpack(tasks))
  760. end
  761. sleep()
  762. end
  763. end
  764.  
  765. local barrel = peripheral.find("minecraft:barrel")
  766. local depot_list = { peripheral.find("create:depot") }
  767. -- Finds an item in the barrel that exactly matches the given display name.
  768. local function findItemByDisplayName(displayName)
  769. -- get a quick list of everything in the barrel
  770. local items = barrel.list()
  771. for slot, data in pairs(items) do
  772. -- get full detail for the item in this slot
  773. local detail = barrel.getItemDetail(slot)
  774. if detail and detail.displayName == displayName then
  775. -- If matched, return slot and quantity
  776. return true, slot, detail.count
  777. end
  778. end
  779. return false
  780. end
  781.  
  782. local function pullItemByDisplayName(displayName)
  783. local found, slot, count = findItemByDisplayName(displayName)
  784. if found then
  785. print("Found item '" .. displayName .. "' in slot ".. slot .." (count = "..count..")")
  786. for _, depot in ipairs(depot_list) do
  787. local pulled = depot.pullItems(peripheral.getName(barrel), slot, 1)
  788. end
  789. print("Pulled 1x '" .. displayName .. "' into deployer.")
  790. else
  791. print("No item named '" .. displayName .. "' in the barrel.")
  792. end
  793. end
  794.  
  795. charge = "4Charge"
  796. local chargeSpeeds = {
  797. ["2Charge"] = 113,
  798. ["3Charge"] = 170,
  799. ["4Charge"] = 230
  800. }
  801. local function firing(charge)
  802. local fireTasks = {} -- Table to store firing tasks
  803. pullItemByDisplayName(charge)
  804. sleep(1.5)
  805. -- Add each cannon's fire task to the table
  806. for index, cannon in pairs(cannons) do
  807. table.insert(fireTasks, function()
  808. cannon.fire()
  809. print("Cannon " .. index .. " FIRING")
  810. end)
  811. end
  812. sleep()
  813.  
  814. -- Execute all tasks simultaneously
  815. parallel.waitForAll(table.unpack(fireTasks))
  816. end
  817.  
  818. local g,cd,c_est = 0.05,0.995,0.0028
  819. local function calculateRange(angle, u, cd, g, c_est)
  820. local radians = math.rad(angle)
  821. local u = u/20
  822. local part1 = u * math.cos(radians) / math.log(cd)
  823. local part2 = ((g * cd) / (g * cd + (1 - cd) * u * math.sin(radians))) ^ (2 + c_est * projectileSpeed * math.sin(radians)) - 1
  824. local XR = part1 * part2
  825.  
  826. return XR
  827. end
  828.  
  829. local function findBestPitch(targetPos, sourcePos, initialVelocity, g, cd, c_est, fireMode)
  830. local bestLowPitch = nil
  831. local bestHighPitch = nil
  832. local bestLowDistance = math.huge
  833. local bestHighDistance = math.huge
  834. local targetDistance = math.sqrt((targetPos.x - sourcePos.x)^2 + (targetPos.z - sourcePos.z)^2)
  835.  
  836. for pitch = 0, 90, 0.05 do -- Iterate over pitch angles
  837. local calculatedRange = calculateRange(pitch, initialVelocity, cd, g, c_est)
  838. local distanceDifference = math.abs(calculatedRange - targetDistance)
  839.  
  840. -- Find the low-angle solution
  841. if pitch <= 30 then
  842. if distanceDifference < 10 and distanceDifference < bestLowDistance then
  843. bestLowDistance = distanceDifference
  844. bestLowPitch = pitch
  845. end
  846. -- Find the high-angle solution
  847. elseif pitch > 30 then
  848. if distanceDifference < 10 and distanceDifference < bestHighDistance then
  849. bestHighDistance = distanceDifference
  850. bestHighPitch = pitch
  851. end
  852. end
  853. end
  854.  
  855. if fireMode == "indirect" then
  856. return bestHighPitch or bestLowPitch
  857. else
  858. return bestLowPitch
  859. end
  860. end
  861.  
  862. local function estimateFlightTime(initialSpeed, angle, cd, g)
  863. -- 模拟每 tick 速度衰减,单位 tick = 1/20 秒
  864. local dt = 1 / 20
  865. local rad = math.rad(angle)
  866.  
  867. local vx = initialSpeed/20 * math.cos(rad)
  868. local vy = initialSpeed/20 * math.sin(rad)
  869.  
  870. local x, y = 0, 0
  871. local t = 0
  872.  
  873. while y >= 0 do
  874. -- 更新位置
  875. x = x + vx * dt
  876. y = y + vy * dt
  877.  
  878. -- 更新速度(考虑阻力和重力)
  879. vx = vx * cd
  880. vy = vy * cd - g
  881.  
  882. t = t + dt
  883.  
  884. -- 安全终止(避免死循环)
  885. if t > 60 then break end
  886. end
  887.  
  888. return t
  889. end
  890.  
  891. local function aimSimpleFire(lockedTargetInfo)
  892. if lockedTargetInfo then
  893. local currentTime = os.clock()
  894. local dt = currentTime - lastTime
  895. if dt == 0 then return end -- Prevent division by zero
  896. lastTime = currentTime
  897. currentYaw = math.deg(getYaw())
  898.  
  899. local currentPosition = ship.getWorldspacePosition()
  900.  
  901. local dx = lockedTargetInfo.pos.x - currentPosition.x
  902. local dy = lockedTargetInfo.pos.y - currentPosition.y
  903. local dz = lockedTargetInfo.pos.z - currentPosition.z
  904. local distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  905.  
  906. local shipVelocity = ship.getVelocity()
  907.  
  908. local estimate = {}
  909. local estimateTime = distance / (projectileSpeed)
  910. estimate.x = lockedTargetInfo.pos.x + lockedTargetInfo.velocity.x * estimateTime
  911. estimate.y = lockedTargetInfo.pos.y + lockedTargetInfo.velocity.y * estimateTime
  912. estimate.z = lockedTargetInfo.pos.z + lockedTargetInfo.velocity.z * estimateTime
  913.  
  914. local dx = estimate.x - currentPosition.x
  915. local dy = estimate.y - currentPosition.y
  916. local dz = estimate.z - currentPosition.z
  917. local distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  918.  
  919. local estimateTime = distance / (projectileSpeed)
  920. estimate.x = lockedTargetInfo.pos.x + lockedTargetInfo.velocity.x * estimateTime
  921. estimate.y = lockedTargetInfo.pos.y + lockedTargetInfo.velocity.y * estimateTime
  922. estimate.z = lockedTargetInfo.pos.z + lockedTargetInfo.velocity.z * estimateTime
  923.  
  924. local dx = estimate.x - currentPosition.x
  925. local dy = estimate.y - currentPosition.y
  926. local dz = estimate.z - currentPosition.z
  927.  
  928. local horizontalDistance = math.sqrt(dx * dx + dz * dz)
  929. local pitch = math.deg(math.atan2(dy, horizontalDistance))
  930.  
  931. local yaw = math.deg(math.atan2(-dx, dz))
  932. yaw = (yaw + 180) % 360
  933.  
  934. -- Adjust pitch based on distance adjustments
  935. projectileSpeed = 240
  936. if lockedTarget.lockMode == "direct" then
  937. pitch = pitch + findBestPitch(estimate,currentPosition, projectileSpeed, g, cd, c_est, "direct")
  938. charge = "4Charge"
  939. elseif lockedTarget.lockMode == "indirect" then
  940. pitch = pitch + findBestPitch(estimate,currentPosition, projectileSpeed, g, cd, c_est, "indirect")
  941. end
  942. local deltaYaw = (yaw - currentYaw + 180) % 360 - 180
  943.  
  944. -- Turning and pitch adjustment logic
  945. yawControl(deltaYaw, currentYaw)
  946. -- Using vs addition to turn cannon
  947. requiredRelativeYaw, requiredRelativePitch = findRelativeAngle(yaw,pitch)
  948.  
  949. lastCurrentYaw = currentYaw
  950. end
  951. end
  952.  
  953. local function updateTargetInfo(lockedTarget)
  954. if lockedTarget.type == "waypoint" then
  955. return {pos = {x=lockedTarget.x,y=lockedTarget.y,z=lockedTarget.z}, velocity = {x = 0, y = 0, z = 0}, type = "waypoint", lockMode = lockMode}
  956. else -- handling ships target
  957. local scanResults = radar.scanForShips(9999)
  958. for _, object in ipairs(scanResults) do
  959. if object.id == lockedTarget.id then
  960. return {pos = object.pos, velocity = object.velocity, type = "ship", lockMode = lockMode}
  961. end
  962. end
  963. end
  964. end
  965.  
  966. local deltaYaw = 180
  967. local function aimMRSIFire(lockedTarget)
  968. local lockedTargetInfo = updateTargetInfo(lockedTarget)
  969. if not lockedTargetInfo then
  970. print("No target info available.")
  971. return
  972. end
  973.  
  974. local currentPosition = ship.getWorldspacePosition()
  975. local dx = lockedTargetInfo.pos.x - currentPosition.x
  976. local dz = lockedTargetInfo.pos.z - currentPosition.z
  977. local distance = math.sqrt(dx * dx + dz * dz)
  978.  
  979. local viableCharges = {}
  980.  
  981. -- Only collect indirect charges with pitch > 25
  982. for chargeName, speed in pairs(chargeSpeeds) do
  983. local indirectPitch = findBestPitch(lockedTargetInfo.pos, currentPosition, speed, g, cd, c_est, "indirect")
  984. if indirectPitch and indirectPitch > 13 then
  985. local flightTime = estimateFlightTime(speed, indirectPitch,cd, g)
  986. print(flightTime)
  987. table.insert(viableCharges, {
  988. charge = chargeName,
  989. speed = speed,
  990. pitch = indirectPitch,
  991. flightTime = flightTime
  992. })
  993. end
  994. local directPitch = findBestPitch(lockedTargetInfo.pos, currentPosition, speed, g, cd, c_est, "direct")
  995. if directPitch and directPitch > 13 then
  996. local flightTime = estimateFlightTime(speed, directPitch,cd, g)
  997. print(flightTime)
  998. table.insert(viableCharges, {
  999. charge = chargeName,
  1000. speed = speed,
  1001. pitch = directPitch,
  1002. flightTime = flightTime
  1003. })
  1004. end
  1005. print("Charge: "..chargeName.." speed: "..speed)
  1006. print(indirectPitch,directPitch)
  1007. end
  1008.  
  1009. if #viableCharges == 0 then
  1010. print("No viable indirect charges with pitch > 25.")
  1011. return
  1012. end
  1013.  
  1014. -- Sort descending by flightTime
  1015. table.sort(viableCharges, function(a, b) return a.flightTime > b.flightTime end)
  1016.  
  1017. -- Build MRSI sequence
  1018. local mrsiSequence = {}
  1019. local lastTime = viableCharges[1].flightTime
  1020. table.insert(mrsiSequence, viableCharges[1])
  1021.  
  1022. for i = 2, #viableCharges do
  1023. local delta = lastTime - viableCharges[i].flightTime
  1024. if delta >= 3 then -- allow a small lag, e.g., 4.0 not strict 4.5
  1025. table.insert(mrsiSequence, viableCharges[i])
  1026. lastTime = viableCharges[i].flightTime
  1027. end
  1028. end
  1029.  
  1030. for i, data in ipairs(mrsiSequence) do
  1031. print(string.format("Shot %d: %s | FlightTime: %.2f | Pitch: %.1f", i, data.charge, data.flightTime, data.pitch))
  1032. end
  1033. while deltaYaw > 5 do
  1034. sleep(0.1)
  1035. end
  1036. -- For each charge, aim and fire sequentially
  1037. local lastFlightTime = mrsiSequence[1].flightTime
  1038. parallel.waitForAny(
  1039. function()
  1040. for i, data in ipairs(mrsiSequence) do
  1041. -- Update target info and aim
  1042. pullItemByDisplayName(data.charge) -- load round
  1043. sleep(0.9) -- wait for reload
  1044. local delay = math.sqrt(lastFlightTime - data.flightTime -4) -- how long to wait before firing
  1045. lastFlightTime = data.flightTime
  1046. if delay > 0 then
  1047. print(string.format("Waiting %.2f s to fire %s", delay, data.charge))
  1048. sleep(delay)
  1049. end
  1050. lockedTargetInfo = updateTargetInfo(lockedTarget)
  1051. currentPosition = ship.getWorldspacePosition()
  1052. local dx = lockedTargetInfo.pos.x - currentPosition.x
  1053. local dy = lockedTargetInfo.pos.y - currentPosition.y
  1054. local dz = lockedTargetInfo.pos.z - currentPosition.z
  1055. local horizontalDistance = math.sqrt(dx * dx + dz * dz)
  1056. local pitch = math.deg(math.atan2(dy, horizontalDistance))
  1057. local yaw = math.deg(math.atan2(-dx, dz))
  1058. if data.pitch < 30 then
  1059. pitch = pitch + findBestPitch(lockedTargetInfo.pos, currentPosition, data.speed, g, cd, c_est, "direct")
  1060. else
  1061. pitch = findBestPitch(lockedTargetInfo.pos, currentPosition, data.speed, g, cd, c_est, "indirect")
  1062. end
  1063.  
  1064. yaw = (yaw + 180) % 360
  1065. local currentYaw = math.deg(getYaw())
  1066. if currentYaw < 0 then currentYaw = currentYaw + 360 end
  1067. local deltaYaw = yaw - currentYaw
  1068. if deltaYaw > 180 then
  1069. deltaYaw = deltaYaw - 360
  1070. elseif deltaYaw < -180 then
  1071. deltaYaw = deltaYaw + 360
  1072. end
  1073. print(string.format("Firing %s | Pitch: %.2f | Yaw: %.2f", data.charge, pitch, yaw))
  1074. requiredRelativeYaw, requiredRelativePitch = findRelativeAngle(yaw, pitch)
  1075. sleep(0.3)
  1076. -- Fire
  1077. for _, cannon in pairs(cannons) do
  1078. cannon.fire()
  1079. end
  1080. sleep(0.5)
  1081. for _, cannon in pairs(cannons) do
  1082. cannon.fire()
  1083. end
  1084. sleep(2.5)
  1085. end
  1086. end,
  1087. function()
  1088. while true do
  1089. for index, cannon in pairs(cannons) do
  1090. --cannon.fire()
  1091. end
  1092. sleep(0.1)
  1093. end
  1094. end
  1095. )
  1096. end
  1097.  
  1098. local function aimCannonContinuous()
  1099. while true do
  1100. if lockedTarget.lockMode then
  1101. local lockedTargetInfo = updateTargetInfo(lockedTarget)
  1102. if lockedTarget.lockMode == "direct" or lockedTarget.lockMode == "indirect" then
  1103. aimSimpleFire(lockedTargetInfo)
  1104. elseif lockedTarget.lockMode == "MRSI" then
  1105. --Lock yaw
  1106. -- Calculate yaw
  1107. local currentPosition = ship.getWorldspacePosition()
  1108. local yaw = math.deg(math.atan2(-(lockedTargetInfo.pos.x - currentPosition.x), lockedTargetInfo.pos.z - currentPosition.z))
  1109. yaw = (yaw + 180) % 360
  1110.  
  1111. -- Calculate requiredRelativeYaw/Pitch (these will be applied by setPitchYaw loop)
  1112. local currentYaw = math.deg(getYaw())
  1113. if currentYaw < 0 then currentYaw = currentYaw + 360 end
  1114.  
  1115. deltaYaw = yaw - currentYaw
  1116. if deltaYaw > 180 then
  1117. deltaYaw = deltaYaw - 360
  1118. elseif deltaYaw < -180 then
  1119. deltaYaw = deltaYaw + 360
  1120. end
  1121. yawControl(deltaYaw, currentYaw)
  1122. end
  1123. end
  1124. sleep()
  1125. end
  1126. end
  1127.  
  1128. local function handleTouch()
  1129. local w, h = monitor.getSize()
  1130. while true do
  1131. local event, side, x, y = os.pullEvent("monitor_touch")
  1132. if displayState == "radar" then
  1133. if y == h-1 and x >= 8 and x <= 9 then
  1134. radarScale = math.max(100, radarScale - 100)
  1135. drawControls()
  1136. drawRadarDisplay()
  1137. elseif y == h-1 and x >= 10 and x <= 11 then
  1138. radarScale = math.min(10000, radarScale + 100)
  1139. drawControls()
  1140. drawRadarDisplay()
  1141. elseif y == h-1 and x >= w-10 and x <= w then
  1142. displayState = "waypoints"
  1143. monitor.clear()
  1144. drawWaypointPage()
  1145.  
  1146. print("Enter waypoint coordinates (x, y, z, color), color options: red, yellow, green, blue (or leave blank for random):")
  1147. local input = read()
  1148.  
  1149. -- Parse input with better error handling
  1150. local x, y, z, color = input:match("([^,]+),([^,]+),([^,]+),?([^,]*)")
  1151.  
  1152. -- Trim whitespace from all values
  1153. x = x and x:match("^%s*(.-)%s*$")
  1154. y = y and y:match("^%s*(.-)%s*$")
  1155. z = z and z:match("^%s*(.-)%s*$")
  1156. color = color and color:match("^%s*(.-)%s*$")
  1157.  
  1158. -- Color handling with random fallback
  1159. local colorMap = {
  1160. red = colors.red,
  1161. yellow = colors.yellow,
  1162. green = colors.green,
  1163. blue = colors.blue,
  1164. white = colors.white,
  1165. orange = colors.orange,
  1166. lightBlue = colors.lightBlue,
  1167. lime = colors.lime,
  1168. pink = colors.pink,
  1169. gray = colors.gray,
  1170. lightGray = colors.lightGray,
  1171. cyan = colors.cyan,
  1172. purple = colors.purple,
  1173. brown = colors.brown,
  1174. black = colors.black
  1175. }
  1176.  
  1177. local colorValue
  1178. if not color or color == "" then
  1179. -- Generate random color from available options
  1180. local colorKeys = {}
  1181. for k in pairs(colorMap) do table.insert(colorKeys, k) end
  1182. local randomColor = colorKeys[math.random(#colorKeys)]
  1183. colorValue = colorMap[randomColor]
  1184. print("Assigned random color: "..randomColor)
  1185. else
  1186. colorValue = colorMap[color:lower()] or colors.yellow -- Default to yellow if invalid color
  1187. end
  1188.  
  1189. -- Validate coordinates
  1190. if x and y and z then
  1191. x, y, z = tonumber(x), tonumber(y), tonumber(z)
  1192. if x and y and z then
  1193. addWaypoint(x, y, z, colorValue)
  1194. else
  1195. print("Error: Invalid coordinates")
  1196. end
  1197. else
  1198. print("Error: Missing coordinates")
  1199. end
  1200.  
  1201. -- Return to radar view
  1202. displayState = "radar"
  1203. monitor.clear()
  1204. drawControls()
  1205. drawRadarDisplay()
  1206. elseif y == 1 and x >= w-13 and x <= w then
  1207. displayState = "adjustCannon"
  1208. monitor.clear()
  1209. drawCannonAdjustmentPage()
  1210. elseif y == h-2 and x < 10 then
  1211. lockedTarget = {pos = {x = nil, y = nil, z = nil}, velocity = {x = nil, y = nil, z = nil}, type = nil, lockMode = nil}
  1212. monitor.setCursorPos(1, 1)
  1213. monitor.clear()
  1214. drawRadarDisplay()
  1215. monitor.write("Locking stopped.")
  1216. elseif y == h-3 and x < 13 then
  1217. if lockedTarget.lockMode == "indirect" or lockedTarget.lockMode == "direct" then
  1218. firing(charge)
  1219. monitor.setCursorPos(1, 1)
  1220. monitor.write("Firing!")
  1221. elseif lockedTarget.lockMode == "MRSI" then
  1222. aimMRSIFire(lockedTarget)
  1223. end
  1224. else
  1225. for _, target in ipairs(targetPositions) do
  1226. if x == target.x and y == target.y then
  1227. selectedTarget = target.data
  1228. displayState = "targetInfo"
  1229. displayTargetInfo(selectedTarget)
  1230. break
  1231. end
  1232. end
  1233. end
  1234. elseif displayState == "targetInfo" then
  1235. if y == h and x >= 1 and x <= 4 then
  1236. -- Back button
  1237. displayState = "radar"
  1238. monitor.clear()
  1239. drawRadarDisplay()
  1240. elseif y == h-5 and x >= 1 and x <= 10 then
  1241. -- Lock with direct fire mode
  1242. lockedTarget = selectedTarget
  1243. lockedTarget.lockMode = "direct"
  1244. displayState = "radar"
  1245. monitor.clear()
  1246. drawRadarDisplay()
  1247. monitor.setCursorPos(1, 1)
  1248. monitor.write("Target locked: " .. (selectedTarget.type == "waypoint" and "Waypoint" or selectedTarget.id))
  1249. elseif y == h-4 and x >= 1 and x <= 18 then
  1250. -- Lock with indirect fire mode
  1251. lockedTarget = selectedTarget
  1252. lockedTarget.lockMode = "indirect"
  1253. displayState = "radar"
  1254. monitor.clear()
  1255. drawRadarDisplay()
  1256. monitor.setCursorPos(1, 1)
  1257. monitor.write("Target locked: " .. (selectedTarget.type == "waypoint" and "Waypoint" or selectedTarget.id))
  1258. elseif y == h-3 and x >= 1 and x <= 10 then
  1259. -- Lock with MIRS mode
  1260. lockedTarget = selectedTarget
  1261. lockedTarget.lockMode = "MRSI"
  1262. displayState = "radar"
  1263. monitor.clear()
  1264. drawRadarDisplay()
  1265. monitor.setCursorPos(1, 1)
  1266. monitor.write("Target locked: " .. (selectedTarget.type == "waypoint" and "Waypoint" or selectedTarget.id))
  1267. elseif selectedTarget.type == "waypoint" and y == h-2 and x>=1 and x <= 17 then
  1268. --delete waypoint
  1269. deleteWaypointByPos(selectedTarget.x,selectedTarget.y,selectedTarget.z)
  1270. drawRadarDisplay()
  1271. displayState = "radar"
  1272. monitor.setCursorPos(1, 1)
  1273. monitor.write("Deleted")
  1274. end
  1275. elseif displayState == "adjustCannon" then
  1276. -- Back button
  1277. if y == h and x >= 1 and x <= 4 then
  1278. displayState = "radar"
  1279. monitor.clear()
  1280. drawRadarDisplay()
  1281. elseif y == 3 and x>= 9 and x <= 11 then
  1282. --decrease spreadConstant
  1283. spreadConstant = spreadConstant - 0.1
  1284. elseif y == 3 and x>=15 and x <= 18 then
  1285. --increase spreadConstant
  1286. spreadConstant = spreadConstant + 0.1
  1287. elseif (y == 1 and x <= w-5 and x >= w - 12) or (y == 2 and x <= w-5 and x >= w - 12) or (y == 3 and x <= w-5 and x >= w - 12)then
  1288. -- increase pitch
  1289. requiredRelativePitch = requiredRelativePitch + 2
  1290. for index, cannon in pairs(cannons) do
  1291. cannon.setPitch(requiredRelativePitch)
  1292. end
  1293. elseif (y == 7 and x <= w-5 and x >= w - 12) or (y == 8 and x <= w-5 and x >= w - 12) or (y == 9 and x <= w-5 and x >= w - 12)then
  1294. -- decrease pitch
  1295. requiredRelativePitch = requiredRelativePitch - 2
  1296. for index, cannon in pairs(cannons) do
  1297. cannon.setPitch(requiredRelativePitch)
  1298. end
  1299. elseif y == 5 and x == w-8 then
  1300. requiredRelativePitch = 0
  1301. for index, cannon in pairs(cannons) do
  1302. cannon.setPitch(requiredRelativePitch)
  1303. end
  1304. elseif (y==4 and x <= w-1 and x>=w-8) or (y==5 and x <= w-1 and x>=w-8) or (y==6 and x <= w-1 and x>=w-8) then
  1305. --turn right
  1306. yawMotor.setTargetSpeed(-8)
  1307. sleep(0.1)
  1308. yawMotor.setTargetSpeed(0)
  1309. elseif (y==4 and x <= w-13 and x>=w-20) or (y==5 and x <= w-13 and x>=w-20) or (y==6 and x <= w-13 and x>=w-20) then
  1310. --turn left
  1311. yawMotor.setTargetSpeed(8)
  1312. sleep(0.1)
  1313. yawMotor.setTargetSpeed(0)
  1314. elseif y == h-2 and x < 10 then
  1315. lockedTarget = {pos = {x = nil, y = nil, z = nil}, velocity = {x = nil, y = nil, z = nil}, type = nil, lockMode = nil}
  1316. monitor.setCursorPos(1, 2)
  1317. monitor.clear()
  1318. monitor.write("Locking stopped.")
  1319. elseif y == h-3 and x < 10 then
  1320. firing("4Charge")
  1321. monitor.setCursorPos(1, 2)
  1322. monitor.write("Firing!")
  1323. end
  1324. end
  1325. end
  1326. end
  1327.  
  1328. local newExternalWaypoint = nil
  1329. local function modemMessage()
  1330. while true do
  1331. if modem then
  1332. local event, side, channel, replyChannel, message, distance = os.pullEvent("modem_message")
  1333. if channel == port5inchChannel then
  1334. cannonData.port5inch.hitPosX = message.x
  1335. cannonData.port5inch.hitPosY = message.y
  1336. cannonData.port5inch.hitPosZ = message.z
  1337. cannonData.port5inch.pitch = message.cannonPitch
  1338. cannonData.port5inch.yaw = message.cannonYaw
  1339. cannonData.port5inch.source = message.source
  1340. elseif channel == starboard5inchChannel then
  1341. cannonData.starboard5inch.hitPosX = message.x
  1342. cannonData.starboard5inch.hitPosY = message.y
  1343. cannonData.starboard5inch.hitPosZ = message.z
  1344. cannonData.starboard5inch.pitch = message.cannonPitch
  1345. cannonData.starboard5inch.yaw = message.cannonYaw
  1346. cannonData.starboard5inch.source = message.source
  1347. elseif channel == bow15inchChannel then
  1348. cannonData.bow15inch.hitPosX = message.x
  1349. cannonData.bow15inch.hitPosY = message.y
  1350. cannonData.bow15inch.hitPosZ = message.z
  1351. cannonData.bow15inch.pitch = message.cannonPitch
  1352. cannonData.bow15inch.yaw = message.cannonYaw
  1353. cannonData.bow15inch.source = message.source
  1354. elseif channel == stern15inchChannel then
  1355. cannonData.stern15inch.hitPosX = message.x
  1356. cannonData.stern15inch.hitPosY = message.y
  1357. cannonData.stern15inch.hitPosZ = message.z
  1358. cannonData.stern15inch.pitch = message.cannonPitch
  1359. cannonData.stern15inch.yaw = message.cannonYaw
  1360. cannonData.stern15inch.source = message.source
  1361. elseif channel == missileInfoChannel then
  1362. immediateMissileInfo = message
  1363. elseif channel == waypointChannel then
  1364. newExternalWaypoint = message
  1365. print("newExternalWaypoin recieved")
  1366. end
  1367. else
  1368. sleep()
  1369. end
  1370. end
  1371. end
  1372.  
  1373. local function externalWaypointHandler()
  1374. while true do
  1375. if newExternalWaypoint then
  1376. print("Adding waypoint")
  1377. if newExternalWaypoint.x and newExternalWaypoint.y and newExternalWaypoint.z and newExternalWaypoint.color then
  1378. print(textutils.serialize(newExternalWaypoint))
  1379. addWaypoint(newExternalWaypoint.x,newExternalWaypoint.y,newExternalWaypoint.z,newExternalWaypoint.color)
  1380. newExternalWaypoint = nil
  1381. end
  1382. end
  1383. sleep()
  1384. end
  1385. end
  1386.  
  1387. local function missileWarning()
  1388. local previousPositions = {}
  1389. while true do
  1390. local objectList = radar.scanForEntities(600)
  1391. -- Initial scan to capture positions
  1392. local initialPositions = {}
  1393. local shipPos = ship.getWorldspacePosition()
  1394. for _, object in ipairs(objectList) do
  1395. if object and (object.entity_type == "entity.tallyho.ir_missile" or object.entity_type == "entity.smallarm.at_rocket") then
  1396. if object.pos then
  1397. initialPositions[object.entity_type .. table.concat(object.pos, ":")] = object.pos
  1398. print("missile detected")
  1399. end
  1400. end
  1401. end
  1402.  
  1403. sleep(0.1) -- Short delay to measure displacement
  1404.  
  1405. objectList = radar.scanForEntities(600) -- Second scan to calculate speed
  1406. local currentPositions = {}
  1407. for _, object in ipairs(objectList) do
  1408. if object and (object.entity_type == "entity.tallyho.ir_missile" or object.entity_type == "entity.smallarm.at_rocket") then
  1409. if object.pos then
  1410. print("Missile detected for second time")
  1411. local key = object.entity_type .. table.concat(object.pos, ":")
  1412. currentPositions[key] = object.pos
  1413. local previousPos = initialPositions[key]
  1414. previousPos = nil
  1415. if previousPos then
  1416. local speed = calculateSpeed(previousPos, object.pos, 0.1)
  1417. print(textutils.serialize(previousPos))
  1418. print(textutils.serialize(object.pos))
  1419. print("speed: "..speed)
  1420. if speed > 5 then -- Check if speed exceeds threshold
  1421. local objX, objY, objZ = object.pos[1], object.pos[2], object.pos[3]
  1422. local missileVector = {x = objX - previousPos[1], y = objY - previousPos[2], z = objZ - previousPos[3]}
  1423. local toPlayerVector = {x = shipPos.x - objX, y = shipPos.y - objY, z = shipPos.z - objZ}
  1424. local dotProduct = missileVector.x * toPlayerVector.x + missileVector.y * toPlayerVector.y + missileVector.z * toPlayerVector.z
  1425. print("Missile with speed > 10 detected")
  1426. if dotProduct then -- Missile is moving towards the player
  1427. print("Missile coming for player")
  1428. local angle = math.deg(math.atan2(missileVector.z, missileVector.x) - math.atan2(toPlayerVector.z, toPlayerVector.x))
  1429. local direction = ((angle + 360) % 360) / 30
  1430. local clockDirection = math.floor(direction + 1)
  1431. if clockDirection == 0 then clockDirection = 12 end
  1432. monitor.setCursorPos(0,6)
  1433. monitor.write("Missile incoming from " .. clockDirection .. " o'clock")
  1434. if speaker then
  1435. speaker.playSound("entity.lightning_bolt.thunder", 1.0)
  1436. end
  1437. end
  1438. end
  1439. end
  1440. end
  1441. end
  1442. end
  1443.  
  1444. previousPositions = currentPositions
  1445. sleep() -- Delay before the next round of scanning
  1446. end
  1447. end
  1448.  
  1449. local function broadCastWaypoint()
  1450. while true do
  1451. modem.transmit(waypointChannel,0,waypoints)
  1452. sleep(1)
  1453. end
  1454. end
  1455.  
  1456. local function controlsSending()
  1457. while true do
  1458. --modem.transmit(missileControlChannel,missileControlChannel,missileControls)
  1459. sleep()
  1460. end
  1461. end
  1462.  
  1463. local function missileListBuilding()
  1464. while true do
  1465. if immediateMissileInfo and immediateMissileInfo.id and immediateMissileInfo.type then
  1466. local foundMissile = false
  1467.  
  1468. -- Update the existing missile state instead of adding duplicates
  1469. for _, missileInfo in ipairs(AIMInfoList) do
  1470. if missileInfo.id == immediateMissileInfo.id then
  1471. missileInfo.launchState = immediateMissileInfo.launchState
  1472. foundMissile = true
  1473. break
  1474. end
  1475. end
  1476. for _, missileInfo in ipairs(GBUInfoList) do
  1477. if missileInfo.id == immediateMissileInfo.id then
  1478. missileInfo.launchState = immediateMissileInfo.launchState
  1479. foundMissile = true
  1480. break
  1481. end
  1482. end
  1483. for _, missileInfo in ipairs(thunderBoltInfoList) do
  1484. if missileInfo.id == immediateMissileInfo.id then
  1485. missileInfo.launchState = immediateMissileInfo.launchState
  1486. foundMissile = true
  1487. break
  1488. end
  1489. end
  1490.  
  1491. -- If it's a new missile, add it to the list
  1492. if not foundMissile then
  1493. if immediateMissileInfo.type == "AIM-220" then
  1494. table.insert(AIMInfoList, immediateMissileInfo)
  1495. elseif immediateMissileInfo.type == "GBU-42" then
  1496. table.insert(GBUInfoList, immediateMissileInfo)
  1497. elseif immediateMissileInfo.type == "thunderBolt" then
  1498. table.insert(thunderBoltInfoList, immediateMissileInfo)
  1499. end
  1500. end
  1501. end
  1502.  
  1503. -- Remove missiles that have launched
  1504. for i = #AIMInfoList, 1, -1 do
  1505. if AIMInfoList[i].launchState == true then
  1506. table.remove(AIMInfoList, i)
  1507. end
  1508. end
  1509. for i = #GBUInfoList, 1, -1 do
  1510. if GBUInfoList[i].launchState == true then
  1511. table.remove(GBUInfoList, i)
  1512. end
  1513. end
  1514. for i = #thunderBoltInfoList, 1, -1 do
  1515. if thunderBoltInfoList[i].launchState == true then
  1516. table.remove(thunderBoltInfoList, i)
  1517. end
  1518. end
  1519.  
  1520. -- Count unlaunched missiles
  1521. AIMCount, GBUCount, thunderboltCount = 0, 0, 0
  1522. for _, missileInfo in ipairs(AIMInfoList) do
  1523. if not missileInfo.launchState then
  1524. AIMCount = AIMCount + 1
  1525. end
  1526. end
  1527. for _, missileInfo in ipairs(GBUInfoList) do
  1528. if not missileInfo.launchState then
  1529. GBUCount = GBUCount + 1
  1530. end
  1531. end
  1532. for _, missileInfo in ipairs(thunderBoltInfoList) do
  1533. if not missileInfo.launchState then
  1534. thunderboltCount = thunderboltCount + 1
  1535. end
  1536. end
  1537. sleep()
  1538. end
  1539. end
  1540.  
  1541. local function printOutput()
  1542. while true do
  1543. if displayState == "radar" or displayState == "targetInfo" then
  1544. --print(textutils.serialize(lockedTarget))
  1545. --print(lockedTarget.lockMode)
  1546. --print("Yaw: "..requiredRelativeYaw.." Pitch: "..requiredRelativePitch)
  1547. end
  1548. sleep()
  1549. end
  1550. end
  1551.  
  1552. parallel.waitForAny(
  1553. function()
  1554. -- Main loop
  1555. while true do
  1556. if displayState == "radar" then
  1557. monitor.clear()
  1558. monitor.setTextScale(0.5)
  1559. drawRadarDisplay()
  1560. drawControls()
  1561. elseif displayState == "targetInfo" and selectedTarget then
  1562. displayTargetInfo(selectedTarget)
  1563. elseif displayState == "adjustCannon" then
  1564. monitor.clear()
  1565. drawCannonAdjustmentPage()
  1566. end
  1567. sleep(0.1)
  1568. -- Adjust this duration if needed
  1569. end
  1570. end,
  1571. handleTouch,
  1572. modemMessage,
  1573. missileWarning,
  1574. broadCastWaypoint,
  1575. missileListBuilding,
  1576. controlsSending,
  1577. printOutput,
  1578. aimCannonContinuous,
  1579. setPitchYaw,
  1580. externalWaypointHandler
  1581. )
Add Comment
Please, Sign In to add comment