diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml new file mode 100644 index 00000000..9e1fa95a --- /dev/null +++ b/.github/workflows/gh-pages.yml @@ -0,0 +1,34 @@ +name: github pages + +on: + push: + branches: + - master + +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: '3.x' + + - name: Install dependencies + run: | + sudo apt -y -qq install bundler python3-pip + pip3 install ruamel.yaml --user + + - name: Build + run: ./docs/generate.sh + + - name: Deploy + uses: peaceiris/actions-gh-pages@v3 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + publish_dir: ./docs/_site + user_name: 'github-actions[bot]' + user_email: 'github-actions[bot]@users.noreply.github.com' diff --git a/.gitignore b/.gitignore index 8539e29c..06c1c71a 100644 --- a/.gitignore +++ b/.gitignore @@ -55,8 +55,10 @@ nb-configuration.xml # Build results [Dd]ebug/ [Dd]ebugPublic/ +[Dd]evXP [Rr]elease/ [Rr]eleases/ +[Rr]eleaseXP/ x64/ x86/ build/ @@ -222,3 +224,9 @@ FakesAssemblies/ # Visual Studio 6 workspace options file *.opt sfall/postbuild.cmd + +# jekyll build files +docs/_site +docs/.sass-cache +docs/.jekyll-metadata +docs/pages/*.md diff --git a/README.md b/README.md index e1f49bf4..7d495aad 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # sfall +[![github pages](https://github.com/phobos2077/sfall/actions/workflows/gh-pages.yml/badge.svg)](https://github.com/phobos2077/sfall/actions/workflows/gh-pages.yml) A set of engine modifications for the classic game Fallout 2 in form of a DLL, which modifies executable in memory without changing anything in EXE file itself. diff --git a/artifacts/ddraw.ini b/artifacts/ddraw.ini index 41bb06ed..e0bee64f 100644 --- a/artifacts/ddraw.ini +++ b/artifacts/ddraw.ini @@ -1,27 +1,27 @@ ;sfall configuration settings -;v4.2.9 +;v4.3 [Main] ;Change to 1 if you want to use command line args to tell sfall to use another ini file. UseCommandLine=0 ;Uncomment and point to a file to get alternate translations for some sfall messages +;This file can be placed in text\\ for sfall to get the translations depending on the game language ;TranslationsINI=sfall\Translations.ini ;XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX [ExtraPatches] ;This section allows you to set multiple paths to folders containing mods or patches that will be loaded by the game -;The priority of read files will be higher than the files in patchXXX.dat -;If DataLoadOrderPatch is enabled, the data load order will be: -;master_patches > critter_patches > PatchFile99 - PatchFile0 > patchXXX.dat > ... -;Paths to folders and Fallout .dat files are supported. The available range for PatchFile option names is from 0 to 99 -;The greater numbers take precedence over lesser numbers +;If DataLoadOrderPatch is enabled, the data load order is: +;master_patches > critter_patches > PatchFile99..PatchFile0 > patchXXX.dat > critter_dat > f2_res_patches > f2_res_dat > master_dat +;Paths to folders and Fallout .dat files are supported +;The PatchFile## options are available from 0 to 99. Larger numbers take precedence over smaller numbers (same as patchXXX.dat) ;PatchFile0=mods\RP_data ;Path to the folder in which the game will automatically search and load custom files (by *.dat mask, including folders) ;The data load order of the files in the folder will be in reverse alphabetical order of the filenames -;The files placed in this folder will have higher priority than the PatchFileXX options -;This option has no effect in v4.2.6 or later. The default path is \mods\ +;The files placed in this folder will have higher priority than the PatchFile## options +;This option has no effect in 4.2.6 or later. The path is fixed to \mods\ ;AutoSearchPath=mods ;XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX @@ -149,7 +149,7 @@ OverrideMusicDir=1 UseScrollWheel=1 ;The mouse Z position is divided by this modifier to calculate the number of inventory -;slots to scroll. My mouse moves 120 pixel in the z direction for one click of the mouse +;slots to scroll. My mouse moves 120 pixels in the z direction for one click of the mouse ;wheel, but this may vary depending on your mouse manufacturer and windows settings. ;Set to 0 to only ever scroll 1 click ScrollMod=0 @@ -159,9 +159,9 @@ ScrollMod=0 MouseSensitivity=100 ;DX scancode of a key to press when the middle mouse button is clicked -;The default of 0x30 toggles between your two weapons +;The default of 48 ('B' key) toggles between your active items ;Set to 0 to disable -MiddleMouse=0x30 +MiddleMouse=48 ;Set to 1 to reverse the left and right mouse buttons ReverseMouseButtons=0 @@ -240,6 +240,7 @@ WorldMapTimeMod=100 WorldMapFPSPatch=1 ;Controls the world map speed if WorldMapFPSPatch is 1. Higher values cause slower movement +;Default is 66 milliseconds WorldMapDelay2=66 ;Set to 1 to enable Ray's patch to make world map encounter rate independent of your travel speed @@ -272,7 +273,8 @@ UseFileSystemOverride=0 ;Set to 1 to use the modified data load order for the engine to find game data ;Original: patchXXX.dat > critter_patches > critter_dat > f2_res_patches > f2_res_dat > master_patches > master_dat ;Modified: master_patches > critter_patches > patchXXX.dat > critter_dat > f2_res_patches > f2_res_dat > master_dat -DataLoadOrderPatch=1 +;This option is always enabled in 4.3/3.8.30 or later. The information is left for reference only +;DataLoadOrderPatch=1 ;Set to 1 to load alternative dialog msg files from text\\dialog_female\ for female PC ;Set to 2 to also load subtitle files from text\\cuts_female\ for female PC @@ -369,7 +371,7 @@ SingleCore=1 OverrideArtCacheSize=0 ;Prevents you from saving in combat except at the start of your turn to avoid a few bugs -;Note that even with this option enabled, it is still not advisable to save in combat at all (obsolete information) +;Note that even with this option enabled, it is still not advisable to save in combat ;Set to 2 to block all saving in combat SaveInCombatFix=1 @@ -419,7 +421,7 @@ CorpseDeleteTime=6 ;Set a number of milliseconds to idle each input loop ;Set to -1 to disable ;Set to 0 to idle only if other processes are waiting for processor time (WinXP/2000: if processes have equal priority) -;Set to 1 (or some higher number if needed) to prevent 100% CPU use. The maximum is 127 +;Set to 1 (or some higher number if needed) to prevent 100% CPU use. The maximum is 30 ProcessorIdle=-1 ;Set to 1 if using the hero appearance mod @@ -436,17 +438,19 @@ SkipOpeningMovies=0 ;Set to 0 to disable NPCsTryToSpendExtraAP=0 -;Set to 1 to fix NPCs not checking weapon perks properly when choosing the best weapon in combat -;Set to 2 to change the priority multiplier for having weapon perk to 3x (the original is 5x) -;Note that enabling this option can significantly affect the weapon of choice for some NPCs -AIBestWeaponFix=0 +;Set to 1 to fix the priority score calculation for choosing the best weapon for NPCs +;Note that enabling this option can affect the weapon of choice for some NPCs +AIBestWeaponFix=1 ;Set to 1 to fix NPCs not taking chem_primary_desire in AI.txt as drug use preference when using drugs in their inventory +;Set to 2 to allow NPCs to use only the drugs listed in chem_primary_desire and healing drugs (stimpaks and healing powder) +;Note: chem_primary_desire w/o fixes prevents the specified item PID from being consumed if all three values in the list are the same PID +;chem_primary_desire also works as a priority list of drug items the NPC will try to pick up in combat when they are on the ground AIDrugUsePerfFix=0 -;Allows the use of tiles over 80x36 in size. sfall will just split and resave them at startup -;Set to 1 to check all tiles on started (slow) -;Set to 2 if you provide a XLtiles.lst file in art\tiles\ containing a list of the tile ids that need checking +;Allows the use of tiles over 80x36 in size. sfall will just split and resave them to art\tiles\zzz####.frm at startup +;Set to 1 to check all tiles on started (slow, but can also be useful for checking the correct size of your new tiles) +;Set to 2 if you provide a XLtiles.lst file in art\tiles\ containing a list of the tile indexes that need checking AllowLargeTiles=0 ;Set to 1 to boost the maximum number of tile FRMs from 4096 to 16383 @@ -541,11 +545,11 @@ RemoveCriticalTimelimits=0 ;MainMenuBigFontColour=0x3C ;Alternative behaviors to the Fast Shot trait -;0 - Fallout 2 original behavior: -1 AP cost for ranged weapons; aimed attacks are disabled -;1 - Haenlomal's fix: aimed attacks are enabled for melee/unarmed weapons and HtH attacks +;0 - Fallout 2 original behavior: -1 AP cost for ranged weapons. Aimed attacks are disabled +;1 - Haenlomal's tweak: aimed attacks are enabled for melee/unarmed weapons and HtH attacks ;2 - Alternative behavior: apply -1 AP cost to melee/unarmed weapons and HtH attacks -;3 - Fallout 1 original behavior: -1 AP cost for all weapons; aimed attacks are disabled -FastShotFix=1 +;3 - Fallout 1 original behavior: -1 AP cost for all weapons. Aimed attacks are disabled +FastShotFix=0 ;Set to 1 to fix the carry weight penalty of the Small Frame trait not being applied to bonus Strength points SmallFrameFix=0 @@ -595,7 +599,7 @@ ObjCanSeeObj_ShootThru_Fix=0 ;Set to 1 to fix the broken obj_can_hear_obj script function ObjCanHearObjFix=0 -;Set to 1 to enable the mood argument of start_gdialog script function to be available for talking heads +;Set to 1 to enable the 'mood' argument of start_gdialog script function for talking heads ;If the argument value is -1, the mood will be determined by the local variable 0 of the script (vanilla behavior) StartGDialogFix=0 @@ -605,6 +609,11 @@ StartGDialogFix=0 ;num_attacks - the number of free action points on the first turn only AttackComplexFix=0 +;Set to 1 to make the create_object_sid script function run the 'start' procedure of attached script upon object creation +;By default, the 'start' procedure of attached script is executed after the current script procedure is finished +;Note that enabling this option may cause unexpected results with some existing game scripts +CreateObjectSidFix=0 + ;Set to 1 to fix the issue with the division operator treating negative integers as unsigned ;Note: To perform the unsigned integer division, use the new 'div' operator DivisionOperatorFix=1 @@ -642,7 +651,7 @@ ExplosionsEmitLight=0 ;Set to 0 for backward compatibility with pre-3.4 scripts arraysBehavior=1 -;Set to 1 to add proper checks if there is enough ammo to use weapons that use multiple ammo per shot +;Set to 1 to add proper checks to see if there is enough ammo to attack with weapons that use multiple ammo per shot CheckWeaponAmmoCost=0 ;Controls the speed of combat panel animations (lower - faster; valid range: 0..65535) @@ -738,9 +747,14 @@ SkipLoadingGameSettings=0 SpecialDeathGVAR=491 ;Set to 1 to disable the special handling of map IDs 19 and 37 in the engine when entering the maps -;Note that enabling this option can break the map changes in Modoc and Vault 15 +;Note that enabling this option will break the map changes in Modoc and Vault 15 in Fallout 2 DisableSpecialMapIDs=0 +;Set to 1 to disable the special handling of city areas 45 and 46 in the engine when visiting Area 45: +;Area 45 automatically disappears from the world map, and Area 46 appears on the world map +;Note that enabling this option will break the location change of the 'Fake Vault 13' in Fallout 2 +DisableSpecialAreas=0 + ;Changes the base value of the duration of the knockout effect (valid range: 35..100; default is 35) ;The formula for the duration in ticks is: 10 * (value - 3 * EN) KnockoutTime=35 @@ -851,10 +865,12 @@ Test_ForceFloats=0 ;These options control what output is saved in the debug log (sfall-log.txt) ;Prints messages duing sfall initialization -Init=0 +Init=1 ;Prints messages relating to hook scripts Hook=0 ;Prints messages relating to scripting Script=0 ;Prints messages relating to the critical table -Criticals=0 +Criticals=1 +;Prints messages relating to engine fixes +Fixes=1 diff --git a/artifacts/example_mods/AutoCloseBox/gl_auto_closebox.int b/artifacts/example_mods/AutoCloseBox/gl_auto_closebox.int index a308c257..96d5499a 100644 Binary files a/artifacts/example_mods/AutoCloseBox/gl_auto_closebox.int and b/artifacts/example_mods/AutoCloseBox/gl_auto_closebox.int differ diff --git a/artifacts/example_mods/AutoCloseBox/gl_auto_closebox.ssl b/artifacts/example_mods/AutoCloseBox/gl_auto_closebox.ssl index a4d1a7ea..0c6f9e23 100644 --- a/artifacts/example_mods/AutoCloseBox/gl_auto_closebox.ssl +++ b/artifacts/example_mods/AutoCloseBox/gl_auto_closebox.ssl @@ -13,8 +13,10 @@ Requires sfall 4.2.2/3.8.29 or higher #include "..\headers\sfall\define_extra.h" procedure start; +procedure close; variable lootObject; +variable closeObject; procedure start begin if (game_loaded) then begin @@ -26,8 +28,14 @@ procedure start begin lootObject := loot_obj; if (obj_type(lootObject) != OBJ_TYPE_ITEM) then lootObject = 0; end else if (lootObject andAlso get_sfall_arg_at(1) == INTFACELOOT) then begin - obj_close(lootObject); - lootObject = 0; + if (get_object_data(lootObject, OBJ_DATA_CUR_FRM) > 1) then begin + closeObject = lootObject; + call close in 0; + end end end end + +procedure close begin + obj_close(closeObject); +end diff --git a/artifacts/mods/gl_highlighting.int b/artifacts/mods/gl_highlighting.int index fca11798..ecfbf585 100644 Binary files a/artifacts/mods/gl_highlighting.int and b/artifacts/mods/gl_highlighting.int differ diff --git a/artifacts/mods/gl_npcarmor.int b/artifacts/mods/gl_npcarmor.int index 1fb06619..23bfdaa7 100644 Binary files a/artifacts/mods/gl_npcarmor.int and b/artifacts/mods/gl_npcarmor.int differ diff --git a/artifacts/mods/gl_npcarmor.ssl b/artifacts/mods/gl_npcarmor.ssl index 422154cd..4d00e48a 100644 --- a/artifacts/mods/gl_npcarmor.ssl +++ b/artifacts/mods/gl_npcarmor.ssl @@ -9,7 +9,7 @@ NOTE: this script requires compiler from sfall modderspack with -s option (short circuit evaluation) - version 1.1 + version 1.2 */ @@ -21,6 +21,7 @@ #define FID_OBJ_CRITTER (0x01000000) procedure update_armor_apperance; +procedure canuseweapon_handler; variable modIni := "npcarmor.ini", @@ -203,6 +204,7 @@ procedure start begin register_hook_proc(HOOK_INVENWIELD, invenwield_handler); register_hook_proc(HOOK_ADJUSTFID, adjustfid_handler); register_hook_proc(HOOK_INVENTORYMOVE, inventorymove_handler); + register_hook_proc_spec(HOOK_CANUSEWEAPON, canuseweapon_handler); debug_msg("NPC armor appearance mod: Done."); end @@ -220,3 +222,14 @@ procedure update_armor_apperance begin end end end + +procedure canuseweapon_handler begin + variable critter, canWield; + critter := get_sfall_arg; + //if (critter) then begin + canWield := check_weapon_change(critter, get_sfall_arg, true); + // override result + set_sfall_arg(3, canWield); + set_sfall_return(canWield); + //end +end diff --git a/artifacts/mods/gl_partycontrol.ssl b/artifacts/mods/gl_partycontrol.ssl index c852c649..39babe9c 100644 --- a/artifacts/mods/gl_partycontrol.ssl +++ b/artifacts/mods/gl_partycontrol.ssl @@ -137,7 +137,7 @@ end procedure start begin if (game_loaded and sfall_ver_major >= 4) then begin - variable configSection := "CombatControl"; + //variable configSection := "CombatControl"; set_perk_ranks(PERK_gecko_skinning_perk, 1); set_perk_level(PERK_gecko_skinning_perk, 999); // prevent it from appearing in the perk selection window diff --git a/artifacts/mods/main.h b/artifacts/mods/main.h index 28c719f3..5f545e45 100644 --- a/artifacts/mods/main.h +++ b/artifacts/mods/main.h @@ -25,7 +25,7 @@ end // Gets the string value from the specified ini procedure GetIniConfigStr(variable section, variable key, variable def, variable inifile) begin variable val := get_ini_string(inifile + "|" + section + "|" + key); - if val == -1 or val == "" then val := def; + if val == -1 orElse val == "" then val := def; return val; end @@ -39,14 +39,14 @@ end // Gets the string value from sfall-mods.ini procedure GetConfigStr(variable section, variable key, variable def) begin variable val := get_ini_string(ini + "|" + section + "|" + key); - if val == -1 or val == "" then val := def; + if val == -1 orElse val == "" then val := def; return val; end // Gets the value from sfall-mods.ini as a temp array of strings procedure GetConfigList(variable section, variable key) begin variable val := get_ini_string(ini + "|" + section + "|" + key); - if val == -1 or val == "" then return []; + if val == -1 orElse val == "" then return []; return string_split(val, ","); end @@ -65,7 +65,7 @@ end // Translates given string using Translations.ini procedure Translate(variable id, variable def) begin variable str := get_ini_string(translationIni + "|Sfall|" + id); - if not str or (strlen(str) == 0) then begin + if (str == 0 orElse (strlen(str) == 0)) then begin str := def; end return str; diff --git a/artifacts/scripting/README.md b/artifacts/scripting/README.md new file mode 100644 index 00000000..018bdf2f --- /dev/null +++ b/artifacts/scripting/README.md @@ -0,0 +1,25 @@ +This folder contains documentation about sfall scripting extensions. + + headers\ - folder contains sfall headers that you should #include in your scripts + sfall.h - main sfall header, always include it + define_extra.h - some additional preprocessor constants for vanilla engine stuff (proto offsets, etc.) + define_lite.h - a lite version of official define.h + command_lite.h - a lite version of official command.h + dik.h - DX scancodes constants for use with key_pressed function and HOOK_KEYPRESS + lib.arrays.h - procedures that will help you use arrays in their full: + - use them as stacks, sets + - easily compare, copy, slice, cut, add arrays + - display array contents (for debugging) + - save/load two-dimensional arrays to savegame in one command (e.g. arrays of objects) + lib.inven.h - fallout items manipulation functions + lib.math.h - a few simple functions for calculations + lib.strings.h - search in strings, join, repeat, etc. + lib.misc.h - misc stuff + + sfall function notes.md - incomplete reference for new opcodes + sfall opcode list.md - list of all sfall opcodes (w/o descriptions) + hookscripts.md - detailed manual for using hook scripts to modify engine behavior + arrays.md - manual for sfall arrays + +If you are/will be using sfall Script Editor, don't forget to check out new compiler documentation in **.\compiler\sslc_readme.txt**. +There are numerious new syntax features and extensions to SSL (Star-Trek Scripting language). diff --git a/artifacts/scripting/README.txt b/artifacts/scripting/README.txt index 8c766d99..c5e1dc89 100644 --- a/artifacts/scripting/README.txt +++ b/artifacts/scripting/README.txt @@ -4,12 +4,13 @@ This folder contains documentation about sfall scripting extensions. sfall.h - main sfall header, always include it define_extra.h - some additional preprocessor constants for vanilla engine stuff (proto offsets, etc.) define_lite.h - a lite version of official define.h + command_lite.h - a lite version of official command.h dik.h - DX scancodes constants for use with key_pressed function and HOOK_KEYPRESS lib.arrays.h - procedures that will help you use arrays in their full: - - use them as stacks, sets - - easily compare, copy, slice, cut, add arrays - - display array contents (for debugging) - - save/load two-dimensional arrays to savegame in one command (e.g. arrays of objects) + - use them as stacks, sets + - easily compare, copy, slice, cut, add arrays + - display array contents (for debugging) + - save/load two-dimensional arrays to savegame in one command (e.g. arrays of objects) lib.inven.h - fallout items manipulation functions lib.math.h - a few simple functions for calculations lib.strings.h - search in strings, join, repeat, etc. @@ -20,6 +21,5 @@ This folder contains documentation about sfall scripting extensions. hookscripts.txt - detailed manual for using hook scripts to modify engine behavior arrays.txt - manual for sfall arrays -If you are/will be using sfall Script Editor, don't forget to check out new compiler documentation in ScriptEditor\docs\sslc_readme.txt, -there are numerious new syntax features and extensions to SSL (Star-Trek Scripting language). - +If you are/will be using sfall Script Editor, don't forget to check out new compiler documentation in .\compiler\sslc_readme.txt. +There are numerious new syntax features and extensions to SSL (Star-Trek Scripting language). diff --git a/artifacts/scripting/arrays.md b/artifacts/scripting/arrays.md new file mode 100644 index 00000000..b905991b --- /dev/null +++ b/artifacts/scripting/arrays.md @@ -0,0 +1,244 @@ +ARRAYS +------ + +sfall introduces new method of storing variables - arrays. + +Array is basically a container which can store variable number of values (elements). Each element in array can be of any type. +Arrays can be extremely useful for some more advanced scripting, in conjunction with loops. + +*** +### ARRAYS CONCEPT + +Arrays are created and manipulated with the array functions. An array must first be created with `create_array` or `temp_array`, specifying how many data elements the array can hold. You can store any of ints, floats and strings in an array, and can mix all 3 in a single array. The ID returned by `create_array` or `temp_array` can then be used with the other array functions. Arrays are shared between all scripts (i.e. you can call `create_array` from one script, and then use the returned ID from another script). They are also saved across savegames. + +Arrays created with `temp_array` will be automatically freed at the end of the frame. These functions are safe, in that supplying a bad ID or trying to access out of range elements will not crash the script. `create_array` is the only function that returns a permanent array, all other functions which return arrays (`string_split`, `list_as_array`, etc,) all return temporary arrays. You can use `fix_array` to make a temporary array permanent. + +Array elements are accessed by index or key. For example: +```js +// this code puts some string in array "list" at index 5: +list[5] := "Value"; +``` + +There are 2 different types of arrays currently available: + +* **Lists** - a set of values with specific size (number of elements), where all elements have numeric indexes starting from zero (0) up to array length minus one. + + For example: + ```js + // this creates list with 3 elements. Element "A" has index 0, element "B" has index 1, element "C" - 2 + list := ["A", "B", "C"]; + ``` + + Limitations: + - all indexes are numeric, starting from 0; + - to assign value to a specific index, you must first resize array to contain this index + (for example, if list is of size 3 (indexes from 0 to 2), you can't assign value to index 4 unless you change list size to 5 first). + +* **Maps** (or associative arrays) - a set of key=>value pairs, where all elements (values) are accessed by corresponding keys. + + Differences from list: + - maps don't have specific size (to assign values, you don't need to resize array first); + - keys, just like values, can be of any type (but avoid using -1 as array keys or you won't be able to use some functions reliably). + +Both array types have their pros and cons and are suited for different tasks. + +___ +### ARRAYS SYNTAX + +Basically arrays are implemented using number of new operators (scripting functions). But for ease of use, there are some new syntax elements: + +* Accessing elements. Use square brackets: + ```js + display_msg(arr[5]); + mymap["price"] := 515.23; + ``` + +* Alternative accessing for maps. Use dot: + ```js + display_msg(mymap.name); + mymap.price := 232.23; + ``` + +* Array expressions. Create and fill arrays with just one expression: + ```js + // create list with 5 values + [5, 777, 0, 3.14, "Cool Value"] + + // create map: + {5: "Five", "health": 50, "speed": 0.252} + ``` + __NOTES:__ + Make sure to call `fix_array` if you want new array to be available in the next frame or `save_array` if you want to use it for a longer period (see next section for details). + +* Iterating in loop. Use `foreach` key word like this: + ```js + foreach (item in myarray) begin + // this block is executed for each array element, where "item" contains current value on each step + end + + // alternative syntax: + foreach (key: item in myarray) begin + // "key" will contain current key (or numeric index, for lists) + end + ``` + +See **sslc_readme.txt** file for full information on new SSL syntax features. + +___ +### STORING ARRAYS + +Apart from lists/maps, arrays are divided by how they are stored. +There a 3 types of arrays: + +* **Temporary**. They are created using `temp_array` function or when using array expressions. +Arrays of this type are auto-deleted at the end of the frame. So, for example, if you have a global script which runs at regular intervals, where you create a temporary array, it will not be available next time your global script is executed. + +* **Permanent**. They are created using `create_array` function or `fix_array` (from pre-existing temporary array). +This type of arrays are always available (by their ID) until you start a new game or load a saved game (at which point they are deleted). + +* **Saved**. If you want your array to really stay for a while, use function `save_array` to make any array "saved". However, they are, like permanent arrays, "deleted" from memory when loading game. In order to use them properly, you must load them from the savegame using `load_array` whenever you want to use them. + + Example: + ```js + variable savedArray; + procedure start begin + if game_loaded then begin + savedArray := load_array("traps"); + end else begin + foreach trap in traps begin + .... + end + end + end + ``` + +___ +### PRACTICAL EXAMPLES + +**Use arrays to implement variable-argument procedures:** +```js +// define it +procedure give_item(variable critter, variable pidList) begin + foreach (pid: qty in pidList) begin + give_pid_qty(critter, pid, qty); + end +end + +// call it: +call give_item(dude_obj, {PID_SHOTGUN: 1, PID_SHOTGUN_SHELLS: 4, PID_STIMPAK: 3}); +``` + +**Create arrays of objects (maps) for advanced scripting:** +```js +variable traps; +procedure init_traps begin + // just a quick example, there is a better way of doing it... + traps := load_array("traps"); + if (traps == 0) then begin + traps := []; + save_array("traps", traps); + end + foreach k: v in traps begin + traps[k] := load_array("trap_"+k); // each object is stored separately + end +end + +procedure add_trap(variable trapArray) begin + variable index; + index := len_array(traps); + save_array("trap_"+k, trapArray); + array_push(traps, trapArray); +end + +// use them: +foreach trap in traps begin + if (self_elevation == trap["elev"] and tile_distance(self_tile, trap["tile"]) < trap["radius"]) then + // kaboom!!! + end +end +``` + +___ +### ARRAY OPERATORS REFERENCE + +_*mixed means any type_ + +#### `int create_array(int size, int flags)` +- creates permanent array (but not "saved") +- if `size >= 0`, creates list with given size +- if `size == -1`, creates map (associative array) +- if `size == -1` and `flags == 2`, creates a "lookup" map (associative array) in which the values of existing keys are read-only and can't be updated. This type of array allows you to store a zero (0) key value + * NOTE: in earlier versions (up to 4.1.3/3.8.13) the second argument is not used, just use 0 +- returns array ID (valid until array is deleted) + +#### `int temp_array(int size, int flags)` +- works exactly like `create_array`, only created array becomes "temporary" + +#### `void fix_array(int arrayID)` +- changes "temporary" array into "permanent" ("permanent" arrays are not automatically saved into savegames) + +#### `void set_array(int arrayID, mixed key, mixed value)` +- sets array value +- if used on list, "key" must be numeric and within valid index range (0..size-1) +- if used on map, key can be of any type +- to "unset" a value from map, just set it to zero (0) + * NOTE: to add a value of 0 for the key, use the float value of 0.0 +- this works exactly like statement: `arrayID[key] := value;` + +#### `mixed get_array(int arrayID, mixed key)` +- returns array value by key or index +- if key doesn't exist or index is not in valid range, returns 0 +- works exactly like expression: `(arrayID[key])` + +#### `void resize_array(int arrayID, int size)` +- changes array size +- applicable to maps too, but only to reduce elements +- there are number of special negative values of "size" which perform various operations on the array, use macros `sort_array`, `sort_array_reverse`, `reverse_array`, `shuffle_array` from **sfall.h** header + +#### `void free_array(int arrayID)` +- deletes any array +- if array was "saved", it will be removed from a savegame + +#### `mixed scan_array(int arrayID, mixed value)` +- searches for a first occurence of given value inside given array +- if value is found, returns it's index (for lists) or key (for maps) +- if value is not found, returns -1 (be careful, as -1 can be a valid key for a map) + +#### `int len_array(int arrayID)` +- returns number of elements or key=>value pairs in a given array +- if array is not found, returns -1 (can be used to check if given array exist) + +#### `mixed array_key(int arrayID, int index)` +- don't use it directly; it is generated by the compiler in foreach loops +- for lists, returns index back (no change) +- for maps, returns a key at the specified numeric index (don't rely on the order in which keys are stored though) +- can be checked if given array is associative or not, by using index (-1): 0 - array is list, 1 - array is map + +#### `int arrayexpr(mixed key, mixed value)` +- don't use it directly; it is used by compiler to create array expressions +- assigns value to a given key in an array, created by last `create_array` or `temp_array` call +- always returns 0 + +#### `void save_array(mixed key, int arrayID)` +- makes the array saveable; it will be saved in **sfallgv.sav** file when saving the game +- array ID is associated with given "key" +- array becomes permanent (if it was temporary) and "saved" +- key can be of any type (int, float or string) +- if you specify 0 as the key for the array ID, it will make the array "unsaved" + +#### `int load_array(mixed key)` +- loads array from savegame data by the same key provided in `save_array` +- returns array ID or zero (0) if none found + + +___ +### BACKWARD COMPATIBILITY NOTES + +For those who used arrays in their mods before sfall 3.4: + +* There is an INI parameter **arraysBehavior** in **Misc** section of ddraw.ini. If set to 0, all scripts which used sfall arrays before should work. This basically changes that `create_array` will create permanent arrays which are "saved" by default and their ID is also permanent. It is 1 by default. + +* How savegame compatibility is handled?
+ Saved arrays are stored in **sfallgv.sav** file (in savegame) in new (more flexible) format, just after the old arrays. So basically, when you load older savegame, sfall will load arrays from old format and save them to new format on next game save. If you load savegame made with sfall 3.4 using sfall 3.3 (for example), game shouldn't crash, but all arrays will be lost. + +* Previously you had to specify size in bytes for array elements. This parameter is now ignored and you can store strings of arbitrary length in arrays. diff --git a/artifacts/scripting/arrays.txt b/artifacts/scripting/arrays.txt deleted file mode 100644 index 44f2b7a3..00000000 --- a/artifacts/scripting/arrays.txt +++ /dev/null @@ -1,234 +0,0 @@ ->>> ARRAYS CONCEPT <<< - -Sfall introduces new method of storing variables - arrays. - -Array is basically a container which can store variable number of values (elements). Each element in array can be of any type. -Arrays can be extremely useful for some more advanced scripting, in conjunction with loops. - -Array elements are accessed by index or key. For example: - - // this code puts some string in array "list" at index 5: - list[5] := "Value"; - - -There are 2 different types of arrays currently available: -1) Lists - a set of values with specific size (number of elements), where all elements have numeric indexes starting from zero (0) up to array length minus one. -For example: - - // this creates list with 3 elements. Element "A" has index 0, element "B" has index 1, element "C" - 2 - list := ["A", "B", "C"]; - -Limitations: -- all indexes are numeric, starting from 0; -- to assign value to a specific index, you must first resize array to contain this index -(for example, if list is of size 3 (indexes from 0 to 2), you can't assign value to index 4 unless you change list size to 5 first). - - -2) Maps (or associative arrays) - a set of key=>value pairs, where all elements (values) are accessed by corresponding keys. -Differences from list: -- maps don't have specific size (to assign values, you don't need to resize array first); -- keys, just like values, can be of any type (but avoid using -1 as array keys or you won't be able to use some functions reliably). - -Both array types have their pros and cons and are suited for different tasks. - - ->>> ARRAYS SYNTAX <<< - -Basically arrays are implemented using number of new operators (scripting functions). But for ease of use, there are some new syntax elements: - -1) Accessing elements. Use square brackets: - - display_msg(arr[5]); - mymap["price"] := 515.23; - -2) Alternative accessing for maps. Use dot: - - display_msg(mymap.name); - mymap.price := 232.23; - -3) Array expressions. Create and fill arrays with just one expression: - - // create list with 5 values - [5, 777, 0, 3.14, "Cool Value"] - - // create map: - {5: "Five", "health": 50, "speed": 0.252} - -NOTES: -- make sure to call "fix_array" if you want new array to be available in the next frame or "save_array" if you want to use it for a longer period -(see next section for details) - - -4) Iterating in loop. Use "foreach" key word like this: - - foreach (item in myarray) begin - // this block is executed for each array element, where "item" contains current value on each step - end - - // alternative syntax: - foreach (key: item in myarray) begin - // "key" will contain current key (or numeric index, for lists) - end - -See "Script editor\docs\sslc readme.txt" file for full information on new SSL syntax features. - ->>> STORING ARRAYS <<< - -Apart from lists/maps arrays are divided by how they are stored. -There a 3 types of arrays: - -1) Temporary. They are created using temp_array function or when using array expressions. -Arrays of this type are auto-deleted at the end of the frame. So, for example, if you have a global script which runs at regular intervals, -where you create temp_array, it will not be available next time your global script is executed. - -2) Permanent. They are created using "create_array" function or "fix_array" (from pre-existing temporary array). -This type of arrays are always available (by their ID) until you start a new game or load a saved game (at which point they are deleted). - -3) Saved. If you want your array to really stay for a while, use function "save_array" to make any array "saved". However, they are, like permanent arrays, -"deleted" from memory when loading game. In order to use them properly, you must load them from the savegame using "load_array" whenever you want to use them. -Example: - - variable savedArray; - procedure start begin - if game_loaded then begin - savedArray := load_array("traps"); - end else begin - foreach trap in traps begin - .... - end - end - end - - - ->>> PRACTICAL EXAMPLES <<< - -> Use arrays to implement variable-argument procedures: - - // define it - procedure give_item(variable critter, variable pidList) begin - foreach (pid: qty in pidList) begin - give_pid_qty(critter, pid, qty); - end - end - - // call it: - call give_item(dude_obj, {PID_SHOTGUN: 1, PID_SHOTGUN_SHELLS: 4, PID_STIMPAK: 3}); - - -> Create arrays of objects (maps) for advanced scripting: - - variable traps; - procedure init_traps begin - // just a quick example, there is a better way of doing it... - traps := load_array("traps"); - if (traps == 0) then begin - traps := []; - save_array("traps", traps); - end - foreach k: v in traps begin - traps[k] := load_array("trap_"+k); // each object is stored separately - end - end - - procedure add_trap(variable trapArray) begin - variable index; - index := len_array(traps); - save_array("trap_"+k, trapArray); - array_push(traps, trapArray); - end - - // use them: - foreach trap in traps begin - if (self_elevation == trap["elev"] and tile_distance(self_tile, trap["tile"]) < trap["radius"]) then - // kaboom!!! - end - end - - - ->>> ARRAY OPERATORS REFERENCE <<< - -*mixed means any type - -> int create_array(int size, int flags): -- creates permanent array (but not "saved") -- if size is >= 0, creates list with given size -- if size == -1, creates map (associative array) -- if size == -1 and flags == 2, creates a "lookup" map (associative array) in which the values of existing keys are read-only and can't be updated. -This type of array allows you to store a zero (0) key value -- NOTE: in earlier versions (up to 4.1.3/3.8.13) the second argument is not used, just use 0 -- returns arrayID (valid until array is deleted) - -> int temp_array(int size, int flags): -- works exactly like "create_array", only created array becomes "temporary" - -> void fix_array(int arrayID): -- changes "temporary" array into "permanent" ("permanent" arrays are not automatically saved into savegames) - -> void set_array(int arrayID, mixed key, mixed value): -- sets array value -- if used on list, "key" must be numeric and within valid index range (0..size-1) -- if used on map, key can be of any type -- to "unset" a value from map, just set it to zero (0) -- NOTE: to add a value of 0 for the key, use the float value of 0.0 -- this works exactly like statement: - arrayID[key] := value; - -> mixed get_array(int arrayID, mixed key): -- returns array value by key or index -- if key doesn't exist or index is not in valid range, returns 0 -- works exactly like expression: - (arrayID[key]) - -> void resize_array(int arrayID, int size): -- changes array size -- applicable to maps too, but only to reduce elements -- there are number of special negative values of "size" which perform various operations on the array, -use macros sort_array, sort_array_reverse, reverse_array, shuffle_array from sfall.h header - -> void free_array(int arrayID): -- deletes any array -- if array was "saved", it will be removed from a savegame - -> mixed scan_array(int arrayID, mixed value): -- searches for a first occurence of given value inside given array -- if value is found, returns it's index (for lists) or key (for maps) -- if value is not found, returns -1 (be careful, as -1 can be a valid key for a map) - -> int len_array(int arrayID): -- returns number of elements or key=>value pairs in a given array -- if array is not found, returns -1 (can be used to check if given array exist) - -> mixed array_key(int arrayID, int index): -- don't use it directly; it is generated by the compiler in foreach loops -- for lists, returns index back (no change) -- for maps, returns a key at the specified numeric index (don't rely on the order in which keys are stored though) -- can be checked if given array is associative or not, by using index (-1): 0 - array is list, 1 - array is map - -> int arrayexpr(mixed key, mixed value): -- don't use it directly; it is used by compiler to create array expressions -- assigns value to a given key in an array, created by last "create_array" or "temp_array" call -- always returns 0 - -> void save_array(mixed key, int arrayID): -- makes the array saveable; it will be saved in sfallgv.sav file when saving the game -- arrayID is associated with given "key" -- array becomes permanent (if it was temporary) and "saved" -- key can be of any type (int, float or string) -- if you specify 0 as the key for the array ID, it will make the array "unsaved" - -> int load_array(mixed key): -- load array from savegame data by the same key provided in "save_array" -- arrayID is returned or zero (0) if none found - - - ->>> BACKWARD COMPATIBILITY NOTES <<< - -For those who used arrays in their mods before sfall 3.4: -1) There is an INI parameter "arraysBehavior" in "Misc" section of ddraw.ini. If set to 0, all scripts which used sfall arrays before should work. This basically changes that "create_array" will create permanent arrays which are "saved" by default and their ID is also permanent. It is 1 by default. -2) How savegame compatibility is handled? -Saved arrays are stored in sfallgv.sav file (in savegame) in new (more flexible) format, just after the old arrays. So basically, when you load older savegame, sfall will load arrays from old format and save them to new format on next game save. If you load savegame made with sfall 3.4 using sfall 3.3 (for example), game shouldn't crash, but all arrays will be lost. -3) Previously you had to specify size in bytes for array elements. This parameter is now ignored and you can store strings of arbitrary length in arrays. - diff --git a/artifacts/scripting/compiler/sslc_readme.txt b/artifacts/scripting/compiler/sslc_readme.txt index 360921a7..7a30d406 100644 --- a/artifacts/scripting/compiler/sslc_readme.txt +++ b/artifacts/scripting/compiler/sslc_readme.txt @@ -90,7 +90,7 @@ old: x := 5; -> Multiple variable decleration: Multiple variables can be declared on one line, seperated by commas. This is an alterative to the ugly begin/end block, or the bulky single variable per line style. +> Multiple variable declaration: Multiple variables can be declared on one line, seperated by commas. This is an alterative to the ugly begin/end block, or the bulky single variable per line style. new: variable a, b, c; diff --git a/artifacts/scripting/functions.yml b/artifacts/scripting/functions.yml new file mode 100644 index 00000000..91d48ba3 --- /dev/null +++ b/artifacts/scripting/functions.yml @@ -0,0 +1,1903 @@ +# Important notes on format: +# +# 1. The file must be valid YAML. (Use VScode with YAML extension to check). +# +# 2. General structure: +# - name: Category name # REQUIRED, must be UNIQUE +# parent: Parent category name # OPTIONAL. If set, will generate a subcategory page on the site. Parent category must exist. +# doc: Category doc # OPTIONAL. Must be RELEVANT for ALL functions in the category. Will be displayed in IDE for EACH function under this category, in addition to function's individual doc. +# items: +# - name: function_name # REQUIRED +# detail: void function_name(ObjectPtr obj, string text) # REQUIRED. Invocation details. SINGLE line. Will be displayed in IDE. +# doc: fuction documentation in markdown format # OPTIONAL. Will be displayed in IDE. +# opcode: function opcode # OPTIONAL +# unsafe: true/false # OPTIONAL. Whether it requires AllowUnsafeScripting. +# macro: header file name # OPTIONAL. What to include to use this. + +- name: Direct memory access # just parent page + +- name: read_xxx + parent: Direct memory access + doc: These functions take a memory address as the parameter and can read arbitrary pieces of Fallout's address space. + items: + - name: read_byte + detail: int read_byte(int address) + opcode: 0x8156 + - name: read_short + detail: int read_short(int address) + opcode: 0x8157 + - name: read_int + detail: int read_int(int address) + opcode: 0x8158 + - name: read_string + detail: int read_string(int address) + opcode: 0x8159 + +- name: write_xxx + parent: Direct memory access + doc: These functions take a memory address as the parameter and can write to arbitrary pieces of Fallout's address _None of these functions will work unless_ `AllowUnsafeScripting` _is enabled in_ `ddraw.ini`. + items: + - name: write_byte + detail: void write_byte(int address, int value) + opcode: 0x81cf + unsafe: true + - name: write_short + detail: void write_short(int address, int value) + opcode: 0x81d0 + unsafe: true + - name: write_int + detail: void write_int(int address, int value) + opcode: 0x81d1 + unsafe: true + - name: write_string + detail: void write_string(int address, string value) + opcode: 0x821b + unsafe: true + +- name: call_offset_vX + parent: Direct memory access + doc: Can be used to call arbitrary functions inside Fallout. Different versions are used to call functions with different numbers of arguments. _None of these functions will work unless_ `AllowUnsafeScripting` _is enabled in_ `ddraw.ini`. + items: + - name: call_offset_v0 + detail: void call_offset_v0(int address) + opcode: 0x81d2 + unsafe: true + - name: call_offset_v1 + detail: void call_offset_v1(int address, int arg1) + opcode: 0x81d3 + unsafe: true + - name: call_offset_v2 + detail: void call_offset_v2(int address, int arg1, int arg2) + opcode: 0x81d4 + unsafe: true + - name: call_offset_v3 + detail: void call_offset_v3(int address, int arg1, int arg2, int arg3) + opcode: 0x81d5 + unsafe: true + - name: call_offset_v4 + detail: void call_offset_v4(int address, int arg1, int arg2, int arg3, int arg4) + opcode: 0x81d6 + unsafe: true + - name: call_offset_r0 + detail: int call_offset_r0(int address) + opcode: 0x81d7 + unsafe: true + - name: call_offset_r1 + detail: int call_offset_r1(int address, int arg1) + opcode: 0x81d8 + unsafe: true + - name: call_offset_r2 + detail: int call_offset_r2(int address, int arg1, int arg2) + opcode: 0x81d9 + unsafe: true + - name: call_offset_r3 + detail: int call_offset_r3(int address, int arg1, int arg2, int arg3) + opcode: 0x81da + unsafe: true + - name: call_offset_r4 + detail: int call_offset_r4(int address, int arg1, int arg2, int arg3, int arg4) + opcode: 0x81db + unsafe: true + +- name: Stats + doc: The `get/set_pc_base/extra_stat` functions are equivalent to calling `get/set_critter_base/extra_stat` with `dude_obj` as the critter pointer. None of these stat functions take perks into account, and neither do they do range clamping to make sure the stats are valid. Use the normal `get_critter_stat` function to get a correctly perk adjusted and range clamped value for a stat. + items: + - name: set_pc_base_stat + detail: void set_pc_base_stat(int StatID, int value) + opcode: 0x815a + - name: set_pc_extra_stat + detail: void set_pc_extra_stat(int StatID, int value) + opcode: 0x815b + - name: get_pc_base_stat + detail: int get_pc_base_stat(int StatID) + opcode: 0x815c + - name: get_pc_extra_stat + detail: int get_pc_extra_stat(int StatID) + opcode: 0x815d + - name: set_critter_base_stat + detail: void set_critter_base_stat(CritterPtr, int StatID, int value) + opcode: 0x815e + - name: set_critter_extra_stat + detail: void set_critter_extra_stat(CritterPtr, int StatID, int value) + opcode: 0x815f + - name: get_critter_base_stat + detail: int get_critter_base_stat(CritterPtr, int StatID) + opcode: 0x8160 + - name: get_critter_extra_stat + detail: int get_critter_extra_stat(CritterPtr, int StatID) + opcode: 0x8161 + - name: get_stat_min + detail: get_stat_min(int stat, bool who = False) + doc: | + - Returns the minimum set value of the specified stat (see `set_stat_min` functions) + - who: 0 (`false`) or omitting the argument - returns the value of the player, 1 (true) - returns the value set for other critters + - name: get_stat_max + detail: get_stat_max(int stat, bool who = False) + doc: | + - Returns the maximum set value of the specified stat (see `set_stat_max` functions) + - who: 0 (`false`) or omitting the argument - returns the value of the player, 1 (true) - returns the value set for other critters + +- name: Alter min/max + doc: The `set_stat_max/min` functions can be used to set the valid ranges on stats. Values returned by `get_current_stat` will be clamped to this range. The `set_pc_` function only affects the player, the `set_npc_` functions only affects other critters, and the `set_` functions affects both. + parent: Stats + items: + - name: set_stat_max + detail: void set_stat_max(int stat, int value) + opcode: 0x81b4 + - name: set_stat_min + detail: void set_stat_min(int stat, int value) + opcode: 0x81b5 + - name: set_pc_stat_max + detail: void set_pc_stat_max(int stat, int value) + opcode: 0x81b7 + - name: set_pc_stat_min + detail: void set_pc_stat_min(int stat, int value) + opcode: 0x81b8 + - name: set_npc_stat_max + detail: void set_npc_stat_max(int stat, int value) + opcode: 0x81b9 + - name: set_npc_stat_min + detail: void set_npc_stat_min(int stat, int value) + opcode: 0x81ba + +- name: Skills + items: + - name: set_critter_skill_points + detail: void set_critter_skill_points(int critter, int skill, int value) + opcode: 0x8242 + doc: Will set the number of additional points a critter has in a skill, on top of whatever they have from their stats and other bonuses. Note that skill points are part of the proto, so calling it on a critter will affect all critters that share the same proto. + - name: get_critter_skill_points + detail: int get_critter_skill_points(int critter, int skill) + opcode: 0x8243 + doc: Will get the number of additional points a critter has in a skill, on top of whatever they have from their stats and other bonuses + - name: set_available_skill_points + detail: void set_available_skill_points(int value) + opcode: 0x8244 + - name: get_available_skill_points + detail: int get_available_skill_points() + opcode: 0x8245 + + - name: set_skill_max + detail: void set_skill_max(int value) + opcode: 0x81a2 + doc: Can't be used to increase the skill cap above 300. + - name: set_critter_skill_mod + detail: void set_critter_skill_mod(CritterPtr, int max) + opcode: 0x81c7 + - name: set_base_skill_mod + detail: void set_base_skill_mod(int max) + opcode: 0x81c8 + - name: mod_skill_points_per_level + detail: void mod_skill_points_per_level(int value) + doc: Accepts a value of between -100 and 100, and modifies the number of skill points the player recieves when they level up. This is a modification of what would otherwise happen, rather than a replacement. The value is not saved into the save game, so should be reset in the `game_loaded` section of a script. + opcode: 0x8246 + +- name: Graphics + doc: The graphics functions are only available if the user is using graphics mode 4 or 5. Use `graphics_funcs_available` to check; it returns 1 if you can use them or 0 if you can't. Calling graphics functions when `graphics_funcs_available` returns 0 will do nothing. + items: + - name: graphics_funcs_available + detail: bool graphics_funcs_available + opcode: 0x8165 + - name: load_shader + detail: int load_shader(string path) + doc: Takes a path relative to the `\\shaders\` directory as an argument and returns a shader ID. That ID should be passed as the first argument to all other shader functions, and is valid until `free_shader` is called on the ID, the player loads a saved game or the player quits to the main menu. + opcode: 0x8166 + - name: free_shader + detail: void free_shader(int ID) + opcode: 0x8167 + - name: activate_shader + detail: void activate_shader(int ID) + opcode: 0x8168 + - name: deactivate_shader + detail: void deactivate_shader(int ID) + opcode: 0x8169 + - name: set_shader_int + detail: void set_shader_int(int ID, string param, int value) + opcode: 0x816d + - name: set_shader_float + detail: void set_shader_float(int ID, string param, float value) + opcode: 0x816e + - name: set_shader_vector + detail: void set_shader_vector(int ID, string param, float f1, float f2, float f3, float f4) + opcode: 0x816f + - name: get_shader_version + detail: int get_shader_version + doc: Gives you the highest shader version supported by the player's graphics cards. Possible return values are 11, 12, 13, 14, 20, 21 and 30. + opcode: 0x81ad + - name: set_shader_mode + detail: void set_shader_mode(int mode) + opcode: 0x81ae + doc: Tells sfall when to use a shader. The parameter is a set of 32 flags which specify the screens on which the shader will be disabled, unless bit 32 is set, in which case the shader will only be active on those screens. Remember that screens are displayed on top of each other; if the player opens the character menu which in combat, the game still considers the player to be in combat. See `sfall.h` for a list of defines. + - name: force_graphics_refresh + detail: void force_graphics_refresh(bool enabled) + opcode: 0x81b0 + doc: Forces the screen to redraw at times when it normally wouldn't. If you're using animated shader, turning this option on is recommended. + - name: get_shader_texture + detail: int get_shader_texture(int ID, int texture) + opcode: 0x81b1 + - name: set_shader_texture + detail: void set_shader_texture(int ID, string param, int texID) + opcode: 0x81b2 + - name: get_screen_width + detail: int get_screen_width() + opcode: 0x8220 + - name: get_screen_height + detail: int get_screen_height() + opcode: 0x8221 + - name: set_palette + detail: void set_palette(string path) + opcode: 0x81f2 +- name: Perks and traits + items: + - name: set_perk_image + detail: void set_perk_image(int perkID, int value) + opcode: 0x8178 + - name: set_perk_ranks + detail: void set_perk_ranks(int perkID, int value) + opcode: 0x8179 + - name: set_perk_level + detail: void set_perk_level(int perkID, int value) + opcode: 0x817a + - name: set_perk_stat + detail: void set_perk_stat(int perkID, int value) + opcode: 0x817b + - name: set_perk_stat_mag + detail: void set_perk_stat_mag(int perkID, int value) + opcode: 0x817c + - name: set_perk_skill1 + detail: void set_perk_skill1(int perkID, int value) + opcode: 0x817d + - name: set_perk_skill1_mag + detail: void set_perk_skill1_mag(int perkID, int value) + opcode: 0x817e + - name: set_perk_type + detail: void set_perk_type(int perkID, int value) + opcode: 0x817f + - name: set_perk_skill2 + detail: void set_perk_skill2(int perkID, int value) + opcode: 0x8180 + - name: set_perk_skill2_mag + detail: void set_perk_skill2_mag(int perkID, int value) + opcode: 0x8181 + - name: set_perk_str + detail: void set_perk_str(int perkID, int value) + opcode: 0x8182 + - name: set_perk_per + detail: void set_perk_per(int perkID, int value) + opcode: 0x8183 + - name: set_perk_end + detail: void set_perk_end(int perkID, int value) + opcode: 0x8184 + - name: set_perk_chr + detail: void set_perk_chr(int perkID, int value) + opcode: 0x8185 + - name: set_perk_int + detail: void set_perk_int(int perkID, int value) + opcode: 0x8196 + - name: set_perk_agl + detail: void set_perk_agl(int perkID, int value) + opcode: 0x8187 + - name: set_perk_lck + detail: void set_perk_lck(int perkID, int value) + opcode: 0x8188 + - name: set_perk_name + detail: void set_perk_name(int perkID, string value) + opcode: 0x8189 + - name: set_perk_desc + detail: void set_perk_desc(int perkID, string value) + opcode: 0x818a + - name: set_perk_freq + detail: void set_perk_freq(int value) + opcode: 0x8247 + doc: Sets the number of levels between each perk. Setting to 0 will reset it back to the default. This overrides the effects of the skilled trait. Not saved into the save game, so needs to be called once per reload. Be careful not to let the player obtain a perk when no perks are available to pick, or the game may crash. + - name: get_perk_owed + detail: int get_perk_owed + opcode: 0x818e + - name: set_perk_owed + detail: void set_perk_owed(int value) + opcode: 0x818f + - name: get_perk_available + detail: int get_perk_available(int perk) + opcode: 0x8190 + - name: set_perk_level_mod + detail: void set_perk_level_mod(int levels) + opcode: 0x81ab + doc: Sets a modifier between +25 and -25 that is added/subtracted from the player's level for the purposes of deciding which perks can be chosen. + - name: set_pyromaniac_mod + detail: void set_pyromaniac_mod(int bonus) + opcode: 0x81cb + - name: apply_heaveho_fix + detail: void apply_heaveho_fix + opcode: 0x81cc + - name: set_swiftlearner_mod + detail: void set_swiftlearner_mod(int bonus) + opcode: 0x81cd + + + - name: set_fake_perk + detail: void set_fake_perk(string name, int level, int image, string desc) + opcode: 0x81bb + doc: Used to add additional traits and perks to the character screen. They will be saved correctly when the player saves and reloads games, but by themselves they will have no further effect on the character. For perks, the allowed range for levels is between 0 and 100; setting the level to 0 removes that perk. For traits, the level must be 0 or 1. The image is a numeric id that corresponds to an entry in `skilldex.lst`. The name is limited to 63 characters and the description to 255 characters by sfall, but internal Fallout limits may be lower. + - name: set_fake_trait + detail: void set_fake_trait(string name, int active, int image, string desc) + opcode: 0x81bc + doc: Used to add additional traits and perks to the character screen. They will be saved correctly when the player saves and reloads games, but by themselves they will have no further effect on the character. For perks, the allowed range for levels is between 0 and 100; setting the level to 0 removes that perk. For traits, the level must be 0 or 1. The image is a numeric id that corresponds to an entry in `skilldex.lst`. The name is limited to 63 characters and the description to 255 characters by sfall, but internal Fallout limits may be lower. + + - name: set_selectable_perk + detail: void set_selectable_perk(string name, int active, int image, string desc) + opcode: 0x81bd + doc: Used to add additional items to "select a perk" box by setting the 'active' parameter to 1, and to remove them again by setting it to 0. + - name: set_perkbox_title + detail: void set_perkbox_title(string title) + opcode: 0x81be + doc: Used to change the title of the "select a perk" box, or by using "" it will be set back to the default. + - name: hide_real_perks + detail: void hide_real_perks() + opcode: 0x81bf + doc: Prevent the "select a perk" box from displaying any of the original 119 perks. + - name: show_real_perks + detail: void show_real_perks() + opcode: 0x81c0 + doc: Reverts the effect os `hide_real_perks`. + - name: perk_add_mode + detail: void perk_add_mode(int type) + opcode: 0x81c3 + doc: Modifies what happens when a fake perk is selected from the perks dialog. It is treated as a set of flags - if bit 1 is set then it is added to the player's traits, if bit 2 is set it is added to the player's perks, and if bit 3 is set it is removed from the list of selectable perks. The default is 0x2. + - name: clear_selectable_perks + detail: void clear_selectable_perks() + opcode: 0x81c4 + doc: Restores the "select a perk" box to its default state. + + - name: has_fake_perk + detail: int has_fake_perk(string name) + opcode: 0x81c1 + doc: Returns the number of levels the player has of the perks with the given name or ID of extra perk. + - name: has_fake_trait + detail: int has_fake_trait(string name) + opcode: 0x81c2 + doc: Returns the number of levels the player has of the traits with the given name or ID of extra trait. + - name: remove_trait + detail: void remove_trait(int traitID) + opcode: 0x8225 + - name: seq_perk_freq + detail: void seq_perk_freq(int value) + doc: Sets the number of levels between each perk. + +- name: Virtual file system + doc: The `fs_*` functions are used to manipulate a virtual file system. Files saved here should have paths relative to the data folder, and use backslashes as the directory separator. They will take precedence over files stored in the normal data folder. They will also be saved into save games if you set a flag for them using `fs_resize(fileId, -1)`, so be avoid creating large files. Using `fs_copy` followed by `fs_read_xxx`, you can read the contents of existing files. + items: + - name: fs_create + detail: int fs_create(string path, int size) + opcode: 0x81f7 + - name: fs_copy + detail: int fs_copy(string path, string source) + opcode: 0x81f8 + - name: fs_find + detail: int fs_find(string path) + opcode: 0x81f9 + - name: fs_write_byte + detail: void fs_write_byte(int id, int data) + opcode: 0x81fa + - name: fs_write_short + detail: void fs_write_short(int id, int data) + opcode: 0x81fb + - name: fs_write_int + detail: void fs_write_int(int id, int data) + opcode: 0x81fc + - name: fs_write_float + detail: void fs_write_float(int id, int data) + opcode: 0x81fd + - name: fs_write_string + detail: void fs_write_string(int id, string data) + opcode: 0x81fe + - name: fs_write_bstring + detail: void fs_write_bstring(int id, string data) + opcode: 0x8208 + - name: fs_read_byte + detail: int fs_read_byte(int id) + opcode: 0x8209 + - name: fs_read_short + detail: int fs_read_short(int id) + opcode: 0x820a + - name: fs_read_int + detail: int fs_read_int(int id) + opcode: 0x820b + - name: fs_read_float + detail: float fs_read_float(int id) + opcode: 0x820c + - name: fs_delete + detail: void fs_delete(int id) + opcode: 0x81ff + - name: fs_size + detail: int fs_size(int id) + opcode: 0x8200 + - name: fs_pos + detail: int fs_pos(int id) + opcode: 0x8201 + - name: fs_seek + detail: void fs_seek(int id, int pos) + opcode: 0x8202 + - name: fs_resize + detail: void fs_resize(int id, int size) + opcode: 0x8203 + +- name: Knockback + parent: Combat + doc: The `type` value in the weapon knockback functions can be 0 or 1. If 0, the value becomes an absolute distance that targets will be knocked back. If 1, the value is multiplied by the distance they would normally have been knocked back. Weapon knockback modifiers are applied in the order weapon -> attacker -> target, so a x2 weapon wielded by an abs 6 attacker hitting a /2 target will knock the target back 3 squares. The knockback functions will not override the stonewall perk or knockdowns resulting from criticals. knockback values set on weapons or critters are not saved, and must be reset each time the player reloads. + items: + - name: set_weapon_knockback + detail: void set_weapon_knockback(WeaponPtr, int type, float value) + opcode: 0x8195 + - name: set_target_knockback + detail: void set_target_knockback(CritterPtr, int type, float value) + opcode: 0x8196 + - name: set_attacker_knockback + detail: void set_attacker_knockback(CritterPtr, int type, float value) + opcode: 0x8197 + - name: remove_weapon_knockback + detail: void remove_weapon_knockback(WeaponPtr) + opcode: 0x8198 + - name: remove_target_knockback + detail: void remove_target_knockback(CritterPtr) + opcode: 0x8199 + - name: remove_attacker_knockback + detail: void remove_attacker_knockback(CritterPtr) + opcode: 0x819a + +- name: Maps and encounters + items: + - name: in_world_map + detail: bool in_world_map + opcode: 0x8170 + doc: Returns 1 if the player is looking at the world map, or 0 at any other time. Obviously this is only useful in global scripts, since normal scripts will never get the chance to run on the world map. + - name: force_encounter + detail: void force_encounter(int map) + opcode: 0x8171 + doc: Can be called either from a global script while traveling on the world map, or from a normal script while on a local map. In either case the encounter occurs shortly after the next time the player moves on the world map. The player will not get an outdoorsman skill check. + - name: force_encounter_with_flags + detail: void force_encounter_with_flags(int map, int flags) + opcode: 0x8229 + doc: | + Does the same thing as force_encounter, but allows the specification of some extra options (see `sfall.h` for available flags). + Forcing a random encounter on a map that is not normally used for random encounters may cause the player to lose the car, if they have it. In this case use `force_encounter_with_flags` with the `ENCOUNTER_FLAG_NO_CAR` flag set. + - name: set_map_time_multi + detail: void set_map_time_multi(float multi) + opcode: 0x822a + doc: Adjusts how fast time passes while you're on the world map. It takes a single float as an argument, where 1 is the normal speed. This function works in addition to the `WorldMapTimeMod` setting in `ddraw.ini` and the Pathfinder perk, rather than overriding it, so calling `set_map_time_multi(0.5)` when the player has 2 levels of Pathfinder would result in time passing at 25% the normal speed on the world map. + - name: set_map_enter_position + detail: void set_map_enter_position(int tile, int elevation, int rotation) + doc: Overrides the players entry position when entering the map through exit grids. Setting the tile to 0 will put the player on the start hex (default tile and elevation) of the map. Works only in `map_enter_p_proc` procedure. + - name: get_map_enter_position + detail: array get_map_enter_position() + doc: "Returns an array of the player's position data (index: 0 - tile, 1 - elevation, 2 - rotation) when entering the map through exit grids. If entering from the world map, the tile value will be -1. Should be called in `map_enter_p_proc` procedure to get the correct position data." + - name: exec_map_update_scripts + detail: void exec_map_update_scripts() + doc: Executes `map_update_p_proc` for all objects on map and global/hook scripts as well. + macro: sfall.h + - name: set_terrain_name + detail: void sfall_func3("set_terrain_name", int x, int y, string name) + doc: Overrides the terrain type name for the sub-tile on the world map by the specified coordinates. + - name: set_town_title + detail: void sfall_func2("set_town_title", int areaID, string title) + doc: | + Sets a floating text for a town on the world map when hovering the cursor over the player's marker. + ``` + - areaID: the ID number of the town from city.txt + ``` + +- name: Rest + parent: Maps and encounters + items: + - name: set_can_rest_on_map + detail: void set_can_rest_on_map(int mapNum, int elev, bool value) + doc: | + Allows/disallows to rest on the map for the specified level, overrides the `can_rest_here` values in `maps.txt`. + - `mapNum` is the map index from `maps.txt` + - passing -1 to the elev argument will set the rest value for all map elevations + - the set rest value will be stored in `sfalldb.sav` file (in savegame) + macro: sfall.h + - name: get_can_rest_on_map + detail: get_can_rest_on_map(int mapNum, int elev) + doc: | + - returns the set rest value of the map after using the `set_can_rest_on_map` function + - Returns -1 if the rest value of the map was not previously set (i.e. no data for the map in `sfalldb.sav`) + - the `can_rest_here values` from `maps.txt` are ignored. + macro: sfall.h + +- name: Worldmap + parent: Maps and encounters + doc: The mapper manual lists the functions `world_map_x_pos` and `world_map_y_pos`, which supposedly return the player's x and y positions on the world map. `get_world_map_x/y_pos` are included here anyway, because I was unable to get those original functions to work, or even to find any evidence that they existed in game. + items: + - name: get_world_map_x_pos + detail: int get_world_map_x_pos() + opcode: 0x8173 + - name: get_world_map_y_pos + detail: int get_world_map_y_pos() + opcode: 0x8174 + - name: set_world_map_pos + detail: void set_world_map_pos(int x, int y) + opcode: 0x8172 + + +- name: Audio + items: + - name: eax_available + detail: int eax_available + opcode: 0x81a3 + - name: set_eax_environment + detail: void set_eax_environment(int environment) + opcode: 0x81a4 + + - name: play_sfall_sound + detail: int play_sfall_sound(string file, int mode) + opcode: 0x822b + doc: | + Used to play `mp3/wav/wma` files. The path given is relative to the Fallout folder. Specify mode as 1 to loop the file continuously, 2 to replace the current background game music with playing the specified file in loop mode, or 0 to play the file once. If you don't wish to loop, `play_sfall_sound` returns 0. If you do loop, it returns an id which can be passed back to `stop_sfall_sound` when you want to stop the effect. All sounds effects will be stopped on game reload, looping or not. Does not require `AllowDShowSound` to be set to 1 in `ddraw.ini`. + + Starting from sfall 4.2.8/3.8.28, you can pass a value in the `mode` argument for a reduced sound volume. To set the volume, You need to convert the number to hexadecimal and use the argument format `0xZZZZ000Y`, where `ZZZZ` is the volume reduction value in range from 0 to 32767 (the value 32767 is mute), and `Y` is the playback mode. + - name: stop_sfall_sound + detail: void stop_sfall_sound(int soundID) + opcode: 0x822c + doc: Stops looping `mp3/wav/wma` files previously launched by `play_sfall_sound`. All sounds effects will be stopped on game reload, looping or not. Does not require `AllowDShowSound` to be set to 1 in `ddraw.ini`. + +- name: Weapons and ammo + parent: Combat + items: + - name: get_weapon_ammo_pid + detail: int get_weapon_ammo_pid(ObjectPtr weapon) + opcode: 0x8217 + - name: set_weapon_ammo_pid + detail: void set_weapon_ammo_pid(ObjectPtr weapon, int pid) + opcode: 0x8218 + - name: get_weapon_ammo_count + detail: int get_weapon_ammo_count(ObjectPtr weapon) + opcode: 0x8219 + doc: This also allows to get current charges of a misc item (Geiger counter, etc). + - name: set_weapon_ammo_count + detail: void set_weapon_ammo_count(ObjectPtr weapon, int count) + opcode: 0x821a + doc: This also allows to set current charges of a misc item (Geiger counter, etc). + +- name: Version + parent: Sfall + items: + - name: sfall_ver_major + detail: int sfall_ver_major() + opcode: 0x8210 + - name: sfall_ver_minor + detail: int sfall_ver_minor() + opcode: 0x8211 + - name: sfall_ver_build + detail: int sfall_ver_build() + opcode: 0x8212 + +- name: Math + parent: Variables + items: + - name: log + detail: float log(float x) + doc: Natural logarithm of x. + opcode: 0x8264 + - name: exponent + detail: float exponent(float x) + doc: E^X + opcode: 0x8265 + - name: round + detail: int round(float x) + doc: Round x to the nearest integer. + opcode: 0x8267 + - name: sqrt + detail: float sqrt(float x) + doc: Square root of x. + opcode: 0x81ec + - name: abs + detail: int/float abs(int/float x) + doc: Absolute (positive) value of x. + opcode: 0x81ed + - name: sin + detail: float sin(float x) + doc: Sine of x + opcode: 0x81ee + - name: cos + detail: float cos(float x) + doc: Cosine of x + opcode: 0x81ef + - name: tan + detail: float tan(float x) + doc: Tangent of x + opcode: 0x81f0 + - name: arctan + detail: float arctan(float x, float y) + doc: Arctangent of x. Pass 1 as y (don't ask...). + opcode: 0x81f1 + - name: ceil + detail: int ceil(float) + opcode: 0x8266 + doc: Round x to the nearest integer that is not less than x. + - name: ^ + detail: x^y + doc: | + Exponentiation. Use as any other arithmetic operator, like `5^(1/3)`. + If exponent is an integer, you can use a negative base, otherwise you will get "NaN" with a negative base. + If both arguments are integers, the result will be an integer. + - name: floor2 + detail: int floor2(int/float value) + doc: Works just like vanilla floor function, but returns correct integers for negative values (vanilla floor function works exactly the same as `ceil` for negative values, much like `trunc` in C/C++). + macro: sfall.h + - name: div + detail: div(x, y) + doc: | + Unsigned integer division. Use as a division operator, like `3 + (20 div 5)`. + If both dividend and divisor are integers, they will be treated as unsigned integers. + If one of them is a float, div will perform the signed division just like vanilla division operator. + opcode: 0x827f + +- name: Keyboard and mouse + items: + - name: key_pressed + detail: int key_pressed(int dxScancode) + opcode: 0x816c + - name: tap_key + detail: void tap_key(int dxScancode) + opcode: 0x8162 + - name: get_mouse_x + detail: int get_mouse_x() + opcode: 0x821c + - name: get_mouse_y + detail: int get_mouse_y() + opcode: 0x821d + - name: get_mouse_buttons + detail: int get_mouse_buttons() + doc: Returns the number of the mouse button that is currently pressed (1 - left, 2 - right, 3 - left+right, 4 - middle, 0 otherwise). + opcode: 0x821e + +- name: Lists + parent: Arrays + doc: The `list_xxx` functions can be used to loop over all items on a map. `list_begin` takes an argument telling sfall what you want to list. (Defined in `sfall.h`) It returns a list pointer, which you iterate through with `list_next`. Finally, when you've finished with the list use `list_end` on it. Not calling `list_end` will result in a memory leak. Alternatively, use `list_as_array` to get the whole list at once as a temp array variable, which can be looped over using `len_array` and which you don't need to remember to free afterwards. + items: + - name: list_begin + detail: int list_begin(int type) + opcode: 0x820d + - name: list_next + detail: int list_next(int listid) + opcode: 0x820e + - name: list_end + detail: void list_end(int listid) + opcode: 0x820f + - name: list_as_array + detail: array list_as_array(int type) + opcode: 0x8236 + - name: party_member_list + detail: array party_member_list(int includeHidden) + doc: Returns an array of all current party members (0 - only critter-type, alive and visible will be returned, 1 - all object, including Trunk, etc.) + opcode: 0x8271 + +- name: Explosions + items: + - name: metarule2_explosions + detail: int metarule2_explosions(int arg1, int arg2) + doc: Was made as a dirty easy hack to allow dynamically change some explosion parameters (ranged attack). All changed parameters are reset to vanilla state automatically after each attack action. + opcode: 0x8261 + + - name: set_attack_explosion_pattern + detail: void set_attack_explosion_pattern(x, y) + doc: 'Currently Y is not used and X means: 1 - reduced explosion pattern (3 effects are spawned instead of 7), 0 - full pattern.' + macro: sfall.h + + - name: set_attack_explosion_art + detail: void set_attack_explosion_art(x, y) + doc: Y not used and X is a misc frame ID (last 3 bytes, without object type) to use for the next explosion. + macro: sfall.h + + - name: set_attack_explosion_radius + detail: void set_attack_explosion_radius(x) + doc: Changes radius at which explosion will hit secondary targets for the next attack (from the experiments it is limited to something around 8 by the engine). + macro: sfall.h + + - name: set_attack_is_explosion_fire + detail: void set_attack_is_explosion_fire + doc: If you call this right before using a weapon with fire damage type (e.g. in `HOOK_AFTERHITROLL`), it will produce explosion effects (and radius damage) just like "explosion" type, but all targets will still receive fire damage. + macro: sfall.h + + - name: set_explosion_radius + detail: void set_explosion_radius(grenade, rocket) + doc: Sets a permanent radius of the explosion for grenades and/or rockets. Passing 0 means not changing the corresponding radius. Changed radius will be reset each time the player reloads the game. + macro: sfall.h + + - name: set_dynamite_damage + detail: void set_dynamite_damage(minDmg, maxDmg) + doc: Sets the minimum and maximum damage for Dynamite. Changed damage will be reset each time the player reloads the game. + macro: sfall.h + + - name: set_plastic_damage + detail: void set_plastic_damage(minDmg, maxDmg) + doc: Sets the minimum and maximum damage for Plastic Explosives. Changed damage will be reset each time the player reloads the game. + macro: sfall.h + + - name: get_explosion_damage + detail: array get_explosion_damage(itemPid) + doc: Returns an array of the minimum and maximum damage of the explosive item. + macro: sfall.h + + - name: set_explosion_max_targets + detail: void set_explosion_max_targets(x) + doc: "Sets the maximum number of additional targets for an explosion, valid range: 1..6 (default is 6)." + macro: sfall.h + + - name: item_make_explosive + detail: void item_make_explosive(int pid, int activePid, int minDamage, int maxDamage) + doc: | + - makes the specified item (pid) an explosive item like Dynamite or Plastic Explosives + - `maxDamage` is optional + - `activePid` is for an item with an active timer, can be the same as the `pid` argument + - the item proto must be "Misc Item" type and have "Use" action flag + - minDamage/maxDamage are the minimum and maximum explosion damage + - using the function on an item that is already set as an explosive will override its previous settings + - NOTE: this function does not work for pids of Dynamite and Plastic Explosives + macro: sfall.h + +- name: Animations + items: + - name: reg_anim_combat_check + detail: void reg_anim_combat_check(int enable) + doc: Allows to enable all `reg_anim_*` functions in combat (including vanilla functions) if set to 0. It is automatically reset at the end of each frame, so you need to call it before `reg_anim_begin` - `reg_anim_end` block. + opcode: 0x825c + - name: reg_anim_destroy + detail: void reg_anim_destroy(ObjectPtr) + doc: Given object is destroyed at the end of current animation set. + opcode: 0x825a + - name: reg_anim_animate_and_hide + detail: void reg_anim_animate_and_hide(ObjectPtr, int animID, int delay) + doc: Exactly like `reg_anim_animate` but the object will automatically disappear after the last animation frame (but not destroyed). + opcode: 0x825b + - name: reg_anim_light + detail: void reg_anim_light(ObjectPtr, int light, int delay) + doc: 'Change light of any object. Light argument is a light radius (0-8), but you can use highest 2 bytes to pass light intensity as well (example: 0xFFFF0008 - intensity 65535 and radius 8). If highest 2 bytes are 0, intensity will not be changed. Intensity range is from 0 to 65535 (0xFFFF)' + opcode: 0x825d + - name: reg_anim_change_fid + detail: void reg_anim_change_fid(ObjectPtr, int FID, int delay) + doc: Should work like `art_change_fid_num` but in `reg_anim` sequence. + opcode: 0x825e + - name: reg_anim_take_out + detail: void reg_anim_take_out(ObjectPtr, holdFrameID, delay) + doc: Plays "take out weapon" animation for given `holdFrameID`. It is not required to have such weapon in critter's inventory. + opcode: 0x825f + - name: reg_anim_turn_towards + detail: void reg_anim_turn_towards(ObjectPtr, int tile/target, delay) + doc: Makes object change its direction to face given tile num or target object. + opcode: 0x8260 + - name: reg_anim_callback + detail: void reg_anim_callback(procedure proc) + doc: Adds the given procedure to an animation sequence-list and executes it in the registered sequence. + opcode: 0x827e + +- name: Art and appearance + items: + - name: art_exists + detail: int art_exists(int artFID) + doc: 'checks if given artFID exists in the game. Useful when you want to check if critter can use specific weapon: `art_exists((artFid bwand 0xffff0fff) bwor (weaponAnim * 0x1000))`.' + opcode: 0x8274 + - name: refresh_pc_art + detail: void refresh_pc_art + opcode: 0x8227 + - name: art_cache_clear + detail: void art_cache_clear() + doc: Clears the cache of FRM image files loaded into memory. + macro: sfall.h + + - name: set_hero_race + detail: void set_hero_race(int style) + opcode: 0x8214 + - name: set_hero_style + detail: void set_hero_style(int style) + opcode: 0x8215 + + +- name: Tiles and paths + items: + - name: get_tile_fid + detail: int get_tile_fid(int tile) + opcode: 0x823a + - name: tile_under_cursor + detail: int tile_under_cursor + opcode: 0x824b + - name: tile_light + detail: int tile_light(int elevation, int tileNum) + doc: Returns light intensity at the given tile in range from 0 to 65535. + opcode: 0x826d + - name: tile_get_objs + detail: array tile_get_objs(int tileNum, int elevation) + doc: Returns an array of all objects at given tile. It will include any hidden, dead or system objects (like cursor), so make sure to check properly when iterating. + opcode: 0x8270 + - name: tile_refresh_display + detail: void tile_refresh_display() + doc: Redraws the game scene (tiles, walls, objects, etc.). + - name: obj_blocking_tile + detail: ObjectPtr obj_blocking_tile(int tileNum, int elevation, int blockingType) + doc: Returns first object blocking given tile using given blocking function or 0 if tile is clear. + opcode: 0x826f + + - name: tile_by_position + detail: int tile_by_position(int x, int y) + doc: | + - returns the tile number at the x, y position relative to the top-left corner of the screen + - if the position is outside of the range of tiles, it will return -1 + macro: sfall.h + + - name: obj_blocking_line + detail: ObjectPtr obj_blocking_line(ObjectPtr objFrom, int tileTo, int blockingType) + doc: Returns first object which blocks direct linear path from `objFrom` to `tileTo` using selected blocking function (see `BLOCKING_TYPE_*` constants in `sfall.h`). If path is clear (no blocker was encountered by selected function) - returns 0. `objFrom` is always excluded from calculations, but is required to be a valid object. + opcode: 0x826e + - name: path_find_to + detail: array path_find_to(ObjectPtr objFrom, int tileTo, int blockingType) + doc: Returns the shortest path to a given tile using given blocking function as an array of tile directions (0..5) to move on each step. Array length equals to a number of steps. Empty array means that specified target cannot be reached. + opcode: 0x8272 + +- name: Other + items: + - name: input_funcs_available + detail: int input_funcs_available() + opcode: 0x816b + doc: The input functions are only available if the user has the input hook turned on in `ddraw.ini`. Use `input_funcs_available` to check. + - name: get_year + detail: int get_year + opcode: 0x8163 + - name: set_dm_model + detail: void set_dm_model(string name) + opcode: 0x8175 + - name: set_df_model + detail: void set_df_model(string name) + opcode: 0x8176 + - name: set_movie_path + detail: void set_movie_path(string filename, int movieid) + opcode: 0x8177 + - name: set_pipboy_available + detail: void set_pipboy_available(int available) + doc: Will only accept 0 or 1 as an argument. Using any other value will cause the function to have no effect. Use 0 to disable the pipboy, and 1 to enable it. + opcode: 0x818b + - name: get_kill_counter + detail: int get_kill_counter(int critterType) + opcode: 0x818c + - name: mod_kill_counter + detail: void mod_kill_counter(int critterType, int amount) + opcode: 0x818d + - name: active_hand + detail: int active_hand + opcode: 0x8193 + - name: toggle_active_hand + detail: void toggle_active_hand + opcode: 0x8194 + - name: set_pickpocket_max + detail: void set_pickpocket_max(int percentage) + opcode: 0x81a0 + doc: Effects all critters rather than just the player and can set the maximum in range from 0 to 999. + - name: set_hit_chance_max + detail: void set_hit_chance_max(int percentage) + opcode: 0x81a1 + doc: Effects all critters rather than just the player and can set the maximum in range from 0 to 999. + - name: set_xp_mod + detail: void set_xp_mod(int percentage) + opcode: 0x81aa + - name: set_critter_hit_chance_mod + detail: void set_critter_hit_chance_mod(CritterPtr, int max, int mod) + opcode: 0x81c5 + - name: set_base_hit_chance_mod + detail: void set_base_hit_chance_mod(int max, int mod) + opcode: 0x81c6 + - name: inc_npc_level + detail: void inc_npc_level(int party_member_pid) + opcode: 0x81a5 + doc: Takes a party member PID or an NPC name (deprecated, for compatibility with sfall 4.1.5/3.8.15 or earlier) as an argument. The NPC must be in your party. This function ignores player level requirements and the minimum 3 player level delay between NPC level gains. It also ignores the random element, regardless of sfall's `NPCAutoLevel` setting. + - name: get_npc_level + detail: int get_npc_level(string npc) + opcode: 0x8241 + - name: get_viewport_x + detail: int get_viewport_x() + opcode: 0x81a6 + - name: get_viewport_y + detail: int get_viewport_y() + opcode: 0x81a7 + - name: set_viewport_x + detail: void set_viewport_x(int view_x) + opcode: 0x81a8 + - name: set_viewport_y + detail: void set_viewport_y(int view_y) + opcode: 0x81a9 + - name: set_hp_per_level_mod + detail: void set_hp_per_level_mod(int mod) + opcode: 0x81ce + + + - name: set_unspent_ap_bonus + detail: void set_unspent_ap_bonus(int multiplier) + opcode: 0x81e6 + doc: Alters the AC bonus you receive per unused action point at the end of your turn in combat. To allow for fractional values, the value given if divided by 4. (Hence the default value is 4 and not 1.) + - name: get_unspent_ap_bonus + detail: int get_unspent_ap_bonus() + doc: Gets the AC bonus you receive per unused action point at the end of your turn in combat. To allow for fractional values, the value given if divided by 4. (Hence the default value is 4 and not 1.) + opcode: 0x81e7 + - name: set_unspent_ap_perk_bonus + detail: void set_unspent_ap_perk_bonus(int multiplier) + opcode: 0x81e8 + doc: Similar to `set_unspent_ap_bonus`, but effects the extra AC granted by the H2H Evade perk. (The default value of this is also 4, equivalent to doubling the original bonus. + - name: get_unspent_ap_perk_bonus + detail: int get_unspent_ap_perk_bonus() + opcode: 0x81e9 + doc: Similar to `get_unspent_ap_bonus`, but accounts for the extra AC granted by the H2H Evade perk. (The default value of this is also 4, equivalent to doubling the original bonus. + + - name: nb_create_char + detail: int nb_create_char() + opcode: 0x81f6 + doc: "`nb_*` functions are reserved for the brotherhood tactical training mod, and should be avoided." + + - name: get_proto_data + detail: int get_proto_data(int pid, int offset) + opcode: 0x8204 + doc: Used to read the in-memory copies of the .pro files Fallout makes when they are loaded. The offset refers to the offset in memory from the start of the proto to the element you are reading. + - name: set_proto_data + detail: void set_proto_data(int pid, int offset, int value) + opcode: 0x8205 + doc: Used to alter the in-memory copies of the .pro files Fallout makes when they are loaded. The offset refers to the offset in memory from the start of the proto to the element you are reading. Changes are not stored on disc, and are not permanent. If you modify the protos, and then Fallout subsequently reloads the file your changes will be lost. + + - name: hero_select_win + detail: void hero_select_win(int) + opcode: 0x8213 + - name: stop_game + detail: void stop_game() + opcode: 0x8222 + - name: resume_game + detail: void resume_game() + opcode: 0x8223 + - name: create_message_window + detail: void create_message_window(string message) + opcode: 0x8224 + - name: get_light_level + detail: int get_light_level() + opcode: 0x8226 + doc: Returns ambient light level in range 0..65536. The value returned by get_light_level may not exactly match that set by `set_light_level`, as `set_light_level` applies modifiers from the Night Vision perk. + + - name: mark_movie_played + detail: void mark_movie_played(int id) + opcode: 0x8240 + - name: gdialog_get_barter_mod + detail: int gdialog_get_barter_mod + opcode: 0x824c + - name: set_inven_ap_cost + detail: void set_inven_ap_cost + opcode: 0x824d + - name: game_loaded + detail: int game_loaded() + doc: Returns 1 the first time it is called after a new game or game load, and 0 any time after. It works on an individual basis for each script, so one script wont interfere with others. Its primary use is for global scripts, so that they know when to call `set_global_script_repeat`, but it can be called from normal scripts too. + opcode: 0x8164 + + - name: get_game_mode + detail: int get_game_mode() + doc: A more flexible version of in_world_map. It will return a set of flags indicating which mode the game is currently in. These flags are the same as those used in the `set_shader_mode function`. + opcode: 0x81af + - name: get_uptime + detail: int get_uptime() + doc: Just a wrapper around the windows GetTickCount() function. It's useful for making time fade effects in shaders, since they already have access to the current tick count. + opcode: 0x81b3 + + - name: set_base_pickpocket_mod + detail: void set_base_pickpocket_mod(int max, int mod) + doc: Changes maximum chance of success and chance mod for each steal attempt. `max` will replace 95% success chance cap (so you can set 100% maximum chance, for instance). `mod` will add this much percent to each success chance. for example if your chance is 50% and `mod` is 20, you will get 70% actual success rate + opcode: 0x81ca + - name: set_critter_pickpocket_mod + detail: void set_critter_pickpocket_mod(CritterPtr, int max, int mod) + doc: The same as `set_base_pickpocket`, but applies only to specific critter. + opcode: 0x81c9 + + - name: message_str_game + detail: string message_str_game(int fileId, int messageId) + doc: | + Works exactly the same as message_str, except you get messages from files in `text/english/game` folder. Use `GAME_MSG_*` defines or `mstr_*` macros from `sfall.h` to use specific msg file + - Additional game msg files added by `ExtraGameMsgFileList` setting will have consecutive fileIds assigned beginning from 0x2000 to 0x2FFF. (e.g. if you set `ExtraGameMsgFileList=foo,bar` in `ddraw.ini`, `foo.msg` will be associated with 0x2000 and `bar.msg` with 0x2001.). + - If a file has a specific number assigned in `ExtraGameMsgFileList`, its fileId will be (0x2000 + assigned number). (e.g. with `ExtraGameMsgFileList=foo,bar:2,foobar` in `ddraw.ini`, `bar.msg` will be associated with 0x2002 and `foobar.msg` with 0x2003.) + opcode: 0x826b + + - name: sneak_success + detail: int sneak_success + doc: Returns 1 if last sneak attempt (roll against skill) was successful, 0 otherwise. This calls an internal engine function which is used to determine the perception range of critters (which you can override using `HOOK_WITHINPERCEPTION`). + opcode: 0x826c + + - name: create_spatial + detail: ObjectPtr create_spatial(int scriptID, int tile, int elevation, int radius) + doc: Creates new spatial script with given SID, at given tile, and radius. + opcode: 0x8273 + + - name: unwield_slot + detail: void sfall_func2("unwield_slot", object critter, int slot) + doc: | + unequips an item from the specified slot for a critter or the player + can take off player's equipped item when the inventory is opened, or the player is in the barter screen + slot: 0 - armor slot, 1 - right slot, 2 - left slot (see `INVEN_TYPE_*` in `define.h`) + + + - name: add_trait + detail: void add_trait(int traitID) + doc: adds the specified trait to the player + macro: sfall.h + - name: get_inven_ap_cost + detail: int get_inven_ap_cost + doc: Returns the current AP cost to access the inventory in combat + - name: add_g_timer_event + detail: void add_g_timer_event(int time, int fixedParam) + doc: | + Adds a timer event that calls the `timed_event_p_proc` procedure in the current global script + `time`: the number of ticks after which the event timer is triggered + `fixedParam`: the value that is passed to the `timed_event_p_proc` procedure for the `fixed_param` function + macro: sfall.h + +- name: Variables + items: + - name: sprintf + detail: string sprintf(string format, any value) + doc: Formats given value using standart syntax of C printf function (google "printf" for format details). However it is limited to formatting only 1 value. Can be used to get character by ASCII code ("%c"). + opcode: 0x8250 + - name: typeof + detail: int typeof(any value) + doc: 'Returns type of the given value: VALTYPE_INT, VALTYPE_FLOAT or VALTYPE_STR.' + opcode: 0x8253 + - name: atoi + detail: int atoi(string text) + opcode: 0x8237 + - name: atof + detail: float atof(string text) + opcode: 0x8238 + +- name: Strings + parent: Variables + items: + - name: string_split + detail: array string_split(string, split) + doc: "Takes a string and a seperator, searches the string for all instances of the seperator, and returns a temp array filled with the pieces of the string split at each instance. If you give an empty string as the seperator, the string is split into individual characters. You can use this to search for a substring in a string like this: `strlen(get_array(string_split(haystack, needle), 0))`" + opcode: 0x8235 + - name: substr + detail: string substr(string, start, length) + doc: | + Cuts a substring from a string starting at "start" up to "length" characters. The first character position is 0 (zero). + - If start is negative - it indicates starting position from the end of the string (for example `substr("test", -2, 2)` will return last 2 charactes: "st"). + - If length is negative - it means so many characters will be omitted from the end of string (example: `substr("test", 0, -2)` will return string without last 2 characters: "te"). + - If length is zero - it will return a string from the starting position to the end of the string **New behavior** for sfall 4.2.2/3.8.22 + opcode: 0x824e + - name: strlen + detail: int strlen(string text) + doc: Returns string length. + opcode: 0x824f + - name: charcode + detail: int charcode(string text) + doc: Returns ASCII code for the first character in given string. + opcode: 0x8251 + - name: get_string_pointer + detail: int get_string_pointer(string text) + doc: Returns a pointer to a string variable or to a text. + macro: sfall.h + - name: string_format + detail: string string_format(string format, any val1, any val2, ...) + doc: | + Formats given value using standard syntax of C printf function (google "printf" for format details). However it is limited to formatting up to 4 values. + - formatting is only supported for %s and %d, and the format string is limited to 1024 characters + macro: sfall.h + - name: string_to_case + detail: string sfall_func2("string_to_case", string text, int toCase) + doc: | + Converts all letters in the given string to the specified case. + ``` + toCase: 0 - lowercase, 1 - uppercase + ``` + NOTE: this function works only for English letters of A-Z/a-z. + +- name: Interface + +- name: Tags + parent: Interface + doc: show_iface_tag, hide_iface_tag and is_iface_tag_active relate to the boxes that appear above the interface such as SNEAK and LEVEL. You can use 3 for LEVEL and 4 for ADDICT, or the range from 5 to (4 + the value of BoxBarCount in `ddraw.ini`) for custom boxes. Remember to add your messages to `intrface.msg` and set up the font colours in `ddraw.ini` if you're going to use custom boxes. Starting from sfall 4.1/3.8.12, is_iface_tag_active can also be used to check 0 for SNEAK, 1 for POISONED, and 2 for RADIATED. + items: + - name: show_iface_tag + detail: void show_iface_tag(int tag) + opcode: 0x81dc + - name: hide_iface_tag + detail: void hide_iface_tag(int tag) + opcode: 0x81dd + - name: is_iface_tag_active + detail: int is_iface_tag_active(int tag) + opcode: 0x81de + doc: Starting from sfall 4.1, can also be used to check 0 for SNEAK, 1 for POISONED, and 2 for RADIATED. + - name: set_iface_tag_text + detail: void set_iface_tag_text(int tag, string text, int color) + doc: Sets the text messages and colors for custom notification boxes to the interface without the need to add messages to `intrface.msg` and set up the font colors in `ddraw.ini`. Tag value is the same as used in `show_iface_tag`, `hide_iface_tag`, and `is_iface_tag_active`. The valid range is from 5 to (4 + the value of `BoxBarCount` in `ddraw.ini`) or the number of the last custom box added using the `add_iface_tag` function. The text is limited to 19 characters. + macro: sfall.h + - name: add_iface_tag + detail: void add_iface_tag() + doc: Adds one custom box to the current boxes, and returns the number of the added tag (-1 if the tags limit is exceeded. The maximum number of boxes is limited to 126 tags. + macro: sfall.h + +- name: Global variables + doc: These functions require an __EXACTLY 8 characters long__, case sensitive string for the variable name. The variables behave the same as normal Fallout globals, except that they don't have to be declared beforehand in `vault13.gam`. Trying to get a variable which hasn't been set will always return 0. The functions are intended for use when a patch to a mod requires the addition of a new global variable, a case which would otherwise require the player to start a new game. + items: + - name: set_sfall_global + detail: void set_sfall_global(string/int varname, int/float value) + opcode: 0x819d + - name: get_sfall_global_int + detail: int get_sfall_global_int(string/int varname) + opcode: 0x819e + - name: get_sfall_global_float + detail: float get_sfall_global_float(string/int varname) + opcode: 0x819f + +- name: Hook functions + parent: Hooks # normal page + items: + - name: init_hook + detail: int init_hook() + doc: The hook script equivalent of `game_loaded`; it returns 1 when the script is loaded for the first time or when the player reloads the game, and 0 otherwise. + opcode: 0x81ea + - name: get_sfall_arg + detail: mixed get_sfall_arg() + doc: Gets the next argument from sfall. Each time it's called it returns the next argument, or otherwise it returns 0 if there are no more arguments left. You can arbitrarily get the value of any argument using the `sfall_func1("get_sfall_arg_at", argNum)` function. + opcode: 0x81e4 + - name: get_sfall_args + detail: int get_sfall_args() + doc: Returns all hook arguments as a new temp array. + opcode: 0x823c + - name: get_sfall_arg_at + detail: mixed get_sfall_arg_at(int argNum) + doc: Gets the value of hook argument with the specified argument number (first argument of hook starts from 0) + macro: sfall.h + - name: set_sfall_return + detail: void set_sfall_return(int value) + doc: Used to return the new values from the script. Each time it's called it sets the next value, or if you've already set all return values it does nothing. + opcode: 0x81e5 + - name: set_sfall_arg + detail: void set_sfall_arg(int argNum, int value) + doc: Changes argument value. The argument number (argNum) is 0-indexed. This is useful if you have several hook scripts attached to one hook point (see `register_hook_proc`). + opcode: 0x823d + - name: register_hook + detail: void register_hook(int hookID) + doc: Used from a normal global script if you want to run it at the same point a full hook script would normally run. In case of this function, `start` proc will be executed in current global script. You can use all above functions like normal. + opcode: 0x8207 + - name: register_hook_proc + detail: void register_hook_proc(int hookID, proc procedure) + doc: | + The same as `register_hook`, except that you specifically define which procedure in the current script should be called as a hook (instead of "start" by default). Pass procedure the same as how you use dialog option functions. This IS the recommended way to use hook scripts, as it gives both modularity (each mod logic in a separate global script, no conflicts if you don't use "hs_*.int" scripts) and flexibility (you can place all related hook scripts for specific mod in a single script!). + + Use zero (0) as second argument to unregister hook script from current global script. + + __NOTE:__ you can hook several scripts to a single hook point, for example if it's different mods from different authors or just some different aspects of one larger mod. In this case scripts are executed in reverse order of how they were registered. When one of the scripts in a chain returns value with `set_sfall_return`, the next script may override this value if calls `set_sfall_return` again. Sometimes you need to multiply certain value in a chain of hook scripts. + + Example: let's say we have a Mod A which reduces all "to hit" chances by 50%. The code might look like this: + + ```js + original_chance = get_sfall_arg; + set_sfall_return(original_chance / 2); + ``` + + Mod B also want to affect hit chances globally, by increasing them by 50%. Now in order for both mods to work well together, we need to add this line to Mod A hook script: + ```js + set_sfall_arg(0, (original_chance / 2)); + ``` + + This basically changes hook argument for the next script. Mod B code: + ```js + original_chance = get_sfall_arg; + set_sfall_return(original_chance * 1.5); + set_sfall_arg(0, (original_chance * 1.5)); + ``` + + So if you combine both mods together, they will run in chain and the end result will be a 75% from original hit chance (hook register order doesn't matter in this case, if you use `set_sfall_arg` in both hooks). + + The defines to use for the `hookID` are in `sfall.h`. + opcode: 0x8262 + - name: register_hook_proc_spec + detail: void register_hook_proc_spec(int hookID, procedure proc) + doc: Works very similar to `register_hook_proc`, except that it registers the current script at the end of the hook script execution chain (i.e. the script will be executed after all previously registered scripts for the same hook, including the `hs_*.int` script). All scripts hooked to a single hook point with this function are executed in exact order of how they were registered, as opposed to the description below, which refers to using `register_hook/register_hook_proc` functions. + +- name: Array functions + parent: Arrays # not in this files, normal page + items: + - name: create_array + detail: int create_array(int size, int nothing) + doc: Creates permanent array (but not "saved"). + opcode: 0x822d + - name: temp_array + detail: int temp_array(int size, int nothing) + doc: Works exactly like "create_array", only created array becomes "temporary." + opcode: 0x8233 + - name: fix_array + detail: void fix_array(int arrayID) + doc: Changes "temporary" array into "permanent" ("permanent" arrays are not automatically saved into savegames). + opcode: 0x8234 + - name: set_array + detail: void set_array(int arrayID, mixed key, mixed value) + doc: 'Sets array value (shorthand: arrayID[key] := value).' + opcode: 0x822e + - name: get_array + detail: mixed get_array(int arrayID, mixed key) + doc: 'Returns array value by key or index (shorthand: arrayID[key]).' + opcode: 0x822f + - name: resize_array + detail: void resize_array(int arrayID, int size) + doc: Changes array size. + opcode: 0x8232 + - name: free_array + detail: void free_array(int arrayID) + doc: Deletes any array. + opcode: 0x8230 + - name: scan_array + detail: mixed scan_array(int arrayID, mixed value) + doc: Searches for a first occurence of given value inside given array. + opcode: 0x8239 + - name: len_array + detail: int len_array(int arrayID) + doc: Returns number of elements or key=>value pairs in a given array. + opcode: 0x8231 + - name: array_key + detail: mixed array_key(int arrayID, int index) + doc: Don't use it directly; it is generated by the compiler in foreach loops. + opcode: 0x8256 + - name: arrayexpr + detail: int arrayexpr(mixed key, mixed value) + doc: Don't use it directly; it is used by compiler to create array expressions. + opcode: 0x8257 + - name: save_array + detail: void save_array(mixed key, int arrayID) + doc: Array is saved (arrayID is associated with given "key"). + opcode: 0x8254 + - name: load_array + detail: int load_array(mixed key) + doc: Load array from savegame data by the same key provided in "save_array". + opcode: 0x8255 + +- name: Sfall # just parent page + +- name: funcX + parent: Sfall + items: + - name: sfall_func0 + detail: any sfall_func0(char* funcName) + doc: Calls scripting function with given name and no arguments. + opcode: 0x8276 + - name: sfall_func1 + detail: any sfall_func1(char* funcName, arg1) + doc: Calls scripting function with given name and 1 argument. + opcode: 0x8277 + - name: sfall_func2 + detail: any sfall_func2(char* funcName, arg1, arg2) + doc: Calls scripting function with given name and 2 arguments. + opcode: 0x8278 + - name: sfall_func3 + detail: any sfall_func3(char* funcName, arg1, arg2, arg3) + doc: Calls scripting function with given name and 3 arguments. + opcode: 0x8279 + - name: sfall_func4 + detail: any sfall_func4(char* funcName, arg1, arg2, arg3, arg4) + doc: Calls scripting function with given name and 4 arguments. + opcode: 0x827a + - name: sfall_func5 + detail: any sfall_func5(char* funcName, arg1, arg2, arg3, arg4, arg5) + doc: Calls scripting function with given name and 5 arguments. + opcode: 0x827b + - name: sfall_func6 + detail: any sfall_func6(char* funcName, arg1, arg2, arg3, arg4, arg5, arg6) + doc: Calls scripting function with given name and 6 arguments + opcode: 0x827c + - name: sfall_func7 + detail: any sfall_func7(string funcName, arg1, arg2, arg3, arg4, arg5, arg6, arg7) + doc: Calls scripting function with given name and 7 arguments + opcode: 0x8280 + - name: sfall_func8 + detail: any sfall_func8(string funcName, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) + doc: Calls scripting function with given name and 8 arguments + opcode: 0x8281 + +- name: Sfall funcX macros + items: + - name: critter_inven_obj2 + detail: ObjectPtr critter_inven_obj2(ObjectPtr obj, int type) + doc: Works just like vanilla `critter_inven_obj`, but correctly reports item in player's inactive hand slot. + macro: sfall.h + - name: item_weight + detail: int item_weight(ObjectPtr obj) + doc: Gets the current weight of an object. + macro: sfall.h + + - name: spatial_radius + detail: int spatial_radius(ObjectPtr obj) + doc: Returns radius of spatial script, associated with given dummy-object (returned by `create_spatial`). + macro: sfall.h + - name: set_rest_heal_time + detail: void set_rest_heal_time(int time) + doc: 'Sets the time interval in minutes for healing during resting. The default is 180. Note: The interval will be reset each time the player reloads the game.' + macro: sfall.h + - name: set_rest_mode + detail: void set_rest_mode(int flags) + doc: 'Sets the bit flags for the rest mode (see `RESTMODE_*` constants in `sfall.h`). Passing 0 will reset the rest mode. It will also be reset each time the player reloads the game.' + macro: sfall.h + + - name: get_metarule_table + detail: array get_metarule_table + doc: Returns names of all currently available scripting functions. + macro: sfall.h + + - name: dialog_message + detail: void dialog_message(string text) + doc: Displays a message in the NPC response window in dialog or barter screen. + macro: sfall.h + + - name: get_current_inven_size + detail: get_current_inven_size(ObjectPtr object) + doc: Returns the current inventory size of the container or the critter. + macro: sfall.h + + - name: get_object_ai_data + detail: int get_object_ai_data(ObjectPtr object, int aiParam) + doc: Returns the setting value from the AI packet of an object (critter). Use `AI_CAP_*` constants from `define_extra.h` for the `aiParam` argument to get AI value. + macro: sfall.h + + - name: npc_engine_level_up + detail: void npc_engine_level_up(bool toggle) + doc: Enables/disables the engine function that increases the level of party members in the player leveling process. If the engine function is disabled, the process of leveling up party members should be performed by script functions. + macro: sfall.h + + - name: set_drugs_data + detail: void set_drugs_data(int type, int pid, int value) + doc: "Overrides the parameters of drugs set in the configuration file (`DrugsFile` setting in `ddraw.ini`). Type: 0 - changes the value of `NumEffects` for the drug (see `Drugs.ini` for the description of `NumEffects`), 1 - changes the duration of the addiction effect for the drug (a value of 1 = one game minute)." + macro: sfall.h + + - name: metarule_exist + detail: bool metarule_exist(string metaruleName) + doc: Returns True if the specified name of metarule (sfall_funcX) function exists in the current version of sfall. + macro: sfall.h + + - name: add_extra_msg_file + detail: int add_extra_msg_file(string fileName) + doc: | + Loads the custom message file, and returns the file ID number assigned to it in range from 0x3000 to 0x3FFF for the `message_str_game` function to get messages from the file. + - `fileName`: the name of the custom message file (including the .msg extension) in `text\\game\` directory. + + Alternative form: `int add_extra_msg_file(string fileName, int fileNumber)` + - `fileNumber`: the file ID number for the `message_str_game` function. The available range is from 0x2000 to 0x2FFF (see `ExtraGameMsgFileList` setting in `ddraw.ini`) + Use `fileNumber` only if you want to add a message file without editing `ddraw.ini` or existing scripts to support the old way. + macro: sfall.h + + - name: void sfall_func0("remove_timer_event") + detail: void sfall_func0("remove_timer_event") + doc: Clears all set timer events for the current global script. + macro: sfall.h + - name: sfall_func1("remove_timer_event", int fixedParam) + detail: void sfall_func1("remove_timer_event", int fixedParam) + doc: Removes all timer events with the specified `fixedParam` value for the current global script. + macro: sfall.h + + - name: sfall_func0("hide_window") + detail: void sfall_func0("hide_window") + doc: Hides currently active (selected) script window. + macro: sfall.h + - name: sfall_func1("hide_window", string winName) + detail: void sfall_func0("hide_window") + doc: | + Hides the specified script window. + - winName: the window name, assigned to the window by the `CreateWin/create_win` function + macro: sfall.h + - name: sfall_func0("show_window") + detail: void sfall_func0("show_window") + doc: Displays the script window previously hidden with the `sfall_func0("hide_window")` function. + macro: sfall.h + - name: sfall_func1("show_window", string winName) + detail: void sfall_func1("show_window", string winName) + doc: | + Displays the specified hidden script window. + `winName`: the window name, assigned to the window by the `CreateWin/create_win` function + macro: sfall.h + + - name: get_text_width + detail: int get_text_width(string text) + doc: Returns the text width in pixels for the currently set font. + macro: sfall.h + + - name: sfall_func2("string_compare", string str1, string str2) + detail: bool sfall_func2("string_compare", string str1, string str2) + doc: Compares two strings case-insensitive, and returns `True` if the two strings are matched. + macro: sfall.h + - name: sfall_func3("string_compare", string str1, string str2, int codePage) + detail: bool sfall_func3("string_compare", string str1, string str2, int codePage) + doc: | + Compares two strings case-insensitive, and returns `True` if the two strings are matched + - `codePage`: code page number to properly compare national characters in the range 128-255 of the ASCII code table + available encodings: 1250-1252, 866 + macro: sfall.h + + - name: objects_in_radius + detail: objects_in_radius", int tile, int radius, int elevation, int type) + doc: | + - returns an array of objects of a type (see `OBJ_TYPE_*` constants in `define_extra.h`) within the specified radius from the given tile + - passing -1 to the `type` argument or _not specifying it_ will return all objects within the radius + - the radius is limited to 50 hexes + macro: sfall.h + +- name: NPC perks + parent: Perks and traits + doc: These functions are similar to `has_fake_*/set_fake_*/set_selectable_perk` functions, but apply to the specified party member NPC (including `dude_obj`) + items: + - name: set_fake_perk_npc + detail: void set_fake_perk_npc(object npc, string namePerk, int level, int image, string desc) + macro: sfall.h + - name: set_fake_trait_npc + detail: void set_fake_trait_npc(object npc, string nameTrait, int active, int image, string desc) + macro: sfall.h + - name: set_selectable_perk_npc + detail: void set_selectable_perk_npc(object npc, string namePerk, int active, int image, string desc) + macro: sfall.h + - name: has_fake_perk_npc + detail: int has_fake_perk_npc(object npc, string namePerk) + macro: sfall.h + - name: has_fake_trait_npc + detail: int has_fake_trait_npc(object npc, string nameTrait) + macro: sfall.h + +- name: Global script functions + parent: Global scripts + items: + - name: set_global_script_repeat + detail: void set_global_script_repeat(int frames) + opcode: 0x816a + doc: Only has an effect on the script it is called from. Every global script needs its own `game_loaded` block to correctly set up repeat rate. Will have no effect if called on a non-global script. + - name: set_global_script_type + detail: void set_global_script_type(int type) + opcode: 0x819b + doc: Only has an effect on the script it is called from. Every global script needs its own `game_loaded` block to correctly set up the script type. + - name: available_global_script_types + detail: int available_global_script_types + opcode: 0x819c + +- name: Combat + items: + - name: attack_is_aimed + detail: bool attack_is_aimed() + doc: Returns 1 if the aimed attack mode is selected, 0 otherwise. + macro: sfall.h + + - name: block_combat + detail: void block_combat(bool value) + doc: Deny the player to enter combat mode. + opcode: 0x824a + + - name: force_aimed_shots + detail: void force_aimed_shots(int pid) + opcode: 0x823e + doc: Allows overriding the normal rules regarding which weapons are allowed to make aimed attacks. (e.g. weapons that cause explosive damage normally cannot normally make aimed shots.) Will allow a weapon to make aimed shots even if it normally couldn't. Affects player and NPCs alike. Does not override the effects of the fast shot trait. The list of edited weapons is not saved over game loads, so you need to call the function once at each reload. Use a pid of 0 to represent unarmed. + - name: disable_aimed_shots + detail: void disable_aimed_shots(int pid) + opcode: 0x823f + doc: Allows overriding the normal rules regarding which weapons are allowed to make aimed attacks. (e.g. weapons that cause explosive damage normally cannot normally make aimed shots.) stops a weapon from making aimed shots even if it normally coulld. Affects player and NPCs alike. The list of edited weapons is not saved over game loads, so you need to call the function once at each reload. Use a pid of 0 to represent unarmed. + - name: get_attack_type + detail: int get_attack_type + opcode: 0x8228 + - name: get_bodypart_hit_modifier + detail: int get_bodypart_hit_modifier(int bodypart) + opcode: 0x81df + doc: Gets the hit percentage modifiers for aiming at specific bodyparts. Valid bodypart id's are from 0 to 8. + - name: combat_data + detail: mixed combat_data + doc: | + - returns a pointer to the `C_ATTACK_*` data for the current combat attack process (see defined constants in `define_extra.h`) + - can be used in conjunction with the `get_object_data` and `set_object_data` functions + example: `sfall_func3("set_object_data", sfall_func0("combat_data"), C_ATTACK_UNUSED, 255);` + - name: set_bodypart_hit_modifier + detail: void set_bodypart_hit_modifier(int bodypart, int value) + opcode: 0x81e0 + doc: Alters the hit percentage modifiers for aiming at specific bodyparts. Valid bodypart id's are from 0 to 8. Changes are not saved, and will reset to the defaults (or to the values specified in ddraw.ini if they exist) at each reload. + + - name: set_critical_table + detail: void set_critical_table(int crittertype, int bodypart, int level, int valuetype, int value) + opcode: 0x81e1 + doc: Used for modifying the critical table. For details see [critical hit tables](http://falloutmods.wikia.com/wiki/Critical_hit_tables). Changes are not saved, and will reset to the defaults, (or to the contents of `CriticalOverrides.ini`, if it exists) at each game reload. Requires `OverrideCriticalTable` to be set to 1 in `ddraw.ini`. (Disabled by default, because it noticably increases loading times.) + - name: get_critical_table + detail: int get_critical_table(int crittertype, int bodypart, int level, int valuetype) + opcode: 0x81e2 + doc: Gets current critical table. For details see [critical hit tables](http://falloutmods.wikia.com/wiki/Critical_hit_tables). Requires `OverrideCriticalTable` to be set to 1 in `ddraw.ini`. (Disabled by default, because it noticably increases loading times.) + - name: reset_critical_table + detail: void reset_critical_table(int crittertype, int bodypart, int level, int valuetype) + opcode: 0x81e3 + doc: Resets the critical table to default (or to the contents of `CriticalOverrides.ini`, if it exists). For details see 'http://falloutmods.wikia.com/wiki/Critical_hit_tables'. Requires `OverrideCriticalTable` to be set to 1 in `ddraw.ini`. (Disabled by default, because it noticably increases loading times.) + + - name: get_last_target + detail: ObjectPtr get_last_target(ObjectPtr critter) + doc: Will return the last critter to be deliberately attacked. Outside of combat always returns 0. + opcode: 0x8248 + - name: get_last_attacker + detail: ObjectPtr get_last_attacker(ObjectPtr critter) + doc: Will return the last critter to deliberately launch an attack against the argument critter. If a critter has not launched/received an attack, it will return 0. Outside of combat always returns 0. + opcode: 0x8249 + + - name: set_critter_burst_disable + detail: void set_critter_burst_disable(int critter, int disable) + opcode: 0x8216 + + - name: get_critter_current_ap + detail: int get_critter_current_ap(CritterPtr) + opcode: 0x8191 + doc: Should only be used during the target critters turn while in combat. Calling it outside of combat typically returns the critters max ap, but don't rely on that behaviour. (Specifically, if the critter has never before entered combat, it will probably return the critters base ap ignoring any extra bonuses from perks etc.) + - name: set_critter_current_ap + detail: void set_critter_current_ap(CritterPtr, int ap) + opcode: 0x8192 + doc: Should only be used during the target critters turn while in combat. + +- name: Car + items: + - name: set_car_current_town + detail: void set_car_current_town(int town) + opcode: 0x81b6 + doc: Changes the current town index for the player's car. + - name: car_gas_amount + detail: int car_gas_amount() + doc: | + Returns the current amount of fuel in player's car (between 0 and 80000). + To change fuel amount, use vanilla function: `metarule(METARULE_GIVE_CAR_GAS, amount)` - `amount` can be positive or negative. + macro: sfall.h + - name: set_car_intface_art + detail: void set_car_intface_art(int artIndex) + doc: | + - Changes the interface art (index in `intrface.lst`) for the car image on the world map interface + - Should be called before going to the world map + - Vanilla art index is 433 + macro: sfall.h + +- name: Windows and images + parent: Interface + items: + - name: interface_art_draw + detail: int sfall_func4("interface_art_draw", int winType, string artFile/int artID, int x, int y) + doc: | + ```c++ + int sfall_func4("interface_art_draw", int winType, string artFile/int artID, int x, int y) + int sfall_func5("interface_art_draw", int winType, string artFile/int artID, int x, int y, int frame) + int sfall_func6("interface_art_draw", int winType, string artFile/int artID, int x, int y, int frame, array param) + ``` + - draws the specified PCX or FRM image in the game interface window, returns -1 on any error + - `winType`: the type number of the interface window (see `WINTYPE_*` constants in `sfall.h`) + this also takes the value of the flag (0x1000000) to prevent immediate redrawing of the interface window + - `artFile/artId`: path to the PCX/FRM file (e.g. `art\\inven\\5mmap.frm`), or its FRM ID number (e.g. `0x7000026`, see specification of the FID format) + - `x/y`: offset relative to the top-left corner of the window + + optional arguments: + - `frame`: frame number, the first frame starts from zero + - `param`: an array which specifies additional parameters, where: + index 0 - sprite direction for multi-directional FRM + index 1/index 2 - the new width/height to scale the image to. Pass -1 to use the original width/height + + - name: interface_print + detail: int sfall_func5("interface_print", string text, int winType, int x, int y, int color) + doc: | + ```c++ + int sfall_func5("interface_print", string text, int winType, int x, int y, int color) + int sfall_func6("interface_print", string text, int winType, int x, int y, int color, int width) + ``` + - displays the text in the specified interface window with the current font. Use vanilla `SetFont` function to set the font + - returns the count of lines printed, or -1 on any error + - `text`: the text to be printed. Use the `\n` control character to move text to a new line (example: "Hello\nWorld!") + - `winType`: the type number of the interface window (see `WINTYPE_*` constants in sfall.h) + - `x/y`: offset relative to the top-left corner of the window + - `color`: the color index in the game palette. Pass 0 if the text color was previously set by vanilla `SetTextColor` function + It can also take additional flags (via `bwor`) for displaying text: + - `0x0010000` - adds a shadow to the text, the 'textshadow' compiler constant + - `0x1000000` - prevents immediate redrawing of the interface window, the `textdirect` compiler constant (works the other way around) + - `0x2000000` - fills the background of the text with black color, the `textnofill` compiler constant (works the other way around) + - `width` (optional): the maximum width of the text. The text will be wrapped to fit within the specified width + + - name: draw_image + detail: void draw_image(string/int artFile/artId, int frame, int x, int y, bool noTransparent) + doc: | + - displays the specified PCX or FRM image in the active window created by vanilla `CreateWin` or sfall's `create_win` script function + - artFile/artId: path to the PCX/FRM file (e.g. `art\\inven\\5mmap.frm`), or its FRM ID number (e.g. `0x7000026`, see specification of the FID format) + optional arguments: + - `frame`: frame number, the first frame starts from zero + - `x/y`: offset relative to the top-left corner of the window + - `noTransparent`: pass True to display an image without transparent background + - NOTE: to omit optional arguments starting from the right, call the functions with different `sfall_funcX` (e.g. `sfall_func4("draw_image", pathFile, frame, x, y))` + macro: sfall.h + + - name: draw_image_scaled + detail: void draw_image_scaled(string/int artFile/artId, int frame, int x, int y, int width, int height) + doc: | + - displays the specified PCX or FRM image in the active window created by vanilla `CreateWin` or sfall's `create_win` script function + - artFile/artId: path to the PCX/FRM file (e.g. `art\\inven\\5mmap.frm`), or its FRM ID number (e.g. `0x7000026`, see specification of the FID format) + optional arguments: + - `frame`: frame number, the first frame starts from zero + - `x/y`: offset relative to the top-left corner of the window + - `width/height`: the new width/height to scale the image to. Pass -1 to either width or height to keep the aspect ratio when scaling + - NOTE: to omit optional arguments starting from the right, call the functions with different `sfall_funcX` (e.g. `sfall_func4("draw_image", pathFile, frame, x, y))` + - if called without `x/y/width/height` arguments, the image will be scaled to fit the window without transparent background + macro: sfall.h + + - name: get_window_under_mouse + detail: int get_window_under_mouse() + opcode: 0x821f + - name: create_win + detail: void create_win(string winName, int x, int y, int width, int height, int flags) + doc: "`flags` argument is optional. Works just like vanilla `CreateWin` function, but creates a window with `MoveOnTop` flag if the flags argument is not specified, and allows to set additional flags for the created window. `MoveOnTop` flag allows the created window to be placed on top of the game interface." + macro: sfall.h + + - name: get_window_attribute + detail: int sfall_func1("get_window_attribute", int winType) + doc: | + Alternative form: `int sfall_func2("get_window_attribute", int winType, int attrType)` + Returns the attribute of the specified interface window by the `attrType` argument. + - `winType`: the type number of the interface window (see `WINTYPE_*` constants in `sfall.h`) + - `attrType`: `0` - checks and returns a value of 1 if the specified interface window is created by the game (same as without the argument) + `1` - X position, `2` - Y position (relative to the top-left corner of the game screen) + `3` - interface width size, `4` - interface height size + `-1` - returns an associative array of keys (left, top, right, bottom) and values that define the position of the window rectangle + (use standard syntax to access array values, e.g. `winRect.top`, `winRect.bottom`) + - returns -1 if the specified attribute cannot be obtained + - name: message_box + detail: int sfall_func4("message_box", string message, int flags, int color1, int color2) + doc: | + Creates a dialog box with text and returns the result of pressing the button: 0 - No (Escape), 1 - Yes/Done (Enter). Returns -1 if for some reason the dialog box cannot be created. + ``` + - message: the text in the dialog box. Use the `\n` control character to move text to a new line (example: "Hello\nWorld!") + optional arguments: + - flags: mode flags (see `MSGBOX_*` constants in define_extra.h). Pass -1 to skip setting the flags (default flags are NORMAL and YESNO) + - color1/color2: the color index in the game palette. `color1` sets the text color for the first line, and `color2` for all subsequent lines of text (default color is 145) + ``` + - name: set_window_flag + detail: void set_window_flag(string winName/int winID, int flag, bool value) + doc: | + Changes the specified flag for the created script or game interface window. + - winName: the window name, assigned to the window by the `CreateWin/create_win` function + - winID: the ID number of the interface or script window obtained with the `get_window_under_mouse` function, or 0 for the current game interface + - flag: the flag to change (see `WIN_FLAG_*` constants in `define_extra.h`) + - value: `true` - set the flag, `false` - unset the flag + macro: sfall.h + + - name: win_fill_color + detail: int win_fill_color(int x, int y, int width, int height, int color) + doc: | + Fills the rectangle area of the currently selected script window with the specified color, or clears the window with transparent (index 0) color (call the function without arguments). + - `color`: the color index in the game palette (from 0 to 255) + - name: nterface_overlay + detail: sfall_func2("interface_overlay", int winType, int mode) + doc: | + Alternative form: `int sfall_func6("interface_overlay", int winType, 2, int x, int y, int width, int height)`. + + Creates an additional drawing surface above the graphic layer of the specified interface window. All subsequent calls of `interface_art_draw` and `interface_print` functions will draw on it. + - `winType`: the type number of the interface window (see `WINTYPE_*` constants in `sfall.h`) + - `mode`: 1 - creates a new overlay surface + 2 - clears the overlay area or the specified rectangle defined by the `x`, `y`, `width`, `height` arguments + 0 - destroys the created overlay surface (frees up the memory allocated to the surface) + +- name: Outline + parent: Interface + items: + - name: outlined_object + detail: ObjectPtr outlined_object() + doc: Returns an object that is currently highlighted by hovering the mouse above it. + macro: sfall.h + - name: get_outline + detail: int get_outline(ObjectPtr obj) + doc: Gets the current outline color for an object. + macro: sfall.h + - name: set_outline + detail: void set_outline(ObjectPtr obj, int color) + doc: | + - sets the outline color of an object (see `OUTLINE_*` constants in `sfall.h`) + - can also set a custom color from the game palette by shifting the color index value left by 8 bits: `0xCC00` where `CC` is the palette index (available since sfall 4.2.7/3.8.27) + - passing 0 will disable the outline + macro: sfall.h + +- name: Main interface + parent: Interface + items: + - name: intface_is_hidden + detail: bool intface_is_hidden() + macro: sfall.h + doc: Returns 1 if interface is currently hidden, 0 otherwise. + - name: intface_redraw + detail: void intface_redraw(bool winType) + macro: sfall.h + doc: | + Redraws main game interface. Useful after direct changes to current player weapons or stats to reflect changes. + - redraws main game interface, useful to reflect changes after directly changing current player weapons or stats + - `winType`: the type number of the interface window (see `WINTYPE_*` constants in `sfall.h`). Pass `-1` to redraw all interface windows. + - name: intface_hide + detail: void intface_hide() + doc: Hides main interface. + macro: sfall.h + - name: intface_show + detail: void intface_show() + doc: Shows main interface. + macro: sfall.h + +- name: Inventory + parent: Interface + items: + - name: display_stats + detail: void display_stats() + doc: | + - Updates player's stats in the inventory display window or on the character screen. + - NOTE: works only when the interface window is opened + macro: sfall.h + - name: inventory_redraw + detail: void inventory_redraw(invSide) + doc: 'Redraws inventory items list in the inventory/loot/barter screens. Argument invSide specifies which side needs to be redrawn: 0 - the player, 1 - target (container/NPC in loot/barter screens), -1 - both sides (same as without argument).' + macro: sfall.h + +- name: Pip-Boy + parent: Interface + items: + - name: set_quest_failure_value + detail: void sfall_func2("set_quest_failure_value", int gvarNumber, int thresholdValue) + doc: | + - sets the threshold value (failure_threshold) for the quest at which the quest will be considered failed (its description in the pipboy will be crossed out and colored red) + - `gvarNumber`: the number of the global variable controlling the quest + - `thresholdValue`: the value of the global variable at which the quest is counted as a failure + +- name: Cursor + parent: Interface + items: + - name: get_cursor_mode + detail: int get_cursor_mode() + doc: 'Returns the current cursor mode. Values: 0 - movement cursor, 1 - command cursor, 2 - targeting cursor, 4 to 10 are Skilldex skills (yellow targeting cursor).' + macro: sfall.h + - name: set_cursor_mode + detail: void set_cursor_mode(int mode) + doc: Sets the current cursor mode. + macro: sfall.h + +- name: Locks + items: + - name: lock_is_jammed + detail: bool lock_is_jammed(ObjectPtr obj) + doc: Returns 1 if the lock (container or scenery) is currently jammed, 0 otherwise. + macro: sfall.h + - name: unjam_lock + detail: void unjam_lock(ObjectPtr obj) + doc: Unjams a lock immediately without having to wait until the next day, or leave the map and then return after 24 hours. __Does not work__ in `use_skill_on_p_proc` procedure. + macro: sfall.h + - name: set_unjam_locks_time + detail: void set_unjam_locks_time(int time) + doc: Sets after how many hours (up to 127 hours) jammed locks will be unjammed if the player leaves the map. Also disables the auto unjam that occurs at midnight when the player is on the map. Passing 0 will disable the auto unjam mechanism completely. The auto unjam mechanism will be reset each time the player reloads the game. + macro: sfall.h + +- name: INI settings + items: + - name: modified_ini + detail: int modified_ini + opcode: 0x823b + doc: Returns the value of ModifiedIni setting in [Main] section of the INI. + - name: get_ini_setting + detail: int get_ini_setting(string setting) + doc: | + - Reads an integer value from an ini file in the fallout directory. + - It only takes a single argument; seperate the file name, section and key with a "\|" character; e.g. `myvar:=get_ini_setting("myini.ini|mysec|var1")` If the file or key cannot be found, -1 is returned. + - The file name is limited to 63 chars, including the extension. + - The section name is limited to 32 characters. + - It can also be used to get sfall's settings, by using `ddraw.ini` as the file name. + opcode: 0x81ac + - name: get_ini_string + detail: string get_ini_string(string setting) + doc: Reads a string value from an ini file in the fallout directory. + opcode: 0x81eb + - name: get_ini_section + detail: array get_ini_section(string file, string sect) + doc: 'Returns an associative array of keys and values for a given INI file and section. NOTE: all keys and their values will be of String type.' + macro: sfall.h + - name: get_ini_sections + detail: array get_ini_sections(string file) + doc: Returns an array of names of all sections in a given INI file. + macro: sfall.h + - name: set_ini_setting + detail: void set_ini_setting(string setting, int/string value) + doc: 'Writes an integer or a string value to an ini file in the Fallout directory. If the ini file does not exist, it will be created The setting argument works in the same way as in `get_ini_setting`, seperate the file name, section and key with a "|" character. __Note:__ the file name is limited to 63 chars (including the extension), the section name is limited to 32 characters.' + macro: sfall.h + +- name: Objects and scripts + items: + - name: set_self + detail: void set_self(ObjectPtr) + doc: | + Overrides the script's `self_obj` for the next function call. + - It is primarily used to allow the calling of functions which take an implicit `self_obj` parameter (e.g. `drop_obj`) from global scripts, but it can also be used from normal scripts. + - Will revert back to its original value after the next function call. + - Calling `self_obj(0)` will also revert `self_obj` to original value. It is recommended to call this after each use of `set_self` in normal scripts in order to avoid unforeseen side effects. + - `source_obj`, `target_obj`, and similar functions will not work if preceded by `set_self`. + - __NOTE:__ for `use_obj`, `use_obj_on_obj` vanilla functions to work correctly, it is required to call `set_self` twice. + opcode: 0x8206 + - name: set_dude_obj + detail: void set_dude_obj(ObjectPtr critter) + doc: Take control of a given critter. Passing value 0 will reset control back to "real" dude. + macro: sfall.h + - name: real_dude_obj + detail: ObjectPtr real_dude_obj() + doc: Returns the initial `dude_obj` after `set_dude_obj` was used. + macro: sfall.h + + - name: remove_script + detail: void remove_script(ObjectPtr) + opcode: 0x81f3 + doc: Accepts a pointer to an object and will remove the script from that object. + - name: set_script + detail: void set_script(ObjectPtr, int scriptid) + opcode: 0x81f4 + doc: Accepts a pointer to an object and scriptID, and applies the given script to an object (scriptID accept the same values as `create_object_sid `from sfall 3.6). If used on an object that is already scripted, it will remove the existing script first; you cannot have multiple scripts attached to a single object. Calling `set_script` on `self_obj` will have all sorts of wacky side effects, and should be avoided. If you add 0x80000000 to the sid when calling `set_script`, `map_enter_p_proc` will be SKIPPED. The `start` proc will always be run. + - name: get_script + detail: int get_script(ObjectPtr) + opcode: 0x81f5 + doc: | + - accepts a pointer to an object and returns its scriptID (line number in `scripts.lst`), or 0 if the object is unscripted. + - returns -1 on argument error. + + - name: obj_is_carrying_obj + detail: int (ObjectPtr invenObj, ObjectPtr itemObj) + doc: Returns number of `itemObj` inside invenObj's inventory, note that both arguments are object pointers. useful when dealing with different stacks of same item (`obj_is_carrying_obj_pid` just returns total for all stacks of the same PID.) + opcode: 0x8275 + + - name: loot_obj + detail: ObjectPtr loot_obj() + doc: Returns a pointer to the target object (container or critter) of the loot screen. + macro: sfall.h + - name: dialog_obj + detail: ObjectPtr dialog_obj() + doc: Returns a pointer to the object (critter) the player is having a conversation or bartering with. + macro: sfall.h + + - name: obj_under_cursor + detail: ObjectPtr obj_under_cursor(bool onlyCritter, bool includeDude) + doc: | + Returns the object under the cursor on the main game screen. + - onlyCritter: + - True - only checks critters and ignores their cover (roof tiles, walls, scenery, etc.) + - False - checks all objects (can't check critters under objects) + - passing False to the includeDude argument will ignore dude_obj + - **NOTE:** to get an object located on a tile when the cursor is in movement mode (hexagon cursor), use the `tile_under_cursor` function + macro: sfall.h + + - name: get_object_data + detail: get_object_data(ObjectPtr object, int offset) + doc: Returns the data at the specified offset of an object (see `OBJ_DATA_*` constants in `define_extra.h` for offsets). + macro: sfall.h + - name: set_object_data + detail: set_object_data(ObjectPtr object, int offset, int data) + doc: Sets the data at the specified offset of an object. + macro: sfall.h + + - name: get_flags + detail: int get_flags(ObjectPtr obj) + doc: Gets the current value of object flags (see `define_extra.h` for available flags). + macro: sfall.h + - name: set_flags + detail: void set_flags(ObjectPtr obj, int flags) + doc: Sets the current flags of an object. All flags are rewritten with given integer, so first get current flags with `get_flags` and use `bwor/bwand` to set/remove specific flag. + macro: sfall.h + + - name: set_unique_id + detail: int set_unique_id(ObjectPtr object, int flag) + doc: | + Assigns a unique ID number to the object and returns it. If a unique ID number has already been assigned to an object, then ID number is returned without reassignment. `flag` is optional. + - items with unique IDs will not stack with other items of the same type in the inventory + - to just get the current ID number of an object, use `get_object_data(object, OBJ_DATA_ID)` + - unique ID numbers are saved in your savegame, and have a range from 0x10000000 to 0x7FFFFFFF + - there is also a unique ID number range for the player and party members from 18000 to 83535 + - to assign a new ID number generated by the engine to the object (i.e. unassign a unique ID), call the function with two arguments and pass -1 for the flag argument + macro: sfall.h diff --git a/artifacts/scripting/headers/sfall.h b/artifacts/scripting/headers/sfall.h index 87d8fc0e..7c0a0023 100644 --- a/artifacts/scripting/headers/sfall.h +++ b/artifacts/scripting/headers/sfall.h @@ -72,6 +72,8 @@ #define HOOK_ADJUSTPOISON (44) #define HOOK_ADJUSTRADS (45) #define HOOK_ROLLCHECK (46) +#define HOOK_BESTWEAPON (47) +#define HOOK_CANUSEWEAPON (48) //Valid arguments to list_begin #define LIST_CRITTERS (0) @@ -288,6 +290,8 @@ // clears the keyboard input buffer, use it in the HOOK_KEYPRESS hook to clear keyboard events before calling functions that are waiting for keyboard input #define clear_keyboard_buffer metarule3(201, 0, 0, 0) +// checks if the specified PID number exists in the list of registered protos +#define check_pid(pid) (get_proto_data(pid, 0) != -1) /* sfall_funcX macros */ #define add_extra_msg_file(name) sfall_func1("add_extra_msg_file", name) @@ -377,6 +381,7 @@ #define set_map_enter_position(tile, elev, rot) sfall_func3("set_map_enter_position", tile, elev, rot) #define set_object_data(obj, offset, value) sfall_func3("set_object_data", obj, offset, value) #define set_outline(obj, color) sfall_func2("set_outline", obj, color) +#define set_quest_failure_value(gvar, threshold) sfall_func2("set_quest_failure_value", gvar, threshold) #define set_rest_heal_time(time) sfall_func1("set_rest_heal_time", time) #define set_rest_mode(mode) sfall_func1("set_rest_mode", mode) #define set_terrain_name(x, y, name) sfall_func3("set_terrain_name", x, y, name) diff --git a/artifacts/scripting/hooks.yml b/artifacts/scripting/hooks.yml new file mode 100644 index 00000000..db2bd133 --- /dev/null +++ b/artifacts/scripting/hooks.yml @@ -0,0 +1,796 @@ +# Format: +# - name: BlaBla # Human readable hook name. HOOK_BLABLA and hs_blabla.int in the docs are generated from this. Required. +# id: HOOK_BLABLA # real hook id. Optional. +# doc: | +# Hook documentation, markdown format. +# Can be multiline. +# Required. +# filename: override filename (hs_blabla.int), if it doesn't match the generated one. Optional. + +- name: ToHit + id: HOOK_TOHIT + doc: | + Runs when Fallout is calculating the chances of an attack striking a target. Runs after the hit chance is fully calculated normally, including applying the 95% cap. + + ``` + int arg0 - The hit chance (capped) + Critter arg1 - The attacker + Critter arg2 - The target of the attack + int arg3 - The targeted bodypart + int arg4 - Source tile (may differ from attacker's tile, when AI is considering potential fire position) + int arg5 - Attack Type (one of ATKTYPE_*) + int arg6 - Ranged flag. 1 means the hit chance is calculated by taking into account the bonuses/penalties of the distance to the target + int arg7 - The raw hit chance before applying the cap + + int ret0 - the new hit chance + ``` + +- name: AfterHitRoll + id: HOOK_AFTERHITROLL + doc: | + Runs after Fallout has decided if an attack will hit or miss. + + ``` + int arg0 - If the attack will hit: 0 - critical miss, 1 - miss, 2 - hit, 3 - critical hit + Critter arg1 - The attacker + Critter arg2 - The target of the attack + int arg3 - The bodypart + int arg4 - The hit chance + + int ret0 - Override the hit/miss + int ret1 - Override the targeted bodypart + Critter ret2 - Override the target of the attack + ``` + +- name: CalcAPCost + id: HOOK_CALCAPCOST + doc: | + Runs whenever Fallout is calculating the AP cost of using the weapon (or unarmed attack). Doesn't run for using other item types or moving. + Note that the first time a game is loaded, this script doesn't run before the initial interface is drawn, so if the script effects the AP cost of whatever is in the player's hands at the time the wrong AP cost will be shown. It will be fixed the next time the interface is redrawn. + You can get the weapon object by checking item slot based on attack type (`ATKTYPE_LWEP1`, `ATKTYPE_LWEP2`, etc) and then calling `critter_inven_obj`. + + ``` + Critter arg0 - The critter performing the action + int arg1 - Attack Type (see ATKTYPE_* constants) + int arg2 - Is aimed attack (1 or 0) + int arg3 - The default AP cost + Item arg4 - The weapon for which the cost is calculated. If it is 0, the pointer to the weapon can still be obtained by the aforementioned method + + int ret0 - The new AP cost + ``` + +- name: DeathAnim1 + id: HOOK_DEATHANIM1 + doc: | + Runs before Fallout tries to calculate the death animation. Lets you switch out which weapon Fallout sees. + Does not run for critters in the knockdown/out state. + + ``` + int arg0 - The pid of the weapon performing the attack. (May be -1 if the attack is unarmed) + Critter arg1 - The attacker + Critter arg2 - The target + int arg3 - The amount of damage + int arg4 - Unused, always -1. Use this if you are using the same procedure for HOOK_DEATHANIM1 and HOOK_DEATHANIM2 (since sfall 4.1/3.8.24) + + int ret0 - The pid of an object to override the attacking weapon with + ``` + +- name: DeathAnim2 + id: HOOK_DEATHANIM2 + doc: | + Runs after Fallout has calculated the death animation. Lets you set your own custom frame id, so more powerful than `HOOK_DEATHANIM1`, but performs no validation. + When using `critter_dmg` function, this script will also run. In that case weapon pid will be -1 and attacker will point to an object with `obj_art_fid == 0x20001F5`. + Does not run for critters in the knockdown/out state. + + ``` + Item arg0 - The pid of the weapon performing the attack. (May be -1 if the attack is unarmed) + Critter arg1 - The attacker + Critter arg2 - The target + int arg3 - The amount of damage + int arg4 - The death anim id calculated by Fallout + + int ret0 - The death anim id to override with + ``` + +- name: CombatDamage + id: HOOK_COMBATDAMAGE + filename: hs_subcombatdmg.int + doc: | + Runs when: + 1. Game calculates how much damage each target will get. This includes primary target as well as all extras (explosions and bursts). This happens BEFORE the actual attack animation. + 2. AI decides whether it is safe to use area attack (burst, grenades), if he might hit friendlies. + + Does not run for misses, or non-combat damage like dynamite explosions. + + ``` + Critter arg0 - The target + Critter arg1 - The attacker + int arg2 - The amount of damage to the target + int arg3 - The amount of damage to the attacker + int arg4 - The special effect flags for the target (use bwand DAM_* to check specific flags) + int arg5 - The special effect flags for the attacker (use bwand DAM_* to check specific flags) + int arg6 - The weapon used in the attack + int arg7 - The bodypart that was struck + int arg8 - Damage Multiplier (this is divided by 2, so a value of 3 does 1.5x damage, and 8 does 4x damage. Usually it's 2; for critical hits, the value is taken from the critical table; with Silent Death perk and the corresponding attack conditions, the value will be doubled) + int arg9 - Number of bullets actually hit the target (1 for melee attacks) + int arg10 - The amount of knockback to the target + int arg11 - Attack Type (see ATKTYPE_* constants) + mixed arg12 - computed attack data (see C_ATTACK_* for offsets and use get/set_object_data functions to get/set the data) + + int ret0 - The damage to the target + int ret1 - The damage to the attacker + int ret2 - The special effect flags for the target + int ret3 - The special effect flags for the attacker + int ret4 - The amount of knockback to the target + ``` + +- name: OnDeath + id: HOOK_ONDEATH + doc: | + Runs immediately after a critter dies for any reason. No return values; this is just a convenience for when you need to do something after death for a large number of different critters and don't want to have to script each and every one of them. + + ``` + Critter arg0 - The critter that just died + ``` + +- name: FindTarget + id: HOOK_FINDTARGET + doc: | + Runs when the AI is trying to pick a target in combat. Fallout first chooses a list of 4 likely suspects, then normally sorts them in order of weakness/distance/etc depending on the AI caps of the attacker. + This hook replaces that sorting function, allowing you to sort the targets in some arbitrary way. + + The return values can include critters that weren't in the list of possible targets, but the additional targets may still be discarded later on in the combat turn if they are out of the attackers perception or the chance of a successful hit is too low. The list of possible targets often includes duplicated entries, but this is fixed in sfall 4.2.3/3.8.23. + Use `set_sfall_return` to give the 4 targets, in order of preference. If you want to specify less than 4 targets, fill in the extra spaces with 0's or pass -1 to skip the return value. + + __NOTE:__ The engine can choose targets by the following criteria: + 1) The nearest enemy to the attacker. + 2) The enemy that attacked the attacker. + 3) The enemy that attacked an NPC from the same team as the attacker. + 4) The enemy that is attacked by an NPC from the same team as the attacker. + + ``` + Critter arg0 - The attacker + Critter arg1 - A possible target + Critter arg2 - A possible target + Critter arg3 - A possible target + Critter arg4 - A possible target + + Critter ret0 - The first choice of target + Critter ret1 - The second choice of target + Critter ret2 - The third choice of target + Critter ret3 - The fourth choice of target + ``` + +- name: UseObjOn + id: HOOK_USEOBJON + doc: | + Runs when: + 1. a critter uses an object on another critter. (Or themselves) + 1. a critter uses an object from inventory screen AND this object does not have "Use" action flag set and it's not active flare or explosive. + 1. player or AI uses any drug + + This is fired before the object is used, and the relevant use_obj_on script procedures are run. You can disable default item behavior. + NOTE: you can't remove and/or destroy this object during the hookscript (game will crash otherwise). To remove it, return 1. + + ``` + Critter arg0 - The target + Critter arg1 - The user + int arg2 - The object used + + int ret0 - overrides hard-coded handler and selects what should happen with the item (0 - place it back, 1 - remove it, -1 - use engine handler) + ``` + +- name: UseObj + id: HOOK_USEOBJ + doc: | + Runs when: + 1. a critter uses an object from inventory which have "Use" action flag set or it's an active flare or dynamite. + 2. player uses an object from main interface + + This is fired before the object is used, and the relevant `use_obj` script procedures are run. You can disable default item behavior. + + __NOTE:__ You can't remove and/or destroy this object during the hookscript (game will crash otherwise). To remove it, return 1. + + ``` + Critter arg0 - The user + Obj arg1 - The object used + + int ret0 - overrides hard-coded handler and selects what should happen with the item (0 - place it back, 1 - remove it, -1 - use engine handler) + ``` + +- name: RemoveInvenObj + id: HOOK_REMOVEINVENOBJ + doc: | + Runs when an object is removed from a container or critter's inventory for any reason. + + ``` + Obj arg0 - the owner that the object is being removed from + Item arg1 - the item that is being removed + int arg2 - the number of items to remove + int arg3 - The reason the object is being removed (see RMOBJ_* constants) + Obj arg4 - The destination object when the item is moved to another object, 0 otherwise + ``` + +- name: BarterPrice + id: HOOK_BARTERPRICE + doc: | + Runs whenever the value of goods being purchased is calculated. + + NOTE: the hook is executed twice when entering the barter screen or after transaction: the first time is for the player and the second time is for NPC. + + ``` + Critter arg0 - the critter doing the bartering (either dude_obj or inven_dude) + Critter arg1 - the critter being bartered with + int arg2 - the default value of the goods + Critter arg3 - table of requested goods (being bought from NPC) + int arg4 - the amount of actual caps in the barter stack (as opposed to goods) + int arg5 - the value of all goods being traded before skill modifications + Critter arg6 - table of offered goods (being sold to NPC) + int arg7 - the total cost of the goods offered by the player + int arg8 - 1 if the "offers" button was pressed (not for a party member), 0 otherwise + int arg9 - 1 if trading with a party member, 0 otherwise + + int ret0 - the modified value of all of the goods (pass -1 if you just want to modify offered goods) + int ret1 - the modified value of all offered goods + ``` + +- name: MoveCost + id: HOOK_MOVECOST + doc: | + Runs when calculating the AP cost of movement. + + ``` + Critter arg0 - the critter doing the moving + int arg1 - the number of hexes being moved + int arg2 - the original AP cost + + int ret0 - the new AP cost + ``` + +- name: Deprecated hooks + filename: "" # skip + doc: | + * `hs_hexmoveblocking.int` + * `hs_hexaiblocking.int` + * `hs_hexshootblocking.int` + * `hs_hexsightblocking.int` + + Run when checking to see if a hex blocks movement or shooting. (or ai-ing, presumably...) + + __NOTE:__ These hook scripts can become very CPU-intensive and you should avoid using them. + For this reason, these hooks are not thoroughly supported in sfall, and may be removed in future versions.
+ If you want to check if some tile or path is blocked, use functions: `obj_blocking_tile`, `obj_blocking_line`, `path_find_to`.
+ If you want script to be called every time NPC moves by hex in combat, use `HOOK_MOVECOST` hook. + + ``` + Critter arg0 - the critter doing the moving + int arg1 - the tile number being checked + int arg2 - the elevation being checked + int arg3 - 1 if the hex would normally be blocking + + Obj ret0 - 0 if the hex doesn't block, or any sort of object pointer if it does + ``` + +- name: ItemDamage + id: HOOK_ITEMDAMAGE + doc: | + Runs when retrieving the damage rating of the player's used weapon. (Which may be their fists.) + + ``` + int arg0 - The default min damage + int arg1 - The default max damage + Item arg2 - The weapon used (0 if unarmed) + Critter arg3 - The critter doing the attacking + int arg4 - The type of attack + int arg5 - non-zero if this is an attack using a melee weapon + + int ret0 - Either the damage to be used, if ret1 isn't given, or the new minimum damage if it is + int ret1 - The new maximum damage + ``` + +- name: AmmoCost + id: HOOK_AMMOCOST + doc: | + Runs when calculating ammo cost for a weapon. Doesn't affect damage, only how much ammo is spent. + By default, weapon will shoot when at least 1 round is left, regardless of ammo cost calculations. + To add proper check for ammo before shooting and proper calculation of number of burst rounds (hook type 1 and 2 in arg3), set **CheckWeaponAmmoCost=1** in **Misc** section of ddraw.ini. + + ``` + Item arg0 - The weapon + int arg1 - Number of bullets in burst or 1 for single shots + int arg2 - The amount of ammo that will be consumed, calculated by the original ammo cost function (this is basically 2 for Super Cattle Prod and Mega Power Fist) + NOTE: for hook type 2, this value is the ammo cost per round (default is always 1) + int arg3 - Type of hook: + 0 - when subtracting ammo after single shot attack + 1 - when checking for "out of ammo" before attack + 2 - when calculating number of burst rounds + 3 - when subtracting ammo after burst attack + + int ret0 - The new amount of ammo to be consumed, or ammo cost per round for hook type 2 (set to 0 for unlimited ammo) + ``` + +- name: KeyPress + id: HOOK_KEYPRESS + doc: | + Runs once every time when any key was pressed or released. + * DX codes: see **dik.h** header or https://kippykip.com/b3ddocs/commands/scancodes.htm + * [VK codes](http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731%28v=vs.85%29.aspx) + + __NOTE:__ If you want to override a key, the new key DX scancode should be the same for both pressed and released events. + + ``` + int arg0 - event type: 1 - pressed, 0 - released + int arg1 - key DX scancode + int arg2 - key VK code (very similar to ASCII codes) + + int ret0 - overrides the pressed key (a new key DX scancode or 0 for no override) + ``` + +- name: MouseClick + id: HOOK_MOUSECLICK + doc: | + Runs once every time when a mouse button was pressed or released. + + ``` + int arg0 - event type: 1 - pressed, 0 - released + int arg1 - button number (0 - left, 1 - right, up to 7) + ``` + +- name: UseSkill + id: HOOK_USESKILL + doc: | + Runs when using any skill on any object. + + This is fired before the default handlers are called, which you can override. In this case you should write your own skill use handler entirely, or otherwise nothing will happen (this includes fade in/fade out, time lapsing and messages - all of this can be scripted; to get vanilla text messages - use `message_str_game` along with `sprintf`). + Suggested use - override first aid/doctor skills to buff/nerf them, override steal skill to disallow observing NPCs inventories in some cases. + Doesn't seem to run when lock picking. + + ``` + Critter arg0 - The user critter + Obj arg1 - The target object + int arg2 - skill being used + int arg3 - skill bonus from items such as first aid kits + + int ret0 - overrides hard-coded handler (-1 - use engine handler, any other value - override) + ``` + +- name: Steal + id: HOOK_STEAL + doc: | + Runs when checking an attempt to steal or plant an item in other inventory using Steal skill. + + This is fired before the default handlers are called, which you can override. In this case you MUST provide message of the result to player ("You steal the %s", "You are caught planting the %s", etc.). + Example message (vanilla behavior):
+ `display_msg(sprintf(mstr_skill(570 + (isSuccess != false) + arg3 * 2), obj_name(arg2)));` + + ``` + Critter arg0 - Thief + Obj arg1 - The target + Item arg2 - Item being stolen/planted + int arg3 - 0 when stealing, 1 when planting + + int ret0 - overrides hard-coded handler (1 - force success, 0 - force fail, -1 - use engine handler) + ``` + +- name: WithinPerception + id: HOOK_WITHINPRECEPTION + doc: | + Runs when checking if one critter sees another critter. This is used in different situations like combat AI. You can override the result. + + __NOTE:__ `obj_can_see_obj` calls this first when deciding if critter can possibly see another critter with regard to perception, lighting, sneak factors.
+ If check fails, the end result is false. If check succeeds (e.g. critter is within perception range), another check is made if there is any blocking tile between two critters (which includes stuff like windows, large bushes, barrels, etc.) and if there is - check still fails.
+ You can override "within perception" check by returning 0 or 1, OR, as a convenience, you can also override blocking check after the perception check by returning 2 instead. In this case you should add "line of sight" check inside your hook script, otherwise critters will detect you through walls. + + This is fired after the default calculation is made. + + ``` + Critter arg0 - Watcher object + Obj arg1 - Target object + int arg2 - Result of vanilla function: 1 - within perception range, 0 - otherwise + int arg3 - Type of hook: + 1 - when being called from obj_can_see_obj script function + 2 - when being called from obj_can_hear_obj script function (need to set ObjCanHearObjFix=1 in ddraw.ini) + 3 - when AI determines whether it sees a potential target when selecting attack targets + 0 - all other cases + + int ret0 - overrides the returned result of the function: + 0 - not in range (can't see) + 1 - in range (will see if not blocked) + 2 - forced detection (will see regardless, only used in obj_can_see_obj scripting function which is called by every critter in the game) + ``` + +- name: InventoryMove + id: HOOK_INVENTORYMOVE + doc: | + Runs before moving items between inventory slots in dude interface. You can override the action. + What you can NOT do with this hook: + - force moving items to inappropriate slots (like gun in armor slot) + What you can do: + - restrict player from using specific weapons or armors + - add AP costs for all inventory movement including reloading + - apply or remove some special scripted effects depending on PC's armor + + ``` + int arg0 - Target slot: + 0 - main backpack + 1 - left hand + 2 - right hand + 3 - armor slot + 4 - weapon, when reloading it by dropping ammo + 5 - container, like bag/backpack + 6 - dropping on the ground + 7 - picking up item + 8 - dropping item on the character portrait + Item arg1 - Item being moved + Item arg2 - Item being replaced, weapon being reloaded, or container being filled (can be 0) + + int ret0 - Override setting (-1 - use engine handler, any other value - prevent relocation of item/reloading weapon/picking up item) + ``` + +- name: InvenWield + id: HOOK_INVENWIELD + doc: | + Runs before causing a critter or the player to wield/unwield an armor or a weapon (except when using the inventory by PC). + An example usage would be to change critter art depending on armor being used or to dynamically customize weapon animations. + + __NOTE:__ When replacing a previously wielded armor or weapon, the unwielding hook will not be executed. + If you need to rely on this, try checking if armor/weapon is already equipped when wielding hook is executed. + + ``` + Critter arg0 - critter + Item arg1 - item being wielded or unwielded (weapon/armor) + int arg2 - slot (INVEN_TYPE_*) + int arg3 - 1 when wielding, 0 when unwielding + int arg4 - 1 when removing an equipped item from inventory, 0 otherwise + + int ret0 - overrides hard-coded handler (-1 - use engine handler, any other value - override) - NOT RECOMMENDED + ``` + +- name: AdjustFID + id: HOOK_ADJUSTFID + doc: | + Runs after calculating character figure FID on the inventory screen, whenever the game decides that character appearance might change. + Also happens on other screens, like barter. + + __NOTE:__ FID has following format: `0x0ABBCDDD`, where: `A` - object type, `BB` - animation code (always 0 in this case), `C` - weapon code, `DDD` - FRM index in LST file. + + ``` + int arg0 - the vanilla FID calculated by the engine according to critter base FID and armor/weapon being used + int arg1 - the modified FID calculated by the internal sfall code (like Hero Appearance Mod) + + int ret0 - overrides the calculated FID with provided value + ``` + +- name: CombatTurn + id: HOOK_COMBATURN + doc: | + Runs before and after each turn in combat (for both PC and NPC). + + ``` + int arg0 - event type: + 1 - start of turn + 0 - normal end of turn + -1 - combat ends abruptly (by script or by pressing Enter during PC turn) + -2 - combat ends normally (hook always runs at the end of combat) + Critter arg1 - critter doing the turn + bool arg2 - 1 at the start/end of the player's turn after loading a game saved in combat mode, 0 otherwise + + int ret0 - pass 1 at the start of turn to skip the turn, pass -1 at the end of turn to force end of combat + ``` + +- name: StdProcedure + id: HOOK_STDPROCEDURE + doc: | + Runs before Fallout executes a standard procedure (handler) in any script of any object. + NOTE: this hook will not be executed for `start`, `critter_p_proc`, `timed_event_p_proc`, and `map_update_p_proc` procedures. + + ``` + int arg0 - the number of the standard script handler (see define.h) + Obj arg1 - the object that owns this handler (self_obj) + Obj arg2 - the object that called this handler (source_obj, can be 0) + + int ret0 - pass -1 to cancel the execution of the handler + ``` +- name: StdProcedureEnd + id: HOOK_STDPROCEDURE_END + filename: hs_stdprocedure.int + doc: | + Runs after Fallout executes a standard procedure (handler) in any script of any object. + NOTE: this hook will not be executed for `start`, `critter_p_proc`, `timed_event_p_proc`, and `map_update_p_proc` procedures. + + ``` + int arg0 - the number of the standard script handler (see define.h) + Obj arg1 - the object that owns this handler (self_obj) + Obj arg2 - the object that called this handler (source_obj, can be 0) + int arg3 - 1 after procedure execution + ``` + +- name: CarTravel + id: HOOK_CARTRAVEL + doc: | + Runs continuously during worldmap travel on car. + + ``` + int arg0 - vanilla car speed (between 3 and 8 "steps") + int arg1 - vanilla fuel consumption (100 and below) + + int ret0 - car speed override (pass -1 if you just want to override fuel consumption) + int ret1 - fuel consumption override + ``` + +- name: SetGlobalVar + id: HOOK_SETGLOBALVAR + doc: | + Runs when setting the value of a global variable. + + ``` + int arg0 - the index number of the global variable being set + int arg1 - the set value of the global variable + + int ret0 - overrides the value of the global variable + ``` + +- name: RestTimer + id: HOOK_RESTTIMER + doc: | + Runs continuously while the player is resting (using pipboy alarm clock). + + ``` + int arg0 - the game time in ticks + int arg1 - event type: 1 - when the resting ends normally, -1 - when pressing ESC to cancel the timer, 0 - otherwise + int arg2 - the hour part of the length of resting time + int arg3 - the minute part of the length of resting time + + int ret0 - pass 1 to interrupt the resting, pass 0 to continue the rest if it was interrupted by pressing ESC key + ``` + +- name: GameModeChange + id: HOOK_GAMEMODECHANGE + doc: | + Runs once every time when the game mode was changed, like opening/closing the inventory, character screen, pipboy, etc. + + ``` + int arg0 - event type: 1 - when the player exits the game, 0 - otherwise + int arg1 - the previous game mode + ``` + +- name: UseAnimObj + id: HOOK_USEANIMOBJ + doc: | + Runs before playing the "use" (usually "magic hands") animation when a critter uses a scenery/container object on the map, or before walking/running animation if the player is at a distance from the object. + + ``` + Critter arg0 - the critter that uses an object (usually dude_obj) + Obj arg1 - the object being used + int arg2 - the animation code being used (see ANIM_* in Animcomd.h) + + int ret0 - overrides the animation code (pass -1 if you want to skip the animation) + ``` + +- name: ExplosiveTimer + id: HOOK_EXPLOSIVETIMER + doc: | + Runs after setting the explosive timer. You can override the result. + + ``` + int arg0 - the time in ticks set in the timer + Obj arg1 - the explosive object + int arg2 - the result of engine calculation of whether the timer was set successfully: 1 - failure, 2 - success (similar to ROLL_* in Condtion.h) + + int ret0 - overrides the time of the timer (maximum 18000 ticks) + int ret1 - overrides the result of engine calculation: 0/1 - failure, 2/3 - success (similar to ROLL_*), any other value - use engine handler + ``` + +- name: DescriptionObj + id: HOOK_DESCRIPTIONOBJ + doc: | + Runs when using the examine action icon to display the description of an object. You can override the description text. + An example usage would be to add an additional description to the item based on player's stats/skills. + Does not run if the script of the object overrides the description. + + ``` + Obj arg0 - the object + + int ret0 - a pointer to the new text received by using "get_string_pointer" function + ``` + +- name: UseSkillOn + id: HOOK_USESKILLON + doc: | + Runs before using any skill on any object. Lets you override the critter that uses the skill. + + __NOTE:__ The user critter can't be overridden when using Steal skill. + + ``` + Critter arg0 - the user critter (usually dude_obj) + Obj arg1 - the target object/critter + int arg2 - skill being used + + int ret0 - a new critter to override the user critter. Pass -1 to cancel the skill use, pass 0 to skip this return value + int ret1 - pass 1 to allow the skill being used in combat (only for dude_obj or critter being controlled by the player) + ``` + +- name: OnExplosion + id: HOOK_ONEXPLOSION + doc: | + Runs when Fallout is checking all the tiles within the explosion radius for targets before an explosion occurs. + The tile checking will be interrupted when 6 additional targets (critters) are received. + + ``` + int arg0 - event type: 1 - when checking objects within the explosion radius without causing damage (e.g. the player drops an active explosive), 0 - otherwise + Critter arg1 - the attacker + int arg2 - the tile on which the explosion occurs + int arg3 - checked tile within the explosion radius + Obj arg4 - first found object on the checked tile as an additional target + Critter arg5 - the target critter, may be 0 or equal to the attacker + int arg6 - 1 when using throwing weapons (e.g. grenades), 0 otherwise + + int ret0 - overrides the found object on the checked tile, pass 0 to skip the object + ``` + +- name: SubCombatDamage + id: HOOK_SUBCOMBATDAMAGE + doc: | + This hook overrides the vanilla damage calculation formula. + Runs when: + 1. Before the game calculates how much damage each target will get. This includes primary target as well as all extras (explosions and bursts). + 2. AI decides whether it is safe to use area attack (burst, grenades), if he might hit friendlies. + + Does not run for misses, non-combat damage like dynamite explosions, or if one of the damage formulas is selected in ddraw.ini. + + ``` + Critter arg0 - the attacker + Critter arg1 - the target + Item arg2 - the weapon used in the attack + int arg3 - attack type (see ATKTYPE_* constants) + int arg4 - number of bullets actually hit the target (1 for melee attacks) + int arg5 - target's Damage Resistance (DR) value (affected by critical hit effects, perks, traits, and special unarmed attacks) + int arg6 - target's Damage Threshold (DT) value (affected by critical hit effects, perks, traits, and special unarmed attacks) + int arg7 - bonus ranged damage from the perk + int arg8 - damage multiplier (this is divided by 2, so a value of 3 does 1.5x damage, and 8 does 4x damage. Usually it's 2; for critical hits, the value is taken from the critical table; with Silent Death perk and the corresponding attack conditions, the value will be doubled) + int arg9 - combat difficulty multiplier (125 - rough, 100 - normal, 75 - wimpy; for player or party members it's always 100) + int arg10 - the calculated amount of damage (usually 0, required when using multiple hook scripts to calculate damage and using the set_sfall_arg function) + mixed arg11 - computed attack data (see C_ATTACK_* for offsets and use get/set_object_data functions to get/set the data) + + int ret0 - the returned amount of damage + ``` + +- name: SetLighting + id: HOOK_SETLIGHTING + doc: | + Runs before setting the light level for an object or a map. You can override the result. + + ``` + Obj arg0 - the object being set, or -1 when setting the light level for a map + int arg1 - the light intensity + int arg2 - the light radius, or -1 when setting the light level for a map + + int ret0 - overrides the light intensity. Intensity range is from 0 to 65536 + int ret1 - overrides the light radius. Radius range is from 0 to 8 (works only for the object) + ``` + +- name: Sneak + id: HOOK_SNEAK + doc: | + Runs when the Sneak skill is activated, or when the game rolls another Sneak check after the duration for the current one is over. + You can override the result of a random Sneak check or the duration time for the current result. + + ``` + int arg0 - Sneak check result: 1 - success, 0 - failure + int arg1 - the duration in ticks for the current Sneak check (time depends on Sneak skill level) + Critter arg2 - the critter (usually dude_obj) + + int ret0 - overrides the result of the Sneak check + int ret1 - overrides the duration time for the current result + ``` + +- name: TargetObject + id: HOOK_TARGETOBJECT + doc: | + Runs when the targeting cursor hovers over an object, or when the player tries to attack the target object. + You can override the target object or prevent the player from attacking the chosen target. + + ``` + int arg0 - event type: 0 - when the targeting cursor hovers over the object, 1 - when trying to attack the target object + int arg1 - 1 when the target object is valid to attack, 0 otherwise + Obj arg2 - the target object + + mixed ret0 - overrides the target object, or pass -1 to prevent the player from attacking the object + ``` + +- name: Encounter + id: HOOK_ENCOUNTER + doc: | + Runs whenever a random encounter occurs (except the Horrigan meeting and scripted encounters), or when the player enters a local map from the world map. + You can override the map for loading or the encounter. + + ``` + int arg0 - event type: 0 - when a random encounter occurs, 1 - when the player enters from the world map + int arg1 - the map ID that the encounter will load (see MAPS.h or Maps.txt) + int arg2 - 1 when the encounter occurs is a special encounter, 0 otherwise + + int ret0 - overrides the map ID, or pass -1 for event type 0 to cancel the encounter and continue traveling + int ret1 - pass 1 to cancel the encounter and load the specified map from the ret0 (only for event type 0) + ``` + +- name: AdjustPoison + id: HOOK_ADJUSTPOISON + doc: | + Runs when a critter's poison level is changed, or when the player takes damage from the poison. + + ``` + Critter arg0 - the critter + int arg1 - the amount of poison being added/removed + int arg2 - the damage value at the time of applying the poison effect + (damage from the poison effect is implemented only for the player character; for other critters, this value will always be 0) + + int ret0 - the new amount of poison being added/removed + int ret1 - the new damage value, only negative values are allowed (will only be valid at the time of taking damage from the poison) + ``` + +- name: AdjustRads + id: HOOK_ADJUSTRADS + doc: | + Runs when a critter's radiation level is changed. + + ``` + Critter arg0 - the critter (usually dude_obj) + int arg1 - the amount of radiation being added/removed + + int ret0 - the new amount of radiation being added/removed + ``` + +- name: RollCheck + id: HOOK_ROLLCHECK + doc: | + Runs when a game event performs a random roll to check the chance of success or failure. + + ``` + int arg0 - event type: + 1 - checks the chance of an attack hitting the target + 2 - checks the chance of a bullet from a burst hitting the target (for burst attacks) + 3 - checks the chance when using skills (not listed below) + 4 - check the chance of using Repair skill + 5 - check the chance of using Doctor skill + 6 - check the chance of using Steal skill for the thief (usually the player) + 7 - the second Steal skill chance check for the target to catch the thief, in which the target's failure is the thief's success result + int arg1 - the value of roll result (see ROLL_* constants), which is calculated as: + for ROLL_CRITICAL_SUCCESS: random(1, 100) <= (random_chance / 10) + bonus + for ROLL_CRITICAL_FAILURE: random(1, 100) <= -random_chance / 10 + int arg2 - the chance value + int arg3 - the bonus value, used when checking critical success + int arg4 - random chance (calculated as: chance - random(1, 100)), where a negative value is a failure check (ROLL_FAILURE) + + int ret0 - overrides the roll result + ``` + +- name: BestWeapon + id: HOOK_BESTWEAPON + doc: | + Runs when the AI decides which weapon is the best while searching the inventory for a weapon to equip in combat. + This also runs when the player presses the "Use Best Weapon" button on the party member control panel. + + ``` + Critter arg0 - the critter searching for a weapon + Item arg1 - the best weapon chosen from two items + Item arg2 - the first choice of weapon + Item arg3 - the second choice of weapon + Critter arg4 - the target of the critter (can be 0) + + Item ret0 - overrides the chosen best weapon + ``` + +- name: CanUseWeapon + id: HOOK_CANUSEWEAPON + doc: | + Run when the AI checks whether it can use a weapon. + This mostly happens when NPCs try to find weapons in their inventory or on the map. + + ``` + Critter arg0 - the critter doing the check + Item arg1 - the weapon being checked + int arg2 - attack type (see ATKTYPE_* constants) + int arg3 - original result of engine function: 1 - can use, 0 - can't use + + int ret0 - overrides the result of engine function. Any non-zero value allows using the weapon + ``` diff --git a/artifacts/scripting/hookscripts.txt b/artifacts/scripting/hookscripts.md similarity index 65% rename from artifacts/scripting/hookscripts.txt rename to artifacts/scripting/hookscripts.md index cc6a024b..aa70b7cd 100644 --- a/artifacts/scripting/hookscripts.txt +++ b/artifacts/scripting/hookscripts.md @@ -1,15 +1,16 @@ -------------------------------------- ------------ WHAT IS THIS? ----------- -------------------------------------- +HOOK SCRIPTS +------------ Hook scripts are specially named scripts that are run by sfall at specific points to allow mods to override normally hardcoded behaviour in a more flexible way than sfall's normal ini configuration. In addition to the bit of code it overrides, the script will be run once when first loaded and again at each player reload to allow for setup. Hook scripts have access to a set of arguments supplied to sfall, but aren't required to use them all. They also return one or more values, but again they're optional, and you only need to return a value if you want to override the default. -To aid in mods compatibility, avoid using hs_xxx .int scripts. Instead it is recommended to use a normal global script combined with register_hook_proc or register_hook. +### Hooks compatibility + +To aid in mods compatibility, avoid using `hs_xxx.int` scripts. Instead it is recommended to use a normal global script combined with `register_hook_proc` or `register_hook`. Example setup for a hook-script based mod: - +```js procedure tohit_hook_handler begin display_msg("Modifying hit_hook " + get_sfall_arg); set_hit_chance_max(100); @@ -21,68 +22,78 @@ procedure start begin register_hook_proc(HOOK_TOHIT, tohit_hook_handler); end end +``` +------------------------------------------- There are script functions available, specific to hook scripts: -> int init_hook() -The hook script equivalent of game_loaded; it returns 2 when the script is first loaded, 1 when the player reloads and 0 otherwise. +#### `int init_hook()` +The hook script equivalent of `game_loaded`; it returns 1 when the script is loaded for the first time or when the player reloads the game, and 0 otherwise. -> mixed get_sfall_arg() +#### `mixed get_sfall_arg()` Gets the next argument from sfall. Each time it's called it returns the next argument, or otherwise it returns 0 if there are no more arguments left. -You can arbitrarily get the value of any argument using the sfall_func1("get_sfall_arg_at", argNum) function. +You can arbitrarily get the value of any argument using the `sfall_func1("get_sfall_arg_at", argNum)` function. -> array get_sfall_args() +#### `array get_sfall_args()` Returns all hook arguments as a new temp array. -> void set_sfall_return(int value) +#### `void set_sfall_return(int value)` Used to return the new values from the script. Each time it's called it sets the next value, or if you've already set all return values it does nothing. -> void set_sfall_arg(int argNum, int value) +#### `void set_sfall_arg(int argNum, int value)` Changes argument value. The argument number (argNum) is 0-indexed. This is useful if you have several hook scripts attached to one hook point (see below). -> void register_hook(int hookID) -Used from a normal global script if you want to run it at the same point a full hook script would normally run. In case of this function, "start" proc will be executed in a current global script. You can use all above functions like normal. +#### `void register_hook(int hookID)` +Used from a normal global script if you want to run it at the same point a full hook script would normally run. In case of this function, `start` proc will be executed in the current global script. You can use all above functions like normal. -> void register_hook_proc(int hookID, procedure proc) -The same as register_hook, except that you specifically define which procedure in the current script should be called as a hook (instead of "start" by default). Pass procedure the same as how you use dialog option functions. This IS the recommended way to use hook scripts, as it gives both modularity (each mod logic in a separate global script, no conflicts if you don't use "hs_*.int" scripts) and flexibility (you can place all related hook scripts for specific mod in a single script!). +#### `void register_hook_proc(int hookID, procedure proc)` +The same as `register_hook`, except that you specifically define which procedure in the current script should be called as a hook (instead of "start" by default). Pass procedure the same as how you use dialog option functions. +This IS the recommended way to use hook scripts, as it gives both modularity (each mod logic in a separate global script, no conflicts if you don't use `hs_*.int` scripts) and flexibility (you can place all related hook scripts for specific mod in a single script!). -> void register_hook_proc_spec(int hookID, procedure proc) -Works very similar to register_hook_proc, except that it registers the current script at the end of the hook script execution chain (i.e. the script will be executed after all previously registered scripts for the same hook, including the hs_*.int script). All scripts hooked to a single hook point with this function are executed in exact order of how they were registered, as opposed to the description below, which refers to using register_hook/register_hook_proc functions. +Use zero (0) as the second argument to unregister the hook from the current global script. + +#### `void register_hook_proc_spec(int hookID, procedure proc)` +Works very similar to `register_hook_proc`, except that it registers the current script at the end of the hook script execution chain (i.e. the script will be executed after all previously registered scripts for the same hook, including the `hs_*.int` script). All scripts hooked to a single hook point with this function are executed in exact order of how they were registered, as opposed to the description below, which refers to using `register_hook` and `register_hook_proc` functions. + +__NOTE:__ You can hook several scripts to a single hook point, for example, if it's different mods from different authors or just some different aspects of one larger mod. In this case scripts are executed in reverse order of how they were registered. When one of the scripts in a chain returns value with `set_sfall_return`, the next script may override this value if calls `set_sfall_return` again. Sometimes you need to multiply certain value in a chain of hook scripts. -NOTE: you can hook several scripts to a single hook point, for example if it's different mods from different authors or just some different aspects of one larger mod. In this case scripts are executed in reverse order of how they were registered. When one of the scripts in a chain returns value with "set_sfall_return", the next script may override this value if calls "set_sfall_return" again. Sometimes you need to multiply certain value in a chain of hook scripts. Example: let's say we have a Mod A which reduces all "to hit" chances by 50%. The code might look like this: - +```js original_chance = get_sfall_arg; set_sfall_return(original_chance / 2); +``` -Mod B also want to affect hit chances globally, by increasing them by 50%. Now in order for both mods to work well together, we need to add this line to Mod A hook script: - +Mod B also want to affect hit chances globally, by increasing them by 50%. Now in order for both mods to work well together, we need to add this line to **Mod A** hook script: +```js set_sfall_arg(0, (original_chance / 2)); +``` -This basically changes hook argument for the next script. Mod B code: - +This basically changes hook argument for the next script. **Mod B** code: +```js original_chance = get_sfall_arg; set_sfall_return(original_chance * 1.5); set_sfall_arg(0, (original_chance * 1.5)); +``` -So if you combine both mods together, they will run in chain and the end result will be a 75% from original hit chance (hook register order doesn't matter in this case, if you use "set_sfall_arg" in both hooks). +So if you combine both mods together, they will run in chain and the end result will be a 75% from original hit chance (hook register order doesn't matter in this case, if you use `set_sfall_arg` in both hooks). -The defines to use for the hookID are in sfall.h. +The defines to use for the hookID are in **sfall.h**. -------------------------------------------- ------------ HOOK SCRIPT TYPES ------------- ------------------------------------------- -HOOK_TOHIT (hs_tohit.int) +## HOOK SCRIPT TYPES -Runs when Fallout is calculating the chances of an attack striking a target -Runs after the hit chance is fully calculated normally, including applying the 95% cap +#### `HOOK_TOHIT (hs_tohit.int)` +Runs when Fallout is calculating the chances of an attack striking a target. +Runs after the hit chance is fully calculated normally, including applying the 95% cap. + +``` int arg0 - The hit chance (capped) -critter arg1 - The attacker -critter arg2 - The target of the attack +Critter arg1 - The attacker +Critter arg2 - The target of the attack int arg3 - The targeted bodypart int arg4 - Source tile (may differ from attacker's tile, when AI is considering potential fire position) int arg5 - Attack Type (one of ATKTYPE_*) @@ -90,80 +101,92 @@ int arg6 - Ranged flag. 1 means the hit chance is calculated by taking into int arg7 - The raw hit chance before applying the cap int ret0 - the new hit chance +``` ------------------------------------------- -HOOK_AFTERHITROLL (hs_afterhitroll.int) +#### `HOOK_AFTERHITROLL (hs_afterhitroll.int)` -Runs after Fallout has decided if an attack will hit or miss +Runs after Fallout has decided if an attack will hit or miss. -int arg0 - If the attack will hit. (0 - critical miss, 1 - miss, 2 - hit, 3 - critical hit) -critter arg1 - The attacker -critter arg2 - The target of the attack +``` +int arg0 - If the attack will hit: 0 - critical miss, 1 - miss, 2 - hit, 3 - critical hit +Critter arg1 - The attacker +Critter arg2 - The target of the attack int arg3 - The bodypart int arg4 - The hit chance int ret0 - Override the hit/miss int ret1 - Override the targeted bodypart -critter ret2 - Override the target of the attack +Critter ret2 - Override the target of the attack +``` ------------------------------------------- -HOOK_CALCAPCOST (hs_calcapcost.int) +#### `HOOK_CALCAPCOST (hs_calcapcost.int)` Runs whenever Fallout is calculating the AP cost of using the weapon (or unarmed attack). Doesn't run for using other item types or moving. Note that the first time a game is loaded, this script doesn't run before the initial interface is drawn, so if the script effects the AP cost of whatever is in the player's hands at the time the wrong AP cost will be shown. It will be fixed the next time the interface is redrawn. -You can get the weapon object by checking item slot based on attack type (ATKTYPE_LWEP1, ATKTYPE_LWEP2, etc) and then calling critter_inven_obj(). +You can get the weapon object by checking item slot based on attack type (`ATKTYPE_LWEP1`, `ATKTYPE_LWEP2`, etc) and then calling `critter_inven_obj`. -critter arg0 - The critter performing the action +``` +Critter arg0 - The critter performing the action int arg1 - Attack Type (see ATKTYPE_* constants) int arg2 - Is aimed attack (1 or 0) -int arg3 - The normal AP cost +int arg3 - The default AP cost +Item arg4 - The weapon for which the cost is calculated. If it is 0, the pointer to the weapon can still be obtained by the aforementioned method int ret0 - The new AP cost +``` ------------------------------------------- -HOOK_DEATHANIM1 (hs_deathanim1.int) +#### `HOOK_DEATHANIM1 (hs_deathanim1.int)` -Runs before Fallout tries to calculate the death animation. Lets you switch out which weapon Fallout sees +Runs before Fallout tries to calculate the death animation. Lets you switch out which weapon Fallout sees. Does not run for critters in the knockdown/out state. +``` int arg0 - The pid of the weapon performing the attack. (May be -1 if the attack is unarmed) -critter arg1 - The attacker -critter arg2 - The target +Critter arg1 - The attacker +Critter arg2 - The target int arg3 - The amount of damage int arg4 - Unused, always -1. Use this if you are using the same procedure for HOOK_DEATHANIM1 and HOOK_DEATHANIM2 (since sfall 4.1/3.8.24) int ret0 - The pid of an object to override the attacking weapon with +``` ------------------------------------------- -HOOK_DEATHANIM2 (hs_deathanim2.int) +#### `HOOK_DEATHANIM2 (hs_deathanim2.int)` -Runs after Fallout has calculated the death animation. Lets you set your own custom frame id, so more powerful than hs_deathanim1, but performs no validation. -When using critter_dmg function, this script will also run. In that case weapon pid will be -1 and attacker will point to an object with obj_art_fid == 0x20001F5. +Runs after Fallout has calculated the death animation. Lets you set your own custom frame id, so more powerful than `HOOK_DEATHANIM1`, but performs no validation. +When using `critter_dmg` function, this script will also run. In that case weapon pid will be -1 and attacker will point to an object with `obj_art_fid == 0x20001F5`. Does not run for critters in the knockdown/out state. -item arg0 - The pid of the weapon performing the attack. (May be -1 if the attack is unarmed) -critter arg1 - The attacker -critter arg2 - The target +``` +Item arg0 - The pid of the weapon performing the attack. (May be -1 if the attack is unarmed) +Critter arg1 - The attacker +Critter arg2 - The target int arg3 - The amount of damage int arg4 - The death anim id calculated by Fallout int ret0 - The death anim id to override with +``` ------------------------------------------- -HOOK_COMBATDAMAGE (hs_combatdamage.int) +#### `HOOK_COMBATDAMAGE (hs_combatdamage.int)` Runs when: 1) Game calculates how much damage each target will get. This includes primary target as well as all extras (explosions and bursts). This happens BEFORE the actual attack animation. 2) AI decides whether it is safe to use area attack (burst, grenades), if he might hit friendlies. + Does not run for misses, or non-combat damage like dynamite explosions. -critter arg0 - The target -critter arg1 - The attacker +``` +Critter arg0 - The target +Critter arg1 - The attacker int arg2 - The amount of damage to the target int arg3 - The amount of damage to the attacker int arg4 - The special effect flags for the target (use bwand DAM_* to check specific flags) @@ -181,241 +204,284 @@ int ret1 - The damage to the attacker int ret2 - The special effect flags for the target int ret3 - The special effect flags for the attacker int ret4 - The amount of knockback to the target +``` ------------------------------------------- -HOOK_ONDEATH (hs_ondeath.int) +#### `HOOK_ONDEATH (hs_ondeath.int)` Runs immediately after a critter dies for any reason. No return values; this is just a convenience for when you need to do something after death for a large number of different critters and don't want to have to script each and every one of them. +``` Critter arg0 - The critter that just died +``` ------------------------------------------- -HOOK_FINDTARGET (hs_findtarget.int) +#### `HOOK_FINDTARGET (hs_findtarget.int)` Runs when the AI is trying to pick a target in combat. Fallout first chooses a list of 4 likely suspects, then normally sorts them in order of weakness/distance/etc depending on the AI caps of the attacker. This hook replaces that sorting function, allowing you to sort the targets in some arbitrary way. The return values can include critters that weren't in the list of possible targets, but the additional targets may still be discarded later on in the combat turn if they are out of the attackers perception or the chance of a successful hit is too low. The list of possible targets often includes duplicated entries, but this is fixed in sfall 4.2.3/3.8.23. -Use sfall_return to give the 4 targets, in order of preference. If you want to specify less than 4 targets, fill in the extra spaces with 0's or pass -1 to skip the return value. +Use `set_sfall_return` to give the 4 targets, in order of preference. If you want to specify less than 4 targets, fill in the extra spaces with 0's or pass -1 to skip the return value. -NOTE: The engine can choose targets by the following criteria: +__NOTE:__ The engine can choose targets by the following criteria: 1) The nearest enemy to the attacker. 2) The enemy that attacked the attacker. 3) The enemy that attacked an NPC from the same team as the attacker. 4) The enemy that is attacked by an NPC from the same team as the attacker. -critter arg0 - The attacker -critter arg1 - A possible target -critter arg2 - A possible target -critter arg3 - A possible target -critter arg4 - A possible target +``` +Critter arg0 - The attacker +Critter arg1 - A possible target +Critter arg2 - A possible target +Critter arg3 - A possible target +Critter arg4 - A possible target -critter ret0 - The first choice of target -critter ret1 - The second choice of target -critter ret2 - The third choice of target -critter ret3 - The fourth choice of target +Critter ret0 - The first choice of target +Critter ret1 - The second choice of target +Critter ret2 - The third choice of target +Critter ret3 - The fourth choice of target +``` ------------------------------------------- -HOOK_USEOBJON (hs_useobjon.int) +#### `HOOK_USEOBJON (hs_useobjon.int)` Runs when: 1) a critter uses an object on another critter. (Or themselves) 2) a critter uses an object from inventory screen AND this object does not have "Use" action flag set and it's not active flare or explosive. 3) player or AI uses any drug -This is fired before the object is used, and the relevant use_obj_on script procedures are run. You can disable default item behavior. -NOTE: you can't remove and/or destroy this object during the hookscript (game will crash otherwise). To remove it, return 1. +This is fired before the object is used, and the relevant `use_obj_on` script procedures are run. You can disable default item behavior. +__NOTE:__ You can't remove and/or destroy this object during the hookscript (game will crash otherwise). To remove it, return 1. + +``` Critter arg0 - The target Critter arg1 - The user int arg2 - The object used int ret0 - overrides hard-coded handler and selects what should happen with the item (0 - place it back, 1 - remove it, -1 - use engine handler) +``` ------------------------------------------- -HOOK_USEOBJ (hs_useobj.int) +#### `HOOK_USEOBJ (hs_useobj.int)` Runs when: 1) a critter uses an object from inventory which have "Use" action flag set or it's an active flare or dynamite. 2) player uses an object from main interface -This is fired before the object is used, and the relevant use_obj script procedures are run. You can disable default item behavior. -NOTE: you can't remove and/or destroy this object during the hookscript (game will crash otherwise). To remove it, return 1. +This is fired before the object is used, and the relevant `use_obj` script procedures are run. You can disable default item behavior. +__NOTE:__ You can't remove and/or destroy this object during the hookscript (game will crash otherwise). To remove it, return 1. + +``` Critter arg0 - The user -int arg1 - The object used +Obj arg1 - The object used int ret0 - overrides hard-coded handler and selects what should happen with the item (0 - place it back, 1 - remove it, -1 - use engine handler) +``` ------------------------------------------- -HOOK_REMOVEINVENOBJ (hs_removeinvenobj.int) +#### `HOOK_REMOVEINVENOBJ (hs_removeinvenobj.int)` Runs when an object is removed from a container or critter's inventory for any reason +``` Obj arg0 - the owner that the object is being removed from -item arg1 - the item that is being removed +Item arg1 - the item that is being removed int arg2 - the number of items to remove int arg3 - The reason the object is being removed (see RMOBJ_* constants) Obj arg4 - The destination object when the item is moved to another object, 0 otherwise +``` ------------------------------------------- -HOOK_BARTERPRICE (hs_barterprice.int) +#### `HOOK_BARTERPRICE (hs_barterprice.int)` -Runs whenever the value of goods being purchased is calculated -NOTE: the hook is executed twice when entering the barter screen or after transaction: the first time is for the player and the second time is for NPC +Runs whenever the value of goods being purchased is calculated. -critter arg0 - the critter doing the bartering (either dude_obj or inven_dude) -critter arg1 - the critter being bartered with +__NOTE:__ The hook is executed twice when entering the barter screen or after transaction: the first time is for the player and the second time is for NPC. + +``` +Critter arg0 - the critter doing the bartering (either dude_obj or inven_dude) +Critter arg1 - the critter being bartered with int arg2 - the default value of the goods -critter arg3 - table of requested goods (being bought from NPC) +Critter arg3 - table of requested goods (being bought from NPC) int arg4 - the amount of actual caps in the barter stack (as opposed to goods) int arg5 - the value of all goods being traded before skill modifications -critter arg6 - table of offered goods (being sold to NPC) +Critter arg6 - table of offered goods (being sold to NPC) int arg7 - the total cost of the goods offered by the player int arg8 - 1 if the "offers" button was pressed (not for a party member), 0 otherwise int arg9 - 1 if trading with a party member, 0 otherwise int ret0 - the modified value of all of the goods (pass -1 if you just want to modify offered goods) int ret1 - the modified value of all offered goods +``` ------------------------------------------- -HOOK_MOVECOST (hs_movecost.int) +#### `HOOK_MOVECOST (hs_movecost.int)` -Runs when calculating the AP cost of movement +Runs when calculating the AP cost of movement. +``` Critter arg0 - the critter doing the moving int arg1 - the number of hexes being moved int arg2 - the original AP cost int ret0 - the new AP cost +``` ------------------------------------------- -(DEPRECATED) -HOOK_HEXMOVEBLOCKING (hs_hexmoveblocking.int) -HOOK_HEXAIBLOCKING (hs_hexaiblocking.int) -HOOK_HEXSHOOTBLOCKING (hs_hexshootblocking.int) -HOOK_HEXSIGHTBLOCKING (hs_hexsightblocking.int) +#### DEPRECATED HOOKS: +* `HOOK_HEXMOVEBLOCKING (hs_hexmoveblocking.int)` +* `HOOK_HEXAIBLOCKING (hs_hexaiblocking.int)` +* `HOOK_HEXSHOOTBLOCKING (hs_hexshootblocking.int)` +* `HOOK_HEXSIGHTBLOCKING (hs_hexsightblocking.int)` -Runs when checking to see if a hex blocks movement or shooting. (or ai-ing, presumably...) +Run when checking to see if a hex blocks movement or shooting. (or ai-ing, presumably...) -NOTE: these hook scripts can become very CPU-intensive and you should avoid using them. -For this reason, they may be removed in future versions. -If you want to check if some tile or path is blocked, use functions: obj_blocking_tile, obj_blocking_line, path_find_to. -If you want script to be called every time NPC moves by hex in combat, use hs_movecost hook. +__NOTE:__ These hook scripts can become very CPU-intensive and you should avoid using them. +For this reason, these hooks are not thoroughly supported in sfall, and may be removed in future versions.
+If you want to check if some tile or path is blocked, use functions: `obj_blocking_tile`, `obj_blocking_line`, `path_find_to`.
+If you want script to be called every time NPC moves by hex in combat, use `HOOK_MOVECOST` hook. +``` Critter arg0 - the critter doing the moving int arg1 - the tile number being checked int arg2 - the elevation being checked int arg3 - 1 if the hex would normally be blocking -object* ret0 - 0 if the hex doesn't block, or any sort of object pointer if it does +Obj ret0 - 0 if the hex doesn't block, or any sort of object pointer if it does +``` ------------------------------------------- -HOOK_ITEMDAMAGE (hs_itemdamage.int) +#### `HOOK_ITEMDAMAGE (hs_itemdamage.int)` Runs when retrieving the damage rating of the player's used weapon. (Which may be their fists.) +``` int arg0 - The default min damage int arg1 - The default max damage -Item arg2 - The weapon used. (0 if unarmed) +Item arg2 - The weapon used (0 if unarmed) Critter arg3 - The critter doing the attacking int arg4 - The type of attack int arg5 - non-zero if this is an attack using a melee weapon -int ret0 - Either the damage to be used, if ret2 isn't given, or the new minimum damage if it is +int ret0 - Either the damage to be used, if ret1 isn't given, or the new minimum damage if it is int ret1 - The new maximum damage +``` ------------------------------------------- -HOOK_AMMOCOST (hs_ammocost.int) +#### `HOOK_AMMOCOST (hs_ammocost.int)` Runs when calculating ammo cost for a weapon. Doesn't affect damage, only how much ammo is spent. By default, weapon will shoot when at least 1 round is left, regardless of ammo cost calculations. -To add proper check for ammo before shooting and proper calculation of number of burst rounds (hook type 1 and 2 in arg4), set Misc.CheckWeaponAmmoCost=1 in ddraw.ini +To add proper check for ammo before shooting and proper calculation of number of burst rounds (hook type 1 and 2 in `arg3`), set **CheckWeaponAmmoCost=1** in **Misc** section of ddraw.ini. -Item arg0 - weapon -int arg1 - Number of bullets in burst (1 for single shots) -int arg2 - Ammo cost calculated by original function (this is basically 2 for Super Cattle Prod and Mega Power Fist) -int arg3 - Type of hook (0 - when subtracting ammo after single shot attack, 1 - when checking for "out of ammo" before attack, 2 - when calculating number of burst rounds, 3 - when subtracting ammo after burst attack) +``` +Item arg0 - The weapon +int arg1 - Number of bullets in burst or 1 for single shots +int arg2 - The amount of ammo that will be consumed, calculated by the original ammo cost function (this is basically 2 for Super Cattle Prod and Mega Power Fist) + NOTE: for hook type 2, this value is the ammo cost per round (default is always 1) +int arg3 - Type of hook: + 0 - when subtracting ammo after single shot attack + 1 - when checking for "out of ammo" before attack + 2 - when calculating number of burst rounds + 3 - when subtracting ammo after burst attack -int ret0 - new ammo cost value (set to 0 for unlimited ammo) +int ret0 - The new amount of ammo to be consumed, or ammo cost per round for hook type 2 (set to 0 for unlimited ammo) +``` ------------------------------------------- -HOOK_KEYPRESS (hs_keypress.int) +#### `HOOK_KEYPRESS (hs_keypress.int)` Runs once every time when any key was pressed or released. -DX codes: (see dik.h header) -VK codes: http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731%28v=vs.85%29.aspx -NOTE: if you want to override a key, the new key DX scancode should be the same for both pressed and released events. +- DX codes: see **dik.h** header or https://kippykip.com/b3ddocs/commands/scancodes.htm +- VK codes: http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731%28v=vs.85%29.aspx +__NOTE:__ If you want to override a key, the new key DX scancode should be the same for both pressed and released events. + +``` int arg0 - event type: 1 - pressed, 0 - released int arg1 - key DX scancode int arg2 - key VK code (very similar to ASCII codes) int ret0 - overrides the pressed key (a new key DX scancode or 0 for no override) +``` ------------------------------------------- -HOOK_MOUSECLICK (hs_mouseclick.int) +#### `HOOK_MOUSECLICK (hs_mouseclick.int)` Runs once every time when a mouse button was pressed or released. +``` int arg0 - event type: 1 - pressed, 0 - released int arg1 - button number (0 - left, 1 - right, up to 7) +``` ------------------------------------------- -HOOK_USESKILL (hs_useskill.int) +#### `HOOK_USESKILL (hs_useskill.int)` Runs when using any skill on any object. -This is fired before the default handlers are called, which you can override. In this case you should write your own skill use handler entirely, or otherwise nothing will happen (this includes fade in/fade out, time lapsing and messages - all of this can be scripted; to get vanilla text messages - use message_str_game() along with sprintf()). +This is fired before the default handlers are called, which you can override. In this case you should write your own skill use handler entirely, or otherwise nothing will happen (this includes fade in/fade out, time lapsing and messages - all of this can be scripted; to get vanilla text messages - use `message_str_game` along with `sprintf`). Suggested use - override first aid/doctor skills to buff/nerf them, override steal skill to disallow observing NPCs inventories in some cases. Doesn't seem to run when lock picking. +``` Critter arg0 - The user critter Obj arg1 - The target object int arg2 - skill being used int arg3 - skill bonus from items such as first aid kits int ret0 - overrides hard-coded handler (-1 - use engine handler, any other value - override) +``` ------------------------------------------- -HOOK_STEAL (hs_steal.int) +#### `HOOK_STEAL (hs_steal.int)` Runs when checking an attempt to steal or plant an item in other inventory using Steal skill. This is fired before the default handlers are called, which you can override. In this case you MUST provide message of the result to player ("You steal the %s", "You are caught planting the %s", etc.). -Example message (vanilla behavior): display_msg(sprintf(mstr_skill(570 + (isSuccess != false) + arg4*2), obj_name(arg3))); +Example message (vanilla behavior):
+`display_msg(sprintf(mstr_skill(570 + (isSuccess != false) + arg3 * 2), obj_name(arg2)));` + +``` Critter arg0 - Thief Obj arg1 - The target Item arg2 - Item being stolen/planted int arg3 - 0 when stealing, 1 when planting int ret0 - overrides hard-coded handler (1 - force success, 0 - force fail, -1 - use engine handler) +``` ------------------------------------------- -HOOK_WITHINPERCEPTION (hs_withinperception.int) +#### `HOOK_WITHINPERCEPTION (hs_withinperception.int)` Runs when checking if one critter sees another critter. This is used in different situations like combat AI. You can override the result. -NOTE: obj_can_see_obj calls this first when deciding if critter can possibly see another critter with regard to perception, lighting, sneak factors. If check fails, the end result is false. If check succeeds (e.g. critter is within perception range), another check is made if there is any blocking tile between two critters (which includes stuff like windows, large bushes, barrels, etc.) and if there is - check still fails. You can override "within perception" check by returning 0 or 1, OR, as a convenience, you can also override blocking check after the perception check by returning 2 instead. In this case you should add "line of sight" check inside your hook script, otherwise critters will detect you through walls. +__NOTE:__ `obj_can_see_obj` calls this first when deciding if critter can possibly see another critter with regard to perception, lighting, sneak factors.
+If check fails, the end result is false. If check succeeds (e.g. critter is within perception range), another check is made if there is any blocking tile between two critters (which includes stuff like windows, large bushes, barrels, etc.) and if there is - check still fails.
+You can override "within perception" check by returning 0 or 1, OR, as a convenience, you can also override blocking check after the perception check by returning 2 instead. In this case you should add "line of sight" check inside your hook script, otherwise critters will detect you through walls. This is fired after the default calculation is made. +``` Critter arg0 - Watcher object Obj arg1 - Target object int arg2 - Result of vanilla function: 1 - within perception range, 0 - otherwise @@ -425,173 +491,218 @@ int arg3 - Type of hook: 3 - when AI determines whether it sees a potential target when selecting attack targets 0 - all other cases -int ret0 - overrides the returned result of the function: 0 - not in range (can't see), 1 - in range (will see if not blocked), 2 - forced detection (will see regardless, only used in obj_can_see_obj scripting function which is called by every critter in the game) +int ret0 - overrides the returned result of the function: + 0 - not in range (can't see) + 1 - in range (will see if not blocked) + 2 - forced detection (will see regardless, only used in obj_can_see_obj scripting function which is called by every critter in the game) +``` ------------------------------------------- -HOOK_INVENTORYMOVE (hs_inventorymove.int) +#### `HOOK_INVENTORYMOVE (hs_inventorymove.int)` Runs before moving items between inventory slots in dude interface. You can override the action. What you can NOT do with this hook: - force moving items to inappropriate slots (like gun in armor slot) + What you can do: - restrict player from using specific weapons or armors - add AP costs for all inventory movement including reloading - apply or remove some special scripted effects depending on PC's armor -int arg0 - Target slot (0 - main backpack, 1 - left hand, 2 - right hand, 3 - armor slot, 4 - weapon, when reloading it by dropping ammo, 5 - container, like bag/backpack, 6 - dropping on the ground, - 7 - picking up item, 8 - dropping item on the character portrait) +``` +int arg0 - Target slot: + 0 - main backpack + 1 - left hand + 2 - right hand + 3 - armor slot + 4 - weapon, when reloading it by dropping ammo + 5 - container, like bag/backpack + 6 - dropping on the ground + 7 - picking up item + 8 - dropping item on the character portrait Item arg1 - Item being moved Item arg2 - Item being replaced, weapon being reloaded, or container being filled (can be 0) int ret0 - Override setting (-1 - use engine handler, any other value - prevent relocation of item/reloading weapon/picking up item) +``` ------------------------------------------- -HOOK_INVENWIELD (hs_invenwield.int) +#### `HOOK_INVENWIELD (hs_invenwield.int)` Runs before causing a critter or the player to wield/unwield an armor or a weapon (except when using the inventory by PC). An example usage would be to change critter art depending on armor being used or to dynamically customize weapon animations. -NOTE: when replacing a previously wielded armor or weapon, the unwielding hook will not be executed. + +__NOTE:__ When replacing a previously wielded armor or weapon, the unwielding hook will not be executed. If you need to rely on this, try checking if armor/weapon is already equipped when wielding hook is executed. +``` Critter arg0 - critter -Obj arg1 - item being wielded or unwielded (weapon/armor) +Item arg1 - item being wielded or unwielded (weapon/armor) int arg2 - slot (INVEN_TYPE_*) int arg3 - 1 when wielding, 0 when unwielding int arg4 - 1 when removing an equipped item from inventory, 0 otherwise int ret0 - overrides hard-coded handler (-1 - use engine handler, any other value - override) - NOT RECOMMENDED +``` ------------------------------------------- -HOOK_ADJUSTFID (hs_adjustfid.int) +#### `HOOK_ADJUSTFID (hs_adjustfid.int)` Runs after calculating character figure FID on the inventory screen, whenever the game decides that character appearance might change. Also happens on other screens, like barter. -NOTE: FID has following format: 0x0ABBCDDD, where A is object type, BB - animation code (always 0 in this case), C - weapon code, DDD - FRM index in LST file. +__NOTE:__ FID has following format: `0x0ABBCDDD`, where: `A` - object type, `BB` - animation code (always 0 in this case), `C` - weapon code, `DDD` - FRM index in LST file. +``` int arg0 - the vanilla FID calculated by the engine according to critter base FID and armor/weapon being used int arg1 - the modified FID calculated by the internal sfall code (like Hero Appearance Mod) int ret0 - overrides the calculated FID with provided value +``` ------------------------------------------- -HOOK_COMBATTURN (hs_combatturn.int) +#### `HOOK_COMBATTURN (hs_combatturn.int)` Runs before and after each turn in combat (for both PC and NPC). -int arg0 - event type: 1 - start of turn, 0 - normal end of turn, -1 - combat ends abruptly (by script or by pressing Enter during PC turn), -2 - combat ends normally (hook always runs at the end of combat) -int arg1 - critter doing the turn +``` +int arg0 - event type: + 1 - start of turn + 0 - normal end of turn + -1 - combat ends abruptly (by script or by pressing Enter during PC turn) + -2 - combat ends normally (hook always runs at the end of combat) +Critter arg1 - critter doing the turn bool arg2 - 1 at the start/end of the player's turn after loading a game saved in combat mode, 0 otherwise int ret0 - pass 1 at the start of turn to skip the turn, pass -1 at the end of turn to force end of combat +``` ------------------------------------------- -HOOK_CARTRAVEL (hs_cartravel.int) +#### `HOOK_CARTRAVEL (hs_cartravel.int)` Runs continuously during worldmap travel on car. +``` int arg0 - vanilla car speed (between 3 and 8 "steps") int arg1 - vanilla fuel consumption (100 and below) int ret0 - car speed override (pass -1 if you just want to override fuel consumption) int ret1 - fuel consumption override +``` ------------------------------------------- -HOOK_SETGLOBALVAR (hs_setglobalvar.int) +#### `HOOK_SETGLOBALVAR (hs_setglobalvar.int)` Runs when setting the value of a global variable. +``` int arg0 - the index number of the global variable being set int arg1 - the set value of the global variable int ret0 - overrides the value of the global variable +``` ------------------------------------------- -HOOK_RESTTIMER (hs_resttimer.int) +#### `HOOK_RESTTIMER (hs_resttimer.int)` Runs continuously while the player is resting (using pipboy alarm clock). +``` int arg0 - the game time in ticks int arg1 - event type: 1 - when the resting ends normally, -1 - when pressing ESC to cancel the timer, 0 - otherwise int arg2 - the hour part of the length of resting time int arg3 - the minute part of the length of resting time int ret0 - pass 1 to interrupt the resting, pass 0 to continue the rest if it was interrupted by pressing ESC key +``` ------------------------------------------- -HOOK_GAMEMODECHANGE (hs_gamemodechange.int) +#### `HOOK_GAMEMODECHANGE (hs_gamemodechange.int)` Runs once every time when the game mode was changed, like opening/closing the inventory, character screen, pipboy, etc. +``` int arg0 - event type: 1 - when the player exits the game, 0 - otherwise int arg1 - the previous game mode +``` ------------------------------------------- -HOOK_USEANIMOBJ (hs_useanimobj.int) +#### `HOOK_USEANIMOBJ (hs_useanimobj.int)` Runs before playing the "use" (usually "magic hands") animation when a critter uses a scenery/container object on the map, or before walking/running animation if the player is at a distance from the object. +``` Critter arg0 - the critter that uses an object (usually dude_obj) Obj arg1 - the object being used int arg2 - the animation code being used (see ANIM_* in Animcomd.h) int ret0 - overrides the animation code (pass -1 if you want to skip the animation) +``` ------------------------------------------- -HOOK_EXPLOSIVETIMER (hs_explosivetimer.int) +#### `HOOK_EXPLOSIVETIMER (hs_explosivetimer.int)` Runs after setting the explosive timer. You can override the result. +``` int arg0 - the time in ticks set in the timer Obj arg1 - the explosive object int arg2 - the result of engine calculation of whether the timer was set successfully: 1 - failure, 2 - success (similar to ROLL_* in Condtion.h) int ret0 - overrides the time of the timer (maximum 18000 ticks) int ret1 - overrides the result of engine calculation: 0/1 - failure, 2/3 - success (similar to ROLL_*), any other value - use engine handler +``` ------------------------------------------- -HOOK_DESCRIPTIONOBJ (hs_descriptionobj.int) +#### `HOOK_DESCRIPTIONOBJ (hs_descriptionobj.int)` Runs when using the examine action icon to display the description of an object. You can override the description text. An example usage would be to add an additional description to the item based on player's stats/skills. + Does not run if the script of the object overrides the description. +``` Obj arg0 - the object -int ret0 - a pointer to the new text received by using "get_string_pointer" function +int ret0 - a pointer to the new text received by using get_string_pointer function +``` ------------------------------------------- -HOOK_USESKILLON (hs_useskillon.int) +#### `HOOK_USESKILLON (hs_useskillon.int)` Runs before using any skill on any object. Lets you override the critter that uses the skill. -NOTE: the user critter can't be overridden when using Steal skill. +__NOTE:__ The user critter can't be overridden when using Steal skill. + +``` Critter arg0 - the user critter (usually dude_obj) Obj arg1 - the target object/critter int arg2 - skill being used int ret0 - a new critter to override the user critter. Pass -1 to cancel the skill use, pass 0 to skip this return value int ret1 - pass 1 to allow the skill being used in combat (only for dude_obj or critter being controlled by the player) +``` ------------------------------------------- -HOOK_ONEXPLOSION (hs_onexplosion.int) +#### `HOOK_ONEXPLOSION (hs_onexplosion.int)` Runs when Fallout is checking all the tiles within the explosion radius for targets before an explosion occurs. The tile checking will be interrupted when 6 additional targets (critters) are received. +``` int arg0 - event type: 1 - when checking objects within the explosion radius without causing damage (e.g. the player drops an active explosive), 0 - otherwise Critter arg1 - the attacker int arg2 - the tile on which the explosion occurs @@ -601,20 +712,24 @@ Critter arg5 - the target critter, may be 0 or equal to the attacker int arg6 - 1 when using throwing weapons (e.g. grenades), 0 otherwise int ret0 - overrides the found object on the checked tile, pass 0 to skip the object +``` ------------------------------------------- -HOOK_SUBCOMBATDAMAGE (hs_subcombatdmg.int) +#### `HOOK_SUBCOMBATDAMAGE (hs_subcombatdmg.int)` This hook overrides the vanilla damage calculation formula. + Runs when: 1) Before the game calculates how much damage each target will get. This includes primary target as well as all extras (explosions and bursts). 2) AI decides whether it is safe to use area attack (burst, grenades), if he might hit friendlies. + Does not run for misses, non-combat damage like dynamite explosions, or if one of the damage formulas is selected in ddraw.ini. +``` Critter arg0 - the attacker Critter arg1 - the target -Obj arg2 - the weapon used in the attack +Item arg2 - the weapon used in the attack int arg3 - attack type (see ATKTYPE_* constants) int arg4 - number of bullets actually hit the target (1 for melee attacks) int arg5 - target's Damage Resistance (DR) value (affected by critical hit effects, perks, traits, and special unarmed attacks) @@ -626,81 +741,94 @@ int arg10 - the calculated amount of damage (usually 0, required when using mixed arg11 - computed attack data (see C_ATTACK_* for offsets and use get/set_object_data functions to get/set the data) int ret0 - the returned amount of damage +``` ------------------------------------------- -HOOK_SETLIGHTING (hs_setlighting.int) +#### `HOOK_SETLIGHTING (hs_setlighting.int)` Runs before setting the light level for an object or a map. You can override the result. +``` Obj arg0 - the object being set, or -1 when setting the light level for a map int arg1 - the light intensity int arg2 - the light radius, or -1 when setting the light level for a map int ret0 - overrides the light intensity. Intensity range is from 0 to 65536 int ret1 - overrides the light radius. Radius range is from 0 to 8 (works only for the object) +``` ------------------------------------------- -HOOK_SNEAK (hs_sneak.int) +#### `HOOK_SNEAK (hs_sneak.int)` Runs when the Sneak skill is activated, or when the game rolls another Sneak check after the duration for the current one is over. You can override the result of a random Sneak check or the duration time for the current result. +``` int arg0 - Sneak check result: 1 - success, 0 - failure int arg1 - the duration in ticks for the current Sneak check (time depends on Sneak skill level) Critter arg2 - the critter (usually dude_obj) int ret0 - overrides the result of the Sneak check int ret1 - overrides the duration time for the current result +``` ------------------------------------------- -HOOK_STDPROCEDURE, HOOK_STDPROCEDURE_END (hs_stdprocedure.int) +#### `HOOK_STDPROCEDURE, HOOK_STDPROCEDURE_END (hs_stdprocedure.int)` Runs before or after Fallout engine executes a standard procedure (handler) in any script of any object. -NOTE: this hook will not be executed for "start", critter_p_proc, timed_event_p_proc, and map_update_p_proc procedures. +__NOTE:__ This hook will not be executed for `start`, `critter_p_proc`, `timed_event_p_proc`, and `map_update_p_proc` procedures. + +``` int arg0 - the number of the standard script handler (see define.h) Obj arg1 - the object that owns this handler (self_obj) Obj arg2 - the object that called this handler (source_obj, can be 0) int arg3 - 1 after procedure execution (for HOOK_STDPROCEDURE_END), 0 otherwise int ret0 - pass -1 to cancel the execution of the handler (only for HOOK_STDPROCEDURE) +``` ------------------------------------------- -HOOK_TARGETOBJECT (hs_targetobject.int) +#### `HOOK_TARGETOBJECT (hs_targetobject.int)` Runs when the targeting cursor hovers over an object, or when the player tries to attack the target object. You can override the target object or prevent the player from attacking the chosen target. +``` int arg0 - event type: 0 - when the targeting cursor hovers over the object, 1 - when trying to attack the target object int arg1 - 1 when the target object is valid to attack, 0 otherwise Obj arg2 - the target object mixed ret0 - overrides the target object, or pass -1 to prevent the player from attacking the object +``` ------------------------------------------- -HOOK_ENCOUNTER (hs_encounter.int) +#### `HOOK_ENCOUNTER (hs_encounter.int)` Runs whenever a random encounter occurs (except the Horrigan meeting and scripted encounters), or when the player enters a local map from the world map. You can override the map for loading or the encounter. +``` int arg0 - event type: 0 - when a random encounter occurs, 1 - when the player enters from the world map int arg1 - the map ID that the encounter will load (see MAPS.h or Maps.txt) int arg2 - 1 when the encounter occurs is a special encounter, 0 otherwise int ret0 - overrides the map ID, or pass -1 for event type 0 to cancel the encounter and continue traveling -int ret1 - pass 1 to cancel the encounter and load the specified map from the ret1 (only for event type 0) +int ret1 - pass 1 to cancel the encounter and load the specified map from the ret0 (only for event type 0) +``` ------------------------------------------- -HOOK_ADJUSTPOISON (hs_adjustpoison.int) +#### `HOOK_ADJUSTPOISON (hs_adjustpoison.int)` Runs when a critter's poison level is changed, or when the player takes damage from the poison. +``` Critter arg0 - the critter int arg1 - the amount of poison being added/removed int arg2 - the damage value at the time of applying the poison effect @@ -708,24 +836,28 @@ int arg2 - the damage value at the time of applying the poison effect int ret0 - the new amount of poison being added/removed int ret1 - the new damage value, only negative values are allowed (will only be valid at the time of taking damage from the poison) +``` ------------------------------------------- -HOOK_ADJUSTRADS (hs_adjustrads.int) +#### `HOOK_ADJUSTRADS (hs_adjustrads.int)` Runs when a critter's radiation level is changed. +``` Critter arg0 - the critter (usually dude_obj) int arg1 - the amount of radiation being added/removed int ret0 - the new amount of radiation being added/removed +``` ------------------------------------------- -HOOK_ROLLCHECK (hs_rollcheck.int) +#### `HOOK_ROLLCHECK (hs_rollcheck.int)` Runs when a game event performs a random roll to check the chance of success or failure. +``` int arg0 - event type: 1 - checks the chance of an attack hitting the target 2 - checks the chance of a bullet from a burst hitting the target (for burst attacks) @@ -739,6 +871,40 @@ int arg1 - the value of roll result (see ROLL_* constants), which is calcula for ROLL_CRITICAL_FAILURE: random(1, 100) <= -random_chance / 10 int arg2 - the chance value int arg3 - the bonus value, used when checking critical success -int arg4 - random chance (calculated as: chance - random(1, 100)), where a negative value is a failure check (ROLL_FAILURE) +int arg4 - random chance, calculated as: (chance - random(1, 100)), where a negative value is a failure check (ROLL_FAILURE) int ret0 - overrides the roll result +``` + +------------------------------------------- + +#### `HOOK_BESTWEAPON (hs_bestweapon.int)` + +Runs when the AI decides which weapon is the best while searching the inventory for a weapon to equip in combat. +This also runs when the player presses the "Use Best Weapon" button on the party member control panel. + +``` +Critter arg0 - the critter searching for a weapon +Item arg1 - the best weapon chosen from two items +Item arg2 - the first choice of weapon +Item arg3 - the second choice of weapon +Critter arg4 - the target of the critter (can be 0) + +Item ret0 - overrides the chosen best weapon +``` + +------------------------------------------- + +#### `HOOK_CANUSEWEAPON (hs_canuseweapon.int)` + +Run when the AI checks whether it can use a weapon. +This mostly happens when NPCs try to find weapons in their inventory or on the map. + +``` +Critter arg0 - the critter doing the check +Item arg1 - the weapon being checked +int arg2 - attack type (see ATKTYPE_* constants) +int arg3 - original result of engine function: 1 - can use, 0 - can't use + +int ret0 - overrides the result of engine function. Any non-zero value allows using the weapon +``` diff --git a/artifacts/scripting/sfall function notes.md b/artifacts/scripting/sfall function notes.md new file mode 100644 index 00000000..de314955 --- /dev/null +++ b/artifacts/scripting/sfall function notes.md @@ -0,0 +1,1045 @@ +GLOBAL SCRIPTS +-------------- + +As well as the new functions, sfall also adds global scripts. These run independent of any loaded maps, but do not have an attached object. (i.e. using `self_obj` without using `set_self` first will crash the script.) To use a global script, the script must have a name which begins with `gl` and contains a procedure called `start`, `map_enter_p_proc`, `map_exit_p_proc`, or `map_update_p_proc`. The `start` procedure will be executed once when the player loads a saved game or starts a new game. The `map_*_p_proc` procedures will be executed once when a map is being entered/left/updated. If you wish the script to be executed repeatedly, call `set_global_script_repeat` on the first run of the `start` procedure using the number of frames between each run as the argument. (0 disables the script, 1 runs it every frame, 2 runs it every other frame, etc.) + +Global scripts have multiple modes, which can be set using the `set_global_script_type` function. In the default mode (i.e. mode 0) their execution is linked to the local map game loop, so the script will not run in dialogs or on the world map. In mode 1 their execution is linked to the player input, and so they will run whenever the mouse cursor is visible on screen, including the world map, character dialogs, etc. In mode 2, execution is linked to the world map loop, so the script will only be executed on the world map and not on the local map or in any dialog windows. Mode 3 is a combination of modes 0 and 2, so scripts will be executed on both local maps and the world map, but not in dialog windows. +_Using mode 1 requires the input wrapper to be enabled. Use available_global_script_types to check what is available._ - Obsolete. + + +---------------------- +NOTES ON NEW FUNCTIONS +---------------------- + +Both `set_global_script_repeat` and `set_global_script_type` only have an effect on the script they were called from. Every global script needs its own `game_loaded` block to correctly set up the script type and repeat rate. `set_global_script_repeat` will have no effect if called on a non-global script. + +The `read_xxx` functions take a memory address as the parameter and can read arbitrary pieces of Fallout's address space. The `write_xxx` functions are equivalent except that they write to arbitrary memory addresses. + +The `call_offset_xx` functions can be used to call arbitrary functions inside Fallout. Different versions are used to call functions with different numbers of arguments. +None of `write_xxx` and `call_offset_xx` functions will work unless **AllowUnsafeScripting** is enabled in ddraw.ini. + +The `get_pc_base_stat`, `set_pc_base_stat`, `get_pc_extra_stat` and `set_pc_extra_stat` functions are equivalent to calling `get_critter_base_stat`, `set_critter_base_stat`, `get_critter_extra_stat` and `set_critter_extra_stat` with `dude_obj` as the critter pointer. None of these stat functions take perks into account, and neither do they do range clamping to make sure the stats are valid. Use the normal `get_critter_stat` function to get a correctly perk adjusted and range clamped value for a stat. + +The `set_stat_min` and `set_stat_max` functions can be used to set the valid ranges on stats. Values returned by `get_current_stat` will be clamped to this range. The `set_pc_stat_*` functions only affect the player, the `set_npc_stat_*` functions only affect other critters, and the `set_stat_*` functions affect both. + +The input functions are only available if the user has the input hook turned on in ddraw.ini. Use `input_funcs_available` to check. + +The graphics functions are only available if the user is using graphics mode 4 or 5. Use `graphics_funcs_available` to check; it returns 1 if you can use them or 0 if you can't. Calling graphics functions when `graphics_funcs_available` returns 0 will do nothing. + +The `load_shader` takes a path relative to the `\\shaders\` directory as an argument and returns a shader ID. That ID should be passed as the first argument to all other shader functions, and is valid until `free_shader` is called on the ID, the player loads a saved game or the player quits to the main menu. + +The `get_shader_version` gives you the highest shader version supported by the player's graphics cards. Possible return values are 11, 12, 13, 14, 20, 21 and 30. + +The `set_shader_mode` tells sfall when to use a shader. The parameter is a set of 32 flags which specify the screens on which the shader will be disabled, unless bit 32 is set, in which case the shader will only be active on those screens. Remember that screens are displayed on top of each other; if the player opens the character menu which in combat, the game still considers the player to be in combat. See **sfall.h** for a list of defines. + +The `force_graphics_refresh` forces the screen to redraw at times when it normally wouldn't. If you're using animated shader, turning this option on is recommended. + +The mapper manual lists the functions `world_map_x_pos` and `world_map_y_pos`, which supposedly return the player's x and y positions on the world map. The `get_world_map_x_pos` and `get_world_map_y_pos` are included here anyway, because I was unable to get those original functions to work, or even to find any evidence that they existed in game. + +The `set_pipboy_available` will only accept 0 or 1 as an argument. Using any other value will cause the function to have no effect. Use 0 to disable the pipboy, and 1 to enable it. + +The `get_critter_current_ap` and `set_critter_current_ap` functions should only be used during the target critters turn while in combat. Calling them outside of combat typically returns the critters max AP, but don't rely on that behaviour. (Specifically, if the critter has never before entered combat, it will probably return the critters base AP ignoring any extra bonuses from perks etc.) + +The **type** value in the weapon knockback functions can be 0 or 1. If 0, the value becomes an absolute distance that targets will be knocked back. If 1, the value is multiplied by the distance they would normally have been knocked back. Weapon knockback modifiers are applied in the order `weapon -> attacker -> target`, so a x2 weapon wielded by an abs 6 attacker hitting a /2 target will knock the target back 3 squares. The knockback functions will not override the stonewall perk or knockdowns resulting from criticals. knockback values set on weapons or critters are not saved, and must be reset each time the player reloads. + +The `get_sfall_global` and `set_sfall_global` functions require an 8 characters long case sensitive string for the variable name. The variables behave the same as normal Fallout globals, except that they don't have to be declared beforehand in **vault13.gam**. Trying to get a variable which hasn't been set will always return 0. These functions are intended for use when a patch to a mod requires the addition of a new global variable, a case which would otherwise require the player to start a new game. + +The `set_pickpocket_max` and `set_hit_chance_max` affect all critters rather than just the player and can set the maximum in range from 0 to 999. + +The `set_skill_max` can't be used to increase the skill cap above 300. The `set_perk_level_mod` sets a modifier between +25 and -25 that is added/subtracted from the player's level for the purposes of deciding which perks can be chosen. + +The `set_fake_trait` and `set_fake_perk` can be used to add additional traits and perks to the character screen. They will be saved correctly when the player saves and reloads games, but by themselves they will have no further effect on the character. For perks, the allowed range for levels is between 0 and 100; setting the level to 0 removes that perk. For traits, the level must be 0 or 1. The image is a numeric id that corresponds to an entry in **skilldex.lst**. The name is limited to 63 characters and the description to 255 characters by sfall, but internal Fallout limits may be lower. + +The `has_fake_trait` and `has_fake_perk` return the number of levels the player has of the perks/traits with the given name or ID of extra perk. + +The `perk_add_mode`, `set_selectable_perk`, `set_perkbox_title`, `hide_real_perks`, `show_real_perks` and `clear_selectable_perks` control the behaviour of the select a perk box. The `set_selectable_perk` can be used to add additional items by setting the **active** parameter to 1, and to remove them again by setting it to 0. The `set_perkbox_title` can be used to change the title of the box, or by using `""` it will be set back to the default. The `hide_real_perks` and `show_real_perks` can be used to prevent the dialog from displaying any of the original 119 perks. The `perk_add_mode` modifies what happens when a fake perk is selected from the perks dialog. It is treated as a set of flags - if bit 1 is set then it is added to the player's traits, if bit 2 is set it is added to the player's perks, and if bit 3 is set it is removed from the list of selectable perks. The default is 0x2. The `clear_selectable_perks` restores the dialog to its default state. + +The `show_iface_tag`, `hide_iface_tag` and `is_iface_tag_active` relate to the boxes that appear above the interface such as **SNEAK** and **LEVEL**. You can use 3 for **LEVEL** and 4 for **ADDICT**, or the range from 5 to (4 + the value of BoxBarCount in ddraw.ini) for custom boxes. Remember to add your messages to **intrface.msg** and set up the font colours in ddraw.ini if you're going to use custom boxes. Starting from sfall 4.1/3.8.12, `is_iface_tag_active` can also be used to check 0 for **SNEAK**, 1 for **POISONED**, and 2 for **RADIATED**. + +The `get_bodypart_hit_modifier` and `set_bodypart_hit_modifier` alter the hit percentage modifiers for aiming at specific bodyparts. Valid bodypart id's are from 0 to 8. Changes are not saved, and will reset to the defaults (or to the values specified in ddraw.ini if they exist) at each reload. + +The `get_critical_table`, `set_critical_table` and `reset_critical_table` are used for modifying the critical table (for details, see http://falloutmods.wikia.com/wiki/Critical_hit_tables). Changes are not saved, and will reset to the defaults (or to the contents of **CriticalOverrides.ini**, if it exists) at each game reload. These function also require **OverrideCriticalTable** to be enabled in ddraw.ini. + +The `get_unspent_ap_bonus` and `set_unspent_ap_bonus` alter the AC bonus you receive per unused action point at the end of your turn in combat. To allow for fractional values, the value given if divided by 4. (Hence the default value is 4 and not 1.) The `get_unspent_ap_perk_bonus` and `set_unspent_ap_perk_bonus` are similar, but affect the extra AC granted by the HtH Evade perk. (The default value of this is also 4, equivalent to doubling the original bonus.) + +The `nb_*` functions are reserved for the brotherhood tactical training mod, and should be avoided. + +The `fs_*` functions are used to manipulate a virtual file system. Files saved here should have paths relative to the data folder, and use backslashes as the directory separator. They will take precedence over files stored in the normal data folder. They will also be saved into save games if you set a flag for them using `fs_resize(fileId, -1)`, so be avoid creating large files. Using `fs_copy` followed by `fs_read_xxx`, you can read the contents of existing files. + +The `get_proto_data` and `set_proto_data` are used to manipulate the in memory copies of the **.pro** files Fallout makes when they are loaded. The offset refers to the offset in memory from the start of the proto to the element you are reading. Changes are not stored on disc, and are not permanent. If you modify the protos, and then Fallout subsequently reloads the file your changes will be lost. + +The `list_xxx` functions can be used to loop over all items on a map. `list_begin` takes an argument telling sfall what you want to list (defined in **sfall.h**). It returns a list pointer, which you iterate through with `list_next`. Finally, when you've finished with the list use `list_end` on it. Not calling `list_end` will result in a memory leak. Alternatively, use `list_as_array` to get the whole list at once as a temp array variable, which can be looped over using `len_array` and which you don't need to remember to free afterwards. + +The `play_sfall_sound` and `stop_sfall_sound` are used to play **mp3/wav/wma** files. The path given is relative to the Fallout folder. Specify mode as 1 to loop the file continuously, 2 to replace the current background game music with playing the specified file in loop mode, or 0 to play the file once. If you don't wish to loop, `play_sfall_sound` returns 0. If you do loop, it returns an id which can be passed back to `stop_sfall_sound` when you want to stop the effect. All sounds effects will be stopped on game reload, looping or not. These functions do not require **AllowDShowSound** to be set to 1 in ddraw.ini. +Starting from sfall 4.2.8/3.8.28, you can pass a value in the **mode** argument for a reduced sound volume. To set the volume, You need to convert the number to hexadecimal and use the argument format `0xZZZZ000Y`, where `ZZZZ` is the volume reduction value in range from 0 to 32767 (the value 32767 is muted), and `Y` is the playback mode. + +Arrays are created and manipulated with the `xxx_array` functions. An array must first be created with `create_array` or `temp_array`, specifying how many data elements the array can hold. You can store any of ints, floats and strings in an array, and can mix all 3 in a single array. The ID returned by `create_array` or `temp_array` can then be used with the other array functions. Arrays are shared between all scripts. (i.e. you can call `create_array` from one script, and then use the returned ID from another script.) They are also saved across savegames. Arrays created with `temp_array` will be automatically freed at the end of the frame. These functions are safe, in that supplying a bad id or trying to access out of range elements will not crash the script. `create_array` is the only function that returns a permanent array, all other functions which return arrays (`string_split`, `list_as_array`, etc,) all return temp arrays. You can use `fix_array` to make a temp array permanent.
+__NOTE:__ the above description only applies when **arraysBehavior** is set to 0 in ddraw.ini. Refer to **arrays.md** for detailed description of new arrays behavior. + +The `force_aimed_shots` and `disable_aimed_shots` allow overriding the normal rules regarding which weapons are allowed to make aimed attacks. (e.g. weapons that cause explosive damage normally cannot normally make aimed shots.) `force_aimed_shots` will allow a weapon to make aimed shots even if it normally couldn't, and `disable_aimed_shots` stops a weapon from making aimed shots even if it normally could. Both of these functions affect player and NPCs alike. `force_aimed_shots` does not override the effects of the fast shot trait. The list of edited weapons is not saved over game loads, so you need to call the functions once at each reload. Use a pid of 0 to represent unarmed. + +The `get_critter_skill_points` and `set_critter_skill_points` will get or set the number of additional points a critter has in a skill, on top of whatever they have from their stats and other bonuses. Note that skill points are part of the proto, so calling `set_skill_points` on a critter will affect all critters that share the same proto. + + +--------------- +TYPES REFERENCE +--------------- + +Data types mentioned in this document: + +* `void` - means opcode does not return any value +* `any` - any type +* `int` - integer number +* `float` - floating point number +* `string` - string (text) value +* `object` - pointer to game object (actually an integer) +* `array` - array ID to be used with array-related functions (actually an integer) +* `bool` - boolean values: `True` or `False` (actually an integer 1 or 0) + + +------------------ +FUNCTION REFERENCE +------------------ + +##### `int game_loaded()` +- Returns 1 the first time it is called after a new game or game load, and 0 any time after. It works on an individual basis for each script, so one script wont interfere with others. Its primary use is for global scripts, so that they know when to call `set_global_script_repeat`, but it can be called from normal scripts too. + +----- +##### `void inc_npc_level(int pid/string name)` +- Takes a party member PID or an NPC name (deprecated, for compatibility with sfall 4.1.5/3.8.15 or earlier) as an argument. The NPC must be in your party. +- This function ignores player level requirements and the minimum 3 player level delay between NPC level gains. It also ignores the random element, regardless of sfall's **NPCAutoLevel** setting. + +----- +##### `int get_npc_level(int pid/string name)` +- Also takes the party member PID or NPC name (deprecated, for compatibility with sfall 4.1.5/3.8.15 or earlier) as an argument, and returns the NPC's current level. Again, the NPC needs to be in your party. + +----- +##### `void set_car_current_town(int town)` +- Changes the current town index for the player's car. + +----- +##### `int get_ini_setting(string setting)` +- Reads an integer value from an ini file in the Fallout directory. +- It only takes a single argument; seperate the file name, section and key with a `|` character, e.g. `myvar := get_ini_setting("myini.ini|mysec|var1")`. If the file or key cannot be found, -1 is returned. +- The file name is limited to 63 chars, including the extension. +- The section name is limited to 32 characters. +- It can also be used to get sfall settings, by using ddraw.ini as the file name. + +----- +##### `string get_ini_string(string setting)` +- Reads a string value from an ini file in the Fallout directory. + +----- +##### `int get_game_mode()` +- Is a more flexible version of `in_world_map`. It will return a set of flags indicating which mode the game is currently in. +- These flags are the same as those used in the `set_shader_mode` function. + +----- +##### `int get_uptime()` +- Is just a wrapper around the windows `GetTickCount()` function. It's useful for making time fade effects in shaders, since they already have access to the current tick count. + +----- +##### `bool in_world_map()` +- Returns 1 if the player is looking at the world map, or 0 at any other time. +- Obviously this is only useful in global scripts, since normal scripts will never get the chance to run on the world map. + +----- +##### `void force_encounter(int map)` +- Can be called either from a global script while traveling on the world map, or from a normal script while on a local map. +- In either case the encounter occurs shortly after the next time the player moves on the world map. +- The player will not get an outdoorsman skill check. + +----- +##### `void force_encounter_with_flags(int map, int flags)` +- Does the same thing as `force_encounter`, but allows the specification of some extra options (see **sfall.h** for available flags). +- Forcing a random encounter on a map that is not normally used for random encounters may cause the player to lose the car, if they have it. +- In this case use `force_encounter_with_flags` with the `ENCOUNTER_FLAG_NO_CAR` flag set. + +----- +##### `int get_light_level()` +- Ambient light level in range 0..65536 +- The value returned by `get_light_level` may not exactly match that set by `set_light_level`, as `set_light_level` applies modifiers from the night vision perk. + +----- +##### `void set_map_time_multi(float multi)` +- Adjusts how fast time passes while you're on the world map. It takes a single float as an argument, where 1 is the normal speed. +- This function works in addition to the **WorldMapTimeMod** setting in ddraw.ini and the Pathfinder perk, rather than overriding it, so calling `set_map_time_multi(0.5)` when the player has 2 levels of pathfinder would result in time passing at 25% the normal speed on the world map. + +----- +##### `void remove_script(object)` +- Accepts a pointer to an object and will remove the script from that object. + +----- +##### `void set_script(object, int scriptid)` +- Accepts a pointer to an object and **scriptID**, and applies the given script to an object (scriptID accepts the same values as `create_object_sid`) +- If used on an object that is already scripted, it will remove the existing script first; you cannot have multiple scripts attached to a single object. Calling `set_script` on `self_obj` will have all sorts of wacky side effects, and should be avoided. +- If you add `0x80000000` to the SID when calling `set_script`, `map_enter_p_proc` will be SKIPPED. The `start` proc will always be run. + +----- +##### `int get_script(object)` +- Accepts a pointer to an object and returns its scriptID (line number in **scripts.lst**), or 0 if the object is unscripted. +- Returns -1 on argument error. + +----- +##### `void set_self(int obj)` +- Overrides the script's `self_obj` for the next function call. +- It is primarily used to allow the calling of functions which take an implicit `self_obj` parameter (e.g. `drop_obj`) from global scripts, but it can also be used from normal scripts. +- `self_obj` will revert back to its original value after the next function call. +- Calling `self_obj(0)` will also revert `self_obj` to original value. It is recommended to call this after each use of `set_self` in normal scripts in order to avoid unforeseen side effects. +- `source_obj`, `target_obj`, and similar functions will not work if preceded by `set_self`. +- __NOTE:__ for `use_obj` and `use_obj_on_obj` vanilla functions to work correctly, it is required to call `set_self` twice. + +----- +##### `void mod_skill_points_per_level(int x)` +- Accepts a value of between -100 and 100, and modifies the number of skill points the player receives when they level up. +- This is a modification of what would otherwise happen, rather than a replacement. +- The value is not saved into the save game, so should be reset in the `game_loaded` section of a script. + +----- +##### `void set_perk_freq(int x)` +- Sets the number of levels between each perk. +- Setting 0 will reset it back to the default. +- This overrides the effects of the skilled trait. +- It is not saved into the save game, so needs to be called once per reload. +- Be careful not to let the player obtain a perk when no perks are available to pick, or the game may crash. + +----- +##### `object get_last_target(object)` +- Will return the last critter to be deliberately attacked. + +----- +##### `object get_last_attacker(object)` +- Will return the last critter to deliberately launch an attack against the argument critter. +- If a critter has not launched/received an attack, it will return 0. This is only stored for the duration of combat, and outside of combat both functions will always return 0. + +----- +##### `void set_base_pickpocket_mod(int max, int mod)` +- Changes maximum chance of success and chance mod for each steal attempt. +- `max` will replace 95% success chance cap (so you can set 100% maximum chance, for instance). +- `mod` will add this much percent to each success chance. For example, if your chance is 50% and `mod` is 20, you will get 70% actual success rate. + +----- +##### `void set_critter_pickpocket_mod(object, int max, int mod)` +- The same as above, but applies only to specific critter. + +----- +##### `void reg_anim_combat_check` +- Allows to enable all `reg_anim_*` functions in combat (including vanilla functions) if set to 0. It is automatically reset at the end of each frame, so you need to call it before `reg_anim_begin() ... reg_anim_end()` code block. + +**Some additional `reg_anim_*` functions were introduced. They all work in the same convention as vanilla functions and use the same underlying code.** + +##### `void reg_anim_destroy(object)` +- Given object is destroyed at the end of current animation set. + +----- +##### `void reg_anim_animate_and_hide(object, animID, delay)` +- Exactly like `reg_anim_animate` but the object will automatically disappear after the last animation frame (but not destroyed). + +----- +##### `void reg_anim_light(object, light, delay)` +- Change light of any object. light argument is a light radius (0-8), but you can use highest 2 bytes to pass light intensity as well (example: `0xFFFF0008` - intensity 65535 and radius 8). If highest 2 bytes are 0, intensity will not be changed. Intensity range is from 0 to 65535 (0xFFFF). + +----- +##### `void reg_anim_change_fid(object, fid, delay)` +- Should work like `art_change_fid_num` but in `reg_anim` sequence. + +----- +##### `void reg_anim_take_out(object, holdFrameID, delay)` +- Plays "take out weapon" animation for given **holdFrameID**. It is not required to have such weapon in critter's inventory. + +----- +##### `void reg_anim_turn_towards(object, tile/target, delay)` +- Makes object change its direction to face given tile num or target object. + +----- +##### `void reg_anim_callback(procedure proc)` +- Adds the given procedure to an animation sequence-list and executes it in the registered sequence. + +----- +##### `int/array metarule2_explosions(int arg1, int arg2, int arg3)` +- Was made as a dirty easy hack to allow dynamically change some explosion parameters (ranged attack). All changed parameters are reset to vanilla state automatically after each attack action. Following macros are available in **sfall.h**: + +----- +##### `void set_attack_explosion_pattern(x, y)` +- Currently `y` is not used and `x` means: 1 - reduced explosion pattern (3 effects are spawned instead of 7), 0 - full pattern. + +----- +##### `void set_attack_explosion_art(x, y)` +- `y` is not used and `x` is a misc frame ID (last 3 bytes, without object type) to use for the next explosion. + +----- +##### `void set_attack_explosion_radius(x)` +- Changes radius at which explosion will hit secondary targets for the next attack (from the experiments it is limited to something around 8 by the engine) + +----- +##### `void set_attack_is_explosion_fire` +- If you call this right before using a weapon with fire damage type (e.g. in `HOOK_AFTERHITROLL`), it will produce explosion effects (and radius damage) just like "explosion" type, but all targets will still receive fire damage. + +----- +##### `void set_explosion_radius(grenade, rocket)` +- Sets a permanent radius of the explosion for grenades and/or rockets. Passing 0 means not changing the corresponding radius. +- Changed radius will be reset each time the player reloads the game. + +----- +##### `array get_explosion_damage(itemPid)` +- Returns an array of the minimum and maximum damage of the explosive item. + +----- +##### `void set_dynamite_damage(minDmg, maxDmg)` +- Sets the minimum and maximum damage for Dynamite. +- Changed damage will be reset each time the player reloads the game. + +----- +##### `void set_plastic_damage(minDmg, maxDmg)` +- Sets the minimum and maximum damage for Plastic Explosives. +- Changed damage will be reset each time the player reloads the game. + +----- +##### `void set_explosion_max_targets(x)` +- Sets the maximum number of additional targets for an explosion, valid range: 1..6 (default is 6) + +--- +### Some utility/math functions are available: + +##### `array string_split(string, split)` +- Takes a string and a separator, searches the string for all instances of the separator, and returns a temp array filled with the pieces of the string split at each instance. If you give an empty string as the separator, the string is split into individual characters. +- You can use this to search for a substring in a string like this: `strlen(get_array(string_split(haystack, needle), 0))` + +----- +##### `string substr(string, start, length)` +- Cuts a substring from a string starting at `start` up to `length` characters. The first character position is 0 (zero). +- If `start` is negative - it indicates starting position from the end of the string (for example, `substr("test", -2, 2)` will return last 2 charactes: "st"). +- If `length` is negative - it means so many characters will be omitted from the end of string (example: `substr("test", 0, -2)` will return string without last 2 characters: "te"). +- If `length` is zero - it will return a string from the starting position to the end of the string (new behavior for sfall 4.2.2/3.8.22). + +----- +##### `int strlen(string string)` +- Returns string length. + +----- +##### `string sprintf(string format, any value)` +- Formats given value using standard syntax of C `printf` function (google "printf" for format details). However it is limited to formatting only 1 value. +- Can be used to get character by ASCII code (`%c`). + +----- +##### `int typeof(any value)` +- Returns type of the given value: `VALTYPE_INT`, `VALTYPE_FLOAT` or `VALTYPE_STR`. + +----- +##### `int charcode(string string)` +- Returns ASCII code for the first character in given string. + +----- +##### `div` operator (unsigned integer division) +- Use as a division operator, like `3 + (20 div 5)` +- If both dividend and divisor are integers, they will be treated as unsigned integers. +- If one of them is a float, div will perform the signed division just like vanilla division operator. + +----- +##### `^` operator (exponentiation) +- Use as any other arithmetic operator, like `5 ^ (1 / 3)` +- If exponent is an integer, you can use a negative base, otherwise you will get `NaN` with a negative base. +- If both arguments are integers, the result will be an integer. + +----- +##### `float log(float x)` +- Natural logarithm of `x`. + +----- +##### `float exponent(float x)` +- `e ^ x` + +----- +##### `int ceil(float x)` +- Round `x` to the nearest integer that is not less than `x`. + +----- +##### `int round(float x)` +- Round `x` to the nearest integer. + +----- +##### `float sqrt(float x)` +- Square root of `x`. + +----- +##### `int/float abs(int/float x)` +- Absolute (positive) value of `x`. + +----- +##### `float sin(float x)` +- Sine of `x`. + +----- +##### `float cos(float x)` +- Cosine of `x`. + +----- +##### `float tan(float x)` +- Tangent of `x`. + +----- +##### `float arctan(float x, float y)` +- Arctangent of `x`. +- Just pass 1 as `y` (don't ask...) + +----- +##### `void register_hook_proc(int hook, procedure proc)` +- Works just like `register_hook`, but allows to specify which procedure to use for given hook script (instead of `start`). +- Use zero (0) as second argument to unregister hook script from current global script. +- Only use in global scripts. +- Second argument should be passed just like you pass procedures to functions like `gsay_option`, `giq_option`, etc. (name without quotes). +- See **hookscripts.md** for more details. + +----- +##### `void register_hook_proc_spec(int hook, procedure proc)` +- Works just like `register_hook_proc`, but allows to register a script at the end of the hook script execution chain (i.e. the script will be executed after all previously registered scripts for the same hook, including the `hs_*.int` script). +- To unregister hook script from current global script, use the `register_hook_proc` function. + +----- +##### `string message_str_game(int fileId, int messageId)` +- Works exactly the same as `message_str`, except you get messages from files in the `text\\game\` directory. +- Use `GAME_MSG_*` defines or `mstr_*` macros from **sfall.h** to use specific msg file. +- Additional game msg files added by **ExtraGameMsgFileList** setting will have consecutive fileIds assigned beginning from `0x2000` to `0x2FFF`. (e.g. if you set `ExtraGameMsgFileList=foo,bar` in ddraw.ini, foo.msg will be associated with 0x2000 and bar.msg with 0x2001.) +- If a file has a specific number assigned in **ExtraGameMsgFileList**, its fileId will be (`0x2000` + assigned number). (e.g. with `ExtraGameMsgFileList=foo,bar:2,foobar` in ddraw.ini, bar.msg will be associated with 0x2002 and foobar.msg with 0x2003.) + +----- +##### `int sneak_success()` +- Returns 1 if the player is currently sneaking, and last sneak attempt (roll against skill) was successful; 0 otherwise. +- This calls an internal engine function which is used to determine the perception range of critters (which you can override using `HOOK_WITHINPERCEPTION`). + +----- +##### `int tile_light(int elevation, int tileNum)` +- Returns light intensity at the given tile in range from 0 to 65536. + +----- +##### `object obj_blocking_line(object objFrom, int tileTo, int blockingType)` +- Returns first object which blocks direct linear path from objFrom to tileTo using selected blocking function (see `BLOCKING_TYPE_*` constants in **sfall.h**). +- If path is clear (no blocker was encountered by selected function) - returns 0. +- `objFrom` is always excluded from calculations, but is required to be a valid object. + +----- +##### `object obj_blocking_tile(int tileNum, int elevation, int blockingType)` +- Returns first object blocking given tile using given blocking function or 0 if tile is clear. + +----- +##### `array tile_get_objs(int tileNum, int elevation)` +- Returns an array of all objects at given tile. +- It will include any hidden, dead or system objects (like cursor), so make sure to check properly when iterating. + +----- +##### `array party_member_list(int includeHidden)` +- Returns an array of all current party members (0 - only critter-type, alive and visible will be returned, 1 - all object, including Trunk, etc.) + +----- +##### `array path_find_to(object objFrom, int tileTo, int blockingType)` +- Returns the shortest path to a given tile using given blocking function as an array of tile directions (0..5) to move on each step. +- Array length equals to a number of steps. +- Empty array means that specified target cannot be reached. + +----- +##### `object create_spatial(int scriptID, int tile, int elevation, int radius)` +- Creates new spatial script with given SID, at given tile, and radius. + +----- +##### `int art_exists(int artFID)` +- Checks if given **artFID** exists in the game. +- Useful when you want to check if critter can use specific weapon: `art_exists((artFid bwand 0xFFFF0FFF) bwor (weaponAnim * 0x1000))` + +----- +##### `int obj_is_carrying_obj(object invenObj, object itemObj)` +- Returns number of itemObj inside invenObj's inventory, note that both arguments are object pointers. +- Useful when dealing with different stacks of same item (`obj_is_carrying_obj_pid` just returns total for all stacks of the same PID). + +----- +##### `any sfall_funcX(string funcName, ...)` +- These opcodes allows to use additional scripting functions, that do not require new opcode. +- First argument is always function name (string). +- There are 9 versions of this opcode for different number of additional arguments (for convenience). +- Opcodes have return value, but it is not necessary to use it. + + +------------------------------ +sfall_funcX metarule functions +------------------------------ + +#### get_metarule_table +`array sfall_func0("get_metarule_table")` +- Returns names of all currently available scripting functions (via `sfall_funcX`) + +---- +#### metarule_exist +`bool sfall_func1("metarule_exist", string metaruleName)` +- Returns True if the specified name of `sfall_funcX` metarule function exists in the current version of sfall + +---- +#### spatial_radius +`int sfall_func1("spatial_radius", object object)` +- Returns radius of spatial script, associated with given dummy-object (returned by `create_spatial`) + +---- +#### critter_inven_obj2 +`object sfall_func2("critter_inven_obj2", object invenObj, int type)` +- Works just like vanilla `critter_inven_obj`, but correctly reports item in player's inactive hand slot + +---- +#### intface_redraw +`void sfall_func0("intface_redraw")`
+`void sfall_func1("intface_redraw", int winType)` +- Redraws main game interface, useful to reflect changes after directly changing current player weapons or stats +- `winType`: the type number of the interface window (see `WINTYPE_*` constants in **sfall.h**). Pass -1 to redraw all interface windows + +---- +#### intface_hide +`void sfall_func0("intface_hide")` +- Hides main interface + +---- +#### intface_show +`void sfall_func0("intface_show")` +- Shows main interface + +---- +#### intface_is_hidden +`int sfall_func0("intface_is_hidden")` +- Returns 1 if interface is currently hidden, 0 otherwise + +---- +#### exec_map_update_scripts +`void sfall_func0("exec_map_update_scripts")` +- Executes `map_update_p_proc` for all objects on map and global/hook scripts as well + +---- +#### set_ini_setting +`void sfall_func2("set_ini_setting", string setting, int/string value)` +- Writes an integer or a string value to an ini file in the Fallout directory. If the ini file does not exist, it will be created +- The `setting` argument works in the same way as in get_ini_setting; seperate the file name, section and key with a `|` character, e.g. `set_ini_setting("myini.ini|mysec|var1", 42)` +- The file name is limited to 63 chars, including the extension +- The section name is limited to 32 characters + +---- +#### floor2 +`int sfall_func1("floor2", int/float value)` +- Works just like vanilla `floor` function, but returns correct integers for negative values +- __NOTE:__ vanilla `floor` function works exactly the same as ceil for negative values, much like trunc in C/C++ + +---- +#### item_weight +`int sfall_func1("item_weight", object)` +- Gets the current weight of an object + +---- +#### get_outline +`int sfall_func1("get_outline", object)` +- Gets the current outline color for an object + +---- +#### set_outline +`void sfall_func2("set_outline", object, int color)` +- Sets the outline color of an object (see `OUTLINE_*` constants in **sfall.h**) +- Can also set a custom color from the game palette by shifting the color index value left by 8 bits: `0xCC00` where `CC` is the palette index (**available since sfall 4.2.7/3.8.27**) +- Passing 0 will disable the outline +- call `tile_refresh_display` after changing outline of objects to properly redraw the scene + +---- +#### get_flags +`int sfall_func1("get_flags", object)` +- Gets the current value of object flags (see **define_extra.h** for available flags) + +----- +##### set_flags +`void sfall_func2("set_flags", object, int flags)` +- Sets the current flags of an object +- All flags are rewritten with given integer, so first get current flags with `get_flags` and use `bwor`/`bwand` to set/remove specific flag + +---- +#### tile_refresh_display +`void sfall_func0("tile_refresh_display")` +- Redraws the game scene (tiles, walls, objects, etc.) + +---- +#### outlined_object +`object sfall_func0("outlined_object")` +- Returns an object that is currently highlighted by hovering the mouse above it + +---- +#### set_dude_obj +`object sfall_func1("set_dude_obj", critter)` +- Take control of a given critter +- passing 0 will reset control back to "real" dude + +---- +#### real_dude_obj +`void sfall_func0("real_dude_obj")` +- Returns the initial `dude_obj` after `set_dude_obj` was used + +---- +#### get_ini_sections +`array sfall_func1("get_ini_sections", string fileName)` +- Returns an array of names of all sections in a given INI file + +---- +#### get_ini_section +`array sfall_func2("get_ini_section", string fileName, string section)` +- Returns an associative array of keys and values for a given INI file and section +- __NOTE:__ all keys and their values will be of String type + +---- +#### car_gas_amount +`int sfall_func0("car_gas_amount")` +- Returns the current amount of fuel in player's car (between 0 and 80000) +- To change fuel amount, use vanilla function: `metarule(METARULE_GIVE_CAR_GAS, amount)` - amount can be positive or negative + +---- +#### set_car_intface_art +`void sfall_func1("set_car_intface_art", int artIndex)` +- Changes the interface art (index in **intrface.lst**) for the car image on the world map interface +- Should be called before going to the world map +- Vanilla art index is 433 + +---- +#### get_cursor_mode +`int sfall_func0("get_cursor_mode")` +- Returns the current cursor mode: 0 - movement cursor, 1 - command cursor, 2 - targeting cursor +- Mode 4 to 10 are **Skilldex** skills (yellow targeting cursor) + +---- +#### set_cursor_mode +`void sfall_func1("set_cursor_mode", int mode)` +- Sets the current cursor mode + +---- +#### display_stats +`void sfall_func0("display_stats")` +- Updates player stats in the inventory display window or on the character screen +- __NOTE:__ works only when the interface window is opened + +---- +#### lock_is_jammed +`int sfall_func1("lock_is_jammed", object)` +- Returns 1 if the lock (container or scenery) is currently jammed, 0 otherwise + +---- +#### unjam_lock +`void sfall_func1("unjam_lock", object)` +- Unjams a lock immediately without having to wait until the next day, or leave the map and then return after 24 hours +- __NOTE:__ does not work in `use_skill_on_p_proc` procedure + +---- +#### set_unjam_locks_time +`void sfall_func1("set_unjam_locks_time", int time)` +- Sets after how many hours (up to 127 hours) jammed locks will be unjammed if the player leaves the map +- Also disables the auto unjam that occurs at midnight when the player is on the map +- Passing 0 will disable the auto unjam mechanism completely +- The auto unjam mechanism will be reset each time the player reloads the game + +---- +#### get_map_enter_position +`array sfall_func0("get_map_enter_position")` +- Returns an array of the player's position data (index 0 - tile, 1 - elevation, 2 - rotation) when entering the map through exit grids +- If entering from the world map, the tile value will be -1 +- Should be called in `map_enter_p_proc` procedure to get the correct position data + +---- +#### set_map_enter_position +`void sfall_func3("set_map_enter_position", int tile, int elevation, int rotation)` +- Overrides the player's entry position when entering the map through exit grids +- Setting the `tile` to 0 will put the player on the start hex (default tile and elevation) of the map +- __NOTE:__ works only in `map_enter_p_proc` procedure + +---- +#### set_rest_heal_time +`void sfall_func1("set_rest_heal_time", int minutes)` +- Sets the time interval in minutes for healing during resting. The default is 180 +- The time interval will be reset each time the player reloads the game + +---- +#### set_rest_mode +`void sfall_func1("set_rest_mode", int mode)` +- Sets the bit flags for the rest mode (see `RESTMODE_*` constants in **sfall.h**) +- Passing 0 will reset the rest mode. It will also be reset each time the player reloads the game + +---- +#### attack_is_aimed +`int sfall_func0("attack_is_aimed")` +- Returns 1 if the aimed attack mode is selected, 0 otherwise + +---- +#### set_iface_tag_text +`void sfall_func3("set_iface_tag_text", int tag, string text, int color)` +- Sets the text messages and colors for custom notification boxes to the interface without the need to add messages to intrface.msg and set up the font colors in ddraw.ini +- `tag` value is the same as used in `show_iface_tag`, `hide_iface_tag`, and `is_iface_tag_active`. The valid range is from 5 to (4 + the value of **BoxBarCount** in ddraw.ini) or the number of the last custom box added using the `add_ifaca_tag` function +- The text is limited to 19 characters +- Available colors: 0 - green, 1 - red, 2 - white, 3 - yellow, 4 - dark yellow, 5 - blue, 6 - purple, 7 - dull pink + +---- +#### add_iface_tag +`int sfall_func0("add_iface_tag")` +- Adds one custom box to the current boxes, and returns the number of the added tag (-1 if the tags limit is exceeded) +- The maximum number of boxes is limited to 126 tags + +---- +#### inventory_redraw +`void sfall_func0("inventory_redraw")`
+`void sfall_func1("inventory_redraw", int invSide)` +- Redraws inventory list in the inventory/use inventory item on/loot/barter screens +- `invSide` specifies which side needs to be redrawn: 0 - the player, 1 - target (container/NPC in loot/barter screens), -1 - both sides (same as without argument) + +---- +#### item_make_explosive +`void sfall_func3("item_make_explosive", int pid, int activePid, int damage)`
+`void sfall_func4("item_make_explosive", int pid, int activePid, int min, int max)` +- Makes the specified item (pid) an explosive item like Dynamite or Plastic Explosives +- `activePid` is for an item with an active timer, can be the same as the pid argument +- The item proto must be **Misc Item** type and have **Use** action flag +- `min` and `max` are the minimum and maximum explosion damage +- Using the function on an item that is already set as an explosive will override its previous settings +- __NOTE:__ this function does not work for pid's of Dynamite and Plastic Explosives + +---- +#### get_string_pointer +`int sfall_func1("get_string_pointer", string text)` +- Returns a pointer to a string variable or to a text + +---- +#### dialog_message +`void sfall_func1("dialog_message", string text)` +- Displays a message in the NPC response window in dialog or barter screen + +---- +#### get_current_inven_size +`int sfall_func1("get_current_inven_size", object)` +- Returns the current inventory size of the container or the critter + +---- +#### create_win +`void sfall_func5("create_win", string winName, int x, int y, int width, int height)`
+`void sfall_func6("create_win", string winName, int x, int y, int width, int height, int flags)` +- Works just like vanilla `CreateWin` function, but creates a window with `MoveOnTop` flag if the flags argument is not specified, and allows to set additional flags for the created window +- `MoveOnTop` flag allows the created window to be placed on top of the game interface + +---- +#### set_can_rest_on_map +`void sfall_func3("set_can_rest_on_map", int mapNum, int elev, bool value)` +- Allows/disallows to rest on the map for the specified level, overrides the `can_rest_here` values in **maps.txt** +- `mapNum` is the map index from **maps.txt** +- Passing -1 to the `elev` argument will set the rest value for all map elevations +- The set rest value will be stored in **sfalldb.sav** file (in savegame) + +---- +#### get_can_rest_on_map +`int sfall_func2("get_can_rest_on_map", int mapNum, int elev)` +- Returns the set rest value of the map after using the `set_can_rest_on_map` function +- Returns -1 if the rest value of the map was not previously set (i.e. no data for the map in **sfalldb.sav**) +- The `can_rest_here` values from **maps.txt** are ignored + +---- +#### dialog_obj +`object sfall_func0("dialog_obj")` +- Returns a pointer to the object (critter) the player is having a conversation or bartering with + +---- +#### obj_under_cursor +`object sfall_func2("obj_under_cursor", bool onlyCritter, bool includeDude)` +- Returns the object under the cursor on the main game screen +- `onlyCritter`:
+ True - only checks critters and ignores their cover (roof tiles, walls, scenery, etc.)
+ False - checks all objects (can't check critters under objects) +- Passing False to the `includeDude` argument will ignore `dude_obj` +- __NOTE:__ to get an object located on a tile when the cursor is in movement mode (hexagon cursor), use the `tile_under_cursor` function + +---- +#### loot_obj +`object sfall_func0("loot_obj")` +- Returns a pointer to the target object (container or critter) of the loot screen + +---- +#### get_object_data +`int sfall_func2("get_object_data", object, int offset)` +- Returns the data at the specified offset of an object (see `OBJ_DATA_*` constants in **define_extra.h** for offsets) + +---- +#### set_object_data (object, offset, data) +`void sfall_func3("set_object_data", object, int offset, int data)` +- Sets the data at the specified offset of an object + +---- +#### get_object_ai_data +`int sfall_func2("get_object_ai_data", object, int aiParam)` +- Returns the setting value from the AI packet of an object (critter) +- Use `AI_CAP_*` constants from **define_extra.h** for the aiParam argument to get AI value + +----- +##### art_cache_clear +`void sfall_func0("art_cache_clear")` +- Clears the cache of FRM image files loaded into memory + +---- +#### npc_engine_level_up +`void sfall_func1("npc_engine_level_up", bool toggle)` +- Enables/disables the engine function that increases the level of party members in the player leveling process +- If the engine function is disabled, the process of leveling up party members should be performed by script functions + +---- +#### set_drugs_data +`void sfall_func3("set_drugs_data", int type, int pid, int value)` +- Overrides the parameters of drugs set in the configuration file (**DrugsFile** setting in ddraw.ini) +- `type`:
+ 0 - changes the value of **NumEffects** for the drug (see **Drugs.ini** for the description of NumEffects)
+ 1 - changes the duration of the addiction effect for the drug (a value of 1 = one game minute) + +---- +#### set_unique_id +`int sfall_func1("set_unique_id", object)`
+`int sfall_func2("set_unique_id", object, int flag)` +- Assigns a unique ID number to the object and returns it. If a unique ID number has already been assigned to an object, then ID number is returned without reassignment +- Items with unique IDs will not stack with other items of the same type in the inventory +- To just get the current ID number of an object, use `sfall_func2("get_object_data", object, OBJ_DATA_ID)` +- Unique ID numbers are saved in your savegame, and have a range from `0x10000000` to `0x7FFFFFFF` +- There is also a unique ID number range for the player and party members from 18000 to 83535 +- To assign a new ID number generated by the engine to the object (i.e. unassign a unique ID), call the function with two arguments and pass -1 for the flag argument + +---- +#### draw_image | draw_image_scaled +`void sfall_func5("draw_image", string/int artFile/artId, int frame, int x, int y, bool noTransparent)`
+`void sfall_func6("draw_image_scaled", string/int pathFile/artId, int frame, int x, int y, int width, int height)` +- Displays the specified PCX or FRM image in the active window created by vanilla `CreateWin` or sfall's `create_win` script function +- `artFile/artId`: path to the PCX/FRM file (e.g. `art\\inven\\5mmap.frm`), or its FRM ID number (e.g. `0x7000026`, see specification of the FID format) + +**Optional arguments:** +- `frame`: frame number, the first frame starts from zero +- `x/y`: offset relative to the top-left corner of the window +- `width/height`: the new width/height to scale the image to. Pass -1 to either width or height to keep the aspect ratio when scaling +- `noTransparent`: pass True to display an image without transparent background +- __NOTE:__ to omit optional arguments starting from the right, call the functions with different sfall_funcX (e.g. `sfall_func4("draw_image", pathFile, frame, x, y)`) +- If `draw_image_scaled` is called without x/y/width/height arguments, the image will be scaled to fit the window without transparent background + +---- +#### set_fake_perk_npc | set_fake_trait_npc | set_selectable_perk_npc | has_fake_perk_npc | has_fake_trait_npc +`void sfall_func5("set_fake_perk_npc", object npc, string namePerk, int level, int image, string desc)`
+`void sfall_func5("set_fake_trait_npc", object npc, string nameTrait, int active, int image, string desc)`
+`void sfall_func5("set_selectable_perk_npc", object npc, string namePerk, int active, int image, string desc)`
+`int sfall_func2("has_fake_perk_npc", object npc, string namePerk)`
+`int sfall_func2("has_fake_trait_npc", object npc, string nameTrait)` +- These functions are similar to `has_fake_perk`, `has_fake_trait`, `set_fake_perk`, `set_fake_trait`, `set_selectable_perk`, and `set_selectable_trait` functions, but apply to the specified party member NPC (including `dude_obj`) + +---- +#### add_extra_msg_file +`int sfall_func1("add_extra_msg_file", string fileName)`
+`int sfall_func2("add_extra_msg_file", string fileName, int fileNumber)` +- Loads the custom message file, and returns the file ID number assigned to it in range from `0x3000` to `0x3FFF` for the `message_str_game` function to get messages from the file +- `fileName`: the name of the custom message file (including the **.msg** extension) in the `text\\game\` directory +- __NOTE:__ if the msg file does not exist in the current language directory, the function will try to load it from the `text\English\game\` directory + +**Optional argument:** +- `fileNumber`: the file ID number for the `message_str_game` function. The available range is from `0x2000` to `0x2FFF` (see **ExtraGameMsgFileList** setting in ddraw.ini). Use **fileNumber** only if you want to add a message file without editing ddraw.ini or existing scripts to support the old way + +---- +#### unwield_slot +`void sfall_func2("unwield_slot", object critter, int slot)` +- Unequips an item from the specified slot for a critter or the player +- Can take off player's equipped item when the inventory is opened, or the player is in the barter screen +- `slot`: 0 - armor slot, 1 - right slot, 2 - left slot (see `INVEN_TYPE_*` in **define.h**) + +---- +#### add_trait +`void sfall_func1("add_trait", int traitID)` +- Adds the specified trait to the player + +---- +#### get_inven_ap_cost +`int sfall_func0("get_inven_ap_cost")` +- Returns the current AP cost to access the inventory in combat + +---- +#### add_g_timer_event +`void sfall_func2("add_g_timer_event", int time, int fixedParam)` +- Adds a timer event that calls the `timed_event_p_proc` procedure in the current global script +- `time`: the number of ticks after which the event timer is triggered +- `fixedParam`: the value that is passed to the `timed_event_p_proc` procedure for the `fixed_param` function + +---- +#### remove_timer_event +`void sfall_func0("remove_timer_event")`
+`void sfall_func1("remove_timer_event", int fixedParam)` +- Clears all set timer events for the current global script +- `fixedParam`: removes all timer events with the specified value for the current global script + +---- +#### get_sfall_arg_at +`mixed sfall_func1("get_sfall_arg_at", int argNum)` +- Gets the value of hook argument with the specified argument number (*first argument of hook starts from 0*) + +---- +#### hide_window +`void sfall_func0("hide_window")`
+`void sfall_func1("hide_window", string winName)` +- Hides the specified or currently active (selected) script window +- `winName`: the window name, assigned to the window by the `CreateWin` or `create_win` function + +---- +#### show_window +`void sfall_func0("show_window")`
+`void sfall_func1("show_window", string winName)` +- Displays the specified hidden script window or the one previously hidden with the `sfall_func0("hide_window")` function +- `winName`: the window name, assigned to the window by the `CreateWin` or `create_win` function + +---- +#### set_window_flag +`void sfall_func3("set_window_flag", string/int winName/winID, int flag, bool value)` +- Changes the specified flag for the created script or game interface window +- `winName`: the window name, assigned to the window by the `CreateWin` or `create_win` function +- `winID`: the ID number of the interface or script window obtained with the `get_window_under_mouse` function, or 0 for the current game interface +- `flag`: the flag to change (see `WIN_FLAG_*` constants in **define_extra.h**) +- `value`: True - set the flag, False - unset the flag + +---- +#### get_text_width +`int sfall_func1("get_text_width", string text)` +- Returns the text width in pixels for the currently set font + +---- +#### string_compare +`bool sfall_func2("string_compare", string str1, string str2)`
+`bool sfall_func3("string_compare", string str1, string str2, int codePage)` +- Compares two strings case-insensitive, and returns True if the two strings are matched +- `codePage`: code page number to properly compare national characters in the range 128-255 of the ASCII code table. Available encodings: 1250-1252, 866 + +---- +#### string_format +`string sfall_func3("string_format", string format, any val1, any val2, ...)` +- Formats given value using standard syntax of C `printf` function (google "printf" for format details). However it is limited to formatting up to 4 values +- Formatting is only supported for `%s` and `%d`, and the format string is limited to 1024 characters + +---- +#### objects_in_radius +`array sfall_func3("objects_in_radius", int tile, int radius, int elevation)`
+`array sfall_func4("objects_in_radius", int tile, int radius, int elevation, int type)` +- Returns an array of objects of a type (see `OBJ_TYPE_*` constants in **define_extra.h**) within the specified radius from the given tile +- Passing -1 to the `type` argument or not specifying it will return all objects within the radius +- The radius is limited to 50 hexes + +---- +#### tile_by_position +`int sfall_func2("tile_by_position", int x, int y)` +- Returns the tile number at the x, y position relative to the top-left corner of the game screen +- If the position is outside of the range of tiles, it will return -1 + +---- +#### string_to_case +`string sfall_func2("string_to_case", string text, int toCase)` +- Converts all letters in the given string to the specified case +- `toCase`: 0 - lowercase, 1 - uppercase +- __NOTE:__ this function works only for English letters of A-Z and a-z + +---- +#### set_terrain_name +`void sfall_func3("set_terrain_name", int x, int y, string name)` +- Overrides the terrain type name for the sub-tile on the world map by the specified coordinates + +---- +#### get_window_attribute +`int sfall_func1("get_window_attribute", int winType)`
+`int sfall_func2("get_window_attribute", int winType, int attrType)` +- Returns the attribute of the specified interface window by the `attrType` argument +- `winType`: the type number of the interface window (see `WINTYPE_*` constants in **sfall.h**) +- `attrType:`
+ 0 - checks and returns a value of 1 if the specified interface window is created by the game (same as without the argument)
+ 1 - X position, 2 - Y position (relative to the top-left corner of the game screen)
+ 3 - interface width size, 4 - interface height size
+ -1 - returns an associative array of keys (left, top, right, bottom) and values that define the position of the window rectangle (use standard syntax to access array values, e.g. `win.top`, `win.bottom`) +- Returns -1 if the specified attribute cannot be obtained + +---- +#### set_town_title +`void sfall_func2("set_town_title", int areaID, string title)` +- Sets a floating text for a town on the world map when hovering the cursor over the player's marker +- `areaID`: the ID number of the town from **city.txt** + +---- +#### message_box +`int sfall_func4("message_box", string message, int flags, int color1, int color2)` +- Creates a dialog box with text and returns the result of pressing the button: 0 - No (Escape), 1 - Yes/Done (Enter) +- Returns -1 if for some reason the dialog box cannot be created +- `message`: the text in the dialog box. Use the `\n` control character to move text to a new line (example: "Hello\nWorld!") + +**Optional arguments:** +- `flags`: mode flags (see `MSGBOX_*` constants in **define_extra.h**). Pass -1 to skip setting the flags (default flags are `NORMAL` and `YESNO`) +- `color1/color2`: the color index in the game palette. `color1` sets the text color for the first line, and `color2` for all subsequent lines of text (default color is 145) + +---- +#### get_stat_min | get_stat_max +`int sfall_func1("get_stat_min", int stat)`
+`int sfall_func1("get_stat_max", int stat)`
+`int sfall_func2("get_stat_min", int stat, bool who)`
+`int sfall_func2("get_stat_max", int stat, bool who)` +- Returns the maximum or minimum set value of the specified stat (see `set_stat_min` and `set_stat_max` functions) +- `who`: 0 (false) or omitting the argument - returns the value of the player, 1 (true) - returns the value set for other critters + +---- +#### interface_art_draw +`int sfall_func4("interface_art_draw", int winType, string/int artFile/artId, int x, int y)`
+`int sfall_func5("interface_art_draw", int winType, string/int artFile/artId, int x, int y, int frame)`
+`int sfall_func6("interface_art_draw", int winType, string/int artFile/artId, int x, int y, int frame, array param)` +- Draws the specified PCX or FRM image in the game interface window, returns -1 on any error +- `winType`: the type number of the interface window (see `WINTYPE_*` constants in **sfall.h**). This also takes the value of the flag `0x1000000` to prevent immediate redrawing of the interface window +- `artFile/artId`: path to the PCX/FRM file (e.g. `art\\inven\\5mmap.frm`), or its FRM ID number (e.g. `0x7000026`, see specification of the FID format) +- `x/y`: offset relative to the top-left corner of the window + +**Optional arguments:** +- `frame`: frame number, the first frame starts from zero +- `param`: an array which specifies additional parameters, where:
+ index 0 - sprite direction for multi-directional FRM
+ index 1/index 2 - the new width/height to scale the image to. Pass -1 to use the original width/height + +---- +#### interface_print +`int sfall_func5("interface_print", string text, int winType, int x, int y, int color)`
+`int sfall_func6("interface_print", string text, int winType, int x, int y, int color, int width)` +- Displays the text in the specified interface window with the current font. Use vanilla `SetFont` function to set the font +- Returns the count of lines printed, or -1 on any error +- `text`: the text to be printed. Use the `\n` control character to move text to a new line (example: "Hello\nWorld!") +- `winType`: the type number of the interface window (see `WINTYPE_*` constants in **sfall.h**) +- `x/y`: offset relative to the top-left corner of the window +- `color`: the color index in the game palette. Pass 0 if the text color was previously set by vanilla `SetTextColor` function. It can also take additional flags (via `bwor`) for displaying text:
+ `0x0010000` - adds a shadow to the text, the 'textshadow' compiler constant
+ `0x1000000` - prevents immediate redrawing of the interface window, the `textdirect` compiler constant (works the other way around)
+ `0x2000000` - fills the background of the text with black color, the `textnofill` compiler constant (works the other way around) + +**Optional argument:** +- `width`: the maximum width of the text. The text will be wrapped to fit within the specified width + +---- +#### combat_data +`mixed sfall_func0("combat_data")` +- Returns a pointer to the `C_ATTACK_*` data for the current combat attack turn (see defined constants in **define_extra.h**) +- Can be used in conjunction with the `get_object_data` and `set_object_data` functions
+ Example: `sfall_func3("set_object_data", sfall_func0("combat_data"), C_ATTACK_UNUSED, 255);` + +---- +#### win_fill_color +`int sfall_func0("win_fill_color")`
+`int sfall_func5("win_fill_color", int x, int y, int width, int height, int color)` +- Fills the rectangle area of the currently selected script window with the specified color, or clears the window with transparent color (use index 0 or call the function without arguments) +- `color`: the color index in the game palette (from 0 to 255) + +---- +#### interface_overlay +`int sfall_func2("interface_overlay", int winType, int mode)`
+`int sfall_func6("interface_overlay", int winType, 2, int x, int y, int width, int height)` +- Creates an additional drawing surface above the graphic layer of the specified interface window. All subsequent calls of `interface_art_draw` and `interface_print` functions will draw on it +- `winType`: the type number of the interface window (see `WINTYPE_*` constants in **sfall.h**) +- `mode`:
+ 1 - creates a new overlay surface
+ 2 - clears the overlay area or the specified rectangle defined by the x, y, width, height arguments
+ 0 - destroys the created overlay surface (frees up the memory allocated to the surface) + +---- +#### set_quest_failure_value +`void sfall_func2("set_quest_failure_value", int gvarNumber, int thresholdValue)` +- Sets the threshold value (failure_threshold) for the quest at which the quest will be considered failed (its description in the pipboy will be crossed out and colored red) +- `gvarNumber`: the number of the global variable controlling the quest +- `thresholdValue`: the value of the global variable at which the quest is counted as a failure + + +**** +_See other documentation files (arrays.md, hookscripts.md) for related functions reference._ diff --git a/artifacts/scripting/sfall function notes.txt b/artifacts/scripting/sfall function notes.txt deleted file mode 100644 index 8824c34f..00000000 --- a/artifacts/scripting/sfall function notes.txt +++ /dev/null @@ -1,799 +0,0 @@ -------------------------------------- ----------- GLOBAL SCRIPTS ----------- -------------------------------------- - -As well as the new functions, sfall also adds global scripts. These run independent of any loaded maps, but do not have an attached object. (i.e. using self_obj without using set_self first will crash the script.) To use a global script, the script must have a name which begins with 'gl' and contains a procedure called 'start', 'map_enter_p_proc', 'map_exit_p_proc', or 'map_update_p_proc'. The start procedure will be executed once when the player loads a saved game or starts a new game. The map_*_p_proc procedures will be executed once when a map is being entered/left/updated. If you wish the script to be executed repeatedly, call set_global_script_repeat on the first run of the start procedure using the number of frames between each run as the argument. (0 disables the script, 1 runs it every frame, 2 runs it every other frame etc.) - -Global scripts have multiple modes, which can be set using the set_global_script_type function. In the default mode (i.e. mode 0) their execution is linked to the local map game loop, so the script will not run in dialogs or on the world map. In mode 1 their execution is linked to the player input, and so they will run whenever the mouse cursor is visible on screen, including the world map, character dialogs etc. In mode 2, execution is linked to the world map loop, so the script will only be executed on the world map and not on the local map or in any dialog windows. Mode 3 is a combination of modes 0 and 2, so scripts will be executed on both local maps and the world map, but not in dialog windows. -[Using mode 1 requires the input wrapper to be enabled. Use available_global_script_types to check what is available.] - Obsolete. - - - -------------------------------------- ------- NOTES ON NEW FUNCTIONS ------- -------------------------------------- - -Both set_global_script_repeat and set_global_script_type only have an effect on the script they were called from. Every global script needs its own game_loaded block to correctly set up the script type and repeat rate. set_global_script_repeat will have no effect if called on a non-global script. - -The read_xxx functions take a memory address as the parameter and can read arbitrary pieces of Fallout's address space. The write functions are equivalent except that they write to arbitrary memory addresses. The call_offset_xx functions can be used to call arbitrary functions inside Fallout. Different versions are used to call functions with different numbers of arguments. None of these functions will work unless AllowUnsafeScripting is enabled in ddraw.ini - -The get/set_pc_base/extra_stat functions are equivalent to calling get/set_critter_base/extra_stat with dude_obj as the critter pointer. None of these stat functions take perks into account, and neither do they do range clamping to make sure the stats are valid. Use the normal get_critter_stat function to get a correctly perk adjusted and range clamped value for a stat. - -The set_stat_max/min functions can be used to set the valid ranges on stats. Values returned by get_current_stat will be clamped to this range. The set_pc_ function only affects the player, the set_npc_ functions only affects other critters, and the set_ functions affects both. - -The input functions are only available if the user has the input hook turned on in ddraw.ini. Use input_funcs_available to check. - -The graphics functions are only available if the user is using graphics mode 4 or 5. Use graphics_funcs_available to check; it returns 1 if you can use them or 0 if you can't. Calling graphics functions when graphics_funcs_available returns 0 will do nothing. - -load_shader takes a path relative to the \\shaders\ directory as an argument and returns a shader ID. That ID should be passed as the first argument to all other shader functions, and is valid until free_shader is called on the ID, the player loads a saved game or the player quits to the main menu. - -get_shader_version gives you the highest shader version supported by the player's graphics cards. Possible return values are 11, 12, 13, 14, 20, 21 and 30. - -set_shader_mode tells sfall when to use a shader. The parameter is a set of 32 flags which specify the screens on which the shader will be disabled, unless bit 32 is set, in which case the shader will only be active on those screens. Remember that screens are displayed on top of each other; if the player opens the character menu which in combat, the game still considers the player to be in combat. See sfall.h for a list of defines. - -force_graphics_refresh forces the screen to redraw at times when it normally wouldn't. If you're using animated shader, turning this option on is recommended. - -The mapper manual lists the functions 'world_map_x_pos' and 'world_map_y_pos', which supposedly return the player's x and y positions on the world map. get_world_map_x/y_pos are included here anyway, because I was unable to get those original functions to work, or even to find any evidence that they existed in game. - -set_pipboy_available will only accept 0 or 1 as an argument. Using any other value will cause the function to have no effect. Use 0 to disable the pipboy, and 1 to enable it. - -get/set_critter_current_ap functions should only be used during the target critters turn while in combat. Calling them outside of combat typically returns the critters max ap, but don't rely on that behaviour. (Specifically, if the critter has never before entered combat, it will probably return the critters base ap ignoring any extra bonuses from perks etc.) - -The 'type' value in the weapon knockback functions can be 0 or 1. If 0, the value becomes an absolute distance that targets will be knocked back. If 1, the value is multiplied by the distance they would normally have been knocked back. Weapon knockback modifiers are applied in the order weapon -> attacker -> target, so a x2 weapon wielded by an abs 6 attacker hitting a /2 target will knock the target back 3 squares. The knockback functions will not override the stonewall perk or knockdowns resulting from criticals. knockback values set on weapons or critters are not saved, and must be reset each time the player reloads. - -The get/set_sfall_global functions require an 8 characters long case sensitive string for the variable name. The variables behave the same as normal Fallout globals, except that they don't have to be declared beforehand in vault13.gam. Trying to get a variable which hasn't been set will always return 0. These functions are intended for use when a patch to a mod requires the addition of a new global variable, a case which would otherwise require the player to start a new game. - -set_pickpocket_max and set_hit_chance_max affect all critters rather than just the player and can set the maximum in range from 0 to 999. set_skill_max can't be used to increase the skill cap above 300. set_perk_level_mod sets a modifier between +25 and -25 that is added/subtracted from the player's level for the purposes of deciding which perks can be chosen. - -set_fake_trait and set_fake_perk can be used to add additional traits and perks to the character screen. They will be saved correctly when the player saves and reloads games, but by themselves they will have no further effect on the character. For perks, the allowed range for levels is between 0 and 100; setting the level to 0 removes that perk. For traits, the level must be 0 or 1. The image is a numeric id that corresponds to an entry in skilldex.lst. The name is limited to 63 characters and the description to 255 characters by sfall, but internal Fallout limits may be lower. - -has_fake_trait and has_fake_perk return the number of levels the player has of the perks/traits with the given name or ID of extra perk. - -perk_add_mode, set_selectable_perk, set_perkbox_title, hide_real_perks, show_real_perks and clear_selectable_perks control the behaviour of the select a perk box. set_selectable_perk can be used to add additional items by setting the 'active' parameter to 1, and to remove them again by setting it to 0. set_perkbox_title can be used to change the title of the box, or by using "" it will be set back to the default. hide and show_real_perks can be used to prevent the dialog from displaying any of the original 119 perks. perk_add_mode modifies what happens when a fake perk is selected from the perks dialog. It is treated as a set of flags - if bit 1 is set then it is added to the player's traits, if bit 2 is set it is added to the player's perks, and if bit 3 is set it is removed from the list of selectable perks. The default is 0x2. clear_selectable_perks restores the dialog to its default state. - -show_iface_tag, hide_iface_tag and is_iface_tag_active relate to the boxes that appear above the interface such as SNEAK and LEVEL. You can use 3 for LEVEL and 4 for ADDICT, or the range from 5 to (4 + the value of BoxBarCount in ddraw.ini) for custom boxes. Remember to add your messages to intrface.msg and set up the font colours in ddraw.ini if you're going to use custom boxes. Starting from sfall 4.1/3.8.12, is_iface_tag_active can also be used to check 0 for SNEAK, 1 for POISONED, and 2 for RADIATED. - -get/set_bodypart_hit_modifier alter the hit percentage modifiers for aiming at specific bodyparts. Valid bodypart id's are from 0 to 8. Changes are not saved, and will reset to the defaults (or to the values specified in ddraw.ini if they exist) at each reload. - -(re)set/get_critical_table are used for modifying the critical table. For details see 'http://falloutmods.wikia.com/wiki/Critical_hit_tables'. Changes are not saved, and will reset to the defaults, (or to the contents of CriticalOverrides.ini, if it exists,) at each game reload. These function also require OverrideCriticalTable to be set to 1 in ddraw.ini. (Disabled by default, because it noticably increases loading times.) - -get/set_unspent_ap_bonus alter the AC bonus you receive per unused action point at the end of your turn in combat. To allow for fractional values, the value given if divided by 4. (Hence the default value is 4 and not 1.) get/set_unspent_ap_perk_bonus are similar, but affect the extra AC granted by the HtH Evade perk. (The default value of this is also 4, equivalent to doubling the original bonus.) - -nb_* functions are reserved for the brotherhood tactical training mod, and should be avoided. - -The fs_* functions are used to manipulate a virtual file system. Files saved here should have paths relative to the data folder, and use backslashes as the directory separator. They will take precedence over files stored in the normal data folder. They will also be saved into save games if you set a flag for them using fs_resize(fileId, -1), so be avoid creating large files. Using fs_copy followed by fs_read_xxx, you can read the contents of existing files. - -get/set_proto_data are used to manipulate the in memory copies of the .pro files Fallout makes when they are loaded. The offset refers to the offset in memory from the start of the proto to the element you are reading. Changes are not stored on disc, and are not permanent. If you modify the protos, and then Fallout subsequently reloads the file your changes will be lost. - -the list_xxx functions can be used to loop over all items on a map. list_begin takes an argument telling sfall what you want to list. (Defined in sfall.h) It returns a list pointer, which you iterate through with list_next. Finally, when you've finished with the list use list_end on it. Not calling list_end will result in a memory leak. Alternatively, use list_as_array to get the whole list at once as a temp array variable, which can be looped over using len_array and which you don't need to remember to free afterwards. - -play_sfall_sound and stop_sfall_sound are used to play mp3/wav/wma files. The path given is relative to the Fallout folder. Specify mode as 1 to loop the file continuously, 2 to replace the current background game music with playing the specified file in loop mode, or 0 to play the file once. If you don't wish to loop, play_sfall_sound returns 0. If you do loop, it returns an id which can be passed back to stop_sfall_sound when you want to stop the effect. All sounds effects will be stopped on game reload, looping or not. These functions do not require 'AllowDShowSound' to be set to 1 in ddraw.ini. -Starting from sfall 4.2.8/3.8.28, you can pass a value in the 'mode' argument for a reduced sound volume. To set the volume, You need to convert the number to hexadecimal and use the argument format 0xZZZZ000Y, where ZZZZ is the volume reduction value in range from 0 to 32767 (the value 32767 is mute), and Y is the playback mode. - -arrays are created and manipulated with the xxx_array functions. An array must first be created with create_array or temp_array, specifying how many data elements the array can hold. You can store any of ints, floats and strings in an array, and can mix all 3 in a single array. The id returned by create/temp_array can then be used with the other array functions. Arrays are shared between all scripts. (i.e. you can call create_array from one script, and then use the returned id from another script.) They are also saved across savegames. You must remember to free any arrays you create with create_array when you are done with them, or you will leak memory. arrays created with temp_array will be automatically freed at the end of the frame. These functions are safe, in that supplying a bad id or trying to access out of range elements will not crash the script. create_array is the only function that returns a permanent array, all other functions which return arrays (string_split, list_as_array etc,) all return temp arrays. You can use fix_array to make a temp array permanent. - -NOTE: the above description only applies when "arraysBehavior" is set to 0 in ddraw.ini. Refer to "arrays.txt" for detailed description of new arrays behavior. - -force_aimed_shots and disable_aimed_shots allow overriding the normal rules regarding which weapons are allowed to make aimed attacks. (e.g. weapons that cause explosive damage normally cannot normally make aimed shots.) force_aimed_shots will allow a weapon to make aimed shots even if it normally couldn't, and disable_aimed_shots stops a weapon from making aimed shots even if it normally could. Both of these functions affect player and NPCs alike. force_aimed_shots does not override the effects of the fast shot trait. The list of edited weapons is not saved over game loads, so you need to call the functions once at each reload. Use a pid of 0 to represent unarmed. - -get/set_critter_skill_points will get/set the number of additional points a critter has in a skill, on top of whatever they have from their stats and other bonuses. Note that skill points are part of the proto, so calling set_skill_points on a critter will affect all critters that share the same proto. - - - ------------------------------- ------- TYPES REFERENCE ------- ------------------------------- - -> Data types mentioned in this document: - -void - means opcode does not return any value -any - any type -int - integer number -float - floating point number -string - string (text) value -object - pointer to game object (actually an integer) -array - array ID to be used with array-related functions (actually an integer) - - ----------------------------------------------- ------- FUNCTION REFERENCE (incomplete) ------- ----------------------------------------------- - -> int game_loaded() -- returns 1 the first time it is called after a new game or game load, and 0 any time after. It works on an individual basis for each script, so one script wont interfere with others. Its primary use is for global scripts, so that they know when to call set_global_script_repeat, but it can be called from normal scripts too. - -> void inc_npc_level(int pid/string name) -- takes a party member PID or an NPC name (deprecated, for compatibility with sfall 4.1.5/3.8.15 or earlier) as an argument. The NPC must be in your party. -- This function ignores player level requirements and the minimum 3 player level delay between NPC level gains. It also ignores the random element, regardless of sfall's NPCAutoLevel setting. - -> int get_npc_level(int pid/string name) -- also takes the party member PID or NPC name (deprecated, for compatibility with sfall 4.1.5/3.8.15 or earlier) as an argument, and returns the NPC's current level. Again, the NPC needs to be in your party. - -> void set_car_current_town(int town) -- changes the current town index for the player's car - -> int get_ini_setting(string setting) -- reads an integer value from an ini file in the Fallout directory. -- It only takes a single argument; seperate the file name, section and key with a '|' character; e.g. 'myvar:=get_ini_setting("myini.ini|mysec|var1")' If the file or key cannot be found, -1 is returned. -- The file name is limited to 63 chars, including the extension. -- The section name is limited to 32 characters. -- It can also be used to get sfalls settings, by using ddraw.ini as the file name. - -> string get_ini_string(string setting) -- reads a string value from an ini file in the Fallout directory. - -> int get_game_mode() -- is a more flexible version of in_world_map. It will return a set of flags indicating which mode the game is currently in. -- These flags are the same as those used in the set_shader_mode function. - -> int get_uptime() -- is just a wrapper around the windows GetTickCount() function. It's useful for making time fade effects in shaders, since they already have access to the current tick count. - -> boolean in_world_map() -- returns 1 if the player is looking at the world map, or 0 at any other time. -- Obviously this is only useful in global scripts, since normal scripts will never get the chance to run on the world map. - -> void force_encounter(int map) -- can be called either from a global script while traveling on the world map, or from a normal script while on a local map. -- In either case the encounter occurs shortly after the next time the player moves on the world map. -- The player will not get an outdoorsman skill check. - -> void force_encounter_with_flags(int map, int flags) -- does the same thing as force_encounter, but allows the specification of some extra options (see sfall.h for available flags). -- Forcing a random encounter on a map that is not normally used for random encounters may cause the player to lose the car, if they have it. -- In this case use force_encounter_with_flags with the ENCOUNTER_FLAG_NO_CAR flag set. - -> int get_light_level() -- ambient light level in range 0..65536 -- The value returned by get_light_level may not exactly match that set by set_light_level, as set_light_level applies modifiers from the night vision perk. - -> void set_map_time_multi(float multi) -- adjusts how fast time passes while you're on the world map. It takes a single float as an argument, where 1 is the normal speed. -- This function works in addition to the WorldMapTimeMod setting in ddraw.ini and the pathfinder perk, rather than overriding it, so calling set_map_time_multi(0.5) when the player has 2 levels of pathfinder would result in time passing at 25% the normal speed on the world map. - -> void remove_script(object) -- accepts a pointer to an object and will remove the script from that object. - -> void set_script(object, int scriptid) -- accepts a pointer to an object and scriptID, and applies the given script to an object (scriptID accepts the same values as create_object_sid) -- If used on an object that is already scripted, it will remove the existing script first; you cannot have multiple scripts attached to a single object. Calling set_script on self_obj will have all sorts of wacky side effects, and should be avoided. -- if you add 0x80000000 to the sid when calling set_script, map_enter_p_proc will be SKIPPED. The start proc will always be run. - -> int get_script(object) -- accepts a pointer to an object and returns its scriptID (line number in scripts.lst), or 0 if the object is unscripted. -- returns -1 on argument error. - -> void set_self(int obj) -- overrides the scripts self_obj for the next function call. -- It is primarily used to allow the calling of functions which take an implicit self_obj parameter (e.g. drop_obj) from global scripts, but it can also be used from normal scripts; -- self_obj will revert back to its original value after the next function call. -- calling self_obj(0) will also revert self_obj to original value. It is recommended to call this after each use of set_self in normal scripts in order to avoid unforeseen side effects. -- source_obj, target_obj, and similar functions will not work if preceded by "set_self" -- NOTE: for use_obj/use_obj_on_obj vanilla functions to work correctly, it is required to call set_self twice. - -> void mod_skill_points_per_level(int x) -- accepts a value of between -100 and 100, and modifies the number of skill points the player receives when they level up. -- This is a modification of what would otherwise happen, rather than a replacement. -- The value is not saved into the save game, so should be reset in the game_loaded section of a script. - -> void set_perk_freq(int x) -- sets the number of levels between each perk. -- Setting 0 will reset it back to the default. -- This overrides the effects of the skilled trait. -- It is not saved into the save game, so needs to be called once per reload. -- Be careful not to let the player obtain a perk when no perks are available to pick, or the game may crash. - -> object get_last_target(object) -- will return the last critter to be deliberately attacked -> object get_last_attacker(object) -- will return the last critter to deliberately launch an attack against the argument critter. -- If a critter has not launched/received an attack, it will return 0. This is only stored for the duration of combat, and outside of combat both functions will always return 0. - -> void set_base_pickpocket_mod(int max, int mod) -- changes maximum chance of success and chance mod for each steal attempt -- "max" will replace 95% success chance cap (so you can set 100% maximum chance, for instance) -- "mod" will add this much percent to each success chance. for example if your chance is 50% and "mod" is 20, you will get 70% actual success rate - -> void set_critter_pickpocket_mod(object, int max, int mod) -- the same as above, but applies only to specific critter - -> void reg_anim_combat_check -- allows to enable all reg_anim_* functions in combat (including vanilla functions) if set to 0. It is automatically reset at the end of each frame, so you need to call it before "reg_anim_begin" - "reg_anim_end" block. - - -Some additional reg_anim_* functions were introduced. They all work in the same convention as vanilla functions and use the same underlying code. - -> void reg_anim_destroy(object) -- given object is destroyed at the end of current animation set - -> void reg_anim_animate_and_hide(object, animID, delay) -- exactly like "reg_anim_animate" but the object will automatically disappear after the last animation frame (but not destroyed) - -> void reg_anim_light(object, light, delay) -- change light of any object. light argument is a light radius (0-8), but you can use highest 2 bytes to pass light intensity as well (example: 0xFFFF0008 - intensity 65535 and radius 8). If highest 2 bytes are 0, intensity will not be changed. Intensity range is from 0 to 65535 (0xFFFF). - -> void reg_anim_change_fid(object, fid, delay) -- should work like art_change_fid_num but in reg_anim sequence - -> void reg_anim_take_out(object, holdFrameID, delay) -- plays "take out weapon" animation for given holdFrameID. It is not required to have such weapon in critter's inventory. - -> void reg_anim_turn_towards(object, tile/target, delay) -- makes object change its direction to face given tile num or target object. - -> void reg_anim_callback(procedure proc) -- adds the given procedure to an animation sequence-list and executes it in the registered sequence. - -> int/array metarule2_explosions(int arg1, int arg2, int arg3) -was made as a dirty easy hack to allow dynamically change some explosion parameters (ranged attack). All changed parameters are reset to vanilla state automatically after each attack action. Following macros are available in sfall.h: - -> void set_attack_explosion_pattern(x, y) -- currently y is not used and x means: 1 - reduced explosion pattern (3 effects are spawned instead of 7), 0 - full pattern - -> void set_attack_explosion_art(x, y) -- y is not used and x is a misc frame ID (last 3 bytes, without object type) to use for the next explosion. - -> void set_attack_explosion_radius(x) -- changes radius at which explosion will hit secondary targets for the next attack (from the experiments it is limited to something around 8 by the engine) - -> void set_attack_is_explosion_fire -- if you call this right before using a weapon with fire damage type (e.g. in HOOK_AFTERHITROLL), it will produce explosion effects (and radius damage) just like "explosion" type, but all targets will still receive fire damage. - -> void set_explosion_radius(grenade, rocket) -- sets a permanent radius of the explosion for grenades and/or rockets. Passing 0 means not changing the corresponding radius. -- changed radius will be reset each time the player reloads the game. - -> array get_explosion_damage(itemPid) -- returns an array of the minimum and maximum damage of the explosive item. - -> void set_dynamite_damage(minDmg, maxDmg) -- sets the minimum and maximum damage for Dynamite. -- changed damage will be reset each time the player reloads the game. - -> void set_plastic_damage(minDmg, maxDmg) -- sets the minimum and maximum damage for Plastic Explosives. -- changed damage will be reset each time the player reloads the game. - -> void set_explosion_max_targets(x) -- sets the maximum number of additional targets for an explosion, valid range: 1..6 (default is 6) - - -Some utility/math functions are available: - -> array string_split(string, split) -- takes a string and a separator, searches the string for all instances of the separator, and returns a temp array filled with the pieces of the string split at each instance. If you give an empty string as the separator, the string is split into individual characters. -- you can use this to search for a substring in a string like this: strlen(get_array(string_split(haystack, needle), 0)) - -> string substr(string, start, length) -- cuts a substring from a string starting at "start" up to "length" characters. The first character position is 0 (zero). -- If start is negative - it indicates starting position from the end of the string (for example substr("test", -2, 2) will return last 2 charactes: "st"). -- If length is negative - it means so many characters will be omitted from the end of string (example: substr("test", 0, -2) will return string without last 2 characters: "te"). -- If length is zero - it will return a string from the starting position to the end of the string **New behavior** for sfall 4.2.2/3.8.22 - -> int strlen(string string) -- returns string length - -> string sprintf(string format, any value) -- formats given value using standard syntax of C printf function (google "printf" for format details). However it is limited to formatting only 1 value. -- can be used to get character by ASCII code ("%c") - -> int typeof(any value) -- returns type of the given value: VALTYPE_INT, VALTYPE_FLOAT or VALTYPE_STR. - -> int charcode(string string) -- returns ASCII code for the first character in given string - -> div operator (unsigned integer division) -- use as a division operator, like 3 + (20 div 5) -- if both dividend and divisor are integers, they will be treated as unsigned integers -- if one of them is a float, div will perform the signed division just like vanilla division operator - -> ^ operator (exponentiation) -- use as any other arithmetic operator, like 5^(1/3) -- if exponent is an integer, you can use a negative base, otherwise you will get "NaN" with a negative base -- if both arguments are integers, the result will be an integer - -> float log(float x) -- natural logarithm of x - -> float exponent(float x) -- e^x - -> int ceil(float x) -- round x to the nearest integer that is not less than x - -> int round(float x) -- round x to the nearest integer - -> float sqrt(float x) -- square root of x - -> int/float abs(int/float x) -- absolute (positive) value of x - -> float sin(float x) - -> float cos(float x) - -> float tan(float x) -- tangent of x - -> float arctan(float x, float y) -- arctangent of x -- just pass 1 as y (don't ask...) - - -> void register_hook_proc(int hook, procedure proc) -- works just like "register_hook", but allows to specify which procedure to use for given hook script (instead of "start") -- use zero (0) as second argument to unregister hook script from current global script -- only use in global scripts -- second argument should be passed just like you pass procedures to functions like gsay_option, giq_option, etc (name without quotes) -- see "hookscripts.txt" for more details - -> void register_hook_proc_spec(int hook, procedure proc) -- works just like "register_hook_proc", but allows to register a script at the end of the hook script execution chain (i.e. the script will be executed after all previously registered scripts for the same hook, including the hs_*.int script) -- to unregister hook script from current global script, use the register_hook_proc function - -> string message_str_game(int fileId, int messageId) -- works exactly the same as message_str, except you get messages from files in "text\\game\" directory -- use GAME_MSG_* defines or mstr_* macros from sfall.h to use specific msg file -- Additional game msg files added by ExtraGameMsgFileList setting will have consecutive fileIds assigned beginning from 0x2000 to 0x2FFF. (e.g. if you set ExtraGameMsgFileList=foo,bar in ddraw.ini, foo.msg will be associated with 0x2000 and bar.msg with 0x2001.) -- if a file has a specific number assigned in ExtraGameMsgFileList, its fileId will be (0x2000 + assigned number). (e.g. with ExtraGameMsgFileList=foo,bar:2,foobar in ddraw.ini, bar.msg will be associated with 0x2002 and foobar.msg with 0x2003.) - -> int sneak_success -- returns 1 if the player is currently sneaking, and last sneak attempt (roll against skill) was successful; 0 otherwise -- this calls an internal engine function which is used to determine the perception range of critters (which you can override using HOOK_WITHINPERCEPTION) - -> int tile_light(int elevation, int tileNum) -- returns light intensity at the given tile in range from 0 to 65536 - -> object obj_blocking_line(object objFrom, int tileTo, int blockingType) -- returns first object which blocks direct linear path from objFrom to tileTo using selected blocking function (see BLOCKING_TYPE_* constants in sfall.h) -- if path is clear (no blocker was encountered by selected function) - returns 0 -- objFrom is always excluded from calculations, but is required to be a valid object - -> object obj_blocking_tile(int tileNum, int elevation, int blockingType) -- returns first object blocking given tile using given blocking function or 0 if tile is clear - -> array tile_get_objs(int tileNum, int elevation) -- returns an array of all objects at given tile -- it will include any hidden, dead or system objects (like cursor), so make sure to check properly when iterating - -> array party_member_list(int includeHidden) -- returns an array of all current party members (0 - only critter-type, alive and visible will be returned, 1 - all object, including Trunk, etc.) - -> array path_find_to(object objFrom, int tileTo, int blockingType) -- returns the shortest path to a given tile using given blocking function as an array of tile directions (0..5) to move on each step -- array length equals to a number of steps -- empty array means that specified target cannot be reached - -> object create_spatial(int scriptID, int tile, int elevation, int radius) -- creates new spatial script with given SID, at given tile, and radius - -> int art_exists(int artFID) -- checks if given artFID exists in the game -- useful when you want to check if critter can use specific weapon: art_exists((artFid bwand 0xffff0fff) bwor (weaponAnim * 0x1000)) - -> int obj_is_carrying_obj(object invenObj, object itemObj) -- returns number of itemObj inside invenObj's inventory, note that both arguments are object pointers -- useful when dealing with different stacks of same item (obj_is_carrying_obj_pid just returns total for all stacks of the same PID) - -> any sfall_funcX(string funcName, ...) -- these opcodes allows to use additional scripting functions, that do not require new opcode -- first argument is always function name (string) -- there are 9 versions of this opcode for different number of additional arguments (for convenience) -- opcodes have return value, but it is not necessary to use it - - ------------------------------------- ------- sfall_funcX functions ------- ------------------------------------- - -> array sfall_func0("get_metarule_table") -- returns names of all currently available scripting functions (via sfall_funcX) - -> bool sfall_func1("metarule_exist", string metaruleName) -- returns True if the specified name of metarule (sfall_funcX) function exists in the current version of sfall - -> int sfall_func1("spatial_radius", object object) -- returns radius of spatial script, associated with given dummy-object (returned by create_spatial) - -> object sfall_func2("critter_inven_obj2", object invenObj, int type) -- works just like vanilla critter_inven_obj, but correctly reports item in player's inactive hand slot - -> void sfall_func0("intface_redraw") -> void sfall_func1("intface_redraw", int winType) -- redraws main game interface, useful to reflect changes after directly changing current player weapons or stats -- winType: the type number of the interface window (see WINTYPE_* constants in sfall.h). Pass -1 to redraw all interface windows - -> void sfall_func0("intface_hide") -- hides main interface - -> void sfall_func0("intface_show") -- shows main interface - -> int sfall_func0("intface_is_hidden") -- returns 1 if interface is currently hidden, 0 otherwise - -> void sfall_func0("exec_map_update_scripts") -- executes map_update_p_proc for all objects on map and global/hook scripts as well - -> void sfall_func2("set_ini_setting", string setting, int/string value) -- writes an integer or a string value to an ini file in the Fallout directory. If the ini file does not exist, it will be created -- The setting argument works in the same way as in get_ini_setting; seperate the file name, section and key with a '|' character; e.g. 'set_ini_setting("myini.ini|mysec|var1", 42)' -- The file name is limited to 63 chars, including the extension -- The section name is limited to 32 characters - -> int sfall_func1("floor2", int/float value) -- works just like vanilla floor function, but returns correct integers for negative values -- vanilla floor function works exactly the same as ceil for negative values, much like trunc in C/C++ - -> int sfall_func1("item_weight", object) -- gets the current weight of an object - -> int sfall_func1("get_outline", object) -- gets the current outline color for an object - -> void sfall_func2("set_outline", object, int color) -- sets the outline color of an object (see OUTLINE_* constants in sfall.h) -- can also set a custom color from the game palette by shifting the color index value left by 8 bits: 0xCC00 where CC is the palette index (available since sfall 4.2.7/3.8.27) -- passing 0 will disable the outline -- call "tile_refresh_display" after changing outline of objects to properly redraw the scene - -> int sfall_func1("get_flags", object) -- gets the current value of object flags (see define_extra.h for available flags) - -> void sfall_func2("set_flags", object, int flags) -- sets the current flags of an object -- all flags are rewritten with given integer, so first get current flags with "get_flags" and use bwor/bwand to set/remove specific flag - -> void sfall_func0("tile_refresh_display") -- redraws the game scene (tiles, walls, objects, etc.) - -> object sfall_func0("outlined_object") -- returns an object that is currently highlighted by hovering the mouse above it - -> object sfall_func1("set_dude_obj", critter) -- take control of a given critter -- passing 0 will reset control back to "real" dude - -> void sfall_func0("real_dude_obj") -- returns the initial dude_obj after set_dude_obj was used - -> array sfall_func1("get_ini_sections", string fileName) -- returns an array of names of all sections in a given INI file - -> array sfall_func2("get_ini_section", string fileName, string section) -- returns an associative array of keys and values for a given INI file and section -- NOTE: all keys and their values will be of String type - -> int sfall_func0("car_gas_amount") -- returns the current amount of fuel in player's car (between 0 and 80000) -- to change fuel amount, use vanilla function: metarule(METARULE_GIVE_CAR_GAS, amount) - amount can be positive or negative - -> void sfall_func1("set_car_intface_art", int artIndex) -- changes the interface art (index in intrface.lst) for the car image on the world map interface -- should be called before going to the world map -- vanilla art index is 433 - -> int sfall_func0("get_cursor_mode") -- returns the current cursor mode (0 - movement cursor, 1 - command cursor, 2 - targeting cursor) -- mode 4 to 10 are Skilldex skills (yellow targeting cursor) - -> void sfall_func1("set_cursor_mode", int mode) -- sets the current cursor mode - -> void sfall_func0("display_stats") -- updates player's stats in the inventory display window or on the character screen -- NOTE: works only when the interface window is opened - -> int sfall_func1("lock_is_jammed", object) -- returns 1 if the lock (container or scenery) is currently jammed, 0 otherwise - -> void sfall_func1("unjam_lock", object) -- unjams a lock immediately without having to wait until the next day, or leave the map and then return after 24 hours -- does not work in use_skill_on_p_proc procedure - -> void sfall_func1("set_unjam_locks_time", int time) -- sets after how many hours (up to 127 hours) jammed locks will be unjammed if the player leaves the map -- also disables the auto unjam that occurs at midnight when the player is on the map -- passing 0 will disable the auto unjam mechanism completely -- The auto unjam mechanism will be reset each time the player reloads the game - -> array sfall_func0("get_map_enter_position") -- returns an array of the player's position data (index 0 - tile, 1 - elevation, 2 - rotation) when entering the map through exit grids -- if entering from the world map, the tile value will be -1 -- should be called in map_enter_p_proc procedure to get the correct position data - -> void sfall_func3("set_map_enter_position", int tile, int elevation, int rotation) -- overrides the player's entry position when entering the map through exit grids -- setting the tile to 0 will put the player on the start hex (default tile and elevation) of the map -- works only in map_enter_p_proc procedure - -> void sfall_func1("set_rest_heal_time", int minutes) -- sets the time interval in minutes for healing during resting. The default is 180 -- The time interval will be reset each time the player reloads the game - -> void sfall_func1("set_rest_mode", int mode) -- sets the bit flags for the rest mode (see RESTMODE_* constants in sfall.h) -- passing 0 will reset the rest mode. It will also be reset each time the player reloads the game - -> int sfall_func0("attack_is_aimed") -- returns 1 if the aimed attack mode is selected, 0 otherwise - -> void sfall_func3("set_iface_tag_text", int tag, string text, int color) -- sets the text messages and colors for custom notification boxes to the interface without the need to add messages to intrface.msg and set up the font colors in ddraw.ini -- tag value is the same as used in show_iface_tag, hide_iface_tag, and is_iface_tag_active. The valid range is from 5 to (4 + the value of BoxBarCount in ddraw.ini) or the number of the last custom box added using the add_ifaca_tag function -- The text is limited to 19 characters -- available colors: 0 - green, 1 - red, 2 - white, 3 - yellow, 4 - dark yellow, 5 - blue, 6 - purple, 7 - dull pink - -> int sfall_func0("add_iface_tag") -- adds one custom box to the current boxes, and returns the number of the added tag (-1 if the tags limit is exceeded) -- The maximum number of boxes is limited to 126 tags - -> void sfall_func0("inventory_redraw") -> void sfall_func1("inventory_redraw", int invSide) -- redraws inventory list in the inventory/use inventory item on/loot/barter screens -- invSide specifies which side needs to be redrawn: 0 - the player, 1 - target (container/NPC in loot/barter screens), -1 - both sides (same as without argument) - -> void sfall_func3("item_make_explosive", int pid, int activePid, int damage) -> void sfall_func4("item_make_explosive", int pid, int activePid, int min, int max) -- makes the specified item (pid) an explosive item like Dynamite or Plastic Explosives -- activePid is for an item with an active timer, can be the same as the pid argument -- the item proto must be "Misc Item" type and have "Use" action flag -- min/max are the minimum and maximum explosion damage -- using the function on an item that is already set as an explosive will override its previous settings -- NOTE: this function does not work for pid's of Dynamite and Plastic Explosives - -> int sfall_func1("get_string_pointer", string text) -- returns a pointer to a string variable or to a text - -> void sfall_func1("dialog_message", string text) -- displays a message in the NPC response window in dialog or barter screen - -> int sfall_func1("get_current_inven_size", object) -- returns the current inventory size of the container or the critter - -> void sfall_func5("create_win", string winName, int x, int y, int width, int height) -> void sfall_func6("create_win", string winName, int x, int y, int width, int height, int flags) -- works just like vanilla CreateWin function, but creates a window with MoveOnTop flag if the flags argument is not specified, and allows to set additional flags for the created window -- MoveOnTop flag allows the created window to be placed on top of the game interface - -> void sfall_func3("set_can_rest_on_map", int mapNum, int elev, bool value) -- allows/disallows to rest on the map for the specified level, overrides the can_rest_here values in maps.txt -- mapNum is the map index from maps.txt -- passing -1 to the elev argument will set the rest value for all map elevations -- the set rest value will be stored in sfalldb.sav file (in savegame) - -> int sfall_func2("get_can_rest_on_map", int mapNum, int elev) -- returns the set rest value of the map after using the set_can_rest_on_map function -- returns -1 if the rest value of the map was not previously set (i.e. no data for the map in sfalldb.sav) -- the can_rest_here values from maps.txt are ignored - -> object sfall_func0("dialog_obj") -- returns a pointer to the object (critter) the player is having a conversation or bartering with - -> object sfall_func2("obj_under_cursor", bool onlyCritter, bool includeDude) -- returns the object under the cursor on the main game screen -- onlyCritter: True - only checks critters and ignores their cover (roof tiles, walls, scenery, etc.) - False - checks all objects (can't check critters under objects) -- passing False to the includeDude argument will ignore dude_obj -- NOTE: the function will always return 0 if the cursor is in movement mode (hexagon cursor) - -> object sfall_func0("loot_obj") -- returns a pointer to the target object (container or critter) of the loot screen - -> int sfall_func2("get_object_data", object, int offset) -- returns the data at the specified offset of an object (see OBJ_DATA_* constants in define_extra.h for offsets) - -> void sfall_func3("set_object_data", object, int offset, int data) -- sets the data at the specified offset of an object - -> int sfall_func2("get_object_ai_data", object, int aiParam) -- returns the setting value from the AI packet of an object (critter) -- use AI_CAP_* constants from define_extra.h for the aiParam argument to get AI value - -> void sfall_func0("art_cache_clear") -- clears the cache of FRM image files loaded into memory - -> void sfall_func1("npc_engine_level_up", bool toggle) -- enables/disables the engine function that increases the level of party members in the player leveling process -- if the engine function is disabled, the process of leveling up party members should be performed by script functions - -> void sfall_func3("set_drugs_data", int type, int pid, int value) -- overrides the parameters of drugs set in the configuration file (DrugsFile setting in ddraw.ini) -- type: 0 - changes the value of NumEffects for the drug (see Drugs.ini for the description of NumEffects) - 1 - changes the duration of the addiction effect for the drug (a value of 1 = one game minute) - -> int sfall_func1("set_unique_id", object) -> int sfall_func2("set_unique_id", object, int flag) -- assigns a unique ID number to the object and returns it. If a unique ID number has already been assigned to an object, then ID number is returned without reassignment -- items with unique IDs will not stack with other items of the same type in the inventory -- to just get the current ID number of an object, use sfall_func2("get_object_data", object, OBJ_DATA_ID) -- unique ID numbers are saved in your savegame, and have a range from 0x10000000 to 0x7FFFFFFF -- there is also a unique ID number range for the player and party members from 18000 to 83535 -- to assign a new ID number generated by the engine to the object (i.e. unassign a unique ID), call the function with two arguments and pass -1 for the flag argument - -> void sfall_func5("draw_image", string/int artFile/artId, int frame, int x, int y, bool noTransparent) -> void sfall_func6("draw_image_scaled", string/int artFile/artId, int frame, int x, int y, int width, int height) -- displays the specified PCX or FRM image in the active window created by vanilla CreateWin or sfall's create_win script function -- artFile/artId: path to the PCX/FRM file (e.g. "art\\inven\\5mmap.frm"), or its FRM ID number (e.g. 0x7000026, see specification of the FID format) -optional arguments: -- frame: frame number, the first frame starts from zero -- x/y: offset relative to the top-left corner of the window -- width/height: the new width/height to scale the image to. Pass -1 to either width or height to keep the aspect ratio when scaling -- noTransparent: pass True to display an image without transparent background -- NOTE: to omit optional arguments starting from the right, call the functions with different sfall_funcX (e.g. sfall_func4("draw_image", pathFile, frame, x, y)) -- if draw_image_scaled is called without x/y/width/height arguments, the image will be scaled to fit the window without transparent background - -> void sfall_func5("set_fake_perk_npc", object npc, string namePerk, int level, int image, string desc) -> void sfall_func5("set_fake_trait_npc", object npc, string nameTrait, int active, int image, string desc) -> void sfall_func5("set_selectable_perk_npc", object npc, string namePerk, int active, int image, string desc) -> int sfall_func2("has_fake_perk_npc", object npc, string namePerk) -> int sfall_func2("has_fake_trait_npc", object npc, string nameTrait) -- these functions are similar to has_fake_*/set_fake_*/set_selectable_perk functions, but apply to the specified party member NPC (including dude_obj) - -> int sfall_func1("add_extra_msg_file", string fileName) -> int sfall_func2("add_extra_msg_file", string fileName, int fileNumber) -- loads the custom message file, and returns the file ID number assigned to it in range from 0x3000 to 0x3FFF for the message_str_game function to get messages from the file -- fileName: the name of the custom message file (including the .msg extension) in "text\\game\" directory -- NOTE: if the msg file does not exist in the current language directory, the function will try to load it from "text\English\game\" directory -optional argument: -- fileNumber: the file ID number for the message_str_game function. The available range is from 0x2000 to 0x2FFF (see ExtraGameMsgFileList setting in ddraw.ini) - use fileNumber only if you want to add a message file without editing ddraw.ini or existing scripts to support the old way - -> void sfall_func2("unwield_slot", object critter, int slot) -- unequips an item from the specified slot for a critter or the player -- can take off player's equipped item when the inventory is opened, or the player is in the barter screen -- slot: 0 - armor slot, 1 - right slot, 2 - left slot (see INVEN_TYPE_* in define.h) - -> void sfall_func1("add_trait", int traitID) -- adds the specified trait to the player - -> int sfall_func0("get_inven_ap_cost") -- returns the current AP cost to access the inventory in combat - -> void sfall_func2("add_g_timer_event", int time, int fixedParam) -- adds a timer event that calls the timed_event_p_proc procedure in the current global script -- time: the number of ticks after which the event timer is triggered -- fixedParam: the value that is passed to the timed_event_p_proc procedure for the fixed_param function - -> void sfall_func0("remove_timer_event") -- clears all set timer events for the current global script - -> void sfall_func1("remove_timer_event", int fixedParam) -- removes all timer events with the specified 'fixedParam' value for the current global script - -> mixed sfall_func1("get_sfall_arg_at", int argNum) -- gets the value of hook argument with the specified argument number (first argument of hook starts from 0) - -> void sfall_func0("hide_window") -> void sfall_func1("hide_window", string winName) -- hides the specified or currently active (selected) script window -- winName: the window name, assigned to the window by the CreateWin/create_win function - -> void sfall_func0("show_window") -> void sfall_func1("show_window", string winName) -- displays the specified hidden script window or the one previously hidden with the sfall_func0("hide_window") function -- winName: the window name, assigned to the window by the CreateWin/create_win function - -> void sfall_func3("set_window_flag", string winName/int winID, int flag, bool value) -- changes the specified flag for the created script or game interface window -- winName: the window name, assigned to the window by the CreateWin/create_win function -- winID: the ID number of the interface or script window obtained with the get_window_under_mouse function, or 0 for the current game interface -- flag: the flag to change (see WIN_FLAG_* constants in define_extra.h) -- value: true - set the flag, false - unset the flag - -> int sfall_func1("get_text_width", string text) -- returns the text width in pixels for the currently set font - -> bool sfall_func2("string_compare", string str1, string str2) -> bool sfall_func3("string_compare", string str1, string str2, int codePage) -- compares two strings case-insensitive, and returns True if the two strings are matched -- codePage: code page number to properly compare national characters in the range 128-255 of the ASCII code table - available encodings: 1250-1252, 866 - -> string sfall_func3("string_format", string format, any val1, any val2, ...) -- formats given value using standard syntax of C printf function (google "printf" for format details). However it is limited to formatting up to 4 values -- formatting is only supported for %s and %d, and the format string is limited to 1024 characters - -> array sfall_func3("objects_in_radius", int tile, int radius, int elevation) -> array sfall_func4("objects_in_radius", int tile, int radius, int elevation, int type) -- returns an array of objects of a type (see OBJ_TYPE_* constants in define_extra.h) within the specified radius from the given tile -- passing -1 to the type argument or not specifying it will return all objects within the radius -- the radius is limited to 50 hexes - -> int sfall_func2("tile_by_position", int x, int y) -- returns the tile number at the x, y position relative to the top-left corner of the game screen -- if the position is outside of the range of tiles, it will return -1 - -> string sfall_func2("string_to_case", string text, int toCase) -- converts all letters in the given string to the specified case -- toCase: 0 - lowercase, 1 - uppercase -- NOTE: this function works only for English letters of A-Z/a-z - -> void sfall_func3("set_terrain_name", int x, int y, string name) -- overrides the terrain type name for the sub-tile on the world map by the specified coordinates - -> int sfall_func1("get_window_attribute", int winType) -> int sfall_func2("get_window_attribute", int winType, int attrType) -- returns the attribute of the specified interface window by the attrType argument -- winType: the type number of the interface window (see WINTYPE_* constants in sfall.h) -- attrType: 0 - checks and returns a value of 1 if the specified interface window is created by the game (same as without the argument) - 1 - X position, 2 - Y position (relative to the top-left corner of the game screen) - 3 - interface width size, 4 - interface height size - -1 - returns an associative array of keys (left, top, right, bottom) and values that define the position of the window rectangle - (use standard syntax to access array values, e.g. winRect.top, winRect.bottom) -- returns -1 if the specified attribute cannot be obtained - -> void sfall_func2("set_town_title", int areaID, string title) -- sets a floating text for a town on the world map when hovering the cursor over the player's marker -- areaID: the ID number of the town from city.txt - -> int sfall_func4("message_box", string message, int flags, int color1, int color2) -- creates a dialog box with text and returns the result of pressing the button: 0 - No (Escape), 1 - Yes/Done (Enter) -- returns -1 if for some reason the dialog box cannot be created -- message: the text in the dialog box. Use the '\n' control character to move text to a new line (example: "Hello\nWorld!") -optional arguments: -- flags: mode flags (see MSGBOX_* constants in define_extra.h). Pass -1 to skip setting the flags (default flags are NORMAL and YESNO) -- color1/color2: the color index in the game palette. color1 sets the text color for the first line, and color2 for all subsequent lines of text (default color is 145) - -> int sfall_func1("get_stat_min", int stat) -> int sfall_func1("get_stat_max", int stat) -> int sfall_func2("get_stat_min", int stat, bool who) -> int sfall_func2("get_stat_max", int stat, bool who) -- returns the maximum or minimum set value of the specified stat (see set_stat_max/min functions) -- who: 0 (false) or omitting the argument - returns the value of the player, 1 (true) - returns the value set for other critters - -> int sfall_func4("interface_art_draw", int winType, string artFile/int artID, int x, int y) -> int sfall_func5("interface_art_draw", int winType, string artFile/int artID, int x, int y, int frame) -> int sfall_func6("interface_art_draw", int winType, string artFile/int artID, int x, int y, int frame, array param) -- draws the specified PCX or FRM image in the game interface window, returns -1 on any error -- winType: the type number of the interface window (see WINTYPE_* constants in sfall.h) - this also takes the value of the flag (0x1000000) to prevent immediate redrawing of the interface window -- artFile/artId: path to the PCX/FRM file (e.g. "art\\inven\\5mmap.frm"), or its FRM ID number (e.g. 0x7000026, see specification of the FID format) -- x/y: offset relative to the top-left corner of the window -optional arguments: -- frame: frame number, the first frame starts from zero -- param: an array which specifies additional parameters, where: - index 0 - sprite direction for multi-directional FRM - index 1/index 2 - the new width/height to scale the image to. Pass -1 to use the original width/height - -> int sfall_func5("interface_print", string text, int winType, int x, int y, int color) -> int sfall_func6("interface_print", string text, int winType, int x, int y, int color, int width) -- displays the text in the specified interface window with the current font. Use vanilla SetFont function to set the font -- returns the count of lines printed, or -1 on any error -- text: the text to be printed. Use the '\n' control character to move text to a new line (example: "Hello\nWorld!") -- winType: the type number of the interface window (see WINTYPE_* constants in sfall.h) -- x/y: offset relative to the top-left corner of the window -- color: the color index in the game palette. Pass 0 if the text color was previously set by vanilla SetTextColor function - it can also take additional flags (via bwor) for displaying text: - 0x0010000 - adds a shadow to the text, the 'textshadow' compiler constant - 0x1000000 - prevents immediate redrawing of the interface window, the 'textdirect' compiler constant (works the other way around) - 0x2000000 - fills the background of the text with black color, the 'textnofill' compiler constant (works the other way around) -- width (optional): the maximum width of the text. The text will be wrapped to fit within the specified width - -> mixed sfall_func0("combat_data") -- returns a pointer to the C_ATTACK_* data for the current combat attack process (see defined constants in define_extra.h) -- can be used in conjunction with the get_object_data and set_object_data functions - example: sfall_func3("set_object_data", sfall_func0("combat_data"), C_ATTACK_UNUSED, 255); - -> int sfall_func0("win_fill_color") -> int sfall_func5("win_fill_color", int x, int y, int width, int height, int color) -- fills the rectangle area of the currently selected script window with the specified color, or clears the window with transparent (index 0) color (call the function without arguments) -- color: the color index in the game palette (from 0 to 255) - -> int sfall_func2("interface_overlay", int winType, int mode) -> int sfall_func6("interface_overlay", int winType, 2, int x, int y, int width, int height) -- creates an additional drawing surface above the graphic layer of the specified interface window. All subsequent calls of interface_art_draw and interface_print functions will draw on it -- winType: the type number of the interface window (see WINTYPE_* constants in sfall.h) -- mode: 1 - creates a new overlay surface - 2 - clears the overlay area or the specified rectangle defined by the x, y, width, height arguments - 0 - destroys the created overlay surface (frees up the memory allocated to the surface) - ------------------------- ------- MORE INFO ------- ------------------------- - -See other documentation files (arrays.txt, hookscripts.txt) for related functions reference. - diff --git a/artifacts/scripting/sfall opcode list.md b/artifacts/scripting/sfall opcode list.md new file mode 100644 index 00000000..e39aa2b6 --- /dev/null +++ b/artifacts/scripting/sfall opcode list.md @@ -0,0 +1,368 @@ + +_^ - These functions require AllowUnsafeScripting to be enabled in ddraw.ini_ + +0x8156 - `int read_byte(int address)`
+0x8157 - `int read_short(int address)`
+0x8158 - `int read_int(int address)`
+0x8159 - `string read_string(int address)`
+ +^ 0x81cf - `void write_byte(int address, int value)`
+^ 0x81d0 - `void write_short(int address, int value)`
+^ 0x81d1 - `void write_int(int address, int value)`
+^ 0x821b - `void write_string(int address, string value)`
+ +^ 0x81d2 - `void call_offset_v0(int address)`
+^ 0x81d3 - `void call_offset_v1(int address, int arg1)`
+^ 0x81d4 - `void call_offset_v2(int address, int arg1, int arg2)`
+^ 0x81d5 - `void call_offset_v3(int address, int arg1, int arg2, int arg3)`
+^ 0x81d6 - `void call_offset_v4(int address, int arg1, int arg2, int arg3, int arg4)`
+^ 0x81d7 - `int call_offset_r0(int address)`
+^ 0x81d8 - `int call_offset_r1(int address, int arg1)`
+^ 0x81d9 - `int call_offset_r2(int address, int arg1, int arg2)`
+^ 0x81da - `int call_offset_r3(int address, int arg1, int arg2, int arg3)`
+^ 0x81db - `int call_offset_r4(int address, int arg1, int arg2, int arg3, int arg4)`
+ +0x815a - `void set_pc_base_stat(int StatID, int value)`
+0x815b - `void set_pc_extra_stat(int StatID, int value)`
+0x815c - `int get_pc_base_stat(int StatID)`
+0x815d - `int get_pc_extra_stat(int StatID)`
+ +0x815e - `void set_critter_base_stat(object, int StatID, int value)`
+0x815f - `void set_critter_extra_stat(object, int StatID, int value)`
+0x8160 - `int get_critter_base_stat(object, int StatID)`
+0x8161 - `int get_critter_extra_stat(object, int StatID)`
+0x8242 - `void set_critter_skill_points(int critter, int skill, int value)`
+0x8243 - `int get_critter_skill_points(int critter, int skill)`
+0x8244 - `void set_available_skill_points(int value)`
+0x8245 - `int get_available_skill_points()`
+0x8246 - `void mod_skill_points_per_level(int value)`
+ +0x81b4 - `void set_stat_max(int stat, int value)`
+0x81b5 - `void set_stat_min(int stat, int value)`
+0x81b7 - `void set_pc_stat_max(int stat, int value)`
+0x81b8 - `void set_pc_stat_min(int stat, int value)`
+0x81b9 - `void set_npc_stat_max(int stat, int value)`
+0x81ba - `void set_npc_stat_min(int stat, int value)`
+ +0x816b - `int input_funcs_available()`
+0x816c - `int key_pressed(int dxScancode)`
+0x8162 - `void tap_key(int dxScancode)`
+0x821c - `int get_mouse_x()`
+0x821d - `int get_mouse_y()`
+0x821e - `int get_mouse_buttons()`
+0x821f - `int get_window_under_mouse()`
+ +0x8163 - `int get_year()`
+ +0x8164 - `bool game_loaded()`
+ +0x8165 - `bool graphics_funcs_available()`
+0x8166 - `int load_shader(string path)`
+0x8167 - `void free_shader(int ID)`
+0x8168 - `void activate_shader(int ID)`
+0x8169 - `void deactivate_shader(int ID)`
+0x816d - `void set_shader_int(int ID, string param, int value)`
+0x816e - `void set_shader_float(int ID, string param, float value)`
+0x816f - `void set_shader_vector(int ID, string param, float f1, float f2, float f3, float f4)`
+0x81ad - `int get_shader_version()`
+0x81ae - `void set_shader_mode(int mode)`
+0x81b0 - `void force_graphics_refresh(bool enabled)`
+0x81b1 - `int get_shader_texture(int ID, int texture)`
+0x81b2 - `void set_shader_texture(int ID, string param, int texID)`
+ +0x816a - `void set_global_script_repeat(int frames)`
+0x819b - `void set_global_script_type(int type)`
+0x819c - `int available_global_script_types()`
+ +0x8170 - `bool in_world_map()`
+ +0x8171 - `void force_encounter(int map)`
+0x8229 - `void force_encounter_with_flags(int map, int flags)`
+0x822a - `void set_map_time_multi(float multi)`
+ +0x8172 - `void set_world_map_pos(int x, int y)`
+0x8173 - `int get_world_map_x_pos()`
+0x8174 - `int get_world_map_y_pos()`
+ +0x8175 - `void set_dm_model(string name)`
+0x8176 - `void set_df_model(string name)`
+0x8177 - `void set_movie_path(string filename, int movieid)`
+ +0x8178 - `void set_perk_image(int perkID, int value)`
+0x8179 - `void set_perk_ranks(int perkID, int value)`
+0x817a - `void set_perk_level(int perkID, int value)`
+0x817b - `void set_perk_stat(int perkID, int value)`
+0x817c - `void set_perk_stat_mag(int perkID, int value)`
+0x817d - `void set_perk_skill1(int perkID, int value)`
+0x817e - `void set_perk_skill1_mag(int perkID, int value)`
+0x817f - `void set_perk_type(int perkID, int value)`
+0x8180 - `void set_perk_skill2(int perkID, int value)`
+0x8181 - `void set_perk_skill2_mag(int perkID, int value)`
+0x8182 - `void set_perk_str(int perkID, int value)`
+0x8183 - `void set_perk_per(int perkID, int value)`
+0x8184 - `void set_perk_end(int perkID, int value)`
+0x8185 - `void set_perk_chr(int perkID, int value)`
+0x8196 - `void set_perk_int(int perkID, int value)`
+0x8187 - `void set_perk_agl(int perkID, int value)`
+0x8188 - `void set_perk_lck(int perkID, int value)`
+0x8189 - `void set_perk_name(int perkID, string value)`
+0x818a - `void set_perk_desc(int perkID, string value)`
+0x8247 - `void set_perk_freq(int value)`
+ +0x818b - `void set_pipboy_available(int available)`
+ +0x818c - `int get_kill_counter(int critterType)`
+0x818d - `void mod_kill_counter(int critterType, int amount)`
+ +0x818e - `int get_perk_owed()`
+0x818f - `void set_perk_owed(int value)`
+0x8190 - `int get_perk_available(int perk)`
+ +0x8191 - `int get_critter_current_ap(object critter)`
+0x8192 - `void set_critter_current_ap(object critter, int ap)`
+ +0x8193 - `int active_hand()`
+0x8194 - `void toggle_active_hand()`
+ +0x8195 - `void set_weapon_knockback(object weapon, int type, int/float value)`
+0x8196 - `void set_target_knockback(object critter, int type, int/float value)`
+0x8197 - `void set_attacker_knockback(object critter, int type, int/float value)`
+0x8198 - `void remove_weapon_knockback(object weapon)`
+0x8199 - `void remove_target_knockback(object critter)`
+0x819a - `void remove_attacker_knockback(object critter)`
+ +0x819d - `void set_sfall_global(string/int varname, int/float value)`
+0x819e - `int get_sfall_global_int(string/int varname)`
+0x819f - `float get_sfall_global_float(string/int varname)`
+0x822d - `int create_array(int element_count, int flags)`
+0x822e - `void set_array(int array, any element, any value)`
+0x822f - `any get_array(int array, any element)`
+0x8230 - `void free_array(int array)`
+0x8231 - `int len_array(int array)`
+0x8232 - `void resize_array(int array, int new_element_count)`
+0x8233 - `int temp_array(int element_count, int flags)`
+0x8234 - `void fix_array(int array)`
+0x8239 - `int scan_array(int array, int/float var)`
+0x8256 - `int array_key(int array, int index)`
+0x8257 - `int arrayexpr(any key, any value)`
+0x8254 - `void save_array(any key, int array)`
+0x8255 - `int load_array(any key)`
+ +0x81a0 - `void set_pickpocket_max(int percentage)`
+0x81a1 - `void set_hit_chance_max(int percentage)`
+0x81a2 - `void set_skill_max(int value)`
+0x81aa - `void set_xp_mod(int percentage)`
+0x81ab - `void set_perk_level_mod(int levels)`
+ +0x81c5 - `void set_critter_hit_chance_mod(object, int max, int mod)`
+0x81c6 - `void set_base_hit_chance_mod(int max, int mod)`
+0x81c7 - `void set_critter_skill_mod(object, int max)`
+0x81c8 - `void set_base_skill_mod(int max)`
+0x81c9 - `void set_critter_pickpocket_mod(object, int max, int mod)`
+0x81ca - `void set_base_pickpocket_mod(int max, int mod)`
+ +0x81a3 - `int eax_available()`
+0x81a4 - `void set_eax_environment(int environment)`
+ +0x81a5 - `void inc_npc_level(int pid/string name)`
+0x8241 - `int get_npc_level(int pid/string name)`
+ +0x81a6 - `int get_viewport_x()`
+0x81a7 - `int get_viewport_y()`
+0x81a8 - `void set_viewport_x(int view_x)`
+0x81a9 - `void set_viewport_y(int view_y)`
+ +0x81ac - `int get_ini_setting(string setting)`
+0x81eb - `string get_ini_string(string setting)`
+ +0x81af - `int get_game_mode()`
+ +0x81b3 - `int get_uptime()`
+ +0x81b6 - `void set_car_current_town(int town)`
+ +0x81bb - `void set_fake_perk(string name, int level, int image, string desc)`
+0x81bc - `void set_fake_trait(string name, int active, int image, string desc)`
+0x81bd - `void set_selectable_perk(string name, int active, int image, string desc)`
+0x81be - `void set_perkbox_title(string title)`
+0x81bf - `void hide_real_perks()`
+0x81c0 - `void show_real_perks()`
+0x81c1 - `int has_fake_perk(string name/int extraPerkID)`
+0x81c2 - `int has_fake_trait(string name)`
+0x81c3 - `void perk_add_mode(int type)`
+0x81c4 - `void clear_selectable_perks()`
+0x8225 - `void remove_trait(int traitID)`
+ +0x81cb - `void set_pyromaniac_mod(int bonus)`
+0x81cc - `void apply_heaveho_fix()`
+0x81cd - `void set_swiftlearner_mod(int bonus)`
+0x81ce - `void set_hp_per_level_mod(int mod)`
+ +0x81dc - `void show_iface_tag(int tag)`
+0x81dd - `void hide_iface_tag(int tag)`
+0x81de - `int is_iface_tag_active(int tag)`
+ +0x81df - `int get_bodypart_hit_modifier(int bodypart)`
+0x81e0 - `void set_bodypart_hit_modifier(int bodypart, int value)`
+ +0x81e1 - `void set_critical_table(int crittertype, int bodypart, int level, int valuetype, int value)`
+0x81e2 - `int get_critical_table(int crittertype, int bodypart, int level, int valuetype)`
+0x81e3 - `void reset_critical_table(int crittertype, int bodypart, int level, int valuetype)`
+ +0x81e4 - `int get_sfall_arg()`
+0x823c - `array get_sfall_args()`
+0x823d - `void set_sfall_arg(int argnum, int value)`
+0x81e5 - `void set_sfall_return(int value)`
+0x81ea - `int init_hook()`
+ +0x81e6 - `void set_unspent_ap_bonus(int multiplier)`
+0x81e7 - `int get_unspent_ap_bonus()`
+0x81e8 - `void set_unspent_ap_perk_bonus(int multiplier)`
+0x81e9 - `int get_unspent_ap_perk_bonus()`
+ +0x81ec - `float sqrt(float)`
+0x81ed - `int/float abs(int/float)`
+0x81ee - `float sin(float)`
+0x81ef - `float cos(float)`
+0x81f0 - `float tan(float)`
+0x81f1 - `float arctan(float x, float y)`
+0x8263 - `^` operator (exponentiation)
+0x8264 - `float log(float)`
+0x8265 - `float exponent(float)`
+0x8266 - `int ceil(float)`
+0x8267 - `int round(float)`
+ +0x81f2 - `void set_palette(string path)`
+ +0x81f3 - `void remove_script(object)`
+0x81f4 - `void set_script(object, int scriptid)`
+0x81f5 - `int get_script(object)`
+ +0x81f6 - `int nb_create_char()`
+ +0x81f7 - `int fs_create(string path, int size)`
+0x81f8 - `int fs_copy(string path, string source)`
+0x81f9 - `int fs_find(string path)`
+0x81fa - `void fs_write_byte(int id, int data)`
+0x81fb - `void fs_write_short(int id, int data)`
+0x81fc - `void fs_write_int(int id, int data)`
+0x81fd - `void fs_write_float(int id, int data)`
+0x81fe - `void fs_write_string(int id, string data)`
+0x8208 - `void fs_write_bstring(int id, string data)`
+0x8209 - `int fs_read_byte(int id)`
+0x820a - `int fs_read_short(int id)`
+0x820b - `int fs_read_int(int id)`
+0x820c - `float fs_read_float(int id)`
+0x81ff - `void fs_delete(int id)`
+0x8200 - `int fs_size(int id)`
+0x8201 - `int fs_pos(int id)`
+0x8202 - `void fs_seek(int id, int pos)`
+0x8203 - `void fs_resize(int id, int size)`
+ +0x8204 - `int get_proto_data(int pid, int offset)`
+0x8205 - `void set_proto_data(int pid, int offset, int value)`
+ +0x8206 - `void set_self(object)`
+0x8207 - `void register_hook(int hook)`
+ +0x820d - `int list_begin(int type)`
+0x820e - `int list_next(int listid)`
+0x820f - `void list_end(int listid)`
+0x8236 - `array list_as_array(int type)`
+ +0x8210 - `int sfall_ver_major()`
+0x8211 - `int sfall_ver_minor()`
+0x8212 - `int sfall_ver_build()`
+ +0x8213 - `void hero_select_win(int)`
+0x8214 - `void set_hero_race(int style)`
+0x8215 - `void set_hero_style(int style)`
+ +0x8216 - `void set_critter_burst_disable(object critter, int disable)`
+ +0x8217 - `int get_weapon_ammo_pid(object weapon)`
+0x8218 - `void set_weapon_ammo_pid(object weapon, int pid)`
+0x8219 - `int get_weapon_ammo_count(object weapon)`
+0x821a - `void set_weapon_ammo_count(object weapon, int count)`
+ +0x8220 - `int get_screen_width()`
+0x8221 - `int get_screen_height()`
+ +0x8222 - `void stop_game()`
+0x8223 - `void resume_game()`
+0x8224 - `void create_message_window(string message)`
+ +0x8226 - `int get_light_level()`
+ +0x8227 - `void refresh_pc_art()`
+ +0x8228 - `int get_attack_type()`
+ +0x822b - `int play_sfall_sound(string file, int mode)`
+0x822c - `void stop_sfall_sound(int soundID)`
+ +0x8235 - `array string_split(string string, string split)`
+0x8237 - `int atoi(string string)`
+0x8238 - `float atof(string string)`
+0x824e - `string substr(string string, int start, int length)`
+0x824f - `int strlen(string string)`
+0x8250 - `string sprintf(string format, any value)`
+0x8251 - `int charcode(string string)`
+0x8253 - `int typeof(any value)`
+ +0x823a - `int get_tile_fid(int tile)`
+ +0x823b - `int modified_ini()`
+ +0x823e - `void force_aimed_shots(int pid)`
+0x823f - `void disable_aimed_shots(int pid)`
+ +0x8240 - `void mark_movie_played(int id)`
+ +0x8248 - `object get_last_target(object critter)`
+0x8249 - `object get_last_attacker(object critter)`
+0x824a - `void block_combat(int enable)`
+ +0x824b - `int tile_under_cursor()`
+0x824c - `int gdialog_get_barter_mod()`
+0x824d - `void set_inven_ap_cost()`
+ +0x825c - `void reg_anim_combat_check(int enable)`
+0x825a - `void reg_anim_destroy(object object)`
+0x825b - `void reg_anim_animate_and_hide(object object, int animID, int delay)`
+0x825d - `void reg_anim_light(object object, int radius, int delay)`
+0x825e - `void reg_anim_change_fid(object object, int FID, int delay)`
+0x825f - `void reg_anim_take_out(object object, int holdFrameID, int delay)`
+0x8260 - `void reg_anim_turn_towards(object object, int tile/targetObj, int delay)`
+ +0x8261 - `int metarule2_explosions(object object)`
+ +0x8262 - `void register_hook_proc(int hook, procedure proc)`
+ +0x826b - `string message_str_game(int fileId, int messageId)`
+0x826c - `int sneak_success()`
+0x826d - `int tile_light(int elevation, int tileNum)`
+0x826e - `object obj_blocking_line(object objFrom, int tileTo, int blockingType)`
+0x826f - `object obj_blocking_tile(int tileNum, int elevation, int blockingType)`
+0x8270 - `array tile_get_objs(int tileNum, int elevation)`
+0x8271 - `array party_member_list(int includeHidden)`
+0x8272 - `array path_find_to(object objFrom, int tileTo, int blockingType)`
+0x8273 - `object create_spatial(int scriptID, int tile, int elevation, int radius)`
+0x8274 - `int art_exists(int artFID)`
+0x8275 - `int obj_is_carrying_obj(object invenObj, object itemObj)`
+ +0x8276 - `any sfall_func0(string funcName)`
+0x8277 - `any sfall_func1(string funcName, arg1)`
+0x8278 - `any sfall_func2(string funcName, arg1, arg2)`
+0x8279 - `any sfall_func3(string funcName, arg1, arg2, arg3)`
+0x827a - `any sfall_func4(string funcName, arg1, arg2, arg3, arg4)`
+0x827b - `any sfall_func5(string funcName, arg1, arg2, arg3, arg4, arg5)`
+0x827c - `any sfall_func6(string funcName, arg1, arg2, arg3, arg4, arg5, arg6)`
+ +0x827d - `void register_hook_proc_spec(int hook, procedure proc)`
+0x827e - `void reg_anim_callback(procedure proc)`
+ +0x827f - `div` operator (unsigned integer division)
+ +0x8280 - `any sfall_func7(string funcName, arg1, arg2, arg3, arg4, arg5, arg6, arg7)`
+0x8281 - `any sfall_func8(string funcName, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8)`
diff --git a/artifacts/scripting/sfall opcode list.txt b/artifacts/scripting/sfall opcode list.txt index 7bdaac29..eda12054 100644 --- a/artifacts/scripting/sfall opcode list.txt +++ b/artifacts/scripting/sfall opcode list.txt @@ -1,24 +1,26 @@ +^ - These functions require AllowUnsafeScripting to be enabled in ddraw.ini + 0x8156 - int read_byte(int address) 0x8157 - int read_short(int address) 0x8158 - int read_int(int address) 0x8159 - string read_string(int address) -*0x81cf - void write_byte(int address, int value) -*0x81d0 - void write_short(int address, int value) -*0x81d1 - void write_int(int address, int value) -*0x821b - void write_string(int address, string value) +^ 0x81cf - void write_byte(int address, int value) +^ 0x81d0 - void write_short(int address, int value) +^ 0x81d1 - void write_int(int address, int value) +^ 0x821b - void write_string(int address, string value) -*0x81d2 - void call_offset_v0(int address) -*0x81d3 - void call_offset_v1(int address, int arg1) -*0x81d4 - void call_offset_v2(int address, int arg1, int arg2) -*0x81d5 - void call_offset_v3(int address, int arg1, int arg2, int arg3) -*0x81d6 - void call_offset_v4(int address, int arg1, int arg2, int arg3, int arg4) -*0x81d7 - int call_offset_r0(int address) -*0x81d8 - int call_offset_r1(int address, int arg1) -*0x81d9 - int call_offset_r2(int address, int arg1, int arg2) -*0x81da - int call_offset_r3(int address, int arg1, int arg2, int arg3) -*0x81db - int call_offset_r4(int address, int arg1, int arg2, int arg3, int arg4) +^ 0x81d2 - void call_offset_v0(int address) +^ 0x81d3 - void call_offset_v1(int address, int arg1) +^ 0x81d4 - void call_offset_v2(int address, int arg1, int arg2) +^ 0x81d5 - void call_offset_v3(int address, int arg1, int arg2, int arg3) +^ 0x81d6 - void call_offset_v4(int address, int arg1, int arg2, int arg3, int arg4) +^ 0x81d7 - int call_offset_r0(int address) +^ 0x81d8 - int call_offset_r1(int address, int arg1) +^ 0x81d9 - int call_offset_r2(int address, int arg1, int arg2) +^ 0x81da - int call_offset_r3(int address, int arg1, int arg2, int arg3) +^ 0x81db - int call_offset_r4(int address, int arg1, int arg2, int arg3, int arg4) 0x815a - void set_pc_base_stat(int StatID, int value) 0x815b - void set_pc_extra_stat(int StatID, int value) @@ -192,7 +194,7 @@ 0x8225 - void remove_trait(int traitID) 0x81cb - void set_pyromaniac_mod(int bonus) -0x81cc - void apply_heaveho_fix +0x81cc - void apply_heaveho_fix() 0x81cd - void set_swiftlearner_mod(int bonus) 0x81ce - void set_hp_per_level_mod(int mod) @@ -292,9 +294,9 @@ 0x8226 - int get_light_level() -0x8227 - void refresh_pc_art +0x8227 - void refresh_pc_art() -0x8228 - int get_attack_type +0x8228 - int get_attack_type() 0x822b - int play_sfall_sound(string file, int mode) 0x822c - void stop_sfall_sound(int soundID) @@ -321,9 +323,9 @@ 0x8249 - object get_last_attacker(object critter) 0x824a - void block_combat(int enable) -0x824b - int tile_under_cursor -0x824c - int gdialog_get_barter_mod -0x824d - void set_inven_ap_cost +0x824b - int tile_under_cursor() +0x824c - int gdialog_get_barter_mod() +0x824d - void set_inven_ap_cost() 0x825c - void reg_anim_combat_check(int enable) 0x825a - void reg_anim_destroy(object object) @@ -338,7 +340,7 @@ 0x8262 - void register_hook_proc(int hook, procedure proc) 0x826b - string message_str_game(int fileId, int messageId) -0x826c - int sneak_success +0x826c - int sneak_success() 0x826d - int tile_light(int elevation, int tileNum) 0x826e - object obj_blocking_line(object objFrom, int tileTo, int blockingType) 0x826f - object obj_blocking_tile(int tileNum, int elevation, int blockingType) @@ -364,5 +366,3 @@ 0x8280 - any sfall_func7(string funcName, arg1, arg2, arg3, arg4, arg5, arg6, arg7) 0x8281 - any sfall_func8(string funcName, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) - -* These functions require AllowUnsafeScripting to be enabled in ddraw.ini diff --git a/artifacts/sfall.dat b/artifacts/sfall.dat index fa5c1281..8ed060f7 100644 Binary files a/artifacts/sfall.dat and b/artifacts/sfall.dat differ diff --git a/artifacts/sfall_ru.dat b/artifacts/sfall_ru.dat new file mode 100644 index 00000000..4d617324 Binary files /dev/null and b/artifacts/sfall_ru.dat differ diff --git a/artifacts/sfall_zh.dat b/artifacts/sfall_zh.dat new file mode 100644 index 00000000..02f42373 Binary files /dev/null and b/artifacts/sfall_zh.dat differ diff --git a/docs/404.html b/docs/404.html new file mode 100644 index 00000000..c472b4ea --- /dev/null +++ b/docs/404.html @@ -0,0 +1,24 @@ +--- +layout: default +--- + + + +
+

404

+ +

Page not found :(

+

The requested page could not be found.

+
diff --git a/docs/CNAME b/docs/CNAME new file mode 100644 index 00000000..f6d9b101 --- /dev/null +++ b/docs/CNAME @@ -0,0 +1 @@ +sfall.bgforge.net diff --git a/docs/Gemfile b/docs/Gemfile new file mode 100644 index 00000000..d5e88f5f --- /dev/null +++ b/docs/Gemfile @@ -0,0 +1,27 @@ +source "https://rubygems.org" + +# Hello! This is where you manage which Jekyll version is used to run. +# When you want to use a different version, change it below, save the +# file and run `bundle install`. Run Jekyll with `bundle exec`, like so: +# +# bundle exec jekyll serve +# +# This will help ensure the proper Jekyll version is running. +# Happy Jekylling! + +# If you want to use GitHub Pages, remove the "gem "jekyll"" above and +# uncomment the line below. To upgrade, run `bundle update github-pages`. +gem "github-pages", group: :jekyll_plugins +gem "jekyll-remote-theme" + +# If you have any plugins, put them here! +group :jekyll_plugins do + gem "jekyll-feed", "~> 0.6" + gem 'jekyll-analytics' +end + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem "tzinfo-data", platforms: [:mingw, :mswin, :x64_mingw, :jruby] + +# Performance-booster for watching directories on Windows +gem "wdm", "~> 0.1.0" if Gem.win_platform? diff --git a/docs/Gemfile.lock b/docs/Gemfile.lock new file mode 100644 index 00000000..01778947 --- /dev/null +++ b/docs/Gemfile.lock @@ -0,0 +1,230 @@ +GEM + remote: https://rubygems.org/ + specs: + activesupport (4.2.9) + i18n (~> 0.7) + minitest (~> 5.1) + thread_safe (~> 0.3, >= 0.3.4) + tzinfo (~> 1.1) + addressable (2.6.0) + public_suffix (>= 2.0.2, < 4.0) + coffee-script (2.4.1) + coffee-script-source + execjs + coffee-script-source (1.11.1) + colorator (1.1.0) + concurrent-ruby (1.1.5) + ethon (0.12.0) + ffi (>= 1.3.0) + execjs (2.7.0) + faraday (0.15.4) + multipart-post (>= 1.2, < 3) + ffi (1.11.1) + forwardable-extended (2.6.0) + gemoji (3.0.1) + github-pages (170) + activesupport (= 4.2.9) + github-pages-health-check (= 1.3.5) + jekyll (= 3.6.2) + jekyll-avatar (= 0.5.0) + jekyll-coffeescript (= 1.0.2) + jekyll-default-layout (= 0.1.4) + jekyll-feed (= 0.9.2) + jekyll-gist (= 1.4.1) + jekyll-github-metadata (= 2.9.3) + jekyll-mentions (= 1.2.0) + jekyll-optional-front-matter (= 0.3.0) + jekyll-paginate (= 1.1.0) + jekyll-readme-index (= 0.2.0) + jekyll-redirect-from (= 0.12.1) + jekyll-relative-links (= 0.5.2) + jekyll-sass-converter (= 1.5.0) + jekyll-seo-tag (= 2.3.0) + jekyll-sitemap (= 1.1.1) + jekyll-swiss (= 0.4.0) + jekyll-theme-architect (= 0.1.0) + jekyll-theme-cayman (= 0.1.0) + jekyll-theme-dinky (= 0.1.0) + jekyll-theme-hacker (= 0.1.0) + jekyll-theme-leap-day (= 0.1.0) + jekyll-theme-merlot (= 0.1.0) + jekyll-theme-midnight (= 0.1.0) + jekyll-theme-minimal (= 0.1.0) + jekyll-theme-modernist (= 0.1.0) + jekyll-theme-primer (= 0.5.2) + jekyll-theme-slate (= 0.1.0) + jekyll-theme-tactile (= 0.1.0) + jekyll-theme-time-machine (= 0.1.0) + jekyll-titles-from-headings (= 0.5.0) + jemoji (= 0.8.1) + kramdown (= 1.14.0) + liquid (= 4.0.0) + listen (= 3.0.6) + mercenary (~> 0.3) + minima (= 2.1.1) + rouge (= 2.2.1) + terminal-table (~> 1.4) + github-pages-health-check (1.3.5) + addressable (~> 2.3) + net-dns (~> 0.8) + octokit (~> 4.0) + public_suffix (~> 2.0) + typhoeus (~> 0.7) + html-pipeline (2.11.0) + activesupport (>= 2) + nokogiri (>= 1.4) + i18n (0.9.5) + concurrent-ruby (~> 1.0) + jekyll (3.6.2) + addressable (~> 2.4) + colorator (~> 1.0) + jekyll-sass-converter (~> 1.0) + jekyll-watch (~> 1.1) + kramdown (~> 1.14) + liquid (~> 4.0) + mercenary (~> 0.3.3) + pathutil (~> 0.9) + rouge (>= 1.7, < 3) + safe_yaml (~> 1.0) + jekyll-analytics (0.1.11) + jekyll-avatar (0.5.0) + jekyll (~> 3.0) + jekyll-coffeescript (1.0.2) + coffee-script (~> 2.2) + coffee-script-source (~> 1.11.1) + jekyll-default-layout (0.1.4) + jekyll (~> 3.0) + jekyll-feed (0.9.2) + jekyll (~> 3.3) + jekyll-gist (1.4.1) + octokit (~> 4.2) + jekyll-github-metadata (2.9.3) + jekyll (~> 3.1) + octokit (~> 4.0, != 4.4.0) + jekyll-mentions (1.2.0) + activesupport (~> 4.0) + html-pipeline (~> 2.3) + jekyll (~> 3.0) + jekyll-optional-front-matter (0.3.0) + jekyll (~> 3.0) + jekyll-paginate (1.1.0) + jekyll-readme-index (0.2.0) + jekyll (~> 3.0) + jekyll-redirect-from (0.12.1) + jekyll (~> 3.3) + jekyll-relative-links (0.5.2) + jekyll (~> 3.3) + jekyll-remote-theme (0.4.0) + addressable (~> 2.0) + jekyll (~> 3.5) + rubyzip (>= 1.2.1, < 3.0) + jekyll-sass-converter (1.5.0) + sass (~> 3.4) + jekyll-seo-tag (2.3.0) + jekyll (~> 3.3) + jekyll-sitemap (1.1.1) + jekyll (~> 3.3) + jekyll-swiss (0.4.0) + jekyll-theme-architect (0.1.0) + jekyll (~> 3.5) + jekyll-seo-tag (~> 2.0) + jekyll-theme-cayman (0.1.0) + jekyll (~> 3.5) + jekyll-seo-tag (~> 2.0) + jekyll-theme-dinky (0.1.0) + jekyll (~> 3.5) + jekyll-seo-tag (~> 2.0) + jekyll-theme-hacker (0.1.0) + jekyll (~> 3.5) + jekyll-seo-tag (~> 2.0) + jekyll-theme-leap-day (0.1.0) + jekyll (~> 3.5) + jekyll-seo-tag (~> 2.0) + jekyll-theme-merlot (0.1.0) + jekyll (~> 3.5) + jekyll-seo-tag (~> 2.0) + jekyll-theme-midnight (0.1.0) + jekyll (~> 3.5) + jekyll-seo-tag (~> 2.0) + jekyll-theme-minimal (0.1.0) + jekyll (~> 3.5) + jekyll-seo-tag (~> 2.0) + jekyll-theme-modernist (0.1.0) + jekyll (~> 3.5) + jekyll-seo-tag (~> 2.0) + jekyll-theme-primer (0.5.2) + jekyll (~> 3.5) + jekyll-github-metadata (~> 2.9) + jekyll-seo-tag (~> 2.2) + jekyll-theme-slate (0.1.0) + jekyll (~> 3.5) + jekyll-seo-tag (~> 2.0) + jekyll-theme-tactile (0.1.0) + jekyll (~> 3.5) + jekyll-seo-tag (~> 2.0) + jekyll-theme-time-machine (0.1.0) + jekyll (~> 3.5) + jekyll-seo-tag (~> 2.0) + jekyll-titles-from-headings (0.5.0) + jekyll (~> 3.3) + jekyll-watch (1.5.1) + listen (~> 3.0) + jemoji (0.8.1) + activesupport (~> 4.0, >= 4.2.9) + gemoji (~> 3.0) + html-pipeline (~> 2.2) + jekyll (>= 3.0) + kramdown (1.14.0) + liquid (4.0.0) + listen (3.0.6) + rb-fsevent (>= 0.9.3) + rb-inotify (>= 0.9.7) + mercenary (0.3.6) + mini_portile2 (2.4.0) + minima (2.1.1) + jekyll (~> 3.3) + minitest (5.11.3) + multipart-post (2.1.1) + net-dns (0.9.0) + nokogiri (1.10.3) + mini_portile2 (~> 2.4.0) + octokit (4.14.0) + sawyer (~> 0.8.0, >= 0.5.3) + pathutil (0.16.2) + forwardable-extended (~> 2.6) + public_suffix (2.0.5) + rb-fsevent (0.10.3) + rb-inotify (0.10.0) + ffi (~> 1.0) + rouge (2.2.1) + rubyzip (1.2.3) + safe_yaml (1.0.5) + sass (3.7.4) + sass-listen (~> 4.0.0) + sass-listen (4.0.0) + rb-fsevent (~> 0.9, >= 0.9.4) + rb-inotify (~> 0.9, >= 0.9.7) + sawyer (0.8.2) + addressable (>= 2.3.5) + faraday (> 0.8, < 2.0) + terminal-table (1.8.0) + unicode-display_width (~> 1.1, >= 1.1.1) + thread_safe (0.3.6) + typhoeus (0.8.0) + ethon (>= 0.8.0) + tzinfo (1.2.5) + thread_safe (~> 0.1) + unicode-display_width (1.6.0) + +PLATFORMS + ruby + +DEPENDENCIES + github-pages + jekyll-analytics + jekyll-feed (~> 0.6) + jekyll-remote-theme + tzinfo-data + +BUNDLED WITH + 2.0.1 diff --git a/docs/_config.yml b/docs/_config.yml new file mode 100644 index 00000000..1569814b --- /dev/null +++ b/docs/_config.yml @@ -0,0 +1,57 @@ +# Welcome to Jekyll! +# +# This config file is meant for settings that affect your whole blog, values +# which you are expected to set up once and rarely edit after that. If you find +# yourself editing this file very often, consider using Jekyll's data files +# feature for the data you need to update frequently. +# +# For technical reasons, this file is *NOT* reloaded automatically when you use +# 'bundle exec jekyll serve'. If you change this file, please restart the server process. + +# Site settings +# These are used to personalize your new site. If you look in the HTML files, +# you will see them accessed via {{ site.title }}, {{ site.email }}, and so on. +# You can create any custom variable you would like, and they will be accessible +# in the templates via {{ site.myvariable }}. +title: sfall +email: your-email@example.com +description: >- # this means to ignore newlines until "baseurl:" + Sfall documentation +baseurl: "" # the subpath of your site, e.g. /blog +url: "" # the base hostname & protocol for your site, e.g. http://example.com +github_username: BGforgeNet + +# Build settings +markdown: kramdown +plugins: + - jekyll-remote-theme + - jekyll-analytics + +remote_theme: pmarsceill/just-the-docs +search_enabled: true +color_scheme: custom + +# Exclude from processing. +# The following items will not be processed, by default. Create a custom list +# to override the default setting. +exclude: + - Gemfile + - Gemfile.lock + - node_modules + - vendor/bundle/ + - vendor/cache/ + - vendor/gems/ + - vendor/ruby/ + - generate.sh + - yaml_to_md.py + +aux_links: + "Forum": + - "https://nma-fallout.com/threads/fo2-engine-tweaks-sfall.178390/" + "GitHub": + - "https://github.com/phobos2077/sfall/" + +jekyll_analytics: + Matomo: + url: st.bgforge.net + siteId: "16" diff --git a/docs/_includes/head_custom.html b/docs/_includes/head_custom.html new file mode 100644 index 00000000..a794d036 --- /dev/null +++ b/docs/_includes/head_custom.html @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/docs/_sass/color_schemes/custom.scss b/docs/_sass/color_schemes/custom.scss new file mode 100644 index 00000000..6f3f9e45 --- /dev/null +++ b/docs/_sass/color_schemes/custom.scss @@ -0,0 +1,15 @@ +$link-color: $blue-100; + +.navigation { + padding-top: 1rem !important; +} +.main-content { + padding-top: 1rem !important; +} + +.highlight .kt { + color: #93a1a1 !important; +} +.highlight .n { + color: #dc322f !important; +} diff --git a/docs/arrays.md b/docs/arrays.md new file mode 100644 index 00000000..e20ea528 --- /dev/null +++ b/docs/arrays.md @@ -0,0 +1,249 @@ +--- +layout: page +title: Arrays +nav_order: 2 +has_children: true +permalink: /arrays/ +--- + +# Arrays +{: .no_toc} + +sfall introduces new method of storing variables - arrays. + +Array is basically a container which can store variable number of values (elements). Each element in array can be of any type. Arrays can be extremely useful for some more advanced scripting, in conjunction with loops. +See array function reference [here]({{ site.baseurl }}/array-functions/). + +* TOC +{:toc} + +## Arrays concept + +Array elements are accessed by index or key. For example: +```c++ +// this code puts some string in array "list" at index 5: +list[5] := "Value"; +``` + +There are 2 different types of arrays currently available: + +* **Lists** - a set of values with specific size (number of elements), where all elements have numeric indexes starting from zero (0) up to array length minus one. + + For example: + ```c++ + // this creates list with 3 elements. Element "A" has index 0, element "B" has index 1, element "C" - 2 + list := ["A", "B", "C"]; + ``` + + Limitations: + - all indexes are numeric, starting from 0; + - to assign value to a specific index, you must first resize array to contain this index + (for example, if list is of size 3 (indexes from 0 to 2), you can't assign value to index 4 unless you change list size to 5 first). + +* **Maps** (or associative arrays) - a set of key=>value pairs, where all elements (values) are accessed by corresponding keys. + + Differences from list: + - maps don't have specific size (to assign values, you don't need to resize array first); + - keys, just like values, can be of any type (but avoid using -1 as array keys or you won't be able to use some functions reliably). + +Both array types have their pros and cons and are suited for different tasks. + + +## Arrays syntax + +Basically arrays are implemented using number of new operators (scripting functions). But for ease of use, there are some new syntax elements: + +* Accessing elements. Use square brackets: + ```js + display_msg(arr[5]); + mymap["price"] := 515.23; + ``` + +* Alternative accessing for maps. Use dot: + ```js + display_msg(mymap.name); + mymap.price := 232.23; + ``` + +* Array expressions. Create and fill arrays with just one expression: + ```c++ + // create list with 5 values + [5, 777, 0, 3.14, "Cool Value"] + + // create map: + {5: "Five", "health": 50, "speed": 0.252} + ``` + __NOTES:__ + Make sure to call `fix_array` if you want new array to be available in the next frame or `save_array` if you want to use it for a longer period (see next section for details). + +* Iterating in loop. Use `foreach` key word like this: + ```js + foreach (item in myarray) begin + // this block is executed for each array element, where "item" contains current value on each step + end + + // alternative syntax: + foreach (key: item in myarray) begin + // "key" will contain current key (or numeric index, for lists) + end + ``` + +See "scripting_docs\compiler\sslc_readme.txt" file for full information on new SSL syntax features. + +## Storing arrays + +Apart from lists/maps arrays are divided by how they are stored. +There a 3 types of arrays: + +* **Temporary**. They are created using `temp_array` function or when using array expressions. +Arrays of this type are auto-deleted at the end of the frame. So, for example, if you have a global script which runs at regular intervals, +where you create temp_array, it will not be available next time your global script is executed. + +* **Permanent**. They are created using `create_array` function or `fix_array` (from pre-existing temporary array). +This type of arrays are always available (by their ID) until you start a new game or load a saved game (at which point they are deleted). + +* **Saved**. If you want your array to really stay for a while, use function `save_array` to make any array "saved". However, they are, like permanent arrays, "deleted" from memory when loading game. In order to use them properly, you must load them from the savegame using `load_array` whenever you want to use them. + + Example: + ```js + variable savedArray; + procedure start begin + if game_loaded then begin + savedArray := load_array("traps"); + end else begin + foreach trap in traps begin + .... + end + end + end + ``` + +## Practical examples + +### Use arrays to implement variable-argument procedures +```js +// define it +procedure give_item(variable critter, variable pidList) begin + foreach (pid: qty in pidList) begin + give_pid_qty(critter, pid, qty); + end +end + +// call it: +call give_item(dude_obj, {PID_SHOTGUN: 1, PID_SHOTGUN_SHELLS: 4, PID_STIMPAK: 3}); +``` + +### Create arrays of objects (maps) for advanced scripting +```js +variable traps; +procedure init_traps begin + // just a quick example, there is a better way of doing it... + traps := load_array("traps"); + if (traps == 0) then begin + traps := []; + save_array("traps", traps); + end + foreach k: v in traps begin + traps[k] := load_array("trap_"+k); // each object is stored separately + end +end + +procedure add_trap(variable trapArray) begin + variable index; + index := len_array(traps); + save_array("trap_"+k, trapArray); + array_push(traps, trapArray); +end + +// use them: +foreach trap in traps begin + if (self_elevation == trap["elev"] and tile_distance(self_tile, trap["tile"]) < trap["radius"]) then + // kaboom!!! + end +end +``` + +## Array operators reference + +_*mixed means any type_ + +* `int create_array(int size, int flags)`: + - creates permanent array (but not "saved") + - if `size >= 0`, creates list with given size + - if `size == -1`, creates map (associative array) + - if `size == -1` and `flags == 2`, creates a "lookup" map (associative array) in which the values of existing keys are read-only and can't be updated. This type of array allows you to store a zero (0) key value + * NOTE: in earlier versions (up to 4.1.3/3.8.13) the second argument is not used, just use 0 + - returns arrayID (valid until array is deleted) + +* `int temp_array(int size, int flags)`: + - works exactly like `create_array`, only created array becomes "temporary" + +* `void fix_array(int arrayID)`: + - changes "temporary" array into "permanent" ("permanent" arrays are not automatically saved into savegames) + +* `void set_array(int arrayID, mixed key, mixed value)`: + - sets array value + - if used on list, "key" must be numeric and within valid index range (0..size-1) + - if used on map, key can be of any type + - to "unset" a value from map, just set it to zero (0) + * NOTE: to add a value of 0 for the key, use the float value of 0.0 + - this works exactly like statement: `arrayID[key] := value;` + +* `mixed get_array(int arrayID, mixed key)`: + - returns array value by key or index + - if key doesn't exist or index is not in valid range, returns 0 + - works exactly like expression: `(arrayID[key])` + +* `void resize_array(int arrayID, int size)`: + - changes array size + - applicable to maps too, but only to reduce elements + - there are number of special negative values of "size" which perform various operations on the array, use macros `sort_array`, `sort_array_reverse`, `reverse_array`, `shuffle_array` from **sfall.h** header + +* `void free_array(int arrayID)`: + - deletes any array + - if array was "saved", it will be removed from a savegame + +* `mixed scan_array(int arrayID, mixed value)`: + - searches for a first occurence of given value inside given array + - if value is found, returns it's index (for lists) or key (for maps) + - if value is not found, returns -1 (be careful, as -1 can be a valid key for a map) + +* `int len_array(int arrayID)`: + - returns number of elements or key=>value pairs in a given array + - if array is not found, returns -1 (can be used to check if given array exist) + +* `mixed array_key(int arrayID, int index)`: + - don't use it directly; it is generated by the compiler in foreach loops + - for lists, returns index back (no change) + - for maps, returns a key at the specified numeric index (don't rely on the order in which keys are stored though) + - can be checked if given array is associative or not, by using index (-1): 0 - array is list, 1 - array is map + +* `int arrayexpr(mixed key, mixed value)`: + - don't use it directly; it is used by compiler to create array expressions + - assigns value to a given key in an array, created by last `create_array` or `temp_array` call + - always returns 0 + +* `void save_array(mixed key, int arrayID)`: + - makes the array saveable; it will be saved in **sfallgv.sav** file when saving the game + - arrayID is associated with given "key" + - array becomes permanent (if it was temporary) and "saved" + - key can be of any type (int, float or string) + - if you specify 0 as the key for the array ID, it will make the array "unsaved" + +* `int load_array(mixed key)`: + - loads array from savegame data by the same key provided in `save_array` + - returns array ID or zero (0) if none found + +## Backward compatibility notes + +For those who used arrays in their mods before sfall 3.4: + +* There is an INI parameter **arraysBehavior** in **Misc** section of ddraw.ini. If set to 0, all scripts which used sfall arrays before should work. This basically changes that `create_array` will create permanent arrays which are "saved" by default and their ID is also permanent. It is 1 by default. + +* If `arraysBehaviour=0`: + Arrays are created and manipulated with the `xxx_array` functions. An array must first be created with `create_array` or `temp_array`, specifying how many data elements the array can hold. You can store any of ints, floats and strings in an array, and can mix all 3 in a single array. The id returned by `create/temp_array` can then be used with the other array functions. Arrays are shared between all scripts. (i.e. you can call `create_array` from one script, and then use the returned id from another script.) They are also saved across savegames. Arrays created with `temp_array` will be automatically freed at the end of the frame. These functions are safe, in that supplying a bad id or trying to access out of range elements will not crash the script. `create_array` is the only function that returns a permanent array, all other functions which return arrays (`string_split`, `list_as_array` etc,) all return temp arrays. You can use `fix_array` to make a temp array permanent. + +* How savegame compatibility is handled?
+ Saved arrays are stored in **sfallgv.sav** file (in savegame) in new (more flexible) format, just after the old arrays. So basically, when you load older savegame, sfall will load arrays from old format and save them to new format on next game save. If you load savegame made with sfall 3.4 using sfall 3.3 (for example), game shouldn't crash, but all arrays will be lost. + +* Previously you had to specify size in bytes for array elements. This parameter is now ignored and you can store strings of arbitrary length in arrays. diff --git a/docs/assets/favicon/android-chrome-192x192.png b/docs/assets/favicon/android-chrome-192x192.png new file mode 100644 index 00000000..d78523f3 Binary files /dev/null and b/docs/assets/favicon/android-chrome-192x192.png differ diff --git a/docs/assets/favicon/android-chrome-512x512.png b/docs/assets/favicon/android-chrome-512x512.png new file mode 100644 index 00000000..5949fa24 Binary files /dev/null and b/docs/assets/favicon/android-chrome-512x512.png differ diff --git a/docs/assets/favicon/apple-touch-icon.png b/docs/assets/favicon/apple-touch-icon.png new file mode 100644 index 00000000..41afb3c3 Binary files /dev/null and b/docs/assets/favicon/apple-touch-icon.png differ diff --git a/docs/assets/favicon/browserconfig.xml b/docs/assets/favicon/browserconfig.xml new file mode 100644 index 00000000..b798281a --- /dev/null +++ b/docs/assets/favicon/browserconfig.xml @@ -0,0 +1,9 @@ + + + + + + #da532c + + + diff --git a/docs/assets/favicon/favicon-16x16.png b/docs/assets/favicon/favicon-16x16.png new file mode 100644 index 00000000..b8280fbb Binary files /dev/null and b/docs/assets/favicon/favicon-16x16.png differ diff --git a/docs/assets/favicon/favicon-32x32.png b/docs/assets/favicon/favicon-32x32.png new file mode 100644 index 00000000..3aad60b6 Binary files /dev/null and b/docs/assets/favicon/favicon-32x32.png differ diff --git a/docs/assets/favicon/favicon.ico b/docs/assets/favicon/favicon.ico new file mode 100644 index 00000000..4e313bad Binary files /dev/null and b/docs/assets/favicon/favicon.ico differ diff --git a/docs/assets/favicon/mstile-144x144.png b/docs/assets/favicon/mstile-144x144.png new file mode 100644 index 00000000..89e8337e Binary files /dev/null and b/docs/assets/favicon/mstile-144x144.png differ diff --git a/docs/assets/favicon/mstile-150x150.png b/docs/assets/favicon/mstile-150x150.png new file mode 100644 index 00000000..f8b483d9 Binary files /dev/null and b/docs/assets/favicon/mstile-150x150.png differ diff --git a/docs/assets/favicon/mstile-310x150.png b/docs/assets/favicon/mstile-310x150.png new file mode 100644 index 00000000..2627bdb7 Binary files /dev/null and b/docs/assets/favicon/mstile-310x150.png differ diff --git a/docs/assets/favicon/mstile-310x310.png b/docs/assets/favicon/mstile-310x310.png new file mode 100644 index 00000000..529640c5 Binary files /dev/null and b/docs/assets/favicon/mstile-310x310.png differ diff --git a/docs/assets/favicon/mstile-70x70.png b/docs/assets/favicon/mstile-70x70.png new file mode 100644 index 00000000..dbdb9ef3 Binary files /dev/null and b/docs/assets/favicon/mstile-70x70.png differ diff --git a/docs/assets/favicon/safari-pinned-tab.svg b/docs/assets/favicon/safari-pinned-tab.svg new file mode 100644 index 00000000..0cdc9f87 --- /dev/null +++ b/docs/assets/favicon/safari-pinned-tab.svg @@ -0,0 +1,31 @@ + + + + +Created by potrace 1.11, written by Peter Selinger 2001-2013 + + + + + diff --git a/docs/assets/favicon/site.webmanifest b/docs/assets/favicon/site.webmanifest new file mode 100644 index 00000000..df4e213d --- /dev/null +++ b/docs/assets/favicon/site.webmanifest @@ -0,0 +1,19 @@ +{ + "name": "sfall", + "short_name": "sfall", + "icons": [ + { + "src": "/assets/favicon/android-chrome-192x192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "/assets/favicon/android-chrome-512x512.png", + "sizes": "512x512", + "type": "image/png" + } + ], + "theme_color": "#ffffff", + "background_color": "#ffffff", + "display": "standalone" +} diff --git a/docs/best-practices.md b/docs/best-practices.md new file mode 100644 index 00000000..ae044115 --- /dev/null +++ b/docs/best-practices.md @@ -0,0 +1,49 @@ +--- +title: Best practices +permalink: /best-practices/ +nav_order: 2 +--- + + +# Best practices +{: .no_toc} + +* TOC +{: toc} + +## Mod compatibility + +0. If it can be done in a [global script]({{ site.baseurl }}/global-scripts/), do it in a global script. Combined with hooks, they are extremely powerful, possibilities ranging from creating new perks to UI scripting to prototype altering on-the-fly. + While scripting _does_ take a bit longer to get started, and hacking prototypes directly with GUI programs _might look_ easier at first, consider that: + * Scripts from different mods modifying the same thing can actually be compatible with each other. Binary files can't. + * Scripts can be version controlled and thus are much more easier to maintain. + +1. If you're using [set_sfall_return]({{ site.baseurl }}/hook-functions/#set_sfall_return), always couple it with [set_sfall_arg]({{ site.baseurl }}/hook-functions/#set_sfall_arg) for the corresponding `arg`(s), unless you have a specific reason not to. Detailed explanation is available [here]({{ site.baseurl }}/hook-functions/#register_hook_proc). + +2. Pick yourself a 2-3 character [modding prefix](http://www.nma-fallout.com/threads/a-modding-prefix-for-your-mods.217791/). Use it for: + * global script names + * global variable names and saved array names + * debug messages + + This will ensure (to some degree), that another mod doesn't overwrite your scripts, doesn't mess with your global variables, and that debug messages coming from your scripts can be distinguished easily. + + For example, if you pick prefix "**a_**", your script could be named `gl_a_myscript.int`, and might look like this: + + ```js + #define NAME "gl_a_myscript" + #define ndebug(message) debug_msg(NAME + ": " + message + "\n") + + procedure start begin + if game_loaded then begin + set_sfall_global("a_myvar", 1000); + ndebug("initialized"); + end + end + ... + ``` + +## Performance + +1. Do not abuse [set_global_script_repeat]({{ site.baseurl }}/global-scripts/). Whenever possible, register your script as a [hook]({{ site.baseurl }}/hooks/) instead. You can register the same procedure at multiple hook points, if necessary. + - If you have `set_global_script_repeat(300)` in your script, you're probably doing something wrong. That's an invocation every 3-5 seconds, approximately. + - If you have `set_global_script_repeat(30)`, you are definitely doing something wrong. Look for suitable hooks harder, think of another way for implementing it, ask fellow modders for help. diff --git a/docs/data-types.md b/docs/data-types.md new file mode 100644 index 00000000..942803e7 --- /dev/null +++ b/docs/data-types.md @@ -0,0 +1,21 @@ +--- +title: Data types +nav_order: 2 +permalink: /data-types/ +--- + +# Data types +{: .no_toc} + +Data types mentioned in this document + +* `array` - array ID to be used with array-related functions (actually an integer) +* `any` - any type +* `bool` - boolean (in fact, `int`: `True` is 1 and `False` is 0) +* `int` - integer number +* `mixed` - type depends on exact use case +* `float` - floating point number +* `ObjectPtr` - pointer to a game object (actually an integer) +* `proc` - procedure name (used in [register_hook_proc]({{ site.baseurl }}/hook-functions/#register_hook_proc)) +* `string` - string (text) value +* `void` - means opcode does not return any value diff --git a/docs/favicon.ico b/docs/favicon.ico new file mode 120000 index 00000000..50003e99 --- /dev/null +++ b/docs/favicon.ico @@ -0,0 +1 @@ +assets/favicon/favicon.ico \ No newline at end of file diff --git a/docs/generate.sh b/docs/generate.sh new file mode 100755 index 00000000..73ae9a15 --- /dev/null +++ b/docs/generate.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +set -xeu -o pipefail + +site_dir="docs" +yml_dir="../artifacts/scripting" +pages_dir="pages" + +cd "$site_dir" +echo "sfall.bgforge.net" > CNAME +mkdir -p "$pages_dir" +./yaml_to_md.py "$yml_dir/functions.yml" "$yml_dir/hooks.yml" "$pages_dir" + +bundle install +bundle exec jekyll build diff --git a/docs/global-scripts.md b/docs/global-scripts.md new file mode 100644 index 00000000..1d454298 --- /dev/null +++ b/docs/global-scripts.md @@ -0,0 +1,20 @@ +--- +layout: page +title: Global scripts +nav_order: 2 +has_children: true +has_toc: false +permalink: /global-scripts/ +--- + +# Global scripts + +As well as the new functions, sfall also adds global scripts. These run independent of any loaded maps, but do not have an attached object. (i.e. using `self_obj` without using `set_self` first will crash the script.) To use a global script, the script must have a name which begins with `gl` and contains a procedure called `start`, `map_enter_p_proc`, `map_exit_p_proc`, or `map_update_p_proc`. The start procedure will be executed once when the player loads a saved game or starts a new game. The `map_*_p_proc` procedures will be executed once when a map is being entered/left/updated. If you wish the script to be executed repeatedly, call `set_global_script_repeat` on the first run of the start procedure using the number of frames between each run as the argument. (0 disables the script, 1 runs it every frame, 2 runs it every other frame etc.) + +Global scripts have multiple modes, which can be set using the `set_global_script_type` function. +- In the default mode (i.e. mode 0) their execution is linked to the local map game loop, so the script will not run in dialogs or on the world map. + [Using mode 1 requires the input wrapper to be enabled. Use `available_global_script_types` to check what is available.] - Obsolete. +- In mode 1 their execution is linked to the player input, and so they will run whenever the mouse cursor is visible on screen, including the world map, character dialogs etc. +- In mode 2, execution is linked to the world map loop, so the script will only be executed on the world map and not on the local map or in any dialog windows. +- Mode 3 is a combination of modes 0 and 2, so scripts will be executed on both local maps and the world map, but not in dialog windows. + diff --git a/docs/hooks.md b/docs/hooks.md new file mode 100644 index 00000000..10841a03 --- /dev/null +++ b/docs/hooks.md @@ -0,0 +1,34 @@ +--- +title: Hooks +nav_order: 2 +has_children: true +permalink: /hooks/ +--- + +# Hooks + +Hook scripts are specially named scripts that are run by sfall at specific points to allow mods to override normally hardcoded behaviour in a more flexible way than sfall's normal ini configuration. + +In addition to the bit of code it overrides, the script will be run once when first loaded and again at each player reload to allow for setup. Hook scripts have access to a set of arguments supplied to sfall, but aren't required to use them all. They also return one or more values, but again they're optional, and you only need to return a value if you want to override the default. + +See [hook types]({{ site.baseurl }}/hook-types/) and hook [functions reference]({{ site.baseurl }}/hook-functions/) for details. + +## Hooks compatibility + +To aid in mods compatibility, avoid using `hs_xxx` .int scripts. Instead it is recommended to use a normal global script combined with [register_hook_proc]({{ site.baseurl }}/hook-functions/#register_hook_proc) or [register_hook]({{ site.baseurl }}/hook-functions/#register_hook). + +Example setup for a hook-script based mod: + +```js +procedure tohit_hook_handler begin + display_msg("Modifying hit_hook " + get_sfall_arg); + set_hit_chance_max(100); + set_sfall_return(100); +end + +procedure start begin + if game_loaded then begin + register_hook_proc(HOOK_TOHIT, tohit_hook_handler); + end +end +``` diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 00000000..4e320e9d --- /dev/null +++ b/docs/index.md @@ -0,0 +1,41 @@ +--- +navigation: 1 +title: Home +permalink: / +nav_order: 1 +--- + +## sfall +{: .no_toc} + +* TOC +{: toc} + +Sfall is a set of engine modifications for the classic game Fallout 2 in form of a DLL, which modifies executable in memory without changing anything in EXE file itself. + +Engine modifications include: + +* Better support for modern operating systems +* Externalizing many settings like starting map and game time, skills, perks, critical hit tables, books, etc. +* Bug fixes +* Many additional features for users, such as item highlight button, party member control, etc. +* Extended scripting capabilities for modders (many new opcodes to control sfall features as well as previously unavailable vanilla engine functions) + +Note that this is documentation for sfall specifically, not Fallout scripting in general. For vanilla function reference, refer to the [wiki](https://falloutmods.fandom.com/wiki/Fallout_1_and_Fallout_2_scripting_-_commands,_reference,_tutorials). + +## Getting started + +To get started with sfall, first familiarize yourself with new concepts: +* Global [scripts]({{ site.baseurl }}/global-scripts/) and [variables]({{ site.baseurl }}/global-variables/). +* [Arrays]({{ site.baseurl }}/arrays/) and [lists]({{ site.baseurl }}/lists/). +* [Hooks]({{ site.baseurl }}/hooks/). +* [Data types]({{ site.baseurl }}/data-types/). +* [Object and script manipulation]({{ site.baseurl }}/objects-and-scripts/). + +Pay special attention to the [best practices]({{ site.baseurl }}/best-practices/) page. Also, take a look at [SSLC features]({{ site.baseurl }}/sslc/) and [optimization guide]({{ site.baseurl }}/optimization/). + +Next, proceed to discover new functions. They are categorized, use the menu to find the one you need. If you can't, check [uncategorized functions]({{ site.baseurl }}/other/) list and [sfall macros]({{ site.baseurl }}/sfall-funcx-macros/). Also, there's search at the top of the page. + +## Questions and problems +* Report bugs and suggest features on [Github](https://github.com/phobos2077/sfall/issues). +* Ask questions and discuss on the [forum](http://nma-fallout.com/threads/fo2-engine-tweaks-sfall.178390/). diff --git a/docs/optimization.md b/docs/optimization.md new file mode 100644 index 00000000..87ced15e --- /dev/null +++ b/docs/optimization.md @@ -0,0 +1,105 @@ +--- +layout: page +title: Optimization +permalink: /optimization/ +nav_order: 5 +--- + + +# Optimization +{: .no_toc} + +* TOC +{: toc} + +The executation speed of scripts is not typically important in an unmodded game, given the difference in performance between a modern computer and what Fallout was designed for. When you start adding mods to the mix there's the potential for problems again, since sfall's global script system means that you can have a large amount of scripts being run every single frame. + +## sslc -O option + +The sfall build of sslc supports a -O command line option to perform an optimization pass over the generated code. This isn't a magic make-my-code-go-faster bullet; most of what it does is very limited in scope. It's primary purpose was to strip out the procedures and variables which get automatically pulled into every script that includes define.h, whether you use them or not, and to do something about the additional variables that get created by foreach loops. + +There are several levels of optimization available: +- `-O1` - Basic, only removes unreferenced globals variables and procedures, code itself remains untouched. +- `-O2` - Full, most code optimizations are on, but only those that were tested on complex scripts. +- `-O3` - Experimental, provides most efficiency, but tend to break some complex code due to bugs. + +The following optimizations are performed: + +- constant expression folding: if an expression depends only on values which are known at compile time, then the expression is replaced by its result. + `a:=2+2;` -> `a:=4;` +- constant variable initialization: All variables are initialised to some value, ('0', if you don't specify anything else,) so sslc attempts to make use of that fact to remove the first assignment to a variable if the first assignment is a constant expression. + ``` + variable a; -> variable a:=4; + a:=4; -> + ``` +- constant propagation: checks for values assigned to variables which can be computed at compile time, and replaces relevent references to the symbol by the constant. The original store is not removed by this optimization. Global variables are considered for this optimization only if they are not marked import or export, and are not assigned to anywhere in the script. + ``` + a:=4 -> a:=4 + foo(a); -> foo(4); + ``` +- dead code removal: Checks for and removes code which cannot be reached, either because it is hidden behind a return or because the argument to an if statement can be computed at compile time. + ``` + if 1 then begin -> display_msg("foo"); + display_msg("foo"); -> + end else begin -> + display_msg("bar"); -> + end -> + ``` +- unreferenced variable elimination: Checks for variables which are never referenced, and removes them. Also applies to global variables, as long as they are not marked for export. + ``` + variable i, j, k; -> variable i; + i:=1; -> i:=1; + return; -> return; + ``` +- unreferenced procedure elimination: Checks for any procedures which are never called, and removes them. + ``` + procedure foo begin return "foo"; end -> procedure foo begin return "foo"; end + procedure bar begin return "bar"; end -> procedure start begin + procedure start begin -> display_msg(foo); + display_msg(foo); -> end + end -> + ``` +- dead store removal: Removes variable assignments if the result of the variable is unused, and if the expression used to compute the value of the variable is provably free of side effects. (See 'pure' keyword) + ``` + a:="moo"; -> a:="foo"; + a:="foo"; -> display_msg(a); + display_msg(a); -> + a:="bar"; -> + ``` +- store combination: Where there are two stores in a row to the same variable, the two expressions are combined. + ``` + var1 := var2; -> var1 := var2 + var3; + var1 += var3; -> + ``` +- variable combination: Where usage regions of variables do not overlap, combine the variables to provide additional candidates for unreferenced variable elimination. Very useful for scripts containing multiple foreach loops, which generate 2 or 3 hidden variables each. + ``` + a:="foo"; -> a:="foo"; + display_msg(a); -> display_msg(a); + b:="bar"; -> a:="bar"; + display_msg(b); -> display_msg(a); + ``` +- namelist compression: Fallout stores the names of all file scope variables and procedures in a namelist which is saved into the .int. Any of these that are unreferenced can be removed, and the names of global variables can be modified to make them shorter. + +## Writing your own code + +- Don't have global scripts running any more often that you need them to. Not everything needs to be run every single frame. +- Never concat constant strings with the '+' operator, as it forces the operation to be done at runtime. The compiler can cope with constant strings being placed next to each other without the need for a +, which results in far more efficient code as the combination is done at lex time. + ``` + #define GLOB_PREFIX "ts__" -> #define GLOB_PREFIX "ts__" + + procedure start begin -> procedure start begin + set_sfall_global(GLOB_PREFIX + "foo1", 0); -> set_sfall_global(GLOB_PREFIX "foo1", 0); + end -> end + ``` +- Avoid function calls in while loops. function calls are expensive in comparison to variable lookups, so it's more efficient to move the function call out of the loop and store the result in a variable + ``` + while i < len_array(array) do begin -> tmp:= len_array(array); + ... -> while i < tmp do begin + end -> ... + -> end + ``` +- Mark functions with pure or inline where relevent. + + 'pure' is a hint to the optimizer that a procedure has no side effects. (i.e. there's no way to tell that it's been called aside from its return value.) Pure procedures cannot modify global variables, or call any other procedure that isn't itself pure. Functions marked with pure can only be used in expressions (i.e. you cannot use the `call ` syntax to call them.) If there are non-pure terms in an expression, it prevents that expression being considered for dead store removal. Where no such optimizations can be performed, or if optimization is disabled, marking a procedure with pure will have no effect on the compiled code. + + 'inline' is an instruction to the compiler to replace calls to the marked procedure with a copy of the procedures code instead of having a seperate call. inlined procedures cannot use the 'return' command, cannot be predefined, and cannot be used as part of an expression. inlining if a procedure is only going to be called once is always a win, but if there are multiple calls to a procedure you will end up bloating the size of the generated code. diff --git a/docs/sslc.md b/docs/sslc.md new file mode 100644 index 00000000..68b6afaa --- /dev/null +++ b/docs/sslc.md @@ -0,0 +1,352 @@ +--- +layout: page +title: SSLC +permalink: /sslc/ +nav_order: 4 +--- + +# SSLC +{: .no_toc} + +* TOC +{: toc} + +This is a modified copy of sslc, that has a few bugfixes from the original, that will recognise and compile the additional scripting functions provided by sfall, that can also understand some additional syntax, and that has an integrated preprocessor and optimizer. + +Unlike the original script compiler, this has not been compiled as a dos program. When using this in place of the original compile.exe but still using p.bat, you need to either get rid of the dos4gw.exe reference from p.bat or replace the original dos4gw.exe with the one in this archive. + +If you use fallout script editor, you can extract `compile.exe` and `dos4gw.exe` to its `\binary` folder, or extract them somewhere else and change your preferences in FSE to point there. FSE doesn't seem to be able to tell when errors occur when using this compiler though, so I'd recommend either using sfall's script editor instead or compiling by hand if possible. + +When compiling global or hook scripts for sfall 3.4 or below, you _must_ include the line `procedure start;` before any `#include`s that define procedures to avoid a few weird problems. (this is no longer required starting from 3.5) + +This version of compiler was designed primarily for new sfall functions, but it can safely (and is recommended) to be used with non-sfall scripts as well, as long as you don't use any of the arrays syntax and any sfall scripting functions. + +The original unmodified sslc source is over here: [http://www.teamx.ru/eng/files/srcs/index.shtml](http://www.teamx.ru/eng/files/srcs/index.shtml). + +## Command line options + +``` +-q don't wait for input on error +-n no warnings +-b backward compatibility mode +-l no logo +-p preprocess source +-O optimize code (full, see optimization.txt) +-O set specific level of optimization (0 - off, 1 - basic, 2 - full, 3 - experimental) +-d print debug messages +-D output an abstract syntax tree of the program +-o set output path (follows the input file name) +-s enable short-circuit evaluation for all AND, OR operators +-m define a macro named "macro" for conditional compilation +-I specify an additional directory to search for include files +``` + +The original command line option `-w` to turn on warnings no longer has an effect, since warnings are now on by default + +## Additional supported syntax + +Syntax which requires sfall for compiled scripts to be interpreted, is marked by asterix (*). + +- Optional arguments in user-defined procedures. You can only use constants for default values. It basically puts those constants in place of omitted arguments. + + - new: + ``` + procedure test(variable x, variable y := 0, variable z := -1) begin + ... + end + ... + call test("value"); + ``` + - old: + ``` + procedure test(variable x, variable y, variable z) begin + ... + end + ... + call test("value", 0, -1); + ``` + +- New logical operators `AndAlso`, `OrElse` for short-circuit evaluation of logical expressions. + Using these operators allow the right part of logical expressions not to be evaluated (executed, computed) if the result is already known. This can improve the performance of running scripts. + + Example: `if (obj andAlso obj_pid(obj) == PID_STIMPAK) then ...` + + If `obj` is `null`, the second condition will not be checked and your script won't fail with "obj is null" error in debug.log + + This also has an effect that a value of last computed argument is returned as a result of whole expressions, instead of always 0 (`false`) or 1 (`true`): + ``` + obj := false; + display_msg(obj orElse "something"); // will print "something" + ``` + You can also use the `-s` option to enable short-circuit evaluation for all the `AND`, `OR` operators in the script. + + NOTE: Be aware that it may break some old scripts because operators behavior is changed slightly. + +- Conditional expressions (Python-inspired), also known as ternary operator: + - new: + ``` + X := value1 if condition else value2 + ``` + - old: + ``` + if (condition) then + X := value1; + else + X := value2; + ``` +- To assign values, you can use the alternative assignment operator from C/Java instead of Pascal syntax. + - new: + ``` + x = 5; + ``` + - old: + ``` + x := 5; + ``` +- Multiple variable declaration: Multiple variables can be declared on one line, seperated by commas. This is an alterative to the ugly begin/end block, or the bulky single variable per line style. + - new: + ``` + variable a, b, c; + ``` + - old: + ``` + variable begin a; b; c; end + ``` +- Variable initialization with expressions: You can now initialize local variables with complex expressions instead of constants. + - new: + ``` + variable tile := tile_num(dude_obj); + ``` + - old: + ``` + variable tile; + tile := tile_num(dude_obj); + ``` + NOTE: if your expression starts with a constant (eg. `2+2`), enclose it in parentheses, otherwise compiler will be confused and give you errors. + +- Hexadecimal numerical constants: Simply prefix a number with `0x` to create a hexadecimal. The numbers `0` to `9` and `a-f` are allowed in the number. The number may not have a decimal point. + - new: + ``` + a := 0x1000; + ``` + - old: + ``` + a := 4096; + ``` +- Increment/decrement operators: `++` and `--` can be used as shorthand for `+=1` and `-=1` respectively. They are mearly a syntactic shorthand to improve readability, and so their use is only allowed where `+=1` would normally be allowed. + - new: + ``` + a++; + ``` + - old: + ``` + a += 1; + ``` + +- `break` & `continue` statements: they work just like in most high-level languages. `break` jumps out of the loop. `continue` jumps right to the beginning of the next iteration (see `for` and `foreach` sections for additional details). + - new: + ``` + while (i < N) begin + // ... + if (/* some condition */) then break; + // ... + end + ``` + - old: + ``` + while (i < N and not(breakFlag)) begin + // ... + if (/* condition */) then breakFlag := true; + // ... + end + ``` + - new: + ``` + for (i := 0; i < N; i++) begin + // ... + if (/* condition */) then begin + // action + continue; + end + // else actions + end + ``` + - old: + ``` + for (i := 0; i < N; i++) begin + // ... + if (/* condition */) then begin + // action + end else begin + // else actions + end + end + ``` + +- `for` loops: Another piece of syntactic shorthand, to shorten `while` loops in many cases. Parentheses around the loop statements are recommended but not required (when not using parentheses, a semicolon is required after the 3rd loop statement). + - new: + ``` + for (i := 0; i < 5; i++) begin + display_msg("i = "+i); + end + ``` + - old: + ``` + i := 0; + while (i < 5) do begin + display_msg("i = "+i); + i++; + end + ``` + NOTE: `continue` statement in a `for` loop will recognize increment statement (third statement in parentheses) and will execute it before jumping back to the beginning of loop. This way you will not get an endless loop. + +- `switch` statements: A shorthand way of writing big `if then else if...` blocks + - new: + ``` + switch get_attack_type begin + case ATKTYPE_PUNCH: display_msg("punch"); + case ATKTYPE_KICK: display_msg("kick"); + default: display_msg("something else"); + end + ``` + - old: + ``` + variable tmp; + tmp := get_attack_type; + if tmp == ATKTYPE_PUNCH then begin + display_msg("punch"); + end else if tmp == ATKTYPE_KICK then begin + display_msg("kick"); + end else begin + display_msg("something else"); + end + ``` + +- empty statements in blocks are allowed: This is just a convenience to save scripters a bit of memory. Some of the macros in the fallout headers include their own semicolons while others do not. With the original compiler you had to remember which was which, and if you got it wrong the script would not compile. Now it's always safe to include your own semicolon, even if the macro already had its own. For example, this would not compile with the original sslc, but will with the sfall edition: + ``` + #define my_macro diplay_msg("foo"); + + procedure start begin + my_macro; + end + ``` + +- Procedure stringify operator `@`: designed to make callback-procedures a better option and allow for basic functional programming. Basically it replaces procedure names preceeded by `@` by a string constant. + Not many people know that since vanilla Fallout you can call procedures by "calling a variable" containing it's name as a string value. There was a couple of problems using this: + - optimizer wasn't aware that you are referencing a procedure, and could remove it, if you don't call it explicitly (can be solved by adding making procedure "critical") + - you couldn't see all references of a procedure from a Script Editor + - it was completely not obvious that you could do such a thing, it was a confusing syntax + - old: + ``` + callbackVar := "Node000"; + callbackVar(); + ``` + - new: + ``` + callbackVar := @Node000; + callbackVar(); + ``` +- *arrays: In vanilla fallout arrays had to be constructed by reserving a block of global/map variables. Since sfall 2.7, specific array targeted functions have been available, but they are fairly messy and long winded to use. The compiler provides additional syntactic shorthand for accessing and setting array variables, as well as for array creation. When declaring an array variable, put a constant integer in []'s to give the number of elements in the array. (before sfall 3.4 you had to specify size in bytes for array elements, now it's not required, see "arrays.txt" for more information) + - new: + ``` + procedure bingle begin + variable a[2]; + a[0] := 5; + a[a[0] - 4] := a[0] + 4; + display_msg("a[0]=" + a[0] + ", a[1]=" + a[1]); + end + ``` + - old: + ``` + procedure bingle begin + variable a; + a := temp_array(2, 4); + set_array(a, 0, 5); + set_array(a, get_array(a, 0) - 4, get_array(a, 0) + 4); + display_msg("a[0]=" + get_array(a, 0) + ", a[1]=" + get_array(a, 1)); + end + ``` + +- *array expressions: sometimes you need to construct an array of elements and you will probably want to do it in just one expression. This is now possible: + - new: + ``` + list := ["A", "B", "C", "D"]; + ``` + - old: + ``` + list := temp_array(4, 2); + list[0] := "A"; + list[1] := "B"; + list[2] := "C"; + list[3] := "D"; + ``` + Syntax specific for associative arrays is also available. (see "arrays.txt" for full introduction to this type of arrays). + +- *map array expressions: + ``` + map := {5: "five", 10: "ten", 15: "fifteen", 20: "twelve"}; + ``` + +- * "dot" syntax to access elements of associative arrays. "dot" syntax allows to work with arrays like objects: + ``` + trap.radius := 3; + trap.tile := tile_num(dude_obj); + ``` + You can chain dot and bracket syntax to access elements of multi-dimensional arrays: + ``` + collectionList[5].objectList[5].name += " foo"; + ``` + + NOTE: when using incremental operators like `+=`, `*=`, `++`, `--` compiler will use additional temp variable to get an array at penultimate level in order to avoid making the same chain of "get_array" calls twice. + +- * `foreach` loops: A shorthand method of looping over all elements in an array. Syntax is `foreach ( in )`. + - new: + ``` + procedure bingle begin + variable critter; + foreach (critter in list_as_array(LIST_CRITTERS)) begin + display_msg(""+critter); + end + end + ``` + - old: + ``` + procedure bingle begin + variable begin critter; array; len; count; end + array := list_as_array(LIST_CRITTERS); + len := len_array(array); + count := 0; + while count < len do begin + critter := array[count]; + display_msg("" + critter); + end + end + ``` + If you want an index array element (or key for "maps") at each iteration, use syntax: `foreach (: in )` + ``` + foreach (pid: price in itemPriceMap) begin + if (itemPid == pid) then + itemPrice := price; + end + ``` + If you want to add additional condition for continuing the loop, use syntax: `foreach ( in while )`. In this case loop will iterate over elements of an array until last element or until "while" expression is true (whatever comes first). + + NOTE: just like `for` loop, "continue" statement will respect increments of a hidden counter variable, so you can safely use it inside `foreach`. + +## int2ssl note + +int2ssl by Anchorite (TeamX) is included in sfall modderspack package. It was updated to support all additional opcodes of sfall, along with some syntax features. You can use it to decompile any sfall or non-sfall script. + +## Fixes +- `playmoviealpharect` was using the token for `playmoviealpha`, breaking both functions in the process. +- `addbuttonflag` had an entry in the token table, and could be parsed, but was missing an entry in the emit list. This resulted in the compiler accepting it as a valid function, but not outputting any code for it into the compiled script. +- The function `tokenize` was missing an entry in the token table, and so would not be recognised by the compiler. +- Fixed the check for the `call "foo"` syntax so that non-string constants will no longer be accepted. + +## Backward compatibility + +There are several changes in this version of sslc which may result in problems for previously working scripts. A new command line option `-b` is available, which will turn off all new fixes and features which have the possibility of causing a previously compiling script to change its behaviour. (And only those features; anything which would not compile under the old sslc is not affected.) This includes the following: +- Since `for`, `foreach`, `break`, `continue`, `in` and `tokenize` are now hardcoded names, existing scripts that use any of them as a variable or procedure name will no longer compile. +- Missing a semicolon after a variable declaration is now a hard error. (Originally sslc would check for the semicolon, but would not complain if it was missing.) +- The function `addbuttonflag` used to be recognised by the compiler, but would not emit any code into the int file. +- The function `playmoviealpharect` compiled as `playmoviealpha`. diff --git a/docs/yaml_to_md.py b/docs/yaml_to_md.py new file mode 100755 index 00000000..2873d427 --- /dev/null +++ b/docs/yaml_to_md.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +# coding: utf-8 + +import sys, os +import ruamel.yaml +yaml = ruamel.yaml.YAML(typ="rt") +yaml.width = 4096 +yaml.indent(mapping=2, sequence=4, offset=2) + +functions_yaml = sys.argv[1] +hooks_yaml = sys.argv[2] +md_dir = sys.argv[3] + +# template for functions pages +function_header_template = '''--- +layout: page +title: '{name}' # quote just in case +nav_order: 6 +{has_children} +# parent - could be empty +{parent} +has_toc: false +permalink: {permalink} +--- + +# {name} +{{: .no_toc}} +''' + +# template for hooks types page - hardcoded +hooks_header = '''--- +layout: page +title: Hook types +nav_order: 6 +parent: Hooks +permalink: /hook-types/ +--- + +# Hook types +{: .no_toc} + +* TOC +{:toc} +--- +''' + +def get_slug(string): + return string.lower().replace(' ','-').replace(':','-').replace('/','-').replace('--','-') + +# functions pages +with open(functions_yaml) as yf: + data = yaml.load(yf) + for cat in data: # list categories + text = "" + + # check for childre + has_children = "" + children = [x for x in data if "parent" in x and x["parent"] == cat["name"]] + if len(children) > 0: + has_children = "has_children: true" + + # used in filename and permalink + slug = get_slug(cat['name']) + + # if parent is present, this is a subcategory + parent = "" + if 'parent' in cat: + parent = "parent: " + cat['parent'] + header = function_header_template.format(name=cat['name'], parent=parent, has_children=has_children, permalink="/{}/".format(slug)) + text += header + + # common doc for category + if 'doc' in cat: + text = text + '\n' + cat['doc'] + '\n' + + if len(children) > 0: + text += "\n## Subcategories\n{: .no_toc}\n\n" + for c in children: + text += "- [**{}**](/{}/)\n".format(c["name"], get_slug(c["name"])) + text += "\n" + + if 'items' in cat: # allow parent pages with no immediate items + text += "## Functions\n{: .no_toc}\n\n" + text += "* TOC\n{: toc}\n" + # individual functions + items = cat['items'] + items = sorted(items, key=lambda k: k['name']) + + for i in items: + # header + text += "\n---\n\n### **{}**\n".format(i['name']) + # macro label + if 'macro' in i: + text += "{: .d-inline-block }\n" + format(i['macro']) + "\n{: .label .label-green }\n" + # unsafe label + if 'unsafe' in i and i['unsafe'] is True: + text += '{: .d-inline-block }\nUNSAFE\n{: .label .label-red }\n' + # usage + text += "```c++\n{}\n```\n".format(i['detail']) + # doc, if present + if 'doc' in i: + text += i['doc'] + '\n' + + md_path = os.path.join(md_dir, slug + ".md") + with open(md_path, 'w') as f: + f.write(text) + + +# hook types page +with open(hooks_yaml) as yf: + hooks = yaml.load(yf) + hooks = sorted(hooks, key=lambda k: k['name']) # alphabetical sort + text = hooks_header + + for h in hooks: + name = h['name'] + doc = h['doc'] + try: + hid = h['id'] + except: + hid = "HOOK_" + name.upper() + if 'filename' in h: # overriden filename? + filename = h['filename'] + else: + filename = "hs_" + name.lower() + ".int" + + text += "\n## {}\n\n".format(name) # header + if filename != "": # if not skip + text += "`{}` ({})\n\n".format(hid, filename) # `HOOK_SETLIGHTING` (hs_setlighting.int) + text += doc # actual documentation + + md_path = os.path.join(md_dir, "hook-types.md") + with open(md_path, 'w') as f: + f.write(text) diff --git a/sfall/CRC.cpp b/sfall/CRC.cpp index 82f94616..81c6fa90 100644 --- a/sfall/CRC.cpp +++ b/sfall/CRC.cpp @@ -83,14 +83,14 @@ void CRC(const char* filepath) { DWORD size = GetFileSize(h, 0), crc; bool sizeMatch = (size == ExpectedSize); - if (!sizeMatch && iniGetInt("Debugging", "SkipSizeCheck", 0, ::sfall::ddrawIni)) { + if (!sizeMatch && IniReader::GetIntDefaultConfig("Debugging", "SkipSizeCheck", 0)) { sizeMatch = true; } if (!sizeMatch) { sprintf_s(buf, "You're trying to use sfall with an incompatible version of Fallout.\n" - "Was expecting '" TARGETVERSION "'.\n\n" - "fallout2.exe has an unexpected size. Expected %d bytes but got %d bytes.", ExpectedSize, size); + "Was expecting '" TARGETVERSION "'.\n\n" + "fallout2.exe has an unexpected size. Expected %d bytes but got %d bytes.", ExpectedSize, size); Fail(buf); } BYTE* bytes = new BYTE[size]; @@ -99,7 +99,7 @@ void CRC(const char* filepath) { bool matchedCRC = false; - auto extraCrcList = GetIniList("Debugging", "ExtraCRC", "", 512, ',', ::sfall::ddrawIni); + auto extraCrcList = IniReader::GetListDefaultConfig("Debugging", "ExtraCRC", "", 512, ','); if (!extraCrcList.empty()) { matchedCRC = std::any_of(extraCrcList.begin(), extraCrcList.end(), [crc](const std::string& testCrcStr) { auto testedCrc = strtoul(testCrcStr.c_str(), 0, 16); @@ -112,8 +112,8 @@ void CRC(const char* filepath) { } if (!matchedCRC) { sprintf_s(buf, "You're trying to use sfall with an incompatible version of Fallout.\n" - "Was expecting '" TARGETVERSION "'.\n\n" - "fallout2.exe has an unexpected CRC. Expected 0x%x but got 0x%x.", ExpectedCRC[0], crc); + "Was expecting '" TARGETVERSION "'.\n\n" + "fallout2.exe has an unexpected CRC. Expected 0x%x but got 0x%x.", ExpectedCRC[0], crc); Fail(buf); } diff --git a/sfall/CheckAddress.cpp b/sfall/CheckAddress.cpp index b5980591..cfceb1de 100644 --- a/sfall/CheckAddress.cpp +++ b/sfall/CheckAddress.cpp @@ -1,3 +1,5 @@ +#include + #include "main.h" #include "CheckAddress.h" @@ -9,12 +11,12 @@ namespace sfall std::multimap writeAddress; -static std::vector excludeWarning = { +static std::array excludeWarning = { 0x44E949, 0x44E94A, 0x44E937, 0x4F5F40, 0x44E932, // from movies.cpp 0x42D21C, // CritterPoison.cpp }; -static std::vector excludeConflict = { +static std::array excludeConflict = { 0x42A0F8, // bugfixes.cpp 0x461495, // BarBoxes.cpp 0x42D21C, // CritterPoison.cpp @@ -41,7 +43,7 @@ static std::vector hackAddr = { {0x4C06D1, 5}, // module: AI - {0x4290B6, 5}, + //{0x4290B6, 5}, // module: BarBoxes {0x461342, 5}, {0x461243, 5}, {0x461493, 5}, //{0x461495, 1}, @@ -128,7 +130,7 @@ static std::vector hackAddr = { // Checking for conflicts requires all options in ddraw.ini to be enabled void PrintAddrList() { - long level = iniGetInt("Debugging", "Enable", 0, ::sfall::ddrawIni); + long level = IniReader::GetIntDefaultConfig("Debugging", "Enable", 0); if (level < 10) hackAddr.clear(); std::vector sortAddr(hackAddr); diff --git a/sfall/Delegate.h b/sfall/Delegate.h index 2ea67b89..6dd61215 100644 --- a/sfall/Delegate.h +++ b/sfall/Delegate.h @@ -51,11 +51,11 @@ public: } // Replaces the current list of functions with single function provided. - Delegate operator =(Functor func) { - clear(); - add(std::move(func)); - return *this; - } + //Delegate operator =(Functor func) { + // clear(); + // add(std::move(func)); + // return *this; + //} // Removes all functions. Delegate operator=(std::nullptr_t) { diff --git a/sfall/FalloutEngine/EngineUtils.cpp b/sfall/FalloutEngine/EngineUtils.cpp index 0935543a..bd18c3b8 100644 --- a/sfall/FalloutEngine/EngineUtils.cpp +++ b/sfall/FalloutEngine/EngineUtils.cpp @@ -28,23 +28,57 @@ namespace fo { -static MessageNode messageBuf; +static fo::MessageNode messageBuf; -const char* GetMessageStr(const MessageList* fileAddr, long messageId) { - return fo::func::getmsg(fileAddr, &messageBuf, messageId); +const char* GetMessageStr(const fo::MessageList* file, long messageId) { + return fo::func::getmsg(file, &messageBuf, messageId); } -const char* MessageSearch(const MessageList* fileAddr, long messageId) { +const char* MessageSearch(const fo::MessageList* file, long messageId) { messageBuf.number = messageId; - if (fo::func::message_search(fileAddr, &messageBuf) == 1) { + if (fo::func::message_search(file, &messageBuf) == 1) { return messageBuf.message; } return nullptr; } -Queue* QueueFind(GameObject* object, long type) { +fo::MessageNode* GetMsgNode(fo::MessageList* msgList, int msgNum) { + if (msgList != nullptr && msgList->numMsgs > 0) { + fo::MessageNode *msgNode = msgList->nodes; + long last = msgList->numMsgs - 1; + long first = 0; + long mid; + + // Use Binary Search to find msg + while (first <= last) { + mid = (first + last) / 2; + if (msgNum > msgNode[mid].number) + first = mid + 1; + else if (msgNum < msgNode[mid].number) + last = mid - 1; + else + return &msgNode[mid]; + } + } + return nullptr; +} + +// Alternative version of getmsg_ function +char* GetMsg(fo::MessageList* msgList, int msgNum, int msgType) { + fo::MessageNode *msgNode = GetMsgNode(msgList, msgNum); + if (msgNode) { + if (msgType == 2) { + return msgNode->message; + } else if (msgType == 1) { + return msgNode->audio; + } + } + return nullptr; +} + +fo::Queue* QueueFind(fo::GameObject* object, long type) { if (fo::var::queue) { - Queue* queue = fo::var::queue; + fo::Queue* queue = fo::var::queue; while (queue->object != object && queue->type != type) { queue = queue->next; if (!queue) break; @@ -54,33 +88,37 @@ Queue* QueueFind(GameObject* object, long type) { return nullptr; } -long AnimCodeByWeapon(GameObject* weapon) { +long AnimCodeByWeapon(fo::GameObject* weapon) { if (weapon != nullptr) { - Proto* proto = GetProto(weapon->protoId); - if (proto != nullptr && proto->item.type == item_type_weapon) { + fo::Proto* proto; + if (GetProto(weapon->protoId, &proto) && proto->item.type == item_type_weapon) { return proto->item.weapon.animationCode; } } return 0; } -Proto* GetProto(long pid) { - Proto* protoPtr; - if (fo::func::proto_ptr(pid, &protoPtr) != -1) { - return protoPtr; - } - return nullptr; +bool CheckProtoID(DWORD pid) { + if (pid == 0) return false; + long type = pid >> 24; + if (type > fo::ObjType::OBJ_TYPE_MISC) return false; + return (static_cast(pid & 0xFFFF) < fo::var::protoLists[type].totalCount); +} + +bool GetProto(long pid, fo::Proto** outProto) { + return (fo::func::proto_ptr(pid, outProto) != -1); } bool CritterCopyProto(long pid, long* &proto_dst) { - fo::Proto* protoPtr; - if (fo::func::proto_ptr(pid, &protoPtr) == -1) { + fo::Proto* proto; + bool result = GetProto(pid, &proto); + if (result) { + proto_dst = reinterpret_cast(new int32_t[104]); + std::memcpy(proto_dst, proto, 416); + } else { proto_dst = nullptr; - return false; } - proto_dst = reinterpret_cast(new long[104]); - memcpy(proto_dst, protoPtr, 416); - return true; + return result; } void SkillGetTags(long* result, long num) { @@ -93,20 +131,20 @@ void SkillSetTags(long* tags, long num) { fo::func::skill_set_tags(tags, num); } -long __fastcall GetItemType(GameObject* item) { - return fo::func::item_get_type(item); +long GetItemType(fo::GameObject* item) { + return fo::GetProto(item->protoId)->item.type; } -__declspec(noinline) GameObject* GetItemPtrSlot(GameObject* critter, InvenType slot) { - GameObject* itemPtr = nullptr; +__declspec(noinline) fo::GameObject* GetItemPtrSlot(fo::GameObject* critter, fo::InvenType slot) { + fo::GameObject* itemPtr = nullptr; switch (slot) { - case fo::INVEN_TYPE_LEFT_HAND: + case fo::InvenType::INVEN_TYPE_LEFT_HAND: itemPtr = fo::func::inven_left_hand(critter); break; - case fo::INVEN_TYPE_RIGHT_HAND: + case fo::InvenType::INVEN_TYPE_RIGHT_HAND: itemPtr = fo::func::inven_right_hand(critter); break; - case fo::INVEN_TYPE_WORN: + case fo::InvenType::INVEN_TYPE_WORN: itemPtr = fo::func::inven_worn(critter); break; } @@ -117,7 +155,7 @@ long& GetActiveItemMode() { return fo::var::itemButtonItems[fo::var::itemCurrentItem].mode; } -GameObject* GetActiveItem() { +fo::GameObject* GetActiveItem() { return fo::var::itemButtonItems[fo::var::itemCurrentItem].item; } @@ -135,12 +173,28 @@ long GetCurrentAttackMode() { hitMode = fo::var::itemButtonItems[activeHand].secondaryAttack; break; case 5: // reload mode - hitMode = fo::ATKTYPE_LWEAPON_RELOAD + activeHand; + hitMode = fo::AttackType::ATKTYPE_LWEAPON_RELOAD + activeHand; } } return hitMode; } +fo::AttackSubType GetWeaponType(DWORD weaponFlag) { + static const fo::AttackSubType weapon_types[9] = { + fo::AttackSubType::NONE, + fo::AttackSubType::UNARMED, + fo::AttackSubType::UNARMED, + fo::AttackSubType::MELEE, + fo::AttackSubType::MELEE, + fo::AttackSubType::THROWING, + fo::AttackSubType::GUNS, + fo::AttackSubType::GUNS, + fo::AttackSubType::GUNS + }; + DWORD type = weaponFlag & 0xF; + return (type < 9) ? weapon_types[type] : fo::AttackSubType::NONE; +} + bool HeroIsFemale() { return (fo::func::stat_level(fo::var::obj_dude, fo::Stat::STAT_gender) == fo::Gender::GENDER_FEMALE); } @@ -165,26 +219,26 @@ long __fastcall IsRadInfluence() { } bool IsNpcFlag(fo::GameObject* npc, long flag) { - Proto* protoPtr; - if (fo::func::proto_ptr(npc->protoId, &protoPtr) != -1) { - return (protoPtr->critter.critterFlags & (1 << flag)) != 0; + fo::Proto* proto; + if (GetProto(npc->protoId, &proto)) { + return (proto->critter.critterFlags & (1 << flag)) != 0; } return false; } void ToggleNpcFlag(fo::GameObject* npc, long flag, bool set) { - Proto* protoPtr; - if (fo::func::proto_ptr(npc->protoId, &protoPtr) != -1) { + fo::Proto* proto; + if (GetProto(npc->protoId, &proto)) { long bit = (1 << flag); if (set) { - protoPtr->critter.critterFlags |= bit; + proto->critter.critterFlags |= bit; } else { - protoPtr->critter.critterFlags &= ~bit; + proto->critter.critterFlags &= ~bit; } } } -// Returns the position of party member in the existing table (begins from 1) +// Returns the position of party member in the existing table (1 is added to the index position) long IsPartyMemberByPid(long pid) { size_t partyCount = fo::var::partyMemberMaxCount; if (partyCount) { @@ -372,8 +426,17 @@ void DrawToSurface(long width, long height, long fromX, long fromY, long fromWid //} // Fills the specified interface window with index color -void WinFillRect(long winID, long x, long y, long width, long height, BYTE indexColor) { +bool WinFillRect(long winID, long x, long y, long width, long height, BYTE indexColor) { fo::Window* win = fo::func::GNW_find(winID); + bool result = false; + if ((x + width) > win->width) { + width = win->width - x; + result = true; + } + if ((y + height) > win->height) { + height = win->height - y; + result = true; + } BYTE* surf = win->surface + (win->width * y) + x; long pitch = win->width - width; while (height--) { @@ -381,6 +444,7 @@ void WinFillRect(long winID, long x, long y, long width, long height, BYTE index while (w--) *surf++ = indexColor; surf += pitch; }; + return result; } // Fills the specified interface window with index color 0 (black color) @@ -505,10 +569,10 @@ DWORD GetMaxCharWidth() { // return charWidth; } -void RedrawObject(GameObject* obj) { - BoundRect rect; - func::obj_bound(obj, &rect); - func::tile_refresh_rect(&rect, obj->elevation); +void RedrawObject(fo::GameObject* obj) { + fo::BoundRect rect; + fo::func::obj_bound(obj, &rect); + fo::func::tile_refresh_rect(&rect, obj->elevation); } // Redraws all windows @@ -521,9 +585,9 @@ void RefreshGNW(bool skipOwner) { *(DWORD*)FO_VAR_doing_refresh_all = 0; } -/////////////////////////////////////////////////////////////////UNLISTED FRM FUNCTIONS////////////////////////////////////////////////////////////// +//////////////////////////// UNLISTED FRM FUNCTIONS //////////////////////////// -static bool LoadFrmHeader(UnlistedFrm *frmHeader, fo::DbFile* frmStream) { +static bool LoadFrmHeader(fo::UnlistedFrm *frmHeader, fo::DbFile* frmStream) { if (fo::func::db_freadInt(frmStream, &frmHeader->version) == -1) return false; else if (fo::func::db_freadShort(frmStream, &frmHeader->FPS) == -1) @@ -544,7 +608,7 @@ static bool LoadFrmHeader(UnlistedFrm *frmHeader, fo::DbFile* frmStream) { return true; } -static bool LoadFrmFrame(UnlistedFrm::Frame *frame, fo::DbFile* frmStream) { +static bool LoadFrmFrame(fo::UnlistedFrm::Frame *frame, fo::DbFile* frmStream) { //FRMframe *frameHeader = (FRMframe*)frameMEM; //BYTE* frameBuff = frame + sizeof(FRMframe); @@ -560,23 +624,32 @@ static bool LoadFrmFrame(UnlistedFrm::Frame *frame, fo::DbFile* frmStream) { return false; frame->indexBuff = new BYTE[frame->size]; - if (fo::func::db_fread(frame->indexBuff, frame->size, 1, frmStream) != 1) + if (fo::func::db_fread(frame->indexBuff, 1, frame->size, frmStream) != frame->size) return false; return true; } -UnlistedFrm *LoadUnlistedFrm(char *frmName, unsigned int folderRef) { +fo::UnlistedFrm *LoadUnlistedFrm(char *frmName, unsigned int folderRef) { if (folderRef > fo::OBJ_TYPE_SKILLDEX) return nullptr; - char *artfolder = fo::var::art[folderRef].path; // address of art type name + const char *artfolder = fo::var::art[folderRef].path; // address of art type name char frmPath[MAX_PATH]; - sprintf_s(frmPath, MAX_PATH, "art\\%s\\%s", artfolder, frmName); + if (fo::var::use_language) { + sprintf_s(frmPath, MAX_PATH, "art\\%s\\%s\\%s", (const char*)fo::var::language, artfolder, frmName); + } else { + sprintf_s(frmPath, MAX_PATH, "art\\%s\\%s", artfolder, frmName); + } - UnlistedFrm *frm = new UnlistedFrm; + fo::UnlistedFrm *frm = new fo::UnlistedFrm; - auto frmStream = fo::func::xfopen(frmPath, "rb"); + auto frmStream = fo::func::db_fopen(frmPath, "rb"); + + if (!frmStream && fo::var::use_language) { + sprintf_s(frmPath, MAX_PATH, "art\\%s\\%s", artfolder, frmName); + frmStream = fo::func::db_fopen(frmPath, "rb"); + } if (frmStream != nullptr) { if (!LoadFrmHeader(frm, frmStream)) { @@ -587,7 +660,7 @@ UnlistedFrm *LoadUnlistedFrm(char *frmName, unsigned int folderRef) { DWORD oriOffset_1st = frm->oriOffset[0]; DWORD oriOffset_new = 0; - frm->frames = new UnlistedFrm::Frame[6 * frm->numFrames]; + frm->frames = new fo::UnlistedFrm::Frame[6 * frm->numFrames]; for (int ori = 0; ori < 6; ori++) { if (ori == 0 || frm->oriOffset[ori] != oriOffset_1st) { frm->oriOffset[ori] = oriOffset_new; diff --git a/sfall/FalloutEngine/EngineUtils.h b/sfall/FalloutEngine/EngineUtils.h index 437440a6..d0ad2a51 100644 --- a/sfall/FalloutEngine/EngineUtils.h +++ b/sfall/FalloutEngine/EngineUtils.h @@ -43,18 +43,32 @@ __forceinline void sf_rect_free(fo::RectList* rect) { } // returns message string from given file or "Error" when not found -const char* GetMessageStr(const MessageList* fileAddr, long messageId); +const char* GetMessageStr(const fo::MessageList* file, long messageId); // similar to GetMessageStr, but returns nullptr when no message is found -const char* MessageSearch(const MessageList* fileAddr, long messageId); +const char* MessageSearch(const fo::MessageList* file, long messageId); -Queue* QueueFind(GameObject* object, long type); +fo::MessageNode* GetMsgNode(fo::MessageList* msgList, int msgNum); + +char* GetMsg(fo::MessageList* msgList, int msgNum, int msgType); + +fo::Queue* QueueFind(fo::GameObject* object, long type); // returns weapon animation code -long AnimCodeByWeapon(GameObject* weapon); +long AnimCodeByWeapon(fo::GameObject* weapon); -// returns pointer to prototype by PID, or nullptr on failure -Proto* GetProto(long pid); +bool CheckProtoID(DWORD pid); + +// returns False if the prototype does not exist, or pointer to prototype by PID in the outProto argument +bool GetProto(long pid, fo::Proto** outProto); + +// returns pointer to prototype by PID +// Note: use this function if you need to get the proto immediately without extra checks +__forceinline fo::Proto* GetProto(long pid) { + fo::Proto* proto; + fo::func::proto_ptr(pid, &proto); + return proto; +} bool CritterCopyProto(long pid, long* &proto_dst); @@ -64,16 +78,18 @@ void SkillGetTags(long* result, long num); // wrapper for skill_set_tags with bounds checking void SkillSetTags(long* tags, long num); -long __fastcall GetItemType(GameObject* item); +long GetItemType(fo::GameObject* item); -__declspec(noinline) GameObject* GetItemPtrSlot(GameObject* critter, InvenType slot); +__declspec(noinline) fo::GameObject* GetItemPtrSlot(fo::GameObject* critter, fo::InvenType slot); long& GetActiveItemMode(); -GameObject* GetActiveItem(); +fo::GameObject* GetActiveItem(); long GetCurrentAttackMode(); +fo::AttackSubType GetWeaponType(DWORD weaponFlag); + bool HeroIsFemale(); long CheckAddictByPid(fo::GameObject* critter, long pid); @@ -116,7 +132,7 @@ void DrawToSurface(long width, long height, long fromX, long fromY, long fromWid void DrawToSurface(long width, long height, long fromX, long fromY, long fromWidth, BYTE* fromSurf, long toX, long toY, long toWidth, long toHeight, BYTE* toSurf); // Fills the specified interface window with index color -void WinFillRect(long winID, long x, long y, long width, long height, BYTE indexColor); +bool WinFillRect(long winID, long x, long y, long width, long height, BYTE indexColor); // Fills the specified interface window with index color 0 (black color) void ClearWindow(long winID, bool refresh = true); @@ -148,11 +164,11 @@ DWORD GetCharGapWidth(); DWORD GetMaxCharWidth(); // Redraw the given object on screen (does not always redraws the whole object) -void RedrawObject(GameObject* obj); +void RedrawObject(fo::GameObject* obj); // Redraws all windows void RefreshGNW(bool skipOwner = false); -UnlistedFrm *LoadUnlistedFrm(char *frmName, unsigned int folderRef); +fo::UnlistedFrm *LoadUnlistedFrm(char *frmName, unsigned int folderRef); } diff --git a/sfall/FalloutEngine/Enums.h b/sfall/FalloutEngine/Enums.h index c5cea74b..0b2cdece 100644 --- a/sfall/FalloutEngine/Enums.h +++ b/sfall/FalloutEngine/Enums.h @@ -99,6 +99,18 @@ enum AnimCommand : long RB_END_ANIM = 0x200 }; +enum BodyPart : long { + Head = 0, + ArmLeft = 1, + ArmRight = 2, + Torso = 3, + LegRight = 4, + LegLeft = 5, + Eyes = 6, + Groin = 7, + Uncalled = 8 +}; + enum CritterFlags : long { Sneak = 0x01, // Can sneak ? @@ -117,6 +129,19 @@ enum CritterFlags : long NoKnockBack = 0x4000, // Can't be knocked back }; +enum ItemFlags : long +{ + // Weapon Flags: + BigGun = 0x00000100, + TwoHand = 0x00000200, + EnergyGun = 0x00000400, // sfall flag + + // Action Flags: + Use = 0x00000800, // object can be used + + HiddenItem = 0x08000000 // item is hidden +}; + enum DamageFlag : unsigned long { DAM_KNOCKED_OUT = 0x1, @@ -143,7 +168,9 @@ enum DamageFlag : unsigned long DAM_CRIP_RANDOM = 0x200000, DAM_BACKWASH = 0x400000, DAM_PERFORM_REVERSE = 0x800000, - DAM_PRESERVE_FLAGS = 0x80000000 // sfall, used for attack_complex + // sfall flags + DAM_KNOCKOUT_WOKEN = 0x40000000, // internal for op_critter_state_ + DAM_PRESERVE_FLAGS = 0x80000000 // used for attack_complex }; enum DamageType @@ -204,30 +231,30 @@ enum class Material : long }; namespace ObjectFlag { - enum ObjectFlag : DWORD { - Mouse_3d = 0x1, - WalkThru = 0x4, - Flat = 0x8, - NoBlock = 0x10, - Lighting = 0x20, - Temp = 0x400, - MultiHex = 0x800, - NoHighlight = 0x1000, - Used = 0x2000, - TransRed = 0x4000, - TransNone = 0x8000, - TransWall = 0x10000, - TransGlass = 0x20000, - TransSteam = 0x40000, - TransEnergy = 0x80000, - Left_Hand = 0x1000000, - Right_Hand = 0x2000000, - Worn = 0x4000000, - HiddenItem = 0x8000000, + enum ObjectFlag : unsigned long { + Mouse_3d = 0x00000001, + WalkThru = 0x00000004, + Flat = 0x00000008, + NoBlock = 0x00000010, + Lighting = 0x00000020, + Temp = 0x00000400, + MultiHex = 0x00000800, + NoHighlight = 0x00001000, + Used = 0x00002000, + TransRed = 0x00004000, + TransNone = 0x00008000, + TransWall = 0x00010000, + TransGlass = 0x00020000, + TransSteam = 0x00040000, + TransEnergy = 0x00080000, + Left_Hand = 0x01000000, + Right_Hand = 0x02000000, + Worn = 0x04000000, + HiddenItem = 0x08000000, WallTransEnd = 0x10000000, - LightThru = 0x20000000, - Seen = 0x40000000, - ShootThru = 0x80000000, + LightThru = 0x20000000, + Seen = 0x40000000, + ShootThru = 0x80000000, }; } @@ -252,8 +279,9 @@ enum ArtType : char }; // Some FO2 PIDs possibly used by engine -enum ProtoId : long +enum ProtoID : unsigned long { + PID_POWERED_ARMOR = 3, // PID_ROCK = 19, PID_SMALL_ENERGY_CELL = 38, PID_MICRO_FUSION_CELL = 39, @@ -293,17 +321,24 @@ enum ProtoId : long PID_ACTIVE_PLASTIC_EXPLOSIVE = 209, PID_ACTIVE_STEALTH_BOY = 210, PID_TECHNICAL_MANUAL = 228, + PID_HARDENED_POWER_ARMOR = 232, PID_CHEMISTRY_MANUAL = 237, PID_JET = 259, PID_JET_ANTIDOTE = 260, + PID_HEALING_POWDER = 273, PID_DECK_OF_TRAGIC_CARDS = 306, + PID_ADVANCED_POWER_ARMOR = 348, + PID_ADVANCED_POWER_ARMOR_MK2 = 349, // PID_GECK = 366, PID_SOLAR_SCORCHER = 390, PID_CAR_TRUNK = 455, PID_JESSE_CONTAINER = 467, - PID_Player = 16777216, - PID_DRIVABLE_CAR = 33555441, + // critter + PID_Player = 0x01000000, + + // scenery + PID_DRIVABLE_CAR = 0x020003F1, // index 1009 // misc type PID_CORPSE_BLOOD = 0x05000004, @@ -313,11 +348,12 @@ enum ProtoId : long //XX Critter defines XX //XXXXXXXXXXXXXXXXXXXXX -// Trait defines // -#define TRAIT_PERK (0) -#define TRAIT_OBJECT (1) -#define TRAIT_TRAIT (2) - +enum TraitType : long +{ + TRAIT_PERK = 0, + TRAIT_OBJECT = 1, + TRAIT_TRAIT = 2 +}; enum Perk : long { @@ -515,10 +551,10 @@ enum Stat : long STAT_rad_resist = 31, STAT_poison_resist = 32, // poison_resist MUST be the last derived stat - // nonderived stats + // non-derived stats STAT_age = 33, STAT_gender = 34, - // gender MUST be the last nonderived stat + // gender MUST be the last non-derived stat STAT_current_hp = 35, STAT_current_poison = 36, STAT_current_rad = 37, @@ -738,6 +774,15 @@ enum RollResult ROLL_CRITICAL_SUCCESS = 0x3, }; +enum CombatStateFlag : long +{ + InCombat = 1, + EnemyOutOfRange = 2, + InFlee = 4, + ReTarget = 8 // sfall flag (set in ai_try_attack_ before run away) +}; + +// Names of structure offsets used in the assembler code namespace Fields { enum CommonObj : long { @@ -753,8 +798,9 @@ namespace Fields { flags = 0x24, elevation = 0x28, inventory = 0x2C, + protoId = 0x64, - cid = 0x68, + cid = 0x68, // combatID, don't change while in combat lightDistance = 0x6C, lightIntensity = 0x70, outline = 0x74, @@ -784,6 +830,14 @@ namespace Fields { charges = 0x3C, ammoPid = 0x40, }; + + enum ComputeAttack : long + { + ctdAttackerFlags = 0x15, // flags2Source + ctdTarget = 0x20, + ctdMainTarget = 0x38, + ctdExtraTarget1 = 0x40, + }; } namespace WinFlags { @@ -805,13 +859,14 @@ namespace WinFlags { namespace AIpref { enum distance : long { - stay_close = 0, - charge = 1, - snipe = 2, - on_your_own = 3, - stay = 4 + stay_close = 0, // the attacker will stay at a distance no more than 5 hexes from the player (behavior only for party members, defined in ai_move_steps_closer, cai_perform_distance_prefs) + charge = 1, // AI will always try to get close to its target before or after attack + snipe = 2, // keep distance, when the distance between the attacker and the target decreases, the attacker will try to move away from the target to a distance of up to 10 hexes + on_your_own = 3, // no special behavior defined for this + stay = 4 // the attacker will, if possible, stay at the hex where the combat started (behavior defined in ai_move_steps_closer, ai_move_away) }; + // presets for party members enum disposition : long { none = -1, @@ -824,11 +879,12 @@ namespace AIpref { enum class attack_who : long { - whomever_attacking_me = 0, - strongest = 1, - weakest = 2, - whomever = 3, - closest = 4, + no_attack_mode = -1, + whomever_attacking_me = 0, // attack the target that the player is attacking (only for party members) + strongest = 1, // attack stronger targets (will always switch to stronger ones in combat) + weakest = 2, // attack weaker targets (will always switch to weaker ones in combat) + whomever = 3, // anyone, will attack the chosen target until it dies, or until retaliation occurs (combatai_check_retalization_) + closest = 4, // only attack near targets }; enum class run_away_mode : long @@ -850,13 +906,13 @@ namespace AIpref { ranged_over_melee = 3, ranged = 4, unarmed = 5, - unarmed_over_thrown = 6, // not available in party member control panel - random = 7 // not available in party member control panel + unarmed_over_thrown = 6, // not available for party member in control panel + random = 7 // not available for party member in control panel }; enum class area_attack_mode : long { - no_pref = -1, // special logic for NPC (not available in party member control panel) + no_pref = -1, // special logic for NPC (not available for party member in control panel) always = 0, sometimes = 1, // use random value from cap.secondary_freq be_sure = 2, // 85% hit chance diff --git a/sfall/FalloutEngine/Functions.cpp b/sfall/FalloutEngine/Functions.cpp index 408b6a65..78755a4b 100644 --- a/sfall/FalloutEngine/Functions.cpp +++ b/sfall/FalloutEngine/Functions.cpp @@ -408,7 +408,7 @@ BYTE* __fastcall loadPCX(const char* file, long* width, long* height) { } } -long __fastcall get_game_config_string(const char* outValue, const char* section, const char* param) { +long __fastcall get_game_config_string(const char** outValue, const char* section, const char* param) { __asm { mov ebx, param; mov eax, FO_VAR_game_config; diff --git a/sfall/FalloutEngine/Functions.h b/sfall/FalloutEngine/Functions.h index b0ad07f3..af529a98 100644 --- a/sfall/FalloutEngine/Functions.h +++ b/sfall/FalloutEngine/Functions.h @@ -82,7 +82,7 @@ void __cdecl trans_buf_to_buf(BYTE* src, long width, long height, long src_width BYTE* __fastcall loadPCX(const char* file, long* width, long* height); -long __fastcall get_game_config_string(const char* outValue, const char* section, const char* param); +long __fastcall get_game_config_string(const char** outValue, const char* section, const char* param); // X-Macro for wrapper functions. #define WRAP_WATCOM_FUNC0(retType, name) \ diff --git a/sfall/FalloutEngine/Functions_def.h b/sfall/FalloutEngine/Functions_def.h index ca2d4224..696c94c9 100644 --- a/sfall/FalloutEngine/Functions_def.h +++ b/sfall/FalloutEngine/Functions_def.h @@ -14,122 +14,106 @@ NOTES: be careful not to use reserved words, including ASM instructions (push, pop, mov, div, etc.) */ -using namespace fo; - /* For functions that have 3 or more arguments, it is preferable to use the fastcall calling convention because the compiler builds the better/optimized code when calling the engine functions */ WRAP_WATCOM_FFUNC4(long, _word_wrap, const char*, text, int, maxWidth, DWORD*, buf, BYTE*, count) -WRAP_WATCOM_FFUNC3(long, ai_pick_hit_mode, GameObject*, source, GameObject*, item, GameObject*, target) -WRAP_WATCOM_FFUNC3(GameObject*, ai_search_inven_weap, GameObject*, source, long, apCheck, GameObject*, target) -WRAP_WATCOM_FFUNC3(void, check_for_death, GameObject*, critter, long, amountDamage, long*, flags) -WRAP_WATCOM_FFUNC3(void, correctFidForRemovedItem, GameObject*, critter, GameObject*, item, long, slotFlag) +WRAP_WATCOM_FFUNC4(fo::GameObject*, ai_best_weapon, fo::GameObject*, source, fo::GameObject*, prevItem, fo::GameObject*, checkItem, fo::GameObject*, target) +WRAP_WATCOM_FFUNC3(bool, ai_can_use_weapon, fo::GameObject*, critter, fo::GameObject*, item, DWORD, hitMode) +WRAP_WATCOM_FFUNC3(long, ai_have_ammo, fo::GameObject*, critter, fo::GameObject*, item, fo::GameObject**, outAmmo) +WRAP_WATCOM_FFUNC3(long, ai_pick_hit_mode, fo::GameObject*, source, fo::GameObject*, item, fo::GameObject*, target) +WRAP_WATCOM_FFUNC3(fo::GameObject*, ai_search_inven_weap, fo::GameObject*, source, long, apCheck, fo::GameObject*, target) +WRAP_WATCOM_FFUNC3(void, check_for_death, fo::GameObject*, critter, long, amountDamage, long*, flags) +WRAP_WATCOM_FFUNC3(void, correctFidForRemovedItem, fo::GameObject*, critter, fo::GameObject*, item, long, slotFlag) WRAP_WATCOM_FFUNC7(long, createWindow, const char*, winName, DWORD, x, DWORD, y, DWORD, width, DWORD, height, long, color, long, flags) -WRAP_WATCOM_FFUNC4(long, determine_to_hit, GameObject*, source, GameObject*, target, long, bodyPart, long, hitMode) +WRAP_WATCOM_FFUNC4(long, determine_to_hit, fo::GameObject*, source, fo::GameObject*, target, long, bodyPart, long, hitMode) WRAP_WATCOM_FFUNC3(void, display_inventory, long, inventoryOffset, long, visibleOffset, long, mode) WRAP_WATCOM_FFUNC4(void, display_target_inventory, long, inventoryOffset, long, visibleOffset, DWORD*, targetInventory, long, mode) -WRAP_WATCOM_FFUNC3(FrmFrameData*, frame_ptr, FrmHeaderData*, frm, long, frame, long, direction) -WRAP_WATCOM_FFUNC3(void, GNW_win_refresh, Window*, win, BoundRect*, rect, long*, buffer) +WRAP_WATCOM_FFUNC3(fo::FrmFrameData*, frame_ptr, fo::FrmHeaderData*, frm, long, frame, long, direction) +WRAP_WATCOM_FFUNC3(void, GNW_win_refresh, fo::Window*, win, fo::BoundRect*, rect, long*, buffer) WRAP_WATCOM_FFUNC3(void, intface_update_items, long, animate, long, modeLeft, long, modeRight) -WRAP_WATCOM_FFUNC3(GameObject*, inven_find_type, GameObject*, critter, long, itemType, DWORD*, buf) -WRAP_WATCOM_FFUNC3(long, item_add_force, GameObject*, critter, GameObject*, item, long, count) -WRAP_WATCOM_FFUNC3(long, item_w_mp_cost, GameObject*, source, long, hitMode, long, isCalled) -WRAP_WATCOM_FFUNC7(void, make_straight_path_func, GameObject*, objFrom, DWORD, tileFrom, DWORD, tileTo, void*, rotationPtr, DWORD*, result, long, flags, void*, func) +WRAP_WATCOM_FFUNC3(fo::GameObject*, inven_find_type, fo::GameObject*, critter, long, itemType, DWORD*, slot) +WRAP_WATCOM_FFUNC3(long, inven_wield, fo::GameObject*, critter, fo::GameObject*, item, long, slot) +WRAP_WATCOM_FFUNC3(long, item_add_force, fo::GameObject*, critter, fo::GameObject*, item, long, count) +WRAP_WATCOM_FFUNC3(long, item_mp_cost, fo::GameObject*, source, long, hitMode, long, isCalled) +WRAP_WATCOM_FFUNC3(long, item_w_mp_cost, fo::GameObject*, source, long, hitMode, long, isCalled) +// Calculates path and returns it's length +WRAP_WATCOM_FFUNC6(long, make_path_func, fo::GameObject*, objectFrom, long, tileFrom, long, tileTo, char*, pathDataBuffer, long, checkTileTo, void*, blockingFunc) +WRAP_WATCOM_FFUNC7(long, make_straight_path_func, fo::GameObject*, objFrom, DWORD, tileFrom, DWORD, tileTo, void*, arrayPtr, DWORD*, outObject, long, flags, void*, blockingFunc) WRAP_WATCOM_FFUNC3(long, message_find, DWORD*, msgFile, long, msgNumber, DWORD*, outBuf) WRAP_WATCOM_FFUNC4(long, mouse_click_in, long, x, long, y, long, x_offs, long, y_offs) WRAP_WATCOM_FFUNC4(long, mouse_in, long, x, long, y, long, x_offs, long, y_offs) -WRAP_WATCOM_FFUNC3(GameObject*, obj_blocking_at, GameObject*, object, long, tile, long, elevation) -WRAP_WATCOM_FFUNC4(long, obj_move_to_tile, GameObject*, object, long, tile, long, elevation, RECT*, rect) -WRAP_WATCOM_FFUNC3(long, obj_new_sid_inst, GameObject*, object, long, sType, long, scriptIndex) -WRAP_WATCOM_FFUNC3(GameObject*, object_under_mouse, long, crSwitch, long, inclDude, long, elevation) -WRAP_WATCOM_FFUNC4(long, queue_add, long, time, GameObject*, object, void*, data, long, qType) +WRAP_WATCOM_FFUNC3(fo::GameObject*, obj_blocking_at, fo::GameObject*, object, long, tile, long, elevation) +WRAP_WATCOM_FFUNC4(long, obj_dist_with_tile, fo::GameObject*, source, long, sourceTile, fo::GameObject*, target, long, targetTile) +WRAP_WATCOM_FFUNC4(long, obj_move_to_tile, fo::GameObject*, object, long, tile, long, elevation, RECT*, rect) +WRAP_WATCOM_FFUNC3(long, obj_new_sid_inst, fo::GameObject*, object, long, sType, long, scriptIndex) +WRAP_WATCOM_FFUNC3(fo::GameObject*, object_under_mouse, long, crSwitch, long, inclDude, long, elevation) +WRAP_WATCOM_FFUNC4(void, qsort, void*, base, long, number, long, elSize, DWORD, comp) +WRAP_WATCOM_FFUNC4(long, queue_add, long, time, fo::GameObject*, object, void*, data, long, qType) WRAP_WATCOM_FFUNC4(void, register_object_call, long*, target, long*, source, void*, func, long, delay) -WRAP_WATCOM_FFUNC4(long, register_object_move_to_object, GameObject*, source, GameObject*, target, long, distance, long, delay) -WRAP_WATCOM_FFUNC4(long, register_object_run_to_object, GameObject*, source, GameObject*, target, long, distance, long, delay) +WRAP_WATCOM_FFUNC4(long, register_object_move_to_object, fo::GameObject*, source, fo::GameObject*, target, long, distance, long, delay) +WRAP_WATCOM_FFUNC4(long, register_object_run_to_object, fo::GameObject*, source, fo::GameObject*, target, long, distance, long, delay) +WRAP_WATCOM_FFUNC3(long, register_object_play_sfx, fo::GameObject*, object, const char*, sfxName, long, delay) WRAP_WATCOM_FFUNC3(long, scr_get_local_var, long, sid, long, varId, long*, value) WRAP_WATCOM_FFUNC3(long, scr_set_local_var, long, sid, long, varId, long, value) -WRAP_WATCOM_FFUNC6(long, text_object_create, GameObject*, object, const char*, text, long, font, long, colorText, long, colorOutline, BoundRect*, rect) +WRAP_WATCOM_FFUNC6(long, text_object_create, fo::GameObject*, object, const char*, text, long, font, long, colorText, long, colorOutline, fo::BoundRect*, rect) +WRAP_WATCOM_FFUNC3(long, tile_coord, long, tile, long*, outX, long*, outY) // the fourth argument of the function is not used WRAP_WATCOM_FFUNC3(long, tile_num_in_direction, long, tile, long, rotation, long, distance) WRAP_WATCOM_FFUNC8(void, trans_cscale, void*, fromBuff, long, width, long, height, long, fromPitch, void*, toBuff, long, toWidth, long, toHeight, long, toPitch) -WRAP_WATCOM_FFUNC3(void, win_clip, Window*, window, RectList**, rects, void*, buffer) +WRAP_WATCOM_FFUNC3(void, win_clip, fo::Window*, window, fo::RectList**, rects, void*, buffer) WRAP_WATCOM_FFUNC9(long, windowWrapLineWithSpacing, long, winID, const char*, text, long, width, long, height, long, x, long, y, long, color, long, alignment, long, lineSpacing) WRAP_WATCOM_FFUNC4(void, wmInterfaceDrawSubTileRectFogged, BYTE*, surface, long, width, long, height, long, surfaceWidth) -WRAP_WATCOM_FFUNC3(const char*, interpretGetString, Program*, scriptPtr, DWORD, dataType, DWORD, strId) +WRAP_WATCOM_FFUNC3(const char*, interpretGetString, fo::Program*, scriptPtr, DWORD, dataType, DWORD, strId) /* stdcall */ -WRAP_WATCOM_FUNC1(AIcap*, ai_cap, GameObject*, critter) -WRAP_WATCOM_FUNC2(void, ai_print_msg, GameObject*, object, long, mode) -WRAP_WATCOM_FUNC1(Program*, allocateProgram, const char*, filePath) +WRAP_WATCOM_FUNC1(fo::AIcap*, ai_cap, fo::GameObject*, critter) +WRAP_WATCOM_FUNC2(void, ai_print_msg, fo::GameObject*, object, long, mode) +WRAP_WATCOM_FUNC1(fo::Program*, allocateProgram, const char*, filePath) WRAP_WATCOM_FUNC1(bool, art_exists, long, artFid) WRAP_WATCOM_FUNC0(void, art_flush) WRAP_WATCOM_FUNC1(const char*, art_get_name, long, artFID) WRAP_WATCOM_FUNC5(long, art_id, long, artType, long, lstIndex, long, animCode, long, weaponCode, long, directionCode) -WRAP_WATCOM_FUNC3(BYTE*, art_frame_data, FrmHeaderData*, frm, long, frameNum, long, rotation) -WRAP_WATCOM_FUNC3(long, art_frame_width, FrmHeaderData*, frm, long, frameNum, long, rotation) -WRAP_WATCOM_FUNC3(long, art_frame_length, FrmHeaderData*, frm, long, frameNum, long, rotation) -WRAP_WATCOM_FUNC2(FrmHeaderData*, art_ptr_lock, long, frmId, DWORD*, lockPtr) +WRAP_WATCOM_FUNC3(BYTE*, art_frame_data, fo::FrmHeaderData*, frm, long, frameNum, long, rotation) +WRAP_WATCOM_FUNC3(long, art_frame_width, fo::FrmHeaderData*, frm, long, frameNum, long, rotation) +WRAP_WATCOM_FUNC3(long, art_frame_length, fo::FrmHeaderData*, frm, long, frameNum, long, rotation) +WRAP_WATCOM_FUNC2(fo::FrmHeaderData*, art_ptr_lock, long, frmId, DWORD*, lockPtr) WRAP_WATCOM_FUNC4(BYTE*, art_ptr_lock_data, long, frmId, long, frameNum, long, rotation, DWORD*, lockPtr) WRAP_WATCOM_FUNC4(BYTE*, art_lock, long, frmId, DWORD*, lockPtr, long*, widthOut, long*, heightOut) WRAP_WATCOM_FUNC1(long, art_ptr_unlock, DWORD, lockId) -WRAP_WATCOM_FUNC2(long, barter_compute_value, GameObject*, source, GameObject*, target) +WRAP_WATCOM_FUNC2(long, barter_compute_value, fo::GameObject*, source, fo::GameObject*, target) WRAP_WATCOM_FUNC1(long, block_for_tocks, long, ticks) -WRAP_WATCOM_FUNC1(const char*, critter_name, GameObject*, critter) // Returns the name of the critter +WRAP_WATCOM_FUNC2(long, combat_turn, fo::GameObject*, critter, long, isDudeTurn) // Perform combat turn for a given critter +WRAP_WATCOM_FUNC1(long, critter_body_type, fo::GameObject*, critter) +WRAP_WATCOM_FUNC1(long, critter_is_dead, fo::GameObject*, critter) +WRAP_WATCOM_FUNC1(const char*, critter_name, fo::GameObject*, critter) // Returns the name of the critter WRAP_WATCOM_FUNC1(void, critter_pc_set_name, const char*, newName) // Change the name of playable character -/* Database functions */ -WRAP_WATCOM_FUNC1(bool, db_access, const char*, fileName) // Checks if given file exists in DB -WRAP_WATCOM_FUNC1(long, db_fclose, DbFile*, file) -WRAP_WATCOM_FUNC2(DbFile*, db_fopen, const char*, path, const char*, mode) -WRAP_WATCOM_FUNC1(long, db_fgetc, DbFile*, file) -WRAP_WATCOM_FUNC3(char*, db_fgets, char*, buf, long, max_count, DbFile*, file) -WRAP_WATCOM_FUNC4(long, db_fread, void*, buf, long, elsize, long, count, DbFile*, file) -WRAP_WATCOM_FUNC3(long, db_fseek, DbFile*, file, long, pos, long, origin) -WRAP_WATCOM_FUNC2(void, db_free_file_list, char***, fileList, DWORD, arg2) // Destroys filelist array created by db_get_file_list -WRAP_WATCOM_FUNC2(long, db_freadByte, DbFile*, file, BYTE*, _out) -WRAP_WATCOM_FUNC2(long, db_freadShort, DbFile*, file, WORD*, _out) -WRAP_WATCOM_FUNC2(long, db_freadInt, DbFile*, file, DWORD*, _out) -WRAP_WATCOM_FUNC3(long, db_freadByteCount, DbFile*, file, BYTE*, cptr, long, count) -WRAP_WATCOM_FUNC3(long, db_freadShortCount, DbFile*, file, WORD*, dest, long, count) -WRAP_WATCOM_FUNC3(long, db_freadIntCount, DbFile*, file, DWORD*, dest, long, count) -WRAP_WATCOM_FUNC2(long, db_fwriteByte, DbFile*, file, long, value) -WRAP_WATCOM_FUNC2(long, db_fwriteInt, DbFile*, file, long, value) -WRAP_WATCOM_FUNC3(long, db_fwriteByteCount, DbFile*, file, const BYTE*, cptr, long, count) -WRAP_WATCOM_FUNC2(long, db_dir_entry, const char*, fileName, DWORD*, sizeOut) // Check fallout file and get file size (result 0 - file exists) -// Searches files in DB by given path/filename mask and stores result in fileList -// fileList is a pointer to a variable, that will be assigned with an address of an array of char* strings -WRAP_WATCOM_FUNC2(long, db_get_file_list, const char*, searchMask, char***, fileList) // Returns number of elements in *fileList -WRAP_WATCOM_FUNC2(long, db_init, const char*, path_dat, const char*, path_patches) -WRAP_WATCOM_FUNC1(void*, dbase_open, const char*, fileName) -WRAP_WATCOM_FUNC1(void, dbase_close, void*, dbPtr) -//////////////////////// +WRAP_WATCOM_FUNC1(long, critterIsOverloaded, fo::GameObject*, critter) WRAP_WATCOM_FUNC1(void, display_print, const char*, msg) // Displays message in main UI console window WRAP_WATCOM_FUNC0(void, display_stats) -WRAP_WATCOM_FUNC2(long, combat_turn, GameObject*, critter, long, isDudeTurn) // Perform combat turn for a given critter -WRAP_WATCOM_FUNC1(long, critter_body_type, GameObject*, critter) -WRAP_WATCOM_FUNC1(long, critter_is_dead, GameObject*, critter) -WRAP_WATCOM_FUNC1(void, EndLoad, DbFile*, file) +WRAP_WATCOM_FUNC1(void, EndLoad, fo::DbFile*, file) // Execute script proc by internal proc number (from script's proc table, basically a sequential number of a procedure as defined in code, starting from 1) -WRAP_WATCOM_FUNC2(void, executeProcedure, Program*, sptr, long, procNum) +WRAP_WATCOM_FUNC2(void, executeProcedure, fo::Program*, sptr, long, procPosition) WRAP_WATCOM_FUNC1(long, folder_print_line, const char*, text) WRAP_WATCOM_FUNC1(long, folder_print_seperator, const char*, text) -WRAP_WATCOM_FUNC1(const char*, findCurrentProc, Program*, program) // Returns the name of current procedure by program pointer +WRAP_WATCOM_FUNC1(const char*, findCurrentProc, fo::Program*, program) // Returns the name of current procedure by program pointer WRAP_WATCOM_FUNC1(long, FMtext_width, const char*, text) WRAP_WATCOM_FUNC1(long, game_get_global_var, long, globalVar) WRAP_WATCOM_FUNC0(long, get_input) // Searches for message ID in given message file and places result in result argument -WRAP_WATCOM_FUNC3(const char*, getmsg, const MessageList*, fileAddr, MessageNode*, result, long, messageId) +WRAP_WATCOM_FUNC3(const char*, getmsg, const fo::MessageList*, fileAddr, fo::MessageNode*, result, long, messageId) WRAP_WATCOM_FUNC1(void, gdialogDisplayMsg, const char*, message) WRAP_WATCOM_FUNC1(void, gmouse_3d_set_mode, long, mode) WRAP_WATCOM_FUNC1(long, gmouse_set_cursor, long, picNum) WRAP_WATCOM_FUNC1(long, gsound_background_volume_get_set, long, setVolume) WRAP_WATCOM_FUNC1(void, gsound_play_sfx_file, const char*, name) // Plays SFX sound with given name -WRAP_WATCOM_FUNC1(Window*, GNW_find, long, winRef) -WRAP_WATCOM_FUNC2(long, interpret, Program*, program, long, arg2) +WRAP_WATCOM_FUNC1(fo::Window*, GNW_find, long, winRef) +WRAP_WATCOM_FUNC2(long, interpret, fo::Program*, program, long, arg2) // Finds procedure ID for given script program pointer and procedure name -WRAP_WATCOM_FUNC2(long, interpretFindProcedure, Program*, scriptPtr, const char*, procName) -WRAP_WATCOM_FUNC1(long, interpretPopShort, Program*, scriptPtr) // Pops value type from Data stack (must be followed by InterpretPopLong) -WRAP_WATCOM_FUNC1(long, interpretPopLong, Program*, scriptPtr) // Pops value from Data stack (must be preceded by InterpretPopShort) +WRAP_WATCOM_FUNC2(long, interpretFindProcedure, fo::Program*, scriptPtr, const char*, procName) +WRAP_WATCOM_FUNC1(long, interpretPopShort, fo::Program*, scriptPtr) // Pops value type from Data stack (must be followed by InterpretPopLong) +WRAP_WATCOM_FUNC1(long, interpretPopLong, fo::Program*, scriptPtr) // Pops value from Data stack (must be preceded by InterpretPopShort) WRAP_WATCOM_FUNC2(long, intface_get_attack, DWORD*, hitMode, DWORD*, isSecondary) WRAP_WATCOM_FUNC0(long, intface_is_item_right_hand) WRAP_WATCOM_FUNC0(long, intface_is_hidden) @@ -138,134 +122,134 @@ WRAP_WATCOM_FUNC0(void, intface_toggle_item_state) WRAP_WATCOM_FUNC1(void, intface_update_ac, long, animate) WRAP_WATCOM_FUNC2(void, intface_update_move_points, long, ap, long, freeAP) WRAP_WATCOM_FUNC0(void, intface_use_item) -WRAP_WATCOM_FUNC1(GameObject*, inven_left_hand, GameObject*, critter) // Item in critter's left hand slot -WRAP_WATCOM_FUNC1(GameObject*, inven_right_hand, GameObject*, critter) // Item in critter's right hand slot -WRAP_WATCOM_FUNC2(GameObject*, inven_pid_is_carried_ptr, GameObject*, invenObj, long, pid) -WRAP_WATCOM_FUNC2(long, inven_unwield, GameObject*, critter, long, slot) -WRAP_WATCOM_FUNC1(GameObject*, inven_worn, GameObject*, critter) // Critter worn item (armor) +WRAP_WATCOM_FUNC1(fo::GameObject*, inven_left_hand, fo::GameObject*, critter) // Item in critter's left hand slot +WRAP_WATCOM_FUNC1(fo::GameObject*, inven_right_hand, fo::GameObject*, critter) // Item in critter's right hand slot +WRAP_WATCOM_FUNC2(fo::GameObject*, inven_pid_is_carried_ptr, fo::GameObject*, invenObj, long, pid) +WRAP_WATCOM_FUNC2(long, inven_unwield, fo::GameObject*, critter, long, slot) +WRAP_WATCOM_FUNC1(fo::GameObject*, inven_worn, fo::GameObject*, critter) // Critter worn item (armor) WRAP_WATCOM_FUNC1(long, is_pc_flag, long, flag) WRAP_WATCOM_FUNC0(long, is_pc_sneak_working) -WRAP_WATCOM_FUNC2(long, is_within_perception, GameObject*, source, GameObject*, target) -WRAP_WATCOM_FUNC1(long, isPartyMember, GameObject*, obj) -WRAP_WATCOM_FUNC1(long, item_c_curr_size, GameObject*, critter) -WRAP_WATCOM_FUNC1(long, item_caps_total, GameObject*, object) -WRAP_WATCOM_FUNC1(long, item_get_type, GameObject*, item) -WRAP_WATCOM_FUNC2(GameObject*, item_hit_with, GameObject*, critter, long, hitMode) -WRAP_WATCOM_FUNC1(long, item_m_dec_charges, GameObject*, item) // Returns 0 on success, -1 if the item has no charges -WRAP_WATCOM_FUNC1(long, item_size, GameObject*, item) -WRAP_WATCOM_FUNC1(long, item_total_cost, GameObject*, object) -WRAP_WATCOM_FUNC1(long, item_total_weight, GameObject*, object) -WRAP_WATCOM_FUNC1(long, item_w_anim_code, GameObject*, item) -WRAP_WATCOM_FUNC2(long, item_w_anim_weap, GameObject*, item, DWORD, hitMode) -WRAP_WATCOM_FUNC2(long, item_w_compute_ammo_cost, GameObject*, item, DWORD*, rounds) -WRAP_WATCOM_FUNC1(long, item_w_curr_ammo, GameObject*, item) -WRAP_WATCOM_FUNC2(long, item_w_damage, GameObject*, critter, long, hitMode) -WRAP_WATCOM_FUNC1(long, item_w_dam_div, GameObject*, item) -WRAP_WATCOM_FUNC1(long, item_w_dam_mult, GameObject*, item) -WRAP_WATCOM_FUNC1(long, item_w_dr_adjust, GameObject*, item) -WRAP_WATCOM_FUNC1(long, item_w_max_ammo, GameObject*, item) -WRAP_WATCOM_FUNC2(long, item_w_range, GameObject*, critter, long, hitMode) -WRAP_WATCOM_FUNC2(long, item_w_reload, GameObject*, weapon, GameObject*, ammo) -WRAP_WATCOM_FUNC1(long, item_w_rounds, GameObject*, item) -WRAP_WATCOM_FUNC2(long, item_w_subtype, GameObject*, item, long, hitMode) -WRAP_WATCOM_FUNC1(long, item_weight, GameObject*, item) +WRAP_WATCOM_FUNC2(long, is_within_perception, fo::GameObject*, source, fo::GameObject*, target) +WRAP_WATCOM_FUNC1(long, isPartyMember, fo::GameObject*, obj) +WRAP_WATCOM_FUNC1(long, item_c_curr_size, fo::GameObject*, critter) +WRAP_WATCOM_FUNC1(long, item_caps_total, fo::GameObject*, object) +WRAP_WATCOM_FUNC1(long, item_get_type, fo::GameObject*, item) +WRAP_WATCOM_FUNC2(fo::GameObject*, item_hit_with, fo::GameObject*, critter, long, hitMode) +WRAP_WATCOM_FUNC1(long, item_m_dec_charges, fo::GameObject*, item) // Returns 0 on success, -1 if the item has no charges +WRAP_WATCOM_FUNC1(long, item_size, fo::GameObject*, item) +WRAP_WATCOM_FUNC1(long, item_total_cost, fo::GameObject*, object) +WRAP_WATCOM_FUNC1(long, item_total_weight, fo::GameObject*, object) +WRAP_WATCOM_FUNC1(long, item_w_anim_code, fo::GameObject*, item) +WRAP_WATCOM_FUNC2(long, item_w_anim_weap, fo::GameObject*, item, fo::AttackType, hitMode) +WRAP_WATCOM_FUNC2(long, item_w_compute_ammo_cost, fo::GameObject*, item, DWORD*, rounds) +WRAP_WATCOM_FUNC1(long, item_w_curr_ammo, fo::GameObject*, item) +WRAP_WATCOM_FUNC2(long, item_w_damage, fo::GameObject*, critter, long, hitMode) +WRAP_WATCOM_FUNC1(long, item_w_dam_div, fo::GameObject*, item) +WRAP_WATCOM_FUNC1(long, item_w_dam_mult, fo::GameObject*, item) +WRAP_WATCOM_FUNC1(long, item_w_dr_adjust, fo::GameObject*, item) +WRAP_WATCOM_FUNC1(long, item_w_max_ammo, fo::GameObject*, item) +WRAP_WATCOM_FUNC1(long, item_w_primary_mp_cost, fo::GameObject*, item) +WRAP_WATCOM_FUNC2(long, item_w_range, fo::GameObject*, critter, long, hitMode) +WRAP_WATCOM_FUNC2(long, item_w_reload, fo::GameObject*, weapon, fo::GameObject*, ammo) +WRAP_WATCOM_FUNC1(long, item_w_rounds, fo::GameObject*, item) +WRAP_WATCOM_FUNC1(long, item_w_secondary_mp_cost, fo::GameObject*, item) +WRAP_WATCOM_FUNC2(long, item_w_subtype, fo::GameObject*, item, long, hitMode) +WRAP_WATCOM_FUNC1(long, item_weight, fo::GameObject*, item) WRAP_WATCOM_FUNC2(long, light_get_tile, long, elevation, long, tileNum) // Returns light level at given tile -WRAP_WATCOM_FUNC2(long, load_frame, const char*, filename, FrmFile**, frmPtr) -WRAP_WATCOM_FUNC1(Program*, loadProgram, const char*, fileName) +WRAP_WATCOM_FUNC2(long, load_frame, const char*, filename, fo::FrmFile**, frmPtr) +WRAP_WATCOM_FUNC1(fo::Program*, loadProgram, const char*, fileName) WRAP_WATCOM_FUNC1(const char*, map_get_short_name, long, mapID) WRAP_WATCOM_FUNC2(void, MapDirErase, const char*, folder, const char*, ext) WRAP_WATCOM_FUNC1(void, mem_free, void*, mem) WRAP_WATCOM_FUNC2(void*, mem_realloc, void*, lpmem, DWORD, msize) -WRAP_WATCOM_FUNC2(long, message_add, MessageList*, file, MessageNode*, msg) -WRAP_WATCOM_FUNC1(long, message_exit, MessageList*, msgList) // Destroys message list -WRAP_WATCOM_FUNC1(long, message_filter, MessageList*, file) -WRAP_WATCOM_FUNC2(long, message_load, MessageList*, msgList, const char*, msgFilePath) // Loads MSG file into given MessageList +WRAP_WATCOM_FUNC2(long, message_add, fo::MessageList*, file, fo::MessageNode*, msg) +WRAP_WATCOM_FUNC1(long, message_exit, fo::MessageList*, msgList) // Destroys message list +WRAP_WATCOM_FUNC1(long, message_filter, fo::MessageList*, file) +WRAP_WATCOM_FUNC2(long, message_load, fo::MessageList*, msgList, const char*, msgFilePath) // Loads MSG file into given MessageList WRAP_WATCOM_FUNC2(long, message_make_path, char*, outpath, char*, path) -WRAP_WATCOM_FUNC2(long, message_search, const MessageList*, file, MessageNode*, msg) +WRAP_WATCOM_FUNC2(long, message_search, const fo::MessageList*, file, fo::MessageNode*, msg) WRAP_WATCOM_FUNC2(void, mouse_get_position, long*, outX, long*, outY) WRAP_WATCOM_FUNC0(void, mouse_show) WRAP_WATCOM_FUNC0(void, mouse_hide) -// Calculates path and returns it's length -WRAP_WATCOM_FUNC6(long, make_path_func, GameObject*, objectFrom, long, tileFrom, long, tileTo, char*, pathDataBuffer, long, arg5, void*, blockingFunc) WRAP_WATCOM_FUNC0(long, new_obj_id) -WRAP_WATCOM_FUNC2(void, obj_bound, GameObject*, object, BoundRect*, boundRect) // Calculates bounding box (rectangle) for a given object -WRAP_WATCOM_FUNC1(long, obj_destroy, GameObject*, object) -WRAP_WATCOM_FUNC2(long, obj_dist, GameObject*, obj_src, GameObject*, obj_trg) -WRAP_WATCOM_FUNC2(long, obj_erase_object, GameObject*, object, BoundRect*, boundRect) -WRAP_WATCOM_FUNC0(GameObject*, obj_find_first) -WRAP_WATCOM_FUNC0(GameObject*, obj_find_next) -WRAP_WATCOM_FUNC2(GameObject*, obj_find_first_at_tile, long, elevation, long, tileNum) -WRAP_WATCOM_FUNC0(GameObject*, obj_find_next_at_tile) -WRAP_WATCOM_FUNC2(long, obj_pid_new, GameObject*, object, long, pid) -WRAP_WATCOM_FUNC1(long, obj_lock_is_jammed, GameObject*, object) // Checks/unjams jammed locks -WRAP_WATCOM_FUNC1(void, obj_unjam_lock, GameObject*, object) -WRAP_WATCOM_FUNC1(long, partyMemberGetCurLevel, GameObject*, obj) +WRAP_WATCOM_FUNC2(void, obj_bound, fo::GameObject*, object, fo::BoundRect*, boundRect) // Calculates bounding box (rectangle) for a given object +WRAP_WATCOM_FUNC1(long, obj_destroy, fo::GameObject*, object) +WRAP_WATCOM_FUNC2(long, obj_dist, fo::GameObject*, obj_src, fo::GameObject*, obj_trg) +WRAP_WATCOM_FUNC2(long, obj_erase_object, fo::GameObject*, object, fo::BoundRect*, boundRect) +WRAP_WATCOM_FUNC0(fo::GameObject*, obj_find_first) +WRAP_WATCOM_FUNC0(fo::GameObject*, obj_find_next) +WRAP_WATCOM_FUNC2(fo::GameObject*, obj_find_first_at_tile, long, elevation, long, tileNum) +WRAP_WATCOM_FUNC0(fo::GameObject*, obj_find_next_at_tile) +WRAP_WATCOM_FUNC2(long, obj_pid_new, fo::GameObject*, object, long, pid) +WRAP_WATCOM_FUNC1(long, obj_lock_is_jammed, fo::GameObject*, object) // Checks/unjams jammed locks +WRAP_WATCOM_FUNC1(void, obj_unjam_lock, fo::GameObject*, object) +WRAP_WATCOM_FUNC1(long, partyMemberGetCurLevel, fo::GameObject*, obj) WRAP_WATCOM_FUNC1(void, pc_flag_on, long, flag) -WRAP_WATCOM_FUNC2(void, perk_add_effect, GameObject*, critter, long, perkId) -WRAP_WATCOM_FUNC2(long, perk_can_add, GameObject*, critter, long, perkId) -WRAP_WATCOM_FUNC2(long, perk_level, GameObject*, critter, long, perkId) -//WRAP_WATCOM_FUNC2(void, perk_remove_effect, GameObject*, critter, long, perkId) -WRAP_WATCOM_FUNC6(long, pick_death, GameObject*, attacker, GameObject*, target, GameObject*, weapon, long, amount, long, anim, long, hitFromBack) +WRAP_WATCOM_FUNC2(void, perk_add_effect, fo::GameObject*, critter, long, perkId) +WRAP_WATCOM_FUNC2(long, perk_can_add, fo::GameObject*, critter, long, perkId) +WRAP_WATCOM_FUNC2(long, perk_level, fo::GameObject*, critter, long, perkId) +//WRAP_WATCOM_FUNC2(void, perk_remove_effect, fo::GameObject*, critter, long, perkId) +WRAP_WATCOM_FUNC6(long, pick_death, fo::GameObject*, attacker, fo::GameObject*, target, fo::GameObject*, weapon, long, amount, long, anim, long, hitFromBack) WRAP_WATCOM_FUNC0(void, process_bk) WRAP_WATCOM_FUNC0(void, proto_dude_update_gender) +WRAP_WATCOM_FUNC2(void, proto_make_path, char*, buffer, long, pid) // Places pointer to a prototype structure into ptrPtr and returns 0 on success or -1 on failure -WRAP_WATCOM_FUNC2(long, proto_ptr, long, pid, Proto**, ptrPtr) +WRAP_WATCOM_FUNC2(long, proto_ptr, long, pid, fo::Proto**, ptrPtr) WRAP_WATCOM_FUNC2(void, queue_clear_type, long, qType, void*, func) // removes all events of the given type and performs func before removal -WRAP_WATCOM_FUNC2(void*, queue_find_first, GameObject*, object, long, qType) -WRAP_WATCOM_FUNC2(void*, queue_find_next, GameObject*, object, long, qType) -WRAP_WATCOM_FUNC2(void, queue_remove_this, GameObject*, object, long, qType) +WRAP_WATCOM_FUNC2(void*, queue_find_first, fo::GameObject*, object, long, qType) +WRAP_WATCOM_FUNC2(void*, queue_find_next, fo::GameObject*, object, long, qType) +WRAP_WATCOM_FUNC2(void, queue_remove_this, fo::GameObject*, object, long, qType) WRAP_WATCOM_FUNC1(long, register_begin, long, regType) WRAP_WATCOM_FUNC0(long, register_end) -WRAP_WATCOM_FUNC3(long, register_object_animate, GameObject*, object, long, anim, long, delay) -WRAP_WATCOM_FUNC3(long, register_object_animate_and_hide, GameObject*, object, long, anim, long, delay) -// WRAP_WATCOM_FUNC3(long, register_object_animate_and_move_straight_, GameObject*, object; -// WRAP_WATCOM_FUNC3(long, register_object_animate_forever_, GameObject*, object; -// WRAP_WATCOM_FUNC3(long, register_object_animate_reverse_, GameObject*, object; -WRAP_WATCOM_FUNC3(long, register_object_change_fid, GameObject*, object, long, artFid, long, delay) -// WRAP_WATCOM_FUNC3(long, register_object_check_falling_, GameObject*, object; -WRAP_WATCOM_FUNC1(long, register_object_dec_rotation, GameObject*, object) -WRAP_WATCOM_FUNC1(long, register_object_erase, GameObject*, object) -WRAP_WATCOM_FUNC3(long, register_object_funset, GameObject*, object, long, action, long, delay) -WRAP_WATCOM_FUNC1(long, register_object_inc_rotation, GameObject*, object) -WRAP_WATCOM_FUNC3(long, register_object_light, GameObject*, object, long, lightRadius, long, delay) -// WRAP_WATCOM_FUNC3(long, register_object_move_on_stairs_, GameObject*, object; -// WRAP_WATCOM_FUNC3(long, register_object_move_straight_to_tile_, GameObject*, object; -// WRAP_WATCOM_FUNC3(long, register_object_move_to_tile_, GameObject*, object; -// WRAP_WATCOM_FUNC3(long, register_object_must_call_, GameObject*, object; -WRAP_WATCOM_FUNC1(long, register_object_must_erase, GameObject*, object) -// WRAP_WATCOM_FUNC3(long, register_object_outline_, GameObject*, object; -// WRAP_WATCOM_FUNC3(long, register_object_play_sfx_, GameObject*, object; -// WRAP_WATCOM_FUNC3(long, register_object_run_to_tile_, GameObject*, object; -WRAP_WATCOM_FUNC3(long, register_object_take_out, GameObject*, object, long, holdFrameId, long, nothing) -WRAP_WATCOM_FUNC3(long, register_object_turn_towards, GameObject*, object, long, tileNum, long, nothing) +WRAP_WATCOM_FUNC3(long, register_object_animate, fo::GameObject*, object, long, anim, long, delay) +WRAP_WATCOM_FUNC3(long, register_object_animate_and_hide, fo::GameObject*, object, long, anim, long, delay) +// WRAP_WATCOM_FUNC3(long, register_object_animate_and_move_straight_, fo::GameObject*, object; +// WRAP_WATCOM_FUNC3(long, register_object_animate_forever_, fo::GameObject*, object; +// WRAP_WATCOM_FUNC3(long, register_object_animate_reverse_, fo::GameObject*, object; +WRAP_WATCOM_FUNC3(long, register_object_change_fid, fo::GameObject*, object, long, artFid, long, delay) +// WRAP_WATCOM_FUNC3(long, register_object_check_falling_, fo::GameObject*, object; +WRAP_WATCOM_FUNC1(long, register_object_dec_rotation, fo::GameObject*, object) +WRAP_WATCOM_FUNC1(long, register_object_erase, fo::GameObject*, object) +WRAP_WATCOM_FUNC3(long, register_object_funset, fo::GameObject*, object, long, action, long, delay) +WRAP_WATCOM_FUNC1(long, register_object_inc_rotation, fo::GameObject*, object) +WRAP_WATCOM_FUNC3(long, register_object_light, fo::GameObject*, object, long, lightRadius, long, delay) +// WRAP_WATCOM_FUNC3(long, register_object_move_on_stairs_, fo::GameObject*, object; +// WRAP_WATCOM_FUNC3(long, register_object_move_straight_to_tile_, fo::GameObject*, object; +// WRAP_WATCOM_FUNC3(long, register_object_must_call_, fo::GameObject*, object; +WRAP_WATCOM_FUNC1(long, register_object_must_erase, fo::GameObject*, object) +// WRAP_WATCOM_FUNC3(long, register_object_outline_, fo::GameObject*, object; +WRAP_WATCOM_FUNC3(long, register_object_take_out, fo::GameObject*, object, long, holdFrameId, long, nothing) +WRAP_WATCOM_FUNC3(long, register_object_turn_towards, fo::GameObject*, object, long, tileNum, long, nothing) WRAP_WATCOM_FUNC2(long, roll_random, long, minValue, long, maxValue) -WRAP_WATCOM_FUNC1(long*, runProgram, Program*, progPtr) +WRAP_WATCOM_FUNC1(long*, runProgram, fo::Program*, progPtr) WRAP_WATCOM_FUNC1(long, selectWindowID, long, sWinID) -WRAP_WATCOM_FUNC1(ScriptInstance*, scr_find_first_at, long, elevation) -WRAP_WATCOM_FUNC0(ScriptInstance*, scr_find_next_at) -WRAP_WATCOM_FUNC1(GameObject*, scr_find_obj_from_program, Program*, program) +WRAP_WATCOM_FUNC1(void, scr_build_lookup_table, fo::ScriptInstance*, script) +WRAP_WATCOM_FUNC1(fo::ScriptInstance*, scr_find_first_at, long, elevation) +WRAP_WATCOM_FUNC0(fo::ScriptInstance*, scr_find_next_at) +WRAP_WATCOM_FUNC1(fo::GameObject*, scr_find_obj_from_program, fo::Program*, program) WRAP_WATCOM_FUNC2(long, scr_new, long*, scriptID, long, sType) // Saves pointer to script object into scriptPtr using scriptID -WRAP_WATCOM_FUNC2(long, scr_ptr, long, scriptId, ScriptInstance**, scriptPtr) // Returns 0 on success, -1 on failure +WRAP_WATCOM_FUNC2(long, scr_ptr, long, scriptId, fo::ScriptInstance**, scriptPtr) // Returns 0 on success, -1 on failure WRAP_WATCOM_FUNC1(long, scr_remove, long, scriptID) WRAP_WATCOM_FUNC1(void, set_focus_func, void*, func) -WRAP_WATCOM_FUNC2(long, skill_dec_point_force, GameObject*, critter, long, skill) -WRAP_WATCOM_FUNC2(long, skill_inc_point_force, GameObject*, critter, long, skill) +WRAP_WATCOM_FUNC2(long, skill_dec_point_force, fo::GameObject*, critter, long, skill) +WRAP_WATCOM_FUNC2(long, skill_inc_point_force, fo::GameObject*, critter, long, skill) WRAP_WATCOM_FUNC1(long, skill_is_tagged, long, skill) -WRAP_WATCOM_FUNC2(long, skill_level, GameObject*, critter, long, statID) -WRAP_WATCOM_FUNC2(long, stat_get_base, GameObject*, critter, long, statID) -WRAP_WATCOM_FUNC2(long, stat_get_base_direct, GameObject*, critter, long, statID) -WRAP_WATCOM_FUNC2(long, stat_get_bonus, GameObject*, critter, long, statID) -WRAP_WATCOM_FUNC3(long, stat_set_bonus, GameObject*, critter, long, statID, long, amount) +WRAP_WATCOM_FUNC2(long, skill_level, fo::GameObject*, critter, long, statID) +WRAP_WATCOM_FUNC2(long, stat_get_base, fo::GameObject*, critter, long, statID) +WRAP_WATCOM_FUNC2(long, stat_get_base_direct, fo::GameObject*, critter, long, statID) +WRAP_WATCOM_FUNC2(long, stat_get_bonus, fo::GameObject*, critter, long, statID) +WRAP_WATCOM_FUNC3(long, stat_set_bonus, fo::GameObject*, critter, long, statID, long, amount) WRAP_WATCOM_FUNC2(void, skill_get_tags, long*, tags, long, num) WRAP_WATCOM_FUNC2(void, skill_set_tags, long*, tags, long, num) -WRAP_WATCOM_FUNC2(long, stat_level, GameObject*, critter, long, statId) +WRAP_WATCOM_FUNC2(long, stat_level, fo::GameObject*, critter, long, statId) WRAP_WATCOM_FUNC1(void, stat_pc_add_experience, long, amount) // Adds experience points to PC WRAP_WATCOM_FUNC1(long, text_font, long, fontNum) WRAP_WATCOM_FUNC2(long, tile_dist, long, scrTile, long, dstTile) WRAP_WATCOM_FUNC2(long, tile_dir, long, scrTile, long, dstTile) +WRAP_WATCOM_FUNC1(long, tile_on_edge, long, tile) WRAP_WATCOM_FUNC0(void, tile_refresh_display) // Redraws the whole screen -WRAP_WATCOM_FUNC2(void, tile_refresh_rect, BoundRect*, boundRect, long, elevation) // Redraws the given rectangle on screen +WRAP_WATCOM_FUNC2(void, tile_refresh_rect, fo::BoundRect*, boundRect, long, elevation) // Redraws the given rectangle on screen WRAP_WATCOM_FUNC1(long, trait_level, long, traitID) WRAP_WATCOM_FUNC6(long, win_add, long, x, long, y, long, width, long, height, long, bgColorIndex, long, flags) WRAP_WATCOM_FUNC1(void, win_show, DWORD, winRef) @@ -276,7 +260,37 @@ WRAP_WATCOM_FUNC2(void, win_draw_rect, DWORD, winRef, RECT*, rect) WRAP_WATCOM_FUNC1(void, win_delete, DWORD, winRef) WRAP_WATCOM_FUNC0(long, windowWidth) WRAP_WATCOM_FUNC1(void, wmCarUseGas, long, gasAmount) +WRAP_WATCOM_FUNC1(long, wmEvalTileNumForPlacement, long, tile) WRAP_WATCOM_FUNC0(void, wmPartyWalkingStep) WRAP_WATCOM_FUNC1(void, wmRefreshInterfaceOverlay, long, isRedraw) -WRAP_WATCOM_FUNC2(DbFile*, xfopen, const char*, fileName, const char*, flags) -WRAP_WATCOM_FUNC3(long, xfseek, DbFile*, file, long, fOffset, long, origin) + +/* Database functions */ +WRAP_WATCOM_FUNC1(bool, db_access, const char*, fileName) // Checks if given file exists in DB +WRAP_WATCOM_FUNC1(long, db_fclose, fo::DbFile*, file) +WRAP_WATCOM_FUNC2(fo::DbFile*, db_fopen, const char*, path, const char*, mode) +//WRAP_WATCOM_FUNC1(long, db_fgetc, fo::DbFile*, file) +WRAP_WATCOM_FUNC3(char*, db_fgets, char*, buf, long, max_count, fo::DbFile*, file) +WRAP_WATCOM_FFUNC4(long, db_fread, void*, buf, long, elsize, long, count, fo::DbFile*, file) +WRAP_WATCOM_FFUNC3(long, db_fseek, fo::DbFile*, file, long, pos, long, origin) +WRAP_WATCOM_FUNC2(void, db_free_file_list, char***, fileList, DWORD, arg2) // Destroys filelist array created by db_get_file_list +WRAP_WATCOM_FUNC2(long, db_freadByte, fo::DbFile*, file, BYTE*, _out) +WRAP_WATCOM_FUNC2(long, db_freadShort, fo::DbFile*, file, WORD*, _out) +WRAP_WATCOM_FUNC2(long, db_freadInt, fo::DbFile*, file, DWORD*, _out) +WRAP_WATCOM_FFUNC3(long, db_freadByteCount, fo::DbFile*, file, BYTE*, dest, long, count) +WRAP_WATCOM_FFUNC3(long, db_freadShortCount, fo::DbFile*, file, WORD*, dest, long, count) +WRAP_WATCOM_FFUNC3(long, db_freadIntCount, fo::DbFile*, file, DWORD*, dest, long, count) +//WRAP_WATCOM_FFUNC3(long, db_freadLongCount, fo::DbFile*, file, DWORD*, dest, long, count) +WRAP_WATCOM_FUNC2(long, db_fwriteByte, fo::DbFile*, file, long, value) +WRAP_WATCOM_FUNC2(long, db_fwriteInt, fo::DbFile*, file, long, value) +WRAP_WATCOM_FFUNC3(long, db_fwriteByteCount, fo::DbFile*, file, const BYTE*, cptr, long, count) +//WRAP_WATCOM_FFUNC3(long, db_fwriteLongCount, fo::DbFile*, file, DWORD*, dest, long, count) +WRAP_WATCOM_FUNC2(long, db_dir_entry, const char*, fileName, DWORD*, sizeOut) // Check fallout file and get file size (result 0 - file exists) +// Searches files in DB by given path/filename mask and stores result in fileList +// fileList is a pointer to a variable, that will be assigned with an address of an array of char* strings +WRAP_WATCOM_FUNC2(long, db_get_file_list, const char*, searchMask, char***, fileList) // Returns number of elements in *fileList +WRAP_WATCOM_FUNC2(long, db_init, const char*, path_dat, const char*, path_patches) +WRAP_WATCOM_FUNC1(void*, dbase_open, const char*, fileName) +WRAP_WATCOM_FUNC1(void, dbase_close, void*, dbPtr) + +WRAP_WATCOM_FUNC2(fo::DbFile*, xfopen, const char*, fileName, const char*, flags) +WRAP_WATCOM_FFUNC3(long, xfseek, fo::DbFile*, file, long, fOffset, long, origin) diff --git a/sfall/FalloutEngine/Structs.h b/sfall/FalloutEngine/Structs.h index 56175cdb..c9ced4cc 100644 --- a/sfall/FalloutEngine/Structs.h +++ b/sfall/FalloutEngine/Structs.h @@ -61,12 +61,13 @@ struct Art { struct AnimationSet { long currentAnim; long counter; - long animCounter; + long totalAnimCount; long flags; + struct Animation { - long number; - long source; - long target; + long animType; + GameObject* source; + GameObject* target; long data1; long elevation; long animCode; @@ -81,6 +82,33 @@ struct AnimationSet { static_assert(sizeof(AnimationSet) == 2656, "Incorrect AnimationSet definition."); +struct AnimationSad { + long flags; + GameObject* source; + long fid; + long animCode; + long ticks; + long tpf; // fps + long animSetSlot; + long pathCount; // len + long animStep; // current step in rotationData/pathData + short dstTile; + char rotation1; + char rotation2; + + union { + long rotationData[800]; + struct BuildPathData { + long tile; + long elevation; + long sX; + long sY; + } pathData[200]; + }; +}; + +static_assert(sizeof(AnimationSad) == 3240, "Incorrect AnimationSad definition."); + // Bounding rectangle, used by tile_refresh_rect and related functions. struct BoundRect { long x; @@ -152,6 +180,7 @@ struct GameObject { long damageLastTurn; long aiPacket; long teamNum; + // current target or the attacker who caused damage in the previous combat turn GameObject* whoHitMe; long health; long rads; @@ -169,10 +198,19 @@ struct GameObject { inline bool IsNotActive() { return ((damageFlags & (DamageFlag::DAM_KNOCKED_OUT | DamageFlag::DAM_LOSE_TURN)) != 0); } + inline bool IsActiveNotDead() { + return ((damageFlags & (DamageFlag::DAM_DEAD | DamageFlag::DAM_KNOCKED_OUT | DamageFlag::DAM_LOSE_TURN)) == 0); + } + inline bool IsNotActiveOrDead() { + return ((damageFlags & (DamageFlag::DAM_DEAD | DamageFlag::DAM_KNOCKED_OUT | DamageFlag::DAM_LOSE_TURN)) != 0); + } + inline bool IsFleeing() { + return ((combatState & CombatStateFlag::InFlee) != 0); + } } critter; }; DWORD protoId; // object PID - long cid; // combat ID + long cid; // combat ID (don't change while in combat) long lightDistance; long lightIntensity; DWORD outline; @@ -272,7 +310,7 @@ struct Program { long *codeStackPtr; long field_8; long field_C; - long *codePtr; + long codePosition; // position in the code stack when reading script opcodes long field_14; // unused? long field_18; // unused? long *dStackPtr; @@ -282,24 +320,17 @@ struct Program { long field_2C; long *stringRefPtr; long *procTablePtr; - long field_38; // same as codeStackPtr + long *codeStack; // same as codeStackPtr long savedEnv[12]; // saved register values long field_6C; // unused? long field_70; // unused? long field_74; // unused? - long field_78; - long field_7C; - union { - long flags; - struct { - char flags1; - char flags2; - char flags3; - char flags4; - }; - }; + long timerTick; // unused? + long func_7C; // always null? + short flags; + short fetchOpcode; long currentScriptWin; // current window for executing script - long field_88; + long shouldRemove; }; static_assert(sizeof(Program) == 140, "Incorrect Program definition."); @@ -417,6 +448,8 @@ struct FrmFile { // sizeof 2954 BYTE pixels[80 * 36]; // for tiles FRM }; + FrmFile() {}; + // Returns a pointer to the data of the frame in the direction FrmFrameData* GetFrameData(long dir, long frame) { BYTE* offsDirectionFrame = (BYTE*)&frameData; @@ -575,12 +608,30 @@ struct PathNode { PathNode* next; }; +struct ObjectTable { + GameObject* object; + ObjectTable* nextObject; +}; + struct PremadeChar { char path[20]; DWORD fid; char unknown[20]; }; +struct ProtoListBlock { + long* protoMem[16]; + long count; + ProtoListBlock* next; +}; + +struct ProtoList { + ProtoListBlock* block; + ProtoListBlock* lastBlock; + long countBlocks; // current + long totalCount; // total number of prototypes for this type +}; + // In-memory PROTO structure, not the same as PRO file format. struct Proto { struct Tile { @@ -918,6 +969,14 @@ struct AIcap { long disposition; long body_type; long general_type; + + inline AIpref::distance getDistance() { + return (AIpref::distance)distance; + } + inline AIpref::run_away_mode getRunAwayMode() { + return (AIpref::run_away_mode)run_away_mode; + } + }; struct Queue { @@ -1052,6 +1111,26 @@ struct AudioFile { long position; }; +// aka PartyMemberRecoveryList +struct ObjectListData { + GameObject* object; + fo::ScriptInstance* script; + long* localVarData; + ObjectListData* nextSaveList; // _itemSaveListHead +}; + +struct PartyMemberPerkListData { + long perkData[fo::Perk::PERK_count]; +}; + +struct QuestData { + long location; + long description; + long gvarIndex; + long displayThreshold; + long completedThreshold; +}; + #pragma pack(pop) } diff --git a/sfall/FalloutEngine/VariableOffsets.h b/sfall/FalloutEngine/VariableOffsets.h index 143e9cf3..4f0f5b15 100644 --- a/sfall/FalloutEngine/VariableOffsets.h +++ b/sfall/FalloutEngine/VariableOffsets.h @@ -14,6 +14,7 @@ #define FO_VAR_art_name 0x56C9E4 #define FO_VAR_art_vault_guy_num 0x5108A4 #define FO_VAR_art_vault_person_nums 0x5108A8 +#define FO_VAR_artCritterFidShouldRunData 0x56CAF0 #define FO_VAR_aTextSCuts 0x501A8C #define FO_VAR_aTextSCutsS 0x503530 #define FO_VAR_aTextSCutsSS 0x50B01C @@ -44,6 +45,8 @@ #define FO_VAR_critterClearObj 0x518438 #define FO_VAR_crnt_func 0x664508 #define FO_VAR_cur_id 0x51C7D4 +#define FO_VAR_curr_anim_set 0x51071C +#define FO_VAR_curr_anim_counter 0x56C7DC #define FO_VAR_curr_font_num 0x51E3B0 #define FO_VAR_curr_pc_stat 0x6681AC #define FO_VAR_curr_stack 0x59E96C @@ -77,6 +80,7 @@ #define FO_VAR_endgame_voiceover_loaded 0x570AB8 #define FO_VAR_Experience_ 0x6681B4 #define FO_VAR_fade_steps 0x6642D0 +#define FO_VAR_fallout_config 0x50281C #define FO_VAR_fallout_game_time 0x51C720 #define FO_VAR_fidgetFID 0x5186F4 #define FO_VAR_fidgetFp 0x5186FC @@ -134,6 +138,7 @@ #define FO_VAR_itemButtonItems 0x5970F8 #define FO_VAR_itemCurrentItem 0x518F78 #define FO_VAR_kb_lock_flags 0x51E2EA +#define FO_VAR_language 0x56C970 // aka _darn_foreign_sub_path #define FO_VAR_last_buttons 0x51E2AC #define FO_VAR_last_button_winID 0x51E404 #define FO_VAR_last_level 0x5707B4 @@ -220,9 +225,11 @@ #define FO_VAR_procTableStrs 0x51C758 // table of procId (from define.h) => procName map #define FO_VAR_proto_main_msg_file 0x6647FC #define FO_VAR_proto_msg_files 0x6647AC +#define FO_VAR_protoLists 0x51C290 #define FO_VAR_ptable 0x59E934 #define FO_VAR_pud 0x59E960 #define FO_VAR_quest_count 0x51C12C +#define FO_VAR_quests 0x51C128 #define FO_VAR_queue 0x6648C0 #define FO_VAR_quick_done 0x5193BC #define FO_VAR_read_callback 0x51DEEC @@ -277,6 +284,7 @@ #define FO_VAR_title_color 0x56D750 #define FO_VAR_title_font 0x56D748 #define FO_VAR_trait_data 0x51DB84 +#define FO_VAR_use_language 0x510898 // aka _darn_foreigners #define FO_VAR_view_page 0x664520 #define FO_VAR_wd_obj 0x59E98C #define FO_VAR_window 0x6ADE58 @@ -286,6 +294,7 @@ #define FO_VAR_wmBkWinBuf 0x51DE24 #define FO_VAR_wmEncounterIconShow 0x672E48 #define FO_VAR_wmLastRndTime 0x51DEA0 +#define FO_VAR_wmMaxAreaNum 0x51DDFC #define FO_VAR_wmMaxMapNum 0x51DE10 #define FO_VAR_wmMaxTileNum 0x51DDF0 #define FO_VAR_wmMsgFile 0x672FB0 diff --git a/sfall/FalloutEngine/Variables.cpp b/sfall/FalloutEngine/Variables.cpp index c16f72ef..5b69d6b0 100644 --- a/sfall/FalloutEngine/Variables.cpp +++ b/sfall/FalloutEngine/Variables.cpp @@ -26,27 +26,31 @@ namespace var { // defines reference to a variable (pointer is constant, but value can be changed) -#define VAR_(name, type) \ - type &name = *reinterpret_cast(FO_VAR_##name); +#define VAR_(name, type) \ + type& name = *reinterpret_cast(FO_VAR_##name); // defines reference to a constant variable (value can't be changed from sfall) -#define VARC(name, type) \ +#define VARC(name, type) \ const type& name = *reinterpret_cast(FO_VAR_##name); // defines reference to static array -#define VARA(name, type, size) \ +#define VARA(name, type, size) \ ArrayWrapper &name = *reinterpret_cast*>(FO_VAR_##name); // defines reference to static 2-dimensional array -#define VAR2(name, type, size1, size2) \ +#define VAR2(name, type, size1, size2) \ ArrayWrapper, size1> &name = *reinterpret_cast, size1>*>(FO_VAR_##name); // defines reference to static 3-dimensional array -#define VAR3(name, type, size1, size2, size3) \ +#define VAR3(name, type, size1, size2, size3) \ ArrayWrapper, size2>, size1> &name = *reinterpret_cast, size2>, size1>*>(FO_VAR_##name); +// defines reference pointer to dynamic array +#define VARD(name, type) \ + type*& name = *reinterpret_cast(FO_VAR_##name); + // defines const pointer to variable (useful for static arrays, when exact size is unknown) -#define VARP(name, type) \ +#define VARP(name, type) \ type* const name = reinterpret_cast(FO_VAR_##name); // X-Macros pattern diff --git a/sfall/FalloutEngine/Variables.h b/sfall/FalloutEngine/Variables.h index 469ea1a3..585bca21 100644 --- a/sfall/FalloutEngine/Variables.h +++ b/sfall/FalloutEngine/Variables.h @@ -52,26 +52,30 @@ struct ArrayWrapper { }; // defines reference to an engine variable -#define VAR_(name, type) \ +#define VAR_(name, type) \ extern type& name; -#define VARC(name, type) \ +#define VARC(name, type) \ extern const type& name; // defines reference to static array -#define VARA(name, type, size) \ +#define VARA(name, type, size) \ extern ArrayWrapper &name; // defines reference to static 2-dimensional array -#define VAR2(name, type, size1, size2) \ +#define VAR2(name, type, size1, size2) \ extern ArrayWrapper, size1> &name; // defines reference to static 3-dimensional array -#define VAR3(name, type, size1, size2, size3) \ +#define VAR3(name, type, size1, size2, size3) \ extern ArrayWrapper, size2>, size1> &name; +// defines reference pointer to dynamic array +#define VARD(name, type) \ + extern type*& name; + // defines const pointer to variable (useful for static arrays, when exact size is unknown) -#define VARP(name, type) \ +#define VARP(name, type) \ extern type* const name; // TODO: assign appropriate types (arrays, structs, strings, etc.) for all variables diff --git a/sfall/FalloutEngine/Variables_def.h b/sfall/FalloutEngine/Variables_def.h index 1af6de19..e117a248 100644 --- a/sfall/FalloutEngine/Variables_def.h +++ b/sfall/FalloutEngine/Variables_def.h @@ -23,7 +23,7 @@ VAR_(cmap, DWORD) VAR_(colorTable, DWORD) VAR_(combat_end_due_to_load, DWORD) VAR_(combat_free_move, DWORD) -VAR_(combat_list, DWORD) +VARD(combat_list, fo::GameObject*) VAR_(combat_state, DWORD) VAR_(combat_turn_running, DWORD) VAR_(combatNumTurns, DWORD) @@ -31,6 +31,9 @@ VAR3(crit_succ_eff, fo::CritInfo, 20, 9, 6) // 20 critters with 9 VAR_(critter_db_handle, fo::PathNode*) VAR_(critterClearObj, DWORD) VAR_(crnt_func, DWORD) +VAR_(cur_id, DWORD) +VAR_(curr_anim_set, DWORD) +VAR_(curr_anim_counter, DWORD) VAR_(curr_font_num, DWORD) VARA(curr_pc_stat, long, fo::PCSTAT_max_pc_stat) VAR_(curr_stack, DWORD) @@ -62,7 +65,7 @@ VAR_(folder_card_title, DWORD) VAR_(folder_card_title2, DWORD) VAR_(frame_time, DWORD) VAR_(free_perk, char) -VAR_(game_global_vars, long*) // dynamic array of size == num_game_global_vars +VARD(game_global_vars, long) // dynamic array of size == num_game_global_vars VAR_(game_user_wants_to_quit, DWORD) VAR_(gcsd, fo::CombatGcsd*) VAR_(gdBarterMod, DWORD) @@ -98,6 +101,7 @@ VAR_(inventry_message_file, fo::MessageList) VARA(itemButtonItems, fo::ItemButtonItem, 2) // 0 - left, 1 - right VAR_(itemCurrentItem, long) // 0 - left, 1 - right VAR_(kb_lock_flags, DWORD) +VARA(language, char, 32) VAR_(last_buttons, DWORD) VAR_(last_button_winID, DWORD) VAR_(last_level, DWORD) @@ -138,7 +142,7 @@ VAR_(num_game_global_vars, DWORD) VAR_(num_map_global_vars, DWORD) VAR_(num_windows, DWORD) VAR_(obj_dude, fo::GameObject*) -VARA(objectTable, DWORD*, 40000) +VARA(objectTable, fo::ObjectTable*, 40000) VAR_(objItemOutlineState, DWORD) VAR_(optionRect, DWORD) VAR_(optionsButtonDown, DWORD) @@ -152,9 +156,9 @@ VAR_(outlined_object, fo::GameObject*) VAR_(partyMemberAIOptions, DWORD) VAR_(partyMemberCount, DWORD) VAR_(partyMemberLevelUpInfoList, DWORD*) -VAR_(partyMemberList, DWORD*) // each struct - 4 integers, first integer - objPtr +VAR_(partyMemberList, fo::ObjectListData*) // dynamic array VAR_(partyMemberMaxCount, DWORD) -VAR_(partyMemberPidList, DWORD*) +VARD(partyMemberPidList, DWORD) // dynamic array VAR_(patches, char*) VAR_(paths, fo::PathNode*) // array VAR2(pc_crit_succ_eff, fo::CritInfo, 9, 6) // 9 body parts, 6 effects @@ -164,7 +168,7 @@ VAR_(pc_proto, fo::Proto) VARA(pc_trait, long, 2) // 2 of them VAR_(PeanutButter, BYTE) VARA(perk_data, fo::PerkInfo, fo::PERK_count) -VAR_(perkLevelDataList, long*) // dynamic array, limited to PERK_Count +VARD(perkLevelDataList, fo::PartyMemberPerkListData) // dynamic array, limited to (PERK_Count * partyMemberMaxCount) VARC(pip_win, DWORD) VAR_(pipboy_message_file, fo::MessageList) VAR_(pipmesg, DWORD) @@ -172,6 +176,7 @@ VAR_(preload_list_index, DWORD) VARA(procTableStrs, const char*, (int)fo::Scripts::ScriptProc::count) // table of procId (from define.h) => procName map VAR_(proto_main_msg_file, fo::MessageList) VARA(proto_msg_files, fo::MessageList, 6) // array of 6 elements +VARA(protoLists, fo::ProtoList, 11) VAR_(ptable, DWORD) VAR_(pud, DWORD) VAR_(queue, fo::Queue*) @@ -197,7 +202,7 @@ VAR_(square, DWORD) VAR_(squares, DWORD*) VARA(stack, DWORD, 10) VARA(stack_offset, DWORD, 10) -VARA(stat_data, fo::StatInfo, fo::STAT_real_max_stat) // dynamic array +VARA(stat_data, fo::StatInfo, fo::STAT_real_max_stat) VAR_(stat_flag, DWORD) VAR_(subtitleList, fo::SubTitleList*) VARA(sWindows, fo::sWindow, 16) @@ -223,6 +228,7 @@ VAR_(tile, DWORD) VAR_(title_color, DWORD) VAR_(title_font, DWORD) VARA(trait_data, fo::TraitInfo, fo::TRAIT_count) +VAR_(use_language, DWORD) VAR_(view_page, DWORD) VAR_(wd_obj, DWORD) VARA(window, fo::Window*, 50) @@ -250,3 +256,4 @@ VAR_(YellowColor, BYTE) #undef VARA #undef VAR2 #undef VAR3 +#undef VARD diff --git a/sfall/Game/combatAI.cpp b/sfall/Game/combatAI.cpp new file mode 100644 index 00000000..f711af2c --- /dev/null +++ b/sfall/Game/combatAI.cpp @@ -0,0 +1,28 @@ +/* + * sfall + * Copyright (C) 2008-2021 The sfall team + * + */ + +//#include "..\main.h" +#include "..\FalloutEngine\Fallout2.h" + +#include "..\Modules\HookScripts\CombatHs.h" + +#include "combatAI.h" + +namespace game +{ + +namespace sf = sfall; + +// Implementation of ai_can_use_weapon_ engine function with the HOOK_CANUSEWEAPON hook +bool CombatAI::ai_can_use_weapon(fo::GameObject* source, fo::GameObject* weapon, long hitMode) { + bool result = fo::func::ai_can_use_weapon(source, weapon, hitMode); + return sf::CanUseWeaponHook_Invoke(result, source, weapon, hitMode); +} + +void CombatAI::init() { // TODO: add to main.cpp +} + +} diff --git a/sfall/Game/combatAI.h b/sfall/Game/combatAI.h new file mode 100644 index 00000000..89404661 --- /dev/null +++ b/sfall/Game/combatAI.h @@ -0,0 +1,19 @@ +/* + * sfall + * Copyright (C) 2008-2021 The sfall team + * + */ + +#pragma once + +namespace game +{ + +class CombatAI { +public: + static void init(); + + static bool ai_can_use_weapon(fo::GameObject* source, fo::GameObject* weapon, long hitMode); +}; + +} \ No newline at end of file diff --git a/sfall/Game/inventory.cpp b/sfall/Game/inventory.cpp index 89c85d18..148a36e7 100644 --- a/sfall/Game/inventory.cpp +++ b/sfall/Game/inventory.cpp @@ -10,6 +10,8 @@ #include "..\Modules\Inventory.h" #include "..\Modules\PartyControl.h" +#include "..\Modules\HookScripts\InventoryHs.h" + #include "inventory.h" namespace game @@ -17,6 +19,13 @@ namespace game namespace sf = sfall; +// Custom implementation of correctFidForRemovedItem_ engine function with the HOOK_INVENWIELD hook +long Inventory::correctFidForRemovedItem(fo::GameObject* critter, fo::GameObject* item, long flags) { + long result = sf::InvenWieldHook_Invoke(critter, item, flags); + if (result) fo::func::correctFidForRemovedItem(critter, item, flags); + return result; +} + DWORD __stdcall Inventory::item_total_size(fo::GameObject* critter) { int totalSize = fo::func::item_c_curr_size(critter); @@ -54,15 +63,15 @@ DWORD __stdcall Inventory::adjust_fid() { } else { // vanilla logic: indexNum = fo::var::art_vault_guy_num; - auto critterPro = fo::GetProto(fo::var::inven_pid); - if (critterPro != nullptr) { + fo::Proto* critterPro; + if (fo::GetProto(fo::var::inven_pid, &critterPro)) { indexNum = critterPro->fid & 0xFFF; } if (fo::var::i_worn != nullptr) { - auto armorPro = fo::GetProto(fo::var::i_worn->protoId); + fo::Proto* armorPro = fo::GetProto(fo::var::i_worn->protoId); DWORD armorFid = fo::func::stat_level(fo::var::inven_dude, fo::STAT_gender) == fo::GENDER_FEMALE - ? armorPro->item.armor.femaleFID - : armorPro->item.armor.maleFID; + ? armorPro->item.armor.femaleFID + : armorPro->item.armor.maleFID; if (armorFid != -1) { indexNum = armorFid; @@ -70,12 +79,12 @@ DWORD __stdcall Inventory::adjust_fid() { } } auto itemInHand = fo::func::intface_is_item_right_hand() - ? fo::var::i_rhand - : fo::var::i_lhand; + ? fo::var::i_rhand + : fo::var::i_lhand; if (itemInHand != nullptr) { - auto itemPro = fo::GetProto(itemInHand->protoId); - if (itemPro->item.type == fo::item_type_weapon) { + fo::Proto* itemPro; + if (fo::GetProto(itemInHand->protoId, &itemPro) && itemPro->item.type == fo::item_type_weapon) { weaponAnimCode = itemPro->item.weapon.animationCode; } } @@ -100,7 +109,7 @@ static void __declspec(naked) adjust_fid_hack() { } void Inventory::init() { - // Replace functions + // Replace adjust_fid_ function sf::MakeJump(fo::funcoffs::adjust_fid_, adjust_fid_hack); // 0x4716E8 } diff --git a/sfall/Game/inventory.h b/sfall/Game/inventory.h index dcfb47a1..a33ac0ba 100644 --- a/sfall/Game/inventory.h +++ b/sfall/Game/inventory.h @@ -15,6 +15,9 @@ class Inventory { public: static void init(); + // Custom implementation of correctFidForRemovedItem_ engine function with the HOOK_INVENWIELD hook + static long correctFidForRemovedItem(fo::GameObject* critter, fo::GameObject* item, long flags); + // This function returns the size of the occupied inventory space for the object or critter // - difference from the item_c_curr_size_ function: includes the size of equipped items for the critter // - does not return the size of nested items diff --git a/sfall/Game/items.cpp b/sfall/Game/items.cpp new file mode 100644 index 00000000..fc69bde2 --- /dev/null +++ b/sfall/Game/items.cpp @@ -0,0 +1,146 @@ +/* + * sfall + * Copyright (C) 2008-2021 The sfall team + * + */ + +#include "..\main.h" +#include "..\FalloutEngine\Fallout2.h" + +#include "..\Modules\HookScripts\CombatHs.h" +#include "..\Modules\Perks.h" + +#include "..\Game\stats.h" + +#include "items.h" + +namespace game +{ + +namespace sf = sfall; + +static constexpr int reloadCostAP = 2; // engine default reload AP cost + +long Items::item_count(fo::GameObject* who, fo::GameObject* item) { + for (int i = 0; i < who->invenSize; i++) { + auto tableItem = &who->invenTable[i]; + if (tableItem->object == item) { + return tableItem->count; // fix + } else if (fo::func::item_get_type(tableItem->object) == fo::item_type_container) { + int count = item_count(tableItem->object, item); + if (count > 0) return count; + } + } + return 0; +} + +long Items::item_weapon_range(fo::GameObject* source, fo::GameObject* weapon, long hitMode) { + fo::Proto* wProto; + if (!GetProto(weapon->protoId, &wProto)) return 0; + + long isSecondMode = (hitMode && hitMode != fo::AttackType::ATKTYPE_RWEAPON_PRIMARY) ? 1 : 0; + long range = wProto->item.weapon.maxRange[isSecondMode]; + + long flagExt = wProto->item.flagsExt; + if (isSecondMode) flagExt = (flagExt >> 4); + long type = fo::GetWeaponType(flagExt); + + if (type == fo::AttackSubType::THROWING) { + long heaveHoMod = Stats::perk_level(source, fo::Perk::PERK_heave_ho); + long stRange = fo::func::stat_level(source, fo::Stat::STAT_st); + + if (sf::Perks::perkHeaveHoModTweak) { + stRange *= 3; + if (stRange > range) stRange = range; + return stRange + (heaveHoMod * 6); + } + + // vanilla + stRange += (heaveHoMod * 2); + if (stRange > 10) stRange = 10; // fix for Heave Ho! + stRange *= 3; + if (stRange < range) range = stRange; + } + return range; +} + +// TODO +//long Items::item_w_range(fo::GameObject* source, long hitMode) { +// return item_weapon_range(source, fo::func::item_hit_with(source, hitMode), hitMode); +//} + +static bool fastShotTweak = false; + +// Implementation of item_w_primary_mp_cost_ and item_w_secondary_mp_cost_ engine functions in a single function with the HOOK_CALCAPCOST hook +long __fastcall Items::item_weapon_mp_cost(fo::GameObject* source, fo::GameObject* weapon, long hitMode, long isCalled) { + long cost = 0; + + switch (hitMode) { + case fo::AttackType::ATKTYPE_LWEAPON_PRIMARY: + case fo::AttackType::ATKTYPE_RWEAPON_PRIMARY: + cost = fo::func::item_w_primary_mp_cost(weapon); + break; + case fo::AttackType::ATKTYPE_LWEAPON_SECONDARY: + case fo::AttackType::ATKTYPE_RWEAPON_SECONDARY: + cost = fo::func::item_w_secondary_mp_cost(weapon); + break; + case fo::AttackType::ATKTYPE_LWEAPON_RELOAD: + case fo::AttackType::ATKTYPE_RWEAPON_RELOAD: + if (weapon && weapon->protoId != fo::ProtoID::PID_SOLAR_SCORCHER) { // Solar Scorcher has no reload AP cost + cost = reloadCostAP; + if (fo::GetProto(weapon->protoId)->item.weapon.perk == fo::Perk::PERK_weapon_fast_reload) { + cost--; + } + } + } + if (hitMode < fo::AttackType::ATKTYPE_LWEAPON_RELOAD) { + if (isCalled) cost++; + if (cost < 0) cost = 0; + + long type = fo::func::item_w_subtype(weapon, hitMode); + + if (source->protoId == fo::ProtoID::PID_Player && sf::Perks::DudeHasTrait(fo::Trait::TRAIT_fast_shot)) { + if (fastShotTweak || // Fallout 1 behavior and Alternative behavior (allowed for all weapons) + (fo::func::item_w_range(source, hitMode) >= 2 && type > fo::AttackSubType::MELEE)) // Fallout 2 behavior (with fix) and Haenlomal's tweak + { + cost--; + } + } + if ((type == fo::AttackSubType::MELEE || type == fo::AttackSubType::UNARMED) && Stats::perk_level(source, fo::Perk::PERK_bonus_hth_attacks)) { + cost--; + } + if (type == fo::AttackSubType::GUNS && Stats::perk_level(source, fo::Perk::PERK_bonus_rate_of_fire)) { + cost--; + } + if (cost < 1) cost = 1; + } + return sf::CalcApCostHook_Invoke(source, hitMode, isCalled, cost, weapon); +} + +// Implementation of item_w_mp_cost_ engine function with the HOOK_CALCAPCOST hook +long Items::item_w_mp_cost(fo::GameObject* source, long hitMode, long isCalled) { + long cost = fo::func::item_w_mp_cost(source, hitMode, isCalled); + return sf::CalcApCostHook_Invoke(source, hitMode, isCalled, cost, nullptr); +} + +static void __declspec(naked) ai_search_inven_weap_hook() { + using namespace fo; + __asm { + push 0; // no called + push ATKTYPE_RWEAPON_PRIMARY; + mov edx, esi; // found weapon + mov ecx, edi; // source + call Items::item_weapon_mp_cost; + retn; + } +} + +void Items::init() { + // Replace the item_w_primary_mp_cost_ function with the sfall implementation + sf::HookCall(0x429A08, ai_search_inven_weap_hook); + + int fastShotFix = sf::IniReader::GetConfigInt("Misc", "FastShotFix", 0); + fastShotTweak = (fastShotFix > 0 && fastShotFix <= 3); +} + +} diff --git a/sfall/Game/items.h b/sfall/Game/items.h new file mode 100644 index 00000000..ddb1909a --- /dev/null +++ b/sfall/Game/items.h @@ -0,0 +1,31 @@ +/* + * sfall + * Copyright (C) 2008-2021 The sfall team + * + */ + +#pragma once + +namespace game +{ + +class Items { +public: + static void init(); + + static long item_count(fo::GameObject* who, fo::GameObject* item); + + static long item_weapon_range(fo::GameObject* source, fo::GameObject* weapon, long hitMode); + + //static long item_w_range(fo::GameObject* source, long hitMode); + + // Implementation of item_w_primary_mp_cost_ and item_w_secondary_mp_cost_ engine functions in a single function with the HOOK_CALCAPCOST hook + // Note: Use only for weapons + static long __fastcall item_weapon_mp_cost(fo::GameObject* source, fo::GameObject* weapon, long hitMode, long isCalled); + + // Implementation of item_w_mp_cost_ engine function with the HOOK_CALCAPCOST hook + // Note: Use the generic item_mp_cost function which has a hook call + static long item_w_mp_cost(fo::GameObject* source, long hitMode, long isCalled); +}; + +} \ No newline at end of file diff --git a/sfall/Game/objects.cpp b/sfall/Game/objects.cpp new file mode 100644 index 00000000..e8cf4239 --- /dev/null +++ b/sfall/Game/objects.cpp @@ -0,0 +1,37 @@ +/* + * sfall + * Copyright (C) 2008-2021 The sfall team + * + */ + +#include "..\main.h" +#include "..\FalloutEngine\Fallout2.h" + +#include "..\Modules\HookScripts\MiscHs.h" + +#include "objects.h" + +namespace game +{ + +namespace sf = sfall; + +// Implementation of is_within_perception_ engine function with the HOOK_WITHINPERCEPTION hook +long Objects::is_within_perception(fo::GameObject* watcher, fo::GameObject* target, long hookType) { + return sf::PerceptionRangeHook_Invoke(watcher, target, hookType, fo::func::is_within_perception(watcher, target)); +} + +// Alternative implementation of objFindObjPtrFromID_ engine function with the type of object to find +fo::GameObject* __fastcall Objects::FindObjectFromID(long id, long type) { + fo::GameObject* obj = fo::func::obj_find_first(); + while (obj) { + if (obj->id == id && obj->Type() == type) return obj; + obj = fo::func::obj_find_next(); + } + return nullptr; +} + +void Objects::init() { +} + +} diff --git a/sfall/Game/objects.h b/sfall/Game/objects.h new file mode 100644 index 00000000..3cd3bfef --- /dev/null +++ b/sfall/Game/objects.h @@ -0,0 +1,23 @@ +/* + * sfall + * Copyright (C) 2008-2021 The sfall team + * + */ + +#pragma once + +namespace game +{ + +class Objects { +public: + static void init(); + + // Implementation of is_within_perception_ engine function with the HOOK_WITHINPERCEPTION hook + static long is_within_perception(fo::GameObject* watcher, fo::GameObject* target, long hookType); + + // Alternative implementation of objFindObjPtrFromID_ engine function with the type of object to find + static fo::GameObject* __fastcall FindObjectFromID(long id, long type); +}; + +} \ No newline at end of file diff --git a/sfall/Game/skills.cpp b/sfall/Game/skills.cpp index 9cd6dbfa..3ddb4f1a 100644 --- a/sfall/Game/skills.cpp +++ b/sfall/Game/skills.cpp @@ -18,10 +18,6 @@ namespace sf = sfall; // TODO: skill_level_, perk_adjust_skill_ -static __forceinline bool CheckTrait(DWORD traitID) { - return (!sf::Perks::IsTraitDisabled(traitID) && (fo::var::pc_trait[0] == traitID || fo::var::pc_trait[1] == traitID)); -} - int __stdcall Skills::trait_adjust_skill(DWORD skillID) { int result = 0; if (sf::Perks::TraitsModEnable()) { @@ -29,9 +25,9 @@ int __stdcall Skills::trait_adjust_skill(DWORD skillID) { if (fo::var::pc_trait[1] != -1) result += sf::Perks::GetTraitSkillBonus(skillID, 1); } - if (CheckTrait(fo::TRAIT_gifted)) result -= 10; + if (sf::Perks::DudeHasTrait(fo::TRAIT_gifted)) result -= 10; - if (CheckTrait(fo::TRAIT_good_natured)) { + if (sf::Perks::DudeHasTrait(fo::TRAIT_good_natured)) { if (skillID <= fo::SKILL_THROWING) { result -= 10; } else if (skillID == fo::SKILL_FIRST_AID || skillID == fo::SKILL_DOCTOR || skillID == fo::SKILL_CONVERSANT || skillID == fo::SKILL_BARTER) { @@ -54,7 +50,7 @@ static void __declspec(naked) trait_adjust_skill_hack() { } void Skills::init() { - // Replace functions + // Replace trait_adjust_skill_ function sf::MakeJump(fo::funcoffs::trait_adjust_skill_, trait_adjust_skill_hack); // 0x4B40FC } diff --git a/sfall/Game/stats.cpp b/sfall/Game/stats.cpp index 46ddbb5e..2d4d2b33 100644 --- a/sfall/Game/stats.cpp +++ b/sfall/Game/stats.cpp @@ -18,12 +18,18 @@ namespace sf = sfall; static bool smallFrameTraitFix = false; -static int DudeGetBaseStat(DWORD statID) { - return fo::func::stat_get_base_direct(fo::var::obj_dude, statID); +int Stats::trait_level(DWORD traitID) { + return sf::Perks::DudeHasTrait(traitID); } -static __forceinline bool CheckTrait(DWORD traitID) { - return (!sf::Perks::IsTraitDisabled(traitID) && (fo::var::pc_trait[0] == traitID || fo::var::pc_trait[1] == traitID)); +// Support the player's party members +int Stats::perk_level(fo::GameObject* source, DWORD perkID) { + if (source != fo::var::obj_dude && !fo::IsPartyMember(source)) return 0; + return fo::func::perk_level(source, perkID); +} + +static int DudeGetBaseStat(DWORD statID) { + return fo::func::stat_get_base_direct(fo::var::obj_dude, statID); } int __stdcall Stats::trait_adjust_stat(DWORD statID) { @@ -37,39 +43,39 @@ int __stdcall Stats::trait_adjust_stat(DWORD statID) { switch (statID) { case fo::STAT_st: - if (CheckTrait(fo::TRAIT_gifted)) result++; - if (CheckTrait(fo::TRAIT_bruiser)) result += 2; + if (Stats::trait_level(fo::TRAIT_gifted)) result++; + if (Stats::trait_level(fo::TRAIT_bruiser)) result += 2; break; case fo::STAT_pe: - if (CheckTrait(fo::TRAIT_gifted)) result++; + if (Stats::trait_level(fo::TRAIT_gifted)) result++; break; case fo::STAT_en: - if (CheckTrait(fo::TRAIT_gifted)) result++; + if (Stats::trait_level(fo::TRAIT_gifted)) result++; break; case fo::STAT_ch: - if (CheckTrait(fo::TRAIT_gifted)) result++; + if (Stats::trait_level(fo::TRAIT_gifted)) result++; break; case fo::STAT_iq: - if (CheckTrait(fo::TRAIT_gifted)) result++; + if (Stats::trait_level(fo::TRAIT_gifted)) result++; break; case fo::STAT_ag: - if (CheckTrait(fo::TRAIT_gifted)) result++; - if (CheckTrait(fo::TRAIT_small_frame)) result++; + if (Stats::trait_level(fo::TRAIT_gifted)) result++; + if (Stats::trait_level(fo::TRAIT_small_frame)) result++; break; case fo::STAT_lu: - if (CheckTrait(fo::TRAIT_gifted)) result++; + if (Stats::trait_level(fo::TRAIT_gifted)) result++; break; case fo::STAT_max_move_points: - if (CheckTrait(fo::TRAIT_bruiser)) result -= 2; + if (Stats::trait_level(fo::TRAIT_bruiser)) result -= 2; break; case fo::STAT_ac: - if (CheckTrait(fo::TRAIT_kamikaze)) return -DudeGetBaseStat(fo::STAT_ac); + if (Stats::trait_level(fo::TRAIT_kamikaze)) return -DudeGetBaseStat(fo::STAT_ac); break; case fo::STAT_melee_dmg: - if (CheckTrait(fo::TRAIT_heavy_handed)) result += 4; + if (Stats::trait_level(fo::TRAIT_heavy_handed)) result += 4; break; case fo::STAT_carry_amt: - if (CheckTrait(fo::TRAIT_small_frame)) { + if (Stats::trait_level(fo::TRAIT_small_frame)) { int st; if (smallFrameTraitFix) { st = fo::func::stat_level(fo::var::obj_dude, fo::STAT_st); @@ -80,22 +86,22 @@ int __stdcall Stats::trait_adjust_stat(DWORD statID) { } break; case fo::STAT_sequence: - if (CheckTrait(fo::TRAIT_kamikaze)) result += 5; + if (Stats::trait_level(fo::TRAIT_kamikaze)) result += 5; break; case fo::STAT_heal_rate: - if (CheckTrait(fo::TRAIT_fast_metabolism)) result += 2; + if (Stats::trait_level(fo::TRAIT_fast_metabolism)) result += 2; break; case fo::STAT_crit_chance: - if (CheckTrait(fo::TRAIT_finesse)) result += 10; + if (Stats::trait_level(fo::TRAIT_finesse)) result += 10; break; case fo::STAT_better_crit: - if (CheckTrait(fo::TRAIT_heavy_handed)) result -= 30; + if (Stats::trait_level(fo::TRAIT_heavy_handed)) result -= 30; break; case fo::STAT_rad_resist: - if (CheckTrait(fo::TRAIT_fast_metabolism)) return -DudeGetBaseStat(fo::STAT_rad_resist); + if (Stats::trait_level(fo::TRAIT_fast_metabolism)) return -DudeGetBaseStat(fo::STAT_rad_resist); break; case fo::STAT_poison_resist: - if (CheckTrait(fo::TRAIT_fast_metabolism)) return -DudeGetBaseStat(fo::STAT_poison_resist); + if (Stats::trait_level(fo::TRAIT_fast_metabolism)) return -DudeGetBaseStat(fo::STAT_poison_resist); break; } return result; @@ -114,11 +120,11 @@ static void __declspec(naked) trait_adjust_stat_hack() { } void Stats::init() { - // Replace functions + // Replace trait_adjust_stat_ function sf::MakeJump(fo::funcoffs::trait_adjust_stat_, trait_adjust_stat_hack); // 0x4B3C7C // Fix the carry weight penalty of the Small Frame trait not being applied to bonus Strength points - smallFrameTraitFix = (sf::GetConfigInt("Misc", "SmallFrameFix", 0) != 0); + smallFrameTraitFix = (sf::IniReader::GetConfigInt("Misc", "SmallFrameFix", 0) != 0); } } diff --git a/sfall/Game/stats.h b/sfall/Game/stats.h index d25a7673..058883f5 100644 --- a/sfall/Game/stats.h +++ b/sfall/Game/stats.h @@ -13,6 +13,9 @@ class Stats { public: static void init(); + static int trait_level(DWORD statID); + static int perk_level(fo::GameObject* source, DWORD perkID); + static int __stdcall trait_adjust_stat(DWORD statID); }; diff --git a/sfall/Game/template.cpp b/sfall/Game/template.cpp new file mode 100644 index 00000000..fa9a5ca2 --- /dev/null +++ b/sfall/Game/template.cpp @@ -0,0 +1,21 @@ +/* + * sfall + * Copyright (C) 2008-2021 The sfall team + * + */ + +#include "..\main.h" +#include "..\FalloutEngine\Fallout2.h" + +#include "x.h" + +namespace game +{ + +namespace sf = sfall; + +void x::init() { + +} + +} \ No newline at end of file diff --git a/sfall/Game/template.h b/sfall/Game/template.h new file mode 100644 index 00000000..412fd22c --- /dev/null +++ b/sfall/Game/template.h @@ -0,0 +1,18 @@ +/* + * sfall + * Copyright (C) 2008-2021 The sfall team + * + */ + +#pragma once + +namespace game +{ + +class x { +public: + static void init(); + +}; + +} \ No newline at end of file diff --git a/sfall/Game/tilemap.cpp b/sfall/Game/tilemap.cpp new file mode 100644 index 00000000..ba1db0f8 --- /dev/null +++ b/sfall/Game/tilemap.cpp @@ -0,0 +1,192 @@ +/* + * sfall + * Copyright (C) 2008-2021 The sfall team + * + */ + +#include "..\main.h" +#include "..\FalloutEngine\Fallout2.h" + +#include "tilemap.h" + +namespace game +{ + +namespace sf = sfall; + +static fo::GameObject* __fastcall obj_path_blocking_at(fo::GameObject* source, long tile, long elev) { + if (tile < 0 || tile >= 40000) return nullptr; + + fo::ObjectTable* obj = fo::var::objectTable[tile]; + while (obj) { + if (elev == obj->object->elevation) { + fo::GameObject* object = obj->object; + long flags = object->flags; + if (!(flags & (fo::ObjectFlag::Mouse_3d | fo::ObjectFlag::NoBlock)) && source != object) { + char type = object->TypeFid(); + if (type == fo::ObjType::OBJ_TYPE_SCENERY || type == fo::ObjType::OBJ_TYPE_WALL) { + return object; + } + } + } + obj = obj->nextObject; + } + // check for multihex objects on the tile + long direction = 0; + do { + long _tile = fo::func::tile_num_in_direction(tile, direction, 1); + if (_tile >= 0 && _tile < 40000) { + obj = fo::var::objectTable[_tile]; + while (obj) { + if (elev == obj->object->elevation) { + fo::GameObject* object = obj->object; + long flags = object->flags; + if (flags & fo::ObjectFlag::MultiHex && !(flags & (fo::ObjectFlag::Mouse_3d | fo::ObjectFlag::NoBlock)) && source != object) { + char type = object->TypeFid(); + if (type == fo::ObjType::OBJ_TYPE_SCENERY || type == fo::ObjType::OBJ_TYPE_WALL) { + return object; + } + } + } + obj = obj->nextObject; + } + } + } while (++direction < 6); + return nullptr; +} + +void __declspec(naked) Tilemap::obj_path_blocking_at_() { + __asm { + push ecx; + push ebx; + mov ecx, eax; + call obj_path_blocking_at; + pop ecx; + retn; + } +} + +//static std::vector buildLineTiles; + +//static bool TileExists(long tile) { +// return (std::find(buildLineTiles.cbegin(), buildLineTiles.cend(), tile) != buildLineTiles.cend()); +//} + +// Fixed and improved implementation of tile_num_beyond_ engine function +// - correctly gets the tile from the constructed line +// - fixed the range when the target tile was positioned at the maximum distance +long __fastcall Tilemap::tile_num_beyond(long sourceTile, long targetTile, long maxRange) { + if (maxRange <= 0 || sourceTile == targetTile) return sourceTile; + + /*if (buildLineTiles.empty()) { + buildLineTiles.reserve(100); + } else { + buildLineTiles.clear(); + }*/ + + long currentRange = fo::func::tile_dist(sourceTile, targetTile); + //fo::func::debug_printf("\ntile_dist: %d", currentRange); + if (currentRange == maxRange) maxRange++; // increase the range if the target is located at a distance equal to maxRange (fix range) + + long lastTile = targetTile; + long source_X, source_Y, target_X, target_Y; + + fo::func::tile_coord(sourceTile, &source_X, &source_Y); + fo::func::tile_coord(targetTile, &target_X, &target_Y); + + // set the point to the center of the hexagon + source_X += 16; + source_Y += 8; + target_X += 16; + target_Y += 8; + + long diffX = target_X - source_X; + long addToX = -1; + if (diffX >= 0) addToX = (diffX > 0); + + long diffY = target_Y - source_Y; + long addToY = -1; + if (diffY >= 0) addToY = (diffY > 0); + + long diffX_x2 = 2 * std::abs(diffX); + long diffY_x2 = 2 * std::abs(diffY); + + const int step = 4; + long stepCounter = step - 1; + + if (diffX_x2 > diffY_x2) { + long stepY = diffY_x2 - (diffX_x2 >> 1); + while (true) { + if (++stepCounter == step) { + long tile = fo::func::tile_num(target_X, target_Y); + //fo::func::debug_printf("\ntile_num: %d [x:%d y:%d]", tile, target_X, target_Y); + if (tile != lastTile) { + //if (!TileExists(tile)) { + long dist = fo::func::tile_dist(targetTile, tile); + if ((dist + currentRange) >= maxRange || fo::func::tile_on_edge(tile)) return tile; + // buildLineTiles.push_back(tile); + //} + lastTile = tile; + } + stepCounter = 0; + } + if (stepY >= 0) { + stepY -= diffX_x2; + target_Y += addToY; + } + stepY += diffY_x2; + target_X += addToX; + + // Example of an algorithm constructing a straight line from point A to B + // source: x = 784(800), y = 278(286) + // target: x = 640(656), y = 314(322) - the target is located to the left and below + // 0. x = 800, y = 286, stepY = -72 + // 1. x = 799, y = 286, stepY = -72+72=0 + // 2. x = 798, y = 287, stepY = 0-288+72=-216 + // 3. x = 797, y = 287, stepY = -216+72=-144 + // 4. x = 796, y = 287, stepY = -144+72=-72 + // 5. x = 795, y = 287, stepY = -72+72=0 + // 6. x = 794, y = 288, stepY = 0-288+72=-216 + } + } else { + long stepX = diffX_x2 - (diffY_x2 >> 1); + while (true) { + if (++stepCounter == step) { + long tile = fo::func::tile_num(target_X, target_Y); + //fo::func::debug_printf("\ntile_num: %d [x:%d y:%d]", tile, target_X, target_Y); + if (tile != lastTile) { + //if (!TileExists(tile)) { + long dist = fo::func::tile_dist(targetTile, tile); + if ((dist + currentRange) >= maxRange || fo::func::tile_on_edge(tile)) return tile; + // buildLineTiles.push_back(tile); + //} + lastTile = tile; + } + stepCounter = 0; + } + if (stepX >= 0) { + stepX -= diffY_x2; + target_X += addToX; + } + stepX += diffX_x2; + target_Y += addToY; + } + } +} + +static void __declspec(naked) tile_num_beyond_hack() { + __asm { //push ecx; + push ebx; + mov ecx, eax; + call Tilemap::tile_num_beyond; + pop ecx; + retn; + } +} + +void Tilemap::init() { + // Replace tile_num_beyond_ function + sf::MakeJump(fo::funcoffs::tile_num_beyond_ + 1, tile_num_beyond_hack); // 0x4B1B84 +} + +} diff --git a/sfall/Game/tilemap.h b/sfall/Game/tilemap.h new file mode 100644 index 00000000..ad5b2edb --- /dev/null +++ b/sfall/Game/tilemap.h @@ -0,0 +1,21 @@ +/* + * sfall + * Copyright (C) 2008-2021 The sfall team + * + */ + +#pragma once + +namespace game +{ + +class Tilemap { +public: + static void init(); + + static void obj_path_blocking_at_(); + + static long __fastcall tile_num_beyond(long sourceTile, long targetTile, long maxRange); +}; + +} \ No newline at end of file diff --git a/sfall/IniReader.cpp b/sfall/IniReader.cpp new file mode 100644 index 00000000..d2ca1e3a --- /dev/null +++ b/sfall/IniReader.cpp @@ -0,0 +1,116 @@ +/* + * sfall + * Copyright (C) 2008-2021 The sfall team + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "Utils.h" + +#include "IniReader.h" + +namespace sfall +{ + +DWORD IniReader::modifiedIni; + +static const char* ddrawIni = ".\\ddraw.ini"; +static char ini[65] = ".\\"; + +static int getInt(const char* section, const char* setting, int defaultValue, const char* iniFile) { + return GetPrivateProfileIntA(section, setting, defaultValue, iniFile); +} + +static size_t getString(const char* section, const char* setting, const char* defaultValue, char* buf, size_t bufSize, const char* iniFile) { + return GetPrivateProfileStringA(section, setting, defaultValue, buf, bufSize, iniFile); +} + +static std::string getString(const char* section, const char* setting, const char* defaultValue, size_t bufSize, const char* iniFile) { + char* buf = new char[bufSize]; + getString(section, setting, defaultValue, buf, bufSize, iniFile); + std::string str(buf); + delete[] buf; + return str; +} + +static std::vector getList(const char* section, const char* setting, const char* defaultValue, size_t bufSize, char delimiter, const char* iniFile) { + auto list = split(getString(section, setting, defaultValue, bufSize, iniFile), delimiter); + std::transform(list.cbegin(), list.cend(), list.begin(), trim); + return list; +} + +const char* IniReader::GetConfigFile() { + return ini; +} + +void IniReader::SetDefaultConfigFile() { + std::strcpy(&ini[2], &ddrawIni[2]); +} + +void IniReader::SetConfigFile(const char* iniFile) { + strcat_s(ini, iniFile); +} + +int IniReader::GetIntDefaultConfig(const char* section, const char* setting, int defaultValue) { + return getInt(section, setting, defaultValue, ddrawIni); +} + +std::vector IniReader::GetListDefaultConfig(const char* section, const char* setting, const char* defaultValue, size_t bufSize, char delimiter) { + return getList(section, setting, defaultValue, bufSize, delimiter, ddrawIni); +} + +int IniReader::GetConfigInt(const char* section, const char* setting, int defaultValue) { + return getInt(section, setting, defaultValue, ini); +} + +std::string IniReader::GetConfigString(const char* section, const char* setting, const char* defaultValue, size_t bufSize) { + return trim(getString(section, setting, defaultValue, bufSize, ini)); +} + +size_t IniReader::GetConfigString(const char* section, const char* setting, const char* defaultValue, char* buf, size_t bufSize) { + return getString(section, setting, defaultValue, buf, bufSize, ini); +} + +std::vector IniReader::GetConfigList(const char* section, const char* setting, const char* defaultValue, size_t bufSize) { + return getList(section, setting, defaultValue, bufSize, ',', ini); +} + +int IniReader::GetInt(const char* section, const char* setting, int defaultValue, const char* iniFile) { + return getInt(section, setting, defaultValue, iniFile); +} + +size_t IniReader::GetString(const char* section, const char* setting, const char* defaultValue, char* buf, size_t bufSize, const char* iniFile) { + return getString(section, setting, defaultValue, buf, bufSize, iniFile); +} + +std::string IniReader::GetString(const char* section, const char* setting, const char* defaultValue, size_t bufSize, const char* iniFile) { + return getString(section, setting, defaultValue, bufSize, iniFile); +} + +std::vector IniReader::GetList(const char* section, const char* setting, const char* defaultValue, size_t bufSize, char delimiter, const char* iniFile) { + return getList(section, setting, defaultValue, bufSize, delimiter, iniFile); +} + +int IniReader::SetConfigInt(const char* section, const char* setting, int value) { + char buf[33]; + _itoa_s(value, buf, 33, 10); + int result = WritePrivateProfileStringA(section, setting, buf, ini); + return result; +} + +void IniReader::init() { + modifiedIni = IniReader::GetConfigInt("Main", "ModifiedIni", 0); +} + +} diff --git a/sfall/IniReader.h b/sfall/IniReader.h new file mode 100644 index 00000000..9858aceb --- /dev/null +++ b/sfall/IniReader.h @@ -0,0 +1,67 @@ +/* + * sfall + * Copyright (C) 2008-2021 The sfall team + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +namespace sfall +{ + +class IniReader { +public: + static void init(); + + static DWORD modifiedIni; + + static const char* GetConfigFile(); + static void SetDefaultConfigFile(); + static void SetConfigFile(const char* iniFile); + + // Gets the integer value from the default config (i.e. ddraw.ini) + static int GetIntDefaultConfig(const char* section, const char* setting, int defaultValue); + + // Gets a list of values separated by the delimiter from the default config (i.e. ddraw.ini) + static std::vector GetListDefaultConfig(const char* section, const char* setting, const char* defaultValue, size_t bufSize, char delimiter); + + // Gets the integer value from sfall configuration INI file + static int GetConfigInt(const char* section, const char* setting, int defaultValue); + + // Gets the string value from sfall configuration INI file with trim function + static std::string GetConfigString(const char* section, const char* setting, const char* defaultValue, size_t bufSize = 128); + + // Loads the string value from sfall configuration INI file into the provided buffer + static size_t GetConfigString(const char* section, const char* setting, const char* defaultValue, char* buffer, size_t bufSize = 128); + + // Parses the comma-separated list from the settings from sfall configuration INI file + static std::vector GetConfigList(const char* section, const char* setting, const char* defaultValue, size_t bufSize = 128); + + // Gets the integer value from given INI file + static int GetInt(const char* section, const char* setting, int defaultValue, const char* iniFile); + + // Gets the string value from given INI file + static size_t GetString(const char* section, const char* setting, const char* defaultValue, char* buf, size_t bufSize, const char* iniFile); + + // Gets the string value from given INI file + static std::string GetString(const char* section, const char* setting, const char* defaultValue, size_t bufSize, const char* iniFile); + + // Parses the comma-separated list setting from given INI file + static std::vector GetList(const char* section, const char* setting, const char* defaultValue, size_t bufSize, char delimiter, const char* iniFile); + + static int SetConfigInt(const char* section, const char* setting, int value); +}; + +} diff --git a/sfall/InputFuncs.cpp b/sfall/InputFuncs.cpp index 99a1dc1d..c28ab9e0 100644 --- a/sfall/InputFuncs.cpp +++ b/sfall/InputFuncs.cpp @@ -52,6 +52,7 @@ static double mousePartX; static double mousePartY; #define MAX_KEYS (264) + static DWORD keysDown[MAX_KEYS] = {0}; static int mouseX; @@ -60,6 +61,7 @@ static int mouseY; static DWORD forcingGraphicsRefresh = 0; void __stdcall ForceGraphicsRefresh(DWORD d) { + if (!d3d9Device) return; forcingGraphicsRefresh = (d == 0) ? 0 : 1; } @@ -301,11 +303,14 @@ public: for (DWORD i = 0; i < *count; i++) { DWORD dxKey = buf[i].dwOfs; + assert(dxKey >= 0 && dxKey < MAX_KEYS); DWORD state = buf[i].dwData & 0x80; DWORD oldState = keysDown[dxKey]; keysDown[dxKey] = state; + HookCommon::KeyPressHook(&dxKey, (state > 0), MapVirtualKeyEx(dxKey, MAPVK_VSC_TO_VK, keyboardLayout)); - if (dxKey > 0 && dxKey != buf[i].dwOfs) { + + if ((long)dxKey > 0 && dxKey != buf[i].dwOfs) { keysDown[buf[i].dwOfs] = oldState; buf[i].dwOfs = dxKey; // Override key keysDown[buf[i].dwOfs] = state; @@ -436,11 +441,11 @@ public: }; inline void InitInputFeatures() { - reverseMouse = GetConfigInt("Input", "ReverseMouseButtons", 0) != 0; + reverseMouse = IniReader::GetConfigInt("Input", "ReverseMouseButtons", 0) != 0; - useScrollWheel = GetConfigInt("Input", "UseScrollWheel", 1) != 0; - wheelMod = GetConfigInt("Input", "ScrollMod", 0); - LONG MouseSpeed = GetConfigInt("Input", "MouseSensitivity", 100); + useScrollWheel = IniReader::GetConfigInt("Input", "UseScrollWheel", 1) != 0; + wheelMod = IniReader::GetConfigInt("Input", "ScrollMod", 0); + LONG MouseSpeed = IniReader::GetConfigInt("Input", "MouseSensitivity", 100); if (MouseSpeed != 100) { adjustMouseSpeed = true; mouseSpeedMod = ((double)MouseSpeed) / 100.0; @@ -448,11 +453,11 @@ inline void InitInputFeatures() { mousePartY = 0; } else adjustMouseSpeed = false; - middleMouseKey = GetConfigInt("Input", "MiddleMouse", 0x30); + middleMouseKey = IniReader::GetConfigInt("Input", "MiddleMouse", DIK_B); middleMouseDown = false; - backgroundKeyboard = GetConfigInt("Input", "BackgroundKeyboard", 0) != 0; - backgroundMouse = GetConfigInt("Input", "BackgroundMouse", 0) != 0; + backgroundKeyboard = IniReader::GetConfigInt("Input", "BackgroundKeyboard", 0) != 0; + backgroundMouse = IniReader::GetConfigInt("Input", "BackgroundMouse", 0) != 0; keyboardLayout = GetKeyboardLayout(0); } diff --git a/sfall/Logging.cpp b/sfall/Logging.cpp index 4a00c069..06568005 100644 --- a/sfall/Logging.cpp +++ b/sfall/Logging.cpp @@ -74,18 +74,21 @@ void devlog_f(...) {} void LoggingInit() { Log.open("sfall-log.txt", std::ios_base::out | std::ios_base::trunc); - if (iniGetInt("Debugging", "Init", 0, ::sfall::ddrawIni)) { + if (IniReader::GetIntDefaultConfig("Debugging", "Init", 0)) { DebugTypes |= DL_INIT; } - if (iniGetInt("Debugging", "Hook", 0, ::sfall::ddrawIni)) { + if (IniReader::GetIntDefaultConfig("Debugging", "Hook", 0)) { DebugTypes |= DL_HOOK; } - if (iniGetInt("Debugging", "Script", 0, ::sfall::ddrawIni)) { + if (IniReader::GetIntDefaultConfig("Debugging", "Script", 0)) { DebugTypes |= DL_SCRIPT; } - if (iniGetInt("Debugging", "Criticals", 0, ::sfall::ddrawIni)) { + if (IniReader::GetIntDefaultConfig("Debugging", "Criticals", 0)) { DebugTypes |= DL_CRITICALS; } + if (IniReader::GetIntDefaultConfig("Debugging", "Fixes", 0)) { + DebugTypes |= DL_FIX; + } } } diff --git a/sfall/Logging.h b/sfall/Logging.h index a0239fc7..d7b2498f 100644 --- a/sfall/Logging.h +++ b/sfall/Logging.h @@ -17,10 +17,11 @@ */ #define DL_MAIN (0) -#define DL_INIT (1<<1) -#define DL_HOOK (1<<2) -#define DL_SCRIPT (1<<3) -#define DL_CRITICALS (1<<4) +#define DL_INIT (0x1) +#define DL_HOOK (0x2) +#define DL_SCRIPT (0x4) +#define DL_CRITICALS (0x8) +#define DL_FIX (0x10) #ifndef NO_SFALL_DEBUG #include diff --git a/sfall/ModuleManager.h b/sfall/ModuleManager.h index aa1101be..c1a5eb07 100644 --- a/sfall/ModuleManager.h +++ b/sfall/ModuleManager.h @@ -5,7 +5,7 @@ #include "Modules\Module.h" -namespace sfall +namespace sfall { // Singleton for managing all of Sfall modules. @@ -17,7 +17,7 @@ public: void initAll(); - template + template void add() { _modules.emplace_back(new T()); diff --git a/sfall/Modules/AI.cpp b/sfall/Modules/AI.cpp index ff2ee259..9c7a448f 100644 --- a/sfall/Modules/AI.cpp +++ b/sfall/Modules/AI.cpp @@ -20,16 +20,16 @@ #include "..\main.h" #include "..\FalloutEngine\Fallout2.h" +#include "LoadGameHook.h" -#include "HookScripts\CombatHS.h" +#include "..\Game\items.h" #include "AI.h" namespace sfall { -using namespace fo; -using namespace Fields; +using namespace fo::Fields; static std::unordered_map targets; static std::unordered_map sources; @@ -47,35 +47,45 @@ fo::GameObject* AI::CheckShootAndFriendlyInLineOfFire(fo::GameObject* object, lo } // continue checking the line of fire from object tile to targetTile fo::GameObject* obj = object; // for ignoring the object (multihex) when building the path - fo::func::make_straight_path_func(object, objTile, targetTile, 0, (DWORD*)&obj, 32, (void*)fo::funcoffs::obj_shoot_blocking_at_); - if (!CheckShootAndFriendlyInLineOfFire(obj, targetTile, team)) return nullptr; + fo::func::make_straight_path_func(object, objTile, targetTile, 0, (DWORD*)&obj, 0x20, (void*)fo::funcoffs::obj_shoot_blocking_at_); + + object = CheckShootAndFriendlyInLineOfFire(obj, targetTile, team); } - return object; + return object; // friendly critter, any object or null } // Returns the friendly critter in the line of fire fo::GameObject* AI::CheckFriendlyFire(fo::GameObject* target, fo::GameObject* attacker) { fo::GameObject* object = nullptr; - fo::func::make_straight_path_func(attacker, attacker->tile, target->tile, 0, (DWORD*)&object, 32, (void*)fo::funcoffs::obj_shoot_blocking_at_); + fo::func::make_straight_path_func(attacker, attacker->tile, target->tile, 0, (DWORD*)&object, 0x20, (void*)fo::funcoffs::obj_shoot_blocking_at_); object = CheckShootAndFriendlyInLineOfFire(object, target->tile, attacker->critter.teamNum); - return (!object || object->TypeFid() == fo::ObjType::OBJ_TYPE_CRITTER) ? object : nullptr; // 0 if there are no friendly critters + return (object && object->IsCritter()) ? object : nullptr; // 0 - if there are no friendly critters } +bool AI::AttackInRange(fo::GameObject* source, fo::GameObject* weapon, long distance) { + if (game::Items::item_weapon_range(source, weapon, fo::AttackType::ATKTYPE_RWEAPON_PRIMARY) >= distance) return true; + return (game::Items::item_weapon_range(source, weapon, fo::AttackType::ATKTYPE_RWEAPON_SECONDARY) >= distance); +} + +//////////////////////////////////////////////////////////////////////////////// + static void __declspec(naked) ai_try_attack_hook_FleeFix() { + using namespace fo; __asm { - or byte ptr [esi + combatState], 8; // set new 'ReTarget' flag + or byte ptr [esi + combatState], ReTarget; // set CombatStateFlag flag jmp fo::funcoffs::ai_run_away_; } } static void __declspec(naked) combat_ai_hook_FleeFix() { static const DWORD combat_ai_hook_flee_Ret = 0x42B206; + using namespace fo; __asm { - test byte ptr [ebp], 8; // 'ReTarget' flag (critter.combat_state) + test byte ptr [ebp], ReTarget; // CombatStateFlag flag (critter.combat_state) jnz reTarget; jmp fo::funcoffs::critter_name_; reTarget: - and byte ptr [ebp], ~(4 | 8); // unset Flee/ReTarget flags + and byte ptr [ebp], ~(InFlee | ReTarget); // unset CombatStateFlag flags xor edi, edi; mov dword ptr [esi + whoHitMe], edi; add esp, 4; @@ -83,6 +93,15 @@ reTarget: } } +static void __declspec(naked) ai_try_attack_hook_runFix() { + __asm { + mov ecx, [esi + combatState]; // save combat flags before ai_run_away + call fo::funcoffs::ai_run_away_; + mov [esi + combatState], ecx; // restore combat flags + retn; + } +} + static void __declspec(naked) combat_ai_hack() { static const DWORD combat_ai_hack_Ret = 0x42B204; __asm { @@ -112,6 +131,45 @@ static void __declspec(naked) ai_check_drugs_hook() { } } +static void __declspec(naked) ai_check_drugs_hook_healing() { + using namespace fo; + __asm { + call fo::funcoffs::ai_retrieve_object_; + cmp [esp + 0x34 - 0x30 + 4], 2; // noInvenItem: is set to 2 that healing is required + jne checkPid; + retn; // use drugs +checkPid: + test eax, eax; + jnz skip; + retn; +skip: + mov edx, [eax + protoId]; + cmp edx, PID_STIMPAK; + je checkHP; + cmp edx, PID_SUPER_STIMPAK; + je checkHP; + cmp edx, PID_HEALING_POWDER; + je checkHP; + retn; +checkHP: + push eax; + mov ebx, 10; + add ebx, [esi + health]; // source + mov eax, esi; + mov edx, STAT_max_hit_points; + call fo::funcoffs::stat_level_; + cmp ebx, eax; + pop eax; + jge dontUse; // 10 + currHP >= maxHP + retn +dontUse: + xor eax, eax; + retn; + } +} + +//////////////////////////////////////////////////////////////////////////////// + static bool __fastcall TargetExistInList(fo::GameObject* target, fo::GameObject** targetList) { char i = 4; do { @@ -181,7 +239,10 @@ skip: } } -static void __declspec(naked) ai_danger_source_hack_pm_newfind() { +//////////////////////////////////////////////////////////////////////////////// + +static void __declspec(naked) ai_danger_source_hack_pm_newFind() { + using namespace fo; __asm { mov ecx, [ebp + 0x18]; // source combat_data.who_hit_me test ecx, ecx; @@ -197,32 +258,45 @@ isNotDead: } } -static long __fastcall sf_ai_check_weapon_switch(fo::GameObject* target, long &hitMode, fo::GameObject* source, fo::GameObject* weapon) { - if (source->critter.movePoints <= 0) return -1; - if (!weapon) return 1; // no weapon in hand slots +//////////////////////////////////////////////////////////////////////////////// - long _hitMode; - if ((_hitMode = fo::func::ai_pick_hit_mode(source, weapon, target)) != hitMode) { - hitMode = _hitMode; - return 0; // change hit mode +static long __fastcall ai_try_attack_switch_fix(fo::GameObject* target, long &hitMode, fo::GameObject* source, fo::GameObject* weapon) { + if (source->critter.movePoints <= 0) return -1; // exit from ai_try_attack_ + if (!weapon) return 1; // no weapon in inventory or hand slot, continue to search weapons on the map (call ai_switch_weapons_) + + long _hitMode = fo::func::ai_pick_hit_mode(source, weapon, target); + if (_hitMode != hitMode && _hitMode != fo::AttackType::ATKTYPE_PUNCH) { + if (game::Items::item_weapon_mp_cost(source, weapon, _hitMode, 0) <= source->critter.movePoints) { + hitMode = _hitMode; + return 0; // change hit mode, continue attack cycle + } } - fo::GameObject* item = fo::func::ai_search_inven_weap(source, 1, target); - if (!item) return 1; // no weapon in inventory, true to allow to continue searching for weapons on the map - - long wType = fo::func::item_w_subtype(item, AttackType::ATKTYPE_RWEAPON_PRIMARY); - if (wType <= AttackSubType::MELEE) { // unarmed and melee weapons, check the distance before switching - if (fo::func::obj_dist(source, target) > 2) return -1; + // does the NPC have other weapons in inventory? + fo::GameObject* item = fo::func::ai_search_inven_weap(source, 1, target); // search based on AP + if (item) { + // is using a close range weapon? + long wType = fo::func::item_w_subtype(item, fo::AttackType::ATKTYPE_RWEAPON_PRIMARY); + if (wType <= fo::AttackSubType::MELEE) { // unarmed and melee weapons, check the distance before switching + if (!AI::AttackInRange(source, item, fo::func::obj_dist(source, target))) return -1; // target out of range, exit ai_try_attack_ + } + return 1; // all good, execute vanilla behavior of ai_switch_weapons_ function } - return 1; + + // no other weapon in inventory + if (fo::func::item_w_range(source, fo::AttackType::ATKTYPE_PUNCH) >= fo::func::obj_dist(source, target)) { + hitMode = fo::AttackType::ATKTYPE_PUNCH; + return 0; // change hit mode, continue attack cycle + } + return -1; // exit, NPC has a weapon in hand slot, so we don't look for another weapon on the map } static void __declspec(naked) ai_try_attack_hook_switch_fix() { __asm { push edx; - push [ebx];//push dword ptr [esp + 0x364 - 0x3C + 8]; // weapon - push esi; // source - call sf_ai_check_weapon_switch; // edx - hit mode + push [ebx]; // weapon + push esi; // source + call ai_try_attack_switch_fix; // ecx - target, edx - hit mode pop edx; test eax, eax; jle noSwitch; // <= 0 @@ -234,6 +308,8 @@ noSwitch: } } +//////////////////////////////////////////////////////////////////////////////// + static long RetryCombatMinAP; static void __declspec(naked) RetryCombatHook() { @@ -262,7 +338,9 @@ end: } } -static long __fastcall sf_ai_weapon_reload(fo::GameObject* weapon, fo::GameObject* ammo, fo::GameObject* critter) { +//////////////////////////////////////////////////////////////////////////////// + +static long __fastcall ai_weapon_reload_fix(fo::GameObject* weapon, fo::GameObject* ammo, fo::GameObject* critter) { fo::Proto* proto = nullptr; long result = -1; long maxAmmo; @@ -299,13 +377,14 @@ static long __fastcall sf_ai_weapon_reload(fo::GameObject* weapon, fo::GameObjec } static void __declspec(naked) item_w_reload_hook() { + using namespace fo; __asm { cmp dword ptr [eax + protoId], PID_SOLAR_SCORCHER; je skip; push ecx; push esi; // source mov ecx, eax; // weapon - call sf_ai_weapon_reload; // edx - ammo + call ai_weapon_reload_fix; // edx - ammo pop ecx; retn; skip: @@ -313,12 +392,60 @@ skip: } } +//////////////////////////////////////////////////////////////////////////////// + +static long tempReloadCost; + +static long __fastcall item_weapon_reload_cost_fix(fo::GameObject* source, fo::GameObject* weapon, fo::GameObject** outAmmo) { + long reloadCost = game::Items::item_weapon_mp_cost(source, weapon, fo::AttackType::ATKTYPE_RWEAPON_RELOAD, 0); + if (reloadCost > source->critter.movePoints) return -1; // not enough action points + tempReloadCost = reloadCost; + + return fo::func::ai_have_ammo(source, weapon, outAmmo); // 0 - no ammo +} + +static void __declspec(naked) ai_try_attack_hook_cost_reload() { + static const DWORD ai_try_attack_hook_goNext_Ret = 0x42A9F2; + __asm { + push ebx; // ammoObj ref + mov ecx, eax; // source + call item_weapon_reload_cost_fix; // edx - weapon + cmp eax, -1; + je noAPs; + retn; +noAPs: // not enough action points + add esp, 4; // destroy ret + mov edi, 10; + jmp ai_try_attack_hook_goNext_Ret; // end ai_try_attack_ + } +} + +static void __declspec(naked) ai_try_attack_hook_cost1() { + __asm { + xor ebx, ebx; + sub edx, tempReloadCost; // curr.mp - reload cost + cmovg ebx, edx; // if curr.mp > 0 + retn; + } +} + +static void __declspec(naked) ai_try_attack_hook_cost2() { + __asm { + xor ecx, ecx; + sub ebx, tempReloadCost; // curr.mp - reload cost + cmovg ecx, ebx; // if curr.mp > 0 + retn; + } +} + +///////////////////////////////////////////////////////////////////////////////////////// + static long __fastcall CheckWeaponRangeAndApCost(fo::GameObject* source, fo::GameObject* target) { long weaponRange = fo::func::item_w_range(source, fo::ATKTYPE_RWEAPON_SECONDARY); long targetDist = fo::func::obj_dist(source, target); if (targetDist > weaponRange) return 0; // don't use secondary mode - return (source->critter.movePoints >= sf_item_w_mp_cost(source, fo::ATKTYPE_RWEAPON_SECONDARY, 0)); // 1 - allow secondary mode + return (source->critter.movePoints >= game::Items::item_w_mp_cost(source, fo::ATKTYPE_RWEAPON_SECONDARY, 0)); // 1 - allow secondary mode } static void __declspec(naked) ai_pick_hit_mode_hook() { @@ -348,16 +475,17 @@ fix: // check result } static void __declspec(naked) cai_perform_distance_prefs_hack() { + using namespace fo; __asm { - mov ebx, eax; // current distance to target - mov ecx, esi; - push 0; // no called shot + mov ecx, eax; // current distance to target + xor ebx, ebx; // no called shot mov edx, ATKTYPE_RWEAPON_PRIMARY; - call sf_item_w_mp_cost; + mov eax, esi; + call fo::funcoffs::item_mp_cost_; mov edx, [esi + movePoints]; sub edx, eax; // ap - cost = free AP's jle moveAway; // <= 0 - lea edx, [edx + ebx - 1]; + lea edx, [edx + ecx - 1]; cmp edx, 5; // minimum threshold distance jge skipMove; // distance >= 5? // check combat rating @@ -421,6 +549,15 @@ friendly: //////////////////////////////////////////////////////////////////////////////// +static void __declspec(naked) ai_try_attack_hack_check_safe_weapon() { + __asm { + mov ebx, [esp + 0x364 - 0x38 + 4]; // hit mode + retn; + } +} + +//////////////////////////////////////////////////////////////////////////////// + static void __fastcall CombatAttackHook(fo::GameObject* source, fo::GameObject* target) { sources[target] = source; // who attacked the 'target' from the last time targets[source] = target; // who was attacked by the 'source' from the last time @@ -440,42 +577,53 @@ static void __declspec(naked) combat_attack_hook() { } } +static void AICombatClear() { + targets.clear(); + sources.clear(); +} + void AI::init() { HookCalls(combat_attack_hook, { 0x426A95, // combat_attack_this_ 0x42A796 // ai_attack_ }); + LoadGameHook::OnCombatStart() += AICombatClear; + LoadGameHook::OnCombatEnd() += AICombatClear; - RetryCombatMinAP = GetConfigInt("Misc", "NPCsTryToSpendExtraAP", 0); + RetryCombatMinAP = IniReader::GetConfigInt("Misc", "NPCsTryToSpendExtraAP", 0); if (RetryCombatMinAP > 0) { dlog("Applying retry combat patch.", DL_INIT); HookCall(0x422B94, RetryCombatHook); // combat_turn_ dlogr(" Done", DL_INIT); } + /////////////////////// Combat behavior AI fixes /////////////////////// #ifndef NDEBUG - if (iniGetInt("Debugging", "AIBugFixes", 1, ::sfall::ddrawIni) == 0) return; + if (IniReader::GetIntDefaultConfig("Debugging", "AIFixes", 1) == 0) return; #endif - // Fix for NPCs not fully reloading a weapon if it has more ammo capacity than a box of ammo + // Fix for NPCs not fully reloading a weapon if it has an ammo capacity more than a box of ammo HookCalls(item_w_reload_hook, { 0x42AF15, // cai_attempt_w_reload_ 0x42A970, 0x42AA56, // ai_try_attack_ }); + // Fix for the incorrect check and AP cost when AI reloads a weapon + HookCall(0x42A955, ai_try_attack_hook_cost_reload); + MakeCall(0x42A9DE, ai_try_attack_hook_cost1); + MakeCall(0x42AABC, ai_try_attack_hook_cost2, 4); + // Adds a check for the weapon range and the AP cost when AI is choosing weapon attack modes HookCall(0x429F6D, ai_pick_hit_mode_hook); - /////////////////////// Combat AI behavior fixes /////////////////////// + // Fix AI weapon switching when not having enough AP to make an attack + // AI will try to change attack mode before deciding to switch weapon + HookCall(0x42AB57, ai_try_attack_hook_switch_fix); // Fix to reduce friendly fire in burst attacks // Adds a check/roll for friendly critters in the line of fire when AI uses burst attacks HookCall(0x421666, combat_safety_invalidate_weapon_func_hook_check); - // Fix AI weapon switching when not having enough action points - // AI will try to change attack mode before deciding to switch weapon - HookCall(0x42AB57, ai_try_attack_hook_switch_fix); - // Fix for duplicate critters being added to the list of potential targets for AI MakeCall(0x428E75, ai_find_attackers_hack_target2, 2); MakeCall(0x428EB5, ai_find_attackers_hack_target3); @@ -483,7 +631,7 @@ void AI::init() { // Tweak for finding new targets for party members // Save the current target in the "target1" variable and find other potential targets - MakeCall(0x429074, ai_danger_source_hack_pm_newfind); + MakeCall(0x429074, ai_danger_source_hack_pm_newFind); SafeWrite16(0x429074 + 5, 0x47EB); // jmp 0x4290C2 // Fix to allow fleeing NPC to use drugs @@ -491,11 +639,17 @@ void AI::init() { // Fix for AI not checking minimum hp properly for using stimpaks (prevents premature fleeing) HookCall(0x428579, ai_check_drugs_hook); + // Fix to prevent the use of healing drugs when not necessary + HookCall(0x4287D7, ai_check_drugs_hook_healing); + SafeWrite8(0x4285A8, 2); // set noInvenItem = 2 + SafeWrite8(0x4287A0, 0x8C); // jnz > jl (noInvenItem < 1) + // Fix for NPC stuck in fleeing mode when the hit chance of a target was too low HookCall(0x42B1E3, combat_ai_hook_FleeFix); HookCalls(ai_try_attack_hook_FleeFix, {0x42ABA8, 0x42ACE5}); - // Disable fleeing when NPC cannot move closer to target - BlockCall(0x42ADF6); // ai_try_attack_ + + // Restore combat flags after fleeing when NPC cannot move closer to target + HookCall(0x42ADF6, ai_try_attack_hook_runFix); // Fix AI target selection for combat_check_bad_shot_ function returning a no_ammo result HookCalls(ai_danger_source_hook, {0x42903A, 0x42918A}); @@ -510,6 +664,9 @@ void AI::init() { // also patch combat_safety_invalidate_weapon_func_ for returning out_range argument in a negative value SafeWrite8(0x421628, 0xD0); // sub edx, eax > sub eax, edx SafeWrite16(0x42162A, 0xFF40); // lea eax, [edx+1] > lea eax, [eax-1] + + // Check the safety of weapons based on the selected attack mode instead of always the primary weapon hit mode + MakeCall(0x42A8D9, ai_try_attack_hack_check_safe_weapon); } fo::GameObject* __stdcall AI::AIGetLastAttacker(fo::GameObject* target) { @@ -522,14 +679,4 @@ fo::GameObject* __stdcall AI::AIGetLastTarget(fo::GameObject* source) { return (itr != targets.end()) ? itr->second : 0; } -void __stdcall AI::AICombatStart() { - targets.clear(); - sources.clear(); -} - -void __stdcall AI::AICombatEnd() { - targets.clear(); - sources.clear(); -} - } diff --git a/sfall/Modules/AI.h b/sfall/Modules/AI.h index 6fe4f0f5..6dae5c5e 100644 --- a/sfall/Modules/AI.h +++ b/sfall/Modules/AI.h @@ -33,9 +33,7 @@ public: static fo::GameObject* CheckShootAndFriendlyInLineOfFire(fo::GameObject* object, long targetTile, long team); static fo::GameObject* CheckFriendlyFire(fo::GameObject* target, fo::GameObject* attacker); - // TODO: use subscription instead - static void __stdcall AICombatStart(); - static void __stdcall AICombatEnd(); + static bool AttackInRange(fo::GameObject* source, fo::GameObject* weapon, long distance); static fo::GameObject* __stdcall AIGetLastAttacker(fo::GameObject* target); static fo::GameObject* __stdcall AIGetLastTarget(fo::GameObject* source); diff --git a/sfall/Modules/Animations.cpp b/sfall/Modules/Animations.cpp index 1921af8b..8cf47119 100644 --- a/sfall/Modules/Animations.cpp +++ b/sfall/Modules/Animations.cpp @@ -25,17 +25,29 @@ namespace sfall { -static constexpr int animRecordSize = sizeof(fo::AnimationSet); -static constexpr int sadSize = 3240; +enum AnimFlags { + e_Priority = 0x001, + e_InCombat = 0x002, + e_Reserved = 0x004, + e_InUse = 0x008, + e_Suspend = 0x010, // animation not start running in register_end + e_Clear = 0x020, + e_EndAnim = 0x040, + e_DontStand = 0x080, + e_Append = 0x100, // sfall flag +}; static int animationLimit = 32; +static int lockLimit; //pointers to new animation struct arrays -static std::vector new_anim_set; -static std::vector new_sad; +static std::vector sf_anim_set; +static std::vector sf_sad; -static DWORD animSetAddr = FO_VAR_anim_set; -static DWORD sadAddr = FO_VAR_sad; +static std::vector lockAnimSet; + +static fo::AnimationSet* animSet = (fo::AnimationSet*)FO_VAR_anim_set; +static fo::AnimationSad* animSad = (fo::AnimationSad*)FO_VAR_sad; static const DWORD animPCMove[] = { 0x416E11, 0x416F64, 0x417143, 0x41725C, 0x4179CC, @@ -49,146 +61,382 @@ static const DWORD animMaxSizeCheck[] = { 0x413AA9, 0x413CB7, 0x413DC2, 0x417F3A, }; -static const DWORD fake_anim_set_C[] = { - 0x413AA4, 0x413DBC, -}; +static struct AnimSetHack { + const DWORD anim_set_0[45] = { // curr_anim + 0x413B96, 0x413C5A, 0x413CF0, 0x413DE1, 0x413E66, 0x413EF3, 0x413FA2, + 0x414161, 0x4142D3, 0x41449A, 0x41460B, 0x4146FF, 0x414826, 0x41491A, + 0x4149F8, 0x414AD0, 0x414BA4, 0x414C8C, 0x414CF0, 0x414D60, 0x414DD0, + 0x414E48, 0x414EDA, 0x414F5E, 0x414FEE, 0x41505C, 0x4150D0, 0x415158, + 0x4151B8, 0x415286, 0x41535C, 0x4153D0, 0x41544A, 0x4154EC, 0x4155EA, + 0x4156C0, 0x4156D5, 0x4156F2, 0x41572F, 0x41573E, 0x415B1B, 0x415B56, + 0x415BB6, 0x415C7C, 0x415CA3, /*0x415DE4, - conflict with 0x415DE2*/ + }; -static const DWORD anim_set_0[] = { - 0x413B96, 0x413C5A, 0x413CF0, 0x413DE1, 0x413E66, 0x413EF3, 0x413FA2, - 0x414161, 0x4142D3, 0x41449A, 0x41460B, 0x4146FF, 0x414826, 0x41491A, - 0x4149F8, 0x414AD0, 0x414BA4, 0x414C8C, 0x414CF0, 0x414D60, 0x414DD0, - 0x414E48, 0x414EDA, 0x414F5E, 0x414FEE, 0x41505C, 0x4150D0, 0x415158, - 0x4151B8, 0x415286, 0x41535C, 0x4153D0, 0x41544A, 0x4154EC, 0x4155EA, - 0x4156C0, 0x4156D5, 0x4156F2, 0x41572F, 0x41573E, 0x415B1B, 0x415B56, - 0x415BB6, 0x415C7C, 0x415CA3, /*0x415DE4, - conflct with 0x415DE2*/ -}; + const DWORD anim_set_4[9] = { // counter + 0x413D07, 0x415700, 0x415B6B, 0x415B78, 0x415C2D, 0x415D38, 0x415D56, + 0x415D63, 0x415DCF, + }; -static const DWORD anim_set_4[] = { - 0x413D07, 0x415700, 0x415B6B, 0x415B78, 0x415C2D, 0x415D38, 0x415D56, - 0x415D63, 0x415DCF, -}; + const DWORD anim_set_8[14] = { // anim_counter + 0x413C6A, 0x413CA3, 0x413CF6, 0x413E76, 0x413EA4, 0x413F03, 0x413F20, + 0x413F3A, 0x4156EC, 0x415B72, 0x415C18, 0x415C58, 0x415C6D, 0x415DBE, + }; -static const DWORD anim_set_8[] = { - 0x413C6A, 0x413CA3, 0x413CF6, 0x413E76, 0x413EA4, 0x413F03, 0x413F20, - 0x413F3A, 0x4156EC, 0x415B72, 0x415C18, 0x415C58, 0x415C6D, 0x415DBE, -}; + const DWORD anim_set_C[25] = { // flags + 0x413B2A, 0x413B33, 0x413B43, 0x413B54, 0x413B66, 0x413BA2, 0x413BAB, + 0x413BC0, 0x413BCD, 0x413C3C, 0x413C87, 0x413D01, 0x413D10, 0x413D36, + 0x413D53, 0x413DAD, 0x413E93, 0x4155DF, 0x415AE2, 0x415D9A, 0x415DDE, + 0x415E06, 0x415E12, 0x417F25, 0x417F30, + }; -static const DWORD anim_set_C[] = { - 0x413B2A, 0x413B33, 0x413B43, 0x413B54, 0x413B66, 0x413BA2, 0x413BAB, - 0x413BC0, 0x413BCD, 0x413C3C, 0x413C87, 0x413D01, 0x413D10, 0x413D36, - 0x413D53, 0x413DAD, 0x413E93, 0x4155DF, 0x415AE2, 0x415D9A, 0x415DDE, - 0x415E06, 0x415E12, 0x417F25, 0x417F30, -}; + const DWORD anim_set_C_shift[2] = { // flags + 0x413AA4, 0x413DBC, + }; -static const DWORD anim_set_10[] = { - 0x413C7E, 0x413E8A, 0x413F17, 0x415C24, 0x415D16, 0x415D44, -}; + const DWORD anim_set_10[5] = { // anim_0.animType + 0x413C7E, 0x413F17, 0x415C24, 0x415D16, 0x415D44, + /*0x413E8A, - conflict with 0x413E88*/ + }; -static const DWORD anim_set_14[] = { - 0x413C76, 0x413E82, 0x413F0F, 0x415C3E, 0x415D0E, 0x415D4D, -}; + const DWORD anim_set_14[6] = { // anim_0.source + 0x413C76, 0x413E82, 0x413F0F, 0x415C3E, 0x415D0E, 0x415D4D, + }; -static const DWORD anim_set_28[] = { - 0x413D1C, 0x41570D, 0x415720, -}; + const DWORD anim_set_28[3] = { // anim_0.delay + 0x413D1C, 0x41570D, 0x415720, + }; +} animSetAddrs; -static const DWORD sad_0[] = { - 0x416E4A, 0x416E56, 0x416EBD, 0x416F98, 0x416FAC, 0x4170C5, 0x417167, - 0x4171F6, 0x4172A5, 0x417583, 0x417856, 0x4178AE, 0x417937, 0x4179FA, - 0x417A86, 0x417BB7, 0x417CD1, 0x417D54, 0x417E14, 0x417E3C, 0x417FB1, - 0x417FB7, 0x417FCC, -}; +static struct SadHack { + const DWORD sad_0[23] = { + 0x416E4A, 0x416E56, 0x416EBD, 0x416F98, 0x416FAC, 0x4170C5, 0x417167, + 0x4171F6, 0x4172A5, 0x417583, 0x417856, 0x4178AE, 0x417937, 0x4179FA, + 0x417A86, 0x417BB7, 0x417CD1, 0x417D54, 0x417E14, 0x417E3C, 0x417FB1, + 0x417FB7, 0x417FCC, + }; -static const DWORD sad_4[] = { - 0x415D7D, 0x416E40, 0x416F8F, 0x41738B, 0x417786, 0x4177E7, 0x417983, - 0x417AC1, 0x417B70, 0x417C0D, -}; + const DWORD sad_4[10] = { + 0x415D7D, 0x416E40, 0x416F8F, 0x41738B, 0x417786, 0x4177E7, 0x417983, + 0x417AC1, 0x417B70, 0x417C0D, + }; -static const DWORD sad_8[] = { - 0x416EB8, 0x416ECB, 0x416FA6, 0x416FFF, 0x41702F, 0x4177F9, 0x417AC7, - 0x417ADB, 0x417C63, 0x417CA3, -}; + const DWORD sad_8[10] = { + 0x416EB8, 0x416ECB, 0x416FA6, 0x416FFF, 0x41702F, 0x4177F9, 0x417AC7, + 0x417ADB, 0x417C63, 0x417CA3, + }; -static const DWORD sad_C[] = { - 0x416EF8, 0x4173EE, -}; + const DWORD sad_C[2] = { + 0x416EF8, 0x4173EE, + }; -static const DWORD sad_10[] = { - 0x416EC3, 0x417035, 0x417AD5, 0x417B7B, 0x417B9A, -}; + const DWORD sad_10[5] = { + 0x416EC3, 0x417035, 0x417AD5, 0x417B7B, 0x417B9A, + }; -static const DWORD sad_14[] = { - 0x416ED8, 0x417066, 0x417B08, 0x417B88, -}; + const DWORD sad_14[4] = { + 0x416ED8, 0x417066, 0x417B08, 0x417B88, + }; -static const DWORD sad_18[] = { - 0x415BF7, 0x416EEC, 0x41706C, 0x4177AB, 0x4179A4, 0x417ACF, 0x417B94, - 0x417C30, 0x417D73, 0x417E78, -}; + const DWORD sad_18[10] = { + 0x415BF7, 0x416EEC, 0x41706C, 0x4177AB, 0x4179A4, 0x417ACF, 0x417B94, + 0x417C30, 0x417D73, 0x417E78, + }; -static const DWORD sad_1C[] = { - 0x416869, 0x416871, 0x4168B0, 0x4168FC, 0x416942, 0x41694A, 0x416D6D, - 0x416D74, 0x416DB2, 0x416DE4, 0x416DEC, 0x416F08, 0x416F36, 0x4170FC, - 0x41759D, 0x4176EE, 0x4178A7, 0x41792F, 0x417B1A, 0x417BAE, -}; + const DWORD sad_1C[20] = { + 0x416869, 0x416871, 0x4168B0, 0x4168FC, 0x416942, 0x41694A, 0x416D6D, + 0x416D74, 0x416DB2, 0x416DE4, 0x416DEC, 0x416F08, 0x416F36, 0x4170FC, + 0x41759D, 0x4176EE, 0x4178A7, 0x41792F, 0x417B1A, 0x417BAE, + }; -static const DWORD sad_20[] = { - 0x415BFF, 0x415D85, 0x41687B, 0x416D7E, 0x416E7A, 0x416F12, 0x417023, - 0x417106, 0x417385, 0x417434, 0x4174BA, 0x4175A7, 0x41760D, 0x4176E7, - 0x4176F4, 0x41771E, 0x41779A, 0x4177E1, 0x417806, 0x4178A1, 0x4178B4, - 0x41790B, 0x417929, 0x417961, 0x417993, 0x417B0E, 0x417B60, 0x417BF8, - 0x417C15, 0x417C21, 0x417C4B, 0x417D79, 0x417E31, 0x417F58, 0x417F81, - 0x417FC6, -}; + const DWORD sad_20[36] = { + 0x415BFF, 0x415D85, 0x41687B, 0x416D7E, 0x416E7A, 0x416F12, 0x417023, + 0x417106, 0x417385, 0x417434, 0x4174BA, 0x4175A7, 0x41760D, 0x4176E7, + 0x4176F4, 0x41771E, 0x41779A, 0x4177E1, 0x417806, 0x4178A1, 0x4178B4, + 0x41790B, 0x417929, 0x417961, 0x417993, 0x417B0E, 0x417B60, 0x417BF8, + 0x417C15, 0x417C21, 0x417C4B, 0x417D79, 0x417E31, 0x417F58, 0x417F81, + 0x417FC6, + }; -static const DWORD sad_24[] = { - 0x4168D7, 0x416914, 0x41691F, 0x416DD9, 0x416EE1, 0x41758F, -}; + const DWORD sad_24[6] = { + 0x4168D7, 0x416914, 0x41691F, 0x416DD9, 0x416EE1, 0x41758F, + }; -static const DWORD sad_27[] = { - 0x4168C5, 0x416DBD, -}; + const DWORD sad_27[2] = { + 0x4168C5, 0x416DBD, + }; -static const DWORD sad_28[] = { - 0x4173CE, 0x4174C1, 0x4175F1, 0x417730, -}; + const DWORD sad_28[4] = { + 0x4173CE, 0x4174C1, 0x4175F1, 0x417730, + }; +} sadAddrs; -static DWORD __fastcall AnimCombatFix(fo::GameObject* src, BYTE combatFlag) { - DWORD animAddr = animSetAddr; +//////////////////////////////////////////////////////////////////////////////// - if (animationLimit > 32) { - animAddr += animRecordSize; // include a dummy +static long appendSlot = -2; + +/* + When the check_registry_ function finds an object for which a new animation + is being registered in the list of a sequence of already registered + animations, the engine stops registering animations for this object. + + This implementation will copy all currently registered animations from the + current slot to another slot with already registered animations, appending + them to the end of the sequence. + + This allows the engine to continue to animate the object sequentially. +*/ +static long __fastcall CopyRegistry(long checkSlot) { + long currRegSlot = fo::var::curr_anim_set; + if (!(animSet[currRegSlot].flags & AnimFlags::e_Reserved)) return 0; + + if (currRegSlot == checkSlot) { // this will be bug! + #ifndef NDEBUG + BREAKPOINT; + #endif + return 0; + } + long currRegAnims = fo::var::curr_anim_counter; + long lastAnim = animSet[checkSlot].totalAnimCount; + + devlog_f("\n\nCopyRegistry: animSet[%d] anims:%d >> animSet[%d] anims:%d", 0, currRegSlot, currRegAnims, checkSlot, lastAnim); + devlog_f("\n checkSlot: currAnim:%d, counter:%d", 0, animSet[checkSlot].currentAnim, animSet[checkSlot].counter); + + for (long i = animSet[checkSlot].counter; i < lastAnim; i++) { + long animType = animSet[checkSlot].animations[i].animType; + devlog_f("\n anim[%d]: animType:%d, animCode:%d", 0, i, animType, animSet[checkSlot].animations[i].animCode); + if (animType < 4) return 0; // don't add to "move to" types of animations } - if (combatFlag & 2) { // combat flag is set - __asm call fo::funcoffs::combat_anim_finished_; + long totalRegAnims = (animSet[checkSlot].flags & AnimFlags::e_Append) ? currRegAnims : lastAnim + currRegAnims; + if (totalRegAnims >= 55) return 0; // not enough slots for animations + + // copy the animations of the registered slot to the slot with the existing animations + for (long i = 0; i < currRegAnims; i++) { + devlog_f("\n copy slot: animSet[%d].anim[%d] >> animSet[%d].anim[%d]", 0, currRegSlot, i, checkSlot, lastAnim); + animSet[checkSlot].animations[lastAnim++] = animSet[currRegSlot].animations[i]; } - return animAddr; + animSet[checkSlot].flags |= animSet[currRegSlot].flags | AnimFlags::e_Append | AnimFlags::e_Suspend; // set flags + animSet[currRegSlot].flags = 0; + + fo::var::curr_anim_counter = totalRegAnims; // set the current number of registered animations in the slot + fo::var::curr_anim_set = checkSlot; // replace the currently registered slot with a slot with existing registered animations + + appendSlot = checkSlot; + return lastAnim; } -static void __declspec(naked) anim_set_end_hack() { +static void __declspec(naked) check_registry_hack() { __asm { + mov eax, animSet; + cmp [eax][edx][0x10], 0x0B; // animSet[].anim[].animType == Must_Call + je skip; + //cmp [eax][edx][0x10], 0x0C; // animSet[].anim[].animType == Call3 + //je skip; + test [eax][esi][0x0C], e_EndAnim; // anim_set[].flags + jnz skip; push ecx; - call AnimCombatFix; - mov [eax][esi], ebx; + push edx; + call CopyRegistry; + test eax, eax; + cmovnz ebx, eax; // set ebx to the current count of animations to check the next anim_set slot + pop edx; pop ecx; - xor dl, dl; // for goto 0x415DF2; + // (re)set ZF + setz al; + test al, al; +skip: retn; } } -static DWORD __fastcall CheckSetSad(BYTE openFlag, DWORD valueMul) { - bool result = false; - int offset = (sadSize * valueMul) + 32; - - if (*(DWORD*)(sadAddr + offset) == -1000) { - result = true; - } else if (!InCombat() && !(openFlag & 1)) { - *(DWORD*)(sadAddr + offset) = -1000; - result = true; +// sets the counter to the index of the anim_# slot with the added animation +static long __fastcall anim_cleanup_sub(long currAnims) { + //long currAnims = fo::var::curr_anim_counter; + fo::AnimationSet* set = &animSet[fo::var::curr_anim_set]; + if (set->flags & AnimFlags::e_Append) { + set->flags ^= AnimFlags::e_Append; + if (set->currentAnim == -1000 || set->totalAnimCount >= currAnims) return -1; + return set->totalAnimCount; } + // default + return (currAnims <= 0) ? -1 : 0; +} - return result; +static void __declspec(naked) anim_cleanup_hack() { + __asm { + call anim_cleanup_sub; + mov ecx, eax; // ecx - anims slot index + mov ebx, eax; // ebx - anims counter + test eax, eax; + retn; + } +} + +static long __fastcall LockAnimSlot(long slot) { + if (animSet[slot].counter != animSet[slot].totalAnimCount) { + lockAnimSet[slot] = 8; + } + return slot; +} + +static long __fastcall UnlockAnimSlot() { + long lockCount = 0; + for (auto it = lockAnimSet.begin(); it != lockAnimSet.end(); ++it) { + if (*it > 0) { + (*it)--; + lockCount++; + } + } + if (lockCount >= lockLimit) fo::func::debug_printf("\n[SFALL] Warning: The number of animated slots in the lock is too large, locked %d of %d", lockCount, animationLimit); + return 0; +} + +static BYTE __fastcall CheckLockAnimSlot(long, long slot) { + return lockAnimSet[slot]; +} + +static void __fastcall CheckAppendReg(long, long totalAnims) { + long slot = appendSlot; + appendSlot = -2; + if (slot != fo::var::curr_anim_set) return; + + //long totalAnims = fo::var::curr_anim_counter; + fo::AnimationSet* set = &animSet[slot]; + + #ifndef NDEBUG + devlog_f("\nregister_end: anim_set: %d, total_anim: %d", 0, slot, totalAnims); + for (long i = 0; i < totalAnims; i++) { + devlog_f("\n anim[%d]: animType:%d, animCode:%d, source:%x (%s), callFunc:%x, callFunc3:%x", 0, i, + set->animations[i].animType, set->animations[i].animCode, + set->animations[i].source, fo::func::critter_name(set->animations[i].source), + set->animations[i].callFunc, set->animations[i].callFunc3 + ); + } + #endif + + for (long i = set->totalAnimCount; i < totalAnims; i++) { + if (set->animations[i].animType < 4) { + for (long i = set->totalAnimCount; i < totalAnims; i++) { + // cleanup + long frm = set->animations[i].frmPtr; + if (frm) fo::func::art_ptr_unlock(frm); + // anim Must_Call + if (set->animations[i].animType == 11 && (DWORD)set->animations[i].callFunc == (DWORD)fo::funcoffs::gsnd_anim_sound_) { + long sfx = (long)set->animations[i].target; + __asm { + mov eax, sfx; + call fo::funcoffs::gsound_delete_sfx_; + } + } + } + return; // exit, do not set the total number of animations in the slot (the value remains the same) + } + } + set->totalAnimCount = totalAnims; +} + +static void __declspec(naked) register_end_hack_begin() { + __asm { + mov edx, ds:[FO_VAR_curr_anim_counter]; + mov esi, animSet; + and [esi][eax][0xC], ~e_InUse; // animSet[].flags (unset inUse flag) + test word ptr [esi][eax][0xC], e_Append; // animSet[].flags + jnz isAppend; // slot with added animation + retn; +isAppend: + mov esi, eax; // keep offset to anim_set slot + call CheckAppendReg; + xor ecx, ecx; + add esp, 4; + mov edx, 0x413D14; + mov eax, esi; + jmp edx; + } +} + +static void __declspec(naked) register_end_hack_end() { + __asm { + mov eax, animSet; + test word ptr [eax][esi][0xC], e_Append; // slot with added animation? + jz skip; + and word ptr [eax][esi][0xC], ~(e_Append | e_Suspend); // animSet[].flags (unset flags) +skip: + call UnlockAnimSlot; + pop esi; + pop edx; + pop ecx; + retn; + } +} + +static void __declspec(naked) register_clear_hook() { + __asm { + mov ecx, eax; + call LockAnimSlot; + jmp fo::funcoffs::anim_set_end_; + } +} + +static void __declspec(naked) anim_free_slot_hack() { + static const DWORD anim_free_slot_next = 0x413BD5; + using namespace fo; + __asm { + pushadc; + call CheckLockAnimSlot; + test al, al; + popadc; + jnz isLock; + test word ptr [esp + 0x10 - 0x10 + 4], RB_UNKNOWN; // command & RB_100_ (register_ping_) + retn; +isLock: + add esp, 4; + jmp anim_free_slot_next; + } +} + +static void ClearAllLock() { + std::fill(lockAnimSet.begin(), lockAnimSet.end(), 0); +} + +static void __declspec(naked) anim_stop_hack() { + __asm { + call ClearAllLock; + mov edx, 1; + retn; + } +} + +//////////////////////////////////////////////////////////////////////////////// +#ifndef NDEBUG +static void __fastcall ClearDataAnimations(long slot) { + std::memset(animSet[slot].animations, 0, sizeof(fo::AnimationSet) - 16); +} +#endif + +static void __declspec(naked) anim_set_end_hack() { + __asm { + test dl, e_InCombat; // is combat flag set? + jz skip; + call fo::funcoffs::combat_anim_finished_; +skip: + mov eax, animSet; + mov [eax][esi], ebx; // anim_set[].curr_anim = -1000 + #ifndef NDEBUG + mov ecx, [esp + 0x2C - 0x1C + 4]; // current slot + call ClearDataAnimations; + #endif + retn; + } +} + +static bool __fastcall CheckSetSad(BYTE openFlag, DWORD slot) { + if (animSad[slot].animStep == -1000) { + return true; + } else if (!InCombat() && !(openFlag & 1)) { + animSad[slot].animStep = -1000; + return true; + } + return false; } static void __declspec(naked) object_move_hack() { @@ -196,9 +444,9 @@ static void __declspec(naked) object_move_hack() { static const DWORD object_move_back1 = 0x417616; __asm { mov ecx, ds:[ecx + 0x3C]; // openFlag - mov edx, [esp + 0x4C - 0x20]; // valueMul + mov edx, [esp + 0x4C - 0x20]; // slot (current) call CheckSetSad; - test eax, eax; + test al, al; jz end; jmp object_move_back0; // fixed jump end: @@ -207,6 +455,7 @@ end: } static void __declspec(naked) action_climb_ladder_hook() { + using namespace fo; __asm { cmp word ptr [edi + 0x40], 0xFFFF; // DestTile je skip; @@ -218,7 +467,7 @@ static void __declspec(naked) action_climb_ladder_hook() { pop edx; jne skip; reset: - and al, ~0x4; // reset RB_DONTSTAND flag + and al, ~RB_DONTSTAND; // unset flag skip: jmp fo::funcoffs::register_begin_; } @@ -242,122 +491,100 @@ skip: } void ApplyAnimationsAtOncePatches(signed char aniMax) { - if (aniMax <= 32) return; - //allocate memory to store larger animation struct arrays - new_anim_set.resize(aniMax + 1); - new_sad.resize(sadSize * (aniMax + 1)); + sf_anim_set.resize(aniMax + 1); // include a dummy + sf_sad.resize(aniMax + 1); // -8? - animSetAddr = reinterpret_cast(new_anim_set.data()); - sadAddr = reinterpret_cast(new_sad.data()); + //replace addresses for arrays + animSet = &sf_anim_set[1]; // the zero slot for the game remains unused + animSad = sf_sad.data(); - //set general animation limit check (old 20) aniMax-12 -- +12 reserved for PC movement(4) + other critical animations(8)? + //set general animation limit check (old 20) aniMax-12 (4 reserved for PC movement + 8 other critical animations?) SafeWriteBatch(aniMax - 12, { 0x413C07 }); - //PC movement animation limit checks (old 24) aniMax-8 -- +8 reserved for other critical animations?. + //PC movement animation limit checks (old 24) aniMax-8 (8 reserved for other critical animations?) SafeWriteBatch(aniMax - 8, animPCMove); //Max animation limit checks (old 32) aniMax SafeWriteBatch(aniMax, animMaxCheck); //Max animations checks - animation struct size * max num of animations (old 2656*32=84992) - SafeWriteBatch(animRecordSize * aniMax, animMaxSizeCheck); + SafeWriteBatch(sizeof(fo::AnimationSet) * aniMax, animMaxSizeCheck); //divert old animation structure list pointers to newly allocated memory - //struct array 1/////////////////// + fo::AnimationSet* animSetAddr = &sf_anim_set[0]; //old addr 0x54C1B4 - SafeWriteBatch(animSetAddr, { 0x413A9E }); - + SafeWriteBatch((DWORD)&animSetAddr->currentAnim, { 0x413A9E }); // anim_reset_ //old addr 0x54C1C0 - SafeWriteBatch(12 + animSetAddr, fake_anim_set_C); + SafeWriteBatch((DWORD)&animSetAddr->flags, animSetAddrs.anim_set_C_shift); - //old addr 0x54CC14 - SafeWriteBatch(animRecordSize + animSetAddr, anim_set_0); + SafeWriteBatch((DWORD)&animSet->currentAnim, animSetAddrs.anim_set_0); + SafeWriteBatch((DWORD)&animSet->counter, animSetAddrs.anim_set_4); + SafeWriteBatch((DWORD)&animSet->totalAnimCount, animSetAddrs.anim_set_8); + SafeWriteBatch((DWORD)&animSet->flags, animSetAddrs.anim_set_C); + SafeWriteBatch((DWORD)&animSet->animations[0].animType, animSetAddrs.anim_set_10); + SafeWriteBatch((DWORD)&animSet->animations[0].source, animSetAddrs.anim_set_14); + SafeWriteBatch((DWORD)&animSet->animations[0].animCode, { 0x413F29 }); + SafeWriteBatch((DWORD)&animSet->animations[0].delay, animSetAddrs.anim_set_28); + SafeWriteBatch((DWORD)&animSet->animations[0].flags, { 0x415C35 }); - //old addr 0x54CC18 - SafeWriteBatch(animRecordSize + 4 + animSetAddr, anim_set_4); - - //old addr 0x54CC1C - SafeWriteBatch(animRecordSize + 8 + animSetAddr, anim_set_8); - - //old addr 0x54CC20 - SafeWriteBatch(animRecordSize + 12 + animSetAddr, anim_set_C); - - //old addr 0x54CC24 - SafeWriteBatch(animRecordSize + 16 + animSetAddr, anim_set_10); - - //old addr 0x54CC28 - SafeWriteBatch(animRecordSize + 20 + animSetAddr, anim_set_14); - - //old addr 0x54CC38 - SafeWriteBatch(animRecordSize + 36 + animSetAddr, { 0x413F29 }); - - //old addr 0x54CC3C - SafeWriteBatch(animRecordSize + 40 + animSetAddr, anim_set_28); - - //old addr 0x54CC48 - SafeWriteBatch(animRecordSize + 52 + animSetAddr, { 0x415C35 }); - - //struct array 2/////////////////// - - //old addr 0x530014 - SafeWriteBatch(sadAddr, sad_0); - - //old addr 0x530018 - SafeWriteBatch(4 + sadAddr, sad_4); - - //old addr 0x53001C - SafeWriteBatch(8 + sadAddr, sad_8); - - //old addr 0x530020 - SafeWriteBatch(12 + sadAddr, sad_C); - - //old addr 0x530024 - SafeWriteBatch(16 + sadAddr, sad_10); - - //old addr 0x530028 - SafeWriteBatch(20 + sadAddr, sad_14); - - //old addr 0x53002C - SafeWriteBatch(24 + sadAddr, sad_18); - - //old addr 0x530030 - SafeWriteBatch(28 + sadAddr, sad_1C); - - //old addr 0x530034 - SafeWriteBatch(32 + sadAddr, sad_20); - - //old addr 0x530038 - SafeWriteBatch(36 + sadAddr, sad_24); - - //old addr 0x53003A - SafeWriteBatch(38 + sadAddr, { 0x416903 }); - - //old addr 0x53003B - SafeWriteBatch(39 + sadAddr, sad_27); - - //old addr 0x53003C - SafeWriteBatch(40 + sadAddr, sad_28); + SafeWriteBatch((DWORD)&animSad->flags, sadAddrs.sad_0); + SafeWriteBatch((DWORD)&animSad->source, sadAddrs.sad_4); + SafeWriteBatch((DWORD)&animSad->fid, sadAddrs.sad_8); + SafeWriteBatch((DWORD)&animSad->animCode, sadAddrs.sad_C); + SafeWriteBatch((DWORD)&animSad->ticks, sadAddrs.sad_10); + SafeWriteBatch((DWORD)&animSad->tpf, sadAddrs.sad_14); + SafeWriteBatch((DWORD)&animSad->animSetSlot, sadAddrs.sad_18); + SafeWriteBatch((DWORD)&animSad->pathCount, sadAddrs.sad_1C); + SafeWriteBatch((DWORD)&animSad->animStep, sadAddrs.sad_20); + SafeWriteBatch((DWORD)&animSad->dstTile, sadAddrs.sad_24); + SafeWriteBatch((DWORD)&animSad->rotation1, { 0x416903 }); + SafeWriteBatch((DWORD)&animSad->rotation2, sadAddrs.sad_27); + SafeWriteBatch((DWORD)&animSad->pathData[0].tile, sadAddrs.sad_28); } void Animations::init() { - animationLimit = GetConfigInt("Misc", "AnimationsAtOnceLimit", 32); + animationLimit = IniReader::GetConfigInt("Misc", "AnimationsAtOnceLimit", 32); + if (animationLimit < 32) animationLimit = 32; if (animationLimit > 32) { - if (animationLimit > 127) { - animationLimit = 127; - } + if (animationLimit > 127) animationLimit = 127; dlog("Applying AnimationsAtOnceLimit patch.", DL_INIT); ApplyAnimationsAtOncePatches(animationLimit); dlogr(" Done", DL_INIT); } + + // Improved implementation of animation registration + MakeCall(0x413E88, check_registry_hack, 2); + MakeCall(0x413DCE, anim_cleanup_hack, 1); + SafeWrite16(0x413DD4, 0x4478); // js 0x413E1A + MakeCall(0x413CE8, register_end_hack_begin, 1); + MakeJump(0x413D64, register_end_hack_end); + SafeWrite16(0x413D0B, 0xC689); // and dl, not 8 > mov esi, eax (keep offset to anim_set slot) + SafeWrite8(0x413D0D, CodeType::Nop); + + // Implement a temporary lock on an animation slot after it is cleared by the register_clear_ function + // to prevent it from being used as a free slot when registering a nested animation + HookCall(0x413C97, register_clear_hook); + MakeCall(0x413BB7, anim_free_slot_hack); + MakeCall(0x4186CF, anim_stop_hack); + + lockAnimSet.resize(animationLimit); + lockLimit = animationLimit / 2; + + LoadGameHook::OnGameReset() += ClearAllLock; + // Fix for calling anim() functions in combat MakeCall(0x415DE2, anim_set_end_hack, 1); + SafeWrite8(0x415DEB, CodeType::JumpShort); // jz > jmp // Fix crash when the critter goes through a door with animation trigger MakeJump(0x41755E, object_move_hack); + // Allow playing the "magic hands" animation when using an item on an object + SafeWrite16(0x4120B8, 0x9090); // action_use_an_item_on_object_ + // Fix for the player stuck at "climbing" frame after ladder climbing animation HookCall(0x411E1F, action_climb_ladder_hook); diff --git a/sfall/Modules/BarBoxes.cpp b/sfall/Modules/BarBoxes.cpp index 7a8ccd2a..13fd4c66 100644 --- a/sfall/Modules/BarBoxes.cpp +++ b/sfall/Modules/BarBoxes.cpp @@ -262,7 +262,7 @@ static void __declspec(naked) refresh_box_bar_win_hack() { } void BarBoxes::init() { - initCount += GetConfigInt("Misc", "BoxBarCount", 5); + initCount += IniReader::GetConfigInt("Misc", "BoxBarCount", 5); if (initCount < 5) initCount = 5; // exclude the influence of negative values from the config if (initCount > 100) initCount = 100; @@ -276,7 +276,7 @@ void BarBoxes::init() { boxes[i].msg = 100 + i; } - auto boxBarColors = GetConfigString("Misc", "BoxBarColours", "", actualBoxCount + 1); + auto boxBarColors = IniReader::GetConfigString("Misc", "BoxBarColours", "", actualBoxCount + 1); for (size_t i = 0; i < boxBarColors.size(); i++) { if (boxBarColors[i] == '1') { boxes[i + 5].colour = 1; // red color @@ -303,7 +303,7 @@ void BarBoxes::init() { MakeCall(0x4615FA, refresh_box_bar_win_hack); SafeWriteBatch((DWORD)newBoxSlot, bboxSlotAddr); // _bboxslot - ifaceWidth = iniGetInt("IFACE", "IFACE_BAR_WIDTH", 640, ".\\f2_res.ini"); + ifaceWidth = IniReader::GetInt("IFACE", "IFACE_BAR_WIDTH", 640, ".\\f2_res.ini"); if (ifaceWidth < 640) ifaceWidth = 640; LoadGameHook::OnAfterGameInit() += SetMaxSlots; diff --git a/sfall/Modules/Books.cpp b/sfall/Modules/Books.cpp index 69c3a4ad..4ef6155d 100644 --- a/sfall/Modules/Books.cpp +++ b/sfall/Modules/Books.cpp @@ -86,15 +86,15 @@ static void LoadVanillaBooks() { } void Books::init() { - auto booksFile = GetConfigString("Misc", "BooksFile", "", MAX_PATH); + auto booksFile = IniReader::GetConfigString("Misc", "BooksFile", "", MAX_PATH); if (!booksFile.empty()) { dlog("Applying books patch...", DL_INIT); const char* iniBooks = booksFile.insert(0, ".\\").c_str(); - bool includeVanilla = (iniGetInt("main", "overrideVanilla", 0, iniBooks) == 0); + bool includeVanilla = (IniReader::GetInt("main", "overrideVanilla", 0, iniBooks) == 0); if (includeVanilla) BooksCount = 5; - int count = iniGetInt("main", "count", 0, iniBooks); + int count = IniReader::GetInt("main", "count", 0, iniBooks); int n = 0; if (count > 0) { @@ -106,9 +106,9 @@ void Books::init() { char section[4]; for (int i = 1; i <= count; i++) { _itoa_s(i, section, 10); - if (books[BooksCount].bookPid = iniGetInt(section, "PID", 0, iniBooks)) { - books[BooksCount].msgID = iniGetInt(section, "TextID", 0, iniBooks); - books[BooksCount].skill = iniGetInt(section, "Skill", 0, iniBooks); + if (books[BooksCount].bookPid = IniReader::GetInt(section, "PID", 0, iniBooks)) { + books[BooksCount].msgID = IniReader::GetInt(section, "TextID", 0, iniBooks); + books[BooksCount].skill = IniReader::GetInt(section, "Skill", 0, iniBooks); BooksCount++; n++; } diff --git a/sfall/Modules/BugFixes.cpp b/sfall/Modules/BugFixes.cpp index 7097a746..5d082ede 100644 --- a/sfall/Modules/BugFixes.cpp +++ b/sfall/Modules/BugFixes.cpp @@ -1,6 +1,11 @@ #include "..\main.h" #include "..\FalloutEngine\Fallout2.h" +#include "..\Translate.h" + #include "HookScripts\InventoryHs.h" + +#include "..\Game\objects.h" + #include "Drugs.h" #include "LoadGameHook.h" #include "ScriptExtender.h" @@ -10,6 +15,7 @@ namespace sfall { + using namespace fo; using namespace Fields; using namespace ObjectFlag; @@ -18,7 +24,7 @@ static DWORD critterBody = 0; static DWORD sizeOnBody = 0; static DWORD weightOnBody = 0; -static char tempBuffer[355]; +static char messageBuffer[355]; /* Saving a list of PIDs for saved drug effects @@ -1004,39 +1010,35 @@ runToObject: } } -//checks if an attacked object is a critter before attempting dodge animation +// checks if an attacked object is a critter before attempting dodge animation static void __declspec(naked) action_melee_hack() { __asm { - mov edx, 0x4113DC - mov ebx, [eax + artFid] // objStruct->FID - and ebx, 0x0F000000 - cmp ebx, OBJ_TYPE_CRITTER << 24 // check if object FID type flag is set to critter - jne end // if object not a critter leave jump condition flags - // set to skip dodge animation - test byte ptr [eax + damageFlags], DAM_KNOCKED_OUT or DAM_KNOCKED_DOWN // (original code) - jnz end - mov edx, 0x4113FE + mov eax, [ebp + ctdTarget]; + mov ebx, [eax + artFid]; // objStruct->FID + and ebx, 0x0F000000; + cmp ebx, OBJ_TYPE_CRITTER << 24; // check if object FID type flag is set to critter + jne end; // if object not a critter leave jump condition flags + test byte ptr [eax + damageFlags], DAM_KNOCKED_OUT or DAM_KNOCKED_DOWN; // (original code) end: - jmp edx + retn; // JNZ to skip dodge animation } } static void __declspec(naked) action_ranged_hack() { __asm { - mov edx, 0x411B6D - mov ebx, [eax + artFid] // objStruct->FID - and ebx, 0x0F000000 - cmp ebx, OBJ_TYPE_CRITTER << 24 // check if object FID type flag is set to critter - jne end // if object not a critter leave jump condition flags - // set to skip dodge animation - test byte ptr [eax + damageFlags], DAM_KNOCKED_OUT or DAM_KNOCKED_DOWN // (original code) - jnz end - mov edx, 0x411BD2 + mov eax, [eax + ctdTarget]; + mov ebx, [eax + artFid]; // objStruct->FID + and ebx, 0x0F000000; + cmp ebx, OBJ_TYPE_CRITTER << 24; // check if object FID type flag is set to critter + jne end; // if object not a critter leave jump condition flags + test byte ptr [eax + damageFlags], DAM_KNOCKED_OUT or DAM_KNOCKED_DOWN; // (original code) end: - jmp edx + retn; // JNZ to skip dodge animation } } +////////// "NPC turns into a container" bug and knockout/down issues /////////// + static void __declspec(naked) set_new_results_hack() { __asm { call fo::funcoffs::stat_level_; @@ -1050,6 +1052,51 @@ static void __declspec(naked) set_new_results_hack() { } } +static void __declspec(naked) op_critter_state_hack() { + __asm { + mov ebx, 2; + test eax, DAM_KNOCKOUT_WOKEN; + cmovnz esi, ebx; + and eax, (DAM_CRIP_LEG_LEFT or DAM_CRIP_LEG_RIGHT or DAM_CRIP_ARM_LEFT or DAM_CRIP_ARM_RIGHT or DAM_BLIND); + retn; + } +} + +// if the combat ends before the turn passes to the critter, the DAM_KNOCKOUT_WOKEN flag will remain set +// therefore the flag for the critter is removed before the combat_turn_ execution, as well as when the combat ends in combat_over_ +static void __declspec(naked) critter_wake_up_hack() { + using fo::InCombat; + __asm { + or byte ptr [eax], InCombat; // combat_data.combat_state + test dl, DAM_KNOCKED_OUT; // is critter knocked out? + jz skip; // No + or dword ptr [ebx + damageFlags], DAM_KNOCKOUT_WOKEN; // game is in combat, set the flag +skip: + xor eax, eax; + retn; + } +} + +// used when the player leaves the map and the time has been advanced in the map_exit_p_proc procedure +// in that case, the critter_wake_up_ function will not work properly and the critter will remain in the prone position +static void __fastcall sf_critter_wake_clear(fo::GameObject* critter) { + if (critter->IsCritter()) { + critter->critter.damageFlags &= ~(fo::DAM_KNOCKED_DOWN | fo::DAM_KNOCKED_OUT); + critter->artFid = fo::func::art_id(fo::ObjType::OBJ_TYPE_CRITTER, critter->artFid & 0xFFF, 0, (critter->artFid & 0xF000) >> 12, critter->rotation + 1); + //fo::func::obj_change_fid(critter, artID, 0); + } +} + +static void __declspec(naked) critter_wake_up_hook() { + __asm { + mov ecx, eax; + test ScriptExtender::OnMapLeave, 1; + jnz sf_critter_wake_clear; + jmp fo::funcoffs::dude_standup_; + } +} + +// called when leaving the map if the critter has a "knockout_event" event in the queue static void __declspec(naked) critter_wake_clear_hack() { __asm { jne end; // This is not a critter @@ -1069,8 +1116,10 @@ end: } } +// when loading the map static void __declspec(naked) obj_load_func_hack() { static const DWORD obj_load_func_Ret = 0x488F14; + using fo::InCombat; __asm { test word ptr [eax + flags], Temp; // engine code jz fix; @@ -1080,22 +1129,20 @@ fix: and edi, 0x0F000000; cmp edi, OBJ_TYPE_CRITTER << 24; jne skip; + test byte ptr [eax + combatState], InCombat; + jnz skip; // do nothing if the critter has the flag set test byte ptr [eax + damageFlags], DAM_DEAD; jnz skip; // is dead + and dword ptr [eax + damageFlags], ~(DAM_KNOCKOUT_WOKEN or DAM_LOSE_TURN); // clear DAM_LOSE_TURN for "NPC turns into a container" bug test byte ptr [eax + damageFlags], DAM_KNOCKED_OUT; - jnz clear; // Yes + jnz clear; // flag is set, so the "knockout_event" event is already in the queue (if there is no event, then there is a bug somewhere) test byte ptr [eax + damageFlags], DAM_KNOCKED_DOWN; jz clear; // No push eax; - xor ecx, ecx; - mov edx, eax; // object - mov ebx, ecx; // extramem null - mov eax, ecx; // time = 0 - inc ecx; // type = 1 - call fo::funcoffs::queue_add_; // run stand up anim + call fo::funcoffs::critter_wake_up_; // (stand up anim) pop eax; clear: - and word ptr [eax + damageFlags], ~(DAM_LOSE_TURN or DAM_KNOCKED_DOWN); + //and word ptr [eax + damageFlags], ~(DAM_LOSE_TURN or DAM_KNOCKED_DOWN); skip: add esp, 4; jmp obj_load_func_Ret; @@ -1104,33 +1151,64 @@ skip: static void __declspec(naked) partyMemberPrepLoadInstance_hook() { __asm { - and word ptr [eax + damageFlags], ~(DAM_LOSE_TURN or DAM_KNOCKED_DOWN); + and word ptr [eax + damageFlags], ~(DAM_LOSE_TURN or DAM_KNOCKED_DOWN); // clear DAM_LOSE_TURN for "NPC turns into a container" bug jmp fo::funcoffs::dude_stand_; } } +// after combat_is_over_p_proc static void __declspec(naked) combat_over_hack() { __asm { - mov [eax + combatState], edx; - and word ptr [eax + damageFlags], ~DAM_LOSE_TURN; + mov eax, esi; // critter + mov esi, ds:[FO_VAR_list_total]; + mov edx, [eax + damageFlags]; + and dword ptr [eax + damageFlags], ~(DAM_LOSE_TURN or DAM_KNOCKOUT_WOKEN); // clear DAM_LOSE_TURN for "NPC turns into a container" bug + test dl, DAM_DEAD or DAM_KNOCKED_OUT; + jnz end; + test dl, DAM_KNOCKED_DOWN; + jnz standup; +end: retn; +standup: + test edx, DAM_KNOCKOUT_WOKEN; + jnz delay; + jmp fo::funcoffs::dude_standup_; +delay: + xor ecx, ecx; + mov edx, eax; // object + xor ebx, ebx; // extramem + inc ecx; // type = 1 (knockout_event) + mov eax, ecx; // time + jmp fo::funcoffs::queue_add_; // critter_wake_up_ will be called (stand up anim) } } +static void __declspec(naked) dude_standup_hook() { + __asm { + mov edx, [ecx + artFid]; + and edx, 0xFF0000; + cmp edx, ANIM_fall_back << 16; + je standup; + cmp edx, ANIM_fall_front << 16; + jne skip; +standup: + jmp fo::funcoffs::register_begin_; +skip: + add esp, 4; + mov edx, 0x4185AD; + jmp edx; + } +} + +//////////////////////////////////////////////////////////////////////////////// + static void __declspec(naked) combat_over_hook() { __asm { test byte ptr [eax + damageFlags], DAM_DEAD; - jz fix; - retn; // the dead cannot reload their weapons -fix: - test byte ptr [eax + damageFlags], DAM_KNOCKED_DOWN; - jz skip; - push eax; - call fo::funcoffs::dude_standup_; - pop eax; - xor edx, edx; -skip: + jnz fix; jmp fo::funcoffs::cai_attempt_w_reload_; +fix: + retn; // the dead cannot reload their weapons } } @@ -1149,15 +1227,16 @@ end: static void __declspec(naked) obj_save_hack() { __asm { // edx - combat_data - mov eax, [eax + cid]; // pobj.who_hit_me.cid test byte ptr ds:[FO_VAR_combat_state], 1; // in combat? - jz clear; // No - cmp dword ptr [edx], 0; // in combat? - jne skip; // Yes + jnz inCombat; // Yes clear: - xor eax, eax; - dec eax; // -1 -skip: + mov [edx + 0x18], -1; // combat_data.who_hit_me + retn; +inCombat: + cmp dword ptr [edx], 0; // critter in combat? + je clear; // No + // default + mov eax, [eax + cid]; // pobj.who_hit_me.cid mov [edx + 0x18], eax; // combat_data.who_hit_me retn; } @@ -1220,33 +1299,31 @@ static void __declspec(naked) item_m_turn_off_hook() { static void __declspec(naked) combat_hack() { __asm { - mov eax, [ecx+eax] // eax = source - test eax, eax - jz end - push eax - mov edx, STAT_max_move_points - call fo::funcoffs::stat_level_ - mov edx, ds:[FO_VAR_gcsd] - test edx, edx - jz skip - add eax, [edx+0x8] // gcsd.free_move + mov eax, [ecx + eax]; // eax = source combat turn + push eax; + mov edx, STAT_max_move_points; + call fo::funcoffs::stat_level_; + mov edx, ds:[FO_VAR_gcsd]; + test edx, edx; + jz skip; + add eax, [edx + 0x8]; // gcsd.free_move skip: - pop edx - xchg edx, eax // eax = source, edx = Max action points - mov [eax + movePoints], edx // pobj.curr_mp - test byte ptr ds:[FO_VAR_combat_state], 1 // in combat? - jz end // No - mov edx, [eax + cid] // pobj.cid - cmp edx, -1 - je end - push eax - mov eax, ds:[FO_VAR_aiInfoList] - shl edx, 4 - mov dword ptr [edx+eax+0xC], 0 // aiInfo.lastMove - pop eax + pop edx; // source + xchg edx, eax; // eax = source, edx = Max action points + mov [eax + movePoints], edx; // pobj.curr_mp + test byte ptr ds:[FO_VAR_combat_state], 1; // in combat? + jz end; // No + mov edx, [eax + cid]; // pobj.cid + cmp edx, -1; + je end; + mov esi, ds:[FO_VAR_aiInfoList]; + shl edx, 4; + mov dword ptr [edx + esi + 0xC], 0; // aiInfo.lastMove end: - mov edx, edi // dude_turn - retn + // remove the flag set by critter_wake_up_ function if critter was knocked out + and dword ptr [eax + damageFlags], ~DAM_KNOCKOUT_WOKEN; + mov edx, edi; // dude_turn + retn; } } @@ -1401,32 +1478,6 @@ end: } } -static int __stdcall ItemCountFix(fo::GameObject* who, fo::GameObject* item) { - int count = 0; - for (int i = 0; i < who->invenSize; i++) { - auto tableItem = &who->invenTable[i]; - if (tableItem->object == item) { - count += tableItem->count; - } else if (fo::func::item_get_type(tableItem->object) == fo::item_type_container) { - count += ItemCountFix(tableItem->object, item); - } - } - return count; -} - -static void __declspec(naked) item_count_hack() { - __asm { - push ecx; - push edx; // save state - push edx; // item - push eax; // container-object - call ItemCountFix; - pop edx; - pop ecx; // restore - retn; - } -} - static void __declspec(naked) Save_as_ASCII_hack() { __asm { mov edx, STAT_sequence; @@ -1435,7 +1486,30 @@ static void __declspec(naked) Save_as_ASCII_hack() { } } +static void __declspec(naked) combat_load_hook_critter() { + __asm { + push ecx; + mov edx, OBJ_TYPE_CRITTER; + mov ecx, eax; + call game::Objects::FindObjectFromID; + pop ecx; + retn; + } +} + +static void __declspec(naked) combat_load_hook_item() { + __asm { + push ecx; + mov edx, OBJ_TYPE_ITEM; + mov ecx, eax; + call game::Objects::FindObjectFromID; + pop ecx; + retn; + } +} + static DWORD combatFreeMoveTmp = 0xFFFFFFFF; + static void __declspec(naked) combat_load_hook() { __asm { call fo::funcoffs::db_freadInt_; @@ -1559,11 +1633,11 @@ end: static void __declspec(naked) ai_combat_turn_run_hook() { __asm { - call fo::funcoffs::combat_turn_run_; - movzx dx, word ptr [esi + damageFlags]; // combat_data.results - test dx, DAM_DEAD or DAM_KNOCKED_OUT or DAM_LOSE_TURN; - jz end; - mov [esi + movePoints], 0; // pobj.curr_mp (source reset ap) + call fo::funcoffs::combat_turn_run_; + mov edx, [esi + damageFlags]; // combat_data.results + test edx, DAM_DEAD or DAM_KNOCKED_OUT or DAM_LOSE_TURN; + jz end; + mov [esi + movePoints], 0; // pobj.curr_mp (source reset ap) end: retn; } @@ -1594,27 +1668,27 @@ static bool showItemDescription = false; static void __stdcall AppendText(const char* text, const char* desc) { if (showItemDescription && currDescLen == 0) { - strncpy_s(tempBuffer, desc, 161); - int len = strlen(tempBuffer); + strncpy_s(messageBuffer, desc, 161); + int len = strlen(messageBuffer); if (len > 160) { len = 158; - tempBuffer[len++] = '.'; - tempBuffer[len++] = '.'; - tempBuffer[len++] = '.'; + messageBuffer[len++] = '.'; + messageBuffer[len++] = '.'; + messageBuffer[len++] = '.'; } - tempBuffer[len++] = ' '; - tempBuffer[len] = 0; + messageBuffer[len++] = ' '; + messageBuffer[len] = 0; currDescLen = len; } else if (currDescLen == 0) { - tempBuffer[0] = 0; + messageBuffer[0] = 0; } - strncat(tempBuffer, text, 64); + strncat(messageBuffer, text, 64); currDescLen += strlen(text); if (currDescLen < 300) { - tempBuffer[currDescLen++] = '.'; - tempBuffer[currDescLen++] = ' '; - tempBuffer[currDescLen] = 0; + messageBuffer[currDescLen++] = '.'; + messageBuffer[currDescLen++] = ' '; + messageBuffer[currDescLen] = 0; } } @@ -1639,7 +1713,7 @@ static void __declspec(naked) obj_examine_func_hack_ammo1() { push eax; call AppendText; mov currDescLen, 0; - lea eax, [tempBuffer]; + lea eax, [messageBuffer]; jmp fo::funcoffs::gdialogDisplayMsg_; skip: jmp dword ptr [esp + 0x1AC - 0x14 + 4]; @@ -1656,9 +1730,9 @@ static void __declspec(naked) obj_examine_func_hack_weapon() { call AppendText; mov eax, currDescLen; sub eax, 2; - mov byte ptr tempBuffer[eax], 0; // cutoff last character + mov byte ptr messageBuffer[eax], 0; // cutoff last character mov currDescLen, 0; - lea eax, [tempBuffer]; + lea eax, [messageBuffer]; skip: jmp ObjExamineFuncWeapon_Ret; } @@ -1750,6 +1824,17 @@ static void __declspec(naked) op_obj_can_hear_obj_hack() { } } +// correct signed division by 4 +static void __declspec(naked) ai_best_weapon_hack() { + __asm { + add edx, 3; + test eax, eax; + cmovs eax, edx; + sar eax, 1; + retn; + } +} + static void __declspec(naked) ai_best_weapon_hook() { __asm { mov eax, [esp + 0xF4 - 0x10 + 4]; // prev.item @@ -1762,7 +1847,7 @@ static void __declspec(naked) wmSetupRandomEncounter_hook() { push eax; // text 2 push edi; // text 1 push 0x500B64; // fmt '%s %s' - lea edi, tempBuffer; + lea edi, messageBuffer; push edi; // buf call fo::funcoffs::sprintf_; add esp, 16; @@ -1933,34 +2018,35 @@ skip: } static DWORD firstItemDrug = -1; + static void __declspec(naked) ai_check_drugs_hack_break() { static const DWORD ai_check_drugs_hack_Ret = 0x42878B; __asm { mov eax, -1; cmp firstItemDrug, eax; - jnz firstDrugs; + jne firstDrugs; // pid != -1 add esp, 4; jmp ai_check_drugs_hack_Ret; // break loop firstDrugs: - mov dword ptr [esp + 4], eax; // buf + mov dword ptr [esp + 4], eax; // slot set -1 mov edi, firstItemDrug; mov ebx, edi; - mov firstItemDrug, eax; + mov firstItemDrug, eax; // set -1 retn; // use drug } } static void __declspec(naked) ai_check_drugs_hack_check() { __asm { - test [esp + 0x34 - 0x30 + 4], 1; // check NoInvenItem flag + test [esp + 0x34 - 0x30 + 4], 0; // check NoInvenItem != 0 jnz skip; - cmp dword ptr [edx + 0xAC], -1; // Chemical Preference Number (cap.chem_primary_desire) + cmp dword ptr [edx + 0xAC], -1; // cap.chem_primary_desire (Chemical Preference Number) jnz checkDrugs; skip: - xor ebx, ebx; // set zero flag for skipping preference list check + xor ebx, ebx; // set ZF for skipping preference list check retn; checkDrugs: - cmp ebx, [edx + 0xAC]; // Chemical Preference Number + cmp ebx, [edx + 0xAC]; // check item.pid against cap.chem_primary_desire retn; } } @@ -1968,16 +2054,16 @@ checkDrugs: static void __declspec(naked) ai_check_drugs_hack_use() { static const DWORD ai_check_drugs_hack_Loop = 0x428675; __asm { - cmp eax, 3; + cmp eax, 3; // counter jge beginLoop; retn; // use drug beginLoop: cmp firstItemDrug, -1; - jnz skip; - mov firstItemDrug, edi; // keep drug item + jne skip; + mov firstItemDrug, edi; // keep first found drug item skip: add esp, 4; - jmp ai_check_drugs_hack_Loop; // goto begin loop + jmp ai_check_drugs_hack_Loop; // goto begin loop, search next item } } @@ -2211,7 +2297,16 @@ skip: } } -static DWORD dudeScriptID; +static void __declspec(naked) map_load_file_hook() { + __asm { + mov eax, 0x04004650; // dude script ID + call fo::funcoffs::scr_remove_; + jmp fo::funcoffs::partyMemberRecoverLoad_; + } +} + +static DWORD dudeScriptID; // usually equal to 0x04004650 + static void __declspec(naked) obj_load_dude_hook0() { __asm { mov eax, ds:[FO_VAR_obj_dude]; @@ -2223,8 +2318,10 @@ static void __declspec(naked) obj_load_dude_hook0() { static void __declspec(naked) obj_load_dude_hook1() { __asm { - mov ebx, dudeScriptID; - mov [eax + scriptId], ebx; + call fo::funcoffs::scr_clear_dude_script_; + mov ebx, ds:[FO_VAR_obj_dude]; + mov eax, dudeScriptID; + mov [ebx + scriptId], eax; retn; } } @@ -2241,10 +2338,12 @@ skip: static void __declspec(naked) exec_script_proc_hack() { __asm { - mov eax, [esi + 0x58]; + test edi, edi; // loading? + jnz end; + mov eax, [esi + 0x58]; // script.procedure_table.start test eax, eax; - ja end; - inc eax; // start proc + ja end; // != 0 + dec eax; // is bad - set to -1 for skipping execution end: retn; } @@ -2252,10 +2351,10 @@ end: static void __declspec(naked) exec_script_proc_hack1() { __asm { - mov esi, [edi + 0x58]; + mov esi, [edi + 0x58]; // script.procedure_table.start test esi, esi; - ja end; - inc esi; // start proc + ja end; // != 0 + inc esi; // 1 - default position end: retn; } @@ -2289,13 +2388,11 @@ dude: } } -static char pickupMessageBuf[65] = {0}; +static char pickupMessage[65] = {0}; + static const char* __fastcall GetPickupMessage(const char* name) { - if (pickupMessageBuf[0] == 0) { - Translate("sfall", "NPCPickupFail", "%s cannot pick up the item.", pickupMessageBuf, 64); - } - sprintf(tempBuffer, pickupMessageBuf, name); - return tempBuffer; + std::sprintf(messageBuffer, pickupMessage, name); + return messageBuffer; } static void __declspec(naked) obj_pickup_hook_message() { @@ -2512,19 +2609,37 @@ end: } } +static bool __fastcall combat_should_end_check_fix(long dudeTeam, fo::GameObject* critter, fo::GameObject* target) { + // target: the current target of the critter (does not need to be checked for null) + + if (critter->critter.teamNum == dudeTeam) { // critter is in the player's team + // EnemyOutOfRange - set when the critter does not want (can't continue) combat or has left the combat due to exceeding the max distance + if ((target->critter.combatState & fo::CombatStateFlag::EnemyOutOfRange) == false && target->critter.IsNotDead()) return false; + } else { + if (target->critter.teamNum == dudeTeam) return false; // don't end combat: target is from the player's team + // for other targets + if (target->critter.IsNotDead()) return false; // don't end combat: target is still alive + //if (critter->critter.combatState & fo::CombatStateFlag::InCombat) return false; // critter is in combat + } + return true; // check next critter +} + static void __declspec(naked) combat_should_end_hack() { static const DWORD combat_should_end_break = 0x422D00; - __asm { // ecx = dude.team_num - cmp ecx, [ebp + teamNum]; // npc->combat_data.who_hit_me.team_num (engine code) - je break; // attacker is in the player's team - test [ebp + damageFlags], DAM_DEAD; // npc->combat_data.who_hit_me.damageFlags - jz break; // target is still alive - test byte ptr [edx], 1; // npc->combat_data.combat_state - jnz break; // npc is in combat + __asm { // ecx = dude.team_num; ebp = critter->who_hit_me + push eax; + push ecx; + sub edx, 0x3C; // critter + push ebp; // target + call combat_should_end_check_fix; + test al, al; + jz break; + pop ecx; + pop eax; retn; // check next critter break: - add esp, 4; - jmp combat_should_end_break; + add esp, 8+4; + jmp combat_should_end_break; // break check loop (don't end combat) } } @@ -2567,6 +2682,61 @@ static void __declspec(naked) map_check_state_hook() { } } +static long __fastcall MultiHexPlacement(fo::GameObject* source) { + //if (!(source->flags & fo::ObjectFlag::MultiHex)) return 0; + long elevation = fo::var::obj_dude->elevation; + long dudeTile = fo::var::obj_dude->tile; + long dudeRot = (fo::var::obj_dude->rotation + 3) % 6; // invert rotation + + long count = 2; + do { + for (long distance = 2; distance < 8; distance++) { + long tilePlace = fo::func::tile_num_in_direction(dudeTile, dudeRot, distance); + if (fo::func::wmEvalTileNumForPlacement(tilePlace)) { + for (long dir = 5; dir >= 0; dir--) { + if (fo::func::obj_blocking_at(source, fo::func::tile_num_in_direction(tilePlace, dir, 1), elevation)) { + tilePlace = 0; + break; + } + } + if (tilePlace) { + __asm { + xor edx, edx; + mov eax, source; + call fo::funcoffs::obj_turn_on_; + xor ecx, ecx; + mov ebx, elevation; + mov edx, tilePlace; + mov eax, source; + call fo::funcoffs::obj_move_to_tile_; + } + return 1; // next PM + } + } + } + dudeRot = fo::var::obj_dude->rotation; + } while (--count); + return 0; // default placement +} + +static void __declspec(naked) partyMemberSyncPosition_hack() { + __asm { + and eax, 0x0F000000; + cmp eax, OBJ_TYPE_CRITTER << 24; + jne default; + test [edx + flags + 1], MultiHex >> 8; + jnz isMultiHex; + xor eax, eax; +default: + retn; +isMultiHex: + mov ecx, edx; + call MultiHexPlacement; + test eax, eax; + retn; + } +} + static void __declspec(naked) op_critter_rm_trait_hook() { __asm { mov ebx, [esp + 0x34 - 0x34 + 4]; // amount @@ -2703,11 +2873,11 @@ skip0: call fo::funcoffs::item_caps_total_; push eax; // caps push 0x502B1C; // fmt: $%d - lea eax, tempBuffer; + lea eax, messageBuffer; push eax; call fo::funcoffs::sprintf_; add esp, 3 * 4; - lea eax, tempBuffer; + lea eax, messageBuffer; call ds:[FO_VAR_text_width]; mov edx, 60; // max width mov ebx, eax; // ebx - textWidth @@ -2721,7 +2891,7 @@ skip0: push 36; // y sar eax, 1; sub ecx, eax; // x shift - lea edx, tempBuffer; + lea edx, messageBuffer; mov eax, ds:[FO_VAR_dialogueWindow]; call fo::funcoffs::win_print_; test ebp, ebp; @@ -2734,7 +2904,18 @@ skip1: } } -static void __declspec(naked) combat_ai_hook() { +static void __declspec(naked) gdReviewDisplay_hack() { + __asm { + mov ebx, eax; + mov eax, -3; + cmp ebx, 407; // vertical position limit + cmovge ecx, eax; + cmp ecx, eax; + retn; + } +} + +static void __declspec(naked) combat_hook() { __asm { call fo::funcoffs::combat_should_end_; test eax, eax; @@ -2859,7 +3040,7 @@ static void __declspec(naked) checkAllRegions_hack() { static const DWORD checkAllRegions_FixRet = 0x4B6AAB; __asm { test eax, eax; - jnz skip; + jnz skip; // != 0 cmp dword ptr ds:[FO_VAR_lastWin], -1; je skip; mov fixRegion, 1; @@ -2875,19 +3056,63 @@ skip: static void __declspec(naked) checkAllRegions_hook() { __asm { test byte ptr fixRegion, 1; - jnz skip; + jnz skip; // == 1 jmp fo::funcoffs::windowCheckRegion_; skip: mov fixRegion, 0; + mov dword ptr ds:[FO_VAR_lastWin], -1; retn; } } +static bool createObjectSidStartFix = false; + +static void __declspec(naked) op_create_object_sid_hack() { + static const char* proDbgMsg = "\nError: attempt to create object with PID of %d: %s!"; + using fo::Scripts::start; + __asm { + mov ebx, [esp + 0x50 - 0x20 + 4]; // createObj + test ebx, ebx; + jz noObject; + mov ecx, [ebx + scriptId]; + cmp ecx, -1; + jne init; + mov edx, ebx; + mov eax, esi; + retn; +init: + call LoadGameHook::IsMapLoading; + test al, al; + jnz end; // yes - initialization will be performed by engine functions + cmp createObjectSidStartFix, 0; + jne runStart; + call ScriptExtender::InitScript; + mov edx, ebx; + mov eax, esi; + retn; +runStart: + mov edx, start; // procedure + mov eax, ecx; + call fo::funcoffs::exec_script_proc_; +end: + mov edx, ebx; + mov eax, esi; + retn; +noObject: + push [esi]; + push [esp + 0x50 - 0x34 + 8]; // object pid + push proDbgMsg; + call fo::funcoffs::debug_printf_; + add esp, 3*4; + jmp end; + } +} + void BugFixes::init() { #ifndef NDEBUG LoadGameHook::OnBeforeGameClose() += PrintAddrList; - if (iniGetInt("Debugging", "BugFixes", 1, ::sfall::ddrawIni) == 0) return; + if (IniReader::GetIntDefaultConfig("Debugging", "BugFixes", 1) == 0) return; #endif // Missing game initialization @@ -2904,74 +3129,74 @@ void BugFixes::init() SafeWrite16(0x46A566, 0x04DB); SafeWrite16(0x46A4E7, 0x04DB); // Fix for vanilla division operator treating negative integers as unsigned - if (GetConfigInt("Misc", "DivisionOperatorFix", 1)) { - dlog("Applying division operator fix.", DL_INIT); + if (IniReader::GetConfigInt("Misc", "DivisionOperatorFix", 1)) { + dlog("Applying division operator fix.", DL_FIX); SafeWrite32(0x46A51D, 0xFBF79990); // xor edx, edx; div ebx > cdq; idiv ebx - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); } - //if (GetConfigInt("Misc", "SpecialUnarmedAttacksFix", 1)) { - dlog("Applying Special Unarmed Attacks fix.", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "SpecialUnarmedAttacksFix", 1)) { + dlog("Applying Special Unarmed Attacks fix.", DL_FIX); MakeJump(0x42394D, compute_attack_hack); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} - //if (GetConfigInt("Misc", "SharpshooterFix", 1)) { - dlog("Applying Sharpshooter patch.", DL_INIT); - // http://www.nma-fallout.com/threads/fo2-engine-tweaks-sfall.178390/page-119#post-4050162 + //if (IniReader::GetConfigInt("Misc", "SharpshooterFix", 1)) { + dlog("Applying Sharpshooter patch.", DL_FIX); + // https://www.nma-fallout.com/threads/fo2-engine-tweaks-sfall.178390/page-119#post-4050162 // by Slider2k HookCall(0x4244AB, SharpShooterFix); // hooks stat_level_() call in detemine_to_hit_func_() // // removes this line by making unconditional jump: // if ( who == obj_dude ) // dist -= 2 * perk_level_(obj_dude, PERK_sharpshooter); SafeWrite8(0x424527, CodeType::JumpShort); // in detemine_to_hit_func_() - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} // Fixes for clickability issue in Pip-Boy and exploit that allows to rest in places where you shouldn't be able to rest - dlog("Applying fix for Pip-Boy clickability issues and rest exploit.", DL_INIT); + dlog("Applying fix for Pip-Boy clickability issues and rest exploit.", DL_FIX); MakeCall(0x4971C7, pipboy_hack); MakeCall(0x499530, PipAlarm_hack); // Fix for clickability issue of holodisk list HookCall(0x497E9F, PipStatus_hook); SafeWrite16(0x497E8C, 0xD389); // mov ebx, edx SafeWrite32(0x497E8E, 0x90909090); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); // Fix for "Too Many Items" bug // http://fforum.kochegarov.com/index.php?showtopic=29288&view=findpost&p=332242 - //if (GetConfigInt("Misc", "TooManyItemsBugFix", 1)) { - dlog("Applying preventive patch for \"Too Many Items\" bug.", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "TooManyItemsBugFix", 1)) { + dlog("Applying preventive patch for \"Too Many Items\" bug.", DL_FIX); HookCalls(scr_write_ScriptNode_hook, {0x4A596A, 0x4A59C1}); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} // Fix for cells getting consumed even when the car is already fully charged MakeCall(0x49BE70, obj_use_power_on_car_hack); // Fix for being able to charge the car by using cells on other scenery/critters - if (GetConfigInt("Misc", "CarChargingFix", 1)) { - dlog("Applying car charging fix.", DL_INIT); + if (IniReader::GetConfigInt("Misc", "CarChargingFix", 1)) { + dlog("Applying car charging fix.", DL_FIX); MakeJump(0x49C36D, protinst_default_use_item_hack); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); } // Fix for gaining stats from more than two doses of a specific chem after save-load - dlog("Applying fix for save-load unlimited drug use exploit.", DL_INIT); + dlog("Applying fix for save-load unlimited drug use exploit.", DL_FIX); MakeCall(0x47A25B, item_d_save_hack); MakeCall(0x47A243, item_d_load_hack); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); // Fix crash when leaving the map while waiting for someone to die of a super stimpak overdose - dlog("Applying fix for \"leaving the map while waiting for a super stimpak overdose death\" crash.", DL_INIT); + dlog("Applying fix for \"leaving the map while waiting for a super stimpak overdose death\" crash.", DL_FIX); HookCall(0x4A27E7, queue_clear_type_mem_free_hook); // hooks mem_free_() - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); // Evil bug! If party member has the same armor type in inventory as currently equipped, then // on level up he loses Armor Class equal to the one received from this armor. // The same happens if you just order NPC to remove the armor through dialogue. - //if (GetConfigInt("Misc", "ArmorCorruptsNPCStatsFix", 1)) { - dlog("Applying fix for armor reducing NPC original stats when removed.", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "ArmorCorruptsNPCStatsFix", 1)) { + dlog("Applying fix for armor reducing NPC original stats when removed.", DL_FIX); HookCall(0x495F3B, partyMemberCopyLevelInfo_hook_stat_level); HookCall(0x45419B, correctFidForRemovedItem_hook_adjust_ac); // Fix for move_obj_inven_to_obj function @@ -2980,47 +3205,47 @@ void BugFixes::init() SafeWrite8(0x45C4A3, CodeType::JumpNZ); // jmp > jnz // Fix for drop_obj function HookCall(0x49B965, obj_drop_hook); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} // Fix of invalid stats when party member gains a level while being on drugs - dlog("Applying fix for addicted party member level up bug.", DL_INIT); + dlog("Applying fix for addicted party member level up bug.", DL_FIX); HookCall(0x495D5C, partyMemberIncLevels_hook); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); // Allow 9 options (lines of text) to be displayed correctly in a dialog window - //if (GetConfigInt("Misc", "DialogOptions9Lines", 1)) { - dlog("Applying 9 dialog options patch.", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "DialogOptions9Lines", 1)) { + dlog("Applying 9 dialog options patch.", DL_FIX); MakeCall(0x447021, gdProcessUpdate_hack, 1); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} // Fix for "Unlimited Ammo" exploit - dlog("Applying fix for Unlimited Ammo exploit.", DL_INIT); + dlog("Applying fix for Unlimited Ammo exploit.", DL_FIX); HookCall(0x472957, invenWieldFunc_item_get_type_hook); // hooks item_get_type_() - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); // Fix for negative values in Skilldex window ("S") - dlog("Applying fix for negative values in Skilldex window.", DL_INIT); + dlog("Applying fix for negative values in Skilldex window.", DL_FIX); SafeWrite8(0x4AC377, 0x7F); // jg - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); // Fix for negative SPECIAL values in character creation - dlog("Applying fix for negative SPECIAL values in character creation.", DL_INIT); + dlog("Applying fix for negative SPECIAL values in character creation.", DL_FIX); MakeCall(0x43DF6F, is_supper_bonus_hack); MakeCall(0x434BFF, PrintBasicStat_hack); HookCall(0x437AB4, StatButtonUp_hook); HookCall(0x437B26, StatButtonDown_hook); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); // Fix for not counting in the weight/size of equipped items on NPC when stealing or bartering - //if (GetConfigInt("Misc", "NPCWeightFix", 1)) { - dlog("Applying fix for not counting in weight of equipped items on NPC.", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "NPCWeightFix", 1)) { + dlog("Applying fix for not counting in weight of equipped items on NPC.", DL_FIX); MakeCall(0x473B4E, loot_container_hack); HookCall(0x4758AB, barter_inventory_hook); MakeCall(0x477EAB, item_total_weight_hack, 1); MakeCall(0x479A2F, item_c_curr_size_hack, 1); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} // Corrects the max text width of the item weight in trading interface to be 64 (was 80), which matches the table width @@ -3029,8 +3254,8 @@ void BugFixes::init() // Corrects the max text width of the player name in inventory to be 140 (was 80), which matches the width for item name SafeWrite32(0x471E48, 140); - //if (GetConfigInt("Misc", "InventoryDragIssuesFix", 1)) { - dlog("Applying inventory reverse order issues fix.", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "InventoryDragIssuesFix", 1)) { + dlog("Applying inventory reverse order issues fix.", DL_FIX); // Fix for minor visual glitch when picking up solo item from the top of inventory // and there is multiple item stack at the bottom of inventory MakeCall(0x470EC2, inven_pickup_hack, 2); @@ -3039,80 +3264,80 @@ void BugFixes::init() MakeJump(0x47114A, inven_pickup_hack2); // Fix for using only one box of ammo when a weapon is above the ammo in the inventory list HookCall(0x476598, drop_ammo_into_weapon_hook); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} // Enable party members with level 6 protos to reach level 6 - //if (GetConfigInt("Misc", "NPCStage6Fix", 1)) { - dlog("Applying NPC Stage 6 Fix.", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "NPCStage6Fix", 1)) { + dlog("Applying NPC Stage 6 Fix.", DL_FIX); MakeJump(0x493CE9, NPCStage6Fix1); // partyMember_init_ MakeJump(0x494224, NPCStage6Fix2); // partyMemberGetAIOptions_ SafeWrite8(0x494063, 6); // loop should look for a potential 6th stage (partyMember_init_) SafeWrite8(0x4940BB, 204); // move pointer by 204 bytes instead of 200 - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} - //if (GetConfigInt("Misc", "NPCLevelFix", 1)) { - dlog("Applying NPC level fix.", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "NPCLevelFix", 1)) { + dlog("Applying NPC level fix.", DL_FIX); HookCall(0x495BC9, (void*)0x495E51); // jz 0x495E7F > jz 0x495E51 - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} - //if (GetConfigInt("Misc", "BlackSkilldexFix", 1)) { - dlog("Applying black Skilldex patch.", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "BlackSkilldexFix", 1)) { + dlog("Applying black Skilldex patch.", DL_FIX); HookCall(0x497D0F, PipStatus_AddHotLines_hook); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} - //if (GetConfigInt("Misc", "FixWithdrawalPerkDescCrash", 1)) { - dlog("Applying withdrawal perk description crash fix.", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "FixWithdrawalPerkDescCrash", 1)) { + dlog("Applying withdrawal perk description crash fix.", DL_FIX); HookCall(0x47A501, perform_withdrawal_start_display_print_hook); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} - //if (GetConfigInt("Misc", "JetAntidoteFix", 1)) { - dlog("Applying Jet Antidote fix.", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "JetAntidoteFix", 1)) { + dlog("Applying Jet Antidote fix.", DL_FIX); // the original jet antidote fix MakeJump(0x47A013, (void*)0x47A168); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} - //if (GetConfigInt("Misc", "NPCDrugAddictionFix", 1)) { - dlog("Applying NPC's drug addiction fix.", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "NPCDrugAddictionFix", 1)) { + dlog("Applying NPC's drug addiction fix.", DL_FIX); // proper checks for NPC's addiction instead of always using global vars MakeJump(0x47A644, item_d_check_addict_hack); MakeJump(0x479FC5, item_d_take_drug_hack); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} - //if (GetConfigInt("Misc", "ShivPatch", 1)) { - dlog("Applying shiv patch.", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "ShivPatch", 1)) { + dlog("Applying shiv patch.", DL_FIX); SafeWrite8(0x477B2B, CodeType::JumpShort); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} - //if (GetConfigInt("Misc", "ImportedProcedureFix", 0)) { - dlog("Applying imported procedure patch.", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "ImportedProcedureFix", 0)) { + dlog("Applying imported procedure patch.", DL_FIX); // http://teamx.ru/site_arc/smf/index.php-topic=398.0.htm SafeWrite16(0x46B35B, 0x1C60); // Fix problems with the temporary stack SafeWrite32(0x46B35D, 0x90909090); SafeWriteBatch(CodeType::JumpShort, {0x46DBF1, 0x46DDC4}); // Disable warnings SafeWrite8(0x4415CC, 0x00); // Prevent crashes when re-exporting - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} // Fix for op_lookup_string_proc_ engine function not searching the last procedure in a script SafeWrite8(0x46C7AC, 0x76); // jb > jbe // Update the AC counter - //if (GetConfigInt("Misc", "WieldObjCritterFix", 1)) { - dlog("Applying wield_obj_critter fix.", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "WieldObjCritterFix", 1)) { + dlog("Applying wield_obj_critter fix.", DL_FIX); SafeWrite8(0x456912, 0x1E); // jnz 0x456931 HookCall(0x45697F, op_wield_obj_critter_adjust_ac_hook); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} - //if (GetConfigInt("Misc", "MultiHexPathingFix", 1)) { - dlog("Applying MultiHex Pathing Fix.", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "MultiHexPathingFix", 1)) { + dlog("Applying MultiHex Pathing Fix.", DL_FIX); HookCall(0x416144, make_path_func_hook); // Fix for building the path to the central hex of a multihex object //MakeCalls(MultiHexFix, {0x42901F, 0x429170}); // obsolete fix @@ -3122,79 +3347,91 @@ void BugFixes::init() // Check neighboring tiles to prevent critters from overlapping other object tiles when moving to the retargeted tile SafeWrite16(0x42A3A6, 0xE889); // xor eax, eax > mov eax, ebp (fix retargeting tile for multihex critters) HookCall(0x42A3A8, MultiHexRetargetTileFix); // cai_retargetTileFromFriendlyFire_ - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} - //if (GetConfigInt("Misc", "DodgyDoorsFix", 1)) { - dlog("Applying Dodgy Door Fix.", DL_INIT); - MakeJump(0x4113D6, action_melee_hack); - MakeJump(0x411BCC, action_ranged_hack); - dlogr(" Done", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "DodgyDoorsFix", 1)) { + dlog("Applying Dodgy Door Fix.", DL_FIX); + MakeCall(0x4113D3, action_melee_hack, 2); + MakeCall(0x411BC9, action_ranged_hack, 2); + dlogr(" Done", DL_FIX); //} + // Fix for multiple knockout events being added to the queue + HookCall(0x424F9A, set_new_results_hack); + + // Fix for critter_state function when a critter in combat recovers from the knockout state outside its turn + // DAM_KNOCKOUT_WOKEN flag lets the function know that the critter was knocked out before it actually woke up (stand up) + MakeCall(0x45868E, op_critter_state_hack, 1); + MakeCall(0x42E44C, critter_wake_up_hack); + + // Fixes for knockout/down issues + HookCall(0x42E456, critter_wake_up_hook); + HookCall(0x41857E, dude_standup_hook); // check if the critter is actually in the prone position + // Fix for "NPC turns into a container" bug - //if (GetConfigInt("Misc", "NPCTurnsIntoContainerFix", 1)) { - dlog("Applying fix for \"NPC turns into a container\" bug.", DL_INIT); + // https://www.nma-fallout.com/threads/fo2-engine-tweaks-sfall.178390/page-123#post-4065716 + //if (IniReader::GetConfigInt("Misc", "NPCTurnsIntoContainerFix", 1)) { + dlog("Applying fix for \"NPC turns into a container\" bug.", DL_FIX); MakeJump(0x42E46E, critter_wake_clear_hack); MakeCall(0x488EF3, obj_load_func_hack, 1); HookCall(0x4949B2, partyMemberPrepLoadInstance_hook); - MakeCall(0x421F64, combat_over_hack, 1); - dlogr(" Done", DL_INIT); + // Fix for knocked down critters not playing stand up animation when the combat ends (when DAM_LOSE_TURN and DAM_KNOCKED_DOWN flags are set) + MakeCall(0x42206F, combat_over_hack, 1); + dlogr(" Done", DL_FIX); //} - // Fix for multiple knockout events being added to the queue - HookCall(0x424F9A, set_new_results_hack); - // Fix for knocked down critters not playing stand up animation when the combat ends (when DAM_LOSE_TURN and DAM_KNOCKED_DOWN - // flags are set) and prevent dead NPCs from reloading their weapons + + // Fix to prevent dead NPCs from reloading their weapons when the combat ends HookCall(0x421F30, combat_over_hook); - dlog("Applying fix for explosives bugs.", DL_INIT); + dlog("Applying fix for explosives bugs.", DL_FIX); // Fix crashes when killing critters with explosives MakeJump(0x422F05, combat_ctd_init_hack); MakeCall(0x48941C, obj_save_hack, 1); // Fix for destroy_p_proc not being called if the critter is killed by explosives when you leave the map MakeCall(0x4130C3, action_explode_hack); MakeCall(0x4130E5, action_explode_hack1); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); // Fix for being unable to sell used geiger counters or stealth boys - if (GetConfigInt("Misc", "CanSellUsedGeiger", 1)) { - dlog("Applying fix for being unable to sell used geiger counters or stealth boys.", DL_INIT); + if (IniReader::GetConfigInt("Misc", "CanSellUsedGeiger", 1)) { + dlog("Applying fix for being unable to sell used geiger counters or stealth boys.", DL_FIX); SafeWriteBatch(0xBA, {0x478115, 0x478138}); // item_queued_ (will return the found item) MakeJump(0x474D22, barter_attempt_transaction_hack, 1); HookCall(0x4798B1, item_m_turn_off_hook); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); } // Fix for incorrect initialization of action points at the beginning of each turn - dlog("Applying Action Points initialization fix.", DL_INIT); + dlog("Applying Action Points initialization fix.", DL_FIX); BlockCall(0x422E02); MakeCall(0x422E1B, combat_hack); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); // Fix for incorrect death animations being used when killing critters with kill_critter_type function - dlog("Applying kill_critter_type fix.", DL_INIT); + dlog("Applying kill_critter_type fix.", DL_FIX); SafeWrite16(0x457E22, 0xDB31); // xor ebx, ebx SafeWrite32(0x457C99, 0x30BE0075); // jnz loc_457C9B; mov esi, 48 - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); // Fix for checking the horizontal position on the y-axis instead of x when setting coordinates on the world map SafeWrite8(0x4C4743, 0xC6); // cmp esi, eax - //if (GetConfigInt("Misc", "PrintToFileFix", 1)) { - dlog("Applying print to file fix.", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "PrintToFileFix", 1)) { + dlog("Applying print to file fix.", DL_FIX); MakeCall(0x4C67D4, db_get_file_list_hack); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} // Fix for display issues when calling gdialog_mod_barter with critters with no "Barter" flag set - //if (GetConfigInt("Misc", "gdBarterDispFix", 1)) { - dlog("Applying gdialog_mod_barter display fix.", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "gdBarterDispFix", 1)) { + dlog("Applying gdialog_mod_barter display fix.", DL_FIX); HookCall(0x448250, gdActivateBarter_hook); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} - //if (GetConfigInt("Misc", "BagBackpackFix", 1)) { - dlog("Applying fix for bag/backpack bugs.", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "BagBackpackFix", 1)) { + dlog("Applying fix for bag/backpack bugs.", DL_FIX); // Fix for items disappearing from inventory when you try to drag them to bag/backpack in the inventory list // and are overloaded HookCall(0x4764FC, (void*)fo::funcoffs::item_add_force_); @@ -3206,24 +3443,28 @@ void BugFixes::init() MakeCall(0x471C17, inven_item_wearing, 1); // inven_worn_ // Fix crash when trying to open bag/backpack on the table in the bartering interface MakeCall(0x473191, inven_action_cursor_hack); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} // Fix crash when clicking on empty space in the inventory list opened by "Use Inventory Item On" (backpack) action icon MakeCall(0x471A94, use_inventory_on_hack); - // Fix item_count function returning incorrect value when there is a container-item inside - MakeJump(0x47808C, item_count_hack); // replacing item_count_ function + // Fix item_count_ function returning incorrect value when there is a container-item inside + SafeWrite8(0x4780B1, 0x29); // jmp 0x4780DB // Fix for Sequence stat value not being printed correctly when using "print to file" option MakeCall(0x4396F5, Save_as_ASCII_hack, 2); + // Fix for the incorrect object type search when loading a game saved in combat mode + HookCalls(combat_load_hook_critter, {0x42113B, 0x42117D}); + HookCall(0x4211C0, combat_load_hook_item); + // Fix for Bonus Move APs being replenished when you save and load the game in combat - //if (GetConfigInt("Misc", "BonusMoveFix", 1)) { - dlog("Applying fix for Bonus Move exploit.", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "BonusMoveFix", 1)) { + dlog("Applying fix for Bonus Move exploit.", DL_FIX); HookCall(0x420E93, combat_load_hook); MakeCall(0x422A06, combat_turn_hack); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} // Fix for the displayed message when the attack randomly hits a target that is not a critter and has a script attached @@ -3234,11 +3475,11 @@ void BugFixes::init() MakeCall(0x424CD2, apply_damage_hack); // Fix for the double damage effect of Silent Death perk not being applied to critical hits - //if (GetConfigInt("Misc", "SilentDeathFix", 1)) { - dlog("Applying Silent Death patch.", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "SilentDeathFix", 1)) { + dlog("Applying Silent Death patch.", DL_FIX); SafeWrite8(0x4238DF, 0x8C); // jl loc_423A0D HookCall(0x423A99, compute_attack_hook); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} // Fix crash when calling partyMemberGetCurLevel_ on a critter that has no data in party.txt @@ -3250,8 +3491,8 @@ void BugFixes::init() // Fix for add_mult_objs_to_inven only adding 500 of an object when the value of the "count" argument is over 99999 SafeWrite32(0x45A2A0, 99999); - // Fix for being at incorrect hex after map change when the exit hex in source map is at the same position as - // some exit hex in destination map + // Fix for being at incorrect hex after map change when the exit hex in source map is at the same position as some exit hex + // in destination map MakeCall(0x48A704, obj_move_to_tile_hack); // Fix for critters killed in combat by scripting still being able to move in their combat turn if the distance parameter @@ -3263,34 +3504,34 @@ void BugFixes::init() }); // Fix instant death critical - dlog("Applying instant death fix.", DL_INIT); + dlog("Applying instant death fix.", DL_FIX); MakeJump(0x424BA2, compute_damage_hack); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); // Fix missing AC/DR mod stats when examining ammo in the barter screen - dlog("Applying fix for displaying ammo stats in barter screen.", DL_INIT); + dlog("Applying fix for displaying ammo stats in barter screen.", DL_FIX); MakeCall(0x49B4AD, obj_examine_func_hack_ammo0, 2); MakeCall(0x49B504, obj_examine_func_hack_ammo0, 2); MakeCall(0x49B563, obj_examine_func_hack_ammo1, 2); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); // Display full item description for weapon/ammo in the barter screen - showItemDescription = (GetConfigInt("Misc", "FullItemDescInBarter", 0) != 0); + showItemDescription = (IniReader::GetConfigInt("Misc", "FullItemDescInBarter", 0) != 0); if (showItemDescription) { - dlog("Applying full item description in barter patch.", DL_INIT); + dlog("Applying full item description in barter patch.", DL_FIX); HookCall(0x49B452, obj_examine_func_hack_weapon); // it's jump - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); } // Display experience points with the bonus from Swift Learner perk when gained from non-scripted situations - if (GetConfigInt("Misc", "DisplaySwiftLearnerExp", 1)) { - dlog("Applying Swift Learner exp display patch.", DL_INIT); + if (IniReader::GetConfigInt("Misc", "DisplaySwiftLearnerExp", 1)) { + dlog("Applying Swift Learner exp display patch.", DL_FIX); MakeCall(0x4AFAEF, statPCAddExperienceCheckPMs_hack); HookCall(0x4221E2, combat_give_exps_hook); MakeJump(0x4745AE, loot_container_exp_hack); SafeWrite16(0x4C0AB1, 0x23EB); // jmps 0x4C0AD6 HookCall(0x4C0AEB, wmRndEncounterOccurred_hook); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); } // Fix for obj_can_see_obj not checking if source and target objects are on the same elevation before calling @@ -3299,24 +3540,24 @@ void BugFixes::init() SafeWrite16(0x456B76, 0x23EB); // jmp loc_456B9B (skip unused engine code) // Fix broken obj_can_hear_obj function - if (GetConfigInt("Misc", "ObjCanHearObjFix", 0)) { - dlog("Applying obj_can_hear_obj fix.", DL_INIT); + if (IniReader::GetConfigInt("Misc", "ObjCanHearObjFix", 0)) { + dlog("Applying obj_can_hear_obj fix.", DL_FIX); SafeWrite8(0x4583D8, 0x3B); // jz loc_458414 SafeWrite8(0x4583DE, CodeType::JumpZ); // jz loc_458414 MakeCall(0x4583E0, op_obj_can_hear_obj_hack, 1); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); } - // Fix for AI not checking weapon perks properly when searching for the best weapon - int bestWeaponPerkFix = GetConfigInt("Misc", "AIBestWeaponFix", 0); - if (bestWeaponPerkFix > 0) { - dlog("Applying AI best weapon choice fix.", DL_INIT); + if (IniReader::GetConfigInt("Misc", "AIBestWeaponFix", 1)) { + dlog("Applying AI best weapon choice fix.", DL_FIX); + // Fix for the incorrect item being checked for the presence of weapon perks HookCall(0x42954B, ai_best_weapon_hook); - // also change the priority multiplier for having weapon perk to 3x (the original is 5x) - if (bestWeaponPerkFix > 1) { - SafeWriteBatch(0x55, {0x42955E, 0x4296E7}); // lea eax, [edx * 2]; - } - dlogr(" Done", DL_INIT); + // Corrects the calculation of the weapon score to: (maxDmg + minDmg) / 4 + SafeWriteBatch(0x01, {0x4294E2, 0x429675}); // sub > add + MakeCalls(ai_best_weapon_hack, {0x4294E6, 0x429679}); + // Corrects the weapon score multiplier for having perks to 2x (was 5x) + SafeWriteBatch(0x15, {0x42955E, 0x4296E7}); // lea eax, [edx*4] > lea eax, [edx] + dlogr(" Done", DL_FIX); } // Fix for the encounter description being displayed in two lines instead of one @@ -3331,29 +3572,29 @@ void BugFixes::init() MakeCall(0x472F5F, inven_obj_examine_func_hack, 1); // Fix for the exploit that allows you to gain excessive skill points from Tag! perk before leaving the character screen - dlog("Applying fix for Tag! exploit.", DL_INIT); + dlog("Applying fix for Tag! exploit.", DL_FIX); HookCall(0x43B463, SliderBtn_hook_down); HookCall(0x43D7DD, Add4thTagSkill_hook); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); // Fix for ai_retrieve_object_ engine function not returning the requested object when there are different objects // with the same ID - dlog("Applying ai_retrieve_object engine function fix.", DL_INIT); + dlog("Applying ai_retrieve_object engine function fix.", DL_FIX); HookCall(0x429D7B, ai_retrieve_object_hook); MakeCall(0x472708, inven_find_id_hack); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); // Fix for the "mood" argument of start_gdialog function being ignored for talking heads - if (GetConfigInt("Misc", "StartGDialogFix", 0)) { - dlog("Applying start_gdialog argument fix.", DL_INIT); + if (IniReader::GetConfigInt("Misc", "StartGDialogFix", 0)) { + dlog("Applying start_gdialog argument fix.", DL_FIX); MakeCall(0x456F08, op_start_gdialog_hack); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); } // Fix for Heave Ho! perk increasing Strength stat above 10 when determining the maximum range of thrown weapons - dlog("Applying Heave Ho! perk fix.", DL_INIT); + dlog("Applying Heave Ho! perk fix.", DL_FIX); HookCall(0x478AD9, item_w_range_hook); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); // Fix for determine_to_hit_func_ engine function taking distance into account when called from determine_to_hit_no_range_ HookCall(0x4244C3, determine_to_hit_func_hook); @@ -3361,25 +3602,29 @@ void BugFixes::init() // Radiation fixes MakeCall(0x42D6C3, process_rads_hack, 1); // prevents player's death if a stat is less than 1 when removing radiation effects HookCall(0x42D67A, process_rads_hook); // fix for the same effect message being displayed when removing radiation effects - radEffectsMsgNum = GetConfigInt("Misc", "RadEffectsRemovalMsg", radEffectsMsgNum); + radEffectsMsgNum = IniReader::GetConfigInt("Misc", "RadEffectsRemovalMsg", radEffectsMsgNum); // Display messages about radiation for the active geiger counter - if (GetConfigInt("Misc", "ActiveGeigerMsgs", 1)) { - dlog("Applying active geiger counter messages patch.", DL_INIT); + if (IniReader::GetConfigInt("Misc", "ActiveGeigerMsgs", 1)) { + dlog("Applying active geiger counter messages patch.", DL_FIX); SafeWriteBatch(CodeType::JumpZ, {0x42D424, 0x42D444}); // jnz > jz - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); } // Display a pop-up message box about death from radiation HookCall(0x42D733, process_rads_hook_msg); - // Fix for AI not taking chem_primary_desire in AI.txt as drug use preference when using drugs in their inventory - if (GetConfigInt("Misc", "AIDrugUsePerfFix", 0)) { - dlog("Applying AI drug use preference fix.", DL_INIT); - MakeCall(0x42869D, ai_check_drugs_hack_break); - MakeCall(0x4286AB, ai_check_drugs_hack_check); - SafeWrite16(0x4286B0, 0x7490); // jnz > jz - SafeWrite8(0x4286C5, CodeType::JumpNZ); // jz > jnz - MakeCall(0x4286C7, ai_check_drugs_hack_use); - dlogr(" Done", DL_INIT); + int drugUsePerfFix = IniReader::GetConfigInt("Misc", "AIDrugUsePerfFix", 0); + if (drugUsePerfFix > 0) { + dlog("Applying AI drug use preference fix.", DL_FIX); + if (drugUsePerfFix == 1) { + // Fix for AI not taking chem_primary_desire in AI.txt as drug use preference when using drugs in their inventory + MakeCall(0x42869D, ai_check_drugs_hack_break); + MakeCall(0x4286AB, ai_check_drugs_hack_check, 1); + MakeCall(0x4286C7, ai_check_drugs_hack_use); + } + // Fix to allow using only the drugs listed in chem_primary_desire and healing drugs (stimpaks and healing powder) + SafeWrite8(0x4286B1, CodeType::JumpZ); // jnz > jz (ai_check_drugs_) + SafeWrite8(0x4286C5, CodeType::JumpNZ); // jz > jnz (ai_check_drugs_) + dlogr(" Done", DL_FIX); } // Fix for config_get_values_ engine function not getting the last value in a list if the list has less than the requested @@ -3392,8 +3637,8 @@ void BugFixes::init() // Fix and repurpose the unused called_shot/num_attack arguments of attack_complex function // called_shot - additional damage when hitting the target // num_attacks - the number of free action points on the first turn only - if (GetConfigInt("Misc", "AttackComplexFix", 0)) { - dlog("Applying attack_complex arguments fix.", DL_INIT); + if (IniReader::GetConfigInt("Misc", "AttackComplexFix", 0)) { + dlog("Applying attack_complex arguments fix.", DL_FIX); HookCall(0x456D4A, op_attack_hook); SafeWrite8(0x456D61, 0x74); // mov [gcsd.free_move], esi SafeWrite8(0x456D92, 0x5C); // mov [gcsd.amount], ebx @@ -3404,7 +3649,7 @@ void BugFixes::init() SafeWrite16(0x456DA7, 0x8489); // mov [gcsd.changeFlags], 1 > mov [gcsd.changeFlags], eax SafeWrite8(0x456DAB, 0); SafeWrite8(0x456DAE, CodeType::Nop); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); } else { // Fix setting result flags argument for the target SafeWrite16(0x456D95, 0xED85); // cmp eax, ebp > test ebp, ebp @@ -3416,9 +3661,9 @@ void BugFixes::init() MakeJump(0x422FE5, combat_attack_hack, 1); // Fix for critter_mod_skill taking a negative amount value as a positive - dlog("Applying critter_mod_skill fix.", DL_INIT); + dlog("Applying critter_mod_skill fix.", DL_FIX); SafeWrite8(0x45B910, 0x7E); // jbe > jle - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); // Fix crash when calling use_obj/use_obj_on_obj without using set_self in global scripts // also change the behavior of use_obj_on_obj function @@ -3428,14 +3673,14 @@ void BugFixes::init() // Fix pickup_obj/drop_obj/use_obj functions, change them to get pointer from script.self instead of script.target // script.target contains an incorrect pointer, which may vary depending on the situations in the game - dlog("Applying pickup_obj/drop_obj/use_obj fix.", DL_INIT); + dlog("Applying pickup_obj/drop_obj/use_obj fix.", DL_FIX); SafeWriteBatch(0x34, { // script.target > script.self 0x456554, // op_pickup_obj_ 0x456600, // op_drop_obj_ 0x456A6D, // op_use_obj_ 0x456AA4 // op_use_obj_ }); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); // Fix for critters not attacking the player in combat when loading a game saved in combat mode BlockCall(0x48D6F0); // obj_fix_combat_cid_for_dude_ @@ -3450,17 +3695,17 @@ void BugFixes::init() SafeWrite32(0x4AA56B, 0); // Fix for NPC stuck in a loop of reloading melee/unarmed weapons when out of ammo - dlog("Applying fix for NPC stuck in a loop of reloading melee/unarmed weapons.", DL_INIT); + dlog("Applying fix for NPC stuck in a loop of reloading melee/unarmed weapons.", DL_FIX); HookCall(0x429A2B, ai_search_inven_weap_hook); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); // Fix for critters not being healed over time when entering the map if 'dead_bodies_age=No' is set in maps.txt // also fix the zero initialization of a local variable to correct time for removing corpses and blood - dlog("Applying fix for the self-healing of critters when entering the map.", DL_INIT); + dlog("Applying fix for the self-healing of critters when entering the map.", DL_FIX); MakeCall(0x483356, map_age_dead_critters_hack); SafeWrite32(0x4832A0, 0x9090C189); // mov ecx, eax (keep dead_bodies_age flag) SafeWrite32(0x4832A4, 0x0C245489); // mov [esp + var_30], edx - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); // Fix for the removal of party member's corpse when loading the map MakeCall(0x495769, partyFixMultipleMembers_hack, 1); @@ -3479,6 +3724,7 @@ void BugFixes::init() HookCall(0x499240, PrintAMList_hook); // Fix for a duplicate obj_dude script being created when loading a saved game + HookCall(0x48306E, map_load_file_hook); // removes the redundant saved dude script data from the scripts block HookCall(0x48D63E, obj_load_dude_hook0); HookCall(0x48D666, obj_load_dude_hook1); BlockCall(0x48D675); @@ -3495,6 +3741,7 @@ void BugFixes::init() // up an item due to not enough space in the inventory HookCall(0x49B6E7, obj_pickup_hook); HookCall(0x49B71C, obj_pickup_hook_message); + Translate::Get("sfall", "NPCPickupFail", "%s cannot pick up the item.", pickupMessage, 65); // Fix for anim_move_to_tile_ engine function ignoring the distance argument for the player HookCall(0x416D44, anim_move_to_tile_hook); @@ -3505,10 +3752,10 @@ void BugFixes::init() MakeCall(0x411DF7, action_climb_ladder_hack); // bug caused by anim_move_to_tile_ fix // Partial fix for incorrect positioning after exiting small/medium locations (e.g. Ghost Farm) - //if (GetConfigInt("Misc", "SmallLocExitFix", 1)) { - dlog("Applying fix for incorrect positioning after exiting small/medium locations.", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "SmallLocExitFix", 1)) { + dlog("Applying fix for incorrect positioning after exiting small/medium locations.", DL_FIX); MakeJump(0x4C5A41, wmTeleportToArea_hack); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} // Fix for Scout perk being taken into account when setting the visibility of locations with mark_area_known function @@ -3521,38 +3768,41 @@ void BugFixes::init() MakeCall(0x4C03AA, wmWorldMap_hack, 2); // Fix to prevent using number keys to enter unvisited areas on a town map - if (GetConfigInt("Misc", "TownMapHotkeysFix", 1)) { - dlog("Applying town map hotkeys patch.", DL_INIT); + if (IniReader::GetConfigInt("Misc", "TownMapHotkeysFix", 1)) { + dlog("Applying town map hotkeys patch.", DL_FIX); MakeCall(0x4C495A, wmTownMapFunc_hack, 1); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); } // Fix for combat not ending automatically when there are no hostile critters MakeCall(0x422CF3, combat_should_end_hack); - SafeWrite16(0x422CEA, 0x0C74); // jz 0x422CF8 (skip party members) + SafeWrite16(0x422CEA, 0x9090); // Fix for the car being lost when entering a location via the Town/World button and then leaving on foot // (sets GVAR_CAR_PLACED_TILE (633) to -1 on exit to the world map) - if (GetConfigInt("Misc", "CarPlacedTileFix", 1)) { - dlog("Applying car placed tile fix.", DL_INIT); + if (IniReader::GetConfigInt("Misc", "CarPlacedTileFix", 1)) { + dlog("Applying car placed tile fix.", DL_FIX); MakeCall(0x4C2367, wmInterfaceInit_hack); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); } // Place the player on a nearby empty tile if the entrance tile is blocked by another object when entering a map HookCall(0x4836F8, map_check_state_hook); + // Fix the placement of multihex critters in the player's party when entering a map or elevation + MakeCall(0x494E33, partyMemberSyncPosition_hack, 1); + // Fix for critter_add/rm_trait functions ignoring the value of the "amount" argument // Note: pass negative amount values to critter_rm_trait to remove all ranks of the perk (vanilla behavior) HookCall(0x458CDB, op_critter_rm_trait_hook); HookCall(0x458B3D, op_critter_add_trait_hook); // Fix to prevent corpses from blocking line of fire - //if (GetConfigInt("Misc", "CorpseLineOfFireFix", 1)) { - dlog("Applying fix for corpses blocking line of fire.", DL_INIT); + //if (IniReader::GetConfigInt("Misc", "CorpseLineOfFireFix", 1)) { + dlog("Applying fix for corpses blocking line of fire.", DL_FIX); MakeJump(0x48B994, obj_shoot_blocking_at_hack0); MakeJump(0x48BA04, obj_shoot_blocking_at_hack1); - dlogr(" Done", DL_INIT); + dlogr(" Done", DL_FIX); //} // Fix for party member's equipped weapon being placed in the incorrect item slot after leveling up @@ -3575,10 +3825,15 @@ void BugFixes::init() // Fix for the player's money not being displayed in the dialog window after leaving the barter/combat control interface HookCall(0x447ACD, gdialog_bk_hook); - // Fix crash or animation glitch of the critter in combat when an explosion from explosives - // and the AI attack animation are performed simultaneously + // Cosmetic fix to the dialog review interface + // to prevent the player name from being displayed at the bottom of the window when the text is longer than one screen + MakeCall(0x445ECC, gdReviewDisplay_hack); + + // TODO: If a bug is found that leads to an animation glitch, then this fix can be removed + // Fix crash or animation glitch of the critter in combat when an explosion from explosives and the AI attack animation are + // performed simultaneously // Note: all events in combat will occur before the AI (party member) attack - HookCall(0x422E5F, combat_ai_hook); // execute all events after the end of the combat sequence + HookCall(0x422E5F, combat_hook); // execute all events after the end of the combat sequence // Fix for the "Fill_W" flag in worldmap.txt not uncovering all tiles to the left edge of the world map MakeJump(0x4C372B, wmSubTileMarkRadiusVisited_hack); @@ -3609,6 +3864,12 @@ void BugFixes::init() }; SafeWriteBytes(0x42A0F4, codeData1, 18); // ai_move_steps_closer_ HookCall(0x42A0F8, (void*)fo::funcoffs::obj_dist_); + BYTE codeData2[] = { // swap code + 0x90, 0x90, 0x31, 0xC0, // xor eax, eax + 0xF6, 0x47, 0x25, 0x08, // test [edi + 0x25], MultiHex_ + }; + SafeWriteBytes(0x42A0E6, codeData2, 8); // ai_move_steps_closer_ + SafeWrite8(0x42A0F2, CodeType::JumpZ); // jmp > jz // Fix to prevent the execution of critter_p_proc and game events when playing movies (same as when the dialog is active) HookCall(0x4A3C89, doBkProcesses_hook); @@ -3636,6 +3897,12 @@ void BugFixes::init() // Fix for the "Leave" event procedure of the window region not being triggered when the cursor moves to a non-scripted window MakeJump(0x4B6C3B, checkAllRegions_hack); HookCall(0x4B6C13, checkAllRegions_hook); + + // Fix for the script attached to an object not being initialized properly upon object creation + createObjectSidStartFix = (IniReader::GetConfigInt("Misc", "CreateObjectSidFix", 0) != 0); + MakeCall(0x4551C0, op_create_object_sid_hack, 1); + // Fix the error handling in create_object_sid function to prevent a crash when the proto is missing + SafeWrite8(0x45507B, 0x51); // jz 0x4550CD } } diff --git a/sfall/Modules/BurstMods.cpp b/sfall/Modules/BurstMods.cpp index 855de49f..7d4f7262 100644 --- a/sfall/Modules/BurstMods.cpp +++ b/sfall/Modules/BurstMods.cpp @@ -67,18 +67,18 @@ static void __declspec(naked) compute_spray_rounds_distribution() { } void BurstMods::init() { - if (GetConfigInt("Misc", "ComputeSprayMod", 0)) { + if (IniReader::GetConfigInt("Misc", "ComputeSprayMod", 0)) { dlog("Applying ComputeSpray changes.", DL_INIT); - compute_spray_center_mult = GetConfigInt("Misc", "ComputeSpray_CenterMult", 1); - compute_spray_center_div = GetConfigInt("Misc", "ComputeSpray_CenterDiv", 3); + compute_spray_center_mult = IniReader::GetConfigInt("Misc", "ComputeSpray_CenterMult", 1); + compute_spray_center_div = IniReader::GetConfigInt("Misc", "ComputeSpray_CenterDiv", 3); if (compute_spray_center_div < 1) { compute_spray_center_div = 1; } if (compute_spray_center_mult > compute_spray_center_div) { compute_spray_center_mult = compute_spray_center_div; } - compute_spray_target_mult = GetConfigInt("Misc", "ComputeSpray_TargetMult", 1); - compute_spray_target_div = GetConfigInt("Misc", "ComputeSpray_TargetDiv", 2); + compute_spray_target_mult = IniReader::GetConfigInt("Misc", "ComputeSpray_TargetMult", 1); + compute_spray_target_div = IniReader::GetConfigInt("Misc", "ComputeSpray_TargetDiv", 2); if (compute_spray_target_div < 1) { compute_spray_target_div = 1; } diff --git a/sfall/Modules/Combat.cpp b/sfall/Modules/Combat.cpp index f139fd5d..da0f4574 100644 --- a/sfall/Modules/Combat.cpp +++ b/sfall/Modules/Combat.cpp @@ -16,8 +16,6 @@ * along with this program. If not, see . */ -#include - #include "..\main.h" #include "..\FalloutEngine\Fallout2.h" #include "..\SimplePatch.h" @@ -25,10 +23,12 @@ #include "LoadGameHook.h" #include "Objects.h" -#include "SubModules\CombatBlock.h" - #include "HookScripts\CombatHS.h" +//#include "..\Game\items.h" + +#include "SubModules\CombatBlock.h" + #include "Combat.h" namespace sfall @@ -37,7 +37,7 @@ namespace sfall static const DWORD bodypartAddr[] = { 0x425562, // combat_display_ 0x42A68F, 0x42A739, // ai_called_shot_ -// 0x429E82, 0x429EC2, 0x429EFF, // ai_pick_hit_mode_ +// 0x429E82, 0x429EC2, 0x429EFF, // ai_pick_hit_mode_ (used for hit mode) 0x423231, 0x423268, // check_ranged_miss_ 0x4242D4, // attack_crit_failure_ // for combat_ctd_init_ func @@ -54,7 +54,7 @@ static const DWORD bodypartAddr[] = { 0x49C00C, // protinstTestDroppedExplosive_ }; -static struct BodyParts { +static struct { long Head; long Left_Arm; long Right_Arm; @@ -64,7 +64,7 @@ static struct BodyParts { long Eyes; long Groin; long Uncalled; -} bodypartHit; +} bodyPartHit; struct KnockbackModifier { long id; @@ -74,7 +74,7 @@ struct KnockbackModifier { long Combat::determineHitChance; // the value of hit chance w/o any cap -static std::vector noBursts; // object id +static std::vector noBursts; // critter id static std::vector mTargets; static std::vector mAttackers; @@ -87,34 +87,39 @@ static bool hookedAimedShot; static std::vector disabledAS; static std::vector forcedAS; -DWORD __fastcall Combat::check_item_ammo_cost(fo::GameObject* weapon, DWORD hitMode) { - DWORD rounds = 1; +static bool checkWeaponAmmoCost; + +// Compares the cost (required count of rounds) for one shot with the current amount of ammo to make an attack or other checks +long __fastcall Combat::check_item_ammo_cost(fo::GameObject* weapon, fo::AttackType hitMode) { + long currAmmo = fo::func::item_w_curr_ammo(weapon); + if (!checkWeaponAmmoCost || currAmmo <= 0) return currAmmo; + + long rounds = 1; // default ammo for single shot long anim = fo::func::item_w_anim_weap(weapon, hitMode); if (anim == fo::Animation::ANIM_fire_burst || anim == fo::Animation::ANIM_fire_continuous) { rounds = fo::func::item_w_rounds(weapon); // ammo in burst } - if (HookScripts::IsInjectHook(HOOK_AMMOCOST)) { - AmmoCostHook_Script(1, weapon, rounds); // get rounds cost from hook - } else if (rounds == 1) { - fo::func::item_w_compute_ammo_cost(weapon, &rounds); - } - long currAmmo = fo::func::item_w_curr_ammo(weapon); - long cost = 1; // default cost - if (currAmmo > 0) { - cost = rounds / currAmmo; - if (rounds % currAmmo) cost++; // round up + DWORD newRounds = rounds; + + if (HookScripts::IsInjectHook(HOOK_AMMOCOST)) { + AmmoCostHook_Script(1, weapon, newRounds); // newRounds returns the new "ammo" value multiplied by the cost + } else if (rounds == 1) { // NOTE: it doesn't make sense to call item_w_compute_ammo_cost for rounds greater than one + fo::func::item_w_compute_ammo_cost(weapon, &newRounds); } - return (cost > currAmmo) ? 0 : 1; // 0 - this will force "Out of ammo", 1 - this will force success (enough ammo) + + // calculate the cost + long cost = (newRounds != rounds) ? newRounds / rounds : 1; // 1 - default cost + return (cost > currAmmo) ? 0 : currAmmo; // 0 - this will force "Not Enough Ammo" } // adds check for weapons which require more than 1 ammo for single shot (super cattle prod & mega power fist) and burst rounds static void __declspec(naked) combat_check_bad_shot_hook() { __asm { push edx; - push ecx; // weapon - mov edx, edi; // hitMode + push ecx; // weapon + mov edx, edi; // hitMode call Combat::check_item_ammo_cost; pop ecx; pop edx; @@ -127,9 +132,9 @@ static void __declspec(naked) ai_search_inven_weap_hook() { using namespace fo; __asm { push ecx; - mov ecx, eax; // weapon - mov edx, ATKTYPE_RWEAPON_PRIMARY; // hitMode - call Combat::check_item_ammo_cost; // enough ammo? + mov edx, ATKTYPE_RWEAPON_PRIMARY; // hitMode + mov ecx, eax; // weapon + call Combat::check_item_ammo_cost; // enough ammo? pop ecx; retn; } @@ -158,34 +163,36 @@ tryAttack: } } -static DWORD __fastcall divide_burst_rounds_by_ammo_cost(fo::GameObject* weapon, register DWORD currAmmo, DWORD burstRounds) { - DWORD rounds = 1; // default multiply +/*** The return value should set the correct count of rounds for the burst calculated based on the cost ***/ +static long __fastcall divide_burst_rounds_by_ammo_cost(long currAmmo, fo::GameObject* weapon, long burstRounds) { + DWORD roundsCost = 1; // default burst cost if (HookScripts::IsInjectHook(HOOK_AMMOCOST)) { - rounds = burstRounds; // rounds in burst - AmmoCostHook_Script(2, weapon, rounds); + roundsCost = burstRounds; // rounds in burst (the number of rounds fired in the burst) + AmmoCostHook_Script(2, weapon, roundsCost); // roundsCost returns the new cost } - DWORD cost = burstRounds * rounds; // so much ammo is required for this burst + long cost = burstRounds * roundsCost; // amount of ammo required for this burst (multiplied by 1 or by the value returned from HOOK_AMMOCOST) if (cost > currAmmo) cost = currAmmo; // if cost ammo more than current ammo, set it to current - return (cost / rounds); // divide back to get proper number of rounds for damage calculations + return (cost / roundsCost); // divide back to get proper number of rounds for damage calculations } static void __declspec(naked) compute_spray_hack() { - __asm { - push edx; // weapon - push ecx; // current ammo in weapon - xchg ecx, edx; - push eax; // eax - rounds in burst attack, need to set ebp + __asm { // ebp = current ammo +// push edx; // weapon +// push ecx; // current ammo in weapon + push eax; // rounds in burst attack, need to set ebp call divide_burst_rounds_by_ammo_cost; - mov ebp, eax; // overwriten code - pop ecx; - pop edx; + mov ebp, eax; // overwriten code +// pop ecx; +// pop edx; retn; } } +//////////////////////////////////////////////////////////////////////////////// + static double ApplyModifiers(std::vector* mods, fo::GameObject* object, double val) { for (size_t i = 0; i < mods->size(); i++) { KnockbackModifier* mod = &(*mods)[i]; @@ -261,24 +268,32 @@ static void __declspec(naked) determine_to_hit_func_hack() { } } -static long __fastcall CheckDisableBurst(fo::GameObject* critter) { +bool Combat::IsBurstDisabled(fo::GameObject* critter) { for (size_t i = 0; i < noBursts.size(); i++) { - if (noBursts[i] == critter->id) { + if (noBursts[i] == critter->id) return true; + } + return false; +} + +static long __fastcall CheckDisableBurst(fo::GameObject* critter, fo::GameObject* weapon, fo::AIcap* cap) { + if (Combat::IsBurstDisabled(critter)) { + long anim = fo::func::item_w_anim_weap(weapon, fo::AttackType::ATKTYPE_RWEAPON_SECONDARY); + if (anim == fo::Animation::ANIM_fire_burst || anim == fo::Animation::ANIM_fire_continuous) { return 10; // Disable Burst (area_attack_mode - non-existent value) } } - return 0; + return cap->area_attack_mode; // default engine code } -static void __declspec(naked) ai_pick_hit_mode_hack_noSecondary() { +static void __declspec(naked) ai_pick_hit_mode_hack_noBurst() { __asm { - mov ebx, [eax + 0x94]; // cap->area_attack_mode push eax; push ecx; - mov ecx, esi; // source + push eax; // cap + mov edx, ebp; // weapon + mov ecx, esi; // source call CheckDisableBurst; - test eax, eax; - cmovnz ebx, eax; + mov ebx, eax; pop ecx; pop eax; retn; @@ -302,8 +317,8 @@ void __stdcall KnockbackSetMod(fo::GameObject* object, DWORD type, float val, DW } long id = (mode == 0) - ? Objects::SetSpecialID(object) - : Objects::SetObjectUniqueID(object); + ? Objects::SetSpecialID(object) + : Objects::SetObjectUniqueID(object); KnockbackModifier mod = { id, type, (double)val }; for (size_t i = 0; i < mods->size(); i++) { @@ -386,7 +401,7 @@ static void __declspec(naked) item_w_called_shot_hook() { static const DWORD aimedShotRet2 = 0x478EEA; __asm { push edx; - mov ecx, edx; // item + mov ecx, edx; // item call AimedShotTest; test eax, eax; jg force; @@ -432,50 +447,96 @@ void __stdcall ForceAimedShots(DWORD pid) { static void BodypartHitChances() { using fo::var::hit_location_penalty; - hit_location_penalty[0] = bodypartHit.Head; - hit_location_penalty[1] = bodypartHit.Left_Arm; - hit_location_penalty[2] = bodypartHit.Right_Arm; - hit_location_penalty[3] = bodypartHit.Torso; - hit_location_penalty[4] = bodypartHit.Right_Leg; - hit_location_penalty[5] = bodypartHit.Left_Leg; - hit_location_penalty[6] = bodypartHit.Eyes; - hit_location_penalty[7] = bodypartHit.Groin; - hit_location_penalty[8] = bodypartHit.Uncalled; + hit_location_penalty[0] = bodyPartHit.Head; + hit_location_penalty[1] = bodyPartHit.Left_Arm; + hit_location_penalty[2] = bodyPartHit.Right_Arm; + hit_location_penalty[3] = bodyPartHit.Torso; + hit_location_penalty[4] = bodyPartHit.Right_Leg; + hit_location_penalty[5] = bodyPartHit.Left_Leg; + hit_location_penalty[6] = bodyPartHit.Eyes; + hit_location_penalty[7] = bodyPartHit.Groin; + hit_location_penalty[8] = bodyPartHit.Uncalled; } static void BodypartHitReadConfig() { - bodypartHit.Head = static_cast(GetConfigInt("Misc", "BodyHit_Head", -40)); - bodypartHit.Left_Arm = static_cast(GetConfigInt("Misc", "BodyHit_Left_Arm", -30)); - bodypartHit.Right_Arm = static_cast(GetConfigInt("Misc", "BodyHit_Right_Arm", -30)); - bodypartHit.Torso = static_cast(GetConfigInt("Misc", "BodyHit_Torso", 0)); - bodypartHit.Right_Leg = static_cast(GetConfigInt("Misc", "BodyHit_Right_Leg", -20)); - bodypartHit.Left_Leg = static_cast(GetConfigInt("Misc", "BodyHit_Left_Leg", -20)); - bodypartHit.Eyes = static_cast(GetConfigInt("Misc", "BodyHit_Eyes", -60)); - bodypartHit.Groin = static_cast(GetConfigInt("Misc", "BodyHit_Groin", -30)); - bodypartHit.Uncalled = static_cast(GetConfigInt("Misc", "BodyHit_Torso_Uncalled", 0)); + bodyPartHit.Head = static_cast(IniReader::GetConfigInt("Misc", "BodyHit_Head", -40)); + bodyPartHit.Left_Arm = static_cast(IniReader::GetConfigInt("Misc", "BodyHit_Left_Arm", -30)); + bodyPartHit.Right_Arm = static_cast(IniReader::GetConfigInt("Misc", "BodyHit_Right_Arm", -30)); + bodyPartHit.Torso = static_cast(IniReader::GetConfigInt("Misc", "BodyHit_Torso", 0)); + bodyPartHit.Right_Leg = static_cast(IniReader::GetConfigInt("Misc", "BodyHit_Right_Leg", -20)); + bodyPartHit.Left_Leg = static_cast(IniReader::GetConfigInt("Misc", "BodyHit_Left_Leg", -20)); + bodyPartHit.Eyes = static_cast(IniReader::GetConfigInt("Misc", "BodyHit_Eyes", -60)); + bodyPartHit.Groin = static_cast(IniReader::GetConfigInt("Misc", "BodyHit_Groin", -30)); + bodyPartHit.Uncalled = static_cast(IniReader::GetConfigInt("Misc", "BodyHit_Torso_Uncalled", 0)); } static void __declspec(naked) ai_pick_hit_mode_hook_bodypart() { + using fo::Uncalled; __asm { - mov ebx, 8; // replace Body_Torso with Body_Uncalled + mov ebx, Uncalled; // replace Body_Torso with Body_Uncalled jmp fo::funcoffs::determine_to_hit_; } } +//////////////////////////////////////////////////////////////////////////////// + +static void __declspec(naked) apply_damage_hack_main() { + using namespace fo::Fields; + __asm { + mov edx, [eax + teamNum]; // ctd.target.team_num + mov ecx, [ebx + teamNum]; // ctd.source.team_num (attacker) + cmp edx, ecx; + jnz check; + retn; // skip combatai_check_retaliation_ +check: // does the target belong to the player's team? + test edx, edx; + jz dudeTeam; + retn; // call combatai_check_retaliation_ +dudeTeam: // check who the attacker was attacking + mov ecx, [esi + ctdMainTarget]; // ctd.mainTarget + cmp edx, [ecx + teamNum]; // dude.team_num == mainTarget.team_num? + jne skipSetHitTarget; // target is not main + or edx, 1; + retn; // call combatai_check_retaliation_ +skipSetHitTarget: + xor edx, edx; + retn; + } +} + +static void __declspec(naked) apply_damage_hook_extra() { + using namespace fo::Fields; + __asm { // eax - target1-6 + // does the target belong to the player's team? + test ebx, ebx; // target.team_num + jz dudeTeam; +default: + jmp fo::funcoffs::combatai_check_retaliation_; +dudeTeam: // check who the attacker was attacking + mov ecx, [esi + ctdMainTarget]; // ctd.mainTarget + cmp ebx, [ecx + teamNum]; // dude.team_num == mainTarget.team_num? + je default; + retn; + } +} + +//////////////////////////////////////////////////////////////////////////////// + +// Ray's combat_p_proc patch static void __declspec(naked) apply_damage_hack() { + using namespace fo::Fields; __asm { xor edx, edx; - inc edx; // COMBAT_SUBTYPE_WEAPON_USED - test [esi + 0x15], dl; // ctd.flags2Source & DAM_HIT_ - jz end; // no hit - inc edx; // COMBAT_SUBTYPE_HIT_SUCCEEDED + inc edx; // 1 - COMBAT_SUBTYPE_WEAPON_USED + test [esi + ctdAttackerFlags], dl; // ctd.flags2Source & DAM_HIT_ + jz end; // no hit + inc edx; // 2 - COMBAT_SUBTYPE_HIT_SUCCEEDED end: retn; } } -static void CombatProcFix() { - //Ray's combat_p_proc fix +static void CombatProcPatch() { dlog("Applying Ray's combat_p_proc patch.", DL_INIT); MakeCall(0x424DD9, apply_damage_hack); SafeWrite16(0x424DC6, 0x9090); @@ -495,7 +556,12 @@ static void Combat_OnGameLoad() { void Combat::init() { CombatBlock::init(); - CombatProcFix(); + + CombatProcPatch(); + + // Prevents NPC aggression when non-hostile NPCs accidentally hit the player or members of the player's team + MakeCall(0x424D6B, apply_damage_hack_main, 1); + HookCall(0x424E58, apply_damage_hook_extra); MakeCall(0x424B76, compute_damage_hack, 2); // KnockbackMod MakeJump(0x4136D3, compute_dmg_damage_hack); // for op_critter_dmg @@ -503,13 +569,14 @@ void Combat::init() { MakeCall(0x424791, determine_to_hit_func_hack); // HitChanceMod BlockCall(0x424796); - // Actually disables all secondary attacks for the critter, regardless of whether the weapon has a burst attack - MakeCall(0x429E44, ai_pick_hit_mode_hack_noSecondary, 1); // NoBurst + // Disables secondary burst attacks for the critter + MakeCall(0x429E44, ai_pick_hit_mode_hack_noBurst, 1); - if (GetConfigInt("Misc", "CheckWeaponAmmoCost", 0)) { + checkWeaponAmmoCost = (IniReader::GetConfigInt("Misc", "CheckWeaponAmmoCost", 0) != 0); + if (checkWeaponAmmoCost) { MakeCall(0x4234B3, compute_spray_hack, 1); HookCall(0x4266E9, combat_check_bad_shot_hook); - HookCall(0x429A37, ai_search_inven_weap_hook); + HookCall(0x429A37, ai_search_inven_weap_hook); // check if there is enough ammo to shoot HookCall(0x42A95D, ai_try_attack_hook); // jz func } @@ -521,8 +588,8 @@ void Combat::init() { // Remove the dependency of Body_Torso from Body_Uncalled SafeWrite8(0x423830, CodeType::JumpShort); // compute_attack_ BlockCall(0x42303F); // block Body_Torso check (combat_attack_) - SafeWrite8(0x42A713, 7); // Body_Uncalled > Body_Groin (ai_called_shot_) - SafeWriteBatch(8, bodypartAddr); // replace Body_Torso with Body_Uncalled + SafeWrite8(0x42A713, fo::BodyPart::Groin); // Body_Uncalled > Body_Groin (ai_called_shot_) + SafeWriteBatch(fo::BodyPart::Uncalled, bodypartAddr); // replace Body_Torso with Body_Uncalled HookCalls(ai_pick_hit_mode_hook_bodypart, {0x429E8C, 0x429ECC, 0x429F09}); LoadGameHook::OnGameReset() += Combat_OnGameLoad; diff --git a/sfall/Modules/Combat.h b/sfall/Modules/Combat.h index 1a0055ea..2ad8bdc0 100644 --- a/sfall/Modules/Combat.h +++ b/sfall/Modules/Combat.h @@ -23,16 +23,6 @@ namespace sfall { -class Combat : public Module { -public: - const char* name() { return "Combat"; } - void init(); - - static long determineHitChance; - - static DWORD __fastcall check_item_ammo_cost(fo::GameObject* weapon, DWORD hitMode); -}; - struct ChanceModifier { long id; int maximum; @@ -52,6 +42,18 @@ struct ChanceModifier { } }; +class Combat : public Module { +public: + const char* name() { return "Combat"; } + void init(); + + static long determineHitChance; + + static long __fastcall check_item_ammo_cost(fo::GameObject* weapon, fo::AttackType hitMode); + + static bool IsBurstDisabled(fo::GameObject* critter); +}; + void __stdcall SetHitChanceMax(fo::GameObject* critter, DWORD maximum, DWORD mod); void __stdcall KnockbackSetMod(fo::GameObject* object, DWORD type, float val, DWORD mode); void __stdcall KnockbackRemoveMod(fo::GameObject* object, DWORD mode); diff --git a/sfall/Modules/Console.cpp b/sfall/Modules/Console.cpp index eed99bff..f4622b26 100644 --- a/sfall/Modules/Console.cpp +++ b/sfall/Modules/Console.cpp @@ -48,7 +48,7 @@ static void __declspec(naked) ConsoleHook() { } void Console::init() { - auto path = GetConfigString("Misc", "ConsoleOutputPath", "", MAX_PATH); + auto path = IniReader::GetConfigString("Misc", "ConsoleOutputPath", "", MAX_PATH); if (!path.empty()) { consoleFile.open(path); if (consoleFile.is_open()) { diff --git a/sfall/Modules/Credits.cpp b/sfall/Modules/Credits.cpp index 3181da3d..9a4d537d 100644 --- a/sfall/Modules/Credits.cpp +++ b/sfall/Modules/Credits.cpp @@ -160,7 +160,7 @@ morelines: void Credits::init() { HookCalls(ShowCreditsHook, {0x480C49, 0x43F881}); - if (GetConfigInt("Misc", "CreditsAtBottom", 0)) { + if (IniReader::GetConfigInt("Misc", "CreditsAtBottom", 0)) { HookCall(0x42CB49, CreditsNextLineHook_Bottom); } else { HookCall(0x42CB49, CreditsNextLineHook_Top); diff --git a/sfall/Modules/Criticals.cpp b/sfall/Modules/Criticals.cpp index 75193d63..8c35abd2 100644 --- a/sfall/Modules/Criticals.cpp +++ b/sfall/Modules/Criticals.cpp @@ -89,7 +89,7 @@ static int CritTableLoad() { fo::CritInfo& newEffect = baseCritTable[newCritter][part][crit]; fo::CritInfo& defaultEffect = fo::var::crit_succ_eff[critter][part][crit]; for (int i = 0; i < 7; i++) { - newEffect.values[i] = iniGetInt(section, critNames[i], defaultEffect.values[i], critTableFile.c_str()); + newEffect.values[i] = IniReader::GetInt(section, critNames[i], defaultEffect.values[i], critTableFile.c_str()); if (isDebug) { char logmsg[256]; if (newEffect.values[i] != defaultEffect.values[i]) { @@ -114,11 +114,11 @@ static int CritTableLoad() { for (int critter = 0; critter < Criticals::critTableCount; critter++) { sprintf_s(buf, "c_%02d", critter); int all; - if (!(all = iniGetInt(buf, "Enabled", 0, critTableFile.c_str()))) continue; + if (!(all = IniReader::GetInt(buf, "Enabled", 0, critTableFile.c_str()))) continue; for (int part = 0; part < 9; part++) { if (all < 2) { sprintf_s(buf2, "Part_%d", part); - if (!iniGetInt(buf, buf2, 0, critTableFile.c_str())) continue; + if (!IniReader::GetInt(buf, buf2, 0, critTableFile.c_str())) continue; } sprintf_s(buf2, "c_%02d_%d", critter, part); @@ -126,7 +126,7 @@ static int CritTableLoad() { fo::CritInfo& effect = baseCritTable[critter][part][crit]; for (int i = 0; i < 7; i++) { sprintf_s(buf3, "e%d_%s", crit, critNames[i]); - effect.values[i] = iniGetInt(buf2, buf3, effect.values[i], critTableFile.c_str()); + effect.values[i] = IniReader::GetInt(buf2, buf3, effect.values[i], critTableFile.c_str()); } } } @@ -138,18 +138,6 @@ static int CritTableLoad() { return 0; } -enum BodyPart { - Head, - ArmLeft, - ArmRight, - Torso, - LegRight, - LegLeft, - Eyes, - Groin, - Uncalled -}; - enum CritParam { DmgMult, Flags, @@ -169,6 +157,7 @@ static void CriticalTableOverride() { SafeWrite32(0x423FB3, (DWORD)critTable); if (mode == 2 || mode == 3) { // bug fixes + using namespace fo; // Children SetEntry(2, LegRight, 1, FlagsFail, 0); SetEntry(2, LegRight, 1, Message, 5216); @@ -315,7 +304,7 @@ static void CriticalTableOverride() { #undef SetEntry static void RemoveCriticalTimeLimitsPatch() { - if (GetConfigInt("Misc", "RemoveCriticalTimelimits", 0)) { + if (IniReader::GetConfigInt("Misc", "RemoveCriticalTimelimits", 0)) { dlog("Removing critical time limits.", DL_INIT); SafeWrite8(0x424118, CodeType::JumpShort); // jump to 0x424131 SafeWriteBatch(0x9090, {0x4A3052, 0x4A3093}); @@ -324,10 +313,10 @@ static void RemoveCriticalTimeLimitsPatch() { } void Criticals::init() { - mode = GetConfigInt("Misc", "OverrideCriticalTable", 2); + mode = IniReader::GetConfigInt("Misc", "OverrideCriticalTable", 2); if (mode < 0 || mode > 3) mode = 0; if (mode) { - critTableFile += GetConfigString("Misc", "OverrideCriticalFile", "CriticalOverrides.ini", MAX_PATH); + critTableFile += IniReader::GetConfigString("Misc", "OverrideCriticalFile", "CriticalOverrides.ini", MAX_PATH); CriticalTableOverride(); LoadGameHook::OnBeforeGameStart() += []() { memcpy(critTable, baseCritTable, sizeof(critTable)); // Apply loaded critical table diff --git a/sfall/Modules/CritterStats.cpp b/sfall/Modules/CritterStats.cpp index da8f04f6..f5adcda0 100644 --- a/sfall/Modules/CritterStats.cpp +++ b/sfall/Modules/CritterStats.cpp @@ -426,12 +426,14 @@ void CritterStats::SaveStatData(HANDLE file) { for (size_t i = 0; i < count; i++) { WriteFile(file, &s_baseStatProto[i], 20, &sizeWrite, 0); } + fo::func::debug_printf("LOADSAVE: Total critter base stats saved: %d\n", count); count = s_bonusStatProto.size(); WriteFile(file, &count, 4, &sizeWrite, 0); for (size_t i = 0; i < count; i++) { WriteFile(file, &s_bonusStatProto[i], 20, &sizeWrite, 0); } + fo::func::debug_printf("LOADSAVE: Total critter bonus stats saved: %d\n", count); } bool CritterStats::LoadStatData(HANDLE file) { diff --git a/sfall/Modules/DamageMod.cpp b/sfall/Modules/DamageMod.cpp index 596eeb45..bcd84326 100644 --- a/sfall/Modules/DamageMod.cpp +++ b/sfall/Modules/DamageMod.cpp @@ -26,7 +26,6 @@ namespace sfall { -using namespace fo; int DamageMod::formula; @@ -284,6 +283,7 @@ void DamageMod::DamageYAAM(fo::ComputeAttackResult &ctd, DWORD &accumulatedDamag // Display melee damage w/o perk bonus static __declspec(naked) void MeleeDmgDisplayPrintFix_hook() { + using namespace fo; __asm { mov ecx, eax; // Store pointer to critter call fo::funcoffs::stat_level_; // Get Melee Damage @@ -303,6 +303,7 @@ static __declspec(naked) void MeleeDmgDisplayPrintFix_hook() { // Display max melee damage w/o perk bonus static __declspec(naked) void CommonDmgRngDispFix_hook() { + using namespace fo; __asm { mov ebx, eax; // Store pointer to critter call fo::funcoffs::stat_level_; // Get Melee Damage @@ -321,6 +322,7 @@ static __declspec(naked) void CommonDmgRngDispFix_hook() { } static __declspec(naked) void HtHDamageFix1a_hack() { + using namespace fo; __asm { cmp ecx, dword ptr ds:[FO_VAR_obj_dude]; // Is the critter == PC? je fix; // Skip if no @@ -337,6 +339,7 @@ fix: } static __declspec(naked) void HtHDamageFix1b_hook() { + using namespace fo; __asm { call fo::funcoffs::stat_level_; // Get Total_Melee_Damage cmp ecx, dword ptr ds:[FO_VAR_obj_dude]; // Is the critter == PC? @@ -355,6 +358,7 @@ fix: } static void __declspec(naked) DisplayBonusRangedDmg_hook() { + using namespace fo; __asm { mov edx, PERK_bonus_ranged_damage; mov eax, dword ptr ds:[FO_VAR_stack]; @@ -367,6 +371,7 @@ static void __declspec(naked) DisplayBonusRangedDmg_hook() { } static void __declspec(naked) DisplayBonusHtHDmg1_hook() { + using namespace fo; __asm { mov edx, PERK_bonus_hth_damage; mov eax, dword ptr ds:[FO_VAR_stack]; @@ -379,6 +384,7 @@ static void __declspec(naked) DisplayBonusHtHDmg1_hook() { static void __declspec(naked) DisplayBonusHtHDmg2_hack() { static const DWORD DisplayBonusHtHDmg2Exit = 0x47254E; + using namespace fo; __asm { mov ecx, eax; call fo::funcoffs::stat_level_; @@ -394,7 +400,7 @@ static void __declspec(naked) DisplayBonusHtHDmg2_hack() { } void DamageMod::init() { - if (formula = GetConfigInt("Misc", "DamageFormula", 0)) { + if (formula = IniReader::GetConfigInt("Misc", "DamageFormula", 0)) { switch (formula) { case 1: case 2: @@ -406,8 +412,8 @@ void DamageMod::init() { } } - int BonusHtHDmgFix = GetConfigInt("Misc", "BonusHtHDamageFix", 1); - int DisplayBonusDmg = GetConfigInt("Misc", "DisplayBonusDamage", 0); + int BonusHtHDmgFix = IniReader::GetConfigInt("Misc", "BonusHtHDamageFix", 1); + int DisplayBonusDmg = IniReader::GetConfigInt("Misc", "DisplayBonusDamage", 0); if (BonusHtHDmgFix) { dlog("Applying Bonus HtH Damage Perk fix.", DL_INIT); if (DisplayBonusDmg == 0) { // Subtract damage from perk bonus (vanilla displaying) diff --git a/sfall/Modules/DebugEditor.cpp b/sfall/Modules/DebugEditor.cpp index 57cbfe75..8b33af3d 100644 --- a/sfall/Modules/DebugEditor.cpp +++ b/sfall/Modules/DebugEditor.cpp @@ -313,7 +313,7 @@ hide: } static void __declspec(naked) art_data_size_hook() { - static char* artDbgMsg = "\nERROR: File not found: %s\n"; + static const char* artDbgMsg = "\nERROR: File not found: %s\n"; __asm { test edi, edi; jz artNotExist; @@ -340,7 +340,7 @@ display: } static void __declspec(naked) proto_load_pid_hack() { - static char* proDbgMsg = "\nERROR reading prototype file: %s\n"; + static const char* proDbgMsg = "\nERROR: Reading prototype file: %s\n"; __asm { mov dword ptr [esp + 0x120 - 0x1C + 4], -1; lea eax, [esp + 0x120 - 0x120 + 4]; // pro file @@ -373,23 +373,49 @@ static void __declspec(naked) debug_log_hack() { } } -const char* scrNameFmt = "\nScript: %s "; - static void __declspec(naked) debugMsg() { + static const char* scrNameFmt = "\nScript: %s "; __asm { mov edx, ds:[FO_VAR_currentProgram]; push [edx]; // script name push scrNameFmt; call fo::funcoffs::debug_printf_; add esp, 8; - jmp fo::funcoffs::debug_printf_; + jmp fo::funcoffs::debug_printf_; // ERROR: attempt to reference... } } -//static const DWORD addrNewLine[] = {0x50B244, 0x50B27C, 0x50B2B6, 0x50B2EE}; // ERROR: attempt to reference * var out of range: %d +static void __declspec(naked) combat_load_hack() { + static const char* msgCombat = "LOADSAVE: Object ID not found while loading the combat data.\n"; + __asm { + push msgCombat; + call fo::funcoffs::debug_printf_; + add esp, 4; + mov eax, -1; + retn; + } +} + +// Shifts the string one character to the right and inserts a newline control character at the beginning +static void MoveDebugString(char* messageAddr) { + int i = 0; + do { + messageAddr[i + 1] = messageAddr[i]; + i--; + } while (messageAddr[i] != '\0'); + messageAddr[i + 1] = '\n'; +} + +static const DWORD addrDotChar[] = { + 0x50B244, 0x50B27C, 0x50B2B6, 0x50B2EE // "ERROR: attempt to reference * var out of range: %d" +}; + +static const DWORD addrNewLineChar[] = { + 0x500A64, // "Friendly was in the way!" +}; static void DebugModePatch() { - int dbgMode = iniGetInt("Debugging", "DebugMode", 0, ::sfall::ddrawIni); + int dbgMode = IniReader::GetIntDefaultConfig("Debugging", "DebugMode", 0); if (dbgMode > 0) { dlog("Applying debugmode patch.", DL_INIT); // If the player is using an exe with the debug patch already applied, just skip this block without erroring @@ -411,7 +437,7 @@ static void DebugModePatch() { } else { SafeWrite32(0x4C6D9C, (DWORD)debugGnw); } - if (iniGetInt("Debugging", "HideObjIsNullMsg", 0, ::sfall::ddrawIni)) { + if (IniReader::GetIntDefaultConfig("Debugging", "HideObjIsNullMsg", 0)) { MakeJump(0x453FD2, dbg_error_hack); } // prints a debug message about a missing critter art file to both debug.log and the message window in sfall debugging mode @@ -430,36 +456,64 @@ static void DebugModePatch() { SafeWrite8(0x4DC34D, 15); // Fix the format of some debug messages - //SafeWriteBatch(0xA, addrNewLine); + SafeWriteBatch('\n', addrNewLineChar); + SafeWriteBatch('.', addrDotChar); HookCalls(debugMsg, { 0x482240, // map_set_global_var_ 0x482274, // map_get_global_var_ 0x4822A0, // map_set_local_var_ 0x4822D4 // map_get_local_var_ }); - + if (dbgMode != 1) { + MoveDebugString((char*)0x500A9B); // "computing attack..." + } dlogr(" Done", DL_INIT); } } static void DontDeleteProtosPatch() { - if (iniGetInt("Debugging", "DontDeleteProtos", 0, ::sfall::ddrawIni)) { + if (IniReader::GetIntDefaultConfig("Debugging", "DontDeleteProtos", 0)) { dlog("Applying permanent protos patch.", DL_INIT); SafeWrite8(0x48007E, CodeType::JumpShort); dlogr(" Done", DL_INIT); } } +/* +void CheckTimerResolution() { + DWORD ticksList[50]; + DWORD old_ticks = GetTickCount(); + for (size_t i = 0; i < 50;) { + DWORD ticks = GetTickCount(); + if (ticks != old_ticks) { + old_ticks = ticks; + ticksList[i++] = ticks; + } + } + int min = 100, max = 0; + for (size_t i = 0; i < 49; i++) { + int ms = ticksList[i + 1] - ticksList[i]; + if (ms < min) min = ms; + if (ms > max) max = ms; + } + fo::func::debug_printf("System timer resolution: %d - %d ms.\n", min, max); +} +*/ + void DebugEditor::init() { DebugModePatch(); // Notifies and prints a debug message about a corrupted proto file to debug.log MakeCall(0x4A1D73, proto_load_pid_hack, 6); + // Prints a debug message about a missing combat object to debug.log + MakeCalls(combat_load_hack, {0x421146, 0x421189, 0x4211CC}); + if (!isDebug) SafeWriteBatch(0x909008EB, {0x42114B, 0x42118E, 0x4211D1}); // jmp $+8 + if (!isDebug) return; DontDeleteProtosPatch(); - debugEditorKey = GetConfigInt("Input", "DebugEditorKey", 0); + debugEditorKey = IniReader::GetConfigInt("Input", "DebugEditorKey", 0); if (debugEditorKey != 0) { OnKeyPressed() += [](DWORD scanCode, bool pressed) { if (scanCode == debugEditorKey && pressed && IsGameLoaded()) { diff --git a/sfall/Modules/Drugs.cpp b/sfall/Modules/Drugs.cpp index 36c93c7a..999107ad 100644 --- a/sfall/Modules/Drugs.cpp +++ b/sfall/Modules/Drugs.cpp @@ -282,14 +282,14 @@ long Drugs::SetDrugAddictTimeOff(long pid, long time) { } void Drugs::init() { - auto drugsFile = GetConfigString("Misc", "DrugsFile", "", MAX_PATH); + auto drugsFile = IniReader::GetConfigString("Misc", "DrugsFile", "", MAX_PATH); if (!drugsFile.empty()) { dlog("Applying drugs patch...", DL_INIT); const char* iniDrugs = drugsFile.insert(0, ".\\").c_str(); - if (iniGetInt("main", "JetWithdrawal", 0, iniDrugs) == 1) SafeWrite8(0x47A3A8, 0); + if (IniReader::GetInt("main", "JetWithdrawal", 0, iniDrugs) == 1) SafeWrite8(0x47A3A8, 0); - int count = iniGetInt("main", "Count", 0, iniDrugs); + int count = IniReader::GetInt("main", "Count", 0, iniDrugs); if (count > 0) { if (count > drugsMax) count = drugsMax; drugs = new sDrugs[count](); @@ -298,12 +298,12 @@ void Drugs::init() { char section[4]; for (int i = 1; i <= count; i++) { _itoa(i, section, 10); - int pid = iniGetInt(section, "PID", 0, iniDrugs); + int pid = IniReader::GetInt(section, "PID", 0, iniDrugs); if (pid > 0) { CheckEngineNumEffects(set, pid); drugs[drugsCount].drugPid = pid; - drugs[drugsCount].addictTimeOff = drugs[drugsCount].iniAddictTimeOff = iniGetInt(section, "AddictTime", 0, iniDrugs); - long ef = iniGetInt(section, "NumEffects", -1, iniDrugs); + drugs[drugsCount].addictTimeOff = drugs[drugsCount].iniAddictTimeOff = IniReader::GetInt(section, "AddictTime", 0, iniDrugs); + long ef = IniReader::GetInt(section, "NumEffects", -1, iniDrugs); if (set != -1) { if (ef < -1) { ef = -1; @@ -317,12 +317,12 @@ void Drugs::init() { drugs[drugsCount].numEffects = ef; // -1 to use the value from the engine } else { drugs[drugsCount].numEffects = drugs[drugsCount].iniNumEffects = max(0, ef); - int gvar = iniGetInt(section, "GvarID", 0, iniDrugs); + int gvar = IniReader::GetInt(section, "GvarID", 0, iniDrugs); drugs[drugsCount].gvarID = max(0, gvar); // not allow negative values if (gvar) { - int msg = iniGetInt(section, "TextID", -1, iniDrugs); + int msg = IniReader::GetInt(section, "TextID", -1, iniDrugs); drugs[drugsCount].msgID = (msg > 0) ? msg : -1; - drugs[drugsCount].frmID = iniGetInt(section, "FrmID", -1, iniDrugs); + drugs[drugsCount].frmID = IniReader::GetInt(section, "FrmID", -1, iniDrugs); addictionGvarCount++; } } diff --git a/sfall/Modules/Elevators.cpp b/sfall/Modules/Elevators.cpp index 47cfd48b..57141675 100644 --- a/sfall/Modules/Elevators.cpp +++ b/sfall/Modules/Elevators.cpp @@ -116,23 +116,23 @@ static void LoadElevators(const char* elevFile) { if (elevFile && GetFileAttributes(elevFile) != INVALID_FILE_ATTRIBUTES) { for (int i = 0; i < elevatorCount; i++) { _itoa_s(i, section, 10); - int type = iniGetInt(section, "Image", elevatorType[i], elevFile); + int type = IniReader::GetInt(section, "Image", elevatorType[i], elevFile); elevatorType[i] = min(type, elevatorCount - 1); if (i >= vanillaElevatorCount) { - int cBtn = iniGetInt(section, "ButtonCount", 2, elevFile); + int cBtn = IniReader::GetInt(section, "ButtonCount", 2, elevFile); if (cBtn < 2) cBtn = 2; elevatorsBtnCount[i] = min(cBtn, exitsPerElevator); } - elevatorsFrms[i].main = iniGetInt(section, "MainFrm", elevatorsFrms[i].main, elevFile); - elevatorsFrms[i].buttons = iniGetInt(section, "ButtonsFrm", elevatorsFrms[i].buttons, elevFile); + elevatorsFrms[i].main = IniReader::GetInt(section, "MainFrm", elevatorsFrms[i].main, elevFile); + elevatorsFrms[i].buttons = IniReader::GetInt(section, "ButtonsFrm", elevatorsFrms[i].buttons, elevFile); char setting[32]; for (int j = 0; j < exitsPerElevator; j++) { sprintf(setting, "ID%d", j + 1); - elevatorExits[i][j].id = iniGetInt(section, setting, elevatorExits[i][j].id, elevFile); + elevatorExits[i][j].id = IniReader::GetInt(section, setting, elevatorExits[i][j].id, elevFile); sprintf(setting, "Elevation%d", j + 1); - elevatorExits[i][j].elevation = iniGetInt(section, setting, elevatorExits[i][j].elevation, elevFile); + elevatorExits[i][j].elevation = IniReader::GetInt(section, setting, elevatorExits[i][j].elevation, elevFile); sprintf(setting, "Tile%d", j + 1); - elevatorExits[i][j].tile = iniGetInt(section, setting, elevatorExits[i][j].tile, elevFile); + elevatorExits[i][j].tile = IniReader::GetInt(section, setting, elevatorExits[i][j].tile, elevFile); } } } @@ -159,7 +159,7 @@ static void ElevatorsInit() { } void Elevators::init() { - auto elevPath = GetConfigString("Misc", "ElevatorsFile", "", MAX_PATH); + auto elevPath = IniReader::GetConfigString("Misc", "ElevatorsFile", "", MAX_PATH); if (!elevPath.empty()) { dlog("Applying elevator patch.", DL_INIT); ElevatorsInit(); diff --git a/sfall/Modules/Explosions.cpp b/sfall/Modules/Explosions.cpp index c9c175d9..731d2fbf 100644 --- a/sfall/Modules/Explosions.cpp +++ b/sfall/Modules/Explosions.cpp @@ -349,11 +349,11 @@ static void SetExplosionRadius(int arg1, int arg2) { static void SetExplosionDamage(int pid, int min, int max) { explosionsDamageReset = true; switch (pid) { - case fo::ProtoId::PID_DYNAMITE: + case fo::ProtoID::PID_DYNAMITE: SafeWrite32(dynamite_min_dmg_addr, min); SafeWrite32(dynamite_max_dmg_addr, max); break; - case fo::ProtoId::PID_PLASTIC_EXPLOSIVES: + case fo::ProtoID::PID_PLASTIC_EXPLOSIVES: SafeWrite32(plastic_min_dmg_addr, min); SafeWrite32(plastic_max_dmg_addr, max); break; @@ -363,11 +363,11 @@ static void SetExplosionDamage(int pid, int min, int max) { static int GetExplosionDamage(int pid) { DWORD min = 0, max = 0; switch (pid) { - case fo::ProtoId::PID_DYNAMITE: + case fo::ProtoID::PID_DYNAMITE: min = *(DWORD*)dynamite_min_dmg_addr; max = *(DWORD*)dynamite_max_dmg_addr; break; - case fo::ProtoId::PID_PLASTIC_EXPLOSIVES: + case fo::ProtoID::PID_PLASTIC_EXPLOSIVES: min = *(DWORD*)plastic_min_dmg_addr; max = *(DWORD*)plastic_max_dmg_addr; break; @@ -422,10 +422,10 @@ int __stdcall ExplosionsMetaruleFunc(int mode, int arg1, int arg2) { case EXPL_GET_EXPLOSION_DAMAGE: return GetExplosionDamage(arg1); case EXPL_SET_DYNAMITE_EXPLOSION_DAMAGE: - SetExplosionDamage(fo::ProtoId::PID_DYNAMITE, arg1, arg2); + SetExplosionDamage(fo::ProtoID::PID_DYNAMITE, arg1, arg2); return 0; case EXPL_SET_PLASTIC_EXPLOSION_DAMAGE: - SetExplosionDamage(fo::ProtoId::PID_PLASTIC_EXPLOSIVES, arg1, arg2); + SetExplosionDamage(fo::ProtoID::PID_PLASTIC_EXPLOSIVES, arg1, arg2); return 0; case EXPL_SET_EXPLOSION_MAX_TARGET: if (arg1 > 0 && arg1 < 7) { @@ -481,7 +481,7 @@ static void ResetExplosionDamage() { void Explosions::init() { MakeJump(0x411AB4, explosion_effect_hook); // required for explosions_metarule - lightingEnabled = GetConfigInt("Misc", "ExplosionsEmitLight", 0) != 0; + lightingEnabled = IniReader::GetConfigInt("Misc", "ExplosionsEmitLight", 0) != 0; if (lightingEnabled) { dlog("Applying Explosion changes.", DL_INIT); MakeJump(0x4118E1, ranged_attack_lighting_fix); diff --git a/sfall/Modules/ExtraSaveSlots.cpp b/sfall/Modules/ExtraSaveSlots.cpp index 46431f88..78faa621 100644 --- a/sfall/Modules/ExtraSaveSlots.cpp +++ b/sfall/Modules/ExtraSaveSlots.cpp @@ -59,11 +59,11 @@ void LoadPageOffsets() { sprintf_s(LoadPath, MAX_PATH, filename, fo::var::patches); - fo::var::slot_cursor = iniGetInt("POSITION", "ListNum", 0, LoadPath); + fo::var::slot_cursor = IniReader::GetInt("POSITION", "ListNum", 0, LoadPath); if (fo::var::slot_cursor > 9) { fo::var::slot_cursor = 0; } - LSPageOffset = iniGetInt("POSITION", "PageOffset", 0, LoadPath); + LSPageOffset = IniReader::GetInt("POSITION", "PageOffset", 0, LoadPath); if (LSPageOffset > 9990) { LSPageOffset = 0; } @@ -437,8 +437,8 @@ static DWORD __stdcall QuickSaveGame(fo::DbFile* file, char* filename) { FILETIME ftCurrSlot; GetSaveFileTime(filename, &ftCurrSlot); - if (currSlot == 0 || ftCurrSlot.dwHighDateTime > ftPrevSlot.dwHighDateTime - || (ftCurrSlot.dwHighDateTime == ftPrevSlot.dwHighDateTime && ftCurrSlot.dwLowDateTime > ftPrevSlot.dwLowDateTime)) + if (currSlot == 0 || ftCurrSlot.dwHighDateTime > ftPrevSlot.dwHighDateTime || + (ftCurrSlot.dwHighDateTime == ftPrevSlot.dwHighDateTime && ftCurrSlot.dwLowDateTime > ftPrevSlot.dwLowDateTime)) { ftPrevSlot.dwHighDateTime = ftCurrSlot.dwHighDateTime; ftPrevSlot.dwLowDateTime = ftCurrSlot.dwLowDateTime; @@ -483,20 +483,20 @@ static void __declspec(naked) SaveGame_hack1() { } void ExtraSaveSlots::init() { - bool extraSaveSlots = (GetConfigInt("Misc", "ExtraSaveSlots", 0) != 0); + bool extraSaveSlots = (IniReader::GetConfigInt("Misc", "ExtraSaveSlots", 0) != 0); if (extraSaveSlots) { dlog("Applying extra save slots patch.", DL_INIT); EnableSuperSaving(); dlogr(" Done", DL_INIT); } - autoQuickSave = GetConfigInt("Misc", "AutoQuickSave", 0); + autoQuickSave = IniReader::GetConfigInt("Misc", "AutoQuickSave", 0); if (autoQuickSave > 0) { dlog("Applying auto quick save patch.", DL_INIT); if (autoQuickSave > 10) autoQuickSave = 10; autoQuickSave--; // reserved slot count - quickSavePage = GetConfigInt("Misc", "AutoQuickSavePage", 0); + quickSavePage = IniReader::GetConfigInt("Misc", "AutoQuickSavePage", 0); if (quickSavePage > 1000) quickSavePage = 1000; if (extraSaveSlots && quickSavePage > 0) { diff --git a/sfall/Modules/FileSystem.cpp b/sfall/Modules/FileSystem.cpp index b52ef409..cc8808f0 100644 --- a/sfall/Modules/FileSystem.cpp +++ b/sfall/Modules/FileSystem.cpp @@ -540,7 +540,7 @@ DWORD __stdcall FScopy(const char* path, const char* source) { DWORD fsize; sFile* file; - const char* mode = "r"; + const char* mode = "rb"; // was 'r' __asm { mov eax, source; mov edx, mode; @@ -705,7 +705,7 @@ bool FileSystem::IsEmpty() { } void FileSystem::init() { - if (GetConfigInt("Misc", "UseFileSystemOverride", 0)) { + if (IniReader::GetConfigInt("Misc", "UseFileSystemOverride", 0)) { FileSystemOverride(); UsingFileSystem = true; } diff --git a/sfall/Modules/Graphics.cpp b/sfall/Modules/Graphics.cpp index f6552c53..173074fc 100644 --- a/sfall/Modules/Graphics.cpp +++ b/sfall/Modules/Graphics.cpp @@ -1062,7 +1062,9 @@ public: AdjustWindowRect(&r, windowStyle, false); r.right -= r.left; r.bottom -= r.top; - SetWindowPos(a, HWND_NOTOPMOST, windowLeft, windowTop, r.right, r.bottom, SWP_DRAWFRAME | SWP_FRAMECHANGED | SWP_SHOWWINDOW); + if (!SetWindowPos(a, HWND_NOTOPMOST, windowLeft, windowTop, r.right, r.bottom, SWP_DRAWFRAME | SWP_FRAMECHANGED | SWP_SHOWWINDOW)) { + windowLeft = windowTop = 0; // fail to set position + } } dlogr(" Done", DL_MAIN); @@ -1109,21 +1111,21 @@ HRESULT __stdcall InitFakeDirectDrawCreate(void*, IDirectDraw** b, void*) { gWidth = dispMode.Width; gHeight = dispMode.Height; } else { - gWidth = GetConfigInt("Graphics", "GraphicsWidth", 0); - gHeight = GetConfigInt("Graphics", "GraphicsHeight", 0); + gWidth = IniReader::GetConfigInt("Graphics", "GraphicsWidth", 0); + gHeight = IniReader::GetConfigInt("Graphics", "GraphicsHeight", 0); if (!gWidth || !gHeight) { gWidth = ResWidth; gHeight = ResHeight; } } - Graphics::GPUBlt = GetConfigInt("Graphics", "GPUBlt", 0); // 0 - auto, 1 - GPU, 2 - CPU + Graphics::GPUBlt = IniReader::GetConfigInt("Graphics", "GPUBlt", 0); // 0 - auto, 1 - GPU, 2 - CPU if (!Graphics::GPUBlt || Graphics::GPUBlt > 2) Graphics::GPUBlt = 2; // Swap them around to keep compatibility with old ddraw.ini else if (Graphics::GPUBlt == 2) Graphics::GPUBlt = 0; // Use CPU if (Graphics::mode == 5) { - moveWindowKey[0] = GetConfigInt("Input", "WindowScrollKey", 0); + moveWindowKey[0] = IniReader::GetConfigInt("Input", "WindowScrollKey", 0); if (moveWindowKey[0] < 0) { switch (moveWindowKey[0]) { case -1: @@ -1144,7 +1146,7 @@ HRESULT __stdcall InitFakeDirectDrawCreate(void*, IDirectDraw** b, void*) { } else { moveWindowKey[0] &= 0xFF; } - windowData = GetConfigInt("Graphics", "WindowData", 0); + windowData = IniReader::GetConfigInt("Graphics", "WindowData", 0); if (windowData > 0) { windowLeft = windowData >> 16; windowTop = windowData & 0xFFFF; @@ -1183,7 +1185,7 @@ static __declspec(naked) void game_init_hook() { } void Graphics::init() { - Graphics::mode = GetConfigInt("Graphics", "Mode", 0); + Graphics::mode = IniReader::GetConfigInt("Graphics", "Mode", 0); if (Graphics::mode == 6) { windowStyle = WS_OVERLAPPED; } else if (Graphics::mode != 4 && Graphics::mode != 5) { @@ -1196,7 +1198,7 @@ void Graphics::init() { HMODULE h = LoadLibraryEx(_DLL_NAME, 0, LOAD_LIBRARY_AS_DATAFILE); if (!h) { MessageBoxA(0, "You have selected DirectX graphics mode, but " _DLL_NAME " is missing.\n" - "Switch back to mode 0, or install an up to date version of DirectX.", "Error", MB_TASKMODAL | MB_ICONERROR); + "Switch back to mode 0, or install an up to date version of DirectX.", "Error", MB_TASKMODAL | MB_ICONERROR); #undef _DLL_NAME ExitProcess(-1); } else { @@ -1205,7 +1207,10 @@ void Graphics::init() { SafeWrite8(0x50FB6B, '2'); // Set call DirectDrawCreate2 HookCall(0x44260C, game_init_hook); - textureFilter = GetConfigInt("Graphics", "TextureFilter", 1); + // Patch HRP to show the mouse cursor over the window title + if (Graphics::mode == 5 && hrpVersionValid) SafeWrite8(HRPAddress(0x10027142), CodeType::JumpShort); + + textureFilter = IniReader::GetConfigInt("Graphics", "TextureFilter", 1); dlogr(" Done", DL_INIT); } @@ -1214,9 +1219,10 @@ void Graphics::init() { void Graphics::exit() { if (Graphics::mode) { - if (Graphics::mode == 5) { - int data = windowTop | (windowLeft << 16); - if (data >= 0 && data != windowData) SetConfigInt("Graphics", "WindowData", data); + RECT rect; + if (Graphics::mode == 5 && GetWindowRect(window, &rect)) { + int data = rect.top | (rect.left << 16); + if (data >= 0 && data != windowData) IniReader::SetConfigInt("Graphics", "WindowData", data); } CoUninitialize(); } diff --git a/sfall/Modules/HeroAppearance.cpp b/sfall/Modules/HeroAppearance.cpp index a38f10c0..942c5c63 100644 --- a/sfall/Modules/HeroAppearance.cpp +++ b/sfall/Modules/HeroAppearance.cpp @@ -16,15 +16,13 @@ * along with this program. If not, see . */ -#include - #include "..\main.h" #include "..\FalloutEngine\Fallout2.h" -#include "..\FalloutEngine\EngineUtils.h" +#include "..\Translate.h" + #include "Inventory.h" #include "LoadGameHook.h" #include "LoadOrder.h" -#include "Message.h" #include "PartyControl.h" #include "ScriptExtender.h" @@ -35,8 +33,6 @@ namespace sfall { -using namespace fo; - bool HeroAppearance::appModEnabled = false; // check if Appearance mod enabled for script functions const char* appearancePathFmt = "Appearance\\h%cR%02dS%02d%s"; @@ -69,7 +65,7 @@ typedef struct LineNode { } } LineNode; -/////////////////////////////////////////////////////////////////TEXT FUNCTIONS////////////////////////////////////////////////////////////////////// +//////////////////////////////// TEXT FUNCTIONS //////////////////////////////// static void SetFont(long ref) { fo::func::text_font(ref); @@ -132,7 +128,7 @@ static void DeleteWordWrapList(LineNode *CurrentLine) { } } -/////////////////////////////////////////////////////////////////DAT FUNCTIONS/////////////////////////////////////////////////////////////////////// +//////////////////////////////// DAT FUNCTIONS ///////////////////////////////// static void* LoadDat(const char* fileName) { return fo::func::dbase_open(fileName); @@ -142,13 +138,13 @@ static void UnloadDat(void* dat) { fo::func::dbase_close(dat); } -/////////////////////////////////////////////////////////////////OTHER FUNCTIONS///////////////////////////////////////////////////////////////////// +/////////////////////////////// OTHER FUNCTIONS //////////////////////////////// static DWORD BuildFrmId(DWORD lstRef, DWORD lstNum) { return (lstRef << 24) | lstNum; } -/////////////////////////////////////////////////////////////////APP MOD FUNCTIONS/////////////////////////////////////////////////////////////////// +////////////////////////////// APP MOD FUNCTIONS /////////////////////////////// static char GetSex() { return (fo::HeroIsFemale()) ? 'F' : 'M'; @@ -180,11 +176,11 @@ static __declspec(noinline) int __stdcall LoadHeroDat(unsigned int race, unsigne } const char sex = GetSex(); - bool folderIsExist = false, heroDatIsExist = false; + bool folderExists = false, heroDatExists = false; // check if folder exists for selected appearance sprintf_s(heroPathPtr[0]->path, 64, appearancePathFmt, sex, race, style, ""); if (GetFileAttributes(heroPathPtr[0]->path) != INVALID_FILE_ATTRIBUTES) { - folderIsExist = true; + folderExists = true; } // check if Dat exists for selected appearance sprintf_s(heroPathPtr[1]->path, 64, appearancePathFmt, sex, race, style, ".dat"); @@ -194,21 +190,21 @@ static __declspec(noinline) int __stdcall LoadHeroDat(unsigned int race, unsigne heroPathPtr[1]->pDat = LoadDat(heroPathPtr[1]->path); heroPathPtr[1]->isDat = 1; } - if (folderIsExist) heroPathPtr[0]->next = heroPathPtr[1]; - heroDatIsExist = true; - } else if (!folderIsExist) { + if (folderExists) heroPathPtr[0]->next = heroPathPtr[1]; + heroDatExists = true; + } else if (!folderExists) { return -1; // no .dat files and folder } - heroAppPaths = &heroPathPtr[1 - folderIsExist]; // set path for selected appearance - heroPathPtr[0 + heroDatIsExist]->next = &fo::var::paths[0]; // heroPathPtr[] >> foPaths + heroAppPaths = &heroPathPtr[1 - folderExists]; // set path for selected appearance + heroPathPtr[0 + heroDatExists]->next = &fo::var::paths[0]; // heroPathPtr[] >> foPaths if (style != 0) { - bool raceDatIsExist = false, folderIsExist = false; + bool raceDatExists = false, folderExists = false; // check if folder exists for selected race base appearance sprintf_s(racePathPtr[0]->path, 64, appearancePathFmt, sex, race, 0, ""); if (GetFileAttributes(racePathPtr[0]->path) != INVALID_FILE_ATTRIBUTES) { - folderIsExist = true; + folderExists = true; } // check if Dat (or folder) exists for selected race base appearance sprintf_s(racePathPtr[1]->path, 64, appearancePathFmt, sex, race, 0, ".dat"); @@ -218,14 +214,14 @@ static __declspec(noinline) int __stdcall LoadHeroDat(unsigned int race, unsigne racePathPtr[1]->pDat = LoadDat(racePathPtr[1]->path); racePathPtr[1]->isDat = 1; } - if (folderIsExist) racePathPtr[0]->next = racePathPtr[1]; - raceDatIsExist = true; - } else if (!folderIsExist) { + if (folderExists) racePathPtr[0]->next = racePathPtr[1]; + raceDatExists = true; + } else if (!folderExists) { return 0; } - heroPathPtr[0 + heroDatIsExist]->next = racePathPtr[1 - folderIsExist]; // set path for selected race base appearance - racePathPtr[0 + raceDatIsExist]->next = &fo::var::paths[0]; // insert racePathPtr in chain path: heroPathPtr[] >> racePathPtr[] >> foPaths + heroPathPtr[0 + heroDatExists]->next = racePathPtr[1 - folderExists]; // set path for selected race base appearance + racePathPtr[0 + raceDatExists]->next = &fo::var::paths[0]; // insert racePathPtr in chain path: heroPathPtr[] >> racePathPtr[] >> foPaths } return 0; } @@ -336,7 +332,7 @@ static long __stdcall AddHeroCritNames() { // art_init_ critterListSize = critterArt.total / 2; if (critterListSize > 2048) { MessageBoxA(0, "This mod cannot be used because the maximum limit of the FID count in the critters.lst is exceeded.\n" - "Please disable the mod and restart the game.", "Hero Appearance mod", MB_TASKMODAL | MB_ICONERROR); + "Please disable the mod and restart the game.", "Hero Appearance mod", MB_TASKMODAL | MB_ICONERROR); ExitProcess(-1); } critterArraySize = critterListSize * 13; @@ -360,7 +356,7 @@ static void DoubleArtAlias() { std::memcpy(crittersAliasData + critterListSize, crittersAliasData, critterListSize * 4); } -///////////////////////////////////////////////////////////////GRAPHICS HERO FUNCTIONS/////////////////////////////////////////////////////////////// +/////////////////////////// GRAPHICS HERO FUNCTIONS //////////////////////////// static void DrawPC() { fo::RedrawObject(fo::var::obj_dude); @@ -488,7 +484,7 @@ endFunc: } } -/////////////////////////////////////////////////////////////////INTERFACE FUNCTIONS///////////////////////////////////////////////////////////////// +///////////////////////////// INTERFACE FUNCTIONS ////////////////////////////// static void surface_draw(long width, long height, long fromWidth, long fromX, long fromY, BYTE *fromBuff, long toWidth, long toX, long toY, BYTE *toBuff, int maskRef) @@ -580,8 +576,8 @@ static void DrawCharNote(bool style, int winRef, DWORD xPosWin, DWORD yPosWin, B char *MsgFileName = (style) ? "game\\AppStyle.msg" : "game\\AppRace.msg"; if (fo::func::message_load(&MsgList, MsgFileName) == 1) { - TitleMsg = GetMsg(&MsgList, 100, 2); - InfoMsg = GetMsg(&MsgList, 101, 2); + TitleMsg = fo::GetMsg(&MsgList, 100, 2); + InfoMsg = fo::GetMsg(&MsgList, 101, 2); } fo::Window *winInfo = fo::func::GNW_find(winRef); @@ -589,7 +585,7 @@ static void DrawCharNote(bool style, int winRef, DWORD xPosWin, DWORD yPosWin, B BYTE *PadSurface = new BYTE [280 * 168]; surface_draw(280, 168, widthBG, xPosBG, yPosBG, BGSurface, 280, 0, 0, PadSurface); - UnlistedFrm *frm = LoadUnlistedFrm((style) ? "AppStyle.frm" : "AppRace.frm", fo::OBJ_TYPE_SKILLDEX); + fo::UnlistedFrm *frm = LoadUnlistedFrm((style) ? "AppStyle.frm" : "AppRace.frm", fo::OBJ_TYPE_SKILLDEX); if (frm) { fo::DrawToSurface(frm->frames[0].width, frm->frames[0].height, 0, 0, frm->frames[0].width, frm->frames[0].indexBuff, 136, 37, 280, 168, PadSurface, 0); // cover buttons pics bottom delete frm; @@ -657,7 +653,7 @@ static void __stdcall DrawCharNoteNewChar(bool type) { void __stdcall HeroSelectWindow(int raceStyleFlag) { if (!HeroAppearance::appModEnabled) return; - UnlistedFrm *frm = LoadUnlistedFrm("AppHeroWin.frm", fo::OBJ_TYPE_INTRFACE); + fo::UnlistedFrm *frm = LoadUnlistedFrm("AppHeroWin.frm", fo::OBJ_TYPE_INTRFACE); if (frm == nullptr) { fo::func::debug_printf("\nApperanceMod: art\\intrface\\AppHeroWin.frm file not found."); return; @@ -702,21 +698,32 @@ void __stdcall HeroSelectWindow(int raceStyleFlag) { int oldFont = GetFont(); SetFont(0x67); - char titleText[16]; - // Get alternate text from ini if available - if (isStyle) { - Translate("AppearanceMod", "StyleText", "Style", titleText, 16); + char *RaceStyleBtn, *DoneBtn; + fo::MessageList MsgList; + + if (fo::func::message_load(&MsgList, "game\\AppIface.msg") == 1) { + RaceStyleBtn = fo::GetMsg(&MsgList, (isStyle) ? 101 : 100, 2); + DoneBtn = fo::GetMsg(&MsgList, 102, 2); } else { - Translate("AppearanceMod", "RaceText", "Race", titleText, 16); + // Get alternate text from ini if available (TODO: remove this in the future) + char titleText[16]; + char doneText[16]; + if (isStyle) { + Translate::Get("AppearanceMod", "StyleText", "Style", titleText, 16); + } else { + Translate::Get("AppearanceMod", "RaceText", "Race", titleText, 16); + } + Translate::Get("AppearanceMod", "DoneBtn", "Done", doneText, 16); + RaceStyleBtn = titleText; + DoneBtn = doneText; } BYTE textColour = fo::var::PeanutButter; // PeanutButter colour - palette offset stored in mem - DWORD titleTextWidth = fo::GetTextWidth(titleText); - fo::PrintText(titleText, textColour, 92 - titleTextWidth / 2, 10, titleTextWidth, 484, mainSurface); + DWORD titleTextWidth = fo::GetTextWidth(RaceStyleBtn); + fo::PrintText(RaceStyleBtn, textColour, 92 - titleTextWidth / 2, 10, titleTextWidth, 484, mainSurface); - Translate("AppearanceMod", "DoneBtn", "Done", titleText, 16); - titleTextWidth = fo::GetTextWidth(titleText); - fo::PrintText(titleText, textColour, 80 - titleTextWidth / 2, 185, titleTextWidth, 484, mainSurface); + titleTextWidth = fo::GetTextWidth(DoneBtn); + fo::PrintText(DoneBtn, textColour, 80 - titleTextWidth / 2, 185, titleTextWidth, 484, mainSurface); surface_draw(484, 230, 484, 0, 0, mainSurface, 484, 0, 0, winSurface); fo::func::win_show(winRef); @@ -1023,11 +1030,11 @@ endFunc: static void __fastcall HeroGenderChange(long gender) { // get PC stat current gender long newGender = fo::func::stat_level(fo::var::obj_dude, fo::STAT_gender); - if (newGender == gender) return; // check if gender has been changed + if (newGender == gender) return; // check if gender has been changed - long baseModel = (newGender) // check if male 0 - ? *(DWORD*)0x5108AC // base female model - : fo::var::art_vault_person_nums; // base male model + long baseModel = (newGender) // check if male (0) + ? *(DWORD*)0x5108AC // base female model + : fo::var::art_vault_person_nums; // base male model // adjust base hero art baseModel += critterListSize; @@ -1142,7 +1149,7 @@ static void __declspec(naked) FixCharScrnBack() { if (charScrnBackSurface == nullptr) { charScrnBackSurface = new BYTE [640 * 480]; - UnlistedFrm *frm = LoadUnlistedFrm((fo::var::glblmode) ? "AppChCrt.frm" : "AppChEdt.frm", fo::OBJ_TYPE_INTRFACE); + fo::UnlistedFrm *frm = LoadUnlistedFrm((fo::var::glblmode) ? "AppChCrt.frm" : "AppChEdt.frm", fo::OBJ_TYPE_INTRFACE); if (frm != nullptr) { surface_draw(640, 480, 640, 0, 0, frm->frames[0].indexBuff, 640, 0, 0, charScrnBackSurface); @@ -1217,18 +1224,27 @@ static void __declspec(naked) FixCharScrnBack() { int oldFont = GetFont(); SetFont(0x67); - char RaceText[8], StyleText[8]; - // Get alternate text from ini if available - Translate("AppearanceMod", "RaceText", "Race", RaceText, 8); - Translate("AppearanceMod", "StyleText", "Style", StyleText, 8); + char *RaceBtn, *StyleBtn; + fo::MessageList MsgList; - DWORD raceTextWidth = fo::GetTextWidth(RaceText); - DWORD styleTextWidth = fo::GetTextWidth(StyleText); + if (fo::func::message_load(&MsgList, "game\\AppIface.msg") == 1) { + RaceBtn = fo::GetMsg(&MsgList, 100, 2); + StyleBtn = fo::GetMsg(&MsgList, 101, 2); + } else { + // Get alternate text from ini if available (TODO: remove this in the future) + char RaceText[8], StyleText[8]; + Translate::Get("AppearanceMod", "RaceText", "Race", RaceText, 8); + Translate::Get("AppearanceMod", "StyleText", "Style", StyleText, 8); + RaceBtn = RaceText; + StyleBtn = StyleText; + } + DWORD raceTextWidth = fo::GetTextWidth(RaceBtn); + DWORD styleTextWidth = fo::GetTextWidth(StyleBtn); BYTE PeanutButter = fo::var::PeanutButter; // palette offset stored in mem - fo::PrintText(RaceText, PeanutButter, 372 - raceTextWidth / 2, 6, raceTextWidth, 640, charScrnBackSurface); - fo::PrintText(StyleText, PeanutButter, 372 - styleTextWidth / 2, 231, styleTextWidth, 640, charScrnBackSurface); + fo::PrintText(RaceBtn, PeanutButter, 372 - raceTextWidth / 2, 6, raceTextWidth, 640, charScrnBackSurface); + fo::PrintText(StyleBtn, PeanutButter, 372 - styleTextWidth / 2, 231, styleTextWidth, 640, charScrnBackSurface); SetFont(oldFont); } @@ -1260,7 +1276,7 @@ static void __declspec(naked) CharScrnEnd() { } } -//////////////////////////////////////////////////////////////////////FIX FUNCTIONS////////////////////////////////////////////////////////////////// +//////////////////////////////// FIX FUNCTIONS ///////////////////////////////// // Adjust PC SFX acm name. Skip Underscore char at the start of PC frm file name static void __declspec(naked) FixPcSFX() { @@ -1306,6 +1322,7 @@ endFunc: static void __declspec(naked) op_obj_art_fid_hack() { static const DWORD op_obj_art_fid_Ret = 0x45C5D9; + using namespace fo; using namespace Fields; __asm { mov esi, [edi + artFid]; @@ -1323,6 +1340,7 @@ skip: } static void __declspec(naked) op_metarule3_hook() { + using namespace fo; using namespace Fields; __asm { mov edi, [esp + 0x4C - 0x44 + 8]; // source @@ -1341,7 +1359,7 @@ skip: } } -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// // Load Appearance data from GCD file static void __fastcall LoadGCDAppearance(fo::DbFile* fileStream) { @@ -1517,7 +1535,7 @@ static void HeroAppearanceModExit() { } void HeroAppearance::init() { - int heroAppearanceMod = GetConfigInt("Misc", "EnableHeroAppearanceMod", 0); + int heroAppearanceMod = IniReader::GetConfigInt("Misc", "EnableHeroAppearanceMod", 0); if (heroAppearanceMod > 0) { dlog("Setting up Appearance Char Screen buttons.", DL_INIT); EnableHeroAppearanceMod(); diff --git a/sfall/Modules/HookScripts.cpp b/sfall/Modules/HookScripts.cpp index c0c34f18..27a2e7e9 100644 --- a/sfall/Modules/HookScripts.cpp +++ b/sfall/Modules/HookScripts.cpp @@ -108,6 +108,8 @@ static HooksInjectInfo injectHooks[] = { {HOOK_ADJUSTPOISON, Inject_AdjustPoisonHook, 0}, {HOOK_ADJUSTRADS, Inject_AdjustRadsHook, 1}, // always embedded for party control fix {HOOK_ROLLCHECK, Inject_RollCheckHook, 0}, + {HOOK_BESTWEAPON, Inject_BestWeaponHook, 0}, + {HOOK_CANUSEWEAPON, Inject_CanUseWeaponHook, 0}, }; void HookScripts::InjectingHook(int hookId) { @@ -255,7 +257,7 @@ void HookScripts::init() { LoadGameHook::OnGameModeChange() += HookCommon::GameModeChangeHook; LoadGameHook::OnAfterGameStarted() += SourceUseSkillOnInit; - injectAllHooks = isDebug && (iniGetInt("Debugging", "InjectAllGameHooks", 0, ::sfall::ddrawIni) != 0); + injectAllHooks = isDebug && (IniReader::GetIntDefaultConfig("Debugging", "InjectAllGameHooks", 0) != 0); if (injectAllHooks) dlogr("Injecting all game hooks.", DL_HOOK|DL_INIT); } diff --git a/sfall/Modules/HookScripts.h b/sfall/Modules/HookScripts.h index d3803957..fa069ebd 100644 --- a/sfall/Modules/HookScripts.h +++ b/sfall/Modules/HookScripts.h @@ -73,6 +73,8 @@ enum HookType HOOK_ADJUSTPOISON = 44, HOOK_ADJUSTRADS = 45, HOOK_ROLLCHECK = 46, + HOOK_BESTWEAPON = 47, + HOOK_CANUSEWEAPON = 48, HOOK_COUNT }; diff --git a/sfall/Modules/HookScripts/CombatHs.cpp b/sfall/Modules/HookScripts/CombatHs.cpp index a4206b08..c8ac5425 100644 --- a/sfall/Modules/HookScripts/CombatHs.cpp +++ b/sfall/Modules/HookScripts/CombatHs.cpp @@ -79,18 +79,15 @@ static void __declspec(naked) AfterHitRollHook() { } } -// Implementation of item_w_mp_cost_ engine function with the hook -long __fastcall sf_item_w_mp_cost(fo::GameObject* source, long hitMode, long isCalled) { - long cost = fo::func::item_w_mp_cost(source, hitMode, isCalled); - if (!HookScripts::HookHasScript(HOOK_CALCAPCOST)) return cost; - +static long CalcApCostHook_Script(fo::GameObject* source, long hitMode, long isCalled, long cost, fo::GameObject* weapon) { BeginHook(); - argCount = 4; + argCount = 5; args[0] = (DWORD)source; args[1] = hitMode; args[2] = isCalled; args[3] = cost; + args[4] = (DWORD)weapon; RunHookScript(HOOK_CALCAPCOST); @@ -100,6 +97,12 @@ long __fastcall sf_item_w_mp_cost(fo::GameObject* source, long hitMode, long isC return cost; } +long CalcApCostHook_Invoke(fo::GameObject* source, long hitMode, long isCalled, long cost, fo::GameObject* weapon) { + return (HookScripts::HookHasScript(HOOK_CALCAPCOST)) + ? CalcApCostHook_Script(source, hitMode, isCalled, cost, weapon) + : cost; +} + static void __declspec(naked) CalcApCostHook() { __asm { HookBegin; @@ -112,7 +115,9 @@ static void __declspec(naked) CalcApCostHook() { push ecx; } - argCount = 4; + argCount = 5; + args[4] = 0; + RunHookScript(HOOK_CALCAPCOST); __asm { @@ -137,7 +142,9 @@ static void __declspec(naked) CalcApCostHook2() { //push ecx; } - argCount = 4; + argCount = 5; + args[4] = 0; + RunHookScript(HOOK_CALCAPCOST); __asm { @@ -254,11 +261,11 @@ static void __declspec(naked) SubComputeDamageHook() { } } -static void __fastcall FindTargetHook_Script(DWORD* target, DWORD attacker) { +static void __fastcall FindTargetHook_Script(DWORD* target, fo::GameObject* attacker) { BeginHook(); argCount = 5; - args[0] = attacker; + args[0] = (DWORD)attacker; args[1] = target[0]; args[2] = target[1]; args[3] = target[2]; @@ -275,6 +282,12 @@ static void __fastcall FindTargetHook_Script(DWORD* target, DWORD attacker) { EndHook(); } +/* +void FindTargetHook_Invoke(fo::GameObject* targets[], fo::GameObject* attacker) { + if (HookScripts::HookHasScript(HOOK_FINDTARGET)) FindTargetHook_Script((DWORD*)targets, attacker); +} +*/ + static void __declspec(naked) FindTargetHook() { __asm { push eax; @@ -332,7 +345,7 @@ int __fastcall AmmoCostHook_Script(DWORD hookType, fo::GameObject* weapon, DWORD rounds = 1; // set default multiply for check burst attack } else { result = fo::func::item_w_compute_ammo_cost(weapon, &rounds); - if (result == -1) goto failed; // failed computed + if (result == -1) goto failed; // computation failed } args[2] = rounds; // rounds as computed by game (cost) @@ -356,7 +369,7 @@ static void __declspec(naked) AmmoCostHook() { mov ecx, 3; // hook type burst skip: xchg eax, edx; - push eax; // rounds in attack + push eax; // rounds in attack ref call AmmoCostHook_Script; // edx - weapon retn; } @@ -567,6 +580,85 @@ default: } } +static fo::GameObject* __stdcall BestWeaponHook_Script(fo::GameObject* bestWeapon, fo::GameObject* source, fo::GameObject* weapon1, fo::GameObject* weapon2, fo::GameObject* target) { + BeginHook(); + argCount = 5; + + args[0] = (DWORD)source; + args[1] = (DWORD)bestWeapon; + args[2] = (DWORD)weapon1; + args[3] = (DWORD)weapon2; + args[4] = (DWORD)target; + + RunHookScript(HOOK_BESTWEAPON); + + if (cRet > 0) bestWeapon = (fo::GameObject*)rets[0]; + + EndHook(); + return bestWeapon; +} + +static void __declspec(naked) ai_search_inven_weap_hook() { + __asm { + push ecx; // target + push ebx; // weapon2 (secondary) + push edx; // weapon1 (primary) + push eax; // source + call fo::funcoffs::ai_best_weapon_; + push eax; // bestWeapon + call BestWeaponHook_Script; + retn; + } +} + +/* +fo::GameObject* BestWeaponHook_Invoke(fo::GameObject* bestWeapon, fo::GameObject* source, fo::GameObject* weapon1, fo::GameObject* weapon2, fo::GameObject* target) { + return (HookScripts::HookHasScript(HOOK_BESTWEAPON)) + ? BestWeaponHook_Script(bestWeapon, source, weapon1, weapon2, target) + : bestWeapon; +} +*/ + +static bool __stdcall CanUseWeaponHook_Script(bool result, fo::GameObject* source, fo::GameObject* weapon, long hitMode) { + BeginHook(); + argCount = 4; + + args[0] = (DWORD)source; + args[1] = (DWORD)weapon; + args[2] = hitMode; + args[3] = 0 | result; + + RunHookScript(HOOK_CANUSEWEAPON); + + if (cRet > 0) result = rets[0] ? true : false; + + EndHook(); + return result; // only 0 and 1 +} + +static void __declspec(naked) CanUseWeaponHook() { + __asm { + push ecx; + push ebx; // hitMode + push edx; // weapon + push eax; // source + call fo::funcoffs::ai_can_use_weapon_; + push eax; // result + call CanUseWeaponHook_Script; + and eax, 1; + pop ecx; + retn; + } +} + +bool CanUseWeaponHook_Invoke(bool result, fo::GameObject* source, fo::GameObject* weapon, long hitMode) { + return (HookScripts::HookHasScript(HOOK_CANUSEWEAPON)) + ? CanUseWeaponHook_Script(result, source, weapon, hitMode) + : result; +} + +//////////////////////////////////////////////////////////////////////////////// + void Inject_ToHitHook() { HookCalls(ToHitHook, { 0x421686, // combat_safety_invalidate_weapon_func_ @@ -623,7 +715,7 @@ void Inject_ItemDamageHook() { } void Inject_AmmoCostHook() { - HookCall(0x423A7C, AmmoCostHook); + HookCall(0x423A7C, AmmoCostHook); // compute_attack_ } void Inject_CombatTurnHook() { @@ -653,6 +745,18 @@ void Inject_TargetObjectHook() { SafeWrite8(0x44C26E, 0x17); } +void Inject_BestWeaponHook() { + HookCall(0x429A59, ai_search_inven_weap_hook); +} + +void Inject_CanUseWeaponHook() { + HookCalls(CanUseWeaponHook, { + 0x429A1B, // ai_search_inven_weap_ + 0x429CF2, // ai_search_environ_ + 0x429E1C // ai_pick_hit_mode_ + }); +} + void InitCombatHookScripts() { HookScripts::LoadHookScript("hs_tohit", HOOK_TOHIT); HookScripts::LoadHookScript("hs_afterhitroll", HOOK_AFTERHITROLL); @@ -665,6 +769,8 @@ void InitCombatHookScripts() { HookScripts::LoadHookScript("hs_onexplosion", HOOK_ONEXPLOSION); HookScripts::LoadHookScript("hs_subcombatdmg", HOOK_SUBCOMBATDAMAGE); HookScripts::LoadHookScript("hs_targetobject", HOOK_TARGETOBJECT); + HookScripts::LoadHookScript("hs_bestweapon", HOOK_BESTWEAPON); + HookScripts::LoadHookScript("hs_canuseweapon", HOOK_CANUSEWEAPON); } } diff --git a/sfall/Modules/HookScripts/CombatHs.h b/sfall/Modules/HookScripts/CombatHs.h index 981d6f0a..941447ec 100644 --- a/sfall/Modules/HookScripts/CombatHs.h +++ b/sfall/Modules/HookScripts/CombatHs.h @@ -18,10 +18,14 @@ void Inject_CombatTurnHook(); void Inject_OnExplosionHook(); void Inject_SubCombatDamageHook(); void Inject_TargetObjectHook(); +void Inject_BestWeaponHook(); +void Inject_CanUseWeaponHook(); int __fastcall AmmoCostHook_Script(DWORD hookType, fo::GameObject* weapon, DWORD &rounds); -// Implementation of item_w_mp_cost_ engine function with the hook -long __fastcall sf_item_w_mp_cost(fo::GameObject* source, long hitMode, long isCalled); +long CalcApCostHook_Invoke(fo::GameObject* source, long hitMode, long isCalled, long cost, fo::GameObject* weapon); +//void FindTargetHook_Invoke(fo::GameObject* targets[], fo::GameObject* attacker); +//fo::GameObject* BestWeaponHook_Invoke(fo::GameObject* bestWeapon, fo::GameObject* source, fo::GameObject* weapon1, fo::GameObject* weapon2, fo::GameObject* target); +bool CanUseWeaponHook_Invoke(bool result, fo::GameObject* source, fo::GameObject* weapon, long hitMode); } diff --git a/sfall/Modules/HookScripts/Common.cpp b/sfall/Modules/HookScripts/Common.cpp index f8347dd7..766a46fb 100644 --- a/sfall/Modules/HookScripts/Common.cpp +++ b/sfall/Modules/HookScripts/Common.cpp @@ -69,6 +69,8 @@ static bool CheckRecursiveHooks(DWORD hook) { case HOOK_SETGLOBALVAR: case HOOK_SETLIGHTING: return true; + default: + if (isDebug) fo::func::debug_printf("\nWARNING: A recursive hook with ID %d was running.", hook); } } return false; @@ -172,7 +174,10 @@ void HookCommon::KeyPressHook(DWORD* dxKey, bool pressed, DWORD vKey) { args[1] = *dxKey; args[2] = vKey; RunHookScript(HOOK_KEYPRESS); - if (cRet != 0) *dxKey = rets[0]; + if (cRet != 0) { + long retKey = rets[0]; + if (retKey > 0 && retKey < 264) *dxKey = retKey; + } EndHook(); } diff --git a/sfall/Modules/HookScripts/Common.h b/sfall/Modules/HookScripts/Common.h index 1adaf37c..436335b1 100644 --- a/sfall/Modules/HookScripts/Common.h +++ b/sfall/Modules/HookScripts/Common.h @@ -27,7 +27,7 @@ public: // Struct for registered hook script struct HookScript { ScriptProgram prog; - int callback; // proc number in script's proc table + int callback; // procedure position in script's proc table bool isGlobalScript; // false for hs_* scripts, true for gl* scripts }; diff --git a/sfall/Modules/HookScripts/InventoryHs.cpp b/sfall/Modules/HookScripts/InventoryHs.cpp index 8fa0a982..f742fbeb 100644 --- a/sfall/Modules/HookScripts/InventoryHs.cpp +++ b/sfall/Modules/HookScripts/InventoryHs.cpp @@ -69,7 +69,7 @@ static void __declspec(naked) MoveCostHook() { } static int __fastcall SwitchHandHook_Script(fo::GameObject* item, fo::GameObject* itemReplaced, DWORD addr) { - if (itemReplaced && fo::GetItemType(itemReplaced) == fo::item_type_weapon && fo::GetItemType(item) == fo::item_type_ammo) { + if (itemReplaced && fo::func::item_get_type(itemReplaced) == fo::item_type_weapon && fo::func::item_get_type(item) == fo::item_type_ammo) { return -1; // to prevent inappropriate hook call after dropping ammo on weapon } @@ -269,7 +269,6 @@ static void __declspec(naked) DropIntoContainerHandSlotHack() { } static void __declspec(naked) DropAmmoIntoWeaponHook() { - //static const DWORD DropAmmoIntoWeaponHack_back = 0x47658D; // proceed with reloading static const DWORD DropAmmoIntoWeaponHack_return = 0x476643; __asm { pushadc; @@ -278,13 +277,11 @@ static void __declspec(naked) DropAmmoIntoWeaponHook() { push 4; // event: weapon reloading call InventoryMoveHook_Script; cmp eax, -1; // ret value - popadc; jne donothing; + popadc; jmp fo::funcoffs::item_w_can_reload_; - //mov ebx, 1; // overwritten code - //jmp DropAmmoIntoWeaponHack_back; donothing: - add esp, 4; // destroy return address + add esp, 4*4; // destroy all pushed values and return address xor eax, eax; // result 0 jmp DropAmmoIntoWeaponHack_return; } @@ -384,7 +381,7 @@ static void __declspec(naked) InvenWieldFuncHook() { } // right hand slot? - if (args[2] != fo::INVEN_TYPE_RIGHT_HAND && fo::GetItemType((fo::GameObject*)args[1]) != fo::item_type_armor) { + if (args[2] != fo::INVEN_TYPE_RIGHT_HAND && fo::func::item_get_type((fo::GameObject*)args[1]) != fo::item_type_armor) { args[2] = fo::INVEN_TYPE_LEFT_HAND; } InvenWieldHook_ScriptPart(1); // wield event @@ -458,6 +455,18 @@ static void __declspec(naked) CorrectFidForRemovedItemHook() { } } +long InvenWieldHook_Invoke(fo::GameObject* critter, fo::GameObject* item, long flags) { + if (!HookScripts::HookHasScript(HOOK_INVENWIELD)) return 1; + + long slot = fo::INVEN_TYPE_WORN; + if (flags & fo::ObjectFlag::Right_Hand) { // right hand slot + slot = fo::INVEN_TYPE_RIGHT_HAND; + } else if (flags & fo::ObjectFlag::Left_Hand) { // left hand slot + slot = fo::INVEN_TYPE_LEFT_HAND; + } + return InvenWieldHook_Script(critter, item, slot, 0, 0); +} + static void __declspec(naked) item_drop_all_hack() { using namespace fo::ObjectFlag; __asm { @@ -654,22 +663,6 @@ void Inject_InvenWieldHook() { hookInvenWieldIsInject = true; } -// internal function implementation with hook -long CorrectFidForRemovedItem_wHook(fo::GameObject* critter, fo::GameObject* item, long flags) { - long result = 1; - if (!hooks[HOOK_INVENWIELD].empty()) { - long slot = fo::INVEN_TYPE_WORN; - if (flags & fo::ObjectFlag::Right_Hand) { // right hand slot - slot = fo::INVEN_TYPE_RIGHT_HAND; - } else if (flags & fo::ObjectFlag::Left_Hand) { // left hand slot - slot = fo::INVEN_TYPE_LEFT_HAND; - } - result = InvenWieldHook_Script(critter, item, slot, 0, 0); - } - if (result) fo::func::correctFidForRemovedItem(critter, item, flags); - return result; -} - void InitInventoryHookScripts() { HookScripts::LoadHookScript("hs_removeinvenobj", HOOK_REMOVEINVENOBJ); HookScripts::LoadHookScript("hs_movecost", HOOK_MOVECOST); diff --git a/sfall/Modules/HookScripts/InventoryHs.h b/sfall/Modules/HookScripts/InventoryHs.h index b8f30750..a29b12ac 100644 --- a/sfall/Modules/HookScripts/InventoryHs.h +++ b/sfall/Modules/HookScripts/InventoryHs.h @@ -13,7 +13,8 @@ void Inject_SwitchHandHook(); void Inject_InventoryMoveHook(); void Inject_InvenWieldHook(); -long CorrectFidForRemovedItem_wHook(fo::GameObject* critter, fo::GameObject* item, long flags); +long InvenWieldHook_Invoke(fo::GameObject* critter, fo::GameObject* item, long flags); + void InvenUnwield_HookDrop(); void InvenUnwield_HookMove(); diff --git a/sfall/Modules/HookScripts/MiscHs.cpp b/sfall/Modules/HookScripts/MiscHs.cpp index 8797e6a0..420e5555 100644 --- a/sfall/Modules/HookScripts/MiscHs.cpp +++ b/sfall/Modules/HookScripts/MiscHs.cpp @@ -255,15 +255,13 @@ skip: } } -static long __fastcall PerceptionRangeHook_Script(fo::GameObject* watcher, fo::GameObject* target, int type) { - long result = fo::func::is_within_perception(watcher, target); - +static __forceinline long PerceptionRangeHook_Script(fo::GameObject* watcher, fo::GameObject* target, int type, long result) { BeginHook(); argCount = 4; args[0] = (DWORD)watcher; args[1] = (DWORD)target; - args[2] = result; + args[2] = result; // engine result args[3] = type; RunHookScript(HOOK_WITHINPERCEPTION); @@ -274,12 +272,13 @@ static long __fastcall PerceptionRangeHook_Script(fo::GameObject* watcher, fo::G return result; } -// Implementation of is_within_perception_ engine function with the hook -long __fastcall sf_is_within_perception(fo::GameObject* watcher, fo::GameObject* target) { // TODO: add type arg - if (HookScripts::HookHasScript(HOOK_WITHINPERCEPTION)) { - return PerceptionRangeHook_Script(watcher, target, 0); - } - return fo::func::is_within_perception(watcher, target); +long PerceptionRangeHook_Invoke(fo::GameObject* watcher, fo::GameObject* target, long type, long result) { + if (!HookScripts::HookHasScript(HOOK_WITHINPERCEPTION)) return result; + return PerceptionRangeHook_Script(watcher, target, type, result); +} + +static long __fastcall PerceptionRange_Hook(fo::GameObject* watcher, fo::GameObject* target, int type) { + return PerceptionRangeHook_Script(watcher, target, type, fo::func::is_within_perception(watcher, target)); } static void __declspec(naked) PerceptionRangeHook() { @@ -287,7 +286,7 @@ static void __declspec(naked) PerceptionRangeHook() { push ecx; push 0; mov ecx, eax; - call PerceptionRangeHook_Script; + call PerceptionRange_Hook; pop ecx; retn; } @@ -298,7 +297,7 @@ static void __declspec(naked) PerceptionRangeSeeHook() { push ecx; push 1; mov ecx, eax; - call PerceptionRangeHook_Script; + call PerceptionRange_Hook; pop ecx; cmp eax, 2; jne nevermind; // normal return @@ -315,7 +314,7 @@ static void __declspec(naked) PerceptionRangeHearHook() { push ecx; push 2; mov ecx, eax; - call PerceptionRangeHook_Script; + call PerceptionRange_Hook; pop ecx; retn; } @@ -326,7 +325,7 @@ static void __declspec(naked) PerceptionSearchTargetHook() { push ecx; push 3; mov ecx, eax; - call PerceptionRangeHook_Script; + call PerceptionRange_Hook; pop ecx; retn; } diff --git a/sfall/Modules/HookScripts/MiscHs.h b/sfall/Modules/HookScripts/MiscHs.h index 6c0cc6be..8c79f542 100644 --- a/sfall/Modules/HookScripts/MiscHs.h +++ b/sfall/Modules/HookScripts/MiscHs.h @@ -18,7 +18,5 @@ namespace sfall void Inject_EncounterHook(); void Inject_RollCheckHook(); - // Implementation of is_within_perception_ engine function with the hook - long __fastcall sf_is_within_perception(fo::GameObject* watcher, fo::GameObject* target); - + long PerceptionRangeHook_Invoke(fo::GameObject* watcher, fo::GameObject* target, long type, long result); } diff --git a/sfall/Modules/Input.cpp b/sfall/Modules/Input.cpp index 1dbe37b7..e9026b47 100644 --- a/sfall/Modules/Input.cpp +++ b/sfall/Modules/Input.cpp @@ -11,7 +11,7 @@ namespace sfall { void Input::init() { - //if (GetConfigInt("Input", "Enable", 0)) { + //if (IniReader::GetConfigInt("Input", "Enable", 0)) { dlog("Applying input patch.", DL_INIT); SafeWriteStr(0x50FB70, "ddraw.dll"); ::sfall::availableGlobalScriptTypes |= 1; diff --git a/sfall/Modules/Interface.cpp b/sfall/Modules/Interface.cpp index 427399fe..6940bca9 100644 --- a/sfall/Modules/Interface.cpp +++ b/sfall/Modules/Interface.cpp @@ -783,7 +783,7 @@ static void __declspec(naked) wmInterfaceRefreshCarFuel_hack() { static void WorldMapInterfacePatch() { BlockCall(0x4C2380); // Remove disabling palette animations (can be used as a place to call a hack function in wmInterfaceInit_) - if (GetConfigInt("Misc", "WorldMapFontPatch", 0)) { + if (IniReader::GetConfigInt("Misc", "WorldMapFontPatch", 0)) { dlog("Applying world map font patch.", DL_INIT); HookCall(0x4C2343, wmInterfaceInit_text_font_hook); dlogr(" Done", DL_INIT); @@ -795,13 +795,13 @@ static void WorldMapInterfacePatch() { SafeWrite32(0x4C2C92, 181); // index of DNARWOFF.FRM SafeWrite8(0x4C2D04, 0x46); // dec esi > inc esi - //if (GetConfigInt("Misc", "WorldMapCitiesListFix", 0)) { + //if (IniReader::GetConfigInt("Misc", "WorldMapCitiesListFix", 0)) { dlog("Applying world map cities list patch.", DL_INIT); HookCalls(ScrollCityListFix, {0x4C04B9, 0x4C04C8, 0x4C4A34, 0x4C4A3D}); dlogr(" Done", DL_INIT); //} - DWORD wmSlots = GetConfigInt("Misc", "WorldMapSlots", 0); + DWORD wmSlots = IniReader::GetConfigInt("Misc", "WorldMapSlots", 0); if (wmSlots && wmSlots < 128) { dlog("Applying world map slots patch.", DL_INIT); if (wmSlots < 7) wmSlots = 7; @@ -813,20 +813,20 @@ static void WorldMapInterfacePatch() { } if (hrpIsEnabled && hrpVersionValid) { - if (worldmapInterface = GetConfigInt("Interface", "ExpandWorldMap", 0)) { + if (worldmapInterface = IniReader::GetConfigInt("Interface", "ExpandWorldMap", 0)) { LoadGameHook::OnAfterGameInit() += WorldmapViewportPatch; // Note: must be applied after WorldMapSlots patch } } // Fallout 1 features, travel markers and displaying terrain types or town titles - if (GetConfigInt("Interface", "WorldMapTravelMarkers", 0)) { + if (IniReader::GetConfigInt("Interface", "WorldMapTravelMarkers", 0)) { dlog("Applying world map travel markers patch.", DL_INIT); - int color = GetConfigInt("Interface", "TravelMarkerColor", 134); // color index in palette: R = 224, G = 0, B = 0 + int color = IniReader::GetConfigInt("Interface", "TravelMarkerColor", 134); // color index in palette: R = 224, G = 0, B = 0 if (color > 255) color = 255; else if (color < 1) color = 1; colorDot = color; - auto dotList = GetConfigList("Interface", "TravelMarkerStyles", "", 512); + auto dotList = IniReader::GetConfigList("Interface", "TravelMarkerStyles", "", 512); if (!dotList.empty()) { terrainCount = dotList.size(); dotStyle = new DotStyle[terrainCount]; @@ -853,7 +853,7 @@ static void WorldMapInterfacePatch() { }; dlogr(" Done", DL_INIT); } - showTerrainType = (GetConfigInt("Interface", "WorldMapTerrainInfo", 0) != 0); + showTerrainType = (IniReader::GetConfigInt("Interface", "WorldMapTerrainInfo", 0) != 0); HookCall(0x4C3C7E, wmInterfaceRefresh_hook); // when calling wmDrawCursorStopped_ MakeCall(0x4BFE84, wmWorldMap_hack); @@ -890,7 +890,7 @@ negative: } static void SpeedInterfaceCounterAnimsPatch() { - switch (GetConfigInt("Misc", "SpeedInterfaceCounterAnims", 0)) { + switch (IniReader::GetConfigInt("Misc", "SpeedInterfaceCounterAnims", 0)) { case 1: dlog("Applying SpeedInterfaceCounterAnims patch.", DL_INIT); MakeJump(0x460BA1, intface_rotate_numbers_hack); @@ -963,7 +963,7 @@ fix: } void Interface::init() { - if (GetConfigInt("Interface", "ActionPointsBar", 0)) { + if (IniReader::GetConfigInt("Interface", "ActionPointsBar", 0)) { ActionPointsBarPatch(); } DrawActionPointsNumber(); @@ -980,7 +980,7 @@ void Interface::init() { }; // Set the normal font for death screen subtitles - if (GetConfigInt("Misc", "DeathScreenFontPatch", 0)) { + if (IniReader::GetConfigInt("Misc", "DeathScreenFontPatch", 0)) { dlog("Applying death screen font patch.", DL_INIT); HookCall(0x4812DF, main_death_scene_hook); dlogr(" Done", DL_INIT); diff --git a/sfall/Modules/Inventory.cpp b/sfall/Modules/Inventory.cpp index 39029545..526a0f09 100644 --- a/sfall/Modules/Inventory.cpp +++ b/sfall/Modules/Inventory.cpp @@ -16,11 +16,11 @@ * along with this program. If not, see . */ -#include - #include "..\main.h" #include "..\FalloutEngine\Fallout2.h" #include "..\InputFuncs.h" +#include "..\Translate.h" + #include "LoadGameHook.h" #include "..\Game\inventory.h" @@ -75,8 +75,8 @@ static int __stdcall CritterGetMaxSize(fo::GameObject* critter) { } int statSize = 0; - fo::Proto* proto = fo::GetProto(critter->protoId); - if (proto != nullptr) { + fo::Proto* proto; + if (fo::GetProto(critter->protoId, &proto)) { statSize = proto->critter.base.unarmedDamage + proto->critter.bonus.unarmedDamage; // The unused stat in the base + extra block } return (statSize > 0) ? statSize : 100; // 100 - default value, for all critters if not set stats @@ -630,7 +630,7 @@ void Inventory::init() { long widthWeight = 135; - sizeLimitMode = GetConfigInt("Misc", "CritterInvSizeLimitMode", 0); + sizeLimitMode = IniReader::GetConfigInt("Misc", "CritterInvSizeLimitMode", 0); if (sizeLimitMode > 0 && sizeLimitMode <= 7) { if (sizeLimitMode >= 4) { sizeLimitMode -= 4; @@ -638,7 +638,7 @@ void Inventory::init() { SafeWrite8(0x477EB3, CodeType::JumpShort); SafeWriteBatch(0, {0x477EF5, 0x477F11, 0x477F29}); } - invSizeMaxLimit = GetConfigInt("Misc", "CritterInvSizeLimit", 100); + invSizeMaxLimit = IniReader::GetConfigInt("Misc", "CritterInvSizeLimit", 100); // Check item_add_multi (picking stuff from the floor, etc.) HookCall(0x4771BD, item_add_mult_hack); // jle addr @@ -681,26 +681,26 @@ void Inventory::init() { // Adjust the max text width of the total weight display on the inventory screen SafeWrite32(0x472632, widthWeight); - if (GetConfigInt("Misc", "SuperStimExploitFix", 0)) { - superStimMsg = Translate("sfall", "SuperStimExploitMsg", "You cannot use a super stim on someone who is not injured!"); + if (IniReader::GetConfigInt("Misc", "SuperStimExploitFix", 0)) { + superStimMsg = Translate::Get("sfall", "SuperStimExploitMsg", "You cannot use a super stim on someone who is not injured!"); MakeCall(0x49C3D9, protinst_use_item_on_hack); } - reloadWeaponKey = GetConfigInt("Input", "ReloadWeaponKey", 0); + reloadWeaponKey = IniReader::GetConfigInt("Input", "ReloadWeaponKey", 0); - invenApCost = invenApCostDef = GetConfigInt("Misc", "InventoryApCost", 4); - invenApQPReduction = GetConfigInt("Misc", "QuickPocketsApCostReduction", 2); + invenApCost = invenApCostDef = IniReader::GetConfigInt("Misc", "InventoryApCost", 4); + invenApQPReduction = IniReader::GetConfigInt("Misc", "QuickPocketsApCostReduction", 2); if (invenApCostDef != 4 || invenApQPReduction != 2) { ApplyInvenApCostPatch(); } - if (GetConfigInt("Misc", "StackEmptyWeapons", 0)) { + if (IniReader::GetConfigInt("Misc", "StackEmptyWeapons", 0)) { MakeCall(0x4736C6, inven_action_cursor_hack); HookCall(0x4772AA, item_add_mult_hook); } // Do not call the 'Move Items' window when using drag and drop to reload weapons in the inventory - int ReloadReserve = GetConfigInt("Misc", "ReloadReserve", -1); + int ReloadReserve = IniReader::GetConfigInt("Misc", "ReloadReserve", -1); if (ReloadReserve >= 0) { SafeWrite32(0x47655F, ReloadReserve); // mov eax, ReloadReserve SafeWrite32(0x476563, 0x097EC139); // cmp ecx, eax; jle 0x476570 @@ -708,14 +708,14 @@ void Inventory::init() { SafeWrite8(0x476569, 0x91); // xchg ecx, eax }; - itemFastMoveKey = GetConfigInt("Input", "ItemFastMoveKey", DIK_LCONTROL); + itemFastMoveKey = IniReader::GetConfigInt("Input", "ItemFastMoveKey", DIK_LCONTROL); if (itemFastMoveKey > 0) { HookCall(0x476897, do_move_timer_hook); // Do not call the 'Move Items' window when taking items from containers or corpses - skipFromContainer = GetConfigInt("Input", "FastMoveFromContainer", 0); + skipFromContainer = IniReader::GetConfigInt("Input", "FastMoveFromContainer", 0); } - if (GetConfigInt("Misc", "ItemCounterDefaultMax", 0)) { + if (IniReader::GetConfigInt("Misc", "ItemCounterDefaultMax", 0)) { MakeCall(0x4768A3, do_move_timer_hack); } diff --git a/sfall/Modules/Karma.cpp b/sfall/Modules/Karma.cpp index 115473e5..ba268de3 100644 --- a/sfall/Modules/Karma.cpp +++ b/sfall/Modules/Karma.cpp @@ -16,13 +16,13 @@ * along with this program. If not, see . */ -#include -#include #include #include #include "..\main.h" #include "..\FalloutEngine\Fallout2.h" +#include "..\Translate.h" + #include "HookScripts.h" #include "Karma.h" @@ -78,22 +78,22 @@ void Karma::DisplayKarma(int value) { } static void ApplyDisplayKarmaChangesPatch() { - displayKarmaChanges = GetConfigInt("Misc", "DisplayKarmaChanges", 0) != 0; + displayKarmaChanges = IniReader::GetConfigInt("Misc", "DisplayKarmaChanges", 0) != 0; if (displayKarmaChanges) { dlog("Applying display karma changes patch.", DL_INIT); - karmaGainMsg = Translate("sfall", "KarmaGain", "You gained %d karma."); - karmaLossMsg = Translate("sfall", "KarmaLoss", "You lost %d karma."); + karmaGainMsg = Translate::Get("sfall", "KarmaGain", "You gained %d karma."); + karmaLossMsg = Translate::Get("sfall", "KarmaLoss", "You lost %d karma."); HookScripts::InjectingHook(HOOK_SETGLOBALVAR); dlogr(" Done", DL_INIT); } } static void ApplyKarmaFRMsPatch() { - auto karmaFrmList = GetConfigList("Misc", "KarmaFRMs", "", 512); + auto karmaFrmList = IniReader::GetConfigList("Misc", "KarmaFRMs", "", 512); size_t countFrm = karmaFrmList.size(); if (countFrm) { dlog("Applying karma FRM patch.", DL_INIT); - auto karmaPointsList = GetConfigList("Misc", "KarmaPoints", "", 512); + auto karmaPointsList = IniReader::GetConfigList("Misc", "KarmaPoints", "", 512); karmaFrms.resize(countFrm); size_t countPoints = karmaPointsList.size(); diff --git a/sfall/Modules/KillCounter.cpp b/sfall/Modules/KillCounter.cpp index 725af797..c98a725c 100644 --- a/sfall/Modules/KillCounter.cpp +++ b/sfall/Modules/KillCounter.cpp @@ -73,7 +73,7 @@ bool KillCounter::UsingExtraKillTypes() { } void KillCounter::init() { - if (GetConfigInt("Misc", "ExtraKillTypes", 0)) { + if (IniReader::GetConfigInt("Misc", "ExtraKillTypes", 0)) { dlog("Applying extra kill types patch.", DL_INIT); KillCounterInit(); dlogr(" Done", DL_INIT); diff --git a/sfall/Modules/LoadGameHook.cpp b/sfall/Modules/LoadGameHook.cpp index 0dbb725c..2960cbf3 100644 --- a/sfall/Modules/LoadGameHook.cpp +++ b/sfall/Modules/LoadGameHook.cpp @@ -21,9 +21,9 @@ #include "..\FalloutEngine\Fallout2.h" #include "..\InputFuncs.h" #include "..\Logging.h" +#include "..\Translate.h" #include "..\version.h" -#include "AI.h" #include "BugFixes.h" #include "CritterStats.h" #include "ExtraSaveSlots.h" @@ -63,13 +63,20 @@ static Delegate<> onAfterGameStarted; static Delegate<> onAfterNewGame; static Delegate onGameModeChange; static Delegate<> onBeforeGameClose; +static Delegate<> onCombatStart; +static Delegate<> onCombatEnd; static DWORD inLoop = 0; static DWORD saveInCombatFix; static bool gameLoaded = false; +static bool onLoadingMap = false; long LoadGameHook::interfaceWID = -1; +bool LoadGameHook::IsMapLoading() { + return onLoadingMap; +} + // True if game was started, false when on the main menu bool IsGameLoaded() { return gameLoaded; @@ -117,8 +124,6 @@ void GetSavePath(char* buf, char* ftype) { sprintf(buf, "%s\\savegame\\slot%.2d\\sfall%s.sav", fo::var::patches, fo::var::slot_cursor + 1 + LSPageOffset, ftype); //add SuperSave Page offset } -static std::string saveSfallDataFailMsg; - static void __stdcall SaveGame2() { char buf[MAX_PATH]; GetSavePath(buf, "gv"); @@ -168,23 +173,21 @@ static void __stdcall SaveGame2() { ///////////////////////////////////////////////// errorSave: dlog_f("ERROR creating: %s\n", DL_MAIN, buf); - fo::DisplayPrint(saveSfallDataFailMsg); + fo::DisplayPrint(Translate::SfallSaveDataFailure()); fo::func::gsound_play_sfx_file("IISXXXX1"); } -static std::string saveFailMsg; - static DWORD __stdcall CombatSaveTest() { if (!saveInCombatFix && !PartyControl::IsNpcControlled()) return 1; if (inLoop & COMBAT) { if (saveInCombatFix == 2 || PartyControl::IsNpcControlled() || !(inLoop & PCOMBAT)) { - fo::DisplayPrint(saveFailMsg); + fo::DisplayPrint(Translate::CombatSaveBlockMessage()); return 0; } int ap = fo::func::stat_level(fo::var::obj_dude, fo::STAT_max_move_points); int bonusmove = fo::func::perk_level(fo::var::obj_dude, fo::PERK_bonus_move); if (fo::var::obj_dude->critter.movePoints != ap || bonusmove * 2 != fo::var::combat_free_move) { - fo::DisplayPrint(saveFailMsg); + fo::DisplayPrint(Translate::CombatSaveBlockMessage()); return 0; } } @@ -269,7 +272,7 @@ static bool __stdcall GameReset(DWORD isGameLoad) { onGameReset.invoke(); if (isDebug) { char* str = (isGameLoad) ? "on Load" : "on Exit"; - fo::func::debug_printf("\n[SFALL: State reset %s]", str); + fo::func::debug_printf("\nSFALL: [State reset %s]\n", str); } } inLoop = 0; @@ -429,6 +432,16 @@ static void __declspec(naked) game_close_hook() { } } + +static void __declspec(naked) map_load_hook() { + __asm { + mov onLoadingMap, 1; + call fo::funcoffs::map_load_file_; + mov onLoadingMap, 0; + retn; + } +} + static void __declspec(naked) WorldMapHook_Start() { __asm { call fo::funcoffs::wmInterfaceInit_; @@ -451,17 +464,25 @@ static void __declspec(naked) WorldMapHook_End() { } } +static void __fastcall CombatInternal(fo::CombatGcsd* gcsd) { + onCombatStart.invoke(); + SetInLoop(1, COMBAT); + + __asm mov eax, gcsd; + __asm call fo::funcoffs::combat_; + + onCombatEnd.invoke(); + SetInLoop(0, COMBAT); +} + static void __declspec(naked) CombatHook() { __asm { - pushadc; - call AI::AICombatStart; - _InLoop2(1, COMBAT); - popadc; - call fo::funcoffs::combat_; - pushadc; - call AI::AICombatEnd; - _InLoop2(0, COMBAT); - popadc; + push ecx; + push edx; + mov ecx, eax; + call CombatInternal; + pop edx; + pop ecx; retn; } } @@ -727,18 +748,18 @@ static void __declspec(naked) gdialogUpdatePartyStatus_hook0() { } void LoadGameHook::init() { - saveInCombatFix = GetConfigInt("Misc", "SaveInCombatFix", 1); + saveInCombatFix = IniReader::GetConfigInt("Misc", "SaveInCombatFix", 1); if (saveInCombatFix > 2) saveInCombatFix = 0; - saveFailMsg = Translate("sfall", "SaveInCombat", "Cannot save at this time."); - saveSfallDataFailMsg = Translate("sfall", "SaveSfallDataFail", - "ERROR saving extended savegame information! Check if other programs interfere with savegame files/folders and try again!"); + HookCall(0x482AEC, map_load_hook); HookCall(0x4809BA, main_init_system_hook); HookCall(0x4426A6, game_init_hook); HookCall(0x480AAE, main_load_new_hook); + HookCalls(LoadGame_hook, {0x443AE4, 0x443B89, 0x480B77, 0x48FD35}); SafeWrite32(0x5194C0, (DWORD)&EndLoadHook); HookCalls(SaveGame_hook, {0x443AAC, 0x443B1C, 0x48FCFF}); + HookCalls(game_reset_hook, { 0x47DD6B, // LoadSlot_ (on load error) 0x47DDF3, // LoadSlot_ (on load error) @@ -754,6 +775,7 @@ void LoadGameHook::init() { HookCalls(game_reset_on_load_hook, { 0x47F491, // PrepLoad_ (the very first step during save game loading) }); + HookCalls(before_game_exit_hook, {0x480ACE, 0x480BC7}); HookCalls(after_game_exit_hook, {0x480AEB, 0x480BE4}); HookCalls(game_close_hook, { @@ -848,4 +870,11 @@ Delegate<>& LoadGameHook::OnBeforeGameClose() { return onBeforeGameClose; } +Delegate<>& LoadGameHook::OnCombatStart() { + return onCombatStart; +} + +Delegate<>& LoadGameHook::OnCombatEnd() { + return onCombatEnd; +} } diff --git a/sfall/Modules/LoadGameHook.h b/sfall/Modules/LoadGameHook.h index 306ce739..3e07307a 100644 --- a/sfall/Modules/LoadGameHook.h +++ b/sfall/Modules/LoadGameHook.h @@ -59,6 +59,11 @@ public: // Invoked before the game exits to windows static Delegate<>& OnBeforeGameClose(); + static Delegate<>& OnCombatStart(); + static Delegate<>& OnCombatEnd(); + + static bool IsMapLoading(); + static long interfaceWID; }; diff --git a/sfall/Modules/LoadOrder.cpp b/sfall/Modules/LoadOrder.cpp index d4954240..882c3c1f 100644 --- a/sfall/Modules/LoadOrder.cpp +++ b/sfall/Modules/LoadOrder.cpp @@ -18,7 +18,6 @@ #include "..\main.h" #include "..\FalloutEngine\Fallout2.h" -#include "..\Logging.h" #include "LoadGameHook.h" #include "LoadOrder.h" @@ -40,6 +39,15 @@ static bool cutsPatch = false; static std::vector patchFiles; static std::vector savPrototypes; +static void PlayerGenderCutsRestore() { + if (cutsPatch) { // restore + SafeWrite32(0x43FA9F, FO_VAR_aTextSCuts); + SafeWrite32(0x44EB5B, FO_VAR_aTextSCutsS); + SafeWrite32(0x48152E, FO_VAR_aTextSCutsSS); + cutsPatch = false; + } +} + static void CheckPlayerGender() { isFemale = fo::HeroIsFemale(); @@ -50,11 +58,8 @@ static void CheckPlayerGender() { SafeWrite32(0x43FA9F, (DWORD)cutsEndGameFemale); SafeWrite32(0x44EB5B, (DWORD)cutsSubFemale); SafeWrite32(0x48152E, (DWORD)cutsDeathFemale); - } else if (cutsPatch) { - SafeWrite32(0x43FA9F, FO_VAR_aTextSCuts); - SafeWrite32(0x44EB5B, FO_VAR_aTextSCutsS); - SafeWrite32(0x48152E, FO_VAR_aTextSCutsSS); - cutsPatch = false; + } else { + PlayerGenderCutsRestore(); } } } @@ -103,6 +108,8 @@ static void __declspec(naked) gnw_main_hack() { } } +//////////////////////////////////////////////////////////////////////////////// + static fo::PathNode* __fastcall RemoveDatabase(const char* pathPatches) { auto paths = fo::var::paths; // curr.node (beginning of the chain of paths) auto _paths = paths; // prev.node @@ -178,10 +185,10 @@ static void __fastcall game_init_databases_hook() { // eax = _master_db_handle master_patches->next = paths; // master_patches.next -> paths fo::var::paths = master_patches; // set master_patches node at the beginning of the chain of paths } - +/* static void __fastcall game_init_databases_hook1() { char masterPatch[MAX_PATH]; - iniGetString("system", "master_patches", "", masterPatch, MAX_PATH - 1, (const char*)FO_VAR_gconfig_file_name); + IniReader::GetString("system", "master_patches", "", masterPatch, MAX_PATH - 1, (const char*)FO_VAR_gconfig_file_name); fo::PathNode* node = fo::var::paths; while (node->next) { @@ -192,14 +199,16 @@ static void __fastcall game_init_databases_hook1() { InitExtraPatches(); } - +*/ static bool NormalizePath(std::string &path) { if (path.find(':') != std::string::npos) return false; + int pos = 0; do { // replace all '/' char to '\' pos = path.find('/', pos); if (pos != std::string::npos) path[pos] = '\\'; } while (pos != std::string::npos); + if (path.find(".\\") != std::string::npos || path.find("..\\") != std::string::npos) return false; while (path.front() == '\\') path.erase(0, 1); // remove firsts '\' return true; @@ -210,11 +219,11 @@ static void GetExtraPatches() { char patchFile[12] = "PatchFile"; for (int i = 0; i < 100; i++) { _itoa(i, &patchFile[9], 10); - auto patch = GetConfigString("ExtraPatches", patchFile, "", MAX_PATH); + auto patch = IniReader::GetConfigString("ExtraPatches", patchFile, "", MAX_PATH); if (patch.empty() || !NormalizePath(patch) || GetFileAttributes(patch.c_str()) == INVALID_FILE_ATTRIBUTES) continue; patchFiles.push_back(patch); } - std::string searchPath = "mods\\"; //GetConfigString("ExtraPatches", "AutoSearchPath", "mods\\", MAX_PATH); + std::string searchPath = "mods\\"; //IniReader::GetConfigString("ExtraPatches", "AutoSearchPath", "mods\\", MAX_PATH); //if (!searchPath.empty() && NormalizePath(searchPath)) { //if (searchPath.back() != '\\') searchPath += "\\"; @@ -244,7 +253,7 @@ static void GetExtraPatches() { } static void MultiPatchesPatch() { - //if (GetConfigInt("Misc", "MultiPatches", 0)) { + //if (IniReader::GetConfigInt("Misc", "MultiPatches", 0)) { dlog("Applying load multiple patches patch.", DL_INIT); SafeWrite8(0x444354, CodeType::Nop); // Change step from 2 to 1 SafeWrite8(0x44435C, 0xC4); // Disable check @@ -252,7 +261,7 @@ static void MultiPatchesPatch() { //} } -////////////////////////////// SAVE PARTY MEMBER PROTOTYPES ////////////////////////////// +///////////////////////// SAVE PARTY MEMBER PROTOTYPES ///////////////////////// static void __fastcall AddSavPrototype(long pid) { for (const auto& _pid : savPrototypes) { @@ -431,25 +440,62 @@ artNotExist: } } -void LoadOrder::init() { - // Load external sfall resource file (load order is before patchXXX.dat) - patchFiles.push_back("sfall.dat"); +static fo::DbFile* __fastcall LoadFont(const char* font, const char* mode) { + char file[128]; + const char* lang; + if (fo::func::get_game_config_string(&lang, "system", "language") && _stricmp(lang, "english") != 0) { + std::sprintf(file, "fonts\\%s\\%s", lang, font); + return fo::func::db_fopen(file, mode); + } + return nullptr; +} +void __declspec(naked) load_font_hook() { + __asm { + mov ebp, edx; + mov ebx, eax; + mov ecx, eax; + call LoadFont; + test eax, eax; + jz default; + retn; +default: + mov edx, ebp; + mov eax, ebx; + jmp fo::funcoffs::db_fopen_; + } +} + +static void SfallResourceFile() { + const char* sfallRes = "sfall.dat"; + + WIN32_FIND_DATA findData; + HANDLE hFind = FindFirstFile("sfall_??.dat", &findData); // example: sfall_ru.dat, sfall_zh.dat + if (hFind != INVALID_HANDLE_VALUE) { + FindClose(hFind); + dlog_f("Loading a localized sfall resource file: %s\n", DL_MAIN, findData.cFileName); + sfallRes = findData.cFileName; + } + patchFiles.push_back(sfallRes); +} + +void LoadOrder::init() { + SfallResourceFile(); // Add external sfall resource file (load order is before patchXXX.dat) GetExtraPatches(); MultiPatchesPatch(); - if (GetConfigInt("Misc", "DataLoadOrderPatch", 1)) { + //if (IniReader::GetConfigInt("Misc", "DataLoadOrderPatch", 1)) { dlog("Applying data load order patch.", DL_INIT); MakeCall(0x444259, game_init_databases_hack1); MakeCall(0x4442F1, game_init_databases_hack2); HookCall(0x44436D, game_init_databases_hook); SafeWrite8(0x4DFAEC, 0x1D); // error correction (ecx > ebx) dlogr(" Done", DL_INIT); - } else /*if (!patchFiles.empty())*/ { - HookCall(0x44436D, game_init_databases_hook1); - } + //} else /*if (!patchFiles.empty())*/ { + // HookCall(0x44436D, game_init_databases_hook1); + //} - femaleMsgs = GetConfigInt("Misc", "FemaleDialogMsgs", 0); + femaleMsgs = IniReader::GetConfigInt("Misc", "FemaleDialogMsgs", 0); if (femaleMsgs) { dlog("Applying alternative female dialog files patch.", DL_INIT); MakeJump(0x4A6BCD, scr_get_dialog_msg_file_hack1); @@ -457,14 +503,7 @@ void LoadOrder::init() { LoadGameHook::OnAfterGameStarted() += CheckPlayerGender; if (femaleMsgs > 1) { MakeCall(0x480A95, gnw_main_hack); // before new game start from main menu. TODO: need moved to address 0x480A9A (it busy in movies.cpp) - LoadGameHook::OnGameExit() += []() { - if (cutsPatch) { // restore - SafeWrite32(0x43FA9F, FO_VAR_aTextSCuts); - SafeWrite32(0x44EB5B, FO_VAR_aTextSCutsS); - SafeWrite32(0x48152E, FO_VAR_aTextSCutsSS); - cutsPatch = false; - } - }; + LoadGameHook::OnGameExit() += PlayerGenderCutsRestore; } dlogr(" Done", DL_INIT); } @@ -473,7 +512,7 @@ void LoadOrder::init() { // first check the existence of the art file of the current critter and then replace the art alias if file not found HookCall(0x419440, art_get_name_hook); SafeWrite16(0x419521, 0x003B); // jmp 0x419560 - if (GetConfigInt("Misc", "EnableHeroAppearanceMod", 0) <= 0) { // Hero Appearance mod uses an alternative code + if (IniReader::GetConfigInt("Misc", "EnableHeroAppearanceMod", 0) <= 0) { // Hero Appearance mod uses an alternative code MakeCall(0x419560, art_get_name_hack); } @@ -486,6 +525,12 @@ void LoadOrder::init() { MakeCall(0x47FBBF, SlotMap2Game_hack_attr, 1); dlogr(" Done", DL_INIT); + // Load fonts based on the game language + HookCalls(load_font_hook, { + 0x4D5621, // load_font_ + 0x441D58 // FMLoadFont_ + }); + LoadGameHook::OnAfterGameInit() += RemoveSavFiles; LoadGameHook::OnGameReset() += []() { savPrototypes.clear(); diff --git a/sfall/Modules/MainMenu.cpp b/sfall/Modules/MainMenu.cpp index baa2bc21..04beb42c 100644 --- a/sfall/Modules/MainMenu.cpp +++ b/sfall/Modules/MainMenu.cpp @@ -101,17 +101,17 @@ static void __declspec(naked) MainMenuTextHook() { void MainMenu::init() { int offset; - if (offset = GetConfigInt("Misc", "MainMenuCreditsOffsetX", 0)) { + if (offset = IniReader::GetConfigInt("Misc", "MainMenuCreditsOffsetX", 0)) { SafeWrite32(0x481753, 15 + offset); } - if (offset = GetConfigInt("Misc", "MainMenuCreditsOffsetY", 0)) { + if (offset = IniReader::GetConfigInt("Misc", "MainMenuCreditsOffsetY", 0)) { SafeWrite32(0x48175C, 460 + offset); } - if (offset = GetConfigInt("Misc", "MainMenuOffsetX", 0)) { + if (offset = IniReader::GetConfigInt("Misc", "MainMenuOffsetX", 0)) { SafeWrite32(0x48187C, 30 + offset); MainMenuTextOffset = offset; } - if (offset = GetConfigInt("Misc", "MainMenuOffsetY", 0)) { + if (offset = IniReader::GetConfigInt("Misc", "MainMenuOffsetY", 0)) { MainMenuYOffset = offset; MainMenuTextOffset += offset * 640; MakeJump(0x481844, MainMenuButtonYHook); @@ -122,14 +122,14 @@ void MainMenu::init() { MakeJump(0x4817AB, MainMenuTextHook); - OverrideColour = GetConfigInt("Misc", "MainMenuFontColour", 0); + OverrideColour = IniReader::GetConfigInt("Misc", "MainMenuFontColour", 0); if (OverrideColour & 0xFF) { OverrideColour &= 0x00FF00FF; OverrideColour |= 0x06000000; unsigned char flags = static_cast((OverrideColour & 0xFF0000) >> 16); if (!(flags & 1)) SafeWrite32(0x481748, (DWORD)&OverrideColour); } - OverrideColour2 = GetConfigInt("Misc", "MainMenuBigFontColour", 0) & 0xFF; + OverrideColour2 = IniReader::GetConfigInt("Misc", "MainMenuBigFontColour", 0) & 0xFF; if (OverrideColour2) SafeWrite32(0x481906, (DWORD)&OverrideColour2); } diff --git a/sfall/Modules/Message.cpp b/sfall/Modules/Message.cpp index 33455d6d..20cad7e0 100644 --- a/sfall/Modules/Message.cpp +++ b/sfall/Modules/Message.cpp @@ -29,7 +29,8 @@ namespace sfall { #define CASTMSG(adr) reinterpret_cast(adr) -const fo::MessageList* gameMsgFiles[] = { + +const fo::MessageList* Message::gameMsgFiles[] = { CASTMSG(MSG_FILE_COMBAT), CASTMSG(MSG_FILE_AI), CASTMSG(MSG_FILE_SCRNAME), @@ -53,7 +54,13 @@ const fo::MessageList* gameMsgFiles[] = { }; #undef CASTMSG -ExtraGameMessageListsMap gExtraGameMsgLists; +static char gameLanguage[32]; // (max length of language string is 40) + +const char* Message::GameLanguage() { + return &gameLanguage[0]; +} + +ExtraGameMessageListsMap Message::gExtraGameMsgLists; static std::vector msgFileList; static long msgNumCounter = 0x3000; @@ -66,12 +73,13 @@ static long __fastcall ReplaceGenderWord(fo::MessageNode* msgData, DWORD* msgFil if (!InDialog() || msgData->flags & MSG_GENDER_CHECK_FLG) return 1; if (heroIsFemale < 0) heroIsFemale = fo::HeroIsFemale(); - unsigned char* _pos = (u_char*)msgData->message; + unsigned char* _pos = (unsigned char*)msgData->message; unsigned char* pos; - while ((pos = (u_char*)std::strchr((char*)_pos, '^')) != 0) { // pos - pointer to the character position + + while ((pos = (unsigned char*)std::strchr((char*)_pos, '^')) != 0) { // pos - pointer to the character position _pos = pos; // next find position - for (u_char* n = pos - 1; ; n--) { - if (n < (u_char*)msgData->message) { + for (unsigned char* n = pos - 1; ; n--) { + if (n < (unsigned char*)msgData->message) { _pos++; // error, open char not found break; } else if (*n == '<') { @@ -104,6 +112,7 @@ static long __fastcall ReplaceGenderWord(fo::MessageNode* msgData, DWORD* msgFil } if (_pos > pos) break; } + // set flag unsigned long outValue; fo::func::message_find(msgFile, msgData->number, &outValue); @@ -150,39 +159,6 @@ noFile: } } -fo::MessageNode* GetMsgNode(fo::MessageList* msgList, int msgRef) { - if (msgList != nullptr && msgList->numMsgs > 0) { - fo::MessageNode *msgNode = msgList->nodes; - long last = msgList->numMsgs - 1; - long first = 0; - long mid; - - // Use Binary Search to find msg - while (first <= last) { - mid = (first + last) / 2; - if (msgRef > msgNode[mid].number) - first = mid + 1; - else if (msgRef < msgNode[mid].number) - last = mid - 1; - else - return &msgNode[mid]; - } - } - return nullptr; -} - -char* GetMsg(fo::MessageList* msgList, int msgRef, int msgNum) { - fo::MessageNode *msgNode = GetMsgNode(msgList, msgRef); - if (msgNode) { - if (msgNum == 2) { - return msgNode->message; - } else if (msgNum == 1) { - return msgNode->audio; - } - } - return nullptr; -} - static void ReadExtraGameMsgFiles() { if (!msgFileList.empty()) { int number = 0; @@ -198,7 +174,7 @@ static void ReadExtraGameMsgFiles() { path += ".msg"; fo::MessageList* list = new fo::MessageList(); if (fo::func::message_load(list, path.c_str()) == 1) { - gExtraGameMsgLists.insert(std::make_pair(0x2000 + number, list)); + Message::gExtraGameMsgLists.insert(std::make_pair(0x2000 + number, list)); } else { delete list; } @@ -211,7 +187,7 @@ static void ReadExtraGameMsgFiles() { long Message::AddExtraMsgFile(const char* msgName, long msgNumber) { if (msgNumber) { if (msgNumber < 0x2000 || msgNumber > 0x2FFF) return -1; - if (gExtraGameMsgLists.count(msgNumber)) return 0; // file has already been added + if (Message::gExtraGameMsgLists.count(msgNumber)) return 0; // file has already been added } else if (msgNumCounter > 0x3FFF) return -3; std::string path("game\\"); @@ -226,15 +202,15 @@ long Message::AddExtraMsgFile(const char* msgName, long msgNumber) { //} } if (msgNumber == 0) msgNumber = msgNumCounter++; - gExtraGameMsgLists.emplace(msgNumber, list); + Message::gExtraGameMsgLists.emplace(msgNumber, list); return msgNumber; } static void ClearScriptAddedExtraGameMsg() { // C++11 - for (auto it = gExtraGameMsgLists.begin(); it != gExtraGameMsgLists.end();) { + for (auto it = Message::gExtraGameMsgLists.begin(); it != Message::gExtraGameMsgLists.end();) { if (it->first >= 0x3000 && it->first <= 0x3FFF) { fo::func::message_exit(it->second.get()); - it = gExtraGameMsgLists.erase(it); + it = Message::gExtraGameMsgLists.erase(it); } else { ++it; } @@ -244,22 +220,23 @@ static void ClearScriptAddedExtraGameMsg() { // C++11 } static void FallbackEnglishLoadMsgFiles() { - char value[128]; - if (fo::func::get_game_config_string(value, "system", "language") && _stricmp(value, "english") != 0) { - HookCall(0x484B18, message_load_hook); + const char* lang; + if (fo::func::get_game_config_string(&lang, "system", "language")) { + strncpy_s(gameLanguage, lang, _TRUNCATE); + if (_stricmp(lang, "english") != 0) HookCall(0x484B18, message_load_hook); } } static void ClearReadExtraGameMsgFiles() { - for (auto it = gExtraGameMsgLists.begin(); it != gExtraGameMsgLists.end(); ++it) { + for (auto it = Message::gExtraGameMsgLists.begin(); it != Message::gExtraGameMsgLists.end(); ++it) { fo::func::message_exit(it->second.get()); } } void Message::init() { - msgFileList = GetConfigList("Misc", "ExtraGameMsgFileList", "", 512); + msgFileList = IniReader::GetConfigList("Misc", "ExtraGameMsgFileList", "", 512); - if (GetConfigInt("Misc", "DialogGenderWords", 0)) { + if (IniReader::GetConfigInt("Misc", "DialogGenderWords", 0)) { dlog("Applying dialog gender words patch.", DL_INIT); HookCall(0x4A6CEE, scr_get_msg_str_speech_hook); SafeWrite16(0x484C62, 0x9090); // message_search_ diff --git a/sfall/Modules/Message.h b/sfall/Modules/Message.h index 1e244000..07204c91 100644 --- a/sfall/Modules/Message.h +++ b/sfall/Modules/Message.h @@ -22,6 +22,7 @@ #include #include "..\main.h" +//#include "..\FalloutEngine\Fallout2.h" #include "Module.h" @@ -50,8 +51,6 @@ namespace sfall #define MSG_FILE_WORLDMAP (0x672FB0) typedef std::unordered_map> ExtraGameMessageListsMap; -extern ExtraGameMessageListsMap gExtraGameMsgLists; -extern const fo::MessageList* gameMsgFiles[]; class Message : public Module { public: @@ -59,10 +58,12 @@ public: void init(); void exit() override; + static const char* GameLanguage(); + + static ExtraGameMessageListsMap gExtraGameMsgLists; + static const fo::MessageList* gameMsgFiles[]; + static long AddExtraMsgFile(const char* msgName, long msgNumber); }; -fo::MessageNode* GetMsgNode(fo::MessageList* msgList, int msgRef); -char* GetMsg(fo::MessageList* msgList, int msgRef, int msgNum); - } diff --git a/sfall/Modules/MetaruleExtender.cpp b/sfall/Modules/MetaruleExtender.cpp index a9fcbcff..9822fc29 100644 --- a/sfall/Modules/MetaruleExtender.cpp +++ b/sfall/Modules/MetaruleExtender.cpp @@ -68,7 +68,7 @@ static long __fastcall op_metarule3_ext(long metafunc, long* args) { break; default: fo::func::debug_printf("\nOPCODE ERROR: metarule3(%d, ...) - metarule function number does not exist.\n > Script: %s, procedure %s.", - metafunc, fo::var::currentProgram->fileName, fo::func::findCurrentProc(fo::var::currentProgram)); + metafunc, fo::var::currentProgram->fileName, fo::func::findCurrentProc(fo::var::currentProgram)); break; } return result; diff --git a/sfall/Modules/MiscPatches.cpp b/sfall/Modules/MiscPatches.cpp index 95b897b3..2fbb6c29 100644 --- a/sfall/Modules/MiscPatches.cpp +++ b/sfall/Modules/MiscPatches.cpp @@ -19,6 +19,8 @@ #include "..\main.h" #include "..\FalloutEngine\Fallout2.h" #include "..\SimplePatch.h" +#include "..\Translate.h" + #include "LoadGameHook.h" #include "MainLoopHook.h" @@ -27,8 +29,7 @@ namespace sfall { -static char mapName[65] = {}; -static char configName[65] = {}; +static char mapName[16] = {}; static char patchName[65] = {}; static char versionString[65] = {}; @@ -145,7 +146,7 @@ static void __declspec(naked) op_obj_can_see_obj_hook() { using namespace fo; using namespace Fields; __asm { - mov edi, [esp + 4]; // buf **ret_objStruct + mov edi, [esp + 4]; // buf **outObject test ebp, ebp; // check only once jz checkSee; xor ebp, ebp; // for only once @@ -165,10 +166,12 @@ static void __declspec(naked) op_obj_can_see_obj_hook() { call fo::funcoffs::make_straight_path_; retn 8; checkSee: + push eax; // keep source push fo::funcoffs::obj_shoot_blocking_at_; // check hex objects func pointer push 0x20; // flags, 0x20 = check ShootThru push edi; - call fo::funcoffs::make_straight_path_func_; + call fo::funcoffs::make_straight_path_func_; // overlapping if len(eax) == 0 + pop ecx; // source mov edx, [edi - 8]; // target mov ebx, [edi]; // blocking object test ebx, ebx; @@ -186,6 +189,7 @@ checkObj: je continue; // see through critter retn 8; continue: + mov [edi], ecx; // outObject - ignore source (for cases of overlapping tiles from multihex critters) mov [edi - 4], ebx; // replace source with blocking object mov dword ptr [esp], 0x456BAB; // repeat from the blocking object retn 8; @@ -339,41 +343,56 @@ palColor: } } -static void __fastcall RemoveAllFloatTextObjects(DWORD tile, DWORD flags) { - if (fo::var::text_object_index > 0) { - for (size_t i = 0; i < fo::var::text_object_index; i++) { +static void __fastcall RemoveAllFloatTextObjects() { + long textCount = fo::var::text_object_index; + if (textCount > 0) { + for (long i = 0; i < textCount; i++) { fo::func::mem_free(fo::var::text_object_list[i]->unknown10); fo::func::mem_free(fo::var::text_object_list[i]); } fo::var::text_object_index = 0; } - __asm { - mov eax, tile; - mov edx, flags; - call fo::funcoffs::tile_set_center_; - } - MainLoopHook::displayWinUpdateState = true; } static void __declspec(naked) obj_move_to_tile_hook() { __asm { - mov ecx, eax; + push eax; + push edx; call RemoveAllFloatTextObjects; - mov eax, ds:[FO_VAR_display_win]; - jmp fo::funcoffs::win_draw_; // update black edges + pop edx; + pop eax; + jmp fo::funcoffs::map_set_elevation_; } } static void __declspec(naked) map_check_state_hook() { + __asm { + push eax; + call RemoveAllFloatTextObjects; + pop eax; + jmp fo::funcoffs::map_load_idx_; + } +} + +static void __declspec(naked) obj_move_to_tile_hook_redraw() { + __asm { + mov MainLoopHook::displayWinUpdateState, 1; + call fo::funcoffs::tile_set_center_; + mov eax, ds:[FO_VAR_display_win]; + jmp fo::funcoffs::win_draw_; // update black edges after tile_set_center_ + } +} + +static void __declspec(naked) map_check_state_hook_redraw() { __asm { cmp MainLoopHook::displayWinUpdateState, 0; - je obj_move_to_tile_hook; + je obj_move_to_tile_hook_redraw; jmp fo::funcoffs::tile_set_center_; } } static void AdditionalWeaponAnimsPatch() { - if (GetConfigInt("Misc", "AdditionalWeaponAnims", 0)) { + if (IniReader::GetConfigInt("Misc", "AdditionalWeaponAnims", 0)) { dlog("Applying additional weapon animations patch.", DL_INIT); SafeWrite8(0x419320, 18); // art_get_code_ HookCalls(WeaponAnimHook, { @@ -386,25 +405,25 @@ static void AdditionalWeaponAnimsPatch() { static void SkilldexImagesPatch() { dlog("Checking for changed skilldex images.", DL_INIT); - long tmp = GetConfigInt("Misc", "Lockpick", 293); + long tmp = IniReader::GetConfigInt("Misc", "Lockpick", 293); if (tmp != 293) SafeWrite32(0x518D54, tmp); - tmp = GetConfigInt("Misc", "Steal", 293); + tmp = IniReader::GetConfigInt("Misc", "Steal", 293); if (tmp != 293) SafeWrite32(0x518D58, tmp); - tmp = GetConfigInt("Misc", "Traps", 293); + tmp = IniReader::GetConfigInt("Misc", "Traps", 293); if (tmp != 293) SafeWrite32(0x518D5C, tmp); - tmp = GetConfigInt("Misc", "FirstAid", 293); + tmp = IniReader::GetConfigInt("Misc", "FirstAid", 293); if (tmp != 293) SafeWrite32(0x518D4C, tmp); - tmp = GetConfigInt("Misc", "Doctor", 293); + tmp = IniReader::GetConfigInt("Misc", "Doctor", 293); if (tmp != 293) SafeWrite32(0x518D50, tmp); - tmp = GetConfigInt("Misc", "Science", 293); + tmp = IniReader::GetConfigInt("Misc", "Science", 293); if (tmp != 293) SafeWrite32(0x518D60, tmp); - tmp = GetConfigInt("Misc", "Repair", 293); + tmp = IniReader::GetConfigInt("Misc", "Repair", 293); if (tmp != 293) SafeWrite32(0x518D64, tmp); dlogr(" Done", DL_INIT); } static void ScienceOnCrittersPatch() { - switch (GetConfigInt("Misc", "ScienceOnCritters", 0)) { + switch (IniReader::GetConfigInt("Misc", "ScienceOnCritters", 0)) { case 1: HookCall(0x41276E, action_use_skill_on_hook_science); break; @@ -419,7 +438,7 @@ static void BoostScriptDialogLimitPatch() { 0x4A50C2, 0x4A5169, 0x4A52FA, 0x4A5302, 0x4A6B86, 0x4A6BE0, 0x4A6C37, }; - if (GetConfigInt("Misc", "BoostScriptDialogLimit", 0)) { + if (IniReader::GetConfigInt("Misc", "BoostScriptDialogLimit", 0)) { const int scriptDialogCount = 10000; dlog("Applying script dialog limit patch.", DL_INIT); scriptDialog = new int[scriptDialogCount * 2]; // Because the msg structure is 8 bytes, not 4. @@ -432,7 +451,7 @@ static void BoostScriptDialogLimitPatch() { } static void NumbersInDialoguePatch() { - if (GetConfigInt("Misc", "NumbersInDialogue", 0)) { + if (IniReader::GetConfigInt("Misc", "NumbersInDialogue", 0)) { dlog("Applying numbers in dialogue patch.", DL_INIT); SafeWrite32(0x502C32, 0x2000202E); SafeWrite8(0x446F3B, 0x35); @@ -455,7 +474,7 @@ static void InstantWeaponEquipPatch() { 0x472996, // invenWieldFunc_ }; - if (GetConfigInt("Misc", "InstantWeaponEquip", 0)) { + if (IniReader::GetConfigInt("Misc", "InstantWeaponEquip", 0)) { //Skip weapon equip/unequip animations dlog("Applying instant weapon equip patch.", DL_INIT); SafeWriteBatch(CodeType::JumpShort, PutAwayWeapon); // jmps @@ -468,7 +487,7 @@ static void InstantWeaponEquipPatch() { } static void DontTurnOffSneakIfYouRunPatch() { - if (GetConfigInt("Misc", "DontTurnOffSneakIfYouRun", 0)) { + if (IniReader::GetConfigInt("Misc", "DontTurnOffSneakIfYouRun", 0)) { dlog("Applying DontTurnOffSneakIfYouRun patch.", DL_INIT); SafeWrite8(0x418135, CodeType::JumpShort); dlogr(" Done", DL_INIT); @@ -476,7 +495,7 @@ static void DontTurnOffSneakIfYouRunPatch() { } static void PlayIdleAnimOnReloadPatch() { - if (GetConfigInt("Misc", "PlayIdleAnimOnReload", 0)) { + if (IniReader::GetConfigInt("Misc", "PlayIdleAnimOnReload", 0)) { dlog("Applying idle anim on reload patch.", DL_INIT); HookCall(0x460B8C, intface_item_reload_hook); dlogr(" Done", DL_INIT); @@ -484,7 +503,7 @@ static void PlayIdleAnimOnReloadPatch() { } static void MotionScannerFlagsPatch() { - if (long flags = GetConfigInt("Misc", "MotionScannerFlags", 1)) { + if (long flags = IniReader::GetConfigInt("Misc", "MotionScannerFlags", 1)) { dlog("Applying MotionScannerFlags patch.", DL_INIT); if (flags & 1) MakeJump(0x41BBE9, automap_hack); if (flags & 2) { @@ -512,7 +531,7 @@ static void EncounterTableSizePatch() { 0x4C0815, 0x4C0D4A, 0x4C0FD4, }; - int tableSize = GetConfigInt("Misc", "EncounterTableSize", 0); + int tableSize = IniReader::GetConfigInt("Misc", "EncounterTableSize", 0); if (tableSize > 40) { dlog("Applying EncounterTableSize patch.", DL_INIT); if (tableSize > 50) { @@ -528,7 +547,7 @@ static void EncounterTableSizePatch() { } static void DisablePipboyAlarmPatch() { - if (GetConfigInt("Misc", "DisablePipboyAlarm", 0)) { + if (IniReader::GetConfigInt("Misc", "DisablePipboyAlarm", 0)) { dlog("Applying Disable Pip-Boy alarm button patch.", DL_INIT); SafeWrite8(0x499518, CodeType::Ret); SafeWrite8(0x443601, 0x0); @@ -537,7 +556,7 @@ static void DisablePipboyAlarmPatch() { } static void ObjCanSeeShootThroughPatch() { - if (GetConfigInt("Misc", "ObjCanSeeObj_ShootThru_Fix", 0)) { + if (IniReader::GetConfigInt("Misc", "ObjCanSeeObj_ShootThru_Fix", 0)) { dlog("Applying obj_can_see_obj fix for seeing through critters and ShootThru objects.", DL_INIT); HookCall(0x456BC6, op_obj_can_see_obj_hook); dlogr(" Done", DL_INIT); @@ -547,7 +566,7 @@ static void ObjCanSeeShootThroughPatch() { static void OverrideMusicDirPatch() { static const char* musicOverridePath = "data\\sound\\music\\"; - if (long overrideMode = GetConfigInt("Sound", "OverrideMusicDir", 0)) { + if (long overrideMode = IniReader::GetConfigInt("Sound", "OverrideMusicDir", 0)) { SafeWriteBatch((DWORD)musicOverridePath, {0x4449C2, 0x4449DB}); // set paths if not present in the cfg if (overrideMode == 2) { SafeWriteBatch((DWORD)musicOverridePath, {0x518E78, 0x518E7C}); @@ -557,7 +576,7 @@ static void OverrideMusicDirPatch() { } static void DialogueFix() { - if (GetConfigInt("Misc", "DialogueFix", 1)) { + if (IniReader::GetConfigInt("Misc", "DialogueFix", 1)) { dlog("Applying dialogue patch.", DL_INIT); SafeWrite8(0x446848, 0x31); dlogr(" Done", DL_INIT); @@ -565,7 +584,7 @@ static void DialogueFix() { } static void AlwaysReloadMsgs() { - if (GetConfigInt("Misc", "AlwaysReloadMsgs", 0)) { + if (IniReader::GetConfigInt("Misc", "AlwaysReloadMsgs", 0)) { dlog("Applying always reload messages patch.", DL_INIT); SafeWrite8(0x4A6B8D, 0x0); dlogr(" Done", DL_INIT); @@ -573,7 +592,7 @@ static void AlwaysReloadMsgs() { } static void InterfaceWindowPatch() { - if (GetConfigInt("Misc", "RemoveWindowRounding", 1)) { + if (IniReader::GetConfigInt("Misc", "RemoveWindowRounding", 1)) { SafeWriteBatch(CodeType::JumpShort, {0x4D6EDD, 0x4D6F12}); } @@ -602,7 +621,7 @@ static void InterfaceWindowPatch() { } static void InventoryCharacterRotationSpeedPatch() { - long setting = GetConfigInt("Misc", "SpeedInventoryPCRotation", 166); + long setting = IniReader::GetConfigInt("Misc", "SpeedInventoryPCRotation", 166); if (setting != 166 && setting <= 1000) { dlog("Applying SpeedInventoryPCRotation patch.", DL_INIT); SafeWrite32(0x47066B, setting); @@ -622,7 +641,7 @@ static void UIAnimationSpeedPatch() { } static void MusicInDialoguePatch() { - if (GetConfigInt("Misc", "EnableMusicInDialogue", 0)) { + if (IniReader::GetConfigInt("Misc", "EnableMusicInDialogue", 0)) { dlog("Applying music in dialogue patch.", DL_INIT); SafeWrite8(0x44525B, 0); //BlockCall(0x450627); @@ -631,7 +650,7 @@ static void MusicInDialoguePatch() { } static void PipboyAvailableAtStartPatch() { - switch (GetConfigInt("Misc", "PipBoyAvailableAtGameStart", 0)) { + switch (IniReader::GetConfigInt("Misc", "PipBoyAvailableAtGameStart", 0)) { case 1: LoadGameHook::OnBeforeGameStart() += []() { fo::var::gmovie_played_list[3] = true; // PipBoy aquiring video @@ -644,7 +663,7 @@ static void PipboyAvailableAtStartPatch() { } static void DisableHorriganPatch() { - if (GetConfigInt("Misc", "DisableHorrigan", 0)) { + if (IniReader::GetConfigInt("Misc", "DisableHorrigan", 0)) { LoadGameHook::OnAfterGameStarted() += []() { fo::var::Meet_Frank_Horrigan = true; }; @@ -652,8 +671,8 @@ static void DisableHorriganPatch() { } static void DisplaySecondWeaponRangePatch() { - // Display the range of the second attack mode in the inventory when you switch weapon modes in active item slots - //if (GetConfigInt("Misc", "DisplaySecondWeaponRange", 1)) { + // Display the range of the secondary attack mode in the inventory when you switch weapon modes in active item slots + //if (IniReader::GetConfigInt("Misc", "DisplaySecondWeaponRange", 1)) { dlog("Applying display second weapon range patch.", DL_INIT); HookCall(0x472201, display_stats_hook); dlogr(" Done", DL_INIT); @@ -661,7 +680,7 @@ static void DisplaySecondWeaponRangePatch() { } static void KeepWeaponSelectModePatch() { - //if (GetConfigInt("Misc", "KeepWeaponSelectMode", 1)) { + //if (IniReader::GetConfigInt("Misc", "KeepWeaponSelectMode", 1)) { dlog("Applying keep weapon select mode patch.", DL_INIT); MakeCall(0x4714EC, switch_hand_hack, 1); dlogr(" Done", DL_INIT); @@ -673,7 +692,7 @@ static void PartyMemberSkillPatch() { // Note: this will cause the party member to apply his/her skill when you use First Aid/Doctor skill on the player, but only if // the player is standing next to the party member. Because the related engine function is not fully implemented, enabling // this option without a global script that overrides First Aid/Doctor functions has very limited usefulness - if (GetConfigInt("Misc", "PartyMemberSkillFix", 0) != 0) { + if (IniReader::GetConfigInt("Misc", "PartyMemberSkillFix", 0) != 0) { dlog("Applying party member using First Aid/Doctor skill patch.", DL_INIT); HookCall(0x412836, action_use_skill_on_hook); dlogr(" Done", DL_INIT); @@ -691,7 +710,7 @@ struct CodeData { #pragma pack(pop) static void SkipLoadingGameSettingsPatch() { - if (int skipLoading = GetConfigInt("Misc", "SkipLoadingGameSettings", 0)) { + if (int skipLoading = IniReader::GetConfigInt("Misc", "SkipLoadingGameSettings", 0)) { dlog("Applying skip loading game settings from a saved game patch.", DL_INIT); BlockCall(0x493421); SafeWrite8(0x4935A8, 0x1F); @@ -708,7 +727,7 @@ static void SkipLoadingGameSettingsPatch() { } static void UseWalkDistancePatch() { - int distance = GetConfigInt("Misc", "UseWalkDistance", 3) + 2; + int distance = IniReader::GetConfigInt("Misc", "UseWalkDistance", 3) + 2; if (distance > 1 && distance < 5) { dlog("Applying walk distance for using objects patch.", DL_INIT); SafeWriteBatch(distance, {0x411FF0, 0x4121C4, 0x412475, 0x412906}); // default is 5 @@ -717,7 +736,7 @@ static void UseWalkDistancePatch() { } static void F1EngineBehaviorPatch() { - if (GetConfigInt("Misc", "Fallout1Behavior", 0)) { + if (IniReader::GetConfigInt("Misc", "Fallout1Behavior", 0)) { dlog("Applying Fallout 1 engine behavior patch.", DL_INIT); BlockCall(0x4A4343); // disable playing the final movie/credits after the endgame slideshow SafeWrite8(0x477C71, CodeType::JumpShort); // disable halving the weight for power armor items @@ -740,8 +759,10 @@ static void EngineOptimizationPatches() { // Speed up display_msg script function HookCall(0x455404, op_display_msg_hook); - // Remove duplicate code from intface_redraw_ engine function - BlockCall(0x45EBBF); + // Remove redundant/duplicate code + BlockCall(0x45EBBF); // intface_redraw_ + BlockCall(0x4A4859); // exec_script_proc_ + SafeMemSet(0x455189, CodeType::Nop, 11); // op_create_object_sid_ // Improve performance of the data conversion of script interpreter // mov eax, [edx+eax]; bswap eax; ret; @@ -758,31 +779,25 @@ static void EngineOptimizationPatches() { void MiscPatches::init() { EngineOptimizationPatches(); - if (GetConfigString("Misc", "StartingMap", "", mapName, 64)) { + if (IniReader::GetConfigString("Misc", "StartingMap", "", mapName, 16)) { dlog("Applying starting map patch.", DL_INIT); SafeWrite32(0x480AAA, (DWORD)&mapName); dlogr(" Done", DL_INIT); } - if (GetConfigString("Misc", "VersionString", "", versionString, 64)) { + if (IniReader::GetConfigString("Misc", "VersionString", "", versionString, 65)) { dlog("Applying version string patch.", DL_INIT); SafeWrite32(0x4B4588, (DWORD)&versionString); dlogr(" Done", DL_INIT); } - if (GetConfigString("Misc", "ConfigFile", "", configName, 64)) { - dlog("Applying config file patch.", DL_INIT); - SafeWriteBatch((DWORD)&configName, {0x444BA5, 0x444BCA}); - dlogr(" Done", DL_INIT); - } - - if (GetConfigString("Misc", "PatchFile", "", patchName, 64)) { + if (IniReader::GetConfigString("Misc", "PatchFile", "", patchName, 65)) { dlog("Applying patch file patch.", DL_INIT); SafeWrite32(0x444323, (DWORD)&patchName); dlogr(" Done", DL_INIT); } - if (GetConfigInt("Misc", "SingleCore", 1)) { + if (IniReader::GetConfigInt("Misc", "SingleCore", 1)) { dlog("Applying single core patch.", DL_INIT); HANDLE process = GetCurrentProcess(); SetProcessAffinityMask(process, 1); @@ -790,14 +805,14 @@ void MiscPatches::init() { dlogr(" Done", DL_INIT); } - if (GetConfigInt("Misc", "OverrideArtCacheSize", 0)) { + if (IniReader::GetConfigInt("Misc", "OverrideArtCacheSize", 0)) { dlog("Applying override art cache size patch.", DL_INIT); SafeWrite32(0x418867, 0x90909090); SafeWrite32(0x418872, 256); dlogr(" Done", DL_INIT); } - int time = GetConfigInt("Misc", "CorpseDeleteTime", 6); // time in days + int time = IniReader::GetConfigInt("Misc", "CorpseDeleteTime", 6); // time in days if (time != 6) { dlog("Applying corpse deletion time patch.", DL_INIT); if (time <= 0) { @@ -811,17 +826,30 @@ void MiscPatches::init() { dlogr(" Done", DL_INIT); } + // Set idle function + fo::var::idle_func = reinterpret_cast(Sleep); + SafeWrite16(0x4C9F12, 0x7D6A); // push 125 (ms) + BlockCall(0x4425E6); // Patch out ereg call + SafeWrite8(0x4810AB, CodeType::JumpShort); // Disable selfrun + SimplePatch(0x440C2A, "Misc", "SpecialDeathGVAR", fo::GVAR_MODOC_SHITTY_DEATH); // Remove hardcoding for maps with IDs 19 and 37 - if (GetConfigInt("Misc", "DisableSpecialMapIDs", 0)) { - dlog("Applying disable special map IDs patch.", DL_INIT); + if (IniReader::GetConfigInt("Misc", "DisableSpecialMapIDs", 0)) { + dlog("Applying disable special maps handling patch.", DL_INIT); SafeWriteBatch(0, {0x4836D6, 0x4836DB}); dlogr(" Done", DL_INIT); } + // Remove hardcoding for city areas 45 and 46 (AREA_FAKE_VAULT_13) + if (IniReader::GetConfigInt("Misc", "DisableSpecialAreas", 0)) { + dlog("Applying disable special areas handling patch.", DL_INIT); + SafeWrite8(0x4C0576, CodeType::JumpShort); + dlogr(" Done", DL_INIT); + } + // Highlight "Radiated" in red color when the player is under the influence of negative effects of radiation HookCalls(ListDrvdStats_hook, {0x43549C, 0x4354BE}); @@ -834,11 +862,14 @@ void MiscPatches::init() { // Allow setting custom colors from the game palette for object outlines MakeCall(0x48EE00, obj_render_outline_hack); - // Remove floating text messages after moving to another map elevation - // and redraw the screen to update black edges of the map (HRP bug) + // Remove floating text messages after moving to another map or elevation + HookCall(0x48A94B, obj_move_to_tile_hook); + HookCall(0x4836BB, map_check_state_hook); + + // Redraw the screen to update black edges of the map (HRP bug) // https://github.com/phobos2077/sfall/issues/282 - HookCall(0x48A954, obj_move_to_tile_hook); - HookCall(0x483726, map_check_state_hook); + HookCall(0x48A954, obj_move_to_tile_hook_redraw); + HookCall(0x483726, map_check_state_hook_redraw); F1EngineBehaviorPatch(); DialogueFix(); diff --git a/sfall/Modules/Movies.cpp b/sfall/Modules/Movies.cpp index 946cf785..435a6cd7 100644 --- a/sfall/Modules/Movies.cpp +++ b/sfall/Modules/Movies.cpp @@ -522,7 +522,7 @@ static void __declspec(naked) op_play_gmovie_hack() { } void SkipOpeningMoviesPatch() { - int skipOpening = GetConfigInt("Misc", "SkipOpeningMovies", 0); + int skipOpening = IniReader::GetConfigInt("Misc", "SkipOpeningMovies", 0); if (skipOpening) { dlog("Skipping opening movies.", DL_INIT); SafeWrite16(0x4809C7, 0x1CEB); // jmps 0x4809E5 @@ -575,9 +575,9 @@ void Movies::init() { _itoa_s(i + 1, &optName[5], 3, 10); if (i < DEFAULT_MOVIES) { - GetConfigString("Misc", optName, fo::var::movie_list[i], &MoviePaths[index], 65); + IniReader::GetConfigString("Misc", optName, fo::var::movie_list[i], &MoviePaths[index], 65); } else { - GetConfigString("Misc", optName, "", &MoviePaths[index], 65); + IniReader::GetConfigString("Misc", optName, "", &MoviePaths[index], 65); } } dlog(".", DL_INIT); @@ -591,7 +591,7 @@ void Movies::init() { Implement subtitle output from the need to play an mve file in the background. */ if (Graphics::mode != 0) { - int allowDShowMovies = GetConfigInt("Graphics", "AllowDShowMovies", 0); + int allowDShowMovies = IniReader::GetConfigInt("Graphics", "AllowDShowMovies", 0); if (allowDShowMovies > 0) { Graphics::AviMovieWidthFit = (allowDShowMovies >= 2); MakeJump(0x44E690, gmovie_play_hack); @@ -604,7 +604,7 @@ void Movies::init() { DWORD days = SimplePatch(0x4A36EC, "Misc", "MovieTimer_artimer4", 360, 0); days = SimplePatch(0x4A3747, "Misc", "MovieTimer_artimer3", 270, 0, days); days = SimplePatch(0x4A376A, "Misc", "MovieTimer_artimer2", 180, 0, days); - Artimer1DaysCheckTimer = GetConfigInt("Misc", "MovieTimer_artimer1", 90); + Artimer1DaysCheckTimer = IniReader::GetConfigInt("Misc", "MovieTimer_artimer1", 90); if (Artimer1DaysCheckTimer != 90) { Artimer1DaysCheckTimer = max(0, min(days, Artimer1DaysCheckTimer)); char s[255]; diff --git a/sfall/Modules/Objects.cpp b/sfall/Modules/Objects.cpp index d3c0062e..21eab06f 100644 --- a/sfall/Modules/Objects.cpp +++ b/sfall/Modules/Objects.cpp @@ -95,8 +95,9 @@ pickNewID: // skip PM range (18000 - 83535) } // Reassigns object IDs to all critters upon first loading a map and updates their max HP stat +// TODO: for items? static void map_fix_critter_id() { - long npcStartID = 4096; + long npcStartID = 4096; // 0x1000 fo::GameObject* obj = fo::func::obj_find_first(); while (obj) { if (obj->IsCritter()) { @@ -110,22 +111,10 @@ static void map_fix_critter_id() { } } -static void __declspec(naked) map_load_file_hack() { +static void __declspec(naked) map_load_file_hook() { __asm { - jz mapVirgin; - retn; -mapVirgin: - test eax, eax; - jl skip; // check map index > -1 - call fo::funcoffs::wmMapIsSaveable_; - test eax, eax; - jnz saveable; - retn; -saveable: call map_fix_critter_id; -skip: - xor eax, eax; // set ZF - retn; + jmp fo::funcoffs::map_fix_critter_combat_data_; } } @@ -186,7 +175,7 @@ void Objects::SetAutoUnjamLockTime(DWORD time) { } } -void RestoreObjUnjamAllLocks() { +static void RestoreObjUnjamAllLocks() { if (unjamTimeState) { SafeWrite8(0x4A364A, 0xE8); SafeWrite32(0x4A364B, 0xFFFF9E69); @@ -254,6 +243,7 @@ skip: void Objects::init() { LoadGameHook::OnGameReset() += []() { RestoreObjUnjamAllLocks(); + //fo::var::cur_id = 4; }; HookCall(0x4A38A5, new_obj_id_hook); @@ -261,13 +251,12 @@ void Objects::init() { // Fix the ID range check for item objects with IDs in the negative range // Special ID values are assigned in the negative range - SafeWrite8(0x495273, 0x73); // jge > jae + SafeWrite8(0x495273, 0x73); // jge > jae (partyMemberItemSave_) MakeCall(0x477A0E, item_identical_hack); // don't put item with unique ID to items stack // Fix mapper bug by reassigning object IDs to critters (for unvisited maps) - MakeCall(0x482E6B, map_load_file_hack); - SafeWrite8(0x482E71, 0x85); // jz > jnz + HookCall(0x482DE2, map_load_file_hook); // Additionally fix object IDs for queued events MakeCall(0x4A25BA, queue_add_hack); diff --git a/sfall/Modules/PartyControl.cpp b/sfall/Modules/PartyControl.cpp index 15cef0c0..e6b02b3c 100644 --- a/sfall/Modules/PartyControl.cpp +++ b/sfall/Modules/PartyControl.cpp @@ -18,14 +18,19 @@ #include "..\main.h" #include "..\FalloutEngine\Fallout2.h" +#include "..\Translate.h" #include "..\Utils.h" -#include "HookScripts\InventoryHs.h" + #include "Drugs.h" #include "HookScripts.h" #include "LoadGameHook.h" #include "ScriptExtender.h" //#include "Objects.h" +#include "..\Game\inventory.h" +#include "..\Game\objects.h" +#include "..\Game\tilemap.h" + #include "PartyControl.h" namespace sfall @@ -128,9 +133,9 @@ static void SaveRealDudeState() { realDude.obj_dude = fo::var::obj_dude; realDude.art_vault_guy_num = fo::var::art_vault_guy_num; realDude.itemCurrentItem = fo::var::itemCurrentItem; - memcpy(realDude.itemButtonItems, fo::var::itemButtonItems, sizeof(fo::ItemButtonItem) * 2); - memcpy(realDude.traits, fo::var::pc_trait, sizeof(long) * 2); - memcpy(realDude.perkLevelDataList, fo::var::perkLevelDataList, sizeof(DWORD) * fo::PERK_count); + std::memcpy(realDude.itemButtonItems, fo::var::itemButtonItems, sizeof(fo::ItemButtonItem) * 2); + std::memcpy(realDude.traits, fo::var::pc_trait, sizeof(long) * 2); + std::memcpy(realDude.perkLevelDataList, fo::var::perkLevelDataList, sizeof(DWORD) * fo::PERK_count); strcpy_s(realDude.pc_name, sizeof(fo::var::pc_name), fo::var::pc_name); realDude.Level = fo::var::Level_; realDude.last_level = fo::var::last_level; @@ -176,17 +181,15 @@ static void SetCurrentDude(fo::GameObject* npc) { // copy existing party member perks or reset list for non-party member NPC long isPartyMember = fo::IsPartyMemberByPid(npc->protoId); if (isPartyMember) { - memcpy(fo::var::perkLevelDataList, fo::var::perkLevelDataList + (fo::PERK_count * (isPartyMember - 1)), sizeof(DWORD) * fo::PERK_count); + std::memcpy(fo::var::perkLevelDataList, fo::var::perkLevelDataList[isPartyMember - 1].perkData, sizeof(DWORD) * fo::Perk::PERK_count); } else { - for (int i = 0; i < fo::PERK_count; i++) { - fo::var::perkLevelDataList[i] = 0; - } + std::memset(fo::var::perkLevelDataList, 0, sizeof(DWORD) * fo::Perk::PERK_count); } // change level int level = (isPartyMember) // fo::func::isPartyMember(npc) - ? fo::func::partyMemberGetCurLevel(npc) - : 0; + ? fo::func::partyMemberGetCurLevel(npc) + : 0; fo::var::Level_ = level; fo::var::last_level = level; @@ -215,7 +218,7 @@ static void SetCurrentDude(fo::GameObject* npc) { if (weaponState[i].leftIsCopy) { auto item = fo::func::inven_left_hand(npc); if (item && item->protoId == weaponState[i].leftSlot.item->protoId) { - memcpy(&fo::var::itemButtonItems[0], &weaponState[i].leftSlot, 0x14); + std::memcpy(&fo::var::itemButtonItems[0], &weaponState[i].leftSlot, 0x14); isMatch = true; } weaponState[i].leftIsCopy = false; @@ -223,7 +226,7 @@ static void SetCurrentDude(fo::GameObject* npc) { if (weaponState[i].rightIsCopy) { auto item = fo::func::inven_right_hand(npc); if (item && item->protoId == weaponState[i].rightSlot.item->protoId) { - memcpy(&fo::var::itemButtonItems[1], &weaponState[i].rightSlot, 0x14); + std::memcpy(&fo::var::itemButtonItems[1], &weaponState[i].rightSlot, 0x14); isMatch = true; } weaponState[i].rightIsCopy = false; @@ -291,9 +294,9 @@ static void RestoreRealDudeState(bool redraw = true) { fo::var::art_vault_guy_num = realDude.art_vault_guy_num; fo::var::itemCurrentItem = realDude.itemCurrentItem; - memcpy(fo::var::itemButtonItems, realDude.itemButtonItems, sizeof(fo::ItemButtonItem) * 2); - memcpy(fo::var::pc_trait, realDude.traits, sizeof(long) * 2); - memcpy(fo::var::perkLevelDataList, realDude.perkLevelDataList, sizeof(DWORD) * fo::PERK_count); + std::memcpy(fo::var::itemButtonItems, realDude.itemButtonItems, sizeof(fo::ItemButtonItem) * 2); + std::memcpy(fo::var::pc_trait, realDude.traits, sizeof(long) * 2); + std::memcpy(fo::var::perkLevelDataList, realDude.perkLevelDataList, sizeof(DWORD) * fo::PERK_count); strcpy_s(fo::var::pc_name, sizeof(fo::var::pc_name), realDude.pc_name); fo::var::Level_ = realDude.Level; fo::var::last_level = realDude.last_level; @@ -470,11 +473,11 @@ bool PartyControl::IsNpcControlled() { static bool CopyItemSlots(WeaponStateSlot &element, bool isSwap) { bool isCopy = false; if (fo::var::itemButtonItems[0 + isSwap].itsWeapon && fo::var::itemButtonItems[0 + isSwap].item) { - memcpy(&element.leftSlot, &fo::var::itemButtonItems[0 + isSwap], 0x14); + std::memcpy(&element.leftSlot, &fo::var::itemButtonItems[0 + isSwap], 0x14); element.leftIsCopy = isCopy = true; } if (fo::var::itemButtonItems[1 - isSwap].itsWeapon && fo::var::itemButtonItems[1 - isSwap].item) { - memcpy(&element.rightSlot, &fo::var::itemButtonItems[1 - isSwap], 0x14); + std::memcpy(&element.rightSlot, &fo::var::itemButtonItems[1 - isSwap], 0x14); element.rightIsCopy = isCopy = true; } if (isSwap && isCopy) { @@ -583,8 +586,8 @@ void PartyControl::SwitchToCritter(fo::GameObject* critter) { fo::GameObject* PartyControl::RealDudeObject() { return realDude.obj_dude != nullptr - ? realDude.obj_dude - : fo::var::obj_dude; + ? realDude.obj_dude + : fo::var::obj_dude; } static char levelMsg[12], armorClassMsg[12], addictMsg[16]; @@ -627,9 +630,39 @@ static void __declspec(naked) gdControlUpdateInfo_hook() { } } +//////////////////////////////////////////////////////////////////////////////// + static bool partyOrderPickTargetLoop; static std::vector partyOrderAttackMsg; +struct PartyTarget { + fo::GameObject* member; + fo::GameObject* target; +}; + +static std::vector partyOrderAttackTarget; + +static fo::GameObject* GetMemberTarget(fo::GameObject* member) { + for (auto &el : partyOrderAttackTarget) { + if (el.member->id == member->id) { + fo::GameObject* target = el.target; + if (target && target->critter.IsDead()) el.target = nullptr; + return el.target; + } + } + return nullptr; +} + +static void SetMemberTarget(fo::GameObject* member, fo::GameObject* target) { + for (auto &el : partyOrderAttackTarget) { + if (el.member->id == member->id) { + el.target = target; + return; + } + } + partyOrderAttackTarget.push_back({member, target}); +} + // disables the display of the hit chance value when picking a target static void __declspec(naked) gmouse_bk_process_hack() { __asm { @@ -671,7 +704,10 @@ static void __fastcall action_attack_to(long unused, fo::GameObject* partyMember if (underObject->critter.IsNotDead()) { outlineColor = underObject->outline; - if (fo::var::combatNumTurns || underObject->critter.combatState) { + if ((fo::var::combatNumTurns || underObject->critter.combatState) && + game::Objects::is_within_perception(partyMember, underObject, 0) && // HOOK_WITHINPERCEPTION + fo::func::make_path_func(partyMember, partyMember->tile, underObject->tile, 0, 0, game::Tilemap::obj_path_blocking_at_) > 0) + { underObject->outline = 254 << 8; // flashing red validTarget = underObject; } else { @@ -687,7 +723,7 @@ static void __fastcall action_attack_to(long unused, fo::GameObject* partyMember } while (fo::var::mouse_buttons != 2 && fo::func::get_input() != 27); // 27 - escape code if (validTarget && fo::var::mouse_buttons == 1) { - partyMember->critter.whoHitMe = validTarget; + SetMemberTarget(partyMember, validTarget); validTarget->outline = outlineColor; fo::AIcap* cap = fo::func::ai_cap(partyMember); @@ -754,15 +790,37 @@ static void __declspec(naked) gmouse_handle_event_hook_restore() { } } +static void __fastcall SetOrderTarget(fo::GameObject* attacker) { + if (attacker->critter.teamNum || partyOrderAttackTarget.empty()) return; + fo::GameObject* target = GetMemberTarget(attacker); + if (target) attacker->critter.whoHitMe = target; +} + +static void __declspec(naked) combat_ai_hook_targer() { + __asm { + push ecx; + mov ecx, eax; + call SetOrderTarget; + pop ecx; + mov eax, esi; + jmp fo::funcoffs::ai_danger_source_; + } +} + void PartyControl::OrderAttackPatch() { MakeCall(0x44C4A7, gmouse_handle_event_hack, 2); HookCall(0x44C75F, gmouse_handle_event_hook); HookCall(0x44C69A, gmouse_handle_event_hook_restore); MakeCall(0x44B830, gmouse_bk_process_hack); + + HookCall(0x42B235, combat_ai_hook_targer); + LoadGameHook::OnCombatEnd() += []() { + partyOrderAttackTarget.clear(); + }; } static void NpcAutoLevelPatch() { - npcAutoLevelEnabled = GetConfigInt("Misc", "NPCAutoLevel", 0) != 0; + npcAutoLevelEnabled = IniReader::GetConfigInt("Misc", "NPCAutoLevel", 0) != 0; if (npcAutoLevelEnabled) { dlog("Applying NPC autolevel patch.", DL_INIT); SafeWrite8(0x495CFB, CodeType::JumpShort); // jmps 0x495D28 (skip random check) @@ -791,21 +849,21 @@ void PartyControl::init() { NpcAutoLevelPatch(); - skipCounterAnim = (GetConfigInt("Misc", "SpeedInterfaceCounterAnims", 0) == 3); + skipCounterAnim = (IniReader::GetConfigInt("Misc", "SpeedInterfaceCounterAnims", 0) == 3); // Display party member's current level & AC & addict flag - if (GetConfigInt("Misc", "PartyMemberExtraInfo", 0)) { + if (IniReader::GetConfigInt("Misc", "PartyMemberExtraInfo", 0)) { dlog("Applying display NPC extra info patch.", DL_INIT); HookCall(0x44926F, gdControlUpdateInfo_hook); - Translate("sfall", "PartyLvlMsg", "Lvl:", levelMsg, 12); - Translate("sfall", "PartyACMsg", "AC:", armorClassMsg, 12); - Translate("sfall", "PartyAddictMsg", "Addict", addictMsg, 16); + Translate::Get("sfall", "PartyLvlMsg", "Lvl:", levelMsg, 12); + Translate::Get("sfall", "PartyACMsg", "AC:", armorClassMsg, 12); + Translate::Get("sfall", "PartyAddictMsg", "Addict", addictMsg, 16); dlogr(" Done", DL_INIT); } - partyOrderAttackMsg.push_back(std::move(Translate("sfall", "PartyOrderAttackCreature", "::Growl::", 33))); - partyOrderAttackMsg.push_back(std::move(Translate("sfall", "PartyOrderAttackRobot", "::Beep::", 33))); - auto msgs = TranslateList("sfall", "PartyOrderAttackHuman", "I'll take care of it.|Okay, I got it.", '|', 512); + partyOrderAttackMsg.push_back(Translate::Get("sfall", "PartyOrderAttackCreature", "::Growl::", 33)); + partyOrderAttackMsg.push_back(Translate::Get("sfall", "PartyOrderAttackRobot", "::Beep::", 33)); + auto msgs = Translate::GetList("sfall", "PartyOrderAttackHuman", "I'll take care of it.|Okay, I got it.", '|', 512); partyOrderAttackMsg.insert(partyOrderAttackMsg.cend(), msgs.cbegin(), msgs.cend()); } diff --git a/sfall/Modules/Perks.cpp b/sfall/Modules/Perks.cpp index 1f66518c..5faaccca 100644 --- a/sfall/Modules/Perks.cpp +++ b/sfall/Modules/Perks.cpp @@ -29,7 +29,6 @@ namespace sfall { -using namespace fo; long Perks::PerkLevelMod = 0; @@ -39,10 +38,10 @@ static const int descLen = 256; // maximum text length for interface static char perksFile[MAX_PATH] = {0}; -static char Name[maxNameLen * PERK_count] = {0}; -static char Desc[descLen * PERK_count] = {0}; -static char tName[maxNameLen * TRAIT_count] = {0}; -static char tDesc[descLen * TRAIT_count] = {0}; +static char Name[maxNameLen * fo::Perk::PERK_count] = {0}; +static char Desc[descLen * fo::Perk::PERK_count] = {0}; +static char tName[maxNameLen * fo::Trait::TRAIT_count] = {0}; +static char tDesc[descLen * fo::Trait::TRAIT_count] = {0}; static char PerkBoxTitle[33]; static const int startFakeID = 256; @@ -52,15 +51,15 @@ static bool perksReInit = false; static int perksEnable = 0; static int traitsEnable = 0; -static PerkInfo perks[PERK_count]; -static TraitInfo traits[TRAIT_count]; +static fo::PerkInfo perks[fo::Perk::PERK_count]; +static fo::TraitInfo traits[fo::Trait::TRAIT_count]; struct PerkInfoExt { short id; char reserve[6]; char Name[maxNameLen]; char Desc[descLen]; - PerkInfo data; + fo::PerkInfo data; // extra modificators long stat1; long stat1Mod; @@ -105,10 +104,10 @@ static long RemoveTraitID = -1; static std::list RemovePerkID; static std::list RemoveSelectableID; -static DWORD traitSkillBonuses[TRAIT_count * 18] = {0}; -static DWORD traitStatBonuses[TRAIT_count * (STAT_max_derived + 1)] = {0}; +static DWORD traitSkillBonuses[fo::Trait::TRAIT_count * 18] = {0}; +static DWORD traitStatBonuses[fo::Trait::TRAIT_count * (fo::STAT_max_derived + 1)] = {0}; -static bool disableTraits[TRAIT_count]; +static bool disableTraits[fo::Trait::TRAIT_count]; static DWORD IgnoringDefaultPerks = 0; static DWORD PerkFreqOverride = 0; @@ -149,7 +148,7 @@ static DWORD __stdcall LevelUp() { DWORD eachLevel = PerkFreqOverride; if (!eachLevel) { - if (!Perks::IsTraitDisabled(TRAIT_skilled) && fo::func::trait_level(TRAIT_skilled)) { // Check if the player has the skilled trait + if (Perks::DudeHasTrait(fo::Trait::TRAIT_skilled)) { // Check if the player has the skilled trait eachLevel = 4; } else { eachLevel = 3; @@ -293,16 +292,16 @@ static DWORD __stdcall HaveFakePerks() { } static long __fastcall GetFakePerkLevel(int id) { - int i = id - PERK_count; + int i = id - fo::Perk::PERK_count; return IsOwnedFake(fakePerks[i].ownerId) ? fakePerks[i].Level : 0; } static long __fastcall GetFakePerkImage(int id) { - return fakePerks[id - PERK_count].Image; + return fakePerks[id - fo::Perk::PERK_count].Image; } static FakePerk* __fastcall GetFakePerk(int id) { - return &fakePerks[id - PERK_count]; + return &fakePerks[id - fo::Perk::PERK_count]; } // Get level of taken perk @@ -350,10 +349,10 @@ static DWORD HandleFakeTraits(int isSelect) { if (!IsOwnedFake(fakeTraits[i].ownerId)) continue; if (fo::func::folder_print_line(fakeTraits[i].Name) && !isSelect) { isSelect = 1; - var::folder_card_fid = fakeTraits[i].Image; - var::folder_card_title = (DWORD)fakeTraits[i].Name; - var::folder_card_title2 = 0; - var::folder_card_desc = (DWORD)fakeTraits[i].Desc; + fo::var::folder_card_fid = fakeTraits[i].Image; + fo::var::folder_card_title = (DWORD)fakeTraits[i].Name; + fo::var::folder_card_title2 = 0; + fo::var::folder_card_desc = (DWORD)fakeTraits[i].Desc; } } return isSelect; @@ -362,12 +361,12 @@ static DWORD HandleFakeTraits(int isSelect) { static long __fastcall PlayerHasPerk(int &isSelectPtr) { isSelectPtr = HandleFakeTraits(isSelectPtr); - for (int i = 0; i < PERK_count; i++) { + for (int i = 0; i < fo::Perk::PERK_count; i++) { if (fo::func::perk_level(fo::var::obj_dude, i)) return 0x43438A; // print perks } return (!fakePerks.empty()) - ? 0x43438A // print perks - : 0x434446; // skip print perks + ? 0x43438A // print perks + : 0x434446; // skip print perks } static DWORD __fastcall HaveFakeTraits(int &isSelectPtr) { @@ -395,6 +394,7 @@ static void __declspec(naked) PlayerHasTraitHook() { } static void __declspec(naked) GetPerkLevelHook() { + using namespace fo; __asm { cmp edx, PERK_count; jge fake; @@ -409,6 +409,7 @@ fake: } static void __declspec(naked) GetPerkImageHook() { + using namespace fo; __asm { cmp eax, PERK_count; jge fake; @@ -423,6 +424,7 @@ fake: } static void __declspec(naked) GetPerkNameHook() { + using namespace fo; __asm { cmp eax, PERK_count; jge fake; @@ -438,6 +440,7 @@ fake: } static void __declspec(naked) GetPerkDescHook() { + using namespace fo; __asm { cmp eax, PERK_count; jge fake; @@ -456,6 +459,7 @@ fake: static void __declspec(naked) EndPerkLoopHack() { static const DWORD EndPerkLoopExit = 0x434446; static const DWORD EndPerkLoopCont = 0x4343A5; + using namespace fo; __asm { jl cLoop; // if ebx < 119 push ecx; @@ -510,6 +514,7 @@ next: } static void __declspec(naked) GetPerkSLevelHook() { + using namespace fo; __asm { cmp edx, PERK_count; jge fake; @@ -524,6 +529,7 @@ fake: } static void __declspec(naked) GetPerkSImageHook() { + using namespace fo; __asm { cmp eax, PERK_count; jge fake; @@ -540,6 +546,7 @@ fake: } static void __declspec(naked) GetPerkSNameHook() { + using namespace fo; __asm { cmp eax, PERK_count; jge fake; @@ -557,6 +564,7 @@ fake: } static void __declspec(naked) GetPerkSDescHook() { + using namespace fo; __asm { cmp eax, PERK_count; jge fake; @@ -674,6 +682,7 @@ static long __stdcall AddFakePerk(DWORD perkID) { // Adds perk from selection window to player static void __declspec(naked) AddPerkHook() { + using namespace fo; __asm { cmp edx, PERK_count; jl normalPerk; @@ -700,7 +709,7 @@ end: } // Checks player statistics to add perk in selection listing -static PerkInfo* __fastcall CanAddPerk(DWORD perkID) { +static fo::PerkInfo* __fastcall CanAddPerk(DWORD perkID) { int index = PerkSearchID(perkID); if (index != -1) { int ranks = extPerks[index].data.ranks; @@ -736,7 +745,7 @@ end: } } -static PerkInfo* __fastcall PerkData(DWORD perkID, fo::GameObject* critter, long type) { +static fo::PerkInfo* __fastcall PerkData(DWORD perkID, fo::GameObject* critter, long type) { int index = PerkSearchID(perkID); if (index != -1) { ApplyPerkEffect(index, critter, type); // apply ext. perk to critter @@ -786,16 +795,15 @@ end: } static void __declspec(naked) HeaveHoHook() { + using namespace fo; __asm { xor edx, edx; mov eax, ecx; call fo::funcoffs::stat_level_; lea ebx, [0 + eax * 4]; - sub ebx, eax; + sub ebx, eax; // ST * 3 cmp ebx, esi; // ebx = dist (3*ST), esi = max dist weapon - jle lower; // jump if dist <= max - mov ebx, esi; // dist = max -lower: + cmovg ebx, esi; // if dist > max then dist = max mov eax, ecx; mov edx, PERK_heave_ho; call fo::funcoffs::perk_level_; @@ -809,11 +817,12 @@ lower: } } -static bool perkHeaveHoModFix = false; -void __stdcall ApplyHeaveHoFix() { // not really a fix +bool Perks::perkHeaveHoModTweak = false; + +void __stdcall Perks::ApplyHeaveHoFix() { // not really a fix MakeJump(0x478AC4, HeaveHoHook); - perks[PERK_heave_ho].strengthMin = 0; - perkHeaveHoModFix = true; + perks[fo::Perk::PERK_heave_ho].strengthMin = 0; + perkHeaveHoModTweak = true; } static void PerkEngineInit() { @@ -869,52 +878,52 @@ static void PerkSetup() { SafeWrite32(0x496BF5, (DWORD)&perks[0].image); SafeWrite32(0x496AD4, (DWORD)&perks[0].ranks); } - std::memcpy(perks, var::perk_data, sizeof(PerkInfo) * PERK_count); // copy vanilla data + std::memcpy(perks, fo::var::perk_data, sizeof(fo::PerkInfo) * fo::Perk::PERK_count); // copy vanilla data if (perksEnable) { char num[4]; - for (int i = 0; i < PERK_count; i++) { + for (int i = 0; i < fo::Perk::PERK_count; i++) { _itoa(i, num, 10); - if (iniGetString(num, "Name", "", &Name[i * maxNameLen], maxNameLen - 1, perksFile)) { + if (IniReader::GetString(num, "Name", "", &Name[i * maxNameLen], maxNameLen - 1, perksFile)) { perks[i].name = &Name[i * maxNameLen]; } - if (iniGetString(num, "Desc", "", &Desc[i * descLen], descLen - 1, perksFile)) { + if (IniReader::GetString(num, "Desc", "", &Desc[i * descLen], descLen - 1, perksFile)) { perks[i].description = &Desc[i * descLen]; } int value; - value = iniGetInt(num, "Image", -99999, perksFile); + value = IniReader::GetInt(num, "Image", -99999, perksFile); if (value != -99999) perks[i].image = value; - value = iniGetInt(num, "Ranks", -99999, perksFile); + value = IniReader::GetInt(num, "Ranks", -99999, perksFile); if (value != -99999) perks[i].ranks = value; - value = iniGetInt(num, "Level", -99999, perksFile); + value = IniReader::GetInt(num, "Level", -99999, perksFile); if (value != -99999) perks[i].levelMin = value; - value = iniGetInt(num, "Stat", -99999, perksFile); + value = IniReader::GetInt(num, "Stat", -99999, perksFile); if (value != -99999) perks[i].stat = value; - value = iniGetInt(num, "StatMag", -99999, perksFile); + value = IniReader::GetInt(num, "StatMag", -99999, perksFile); if (value != -99999) perks[i].statMod = value; - value = iniGetInt(num, "Skill1", -99999, perksFile); + value = IniReader::GetInt(num, "Skill1", -99999, perksFile); if (value != -99999) perks[i].skill1 = value; - value = iniGetInt(num, "Skill1Mag", -99999, perksFile); + value = IniReader::GetInt(num, "Skill1Mag", -99999, perksFile); if (value != -99999) perks[i].skill1Min = value; - value = iniGetInt(num, "Type", -99999, perksFile); + value = IniReader::GetInt(num, "Type", -99999, perksFile); if (value != -99999) perks[i].skillOperator = value; - value = iniGetInt(num, "Skill2", -99999, perksFile); + value = IniReader::GetInt(num, "Skill2", -99999, perksFile); if (value != -99999) perks[i].skill2 = value; - value = iniGetInt(num, "Skill2Mag", -99999, perksFile); + value = IniReader::GetInt(num, "Skill2Mag", -99999, perksFile); if (value != -99999) perks[i].skill2Min = value; - value = iniGetInt(num, "STR", -99999, perksFile); + value = IniReader::GetInt(num, "STR", -99999, perksFile); if (value != -99999) perks[i].strengthMin = value; - value = iniGetInt(num, "PER", -99999, perksFile); + value = IniReader::GetInt(num, "PER", -99999, perksFile); if (value != -99999) perks[i].perceptionMin = value; - value = iniGetInt(num, "END", -99999, perksFile); + value = IniReader::GetInt(num, "END", -99999, perksFile); if (value != -99999) perks[i].enduranceMin = value; - value = iniGetInt(num, "CHR", -99999, perksFile); + value = IniReader::GetInt(num, "CHR", -99999, perksFile); if (value != -99999) perks[i].charismaMin = value; - value = iniGetInt(num, "INT", -99999, perksFile); + value = IniReader::GetInt(num, "INT", -99999, perksFile); if (value != -99999) perks[i].intelligenceMin = value; - value = iniGetInt(num, "AGL", -99999, perksFile); + value = IniReader::GetInt(num, "AGL", -99999, perksFile); if (value != -99999) perks[i].agilityMin = value; - value = iniGetInt(num, "LCK", -99999, perksFile); + value = IniReader::GetInt(num, "LCK", -99999, perksFile); if (value != -99999) perks[i].luckMin = value; } if (perksReInit) { @@ -922,46 +931,46 @@ static void PerkSetup() { return; } // adding extra perks with IDs from 119 to 255 - extPerks.reserve(startFakeID - PERK_count); + extPerks.reserve(startFakeID - fo::Perk::PERK_count); extPerks.resize(1); int n = 0; - for (int id = PERK_count; id < startFakeID; id++) { + for (int id = fo::Perk::PERK_count; id < startFakeID; id++) { _itoa(id, num, 10); - int ranks = iniGetInt(num, "Ranks", -1, perksFile); + int ranks = IniReader::GetInt(num, "Ranks", -1, perksFile); if (ranks == -1) continue; extPerks[n].data.ranks = ranks; - extPerks[n].data.image = iniGetInt(num, "Image", -1, perksFile); - extPerks[n].data.levelMin = iniGetInt(num, "Level", -1, perksFile); - extPerks[n].data.stat = iniGetInt(num, "Stat", -1, perksFile); - extPerks[n].data.statMod = iniGetInt(num, "StatMag", 0, perksFile); - extPerks[n].data.skill1 = iniGetInt(num, "Skill1", -1, perksFile); - extPerks[n].data.skill1Min = iniGetInt(num, "Skill1Mag", 0, perksFile); - extPerks[n].data.skillOperator = iniGetInt(num, "Type", 0, perksFile); - extPerks[n].data.skill2 = iniGetInt(num, "Skill2", -1, perksFile); - extPerks[n].data.skill2Min = iniGetInt(num, "Skill2Mag", 0, perksFile); - extPerks[n].data.strengthMin = iniGetInt(num, "STR", 0, perksFile); - extPerks[n].data.perceptionMin = iniGetInt(num, "PER", 0, perksFile); - extPerks[n].data.enduranceMin = iniGetInt(num, "END", 0, perksFile); - extPerks[n].data.charismaMin = iniGetInt(num, "CHR", 0, perksFile); - extPerks[n].data.intelligenceMin = iniGetInt(num, "INT", 0, perksFile); - extPerks[n].data.agilityMin = iniGetInt(num, "AGL", 0, perksFile); - extPerks[n].data.luckMin = iniGetInt(num, "LCK", 0, perksFile); + extPerks[n].data.image = IniReader::GetInt(num, "Image", -1, perksFile); + extPerks[n].data.levelMin = IniReader::GetInt(num, "Level", -1, perksFile); + extPerks[n].data.stat = IniReader::GetInt(num, "Stat", -1, perksFile); + extPerks[n].data.statMod = IniReader::GetInt(num, "StatMag", 0, perksFile); + extPerks[n].data.skill1 = IniReader::GetInt(num, "Skill1", -1, perksFile); + extPerks[n].data.skill1Min = IniReader::GetInt(num, "Skill1Mag", 0, perksFile); + extPerks[n].data.skillOperator = IniReader::GetInt(num, "Type", 0, perksFile); + extPerks[n].data.skill2 = IniReader::GetInt(num, "Skill2", -1, perksFile); + extPerks[n].data.skill2Min = IniReader::GetInt(num, "Skill2Mag", 0, perksFile); + extPerks[n].data.strengthMin = IniReader::GetInt(num, "STR", 0, perksFile); + extPerks[n].data.perceptionMin = IniReader::GetInt(num, "PER", 0, perksFile); + extPerks[n].data.enduranceMin = IniReader::GetInt(num, "END", 0, perksFile); + extPerks[n].data.charismaMin = IniReader::GetInt(num, "CHR", 0, perksFile); + extPerks[n].data.intelligenceMin = IniReader::GetInt(num, "INT", 0, perksFile); + extPerks[n].data.agilityMin = IniReader::GetInt(num, "AGL", 0, perksFile); + extPerks[n].data.luckMin = IniReader::GetInt(num, "LCK", 0, perksFile); - iniGetString(num, "Name", "Error", extPerks[n].Name, maxNameLen - 1, perksFile); + IniReader::GetString(num, "Name", "Error", extPerks[n].Name, maxNameLen - 1, perksFile); extPerks[n].data.name = extPerks[n].Name; - iniGetString(num, "Desc", "Error", extPerks[n].Desc, descLen - 1, perksFile); + IniReader::GetString(num, "Desc", "Error", extPerks[n].Desc, descLen - 1, perksFile); extPerks[n].data.description = extPerks[n].Desc; - extPerks[n].stat1 = iniGetInt(num, "Stat1", -1, perksFile); - extPerks[n].stat1Mod = iniGetInt(num, "Stat1Mag", 0, perksFile); - extPerks[n].stat2 = iniGetInt(num, "Stat2", -1, perksFile); - extPerks[n].stat2Mod = iniGetInt(num, "Stat2Mag", 0, perksFile); - extPerks[n].skill3 = iniGetInt(num, "Skill3", -1, perksFile); - extPerks[n].skill3Mod = iniGetInt(num, "Skill3Mod", 0, perksFile); - extPerks[n].skill4 = iniGetInt(num, "Skill4", -1, perksFile); - extPerks[n].skill4Mod = iniGetInt(num, "Skill4Mod", 0, perksFile); - extPerks[n].skill5 = iniGetInt(num, "Skill5", -1, perksFile); - extPerks[n].skill5Mod = iniGetInt(num, "Skill5Mod", 0, perksFile); + extPerks[n].stat1 = IniReader::GetInt(num, "Stat1", -1, perksFile); + extPerks[n].stat1Mod = IniReader::GetInt(num, "Stat1Mag", 0, perksFile); + extPerks[n].stat2 = IniReader::GetInt(num, "Stat2", -1, perksFile); + extPerks[n].stat2Mod = IniReader::GetInt(num, "Stat2Mag", 0, perksFile); + extPerks[n].skill3 = IniReader::GetInt(num, "Skill3", -1, perksFile); + extPerks[n].skill3Mod = IniReader::GetInt(num, "Skill3Mod", 0, perksFile); + extPerks[n].skill4 = IniReader::GetInt(num, "Skill4", -1, perksFile); + extPerks[n].skill4Mod = IniReader::GetInt(num, "Skill4Mod", 0, perksFile); + extPerks[n].skill5 = IniReader::GetInt(num, "Skill5", -1, perksFile); + extPerks[n].skill5Mod = IniReader::GetInt(num, "Skill5Mod", 0, perksFile); extPerks[n].id = id; ++n; extPerks.resize(n + 1); // add next 'empty' perk @@ -990,11 +999,11 @@ bool Perks::IsTraitDisabled(int traitID) { } DWORD Perks::GetTraitStatBonus(int statID, int traitIndex) { - return traitStatBonuses[statID * fo::TRAIT_count + fo::var::pc_trait[traitIndex]]; + return traitStatBonuses[statID * fo::Trait::TRAIT_count + fo::var::pc_trait[traitIndex]]; } DWORD Perks::GetTraitSkillBonus(int skillID, int traitIndex) { - return traitSkillBonuses[skillID * fo::TRAIT_count + fo::var::pc_trait[traitIndex]]; + return traitSkillBonuses[skillID * fo::Trait::TRAIT_count + fo::var::pc_trait[traitIndex]]; } static void __declspec(naked) BlockedTrait() { @@ -1009,7 +1018,7 @@ static void PerkAndTraitSetup() { if (!traitsEnable) return; - std::memcpy(traits, var::trait_data, sizeof(TraitInfo) * TRAIT_count); + std::memcpy(traits, fo::var::trait_data, sizeof(fo::TraitInfo) * fo::Trait::TRAIT_count); // _trait_data SafeWriteBatch((DWORD)traits, {0x4B3A81, 0x4B3B80}); @@ -1018,74 +1027,74 @@ static void PerkAndTraitSetup() { char buf[512], num[5] = {'t'}; char* num2 = &num[1]; - for (int i = 0; i < TRAIT_count; i++) { + for (int i = 0; i < fo::Trait::TRAIT_count; i++) { _itoa_s(i, num2, 4, 10); - if (iniGetString(num, "Name", "", &tName[i * maxNameLen], maxNameLen - 1, perksFile)) { + if (IniReader::GetString(num, "Name", "", &tName[i * maxNameLen], maxNameLen - 1, perksFile)) { traits[i].name = &tName[i * maxNameLen]; } - if (iniGetString(num, "Desc", "", &tDesc[i * descLen], descLen - 1, perksFile)) { + if (IniReader::GetString(num, "Desc", "", &tDesc[i * descLen], descLen - 1, perksFile)) { traits[i].description = &tDesc[i * descLen]; } int value; - value = iniGetInt(num, "Image", -99999, perksFile); + value = IniReader::GetInt(num, "Image", -99999, perksFile); if (value != -99999) traits[i].image = value; - if (iniGetString(num, "StatMod", "", buf, 512, perksFile) > 0) { + if (IniReader::GetString(num, "StatMod", "", buf, 512, perksFile) > 0) { char *stat, *mod; stat = strtok(buf, "|"); mod = strtok(0, "|"); while (stat&&mod) { int _stat = atoi(stat), _mod = atoi(mod); - if (_stat >= 0 && _stat <= STAT_max_derived) traitStatBonuses[_stat * TRAIT_count + i] = _mod; + if (_stat >= 0 && _stat <= fo::STAT_max_derived) traitStatBonuses[_stat * fo::Trait::TRAIT_count + i] = _mod; stat = strtok(0, "|"); mod = strtok(0, "|"); } } - if (iniGetString(num, "SkillMod", "", buf, 512, perksFile) > 0) { + if (IniReader::GetString(num, "SkillMod", "", buf, 512, perksFile) > 0) { char *stat, *mod; stat = strtok(buf, "|"); mod = strtok(0, "|"); while (stat&&mod) { int _stat = atoi(stat), _mod = atoi(mod); - if (_stat >= 0 && _stat < 18) traitSkillBonuses[_stat * TRAIT_count + i] = _mod; + if (_stat >= 0 && _stat < 18) traitSkillBonuses[_stat * fo::Trait::TRAIT_count + i] = _mod; stat = strtok(0, "|"); mod = strtok(0, "|"); } } - if (iniGetInt(num, "NoHardcode", 0, perksFile)) { + if (IniReader::GetInt(num, "NoHardcode", 0, perksFile)) { disableTraits[i] = true; switch (i) { - case TRAIT_one_hander: + case fo::Trait::TRAIT_one_hander: HookCall(0x4245E0, BlockedTrait); // determine_to_hit_func_ break; - case TRAIT_finesse: + case fo::Trait::TRAIT_finesse: HookCall(0x4248F9, BlockedTrait); // compute_damage_ break; - case TRAIT_fast_shot: + case fo::Trait::TRAIT_fast_shot: HookCall(0x478C8A, BlockedTrait); // item_w_mp_cost_ HookCall(0x478E70, BlockedTrait); // item_w_called_shot_ break; - case TRAIT_bloody_mess: + case fo::Trait::TRAIT_bloody_mess: HookCall(0x410707, BlockedTrait); // pick_death_ break; - case TRAIT_jinxed: + case fo::Trait::TRAIT_jinxed: HookCall(0x42389F, BlockedTrait); // compute_attack_ break; - case TRAIT_drug_addict: + case fo::Trait::TRAIT_drug_addict: HookCall(0x47A0CD, BlockedTrait); // item_d_take_drug_ HookCall(0x47A51A, BlockedTrait); // perform_withdrawal_start_ break; - case TRAIT_drug_resistant: + case fo::Trait::TRAIT_drug_resistant: HookCall(0x479BE1, BlockedTrait); // insert_drug_effect_ HookCall(0x47A0DD, BlockedTrait); // item_d_take_drug_ break; - case TRAIT_skilled: + case fo::Trait::TRAIT_skilled: HookCall(0x43C295, BlockedTrait); // UpdateLevel_ HookCall(0x43C2F3, BlockedTrait); // UpdateLevel_ break; - case TRAIT_gifted: + case fo::Trait::TRAIT_gifted: HookCall(0x43C2A4, BlockedTrait); // UpdateLevel_ break; } @@ -1128,9 +1137,10 @@ checkType: } } -// Haenlomal's fix +// Haenlomal's tweak static void __declspec(naked) item_w_called_shot_hack() { static const DWORD FastShotTraitFix_End = 0x478E7F; + using namespace fo; __asm { mov edx, ecx; // argument for item_hit_with_: hit_mode mov eax, ebx; // argument for item_hit_with_: pointer to source_obj (always dude_obj due to code path) @@ -1157,18 +1167,18 @@ cantUse: } static void FastShotTraitFix() { - switch (GetConfigInt("Misc", "FastShotFix", 1)) { + switch (IniReader::GetConfigInt("Misc", "FastShotFix", 0)) { case 1: - dlog("Applying Fast Shot trait patch. (Haenlomal's fix)", DL_INIT); + dlog("Applying Fast Shot trait patch (Haenlomal's tweak).", DL_INIT); MakeJump(0x478E79, item_w_called_shot_hack); goto fix; case 2: - dlog("Applying Fast Shot trait patch. (Alternative behavior)", DL_INIT); + dlog("Applying Fast Shot trait patch (Alternative behavior).", DL_INIT); SafeWrite16(0x478C9F, 0x9090); HookCalls((void*)0x478C7D, {0x478BB8, 0x478BC7, 0x478BD6, 0x478BEA, 0x478BF9, 0x478C08, 0x478C2F}); goto done; case 3: - dlog("Applying Fast Shot trait patch. (Fallout 1 behavior)", DL_INIT); + dlog("Applying Fast Shot trait patch (Fallout 1 behavior).", DL_INIT); HookCall(0x478C97, (void*)fo::funcoffs::item_hit_with_); SafeWrite16(0x478C9E, CodeType::JumpZ << 8); // ignore all unarmed attacks (cmp eax, 0; jz) goto done; @@ -1184,20 +1194,20 @@ static void FastShotTraitFix() { /////////////////////////////////////////////////////////////////////////////// void __fastcall Perks::SetPerkValue(int id, int param, int value) { - if (id < 0 || id >= PERK_count) return; + if (id < 0 || id >= fo::Perk::PERK_count) return; *(DWORD*)((DWORD)(&perks[id]) + param) = value; perksReInit = true; } void Perks::SetPerkName(int id, const char* value) { - if (id < 0 || id >= PERK_count) return; + if (id < 0 || id >= fo::Perk::PERK_count) return; strncpy_s(&Name[id * maxNameLen], maxNameLen, value, _TRUNCATE); perks[id].name = &Name[maxNameLen * id]; perksReInit = true; } void Perks::SetPerkDesc(int id, const char* value) { - if (id < 0 || id >= PERK_count) return; + if (id < 0 || id >= fo::Perk::PERK_count) return; strncpy_s(&Desc[id * descLen], descLen, value, _TRUNCATE); perks[id].description = &Desc[descLen * id]; perksReInit = true; @@ -1224,10 +1234,10 @@ void PerksReset() { // Swift Learner bonus SafeWrite32(0x4AFAE2, 100); // Restore 'Heave Ho' modify fix - if (perkHeaveHoModFix) { + if (Perks::perkHeaveHoModTweak) { SafeWrite8(0x478AC4, 0xBA); SafeWrite32(0x478AC5, 0x23); - perkHeaveHoModFix = false; + Perks::perkHeaveHoModTweak = false; } if (perksReInit) PerkSetup(); // restore perk data } @@ -1291,7 +1301,7 @@ void __stdcall AddPerkMode(DWORD mode) { } DWORD Perks::HasFakePerk(const char* name, long perkId) { - if ((perkId < PERK_count && name[0] == 0) || (perkId && PartyControl::IsNpcControlled())) return 0; + if ((perkId < fo::Perk::PERK_count && name[0] == 0) || (perkId && PartyControl::IsNpcControlled())) return 0; for (DWORD i = 0; i < fakePerks.size(); i++) { if (perkId) { if (fakePerks[i].id == perkId) return fakePerks[i].Level; // current perk level @@ -1384,19 +1394,21 @@ void Perks::init() { HookCall(0x43C80B, perks_dialog_hook); // Disable gain perks for bonus stats - for (int i = STAT_st; i <= STAT_lu; i++) SafeWrite8(GainStatPerks[i][0], (BYTE)GainStatPerks[i][1]); + for (int i = fo::Stat::STAT_st; i <= fo::Stat::STAT_lu; i++) { + SafeWrite8(GainStatPerks[i][0], (BYTE)GainStatPerks[i][1]); + } PerkEngineInit(); // Perk and Trait init HookCall(0x44272E, game_init_hook); - if (GetConfigString("Misc", "PerksFile", "", &perksFile[2], MAX_PATH - 3)) { + if (IniReader::GetConfigString("Misc", "PerksFile", "", &perksFile[2], MAX_PATH - 3)) { perksFile[0] = '.'; perksFile[1] = '\\'; if (GetFileAttributes(perksFile) == INVALID_FILE_ATTRIBUTES) return; - perksEnable = iniGetInt("Perks", "Enable", 1, perksFile); - traitsEnable = iniGetInt("Traits", "Enable", 1, perksFile); + perksEnable = IniReader::GetInt("Perks", "Enable", 1, perksFile); + traitsEnable = IniReader::GetInt("Traits", "Enable", 1, perksFile); // Engine perks settings perk::ReadPerksBonuses(perksFile); diff --git a/sfall/Modules/Perks.h b/sfall/Modules/Perks.h index 51e1055f..8e78e4ee 100644 --- a/sfall/Modules/Perks.h +++ b/sfall/Modules/Perks.h @@ -24,13 +24,15 @@ namespace sfall { class Perks : public Module { +private: + static bool IsTraitDisabled(int traitID); + public: const char* name() { return "Perks"; } void init(); // Enable the modification of the stats/skills for traits by using the perks ini file static int TraitsModEnable(); - static bool IsTraitDisabled(int traitID); static DWORD GetTraitStatBonus(int statID, int traitIndex); static DWORD GetTraitSkillBonus(int skillID, int traitIndex); @@ -52,14 +54,19 @@ public: static void __fastcall SetPerkboxTitle(const char* name); static void SetPerkName(int id, const char* value); static void SetPerkDesc(int id, const char* value); + + static __forceinline bool DudeHasTrait(DWORD traitID) { + return (!IsTraitDisabled(traitID) && (fo::var::pc_trait[0] == traitID || fo::var::pc_trait[1] == traitID)); + } + + static bool perkHeaveHoModTweak; + static void __stdcall ApplyHeaveHoFix(); }; void PerksEnterCharScreen(); void PerksCancelCharScreen(); void PerksAcceptCharScreen(); -void __stdcall ApplyHeaveHoFix(); - void __stdcall IgnoreDefaultPerks(); void __stdcall RestoreDefaultPerks(); void __stdcall AddPerkMode(DWORD mode); diff --git a/sfall/Modules/PlayerModel.cpp b/sfall/Modules/PlayerModel.cpp index 25b5e7c0..fdd5973c 100644 --- a/sfall/Modules/PlayerModel.cpp +++ b/sfall/Modules/PlayerModel.cpp @@ -26,30 +26,30 @@ namespace sfall { -static char startMaleModelName[65] = {}; +static char startMaleModelName[33] = {}; char defaultMaleModelName[65] = {}; -static char startFemaleModelName[65] = {}; +static char startFemaleModelName[33] = {}; char defaultFemaleModelName[65] = {}; void PlayerModel::init() { - if (GetConfigString("Misc", "MaleStartModel", "", startMaleModelName, 64)) { + if (IniReader::GetConfigString("Misc", "MaleStartModel", "", startMaleModelName, 33)) { dlog("Applying male start model patch.", DL_INIT); SafeWrite32(0x418B88, (DWORD)&startMaleModelName); dlogr(" Done", DL_INIT); } - if (GetConfigString("Misc", "FemaleStartModel", "", startFemaleModelName, 64)) { + if (IniReader::GetConfigString("Misc", "FemaleStartModel", "", startFemaleModelName, 33)) { dlog("Applying female start model patch.", DL_INIT); SafeWrite32(0x418BAB, (DWORD)&startFemaleModelName); dlogr(" Done", DL_INIT); } - GetConfigString("Misc", "MaleDefaultModel", "hmjmps", defaultMaleModelName, 64); + IniReader::GetConfigString("Misc", "MaleDefaultModel", "hmjmps", defaultMaleModelName, 65); dlog("Applying male model patch.", DL_INIT); SafeWrite32(0x418B50, (DWORD)&defaultMaleModelName); dlogr(" Done", DL_INIT); - GetConfigString("Misc", "FemaleDefaultModel", "hfjmps", defaultFemaleModelName, 64); + IniReader::GetConfigString("Misc", "FemaleDefaultModel", "hfjmps", defaultFemaleModelName, 65); dlog("Applying female model patch.", DL_INIT); SafeWrite32(0x418B6D, (DWORD)&defaultFemaleModelName); dlogr(" Done", DL_INIT); diff --git a/sfall/Modules/Premade.cpp b/sfall/Modules/Premade.cpp index 340f6a72..d67faa8c 100644 --- a/sfall/Modules/Premade.cpp +++ b/sfall/Modules/Premade.cpp @@ -17,18 +17,77 @@ */ #include "..\main.h" -#include "..\FalloutEngine\Structs.h" +#include "..\FalloutEngine\Fallout2.h" +#include "Message.h" #include "Premade.h" namespace sfall { -fo::PremadeChar* premade; +static fo::PremadeChar* premade; + +static const char* __fastcall GetLangPremadePath(const char* premadePath) { + static char premadeLangPath[56]; // premade\\combat.bio + static bool isDefault = false; + static long len = 0; + + if (isDefault) return nullptr; + if (len == 0) { + len = std::strlen(Message::GameLanguage()); + if (len == 0 || len >= 32) { + isDefault = true; + return nullptr; + } + isDefault = (_stricmp(Message::GameLanguage(), "english") == 0); + if (isDefault) return nullptr; + + std::strncpy(premadeLangPath, premadePath, 8); + std::strcpy(&premadeLangPath[8], Message::GameLanguage()); + } + std::strcpy(&premadeLangPath[8 + len], &premadePath[7]); + + return premadeLangPath; +} + +static const char* __fastcall PremadeGCD(const char* premadePath) { + const char* path = GetLangPremadePath(premadePath); + return (path && fo::func::db_access(path)) ? path : premadePath; +} + +static fo::DbFile* __fastcall PremadeBIO(const char* premadePath, const char* mode) { + premadePath = GetLangPremadePath(premadePath); + return (premadePath) ? fo::func::db_fopen(premadePath, mode) : nullptr; +} + +static void __declspec(naked) select_display_bio_hook() { + __asm { + push eax; + push edx; + mov ecx, eax; // premade path + call PremadeBIO; + test eax, eax; + jz default; + add esp, 8; + retn; +default: + pop edx; + pop eax; + jmp fo::funcoffs::db_fopen_; + } +} + +static void __declspec(naked) select_update_display_hook() { + __asm { + mov ecx, eax; // premade path + call PremadeGCD; + jmp fo::funcoffs::proto_dude_init_; + } +} void Premade::init() { - auto premadePaths = GetConfigList("misc", "PremadePaths", "", 512); - auto premadeFids = GetConfigList("misc", "PremadeFIDs", "", 512); + auto premadePaths = IniReader::GetConfigList("misc", "PremadePaths", "", 512); + auto premadeFids = IniReader::GetConfigList("misc", "PremadeFIDs", "", 512); if (!premadePaths.empty() && !premadeFids.empty()) { dlog("Applying premade characters patch.", DL_INIT); int count = min(premadePaths.size(), premadeFids.size()); @@ -39,17 +98,21 @@ void Premade::init() { dlog_f(" Failed: %s exceeds 11 characters\n", DL_INIT, premadePaths[i].c_str()); return; } - strcpy(premade[i].path, path.c_str()); + std::strcpy(premade[i].path, path.c_str()); premade[i].fid = atoi(premadeFids[i].c_str()); } - SafeWrite32(0x51C8D4, count); - SafeWrite32(0x4A7D76, (DWORD)premade); - SafeWrite32(0x4A8B1E, (DWORD)premade); - SafeWrite32(0x4A7E2C, (DWORD)&premade[0].fid); - strcpy((char*)0x50AF68, premade[0].path); + SafeWrite32(0x51C8D4, count); // _premade_total + SafeWrite32(0x4A7D76, (DWORD)premade); // select_update_display_ + SafeWrite32(0x4A8B1E, (DWORD)premade); // select_display_bio_ + SafeWrite32(0x4A7E2C, (DWORD)&premade[0].fid); // select_display_portrait_ + std::strcpy((char*)0x50AF68, premade[0].path); // for selfrun dlogr(" Done", DL_INIT); } + + // Add language path for premade GCD/BIO files + HookCall(0x4A8B44, select_display_bio_hook); + HookCall(0x4A7D91, select_update_display_hook); } } diff --git a/sfall/Modules/QuestList.cpp b/sfall/Modules/QuestList.cpp index 63cc11dc..3cf60542 100644 --- a/sfall/Modules/QuestList.cpp +++ b/sfall/Modules/QuestList.cpp @@ -18,6 +18,7 @@ #include "..\main.h" #include "..\FalloutEngine\Fallout2.h" +#include "LoadGameHook.h" #include "QuestList.h" @@ -45,7 +46,7 @@ static bool calledflag = false; static DWORD called_quest_number = 0; static DWORD total_quests_pages = 0; static DWORD curent_quest_page = 0; -static DWORD look_quests = 0; // check current quests +static DWORD look_quests = 0; // check current quests static DWORD first_quest_page = 0; static DWORD last_quest_page = INT_MAX; @@ -86,7 +87,7 @@ static void __declspec(naked) pip_print_hack() { __asm { test bh, 1; jz skip; - add edx, 60; // pixel offset + add edx, 60; // pixel offset jmp end; skip: test bh, 2; @@ -178,7 +179,7 @@ static void AddPage(int lines) { } // Print quests page text -static long __fastcall QuestsPrint(const char* text, int width, DWORD* buf, BYTE* count) { +static long __fastcall QuestsPrint(BYTE* count, int width, DWORD* buf, const char* text) { look_quests++; // quests counter if (outRangeFlag) { @@ -223,14 +224,11 @@ static void __declspec(naked) PipStatus_hack_print() { static const DWORD PipStatus_BreakRet = 0x4982A4; __asm { push ecx; - push ebx; push edx; - push ecx; // count + push eax; // text push ebx; // buf - mov ecx, eax; // text - call QuestsPrint; // edx - width + call QuestsPrint; // ecx - count, edx - width pop edx; - pop ebx; pop ecx; cmp eax, 0; jl jbreak; @@ -246,6 +244,7 @@ jbreak: static char bufPage[16]; static const char* format = "%s %d %s %d"; + static void __declspec(naked) PrintPages() { __asm { // total pages @@ -302,7 +301,7 @@ skip: } } -static DWORD __fastcall ActionButtons(register DWORD key) { +static DWORD __fastcall ActionButtons(DWORD key) { buttonsPressed = false; if (key == 0x300) { // up if (curent_quest_page == 0) return -1; @@ -317,8 +316,8 @@ static DWORD __fastcall ActionButtons(register DWORD key) { curent_quest_page++; first_quest_page = pageQuest[curent_quest_page]; last_quest_page = ((pageQuest.size() - 1) > curent_quest_page) - ? pageQuest[curent_quest_page + 1] - 1 - : INT_MAX; + ? pageQuest[curent_quest_page + 1] - 1 + : INT_MAX; buttonsPressed = true; return called_quest_number; } @@ -335,7 +334,7 @@ static void __declspec(naked) pipboy_hack_action() { mov ecx, ebx; call ActionButtons; cmp eax, -1; - cmovne ebx, eax; // called_quest_number + cmovne ebx, eax; // called_quest_number pop edx; pop eax; xor ecx, ecx; @@ -346,31 +345,17 @@ skip: } } -static void RegisterButtonSoundFunc0() { +static void RegisterButtonSound() { __asm { mov ebx, fo::funcoffs::gsound_red_butt_release_; mov edx, fo::funcoffs::gsound_red_butt_press_; - call fo::funcoffs::win_register_button_sound_func_; + call fo::funcoffs::win_register_button_sound_func_; // eax - register button } } -static void __stdcall ArtButtonFunc(DWORD buttonKey, DWORD buttonMem, DWORD indexArt) { -using namespace fo; - __asm { - xor ecx, ecx; - xor ebx, ebx; - mov edx, indexArt; // index from intrface.lst - mov eax, OBJ_TYPE_INTRFACE; - push ecx; - call fo::funcoffs::art_id_; - // - mov ecx, buttonKey; - xor ebx, ebx; - xor edx, edx; - call fo::funcoffs::art_ptr_lock_data_; - mov ecx, buttonMem; - mov dword ptr [ecx], eax; // first texture memory address - } +static void LoadArtButton(DWORD buttonKey, DWORD buttonMem, DWORD indexArt) { // indexArt - index from intrface.lst + long artId = fo::func::art_id(fo::ArtType::OBJ_TYPE_INTRFACE, indexArt, 0, 0, 0); + *(BYTE**)buttonMem = fo::func::art_ptr_lock_data(artId, 0, 0, (DWORD*)buttonKey); // first texture memory address } // Create buttons @@ -410,11 +395,11 @@ static void __declspec(naked) StartPipboy_hack() { // Load new texture for first (up) button. I used memory address for texture from buttons at chracter screen. // Everything fine, because this buttons can't use in one time, and they everytime recreating. // Down - ArtButtonFunc(FO_VAR_optionsButtonUpKey, FO_VAR_optionsButtonUp, indexUpArt0); - ArtButtonFunc(FO_VAR_optionsButtonDownKey, FO_VAR_optionsButtonDown, indexDownArt0); + LoadArtButton(FO_VAR_optionsButtonUpKey, FO_VAR_optionsButtonUp, indexUpArt0); + LoadArtButton(FO_VAR_optionsButtonDownKey, FO_VAR_optionsButtonDown, indexDownArt0); // Up - ArtButtonFunc(FO_VAR_optionsButtonUpKey, FO_VAR_optionsButtonUp1, indexUpArt1); - ArtButtonFunc(FO_VAR_optionsButtonDownKey, FO_VAR_optionsButtonDown1, indexDownArt1); + LoadArtButton(FO_VAR_optionsButtonUpKey, FO_VAR_optionsButtonUp1, indexUpArt1); + LoadArtButton(FO_VAR_optionsButtonDownKey, FO_VAR_optionsButtonDown1, indexDownArt1); xPos = questsScrollButtonsX; yPos = questsScrollButtonsY; @@ -424,19 +409,19 @@ static void __declspec(naked) StartPipboy_hack() { picDown = (BYTE*)fo::var::optionsButtonDown1; picUp = (BYTE*)fo::var::optionsButtonUp1; if (fo::func::win_register_button(winRef, xPos, yPos, width, height, -1, -1, -1, 0x300, picUp, picDown, 0, 32) != -1) { - RegisterButtonSoundFunc0(); + RegisterButtonSound(); } picDown = (BYTE*)fo::var::optionsButtonDown; picUp = (BYTE*)fo::var::optionsButtonUp; if (fo::func::win_register_button(winRef, xPos, yPos + height, width, height, -1, -1, -1, 0x301, picUp, picDown, 0, 32) != -1) { - RegisterButtonSoundFunc0(); + RegisterButtonSound(); } __asm { - mov esp, ebp; // epilog + mov esp, ebp; // epilog pop edi; - mov ebp, 0x1F4; // overwrite engine code + mov ebp, 0x1F4; // overwrite engine code retn; } } @@ -456,6 +441,40 @@ skip: } } +static void __fastcall QuestListSort(fo::QuestData* questList, size_t numElements) { + if (numElements <= 1) return; + + fo::QuestData* tmpList = new fo::QuestData[numElements]; + std::memcpy(tmpList, questList, numElements * sizeof(fo::QuestData)); + + long locStart = 1500; // number from which the locations starting + size_t leftStart = 0; + + for (size_t i = 0; i < numElements;) { + for (size_t j = leftStart; j < numElements; j++) { + if (!tmpList[j].location) { + if ((j - leftStart) == 1) leftStart = j; + continue; + } + if (tmpList[j].location == locStart) { + // unsorted? + if (j != i) questList[i] = tmpList[j]; + if (++i >= numElements) break; + tmpList[j].location = 0; + } + } + locStart++; + } + delete[] tmpList; +} + +static void __declspec(naked) quest_init_hook() { + __asm { + mov ecx, eax; // questList (base) + jmp QuestListSort; // edx - numElements + } +} + void QuestListPatch() { MakeCall(0x4974E4, StartPipboy_hack); @@ -473,15 +492,72 @@ void QuestListPatch() { MakeCall(0x497A7D, pip_print_hack); } +//////////////////////////////////////////////////////////////////////////////// + +struct QuestFailure { + long gvarNum; + long failureVal; +}; + +std::vector questFailures; + +static long FindGVarQuestFailure(long globalVarNum) { + for (size_t i = 0; i < questFailures.size(); i++) { + if (questFailures[i].gvarNum == globalVarNum) return i; + } + return -1; +} + +void QuestList::AddQuestFailureValue(long globalVarNum, long failureThreshold) { + long index = FindGVarQuestFailure(globalVarNum); + if (index == -1) { + questFailures.push_back({ globalVarNum, failureThreshold }); + } else { + questFailures[index].failureVal = failureThreshold; + } +} + +static BYTE __fastcall CheckQuestFailureState(fo::QuestData* quest, BYTE completeColor) { + if (questFailures.empty()) return completeColor; + + const BYTE failureColor = 137; // dark red + + long index = FindGVarQuestFailure(quest->gvarIndex); + return (index != -1 && fo::var::game_global_vars[quest->gvarIndex] >= questFailures[index].failureVal) ? failureColor : completeColor; +} + +static void __declspec(naked) PipStatus_hack() { + __asm { + push eax; + push ecx; + mov dl, ds:[0x6A5B34]; // completeColor (dark green) + mov ecx, ds:[FO_VAR_quests]; + add ecx, [esp + 0x4BC - 0x28 + 12]; + call CheckQuestFailureState; + mov bl, al; + pop ecx; + pop eax; + retn; + } +} + +static void ResetQuests() { + questFailures.clear(); +} + void QuestList::init() { - questsButtonsType = GetConfigInt("Misc", "UseScrollingQuestsList", 0); + LoadGameHook::OnGameReset() += ResetQuests; + + MakeCall(0x498222, PipStatus_hack, 1); + + questsButtonsType = IniReader::GetConfigInt("Misc", "UseScrollingQuestsList", 0); if (questsButtonsType > 0) { dlog("Applying quests list patch.", DL_INIT); QuestListPatch(); - questsScrollButtonsX = GetConfigInt("Misc", "QuestsScrollButtonsX", 140); + questsScrollButtonsX = IniReader::GetConfigInt("Misc", "QuestsScrollButtonsX", 140); if (questsScrollButtonsX < 0 || questsScrollButtonsX > 618) questsScrollButtonsX = 140; - questsScrollButtonsY = GetConfigInt("Misc", "QuestsScrollButtonsY", 334); + questsScrollButtonsY = IniReader::GetConfigInt("Misc", "QuestsScrollButtonsY", 334); if (questsScrollButtonsY < 0 || questsScrollButtonsY > 434) questsScrollButtonsY = 334; pageQuest.reserve(4); // init @@ -491,6 +567,9 @@ void QuestList::init() { } else { HookCall(0x498186, PipStatus_hook_printfix); // fix "out of bounds" bug when printing a list of quests } + + // Replace the qsort_ unstable sorting function with a simple stable sorting algorithm + HookCall(0x49A7C2, quest_init_hook); } } diff --git a/sfall/Modules/QuestList.h b/sfall/Modules/QuestList.h index 4bb9d11b..e71a0f1b 100644 --- a/sfall/Modules/QuestList.h +++ b/sfall/Modules/QuestList.h @@ -25,6 +25,8 @@ class QuestList : public Module { public: const char* name() { return "QuestList"; } void init(); + + static void AddQuestFailureValue(long globalVarNum, long failureThreshold); }; } diff --git a/sfall/Modules/Reputations.cpp b/sfall/Modules/Reputations.cpp index a9437e07..31723268 100644 --- a/sfall/Modules/Reputations.cpp +++ b/sfall/Modules/Reputations.cpp @@ -37,7 +37,7 @@ struct CityRep { static CityRep* repList = nullptr; void Reputations::init() { - auto cityRepList = GetConfigList("Misc", "CityRepsList", "", 512); + auto cityRepList = IniReader::GetConfigList("Misc", "CityRepsList", "", 512); size_t count = cityRepList.size(); if (count) { repList = new CityRep[count]; diff --git a/sfall/Modules/ScriptExtender.cpp b/sfall/Modules/ScriptExtender.cpp index 8fb5ea58..851c9657 100644 --- a/sfall/Modules/ScriptExtender.cpp +++ b/sfall/Modules/ScriptExtender.cpp @@ -27,8 +27,6 @@ #include "..\Logging.h" #include "..\Version.h" #include "..\Utils.h" -#include "BarBoxes.h" -#include "Console.h" #include "HookScripts.h" #include "LoadGameHook.h" #include "MainLoopHook.h" @@ -56,6 +54,8 @@ char ScriptExtender::gTextBuffer[5120]; // used as global temp text buffer for s std::string ScriptExtender::iniConfigFolder; +bool ScriptExtender::OnMapLeave; + static std::vector scriptsIndexList; struct GlobalScript { @@ -428,14 +428,14 @@ void __fastcall SetSelfObject(fo::Program* script, fo::GameObject* obj) { // loads script from .int file into a sScriptProgram struct, filling script pointer and proc lookup table void InitScriptProgram(ScriptProgram &prog, const char* fileName, bool fullPath) { - fo::Program* scriptPtr = fullPath - ? fo::func::allocateProgram(fileName) - : fo::func::loadProgram(fileName); + fo::Program* scriptPtr = (fullPath) + ? fo::func::allocateProgram(fileName) + : fo::func::loadProgram(fileName); if (scriptPtr) { - const char** procTable = fo::var::procTableStrs; prog.ptr = scriptPtr; // fill lookup table + const char** procTable = fo::var::procTableStrs; for (int i = 0; i < fo::Scripts::ScriptProc::count; ++i) { prog.procLookup[i] = fo::func::interpretFindProcedure(prog.ptr, procTable[i]); } @@ -481,6 +481,26 @@ bool IsGameScript(const char* filename) { return false; // script name was not found in scripts.lst } +// loads and initializes script file (for normal game scripts) +long __fastcall ScriptExtender::InitScript(long sid) { + fo::ScriptInstance* scriptPtr; + if (fo::func::scr_ptr(sid, &scriptPtr) == -1) return -1; + + scriptPtr->program = fo::func::loadProgram(fo::var::scriptListInfo[scriptPtr->scriptIdx & 0xFFFFFF].fileName); + if (!scriptPtr->program) return -1; + if (scriptPtr->program->flags & 0x124) return 0; + + // fill lookup table + fo::func::scr_build_lookup_table(scriptPtr); + + scriptPtr->flags |= 4 | 1; // init | loaded + scriptPtr->action = fo::Scripts::ScriptProc::no_p_proc; + scriptPtr->scriptOverrides = 0; + + fo::func::runProgram(scriptPtr->program); + return 0; +} + static void LoadGlobalScriptsList() { dlogr("Running global scripts...", DL_SCRIPT); @@ -603,27 +623,27 @@ static void ClearGlobalScripts() { void RunScriptProc(ScriptProgram* prog, const char* procName) { fo::Program* sptr = prog->ptr; - int procNum = fo::func::interpretFindProcedure(sptr, procName); - if (procNum != -1) { - fo::func::executeProcedure(sptr, procNum); + int procPosition = fo::func::interpretFindProcedure(sptr, procName); + if (procPosition != -1) { + fo::func::executeProcedure(sptr, procPosition); } } void RunScriptProc(ScriptProgram* prog, long procId) { if (procId > 0 && procId < fo::Scripts::ScriptProc::count) { - int procNum = prog->procLookup[procId]; - if (procNum != -1) { - fo::func::executeProcedure(prog->ptr, procNum); + int procPosition = prog->procLookup[procId]; + if (procPosition != -1) { + fo::func::executeProcedure(prog->ptr, procPosition); } } } int RunScriptStartProc(ScriptProgram* prog) { - int procNum = prog->procLookup[fo::Scripts::ScriptProc::start]; - if (procNum != -1) { - fo::func::executeProcedure(prog->ptr, procNum); + int procPosition = prog->procLookup[fo::Scripts::ScriptProc::start]; + if (procPosition != -1) { + fo::func::executeProcedure(prog->ptr, procPosition); } - return procNum; + return procPosition; } static void RunScript(GlobalScript* script) { @@ -853,7 +873,10 @@ static void __declspec(naked) map_save_in_game_hook() { __asm { test cl, 1; jz skip; - jmp fo::funcoffs::scr_exec_map_exit_scripts_; + mov ScriptExtender::OnMapLeave, 1; + call fo::funcoffs::scr_exec_map_exit_scripts_; + mov ScriptExtender::OnMapLeave, 0; + retn; skip: jmp fo::funcoffs::partyMemberSaveProtos_; } @@ -911,20 +934,15 @@ void ScriptExtender::init() { OnInputLoop() += RunGlobalScriptsOnInput; Worldmap::OnWorldmapLoop() += RunGlobalScriptsOnWorldMap; - globalScriptPathList = GetConfigList("Scripts", "GlobalScriptPaths", "scripts\\gl*.int", 255); + globalScriptPathList = IniReader::GetConfigList("Scripts", "GlobalScriptPaths", "scripts\\gl*.int", 255); for (unsigned int i = 0; i < globalScriptPathList.size(); i++) { ToLowerCase(globalScriptPathList[i]); } - idle = GetConfigInt("Misc", "ProcessorIdle", -1); - if (idle > -1) { - if (idle > 127) idle = 127; - fo::var::idle_func = reinterpret_cast(Sleep); - SafeWrite8(0x4C9F12, 0x6A); // push idle - SafeWrite8(0x4C9F13, idle); - } + idle = IniReader::GetConfigInt("Misc", "ProcessorIdle", -1); + if (idle > -1 && idle > 30) idle = 30; - arraysBehavior = GetConfigInt("Misc", "arraysBehavior", 1); + arraysBehavior = IniReader::GetConfigInt("Misc", "arraysBehavior", 1); if (arraysBehavior > 0) { arraysBehavior = 1; // only 1 and 0 allowed at this time dlogr("New arrays behavior enabled.", DL_SCRIPT); @@ -932,7 +950,7 @@ void ScriptExtender::init() { dlogr("Arrays in backward-compatiblity mode.", DL_SCRIPT); } - iniConfigFolder = GetConfigString("Scripts", "IniConfigFolder", "", 64); + iniConfigFolder = IniReader::GetConfigString("Scripts", "IniConfigFolder", "", 64); size_t len = iniConfigFolder.length(); if (len) { char c = iniConfigFolder[len - 1]; @@ -945,7 +963,7 @@ void ScriptExtender::init() { } } - alwaysFindScripts = isDebug && (iniGetInt("Debugging", "AlwaysFindScripts", 0, ::sfall::ddrawIni) != 0); + alwaysFindScripts = isDebug && (IniReader::GetIntDefaultConfig("Debugging", "AlwaysFindScripts", 0) != 0); if (alwaysFindScripts) dlogr("Always searching for global/hook scripts behavior enabled.", DL_SCRIPT); MakeJump(0x4A390C, scr_find_sid_from_program_hack); diff --git a/sfall/Modules/ScriptExtender.h b/sfall/Modules/ScriptExtender.h index 8e5d597b..b9801209 100644 --- a/sfall/Modules/ScriptExtender.h +++ b/sfall/Modules/ScriptExtender.h @@ -39,6 +39,7 @@ public: void init(); static std::string iniConfigFolder; + static bool OnMapLeave; static char gTextBuffer[5120]; @@ -57,6 +58,9 @@ public: static int __stdcall ScriptHasLoaded(fo::Program* script); + // loads and initializes script file (for normal game scripts) + static long __fastcall InitScript(long sid); + // Called before map exit (before map_exit_p_proc handlers in normal scripts) static Delegate<>& OnMapExit(); }; diff --git a/sfall/Modules/ScriptShaders.cpp b/sfall/Modules/ScriptShaders.cpp index 9aa1d7ec..673f1b5a 100644 --- a/sfall/Modules/ScriptShaders.cpp +++ b/sfall/Modules/ScriptShaders.cpp @@ -221,7 +221,7 @@ void ScriptShaders::Release() { void ScriptShaders::init() { if (Graphics::mode) { - for each (const auto& shaderFile in GetConfigList("Graphics", "GlobalShaderFile", "", 1024)) { + for each (const auto& shaderFile in IniReader::GetConfigList("Graphics", "GlobalShaderFile", "", 1024)) { if (shaderFile.length() > 3) gShaderFiles.push_back(GlobalShader(shaderFile)); } globalShadersActive = !gShaderFiles.empty(); diff --git a/sfall/Modules/Scripting/Arrays.cpp b/sfall/Modules/Scripting/Arrays.cpp index 72191fc5..50a0ecd4 100644 --- a/sfall/Modules/Scripting/Arrays.cpp +++ b/sfall/Modules/Scripting/Arrays.cpp @@ -271,7 +271,7 @@ long LoadArrays(HANDLE h) { arrayVar.keyHash[arrayVar.val[j]] = j; } } - while (ArrayExist(nextArrayID)) nextArrayID++; + while (ArrayExists(nextArrayID)) nextArrayID++; if (nextArrayID == 0) nextArrayID++; arrays.insert(array_pair(nextArrayID, arrayVar)); @@ -318,7 +318,7 @@ int GetNumArrays() { return arrays.size(); } -bool ArrayExist(DWORD id) { +bool ArrayExists(DWORD id) { return (arrays.find(id) != arrays.end()); } @@ -397,7 +397,7 @@ DWORD CreateArray(int len, DWORD flags) { var.val.resize(len); } - while (ArrayExist(nextArrayID)) nextArrayID++; + while (ArrayExists(nextArrayID)) nextArrayID++; if (nextArrayID == 0) nextArrayID++; if (arraysBehavior == 0) { @@ -434,7 +434,7 @@ void DeleteAllTempArrays() { } ScriptValue GetArrayKey(DWORD id, int index) { - if (!ArrayExist(id) || index < -1 || index > arrays[id].size()) { + if (!ArrayExists(id) || index < -1 || index > arrays[id].size()) { return ScriptValue(0); } if (index == -1) { // special index to indicate if array is associative @@ -461,7 +461,7 @@ ScriptValue GetArrayKey(DWORD id, int index) { } ScriptValue GetArray(DWORD id, const ScriptValue& key) { - if (!ArrayExist(id)) return 0; + if (!ArrayExists(id)) return 0; int el; sArrayVar &arr = arrays[id]; @@ -497,8 +497,8 @@ void setArray(DWORD id, const ScriptValue& key, const ScriptValue& val, bool all sArrayElement sEl(key.rawValue(), key.type()); ArrayKeysMap::iterator elIter = arr.keyHash.find(sEl); int el = (elIter != arr.keyHash.end()) - ? elIter->second - : -1; + ? elIter->second + : -1; bool lookupMap = (arr.flags & ARRAYFLAG_CONSTVAL) != 0; if (lookupMap && el != -1) return; // don't update value of key @@ -538,7 +538,7 @@ void setArray(DWORD id, const ScriptValue& key, const ScriptValue& val, bool all } void SetArray(DWORD id, const ScriptValue& key, const ScriptValue& val, bool allowUnset) { - if (ArrayExist(id)) setArray(id, key, val, allowUnset); + if (ArrayExists(id)) setArray(id, key, val, allowUnset); } int LenArray(DWORD id) { @@ -603,7 +603,7 @@ static void MapSort(sArrayVar& arr, int type) { } long ResizeArray(DWORD id, int newlen) { - if (newlen == -1 || !ArrayExist(id)) return 0; + if (newlen == -1 || !ArrayExists(id)) return 0; sArrayVar &arr = arrays[id]; int arrSize = arr.size(); @@ -650,7 +650,7 @@ void FixArray(DWORD id) { } ScriptValue ScanArray(DWORD id, const ScriptValue& val) { - if (!ArrayExist(id)) { + if (!ArrayExists(id)) { return ScriptValue(-1); } char step = arrays[id].isAssoc() ? 2 : 1; @@ -737,7 +737,7 @@ void SaveArray(const ScriptValue& key, DWORD id) { Should always return 0! */ long StackArray(const ScriptValue& key, const ScriptValue& val) { - if (stackArrayId == 0 || !ArrayExist(stackArrayId)) return 0; + if (stackArrayId == 0 || !ArrayExists(stackArrayId)) return 0; if (!arrays[stackArrayId].isAssoc()) { // automatically resize array to fit one new element size_t size = arrays[stackArrayId].val.size(); diff --git a/sfall/Modules/Scripting/Arrays.h b/sfall/Modules/Scripting/Arrays.h index db7542c1..95ea6ae1 100644 --- a/sfall/Modules/Scripting/Arrays.h +++ b/sfall/Modules/Scripting/Arrays.h @@ -160,7 +160,7 @@ extern ArrayKeysMap savedArrays; long LoadArrays(HANDLE h); void SaveArrays(HANDLE h); int GetNumArrays(); -bool ArrayExist(DWORD id); +bool ArrayExists(DWORD id); void GetArrays(int* arrays); void DEGetArray(int id, DWORD* types, char* data); diff --git a/sfall/Modules/Scripting/Handlers/Anims.cpp b/sfall/Modules/Scripting/Handlers/Anims.cpp index 35191595..ec6cc59e 100644 --- a/sfall/Modules/Scripting/Handlers/Anims.cpp +++ b/sfall/Modules/Scripting/Handlers/Anims.cpp @@ -17,10 +17,8 @@ */ #include "..\..\..\FalloutEngine\Fallout2.h" -#include "..\..\..\SafeWrite.h" #include "..\..\Explosions.h" #include "..\..\ScriptExtender.h" -#include "..\OpcodeContext.h" #include "Anims.h" @@ -143,6 +141,10 @@ void op_explosions_metarule(OpcodeContext& ctx) { ctx.setReturn(result); } +void op_art_exists(OpcodeContext& ctx) { + ctx.setReturn(fo::func::art_exists(ctx.arg(0).rawValue())); +} + void mf_art_cache_flush(OpcodeContext& ctx) { __asm call fo::funcoffs::art_flush_; } diff --git a/sfall/Modules/Scripting/Handlers/Anims.h b/sfall/Modules/Scripting/Handlers/Anims.h index da27ef87..88b4f14a 100644 --- a/sfall/Modules/Scripting/Handlers/Anims.h +++ b/sfall/Modules/Scripting/Handlers/Anims.h @@ -18,6 +18,8 @@ #pragma once +#include "..\OpcodeContext.h" + namespace sfall { namespace script @@ -40,6 +42,8 @@ void op_reg_anim_callback(OpcodeContext&); void op_explosions_metarule(OpcodeContext&); +void op_art_exists(OpcodeContext&); + void mf_art_cache_flush(OpcodeContext&); } diff --git a/sfall/Modules/Scripting/Handlers/Combat.cpp b/sfall/Modules/Scripting/Handlers/Combat.cpp new file mode 100644 index 00000000..0b75e6f3 --- /dev/null +++ b/sfall/Modules/Scripting/Handlers/Combat.cpp @@ -0,0 +1,245 @@ +/* + * sfall + * Copyright (C) 2008-2021 The sfall team + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "..\..\..\FalloutEngine\AsmMacros.h" +#include "..\..\..\FalloutEngine\Fallout2.h" +#include "..\..\AI.h" +#include "..\..\Combat.h" +#include "..\..\KillCounter.h" + +#include "..\..\SubModules\CombatBlock.h" + +#include "Combat.h" + +namespace sfall +{ +namespace script +{ + +// Kill counters +static bool extraKillCounter; + +void SetExtraKillCounter(bool value) { extraKillCounter = value; } + +void __declspec(naked) op_get_kill_counter() { + __asm { + _GET_ARG_INT(fail); // get kill type value + cmp extraKillCounter, 1; + jne skip; + cmp eax, 38; + jae fail; + movzx edx, word ptr ds:[FO_VAR_pc_kill_counts][eax * 2]; + jmp end; +skip: + cmp eax, 19; + jae fail; + mov edx, ds:[FO_VAR_pc_kill_counts][eax * 4]; +end: + mov eax, ebx; // script + _RET_VAL_INT; + retn; +fail: + xor edx, edx; // return 0 + jmp end; + } +} + +void __declspec(naked) op_mod_kill_counter() { + __asm { + push ecx; + _GET_ARG(ecx, esi); // get mod value + mov eax, ebx; + _GET_ARG_INT(end); // get kill type value + cmp si, VAR_TYPE_INT; + jnz end; + cmp extraKillCounter, 1; + je skip; + cmp eax, 19; + jae end; + add ds:[FO_VAR_pc_kill_counts][eax * 4], ecx; + pop ecx; + retn; +skip: + cmp eax, 38; + jae end; + add word ptr ds:[FO_VAR_pc_kill_counts][eax * 2], cx; +end: + pop ecx; + retn; + } +} + +void op_set_object_knockback(OpcodeContext& ctx) { + int mode = 0; + switch (ctx.opcode()) { + case 0x196: + mode = 1; + break; + case 0x197: + mode = 2; + break; + } + fo::GameObject* object = ctx.arg(0).object(); + if (mode) { + if (object->IsNotCritter()) { + ctx.printOpcodeError("%s() - the object is not a critter.", ctx.getOpcodeName()); + return; + } + } else { + if (object->IsNotItem()) { + ctx.printOpcodeError("%s() - the object is not an item.", ctx.getOpcodeName()); + return; + } + } + KnockbackSetMod(object, ctx.arg(1).rawValue(), ctx.arg(2).asFloat(), mode); +} + +void op_remove_object_knockback(OpcodeContext& ctx) { + int mode = 0; + switch (ctx.opcode()) { + case 0x199: + mode = 1; + break; + case 0x19a: + mode = 2; + break; + } + KnockbackRemoveMod(ctx.arg(0).object(), mode); +} + +void __declspec(naked) op_get_bodypart_hit_modifier() { + __asm { + _GET_ARG_INT(fail); // get body value + cmp eax, 8; // Body_Head - Body_Uncalled + ja fail; + mov edx, ds:[FO_VAR_hit_location_penalty][eax * 4]; +end: + mov eax, ebx; // script + _J_RET_VAL_TYPE(VAR_TYPE_INT); +fail: + xor edx, edx; // return 0 + jmp end; + } +} + +void __declspec(naked) op_set_bodypart_hit_modifier() { + __asm { + push ecx; + _GET_ARG(ecx, esi); // get body value + mov eax, ebx; + _GET_ARG_INT(end); // get modifier value + cmp si, VAR_TYPE_INT; + jnz end; + cmp eax, 8; // Body_Head - Body_Uncalled + ja end; + mov ds:[FO_VAR_hit_location_penalty][eax * 4], ecx; +end: + pop ecx; + retn; + } +} + +void op_get_attack_type(OpcodeContext& ctx) { + ctx.setReturn(fo::GetCurrentAttackMode()); +} + +void __declspec(naked) op_force_aimed_shots() { + __asm { + mov esi, ecx; + _GET_ARG_INT(end); + push eax; + call ForceAimedShots; +end: + mov ecx, esi; + retn; + } +} + +void __declspec(naked) op_disable_aimed_shots() { + __asm { + mov esi, ecx; + _GET_ARG_INT(end); + push eax; + call DisableAimedShots; +end: + mov ecx, esi; + retn; + } +} + +void __declspec(naked) op_get_last_attacker() { + __asm { + _GET_ARG_INT(fail); + mov esi, ecx; + push eax; + call AI::AIGetLastAttacker; + mov edx, eax; + mov ecx, esi; +end: + mov eax, ebx; + _J_RET_VAL_TYPE(VAR_TYPE_INT); +fail: + xor edx, edx; // return 0 + jmp end; + } +} + +void __declspec(naked) op_get_last_target() { + __asm { + _GET_ARG_INT(fail); + mov esi, ecx; + push eax; + call AI::AIGetLastTarget; + mov edx, eax; + mov ecx, esi; +end: + mov eax, ebx; + _J_RET_VAL_TYPE(VAR_TYPE_INT); +fail: + xor edx, edx; // return 0 + jmp end; + } +} + +void __declspec(naked) op_block_combat() { + __asm { + mov esi, ecx; + _GET_ARG_INT(end); + push eax; + call CombatBlock::SetBlockCombat; +end: + mov ecx, esi; + retn; + } +} + +void mf_attack_is_aimed(OpcodeContext& ctx) { + DWORD isAimed, unused; + ctx.setReturn(!fo::func::intface_get_attack(&unused, &isAimed) ? isAimed : 0); +} + +void mf_combat_data(OpcodeContext& ctx) { + fo::ComputeAttackResult* ctd = nullptr; + if (fo::var::combat_state & 1) { + ctd = &fo::var::main_ctd; + } + ctx.setReturn((DWORD)ctd, DataType::INT); +} + +} +} diff --git a/sfall/Modules/Scripting/Handlers/Combat.h b/sfall/Modules/Scripting/Handlers/Combat.h new file mode 100644 index 00000000..b1340565 --- /dev/null +++ b/sfall/Modules/Scripting/Handlers/Combat.h @@ -0,0 +1,60 @@ +/* + * sfall + * Copyright (C) 2008-2021 The sfall team + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include "..\OpcodeContext.h" + +namespace sfall +{ +namespace script +{ + +// Kill counters +void SetExtraKillCounter(bool value); + +void __declspec() op_get_kill_counter(); + +void __declspec() op_mod_kill_counter(); + +void op_set_object_knockback(OpcodeContext&); + +void op_remove_object_knockback(OpcodeContext&); + +void __declspec() op_get_bodypart_hit_modifier(); + +void __declspec() op_set_bodypart_hit_modifier(); + +void op_get_attack_type(OpcodeContext&); + +void __declspec() op_force_aimed_shots(); + +void __declspec() op_disable_aimed_shots(); + +void __declspec() op_get_last_attacker(); + +void __declspec() op_get_last_target(); + +void __declspec() op_block_combat(); + +void mf_attack_is_aimed(OpcodeContext&); + +void mf_combat_data(OpcodeContext&); + +} +} diff --git a/sfall/Modules/Scripting/Handlers/Core.cpp b/sfall/Modules/Scripting/Handlers/Core.cpp index 45e816cf..84ef66b6 100644 --- a/sfall/Modules/Scripting/Handlers/Core.cpp +++ b/sfall/Modules/Scripting/Handlers/Core.cpp @@ -23,7 +23,6 @@ #include "..\..\HookScripts\Common.h" #include "..\..\ScriptExtender.h" #include "..\Arrays.h" -#include "..\OpcodeContext.h" #include "Core.h" @@ -155,6 +154,19 @@ end: } } +void __declspec(naked) op_game_loaded() { + __asm { + mov esi, ecx; + push eax; // script + call ScriptExtender::ScriptHasLoaded; + mov edx, eax; + mov eax, ebx; + _RET_VAL_INT; + mov ecx, esi; + retn; + } +} + void __declspec(naked) op_init_hook() { __asm { mov edx, HookScripts::initingHookScripts; diff --git a/sfall/Modules/Scripting/Handlers/Core.h b/sfall/Modules/Scripting/Handlers/Core.h index e05fd78b..67528ac6 100644 --- a/sfall/Modules/Scripting/Handlers/Core.h +++ b/sfall/Modules/Scripting/Handlers/Core.h @@ -18,6 +18,8 @@ #pragma once +#include "..\OpcodeContext.h" + /* Opcodes for core sfall features. */ namespace sfall @@ -49,6 +51,8 @@ void op_set_sfall_arg(OpcodeContext&); void __declspec() op_set_sfall_return(); +void __declspec() op_game_loaded(); + void __declspec() op_init_hook(); void __declspec() op_set_self(); diff --git a/sfall/Modules/Scripting/Handlers/Interface.cpp b/sfall/Modules/Scripting/Handlers/Interface.cpp index e92f137b..61bcd68f 100644 --- a/sfall/Modules/Scripting/Handlers/Interface.cpp +++ b/sfall/Modules/Scripting/Handlers/Interface.cpp @@ -25,12 +25,10 @@ #include "..\..\ScriptExtender.h" #include "..\..\Interface.h" #include "..\Arrays.h" -#include "..\OpcodeContext.h" -#include "..\..\HookScripts\InventoryHs.h" +#include "..\..\..\Game\render.h" #include "..\..\SubModules\WindowRender.h" -#include "..\..\..\Game\render.h" #include "Interface.h" @@ -46,6 +44,19 @@ void __declspec(naked) op_input_funcs_available() { } } +void __declspec(naked) op_set_pipboy_available() { + __asm { + _GET_ARG_INT(end); + cmp eax, 0; + jl end; + cmp eax, 1; + jg end; + mov byte ptr ds:[FO_VAR_gmovie_played_list][0x3], al; +end: + retn; + } +} + void op_key_pressed(OpcodeContext& ctx) { ctx.setReturn(KeyDown(ctx.arg(0).rawValue())); } @@ -117,18 +128,6 @@ void __declspec(naked) op_get_screen_height() { } } -void __declspec(naked) op_stop_game() { - __asm { - jmp fo::funcoffs::map_disable_bk_processes_; - } -} - -void __declspec(naked) op_resume_game() { - __asm { - jmp fo::funcoffs::map_enable_bk_processes_; - } -} - // copy and split static void SplitToBuffer(const char* str, const char** str_ptr, long &lines) { size_t i = 0; @@ -275,7 +274,7 @@ void mf_intface_redraw(OpcodeContext& ctx) { // fake redraw interfaces (TODO: need a real redraw of interface?) long winType = ctx.arg(0).rawValue(); if (winType == -1) { - fo::func::RefreshGNW(true); + fo::RefreshGNW(true); } else { fo::Window* win = Interface::GetWindow(winType); if (win && (int)win != -1) game::Render::GNW_win_refresh(win, &win->wRect, 0); @@ -384,13 +383,13 @@ void mf_dialog_message(OpcodeContext& ctx) { void mf_create_win(OpcodeContext& ctx) { int flags = (ctx.numArgs() > 5) - ? ctx.arg(5).rawValue() - : fo::WinFlags::MoveOnTop; + ? ctx.arg(5).rawValue() + : fo::WinFlags::MoveOnTop; if (fo::func::createWindow(ctx.arg(0).strValue(), - ctx.arg(1).rawValue(), ctx.arg(2).rawValue(), // x, y - ctx.arg(3).rawValue(), ctx.arg(4).rawValue(), // w, h - (flags & fo::WinFlags::Transparent) ? 0 : 256, flags) == -1) + ctx.arg(1).rawValue(), ctx.arg(2).rawValue(), // x, y + ctx.arg(3).rawValue(), ctx.arg(4).rawValue(), // w, h + (flags & fo::WinFlags::Transparent) ? 0 : 256, flags) == -1) { ctx.printOpcodeError("%s() - couldn't create window.", ctx.getMetaruleName()); ctx.setReturn(-1); @@ -507,16 +506,27 @@ static fo::FrmFile* LoadArtFile(const char* file, long frame, long direction, fo return frmPtr; } -static long GetArtFIDFile(long fid, const char* &file) { +static long GetArtFIDFile(long fid, char* outFilePath) { long direction = 0; long _fid = fid & 0xFFFFFFF; - file = fo::func::art_get_name(_fid); // .frm + + const char* artPathName = fo::func::art_get_name(_fid); // \art\type\file.frm + if (_fid >> 24 == fo::OBJ_TYPE_CRITTER) { direction = (fid >> 28); - if (direction > 0 && !fo::func::db_access(file)) { - file = fo::func::art_get_name(fid); // .fr# + if (direction > 0 && !fo::func::db_access(artPathName)) { + artPathName = fo::func::art_get_name(fid); // .fr# + } + } else { + if (fo::var::use_language) { + const char* _artPathName = std::strchr(artPathName, '\\'); + if (_artPathName && *(++_artPathName)) { + sprintf_s(outFilePath, MAX_PATH, "art\\%s\\%s", (const char*)fo::var::language, _artPathName); + if (fo::func::db_access(outFilePath)) return direction; + } } } + std::strcpy(outFilePath, artPathName); return direction; } @@ -533,7 +543,9 @@ static long DrawImage(OpcodeContext& ctx, bool isScaled) { long fid = ctx.arg(0).rawValue(); if (fid == -1) return -1; - direction = GetArtFIDFile(fid, file); + char fileBuf[MAX_PATH]; + direction = GetArtFIDFile(fid, fileBuf); + file = fileBuf; } else { file = ctx.arg(0).strValue(); // path to frm/pcx file } @@ -603,7 +615,10 @@ static long InterfaceDrawImage(OpcodeContext& ctx, fo::Window* ifaceWin) { if (fid == -1) return -1; useShift = (((fid & 0xF000000) >> 24) == fo::OBJ_TYPE_CRITTER); - direction = GetArtFIDFile(fid, file); + + char fileBuf[MAX_PATH]; + direction = GetArtFIDFile(fid, fileBuf); + file = fileBuf; } else { file = ctx.arg(1).strValue(); // path to frm/pcx file } @@ -663,68 +678,6 @@ void mf_interface_art_draw(OpcodeContext& ctx) { ctx.setReturn(result); } -void mf_unwield_slot(OpcodeContext& ctx) { - fo::InvenType slot = static_cast(ctx.arg(1).rawValue()); - if (slot < fo::INVEN_TYPE_WORN || slot > fo::INVEN_TYPE_LEFT_HAND) { - ctx.printOpcodeError("%s() - incorrect slot number.", ctx.getMetaruleName()); - ctx.setReturn(-1); - return; - } - fo::GameObject* critter = ctx.arg(0).object(); - if (critter->IsNotCritter()) { - ctx.printOpcodeError("%s() - the object is not a critter.", ctx.getMetaruleName()); - ctx.setReturn(-1); - return; - } - bool isDude = (critter == fo::var::obj_dude); - bool update = false; - if (slot && (GetLoopFlags() & (INVENTORY | INTFACEUSE | INTFACELOOT | BARTER)) == false) { - if (fo::func::inven_unwield(critter, (slot == fo::INVEN_TYPE_LEFT_HAND) ? fo::Left : fo::Right) == 0) { - update = isDude; - } - } else { - // force unwield for opened inventory - bool forceAdd = false; - fo::GameObject* item = nullptr; - if (slot != fo::INVEN_TYPE_WORN) { - if (!isDude) return; - long* itemRef = nullptr; - if (slot == fo::INVEN_TYPE_LEFT_HAND) { - item = fo::var::i_lhand; - itemRef = (long*)FO_VAR_i_lhand; - } else { - item = fo::var::i_rhand; - itemRef = (long*)FO_VAR_i_rhand; - } - if (item) { - if (!CorrectFidForRemovedItem_wHook(critter, item, (slot == fo::INVEN_TYPE_LEFT_HAND) ? fo::ObjectFlag::Left_Hand : fo::ObjectFlag::Right_Hand)) { - return; - } - *itemRef = 0; - forceAdd = true; - update = true; - } - } else { - if (isDude) item = fo::var::i_worn; - if (!item) { - item = fo::func::inven_worn(critter); - } else { - fo::var::i_worn = nullptr; - forceAdd = true; - } - if (item) { - if (!CorrectFidForRemovedItem_wHook(critter, item, fo::ObjectFlag::Worn)) { - if (forceAdd) fo::var::i_worn = item; - return; - } - if (isDude) fo::func::intface_update_ac(0); - } - } - if (forceAdd) fo::func::item_add_force(critter, item, 1); - } - if (update) fo::func::intface_update_items(0, -1, -1); -} - void mf_get_window_attribute(OpcodeContext& ctx) { fo::Window* win = Interface::GetWindow(ctx.arg(0).rawValue()); if (win == nullptr) { @@ -817,7 +770,7 @@ void mf_interface_print(OpcodeContext& ctx) { // same as vanilla PrintRect } void mf_win_fill_color(OpcodeContext& ctx) { - long result = fo::func::selectWindowID(ctx.program()->currentScriptWin); + long result = fo::func::selectWindowID(ctx.program()->currentScriptWin); // TODO: examine the issue of restoring program->currentScriptWin of the current window in op_pop_flags_ long iWin = *(DWORD*)FO_VAR_currentWindow; if (!result || iWin == -1) { ctx.printOpcodeError("%s() - no created or selected window.", ctx.getMetaruleName()); @@ -825,11 +778,13 @@ void mf_win_fill_color(OpcodeContext& ctx) { return; } if (ctx.numArgs() > 0) { - fo::WinFillRect(fo::var::sWindows[iWin].wID, - ctx.arg(0).rawValue(), ctx.arg(1).rawValue(), // x, y - ctx.arg(2).rawValue(), ctx.arg(3).rawValue(), // w, h - static_cast(ctx.arg(4).rawValue()) - ); + if (fo::WinFillRect(fo::var::sWindows[iWin].wID, + ctx.arg(0).rawValue(), ctx.arg(1).rawValue(), // x, y + ctx.arg(2).rawValue(), ctx.arg(3).rawValue(), // w, h + static_cast(ctx.arg(4).rawValue()))) + { + ctx.printOpcodeError("%s() - the fill area is truncated because it exceeds the current window.", ctx.getMetaruleName()); + } } else { fo::ClearWindow(fo::var::sWindows[iWin].wID, false); // full clear } diff --git a/sfall/Modules/Scripting/Handlers/Interface.h b/sfall/Modules/Scripting/Handlers/Interface.h index 9d725886..397080be 100644 --- a/sfall/Modules/Scripting/Handlers/Interface.h +++ b/sfall/Modules/Scripting/Handlers/Interface.h @@ -18,6 +18,8 @@ #pragma once +#include "..\OpcodeContext.h" + namespace sfall { namespace script @@ -28,6 +30,8 @@ class OpcodeContext; // input_functions void __declspec() op_input_funcs_available(); +void __declspec() op_set_pipboy_available(); + void op_key_pressed(OpcodeContext& ctx); void __declspec() op_tap_key(); @@ -50,12 +54,6 @@ void __declspec() op_get_screen_width(); //Return screen height void __declspec() op_get_screen_height(); -//Stop game, the same effect as open charsscreen or inventory -void __declspec() op_stop_game(); - -//Resume the game when it is stopped -void __declspec() op_resume_game(); - //Create a message window with given string void op_create_message_window(OpcodeContext&); @@ -113,8 +111,6 @@ void mf_draw_image_scaled(OpcodeContext&); void mf_interface_art_draw(OpcodeContext&); -void mf_unwield_slot(OpcodeContext&); - void mf_get_window_attribute(OpcodeContext&); void mf_interface_print(OpcodeContext&); diff --git a/sfall/Modules/Scripting/Handlers/Inventory.cpp b/sfall/Modules/Scripting/Handlers/Inventory.cpp new file mode 100644 index 00000000..e432d457 --- /dev/null +++ b/sfall/Modules/Scripting/Handlers/Inventory.cpp @@ -0,0 +1,175 @@ +/* + * sfall + * Copyright (C) 2008-2021 The sfall team + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "..\..\..\FalloutEngine\AsmMacros.h" +#include "..\..\..\FalloutEngine\Fallout2.h" +#include "..\..\LoadGameHook.h" +#include "..\..\Inventory.h" + +#include "..\..\..\Game\inventory.h" + +#include "Inventory.h" + +namespace sfall +{ +namespace script +{ + +void __declspec(naked) op_active_hand() { + __asm { + mov edx, dword ptr ds:[FO_VAR_itemCurrentItem]; + _J_RET_VAL_TYPE(VAR_TYPE_INT); + } +} + +void __declspec(naked) op_toggle_active_hand() { + __asm { + mov eax, 1; + jmp fo::funcoffs::intface_toggle_items_; + } +} + +void __declspec(naked) op_set_inven_ap_cost() { + __asm { + mov esi, ecx; + _GET_ARG_INT(end); + mov ecx, eax; + call Inventory::SetInvenApCost; +end: + mov ecx, esi; + retn; + } +} + +void mf_get_inven_ap_cost(OpcodeContext& ctx) { + ctx.setReturn(Inventory::GetInvenApCost()); +} + +void op_obj_is_carrying_obj(OpcodeContext& ctx) { + const ScriptValue &invenObjArg = ctx.arg(0), + &itemObjArg = ctx.arg(1); + + fo::GameObject *invenObj = invenObjArg.object(), + *itemObj = itemObjArg.object(); + + int count = 0; + if (invenObj != nullptr && itemObj != nullptr) { + for (int i = 0; i < invenObj->invenSize; i++) { + if (invenObj->invenTable[i].object == itemObj) { + count = invenObj->invenTable[i].count; + break; + } + } + } + ctx.setReturn(count); +} + +void mf_critter_inven_obj2(OpcodeContext& ctx) { + fo::GameObject* critter = ctx.arg(0).object(); + int slot = ctx.arg(1).rawValue(); + switch (slot) { + case 0: + ctx.setReturn(fo::func::inven_worn(critter)); + break; + case 1: + ctx.setReturn(fo::func::inven_right_hand(critter)); + break; + case 2: + ctx.setReturn(fo::func::inven_left_hand(critter)); + break; + case -2: + ctx.setReturn(critter->invenSize); + break; + default: + ctx.printOpcodeError("%s() - invalid type.", ctx.getMetaruleName()); + } +} + +void mf_item_weight(OpcodeContext& ctx) { + ctx.setReturn(fo::func::item_weight(ctx.arg(0).object())); +} + +void mf_get_current_inven_size(OpcodeContext& ctx) { + ctx.setReturn(game::Inventory::item_total_size(ctx.arg(0).object())); +} + +void mf_unwield_slot(OpcodeContext& ctx) { + fo::InvenType slot = static_cast(ctx.arg(1).rawValue()); + if (slot < fo::INVEN_TYPE_WORN || slot > fo::INVEN_TYPE_LEFT_HAND) { + ctx.printOpcodeError("%s() - incorrect slot number.", ctx.getMetaruleName()); + ctx.setReturn(-1); + return; + } + fo::GameObject* critter = ctx.arg(0).object(); + if (critter->IsNotCritter()) { + ctx.printOpcodeError("%s() - the object is not a critter.", ctx.getMetaruleName()); + ctx.setReturn(-1); + return; + } + bool isDude = (critter == fo::var::obj_dude); + bool update = false; + if (slot && (GetLoopFlags() & (INVENTORY | INTFACEUSE | INTFACELOOT | BARTER)) == false) { + if (fo::func::inven_unwield(critter, (slot == fo::INVEN_TYPE_LEFT_HAND) ? fo::Left : fo::Right) == 0) { + update = isDude; + } + } else { + // force unwield for opened inventory + bool forceAdd = false; + fo::GameObject* item = nullptr; + if (slot != fo::INVEN_TYPE_WORN) { + if (!isDude) return; + long* itemRef = nullptr; + if (slot == fo::INVEN_TYPE_LEFT_HAND) { + item = fo::var::i_lhand; + itemRef = (long*)FO_VAR_i_lhand; + } else { + item = fo::var::i_rhand; + itemRef = (long*)FO_VAR_i_rhand; + } + if (item) { + if (!game::Inventory::correctFidForRemovedItem(critter, item, (slot == fo::INVEN_TYPE_LEFT_HAND) ? fo::ObjectFlag::Left_Hand : fo::ObjectFlag::Right_Hand)) { + return; + } + *itemRef = 0; + forceAdd = true; + update = true; + } + } else { + if (isDude) item = fo::var::i_worn; + if (!item) { + item = fo::func::inven_worn(critter); + } else { + fo::var::i_worn = nullptr; + forceAdd = true; + } + if (item) { + if (!game::Inventory::correctFidForRemovedItem(critter, item, fo::ObjectFlag::Worn)) { + if (forceAdd) fo::var::i_worn = item; + return; + } + if (isDude) fo::func::intface_update_ac(0); + } + } + if (forceAdd) fo::func::item_add_force(critter, item, 1); + } + if (update) fo::func::intface_update_items(0, -1, -1); +} + + +} +} diff --git a/sfall/Modules/Scripting/Handlers/Inventory.h b/sfall/Modules/Scripting/Handlers/Inventory.h new file mode 100644 index 00000000..676d74fa --- /dev/null +++ b/sfall/Modules/Scripting/Handlers/Inventory.h @@ -0,0 +1,47 @@ +/* + * sfall + * Copyright (C) 2008-2021 The sfall team + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include "..\OpcodeContext.h" + +namespace sfall +{ +namespace script +{ + +void __declspec() op_active_hand(); + +void __declspec() op_toggle_active_hand(); + +void __declspec() op_set_inven_ap_cost(); + +void mf_get_inven_ap_cost(OpcodeContext&); + +void op_obj_is_carrying_obj(OpcodeContext&); + +void mf_critter_inven_obj2(OpcodeContext&); + +void mf_item_weight(OpcodeContext&); + +void mf_get_current_inven_size(OpcodeContext&); + +void mf_unwield_slot(OpcodeContext&); + +} +} diff --git a/sfall/Modules/Scripting/Handlers/Math.cpp b/sfall/Modules/Scripting/Handlers/Math.cpp index ceca2d10..a1f3157f 100644 --- a/sfall/Modules/Scripting/Handlers/Math.cpp +++ b/sfall/Modules/Scripting/Handlers/Math.cpp @@ -69,7 +69,7 @@ void op_arctan(OpcodeContext& ctx) { void op_power(OpcodeContext& ctx) { const ScriptValue &base = ctx.arg(0), - &power = ctx.arg(1); + &power = ctx.arg(1); float result = 0.0; if (power.isFloat()) result = pow(base.asFloat(), power.floatValue()); diff --git a/sfall/Modules/Scripting/Handlers/Metarule.cpp b/sfall/Modules/Scripting/Handlers/Metarule.cpp index 66a07160..513d70e5 100644 --- a/sfall/Modules/Scripting/Handlers/Metarule.cpp +++ b/sfall/Modules/Scripting/Handlers/Metarule.cpp @@ -21,8 +21,10 @@ #include "..\Arrays.h" #include "..\OpcodeContext.h" #include "Anims.h" +#include "Combat.h" #include "Core.h" #include "Interface.h" +#include "Inventory.h" #include "Math.h" #include "Misc.h" #include "Objects.h" @@ -134,6 +136,7 @@ static const SfallMetarule metarules[] = { {"set_map_enter_position", mf_set_map_enter_position, 3, 3, -1, {ARG_INT, ARG_INT, ARG_INT}}, {"set_object_data", mf_set_object_data, 3, 3, -1, {ARG_OBJECT, ARG_INT, ARG_INT}}, {"set_outline", mf_set_outline, 2, 2, -1, {ARG_OBJECT, ARG_INT}}, + {"set_quest_failure_value", mf_set_quest_failure_value, 2, 2, -1, {ARG_INT, ARG_INT}}, {"set_rest_heal_time", mf_set_rest_heal_time, 1, 1, -1, {ARG_INT}}, {"set_rest_mode", mf_set_rest_mode, 1, 1, -1, {ARG_INT}}, {"set_selectable_perk_npc", mf_set_selectable_perk_npc, 5, 5, -1, {ARG_OBJECT, ARG_STRING, ARG_INT, ARG_INT, ARG_STRING}}, diff --git a/sfall/Modules/Scripting/Handlers/Misc.cpp b/sfall/Modules/Scripting/Handlers/Misc.cpp index 463124e9..6d765da7 100644 --- a/sfall/Modules/Scripting/Handlers/Misc.cpp +++ b/sfall/Modules/Scripting/Handlers/Misc.cpp @@ -22,24 +22,16 @@ #include "..\..\..\FalloutEngine\Fallout2.h" #include "..\..\..\Utils.h" -#include "..\..\AI.h" -#include "..\..\Combat.h" #include "..\..\Criticals.h" #include "..\..\HeroAppearance.h" -#include "..\..\Inventory.h" -#include "..\..\KillCounter.h" //#include "..\..\MiscPatches.h" #include "..\..\Movies.h" -#include "..\..\PartyControl.h" #include "..\..\PlayerModel.h" +#include "..\..\QuestList.h" #include "..\..\ScriptExtender.h" #include "..\..\Sound.h" -#include "..\..\Stats.h" #include "..\Arrays.h" -#include "..\OpcodeContext.h" - -#include "..\..\SubModules\CombatBlock.h" #include "Misc.h" @@ -50,6 +42,18 @@ namespace script const char* stringTooLong = "%s() - the string exceeds maximum length of 64 characters."; +void __declspec(naked) op_stop_game() { + __asm { + jmp fo::funcoffs::map_disable_bk_processes_; + } +} + +void __declspec(naked) op_resume_game() { + __asm { + jmp fo::funcoffs::map_enable_bk_processes_; + } +} + void op_set_dm_model(OpcodeContext& ctx) { auto model = ctx.arg(0).strValue(); if (strlen(model) > 64) { @@ -90,245 +94,15 @@ void op_get_year(OpcodeContext& ctx) { ctx.setReturn(year); } -void __declspec(naked) op_game_loaded() { - __asm { - mov esi, ecx; - push eax; // script - call ScriptExtender::ScriptHasLoaded; - mov edx, eax; - mov eax, ebx; - _RET_VAL_INT; - mov ecx, esi; - retn; - } -} - -void __declspec(naked) op_set_pipboy_available() { - __asm { - _GET_ARG_INT(end); - cmp eax, 0; - jl end; - cmp eax, 1; - jg end; - mov byte ptr ds:[FO_VAR_gmovie_played_list][0x3], al; -end: - retn; - } -} - -// Kill counters -static bool extraKillCounter; -void SetExtraKillCounter(bool value) { extraKillCounter = value; } - -void __declspec(naked) op_get_kill_counter() { - __asm { - _GET_ARG_INT(fail); // get kill type value - cmp extraKillCounter, 1; - jne skip; - cmp eax, 38; - jae fail; - movzx edx, word ptr ds:[FO_VAR_pc_kill_counts][eax * 2]; - jmp end; -skip: - cmp eax, 19; - jae fail; - mov edx, ds:[FO_VAR_pc_kill_counts][eax * 4]; -end: - mov eax, ebx; // script - _RET_VAL_INT; - retn; -fail: - xor edx, edx; // return 0 - jmp end; - } -} - -void __declspec(naked) op_mod_kill_counter() { - __asm { - push ecx; - _GET_ARG(ecx, esi); // get mod value - mov eax, ebx; - _GET_ARG_INT(end); // get kill type value - cmp si, VAR_TYPE_INT; - jnz end; - cmp extraKillCounter, 1; - je skip; - cmp eax, 19; - jae end; - add ds:[FO_VAR_pc_kill_counts][eax * 4], ecx; - pop ecx; - retn; -skip: - cmp eax, 38; - jae end; - add word ptr ds:[FO_VAR_pc_kill_counts][eax * 2], cx; -end: - pop ecx; - retn; - } -} - -void op_set_object_knockback(OpcodeContext& ctx) { - int mode = 0; - switch (ctx.opcode()) { - case 0x196: - mode = 1; - break; - case 0x197: - mode = 2; - break; - } - fo::GameObject* object = ctx.arg(0).object(); - if (mode) { - if (object->IsNotCritter()) { - ctx.printOpcodeError("%s() - the object is not a critter.", ctx.getOpcodeName()); - return; - } - } else { - if (object->IsNotItem()) { - ctx.printOpcodeError("%s() - the object is not an item.", ctx.getOpcodeName()); - return; - } - } - KnockbackSetMod(object, ctx.arg(1).rawValue(), ctx.arg(2).asFloat(), mode); -} - -void op_remove_object_knockback(OpcodeContext& ctx) { - int mode = 0; - switch (ctx.opcode()) { - case 0x199: - mode = 1; - break; - case 0x19a: - mode = 2; - break; - } - KnockbackRemoveMod(ctx.arg(0).object(), mode); -} - -void __declspec(naked) op_active_hand() { - __asm { - mov edx, dword ptr ds:[FO_VAR_itemCurrentItem]; - _J_RET_VAL_TYPE(VAR_TYPE_INT); -// retn; - } -} - -void __declspec(naked) op_toggle_active_hand() { - __asm { - mov eax, 1; - jmp fo::funcoffs::intface_toggle_items_; - } -} - void __declspec(naked) op_eax_available() { __asm { xor edx, edx _J_RET_VAL_TYPE(VAR_TYPE_INT); -// retn; } } -static const char* nameNPCToInc; -static long pidNPCToInc; -static bool onceNpcLoop; - -static void __cdecl IncNPCLevel(const char* fmt, const char* name) { - fo::GameObject* mObj; - __asm { - push edx; - mov eax, [ebp + 0x150 - 0x1C + 16]; // ebp <- esp - mov edx, [eax]; - mov mObj, edx; - } - - if ((pidNPCToInc && (mObj && mObj->protoId == pidNPCToInc)) || (!pidNPCToInc && !_stricmp(name, nameNPCToInc))) { - fo::func::debug_printf(fmt, name); - - SafeWrite32(0x495C50, 0x01FB840F); // Want to keep this check intact. (restore) - - SafeMemSet(0x495C77, CodeType::Nop, 6); // Check that the player is high enough for the npc to consider this level - //SafeMemSet(0x495C8C, CodeType::Nop, 6); // Check that the npc isn't already at its maximum level - SafeMemSet(0x495CEC, CodeType::Nop, 6); // Check that the npc hasn't already levelled up recently - if (!npcAutoLevelEnabled) { - SafeWrite8(0x495CFB, CodeType::JumpShort); // Disable random element - } - __asm mov [ebp + 0x150 - 0x28 + 16], 255; // set counter for exit loop - } else { - if (!onceNpcLoop) { - SafeWrite32(0x495C50, 0x01FCE9); // set goto next member - onceNpcLoop = true; - } - } - __asm pop edx; -} - -void op_inc_npc_level(OpcodeContext& ctx) { - nameNPCToInc = ctx.arg(0).asString(); - pidNPCToInc = ctx.arg(0).asInt(); // set to 0 if passing npc name - if (pidNPCToInc == 0 && nameNPCToInc[0] == 0) return; - - MakeCall(0x495BF1, IncNPCLevel); // Replace the debug output - __asm call fo::funcoffs::partyMemberIncLevels_; - onceNpcLoop = false; - - // restore code - SafeWrite32(0x495C50, 0x01FB840F); - __int64 data = 0x01D48C0F; - SafeWriteBytes(0x495C77, (BYTE*)&data, 6); - //SafeWrite16(0x495C8C, 0x8D0F); - //SafeWrite32(0x495C8E, 0x000001BF); - data = 0x0130850F; - SafeWriteBytes(0x495CEC, (BYTE*)&data, 6); - if (!npcAutoLevelEnabled) { - SafeWrite8(0x495CFB, CodeType::JumpZ); - } -} - -void op_get_npc_level(OpcodeContext& ctx) { - int level = -1; - DWORD findPid = ctx.arg(0).asInt(); // set to 0 if passing npc name - const char *critterName, *name = ctx.arg(0).asString(); - - if (findPid || name[0] != 0) { - DWORD pid = 0; - DWORD* members = fo::var::partyMemberList; - for (DWORD i = 0; i < fo::var::partyMemberCount; i++) { - if (!findPid) { - __asm { - mov eax, members; - mov eax, [eax]; - call fo::funcoffs::critter_name_; - mov critterName, eax; - } - if (!_stricmp(name, critterName)) { // found npc - pid = ((fo::GameObject*)*members)->protoId; - break; - } - } else { - DWORD _pid = ((fo::GameObject*)*members)->protoId; - if (findPid == _pid) { - pid = _pid; - break; - } - } - members += 4; - } - if (pid) { - DWORD* pids = fo::var::partyMemberPidList; - for (DWORD j = 0; j < fo::var::partyMemberMaxCount; j++) { - if (pids[j] == pid) { - level = fo::var::partyMemberLevelUpInfoList[j * 3]; - break; - } - } - } - } - ctx.setReturn(level); -} - static bool IsSpecialIni(const char* str, const char* end) { - const char* pos = strfind(str, &::sfall::ddrawIni[2]); + const char* pos = strfind(str, &IniReader::GetConfigFile()[2]); // TODO test if (pos && pos < end) return true; pos = strfind(str, "f2_res.ini"); if (pos && pos < end) return true; @@ -379,10 +153,10 @@ static DWORD GetIniSetting(const char* str, bool isString) { } if (isString) { ScriptExtender::gTextBuffer[0] = 0; - iniGetString(section, key, "", ScriptExtender::gTextBuffer, 256, file); + IniReader::GetString(section, key, "", ScriptExtender::gTextBuffer, 256, file); return (DWORD)&ScriptExtender::gTextBuffer[0]; } else { - return iniGetInt(section, key, -1, file); + return IniReader::GetInt(section, key, -1, file); } } @@ -416,51 +190,6 @@ end: } } -void __declspec(naked) op_set_hp_per_level_mod() { - __asm { - mov esi, ecx; - _GET_ARG_INT(end); - push eax; // allowed -/+127 - push 0x4AFBC1; - call SafeWrite8; -end: - mov ecx, esi; - retn; - } -} - -void __declspec(naked) op_get_bodypart_hit_modifier() { - __asm { - _GET_ARG_INT(fail); // get body value - cmp eax, 8; // Body_Head - Body_Uncalled - ja fail; - mov edx, ds:[FO_VAR_hit_location_penalty][eax * 4]; -end: - mov eax, ebx; // script - _J_RET_VAL_TYPE(VAR_TYPE_INT); -fail: - xor edx, edx; // return 0 - jmp end; - } -} - -void __declspec(naked) op_set_bodypart_hit_modifier() { - __asm { - push ecx; - _GET_ARG(ecx, esi); // get body value - mov eax, ebx; - _GET_ARG_INT(end); // get modifier value - cmp si, VAR_TYPE_INT; - jnz end; - cmp eax, 8; // Body_Head - Body_Uncalled - ja end; - mov ds:[FO_VAR_hit_location_penalty][eax * 4], ecx; -end: - pop ecx; - retn; - } -} - static const char* valueOutRange = "%s() - argument values out of range."; void op_set_critical_table(OpcodeContext& ctx) { @@ -502,40 +231,6 @@ void op_reset_critical_table(OpcodeContext& ctx) { } } -void __declspec(naked) op_set_unspent_ap_bonus() { - __asm { - _GET_ARG_INT(end); - mov Stats::standardApAcBonus, eax; -end: - retn; - } -} - -void __declspec(naked) op_get_unspent_ap_bonus() { - __asm { - mov edx, Stats::standardApAcBonus; - _J_RET_VAL_TYPE(VAR_TYPE_INT); -// retn; - } -} - -void __declspec(naked) op_set_unspent_ap_perk_bonus() { - __asm { - _GET_ARG_INT(end); - mov Stats::extraApAcBonus, eax; -end: - retn; - } -} - -void __declspec(naked) op_get_unspent_ap_perk_bonus() { - __asm { - mov edx, Stats::extraApAcBonus; - _J_RET_VAL_TYPE(VAR_TYPE_INT); -// retn; - } -} - void op_set_palette(OpcodeContext& ctx) { const char* palette = ctx.arg(0).strValue(); __asm { @@ -591,7 +286,6 @@ void __declspec(naked) op_get_light_level() { __asm { mov edx, ds:[FO_VAR_ambient_light]; _J_RET_VAL_TYPE(VAR_TYPE_INT); -// retn; } } @@ -604,10 +298,6 @@ void __declspec(naked) op_refresh_pc_art() { } } -void op_get_attack_type(OpcodeContext& ctx) { - ctx.setReturn(fo::GetCurrentAttackMode()); -} - void op_play_sfall_sound(OpcodeContext& ctx) { DWORD soundID = 0; long mode = ctx.arg(1).rawValue(); @@ -656,33 +346,8 @@ fail: void __declspec(naked) op_modified_ini() { __asm { - mov edx, modifiedIni; + mov edx, IniReader::modifiedIni; _J_RET_VAL_TYPE(VAR_TYPE_INT); -// retn; - } -} - -void __declspec(naked) op_force_aimed_shots() { - __asm { - mov esi, ecx; - _GET_ARG_INT(end); - push eax; - call ForceAimedShots; -end: - mov ecx, esi; - retn; - } -} - -void __declspec(naked) op_disable_aimed_shots() { - __asm { - mov esi, ecx; - _GET_ARG_INT(end); - push eax; - call DisableAimedShots; -end: - mov ecx, esi; - retn; } } @@ -699,52 +364,6 @@ end: } } -void __declspec(naked) op_get_last_attacker() { - __asm { - _GET_ARG_INT(fail); - mov esi, ecx; - push eax; - call AI::AIGetLastAttacker; - mov edx, eax; - mov ecx, esi; -end: - mov eax, ebx; - _J_RET_VAL_TYPE(VAR_TYPE_INT); -fail: - xor edx, edx; // return 0 - jmp end; - } -} - -void __declspec(naked) op_get_last_target() { - __asm { - _GET_ARG_INT(fail); - mov esi, ecx; - push eax; - call AI::AIGetLastTarget; - mov edx, eax; - mov ecx, esi; -end: - mov eax, ebx; - _J_RET_VAL_TYPE(VAR_TYPE_INT); -fail: - xor edx, edx; // return 0 - jmp end; - } -} - -void __declspec(naked) op_block_combat() { - __asm { - mov esi, ecx; - _GET_ARG_INT(end); - push eax; - call CombatBlock::SetBlockCombat; -end: - mov ecx, esi; - retn; - } -} - void __declspec(naked) op_tile_under_cursor() { __asm { mov esi, ebx; @@ -759,7 +378,6 @@ void __declspec(naked) op_tile_under_cursor() { mov ebx, esi; mov eax, esi; _J_RET_VAL_TYPE(VAR_TYPE_INT); -// retn; } } @@ -767,31 +385,9 @@ void __declspec(naked) op_gdialog_get_barter_mod() { __asm { mov edx, dword ptr ds:[FO_VAR_gdBarterMod]; _J_RET_VAL_TYPE(VAR_TYPE_INT); -// retn; } } -void __declspec(naked) op_set_inven_ap_cost() { - __asm { - mov esi, ecx; - _GET_ARG_INT(end); - mov ecx, eax; - call Inventory::SetInvenApCost; -end: - mov ecx, esi; - retn; - } -} - -void mf_get_inven_ap_cost(OpcodeContext& ctx) { - ctx.setReturn(Inventory::GetInvenApCost()); -} - -void mf_attack_is_aimed(OpcodeContext& ctx) { - DWORD isAimed, unused; - ctx.setReturn(!fo::func::intface_get_attack(&unused, &isAimed) ? isAimed : 0); -} - void op_sneak_success(OpcodeContext& ctx) { ctx.setReturn(fo::func::is_pc_sneak_working()); } @@ -901,22 +497,8 @@ void mf_get_ini_section(OpcodeContext& ctx) { ctx.setReturn(arrayId); } -void mf_npc_engine_level_up(OpcodeContext& ctx) { - if (ctx.arg(0).asBool()) { - if (!npcEngineLevelUp) SafeWrite16(0x4AFC1C, 0x840F); // enable - npcEngineLevelUp = true; - } else { - if (npcEngineLevelUp) SafeWrite16(0x4AFC1C, 0xE990); - npcEngineLevelUp = false; - } -} - -void mf_combat_data(OpcodeContext& ctx) { - fo::ComputeAttackResult* ctd = nullptr; - if (fo::var::combat_state & 1) { - ctd = &fo::var::main_ctd; - } - ctx.setReturn((DWORD)ctd, DataType::INT); +void mf_set_quest_failure_value(OpcodeContext& ctx) { + QuestList::AddQuestFailureValue(ctx.arg(0).rawValue(), ctx.arg(1).rawValue()); } } diff --git a/sfall/Modules/Scripting/Handlers/Misc.h b/sfall/Modules/Scripting/Handlers/Misc.h index 09357cbd..1af23a26 100644 --- a/sfall/Modules/Scripting/Handlers/Misc.h +++ b/sfall/Modules/Scripting/Handlers/Misc.h @@ -18,6 +18,8 @@ #pragma once +#include "..\OpcodeContext.h" + /* * Misc operators */ @@ -29,6 +31,12 @@ namespace script class OpcodeContext; +//Stop game, the same effect as open charsscreen or inventory +void __declspec() op_stop_game(); + +//Resume the game when it is stopped +void __declspec() op_resume_game(); + void op_set_dm_model(OpcodeContext&); void op_set_df_model(OpcodeContext&); @@ -37,31 +45,8 @@ void op_set_movie_path(OpcodeContext&); void op_get_year(OpcodeContext&); -void __declspec() op_game_loaded(); - -void __declspec() op_set_pipboy_available(); - -// Kill counters -void SetExtraKillCounter(bool value); - -void __declspec() op_get_kill_counter(); - -void __declspec() op_mod_kill_counter(); - -void op_set_object_knockback(OpcodeContext&); - -void op_remove_object_knockback(OpcodeContext&); - -void __declspec() op_active_hand(); - -void __declspec() op_toggle_active_hand(); - void __declspec() op_eax_available(); -void op_inc_npc_level(OpcodeContext&); - -void op_get_npc_level(OpcodeContext&); - void op_get_ini_setting(OpcodeContext&); void op_get_ini_string(OpcodeContext&); @@ -70,26 +55,12 @@ void __declspec() op_get_uptime(); void __declspec() op_set_car_current_town(); -void __declspec() op_set_hp_per_level_mod(); - -void __declspec() op_get_bodypart_hit_modifier(); - -void __declspec() op_set_bodypart_hit_modifier(); - void op_set_critical_table(OpcodeContext&); void op_get_critical_table(OpcodeContext&); void op_reset_critical_table(OpcodeContext&); -void __declspec() op_set_unspent_ap_bonus(); - -void __declspec() op_get_unspent_ap_bonus(); - -void __declspec() op_set_unspent_ap_perk_bonus(); - -void __declspec() op_get_unspent_ap_perk_bonus(); - void op_set_palette(OpcodeContext&); //numbers subgame functions @@ -105,8 +76,6 @@ void __declspec() op_get_light_level(); void __declspec() op_refresh_pc_art(); -void op_get_attack_type(OpcodeContext&); - void op_play_sfall_sound(OpcodeContext&); void __declspec() op_stop_sfall_sound(); @@ -115,28 +84,12 @@ void __declspec() op_get_tile_fid(); void __declspec() op_modified_ini(); -void __declspec() op_force_aimed_shots(); - -void __declspec() op_disable_aimed_shots(); - void __declspec() op_mark_movie_played(); -void __declspec() op_get_last_attacker(); - -void __declspec() op_get_last_target(); - -void __declspec() op_block_combat(); - void __declspec() op_tile_under_cursor(); void __declspec() op_gdialog_get_barter_mod(); -void __declspec() op_set_inven_ap_cost(); - -void mf_get_inven_ap_cost(OpcodeContext&); - -void mf_attack_is_aimed(OpcodeContext&); - void op_sneak_success(OpcodeContext&); void op_tile_light(OpcodeContext&); @@ -149,9 +102,7 @@ void mf_get_ini_sections(OpcodeContext&); void mf_get_ini_section(OpcodeContext&); -void mf_npc_engine_level_up(OpcodeContext&); - -void mf_combat_data(OpcodeContext&); +void mf_set_quest_failure_value(OpcodeContext&); } } diff --git a/sfall/Modules/Scripting/Handlers/Objects.cpp b/sfall/Modules/Scripting/Handlers/Objects.cpp index 3022062e..6990e725 100644 --- a/sfall/Modules/Scripting/Handlers/Objects.cpp +++ b/sfall/Modules/Scripting/Handlers/Objects.cpp @@ -21,15 +21,11 @@ #include "..\..\CritterStats.h" #include "..\..\Drugs.h" #include "..\..\Explosions.h" -//#include "..\..\Inventory.h" #include "..\..\LoadGameHook.h" #include "..\..\Objects.h" #include "..\..\PartyControl.h" #include "..\..\ScriptExtender.h" #include "..\Arrays.h" -#include "..\OpcodeContext.h" - -#include "..\..\..\Game\inventory.h" #include "Objects.h" @@ -38,10 +34,103 @@ namespace sfall namespace script { -#define exec_script_proc(script, proc) __asm { \ - __asm mov eax, script \ - __asm mov edx, proc \ - __asm call fo::funcoffs::exec_script_proc_ \ +static const char* protoFailedLoad = "%s() - failed to load a prototype ID: %d"; + +static const char* nameNPCToInc; +static long pidNPCToInc; +static bool onceNpcLoop; + +static void __cdecl IncNPCLevel(const char* fmt, const char* name) { + fo::GameObject* mObj; + __asm { + push edx; + mov eax, [ebp + 0x150 - 0x1C + 16]; // ebp <- esp + mov edx, [eax]; + mov mObj, edx; + } + + if ((pidNPCToInc && (mObj && mObj->protoId == pidNPCToInc)) || (!pidNPCToInc && !_stricmp(name, nameNPCToInc))) { + fo::func::debug_printf(fmt, name); + + SafeWrite32(0x495C50, 0x01FB840F); // Want to keep this check intact. (restore) + + SafeMemSet(0x495C77, CodeType::Nop, 6); // Check that the player is high enough for the npc to consider this level + //SafeMemSet(0x495C8C, CodeType::Nop, 6); // Check that the npc isn't already at its maximum level + SafeMemSet(0x495CEC, CodeType::Nop, 6); // Check that the npc hasn't already levelled up recently + if (!npcAutoLevelEnabled) { + SafeWrite8(0x495CFB, CodeType::JumpShort); // Disable random element + } + __asm mov [ebp + 0x150 - 0x28 + 16], 255; // set counter for exit loop + } else { + if (!onceNpcLoop) { + SafeWrite32(0x495C50, 0x01FCE9); // set goto next member + onceNpcLoop = true; + } + } + __asm pop edx; +} + +void op_inc_npc_level(OpcodeContext& ctx) { + nameNPCToInc = ctx.arg(0).asString(); + pidNPCToInc = ctx.arg(0).asInt(); // set to 0 if passing npc name + if (pidNPCToInc == 0 && nameNPCToInc[0] == 0) return; + + MakeCall(0x495BF1, IncNPCLevel); // Replace the debug output + __asm call fo::funcoffs::partyMemberIncLevels_; + onceNpcLoop = false; + + // restore code + SafeWrite32(0x495C50, 0x01FB840F); + __int64 data = 0x01D48C0F; + SafeWriteBytes(0x495C77, (BYTE*)&data, 6); + //SafeWrite16(0x495C8C, 0x8D0F); + //SafeWrite32(0x495C8E, 0x000001BF); + data = 0x0130850F; + SafeWriteBytes(0x495CEC, (BYTE*)&data, 6); + if (!npcAutoLevelEnabled) { + SafeWrite8(0x495CFB, CodeType::JumpZ); + } +} + +void op_get_npc_level(OpcodeContext& ctx) { + int level = -1; + DWORD findPid = ctx.arg(0).asInt(); // set to 0 if passing npc name + const char *critterName, *name = ctx.arg(0).asString(); + + if (findPid || name[0] != 0) { + DWORD pid = 0; + auto members = fo::var::partyMemberList; + for (DWORD i = 0; i < fo::var::partyMemberCount; i++) { + if (!findPid) { + __asm { + mov eax, members; + mov eax, [eax]; + call fo::funcoffs::critter_name_; + mov critterName, eax; + } + if (!_stricmp(name, critterName)) { // found npc + pid = members[i].object->protoId; + break; + } + } else { + DWORD _pid = members[i].object->protoId; + if (findPid == _pid) { + pid = _pid; + break; + } + } + } + if (pid) { + DWORD* pidList = fo::var::partyMemberPidList; + for (DWORD j = 0; j < fo::var::partyMemberMaxCount; j++) { + if (pidList[j] == pid) { + level = fo::var::partyMemberLevelUpInfoList[j * 3]; + break; + } + } + } + } + ctx.setReturn(level); } void op_remove_script(OpcodeContext& ctx) { @@ -52,6 +141,12 @@ void op_remove_script(OpcodeContext& ctx) { } } +#define exec_script_proc(script, proc) __asm { \ + __asm mov eax, script \ + __asm mov edx, proc \ + __asm call fo::funcoffs::exec_script_proc_ \ +} + void op_set_script(OpcodeContext& ctx) { using fo::Scripts::start; using fo::Scripts::map_enter_p_proc; @@ -106,6 +201,8 @@ void op_create_spatial(OpcodeContext& ctx) { ctx.setReturn(fo::func::scr_find_obj_from_program(scriptPtr->program)); } +#undef exec_script_proc + void mf_spatial_radius(OpcodeContext& ctx) { auto spatialObj = ctx.arg(0).object(); fo::ScriptInstance* script; @@ -125,25 +222,43 @@ void op_set_critter_burst_disable(OpcodeContext& ctx) { void op_get_weapon_ammo_pid(OpcodeContext& ctx) { auto obj = ctx.arg(0).object(); - ctx.setReturn(obj->item.ammoPid); + long pid = -1; + fo::Proto* proto; + if (obj->IsItem() && GetProto(obj->protoId, &proto)) { + long type = proto->item.type; + if (type == fo::ItemType::item_type_weapon || type == fo::ItemType::item_type_misc_item) { + pid = obj->item.ammoPid; + } + } + ctx.setReturn(pid); } void op_set_weapon_ammo_pid(OpcodeContext& ctx) { auto obj = ctx.arg(0).object(); - obj->item.ammoPid = ctx.arg(1).rawValue(); + if (obj->IsNotItem()) return; + + fo::Proto* proto; + if (GetProto(obj->protoId, &proto)) { + long type = proto->item.type; + if (type == fo::ItemType::item_type_weapon || type == fo::ItemType::item_type_misc_item) { + obj->item.ammoPid = ctx.arg(1).rawValue(); + } + } else { + ctx.printOpcodeError(protoFailedLoad, ctx.getOpcodeName(), obj->protoId); + } } void op_get_weapon_ammo_count(OpcodeContext& ctx) { auto obj = ctx.arg(0).object(); - ctx.setReturn(obj->item.charges); + ctx.setReturn((obj->IsItem()) ? obj->item.charges : 0); } void op_set_weapon_ammo_count(OpcodeContext& ctx) { auto obj = ctx.arg(0).object(); - obj->item.charges = ctx.arg(1).rawValue(); + if (obj->IsItem()) obj->item.charges = ctx.arg(1).rawValue(); } -enum { +enum class BlockType { BLOCKING_TYPE_BLOCK = 0, BLOCKING_TYPE_SHOOT = 1, BLOCKING_TYPE_AI = 2, @@ -151,15 +266,15 @@ enum { BLOCKING_TYPE_SCROLL = 4 }; -static DWORD getBlockingFunc(DWORD type) { +static DWORD getBlockingFunc(BlockType type) { switch (type) { - case BLOCKING_TYPE_BLOCK: default: + case BlockType::BLOCKING_TYPE_BLOCK: default: return fo::funcoffs::obj_blocking_at_; // with calling hook - case BLOCKING_TYPE_SHOOT: + case BlockType::BLOCKING_TYPE_SHOOT: return fo::funcoffs::obj_shoot_blocking_at_; // w/o calling hook - case BLOCKING_TYPE_AI: + case BlockType::BLOCKING_TYPE_AI: return fo::funcoffs::obj_ai_blocking_at_; // w/o calling hook - case BLOCKING_TYPE_SIGHT: + case BlockType::BLOCKING_TYPE_SIGHT: return fo::funcoffs::obj_sight_blocking_at_; // w/o calling hook //case 4: // return obj_scroll_blocking_at_; @@ -168,20 +283,19 @@ static DWORD getBlockingFunc(DWORD type) { void op_make_straight_path(OpcodeContext& ctx) { auto objFrom = ctx.arg(0).object(); - DWORD tileTo = ctx.arg(1).rawValue(), - type = ctx.arg(2).rawValue(); + DWORD tileTo = ctx.arg(1).rawValue(); + BlockType type = (BlockType)ctx.arg(2).rawValue(); - long flag = (type == BLOCKING_TYPE_SHOOT) ? 32 : 0; - DWORD resultObj = 0; - fo::func::make_straight_path_func(objFrom, objFrom->tile, tileTo, 0, &resultObj, flag, (void*)getBlockingFunc(type)); + long flag = (type == BlockType::BLOCKING_TYPE_SHOOT) ? 32 : 0; + fo::GameObject* resultObj = nullptr; + fo::func::make_straight_path_func(objFrom, objFrom->tile, tileTo, 0, (DWORD*)&resultObj, flag, (void*)getBlockingFunc(type)); ctx.setReturn(resultObj); } void op_make_path(OpcodeContext& ctx) { auto objFrom = ctx.arg(0).object(); - auto tileTo = ctx.arg(1).rawValue(), - type = ctx.arg(2).rawValue(); - auto func = getBlockingFunc(type); + auto tileTo = ctx.arg(1).rawValue(); + auto func = getBlockingFunc((BlockType)ctx.arg(2).rawValue()); // if the object is not a critter, then there is no need to check tile (tileTo) for blocking long checkFlag = (objFrom->IsCritter()); @@ -197,11 +311,11 @@ void op_make_path(OpcodeContext& ctx) { void op_obj_blocking_at(OpcodeContext& ctx) { DWORD tile = ctx.arg(0).rawValue(), - elevation = ctx.arg(1).rawValue(), - type = ctx.arg(2).rawValue(); + elevation = ctx.arg(1).rawValue(); + BlockType type = (BlockType)ctx.arg(2).rawValue(); fo::GameObject* resultObj = fo::func::obj_blocking_at_wrapper(0, tile, elevation, (void*)getBlockingFunc(type)); - if (resultObj && type == BLOCKING_TYPE_SHOOT && (resultObj->flags & fo::ObjectFlag::ShootThru)) { // don't know what this flag means, copy-pasted from the engine code + if (resultObj && type == BlockType::BLOCKING_TYPE_SHOOT && (resultObj->flags & fo::ObjectFlag::ShootThru)) { // don't know what this flag means, copy-pasted from the engine code // this check was added because the engine always does exactly this when using shoot blocking checks resultObj = nullptr; } @@ -224,9 +338,8 @@ void op_get_party_members(OpcodeContext& ctx) { auto includeHidden = ctx.arg(0).rawValue(); int actualCount = fo::var::partyMemberCount; DWORD arrayId = CreateTempArray(0, 4); - auto partyMemberList = fo::var::partyMemberList; for (int i = 0; i < actualCount; i++) { - auto obj = reinterpret_cast(partyMemberList[i * 4]); + fo::GameObject* obj = fo::var::partyMemberList[i].object; if (includeHidden || (obj->IsCritter() && !fo::func::critter_is_dead(obj) && !(obj->flags & fo::ObjectFlag::Mouse_3d))) { arrays[arrayId].push_back((long)obj); } @@ -234,49 +347,6 @@ void op_get_party_members(OpcodeContext& ctx) { ctx.setReturn(arrayId); } -void op_art_exists(OpcodeContext& ctx) { - ctx.setReturn(fo::func::art_exists(ctx.arg(0).rawValue())); -} - -void op_obj_is_carrying_obj(OpcodeContext& ctx) { - int num = 0; - const ScriptValue &invenObjArg = ctx.arg(0), - &itemObjArg = ctx.arg(1); - - fo::GameObject *invenObj = invenObjArg.object(), - *itemObj = itemObjArg.object(); - if (invenObj != nullptr && itemObj != nullptr) { - for (int i = 0; i < invenObj->invenSize; i++) { - if (invenObj->invenTable[i].object == itemObj) { - num = invenObj->invenTable[i].count; - break; - } - } - } - ctx.setReturn(num); -} - -void mf_critter_inven_obj2(OpcodeContext& ctx) { - fo::GameObject* critter = ctx.arg(0).object(); - int slot = ctx.arg(1).rawValue(); - switch (slot) { - case 0: - ctx.setReturn(fo::func::inven_worn(critter)); - break; - case 1: - ctx.setReturn(fo::func::inven_right_hand(critter)); - break; - case 2: - ctx.setReturn(fo::func::inven_left_hand(critter)); - break; - case -2: - ctx.setReturn(critter->invenSize); - break; - default: - ctx.printOpcodeError("%s() - invalid type.", ctx.getMetaruleName()); - } -} - void mf_set_outline(OpcodeContext& ctx) { auto obj = ctx.arg(0).object(); int color = ctx.arg(1).rawValue(); @@ -303,10 +373,6 @@ void mf_outlined_object(OpcodeContext& ctx) { ctx.setReturn(fo::var::outlined_object); } -void mf_item_weight(OpcodeContext& ctx) { - ctx.setReturn(fo::func::item_weight(ctx.arg(0).object())); -} - void mf_set_dude_obj(OpcodeContext& ctx) { auto obj = ctx.arg(0).object(); if (obj == nullptr || obj->IsCritter()) { @@ -366,48 +432,43 @@ void mf_item_make_explosive(OpcodeContext& ctx) { } } -void mf_get_current_inven_size(OpcodeContext& ctx) { - ctx.setReturn(game::Inventory::item_total_size(ctx.arg(0).object())); -} - void mf_get_dialog_object(OpcodeContext& ctx) { ctx.setReturn(InDialog() ? fo::var::dialog_target : 0); } void mf_obj_under_cursor(OpcodeContext& ctx) { - ctx.setReturn((fo::var::gmouse_3d_current_mode != 0) - ? fo::func::object_under_mouse(ctx.arg(0).asBool() ? 1 : -1, ctx.arg(1).rawValue(), fo::var::map_elevation) - : 0); + ctx.setReturn( + fo::func::object_under_mouse(ctx.arg(0).asBool() ? 1 : -1, ctx.arg(1).rawValue(), fo::var::map_elevation) + ); } void mf_get_loot_object(OpcodeContext& ctx) { ctx.setReturn((GetLoopFlags() & INTFACELOOT) ? fo::var::target_stack[fo::var::target_curr_stack] : 0); } -static const char* failedLoad = "%s() - failed to load a prototype ID: %d"; static bool protoMaxLimitPatch = false; void op_get_proto_data(OpcodeContext& ctx) { + long result = -1; fo::Proto* protoPtr; int pid = ctx.arg(0).rawValue(); - int result = fo::func::proto_ptr(pid, &protoPtr); - if (result != -1) { + if (fo::CheckProtoID(pid) && fo::func::proto_ptr(pid, &protoPtr) != result) { result = *(long*)((BYTE*)protoPtr + ctx.arg(1).rawValue()); } else { - ctx.printOpcodeError(failedLoad, ctx.getOpcodeName(), pid); + ctx.printOpcodeError(protoFailedLoad, ctx.getOpcodeName(), pid); } ctx.setReturn(result); } void op_set_proto_data(OpcodeContext& ctx) { int pid = ctx.arg(0).rawValue(); - if (CritterStats::SetProtoData(pid, ctx.arg(1).rawValue(), ctx.arg(2).rawValue()) != -1) { + if (fo::CheckProtoID(pid) && CritterStats::SetProtoData(pid, ctx.arg(1).rawValue(), ctx.arg(2).rawValue()) != -1) { if (!protoMaxLimitPatch) { Objects::LoadProtoAutoMaxLimit(); protoMaxLimitPatch = true; } } else { - ctx.printOpcodeError(failedLoad, ctx.getOpcodeName(), pid); + ctx.printOpcodeError(protoFailedLoad, ctx.getOpcodeName(), pid); } } @@ -532,5 +593,15 @@ void mf_objects_in_radius(OpcodeContext& ctx) { ctx.setReturn(id); } +void mf_npc_engine_level_up(OpcodeContext& ctx) { + if (ctx.arg(0).asBool()) { + if (!npcEngineLevelUp) SafeWrite16(0x4AFC1C, 0x840F); // enable + npcEngineLevelUp = true; + } else { + if (npcEngineLevelUp) SafeWrite16(0x4AFC1C, 0xE990); + npcEngineLevelUp = false; + } +} + } } diff --git a/sfall/Modules/Scripting/Handlers/Objects.h b/sfall/Modules/Scripting/Handlers/Objects.h index 10c5f3cf..ba1d8d7e 100644 --- a/sfall/Modules/Scripting/Handlers/Objects.h +++ b/sfall/Modules/Scripting/Handlers/Objects.h @@ -18,15 +18,17 @@ #pragma once -#include "..\..\..\main.h" -#include "..\..\Inventory.h" -#include "..\..\ScriptExtender.h" +#include "..\OpcodeContext.h" namespace sfall { namespace script { +void op_inc_npc_level(OpcodeContext&); + +void op_get_npc_level(OpcodeContext&); + void op_remove_script(OpcodeContext&); void op_set_script(OpcodeContext&); @@ -57,12 +59,6 @@ void op_tile_get_objects(OpcodeContext&); void op_get_party_members(OpcodeContext&); -void op_art_exists(OpcodeContext&); - -void op_obj_is_carrying_obj(OpcodeContext&); - -void mf_critter_inven_obj2(OpcodeContext&); - void mf_set_outline(OpcodeContext&); void mf_get_outline(OpcodeContext&); @@ -73,8 +69,6 @@ void mf_get_flags(OpcodeContext&); void mf_outlined_object(OpcodeContext&); -void mf_item_weight(OpcodeContext&); - void mf_set_dude_obj(OpcodeContext&); void mf_real_dude_obj(OpcodeContext&); @@ -89,8 +83,6 @@ void mf_set_unjam_locks_time(OpcodeContext&); void mf_item_make_explosive(OpcodeContext&); -void mf_get_current_inven_size(OpcodeContext&); - void mf_get_dialog_object(OpcodeContext&); void mf_obj_under_cursor(OpcodeContext&); @@ -113,5 +105,7 @@ void mf_set_unique_id(OpcodeContext&); void mf_objects_in_radius(OpcodeContext&); +void mf_npc_engine_level_up(OpcodeContext&); + } } diff --git a/sfall/Modules/Scripting/Handlers/Perks.cpp b/sfall/Modules/Scripting/Handlers/Perks.cpp index d225e807..19801607 100644 --- a/sfall/Modules/Scripting/Handlers/Perks.cpp +++ b/sfall/Modules/Scripting/Handlers/Perks.cpp @@ -272,7 +272,7 @@ end: void __declspec(naked) op_apply_heaveho_fix() { __asm { mov esi, ecx; - call ApplyHeaveHoFix; + call Perks::ApplyHeaveHoFix; mov ecx, esi; retn; } diff --git a/sfall/Modules/Scripting/Handlers/Stats.cpp b/sfall/Modules/Scripting/Handlers/Stats.cpp index c0de131e..86cf1bec 100644 --- a/sfall/Modules/Scripting/Handlers/Stats.cpp +++ b/sfall/Modules/Scripting/Handlers/Stats.cpp @@ -37,6 +37,19 @@ namespace script const char* invalidStat = "%s() - stat number out of range."; const char* objNotCritter = "%s() - the object is not a critter."; +void __declspec(naked) op_set_hp_per_level_mod() { + __asm { + mov esi, ecx; + _GET_ARG_INT(end); + push eax; // allowed -/+127 + push 0x4AFBC1; + call SafeWrite8; +end: + mov ecx, esi; + retn; + } +} + void op_set_pc_base_stat(OpcodeContext& ctx) { int stat = ctx.arg(0).rawValue(); if (stat >= 0 && stat < fo::STAT_max_stat) { @@ -146,8 +159,8 @@ void op_set_critter_skill_points(OpcodeContext& ctx) { fo::GameObject* obj = ctx.arg(0).object(); if (obj->IsCritter()) { - fo::Proto* proto = fo::GetProto(obj->protoId); - if (proto) proto->critter.skills[skill] = ctx.arg(2).rawValue(); + fo::Proto* proto; + if (fo::GetProto(obj->protoId, &proto)) proto->critter.skills[skill] = ctx.arg(2).rawValue(); } else { ctx.printOpcodeError(objNotCritter, ctx.getOpcodeName()); } @@ -162,8 +175,8 @@ void op_get_critter_skill_points(OpcodeContext& ctx) { fo::GameObject* obj = ctx.arg(0).object(); if (obj->IsCritter()) { - fo::Proto* proto = fo::GetProto(obj->protoId); - if (proto) ctx.setReturn(proto->critter.skills[skill]); + fo::Proto* proto; + if (fo::GetProto(obj->protoId, &proto)) ctx.setReturn(proto->critter.skills[skill]); } else { ctx.printOpcodeError(objNotCritter, ctx.getOpcodeName()); } @@ -209,6 +222,38 @@ end: } } +void __declspec(naked) op_set_unspent_ap_bonus() { + __asm { + _GET_ARG_INT(end); + mov Stats::standardApAcBonus, eax; +end: + retn; + } +} + +void __declspec(naked) op_get_unspent_ap_bonus() { + __asm { + mov edx, Stats::standardApAcBonus; + _J_RET_VAL_TYPE(VAR_TYPE_INT); + } +} + +void __declspec(naked) op_set_unspent_ap_perk_bonus() { + __asm { + _GET_ARG_INT(end); + mov Stats::extraApAcBonus, eax; +end: + retn; + } +} + +void __declspec(naked) op_get_unspent_ap_perk_bonus() { + __asm { + mov edx, Stats::extraApAcBonus; + _J_RET_VAL_TYPE(VAR_TYPE_INT); + } +} + void __declspec(naked) op_get_critter_current_ap() { using namespace fo; using namespace Fields; diff --git a/sfall/Modules/Scripting/Handlers/Stats.h b/sfall/Modules/Scripting/Handlers/Stats.h index 571aae22..7ab03117 100644 --- a/sfall/Modules/Scripting/Handlers/Stats.h +++ b/sfall/Modules/Scripting/Handlers/Stats.h @@ -23,6 +23,8 @@ namespace sfall namespace script { +void __declspec() op_set_hp_per_level_mod(); + // stat_funcs void op_set_pc_base_stat(OpcodeContext&); @@ -50,6 +52,14 @@ void __declspec() op_get_available_skill_points(); void __declspec() op_mod_skill_points_per_level(); +void __declspec() op_set_unspent_ap_bonus(); + +void __declspec() op_get_unspent_ap_bonus(); + +void __declspec() op_set_unspent_ap_perk_bonus(); + +void __declspec() op_get_unspent_ap_perk_bonus(); + void __declspec() op_get_critter_current_ap(); void op_set_critter_current_ap(OpcodeContext&); diff --git a/sfall/Modules/Scripting/Handlers/Utils.cpp b/sfall/Modules/Scripting/Handlers/Utils.cpp index fb4eaa67..8014a851 100644 --- a/sfall/Modules/Scripting/Handlers/Utils.cpp +++ b/sfall/Modules/Scripting/Handlers/Utils.cpp @@ -17,7 +17,6 @@ */ #include "..\..\..\FalloutEngine\Fallout2.h" -#include "..\..\..\FalloutEngine\EngineUtils.h" #include "..\..\ScriptExtender.h" #include "..\..\Message.h" #include "..\Arrays.h" @@ -350,13 +349,13 @@ void op_message_str_game(OpcodeContext& ctx) { if (fileId >= 0) { int msgId = ctx.arg(1).rawValue(); if (fileId < 20) { // main msg files - msg = fo::GetMessageStr(gameMsgFiles[fileId], msgId); + msg = fo::GetMessageStr(Message::gameMsgFiles[fileId], msgId); } else if (fileId >= 0x1000 && fileId <= 0x1005) { // proto msg files msg = fo::GetMessageStr(&fo::var::proto_msg_files[fileId - 0x1000], msgId); } else if (fileId >= 0x2000) { // Extra game message files. - ExtraGameMessageListsMap::iterator it = gExtraGameMsgLists.find(fileId); - if (it != gExtraGameMsgLists.end()) { - msg = GetMsg(it->second.get(), msgId, 2); + ExtraGameMessageListsMap::iterator it = Message::gExtraGameMsgLists.find(fileId); + if (it != Message::gExtraGameMsgLists.end()) { + msg = fo::GetMsg(it->second.get(), msgId, 2); } } } diff --git a/sfall/Modules/Scripting/Opcodes.cpp b/sfall/Modules/Scripting/Opcodes.cpp index 80c89d3d..5da383c2 100644 --- a/sfall/Modules/Scripting/Opcodes.cpp +++ b/sfall/Modules/Scripting/Opcodes.cpp @@ -22,10 +22,12 @@ #include "Handlers\Anims.h" #include "Handlers\Arrays.h" +#include "Handlers\Combat.h" #include "Handlers\Core.h" #include "Handlers\FileSystem.h" #include "Handlers\Graphics.h" #include "Handlers\Interface.h" +#include "Handlers\Inventory.h" #include "Handlers\Math.h" #include "Handlers\Memory.h" #include "Handlers\Misc.h" @@ -287,7 +289,7 @@ void InitNewOpcodes() { ForceEncounterRestore(); // restore if the encounter did not happen }; - if (int unsafe = iniGetInt("Debugging", "AllowUnsafeScripting", 0, ::sfall::ddrawIni)) { + if (int unsafe = IniReader::GetIntDefaultConfig("Debugging", "AllowUnsafeScripting", 0)) { if (unsafe == 2) checkValidMemAddr = false; dlogr(" Unsafe opcodes enabled.", DL_SCRIPT); opcodes[0x1cf] = op_write_byte; diff --git a/sfall/Modules/Scripting/ScriptValue.cpp b/sfall/Modules/Scripting/ScriptValue.cpp index 6d34ebbf..77f090af 100644 --- a/sfall/Modules/Scripting/ScriptValue.cpp +++ b/sfall/Modules/Scripting/ScriptValue.cpp @@ -117,14 +117,14 @@ float ScriptValue::asFloat() const { const char* ScriptValue::asString() const { return (_type == DataType::STR) - ? _val.str - : ""; + ? _val.str + : ""; } fo::GameObject* ScriptValue::asObject() const { return (_type == DataType::INT) - ? _val.gObj - : nullptr; + ? _val.gObj + : nullptr; } fo::GameObject* ScriptValue::object() const { diff --git a/sfall/Modules/Skills.cpp b/sfall/Modules/Skills.cpp index 4ee261a5..8563ca10 100644 --- a/sfall/Modules/Skills.cpp +++ b/sfall/Modules/Skills.cpp @@ -322,6 +322,9 @@ void Skills::init() { SafeWrite8(0x4ABC67, 0x89); // mov [esp + 0x54], eax SafeWrite32(0x4ABC6B, 0x90909090); + // Remove the unspent skill points limit + SafeWrite8(0x43C2B9, CodeType::JumpShort); // UpdateLevel_ + // Add an additional 'Energy Weapon' flag to the weapon flags (offset 0x0018) // Weapon Flags: // 0x00000400 - Energy Weapon (forces weapon to use Energy Weapons skill) @@ -330,7 +333,7 @@ void Skills::init() { LoadGameHook::OnGameReset() += Skills_OnGameLoad; char buf[512], key[16]; - auto skillsFile = GetConfigString("Misc", "SkillsFile", "", MAX_PATH); + auto skillsFile = IniReader::GetConfigString("Misc", "SkillsFile", "", MAX_PATH); if (!skillsFile.empty()) { fo::SkillInfo *skills = fo::var::skill_data; @@ -341,7 +344,7 @@ void Skills::init() { for (int i = 0; i < fo::SKILL_count; i++) { sprintf(key, "Skill%d", i); - if (iniGetString("Skills", key, "", buf, 64, file)) { + if (IniReader::GetString("Skills", key, "", buf, 64, file)) { char* tok = strtok(buf, "|"); while (tok) { if (strlen(tok) >= 2) { @@ -365,7 +368,7 @@ void Skills::init() { if (skills[i].statB >= 0) multipliers[i * 7 + skills[i].statB] = skills[i].statMulti; } sprintf(key, "SkillCost%d", i); - if (iniGetString("Skills", key, "", buf, 512, file)) { + if (IniReader::GetString("Skills", key, "", buf, 512, file)) { char* tok = strtok(buf, "|"); DWORD upto = 0; BYTE price = 1; @@ -387,15 +390,15 @@ void Skills::init() { for (int j = 201; j <= 511; j++) skillCosts[i * 512 + j] = 6; // 311 } sprintf(key, "SkillBase%d", i); - skills[i].base = iniGetInt("Skills", key, skills[i].base, file); + skills[i].base = IniReader::GetInt("Skills", key, skills[i].base, file); sprintf(key, "SkillMulti%d", i); - int multi = iniGetInt("Skills", key, skills[i].skillPointMulti, file); + int multi = IniReader::GetInt("Skills", key, skills[i].skillPointMulti, file); if (multi < 1) multi = 1; else if (multi > 10) multi = 10; skills[i].skillPointMulti = multi; sprintf(key, "SkillImage%d", i); - skills[i].image = iniGetInt("Skills", key, skills[i].image, file); + skills[i].image = IniReader::GetInt("Skills", key, skills[i].image, file); } MakeJump(0x4AA59D, skill_level_hack_bonus, 1); @@ -403,13 +406,13 @@ void Skills::init() { MakeJump(0x4AA940, skill_dec_point_hack_cost, 1); HookCalls(skill_dec_point_hook_cost, {0x4AA9E1, 0x4AA9F1}); - basedOnPoints = iniGetInt("Skills", "BasedOnPoints", 0, file); + basedOnPoints = IniReader::GetInt("Skills", "BasedOnPoints", 0, file); if (basedOnPoints) HookCall(0x4AA9EC, (void*)fo::funcoffs::skill_points_); // skill_dec_point_ - int tagBonus = iniGetInt("Skills", "TagSkillBonus", 20, file); + int tagBonus = IniReader::GetInt("Skills", "TagSkillBonus", 20, file); if (tagBonus != 20 && tagBonus >=0 && tagBonus <= 100) SafeWrite8(0x4AA61E, static_cast(tagBonus)); // skill_level_ - int tagMode = iniGetInt("Skills", "TagSkillMode", 0, file); + int tagMode = IniReader::GetInt("Skills", "TagSkillMode", 0, file); if (tagMode & 1) SafeWrite8(0x4AA612, 0xEB); // 4th tag skill can have initial skill bonus. skill_level_ (jz > jmp) if (tagMode & 2) SafeWrite16(0x4AA60E, 0x9090); // disables double skill points bonus for tag skills. skill_level_ } diff --git a/sfall/Modules/Sound.cpp b/sfall/Modules/Sound.cpp index 4b228616..2d6e4939 100644 --- a/sfall/Modules/Sound.cpp +++ b/sfall/Modules/Sound.cpp @@ -326,13 +326,13 @@ enum PlayType : signed char { slides = 4 // speech for endgame slideshow }; -static bool PrePlaySoundFile(PlayType playType, const wchar_t* file, bool isExist) { +static bool PrePlaySoundFile(PlayType playType, const wchar_t* file, bool hasFile) { if (playType == PlayType::music && backgroundMusic != nullptr) { //if (found && strcmp(path, playingMusicFile) == 0) return true; // don't stop music Sound::StopSfallSound(backgroundMusic->id); backgroundMusic = nullptr; } - if (!isExist) return false; + if (!hasFile) return false; if (playType == PlayType::music) { backgroundMusic = PlayingSound(file, SoundMode::engine_music_play); // background music loop @@ -368,7 +368,7 @@ static bool SearchAlternativeFormats(const char* path, PlayType playType, std::s wPath[len] = L'\0'; len -= 3; // the position of the first character of the file extension - bool isExist = false; + bool hasFile = false; for (int i = 0; i < 3; i++) { int j = len; wPath[j++] = SoundExtensions[i][0]; @@ -377,12 +377,12 @@ static bool SearchAlternativeFormats(const char* path, PlayType playType, std::s if (GetFileAttributesW(wPath) & FILE_ATTRIBUTE_DIRECTORY) continue; // also file not found - isExist = true; + hasFile = true; break; } - soundsFiles.emplace(std::move(pathFile), (isExist) ? wPath : L""); + soundsFiles.emplace(std::move(pathFile), (hasFile) ? wPath : L""); - return PrePlaySoundFile(playType, wPath, isExist); + return PrePlaySoundFile(playType, wPath, hasFile); } static bool __fastcall SoundFileLoad(PlayType playType, const char* path) { @@ -961,7 +961,7 @@ void Sound::init() { void* soundLoad_func; - int allowDShowSound = GetConfigInt("Sound", "AllowDShowSound", 0); + int allowDShowSound = IniReader::GetConfigInt("Sound", "AllowDShowSound", 0); if (allowDShowSound > 0) { soundLoad_func = soundLoad_hack_A; // main hook @@ -998,17 +998,17 @@ void Sound::init() { 0x4A96CC // sfxc_decode_ }); - int sBuff = GetConfigInt("Sound", "NumSoundBuffers", 0); + int sBuff = IniReader::GetConfigInt("Sound", "NumSoundBuffers", 0); if (sBuff > 4) { SafeWrite8(0x451129, (sBuff > 32) ? (BYTE)32 : (BYTE)sBuff); } - if (GetConfigInt("Sound", "AllowSoundForFloats", 0)) { + if (IniReader::GetConfigInt("Sound", "AllowSoundForFloats", 0)) { HookCall(0x42B7C7, combatai_msg_hook); // copy msg HookCall(0x42B849, ai_print_msg_hook); //Yes, I did leave this in on purpose. Will be of use to anyone trying to add in the sound effects - if (isDebug && iniGetInt("Debugging", "Test_ForceFloats", 0, ::sfall::ddrawIni)) { + if (isDebug && IniReader::GetIntDefaultConfig("Debugging", "Test_ForceFloats", 0)) { SafeWrite8(0x42B6F5, CodeType::JumpShort); // bypass chance } } diff --git a/sfall/Modules/SpeedPatch.cpp b/sfall/Modules/SpeedPatch.cpp index a82cd6a3..434c3362 100644 --- a/sfall/Modules/SpeedPatch.cpp +++ b/sfall/Modules/SpeedPatch.cpp @@ -1,20 +1,20 @@ /* -* sfall -* Copyright (C) 2008-2017 The sfall team -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -*/ + * sfall + * Copyright (C) 2008-2017 The sfall team + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #include @@ -39,15 +39,19 @@ static const DWORD offsets[] = { 0x4F4E53, 0x4F5542, 0x4F56CC, 0x4F59C6, // for mve }; -DWORD sf_GetTickCount = (DWORD)&GetTickCount; -DWORD sf_GetLocalTime; +static DWORD getLocalTimeOffs; +DWORD SpeedPatch::getTickCountOffs = (DWORD)&GetTickCount; + +DWORD SpeedPatch::getTickCount() { + return ((DWORD (__stdcall*)())getTickCountOffs)(); +} static bool enabled = true; static bool toggled = false; static bool slideShow = false; static double multi; -static DWORD storedTickCount = 0; +static DWORD sfallTickCount = 0; static DWORD lastTickCount; static double tickCountFraction = 0.0; @@ -58,16 +62,12 @@ static struct SpeedCfg { double multiplier; } *speed = nullptr; -static int modKey; +static int modKey[2]; static int toggleKey; static DWORD __stdcall FakeGetTickCount() { // Keyboard control - if (modKey && ((modKey > 0 && KeyDown(modKey)) - || (modKey == -1 && (KeyDown(DIK_LCONTROL) || KeyDown(DIK_RCONTROL))) - || (modKey == -2 && (KeyDown(DIK_LMENU) || KeyDown(DIK_RMENU))) - || (modKey == -3 && (KeyDown(DIK_LSHIFT) || KeyDown(DIK_RSHIFT))))) - { + if (modKey[0] && (KeyDown(modKey[0]) || (modKey[1] && KeyDown(modKey[1])))) { if (toggleKey && KeyDown(toggleKey)) { if (!toggled) { toggled = true; @@ -86,33 +86,30 @@ static DWORD __stdcall FakeGetTickCount() { } DWORD newTickCount = GetTickCount(); + if (newTickCount == lastTickCount) return sfallTickCount; + // Just in case someone's been running their computer for 49 days straight - if (newTickCount < lastTickCount) { - newTickCount = lastTickCount; - return storedTickCount; + if (lastTickCount > newTickCount) { + lastTickCount = newTickCount; + return sfallTickCount; } double elapsed = (double)(newTickCount - lastTickCount); lastTickCount = newTickCount; // Multiply the tick count difference by the multiplier - if (enabled && !slideShow - && !(GetLoopFlags() & (LoopFlag::INVENTORY | LoopFlag::INTFACEUSE | LoopFlag::INTFACELOOT | LoopFlag::DIALOG))) - { + if (enabled && !slideShow && !(GetLoopFlags() & (LoopFlag::INVENTORY | LoopFlag::INTFACEUSE | LoopFlag::INTFACELOOT | LoopFlag::DIALOG))) { elapsed *= multi; - tickCountFraction += modf(elapsed, &elapsed); + elapsed += tickCountFraction; + tickCountFraction = modf(elapsed, &elapsed); } - storedTickCount += (DWORD)elapsed; + sfallTickCount += (DWORD)elapsed; - if (tickCountFraction > 1.0) { - tickCountFraction -= 1.0; - storedTickCount++; - } - return storedTickCount; + return sfallTickCount; } void __stdcall FakeGetLocalTime(LPSYSTEMTIME time) { - __int64 currentTime = startTime + storedTickCount * 10000; + __int64 currentTime = startTime + sfallTickCount * 10000; FileTimeToSystemTime((FILETIME*)¤tTime, time); } @@ -146,34 +143,51 @@ void TimerInit() { char buf[2], spKey[10] = "SpeedKey#"; char spMulti[12] = "SpeedMulti#"; for (int i = 0; i < 10; i++) { - _itoa_s(i, buf, 10); + _itoa(i, buf, 10); spKey[8] = spMulti[10] = buf[0]; - speed[i].key = GetConfigInt("Input", spKey, 0); - speed[i].multiplier = GetConfigInt("Speed", spMulti, 0) / 100.0; + speed[i].key = IniReader::GetConfigInt("Input", spKey, 0); + speed[i].multiplier = IniReader::GetConfigInt("Speed", spMulti, 0) / 100.0; } } void SpeedPatch::init() { - if (GetConfigInt("Speed", "Enable", 0)) { - modKey = GetConfigInt("Input", "SpeedModKey", 0); - int init = GetConfigInt("Speed", "SpeedMultiInitial", 100); - if (init == 100 && !modKey) return; + if (IniReader::GetConfigInt("Speed", "Enable", 0)) { + modKey[0] = IniReader::GetConfigInt("Input", "SpeedModKey", 0); + int init = IniReader::GetConfigInt("Speed", "SpeedMultiInitial", 100); + if (init == 100 && !modKey[0]) return; dlog("Applying speed patch.", DL_INIT); - multi = (double)init / 100.0; - toggleKey = GetConfigInt("Input", "SpeedToggleKey", 0); + switch (modKey[0]) { + case -1: + modKey[0] = DIK_LCONTROL; + modKey[1] = DIK_RCONTROL; + break; + case -2: + modKey[0] = DIK_LMENU; + modKey[1] = DIK_RMENU; + break; + case -3: + modKey[0] = DIK_LSHIFT; + modKey[1] = DIK_RSHIFT; + break; + default: + modKey[1] = 0; + } - sf_GetTickCount = (DWORD)&FakeGetTickCount; - sf_GetLocalTime = (DWORD)&FakeGetLocalTime; + multi = (double)init / 100.0; + toggleKey = IniReader::GetConfigInt("Input", "SpeedToggleKey", 0); + + getTickCountOffs = (DWORD)&FakeGetTickCount; + getLocalTimeOffs = (DWORD)&FakeGetLocalTime; int size = sizeof(offsets) / 4; - if (GetConfigInt("Speed", "AffectPlayback", 0) == 0) size -= 4; + if (IniReader::GetConfigInt("Speed", "AffectPlayback", 0) == 0) size -= 4; for (int i = 0; i < size; i++) { - SafeWrite32(offsets[i], (DWORD)&sf_GetTickCount); + SafeWrite32(offsets[i], (DWORD)&getTickCountOffs); } - SafeWrite32(0x4FDF58, (DWORD)&sf_GetLocalTime); + SafeWrite32(0x4FDF58, (DWORD)&getLocalTimeOffs); HookCall(0x4A433E, scripts_check_state_hook); TimerInit(); diff --git a/sfall/Modules/SpeedPatch.h b/sfall/Modules/SpeedPatch.h index c1559a6d..e6c1f6db 100644 --- a/sfall/Modules/SpeedPatch.h +++ b/sfall/Modules/SpeedPatch.h @@ -1,20 +1,20 @@ /* -* sfall -* Copyright (C) 2008-2017 The sfall team -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -*/ + * sfall + * Copyright (C) 2008-2017 The sfall team + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #pragma once @@ -28,8 +28,11 @@ public: const char* name() { return "SpeedPatch"; } void init(); void exit() override; + + static DWORD getTickCountOffs; + + // sfall implementation of the GetTickCount() function + static DWORD getTickCount(); }; -extern DWORD sf_GetTickCount; - } diff --git a/sfall/Modules/Stats.cpp b/sfall/Modules/Stats.cpp index a5c4a557..395a604d 100644 --- a/sfall/Modules/Stats.cpp +++ b/sfall/Modules/Stats.cpp @@ -204,7 +204,7 @@ void Stats::UpdateHPStat(fo::GameObject* critter) { if (proto->critter.base.health != calcStatValue) { fo::func::debug_printf("\nWarning: critter PID: %d, ID: %d, has an incorrect base value of the max HP stat: %d (must be %d)", - critter->protoId, critter->id, proto->critter.base.health, calcStatValue); + critter->protoId, critter->id, proto->critter.base.health, calcStatValue); proto->critter.base.health = calcStatValue; critter->critter.health = calcStatValue + proto->critter.bonus.health; @@ -279,7 +279,7 @@ void Stats::init() { MakeCall(0x4AF54E, stat_set_base_hack_allow); MakeCall(0x455D65, op_set_critter_stat_hack); // STAT_unused for other critters - auto xpTableList = GetConfigList("Misc", "XPTable", "", 2048); + auto xpTableList = IniReader::GetConfigList("Misc", "XPTable", "", 2048); size_t numLevels = xpTableList.size(); if (numLevels > 0) { HookCall(0x434AA7, GetNextLevelXPHook); @@ -290,17 +290,17 @@ void Stats::init() { for (size_t i = 0; i < 99; i++) { xpTable[i] = (i < numLevels) - ? atoi(xpTableList[i].c_str()) - : -1; + ? atoi(xpTableList[i].c_str()) + : -1; } SafeWrite8(0x4AFB1B, static_cast(numLevels + 1)); } - auto statsFile = GetConfigString("Misc", "DerivedStats", "", MAX_PATH); + auto statsFile = IniReader::GetConfigString("Misc", "DerivedStats", "", MAX_PATH); if (!statsFile.empty()) { const char* statFile = statsFile.insert(0, ".\\").c_str(); if (GetFileAttributes(statFile) != INVALID_FILE_ATTRIBUTES) { // check if file exists - derivedHPwBonus = (iniGetInt("Main", "HPDependOnBonusStats", 0, statFile) != 0); + derivedHPwBonus = (IniReader::GetInt("Main", "HPDependOnBonusStats", 0, statFile) != 0); engineDerivedStats = false; // STAT_st + STAT_en * 2 + 15 @@ -337,14 +337,14 @@ void Stats::init() { if (i >= fo::Stat::STAT_dmg_thresh && i <= fo::Stat::STAT_dmg_resist_explosion) continue; _itoa(i, key, 10); - statFormulas[i].base = iniGetInt(key, "base", statFormulas[i].base, statFile); - statFormulas[i].min = iniGetInt(key, "min", statFormulas[i].min, statFile); + statFormulas[i].base = IniReader::GetInt(key, "base", statFormulas[i].base, statFile); + statFormulas[i].min = IniReader::GetInt(key, "min", statFormulas[i].min, statFile); for (int j = 0; j < fo::Stat::STAT_max_hit_points; j++) { sprintf(buf2, "shift%d", j); - statFormulas[i].shift[j] = iniGetInt(key, buf2, statFormulas[i].shift[j], statFile); + statFormulas[i].shift[j] = IniReader::GetInt(key, buf2, statFormulas[i].shift[j], statFile); sprintf(buf2, "multi%d", j); _gcvt(statFormulas[i].multi[j], 16, buf3); - iniGetString(key, buf2, buf3, buf2, 256, statFile); + IniReader::GetString(key, buf2, buf3, buf2, 256, statFile); statFormulas[i].multi[j] = atof(buf2); } } diff --git a/sfall/Modules/SubModules/CombatBlock.cpp b/sfall/Modules/SubModules/CombatBlock.cpp index f53a2f5c..bc69bb28 100644 --- a/sfall/Modules/SubModules/CombatBlock.cpp +++ b/sfall/Modules/SubModules/CombatBlock.cpp @@ -18,6 +18,7 @@ #include "..\..\main.h" #include "..\..\FalloutEngine\Fallout2.h" +#include "..\..\Translate.h" #include "CombatBlock.h" @@ -25,10 +26,9 @@ namespace sfall { static bool combatDisabled; -static std::string combatBlockedMessage; static void __stdcall CombatBlocked() { - fo::func::display_print(combatBlockedMessage.c_str()); + fo::func::display_print(Translate::CombatBlockMessage().c_str()); } static void __declspec(naked) intface_use_item_hook() { @@ -67,8 +67,6 @@ void __stdcall CombatBlock::SetBlockCombat(long toggle) { void CombatBlock::init() { HookCall(0x45F626, intface_use_item_hook); // jnz hook HookCall(0x4432A6, game_handle_input_hook); - - combatBlockedMessage = Translate("sfall", "BlockedCombat", "You cannot enter combat at this time."); } } diff --git a/sfall/Modules/SubModules/EnginePerks.cpp b/sfall/Modules/SubModules/EnginePerks.cpp index 0274b4c1..fbf940e5 100644 --- a/sfall/Modules/SubModules/EnginePerks.cpp +++ b/sfall/Modules/SubModules/EnginePerks.cpp @@ -162,41 +162,41 @@ void EnginePerkBonusInit() { } void ReadPerksBonuses(const char* perksFile) { - int wScopeRangeMod = iniGetInt("PerksTweak", "WeaponScopeRangePenalty", 8, perksFile); + int wScopeRangeMod = IniReader::GetInt("PerksTweak", "WeaponScopeRangePenalty", 8, perksFile); if (wScopeRangeMod != 8) perks.setWeaponScopeRangePenalty(wScopeRangeMod); - wScopeRangeMod = iniGetInt("PerksTweak", "WeaponScopeRangeBonus", 5, perksFile); + wScopeRangeMod = IniReader::GetInt("PerksTweak", "WeaponScopeRangeBonus", 5, perksFile); if (wScopeRangeMod != 5) perks.setWeaponScopeRangeBonus(wScopeRangeMod); - int wLongRangeBonus = iniGetInt("PerksTweak", "WeaponLongRangeBonus", 4, perksFile); + int wLongRangeBonus = IniReader::GetInt("PerksTweak", "WeaponLongRangeBonus", 4, perksFile); if (wLongRangeBonus != 4) perks.setWeaponLongRangeBonus(wLongRangeBonus); - int wAccurateBonus = iniGetInt("PerksTweak", "WeaponAccurateBonus", 20, perksFile); + int wAccurateBonus = IniReader::GetInt("PerksTweak", "WeaponAccurateBonus", 20, perksFile); if (wAccurateBonus != 20) perks.setWeaponAccurateBonus(wAccurateBonus); - int wHandlingBonus = iniGetInt("PerksTweak", "WeaponHandlingBonus", 3, perksFile); + int wHandlingBonus = IniReader::GetInt("PerksTweak", "WeaponHandlingBonus", 3, perksFile); if (wHandlingBonus != 3) perks.setWeaponHandlingBonus(wHandlingBonus); - int masterTraderBonus = iniGetInt("PerksTweak", "MasterTraderBonus", 25, perksFile); + int masterTraderBonus = IniReader::GetInt("PerksTweak", "MasterTraderBonus", 25, perksFile); if (masterTraderBonus != 25) perks.setMasterTraderBonus(masterTraderBonus); - int salesmanBonus = iniGetInt("PerksTweak", "SalesmanBonus", 20, perksFile); + int salesmanBonus = IniReader::GetInt("PerksTweak", "SalesmanBonus", 20, perksFile); if (salesmanBonus != 20) perks.setSalesmanBonus(salesmanBonus); - int livingAnatomyBonus = iniGetInt("PerksTweak", "LivingAnatomyBonus", 5, perksFile); + int livingAnatomyBonus = IniReader::GetInt("PerksTweak", "LivingAnatomyBonus", 5, perksFile); if (livingAnatomyBonus != 5) perks.setLivingAnatomyBonus(livingAnatomyBonus); - int pyromaniacBonus = iniGetInt("PerksTweak", "PyromaniacBonus", 5, perksFile); + int pyromaniacBonus = IniReader::GetInt("PerksTweak", "PyromaniacBonus", 5, perksFile); if (pyromaniacBonus != 5) perks.setPyromaniacBonus(pyromaniacBonus); - int stonewallPercent = iniGetInt("PerksTweak", "StonewallPercent", 50, perksFile); + int stonewallPercent = IniReader::GetInt("PerksTweak", "StonewallPercent", 50, perksFile); if (stonewallPercent != 50) perks.setStonewallPercent(stonewallPercent); - int demolitionExpertBonus = iniGetInt("PerksTweak", "DemolitionExpertBonus", 10, perksFile); + int demolitionExpertBonus = IniReader::GetInt("PerksTweak", "DemolitionExpertBonus", 10, perksFile); if (demolitionExpertBonus != 10) perks.setDemolitionExpertBonus(demolitionExpertBonus); - int vaultCityInoculationsBonus = iniGetInt("PerksTweak", "VaultCityInoculationsPoisonBonus", 10, perksFile); + int vaultCityInoculationsBonus = IniReader::GetInt("PerksTweak", "VaultCityInoculationsPoisonBonus", 10, perksFile); if (vaultCityInoculationsBonus != 10) perks.setVaultCityInoculationsPoisonBonus(vaultCityInoculationsBonus); - vaultCityInoculationsBonus = iniGetInt("PerksTweak", "VaultCityInoculationsRadBonus", 10, perksFile); + vaultCityInoculationsBonus = IniReader::GetInt("PerksTweak", "VaultCityInoculationsRadBonus", 10, perksFile); if (vaultCityInoculationsBonus != 10) perks.setVaultCityInoculationsRadBonus(vaultCityInoculationsBonus); } diff --git a/sfall/Modules/SubModules/WindowRender.cpp b/sfall/Modules/SubModules/WindowRender.cpp index a9ba8817..c2f416bd 100644 --- a/sfall/Modules/SubModules/WindowRender.cpp +++ b/sfall/Modules/SubModules/WindowRender.cpp @@ -153,7 +153,7 @@ static __declspec(naked) void palette_fade_to_hook() { } void WindowRender::init() { - fadeMulti = GetConfigInt("Graphics", "FadeMultiplier", 100); + fadeMulti = IniReader::GetConfigInt("Graphics", "FadeMultiplier", 100); if (fadeMulti != 100) { dlog("Applying fade patch.", DL_INIT); HookCall(0x493B16, palette_fade_to_hook); diff --git a/sfall/Modules/TalkingHeads.cpp b/sfall/Modules/TalkingHeads.cpp index 41dbe032..adcf8acb 100644 --- a/sfall/Modules/TalkingHeads.cpp +++ b/sfall/Modules/TalkingHeads.cpp @@ -88,8 +88,8 @@ static long reactionID; static bool GetHeadFrmName(char* name) { int headFid = (*(DWORD*)FO_VAR_lips_draw_head) - ? fo::var::lipsFID - : fo::var::fidgetFID; + ? fo::var::lipsFID + : fo::var::fidgetFID; int index = headFid & 0xFFF; if (index >= fo::var::art[fo::OBJ_TYPE_HEAD].total) return true; int ID2 = (*(DWORD*)FO_VAR_fidgetFp) ? (headFid & 0xFF0000) >> 16 : reactionID; @@ -149,7 +149,7 @@ static bool LoadFrm(Frm* frm) { } frm->textures = textures; texMap.emplace(std::piecewise_construct, std::forward_as_tuple(frm->key), - std::forward_as_tuple(textures, frm->showHighlights, frm->bakedBackground, frm->frames)); + std::forward_as_tuple(textures, frm->showHighlights, frm->bakedBackground, frm->frames)); *(DWORD*)FO_VAR_bk_disabled = 0; } else { // Use preloaded textures @@ -291,7 +291,7 @@ void TalkingHeads::init() { // Disable centering the screen if NPC has talking head HookCall(0x445224, gdialogInitFromScript_hook); - if (Graphics::mode && GetConfigInt("Graphics", "Use32BitHeadGraphics", 0)) { + if (Graphics::mode && IniReader::GetConfigInt("Graphics", "Use32BitHeadGraphics", 0)) { LoadGameHook::OnAfterGameInit() += TalkingHeadsInit; } } diff --git a/sfall/Modules/Tiles.cpp b/sfall/Modules/Tiles.cpp index 0064972a..e50d6474 100644 --- a/sfall/Modules/Tiles.cpp +++ b/sfall/Modules/Tiles.cpp @@ -21,16 +21,15 @@ #include "..\main.h" #include "..\FalloutEngine\Fallout2.h" -#include "FileSystem.h" +#include "..\Utils.h" +//#include "FileSystem.h" #include "Tiles.h" namespace sfall { -using namespace fo; typedef int (__stdcall *functype)(); -static const functype art_init = (functype)fo::funcoffs::art_init_; static const DWORD Tiles_0E[] = { 0x484255, 0x48429D, 0x484377, 0x484385, 0x48A897, 0x48A89A, 0x4B2231, @@ -60,112 +59,143 @@ struct TilesData { #pragma pack(pop) struct OverrideEntry { - DWORD xtiles; - DWORD ytiles; - DWORD replacementid; + DWORD xTiles; + DWORD yTiles; + DWORD replacementID; - OverrideEntry(DWORD _xtiles, DWORD _ytiles, DWORD _repid) - : xtiles(_xtiles), ytiles(_ytiles), replacementid(_repid) { + OverrideEntry(DWORD xtiles, DWORD ytiles, DWORD repid) + : xTiles(xtiles), yTiles(ytiles), replacementID(repid) { } }; -static OverrideEntry** overrides; +static OverrideEntry** overrides = nullptr; static DWORD origTileCount = 0; static DWORD tileMode; static BYTE* mask; -static void CreateMask() { +static bool LoadMask() { + fo::DbFile* file = fo::func::db_fopen("art\\tiles\\gridmask.frm", "rb"); // same as grid000.frm from HRP + if (!file) { + dlogr("AllowLargeTiles: Unable to open art\\tiles\\gridmask.frm file.", DL_INIT); + return false; + } mask = new BYTE[80 * 36]; - fo::DbFile* file = fo::func::db_fopen("art\\tiles\\grid000.frm", "r"); - fo::func::db_fseek(file, 0x4A, 0); + + fo::func::db_fseek(file, 0x4A, SEEK_SET); fo::func::db_freadByteCount(file, mask, 80 * 36); fo::func::db_fclose(file); + return true; } -static WORD ByteSwapW(WORD w) { - return ((w & 0xFF) << 8) | ((w & 0xFF00) >> 8); -} +static int ProcessTile(fo::Art* tiles, int tile, int listPos) { + char buf[32] = "art\\tiles\\"; + const char* name = &tiles->names[13 * tile]; + for (size_t i = 10; ; i++) { + if (i == 32) return 0; // name too long + char c = *name++; + buf[i] = c; + if (c == '\0') break; + } -static DWORD ByteSwapD(DWORD w) { - return ((w & 0xFF) << 24) | ((w & 0xFF00) << 8) | ((w & 0xFF0000) >> 8) | ((w & 0xFF000000) >> 24); -} + fo::DbFile* artFile = fo::func::db_fopen(buf, "rb"); + if (!artFile) return 0; -static int ProcessTile(fo::Art* tiles, int tile, int listpos) { - char buf[32]; - //sprintf_s(buf, "art\\tiles\\%s", &tiles->names[13*tile]); - strcpy_s(buf, "art\\tiles\\"); - strcat_s(buf, &tiles->names[13 * tile]); + fo::func::db_fseek(artFile, 0x3E, SEEK_SET); // frameData - fo::DbFile* art = fo::func::db_fopen(buf, "r"); - if (!art) return 0; - fo::func::db_fseek(art, 0x3E, 0); WORD width; - fo::func::db_freadShort(art, &width); //80; - if (width == 80) { - fo::func::db_fclose(art); + fo::func::db_freadShort(artFile, &width); + if (width <= 80) goto exit; + + WORD height; + fo::func::db_freadShort(artFile, &height); + if (height < 36) goto exit; + + float newWidth = (float)(width - (width % 8)); + float newHeight = (float)(height - (height % 12)); + + // Number of tiles horizontally and vertically + // the calculation is unstable if the large tile is not proportional to the size of 80x36 (aspect ratio) + int xSize = std::lroundf(((newWidth / 32.0f) - (newHeight / 24.0f)) - 0.01f); + int ySize = std::lroundf(((newHeight / 16.0f) - (newWidth / 64.0f)) - 0.01f); + if (xSize <= 0 || ySize <= 0) goto exit; + + // Check if total dimension of split tiles exceeds the original + if (xSize > 1 && (xSize * 80) > width) xSize -= 1; + if (ySize > 1 && (ySize * 36) > height) ySize -= 1; + + long bytes = width * height; + BYTE* pixelData = new BYTE[bytes]; + + // Read pixels data + if (fo::func::db_fseek(artFile, 0x4A, SEEK_SET) || + fo::func::db_fread(pixelData, 1, bytes, artFile) != bytes) + { + delete[] pixelData; +exit: + fo::func::db_fclose(artFile); return 0; } - WORD height; - fo::func::db_freadShort(art, &height); //36 - fo::func::db_fseek(art, 0x4A, 0); - BYTE* pixeldata = new BYTE[width * height]; - fo::func::db_freadByteCount(art, pixeldata, width * height); - DWORD listid = listpos - tiles->total; - float newwidth = (float)(width - width % 8); - float newheight = (float)(height - height % 12); - int xsize = (int)floor(newwidth / 32.0f - newheight / 24.0f); - int ysize = (int)floor(newheight / 16.0f - newwidth / 64.0f); - for (int y = 0; y < ysize; y++) { - for (int x = 0; x < xsize; x++) { - fo::FrmFile frame; - fo::func::db_fseek(art, 0, 0); - fo::func::db_freadByteCount(art, (BYTE*)&frame, 0x4a); - frame.height = ByteSwapW(36); - frame.width = ByteSwapW(80); - frame.frameSize = ByteSwapD(80 * 36); - frame.frameAreaSize = ByteSwapD(80 * 36 + 12); - int xoffset = x * 48 + (ysize - (y + 1)) * 32; - int yoffset = height - (36 + x * 12 + y * 24); - for (int y2 = 0; y2 < 36; y2++) { - for (int x2 = 0; x2 < 80; x2++) { - if (mask[y2 * 80 + x2]) { - frame.pixels[y2 * 80 + x2] = pixeldata[(yoffset + y2) * width + xoffset + x2]; + long listID = listPos - tiles->total; + + fo::FrmFile frame; + fo::func::db_fseek(artFile, 0, SEEK_SET); + fo::func::db_freadByteCount(artFile, (BYTE*)&frame, 74); + + frame.height = ByteSwapW(36); + frame.width = ByteSwapW(80); + frame.frameSize = ByteSwapD(80 * 36); + frame.frameAreaSize = ByteSwapD(80 * 36 + 12); + + for (int y = 0; y < ySize; y++) { + for (int x = 0; x < xSize; x++) { + // offset relative to the top-left corner + int xOffset = x * 48 + (ySize - (y + 1)) * 32; + int yOffset = height - (36 + x * 12 + y * 24); + + for (int pY = 0; pY < 36; pY++) { + for (int pX = 0; pX < 80; pX++) { + int point = (80 * pY) + pX; + if (mask[point]) { + frame.pixels[point] = pixelData[(width * (yOffset + pY)) + xOffset + pX]; } else { - frame.pixels[y2 * 80 + x2] = 0; + frame.pixels[point] = 0; } } } - - sprintf_s(buf, 32, "art\\tiles\\zzz%04d.frm", listid++); + sprintf(&buf[10], "zzz%04d.frm", listID++); //FScreateFromData(buf, &frame, sizeof(frame)); - fo::DbFile* file = fo::func::db_fopen(buf, "w"); + fo::DbFile* file = fo::func::db_fopen(buf, "wb"); fo::func::db_fwriteByteCount(file, (BYTE*)&frame, sizeof(frame)); fo::func::db_fclose(file); } } - overrides[tile] = new OverrideEntry(xsize, ysize, listpos); - fo::func::db_fclose(art); - delete[] pixeldata; - return xsize * ysize; + overrides[tile] = new OverrideEntry(xSize, ySize, listPos); + + fo::func::db_fclose(artFile); + delete[] pixelData; + + return xSize * ySize; // number of tiles added } +static const functype art_init = (functype)fo::funcoffs::art_init_; + static int __stdcall ArtInitHook() { if (art_init()) return -1; - - CreateMask(); + if (!LoadMask()) return 0; fo::Art* tiles = &fo::var::art[4]; - char buf[32]; - DWORD listpos = tiles->total; - origTileCount = listpos; - overrides = new OverrideEntry*[listpos]; - ZeroMemory(overrides, 4 * (listpos - 1)); + + long listpos = origTileCount = tiles->total; + overrides = new OverrideEntry*[listpos](); if (tileMode == 2) { fo::DbFile* file = fo::func::db_fopen("art\\tiles\\xltiles.lst", "rt"); if (!file) return 0; + + char buf[32]; DWORD id; char* comment; + while (fo::func::db_fgets(buf, 31, file) > 0) { if (comment = strchr(buf, ';')) *comment = 0; id = atoi(buf); @@ -177,8 +207,8 @@ static int __stdcall ArtInitHook() { } if (listpos != tiles->total) { tiles->names = (char*)fo::func::mem_realloc(tiles->names, listpos * 13); - for (DWORD i = tiles->total; i < listpos; i++) { - sprintf_s(&tiles->names[i * 13], 12, "zzz%04d.frm", i - tiles->total); + for (long i = tiles->total; i < listpos; i++) { + sprintf(&tiles->names[i * 13], "zzz%04d.frm", i - tiles->total); } tiles->total = listpos; } @@ -199,14 +229,15 @@ static void __declspec(naked) iso_init_hook() { } static long __fastcall SquareLoadCheck(TilesData* data) { + if (!overrides) return 0; for (DWORD y = 0; y < 100; y++) { for (DWORD x = 0; x < 100; x++) { for (DWORD z = 0; z < 2; z++) { DWORD tile = data[y * 100 + x].tile[z]; if (tile > 1 && tile < origTileCount && overrides[tile]) { - DWORD newtile = overrides[tile]->replacementid - 1; - for (DWORD y2 = 0; y2 < overrides[tile]->ytiles; y2++) { - for (DWORD x2 = 0; x2 < overrides[tile]->xtiles; x2++) { + DWORD newtile = overrides[tile]->replacementID - 1; + for (DWORD y2 = 0; y2 < overrides[tile]->yTiles; y2++) { + for (DWORD x2 = 0; x2 < overrides[tile]->xTiles; x2++) { newtile++; if (x - x2 < 0 || y - y2 < 0) continue; data[(y - y2) * 100 + x - x2].tile[z] = (short)newtile; @@ -232,6 +263,7 @@ end: } static void __declspec(naked) art_id_hack() { + using namespace fo; __asm { cmp esi, (OBJ_TYPE_TILE << 24); // 0x4000000 jne end; @@ -244,6 +276,7 @@ end: } static void __declspec(naked) art_get_name_hack() { + using namespace fo; __asm { sar eax, 24; cmp eax, OBJ_TYPE_TILE; @@ -260,14 +293,14 @@ end: } void Tiles::init() { - if (tileMode = GetConfigInt("Misc", "AllowLargeTiles", 0)) { + if (tileMode = IniReader::GetConfigInt("Misc", "AllowLargeTiles", 0)) { dlog("Applying allow large tiles patch.", DL_INIT); HookCall(0x481D72, iso_init_hook); HookCall(0x48434C, square_load_hook); dlogr(" Done", DL_INIT); } - if (GetConfigInt("Misc", "MoreTiles", 0)) { + if (IniReader::GetConfigInt("Misc", "MoreTiles", 0)) { dlog("Applying tile FRM limit patch.", DL_INIT); MakeCall(0x419D46, art_id_hack); MakeCall(0x419479, art_get_name_hack); @@ -283,4 +316,11 @@ void Tiles::init() { } } +void Tiles::exit() { + if (overrides) { + for (size_t i = 0; i < origTileCount; i++) delete overrides[i]; // free OverrideEntry + delete[] overrides; + } +} + } diff --git a/sfall/Modules/Tiles.h b/sfall/Modules/Tiles.h index 3f2c5216..d4fc038f 100644 --- a/sfall/Modules/Tiles.h +++ b/sfall/Modules/Tiles.h @@ -27,6 +27,7 @@ class Tiles : public Module { public: const char* name() { return "Tiles"; } void init(); + void exit() override; }; } diff --git a/sfall/Modules/Worldmap.cpp b/sfall/Modules/Worldmap.cpp index 12a234e5..a0fba288 100644 --- a/sfall/Modules/Worldmap.cpp +++ b/sfall/Modules/Worldmap.cpp @@ -16,6 +16,7 @@ * along with this program. If not, see . */ +#include #include #include @@ -52,6 +53,7 @@ static bool restMap; static bool restMode; static bool restTime; +static bool worldMapLongDelay = false; static DWORD worldMapDelay; static DWORD worldMapTicks; @@ -130,52 +132,39 @@ end: } } -static void __declspec(naked) WorldMapFpsPatch() { +static void WorldMapFPS() { + DWORD prevTicks = worldMapTicks; // previous ticks + do { + WorldmapLoopHook(); + if (worldMapLongDelay) { + __asm call fo::funcoffs::process_bk_; + } + + DWORD tick; // current ticks + do { + tick = SpeedPatch::getTickCount(); + } while (tick == prevTicks); // delay ~15 ms + prevTicks = tick; + + // get elapsed time + } while ((prevTicks - worldMapTicks) < worldMapDelay); + worldMapTicks = prevTicks; +} + +static void __declspec(naked) wmWorldMap_hook_patch1() { __asm { push dword ptr ds:[FO_VAR_last_buttons]; - push dword ptr ds:[0x6AC7B0]; // _mouse_buttons - mov esi, worldMapTicks; - mov ebx, esi; // previous ticks -loopDelay: - call WorldmapLoopHook; - call fo::funcoffs::process_bk_; -subLoop: - call ds:[sf_GetTickCount]; // current ticks - mov edx, eax; - sub eax, ebx; // get elapsed time (cur.ticks - prev.ticks) - cmp eax, 10; // delay - GetTickCount returns minimum difference of 15 units - jb subLoop; // elapsed < invoke delay - mov ebx, edx; - sub edx, esi; // get elapsed time (cur.ticks - worldMapTicks) - cmp edx, worldMapDelay; - jb loopDelay; // elapsed < worldMapDelay - - pop dword ptr ds:[0x6AC7B0]; // _mouse_buttons + push dword ptr ds:[FO_VAR_mouse_buttons]; + call WorldMapFPS; + pop dword ptr ds:[FO_VAR_mouse_buttons]; pop dword ptr ds:[FO_VAR_last_buttons]; - call ds:[sf_GetTickCount]; - mov worldMapTicks, eax; jmp fo::funcoffs::get_input_; } } -static void __declspec(naked) WorldMapFpsPatch2() { +static void __declspec(naked) wmWorldMap_hook_patch2() { __asm { - mov esi, worldMapTicks; - mov ebx, esi; -loopDelay: - call WorldmapLoopHook; -subLoop: - call ds:[sf_GetTickCount]; // current ticks - mov edx, eax; - sub eax, ebx; // get elapsed time - jz subLoop; - mov ebx, edx; - sub edx, esi; // get elapsed time - cmp edx, worldMapDelay; - jb loopDelay; // elapsed < worldMapDelay - - call ds:[sf_GetTickCount]; - mov worldMapTicks, eax; + call WorldMapFPS; jmp fo::funcoffs::get_input_; } } @@ -183,9 +172,12 @@ subLoop: // Only used if the world map speed patch is disabled, so that world map scripts are still run static void __declspec(naked) wmWorldMap_hook() { __asm { - //pushadc; - call WorldmapLoopHook; - //popadc; + call ds:[SpeedPatch::getTickCountOffs]; // current ticks + cmp eax, worldMapTicks; + je skipHook; + mov worldMapTicks, eax; + call WorldmapLoopHook; // hook is called every ~15 ms (GetTickCount returns a difference of 14-16 ms) +skipHook: jmp fo::funcoffs::get_input_; } } @@ -198,7 +190,7 @@ static void __declspec(naked) wmWorldMapFunc_hook() { } static void __declspec(naked) wmRndEncounterOccurred_hack() { - __asm { + __asm { // edx - _wmLastRndTime xor ecx, ecx; cmp edx, WorldMapEncounterRate; retn; @@ -268,6 +260,7 @@ skip: } static const char* automap = "automap"; // no/yes overrides the value in the table to display the automap in pipboy + static void __declspec(naked) wmMapInit_hack() { __asm { mov esi, [esp + 0xA0 - 0x20 + 4]; // curent map number @@ -336,6 +329,30 @@ skip: } } +static bool customPosition = false; + +static void __declspec(naked) main_load_new_hook() { + __asm { + call fo::funcoffs::map_load_; + push -1; + mov edx, esp; + mov eax, dword ptr ds:[FO_VAR_map_number]; + call fo::funcoffs::wmMatchAreaContainingMapIdx_; + pop eax; // area ID + cmp customPosition, 0; + jnz skip; + jmp fo::funcoffs::wmTeleportToArea_; +skip: + test eax, eax; + js end; + cmp eax, dword ptr ds:[FO_VAR_wmMaxAreaNum]; + jge end; + mov dword ptr ds:[FO_VAR_WorldMapCurrArea], eax; +end: + retn; + } +} + static void RestRestore() { if (!restMode) return; restMode = false; @@ -349,20 +366,20 @@ static void RestRestore() { } static void WorldLimitsPatches() { - DWORD data = GetConfigInt("Misc", "LocalMapXLimit", 0); + DWORD data = IniReader::GetConfigInt("Misc", "LocalMapXLimit", 0); if (data) { dlog("Applying local map x limit patch.", DL_INIT); SafeWrite32(0x4B13B9, data); dlogr(" Done", DL_INIT); } - data = GetConfigInt("Misc", "LocalMapYLimit", 0); + data = IniReader::GetConfigInt("Misc", "LocalMapYLimit", 0); if (data) { dlog("Applying local map y limit patch.", DL_INIT); SafeWrite32(0x4B13C7, data); dlogr(" Done", DL_INIT); } - //if (GetConfigInt("Misc", "CitiesLimitFix", 0)) { + //if (IniReader::GetConfigInt("Misc", "CitiesLimitFix", 0)) { dlog("Applying cities limit patch.", DL_INIT); if (*((BYTE*)0x4BF3BB) != CodeType::JumpShort) { SafeWrite8(0x4BF3BB, CodeType::JumpShort); @@ -372,7 +389,7 @@ static void WorldLimitsPatches() { } static void TimeLimitPatch() { - int limit = GetConfigInt("Misc", "TimeLimit", 13); + int limit = IniReader::GetConfigInt("Misc", "TimeLimit", 13); if (limit == -2 || limit == -3) { addYear = true; MakeCall(0x4A33B8, TimeDateFix, 1); // game_time_date_ @@ -399,32 +416,33 @@ static void TimeLimitPatch() { static void WorldmapFpsPatch() { bool fpsPatchOK = (*(DWORD*)0x4BFE5E == 0x8D16); - if (GetConfigInt("Misc", "WorldMapFPSPatch", 0)) { + if (IniReader::GetConfigInt("Misc", "WorldMapFPSPatch", 0)) { dlog("Applying world map fps patch.", DL_INIT); - if (!fpsPatchOK) { - dlogr(" Failed", DL_INIT); - } else { - int delay = GetConfigInt("Misc", "WorldMapDelay2", 66); + if (fpsPatchOK) { + int delay = IniReader::GetConfigInt("Misc", "WorldMapDelay2", 66); worldMapDelay = max(1, delay); dlogr(" Done", DL_INIT); + } else { + dlogr(" Failed", DL_INIT); } } if (fpsPatchOK) { void* func; if (worldMapDelay == 0) { - func = wmWorldMap_hook; + func = wmWorldMap_hook; // only WorldmapLoop hook } else if (worldMapDelay > 25) { - func = WorldMapFpsPatch; + worldMapLongDelay = true; + func = wmWorldMap_hook_patch1; } else { - func = WorldMapFpsPatch2; + func = wmWorldMap_hook_patch2; } - HookCall(0x4BFE5D, func); + HookCall(0x4BFE5D, func); // wmWorldMap_ ::sfall::availableGlobalScriptTypes |= 2; } - if (GetConfigInt("Misc", "WorldMapEncounterFix", 0)) { + if (IniReader::GetConfigInt("Misc", "WorldMapEncounterFix", 0)) { dlog("Applying world map encounter patch.", DL_INIT); - WorldMapEncounterRate = GetConfigInt("Misc", "WorldMapEncounterRate", 5); + WorldMapEncounterRate = IniReader::GetConfigInt("Misc", "WorldMapEncounterRate", 5); SafeWrite32(0x4C232D, 0xB8); // mov eax, 0; (wmInterfaceInit_) HookCall(0x4BFEE0, wmWorldMapFunc_hook); MakeCall(0x4C0667, wmRndEncounterOccurred_hack); @@ -433,30 +451,30 @@ static void WorldmapFpsPatch() { } static void PathfinderFixInit() { - //if (GetConfigInt("Misc", "PathfinderFix", 0)) { + //if (IniReader::GetConfigInt("Misc", "PathfinderFix", 0)) { dlog("Applying Pathfinder patch.", DL_INIT); SafeWrite16(0x4C1FF6, 0x9090); // wmPartyWalkingStep_ HookCall(0x4C1C78, PathfinderFix); // wmGameTimeIncrement_ - mapMultiMod = (double)GetConfigInt("Misc", "WorldMapTimeMod", 100) / 100.0; + mapMultiMod = (double)IniReader::GetConfigInt("Misc", "WorldMapTimeMod", 100) / 100.0; dlogr(" Done", DL_INIT); //} } static void StartingStatePatches() { - int date = GetConfigInt("Misc", "StartYear", -1); + int date = IniReader::GetConfigInt("Misc", "StartYear", -1); if (date >= 0) { dlog("Applying starting year patch.", DL_INIT); SafeWrite32(0x4A336C, date); dlogr(" Done", DL_INIT); } - int month = GetConfigInt("Misc", "StartMonth", -1); + int month = IniReader::GetConfigInt("Misc", "StartMonth", -1); if (month >= 0) { if (month > 11) month = 11; dlog("Applying starting month patch.", DL_INIT); SafeWrite32(0x4A3382, month); dlogr(" Done", DL_INIT); } - date = GetConfigInt("Misc", "StartDay", -1); + date = IniReader::GetConfigInt("Misc", "StartDay", -1); if (date >= 0) { if (month == 1 && date > 28) { // for February date = 28; // set 29th day @@ -468,34 +486,46 @@ static void StartingStatePatches() { dlogr(" Done", DL_INIT); } - date = GetConfigInt("Misc", "StartXPos", -1); - if (date != -1) { + long xPos = IniReader::GetConfigInt("Misc", "StartXPos", -1); + if (xPos != -1) { + if (xPos < 0) xPos = 0; dlog("Applying starting x position patch.", DL_INIT); - SafeWrite32(0x4BC990, date); - SafeWrite32(0x4BCC08, date); + SafeWrite32(0x4BC990, xPos); + SafeWrite32(0x4BCC08, xPos); dlogr(" Done", DL_INIT); + customPosition = true; } - date = GetConfigInt("Misc", "StartYPos", -1); - if (date != -1) { + long yPos = IniReader::GetConfigInt("Misc", "StartYPos", -1); + if (yPos != -1) { + if (yPos < 0) yPos = 0; dlog("Applying starting y position patch.", DL_INIT); - SafeWrite32(0x4BC995, date); - SafeWrite32(0x4BCC0D, date); + SafeWrite32(0x4BC995, yPos); + SafeWrite32(0x4BCC0D, yPos); dlogr(" Done", DL_INIT); + customPosition = true; } - ViewportX = GetConfigInt("Misc", "ViewXPos", -1); - if (ViewportX != -1) { + // Fix the starting position of the player's marker on the world map when starting a new game + // also initialize the value of the current area for METARULE_CURRENT_TOWN metarule function + HookCall(0x480DC0, main_load_new_hook); + + xPos = IniReader::GetConfigInt("Misc", "ViewXPos", -1); + if (xPos != -1) { + if (xPos < 0) xPos = 0; + ViewportX = xPos; dlog("Applying starting x view patch.", DL_INIT); SafeWrite32(FO_VAR_wmWorldOffsetX, ViewportX); dlogr(" Done", DL_INIT); } - ViewportY = GetConfigInt("Misc", "ViewYPos", -1); - if (ViewportY != -1) { + yPos = IniReader::GetConfigInt("Misc", "ViewYPos", -1); + if (yPos != -1) { + if (yPos < 0) yPos = 0; + ViewportY = yPos; dlog("Applying starting y view patch.", DL_INIT); SafeWrite32(FO_VAR_wmWorldOffsetY, ViewportY); dlogr(" Done", DL_INIT); } - if (ViewportX != -1 || ViewportY != -1) HookCall(0x4BCF07, ViewportHook); // game_reset_ + if (xPos != -1 || yPos != -1) HookCall(0x4BCF07, ViewportHook); // game_reset_ } static void PipBoyAutomapsPatch() { @@ -622,8 +652,7 @@ static const char* GetOverrideTerrainName(long x, long y) { long subTileID = x + y * (fo::var::wmNumHorizontalTiles * 7); auto it = std::find_if(wmTerrainTypeNames.crbegin(), wmTerrainTypeNames.crend(), - [=](const std::pair &el) - { return el.first == subTileID; } + [=](const std::pair &el) { return el.first == subTileID; } ); return (it != wmTerrainTypeNames.crend()) ? it->second.c_str() : nullptr; } diff --git a/sfall/ReplacementFuncs.h b/sfall/ReplacementFuncs.h index 9e0adeca..ca4a8258 100644 --- a/sfall/ReplacementFuncs.h +++ b/sfall/ReplacementFuncs.h @@ -7,6 +7,8 @@ #pragma once #include "Game\inventory.h" +#include "Game\items.h" #include "Game\render.h" #include "Game\skills.h" #include "Game\stats.h" +#include "Game\tilemap.h" diff --git a/sfall/SafeWrite.cpp b/sfall/SafeWrite.cpp index 691764ff..5ace5e00 100644 --- a/sfall/SafeWrite.cpp +++ b/sfall/SafeWrite.cpp @@ -14,7 +14,7 @@ static void __stdcall SafeWriteFunc(BYTE code, DWORD addr, void* func) { CheckConflict(addr, 5); } -static __declspec(noinline) void __stdcall SafeWriteFunc(BYTE code, DWORD addr, void* func, DWORD len) { +static __declspec(noinline) void __stdcall SafeWriteFunc(BYTE code, DWORD addr, void* func, size_t len) { DWORD oldProtect, protectLen = len + 5, addrMem = addr + 5, @@ -24,7 +24,7 @@ static __declspec(noinline) void __stdcall SafeWriteFunc(BYTE code, DWORD addr, *((BYTE*)addr) = code; *((DWORD*)(addr + 1)) = data; - for (unsigned int i = 0; i < len; i++) { + for (size_t i = 0; i < len; i++) { *((BYTE*)(addrMem + i)) = CodeType::Nop; } VirtualProtect((void*)addr, protectLen, oldProtect, &oldProtect); @@ -32,7 +32,7 @@ static __declspec(noinline) void __stdcall SafeWriteFunc(BYTE code, DWORD addr, CheckConflict(addr, protectLen); } -void SafeWriteBytes(DWORD addr, BYTE* data, int count) { +void SafeWriteBytes(DWORD addr, BYTE* data, size_t count) { DWORD oldProtect; VirtualProtect((void*)addr, count, PAGE_EXECUTE_READWRITE, &oldProtect); @@ -93,7 +93,7 @@ void MakeCall(DWORD addr, void* func) { SafeWriteFunc(CodeType::Call, addr, func); } -void MakeCall(DWORD addr, void* func, int len) { +void MakeCall(DWORD addr, void* func, size_t len) { SafeWriteFunc(CodeType::Call, addr, func, len); } @@ -101,7 +101,7 @@ void MakeJump(DWORD addr, void* func) { SafeWriteFunc(CodeType::Jump, addr, func); } -void MakeJump(DWORD addr, void* func, int len) { +void MakeJump(DWORD addr, void* func, size_t len) { SafeWriteFunc(CodeType::Jump, addr, func, len); } @@ -123,7 +123,7 @@ void MakeJumps(void* func, std::initializer_list addrs) { } } -void SafeMemSet(DWORD addr, BYTE val, int len) { +void SafeMemSet(DWORD addr, BYTE val, size_t len) { DWORD oldProtect; VirtualProtect((void*)addr, len, PAGE_EXECUTE_READWRITE, &oldProtect); diff --git a/sfall/SafeWrite.h b/sfall/SafeWrite.h index 1369c94d..ea834eda 100644 --- a/sfall/SafeWrite.h +++ b/sfall/SafeWrite.h @@ -49,14 +49,14 @@ void __stdcall SafeWrite16(DWORD addr, WORD data); void __stdcall SafeWrite32(DWORD addr, DWORD data); void __stdcall SafeWriteStr(DWORD addr, const char* data); -void SafeMemSet(DWORD addr, BYTE val, int len); -void SafeWriteBytes(DWORD addr, BYTE* data, int count); +void SafeMemSet(DWORD addr, BYTE val, size_t len); +void SafeWriteBytes(DWORD addr, BYTE* data, size_t count); void HookCall(DWORD addr, void* func); void MakeCall(DWORD addr, void* func); -void MakeCall(DWORD addr, void* func, int len); +void MakeCall(DWORD addr, void* func, size_t len); void MakeJump(DWORD addr, void* func); -void MakeJump(DWORD addr, void* func, int len); +void MakeJump(DWORD addr, void* func, size_t len); void BlockCall(DWORD addr); void HookCalls(void* func, std::initializer_list addrs); diff --git a/sfall/SimplePatch.h b/sfall/SimplePatch.h index dd650e18..a01057ce 100644 --- a/sfall/SimplePatch.h +++ b/sfall/SimplePatch.h @@ -3,18 +3,18 @@ namespace sfall { -template +template T SimplePatch(DWORD addr, const char* iniSection, const char* iniKey, T defaultValue, T minValue = 0, T maxValue = INT_MAX) { return SimplePatch(&addr, 1, iniSection, iniKey, defaultValue, minValue, maxValue); } -template +template T SimplePatch(DWORD *addrs, int numAddrs, const char* iniSection, const char* iniKey, T defaultValue, T minValue = 0, T maxValue = INT_MAX) { T value; char msg[255]; - value = (T)GetConfigInt(iniSection, iniKey, defaultValue); + value = (T)IniReader::GetConfigInt(iniSection, iniKey, defaultValue); if (value != defaultValue) { if (value < minValue) { value = minValue; diff --git a/sfall/Translate.cpp b/sfall/Translate.cpp new file mode 100644 index 00000000..7238f74f --- /dev/null +++ b/sfall/Translate.cpp @@ -0,0 +1,87 @@ +/* + * sfall + * Copyright (C) 2008-2021 The sfall team + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "IniReader.h" + +#include "Translate.h" + +namespace sfall +{ + +static struct Translation { + char def[65]; + char lang[170]; + bool state = false; + + const char* File() { + return (state) ? lang : def; + } +} translationIni; + +size_t Translate::Get(const char* section, const char* setting, const char* defaultValue, char* buffer, size_t bufSize) { + return IniReader::GetString(section, setting, defaultValue, buffer, bufSize, translationIni.File()); +} + +std::string Translate::Get(const char* section, const char* setting, const char* defaultValue, size_t bufSize) { + return std::move(IniReader::GetString(section, setting, defaultValue, bufSize, translationIni.File())); +} + +std::vector Translate::GetList(const char* section, const char* setting, const char* defaultValue, char delimiter, size_t bufSize) { + return std::move(IniReader::GetList(section, setting, defaultValue, bufSize, delimiter, translationIni.File())); +} + +//////////////////////////////////////////////////////////////////////////////// + +static void MakeLangTranslationPath(const char* config) { + char patches[65], language[32]; + char fileConfig[65] = ".\\"; + std::strcpy(&fileConfig[2], config); + + IniReader::GetString("system", "language", "english", language, 32, fileConfig); + IniReader::GetString("system", "master_patches", "data", patches, 65, fileConfig); + + const char* iniDef = translationIni.def; + while (*iniDef == '\\' || *iniDef == '/' || *iniDef == '.') iniDef++; // skip first characters + sprintf(translationIni.lang, "%s\\text\\%s\\%s", patches, language, iniDef); + + translationIni.state = (GetFileAttributes(translationIni.lang) != INVALID_FILE_ATTRIBUTES); +} + +static std::string saveSfallDataFailMsg; +static std::string combatSaveFailureMsg; +static std::string combatBlockedMessage; + +std::string& Translate::SfallSaveDataFailure() { return saveSfallDataFailMsg; } +std::string& Translate::CombatSaveBlockMessage() { return combatSaveFailureMsg; } +std::string& Translate::CombatBlockMessage() { return combatBlockedMessage; } + +static void InitMessagesTranslate() { + combatBlockedMessage = Translate::Get("sfall", "BlockedCombat", "You cannot enter combat at this time."); + combatSaveFailureMsg = Translate::Get("sfall", "SaveInCombat", "Cannot save at this time."); + saveSfallDataFailMsg = Translate::Get("sfall", "SaveSfallDataFail", "ERROR saving extended savegame information! " + "Check if other programs interfere with savegame files/folders and try again!"); +} + +void Translate::init(const char* config) { + IniReader::GetConfigString("Main", "TranslationsINI", ".\\Translations.ini", translationIni.def, 65); + + MakeLangTranslationPath(config); + InitMessagesTranslate(); +} + +} diff --git a/sfall/Translate.h b/sfall/Translate.h new file mode 100644 index 00000000..bbd7bcc9 --- /dev/null +++ b/sfall/Translate.h @@ -0,0 +1,49 @@ +/* + * sfall + * Copyright (C) 2008-2021 The sfall team + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +namespace sfall +{ + +class Translate { +public: + static void init(const char*); + + // Translates given string using sfall translation INI file and puts the result into given buffer + static size_t Get(const char* section, const char* setting, const char* defaultValue, char* buffer, size_t bufSize = 128); + + // Translates given string using sfall translation INI file + static std::string Get(const char* section, const char* setting, const char* defaultValue, size_t bufSize = 128); + + // Translates given list of strings using sfall translation INI file + static std::vector GetList(const char* section, const char* setting, const char* defaultValue, char delimiter, size_t bufSize = 256); + + /* Messages */ + + // SaveSfallDataFail: "ERROR saving extended savegame information!" + static std::string& Translate::SfallSaveDataFailure(); + + // SaveInCombat: "Cannot save at this time." + static std::string& Translate::CombatSaveBlockMessage(); + + // BlockedCombat: "You cannot enter combat at this time." + static std::string& Translate::CombatBlockMessage(); +}; + +} diff --git a/sfall/Utils.cpp b/sfall/Utils.cpp index b0f56dc2..b5d6bdc7 100644 --- a/sfall/Utils.cpp +++ b/sfall/Utils.cpp @@ -6,6 +6,14 @@ namespace sfall { +WORD ByteSwapW(WORD w) { + return ((w & 0xFF) << 8) | ((w & 0xFF00) >> 8); +} + +DWORD ByteSwapD(DWORD dw) { + return ((dw & 0xFF) << 24) | ((dw & 0xFF00) << 8) | ((dw & 0xFF0000) >> 8) | ((dw & 0xFF000000) >> 24); +} + std::vector split(const std::string &s, char delim) { std::vector elems; split(s, delim, std::back_inserter(elems)); diff --git a/sfall/Utils.h b/sfall/Utils.h index 1ebc78f2..4ec24d87 100644 --- a/sfall/Utils.h +++ b/sfall/Utils.h @@ -9,7 +9,7 @@ namespace sfall // splits a string by given delimiter // taken from: http://stackoverflow.com/a/236803/4331475 -template +template void split(const std::string &s, char delim, T result, size_t limit = -1) { std::stringstream ss; ss.str(s); @@ -21,6 +21,9 @@ void split(const std::string &s, char delim, T result, size_t limit = -1) { } } +WORD ByteSwapW(WORD w); +DWORD ByteSwapD(DWORD dw); + // Splits a string by given delimiter std::vector split(const std::string &s, char delim); diff --git a/sfall/ddraw.vcxproj b/sfall/ddraw.vcxproj index 514086e8..497fc3c1 100644 --- a/sfall/ddraw.vcxproj +++ b/sfall/ddraw.vcxproj @@ -291,10 +291,15 @@ + + + + + @@ -319,6 +324,8 @@ + + @@ -383,6 +390,7 @@ + @@ -395,10 +403,15 @@ + + + + + @@ -422,6 +435,8 @@ + + @@ -492,6 +507,7 @@ Create Create + diff --git a/sfall/ddraw.vcxproj.filters b/sfall/ddraw.vcxproj.filters index 39528b5d..edb22c53 100644 --- a/sfall/ddraw.vcxproj.filters +++ b/sfall/ddraw.vcxproj.filters @@ -313,6 +313,7 @@ Modules\SubModules + Game @@ -325,7 +326,26 @@ Game - + + Game + + + Game + + + Modules\Scripting\Handlers + + + Modules\Scripting\Handlers + + + + Game + + + + Game + @@ -602,6 +622,26 @@ Game + + Game + + + Game + + + Modules\Scripting\Handlers + + + Modules\Scripting\Handlers + + + + Game + + + + Game + diff --git a/sfall/main.cpp b/sfall/main.cpp index 871cc5e1..31d3de10 100644 --- a/sfall/main.cpp +++ b/sfall/main.cpp @@ -20,10 +20,6 @@ #include -#include -#include -#include - #include "FalloutEngine\Fallout2.h" #include "ModuleManager.h" #include "Modules\Module.h" @@ -47,8 +43,8 @@ #include "Modules\ExtraSaveSlots.h" #include "Modules\FileSystem.h" #include "Modules\Graphics.h" -#include "Modules\HookScripts.h" #include "Modules\HeroAppearance.h" +#include "Modules\HookScripts.h" #include "Modules\Input.h" #include "Modules\Interface.h" #include "Modules\Inventory.h" @@ -80,11 +76,10 @@ #include "Modules\Worldmap.h" #include "CRC.h" -#include "SimplePatch.h" #include "Logging.h" #include "ReplacementFuncs.h" -#include "Utils.h" -#include "Version.h" +#include "Translate.h" +#include "version.h" #include "main.h" @@ -98,83 +93,21 @@ bool isDebug = false; bool hrpIsEnabled = false; bool hrpVersionValid = false; // HRP 4.1.8 version validation -const char ddrawIni[] = ".\\ddraw.ini"; -static char ini[65] = ".\\"; -static char translationIni[65]; - -DWORD modifiedIni; -DWORD hrpDLLBaseAddr = 0x10000000; +static DWORD hrpDLLBaseAddr = 0x10000000; DWORD HRPAddress(DWORD addr) { return (hrpDLLBaseAddr + (addr & 0xFFFFF)); } -int iniGetInt(const char* section, const char* setting, int defaultValue, const char* iniFile) { - return GetPrivateProfileIntA(section, setting, defaultValue, iniFile); -} - -size_t iniGetString(const char* section, const char* setting, const char* defaultValue, char* buf, size_t bufSize, const char* iniFile) { - return GetPrivateProfileStringA(section, setting, defaultValue, buf, bufSize, iniFile); -} - -std::string GetIniString(const char* section, const char* setting, const char* defaultValue, size_t bufSize, const char* iniFile) { - char* buf = new char[bufSize]; - iniGetString(section, setting, defaultValue, buf, bufSize, iniFile); - std::string str(buf); - delete[] buf; - return str; -} - -std::vector GetIniList(const char* section, const char* setting, const char* defaultValue, size_t bufSize, char delimiter, const char* iniFile) { - auto list = split(GetIniString(section, setting, defaultValue, bufSize, iniFile), delimiter); - std::transform(list.cbegin(), list.cend(), list.begin(), trim); - return list; -} - -/* - For ddraw.ini config -*/ -unsigned int GetConfigInt(const char* section, const char* setting, int defaultValue) { - return iniGetInt(section, setting, defaultValue, ini); -} - -std::string GetConfigString(const char* section, const char* setting, const char* defaultValue, size_t bufSize) { - return trim(GetIniString(section, setting, defaultValue, bufSize, ini)); -} - -size_t GetConfigString(const char* section, const char* setting, const char* defaultValue, char* buf, size_t bufSize) { - return iniGetString(section, setting, defaultValue, buf, bufSize, ini); -} - -std::vector GetConfigList(const char* section, const char* setting, const char* defaultValue, size_t bufSize) { - return GetIniList(section, setting, defaultValue, bufSize, ',', ini); -} - -std::vector TranslateList(const char* section, const char* setting, const char* defaultValue, char delimiter, size_t bufSize) { - return GetIniList(section, setting, defaultValue, bufSize, delimiter, translationIni); -} - -std::string Translate(const char* section, const char* setting, const char* defaultValue, size_t bufSize) { - return GetIniString(section, setting, defaultValue, bufSize, translationIni); -} - -size_t Translate(const char* section, const char* setting, const char* defaultValue, char* buffer, size_t bufSize) { - return iniGetString(section, setting, defaultValue, buffer, bufSize, translationIni); -} - -int SetConfigInt(const char* section, const char* setting, int value) { - char* buf = new char[33]; - _itoa_s(value, buf, 33, 10); - int result = WritePrivateProfileStringA(section, setting, buf, ini); - delete[] buf; - return result; -} +char falloutConfigName[65] = {0}; void InitReplacementHacks() { game::Inventory::init(); + game::Items::init(); game::Render::init(); game::Skills::init(); game::Stats::init(); + game::Tilemap::init(); } static void InitModules() { @@ -265,9 +198,9 @@ static void CompatModeCheck(HKEY root, const char* filepath, int extra) { RegCloseKey(key); MessageBoxA(0, "Fallout appears to be running in compatibility mode.\n" //, and sfall was not able to disable it.\n" - "Please check the compatibility tab of fallout2.exe, and ensure that the following settings are unchecked:\n" - "Run this program in compatibility mode for..., run in 256 colours, and run in 640x480 resolution.\n" - "If these options are disabled, click the 'change settings for all users' button and see if that enables them.", "Error", MB_TASKMODAL | MB_ICONERROR); + "Please check the compatibility tab of fallout2.exe, and ensure that the following settings are unchecked:\n" + "Run this program in compatibility mode for..., run in 256 colours, and run in 640x480 resolution.\n" + "If these options are disabled, click the 'change settings for all users' button and see if that enables them.", "Error", MB_TASKMODAL | MB_ICONERROR); ExitProcess(-1); } @@ -279,10 +212,10 @@ static void CompatModeCheck(HKEY root, const char* filepath, int extra) { inline void SfallInit() { // enabling debugging features - isDebug = (iniGetInt("Debugging", "Enable", 0, ::sfall::ddrawIni) != 0); + isDebug = (IniReader::GetIntDefaultConfig("Debugging", "Enable", 0) != 0); if (isDebug) { LoggingInit(); - if (!ddraw.dll) dlog("Error: Cannot load the original ddraw.dll library.\n", DL_MAIN); + if (!ddraw.dll) dlogr("Error: Cannot load the original ddraw.dll library.", DL_MAIN); } char filepath[MAX_PATH]; @@ -290,7 +223,7 @@ inline void SfallInit() { CRC(filepath); - if (!isDebug || !iniGetInt("Debugging", "SkipCompatModeCheck", 0, ::sfall::ddrawIni)) { + if (!isDebug || !IniReader::GetIntDefaultConfig("Debugging", "SkipCompatModeCheck", 0)) { int is64bit; typedef int (__stdcall *chk64bitproc)(HANDLE, int*); HMODULE h = LoadLibrary("Kernel32.dll"); @@ -308,7 +241,7 @@ inline void SfallInit() { // ini file override bool cmdlineexists = false; char* cmdline = GetCommandLineA(); - if (iniGetInt("Main", "UseCommandLine", 0, ::sfall::ddrawIni)) { + if (IniReader::GetIntDefaultConfig("Main", "UseCommandLine", 0)) { while (cmdline[0] == ' ') cmdline++; bool InQuote = false; int count = -1; @@ -334,20 +267,17 @@ inline void SfallInit() { HANDLE h = CreateFileA(cmdline, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0); if (h != INVALID_HANDLE_VALUE) { CloseHandle(h); - strcat_s(ini, cmdline); + IniReader::SetConfigFile(cmdline); } else { MessageBoxA(0, "You gave a command line argument to Fallout, but it couldn't be matched to a file.\n" \ - "Using default ddraw.ini instead.", "Warning", MB_TASKMODAL | MB_ICONWARNING); + "Using default ddraw.ini instead.", "Warning", MB_TASKMODAL | MB_ICONWARNING); goto defaultIni; } } else { defaultIni: - strcpy(&ini[2], &::sfall::ddrawIni[2]); + IniReader::SetDefaultConfigFile(); } - GetConfigString("Main", "TranslationsINI", ".\\Translations.ini", translationIni, 65); - modifiedIni = GetConfigInt("Main", "ModifiedIni", 0); - hrpIsEnabled = (*(DWORD*)0x4E4480 != 0x278805C7); // check if HRP is enabled if (hrpIsEnabled) { LoadHRPModule(); @@ -360,6 +290,19 @@ defaultIni: } std::srand(GetTickCount()); + IniReader::init(); + + if (IniReader::GetConfigString("Misc", "ConfigFile", "", falloutConfigName, 65)) { + dlog("Applying config file patch.", DL_INIT); + SafeWriteBatch((DWORD)&falloutConfigName, {0x444BA5, 0x444BCA}); + dlogr(" Done", DL_INIT); + } else { + // if the ConfigFile is not assigned a value + std::strcpy(falloutConfigName, (const char*)FO_VAR_fallout_config); + } + + Translate::init(falloutConfigName); + InitReplacementHacks(); InitModules(); } diff --git a/sfall/main.h b/sfall/main.h index f309a85a..b3067297 100644 --- a/sfall/main.h +++ b/sfall/main.h @@ -35,6 +35,7 @@ #include "SafeWrite.h" #include "Logging.h" +#include "IniReader.h" struct ddrawDll { HMODULE dll; @@ -80,46 +81,11 @@ namespace sfall #define pushadc __asm push eax __asm push edx __asm push ecx #define popadc __asm pop ecx __asm pop edx __asm pop eax -// Gets the integer value from given INI file. -int iniGetInt(const char* section, const char* setting, int defaultValue, const char* iniFile); - -// Gets the string value from given INI file. -size_t iniGetString(const char* section, const char* setting, const char* defaultValue, char* buf, size_t bufSize, const char* iniFile); - -// Gets the string value from given INI file. -std::string GetIniString(const char* section, const char* setting, const char* defaultValue, size_t bufSize, const char* iniFile); - -// Parses the comma-separated list setting from given INI file. -std::vector GetIniList(const char* section, const char* setting, const char* defaultValue, size_t bufSize, char delimiter, const char* iniFile); - -// Gets the integer value from Sfall configuration INI file. -unsigned int GetConfigInt(const char* section, const char* setting, int defaultValue); - -// Gets the string value from Sfall configuration INI file with trim function. -std::string GetConfigString(const char* section, const char* setting, const char* defaultValue, size_t bufSize = 128); - -// Loads the string value from Sfall configuration INI file into the provided buffer. -size_t GetConfigString(const char* section, const char* setting, const char* defaultValue, char* buffer, size_t bufSize = 128); - -// Parses the comma-separated list from the settings from Sfall configuration INI file. -std::vector GetConfigList(const char* section, const char* setting, const char* defaultValue, size_t bufSize = 128); - -std::vector TranslateList(const char* section, const char* setting, const char* defaultValue, char delimiter, size_t bufSize = 256); - -// Translates given string using Sfall translation INI file. -std::string Translate(const char* section, const char* setting, const char* defaultValue, size_t bufSize = 128); - -// Translates given string using Sfall translation INI file and puts the result into given buffer. -size_t Translate(const char* section, const char* setting, const char* defaultValue, char* buffer, size_t bufSize = 128); - -int SetConfigInt(const char* section, const char* setting, int value); - DWORD HRPAddress(DWORD addr); -extern const char ddrawIni[]; -extern DWORD modifiedIni; - extern bool hrpIsEnabled; extern bool hrpVersionValid; +extern char falloutConfigName[65]; + } diff --git a/sfall/version.h b/sfall/version.h index 6bce6f1f..0211d936 100644 --- a/sfall/version.h +++ b/sfall/version.h @@ -23,8 +23,8 @@ #define LEGAL_COPYRIGHT "Copyright (C) 2006-2021, sfall team" #define VERSION_MAJOR 4 -#define VERSION_MINOR 2 -#define VERSION_BUILD 9 +#define VERSION_MINOR 3 +#define VERSION_BUILD 0 #define VERSION_REV 0 -#define VERSION_STRING "4.2.9" +#define VERSION_STRING "4.3"