MegiRicky

NGDWBVROnboard

Oct 11th, 2024 (edited)
644
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 21.66 KB | None | 0 0
  1. local modem = peripheral.wrap("right")
  2.  
  3. local cannons = {}
  4. local controls = {cannonControlMode = "mouseAim"}
  5. local targetInfo = {}
  6.  
  7. local k = 1
  8. local nilCount = 0
  9. local i = 0
  10. while nilCount < 200 do
  11. local cannon = peripheral.wrap("createbigcannons:cannon_mount_"..tostring(i))
  12. if not(cannon) then
  13. cannon = peripheral.wrap("cbcmodernwarfare:compact_mount_"..tostring(i))
  14. end
  15. if cannon then
  16. cannons[k] = cannon
  17. k = k + 1
  18. nilCount = 0
  19. print("found cannon")
  20. else
  21. nilCount = nilCount + 1
  22. end
  23. i = i + 1
  24. end
  25. print("Found "..#cannons.." cannons")
  26.  
  27. local function readFriendlyIDs(filename)
  28. if not fs.exists(filename) then
  29. print("Friendly IDs file '" .. filename .. "' does not exist. Creating it.")
  30. local file = fs.open(filename, "w")
  31. print("Input friendly IDs (player names) separated by commas:")
  32. local ids = io.read()
  33. file.write(ids)
  34. file.close()
  35. else
  36. print("Do you want to edit the friendly player id config? (yes/no),press enter to skip")
  37. local editChoice = io.read()
  38. if editChoice == "" then
  39. editChoice = "no"
  40. end
  41. if editChoice:lower() == "yes" then
  42. if fs.exists(filename) then
  43. fs.delete(filename)
  44. print("Friendly IDs file '" .. filename .. "' does not exist. Creating it.")
  45. local file = fs.open(filename, "w")
  46. print("Input friendly IDs (player names) separated by commas:")
  47. local ids = io.read()
  48. file.write(ids)
  49. file.close()
  50. end
  51. end
  52. end
  53.  
  54. local file = fs.open(filename, "r")
  55. local friendlyIDs = {}
  56. if file then
  57. local line = file.readLine()
  58. while line do
  59. print("Line read: " .. line) -- Debug print for the line
  60.  
  61. -- Split the line by commas and insert each name into the friendlyIDs table
  62. for name in string.gmatch(line, '([^,]+)') do
  63. print("Friendly ID (Name): " .. name) -- Debug print for each name
  64. table.insert(friendlyIDs, name) -- Store the player name
  65. end
  66. line = file.readLine() -- Read the next line
  67. end
  68. file.close()
  69. end
  70. return friendlyIDs
  71. end
  72.  
  73. -- Function to check if a player ID is friendly
  74. local function isFriendly(playerID)
  75. for _, friendlyID in ipairs(friendlyIDs) do
  76. if playerID == friendlyID then
  77. return true
  78. end
  79. end
  80. return false
  81. end
  82.  
  83. -- Read friendly IDs from the file
  84. local function saveSettingsToFile(filename, settings)
  85. local file = fs.open(filename, "w")
  86. if file then
  87. file.write(textutils.serialize(settings))
  88. file.close()
  89. print("Settings saved to '" .. filename .. "'")
  90. else
  91. print("Failed to save settings.")
  92. end
  93. end
  94.  
  95. local function loadSettingsFromFile(filename)
  96. if not fs.exists(filename) then
  97. return nil
  98. end
  99.  
  100. local file = fs.open(filename, "r")
  101. local settings = textutils.unserialize(file.readAll())
  102. file.close()
  103. return settings
  104. end
  105.  
  106. local function askForInput(prompt, defaultValue)
  107. print(prompt .. " (default: " .. defaultValue .. "):")
  108. local input = io.read()
  109. if input == "" then
  110. return defaultValue
  111. else
  112. return tonumber(input) or input
  113. end
  114. end
  115.  
  116. local function createSettings()
  117. local settings = {}
  118. settings.controlsChannel = askForInput("Input the controlChannel number",500)
  119. settings.cannonChannel = askForInput("Input the cannonChannel number",900)
  120. settings.projectileSpeed = askForInput("Input the muzzle velocity number", 344)
  121. settings.g = askForInput("Input the gravity acceleration per tick", 0.04)
  122. settings.cd = askForInput("Input the drag per tick", 0.99)
  123. settings.autoSpread = askForInput("Enable automatic spread, yes/no", "yes") == "yes"
  124. settings.useHighPitch = askForInput("Use high pitch?", "yes") == "yes"
  125. settings.lengthCorrection = askForInput("Enter cannon source ship length correction", 35)
  126. settings.heightCorrection = askForInput("Enter cannon source ship height correction", 5)
  127. settings.widthCorrection = askForInput("Enter the cannon source ship width correction, positive if the ship is at the right side",0)
  128. settings.limitor = askForInput("Enable pitch yaw limiter, yes/no", "no") == "no"
  129. settings.pitchLowerLimit = askForInput("Ignore the follwing if no limitr. Input the pitch lower limit, default: -10",-10)
  130. settings.pitchUpperLimit = askForInput("Input the pitch lower limit, default: 90",90)
  131. settings.yawLowerLimit = askForInput("Input the yaw lower limit, default: -120",-120)
  132. settings.yawUpperLimit = askForInput("Input the pitch lower limit, default: 120",120)
  133. return settings
  134. end
  135.  
  136. local function createPresetSettings()
  137. local presets = {
  138. {
  139. filename = "HX3SPA_settings.txt",
  140. settings = {
  141. controlsChannel = 500,
  142. cannonChannel = 900,
  143. projectileSpeed = 344,
  144. g = 0.04,
  145. cd = 0.99,
  146. autoSpread = true,
  147. useHighPitch = true,
  148. lengthCorrection = 0,
  149. heightCorrection = 2.5,
  150. widthCorrection = 3.5,
  151. limitor = false,
  152. pitchLowerLimit = -10,
  153. pitchUpperLimit = 90,
  154. yawLowerLimit = -150,
  155. yawUpperLimit = 0,
  156. }
  157. },
  158. {
  159. filename = "ussNJPort_settings.txt",
  160. settings = {
  161. controlsChannel = 500,
  162. cannonChannel = 900,
  163. projectileSpeed = 240,
  164. g = 0.05,
  165. cd = 0.995,
  166. autoSpread = true,
  167. useHighPitch = false,
  168. lengthCorrection = 0,
  169. heightCorrection = 1.5,
  170. widthCorrection = 0,
  171. limitor = false,
  172. pitchLowerLimit = -10,
  173. pitchUpperLimit = 90,
  174. yawLowerLimit = -150,
  175. yawUpperLimit = 0,
  176. }
  177. },
  178. {
  179. filename = "ussNJStarboard_settings.txt",
  180. settings = {
  181. controlsChannel = 500,
  182. cannonChannel = 901,
  183. projectileSpeed = 240,
  184. g = 0.05,
  185. cd = 0.995,
  186. autoSpread = true,
  187. useHighPitch = false,
  188. lengthCorrection = 0,
  189. heightCorrection = 1.5,
  190. widthCorrection = 0,
  191. limitor = false,
  192. pitchLowerLimit = -10,
  193. pitchUpperLimit = 90,
  194. yawLowerLimit = -150,
  195. yawUpperLimit = 0,
  196. }
  197. },
  198. {
  199. filename = "IJNSKAutocannon_settings.txt",
  200. settings = {
  201. controlsChannel = 500,
  202. cannonChannel = 900,
  203. projectileSpeed = 240,
  204. g = 0.025,
  205. cd = 0.99,
  206. autoSpread = true,
  207. useHighPitch = false,
  208. lengthCorrection = 0,
  209. heightCorrection = 6,
  210. widthCorrection = 0,
  211. limitor = false,
  212. pitchLowerLimit = -10,
  213. pitchUpperLimit = 90,
  214. yawLowerLimit = -150,
  215. yawUpperLimit = 0,
  216. }
  217. },
  218. }
  219.  
  220. for _, preset in ipairs(presets) do
  221. if true then
  222. saveSettingsToFile(preset.filename, preset.settings)
  223. print("Created preset settings: " .. preset.filename)
  224. end
  225. end
  226. end
  227.  
  228. local function handleSettings()
  229. print("Checking for existing settings...")
  230. createPresetSettings()
  231.  
  232. -- List available settings
  233. local settingsFiles = fs.list("/")
  234. local settingsFilesFound = false
  235. local settingsFilesList = {}
  236.  
  237. for _, file in ipairs(settingsFiles) do
  238. if string.match(file, "_settings.txt") then
  239. table.insert(settingsFilesList, file)
  240. settingsFilesFound = true
  241. end
  242. end
  243.  
  244. if not settingsFilesFound then
  245. print("No settings found. Please create a new one.")
  246. local filename = askForInput("Enter a name for the new settings file", "example_settings.txt")
  247. local settings = createSettings()
  248. saveSettingsToFile(filename, settings)
  249. return settings
  250. else
  251. print("Available settings:")
  252.  
  253. local pageSize = 10 -- Number of settings to display per page
  254. local totalFiles = #settingsFilesList
  255. local currentPage = 1
  256. local totalPages = math.ceil(totalFiles / pageSize)
  257.  
  258. while currentPage <= totalPages do
  259. local startIdx = (currentPage - 1) * pageSize + 1
  260. local endIdx = math.min(startIdx + pageSize - 1, totalFiles)
  261.  
  262. -- Display a batch of settings files
  263. for i = startIdx, endIdx do
  264. print(i .. ". " .. settingsFilesList[i])
  265. end
  266.  
  267. if currentPage < totalPages then
  268. print("\nPress Enter to see more settings...")
  269. io.read() -- Wait for the user to press Enter
  270. end
  271.  
  272. currentPage = currentPage + 1
  273. end
  274.  
  275. local selection = askForInput("Select an existing setting to load or create a new one (1-" .. totalFiles .. " or new)", "new")
  276.  
  277. if selection == "new" then
  278. local filename = askForInput("Enter a name for the new settings file", "settings.txt")
  279. local settings = createSettings()
  280. saveSettingsToFile(filename, settings)
  281. return settings
  282. else
  283. local filename = settingsFilesList[tonumber(selection)]
  284. local settings = loadSettingsFromFile(filename)
  285. print("Loaded settings from '" .. filename .. "'")
  286.  
  287. local editChoice = askForInput("Do you want to edit this setting? (yes/no)", "no")
  288. if editChoice == "yes" then
  289. local newSettings = createSettings()
  290. saveSettingsToFile(filename, newSettings)
  291. return newSettings
  292. else
  293. return settings
  294. end
  295. end
  296. end
  297. end
  298.  
  299. -- Main execution
  300. local settings = handleSettings()
  301.  
  302. print("Using settings:")
  303. print(textutils.serialize(settings))
  304. sleep(0.2)
  305.  
  306. print(settings.cannonChannel)
  307.  
  308. if modem then
  309. modem.open(tonumber(settings.cannonChannel))
  310. modem.open(tonumber(settings.controlsChannel))
  311. end
  312.  
  313. -- Normalize a vector
  314. local function normalizeVector(v)
  315. local length = math.sqrt(v[1]^2 + v[2]^2 + v[3]^2)
  316. if length == 0 then
  317. return {0, 0, 0}
  318. end
  319. return {v[1] / length, v[2] / length, v[3] / length}
  320. end
  321.  
  322. -- Normalize the rotation matrix
  323. local function normalizeRotationMatrix(rotMatrix)
  324. local normalizedMatrix = {}
  325. for i = 1, #rotMatrix do
  326. normalizedMatrix[i] = normalizeVector(rotMatrix[i])
  327. end
  328. return normalizedMatrix
  329. end
  330.  
  331. -- Get the pitch of the ship
  332. local function getPitch()
  333. local rotMatrix = ship.getTransformationMatrix()
  334. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  335. return math.asin(normalizedMatrix[2][3]) -- Extract pitch from the matrix
  336. end
  337. --pitch = math.deg(math.asin(ship.getTransformationMatrix()[2][3]))
  338. -- Get the yaw of the ship
  339. local function getYaw()
  340. local rotMatrix = ship.getTransformationMatrix()
  341. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  342. return math.atan2(-normalizedMatrix[3][1], -normalizedMatrix[3][3]) -- Extract yaw from the matrix
  343. end
  344.  
  345. -- Get the roll of the ship
  346. local function getRoll()
  347. local rotMatrix = ship.getTransformationMatrix()
  348. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  349. return math.atan2(normalizedMatrix[2][1], normalizedMatrix[2][2]) -- Extract roll from the matrix
  350. end
  351.  
  352. local function setPitchYaw(targetPitch, targetYaw)
  353. local tasks = {} -- Table to store each cannon's task
  354.  
  355. for index, cannon in pairs(cannons) do
  356. -- Define the function for this cannon's pitch/yaw adjustment
  357. local function adjustCannon()
  358. if index == 1 then
  359. -- No spread for the first cannon
  360. cannon.setPitch(targetPitch)
  361. cannon.setYaw(targetYaw)
  362. print("Cannon " .. index .. " (Primary) set to pitch: " .. targetPitch .. " and yaw: " .. targetYaw)
  363. else
  364. -- Spread logic for other cannons
  365. local spreadConstant
  366. if targetPitch < 30 then
  367. spreadConstant = 0.5
  368. else
  369. spreadConstant = 0.5
  370. end
  371.  
  372. local pitchVariation = math.random(-2, 2) * spreadConstant -- Adjust the range to control the spread
  373. local yawVariation = math.random(-2, 2) * spreadConstant -- Adjust the range to control the spread
  374.  
  375. local adjustedPitch = targetPitch + pitchVariation
  376. local adjustedYaw = targetYaw + yawVariation
  377.  
  378. if settings.autoSpread then
  379. cannon.setPitch(adjustedPitch)
  380. cannon.setYaw(adjustedYaw)
  381. print("Cannon " .. index .. " set to pitch: " .. adjustedPitch .. " and yaw: " .. adjustedYaw)
  382. else
  383. cannon.setPitch(targetPitch)
  384. cannon.setYaw(targetYaw)
  385. print("Cannon " .. index .. " set to uniform pitch: " .. targetPitch .. " and yaw: " .. targetYaw)
  386. end
  387. end
  388. end
  389.  
  390. -- Add this task to the tasks table
  391. table.insert(tasks, adjustCannon)
  392. end
  393.  
  394. -- Execute all tasks in parallel
  395. parallel.waitForAll(table.unpack(tasks))
  396. end
  397.  
  398. local function findRelativeAngle(targetYaw,targetPitch)
  399. rot = ship.getQuaternion()
  400. cacheYaw = math.pi - math.rad(targetYaw)
  401. cachePitch = - math.rad(targetPitch)
  402. rotMatAdj11 = 1 - 2*(rot.x^2 + rot.y^2)
  403. rotMatAdj12 = 2*(rot.z * rot.x + rot.y * rot.w)
  404. rotMatAdj13 = 2*(rot.z * rot.y - rot.x * rot.w)
  405. rotMatAdj21 = 2*(rot.z * rot.x - rot.y * rot.w)
  406. rotMatAdj22 = 1 - 2*(rot.z^2 + rot.y^2)
  407. rotMatAdj23 = 2*(rot.x * rot.y + rot.z * rot.w)
  408. rotMatAdj31 = 2*(rot.z * rot.y + rot.x * rot.w)
  409. rotMatAdj32 = 2*(rot.x * rot.y - rot.z * rot.w)
  410. rotMatAdj33 = 1 - 2*(rot.z^2 + rot.x^2)
  411.  
  412. rotMatTGT11 = math.cos(cacheYaw) * math.cos(cachePitch)
  413. rotMatTGT21 = math.sin(cacheYaw) * math.cos(cachePitch)
  414. rotMatTGT31 = - math.sin(cachePitch)
  415.  
  416. rotMatRSLT11 = rotMatAdj11 * rotMatTGT11 + rotMatAdj12 * rotMatTGT21 + rotMatAdj13 * rotMatTGT31
  417. rotMatRSLT21 = rotMatAdj21 * rotMatTGT11 + rotMatAdj22 * rotMatTGT21 + rotMatAdj23 * rotMatTGT31
  418. rotMatRSLT31 = rotMatAdj31 * rotMatTGT11 + rotMatAdj32 * rotMatTGT21 + rotMatAdj33 * rotMatTGT31
  419.  
  420. turretYaw = math.atan2(rotMatRSLT21, rotMatRSLT11)
  421. barrelPitch = math.asin(-rotMatRSLT31)
  422. return math.deg(-turretYaw),math.deg(-barrelPitch)
  423. end
  424.  
  425. local function calculateRange(angle, u, cd, g, c_est, projectileSpeed)
  426.  
  427. local radians = math.rad(angle)
  428. local u = projectileSpeed/20
  429. local part1 = u * math.cos(radians) / math.log(cd)
  430.  
  431. local part2 = ((g * cd) / (g * cd + (1 - cd) * u * math.sin(radians))) ^ (2 + c_est * projectileSpeed * math.sin(radians)) - 1
  432.  
  433. local XR = part1 * part2
  434.  
  435. return XR
  436. end
  437.  
  438. local function findBestPitch(targetX, targetY, targetZ, sourceX, sourceY, sourceZ, initialVelocity, g, cd, c_est, projectileSpeed)
  439. local bestLowPitch = nil
  440. local bestHighPitch = nil
  441. local bestLowDistance = math.huge
  442. local bestHighDistance = math.huge
  443. local targetDistance = math.sqrt((targetX - sourceX)^2 + (targetZ - sourceZ)^2)
  444.  
  445. for pitch = 0, 65, 0.01 do -- Iterate over pitch angles
  446. local calculatedRange = calculateRange(pitch, initialVelocity, settings.cd, settings.g, c_est, settings.projectileSpeed)
  447. local distanceDifference = math.abs(calculatedRange - targetDistance)
  448.  
  449. -- Find the low-angle solution
  450. if pitch <= 30 then
  451. if distanceDifference < bestLowDistance then
  452. bestLowDistance = distanceDifference
  453. bestLowPitch = pitch
  454. end
  455. -- Find the high-angle solution
  456. elseif pitch > 30 then
  457. if distanceDifference < bestHighDistance then
  458. bestHighDistance = distanceDifference
  459. bestHighPitch = pitch
  460. end
  461. end
  462. end
  463.  
  464. -- Prioritize the high-angle solution if the range difference is smaller than 5
  465. if settings.useHighPitch and bestHighPitch and bestHighDistance < 2 then
  466. return bestHighPitch
  467. else
  468. return bestLowPitch
  469. end
  470.  
  471. -- Fallback to bestLowPitch if bestHighPitch is not suitable
  472. end
  473.  
  474. local function aimCannon(targetPos, targetVel, sourceX, sourceY, sourceZ)
  475. if sourceX and sourceY and sourceZ then
  476. local dx = targetPos.x - sourceX
  477. local dy = targetPos.y - sourceY
  478. local dz = targetPos.z - sourceZ
  479. local distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  480.  
  481. local estimateTime = distance / (settings.projectileSpeed)
  482. local estimateX = targetPos.x + targetVel.x * estimateTime
  483. local estimateY = targetPos.y + targetVel.y * estimateTime
  484. local estimateZ = targetPos.z + targetVel.z * estimateTime
  485.  
  486. local dx = estimateX - sourceX
  487. local dy = estimateY - sourceY
  488. local dz = estimateZ - sourceZ
  489.  
  490. local horizontalDistance = math.sqrt(dx * dx + dz * dz)
  491. local pitch = math.deg(math.atan2(dy, horizontalDistance))
  492.  
  493. local yaw = math.deg(math.atan2(-dx, dz))
  494. yaw = (yaw + 180) % 360 -- normalize yaw
  495. balisticPitch = findBestPitch(estimateX, estimateY, estimateZ, sourceX, sourceY, sourceZ, settings.projectileSpeed, settings.g, settings.cd, 0.0028, settings.projectileSpeed)
  496. if balisticPitch > 30 then
  497. pitch = balisticPitch
  498. else
  499. pitch = pitch + balisticPitch
  500. end
  501.  
  502. local requiredRelativeYaw,requiredRelativePitch = findRelativeAngle(yaw,pitch)
  503. if pitchLimit then
  504. setPitchYaw(math.min(requiredRelativePitch,pitchUpperLimit),requiredRelativeYaw)
  505. else
  506. setPitchYaw(requiredRelativePitch,requiredRelativeYaw)
  507. end
  508. end
  509. end
  510.  
  511. local function manualCannonControl()
  512. while true do
  513. if controls.cannonControlMode == "manual" then
  514. if controls then
  515. local pitch = cannons[1].getPitch()
  516. local yaw = cannons[1].getYaw()
  517. -- Control yaw and pitch manually with arrow keys
  518. if controls.cannonUp then
  519. -- Increase pitch
  520. setPitchYaw(pitch + 2, yaw)
  521. elseif controls.cannonDown then
  522. -- Decrease pitch
  523. setPitchYaw(pitch - 2, yaw)
  524. else
  525.  
  526. end
  527. if controls.cannonLeft then
  528. -- Turn left
  529. setPitchYaw(pitch, yaw - 2)
  530. elseif controls.cannonRight then
  531. -- Turn right
  532. setPitchYaw(pitch, yaw + 2)
  533. else
  534.  
  535. end
  536. else
  537.  
  538. end
  539. sleep()
  540. else
  541. sleep() -- Sleep for a short time if not in manual mode
  542. end
  543. end
  544. end
  545.  
  546. local function firing()
  547. while true do
  548. if controls then
  549. if controls.fireCannon then
  550. local fireTasks = {} -- Table to store firing tasks
  551.  
  552. -- Add each cannon's fire task to the table
  553. for index, cannon in pairs(cannons) do
  554. table.insert(fireTasks, function()
  555. cannon.fire()
  556. print("Cannon " .. index .. " FIRING")
  557. end)
  558. end
  559.  
  560. -- Execute all tasks simultaneously
  561. parallel.waitForAll(table.unpack(fireTasks))
  562.  
  563. redstone.setOutput("top", true)
  564. sleep(0.1)
  565. redstone.setOutput("top", false)
  566. else
  567. redstone.setOutput("top", false)
  568. end
  569. end
  570. sleep()
  571. end
  572. end
  573.  
  574. local function modemMessage()
  575. while true do
  576. if modem then
  577. local event, side, channel, replyChannel, message, distance = os.pullEvent("modem_message")
  578. if channel == settings.cannonChannel then
  579. targetInfo = message
  580. elseif channel == settings.controlsChannel then
  581. controls = message
  582. end
  583. else
  584. sleep()
  585. end
  586. end
  587. end
  588.  
  589. local function main()
  590. while true do
  591. local source = ship.getWorldspacePosition()
  592. local sourceX = source.x + settings.lengthCorrection * math.cos(getYaw() - math.pi/2) + settings.widthCorrection * math.cos(getYaw())
  593. local sourceY = source.y + settings.heightCorrection
  594. local sourceZ = source.z + settings.lengthCorrection * math.sin(getYaw() - math.pi/2) + settings.widthCorrection * math.sin(getYaw())
  595. if targetInfo and targetInfo.targetPos and targetInfo.targetVel and controls.cannonControlMode == "mouseAim" then
  596. aimCannon(targetInfo.targetPos,targetInfo.targetVel,sourceX,sourceY,sourceZ)
  597. end
  598. sleep()
  599. end
  600. end
  601.  
  602. parallel.waitForAny(
  603. manualCannonControl,
  604. modemMessage,
  605. firing,
  606. main
  607. )
  608.  
Advertisement
Add Comment
Please, Sign In to add comment