Files
Bubberstation/code/modules/modular_computers/computers/item/computer.dm
Useroth 59d74624b1 Upstream power stuff combined and shit (#27284)
* Converts arbitrary energy units to the joule. Fixes conservation of energy issues relating to charging cells. (#81579)

Removes all arbitrary energy and power units in the codebase. Everything
is replaced with the joule and watt, with 1 = 1 joule, or 1 watt if you
are going to multiply by time. This is a visible change, where all
arbitrary energy units you see in the game will get proper prefixed
units of energy.

With power cells being converted to the joule, charging one joule of a
power cell will require one joule of energy.

The grid will now store energy, instead of power. When an energy usage
is described as using the watt, a power to energy conversion based on
the relevant subsystem's timing (usually multiplying by seconds_per_tick
or applying power_to_energy()) is needed before adding or removing from
the grid. Power usages that are described as the watt is really anything
you would scale by time before applying the load. If it's described as a
joule, no time conversion is needed. Players will still read the grid as
power, having no visible change.

Machines that dynamically use power with the use_power() proc will
directly drain from the grid (and apc cell if there isn't enough)
instead of just tallying it up on the dynamic power usages for the area.
This should be more robust at conserving energy as the surplus is
updated on the go, preventing charging cells from nothing.

APCs no longer consume power for the dynamic power usage channels. APCs
will consume power for static power usages. Because static power usages
are added up without checking surplus, static power consumption will be
applied before any machine processes. This will give a more truthful
surplus for dynamic power consumers.

APCs will display how much power it is using for charging the cell. APC
cell charging applies power in its own channel, which gets added up to
the total. This will prevent invisible power usage you see when looking
at the power monitoring console.

After testing in MetaStation, I found roundstart power consumption to be
around 406kW after all APCs get fully charged. During the roundstart APC
charge rush, the power consumption can get as high as over 2MW (up to
25kW per roundstart APC charging) as long as there's that much
available.

Because of the absurd potential power consumption of charging APCs near
roundstart, I have changed how APCs decide to charge. APCs will now
charge only after all other machines have processed in the machines
processing subsystem. This will make sure APC charging won't disrupt
machines taking from the grid, and should stop APCs getting their power
drained due to others demanding too much power while charging. I have
removed the delays for APC charging too, so they start charging
immediately whenever there's excess power. It also stops them turning
red when a small amount of cell gets drained (airlocks opening and shit
during APC charge rush), as they immediately become fully charged
(unless too much energy got drained somehow) before changing icon.

Engineering SMES now start at 100% charge instead of 75%. I noticed
cells were draining earlier than usual after these changes, so I am
making them start maxed to try and combat that.

These changes will fix all conservation of energy issues relating to
charging powercells.

Closes #73438
Closes #75789
Closes #80634
Closes #82031

Makes it much easier to interface with the power system in the codebase.
It's more intuitive. Removes a bunch of conservation of energy issues,
making energy and power much more meaningful. It will help the
simulation remain immersive as players won't encounter energy
duplication so easily. Arbitrary energy units getting replaced with the
joule will also tell people more meaningful information when reading it.
APC charging will feel more snappy.

🆑
fix: Fixes conservation of energy issues relating to charging
powercells.
qol: APCs will display how much power they are using to charge their
cell. This is accounted for in the power monitoring console.
qol: All arbitrary power cell energy units you see are replaced with
prefixed joules.
balance: As a consequence of the conservation of energy issues getting
fixed, the power consumption for charging cells is now very significant.
balance: APCs only use surplus power from the grid after every machine
processes when charging, preventing APCs from causing others to
discharge while charging.
balance: Engineering SMES start at max charge to combat the increased
energy loss due to conservation of energy fixes.
/🆑

---------

Co-authored-by: SyncIt21 <110812394+SyncIt21@users.noreply.github.com>
Co-authored-by: Ghom <42542238+Ghommie@users.noreply.github.com>

* Corrects Suit Storage Unit charge rate  (#82192)

## About The Pull Request

Adjusts SSU charge rate according to the new conversion ratio. 

Betcha didn't know SSUs recharge suit and MOD cells? 

This number is actually supposed to be equal to the rate a recharger
station does it.
I don't know if we have some macro for it. 

## Changelog

🆑 Melbert
fix: Fixed Suit Storage Unit cell charging rate
/🆑

* Corrects EVA thermal regulator cell cost (#82195)

## About The Pull Request

Another unit not converted to watts / joules

## Changelog

🆑 Melbert
fix: Fixed space suit thermal regulators cell usage.
/🆑

* Fixing cell power usage (Part 1) (#82197)

## About The Pull Request
Yeah i am not about to create 30 different PR's to address 1 issue at a
time. The changes are small enough to be grouped together in bulk.

This fixes the following issues specified in #82196
- Borg & exosuit RCD (Fixes #82193)
- Motorized wheelchair
- Canister shielding
- Electrolyser
- Potato cell
- Space heater
- Microwave

## Changelog
🆑
fix: Fixed cell energy usage for a bunch of stuff(Part 1). See PR 82197
for details
/🆑

---------

Co-authored-by: Pickle-Coding <58013024+Pickle-Coding@users.noreply.github.com>

* Fixing cell power usage (Part 2) (#82198)

## About The Pull Request
Continuation of #82197.

Fixes these issues in #82196
- Cyborg self repair
- Cyborg lollipop dispenser
- Mauna mug
- Plasma cutter (Initial charge not the number of laser shots so partial
fix)

## Changelog
🆑
fix: Fixed more energy usages for cells(Part 2). See PR 82198 for
details
/🆑

---------

Co-authored-by: Pickle-Coding <58013024+Pickle-Coding@users.noreply.github.com>

* Fixing cell power usage (Part 3) (#82204)

## About The Pull Request
Continuation of #82198

Fixes these issues in #82196
- Borg hypo spray
- Borg projectile dampen
- Borg chameleon
- Firelance
- MODlink scryer
- Emergency light usage

## Changelog
🆑
fix: Fixed more energy usages for cells(Part 3). See PR 82204 for
details
/🆑

---------

Co-authored-by: Pickle-Coding <58013024+Pickle-Coding@users.noreply.github.com>

* [NO GBP]Fixes static power usage not always drawing the remaining energy of an APC cell. (#82205)

## About The Pull Request
Makes APC static power draw consume the remaining energy of the cell if
there's not enough energy.
## Why It's Good For The Game
Prevents a niche issue where an area composed entirely of static power
users with no dynamic users from running forever with no power supply.
## Changelog
🆑
fix: Fixes static power usage from being able to not draw power.
/🆑

* Fixes recharge stations charge rates (#82191)

## About The Pull Request
- Fixes #82190

Have to now use the assigned constants and not magic number `10000`.
Also stuff will take the exact charge needed without any wastage.

## Changelog
🆑
fix: recharge stations draw the same amount of power as before but
directly from grid(without using apc cell power) and won't waste any
excess power
/🆑

---------

Co-authored-by: san7890 <the@san7890.com>

* Fixes space heater power usage (#82208)

## About The Pull Request

Related to https://github.com/tgstation/tgstation/issues/82196 fixes the
space heater power cell usage relating to power per tile heated.

Space heater calculates the amount of power required to heat a tile, but
only uses power at the end of the processing loop. Fixes so the power
consumption matches the calculated usage per tile.

Reverts changes to space heater power efficiency in
https://github.com/tgstation/tgstation/pull/82197 that causes the heater
to instantly drain the cell.

Fixes https://github.com/tgstation/tgstation/issues/82228

## Changelog

🆑 LT3
fix: Fixes Schrödinger's space heater, where a space heater both
consumes a power cell instantly while also not consuming power when
heating adjacent tiles
/🆑

* General maintenance for reagent grinder (#82161)

## About The Pull Request

**1. Qol**
  - Adds examines & screentips for screwdriver, crowbar & wrench acts.
- Adds examines & screentips for inserting, replacing & removing beaker,
Also for inserting items from bags or directly
- Adds an off icon overlay for when the reagent grinder is either
screwed open or loses power,
 
**2. Code Improvements**
- Replaced `attackby()` with `item_interaction()` so we can end the
attack chain early for non combat operations like inserting beakers/
ingredients for grinding etc.
- Removed custom shake animations & replaced it with the global
`Shake()` proc cause it did the same thing
- Removed constructed version of reagent grinder. We instead just check
`mapload` to see if we need the beaker to be created or not for round
start reagent grinders
- Grinding & Juicing use the same `operate_for()` rather than having
seperate procs for each operation
- Removed trait `TRAIT_MAY_CONTAIN_BLENDED_DUST`. Why do we have this?
Its just used to change the grinder description to warn it may contain
dust. It's a waste.
  
**3. Fixes**
- You cannot insert hologram items into the grinder. Rather than
destroying that item & making it vanish you simply won't be allowed to
put it inside the grinder so you can save that item
- You can hit the grinder with items like screwdriver, wrench, crowbar,
beaker & even with stuff you would normally put in the grinder when in
combat mode
  - Adds `can_interact()` checks for using the UI & other stuff 
- Fixes #46356. All items of type `obj/item/grown` can be put from any
bag into the grinder
- The item "and its contents" are now grinded/juiced recursively to get
all the reagents it has to offer just like a real grinder would
- An AI/Human with AI access examining the reagent grinder now actually
works.
 
**4. Refactors**
- The grinder now measures its available capacity based on the "total
weight" of all items present & not its number. This is more realistic
because the grinder has limited space inside & so inserting huge items
should have greater impact rather than deciding on an arbitrary number
like 10(The grinder having the capacity for 10 items of any size inside
its small compartment makes no sense). Examines are displayed to show
how much capacity of the grinder has been filled. Upgrading the grinder
with better matter bins will allow for higher storage capacities.
- Total power consumed is measured based on the duration & weight of all
items grinded cause you know its realistic.


🆑
qol: adds examines & screentips for tool acts & other operations for
reagent grinder
qol: adds an off icon for when the grinder panel is open/not powered
code: auto docs vars & procs. Shared common proc for grinding or juicing
code: removed trait for blended dust, changed some item interactions to
end the attack chain early & save time
fix: no inserting hologram items into the reagent grinder
fix: you can hit the reagent grinder tools like screwdriver, wrench,
crowbar & even beakers/ingredients etc when in combat mode
fix; adds sanity checks for when & how mobs interact with the reagent
grinder
fix: examining a reagent grinder by an AI/Human with AI access now
actually works.
fix: you can insert Nova flowers & other food items from any bag type
fix: reagent grinder now grinds all the contents of an item recursively
to produce maximum reagents like a real grinder would
refactor: reagent grinder now measures available capacity to store items
as total weight of stored items & not number. Capacity can be increased
with upgraded matter bin
refactor: reagent grinder power usage is now a function of duration &
total weight of items blended, meaining blending more number of
items/larger items will consume more power
refactor: reagent grinder code has been optimized overall. Report bugs
on github
/🆑

---------

Co-authored-by: Timberpoes <silent_insomnia_pp@hotmail.co.uk>

* Suit Storage Units / Inducers can charge MODsuits without necessitating them be screwdrivered opened  (#82194)

## About The Pull Request

So MODsuits do this thing here with `get_cell` in that they don't return
anything when they're closed


![image](https://github.com/tgstation/tgstation/assets/51863163/416f8ef5-3bfc-4d2c-a12f-029f051d6692)

And I... can't tell why they do this. 

I looked through every use of `get_cell` and the only things affected by
this are
A. Suit Storage Units, which I believe have always been intended to
charge MODsuits?
and
B. Inducers

So I removed the `open` check. Allowing both Inducers and Suit Storage
Units to charge mods without needing you screwdriver their panel open
first.

I also took the opportunity to allow SSUs to charge multiple items at
once (divvying charge accross all items)

## Why It's Good For The Game

I asked Fikou and they said it was "probably not" intended that you need
to screwdriver them open so yeah.

I think I remember charging my MODs during the original test merges
years back but I can't remember if I opened the suit first when I did or
not.

Either way, it's not super intuitive. Though it's already not very
intuitive that SSUs charge things.

## Changelog

🆑 Melbert
qol: Suit Storage Units charge MODsuits while their cell panel is closed
or open, rather than only when screwed open
qol: Inducers can charge MODsuits while their cell panel is closed or
open, rather than only when screwed open
qol: Suit Storage Units will charge all items within simultaneously (if
possible)
/🆑

---------

Co-authored-by: san7890 <the@san7890.com>

* Fixes modular computer boot-up (#82254)

## About The Pull Request

Fixes a bug where modular computers (specifically PDAs) will fail to
start up if there is zero required application power draw.

PDA will now consume base active power usage during startup.

Related https://github.com/tgstation/tgstation/issues/82196
Fixes https://github.com/tgstation/tgstation/issues/82245
Fixes https://github.com/tgstation/tgstation/issues/82229

## Changelog

🆑 LT3
fix: Fixed modular computers failing to boot up using cell power (eg:
contractor tablet)
/🆑

* Fixing cell power usage (Part 4) (#82227)

## About The Pull Request
Continuation of #82204

Fixes these issues in #82196
- Cyborg Electroadaptive Pseudocircuit
- Defib EMP
- Cell EMP
- `/datum/action/cooldown/mob_cooldown/charge_apc` stuff
- Mecha movement, melee, light ,weapon & tool energy drains
- Ninja drain

## Changelog
🆑
fix: Fixed more energy usages for cells(Part 4). See PR 82227 for
details
/🆑

---------

Co-authored-by: Pickle-Coding <58013024+Pickle-Coding@users.noreply.github.com>

* Fixing cell power usage (Part 5) (#82296)

## About The Pull Request
Continuation of #82227

Fixes these issues in
https://github.com/tgstation/tgstation/issues/82196 and others that
weren't noticed.
- Batton emp protection
- Cyborg stun arm
- Cyborg energy sword
- Cyborg hug attack
- Mechanical god religious sect charge check
- Mecha fixes
  - Phasing energy drain
  - Short circuit energy drain
  - Durand shield damage energy drain
  - Plasma engine recharge rate
- Mechbay recharge power rate
- Recharge station charge rate

Stuff that was already working & didn't require fixing.
- Plasma cutter energy shots
- Botany cell charging

## Changelog
🆑
fix: Fixed cell energy usage for a bunch of stuff(Part 5). See PR 82296
for details
/🆑

---------

Co-authored-by: Pickle-Coding <58013024+Pickle-Coding@users.noreply.github.com>

* Ties power limit of anchored circuits to 20 * standard cell charge to make it consistent with power changes. (#82287)

## About The Pull Request
It just makes the power requirement 20 * standard cell charge instead of
20000
## Why It's Good For The Game
This is too restrictive to make anything with.



https://github.com/tgstation/tgstation/assets/62126254/e39dcf27-8793-42b0-84a0-7f747e95efcc
## Changelog
🆑
fix: anchored circuits no longer blow up after 2 components are used.
/🆑

---------

Co-authored-by: Pickle-Coding <58013024+Pickle-Coding@users.noreply.github.com>

* Space heater power and heating tweaks (#82344)

## About The Pull Request
- Fixes #82342
- Space heater computes total power for heating adjacent turfs and uses
cell energy once rather multiple times per turf
- Improvised space heater actually works & uses beaker heat capacity and
not a constant of 200 for heating beaker contents

## Changelog 
🆑 SyncIt21,Pickle-Coding
fix: space heater(including improvised) turns off when cell is drained
fix: optimized power usage for both improvised and main space heater.
Improvised heater now works & uses beaker heat capacity
/🆑

* Improved lathe error message (#82260)

## About The Pull Request

Improves the auto/protolathe low charge error message. Instead of simply
saying low power, it will tell you how long until it has enough charge
to print.


![image](https://github.com/tgstation/tgstation/assets/83487515/a2aebd3e-b7bf-4a13-ae7a-6c1cc14c9057)

## Why It's Good For The Game

Less mashing the lathe over and over with no idea how much APC charge it
needs to start printing again

## Changelog

🆑 LT3
code: APCs can now calculate time-to-charge
qol: Overloaded lathes will now tell you the wait time until they're
ready to print again
/🆑

---------

Co-authored-by: san7890 <the@san7890.com>

* Fixes issues with multitools on power objects (#82389)

## About The Pull Request

So at some point the power object's `multitool_act(...)` proc was set to
_always_ block, for what I could find to be no discernable reason.

### The Main Thing


d38f9385b8/code/modules/power/power.dm (L62-L74)
Now, of course, it shouldn't, because this cuts the entire chain short
and thus blocks any other multitool interactions. Like opening the wires
panel with a multitool, in this case. Even if `can_change_cable_layer`
were to be false and thus the object would never actually care about
having this interaction, it'd _still_ block it.

So we don't do that. But what _do_ we do?
I decided to just split off the actual cable changing part into its own
proc, `cable_layer_act(...)`.
```dm
/obj/machinery/power/proc/cable_layer_act(mob/living/user, obj/item/tool)
	var/choice = tgui_input_list(user, "Select Power Line For Operation", "Select Cable Layer", GLOB.cable_name_to_layer)
	if(isnull(choice))
		return ITEM_INTERACT_BLOCKING

	cable_layer = GLOB.cable_name_to_layer[choice]
	balloon_alert(user, "now operating on the [choice]")
	return ITEM_INTERACT_SUCCESS
```
Which is then called on `multitool_act(...)`, if
`can_change_cable_layer` is true.
```dm
/obj/machinery/power/multitool_act(mob/living/user, obj/item/tool)
	if(can_change_cable_layer)
		return cable_layer_act(user, tool)
```
Which continues with the chain if we can't change layers by default, and
otherwise lets `cable_layer_act(...)` work out whether we should block
or continue.
Notably, we've removed the `cable_layer_change_checks(...)` proc from
the equation, and just let inheritors override it to add their own
preconditions and what flags they should return.
On its own this fixes the APC wire panel interactions, but also lets us
just return `NONE` when we need to.
```dm
/obj/machinery/power/emitter/cable_layer_act(mob/living/user, obj/item/tool)
	if(panel_open)
		return NONE
	if(welded)
		balloon_alert(user, "unweld first!")
		return ITEM_INTERACT_BLOCKING
	return ..()
```

### The OTHER Things

While doing this I noticed there's actually very little sanity checks
after we close our input list.
```dm
var/choice = tgui_input_list(user, "Select Power Line For Operation", "Select Cable Layer", GLOB.cable_name_to_layer)
if(isnull(choice))
	return ITEM_INTERACT_BLOCKING
```
We only care about whether we made a choice!
Testing this, lo and behold, this can cause runtimes if the power object
gets qdeleted before you close the menu.
As a funny side, it _also_ doesn't care about whether you're on the
other side of the station, while your multitool is on a different
z-level, or just doesn't exist anymore.
So we just add a few basic sanity checks while we're at it.
```dm
var/choice = tgui_input_list(user, "Select Power Line For Operation", "Select Cable Layer", GLOB.cable_name_to_layer)
if(isnull(choice) || QDELETED(src) || QDELETED(user) || QDELETED(tool) || !user.Adjacent(src) || !user.is_holding(tool))
	return ITEM_INTERACT_BLOCKING
```
That's all. Having done some basic testing, I believe the behaviour is
otherwise unaffected.
## Why It's Good For The Game

It's annoying to need to swap to an empty hand or wirecutters to
interact with APC, emitter, or tesla coil wires.
This fixes that. (Fixes #81745.)
...and then a few other tidbits I realized existed.
## Changelog
🆑
fix: Fix using a multitool on a power object with wires not actually
opening the wires menu when it should.
fix: Fix a runtime from a power object being deleted before selecting
what cable layer to put it at.
fix: Fix power object cable changing not caring about whether you were
still adjacent, still holding your multitool, or whether it even still
existed after the selection menu was closed.
/🆑

* Updates cyborg cells created from borgifier to the SI standard (#82437)

## About The Pull Request

Unchanged value in transformer.dm resulted in borg charge draining to
zero immediately after forced conversion in the borgifer. Changing the
value of robot cell charge to 5 MJs to fix this.
## Why It's Good For The Game

Fixes #82426
## Changelog
🆑
fix: changed value of cell charge from 5000 to 5 megajoules
/🆑

* cell chargers now bypass APCs (#82309)

## About The Pull Request
This makes cell chargers and suit storage units draw from the grid
before the local apc

## Why It's Good For The Game
Upgraded Cell chargers have a charging power of 1MW leading to them
instantly draining the apc of any room they are in,
this Pr makes them draw from the grid preventing immediate blackout. 
This is a stopgap until someone smarter than me changes power values so
a pocket-sized battery won't require the same power to charge then over
600 average suburban homes.

## Changelog
🆑
balance: suit and cell chargers should draw from grid preventing instant
apc blackouts in most cases.
/🆑

* Let ethereals starve again (#82308)

## About The Pull Request

Ethereals use energy as 'food', so of course #81579 had to touch them.
To bring them in line with the new standard, the Ethereal charge levels
were updated to be in megajoules.

466b3df048/code/__DEFINES/mobs.dm (L292-L299)

7fa8daad63/code/__DEFINES/mobs.dm (L285-L292)
However! This forgot to update the rate at which Ethereals passively
discharge.

7fa8daad63/code/modules/surgery/organs/internal/stomach/stomach_ethereal.dm (L11-L14)

7fa8daad63/code/__DEFINES/mobs.dm (L437)
Meaning it's effectively a thousand times less with the new charge
levels.

So we simply update this define to be in kilowatts.
```dm
#define ETHEREAL_CHARGE_FACTOR (0.8 KILO WATTS) //factor at which ethereal's charge decreases per second
```
## Why It's Good For The Game

Fixes issue with ethereal hunger caused by #81579.
## Changelog
🆑
fix: Ethereal starvation has been updated to the new joules/watts
standard. Congratulations Ethereals! You can starve again!
/🆑

* [NO GBP]Fixes ethereal charging and recharge station charge speed. (#82483)

## About The Pull Request
Fixes many instances of things not charging ethereals properly. Scales
all things that are meant for charging/taking from the ethereal stomach
by STANDARD_CELL_CHARGE, so we never run into this issue again. Ethereal
stomachs now store a cell inside them, and uses that for the charge
instead of tracking a variable. Fixes recharging stations not being able
to charge ethereal stomachs. The ethereal signal proc attempted to feed
a callback datum to adjust_charge(), which caused a runtime. Changes
that by invoking the charge_cell callback instead.

Also fixes recharge station charging speed. They weren't converted
correctly. Also formats their charging speed in their description, and
displays power rather than referencing cycles.
## Why It's Good For The Game
So ethereals charge properly.

Closes #82470
## Changelog
🆑
fix: Fixes many instances of energy sources for ethereals supplying a
thousand times less energy than intended.
fix: Fixes recharging stations not being able to charge ethereals.
fix: Fixes recharge stations charging too fast.
qol: Recharge stations display their recharging speed in formatted
power, rather than unformatted energy per cycle.
/🆑

---------

Co-authored-by: san7890 <the@san7890.com>

* Update lead acid batteries charge values (#82510)

## About The Pull Request

So during the whole power consistency update thing, it seems lead acid
batteries were entirely forgotten about.
Which, well, is easy, because they never actually used
`STANDARD_CELL_CHARGE`.

c34d56a45b/code/game/objects/items/maintenance_loot.dm (L32-L33)
Looking into it, the previous value for `STANDARD_CELL_CHARGE` seemed to
have been 1000, so we convert it directly:
```dm
maxcharge = STANDARD_CELL_CHARGE * 20
chargerate = STANDARD_CELL_CHARGE * 1.4
```
But, comparing this to the normal power cells, it seems their charge
rates got _halved_ during the update.
So, we do that too.
```dm
maxcharge = STANDARD_CELL_CHARGE * 20
chargerate = STANDARD_CELL_CHARGE * 0.7
```
And that fixes it.
## Why It's Good For The Game

Fixes lead acid batteries still using the old power amounts, and not
being relative to `STANDARD_CELL_CHARGE`.
## Changelog
🆑
fix: Lead acid batteries have had their power values fixed.
/🆑

* This should do for modular code, for now.

* Fixing cell power usage (Part 5) (#82296)

Continuation of #82227

Fixes these issues in
https://github.com/tgstation/tgstation/issues/82196 and others that
weren't noticed.
- Batton emp protection
- Cyborg stun arm
- Cyborg energy sword
- Cyborg hug attack
- Mechanical god religious sect charge check
- Mecha fixes
  - Phasing energy drain
  - Short circuit energy drain
  - Durand shield damage energy drain
  - Plasma engine recharge rate
- Mechbay recharge power rate
- Recharge station charge rate

Stuff that was already working & didn't require fixing.
- Plasma cutter energy shots
- Botany cell charging

🆑
fix: Fixed cell energy usage for a bunch of stuff(Part 5). See PR 82296
for details
/🆑

---------

Co-authored-by: Pickle-Coding <58013024+Pickle-Coding@users.noreply.github.com>

* [NO GBP]Fixes some mapped SMES starting with low energy. (#82203)

## About The Pull Request
Scales them all by up to 20 to account for removing the dumb SMESRATE
define. This isn't a 100% conversion for every SMES because it would go
beyond their capacity (old SMES use to duplicate cell energy, so they
had a higher capacity than their cell parts imply). Also removes
instances of varediting their capacity to fucking 1e+600 and replaces
them with magical SMES.
## Why It's Good For The Game
So lavaland and crap don't instantly run out of power. Also I don't
think we should be varediting anything to 1e+600.
## Changelog
🆑
fix: Fixes lavaland SMES and other crap from not starting with enough
energy.
fix: The pirate SMES are now magical instead of secretly infinite.
/🆑

* Mechbay & modsuit recharger tweaks (#82337)

## About The Pull Request
- Both mechbay & modsuit rechargers now waste a small amount of energy
as heat like it did before
- Fixes #82332. Mechbay recharger displays the energy of the mech in
joules & charges the cell with the exact energy required directly from
the grid thus not causing the room to blackout

## Changelog
🆑
fix: Mechbay & modsuit rechargers waste a small amount of energy as heat
fix: Mechbay recharger console displays mech charge as joules & charges
directly from the grid thus sparing the rooms apc cell from huge loads
/🆑

* Refactor APCs interaction chain from attackby to item_interaction (#82390)

## About The Pull Request

For how many lines this is, there's not a lot to really say.
In general, we simply move all item interactions from `attackby(...)` to
`item_interaction(...)`, split each item interaction off into a separate
proc, and make them all return the proper item interaction flags.
We _do_ kill some probably dead code, and remove a call to
`attackby(...)` elsewhere. Then, for clarity, we move the cell check
below the ID check so it can be next to the other item type checks, as
the priority between cell and ID is unlikely to matter anyway.
Other than what's described above and detailed below, each section's
functionality should be the same.

Now, for the parts that _do_ need to be explained more.

### Killing Probably Dead Code

Alright, so, the first part that does not have the cleanest transition.

d38f9385b8/code/modules/power/apc/apc_attack.dm (L22-L23)
Whatever the fuck this is.

Asking around, this seems to just be dead code.
For sanity's sake removing it and testing, silicon interactions with it
seem to work just fine.
So we kill it. We just kill it. We Just Kill It.

Closest we could find requires the distance check there to be false, so
it wouldn't apply. But it _does_ bring us to the second bit of weird
code.

### Calling APC Attackby Elsewhere?
So wallframes let you screwdriver them to put them up, which from a
comment seems to be because of cyborgs.
APC wallframes of course override this with their own implementation,
that allows you to also replace a damaged cover or frame like that!

d38f9385b8/code/game/objects/items/apc_frame.dm (L29-L39)
...By just calling the wholeass `attackby(...)` proc on the APC and
calling it a day.

But hey, this is where our previous splitting up comes in handy, because
we just have a `wallframe_act(...)` proc!
So we just call that instead.
```dm
var/obj/machinery/power/apc/mounted_apc = locate(/obj/machinery/power/apc) in get_turf(user)
mounted_apc.wallframe_act(user, src)
return ITEM_INTERACT_SUCCESS
```
...And not use single letter variables, while we're at it.

That should be all.
Remember to get snacks and drinks.
## Why It's Good For The Game

Split off 178 line `attackby(...)` item interaction chain into separate
procs called in `item_interaction(...)`.
Screwdrivering APC wallframes no longer calls the wholeass
`attackby(...)` on the APC, but just call the new sub-proc for the
specific interaction it cares about.
## Changelog
🆑
refactor: APCs have had their item interaction chain refactored. This
should functionally be the same, but please report any issues.
/🆑

* [NO GBP]Cells will only consider 0.1% of their charge when shocking a user. (#82456)

## About The Pull Request
Makes cells only consider 0.1% of their charge when calculating the
damage for shocking someone. This makes the minimum damage 20, and goes
up to 22 (previous behaviour, even though that's a shockingly small
difference) with a 50 MJ cell, which is the highest capacity crew can
get. This makes it inversely scale with the standard cell charge define,
so if that gets changed, cells will use a different composition of their
charge to consider.

## Why It's Good For The Game

Airlocks instantly critting people when shocked regardless of what's in
the grid wasn't previous behaviour.

* Oops. There we go.

* Oh, these two too.

---------

Co-authored-by: Pickle-Coding <58013024+Pickle-Coding@users.noreply.github.com>
Co-authored-by: SyncIt21 <110812394+SyncIt21@users.noreply.github.com>
Co-authored-by: Ghom <42542238+Ghommie@users.noreply.github.com>
Co-authored-by: MrMelbert <51863163+MrMelbert@users.noreply.github.com>
Co-authored-by: san7890 <the@san7890.com>
Co-authored-by: lessthanthree <83487515+lessthnthree@users.noreply.github.com>
Co-authored-by: Timberpoes <silent_insomnia_pp@hotmail.co.uk>
Co-authored-by: moocowswag <62126254+moocowswag@users.noreply.github.com>
Co-authored-by: _0Steven <42909981+00-Steven@users.noreply.github.com>
Co-authored-by: Archie700 <archie712@hotmail.com>
Co-authored-by: Blacklist897 <149209377+Blacklist897@users.noreply.github.com>
2024-04-12 06:33:40 +02:00

976 lines
34 KiB
Plaintext

// This is the base type of computer
// Other types expand it - tablets and laptops are subtypes
// consoles use "procssor" item that is held inside it.
/obj/item/modular_computer
name = "modular microcomputer"
desc = "A small portable microcomputer."
icon = 'icons/obj/machines/computer.dmi'
icon_state = "laptop"
light_on = FALSE
light_power = 1.2
integrity_failure = 0.5
max_integrity = 100
armor_type = /datum/armor/item_modular_computer
light_system = OVERLAY_LIGHT_DIRECTIONAL
///The ID currently stored in the computer.
var/obj/item/card/id/computer_id_slot
///The disk in this PDA. If set, this will be inserted on Initialize.
var/obj/item/computer_disk/inserted_disk
///The power cell the computer uses to run on.
var/obj/item/stock_parts/cell/internal_cell = /obj/item/stock_parts/cell
///A pAI currently loaded into the modular computer.
var/obj/item/pai_card/inserted_pai
///Does the console update the crew manifest when the ID is removed?
var/crew_manifest_update = FALSE
///The amount of storage space the computer starts with.
var/max_capacity = 128
///The amount of storage space we've got filled
var/used_capacity = 0
///List of stored files on this drive. Use `store_file` and `remove_file` instead of modifying directly!
var/list/datum/computer_file/stored_files = list()
///Non-static list of programs the computer should receive on Initialize.
var/list/datum/computer_file/starting_programs = list()
///Static list of default programs that come with ALL computers, here so computers don't have to repeat this.
var/static/list/datum/computer_file/default_programs = list(
/datum/computer_file/program/themeify,
/datum/computer_file/program/ntnetdownload,
/datum/computer_file/program/filemanager,
)
///The program currently active on the tablet.
var/datum/computer_file/program/active_program
///Idle programs on background. They still receive process calls but can't be interacted with.
var/list/datum/computer_file/program/idle_threads = list()
/// Amount of programs that can be ran at once
var/max_idle_programs = 2
///Flag of the type of device the modular computer is, deciding what types of apps it can run.
var/hardware_flag = PROGRAM_ALL
// Options: PROGRAM_ALL | PROGRAM_CONSOLE | PROGRAM_LAPTOP | PROGRAM_PDA
///The theme, used for the main menu and file browser apps.
var/device_theme = PDA_THEME_NTOS
///Bool on whether the computer is currently active or not.
var/enabled = FALSE
///If the screen is open, only used by laptops.
var/screen_on = TRUE
///Looping sound for when the computer is on.
var/datum/looping_sound/computer/soundloop
///Whether or not this modular computer uses the looping sound
var/looping_sound = TRUE
///If the computer has a flashlight/LED light built-in.
var/has_light = FALSE
/// If the computer's flashlight/LED light has forcibly disabled for a temporary amount of time.
COOLDOWN_DECLARE(disabled_time)
/// How far the computer's light can reach, is not editable by players.
var/comp_light_luminosity = 3
/// The built-in light's color, editable by players.
var/comp_light_color = COLOR_WHITE
///Power usage when the computer is open (screen is active) and can be interacted with.
var/base_active_power_usage = 15 // SKYRAT EDIT CHANGE - Original: 125
///Power usage when the computer is idle and screen is off.
var/base_idle_power_usage = 2 // SKYRAT EDIT CHANGE - Original: 5
// Modular computers can run on various devices. Each DEVICE (Laptop, Console & Tablet)
// must have it's own DMI file. Icon states must be called exactly the same in all files, but may look differently
// If you create a program which is limited to Laptops and Consoles you don't have to add it's icon_state overlay for Tablets too, for example.
///If set, what the icon_state will be if the computer is unpowered.
var/icon_state_unpowered
///If set, what the icon_state will be if the computer is powered.
var/icon_state_powered
///Icon state overlay when the computer is turned on, but no program is loaded (programs override this).
var/icon_state_menu = "menu"
///The full name of the stored ID card's identity. These vars should probably be on the PDA.
var/saved_identification
///The job title of the stored ID card
var/saved_job
///The 'computer' itself, as an obj. Primarily used for Adjacent() and UI visibility checks, especially for computers.
var/obj/physical
///Amount of steel sheets refunded when disassembling an empty frame of this computer.
var/steel_sheet_cost = 5
///If hit by a Clown virus, remaining honks left until it stops.
var/honkvirus_amount = 0
///Whether the PDA can still use NTNet while out of NTNet's reach.
var/long_ranged = FALSE
/// Allow people with chunky fingers to use?
var/allow_chunky = FALSE
///The amount of paper currently stored in the PDA
var/stored_paper = 10
///The max amount of paper that can be held at once.
var/max_paper = 30
/// The capacity of the circuit shell component of this item
var/shell_capacity = SHELL_CAPACITY_MEDIUM
/**
* Reference to the circuit shell component, because we're special and do special things with it,
* such as creating and deleting unremovable circuit comps based on the programs installed.
*/
var/datum/component/shell/shell
/datum/armor/item_modular_computer
bullet = 20
laser = 20
energy = 100
/obj/item/modular_computer/Initialize(mapload)
. = ..()
START_PROCESSING(SSobj, src)
if(!physical)
physical = src
add_shell_component(shell_capacity)
set_light_color(comp_light_color)
set_light_range(comp_light_luminosity)
if(looping_sound)
soundloop = new(src, enabled)
UpdateDisplay()
if(has_light)
add_item_action(/datum/action/item_action/toggle_computer_light)
RegisterSignal(src, COMSIG_HIT_BY_SABOTEUR, PROC_REF(on_saboteur))
if(inserted_disk)
inserted_disk = new inserted_disk(src)
if(internal_cell)
internal_cell = new internal_cell(src)
install_default_programs()
register_context()
update_appearance()
///Initialize the shell for this item, or the physical machinery it belongs to.
/obj/item/modular_computer/proc/add_shell_component(capacity = SHELL_CAPACITY_MEDIUM, shell_flags = NONE)
shell = physical.AddComponent(/datum/component/shell, list(new /obj/item/circuit_component/modpc), capacity, shell_flags)
RegisterSignal(shell, COMSIG_SHELL_CIRCUIT_ATTACHED, PROC_REF(on_circuit_attached))
RegisterSignal(shell, COMSIG_SHELL_CIRCUIT_REMOVED, PROC_REF(on_circuit_removed))
/obj/item/modular_computer/proc/on_circuit_attached(datum/source)
SIGNAL_HANDLER
RegisterSignal(shell.attached_circuit, COMSIG_CIRCUIT_PRE_POWER_USAGE, PROC_REF(use_energy_for_circuits))
///Try to draw power from our internal cell first, before switching to that of the circuit.
/obj/item/modular_computer/proc/use_energy_for_circuits(datum/source, energy_usage_per_input)
SIGNAL_HANDLER
if(use_energy(energy_usage_per_input, check_programs = FALSE))
return COMPONENT_OVERRIDE_POWER_USAGE
/obj/item/modular_computer/proc/on_circuit_removed(datum/source)
SIGNAL_HANDLER
UnregisterSignal(shell.attached_circuit, COMSIG_CIRCUIT_PRE_POWER_USAGE)
/obj/item/modular_computer/proc/install_default_programs()
SHOULD_CALL_PARENT(FALSE)
for(var/programs in default_programs + starting_programs)
var/datum/computer_file/program_type = new programs
store_file(program_type)
/obj/item/modular_computer/Destroy()
STOP_PROCESSING(SSobj, src)
close_all_programs()
//Some components will actually try and interact with this, so let's do it later
QDEL_NULL(soundloop)
looping_sound = FALSE // Necessary to stop a possible runtime trying to call soundloop.stop() when soundloop has been qdel'd
QDEL_LIST(stored_files)
if(istype(inserted_disk))
QDEL_NULL(inserted_disk)
if(istype(inserted_pai))
QDEL_NULL(inserted_pai)
if(computer_id_slot)
QDEL_NULL(computer_id_slot)
shell = null
physical = null
return ..()
/obj/item/modular_computer/pre_attack_secondary(atom/A, mob/living/user, params)
if(active_program?.tap(A, user, params))
user.do_attack_animation(A) //Emulate this animation since we kill the attack in three lines
playsound(loc, 'sound/weapons/tap.ogg', get_clamped_volume(), TRUE, -1) //Likewise for the tap sound
addtimer(CALLBACK(src, PROC_REF(play_ping)), 0.5 SECONDS, TIMER_UNIQUE) //Slightly delayed ping to indicate success
return SECONDARY_ATTACK_CANCEL_ATTACK_CHAIN
return ..()
// shameless copy of newscaster photo saving
/obj/item/modular_computer/proc/save_photo(icon/photo)
var/photo_file = copytext_char(md5("\icon[photo]"), 1, 6)
if(!fexists("[GLOB.log_directory]/photos/[photo_file].png"))
//Clean up repeated frames
var/icon/clean = new /icon()
clean.Insert(photo, "", SOUTH, 1, 0)
fcopy(clean, "[GLOB.log_directory]/photos/[photo_file].png")
return photo_file
/**
* Plays a ping sound.
*
* Timers runtime if you try to make them call playsound. Yep.
*/
/obj/item/modular_computer/proc/play_ping()
playsound(loc, 'sound/machines/ping.ogg', get_clamped_volume(), FALSE, -1)
/obj/item/modular_computer/get_cell()
return internal_cell
/obj/item/modular_computer/AltClick(mob/user)
. = ..()
if(issilicon(user))
return FALSE
if(!user.can_perform_action(src))
return FALSE
if(RemoveID(user))
return TRUE
if(istype(inserted_pai)) // Remove pAI
remove_pai(user)
return TRUE
// Gets IDs/access levels from card slot. Would be useful when/if PDAs would become modular PCs. //guess what
/obj/item/modular_computer/GetAccess()
if(computer_id_slot)
return computer_id_slot.GetAccess()
return ..()
/obj/item/modular_computer/GetID()
if(computer_id_slot)
return computer_id_slot
return ..()
/obj/item/modular_computer/get_id_examine_strings(mob/user)
. = ..()
if(computer_id_slot)
. += "\The [src] is displaying [computer_id_slot]."
. += computer_id_slot.get_id_examine_strings(user)
/obj/item/modular_computer/proc/print_text(text_to_print, paper_title = "")
if(!stored_paper)
return FALSE
var/obj/item/paper/printed_paper = new /obj/item/paper(drop_location())
printed_paper.add_raw_text(text_to_print)
if(paper_title)
printed_paper.name = paper_title
printed_paper.update_appearance()
stored_paper--
return TRUE
/**
* InsertID
* Attempt to insert the ID in either card slot, if ID is present - attempts swap
* Args:
* inserting_id - the ID being inserted
* user - The person inserting the ID
*/
/obj/item/modular_computer/InsertID(obj/item/card/inserting_id, mob/user)
if(!isnull(user) && !user.transferItemToLoc(inserting_id, src))
return FALSE
else
inserting_id.forceMove(src)
if(!isnull(computer_id_slot))
RemoveID(user, silent = TRUE)
computer_id_slot = inserting_id
if(!isnull(user))
to_chat(user, span_notice("You insert \the [inserting_id] into the card slot."))
balloon_alert(user, "inserted ID")
playsound(src, 'sound/machines/terminal_insert_disc.ogg', 50, FALSE)
if(ishuman(loc))
var/mob/living/carbon/human/human_wearer = loc
if(human_wearer.wear_id == src)
human_wearer.sec_hud_set_ID()
update_appearance()
update_slot_icon()
SEND_SIGNAL(src, COMSIG_MODULAR_COMPUTER_INSERTED_ID, inserting_id, user)
return TRUE
/**
* Removes the ID card from the computer, and puts it in loc's hand if it's a mob
* Args:
* user - The mob trying to remove the ID, if there is one
* silent - Boolean, determines whether fluff text would be printed
*/
/obj/item/modular_computer/RemoveID(mob/user, silent = FALSE)
if(!computer_id_slot)
return ..()
if(crew_manifest_update)
GLOB.manifest.modify(computer_id_slot.registered_name, computer_id_slot.assignment, computer_id_slot.get_trim_assignment())
if(user && !issilicon(user) && in_range(src, user))
user.put_in_hands(computer_id_slot)
else
computer_id_slot.forceMove(drop_location())
computer_id_slot = null
if(!silent && !isnull(user))
to_chat(user, span_notice("You remove the card from the card slot."))
playsound(src, 'sound/machines/terminal_insert_disc.ogg', 50, FALSE)
balloon_alert(user, "removed ID")
if(ishuman(loc))
var/mob/living/carbon/human/human_wearer = loc
if(human_wearer.wear_id == src)
human_wearer.sec_hud_set_ID()
update_slot_icon()
update_appearance()
return TRUE
/obj/item/modular_computer/MouseDrop(obj/over_object, src_location, over_location)
var/mob/M = usr
if((!istype(over_object, /atom/movable/screen)) && usr.can_perform_action(src))
return attack_self(M)
return ..()
/obj/item/modular_computer/attack_ai(mob/user)
return attack_self(user)
/obj/item/modular_computer/attack_ghost(mob/dead/observer/user)
. = ..()
if(.)
return
if(enabled)
ui_interact(user)
else if(isAdminGhostAI(user))
var/response = tgui_alert(user, "This computer is turned off. Would you like to turn it on?", "Admin Override", list("Yes", "No"))
if(response == "Yes")
turn_on(user)
/obj/item/modular_computer/emag_act(mob/user, obj/item/card/emag/emag_card, forced)
if(!enabled && !forced)
balloon_alert(user, "turn it on first!")
return FALSE
if(obj_flags & EMAGGED)
balloon_alert(user, "already emagged!")
if (emag_card)
to_chat(user, span_notice("You swipe \the [src] with [emag_card]. A console window fills the screen, but it quickly closes itself after only a few lines are written to it."))
return FALSE
. = ..()
if(!forced)
add_log("manual overriding of permissions and modification of device firmware detected. Reboot and reinstall required.")
obj_flags |= EMAGGED
device_theme = PDA_THEME_SYNDICATE
if(user)
balloon_alert(user, "syndieOS loaded")
if (emag_card)
to_chat(user, span_notice("You swipe \the [src] with [emag_card]. A console window momentarily fills the screen, with white text rapidly scrolling past."))
return TRUE
/obj/item/modular_computer/examine(mob/user)
. = ..()
var/healthpercent = round((atom_integrity/max_integrity) * 100, 1)
switch(healthpercent)
if(50 to 99)
. += span_info("It looks slightly damaged.")
if(25 to 50)
. += span_info("It appears heavily damaged.")
if(0 to 25)
. += span_warning("It's falling apart!")
if(long_ranged)
. += "It is upgraded with an experimental long-ranged network capabilities, picking up NTNet frequencies while further away."
. += span_notice("It has [max_capacity] GQ of storage capacity.")
if(computer_id_slot)
if(Adjacent(user))
. += "It has \the [computer_id_slot] card installed in its card slot."
else
. += "Its identification card slot is currently occupied."
. += span_info("Alt-click [src] to eject the identification card.")
/obj/item/modular_computer/examine_more(mob/user)
. = ..()
. += "Storage capacity: [used_capacity]/[max_capacity]GQ"
for(var/datum/computer_file/app_examine as anything in stored_files)
if(app_examine.on_examine(src, user))
. += app_examine.on_examine(src, user)
if(Adjacent(user))
. += span_notice("Paper level: [stored_paper] / [max_paper].")
/obj/item/modular_computer/add_context(atom/source, list/context, obj/item/held_item, mob/living/user)
. = ..()
if(computer_id_slot && isidcard(held_item))
context[SCREENTIP_CONTEXT_LMB] = "Swap ID"
. = CONTEXTUAL_SCREENTIP_SET
if(held_item?.tool_behaviour == TOOL_SCREWDRIVER && internal_cell)
context[SCREENTIP_CONTEXT_RMB] = "Remove Cell"
. = CONTEXTUAL_SCREENTIP_SET
if(held_item?.tool_behaviour == TOOL_WRENCH)
context[SCREENTIP_CONTEXT_RMB] = "Deconstruct"
. = CONTEXTUAL_SCREENTIP_SET
if(computer_id_slot) // ID get removed first before pAIs
context[SCREENTIP_CONTEXT_ALT_LMB] = "Remove ID"
. = CONTEXTUAL_SCREENTIP_SET
else if(inserted_pai)
context[SCREENTIP_CONTEXT_ALT_LMB] = "Remove pAI"
. = CONTEXTUAL_SCREENTIP_SET
if(inserted_disk)
context[SCREENTIP_CONTEXT_CTRL_SHIFT_LMB] = "Remove Disk"
. = CONTEXTUAL_SCREENTIP_SET
return . || NONE
/obj/item/modular_computer/update_icon_state()
if(!icon_state_powered || !icon_state_unpowered) //no valid icon, don't update.
return ..()
icon_state = enabled ? icon_state_powered : icon_state_unpowered
return ..()
/obj/item/modular_computer/update_overlays()
. = ..()
var/init_icon = initial(icon)
if(!init_icon)
return
if(enabled)
. += active_program ? mutable_appearance(init_icon, active_program.program_open_overlay) : mutable_appearance(init_icon, icon_state_menu)
if(atom_integrity <= integrity_failure * max_integrity)
. += mutable_appearance(init_icon, "bsod")
. += mutable_appearance(init_icon, "broken")
/obj/item/modular_computer/Exited(atom/movable/gone, direction)
if(internal_cell == gone)
internal_cell = null
if(enabled && !use_energy())
shutdown_computer()
if(computer_id_slot == gone)
computer_id_slot = null
update_slot_icon()
if(ishuman(loc))
var/mob/living/carbon/human/human_wearer = loc
human_wearer.sec_hud_set_ID()
if(inserted_pai == gone)
update_appearance(UPDATE_ICON)
if(inserted_disk == gone)
inserted_disk = null
update_appearance(UPDATE_ICON)
return ..()
/obj/item/modular_computer/CtrlShiftClick(mob/user)
. = ..()
if(.)
return
if(!inserted_disk)
return
user.put_in_hands(inserted_disk)
inserted_disk = null
playsound(src, 'sound/machines/card_slide.ogg', 50)
/obj/item/modular_computer/proc/turn_on(mob/user, open_ui = TRUE)
var/issynth = HAS_SILICON_ACCESS(user) // Robots and AIs get different activation messages.
if(atom_integrity <= integrity_failure * max_integrity)
if(user)
if(issynth)
to_chat(user, span_warning("You send an activation signal to \the [src], but it responds with an error code. It must be damaged."))
else
to_chat(user, span_warning("You press the power button, but the computer fails to boot up, displaying variety of errors before shutting down again."))
return FALSE
if(use_energy(base_active_power_usage)) // checks if the PC is powered
if(looping_sound)
soundloop.start()
enabled = TRUE
update_appearance()
if(user)
if(issynth)
to_chat(user, span_notice("You send an activation signal to \the [src], turning it on."))
else
to_chat(user, span_notice("You press the power button and start up \the [src]."))
if(open_ui)
update_tablet_open_uis(user)
SEND_SIGNAL(src, COMSIG_MODULAR_COMPUTER_TURNED_ON, user)
return TRUE
else // Unpowered
if(user)
if(issynth)
to_chat(user, span_warning("You send an activation signal to \the [src] but it does not respond."))
else
to_chat(user, span_warning("You press the power button but \the [src] does not respond."))
return FALSE
// Process currently calls handle_power(), may be expanded in future if more things are added.
/obj/item/modular_computer/process(seconds_per_tick)
if(!enabled) // The computer is turned off
return
if(atom_integrity <= integrity_failure * max_integrity)
shutdown_computer()
return
if(active_program && (active_program.program_flags & PROGRAM_REQUIRES_NTNET) && !get_ntnet_status())
active_program.event_networkfailure(FALSE) // Active program requires NTNet to run but we've just lost connection. Crash.
for(var/datum/computer_file/program/idle_programs as anything in idle_threads)
idle_programs.process_tick(seconds_per_tick)
idle_programs.ntnet_status = get_ntnet_status()
if((idle_programs.program_flags & PROGRAM_REQUIRES_NTNET) && !idle_programs.ntnet_status)
idle_programs.event_networkfailure(TRUE)
if(active_program)
active_program.process_tick(seconds_per_tick)
active_program.ntnet_status = get_ntnet_status()
handle_power(seconds_per_tick) // Handles all computer power interaction
/**
* Displays notification text alongside a soundbeep when requested to by a program.
*
* After checking that the requesting program is allowed to send an alert, creates
* a visible message of the requested text alongside a soundbeep. This proc adds
* text to indicate that the message is coming from this device and the program
* on it, so the supplied text should be the exact message and ending punctuation.
*
* Arguments:
* The program calling this proc.
* The message that the program wishes to display.
*/
/obj/item/modular_computer/proc/alert_call(datum/computer_file/program/caller, alerttext, sound = 'sound/machines/twobeep_high.ogg')
if(!caller || !caller.alert_able || caller.alert_silenced || !alerttext) //Yeah, we're checking alert_able. No, you don't get to make alerts that the user can't silence.
return FALSE
playsound(src, sound, 50, TRUE)
physical.loc.visible_message(span_notice("[icon2html(physical, viewers(physical.loc))] \The [src] displays a [caller.filedesc] notification: [alerttext]"))
/obj/item/modular_computer/proc/ring(ringtone) // bring bring
if(!use_energy())
return
if(HAS_TRAIT(SSstation, STATION_TRAIT_PDA_GLITCHED))
playsound(src, pick('sound/machines/twobeep_voice1.ogg', 'sound/machines/twobeep_voice2.ogg'), 50, TRUE)
else
playsound(src, 'sound/machines/twobeep_high.ogg', 50, TRUE)
audible_message("*[ringtone]*")
/obj/item/modular_computer/proc/send_sound()
playsound(src, 'sound/machines/terminal_success.ogg', 15, TRUE)
// Function used by NanoUI's to obtain data for header. All relevant entries begin with "PC_"
/obj/item/modular_computer/proc/get_header_data()
var/list/data = list()
data["PC_device_theme"] = device_theme
if(internal_cell)
data["PC_lowpower_mode"] = !internal_cell.charge
switch(internal_cell.percent())
if(80 to INFINITY)
data["PC_batteryicon"] = "batt_100.gif"
if(60 to 80)
data["PC_batteryicon"] = "batt_80.gif"
if(40 to 60)
data["PC_batteryicon"] = "batt_60.gif"
if(20 to 40)
data["PC_batteryicon"] = "batt_40.gif"
if(5 to 20)
data["PC_batteryicon"] = "batt_20.gif"
else
data["PC_batteryicon"] = "batt_5.gif"
data["PC_batterypercent"] = "[round(internal_cell.percent())]%"
else
data["PC_lowpower_mode"] = FALSE
data["PC_batteryicon"] = null
data["PC_batterypercent"] = null
switch(get_ntnet_status())
if(NTNET_NO_SIGNAL)
data["PC_ntneticon"] = "sig_none.gif"
if(NTNET_LOW_SIGNAL)
data["PC_ntneticon"] = "sig_low.gif"
if(NTNET_GOOD_SIGNAL)
data["PC_ntneticon"] = "sig_high.gif"
if(NTNET_ETHERNET_SIGNAL)
data["PC_ntneticon"] = "sig_lan.gif"
if(length(idle_threads))
var/list/program_headers = list()
for(var/datum/computer_file/program/idle_programs as anything in idle_threads)
if(!idle_programs.ui_header)
continue
program_headers.Add(list(list("icon" = idle_programs.ui_header)))
data["PC_programheaders"] = program_headers
data["PC_stationtime"] = station_time_timestamp()
data["PC_stationdate"] = "[time2text(world.realtime, "DDD, Month DD")], [CURRENT_STATION_YEAR]"
data["PC_showexitprogram"] = !!active_program // Hides "Exit Program" button on mainscreen
return data
/obj/item/modular_computer/proc/open_program(mob/user, datum/computer_file/program/program, open_ui = TRUE)
if(program.computer != src)
CRASH("tried to open program that does not belong to this computer")
if(isnull(program) || !istype(program)) // Program not found or it's not executable program.
if(user)
to_chat(user, span_danger("\The [src]'s screen shows \"I/O ERROR - Unable to run program\" warning."))
return FALSE
if(active_program == program)
return FALSE
// The program is already running. Resume it.
if(program in idle_threads)
active_program?.background_program()
active_program = program
program.alert_pending = FALSE
idle_threads.Remove(program)
if(open_ui)
INVOKE_ASYNC(src, PROC_REF(update_tablet_open_uis), user)
update_appearance(UPDATE_ICON)
return TRUE
if(!program.is_supported_by_hardware(hardware_flag, loud = TRUE, user = user))
return FALSE
if(idle_threads.len > max_idle_programs)
if(user)
to_chat(user, span_danger("\The [src] displays a \"Maximal CPU load reached. Unable to run another program.\" error."))
return FALSE
if(program.program_flags & PROGRAM_REQUIRES_NTNET && !get_ntnet_status()) // The program requires NTNet connection, but we are not connected to NTNet.
if(user)
to_chat(user, span_danger("\The [src]'s screen shows \"Unable to connect to NTNet. Please retry. If problem persists contact your system administrator.\" warning."))
return FALSE
if(!program.on_start(user))
return FALSE
active_program?.background_program()
active_program = program
program.alert_pending = FALSE
if(open_ui)
INVOKE_ASYNC(src, PROC_REF(update_tablet_open_uis), user)
update_appearance(UPDATE_ICON)
return TRUE
// Returns 0 for No Signal, 1 for Low Signal and 2 for Good Signal. 3 is for wired connection (always-on)
/obj/item/modular_computer/proc/get_ntnet_status()
// computers are connected through ethernet
if(hardware_flag & PROGRAM_CONSOLE)
return NTNET_ETHERNET_SIGNAL
// NTNet is down and we are not connected via wired connection. No signal.
if(!find_functional_ntnet_relay())
return NTNET_NO_SIGNAL
var/turf/current_turf = get_turf(src)
if(!current_turf || !istype(current_turf))
return NTNET_NO_SIGNAL
if(is_station_level(current_turf.z))
if(hardware_flag & PROGRAM_LAPTOP) //laptops can connect to ethernet but they have to be on station for that
return NTNET_ETHERNET_SIGNAL
return NTNET_GOOD_SIGNAL
else if(is_mining_level(current_turf.z))
return NTNET_LOW_SIGNAL
else if(long_ranged)
return NTNET_LOW_SIGNAL
return NTNET_NO_SIGNAL
/obj/item/modular_computer/proc/add_log(text)
if(!get_ntnet_status())
return FALSE
return SSmodular_computers.add_log("[src]: [text]")
/obj/item/modular_computer/proc/close_all_programs()
active_program?.kill_program()
for(var/datum/computer_file/program/idle as anything in idle_threads)
idle.kill_program()
/obj/item/modular_computer/proc/shutdown_computer(loud = TRUE)
close_all_programs()
if(looping_sound)
soundloop.stop()
if(physical && loud)
physical.visible_message(span_notice("\The [src] shuts down."))
enabled = FALSE
update_appearance()
SEND_SIGNAL(src, COMSIG_MODULAR_COMPUTER_SHUT_DOWN, loud)
///Imprints name and job into the modular computer, and calls back to necessary functions.
///Acts as a replacement to directly setting the imprints fields. All fields are optional, the proc will try to fill in missing gaps.
/obj/item/modular_computer/proc/imprint_id(name = null, job_name = null)
saved_identification = name || computer_id_slot?.registered_name || saved_identification
saved_job = job_name || computer_id_slot?.assignment || saved_job
SEND_SIGNAL(src, COMSIG_MODULAR_PDA_IMPRINT_UPDATED, saved_identification, saved_job)
UpdateDisplay()
///Resets the imprinted name and job back to null.
/obj/item/modular_computer/proc/reset_imprint()
saved_identification = null
saved_job = null
SEND_SIGNAL(src, COMSIG_MODULAR_PDA_IMPRINT_RESET)
UpdateDisplay()
/obj/item/modular_computer/ui_action_click(mob/user, actiontype)
if(istype(actiontype, /datum/action/item_action/toggle_computer_light))
toggle_flashlight(user)
return
return ..()
/**
* Toggles the computer's flashlight, if it has one.
*
* Called from ui_act(), does as the name implies.
* It is separated from ui_act() to be overwritten as needed.
*/
/obj/item/modular_computer/proc/toggle_flashlight(mob/user)
if(!has_light || !internal_cell?.charge)
return FALSE
if(!COOLDOWN_FINISHED(src, disabled_time))
if(user)
balloon_alert(user, "disrupted!")
return FALSE
set_light_on(!light_on)
update_appearance()
update_item_action_buttons(force = TRUE) //force it because we added an overlay, not changed its icon
return TRUE
/**
* Disables the computer's flashlight/LED light, if it has one, for a given disrupt_duration.
*
* Called when sent COMSIG_HIT_BY_SABOTEUR.
*/
/obj/item/modular_computer/proc/on_saboteur(datum/source, disrupt_duration)
SIGNAL_HANDLER
if(!has_light)
return
set_light_on(FALSE)
update_appearance()
update_item_action_buttons(force = TRUE) //force it because we added an overlay, not changed its icon
COOLDOWN_START(src, disabled_time, disrupt_duration)
return COMSIG_SABOTEUR_SUCCESS
/**
* Sets the computer's light color, if it has a light.
*
* Called from ui_act(), this proc takes a color string and applies it.
* It is separated from ui_act() to be overwritten as needed.
* Arguments:
** color is the string that holds the color value that we should use. Proc auto-fails if this is null.
*/
/obj/item/modular_computer/proc/set_flashlight_color(color)
if(!has_light || !color)
return FALSE
comp_light_color = color
set_light_color(color)
return TRUE
/obj/item/modular_computer/proc/UpdateDisplay()
if(!saved_identification && !saved_job)
name = initial(name)
return
name = "[saved_identification] ([saved_job])"
/obj/item/modular_computer/attackby(obj/item/attacking_item, mob/user, params)
// Check for ID first
if(isidcard(attacking_item) && InsertID(attacking_item, user))
return
// Check for cash next
if(computer_id_slot && iscash(attacking_item))
var/obj/item/card/id/inserted_id = computer_id_slot.GetID()
if(inserted_id)
inserted_id.attackby(attacking_item, user) // If we do, try and put that attacking object in
return
// Inserting a pAI
if(istype(attacking_item, /obj/item/pai_card) && insert_pai(user, attacking_item))
return
if(istype(attacking_item, /obj/item/stock_parts/cell))
if(ismachinery(physical))
return
if(internal_cell)
to_chat(user, span_warning("You try to connect \the [attacking_item] to \the [src], but its connectors are occupied."))
return
if(user && !user.transferItemToLoc(attacking_item, src))
return
internal_cell = attacking_item
to_chat(user, span_notice("You plug \the [attacking_item] to \the [src]."))
return
if(istype(attacking_item, /obj/item/photo))
var/obj/item/photo/attacking_photo = attacking_item
if(store_file(new /datum/computer_file/picture(attacking_photo.picture)))
balloon_alert(user, "photo scanned")
else
balloon_alert(user, "no space!")
return
// Check if any Applications need it
for(var/datum/computer_file/item_holding_app as anything in stored_files)
if(item_holding_app.application_attackby(attacking_item, user))
return
if(istype(attacking_item, /obj/item/paper))
if(stored_paper >= max_paper)
balloon_alert(user, "no more room!")
return
if(!user.temporarilyRemoveItemFromInventory(attacking_item))
return FALSE
balloon_alert(user, "inserted paper")
qdel(attacking_item)
stored_paper++
return
if(istype(attacking_item, /obj/item/paper_bin))
var/obj/item/paper_bin/bin = attacking_item
if(bin.total_paper <= 0)
balloon_alert(user, "empty bin!")
return
var/papers_added //just to keep track
while((bin.total_paper > 0) && (stored_paper < max_paper))
papers_added++
stored_paper++
bin.remove_paper()
if(!papers_added)
return
balloon_alert(user, "inserted paper")
to_chat(user, span_notice("Added in [papers_added] new sheets. You now have [stored_paper] / [max_paper] printing paper stored."))
bin.update_appearance()
return
// Insert a data disk
if(istype(attacking_item, /obj/item/computer_disk))
if(inserted_disk)
user.put_in_hands(inserted_disk)
balloon_alert(user, "disks swapped")
if(!user.transferItemToLoc(attacking_item, src))
return
inserted_disk = attacking_item
playsound(src, 'sound/machines/card_slide.ogg', 50)
return
return ..()
/obj/item/modular_computer/screwdriver_act_secondary(mob/living/user, obj/item/tool)
. = ..()
if(internal_cell)
user.balloon_alert(user, "cell removed")
internal_cell.forceMove(drop_location())
internal_cell = null
return ITEM_INTERACT_SUCCESS
else
user.balloon_alert(user, "no cell!")
/obj/item/modular_computer/wrench_act_secondary(mob/living/user, obj/item/tool)
. = ..()
tool.play_tool_sound(src, user, 20, volume=20)
deconstruct(TRUE)
user.balloon_alert(user, "disassembled")
return ITEM_INTERACT_SUCCESS
/obj/item/modular_computer/welder_act(mob/living/user, obj/item/tool)
. = ..()
if(atom_integrity == max_integrity)
to_chat(user, span_warning("\The [src] does not require repairs."))
return ITEM_INTERACT_SUCCESS
if(!tool.tool_start_check(user, amount=1))
return ITEM_INTERACT_SUCCESS
to_chat(user, span_notice("You begin repairing damage to \the [src]..."))
if(!tool.use_tool(src, user, 20, volume=50))
return ITEM_INTERACT_SUCCESS
atom_integrity = max_integrity
to_chat(user, span_notice("You repair \the [src]."))
update_appearance()
return ITEM_INTERACT_SUCCESS
/obj/item/modular_computer/deconstruct(disassembled = TRUE)
remove_pai()
eject_aicard()
if(!(obj_flags & NO_DECONSTRUCTION))
if (disassembled)
internal_cell?.forceMove(drop_location())
computer_id_slot?.forceMove(drop_location())
inserted_disk?.forceMove(drop_location())
new /obj/item/stack/sheet/iron(drop_location(), steel_sheet_cost)
else
physical.visible_message(span_notice("\The [src] breaks apart!"))
new /obj/item/stack/sheet/iron(drop_location(), round(steel_sheet_cost * 0.5))
relay_qdel()
return ..()
// Ejects the inserted intellicard, if one exists. Used when the computer is deconstructed.
/obj/item/modular_computer/proc/eject_aicard()
var/datum/computer_file/program/ai_restorer/program = locate() in stored_files
if (program)
return program.try_eject(forced = TRUE)
return FALSE
// Used by processor to relay qdel() to machinery type.
/obj/item/modular_computer/proc/relay_qdel()
return
// Perform adjacency checks on our physical counterpart, if any.
/obj/item/modular_computer/Adjacent(atom/neighbor)
if(physical && physical != src)
return physical.Adjacent(neighbor)
return ..()
///Returns a string of what to send at the end of messenger's messages.
/obj/item/modular_computer/proc/get_messenger_ending()
return "Sent from my PDA"
/obj/item/modular_computer/proc/insert_pai(mob/user, obj/item/pai_card/card)
if(inserted_pai)
return FALSE
if(!user.transferItemToLoc(card, src))
return FALSE
inserted_pai = card
balloon_alert(user, "inserted pai")
if(inserted_pai.pai)
inserted_pai.pai.give_messenger_ability()
update_appearance(UPDATE_ICON)
return TRUE
/obj/item/modular_computer/proc/remove_pai(mob/user)
if(!inserted_pai)
return FALSE
if(inserted_pai.pai)
inserted_pai.pai.remove_messenger_ability()
if(user)
user.put_in_hands(inserted_pai)
balloon_alert(user, "removed pAI")
else
inserted_pai.forceMove(drop_location())
inserted_pai = null
update_appearance(UPDATE_ICON)
return TRUE
/**
* Debug ModPC
* Used to spawn all programs for Create and Destroy unit test.
*/
/obj/item/modular_computer/debug
max_capacity = INFINITY
/obj/item/modular_computer/debug/Initialize(mapload)
starting_programs += subtypesof(/datum/computer_file/program)
return ..()