system.lua 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  1. MAX_INVENTORY_SLOTS = 320
  2. MAX_KEY_SLOTS = 50
  3. MAX_MATERIA_SLOTS = 200
  4. --- System related parameters and utilities
  5. System = {
  6. --- Indicates if the game is paused.
  7. paused = false,
  8. --- Indicates if the menu was available when paused.
  9. paused_menu_settings_available = false,
  10. --- Pauses the game.
  11. pause = function(self)
  12. if MenuSettings.pause_available == false then
  13. do return end
  14. end
  15. if self.paused == false then
  16. self.paused = true
  17. entity_manager:set_paused(true)
  18. self.paused_menu_settings_available = MenuSettings.available
  19. MenuSettings.available = false
  20. audio_manager:play_sound("Cursor")
  21. UiContainer.PauseMenu:show()
  22. end
  23. end,
  24. --- Unpauses the game.
  25. unpause = function(self)
  26. if self.paused == true then
  27. self.paused = false
  28. entity_manager:set_paused(false)
  29. MenuSettings.available = self.paused_menu_settings_available
  30. audio_manager:play_sound("Cursor")
  31. UiContainer.PauseMenu:hide()
  32. end
  33. end,
  34. --- Checks if the game is paused.
  35. --
  36. -- @return True if the game is paused, false if not.
  37. is_paused = function(self)
  38. return self.paused
  39. end
  40. }
  41. --- Stands for the model of the script entities that have none: the opcodes that move or hide a
  42. -- model are run by them in the original game and do nothing. Any method called on it is ignored.
  43. NullEntity = setmetatable({}, {__index = function() return function() end end})
  44. Timer = {
  45. -- TODO When the game clock is implemented, dont use FPS, call this every second.
  46. FPS = 250,
  47. time = 0,
  48. frames = 0,
  49. update = function()
  50. if Timer.time > 0 or Timer.frames > 0 then
  51. Timer.frames = Timer.frames - 1
  52. if Timer.frames == 0 then
  53. Timer.time = Timer.time - 1
  54. dialog:update_timer(Timer.time)
  55. if Timer.time > 0 then
  56. Timer.frames = Timer.FPS
  57. end
  58. Banks[1][20]--[[timer_hours]] = math.floor(Timer.time / 3600)
  59. Banks[1][21]--[[timer_minutes]] = math.floor(Timer.time / 60) % 60
  60. Banks[1][22]--[[timer_seconds]] = Timer.time % 60
  61. end
  62. Banks[1][23]--[[timer_frames]] = Timer.frames
  63. end
  64. end,
  65. set = function(time)
  66. Timer.time = tonumber(time)
  67. Timer.frames = Timer.FPS
  68. dialog:update_timer(Timer.time)
  69. Banks[1][20]--[[timer_hours]] = math.floor(Timer.time / 3600)
  70. Banks[1][21]--[[timer_minutes]] = math.floor(Timer.time / 60) % 60
  71. Banks[1][22]--[[timer_seconds]] = Timer.time % 60
  72. Banks[1][23]--[[timer_frames]] = Timer.frames
  73. end
  74. }
  75. --- Export character names to the text manager.
  76. --
  77. -- Used to compose dialog with character names. Must be called on start and when a character is
  78. -- renamed.
  79. export_character_names = function()
  80. for c = 0, 8 do
  81. if Characters[c] ~= nil then
  82. text_manager:set_character_name(c, Characters[c].name)
  83. end
  84. end
  85. end
  86. --- Export party members to the text manager.
  87. --
  88. -- Used to compose dialog with party character names. Must be called when the party formation is
  89. -- changed in any way.
  90. export_party_members = function()
  91. if Party[1] == nil then
  92. c1 = -1
  93. else
  94. c1 = Party[1]
  95. end
  96. if Party[2] == nil then
  97. c2 = -1
  98. else
  99. c2 = Party[2]
  100. end
  101. if Party[3] == nil then
  102. c3 = -1
  103. else
  104. c3 = Party[3]
  105. end
  106. text_manager:set_party(c1, c2, c3)
  107. end
  108. --- Restores the HP and MP of every character, also the ones that are not in the party, and clears
  109. -- their status (MHMMX).
  110. restore_all_characters = function()
  111. for id, character in pairs(Characters) do
  112. if type(id) == "number" and type(character) == "table" and character.stats ~= nil
  113. and character.stats.hp ~= nil and character.stats.mp ~= nil then
  114. Characters.recalculate_stats(id)
  115. character.stats.hp.current = character.stats.hp.max
  116. character.stats.mp.current = character.stats.mp.max
  117. character.status = {}
  118. end
  119. end
  120. end
  121. --- Sets the current party.
  122. --
  123. -- This is what the scripts do (PRTYE and the party selection), so the first character also becomes
  124. -- the leader of the field: the character the player controls (see Party.get_leader). Changing the
  125. -- order of the party in the menus does not change the leader, so they pass `keep_leader`.
  126. --
  127. -- @param character1 The first member character ID, the party leader.
  128. -- @param character2 The second member character ID, can be nil.
  129. -- @param character3 The third member character ID, can be nil.
  130. -- @param keep_leader If true, the leader of the field is not changed.
  131. set_party = function(character1, character2, character3, keep_leader)
  132. Party[1] = character1
  133. Party[2] = character2
  134. Party[3] = character3
  135. if not keep_leader then Party.leader = character1 end
  136. export_party_members()
  137. end
  138. --- Gets the leader of the party in the field: the character whose entity the player controls.
  139. --
  140. -- It is set by the scripts when they set the party, and it isn't changed by moving characters
  141. -- around in the Order menu. If there is no leader, or the leader isn't in the party (a party made
  142. -- by adding characters, or a game saved before the leader was saved), the first member of the party
  143. -- becomes the leader, and stays so until a script changes it.
  144. --
  145. -- @return ID of the character, or nil if there is no party.
  146. Party.get_leader = function()
  147. if Party.leader ~= nil then
  148. for slot = 1, 3 do
  149. if Party[slot] == Party.leader then return Party.leader end
  150. end
  151. end
  152. Party.leader = Party[1]
  153. return Party.leader
  154. end
  155. --- Sets the party from three values (SPTYE), the ones that GTPYE stored: 254 and 255 are an empty
  156. -- place.
  157. --
  158. -- @param character1 The first member character ID, the party leader.
  159. -- @param character2 The second member character ID.
  160. -- @param character3 The third member character ID.
  161. set_party_from_values = function(character1, character2, character3)
  162. local function id(value)
  163. if value == nil or value >= 254 then return nil end
  164. return value
  165. end
  166. set_party(id(character1), id(character2), id(character3))
  167. end
  168. --- Checks if a a character ID actually belongs to a character.
  169. --
  170. -- @param character The ID to check.
  171. -- @return True if the ID is a valid character ID, false otherwise.
  172. is_character = function(character)
  173. if Characters[character] == nil then
  174. return false
  175. end
  176. return true
  177. end
  178. --- Adds a character to the curent party.
  179. --
  180. -- @param character ID of the character to add.
  181. add_party_character = function(character)
  182. if Characters[character] == nil then
  183. print("Tried add to party invalid character \"" .. character .. "\".");
  184. return
  185. end
  186. if Characters[character].locked == true then
  187. print("Tried add to party locked character \"" .. character .. "\".");
  188. return
  189. end
  190. -- Check if character already in party
  191. for i = 1, 3 do
  192. if Party[i] == character then
  193. print("Character \"" .. character .. "\" already in party.");
  194. return
  195. end
  196. end
  197. -- Try to add in first free slot.
  198. for i = 1, 3 do
  199. if Party[i] == nil then
  200. Party[i] = character
  201. export_party_members()
  202. return
  203. end
  204. end
  205. end
  206. --- Removes a character from the curent party.
  207. --
  208. -- @param character ID of the character to remove.
  209. remove_party_character = function(character)
  210. if Characters[character] == nil then
  211. print("Tried remove from party invalid character \"" .. character .. "\".");
  212. return
  213. end
  214. if Characters[character].locked == true then
  215. print("Tried remove from party locked character \"" .. character .. "\".");
  216. return
  217. end
  218. for i = 1, 3 do
  219. if Party[i] == character then
  220. Party[i] = nil
  221. if Party.leader == character then Party.leader = nil end
  222. export_party_members()
  223. return
  224. end
  225. end
  226. end
  227. --- Locks a character in the party.
  228. --
  229. -- Locked characters can't be manually swapped in or out of the party.
  230. --
  231. -- @param character ID of the character to lock.
  232. set_party_lock = function(character, lock)
  233. if Characters[character] == nil then
  234. print("Tried set/unset party lock to invalid character \"" .. character .. "\".");
  235. return
  236. end
  237. Characters[character].locked = lock;
  238. end
  239. --- Checks if a character is locked in the party.
  240. --
  241. -- Locked characters can't be manually swapped in or out of the party.
  242. --
  243. -- @param character ID of the character to check for locks.
  244. get_party_lock = function(character)
  245. if Characters[character] == nil then
  246. print("Tried get party lock from invalid character \"" .. character .. "\".");
  247. return false
  248. end
  249. return Characters[character].locked
  250. end
  251. --- Enables or disables a character is the PHS.
  252. --
  253. -- Disabled characters don't appear in the PHS.
  254. --
  255. -- @param character ID of the character to enable or disable.
  256. -- @param enable True to enable, false to disable.
  257. set_character_enable = function(character, enable)
  258. if Characters[character] == nil then
  259. print("Tried enable/disable invalid character \"" .. character .. "\".");
  260. return
  261. end
  262. Characters[character].enabled = enable;
  263. -- As in ff7.exe (0x61c782), a character that is hidden also leaves the party, locked or not.
  264. if not enable then
  265. for i = 1, 3 do
  266. if Party[i] == character then
  267. Party[i] = nil
  268. export_party_members()
  269. end
  270. end
  271. end
  272. end
  273. --- Checks if a character is enabled in the PHS.
  274. --
  275. -- Disabled characters don't appear in the PHS.
  276. --
  277. -- @param character ID of the character to check.
  278. -- @return True if enabled, false if disables.
  279. get_character_enable = function(character)
  280. if Characters[character] == nil then
  281. print("Tried get enabled from invalid character \"" .. character .. "\".");
  282. return false
  283. end
  284. return Characters[character].enabled;
  285. end
  286. --- Checks if a character is in the current party (IFPRTYQ).
  287. --
  288. -- @param character ID of the character to check.
  289. -- @return True if the character is in one of the party slots.
  290. IFPRTYQ = function(character)
  291. for i = 1, 3 do
  292. if Party[i] == character then return true end
  293. end
  294. return false
  295. end
  296. --- Checks if a character is available as a party member (IFMEMBQ).
  297. --
  298. -- A character is available when it is enabled in the PHS, whether it is in the party or not.
  299. --
  300. -- @param character ID of the character to check.
  301. -- @return True if the character is enabled.
  302. IFMEMBQ = function(character)
  303. return Characters[character] ~= nil and Characters[character].enabled == true
  304. end
  305. --- Adds items to the inventory.
  306. --
  307. -- Inventory quantities will be capped at 99.
  308. --
  309. -- @param item Item ID.
  310. -- @param quantity Quantity to add.
  311. Inventory.add_item = function(item, quantity)
  312. -- TODO: Also check weapons, armors and accessories.
  313. if Game.Items[item] == nil then
  314. print("Tried add invalid item \"" .. item .. "\".");
  315. return
  316. end
  317. for i = 1, MAX_INVENTORY_SLOTS do
  318. if Inventory[i] ~= nil and Inventory[i].item == item then
  319. -- Item already in inventory, add quantity
  320. Inventory[i].quantity = Inventory[i].quantity + quantity
  321. if Inventory[i].quantity > 99 then
  322. Inventory[i].quantity = 99
  323. end
  324. return
  325. end
  326. end
  327. -- Item not in inventory, search for the first available position.
  328. for i = 1, MAX_INVENTORY_SLOTS do
  329. if Inventory[i] == nil then
  330. Inventory[i] = {item = item, quantity = quantity}
  331. if Inventory[i].quantity > 99 then
  332. Inventory[i].quantity = 99
  333. end
  334. return
  335. end
  336. end
  337. -- If reached this point, it means that the item is not in inventory, and all slots are full.
  338. -- TODO: The orignal game does nothing, but in here?
  339. return
  340. end
  341. --- Checks how many items of a type are in the inventory.
  342. --
  343. -- @param item The item ID.
  344. -- @return Number of the items in the inventory.
  345. Inventory.get_item_quantity = function(item)
  346. local qty = 0
  347. for i = 1, MAX_INVENTORY_SLOTS do
  348. if Inventory[i] ~= nil and Inventory[i].item == item then
  349. qty = qty + Inventory[i].quantity
  350. end
  351. end
  352. return qty
  353. end
  354. --- Removes items from the inventory.
  355. --
  356. -- Negative quantities can't remain in the inventory. If there are less than requested to remove,
  357. -- all of them will be removed.
  358. --
  359. -- @param item Item ID.
  360. -- @param quantity Quantity to remove.
  361. Inventory.remove_item = function(item, quantity)
  362. for i = 1, MAX_INVENTORY_SLOTS do
  363. if Inventory[i] ~= nil and Inventory[i].item == item then
  364. -- Item already in inventory, add quantity
  365. Inventory[i].quantity = Inventory[i].quantity - quantity
  366. if Inventory[i].quantity <= 0 then
  367. Inventory[i] = nil
  368. end
  369. return
  370. end
  371. end
  372. end
  373. --- Adds a key item.
  374. --
  375. -- @param item ID of the key item (0-50).
  376. Inventory.add_key_item = function(item)
  377. Inventory.key[item] = true
  378. return
  379. end
  380. --- Removes a key item.
  381. --
  382. -- @param item ID of the key item (0-50).
  383. Inventory.remove_key_item = function(item)
  384. Inventory.key[item] = false
  385. return
  386. end
  387. --- Checks if the party has a key item.
  388. --
  389. -- @param item ID of the key item (0-50).
  390. -- @return True if the party has the key item, false otherwise.
  391. Inventory.has_key_item = function(item)
  392. return Inventory.key[item]
  393. end
  394. --- Adds money.
  395. --
  396. -- @param amount The money to add.
  397. Inventory.add_money = function(amount)
  398. Inventory.money = Inventory.money + amount
  399. if Inventory.money > 99999999 then
  400. Inventory.money = 99999999
  401. end
  402. end
  403. --- Removes money.
  404. --
  405. -- Negative quantities can't remain as money. If there are less than requested to remove, all of
  406. -- it will be removed.
  407. --
  408. -- @param amount Money to remove.
  409. Inventory.remove_money = function(amount)
  410. Inventory.money = Inventory.money - amount
  411. if Inventory.money < 0 then
  412. Inventory.money = 0
  413. end
  414. end
  415. --- Copies the amount of gil the party has into data banks
  416. --
  417. -- As the gil amount is a four-byte value, in the original game the arguments require two
  418. -- destination addresses to place two two-byte values into. Address 1 takes the lower two bytes of
  419. -- the gil amount, while address 2 takes the higher two bytes.
  420. --
  421. -- @param b1 Bank of the first destination (lower two bytes).
  422. -- @param b2 Bank of the second destination (higher two bytes).
  423. -- @param a1 Address in the first bank.
  424. -- @param a2 Address in the second bank.
  425. Inventory.money_to_banks = function(b1, b2, a1, a2)
  426. Banks[b1][a1] = Inventory.money % 65536
  427. Banks[b2][a2] = math.floor(Inventory.money / 65536)
  428. end
  429. --- Sorts the items in the inventory.
  430. --
  431. -- @param criteria {@see Inventory.ORDER.CUSTOM} (unimplemented), {@see Inventory.ORDER.FIELD.},
  432. -- {@see Inventory.ORDER.BATTLE}, {@see Inventory.ORDER.THROW}, {@see Inventory.ORDER.TYPE},
  433. -- {@see Inventory.ORDER.NAME}, {@see Inventory.ORDER.MOST} or {@see Inventory.ORDER.LEAST}. Any
  434. -- othe rvalue and the items will not be sorted.
  435. Inventory.sort = function(criteria)
  436. if criteria == Inventory.ORDER.CUSTOM then
  437. print("Custom order unimplemented")
  438. elseif criteria == Inventory.ORDER.FIELD then
  439. table.sort(Inventory, function (left, right)
  440. if Game.Items[left.item].menu ~= Game.Items[right.item].menu then
  441. return Game.Items[left.item].menu > Game.Items[right.item].menu
  442. end
  443. return left.item < right.item
  444. end
  445. )
  446. elseif criteria == Inventory.ORDER.BATTLE then
  447. table.sort(Inventory, function (left, right)
  448. if Game.Items[left.item].battle ~= Game.Items[right.item].battle then
  449. return Game.Items[left.item].battle > Game.Items[right.item].battle
  450. end
  451. return left.item < right.item
  452. end
  453. )
  454. elseif criteria == Inventory.ORDER.THROW then
  455. table.sort(Inventory, function (left, right)
  456. if Game.Items[left.item].throw ~= Game.Items[right.item].throw then
  457. return Game.Items[left.item].throw > Game.Items[right.item].throw
  458. end
  459. return left.item < right.item
  460. end
  461. )
  462. elseif criteria == Inventory.ORDER.TYPE then
  463. table.sort(Inventory, function (left, right)
  464. return left.item < right.item
  465. end
  466. )
  467. elseif criteria == Inventory.ORDER.NAME then
  468. table.sort(Inventory, function (left, right)
  469. return Game.Items[left.item].name < Game.Items[right.item].name
  470. end
  471. )
  472. elseif criteria == Inventory.ORDER.MOST then
  473. table.sort(Inventory, function (left, right)
  474. if left.quantity ~= right.quantity then
  475. return left.quantity > right.quantity
  476. end
  477. return left.item < right.item
  478. end
  479. )
  480. elseif criteria == Inventory.ORDER.LEAST then
  481. table.sort(Inventory, function (left, right)
  482. if left.quantity ~= right.quantity then
  483. return left.quantity < right.quantity
  484. end
  485. return left.item < right.item
  486. end
  487. )
  488. end
  489. end
  490. -- Leveling up, as in ff7.exe (1998 build, functions 0x5c76d9 to 0x5c7bb1).
  491. Characters.MAX_LEVEL = 99
  492. Characters.MAX_EXP = 999999999
  493. --- Caps of the base stats that level ups give. Sources go to the stat bonus, not to the base.
  494. Characters.MAX_BASE_STAT = 100
  495. Characters.MAX_BASE_HP = 9999
  496. Characters.MAX_BASE_MP = 999
  497. --- Divides truncating toward zero, like the integer divisions of the original.
  498. local function divide(a, b)
  499. local quotient = a / b
  500. if quotient < 0 then return math.ceil(quotient) end
  501. return math.floor(quotient)
  502. end
  503. --- Gets the segment of the growth curves used for a level: one every 10 levels up to 60, then one
  504. -- every 20.
  505. local function curve_segment(level)
  506. if level <= 60 then return math.max(0, math.floor((level - 1) / 10)) end
  507. return math.min(7, math.floor((level - 61) / 20) + 6)
  508. end
  509. --- Picks one of the 12 bonuses: a random number from 1 to 8 plus how far the character is behind.
  510. local function bonus_index(difference)
  511. return math.max(0, math.min(11, math.random(1, 8) + difference))
  512. end
  513. --- Gets the total experience a character needs to go from a level to the next one.
  514. --
  515. -- It's the sum of gradient * n^2 / 10 for n from 1 to the level, all of them with the gradient of
  516. -- the segment of that level.
  517. --
  518. -- @param id Character ID.
  519. -- @param level The level.
  520. -- @return The total experience, 0 for level 0.
  521. Characters.exp_threshold = function(id, level)
  522. local gradient = Game.Growth.curves[Game.Characters[id].curves.exp][curve_segment(level)].gradient
  523. local total = 0
  524. for n = 1, level do total = total + math.floor(gradient * n * n / 10) end
  525. return total
  526. end
  527. --- Raises the base stats of a character for one level.
  528. --
  529. -- Each stat has a curve that gives the value expected at the new level; the further the character
  530. -- is below it, the better the bonus is likely to be.
  531. local function level_up(id)
  532. local character = Characters[id]
  533. local stats = character.stats
  534. local level = character.level
  535. local segment = curve_segment(level)
  536. local curves = Game.Characters[id].curves
  537. local function curve(name) return Game.Growth.curves[curves[name]][segment] end
  538. for _, name in ipairs({"str", "vit", "mag", "spr", "dex", "lck"}) do
  539. local stat = stats[name]
  540. local value = math.max(1, stat.base)
  541. local data = curve(name)
  542. local expected = math.floor(data.gradient * (level + 1) / 100) + data.base
  543. local gain = Game.Growth.bonus.primary[bonus_index(expected - value)]
  544. stat.base = math.min(Characters.MAX_BASE_STAT, value + gain)
  545. end
  546. local hp = curve("hp")
  547. local function expected_hp(n) return hp.gradient * n + hp.base * 40 end
  548. local value = math.max(1, stats.hp.base)
  549. local index = bonus_index(divide(expected_hp(level) * 100, value) - 100)
  550. local gain = divide((expected_hp(level + 1) - expected_hp(level)) * Game.Growth.bonus.hp[index], 100)
  551. stats.hp.base = math.min(Characters.MAX_BASE_HP, value + gain)
  552. local mp = curve("mp")
  553. local function expected_mp(n) return math.floor(mp.gradient * n / 10) + mp.base * 2 end
  554. value = math.max(1, stats.mp.base)
  555. index = bonus_index(divide(expected_mp(level) * 100, value) - 100)
  556. gain = divide((expected_mp(level + 1) - expected_mp(level)) * Game.Growth.bonus.mp[index], 100)
  557. stats.mp.base = math.min(Characters.MAX_BASE_MP, value + gain)
  558. character.level = level + 1
  559. end
  560. --- Gives experience to a character, and levels it up as many times as it reaches.
  561. --
  562. -- The current HP and MP don't change, only the base values and the maximums.
  563. --
  564. -- @param id Character ID.
  565. -- @param exp Experience gained.
  566. -- @return The number of levels gained.
  567. Characters.add_exp = function(id, exp)
  568. local character = Characters[id]
  569. local definition = Game.Characters[id]
  570. if character == nil or definition == nil or definition.curves == nil then return 0 end
  571. character.exp = math.min(Characters.MAX_EXP, (character.exp or 0) + exp)
  572. local first_level = character.level
  573. while character.level < Characters.MAX_LEVEL
  574. and character.exp >= Characters.exp_threshold(id, character.level) do
  575. level_up(id)
  576. end
  577. if character.level < Characters.MAX_LEVEL then
  578. character.exp_to_next = Characters.exp_threshold(id, character.level) - character.exp
  579. else
  580. character.exp_to_next = 0
  581. end
  582. if character.level > first_level then Characters.recalculate_stats(id) end
  583. return character.level - first_level
  584. end
  585. --- Variable of the field scripts with the level of the characters whose level doesn't depend on
  586. -- the one of the party (Yuffie): bank 1, address 2.
  587. Characters.JOIN_LEVEL_BANK = 1
  588. Characters.JOIN_LEVEL_ADDRESS = 2
  589. --- Gets the average level of the available characters (in the party or enabled in the PHS), without
  590. -- counting one of them.
  591. --
  592. -- @param excluded ID of the character that isn't counted.
  593. -- @return The average, or the level of the excluded character if there is nobody else.
  594. Characters.average_level = function(excluded)
  595. local sum, count = 0, 0
  596. for id = 0, 8 do
  597. if id ~= excluded and Characters[id] ~= nil and (IFMEMBQ(id) or IFPRTYQ(id)) then
  598. sum = sum + Characters[id].level
  599. count = count + 1
  600. end
  601. end
  602. if count == 0 then return Characters[excluded].level end
  603. return math.floor(sum / count)
  604. end
  605. --- Copies a table and the tables in it.
  606. local function copy_table(source)
  607. if type(source) ~= "table" then return source end
  608. local result = {}
  609. for key, value in pairs(source) do result[key] = copy_table(value) end
  610. return result
  611. end
  612. --- Gives a character the data it joins with. The slots of Cait Sith and Vincent hold young Cloud and
  613. -- Sephiroth at the start: ff7.exe replaces the whole slot with data of its own when the window to
  614. -- name them opens (0x70ec9a). Nothing happens for the other characters.
  615. --
  616. -- The availability and the lock in the party are not part of that data, and are kept.
  617. --
  618. -- @param id Character ID.
  619. Characters.load_recruit_record = function(id)
  620. local record = Game.RecruitRecords ~= nil and Game.RecruitRecords[id] or nil
  621. if record == nil or Characters[id] == nil then return end
  622. local character = copy_table(record)
  623. character.enabled = Characters[id].enabled
  624. character.locked = Characters[id].locked
  625. Characters[id] = character
  626. Characters.recalculate_stats(id)
  627. end
  628. --- Sets the level of a character that joins, as in ff7.exe (0x5c72a6). The original does it when the
  629. -- window to name the character is closed (for everybody but Cloud).
  630. --
  631. -- The level is the average of the other available characters plus half of the level offset of the
  632. -- character. With an odd offset (Yuffie) it comes from a variable of the field scripts instead, and
  633. -- the character is built again from level 1. The experience of the previous level is added to the
  634. -- one the character has, and it levels up as usual, so it never goes down. HP and MP end up filled.
  635. --
  636. -- @param id Character ID.
  637. Characters.join = function(id)
  638. local character = Characters[id]
  639. local definition = Game.Characters[id]
  640. if id == 0 or character == nil or definition == nil or definition.curves == nil then return end
  641. -- The offset is a signed byte.
  642. local offset = tonumber(definition.initial_level) or 0
  643. if offset > 127 then offset = offset - 256 end
  644. local stats = character.stats
  645. local level
  646. if offset % 2 == 0 then
  647. level = Characters.average_level(id) + divide(offset, 2)
  648. else
  649. level = Banks[Characters.JOIN_LEVEL_BANK][Characters.JOIN_LEVEL_ADDRESS] or 0
  650. -- It is unknown what writes the variable in a normal game: without it, the character would
  651. -- be left at level 1, so the average of the party is used.
  652. if level == 0 then level = Characters.average_level(id) end
  653. character.level = 1
  654. character.exp = 0
  655. for _, name in ipairs({"str", "vit", "mag", "spr", "dex", "lck", "hp", "mp"}) do
  656. stats[name].base = 1
  657. end
  658. end
  659. level = math.max(1, math.min(Characters.MAX_LEVEL, level))
  660. Characters.add_exp(id, Characters.exp_threshold(id, level - 1))
  661. stats.hp.current = stats.hp.base
  662. stats.mp.current = stats.mp.base
  663. Characters.recalculate_stats(id)
  664. print(character.name .. " joins at level " .. tostring(character.level))
  665. end
  666. --- Names of the primary stats.
  667. Characters.PRIMARY_STATS = {"str", "vit", "mag", "spr", "dex", "lck"}
  668. --- Cap of the primary stats and of the bonus that the sources give, as in ff7.exe.
  669. Characters.MAX_STAT = 255
  670. --- Primary stat or maximum raised by each of the Plus materia, by the ID of its ability.
  671. Characters.PLUS_MATERIA = {
  672. [0] = "str", [1] = "vit", [2] = "mag", [3] = "spr", [4] = "dex", [5] = "lck", [8] = "hp", [9] = "mp",
  673. }
  674. --- Item ID of the Curse Ring, and what it adds to the stats on top of the bonuses of its data.
  675. Characters.CURSE_RING = 313
  676. Characters.CURSE_RING_BONUS = {str = 15, vit = 15, mag = 15, spr = 15, dex = 15, lck = 10}
  677. --- Uses a source on a character: one more point of bonus for a primary stat.
  678. --
  679. -- @param id Character ID.
  680. -- @param name Name of the stat, one of {@see Characters.PRIMARY_STATS}.
  681. -- @return False if the bonus is already at its cap, and nothing happens.
  682. Characters.add_stat_bonus = function(id, name)
  683. local stat = Characters[id].stats[name]
  684. if (stat.bonus or 0) >= Characters.MAX_STAT then return false end
  685. stat.bonus = (stat.bonus or 0) + 1
  686. Characters.recalculate_stats(id)
  687. return true
  688. end
  689. Characters.recalculate_stats = function(id)
  690. -- Initialize
  691. local stats = Characters[id].stats
  692. -- The primary stats start with the base value, that grows with the levels, plus the bonus that the
  693. -- sources give.
  694. for _, name in ipairs(Characters.PRIMARY_STATS) do
  695. stats[name].total = stats[name].base + (stats[name].bonus or 0)
  696. end
  697. stats.hp.max = stats.hp.base
  698. stats.mp.max = stats.mp.base
  699. local weapon = Game.Items[Characters[id].weapon.id]
  700. local armor = Game.Items[Characters[id].armor.id]
  701. -- Bonuses of the equipment: points added to the primary stats. They are keyed by name, so they are
  702. -- walked with pairs (ipairs only walks the array part and found nothing).
  703. for _, item in pairs({weapon, armor, Game.Items[Characters[id].accessory]}) do
  704. for name, value in pairs(item.stats or {}) do
  705. if stats[name] ~= nil and stats[name].total ~= nil then
  706. stats[name].total = stats[name].total + value
  707. end
  708. end
  709. end
  710. -- The Curse Ring has more bonuses than its data can hold, ff7.exe adds them (0x6bbb04).
  711. if Characters[id].accessory == Characters.CURSE_RING then
  712. for name, value in pairs(Characters.CURSE_RING_BONUS) do stats[name].total = stats[name].total + value end
  713. end
  714. -- Get a list of materias
  715. local materias, equipped_materias = {}, {}
  716. for _, part in ipairs({Characters[id].weapon, Characters[id].armor}) do
  717. for m = 0, 7 do
  718. local equipped = part.materia[m]
  719. if equipped ~= nil and Game.Materia[equipped.id] ~= nil then
  720. table.insert(materias, Game.Materia[equipped.id])
  721. table.insert(equipped_materias, equipped)
  722. end
  723. end
  724. end
  725. -- Materia changes, as in ff7.exe (0x5cd1e8 and 0x5ce487): points for the primary stats and percents
  726. -- for HP and MP, that every equipped materia adds up, and the percents of the Plus materia (HP,
  727. -- MP, Speed, Magic and Luck Plus).
  728. local points, percents = {}, {}
  729. local function add(list, name, value) list[name] = (list[name] or 0) + value end
  730. for index, materia in ipairs(materias) do
  731. for name, value in pairs(materia.stats or {}) do
  732. if name == "hp" or name == "mp" then add(percents, name, value)
  733. else add(points, name, value)
  734. end
  735. end
  736. local name = materia.type == Materia.TYPE.INDEPENDENT and materia.ability ~= nil
  737. and Characters.PLUS_MATERIA[materia.ability.id] or nil
  738. if name ~= nil then
  739. local level = math.max(1, Characters.get_materia_level(materia, equipped_materias[index].ap or 0))
  740. local param = materia.ability.param
  741. add(percents, name, param[level] or param[#param])
  742. end
  743. end
  744. local function percent_of(value, name)
  745. local result = value * math.min(100, percents[name] or 0) / 100
  746. -- Truncated toward zero, like the integer division of the original.
  747. if result < 0 then return math.ceil(result) end
  748. return math.floor(result)
  749. end
  750. -- The percent of a Plus materia applies to the stat with the equipment, without the materia points.
  751. for _, name in ipairs(Characters.PRIMARY_STATS) do
  752. local value = math.min(Characters.MAX_STAT, stats[name].total)
  753. value = value + percent_of(value, name) + (points[name] or 0)
  754. stats[name].total = math.max(0, math.min(Characters.MAX_STAT, math.floor(value)))
  755. end
  756. stats.hp.max = math.min(Characters.MAX_BASE_HP, stats.hp.max + percent_of(stats.hp.max, "hp"))
  757. stats.mp.max = math.min(Characters.MAX_BASE_MP, stats.mp.max + percent_of(stats.mp.max, "mp"))
  758. -- HP<->MP materia swap the maximum HP and MP. TODO: Unverified: its levels (it is done at any level).
  759. for _, materia in ipairs(materias) do
  760. if materia ~= nil and materia.type == Materia.TYPE.INDEPENDENT and materia.ability ~= nil
  761. and materia.ability.id == Materia.ABILITY.HP_MP then
  762. stats.hp.max, stats.mp.max = stats.mp.max, stats.hp.max
  763. break
  764. end
  765. end
  766. -- The current values can't be over the maximums.
  767. if stats.hp.current ~= nil then stats.hp.current = math.min(stats.hp.current, math.max(1, stats.hp.max)) end
  768. if stats.mp.current ~= nil then stats.mp.current = math.min(stats.mp.current, math.max(0, stats.mp.max)) end
  769. if stats.hp.max < 1 then
  770. stats.hp.max = 1
  771. end
  772. if stats.mp.max < 1 then
  773. stats.mp.max = 1
  774. end
  775. -- Calculate composed stats.
  776. stats.atk = stats.str.total + weapon.power
  777. stats.acc = weapon.accuracy
  778. stats.def = stats.vit.total + armor.defense.physical
  779. stats.eva = armor.evasion.physical
  780. stats.matk = stats.mag.total
  781. stats.mdef = stats.spr.total + armor.defense.magical
  782. stats.meva = armor.evasion.magical
  783. -- Cap composed stats. TODO: Max caps?
  784. if stats.atk < 1 then
  785. stats.atk = 1
  786. end
  787. if stats.acc < 1 then
  788. stats.acc = 1
  789. end
  790. if stats.def < 1 then
  791. stats.def = 1
  792. end
  793. if stats.eva < 0 then
  794. stats.eva = 0
  795. end
  796. if stats.matk < 1 then
  797. stats.matk = 1
  798. end
  799. if stats.mdef < 1 then
  800. stats.mdef = 1
  801. end
  802. if stats.meva < 0 then
  803. stats.meva = 0
  804. end
  805. -- Cap current HP/MP
  806. if stats.hp.current > stats.hp.max then
  807. stats.hp.current = stats.hp.max
  808. end
  809. if stats.mp.current > stats.mp.max then
  810. stats.mp.current = stats.mp.max
  811. end
  812. -- Assign
  813. Characters[id].stats = stats
  814. end
  815. --- Sends the materia that doesn't fit in a piece of equipment back to the materia inventory.
  816. --
  817. -- @param char_id ID of the character.
  818. -- @param part "weapon" or "armor".
  819. -- @param slots Number of materia slots the equipment will have. Slots are 0-7 in the character.
  820. Characters.remove_excess_materia = function(char_id, part, slots)
  821. local materia = Characters[char_id][part].materia
  822. for m = slots, 7 do
  823. if materia[m] ~= nil then
  824. Materia.add(materia[m].id, materia[m].ap)
  825. materia[m] = nil
  826. end
  827. end
  828. end
  829. --- Equips an item on a character.
  830. --
  831. -- Works for weapons, armors and accessories. If there is a previously equiped item, it
  832. -- will be unequiped and added to the inventory. The equiped item will be removed form the
  833. -- inventory. For armors and weapons, if the newly equiped item has less materia slots than
  834. -- the previuos one, remainig materia will be unequiped and added to the materia inventory.
  835. --
  836. -- @param char_id ID of the character to equip the item to.
  837. -- @param item_id ID of the item to equip.
  838. -- @return True if the item was equipped. False if the character or item don't exist, if
  839. -- the item is not in the inventory, or if the item is not equippable or not equippable by
  840. -- the selected character. In any of those cases, an error message will be printed.
  841. Characters.equip = function(char_id, item_id)
  842. -- Error checks
  843. if Characters[char_id] == nil then
  844. print("Tried to equip item on wrong character: " .. tostring(char_id))
  845. return false
  846. elseif Game.Items[item_id] == nil then
  847. print("Tried to equip invalid item: " .. tostring(item_id))
  848. return false
  849. elseif Inventory.get_item_quantity(item_id) < 1 then
  850. print("Tried to equip item not in inventory: " .. item_id .. " (" .. Game.Items[item_id].name .. ")")
  851. return false
  852. end
  853. local type = Game.Items[item_id].type
  854. if type ~= Inventory.ITEM_TYPE.WEAPON and type ~= Inventory.ITEM_TYPE.ARMOR and type ~= Inventory.ITEM_TYPE.ACCESSORY then
  855. print("Tried to equip non-equipable item: " .. item_id .. " (" .. Game.Items[item_id].name .. ")")
  856. return false
  857. end
  858. local equipable = false
  859. for _, u in ipairs(Game.Items[item_id].users) do
  860. if u == char_id then
  861. equipable = true
  862. break
  863. end
  864. end
  865. if equipable == false then
  866. print("Tried to equip item " .. tostring(item_id) .. " (" .. Game.Items[item_id].name .. ") on a non valid character: " .. tostring(char_id) .. " (" .. Characters[char_id].name .. ")")
  867. return false
  868. end
  869. -- All is good, equip.
  870. if type == Inventory.ITEM_TYPE.ACCESSORY then
  871. -- Equip accessory. If any was equipped, send it to the inventory.
  872. if Characters[char_id].accessory ~= nil then
  873. Inventory.add_item(Characters[char_id].accessory, 1)
  874. end
  875. Characters[char_id].accessory = item_id
  876. Inventory.remove_item(item_id, 1)
  877. elseif type == Inventory.ITEM_TYPE.WEAPON then
  878. -- Weapon. Remove excess materia, send previuos one to the inventory.
  879. Characters.remove_excess_materia(char_id, "weapon", #(Game.Items[item_id].slots))
  880. Inventory.add_item(Characters[char_id].weapon.id, 1)
  881. Characters[char_id].weapon.id = item_id
  882. Inventory.remove_item(item_id, 1)
  883. elseif type == Inventory.ITEM_TYPE.ARMOR then
  884. -- Armor. Remove excess materia, send previuos one to the inventory.
  885. Characters.remove_excess_materia(char_id, "armor", #(Game.Items[item_id].slots))
  886. Inventory.add_item(Characters[char_id].armor.id, 1)
  887. Characters[char_id].armor.id = item_id
  888. Inventory.remove_item(item_id, 1)
  889. else
  890. return false
  891. end
  892. -- The stats change with the equipment (and the maximum HP and MP, so the current ones may have to be capped).
  893. Characters.recalculate_stats(char_id)
  894. return true
  895. end
  896. --- Takes the equipped materia off a character and puts it in the materia inventory (menu 17 of the
  897. -- field scripts: the "remove materia from other members" of the scenes with a fixed party).
  898. --
  899. -- @param id ID of the character.
  900. Characters.unequip_materia = function(id)
  901. local character = Characters[id]
  902. if character == nil then return end
  903. local free = 1
  904. for _, equipment in ipairs({character.weapon, character.armor}) do
  905. for slot = 0, 7 do
  906. local materia = equipment.materia[slot]
  907. if materia ~= nil then
  908. while free <= MAX_MATERIA_SLOTS and Materia[free] ~= nil do free = free + 1 end
  909. if free > MAX_MATERIA_SLOTS then return end
  910. Materia[free] = materia
  911. equipment.materia[slot] = nil
  912. end
  913. end
  914. end
  915. Characters.recalculate_stats(id)
  916. end
  917. --- Removes all materia from a character.
  918. --
  919. -- @param id ID of the character to remove materia from.
  920. Characters.remove_materia = function(id)
  921. -- TODO: Implement
  922. end
  923. --- Restores all materia to a character.
  924. --
  925. -- @param id ID of the character to restore materia to.
  926. Characters.restore_materia = function(id)
  927. -- TODO: Implement
  928. end
  929. Materia.add = function(id, ap)
  930. local ap = ap or 0
  931. if Game.Materia[id] == nil then
  932. print("Tried to add invalid materia \"" .. tostring(id) .. "\".");
  933. return
  934. end
  935. -- TODO Cap AP?
  936. for i = 1, MAX_MATERIA_SLOTS do
  937. if Materia[i] == nil then
  938. Materia[i] = {id = id, ap = ap}
  939. if Materia[i].id == Materia.ENEMY_SKILL_ID then
  940. Materia[i].ap = 0
  941. Materia[i].skills = {}
  942. for s = 1, 24 do
  943. Materia[i].skills[s] = false
  944. end
  945. end
  946. return
  947. end
  948. end
  949. -- If reached this point, it means that the materia wasn't added because all slots are full.
  950. -- TODO: Do something.
  951. return
  952. end
  953. --- Splits the party in teams.
  954. --
  955. -- @param number Number of teams (only 2 or 3).
  956. Party.split_teams = function(number)
  957. if number < 2 then
  958. number = 2
  959. elseif number > 3 then
  960. number = 3
  961. end
  962. -- TODO: Implement.
  963. end
  964. --- Displays a menu to choose a party of three.
  965. --
  966. -- The script that asks for it waits until the menu is closed.
  967. Party.choose_party = function()
  968. -- The button that asked for the menu (Cancel) is still down: it would close the menu at once.
  969. while entity_manager:is_key_on(64) do script:wait(0) end
  970. UiContainer.PhsMenu.standalone = true
  971. script:request_end_sync(Script.UI, "PhsMenu", "show", 0)
  972. while UiContainer.current_menu == "phs" do script:wait(0) end
  973. -- The button that closed the menu is still down: the script that asked for the menu would
  974. -- read it as a new request (Cancel opens the menu).
  975. while entity_manager:is_key_on(32 + 64) do script:wait(0) end
  976. end
  977. --- Special event. Removes all materia from the party, equipped and unequipped.
  978. Party.steal_materia = function()
  979. -- TODO: Implement.
  980. -- TODO: How is this reversed?
  981. end
  982. --- Integer division of the field scripts (DIV, DIV2).
  983. --
  984. -- @param a Dividend.
  985. -- @param b Divisor. The result is the dividend if it is zero.
  986. -- @return The integer part of a / b.
  987. function math_div(a, b)
  988. if b == 0 then return a end
  989. return math.floor(a / b)
  990. end
  991. --- Implementation of OR bit operation.
  992. --
  993. -- @param a First operand.
  994. -- @param b Second operand.
  995. -- @return a | b.
  996. function bit_or(a, b)
  997. local r, m, s = 0, 2 ^ 31
  998. repeat
  999. s, a, b = a + b + m, a % m, b % m
  1000. r, m = r + m * 1 % (s - a - b), m / 2
  1001. until m < 1
  1002. return r
  1003. end
  1004. --- Implementation of XOR bit operation.
  1005. --
  1006. -- @param a First operand.
  1007. -- @param b Second operand.
  1008. -- @return a ^^ b.
  1009. function bit_xor(a, b)
  1010. local r, m, s = 0, 2 ^ 31
  1011. repeat
  1012. s, a, b = a + b + m, a % m, b % m
  1013. r, m = r + m * 3 % (s - a - b), m / 2
  1014. until m < 1
  1015. return r
  1016. end
  1017. --- Implementation of AND bit operation.
  1018. --
  1019. -- @param a First operand.
  1020. -- @param b Second operand.
  1021. -- @return a & b.
  1022. function bit_and(a, b)
  1023. local r, m, s = 0, 2 ^ 31
  1024. repeat
  1025. s, a, b = a + b + m, a % m, b % m
  1026. r, m = r + m * 4 % (s - a - b), m / 2
  1027. until m < 1
  1028. return r
  1029. end
  1030. --- Obtains a bit from an address in a data bank
  1031. --
  1032. -- @param bank The bank (0-14)
  1033. -- @param address The bank address (0-254)
  1034. -- @param bit The bit to get (0-7)
  1035. -- @return The bit value (1-0)
  1036. function get_bank_bit(bank, address, bit)
  1037. if bank < 0 or bank > Banks.COUNT or address < 0 or address > Banks.SIZE or bit < 0 or bit > 7 then
  1038. print("ERROR: Tried to check invalid bit " .. tostring(bit) .. " from bank " .. tostring(bank) .. " at address " .. tostring(address) .. ".")
  1039. return 0
  1040. end
  1041. local val = Banks[bank][address]
  1042. return get_byte_nth_bit(val, bit)
  1043. end
  1044. --- Sets a bit in an address in a data bank
  1045. --
  1046. -- @param bank The bank (0-14)
  1047. -- @param address The bank address (0-254)
  1048. -- @param bit The bit to set (0-7)
  1049. -- @param value The bit value (1-0)
  1050. function set_bank_bit(bank, address, bit, value)
  1051. if bank < 0 or bank > Banks.COUNT or address < 0 or address > Banks.SIZE or bit < 0 or bit > 7 then
  1052. print("ERROR: Tried to set invalid bit " .. tostring(bit) .. " from bank " .. tostring(bank) .. " at address " .. tostring(address) .. ".")
  1053. return
  1054. end
  1055. if value ~= 1 and value ~= 0 then
  1056. print("ERROR: Tried to set bit to invalid value " .. tostring(value) .. " from bank " .. tostring(bank) .. " at address " .. tostring(address) .. ".")
  1057. return
  1058. end
  1059. local val = Banks[bank][address]
  1060. Banks[bank][address] = set_byte_nth_bit(val, bit, value)
  1061. end
  1062. --- Obtains a bit from an unsigned byte
  1063. --
  1064. -- @param value The value (0-254)
  1065. -- @param bit The bit to get (0-7)
  1066. -- @return The bit value (1-0)
  1067. function get_byte_nth_bit(value, n)
  1068. if n < 0 or n > 7 then
  1069. print("ERROR: Tried to get invalid bit " .. tostring(bit) .. " from value " .. tostring(value) .. ".")
  1070. return 0
  1071. end
  1072. if value < 0 then
  1073. print("ERROR: Tried to get bit " .. tostring(bit) .. " from negative value " .. tostring(value) .. ".")
  1074. return 0
  1075. end
  1076. if value > 254 then
  1077. print("ERROR: Tried to get bit " .. tostring(bit) .. " from value " .. tostring(value) .. " that exceeds byte size.")
  1078. return 0
  1079. end
  1080. -- Convert to binary string
  1081. local s = ""
  1082. local temp = value
  1083. for i = 1, 8 do
  1084. s = s .. tostring(temp % 2)
  1085. temp = math.floor(temp / 2)
  1086. end
  1087. return tonumber(string.sub(s, n + 1, n + 1))
  1088. end
  1089. --- Obtains a bit from an unsigned byte
  1090. --
  1091. -- @param value The value (0-254)
  1092. -- @param bit The bit to get (0-7)
  1093. -- @return The bit value (1-0)
  1094. function set_byte_nth_bit(value, n, bit)
  1095. if bit ~= 0 and bit ~= 1 then
  1096. print("ERROR: Tried to set bit " .. tostring(bit) .. " to an invalid value " .. tostring(bit) .. " from value " .. tostring(value) .. ".")
  1097. return value
  1098. end
  1099. if n < 0 or n > 7 then
  1100. print("ERROR: Tried to set invalid bit " .. tostring(bit) .. " to " .. tostring(bit) .. " from value " .. tostring(value) .. ".")
  1101. return value
  1102. end
  1103. if value < 0 then
  1104. print("ERROR: Tried to set bit " .. tostring(bit) .. " to " .. tostring(bit) .. "from negative value " .. tostring(value) .. ".")
  1105. return value
  1106. end
  1107. if value > 254 then
  1108. print("ERROR: Tried to set bit " .. tostring(bit) .. " to " .. tostring(bit) .. "from value " .. tostring(value) .. " that exceeds byte size.")
  1109. return value
  1110. end
  1111. -- Convert to binary string.
  1112. local s = ""
  1113. local temp = value
  1114. for i = 1, 8 do
  1115. s = s .. tostring(temp % 2)
  1116. temp = math.floor(temp / 2)
  1117. end
  1118. -- Replace the requested bit.
  1119. s = string.sub(s, 1, n) .. tostring(bit) .. string.sub(s, n + 2)
  1120. -- Convert back to a number.
  1121. val = 0
  1122. for i = 1, 8 do
  1123. val = val + (tonumber(string.sub(s, i, i )) * 2 ^ (i - 1))
  1124. end
  1125. return math.floor(val)
  1126. end
  1127. set_byte_nth_bit(25, 2, 1)