Files
0716e3fff4 Atmos refactor & speedup by utilizing BYOND 516 vector functions (#96448)
## About The Pull Request

### Summary
This PR changes internal structure of `/datum/gas_mixture`:
`gases[gas_id][MOLES]` refactored into `moles[gas_id]`,
`gases[gas_id][ARCHIVE]` into `moles_archive[gas_id]` and
`gases[gas_id][GAS_META]` into `gas_meta` static variable. This allows
us to use BYOND 516 vector functions for calculating total moles and
heat capacity. Also it simplifies some parts of the code, allowing us to
get rid of macros `ADD_GAS` and `ASSERT_GAS`. According to the profiler
`/turf/open/process_cell` time is reduced by ~20%.

### Details
`gas_mixture.gases` was a nested 2d-list with MOLES, ARCHIVE and
GAS_META for each gas_id. For example, to get gas moles you had to do
`gases[gas_id][MOLES]`. I've changed this structure to be as follows:
`moles[gas_id]` - moles for the gas, `moles_archive[gas_id]` - archived
version of moles, `gas_meta[KEY][gas_id]` - static var with meta
information for the gas.

Since I removed key GAS_META from the gases, `gas_meta` was moved to the
static variable and the order of keys in the array was changed from
`gas_meta[gas_id][META_KEY]' to 'gas_meta[META_KEY][gas_id]`. This was
done to allow using it in vector calculations (for example heat capacity
or fusion power). Static variable access is very fast and it is
considered as accessing a global in the bytecode.

Byond 516 introduced new vector functions: `values_sum`, `values_dot`
and others. These functions are very fast, but operate only on
associative lists. This allows us to change the way we calculate
total_moles and heat_capacity - very hot and heavily used functions.
`total_moles()` became just `values_sum(moles)`, and `heat_capacity` is
just a dot product: `values_dot(moles,
gas_meta[META_GAS_SPECIFIC_HEAT])`.

As a side bonus, since `moles` is just an associative list, you don't
really need old macros `ADD_GAS` and `ASSERT_GAS` - all they did was to
make a copy of a list[3] with default value [0, 0, gas_meta] for
specific gas. Now when you're adding gas you can just use `moles[gas_id]
+= amount` and when you query amount of gas you can just query the key
(for example `moles[/datum/gas/oxygen]`) if the key does not exist, it
returns null and works as 0 for all arithmetic and logic operations. For
example, old code would be `if (!air.gases[/datum/gas/oxygen] ||
air.gases[/datum/gas/oxygen][MOLES] < 1)` and now it is `if
(moles[/datum/gas/oxygen] < 1)`. This simplifies some parts of the code
and also speeds things up.

For the performance comparison I used Tracy profiler. I've done many
different tests, and they all show slightly different numbers, but
overall speedup for `process_cell` is about 20%. (-20% to average time
per call from ). My testing setup was as follows:
Load Icebox, drop 30/60/90 radius bomb in the middle of the bridge, set
code to blue, wait 10 minutes until the round ends.
Also I fixed random seed in the master controller and in the planetary
gas randomization so generated maps are the same between tests.
Althought it's not very realistic, it generates a lot of samples for the
`process_cell` (around ~3.5M per 10 minutes).
Another test I did was a plasmafire in an 8x8 space, on runtime station,
it showed (-24% time on process_cell).
Another test was a emagged holodeck burn test, it showed (-13% time)
As for other functions of gas_mixture: `total_moles`: -50%(2x speedup),
`heat_capacity`: -65%(3x speedup), `share`: -30%, `react`: -20%. Timings
of all those functions is in microseconds range and they are very hot
(call count is in the same order as process_cell)

<details><summary>Some pictures from profiler</summary>
<img width="569" height="642" alt="process_cell"
src="https://github.com/user-attachments/assets/76fa0c27-719d-485d-9bfc-859fef788999"
/>
<img width="572" height="315" alt="image"
src="https://github.com/user-attachments/assets/f68497e9-4db8-4a9c-b43f-ad04e6dc5cac"
/>
<img width="569" height="317" alt="image"
src="https://github.com/user-attachments/assets/d7249e7b-f344-47a6-8b39-1bab0521182d"
/>
<img width="541" height="316" alt="image"
src="https://github.com/user-attachments/assets/1bef71fd-533d-40fa-a85e-7a803ad322f7"
/>
<img width="519" height="409" alt="image"
src="https://github.com/user-attachments/assets/51165289-174e-403d-a09c-787dd9af136a"
/>
<img width="523" height="318" alt="image"
src="https://github.com/user-attachments/assets/fe4b1db0-17d8-47f9-8fd0-e2ecef2ee66a"
/>
</details>

<details><summary>Setting up a profiler</summary>
If you wanna to reproduce my results here is a list of steps

1. download: https://github.com/goonstation/byond-tracy-writer (this one
has offsets for my version 1677)
2. build the dll, drop in the tgstation/ folder
3. download rtracy https://github.com/Dimach/rtracy
4. download Tracy profiler (0.13.1) https://github.com/wolfpld/tracy
5. uncomment `#define USE_BYOND_TRACY` in `_compile_options.dm`
6. build tgstation
7. open dream daemon, run the desired test, after round end dream daemon
closes
8. navigate to tgstation/data/profiler, find the `123412341234.utracy`
file
9. run `rtracty 123412341234.utracy`
10. open tracy-profiler.exe, press Connect, save the profiler data
11. repeat steps 5-10 with another branch, save another profiler data
12. open tracy-profiler, open first data, press compare, open second
data
</details>

## Why It's Good For The Game

## Changelog
🆑
refactor: Atmos refactor & speedup by utilizing BYOND 516 vector
functions
/🆑

---------

Co-authored-by: san7890 <the@san7890.com>
2026-07-14 20:34:31 -07:00

295 lines
9.7 KiB
Plaintext

/obj/item/flamethrower
name = "flamethrower"
desc = "You are a firestarter!"
icon = 'icons/obj/weapons/flamethrower.dmi'
icon_state = "flamethrowerbase"
inhand_icon_state = "flamethrower_0"
lefthand_file = 'icons/mob/inhands/weapons/flamethrower_lefthand.dmi'
righthand_file = 'icons/mob/inhands/weapons/flamethrower_righthand.dmi'
obj_flags = CONDUCTS_ELECTRICITY
force = 3
throwforce = 10
throw_speed = 1
throw_range = 5
w_class = WEIGHT_CLASS_NORMAL
custom_materials = list(/datum/material/iron = SHEET_MATERIAL_AMOUNT * 1.05, /datum/material/glass = SMALL_MATERIAL_AMOUNT * 0.7)
resistance_flags = FIRE_PROOF
trigger_guard = TRIGGER_GUARD_NORMAL
light_system = OVERLAY_LIGHT
light_color = LIGHT_COLOR_FLARE
light_range = 2
light_power = 2
light_on = FALSE
interaction_flags_click = NEED_DEXTERITY|NEED_HANDS|ALLOW_RESTING
var/status = FALSE
var/lit = FALSE //on or off
var/operating = FALSE//cooldown
var/obj/item/weldingtool/weldtool = null
/// The igniter stored in the flamethrower
var/obj/item/assembly/igniter/igniter = null
/// The plasma tank that we shoot gas from
var/obj/item/tank/internals/plasma/ptank = null
var/warned_admins = FALSE //for the message_admins() when lit
//variables for prebuilt flamethrowers
var/create_full = FALSE
var/create_with_tank = FALSE
var/igniter_type = /obj/item/assembly/igniter
var/acti_sound = 'sound/items/tools/welderactivate.ogg'
var/deac_sound = 'sound/items/tools/welderdeactivate.ogg'
/obj/item/flamethrower/Initialize(mapload)
. = ..()
AddElement(/datum/element/update_icon_updates_onmob)
var/static/list/slapcraft_recipe_list = list(/datum/crafting_recipe/flamethrower)
AddElement(
/datum/element/slapcrafting,\
slapcraft_recipes = slapcraft_recipe_list,\
)
/obj/item/flamethrower/Destroy()
if(weldtool)
QDEL_NULL(weldtool)
if(igniter)
QDEL_NULL(igniter)
if(ptank)
QDEL_NULL(ptank)
return ..()
/obj/item/flamethrower/process()
if(!lit || !igniter)
return PROCESS_KILL
var/turf/location = loc
if(ismob(location))
var/mob/M = location
if(M.is_holding(src))
location = M.loc
if(isturf(location)) //start a fire if possible
igniter.flamethrower_process(location)
/obj/item/flamethrower/update_icon_state()
inhand_icon_state = "flamethrower_[lit]"
return ..()
/obj/item/flamethrower/update_overlays()
. = ..()
if(igniter)
. += "+igniter[status]"
if(ptank)
. += "+ptank"
if(lit)
. += "+lit"
/obj/item/flamethrower/ranged_interact_with_atom(atom/interacting_with, mob/living/user, list/modifiers)
if (!ptank)
return NONE
if(HAS_TRAIT(user, TRAIT_PACIFISM))
to_chat(user, span_warning("You can't bring yourself to fire \the [src]! You don't want to risk harming anyone..."))
log_combat(user, interacting_with, "attempted to flamethrower", src, "with gas mixture: {[print_gas_mixture(ptank.return_analyzable_air())]}, flamethrower: \"[name]\" ([src]), igniter: \"[igniter.name]\", tank: \"[ptank.name]\" and tank distribution pressure: \"[siunit(1000 * ptank.distribute_pressure, unit = "Pa", maxdecimals = 9)]\"" + (lit ? " while lit" : "" + " but failed due to pacifism."))
return ITEM_INTERACT_BLOCKING
var/turf/target_turf = get_turf(interacting_with)
if(target_turf)
var/turflist = get_line(user, target_turf)
log_combat(user, interacting_with, "flamethrowered", src, "with gas mixture: {[print_gas_mixture(ptank.return_analyzable_air())]}, flamethrower: \"[name]\", igniter: \"[igniter.name]\", tank: \"[ptank.name]\" and tank distribution pressure: \"[siunit(1000 * ptank.distribute_pressure, unit = "Pa", maxdecimals = 9)]\"" + (lit ? " while lit." : "."))
flame_turf(turflist)
return ITEM_INTERACT_SUCCESS
/obj/item/flamethrower/wrench_act(mob/living/user, obj/item/tool)
. = ITEM_INTERACT_SUCCESS
if(status)
return ITEM_INTERACT_BLOCKING
tool.play_tool_sound(src)
var/turf/T = get_turf(src)
if(weldtool)
weldtool.forceMove(T)
weldtool = null
if(igniter)
igniter.forceMove(T)
igniter = null
if(ptank)
ptank.forceMove(T)
ptank = null
new /obj/item/stack/rods(T)
qdel(src)
/obj/item/flamethrower/screwdriver_act(mob/living/user, obj/item/tool)
if(igniter && !lit)
tool.play_tool_sound(src)
status = !status
to_chat(user, span_notice("[igniter] is now [status ? "secured" : "unsecured"]!"))
update_appearance()
return TRUE
/obj/item/flamethrower/item_interaction(mob/living/user, obj/item/tool, list/modifiers)
if(isigniter(tool))
var/obj/item/assembly/igniter/inserting_igniter = tool
if(inserting_igniter.secured)
return ITEM_INTERACT_BLOCKING
if(igniter)
return ITEM_INTERACT_BLOCKING
if(!user.transferItemToLoc(tool, src))
return ITEM_INTERACT_BLOCKING
igniter = inserting_igniter
update_appearance()
balloon_alert(user, "attached")
return ITEM_INTERACT_SUCCESS
if(istype(tool, /obj/item/tank/internals/plasma))
if(ptank)
if(!user.transferItemToLoc(tool, src))
return ITEM_INTERACT_BLOCKING
ptank.forceMove(get_turf(src))
ptank = tool
to_chat(user, span_notice("You swap the plasma tank in [src]!"))
return ITEM_INTERACT_SUCCESS
if(!user.transferItemToLoc(tool, src))
return ITEM_INTERACT_BLOCKING
ptank = tool
update_appearance()
return ITEM_INTERACT_SUCCESS
return NONE
/obj/item/flamethrower/return_analyzable_air()
if(ptank)
return ptank.return_analyzable_air()
else
return null
/obj/item/flamethrower/attack_self(mob/user)
toggle_igniter(user)
/obj/item/flamethrower/click_alt(mob/user)
if(isnull(ptank))
return NONE
user.put_in_hands(ptank)
ptank = null
to_chat(user, span_notice("You remove the plasma tank from [src]!"))
update_appearance()
return CLICK_ACTION_SUCCESS
/obj/item/flamethrower/examine(mob/user)
. = ..()
if(ptank)
. += span_notice("\The [src] has \a [ptank] attached. Alt-click to remove it.")
/obj/item/flamethrower/proc/toggle_igniter(mob/user)
if(!ptank)
to_chat(user, span_notice("Attach a plasma tank first!"))
return
if(!status)
to_chat(user, span_notice("Secure the igniter first!"))
return
to_chat(user, span_notice("You [lit ? "extinguish" : "ignite"] [src]!"))
lit = !lit
if(lit)
playsound(loc, acti_sound, 50, TRUE)
START_PROCESSING(SSobj, src)
if(!warned_admins)
message_admins("[ADMIN_LOOKUPFLW(user)] has lit a flamethrower.")
warned_admins = TRUE
else
playsound(loc, deac_sound, 50, TRUE)
STOP_PROCESSING(SSobj,src)
set_light_on(lit)
update_appearance()
/obj/item/flamethrower/on_craft_completion(list/components, datum/crafting_recipe/current_recipe, atom/crafter)
. =..()
weldtool = locate(/obj/item/weldingtool) in contents
igniter = locate(/obj/item/assembly/igniter) in contents
weldtool.status = FALSE
igniter.secured = FALSE
status = TRUE
update_appearance()
//Called from turf.dm turf/dblclick
/obj/item/flamethrower/proc/flame_turf(turflist)
if(!lit || operating)
return
operating = TRUE
var/turf/previousturf = get_turf(src)
for(var/turf/T in turflist)
if(T == previousturf)
continue //so we don't burn the tile we be standin on
var/list/turfs_sharing_with_prev = previousturf.get_atmos_adjacent_turfs(alldir=1)
if(!(T in turfs_sharing_with_prev))
break
if(igniter)
igniter.ignite_turf(src,T)
else
default_ignite(T)
sleep(0.1 SECONDS)
previousturf = T
operating = FALSE
/obj/item/flamethrower/proc/default_ignite(turf/target, release_amount = 0.05)
//TODO: DEFERRED Consider checking to make sure tank pressure is high enough before doing this...
//Transfer 5% of current tank air contents to turf
var/datum/gas_mixture/tank_mix = ptank.return_air()
var/datum/gas_mixture/air_transfer = tank_mix.remove_ratio(release_amount)
if(air_transfer.moles[/datum/gas/plasma])
var/moles = air_transfer.moles[/datum/gas/plasma] * 5 //Suffering
air_transfer.set_gas(/datum/gas/plasma, moles)
target.assume_air(air_transfer)
//Burn it based on transferred gas
target.hotspot_expose((tank_mix.temperature*2) + 380,500)
//location.hotspot_expose(1000,500,1)
/obj/item/flamethrower/Initialize(mapload)
. = ..()
AddComponent(\
/datum/component/bullet_intercepting,\
block_chance = 15,\
on_intercepted = CALLBACK(src, PROC_REF(intercepted_bullet_reaction)),\
active_slots = ITEM_SLOT_HANDS,\
block_type = list(BULLET,LASER),\
is_blocking_check = CALLBACK(src, PROC_REF(check_tank)),\
)
if(create_full)
if(!weldtool)
weldtool = new /obj/item/weldingtool(src)
weldtool.status = FALSE
if(!igniter)
igniter = new igniter_type(src)
igniter.secured = FALSE
status = TRUE
if(create_with_tank)
ptank = new /obj/item/tank/internals/plasma/full(src)
update_appearance()
RegisterSignal(src, COMSIG_ITEM_RECHARGED, PROC_REF(instant_refill))
/obj/item/flamethrower/full
create_full = TRUE
custom_materials = list(/datum/material/iron = HALF_SHEET_MATERIAL_AMOUNT)
/obj/item/flamethrower/full/tank
create_with_tank = TRUE
/obj/item/flamethrower/proc/intercepted_bullet_reaction(mob/living/holder, obj/projectile/bullet)
holder.visible_message(span_danger("\The [bullet] hits the fuel tank on [holder]'s [name], rupturing it! What a shot!"))
var/turf/target_turf = get_turf(holder)
holder.log_message("held a flamethrower tank detonated by a projectile ([bullet])", LOG_GAME)
igniter.ignite_turf(src,target_turf, release_amount = 100)
qdel(ptank)
/obj/item/flamethrower/proc/check_tank()
return ptank
/obj/item/assembly/igniter/proc/flamethrower_process(turf/open/location)
location.hotspot_expose(heat,2)
/obj/item/assembly/igniter/proc/ignite_turf(obj/item/flamethrower/F,turf/open/location,release_amount = 0.05)
F.default_ignite(location,release_amount)
/obj/item/flamethrower/proc/instant_refill()
SIGNAL_HANDLER
if(ptank)
var/datum/gas_mixture/tank_mix = ptank.return_air()
tank_mix.set_gas(/datum/gas/plasma, (10*ONE_ATMOSPHERE)*ptank.volume/(R_IDEAL_GAS_EQUATION*T20C))
else
ptank = new /obj/item/tank/internals/plasma/full(src)
update_appearance()