IconForge: rust-g Spritesheet Generation (#89478)

## About The Pull Request

Replaces the asset subsystem's spritesheet generator with a rust-based
implementation (https://github.com/tgstation/rust-g/pull/160).

This is a rough port of
https://github.com/BeeStation/BeeStation-Hornet/pull/10404, but it
includes fixes for some cases I didn't catch that apply on TG.

(FWIW we've been using this system on prod for over a year and
encountered no major issues.)

### TG MAINTAINER NOTE


![image](https://github.com/user-attachments/assets/53bd2b44-9bb5-42d2-b33f-093651edebc0)

### Batched Spritesheets

`/datum/asset/spritesheet_batched`: A version of the spritesheet system
that collects a list of `/datum/universal_icon`s and sends them off to
rustg asynchronously, and the generation also runs on another thread, so
the game doesn't block during realize_spritesheet. The rust generation
is about 10x faster when it comes to actual icon generation, but the
biggest perk of the batched spritesheets is the caching system.

This PR notably does not convert a few things to the new spritesheet
generator.

- Species and antagonist icons in the preferences view because they use
getFlatIcon ~~which can't be converted to universal icons~~.
- Yes, this is still a *massive* cost to init, unfortunately. On Bee, I
actually enabled the 'legacy' cache on prod and development, which you
can see in my PR. That's why I added the 'clear cache' verb and the
`unregister()` procs, because it can force a regeneration at runtime. I
decided not to port this, since I think it would be detrimental to the
large amount of contributors here.
- It is *technically* possible to port parts of this to the uni_icon
system by making a uni_icon version of getFlatIcon. However, some
overlays use runtime-generated icons which are ~~completely unparseable
to IconForge, since they're stored in the RSC and don't exist as files
anywhere~~. This is most noticeable with things like hair (which blend
additively with the hair mask on the server, thus making them invisible
to `get_flat_uni_icon`). It also doesn't help that species and antag
icons will still need to generate a bunch of dummies and delete them to
even verify cache validity.
- It is actually possible to write the RSC icons to the filesystem
(using fcopy) and reference them in IconForge. However, I'm going to
wait on doing this until I port my GAGS implementation because it
requires GAGS to exist on the filesystem as well.

#### Caching

IconForge generates a cache based on the set of icons used, all
transform operations applied, and the source DMIs of each icon used
within the spritesheet. It can compare the hashes and invalidate the
cache automatically if any of these change. This means we can enable
caching on development, and have absolutely no downsides, because if
anything changes, the cache invalidates itself.

The caching has a mean cost of ~5ms and saves a lot of time compared to
generating the spritesheet, even with rust's faster generation. The main
downside is that the cache still requires building the list of icons and
their transforms, then json encoding it to send to rustg.

Here's an abbreviated example of a cache JSON. All of these need to
match for the cache to be valid. `input_hash` contains the transform
definitions for all the sprites in the spritesheet, so if the input to
iconforge changes, that hash catches it. The `sizes` and `sprites` are
loaded into DM.

```json
{
	"input_hash": "99f1bc67d590e000",
	"dmi_hashes": {
		"icons/ui/achievements/achievements.dmi": "771200c75da11c62"
	},
	"sizes": [
		"76x76"
	],
	"sprites": {
		"achievement-rustascend": {
			"size_id": "76x76",
			"position": 1
		}
	},
	"rustg_version": "3.6.0",
	"dm_version": 1
}
```

### Universal Icons

Universal icons are just a collection of DMI, Icon State, and any icon
transformation procs you apply (blends, crops, scales). They can be
convered to DM icons via `to_icon()`. I've included an implementation of
GAGS that produces universal icons, allowing GAGS items to be converted
into them. IconForge can read universal icons and add them to
spritesheets. It's basically just a wrapper that reimplements BYOND icon
procs.

### Other Stuff

Converts some uses of md5asfile within legacy spritesheets to use
rustg_hash_file instead, improving the performance of their generation.

Fixes lizard body markings not showing in previews, and re-adds eyes to
the ethereal color preview. This is a side effect of IconForge having
*much* better error handling than DM icon procs. Invalid stuff that gets
passed around will error instead of silently doing nothing.

Changes the CSS used in legacy spritesheet generation to split
`background: url(...) no-repeat` into separate props. This is necessary
for WebView2, as IE treats these properties differently - adding
`background-color` to an icon object (as seen in the R&D console) won't
work if you don't split these out.

Deletes unused spritesheets and their associated icons (condiments
spritesheet, old PDA spritesheet)

## Why It's Good For The Game

If you press "Character Setup", the 10-13sec of lag is now approximately
0.5-2 seconds.

Tracy profile showing the time spent on get_asset_datum. I pressed the
preferences button during init on both branches. Do note that this was
ran with a smart cache HIT, so no generation occurred.


![image](https://github.com/user-attachments/assets/3efa71ab-972b-4f5a-acab-0892496ef999)

Much lower worst-case for /datum/asset/New (which includes
`create_spritesheets()` and `register()`)


![image](https://github.com/user-attachments/assets/9ad8ceee-7bd6-4c48-b5f3-006520f527ef)

Here's a look at the internal costs from rustg - as you can see
`generate_spritesheet()` is very fast:


![image](https://github.com/user-attachments/assets/e6892c28-8c31-4af5-96d4-501e966d0ce9)

### Comparison for a single spritesheet - chat spritesheet:

**Before**


![image](https://github.com/user-attachments/assets/cbd65787-42ba-4278-a45c-bd3d538da986)

**After**


![image](https://github.com/user-attachments/assets/d750899a-bd07-4b57-80fb-420fcc0ae416)

## Changelog

🆑
fix: Fixed lizard body markings and ethereal feature previews in the
preference menu missing some overlays.
refactor: Optimized spritesheet asset generation greatly using rustg
IconForge, greatly reducing post-initialization lag as well as reducing
init times and saving server computation.
config: Added 'smart' asset caching, for batched rustg IconForge
spritesheets. It is persistent and suitable for use on local, with
automatic invalidation.
add: Added admin verbs - Debug -> Clear Smart/Legacy Asset Cache for
spritesheets.
fix: Fixed R&D console icons breaking on WebView2/516
/🆑
This commit is contained in:
itsmeow
2025-03-03 07:58:27 -06:00
committed by GitHub
parent 62a37ad555
commit cc335e7e9e
163 changed files with 1828 additions and 870 deletions
+26 -380
View File
@@ -1,5 +1,3 @@
#define ASSET_CROSS_ROUND_CACHE_DIRECTORY "cache/assets"
//These datums are used to populate the asset cache, the proc "register()" does this.
//Place any asset datums you create in asset_list_items.dm
@@ -63,6 +61,17 @@ GLOBAL_LIST_EMPTY(asset_datums)
/datum/asset/proc/should_refresh()
return !cross_round_cachable || !CONFIG_GET(flag/cache_assets)
/// Immediately regenerate the asset, overwriting any cache.
/datum/asset/proc/regenerate()
unregister()
cached_serialized_url_mappings = null
cached_serialized_url_mappings_transport_type = null
register()
/// Unregisters any assets from the transport.
/datum/asset/proc/unregister()
CRASH("unregister() not implemented for asset [type]!")
/// Simply takes any generated file and saves it to the round-specific /logs folder. Useful for debugging potential issues with spritesheet generation/display.
/// Only called when the SAVE_SPRITESHEETS config option is uncommented.
/datum/asset/proc/save_to_logs(file_name, file_location)
@@ -103,6 +112,10 @@ GLOBAL_LIST_EMPTY(asset_datums)
for (var/asset_name in assets)
.[asset_name] = SSassets.transport.get_asset_url(asset_name, assets[asset_name])
/datum/asset/simple/unregister()
for (var/asset_name in assets)
SSassets.transport.unregister_asset(asset_name)
// For registering or sending multiple others at once
/datum/asset/group
_abstract = /datum/asset/group
@@ -123,374 +136,10 @@ GLOBAL_LIST_EMPTY(asset_datums)
var/datum/asset/A = get_asset_datum(type)
. += A.get_url_mappings()
// spritesheet implementation - coalesces various icons into a single .png file
// and uses CSS to select icons out of that file - saves on transferring some
// 1400-odd individual PNG files
#define SPR_SIZE 1
#define SPR_IDX 2
#define SPRSZ_COUNT 1
#define SPRSZ_ICON 2
#define SPRSZ_STRIPPED 3
/datum/asset/spritesheet
_abstract = /datum/asset/spritesheet
cross_round_cachable = TRUE
var/name
/// List of arguments to pass into queuedInsert
/// Exists so we can queue icon insertion, mostly for stuff like preferences
var/list/to_generate = list()
var/list/sizes = list() // "32x32" -> list(10, icon/normal, icon/stripped)
var/list/sprites = list() // "foo_bar" -> list("32x32", 5)
var/list/cached_spritesheets_needed
var/generating_cache = FALSE
var/fully_generated = FALSE
/// If this asset should be fully loaded on new
/// Defaults to false so we can process this stuff nicely
var/load_immediately = FALSE
VAR_PRIVATE
// Kept in state so that the result is the same, even when the files are created, for this run
should_refresh = null
/datum/asset/spritesheet/proc/should_load_immediately()
#ifdef DO_NOT_DEFER_ASSETS
return TRUE
#else
return load_immediately
#endif
/datum/asset/spritesheet/should_refresh()
if (..())
return TRUE
if (isnull(should_refresh))
// `fexists` seems to always fail on static-time
should_refresh = !fexists(css_cache_filename()) || !fexists(data_cache_filename())
return should_refresh
/datum/asset/spritesheet/register()
SHOULD_NOT_OVERRIDE(TRUE)
if (!name)
CRASH("spritesheet [type] cannot register without a name")
if (!should_refresh() && read_from_cache())
fully_generated = TRUE
return
// If it's cached, may as well load it now, while the loading is cheap
if(CONFIG_GET(flag/cache_assets) && cross_round_cachable)
load_immediately = TRUE
create_spritesheets()
if(should_load_immediately())
realize_spritesheets(yield = FALSE)
else
SSasset_loading.queue_asset(src)
/datum/asset/spritesheet/proc/realize_spritesheets(yield)
if(fully_generated)
return
while(length(to_generate))
var/list/stored_args = to_generate[to_generate.len]
to_generate.len--
queuedInsert(arglist(stored_args))
if(yield && TICK_CHECK)
return
ensure_stripped()
for(var/size_id in sizes)
var/size = sizes[size_id]
SSassets.transport.register_asset("[name]_[size_id].png", size[SPRSZ_STRIPPED])
var/css_name = "spritesheet_[name].css"
var/file_directory = "data/spritesheets/[css_name]"
fdel(file_directory)
text2file(generate_css(), file_directory)
SSassets.transport.register_asset(css_name, fcopy_rsc(file_directory))
if(CONFIG_GET(flag/save_spritesheets))
save_to_logs(file_name = css_name, file_location = file_directory)
fdel(file_directory)
if (CONFIG_GET(flag/cache_assets) && cross_round_cachable)
write_to_cache()
fully_generated = TRUE
// If we were ever in there, remove ourselves
SSasset_loading.dequeue_asset(src)
/datum/asset/spritesheet/queued_generation()
realize_spritesheets(yield = TRUE)
/datum/asset/spritesheet/ensure_ready()
if(!fully_generated)
realize_spritesheets(yield = FALSE)
return ..()
/datum/asset/spritesheet/send(client/client)
if (!name)
return
if (!should_refresh())
return send_from_cache(client)
var/all = list("spritesheet_[name].css")
for(var/size_id in sizes)
all += "[name]_[size_id].png"
. = SSassets.transport.send_assets(client, all)
/datum/asset/spritesheet/get_url_mappings()
if (!name)
return
if (!should_refresh())
return get_cached_url_mappings()
. = list("spritesheet_[name].css" = SSassets.transport.get_asset_url("spritesheet_[name].css"))
for(var/size_id in sizes)
.["[name]_[size_id].png"] = SSassets.transport.get_asset_url("[name]_[size_id].png")
/datum/asset/spritesheet/proc/ensure_stripped(sizes_to_strip = sizes)
for(var/size_id in sizes_to_strip)
var/size = sizes[size_id]
if (size[SPRSZ_STRIPPED])
continue
// save flattened version
var/png_name = "[name]_[size_id].png"
var/file_directory = "data/spritesheets/[png_name]"
fcopy(size[SPRSZ_ICON], file_directory)
var/error = rustg_dmi_strip_metadata(file_directory)
if(length(error))
stack_trace("Failed to strip [png_name]: [error]")
size[SPRSZ_STRIPPED] = icon(file_directory)
// this is useful here for determining if weird sprite issues (like having a white background) are a cause of what we're doing DM-side or not since we can see the full flattened thing at-a-glance.
if(CONFIG_GET(flag/save_spritesheets))
save_to_logs(file_name = png_name, file_location = file_directory)
fdel(file_directory)
/datum/asset/spritesheet/proc/generate_css()
var/list/out = list()
for (var/size_id in sizes)
var/size = sizes[size_id]
var/icon/tiny = size[SPRSZ_ICON]
out += ".[name][size_id]{display:inline-block;width:[tiny.Width()]px;height:[tiny.Height()]px;background:url('[get_background_url("[name]_[size_id].png")]') no-repeat;}"
for (var/sprite_id in sprites)
var/sprite = sprites[sprite_id]
var/size_id = sprite[SPR_SIZE]
var/idx = sprite[SPR_IDX]
var/size = sizes[size_id]
var/icon/tiny = size[SPRSZ_ICON]
var/icon/big = size[SPRSZ_STRIPPED]
var/per_line = big.Width() / tiny.Width()
var/x = (idx % per_line) * tiny.Width()
var/y = round(idx / per_line) * tiny.Height()
out += ".[name][size_id].[sprite_id]{background-position:-[x]px -[y]px;}"
return out.Join("\n")
/datum/asset/spritesheet/proc/css_cache_filename()
return "[ASSET_CROSS_ROUND_CACHE_DIRECTORY]/spritesheet.[name].css"
/datum/asset/spritesheet/proc/data_cache_filename()
return "[ASSET_CROSS_ROUND_CACHE_DIRECTORY]/spritesheet.[name].json"
/datum/asset/spritesheet/proc/read_from_cache()
return read_css_from_cache() && read_data_from_cache()
/datum/asset/spritesheet/proc/read_css_from_cache()
var/replaced_css = file2text(css_cache_filename())
var/regex/find_background_urls = regex(@"background:url\('%(.+?)%'\)", "g")
while (find_background_urls.Find(replaced_css))
var/asset_id = find_background_urls.group[1]
var/asset_cache_item = SSassets.transport.register_asset(asset_id, "[ASSET_CROSS_ROUND_CACHE_DIRECTORY]/spritesheet.[asset_id]")
var/asset_url = SSassets.transport.get_asset_url(asset_cache_item = asset_cache_item)
replaced_css = replacetext(replaced_css, find_background_urls.match, "background:url('[asset_url]')")
LAZYADD(cached_spritesheets_needed, asset_id)
var/finalized_name = "spritesheet_[name].css"
var/replaced_css_filename = "data/spritesheets/[finalized_name]"
rustg_file_write(replaced_css, replaced_css_filename)
SSassets.transport.register_asset(finalized_name, replaced_css_filename)
if(CONFIG_GET(flag/save_spritesheets))
save_to_logs(file_name = finalized_name, file_location = replaced_css_filename)
fdel(replaced_css_filename)
return TRUE
/datum/asset/spritesheet/proc/read_data_from_cache()
var/json = json_decode(file2text(data_cache_filename()))
if (islist(json["sprites"]))
sprites = json["sprites"]
return TRUE
/datum/asset/spritesheet/proc/send_from_cache(client/client)
if (isnull(cached_spritesheets_needed))
stack_trace("cached_spritesheets_needed was null when sending assets from [type] from cache")
cached_spritesheets_needed = list()
return SSassets.transport.send_assets(client, cached_spritesheets_needed + "spritesheet_[name].css")
/// Returns the URL to put in the background:url of the CSS asset
/datum/asset/spritesheet/proc/get_background_url(asset)
if (generating_cache)
return "%[asset]%"
else
return SSassets.transport.get_asset_url(asset)
/datum/asset/spritesheet/proc/write_to_cache()
write_css_to_cache()
write_data_to_cache()
/datum/asset/spritesheet/proc/write_css_to_cache()
for (var/size_id in sizes)
fcopy(SSassets.cache["[name]_[size_id].png"].resource, "[ASSET_CROSS_ROUND_CACHE_DIRECTORY]/spritesheet.[name]_[size_id].png")
generating_cache = TRUE
var/mock_css = generate_css()
generating_cache = FALSE
rustg_file_write(mock_css, css_cache_filename())
/datum/asset/spritesheet/proc/write_data_to_cache()
rustg_file_write(json_encode(list(
"sprites" = sprites,
)), data_cache_filename())
/datum/asset/spritesheet/proc/get_cached_url_mappings()
var/list/mappings = list()
mappings["spritesheet_[name].css"] = SSassets.transport.get_asset_url("spritesheet_[name].css")
for (var/asset_name in cached_spritesheets_needed)
mappings[asset_name] = SSassets.transport.get_asset_url(asset_name)
return mappings
/// Override this in order to start the creation of the spritehseet.
/// This is where all your Insert, InsertAll, etc calls should be inside.
/datum/asset/spritesheet/proc/create_spritesheets()
SHOULD_CALL_PARENT(FALSE)
CRASH("create_spritesheets() not implemented for [type]!")
/datum/asset/spritesheet/proc/Insert(sprite_name, icon/I, icon_state="", dir=SOUTH, frame=1, moving=FALSE)
if(should_load_immediately())
queuedInsert(sprite_name, I, icon_state, dir, frame, moving)
else
to_generate += list(args.Copy())
/datum/asset/spritesheet/proc/queuedInsert(sprite_name, icon/I, icon_state="", dir=SOUTH, frame=1, moving=FALSE)
#ifdef UNIT_TESTS
if (I && icon_state && !icon_exists(I, icon_state)) // check the base icon prior to extracting the state we want
stack_trace("Tried to insert nonexistent icon_state '[icon_state]' from [I] into spritesheet [name] ([type])")
return
#endif
I = icon(I, icon_state=icon_state, dir=dir, frame=frame, moving=moving)
if (!I || !length(icon_states(I))) // that direction or state doesn't exist
return
var/start_usage = world.tick_usage
//any sprite modifications we want to do (aka, coloring a greyscaled asset)
I = ModifyInserted(I)
var/size_id = "[I.Width()]x[I.Height()]"
var/size = sizes[size_id]
if (sprites[sprite_name])
CRASH("duplicate sprite \"[sprite_name]\" in sheet [name] ([type])")
if (size)
var/position = size[SPRSZ_COUNT]++
// Icons are essentially representations of files + modifications
// Because of this, byond keeps them in a cache. It does this in a really dumb way tho
// It's essentially a FIFO queue. So after we do icon() some amount of times, our old icons go out of cache
// When this happens it becomes impossible to modify them, trying to do so will instead throw a
// "bad icon" error.
// What we're doing here is ensuring our icon is in the cache by refreshing it, so we can modify it w/o runtimes.
var/icon/sheet = size[SPRSZ_ICON]
var/icon/sheet_copy = icon(sheet)
size[SPRSZ_STRIPPED] = null
sheet_copy.Insert(I, icon_state=sprite_name)
size[SPRSZ_ICON] = sheet_copy
sprites[sprite_name] = list(size_id, position)
else
sizes[size_id] = size = list(1, I, null)
sprites[sprite_name] = list(size_id, 0)
SSblackbox.record_feedback("tally", "spritesheet_queued_insert_time", TICK_USAGE_TO_MS(start_usage), name)
/**
* A simple proc handing the Icon for you to modify before it gets turned into an asset.
*
* Arguments:
* * I: icon being turned into an asset
*/
/datum/asset/spritesheet/proc/ModifyInserted(icon/pre_asset)
return pre_asset
/datum/asset/spritesheet/proc/InsertAll(prefix, icon/I, list/directions)
if (length(prefix))
prefix = "[prefix]-"
if (!directions)
directions = list(SOUTH)
for (var/icon_state_name in icon_states(I))
for (var/direction in directions)
var/prefix2 = (directions.len > 1) ? "[dir2text(direction)]-" : ""
Insert("[prefix][prefix2][icon_state_name]", I, icon_state=icon_state_name, dir=direction)
/datum/asset/spritesheet/proc/css_tag()
return {"<link rel="stylesheet" href="[css_filename()]" />"}
/datum/asset/spritesheet/proc/css_filename()
return SSassets.transport.get_asset_url("spritesheet_[name].css")
/datum/asset/spritesheet/proc/icon_tag(sprite_name)
var/sprite = sprites[sprite_name]
if (!sprite)
return null
var/size_id = sprite[SPR_SIZE]
return {"<span class='[name][size_id] [sprite_name]'></span>"}
/datum/asset/spritesheet/proc/icon_class_name(sprite_name)
var/sprite = sprites[sprite_name]
if (!sprite)
return null
var/size_id = sprite[SPR_SIZE]
return {"[name][size_id] [sprite_name]"}
/**
* Returns the size class (ex design32x32) for a given sprite's icon
*
* Arguments:
* * sprite_name - The sprite to get the size of
*/
/datum/asset/spritesheet/proc/icon_size_id(sprite_name)
var/sprite = sprites[sprite_name]
if (!sprite)
return null
var/size_id = sprite[SPR_SIZE]
return "[name][size_id]"
#undef SPR_SIZE
#undef SPR_IDX
#undef SPRSZ_COUNT
#undef SPRSZ_ICON
#undef SPRSZ_STRIPPED
/datum/asset/group/unregister()
for (var/type in children)
var/datum/asset/A = get_asset_datum(type)
A.unregister()
/datum/asset/changelog_item
_abstract = /datum/asset/changelog_item
@@ -510,13 +159,10 @@ GLOBAL_LIST_EMPTY(asset_datums)
return
. = list("[item_filename]" = SSassets.transport.get_asset_url(item_filename))
/datum/asset/spritesheet/simple
_abstract = /datum/asset/spritesheet/simple
var/list/assets
/datum/asset/spritesheet/simple/create_spritesheets()
for (var/key in assets)
Insert(key, assets[key])
/datum/asset/changelog_item/unregister()
if (!item_filename)
return
SSassets.transport.unregister_asset(item_filename)
//Generates assets based on iconstates of a single icon
/datum/asset/simple/icon_states
@@ -617,13 +263,13 @@ GLOBAL_LIST_EMPTY(asset_datums)
/datum/asset/json/register()
var/filename = "data/[name].json"
fdel(filename)
text2file(json_encode(generate()), filename)
rustg_file_write(json_encode(generate()), filename)
SSassets.transport.register_asset("[name].json", fcopy_rsc(filename))
fdel(filename)
/// Returns the data that will be JSON encoded
/datum/asset/json/proc/generate()
SHOULD_CALL_PARENT(FALSE)
CRASH("generate() not implemented for [type]!")
#undef ASSET_CROSS_ROUND_CACHE_DIRECTORY
/datum/asset/json/unregister()
SSassets.transport.unregister_asset("[name].json")
@@ -1,11 +1,13 @@
/datum/asset/spritesheet/simple/achievements
/datum/asset/spritesheet_batched/achievements
name = "achievements"
/datum/asset/spritesheet/simple/achievements/create_spritesheets()
InsertAll("achievement", ACHIEVEMENTS_SET)
/datum/asset/spritesheet_batched/achievements/create_spritesheets()
for(var/icon_state_name in icon_states(ACHIEVEMENTS_SET))
insert_icon("achievement-[icon_state_name]", uni_icon(ACHIEVEMENTS_SET, icon_state_name))
// catch achievements which are pulling icons from another file
for(var/datum/award/other_award as anything in subtypesof(/datum/award))
var/icon = initial(other_award.icon)
if (icon != ACHIEVEMENTS_SET)
var/icon_state = initial(other_award.icon_state)
Insert("achievement-[icon_state]", icon, icon_state=icon_state)
if (icon == ACHIEVEMENTS_SET)
continue
var/icon_state_name = initial(other_award.icon_state)
insert_icon("achievement-[icon_state_name]", uni_icon(icon, icon_state_name))
+7 -6
View File
@@ -1,10 +1,11 @@
/datum/asset/spritesheet/bibles
/datum/asset/spritesheet_batched/bibles
name = "bibles"
/datum/asset/spritesheet/bibles/create_spritesheets()
/datum/asset/spritesheet_batched/bibles/create_spritesheets()
var/obj/item/book/bible/holy_template = /obj/item/book/bible
InsertAll("display", initial(holy_template.icon))
var/target_icon = initial(holy_template.icon)
var/datum/icon_transformer/transform = new()
transform.scale(224, 224) // Scale up by 7x
/datum/asset/spritesheet/bibles/ModifyInserted(icon/pre_asset)
pre_asset.Scale(224, 224) // Scale up by 7x
return pre_asset
for (var/icon_state_name in icon_states(target_icon))
insert_icon("display-[icon_state_name]", uni_icon(target_icon, icon_state_name, transform=transform))
+6 -7
View File
@@ -1,14 +1,13 @@
/datum/asset/spritesheet/chat
/datum/asset/spritesheet_batched/chat
name = "chat"
/datum/asset/spritesheet/chat/create_spritesheets()
InsertAll("emoji", EMOJI_SET)
/datum/asset/spritesheet_batched/chat/create_spritesheets()
insert_all_icons("emoji", EMOJI_SET)
// pre-loading all lanugage icons also helps to avoid meta
InsertAll("language", 'icons/ui/chat/language.dmi')
insert_all_icons("language", 'icons/ui/chat/language.dmi')
// catch languages which are pulling icons from another file
for(var/path in typesof(/datum/language))
var/datum/language/L = path
for(var/datum/language/L as anything in subtypesof(/datum/language))
var/icon = initial(L.icon)
if (icon != 'icons/ui/chat/language.dmi')
var/icon_state = initial(L.icon_state)
Insert("language-[icon_state]", icon, icon_state=icon_state)
insert_icon("language-[icon_state]", uni_icon(icon, icon_state))
@@ -1,8 +1,8 @@
///Icons for containers printed in ChemMaster
/datum/asset/spritesheet/chemmaster
/datum/asset/spritesheet_batched/chemmaster
name = "chemmaster"
/datum/asset/spritesheet/chemmaster/create_spritesheets()
/datum/asset/spritesheet_batched/chemmaster/create_spritesheets()
var/list/ids = list()
for(var/category in GLOB.reagent_containers)
for(var/obj/item/reagent_containers/container as anything in GLOB.reagent_containers[category])
@@ -12,4 +12,4 @@
if(id in ids) // exclude duplicate containers
continue
ids += id
Insert(id, icon_file, icon_state)
insert_icon(id, uni_icon(icon_file, icon_state))
@@ -1,24 +0,0 @@
/datum/asset/spritesheet/simple/condiments
name = "condiments"
assets = list(
CONDIMASTER_STYLE_FALLBACK = 'icons/ui/condiments/bottle.png',
"flour" = 'icons/ui/condiments/flour.png',
"rice" = 'icons/ui/condiments/rice.png',
"sugar" = 'icons/ui/condiments/sugar.png',
"milk" = 'icons/ui/condiments/milk.png',
"enzyme" = 'icons/ui/condiments/enzyme.png',
"capsaicin" = 'icons/ui/condiments/hotsauce.png',
"frostoil" = 'icons/ui/condiments/coldsauce.png',
"bbqsauce" = 'icons/ui/condiments/bbqsauce.png',
"soymilk" = 'icons/ui/condiments/soymilk.png',
"soysauce" = 'icons/ui/condiments/soysauce.png',
"ketchup" = 'icons/ui/condiments/ketchup.png',
"mayonnaise" = 'icons/ui/condiments/mayonnaise.png',
"oliveoil" = 'icons/ui/condiments/oliveoil.png',
"cooking_oil" = 'icons/ui/condiments/cookingoil.png',
"peanut_butter" = 'icons/ui/condiments/peanutbutter.png',
"cherryjelly" = 'icons/ui/condiments/cherryjelly.png',
"honey" = 'icons/ui/condiments/honey.png',
"blackpepper" = 'icons/ui/condiments/peppermillsmall.png',
"sodiumchloride" = 'icons/ui/condiments/saltshakersmall.png',
)
+28 -28
View File
@@ -1,17 +1,17 @@
///Representative icons for the contents of each crafting recipe
/datum/asset/spritesheet/crafting
/datum/asset/spritesheet_batched/crafting
name = "crafting"
/datum/asset/spritesheet/crafting/create_spritesheets()
/datum/asset/spritesheet_batched/crafting/create_spritesheets()
var/id = 1
for(var/atom in GLOB.crafting_recipes_atoms)
add_atom_icon(atom, id++)
add_tool_icons()
/datum/asset/spritesheet/crafting/cooking
/datum/asset/spritesheet_batched/crafting/cooking
name = "cooking"
/datum/asset/spritesheet/crafting/cooking/create_spritesheets()
/datum/asset/spritesheet_batched/crafting/cooking/create_spritesheets()
var/id = 1
for(var/atom in GLOB.cooking_recipes_atoms)
add_atom_icon(atom, id++)
@@ -24,7 +24,7 @@
* If it a reagent, it will use the default container's icon state,
* OR if it has a glass style associated, it will use that
*/
/datum/asset/spritesheet/crafting/proc/add_atom_icon(ingredient_typepath, id)
/datum/asset/spritesheet_batched/crafting/proc/add_atom_icon(ingredient_typepath, id)
var/icon_file
var/icon_state
var/obj/preview_item = ingredient_typepath
@@ -43,32 +43,32 @@
if(!icon_exists_or_scream(icon_file, icon_state))
return
Insert("a[id]", icon(icon_file, icon_state, SOUTH))
insert_icon("a[id]", uni_icon(icon_file, icon_state, SOUTH))
///Adds tool icons to the spritesheet
/datum/asset/spritesheet/crafting/proc/add_tool_icons()
/datum/asset/spritesheet_batched/crafting/proc/add_tool_icons()
var/list/tool_icons = list(
TOOL_CROWBAR = icon('icons/obj/tools.dmi', "crowbar"),
TOOL_MULTITOOL = icon('icons/obj/devices/tool.dmi', "multitool"),
TOOL_SCREWDRIVER = icon('icons/obj/tools.dmi', "screwdriver_map"),
TOOL_WIRECUTTER = icon('icons/obj/tools.dmi', "cutters_map"),
TOOL_WRENCH = icon('icons/obj/tools.dmi', "wrench"),
TOOL_WELDER = icon('icons/obj/tools.dmi', "welder"),
TOOL_ANALYZER = icon('icons/obj/devices/scanner.dmi', "analyzer"),
TOOL_MINING = icon('icons/obj/mining.dmi', "minipick"),
TOOL_SHOVEL = icon('icons/obj/mining.dmi', "spade"),
TOOL_RETRACTOR = icon('icons/obj/medical/surgery_tools.dmi', "retractor"),
TOOL_HEMOSTAT = icon('icons/obj/medical/surgery_tools.dmi', "hemostat"),
TOOL_CAUTERY = icon('icons/obj/medical/surgery_tools.dmi', "cautery"),
TOOL_DRILL = icon('icons/obj/medical/surgery_tools.dmi', "drill"),
TOOL_SCALPEL = icon('icons/obj/medical/surgery_tools.dmi', "scalpel"),
TOOL_SAW = icon('icons/obj/medical/surgery_tools.dmi', "saw"),
TOOL_BONESET = icon('icons/obj/medical/surgery_tools.dmi', "bonesetter"),
TOOL_KNIFE = icon('icons/obj/service/kitchen.dmi', "knife"),
TOOL_BLOODFILTER = icon('icons/obj/medical/surgery_tools.dmi', "bloodfilter"),
TOOL_ROLLINGPIN = icon('icons/obj/service/kitchen.dmi', "rolling_pin"),
TOOL_RUSTSCRAPER = icon('icons/obj/tools.dmi', "wirebrush"),
TOOL_CROWBAR = uni_icon('icons/obj/tools.dmi', "crowbar"),
TOOL_MULTITOOL = uni_icon('icons/obj/devices/tool.dmi', "multitool"),
TOOL_SCREWDRIVER = uni_icon('icons/obj/tools.dmi', "screwdriver_map"),
TOOL_WIRECUTTER = uni_icon('icons/obj/tools.dmi', "cutters_map"),
TOOL_WRENCH = uni_icon('icons/obj/tools.dmi', "wrench"),
TOOL_WELDER = uni_icon('icons/obj/tools.dmi', "welder"),
TOOL_ANALYZER = uni_icon('icons/obj/devices/scanner.dmi', "analyzer"),
TOOL_MINING = uni_icon('icons/obj/mining.dmi', "minipick"),
TOOL_SHOVEL = uni_icon('icons/obj/mining.dmi', "spade"),
TOOL_RETRACTOR = uni_icon('icons/obj/medical/surgery_tools.dmi', "retractor"),
TOOL_HEMOSTAT = uni_icon('icons/obj/medical/surgery_tools.dmi', "hemostat"),
TOOL_CAUTERY = uni_icon('icons/obj/medical/surgery_tools.dmi', "cautery"),
TOOL_DRILL = uni_icon('icons/obj/medical/surgery_tools.dmi', "drill"),
TOOL_SCALPEL = uni_icon('icons/obj/medical/surgery_tools.dmi', "scalpel"),
TOOL_SAW = uni_icon('icons/obj/medical/surgery_tools.dmi', "saw"),
TOOL_BONESET = uni_icon('icons/obj/medical/surgery_tools.dmi', "bonesetter"),
TOOL_KNIFE = uni_icon('icons/obj/service/kitchen.dmi', "knife"),
TOOL_BLOODFILTER = uni_icon('icons/obj/medical/surgery_tools.dmi', "bloodfilter"),
TOOL_ROLLINGPIN = uni_icon('icons/obj/service/kitchen.dmi', "rolling_pin"),
TOOL_RUSTSCRAPER = uni_icon('icons/obj/tools.dmi', "wirebrush"),
)
for(var/tool in tool_icons)
Insert(replacetext(tool, " ", ""), tool_icons[tool])
insert_icon(replacetext(tool, " ", ""), tool_icons[tool])
@@ -1,5 +1,5 @@
/datum/asset/spritesheet/emojipedia
/datum/asset/spritesheet_batched/emojipedia
name = "emojipedia"
/datum/asset/spritesheet/emojipedia/create_spritesheets()
InsertAll("", EMOJI_SET)
/datum/asset/spritesheet_batched/emojipedia/create_spritesheets()
insert_all_icons("", EMOJI_SET)
+4 -5
View File
@@ -1,14 +1,13 @@
/datum/asset/spritesheet/fish
/datum/asset/spritesheet_batched/fish
name = "fish"
/datum/asset/spritesheet/fish/create_spritesheets()
/datum/asset/spritesheet_batched/fish/create_spritesheets()
var/list/id_list = list()
for (var/path in subtypesof(/obj/item/fish))
var/obj/item/fish/fish_type = path
for (var/obj/item/fish/fish_type as anything in subtypesof(/obj/item/fish))
var/fish_icon = initial(fish_type.icon)
var/fish_icon_state = initial(fish_type.icon_state)
var/id = sanitize_css_class_name("[fish_icon][fish_icon_state]")
if(id in id_list) //no dupes
continue
id_list += id
Insert(id, fish_icon, fish_icon_state)
insert_icon(id, uni_icon(fish_icon, fish_icon_state))
@@ -1,11 +1,7 @@
/datum/asset/spritesheet/lights
/datum/asset/spritesheet_batched/lights
name = "lights"
/datum/asset/spritesheet/lights/create_spritesheets()
// These two are required to ensure this spritesheet is not rendered with a fully white background
// No I have absolutely no idea why, something something alpha maybe? but it does work, so that's for LATER!!
Insert("light_dummy_start_fuckyoubyond", 'icons/obj/medical/bloodpack.dmi', "generic_bloodpack")
/datum/asset/spritesheet_batched/lights/create_spritesheets()
for(var/id in GLOB.light_types)
var/datum/light_template/template = GLOB.light_types[id]
Insert("light_fantastic_[template.id]", template.icon, template.icon_state)
Insert("light_dummy_end_fuckyoubyond", 'icons/mob/silicon/ai.dmi', "questionmark")
insert_icon("light_fantastic_[template.id]", uni_icon(template.icon, template.icon_state))
+3 -3
View File
@@ -1,5 +1,5 @@
/datum/asset/spritesheet/mafia
/datum/asset/spritesheet_batched/mafia
name = "mafia"
/datum/asset/spritesheet/mafia/create_spritesheets()
InsertAll("", 'icons/obj/mafia.dmi')
/datum/asset/spritesheet_batched/mafia/create_spritesheets()
insert_all_icons("", 'icons/obj/mafia.dmi')
+4 -4
View File
@@ -1,6 +1,6 @@
/datum/asset/spritesheet/mecha_equipment
/datum/asset/spritesheet_batched/mecha_equipment
name = "mecha_equipment"
/datum/asset/spritesheet/mecha_equipment/create_spritesheets()
InsertAll("", 'icons/obj/devices/mecha_equipment.dmi')
InsertAll("", 'icons/obj/ore.dmi')
/datum/asset/spritesheet_batched/mecha_equipment/create_spritesheets()
insert_all_icons("", 'icons/obj/devices/mecha_equipment.dmi')
insert_all_icons("", 'icons/obj/ore.dmi')
+16 -25
View File
@@ -1,27 +1,18 @@
/datum/asset/spritesheet/moods
/datum/asset/spritesheet_batched/moods
name = "moods"
var/iconinserted = 1
/datum/asset/spritesheet/moods/create_spritesheets()
for(var/i in 1 to 9)
var/target_to_insert = "mood"+"[iconinserted]"
Insert(target_to_insert, 'icons/hud/screen_gen.dmi', target_to_insert)
iconinserted++
/datum/asset/spritesheet/moods/ModifyInserted(icon/pre_asset)
var/blended_color
switch(iconinserted)
if(1)
blended_color = "#f15d36"
if(2 to 3)
blended_color = "#f38943"
if(4)
blended_color = "#dfa65b"
if(5)
blended_color = "#4b96c4"
if(6)
blended_color = "#86d656"
else
blended_color = "#2eeb9a"
pre_asset.Blend(blended_color, ICON_MULTIPLY)
return pre_asset
/datum/asset/spritesheet_batched/moods/create_spritesheets()
var/list/mood_colors = list(
"mood1" = "#f15d36",
"mood2" = "#f38943",
"mood3" = "#f38943",
"mood4" = "#dfa65b",
"mood5" = "#4b96c4",
"mood6" = "#86d656",
"mood7" = "#2eeb9a",
"mood8" = "#2eeb9a",
"mood9" = "#2eeb9a",
)
for(var/target_to_insert in mood_colors)
var/blended_color = mood_colors[target_to_insert]
insert_icon(target_to_insert, uni_icon('icons/hud/screen_gen.dmi', target_to_insert, color=blended_color))
-34
View File
@@ -1,34 +0,0 @@
/datum/asset/spritesheet/simple/pda
name = "pda"
assets = list(
"atmos" = 'icons/ui/pda/pda_atmos.png',
"back" = 'icons/ui/pda/pda_back.png',
"bell" = 'icons/ui/pda/pda_bell.png',
"blank" = 'icons/ui/pda/pda_blank.png',
"boom" = 'icons/ui/pda/pda_boom.png',
"bucket" = 'icons/ui/pda/pda_bucket.png',
"medbot" = 'icons/ui/pda/pda_medbot.png',
"floorbot" = 'icons/ui/pda/pda_floorbot.png',
"cleanbot" = 'icons/ui/pda/pda_cleanbot.png',
"crate" = 'icons/ui/pda/pda_crate.png',
"cuffs" = 'icons/ui/pda/pda_cuffs.png',
"eject" = 'icons/ui/pda/pda_eject.png',
"flashlight" = 'icons/ui/pda/pda_flashlight.png',
"honk" = 'icons/ui/pda/pda_honk.png',
"mail" = 'icons/ui/pda/pda_mail.png',
"medical" = 'icons/ui/pda/pda_medical.png',
"menu" = 'icons/ui/pda/pda_menu.png',
"mule" = 'icons/ui/pda/pda_mule.png',
"notes" = 'icons/ui/pda/pda_notes.png',
"power" = 'icons/ui/pda/pda_power.png',
"rdoor" = 'icons/ui/pda/pda_rdoor.png',
"reagent" = 'icons/ui/pda/pda_reagent.png',
"refresh" = 'icons/ui/pda/pda_refresh.png',
"scanner" = 'icons/ui/pda/pda_scanner.png',
"signaler" = 'icons/ui/pda/pda_signaler.png',
"skills" = 'icons/ui/pda/pda_skills.png',
"status" = 'icons/ui/pda/pda_status.png',
"dronephone" = 'icons/ui/pda/pda_dronephone.png',
"emoji" = 'icons/ui/pda/pda_emoji.png',
"droneblacklist" = 'icons/ui/pda/pda_droneblacklist.png',
)
+4 -3
View File
@@ -1,6 +1,7 @@
/datum/asset/spritesheet/pipes
/datum/asset/spritesheet_batched/pipes
name = "pipes"
ignore_dir_errors = TRUE
/datum/asset/spritesheet/pipes/create_spritesheets()
/datum/asset/spritesheet_batched/pipes/create_spritesheets()
for (var/each in list('icons/obj/pipes_n_cables/pipe_item.dmi', 'icons/obj/pipes_n_cables/disposal.dmi', 'icons/obj/pipes_n_cables/transit_tube.dmi', 'icons/obj/pipes_n_cables/hydrochem/fluid_ducts.dmi'))
InsertAll("", each, GLOB.alldirs)
insert_all_icons("", each, GLOB.alldirs)
+3 -3
View File
@@ -1,7 +1,7 @@
/datum/asset/spritesheet/plumbing
/datum/asset/spritesheet_batched/plumbing
name = "plumbing-tgui"
/datum/asset/spritesheet/plumbing/create_spritesheets()
/datum/asset/spritesheet_batched/plumbing/create_spritesheets()
//load only what we need from the icon files,format is icon_file_name = list of icon_states we need from this file
var/list/essentials = list(
'icons/obj/medical/iv_drip.dmi' = list("plumb"),
@@ -39,5 +39,5 @@
for(var/icon_file as anything in essentials)
for(var/icon_state as anything in essentials[icon_file])
Insert(sprite_name = icon_state, I = icon_file, icon_state = icon_state)
insert_icon(icon_state, uni_icon(icon_file, icon_state))
+13 -12
View File
@@ -1,7 +1,7 @@
/datum/asset/spritesheet/rcd
/datum/asset/spritesheet_batched/rcd
name = "rcd-tgui"
/datum/asset/spritesheet/rcd/create_spritesheets()
/datum/asset/spritesheet_batched/rcd/create_spritesheets()
for(var/root_category in GLOB.rcd_designs)
var/list/category_designs = GLOB.rcd_designs[root_category]
@@ -12,34 +12,35 @@
var/list/designs = category_designs[category]
var/sprite_name
var/icon/sprite_icon
for(var/list/design as anything in designs)
var/atom/movable/path = design[RCD_DESIGN_PATH]
if(!ispath(path))
continue
sprite_name = initial(path.name)
var/datum/universal_icon/sprite_icon
//icon for windows are blended with grills if required and loaded from radial menu
if(ispath(path, /obj/structure/window))
if(path == /obj/structure/window)
sprite_icon = icon(icon = 'icons/hud/radial.dmi', icon_state = "windowsize")
sprite_icon = uni_icon('icons/hud/radial.dmi', "windowsize")
else if(path == /obj/structure/window/reinforced)
sprite_icon = icon(icon = 'icons/hud/radial.dmi', icon_state = "windowtype")
sprite_icon = uni_icon('icons/hud/radial.dmi', "windowtype")
else if(path == /obj/structure/window/fulltile || path == /obj/structure/window/reinforced/fulltile)
sprite_icon = icon(icon = initial(path.icon), icon_state = initial(path.icon_state))
sprite_icon.Blend(icon(icon = 'icons/obj/structures.dmi', icon_state = "grille"), ICON_UNDERLAY)
sprite_icon = uni_icon(initial(path.icon), initial(path.icon_state))
sprite_icon.blend_icon(uni_icon('icons/obj/structures.dmi', "grille"), ICON_UNDERLAY)
//icons for solid airlocks have an added solid overlay on top of their glass icons
else if(ispath(path, /obj/machinery/door/airlock))
var/obj/machinery/door/airlock/airlock_path = path
var/airlock_icon = initial(airlock_path.icon)
sprite_icon = icon(icon = airlock_icon, icon_state = "closed")
if(!initial(airlock_path.glass))
sprite_icon.Blend(icon(icon = airlock_icon, icon_state = "fill_closed"), ICON_OVERLAY)
sprite_icon = uni_icon(airlock_icon, "closed")
if(!initial(airlock_path.glass) && initial(airlock_path.can_be_glass))
sprite_icon.blend_icon(uni_icon(airlock_icon, "fill_closed"), ICON_OVERLAY)
//for all other icons we load the paths default icon & icon state
else
sprite_icon = icon(icon = initial(path.icon), icon_state = initial(path.icon_state))
sprite_icon = uni_icon(initial(path.icon), initial(path.icon_state))
Insert(sanitize_css_class_name(sprite_name), sprite_icon)
insert_icon(sanitize_css_class_name(sprite_name), sprite_icon)
@@ -1,15 +1,15 @@
// Representative icons for each research design
/datum/asset/spritesheet/research_designs
/datum/asset/spritesheet_batched/research_designs
name = "design"
/datum/asset/spritesheet/research_designs/create_spritesheets()
/datum/asset/spritesheet_batched/research_designs/create_spritesheets()
for (var/datum/design/path as anything in subtypesof(/datum/design))
if(initial(path.id) == DESIGN_ID_IGNORE)
continue
var/icon_file
var/icon_state
var/icon/I
var/datum/icon_transformer/transform = null
if(initial(path.research_icon) && initial(path.research_icon_state)) //If the design has an icon replacement skip the rest
icon_file = initial(path.research_icon)
@@ -18,8 +18,6 @@
if(!icon_exists(icon_file, icon_state))
stack_trace("design [path] with icon '[icon_file]' missing state '[icon_state]'")
continue
I = icon(icon_file, icon_state, SOUTH)
else
// construct the icon and slap it into the resource cache
var/atom/item = initial(path.build_path)
@@ -38,30 +36,32 @@
if (machine)
item = machine
// Check for GAGS support where necessary
var/greyscale_config = initial(item.greyscale_config)
var/greyscale_colors = initial(item.greyscale_colors)
if (greyscale_config && greyscale_colors)
icon_file = SSgreyscale.GetColoredIconByType(greyscale_config, greyscale_colors)
// GAGS icon short-circuit the rest of the checks
if (initial(item.greyscale_config) && initial(item.greyscale_colors))
insert_icon(initial(path.id), gags_to_universal_icon(item))
continue
else
icon_file = initial(item.icon)
icon_state = initial(item.icon_state)
if(initial(item.color))
transform = color_transform(initial(item.color))
if (PERFORM_ALL_TESTS(focus_only/invalid_research_designs))
if(!icon_exists(icon_file, icon_state))
stack_trace("design [path] with icon '[icon_file]' missing state '[icon_state]'")
continue
I = icon(icon_file, icon_state, SOUTH)
// computers (and snowflakes) get their screen and keyboard sprites
if (ispath(item, /obj/machinery/computer) || ispath(item, /obj/machinery/power/solar_control))
if(!transform)
transform = new()
var/obj/machinery/computer/C = item
var/screen = initial(C.icon_screen)
var/keyboard = initial(C.icon_keyboard)
var/all_states = icon_states(icon_file)
if (screen && (screen in all_states))
I.Blend(icon(icon_file, screen, SOUTH), ICON_OVERLAY)
transform.blend_icon(uni_icon(icon_file, screen), ICON_OVERLAY)
if (keyboard && (keyboard in all_states))
I.Blend(icon(icon_file, keyboard, SOUTH), ICON_OVERLAY)
transform.blend_icon(uni_icon(icon_file, keyboard), ICON_OVERLAY)
Insert(initial(path.id), I)
insert_icon(initial(path.id), uni_icon(icon_file, icon_state, transform=transform))
+4 -6
View File
@@ -1,14 +1,12 @@
/datum/asset/spritesheet/rtd
/datum/asset/spritesheet_batched/rtd
name = "rtd"
/datum/asset/spritesheet/rtd/create_spritesheets()
//some tiles may share the same icon but have different properties to animate that icon
//so we keep track of what icons we registered
/datum/asset/spritesheet_batched/rtd/create_spritesheets()
var/list/registered = list()
for(var/main_root in GLOB.floor_designs)
for(var/sub_category in GLOB.floor_designs[main_root])
for(var/list/design in GLOB.floor_designs[main_root][sub_category])
for(var/list/design in GLOB.floor_designs[main_root][sub_category])
if(!design["datum"])
populate_rtd_datums()
var/datum/tile_info/tile_data = design["datum"]
@@ -17,5 +15,5 @@
var/sprite_name = sanitize_css_class_name("[tile_data.icon_file]-[tile_data.icon_state]-[dir2text(direction)]")
if(registered[sprite_name])
continue
Insert(sprite_name, icon(tile_data.icon_file, tile_data.icon_state, direction))
insert_icon(sprite_name, uni_icon(tile_data.icon_file, tile_data.icon_state, direction))
registered[sprite_name] = TRUE
+4 -5
View File
@@ -1,14 +1,13 @@
/datum/asset/spritesheet/seeds
/datum/asset/spritesheet_batched/seeds
name = "seeds"
/datum/asset/spritesheet/seeds/create_spritesheets()
/datum/asset/spritesheet_batched/seeds/create_spritesheets()
var/list/id_list = list()
for (var/path in subtypesof(/obj/item/seeds))
var/obj/item/seeds/seed_type = path
for (var/obj/item/seeds/seed_type as anything in subtypesof(/obj/item/seeds))
var/icon = initial(seed_type.icon)
var/icon_state = initial(seed_type.icon_state)
var/id = sanitize_css_class_name("[icon][icon_state]")
if(id in id_list) //no dupes
continue
id_list += id
Insert(id, icon, icon_state)
insert_icon(id, uni_icon(icon, icon_state))
@@ -1,6 +1,6 @@
/datum/asset/spritesheet/sheetmaterials
/datum/asset/spritesheet_batched/sheetmaterials
name = "sheetmaterials"
/datum/asset/spritesheet/sheetmaterials/create_spritesheets()
InsertAll("", 'icons/obj/stack_objects.dmi')
/datum/asset/spritesheet_batched/sheetmaterials/create_spritesheets()
insert_all_icons("", 'icons/obj/stack_objects.dmi')
@@ -1,27 +1,27 @@
/datum/asset/spritesheet/supplypods
/datum/asset/spritesheet_batched/supplypods
name = "supplypods"
/datum/asset/spritesheet/supplypods/create_spritesheets()
/datum/asset/spritesheet_batched/supplypods/create_spritesheets()
for (var/datum/pod_style/style as anything in typesof(/datum/pod_style))
if (ispath(style, /datum/pod_style/seethrough))
Insert("pod_asset[style::id]", icon('icons/obj/supplypods.dmi' , "seethrough-icon"))
insert_icon("pod_asset[style::id]", uni_icon('icons/obj/supplypods.dmi' , "seethrough-icon"))
continue
var/base = style::icon_state
if (!base)
Insert("pod_asset[style::id]", icon('icons/obj/supplypods.dmi', "invisible-icon"))
insert_icon("pod_asset[style::id]", uni_icon('icons/obj/supplypods.dmi', "invisible-icon"))
continue
var/icon/podIcon = icon('icons/obj/supplypods.dmi', base)
var/datum/universal_icon/pod_icon = uni_icon('icons/obj/supplypods.dmi', base, SOUTH)
var/door = style::has_door
if (door)
door = "[base]_door"
podIcon.Blend(icon('icons/obj/supplypods.dmi', door), ICON_OVERLAY)
pod_icon.blend_icon(uni_icon('icons/obj/supplypods.dmi', door), ICON_OVERLAY)
var/shape = style::shape
if (shape == POD_SHAPE_NORMAL)
var/decal = style::decal_icon
if (decal)
podIcon.Blend(icon('icons/obj/supplypods.dmi', decal), ICON_OVERLAY)
pod_icon.blend_icon(uni_icon('icons/obj/supplypods.dmi', decal), ICON_OVERLAY)
var/glow = style::glow_color
if (glow)
glow = "pod_glow_[glow]"
podIcon.Blend(icon('icons/obj/supplypods.dmi', glow), ICON_OVERLAY)
Insert("pod_asset[style::id]", podIcon)
pod_icon.blend_icon(uni_icon('icons/obj/supplypods.dmi', glow), ICON_OVERLAY)
insert_icon("pod_asset[style::id]", pod_icon)
+3 -3
View File
@@ -1,12 +1,12 @@
/datum/asset/spritesheet/telecomms
/datum/asset/spritesheet_batched/telecomms
name = "tcomms"
/datum/asset/spritesheet/telecomms/create_spritesheets()
/datum/asset/spritesheet_batched/telecomms/create_spritesheets()
var/list/inserted_states = list() // No need to send entire `telecomms.dmi`.
for(var/obj/machinery/telecomms/machine as anything in subtypesof(/obj/machinery/telecomms))
var/icon_state = machine::icon_state
if(icon_state in inserted_states)
continue
Insert(icon_state, machine::icon, icon_state)
insert_icon(icon_state, uni_icon(machine::icon, icon_state))
inserted_states += icon_state
+14 -19
View File
@@ -1,10 +1,10 @@
/datum/asset/spritesheet/vending
/datum/asset/spritesheet_batched/vending
name = "vending"
/datum/asset/spritesheet/vending/create_spritesheets()
/datum/asset/spritesheet_batched/vending/create_spritesheets()
// initialising the list of items we need
var/target_items = list()
for(var/obj/machinery/vending/vendor as anything in typesof(/obj/machinery/vending))
for(var/obj/machinery/vending/vendor as anything in subtypesof(/obj/machinery/vending))
vendor = new vendor() // It seems `initial(list var)` has nothing. need to make a type.
target_items |= vendor.products
target_items |= vendor.premium
@@ -16,21 +16,21 @@
if (!ispath(item, /atom))
continue
var/icon_file
var/icon_state = initial(item.icon_state)
var/icon_color = initial(item.color)
// GAGS icons must be pregenerated
if(initial(item.greyscale_config) && initial(item.greyscale_colors))
icon_file = SSgreyscale.GetColoredIconByType(initial(item.greyscale_config), initial(item.greyscale_colors))
// Colored atoms must be pregenerated
else if(icon_color && icon_state)
icon_file = initial(item.icon)
if(ispath(item, /obj))
var/obj/obj_atom = item
if(initial(obj_atom.icon_state_preview))
icon_state = initial(obj_atom.icon_state_preview)
var/has_gags = initial(item.greyscale_config) && initial(item.greyscale_colors)
var/has_color = initial(item.color) && icon_state
// GAGS and colored icons must be pregenerated
// Otherwise we can rely on DMIcon, so skip it to save init time
else
if(!has_gags && !has_color)
continue
if (PERFORM_ALL_TESTS(focus_only/invalid_vending_machine_icon_states))
if (!icon_exists(icon_file, icon_state))
if (!has_gags && !icon_exists(initial(item.icon), icon_state))
var/icon_file = initial(item.icon)
var/icon_states_string
for (var/an_icon_state in icon_states(icon_file))
if (!icon_states_string)
@@ -41,10 +41,5 @@
stack_trace("[item] does not have a valid icon state, icon=[icon_file], icon_state=[json_encode(icon_state)]([text_ref(icon_state)]), icon_states=[icon_states_string]")
continue
var/icon/produced = icon(icon_file, icon_state, SOUTH)
if (!isnull(icon_color) && icon_color != COLOR_WHITE)
produced.Blend(icon_color, ICON_MULTIPLY)
var/imgid = replacetext(replacetext("[item]", "/obj/item/", ""), "/", "-")
Insert(imgid, produced)
insert_icon(imgid, get_display_icon_for(item))
@@ -0,0 +1,365 @@
#define SPR_SIZE "size_id"
#define SPR_IDX "position"
#define CACHE_WAIT "wait"
#define CACHE_INVALID TRUE
#define CACHE_VALID FALSE
/// This is used to invalidate the cache if something changes on the DM side. For example, if the CSS generator was changed.
#define SPRITESHEET_SYSTEM_VERSION 1
/datum/asset/spritesheet_batched
_abstract = /datum/asset/spritesheet_batched
var/name
/// list("32x32")
var/list/sizes = list()
/// "foo_bar" -> list("32x32", 5, entry_obj)
var/list/sprites = list()
// "foo_bar" -> entry_obj
var/list/entries = list()
/// JSON encoded version of entries.
var/entries_json = null
/// If this spritesheet exists in a completed state.
var/fully_generated = FALSE
/// If this asset should be fully loaded on new
/// Defaults to false so we can process this stuff nicely
var/load_immediately = FALSE
/// If we should avoid propogating 'invalid dir' errors from rust-g. Because sometimes, you just don't know what dirs are valid.
var/ignore_dir_errors = FALSE
/// Forces use of the smart cache. This is for unit tests, please respect the config <3
var/force_cache = FALSE
/// If there is currently an async job, its ID
var/job_id = null
/// If there is currently an async cache job, its ID.
var/cache_job_id = null
// Fields to store async cache task inputs.
var/cache_data = null
var/cache_sizes_data = null
var/cache_sprites_data = null
var/cache_input_hash = null
var/cache_dmi_hashes = null
var/cache_dmi_hashes_json = null
/// Used to prevent async cache refresh jobs from looping on failure.
var/cache_result = null
/datum/asset/spritesheet_batched/proc/should_load_immediately()
#ifdef DO_NOT_DEFER_ASSETS
return TRUE
#else
return load_immediately
#endif
/// Returns true if the cache should be invalidated/doesn't exist.
/datum/asset/spritesheet_batched/should_refresh(yield)
. = CACHE_INVALID // in the case of any errors, we need to regenerate.
if(!fexists("[ASSET_CROSS_ROUND_SMART_CACHE_DIRECTORY]/spritesheet_cache.[name].json"))
return CACHE_INVALID
if(!fexists("data/spritesheets/spritesheet_[name].css"))
return CACHE_INVALID
if(isnull(cache_data) || isnull(cache_dmi_hashes_json))
cache_data = rustg_file_read("[ASSET_CROSS_ROUND_SMART_CACHE_DIRECTORY]/spritesheet_cache.[name].json")
if(!findtext(cache_data, "{", 1, 2)) // cache isn't valid JSON
log_asset("Cache for spritesheet_[name] was not valid JSON. This is abnormal. Likely tampered with or IO failure.")
return CACHE_INVALID
var/cache_json = json_decode(cache_data)
// Best to invalidate if rustg updates, since the way icons are handled can change.
var/cached_rustg_version = cache_json["rustg_version"]
if(isnull(cached_rustg_version))
log_asset("Cache for spritesheet_[name] did not contain a rustg_version!")
return CACHE_INVALID
var/rustg_version = rustg_get_version()
if(cached_rustg_version != rustg_version)
log_asset("Invalidated cache for spritesheet_[name] due to rustg updating from [cached_rustg_version] to [rustg_version].")
return CACHE_INVALID
// Invalidate cache if the DM version changes
var/cached_dm_version = cache_json["dm_version"]
if(isnull(cached_dm_version))
log_asset("Cache for spritesheet_[name] did not contain a dm_version!")
return CACHE_INVALID
if(cached_dm_version != SPRITESHEET_SYSTEM_VERSION)
log_asset("Invalidated cache for spritesheet_[name] due to DM spritesheet system updating from [cached_dm_version] to [SPRITESHEET_SYSTEM_VERSION].")
return CACHE_INVALID
cache_sizes_data = cache_json["sizes"]
cache_sprites_data = cache_json["sprites"]
cache_input_hash = cache_json["input_hash"]
cache_dmi_hashes = cache_json["dmi_hashes"]
if(!length(cache_dmi_hashes) || !length(cache_input_hash) || !length(cache_sizes_data) || !length(cache_sprites_data))
log_asset("Cache for spritesheet_[name] did not contain the correct data. This is abnormal. Likely tampered with.")
return CACHE_INVALID
cache_dmi_hashes_json = json_encode(cache_dmi_hashes)
var/data_out
if(yield || !isnull(cache_job_id))
if(isnull(cache_job_id))
cache_job_id = rustg_iconforge_cache_valid_async(cache_input_hash, cache_dmi_hashes_json, entries_json)
. = CACHE_WAIT // if we return during this, WAIT!!
UNTIL((data_out = rustg_iconforge_check(cache_job_id)) != RUSTG_JOB_NO_RESULTS_YET)
cache_job_id = null
. = CACHE_INVALID // reset back to normal, invalid on CRASH
else
data_out = rustg_iconforge_cache_valid(cache_input_hash, cache_dmi_hashes_json, entries_json)
if (data_out == RUSTG_JOB_ERROR)
CRASH("Spritesheet [name] cache JOB PANIC")
else if(!findtext(data_out, "{", 1, 2))
rustg_file_write(cache_data, "[GLOB.log_directory]/spritesheet_cache_debug.[name].json")
rustg_file_write(entries_json, "[GLOB.log_directory]/spritesheet_debug_[name].json")
CRASH("Spritesheet [name] cache check UNKNOWN ERROR: [data_out]")
var/result = json_decode(data_out)
var/fail = result["fail_reason"]
if(length(fail) || result["result"] != "1")
if(findtextEx(fail, "ERROR:"))
CRASH("Spritesheet [name] cache check UNKNOWN [fail]")
log_asset("Invalidated cache for spritesheet_[name]: [fail]")
return CACHE_INVALID
// Populate the sizes and sprites list.
sizes = cache_sizes_data
sprites = cache_sprites_data
log_asset("Validated cache for spritesheet_[name]!")
return CACHE_VALID
/datum/asset/spritesheet_batched/proc/insert_icon(sprite_name, datum/universal_icon/entry)
if(!istext(sprite_name) || !length(sprite_name))
CRASH("Invalid sprite_name \"[sprite_name]\" given to insert_icon()! Providing non-strings will break icon generation.")
if(!istype(entry))
CRASH("Invalid type provided to insert_icon()! Value: [entry] (type: [entry?.type])")
entries[sprite_name] = entry.to_list()
/datum/asset/spritesheet_batched/register()
SHOULD_NOT_OVERRIDE(TRUE)
if (!name)
CRASH("spritesheet [type] cannot register without a name")
// Create our input data first, so we can compare to the cache.
create_spritesheets()
if(should_load_immediately())
realize_spritesheets(yield = FALSE)
else
SSasset_loading.queue_asset(src)
/datum/asset/spritesheet_batched/unregister()
CRASH("unregister() called on batched spritesheet! Bad!")
/// Call insert_icon or insert_all_icons here, building a spritesheet!
/datum/asset/spritesheet_batched/proc/create_spritesheets()
CRASH("create_spritesheets() not implemented for [type]!")
/datum/asset/spritesheet_batched/proc/insert_all_icons(prefix, icon/I, list/directions, prefix_with_dirs = TRUE)
if (length(prefix))
prefix = "[prefix]-"
if (!directions)
directions = list(SOUTH)
for (var/icon_state_name in icon_states(I))
for (var/direction in directions)
var/prefix2 = (directions.len > 1 && prefix_with_dirs) ? "[dir2text(direction)]-" : ""
insert_icon("[prefix][prefix2][icon_state_name]", uni_icon(I, icon_state_name, direction))
/datum/asset/spritesheet_batched/proc/realize_spritesheets(yield)
if(fully_generated)
return
if(!length(entries))
CRASH("Spritesheet [name] ([type]) is empty! What are you doing?")
if(isnull(entries_json))
entries_json = json_encode(entries)
if(isnull(cache_result))
cache_result = should_refresh(yield)
if(cache_result == CACHE_WAIT) // sleep interrupted by MC. We'll get queried again later.
cache_result = null
return
// read_from_cache returns false if config is disabled, otherwise it fully loads the spritesheet.
if (cache_result == CACHE_VALID && read_from_cache())
SSasset_loading.dequeue_asset(src)
fully_generated = TRUE
return
// Remove the cache, since it's invalid if we get to this point.
fdel("[ASSET_CROSS_ROUND_SMART_CACHE_DIRECTORY]/spritesheet_cache.[name].json")
var/do_cache = CONFIG_GET(flag/smart_cache_assets) || force_cache
var/data_out
if(yield || !isnull(job_id))
if(isnull(job_id))
job_id = rustg_iconforge_generate_async("data/spritesheets/", name, entries_json, do_cache)
UNTIL((data_out = rustg_iconforge_check(job_id)) != RUSTG_JOB_NO_RESULTS_YET)
else
data_out = rustg_iconforge_generate("data/spritesheets/", name, entries_json, do_cache)
if (data_out == RUSTG_JOB_ERROR)
CRASH("Spritesheet [name] JOB PANIC")
else if(!findtext(data_out, "{", 1, 2))
rustg_file_write(entries_json, "[GLOB.log_directory]/spritesheet_debug_[name].json")
CRASH("Spritesheet [name] UNKNOWN ERROR: [data_out]")
var/data = json_decode(data_out)
sizes = data["sizes"]
sprites = data["sprites"]
var/input_hash = data["sprites_hash"]
var/dmi_hashes = data["dmi_hashes"] // this only contains values if do_cache is TRUE.
for(var/size_id in sizes)
var/png_name = "[name]_[size_id].png"
var/file_directory = "data/spritesheets/[png_name]"
var/file_hash = rustg_hash_file(RUSTG_HASH_MD5, file_directory)
SSassets.transport.register_asset(png_name, fcopy_rsc(file_directory), file_hash)
if(CONFIG_GET(flag/save_spritesheets))
save_to_logs(file_name = png_name, file_location = file_directory)
var/css_name = "spritesheet_[name].css"
var/file_directory = "data/spritesheets/[css_name]"
fdel(file_directory)
var/css = generate_css()
rustg_file_write(css, file_directory)
var/css_hash = rustg_hash_string(RUSTG_HASH_MD5, css)
SSassets.transport.register_asset(css_name, fcopy_rsc(file_directory), file_hash=css_hash)
if(CONFIG_GET(flag/save_spritesheets))
save_to_logs(file_name = css_name, file_location = file_directory)
if (do_cache)
write_cache_meta(input_hash, dmi_hashes)
fully_generated = TRUE
// If we were ever in there, remove ourselves
SSasset_loading.dequeue_asset(src)
if(data["error"] && !(ignore_dir_errors && findtext(data["error"], "is not in the set of valid dirs")))
CRASH("Error during spritesheet generation for [name]: [data["error"]]")
/datum/asset/spritesheet_batched/queued_generation()
realize_spritesheets(yield = TRUE)
/datum/asset/spritesheet_batched/ensure_ready()
if(!fully_generated)
realize_spritesheets(yield = FALSE)
return ..()
/datum/asset/spritesheet_batched/send(client/client)
if (!name)
return
var/all = list("spritesheet_[name].css")
for(var/size_id in sizes)
all += "[name]_[size_id].png"
. = SSassets.transport.send_assets(client, all)
/datum/asset/spritesheet_batched/get_url_mappings()
if (!name)
return
. = list("spritesheet_[name].css" = SSassets.transport.get_asset_url("spritesheet_[name].css"))
for(var/size_id in sizes)
.["[name]_[size_id].png"] = SSassets.transport.get_asset_url("[name]_[size_id].png")
/datum/asset/spritesheet_batched/proc/generate_css()
var/list/out = list()
for (var/size_id in sizes)
var/size_split = splittext(size_id, "x")
var/width = text2num(size_split[1])
var/height = text2num(size_split[2])
out += ".[name][size_id]{display:inline-block;width:[width]px;height:[height]px;background-image:url('[get_background_url("[name]_[size_id].png")]');background-repeat:no-repeat;}"
for (var/sprite_id in sprites)
var/sprite = sprites[sprite_id]
var/size_id = sprite[SPR_SIZE]
var/idx = sprite[SPR_IDX]
var/size_split = splittext(size_id, "x")
var/width = text2num(size_split[1])
var/x = idx * width
var/y = 0
out += ".[name][size_id].[sprite_id]{background-position:-[x]px -[y]px;}"
return out.Join("\n")
/datum/asset/spritesheet_batched/proc/read_from_cache()
if(!CONFIG_GET(flag/smart_cache_assets) && !force_cache)
return FALSE
// this is already guaranteed to exist.
var/css_name = "spritesheet_[name].css"
var/css_file_directory = "data/spritesheets/[css_name]"
// sizes gets filled during should_refresh()
for(var/size_id in sizes)
var/fname = "data/spritesheets/[name]_[size_id].png"
if(!fexists(fname))
return FALSE
var/css_hash = rustg_hash_file(RUSTG_HASH_MD5, css_file_directory)
SSassets.transport.register_asset(css_name, fcopy_rsc(css_file_directory), file_hash=css_hash)
for(var/size_id in sizes)
var/fname = "data/spritesheets/[name]_[size_id].png"
var/hash = rustg_hash_file(RUSTG_HASH_MD5, fname)
SSassets.transport.register_asset("[name]_[size_id].png", fcopy_rsc(fname), file_hash=hash)
if(CONFIG_GET(flag/save_spritesheets))
save_to_logs(file_name = css_name, file_location = css_file_directory)
return TRUE
/// Returns the URL to put in the background:url of the CSS asset
/datum/asset/spritesheet_batched/proc/get_background_url(asset)
return SSassets.transport.get_asset_url(asset)
/datum/asset/spritesheet_batched/proc/write_cache_meta(input_hash, dmi_hashes)
var/list/cache_data = list(
"input_hash" = input_hash,
"dmi_hashes" = dmi_hashes,
"sizes" = sizes,
"sprites" = sprites,
"rustg_version" = rustg_get_version(),
"dm_version" = SPRITESHEET_SYSTEM_VERSION,
)
rustg_file_write(json_encode(cache_data), "[ASSET_CROSS_ROUND_SMART_CACHE_DIRECTORY]/spritesheet_cache.[name].json")
/**
* Third party helpers
* ===================
*/
/datum/asset/spritesheet_batched/proc/css_tag()
return {"<link rel="stylesheet" href="[css_filename()]" />"}
/datum/asset/spritesheet_batched/proc/css_filename()
return SSassets.transport.get_asset_url("spritesheet_[name].css")
/datum/asset/spritesheet_batched/proc/icon_tag(sprite_name)
var/sprite = sprites[sprite_name]
if (!sprite)
return null
var/size_id = sprite[SPR_SIZE]
return "<span class='[name][size_id] [sprite_name]'></span>"
/datum/asset/spritesheet_batched/proc/icon_class_name(sprite_name)
var/sprite = sprites[sprite_name]
if (!sprite)
return null
var/size_id = sprite[SPR_SIZE]
return "[name][size_id] [sprite_name]"
/**
* Returns the size class (ex design32x32) for a given sprite's icon
*
* Arguments:
* * sprite_name - The sprite to get the size of
*/
/datum/asset/spritesheet_batched/proc/icon_size_id(sprite_name)
var/sprite = sprites[sprite_name]
if (!sprite)
return null
var/size_id = sprite[SPR_SIZE]
return "[name][size_id]"
#undef SPR_SIZE
#undef SPR_IDX
#undef CACHE_WAIT
#undef CACHE_INVALID
#undef CACHE_VALID
#undef SPRITESHEET_SYSTEM_VERSION
@@ -0,0 +1,374 @@
/// This is intended to replace /icon, allowing rustg to generate icons much faster than DM can at scale.
/// Construct these with the uni_icon() proc, in the same manner as BYOND's icon() proc.
/// Additionally supports a number of transform procs (lowercase, rather than BYOND's uppercase)
/// such as Crop, Scale, and Blend (as blend_icon/blend_color).
/datum/universal_icon
var/icon/icon_file
var/icon_state
var/dir
var/frame
var/datum/icon_transformer/transform
/// Don't instantiate these yourself, use uni_icon.
/datum/universal_icon/New(icon/icon_file, icon_state="", dir=SOUTH, frame=1, datum/icon_transformer/transform=null, color=null)
#ifdef UNIT_TESTS
// This check is kinda slow and shouldn't fail unless a developer makes a mistake. So it'll get caught in unit tests.
if(!isicon(icon_file) || !isfile(icon_file) || "[icon_file]" == "/icon" || !length("[icon_file]"))
// bad! use 'icons/path_to_dmi.dmi' format only
CRASH("FATAL: universal_icon was provided icon_file: [icon_file] - icons provided to batched spritesheets MUST be DMI files, they cannot be /image, /icon, or other runtime generated icons.")
#endif
src.icon_file = icon_file
src.icon_state = icon_state
src.dir = dir
src.frame = frame
if(isnull(transform) && !isnull(color) && uppertext(color) != "#FFFFFF")
var/datum/icon_transformer/T = new()
if(color)
T.blend_color(color, ICON_MULTIPLY)
src.transform = T
else if(!isnull(transform))
src.transform = transform
else // null = empty list
src.transform = null
/datum/universal_icon/proc/copy()
RETURN_TYPE(/datum/universal_icon)
var/datum/universal_icon/new_icon = new(icon_file, icon_state, dir, frame)
if(!isnull(src.transform))
new_icon.transform = src.transform.copy()
return new_icon
/datum/universal_icon/proc/blend_color(color, blend_mode)
if(!transform)
transform = new
transform.blend_color(color, blend_mode)
return src
/datum/universal_icon/proc/blend_icon(datum/universal_icon/icon_object, blend_mode)
if(!transform)
transform = new
transform.blend_icon(icon_object, blend_mode)
return src
/datum/universal_icon/proc/scale(width, height)
if(!transform)
transform = new
transform.scale(width, height)
return src
/datum/universal_icon/proc/crop(x1, y1, x2, y2)
if(!transform)
transform = new
transform.crop(x1, y1, x2, y2)
return src
/// Internally performs a crop.
/datum/universal_icon/proc/shift(dir, amount, icon_width, icon_height)
if(!transform)
transform = new
var/list/offsets = dir2offset(dir)
var/shift_x = -offsets[1] * amount
var/shift_y = -offsets[2] * amount
transform.crop(1 + shift_x, 1 + shift_y, icon_width + shift_x, icon_height + shift_y)
return src
/// Internally performs a color blend.
/// Amount ranges from 0-1 (100% opacity)
/datum/universal_icon/proc/change_opacity(amount)
if(!transform)
transform = new
transform.blend_color("#ffffff[num2hex(clamp(amount, 0, 1) * 255, 2)]", ICON_MULTIPLY)
return src
/datum/universal_icon/proc/to_list()
RETURN_TYPE(/list)
return list("icon_file" = "[icon_file]", "icon_state" = icon_state, "dir" = dir, "frame" = frame, "transform" = !isnull(transform) ? transform.to_list() : list())
/proc/universal_icon_from_list(list/input_in)
RETURN_TYPE(/datum/universal_icon)
var/list/input = input_in.Copy() // copy, since icon_transformer_from_list will mutate the list.
return uni_icon(input["icon_file"], input["icon_state"], input["dir"], input["frame"], icon_transformer_from_list(input["transform"]))
/datum/universal_icon/proc/to_json()
return json_encode(to_list())
/datum/universal_icon/proc/to_icon()
RETURN_TYPE(/icon)
var/icon/self = icon(src.icon_file, src.icon_state, dir=src.dir, frame=src.frame)
if(istype(src.transform))
src.transform.apply(self)
return self
/datum/icon_transformer
var/list/transforms = null
/datum/icon_transformer/New()
transforms = list()
/// Applies the contained set of transforms to an icon
/datum/icon_transformer/proc/apply(icon/target)
RETURN_TYPE(/icon)
for(var/transform in src.transforms)
switch(transform["type"])
if(RUSTG_ICONFORGE_BLEND_COLOR)
target.Blend(transform["color"], transform["blend_mode"])
if(RUSTG_ICONFORGE_BLEND_ICON)
var/datum/universal_icon/icon_object = transform["icon"]
if(!istype(icon_object))
stack_trace("Invalid icon found in icon transformer during apply()! [icon_object]")
continue
target.Blend(icon_object.to_icon(), transform["blend_mode"])
if(RUSTG_ICONFORGE_SCALE)
target.Scale(transform["width"], transform["height"])
if(RUSTG_ICONFORGE_CROP)
target.Crop(transform["x1"], transform["y1"], transform["x2"], transform["y2"])
return target
/datum/icon_transformer/proc/copy()
RETURN_TYPE(/datum/icon_transformer)
var/datum/icon_transformer/new_transformer = new()
new_transformer.transforms = list()
for(var/transform in src.transforms)
new_transformer.transforms += list(deep_copy_list_alt(transform))
return new_transformer
/datum/icon_transformer/proc/blend_color(color, blend_mode)
#ifdef UNIT_TESTS
if(!istext(color))
CRASH("Invalid color provided to blend_color: [color]")
if(!isnum(blend_mode))
CRASH("Invalid blend_mode provided to blend_color: [blend_mode]")
#endif
transforms += list(list("type" = RUSTG_ICONFORGE_BLEND_COLOR, "color" = color, "blend_mode" = blend_mode))
/datum/icon_transformer/proc/blend_icon(datum/universal_icon/icon_object, blend_mode)
#ifdef UNIT_TESTS
// icon_object's type is checked later in to_list
if(!isnum(blend_mode))
CRASH("Invalid blend_mode provided to blend_icon: [blend_mode]")
#endif
transforms += list(list("type" = RUSTG_ICONFORGE_BLEND_ICON, "icon" = icon_object, "blend_mode" = blend_mode))
/datum/icon_transformer/proc/scale(width, height)
#ifdef UNIT_TESTS
if(!isnum(width) || !isnum(height))
CRASH("Invalid arguments provided to scale: [width],[height]")
#endif
transforms += list(list("type" = RUSTG_ICONFORGE_SCALE, "width" = width, "height" = height))
/datum/icon_transformer/proc/crop(x1, y1, x2, y2)
#ifdef UNIT_TESTS
if(!isnum(x1) || !isnum(y1) || !isnum(x2) || !isnum(y2))
CRASH("Invalid arguments provided to crop: [x1],[y1],[x2],[y2]")
#endif
transforms += list(list("type" = RUSTG_ICONFORGE_CROP, "x1" = x1, "y1" = y1, "x2" = x2, "y2" = y2))
/// Recursively converts all contained [/datum/universal_icon]s and their associated [/datum/icon_transformer]s into list form so the transforms can be JSON encoded.
/datum/icon_transformer/proc/to_list()
RETURN_TYPE(/list)
var/list/transforms_out = list()
var/list/transforms_original = src.transforms.Copy()
for(var/list/transform as anything in transforms_original)
var/list/this_transform = transform.Copy() // copy it so we don't mutate the original
if(transform["type"] == RUSTG_ICONFORGE_BLEND_ICON)
var/datum/universal_icon/icon_object = this_transform["icon"]
if(!istype(icon_object))
stack_trace("Invalid icon found in icon transformer during to_list()! [icon_object]")
continue
// This mutates the inner transform list!!! Make sure it only runs on copies.
this_transform["icon"] = icon_object.to_list()
transforms_out += list(this_transform)
return transforms_out
/// Reverse operation of /datum/icon_transformer/to_list()
/proc/icon_transformer_from_list(list/input)
RETURN_TYPE(/datum/icon_transformer)
var/list/transforms = list()
for(var/list/transform as anything in input)
// don't mutate the input :(
var/this_transform = transform.Copy()
if(transform["type"] == RUSTG_ICONFORGE_BLEND_ICON)
this_transform["icon"] = universal_icon_from_list(transform["icon"])
transforms += list(this_transform)
var/datum/icon_transformer/transformer = new()
transformer.transforms = transforms
return transformer
/// Constructs a transformer, with optional color multiply pre-added.
/proc/color_transform(color=null)
RETURN_TYPE(/datum/icon_transformer)
var/datum/icon_transformer/transform = new()
if(color)
transform.blend_color(color, ICON_MULTIPLY)
return transform
/// Converts a GAGS atom to a universal icon by generating blend operations.
/proc/gags_to_universal_icon(atom/path)
RETURN_TYPE(/datum/universal_icon)
if(!ispath(path, /atom) || !initial(path.greyscale_config) || !initial(path.greyscale_colors))
CRASH("gags_to_universal_icon() received an invalid path of \"[path]\"!")
var/datum/greyscale_config/config = initial(path.greyscale_config)
var/colors = initial(path.greyscale_colors)
var/datum/universal_icon/entry = SSgreyscale.GetColoredIconByTypeUniversalIcon(config, colors, initial(path.icon_state))
return entry
/// Gets the relevant universal icon for an atom, when displayed in TGUI. (see: icon_state_preview)
/// Supports GAGS items and colored items.
/proc/get_display_icon_for(atom/atom_path)
if (!ispath(atom_path, /atom))
return FALSE
var/icon_file = initial(atom_path.icon)
var/icon_state = initial(atom_path.icon_state)
if(initial(atom_path.greyscale_config) && initial(atom_path.greyscale_colors))
return gags_to_universal_icon(atom_path)
if(ispath(atom_path, /obj))
var/obj/obj_path = atom_path
if(initial(obj_path.icon_state_preview))
icon_state = initial(obj_path.icon_state_preview)
return uni_icon(icon_file, icon_state, color=initial(atom_path.color))
/// getFlatIcon for [/datum/universal_icon]s
/// Only supports 32x32 icons facing south
/// Tough luck if you want anything else
/// Still fairly slow for complex appearances due to filesystem operations. Try to avoid using it
/proc/get_flat_uni_icon(image/appearance, deficon, defstate, defblend, start = TRUE, parentcolor)
// Loop through the underlays, then overlays, sorting them into the layers list
#define PROCESS_OVERLAYS_OR_UNDERLAYS(flat, process, base_layer) \
for (var/i in 1 to process.len) { \
var/image/current = process[i]; \
if (!current) { \
continue; \
} \
if (current.plane != FLOAT_PLANE && current.plane != appearance.plane) { \
continue; \
} \
var/current_layer = current.layer; \
if (current_layer < 0) { \
if (current_layer <= -1000) { \
return flat; \
} \
current_layer = base_layer + appearance.layer + current_layer / 1000; \
} \
/* If we are using topdown rendering, chop that part off so things layer together as expected */ \
if((current_layer >= TOPDOWN_LAYER && current_layer < EFFECTS_LAYER) || current_layer > TOPDOWN_LAYER + EFFECTS_LAYER) { \
current_layer -= TOPDOWN_LAYER; \
} \
for (var/index_to_compare_to in 1 to layers.len) { \
var/compare_to = layers[index_to_compare_to]; \
if (current_layer < layers[compare_to]) { \
layers.Insert(index_to_compare_to, current); \
break; \
} \
} \
layers[current] = current_layer; \
}
var/datum/universal_icon/flat = uni_icon('icons/blanks/32x32.dmi', "nothing")
if(!appearance || appearance.alpha <= 0)
return flat
if(start)
if(!deficon)
deficon = appearance.icon
if(!defstate)
defstate = appearance.icon_state
if(!defblend)
defblend = appearance.blend_mode
var/should_display = TRUE
var/curicon = appearance.icon || deficon
var/string_curicon = "[curicon]"
var/curstate = appearance.icon_state || defstate
// Filter out 'runtime' icons (server-generated RSC cache icons)
// Write the icon to the filesystem so it can be used by iconforge
if(!isfile(curicon) || string_curicon == "/icon" || string_curicon == "/image" || !length(string_curicon))
var/file_path_tmp = "tmp/uni_icon-tmp-[rand(1, 999)].dmi" // this filename is temporary.
fcopy(curicon, file_path_tmp)
var/file_hash = rustg_hash_file(RUSTG_HASH_MD5, file_path_tmp)
// Use the hash as its new filename - this allows the uni_icon to be smart cached, because the filename will be consistent between runs if the content is the same
var/file_path = "tmp/uni_icon-[file_hash].dmi"
fcopy(file_path_tmp, file_path)
fdel(file_path_tmp) // delete the old one
curicon = file(file_path)
var/curblend = appearance.blend_mode || defblend
var/list/curstates = icon_states(curicon)
if(!(curstate in curstates))
if("" in curstates) // BYOND defaulting functionality
curstate = ""
else
should_display = FALSE
if(appearance.overlays.len || appearance.underlays.len)
// Layers will be a sorted list of icons/overlays, based on the order in which they are displayed
var/list/layers = list()
var/image/copy
if(should_display)
// Add the atom's icon itself, without pixel_x/y offsets.
copy = image(icon=curicon, icon_state=curstate, layer=appearance.layer, dir=SOUTH)
copy.color = appearance.color
copy.alpha = appearance.alpha
copy.blend_mode = curblend
layers[copy] = appearance.layer
PROCESS_OVERLAYS_OR_UNDERLAYS(flat, appearance.underlays, 0)
PROCESS_OVERLAYS_OR_UNDERLAYS(flat, appearance.overlays, 1)
var/datum/universal_icon/add // Icon of overlay being added
if(appearance.color)
if(islist(appearance.color))
stack_trace("Unsupported color map appearance provided to get_flat_uni_icon, ignoring it.")
else
flat.blend_color(appearance.color, ICON_MULTIPLY)
if(parentcolor && !(appearance.appearance_flags & RESET_COLOR))
if(islist(parentcolor))
stack_trace("Unsupported color map appearance provided to get_flat_uni_icon, ignoring it.")
else
flat.blend_color(parentcolor, ICON_MULTIPLY)
var/next_parentcolor = appearance.color || parentcolor
for(var/image/layer_image as anything in layers)
if(layer_image.alpha == 0)
continue
if(layer_image == copy && length("[layer_image.icon]")) // 'layer_image' is an /image based on the object being flattened, and isn't a 'runtime' icon.
curblend = BLEND_OVERLAY
add = uni_icon(layer_image.icon, layer_image.icon_state, SOUTH)
if(appearance.color)
if(islist(appearance.color))
stack_trace("Unsupported color map appearance provided to get_flat_uni_icon, ignoring it.")
else
add.blend_color(appearance.color, ICON_MULTIPLY)
else // 'layer_image' is an appearance object.
add = get_flat_uni_icon(layer_image, curicon, curstate, curblend, FALSE, next_parentcolor)
if(!add || !length(add.icon_file))
continue
// Blend the overlay into the flattened icon
flat.blend_icon(add, blendMode2iconMode(curblend))
if(appearance.alpha < 255)
flat.blend_color(rgb(255, 255, 255, appearance.alpha), ICON_MULTIPLY)
return flat
else if(should_display) // There's no overlays.
var/datum/universal_icon/final_icon = uni_icon(curicon, curstate, SOUTH)
if (appearance.alpha < 255)
final_icon.blend_color(rgb(255,255,255, appearance.alpha), ICON_MULTIPLY)
if (appearance.color)
if (islist(appearance.color))
stack_trace("Unsupported color map appearance provided to get_flat_uni_icon, ignoring it.")
else
final_icon.blend_color(appearance.color, ICON_MULTIPLY)
return final_icon
#undef PROCESS_OVERLAYS_OR_UNDERLAYS
@@ -0,0 +1,418 @@
// spritesheet implementation - coalesces various icons into a single .png file
// and uses CSS to select icons out of that file - saves on transferring some
// 1400-odd individual PNG files
#define SPR_SIZE 1
#define SPR_IDX 2
#define SPRSZ_COUNT 1
#define SPRSZ_ICON 2
#define SPRSZ_STRIPPED 3
/// Deprecated: Use /datum/asset/spritesheet_batched where possible
/datum/asset/spritesheet
_abstract = /datum/asset/spritesheet
cross_round_cachable = TRUE
var/name
/// List of arguments to pass into queuedInsert
/// Exists so we can queue icon insertion, mostly for stuff like preferences
var/list/to_generate = list()
var/list/sizes = list() // "32x32" -> list(10, icon/normal, icon/stripped)
var/list/sprites = list() // "foo_bar" -> list("32x32", 5)
var/list/cached_spritesheets_needed
var/generating_cache = FALSE
var/fully_generated = FALSE
/// If this asset should be fully loaded on new
/// Defaults to false so we can process this stuff nicely
var/load_immediately = FALSE
// Kept in state so that the result is the same, even when the files are created, for this run
VAR_PRIVATE/should_refresh = null
/datum/asset/spritesheet/proc/should_load_immediately()
#ifdef DO_NOT_DEFER_ASSETS
return TRUE
#else
return load_immediately
#endif
/datum/asset/spritesheet/should_refresh()
if (..())
return TRUE
if (isnull(should_refresh))
// `fexists` seems to always fail on static-time
should_refresh = !fexists(css_cache_filename()) || !fexists(data_cache_filename())
return should_refresh
/datum/asset/spritesheet/unregister()
SSassets.transport.unregister_asset("spritesheet_[name].css")
if(length(sizes))
for(var/size_id in sizes)
SSassets.transport.unregister_asset("[name]_[size_id].png")
else
for(var/sheet in cached_spritesheets_needed)
SSassets.transport.unregister_asset(sheet)
/datum/asset/spritesheet/regenerate()
unregister()
sprites = list()
fdel("[ASSET_CROSS_ROUND_CACHE_DIRECTORY]/spritesheet.[name].css")
for(var/sheet in cached_spritesheets_needed)
fdel("[ASSET_CROSS_ROUND_CACHE_DIRECTORY]/spritesheet.[sheet].png")
fdel("data/spritesheets/spritesheet_[name].css")
for(var/size_id in sizes)
fdel("data/spritesheets/[name]_[size_id].png")
sizes = list()
to_generate = list()
cached_serialized_url_mappings = null
cached_serialized_url_mappings_transport_type = null
fully_generated = FALSE
var/old_load = load_immediately
load_immediately = TRUE
create_spritesheets()
realize_spritesheets(yield = FALSE)
load_immediately = old_load
/datum/asset/spritesheet/register()
SHOULD_NOT_OVERRIDE(TRUE)
if (!name)
CRASH("spritesheet [type] cannot register without a name")
if (!should_refresh() && read_from_cache())
fully_generated = TRUE
return
// If it's cached, may as well load it now, while the loading is cheap
if(CONFIG_GET(flag/cache_assets) && cross_round_cachable)
load_immediately = TRUE
create_spritesheets()
if(should_load_immediately())
realize_spritesheets(yield = FALSE)
else
SSasset_loading.queue_asset(src)
/datum/asset/spritesheet/proc/realize_spritesheets(yield)
if(fully_generated)
return
while(length(to_generate))
var/list/stored_args = to_generate[to_generate.len]
to_generate.len--
queuedInsert(arglist(stored_args))
if(yield && TICK_CHECK)
return
ensure_stripped()
for(var/size_id in sizes)
var/size = sizes[size_id]
var/file_path = size[SPRSZ_STRIPPED]
var/file_hash = rustg_hash_file(RUSTG_HASH_MD5, file_path)
SSassets.transport.register_asset("[name]_[size_id].png", file_path, file_hash=file_hash)
var/css_name = "spritesheet_[name].css"
var/file_directory = "data/spritesheets/[css_name]"
fdel(file_directory)
var/css = generate_css()
rustg_file_write(css, file_directory)
var/css_hash = rustg_hash_string(RUSTG_HASH_MD5, css)
SSassets.transport.register_asset(css_name, fcopy_rsc(file_directory), file_hash=css_hash)
if(CONFIG_GET(flag/save_spritesheets))
save_to_logs(file_name = css_name, file_location = file_directory)
fdel(file_directory)
if (CONFIG_GET(flag/cache_assets) && cross_round_cachable)
write_to_cache()
fully_generated = TRUE
// If we were ever in there, remove ourselves
SSasset_loading.dequeue_asset(src)
/datum/asset/spritesheet/queued_generation()
realize_spritesheets(yield = TRUE)
/datum/asset/spritesheet/ensure_ready()
if(!fully_generated)
realize_spritesheets(yield = FALSE)
return ..()
/datum/asset/spritesheet/send(client/client)
if (!name)
return
if (!should_refresh())
return send_from_cache(client)
var/all = list("spritesheet_[name].css")
for(var/size_id in sizes)
all += "[name]_[size_id].png"
. = SSassets.transport.send_assets(client, all)
/datum/asset/spritesheet/get_url_mappings()
if (!name)
return
if (!should_refresh())
return get_cached_url_mappings()
. = list("spritesheet_[name].css" = SSassets.transport.get_asset_url("spritesheet_[name].css"))
for(var/size_id in sizes)
.["[name]_[size_id].png"] = SSassets.transport.get_asset_url("[name]_[size_id].png")
/datum/asset/spritesheet/proc/ensure_stripped(sizes_to_strip = sizes)
for(var/size_id in sizes_to_strip)
var/size = sizes[size_id]
if (size[SPRSZ_STRIPPED])
continue
// save flattened version
var/png_name = "[name]_[size_id].png"
var/file_directory = "data/spritesheets/[png_name]"
fcopy(size[SPRSZ_ICON], file_directory)
var/error = rustg_dmi_strip_metadata(file_directory)
if(length(error))
stack_trace("Failed to strip [png_name]: [error]")
size[SPRSZ_STRIPPED] = icon(file_directory)
// this is useful here for determining if weird sprite issues (like having a white background) are a cause of what we're doing DM-side or not since we can see the full flattened thing at-a-glance.
if(CONFIG_GET(flag/save_spritesheets))
save_to_logs(file_name = png_name, file_location = file_directory)
fdel(file_directory)
/datum/asset/spritesheet/proc/generate_css()
var/list/out = list()
for (var/size_id in sizes)
var/size = sizes[size_id]
var/list/dimensions = get_icon_dimensions(size[SPRSZ_ICON])
out += ".[name][size_id]{display:inline-block;width:[dimensions["width"]]px;height:[dimensions["height"]]px;background-image:url('[get_background_url("[name]_[size_id].png")]');background-repeat:no-repeat;}"
for (var/sprite_id in sprites)
var/sprite = sprites[sprite_id]
var/size_id = sprite[SPR_SIZE]
var/idx = sprite[SPR_IDX]
var/size = sizes[size_id]
var/list/tiny_dimensions = get_icon_dimensions(size[SPRSZ_ICON])
var/icon/big = size[SPRSZ_STRIPPED]
// big width won't be cached ever
var/per_line = big.Width() / tiny_dimensions["width"]
var/x = (idx % per_line) * tiny_dimensions["width"]
var/y = round(idx / per_line) * tiny_dimensions["height"]
out += ".[name][size_id].[sprite_id]{background-position:-[x]px -[y]px;}"
return out.Join("\n")
/datum/asset/spritesheet/proc/css_cache_filename()
return "[ASSET_CROSS_ROUND_CACHE_DIRECTORY]/spritesheet.[name].css"
/datum/asset/spritesheet/proc/data_cache_filename()
return "[ASSET_CROSS_ROUND_CACHE_DIRECTORY]/spritesheet.[name].json"
/datum/asset/spritesheet/proc/read_from_cache()
return read_css_from_cache() && read_data_from_cache()
/datum/asset/spritesheet/proc/read_css_from_cache()
var/replaced_css = rustg_file_read(css_cache_filename())
var/regex/find_background_urls = regex(@"background-image:url\('%(.+?)%'\)", "g")
while (find_background_urls.Find(replaced_css))
var/asset_id = find_background_urls.group[1]
var/file_path = "[ASSET_CROSS_ROUND_CACHE_DIRECTORY]/spritesheet.[asset_id]"
// Hashing it here is a *lot* faster.
var/hash = rustg_hash_file(RUSTG_HASH_MD5, file_path)
var/asset_cache_item = SSassets.transport.register_asset(asset_id, file_path, file_hash=hash)
var/asset_url = SSassets.transport.get_asset_url(asset_cache_item = asset_cache_item)
replaced_css = replacetext(replaced_css, find_background_urls.match, "background-image:url('[asset_url]')")
LAZYADD(cached_spritesheets_needed, asset_id)
var/finalized_name = "spritesheet_[name].css"
var/replaced_css_filename = "data/spritesheets/[finalized_name]"
var/css_hash = rustg_hash_string(RUSTG_HASH_MD5, replaced_css)
rustg_file_write(replaced_css, replaced_css_filename)
SSassets.transport.register_asset(finalized_name, replaced_css_filename, file_hash=css_hash)
if(CONFIG_GET(flag/save_spritesheets))
save_to_logs(file_name = finalized_name, file_location = replaced_css_filename)
fdel(replaced_css_filename)
return TRUE
/datum/asset/spritesheet/proc/read_data_from_cache()
var/json = json_decode(rustg_file_read(data_cache_filename()))
if (islist(json["sprites"]))
sprites = json["sprites"]
return TRUE
/datum/asset/spritesheet/proc/send_from_cache(client/client)
if (isnull(cached_spritesheets_needed))
stack_trace("cached_spritesheets_needed was null when sending assets from [type] from cache")
cached_spritesheets_needed = list()
return SSassets.transport.send_assets(client, cached_spritesheets_needed + "spritesheet_[name].css")
/// Returns the URL to put in the background:url of the CSS asset
/datum/asset/spritesheet/proc/get_background_url(asset)
if (generating_cache)
return "%[asset]%"
else
return SSassets.transport.get_asset_url(asset)
/datum/asset/spritesheet/proc/write_to_cache()
write_css_to_cache()
write_data_to_cache()
/datum/asset/spritesheet/proc/write_css_to_cache()
for (var/size_id in sizes)
fcopy(SSassets.cache["[name]_[size_id].png"].resource, "[ASSET_CROSS_ROUND_CACHE_DIRECTORY]/spritesheet.[name]_[size_id].png")
generating_cache = TRUE
var/mock_css = generate_css()
generating_cache = FALSE
rustg_file_write(mock_css, css_cache_filename())
/datum/asset/spritesheet/proc/write_data_to_cache()
rustg_file_write(json_encode(list(
"sprites" = sprites,
)), data_cache_filename())
/datum/asset/spritesheet/proc/get_cached_url_mappings()
var/list/mappings = list()
mappings["spritesheet_[name].css"] = SSassets.transport.get_asset_url("spritesheet_[name].css")
for (var/asset_name in cached_spritesheets_needed)
mappings[asset_name] = SSassets.transport.get_asset_url(asset_name)
return mappings
/// Override this in order to start the creation of the spritehseet.
/// This is where all your Insert, InsertAll, etc calls should be inside.
/datum/asset/spritesheet/proc/create_spritesheets()
CRASH("create_spritesheets() not implemented for [type]!")
/datum/asset/spritesheet/proc/Insert(sprite_name, icon/inserted_icon, icon_state="", dir=SOUTH, frame=1, moving=FALSE)
if(should_load_immediately())
queuedInsert(sprite_name, inserted_icon, icon_state, dir, frame, moving)
else
to_generate += list(args.Copy())
/datum/asset/spritesheet/proc/queuedInsert(sprite_name, icon/inserted_icon, icon_state="", dir=SOUTH, frame=1, moving=FALSE)
#ifdef UNIT_TESTS
if (inserted_icon && icon_state && !icon_exists(inserted_icon, icon_state)) // check the base icon prior to extracting the state we want
stack_trace("Tried to insert nonexistent icon_state '[icon_state]' from [inserted_icon] into spritesheet [name] ([type])")
return
#endif
inserted_icon = icon(inserted_icon, icon_state=icon_state, dir=dir, frame=frame, moving=moving)
if (!inserted_icon || !length(icon_states(inserted_icon))) // that direction or state doesn't exist
return
var/start_usage = world.tick_usage
//any sprite modifications we want to do (aka, coloring a greyscaled asset)
inserted_icon = ModifyInserted(inserted_icon)
var/list/dimensions = get_icon_dimensions(inserted_icon)
var/size_id = "[dimensions["width"]]x[dimensions["height"]]"
var/size = sizes[size_id]
if (sprites[sprite_name])
CRASH("duplicate sprite \"[sprite_name]\" in sheet [name] ([type])")
if (size)
var/position = size[SPRSZ_COUNT]++
// Icons are essentially representations of files + modifications
// Because of this, byond keeps them in a cache. It does this in a really dumb way tho
// It's essentially a FIFO queue. So after we do icon() some amount of times, our old icons go out of cache
// When this happens it becomes impossible to modify them, trying to do so will instead throw a
// "bad icon" error.
// What we're doing here is ensuring our icon is in the cache by refreshing it, so we can modify it w/o runtimes.
var/icon/sheet = size[SPRSZ_ICON]
var/icon/sheet_copy = icon(sheet)
size[SPRSZ_STRIPPED] = null
sheet_copy.Insert(inserted_icon, icon_state=sprite_name)
size[SPRSZ_ICON] = sheet_copy
sprites[sprite_name] = list(size_id, position)
else
sizes[size_id] = size = list(1, inserted_icon, null)
sprites[sprite_name] = list(size_id, 0)
SSblackbox.record_feedback("tally", "spritesheet_queued_insert_time", TICK_USAGE_TO_MS(start_usage), name)
/**
* A simple proc handing the Icon for you to modify before it gets turned into an asset.
*
* Arguments:
* * I: icon being turned into an asset
*/
/datum/asset/spritesheet/proc/ModifyInserted(icon/pre_asset)
return pre_asset
/datum/asset/spritesheet/proc/InsertAll(prefix, icon/inserted_icon, list/directions)
if (length(prefix))
prefix = "[prefix]-"
if (!directions)
directions = list(SOUTH)
for (var/icon_state_name in icon_states(inserted_icon))
for (var/direction in directions)
var/prefix2 = (directions.len > 1) ? "[dir2text(direction)]-" : ""
Insert("[prefix][prefix2][icon_state_name]", inserted_icon, icon_state=icon_state_name, dir=direction)
/datum/asset/spritesheet/proc/css_tag()
return {"<link rel="stylesheet" href="[css_filename()]" />"}
/datum/asset/spritesheet/proc/css_filename()
return SSassets.transport.get_asset_url("spritesheet_[name].css")
/datum/asset/spritesheet/proc/icon_tag(sprite_name)
var/sprite = sprites[sprite_name]
if (!sprite)
return null
var/size_id = sprite[SPR_SIZE]
return {"<span class='[name][size_id] [sprite_name]'></span>"}
/datum/asset/spritesheet/proc/icon_class_name(sprite_name)
var/sprite = sprites[sprite_name]
if (!sprite)
return null
var/size_id = sprite[SPR_SIZE]
return {"[name][size_id] [sprite_name]"}
/**
* Returns the size class (ex design32x32) for a given sprite's icon
*
* Arguments:
* * sprite_name - The sprite to get the size of
*/
/datum/asset/spritesheet/proc/icon_size_id(sprite_name)
var/sprite = sprites[sprite_name]
if (!sprite)
return null
var/size_id = sprite[SPR_SIZE]
return "[name][size_id]"
#undef SPR_SIZE
#undef SPR_IDX
#undef SPRSZ_COUNT
#undef SPRSZ_ICON
#undef SPRSZ_STRIPPED
/// Spritesheet that only uses simple PNGs and CSS keys. See `assets` variable.
/// Deprecated: Use /datum/asset/spritesheet_batched where possible
/datum/asset/spritesheet/simple
_abstract = /datum/asset/spritesheet/simple
/// Associative list of icon keys (CSS class names) -> PNG filepaths (single quote!)
/// File paths MUST be PNGs
var/list/assets
/datum/asset/spritesheet/simple/create_spritesheets()
for (var/key in assets)
Insert(key, assets[key])
@@ -1,5 +1,3 @@
/// When sending mutiple assets, how many before we give the client a quaint little sending resources message
#define ASSET_CACHE_TELL_CLIENT_AMOUNT 8
/// Base browse_rsc asset transport
/datum/asset_transport
@@ -59,6 +57,10 @@
SSassets.cache[asset_name] = ACI
return ACI
/// Immediately removes an asset from the asset cache.
/datum/asset_transport/proc/unregister_asset(asset_name)
SSassets.cache[asset_name] = null
SSassets.cache.Remove(null)
/// Returns a url for a given asset.
/// asset_name - Name of the asset.
@@ -147,7 +149,7 @@
/// Precache files without clogging up the browse() queue, used for passively sending files on connection start.
/datum/asset_transport/proc/send_assets_slow(client/client, list/files, filerate = 6)
/datum/asset_transport/proc/send_assets_slow(client/client, list/files, filerate = SLOW_ASSET_SEND_RATE)
var/startingfilerate = filerate
for (var/file in files)
if (!client)
@@ -1,4 +1,4 @@
/// CDN Webroot asset transport.
/// CDN Webroot asset transport.
/datum/asset_transport/webroot
name = "CDN Webroot asset transport"
@@ -16,7 +16,7 @@
/// We also save it to the CDN webroot at this step instead of waiting for send_assets()
/// asset_name - the identifier of the asset
/// asset - the actual asset file or an asset_cache_item datum.
/datum/asset_transport/webroot/register_asset(asset_name, asset)
/datum/asset_transport/webroot/register_asset(asset_name, asset, file_hash, dmi_path)
. = ..()
var/datum/asset_cache_item/ACI = .
@@ -59,7 +59,7 @@
if (!islist(asset_list))
asset_list = list(asset_list)
for (var/asset_name in asset_list)
var/datum/asset_cache_item/ACI = asset_list[asset_name]
var/datum/asset_cache_item/ACI = asset_list[asset_name]
if (!istype(ACI))
ACI = SSassets.cache[asset_name]
if (!ACI)
@@ -69,7 +69,7 @@
legacy_assets[asset_name] = ACI
if (length(legacy_assets))
. = ..(client, legacy_assets)
/// webroot slow asset sending - does nothing.
/datum/asset_transport/webroot/send_assets_slow(client/client, list/files, filerate)