Page 1 of 1

New Chemistry

PostPosted: Wed Apr 16, 2014 10:54 am
by Numbers
Well for all those interested, I've uploaded the 85% finished newchemistry code here, as promised. Don't try to download and compile it though - it won't work as 3/4 of the codebase is from around January and some of the other codebase is from after qdel. But you can just grab the invidual files and try them out with current codebase. Or you can just submit PRs to make the code fully compilable with the current version of tgstation13.

Here's the link:

Which features are in and which aren't:
OD (Fully working)
New Antitox (Fully working)
Biochemistry recipes (Fully working)
Reaction Efficiency and waste products (Fully working)
New chemicals (Fully working)
New recipes to include new chemicals (50% done)
LINDA/FEA Temperature code (Bugged - there is no 'depth' check for people holding stuff. Some wonkiness occurring in some cases. It requires bug testing, probably with the airgroup colouration turned on.)
Temperature stabilizers - freezers, ovens etc. (Not tested, lack interface, compilable)
CO2 Extractor - (Not included due to the fact it was coded for a totally different hydro code. Needs a rewrite)
CO2 Converter - (Not included yet. process() is done, lacks interface and tweaking. Will upload soon)
Plasma Converter (Not included yet. process() is done, lacks interface and proper procedures.)

If anyone is willing to tackle with updating/upgrading the chemistry code, feel free to submit your PRs. I know vista is working on making the atmos code work and finish up recipes.

Re: New Chemistry

PostPosted: Wed Apr 16, 2014 11:25 am
by Numbers
This is mostly for Mloc and N3X15 whether they want a similar system implemented:

How temperature reactions in atmosphere work. Apparently my code is almost identical to goon (drsingh told me so) but also has a tweak that makes the whole thing more optimized.:

When a tile is processed there are checks for fire like so:
Code: Select all
   if(air.temperature > FIRE_MINIMUM_TEMPERATURE_TO_EXIST)
      hotspot_expose(air.temperature, CELL_VOLUME)
      for(var/atom/movable/item in src)
         item.temperature_expose(air, air.temperature, CELL_VOLUME)
      temperature_expose(air, air.temperature, CELL_VOLUME)

As you can see temperature_expose is called upon every atom in the cell. During cell process you could do the same but instead of using FIRE_MINIMUM_TEMPERATURE_TO_EXIST, use a much lower value best described as MINIMUM_TEMPERATURE_START_REACTION. This is a rather sane approach because the closer you get to 0K the less likely the reaction to occur. 50K-100K is good enough of a stop.

So we have this added to cell processing

Code: Select all
      for(var/atom/movable/item in src)
         if (istype(item, /obj/item/weapon/reagent_containers)) item.temperature_expose(air, air.temperature, CELL_VOLUME)

Now the istype there is VERY valuable. It limits the amount of temperature_expose calls. You just need to call them on reagent_containers. They hold reagents, right? It is missing the going into objects held by other objects but that's something that could be fixed easily.

Now the next step is going into reagent_containers and modifying the code there and give it a temperature_expose() function

Code: Select all
/obj/item/weapon/reagent_containers/temperature_expose(datum/gas_mixture/air, exposed_temperature, exposed_volume)
   // OPTIMIZATION - Why the hell would you check for every 0.1 change. DELTATEMPKICKIN is to lower the amount of calls to handle_reactions()
   // So that in the scope of +/-DELTATEMPKICKIN change there won't be a call
   if (( oldtemp-DELTATEMPKICKIN > exposed_temperature ) || ( oldtemp+DELTATEMPKICKIN < exposed_temperature ))
   // When it kicks in, write down what was the old temperature
      oldtemp = exposed_temperature
   // WHAM!

Now the DELTATEMPKICKIN is another important define. Since the nature of float operations causes a lot of fluctuations on scale of 10E-7 in case of SINGLE-type floats. 10K is a good treshold for fluctuations - handle_reactions() is a costly procedure because it searches the recipe list and you want to limit its calls.

The next thing you can do is modify handle_reactions code as you please to include the temperature. Either pass the temperature to each reagents and have the temperature with the reaction temperature. Or do something similar to my code. It's up to you really.

Re: New Chemistry

PostPosted: Wed Apr 16, 2014 12:30 pm
by Jalleo
All very interesting Numbers I am sad to of seen you pushed off of coding due to drama if you ever come back I will be happy. Also could you give a full list of the chemicals which are done and you planned to put in?

Re: New Chemistry

PostPosted: Wed Apr 16, 2014 12:45 pm
by Numbers
Thanks. I've been told that my decision to leave was not what everyone expected but I'm really put off by the negative atmosphere.


The original list of chemicals (New Chemistry Version 2. This one failed around late 2012-early 2013) had like 30-60 salts and a lot more organic compounds. You could also oxidize/reduce chemicals to create oxides;pure metals/non-metals;hydrides. It's no point in listing them all.

The problem lies in handle_reaction code. If the chemicals had some kind of a tagging system to make sure the reaction code doesn't search ALL the reactions from the list, just specific branches, we could expand the chemistry system to be more realistic. Cause right now it's a one-way list checking. It's not even two way... just one way which is slow as hell and can cause problems if the list is too long.

Maybe I'll do it in New Chemistry+. Who knows. I'm more concerned about the temperature/efficiency code since that is more important in the long run. I can provide a list of chemicals here with their purpose.

Re: New Chemistry

PostPosted: Wed Apr 16, 2014 12:51 pm
by Jalleo
Thats probably the best solution just give the ideas of at least a good amount of chemicals and how we could possibly make em and what they do nothing more is needed but take your time though I understand about the negative atmosphere.

I do ask that if you can come back onto #coderbus whenever you feel like you will always be welcome it was just shitty how drama eats away at the passion of people to make good overhauls or at least try to.

Re: New Chemistry

PostPosted: Wed Apr 16, 2014 5:53 pm
by Numbers
:!: - Orderable
:idea: - From plants
:evil: - For traitors



Not changed

Water :!:
Holy Water
Space Lube

Not changed

Hydrogen :!:
Nitrogen :!:
Oxygen :!:

Better descriptions were given to these gases. Still orderable from Chemmaster

Lithium :!:
Sodium :!:
Potassium :!:

Better descriptions given. Still orderable from Chemmaster

Aluminum :!:
Carbon :!:
Silicon :!:
Sulfur :!:

Fixed descriptions.

Phosphorus :!:
Fluorine :!:
Chlorine :!:
Bromine :!:
Iodine :!:

More halogens added, fixed their description. Added toxicity to them

Iron :!:
Nickel :!:
Chromium :!:
Tin :!:
Copper :!:

Nickel, Tin, Chromium added for catalysis, descriptions fixed.

Heavy Metal
Mercury :!:
Vanadium :!:
Lead :!:

Heavy metal master class added with a rather silly master item being a Styx reference. Heavy metals now cause brain damage with a regulated variable to adjust severity. Fixed descriptions.

Unstable isotope
Radium :!:
Polonium :evil:

Unstable isotope is a master class and Half-Life Quarter-Life to Desctruction reference. Added Polonium as a traitor item. fixed descriptions.

Generic Salt
Plasma Salt
Lithium Chloride
Table Salt
Potassium Chloride
Iron (III) Chloride
Aluminium Chloride
Phosphorus Tribromide
Lithium Sulfate
Sodium Sulfate
Potassium Sulfate
Lithium nitrate
Sodium Nitrate
Potassium Nitrate

A small ammount of salts were added to help with synthesis and be used as medicine/poisons catalysts. Some of the salts are rather toxic. All of them are makeable with a reaction between an acid and selected metal.

Sulphuric acid :!:
Nitric acid :!:
Hydrochloric acid :!:
Formic acid :idea:
Acetic acid :!: :idea:
Polytrinic acid

Acids reworked with a master class acid (Putting them as toxins was the stupidest shit ever). Expanded amount of acids. Fixed descriptions. Polytrinic is to be phased out

Sodium hydroxide :!:
Potassium hydroxide :!:
Ammonia :!:

Bases are now a separate class and follow their own laws. It would be great if they melted different materials, but whatever... TODO

Benzene :!:
Toluene :!:
Benzoic Acid

Phenyls were added. Completely synthetizable. They're used in synthesis of drugs. Also they're quite toxic. TNT has no use right now but I was thinking of adding plasticizers and making them into C4s. C4s shouldn't gib BTW

Ethanol :!: :idea:
Methanol :!:

Can't get the eye damage in Methanol to work


Nothing new here

Sugar :!: :idea:
Glucose :idea:
Fructose :idea:

New sugars added that are formed after either hyrdolysis of saccharose (sugar) or catalysis of milk.

Stearic acid
Palmitic acid
Oleic acid
Corn Oil
Olive Oil

Proper disollution of fats due to efficency code now added. New oils and LURD added. Needs sources though.

Universal Enzyme
Enzyme A
Enzyme C
Enzyme P
Enzyme T
Enzyme Z

New enzymes were added makeable by combining *SECRET INGREDIENT* with Universal Enzyme! These are basis for biochemistry

Carbon Scaffolding no.21 :!:
Carbon Scaffolding no.27 :!:
Carbon Scaffolding no.41 :!:
Carbon Scaffolding no.46 :!:
Carbon Scaffolding no.47 :!:
Carbon Scaffolding no.51 :!:
Carbon Scaffolding no.63 :!:
Carbon Scaffolding no.67 :!:
Carbon Scaffolding no.72 :!:
Carbon Scaffolding no.73 :!:
Carbon Scaffolding no.100 :!:

These are the basis of new synthesis. It's based on the concept that complex precursors are already available for chemists to order and use to make complex stuff. Most of them are just carbon-oxygen-nitrogen-sulfur scaffolds, reflected in the name

Beta carotene :idea:
Chlorophyll b :idea:
Flavanol :idea:
Vitamin C :idea:

New stuff you can get from plants. Except their usability in synthesis, I was thinking of doing something like stearyn + dye + hardener = crayon. Again TODO

Capsaicin Oil :idea:
Condensed Capsaicin
Frost Oil :idea:
Psilocybin :idea:
Mushroom Hallucinogen

No changes here but I borught back Psilocybin and started phasing out "Mushroom Hallucinogen" because it's a very stupid thing

Anti-Toxin A (Acididexium)
Anti-Toxin B (Basidexium)
Anti-Toxin C (Chelatiom)
Anti-Toxin D (Detoxene)
Anti-Toxin P (Plasmoxan)
Anti-Toxin R (RadAway)
Anti-Toxin T (DeToxina)
Anti-Toxin Z (DeToxina Z)

Antitoxins got expanded. Chelatiom right now takes care of heavy metal in your blood by purging it. Plasmoxan drains Plasma from the blood. Radaway drains radioactive particles. Detoxina variants are for artifical and natural poisons. All to make curing them a bit more challenging. USE THE DAMN SPECTROMETER

Dexalin Plus

New paths for sythesis added here, OD code. Tears. Tears everywhere cause no more "MUH COCKTAILS".

Mutation Toxin
Advanced Mutation Toxin
Space drugs

No changes here


Added Sludge reagent as a waste that might poison you.


Master class of all toxins now. Best to phase this out from syringes.

Ricin :evil:
Amatoxin :idea:
Muscmol :idea:
Slime Jelly
Zombie Powder
Mindbreaker Toxin
Spore Toxin
Coffee Grounds :idea:
Ground Tea Leaves :idea:

These are the natural toxins. Amatoxin got buffed and reserved for Death Angles and Destroying angles. Muscmol was given to Amanita.

Artificial Toxin :evil:
Cyanide :idea:
Mint Toxin
Weed Killer
Pest Killer
Sleep Toxin
Chloral Hydrate
Toxic Beer

Not much changed here


Not much changed here either

Virus Food
Welding fuel
Space cleaner
Foaming agent

Added gunpowder with no reactions though.

Re: New Chemistry

PostPosted: Wed Apr 16, 2014 7:19 pm
by Pomf123
Quite interesting.

Re: New Chemistry

PostPosted: Wed Apr 16, 2014 7:29 pm
by Numbers
The thing that is sill unfinished were the carbon based stuff from CO2 converter which would be stuff like naphtalene, fullerens, graphene, soft carbon, graphite, phenols. Output would've been controllable by reaction temperature and catalyst (Researchable by R&D).

In the long run fullerens would be usable to make better chemicals like Bicard+ with more healing power but less OD chance. While graphene and graphite would be usuable in R&D.

If someone still wants to pick that up I can whip up something in that CO2 converter process() as a hook-up for that.

Re: New Chemistry

PostPosted: Fri Apr 18, 2014 11:30 am
by Numbers
For further reference - reactions in gaseous phase:

I heard a lot of people wanting gas reactions. It's doable as long as you add more gases (and eat more resources). But okay how does it work you ask?

Well first of all - most gaseous phase reactions take place in very extreme pressures and temperatures. So there's that. Plus there's a catalyst involved. So best place for these reactions would be possibly a flow reactor. Do we even have such an item? Yes we do!

It's called a passive gate. How does it work? Well it's a very simplistic one-way valve - it will transfer pressure from one end to another until a certain pressure is reached or pressure on input is smaller than the one on the output. So it's perfect for us to do so.

Now when it comes to reactions - those aren't exactly rocket science. It's either A + B -> C or A -> B + C. The most important thing though is that heat is either lost or gained by this. And this was a thorn in my side for a long time.

Now every gas_mixture datum has a heat capacity function that does heat capacity calculations for us. How does this work for us though?


Cv*T = Q (per mole)

But here comes our saviour:

Code: Select all
#define HEAT_CAPACITY_CALCULATION(oxygen,carbon_dioxide,nitrogen,toxins) \
   (carbon_dioxide*SPECIFIC_HEAT_CDO + (oxygen+nitrogen)*SPECIFIC_HEAT_AIR + toxins*SPECIFIC_HEAT_TOXIN)

Meaning that the heat capacity for the whole gas is already calculated. And thermal_energy() will calculate how much energy the gas really has inside.

So all we need to do is calculate how much energy is used in the reaction. Best to use the amount of product as the determinant but for 1 to 1 reactions either way is possible.

So for example in a CO2 -> O2

You need to take number of moles we want to convert - which would be the number of moles in our mixture that is multiplied by some efficency, rounded up (since number moles is integer). Then you take the number of moles, multiply by reaction energy - you will get the amount of energy that will have to be subtracted from the gas, and based on that calculate the new temperature.

That's the theory. Here it is code wise:

Code: Select all
      if((air1.total_moles() > 0) && (air1.temperature > 0))
         // Energy of the gas at start
         // Efficency to reduce the number of calculations at the cost of memory
         // This is how much end energy will there be
         var/end_energy = start_energy-convertedmoles*REACTION_ENERGY
         // Do reaction
         air1.carbon_dioxide -= convertedmoles
         air1.oxygen += convertedmoles
         // Calculate the output temperature
         air1.temperature = end_energy / air1.heat_capacity()
         // Transfer the gas into the second node and merge
         var/datum/gas_mixture/removed = air1.remove_ratio(1)

            network1.update = 1

            network2.update = 1

Now there are two things here that would be good to include: conversion rate based on air1 temperature (Normally IRL it's a function similar to an inverted parabole) and reaction window based on pressure and temperature. Conversion rate could be calculated easily at the start of the reaction and the window similarly easy. So let's try adding them

For conversion I've used a rather complex function:

We have a golden point for the reaction where the temperature is most optimal. Let's call it GOLDENPOINT now...we need a a PLATEAU point as well which tells us how big the plateau of optimal conversion will be. For this PLATEAU should be a fraction of GOLDENPOINT. Best to use something between 0.5-0.7. So PLATEAU = 0.5*GOLDENPOINT for this. So for temperature we would have:

PLATEAU/sqrt(abs(GOLDENPOINT^2-temperature^2)) but wait... there is a problem for this...

Make sure if temperature = GOLDENPOINT then conversionrate = 1. Because of course this is optimum that would be INF by mathematician logic but instead we get DIV by 0.

Also make sure to min(1,x) everything to make sure we don't get conversion rates higher than 1

Finally make sure to have an average of conversion rates for both pressure and temperature and you're left with this code:

Code: Select all
      //Calculate necessary moles to transfer using PV = nRT
      if((air1.total_moles() > 0) && (air1.temperature > 0))
         if(((air1.temperature >  MINTEMPERATUREFORCO2CONV ) && (air1.temperature <  MAXTEMPERATUREFORCO2CONV)) && ((input_starting_pressure > MINPRESSUREFORCO2CONV) && (input_starting_pressure < MAXPRESSUREFORCO2CONV)))
            // efficency calculations
            if input_starting_pressure <> GOLDENPOINTPRESSURE
               var/conversionratep = min(1,GOLDENPOINTPRESSURE*PRESSUREPLATEAUFRAC/sqrt(abs(GOLDENPOINTPRESSURE^2-air1.input_starting_pressure^2)))
               var/conversionratep = 1
            if air1.temperature <> GOLDENPOINTTEMPERATURE
               var/conversionratet = min(1,GOLDENPOINTTEMPERATURE*TEMPERATUREPLATEAUFRAC/sqrt(abs(GOLDENPOINTTEMPERATURE^2-air1.temperature^2)))
               var/conversionratet = 1
            var/conversionrate = (conversionratet+conversionratep)/2
            // Energy of the gas at start
            // Efficency to reduce the number of calculations at the cost of memory
            // This is how much end energy will there be
            var/end_energy = start_energy-convertedmoles*REACTION_ENERGY
            // Do reaction
            air1.carbon_dioxide -= convertedmoles
            air1.oxygen += convertedmoles
            // Calculate the output temperature
            air1.temperature = end_energy / air1.heat_capacity()
            // Transfer the gas into the second node and merge
         var/datum/gas_mixture/removed = air1.remove_ratio(transfer_ratio)

            network1.update = 1

            network2.update = 1

And there you have it. A realistic flow-based reactor and a new ATMOS toy.

Re: New Chemistry

PostPosted: Fri Apr 18, 2014 11:54 am
by Numbers
I'd also like to add that you could have the reactor loadable with an /obj/s and with certain conditions have those /obj/s be converted into some other objs at expense of the gases. A smart coder should already know how to do this.

Re: New Chemistry

PostPosted: Fri Apr 18, 2014 1:10 pm
by Numbers
The thing I didn't include is better handling input/output but
A) That would require additional computing power on process
B) Complicated math

Anyway... I'll try to put a semi workable code on my Github soon for you guys to play with. This is pretty much process() from it.

Re: New Chemistry

PostPosted: Fri Apr 18, 2014 9:02 pm
by ColonicAcid
You're talking about the basis of biochemistry but that's not biochemistry that's chemical engineering.
Biochemistry depends on the simple organic compounds (CHNOPS) and all you have is CONS. While it's true that all organic compounds have carbon it's not mutually exclusive with all carbon compounds are organic. You would never be able to make anything organic without hydrogen for obvious reasons (no carboxylic acid for one thing) and without phosphorous I'm not quite sure how you would be able to make anything live for very long (IE: You won't have any tri-phosphate and since that's kind of what stores the energy) forgetting the matter that without phosphate lipids there would be no cell membrane to begin with. Scaffolding for Biochemistry are the different types of amino acids, not nanocarbon compounds.

Re: New Chemistry

PostPosted: Fri Apr 18, 2014 9:15 pm
by Numbers
Yes I'm bending the thing here and simplifying things. Generally Carbon Scaffolding (TM) (All rights reserved by NT) was meant to be a general compound with a really shitty named (I queried the names before and people were coming up with CATALYST, which I think would be worse choice.) to build medicine off without ever describing what's inside. You and I know that to actually made a biologically active agent C and H is not gonna cut it and we need to have O, N, S and P as well. Sometimes metals trapped as a complex. Since the medicine has to fit a receptor or/and work against a certain protein type, it has to have a very specific build, that is not a nano-carbon skeleton but either a complex aromatic system or a protein.

If you could suggest a better name for the scaffoldings I'd be glad, I really don't like the name and it needs some really generic "Compound" name that can be marketed and sold as precursors.

The Chemical Engineering stuff is a different thing that is semi-related to the NewChemistry mostly to get more interesting compounds. And I dunno if you read the articles in the past 10 years, but fullerens and nanotubes are considered as medicine-delivery systems. So I was thinking getting them off a very specific high-temperature reactor with a specialist catalyst would make sense and give atmos boys some work.

Re: New Chemistry

PostPosted: Sat Apr 19, 2014 2:44 am
by ColonicAcid
Oh I see what you're trying to do. In medicine the compounds that actually do affect diseases are called lead compounds. The thing is though medicine in ss13 is in a very niche role in that it can heal a person. This is not what medicine is really used for in our current circumstances so the lead compound would only really go with spacealinn. My best guess to how it works is it binds with analytes and works from there and that would suggest it's a biosensor for everything bar spaceallin.
Biosensor could work actually, especially if it's different types of injuries we're talking about. Ex: You need burn biosensors to make kelotane and you need physical/brute biosensors to make Bicardine.

Re: New Chemistry

PostPosted: Sat Apr 19, 2014 10:00 am
by Numbers
Yeah that's one of the big problem with medicine in ss13 - it's just spacealin nothing else. I wish that could be expanded in the near future. We'll see once we get the ball rolling.

I think Biosensors would be a nicer name and more fitting name but it would be a little bit confusing for some still. It's a rather hard thing to come up with something catchy and self-explanatory. "Lead compound" as unfitting may be actually a good name, because to a person that doesn't know 2 shits about RL chemistry he's gonna go "Oh this is the first thing I need to mix then". People suggested real-world names but I think you and I know the complexity of lab medicine synthesis and its paths. Last thing we need is a 10-step synthesis with 5% total efficiency. I hope you didn't look in the biochemistry subsection of the code (The section that uses compounds from the produce as well as various enzymes to produce medicine in a clean, efficient synthesis) because I BSed a lot of stuff there. Even though carotene is a rather nice RL precursor.

Anyway, it's up for change really. I wish for some discussion here on various stuff so it can be changed/tweaked/renamed. The goal is for people to actually get accustomed to the general idea that:

Getting the best results out of a synthesis is going through theses complicated setups usually with specialist catalysts.
Efficency is God when it comes to making stuff.
Biochemistry will help do stuff more efficient if you know how to use the specialized bacteria for a selective synthesis/reactions.

It needs to be a fun activity in game with a little bit of a learning message there and there. Even if it's subtle. Plus I KNOW people like this little bit of "Can I try doing this reaction from real life?". That's why I added fun things like saccharose hydrolysis.

Re: New Chemistry

PostPosted: Sun Apr 20, 2014 11:59 pm
by Numbers
I got asked today to do a compilable version of the New Chemistry stuff... well yeah I think I owe you guys that given the codebase I've used was from pre qdel times and now causes massive compile errors.

I tell you what - I can do this either way. Either a clean wipe of newchemistry branch and re-upload with the fixed version. Or I can do newchemistry-compilable branch that will be just for demonstration purpsoes.

Re: New Chemistry

PostPosted: Mon Apr 21, 2014 11:09 pm
by Jalleo
Numbers I would suggest getting as much of it into the actual code in a unused section to make sure it works or work with MrPerson to get qdel() working with it if possible. Just a demonstration one while good in a sense may mean we will still have a long haul for it.

Maybe we could do a coder focus on anyone willing to get your code working well and compatible I dont know I like it. I just dont want a demonstration code for it. Anyhow wouldnt it only require a rewrite for the qdel or is it entirely incompatible?

Re: New Chemistry

PostPosted: Mon Apr 21, 2014 11:27 pm
by Numbers
Well the demonstration version would be good for people compiling and actually trying it out... Attracting some attention from people outside from TGStation.

And the thing is - I can't put this in unused section because it would conflict with existing files.

Some of this stuff needs qdel(). The version I have on my repo right now is not even compilable because I've included Kelenius stuff which uses qdel() so what I get is a huge amount of compilation errors.

The state of it right now is that it just lacks most of the recipes and bug testing. And other than that I THINK it could be put in a PR after running a beta test.

Re: New Chemistry

PostPosted: Sun Jun 24, 2018 10:19 pm
by DemonFiren
would this have been goofchem except gud?

Re: New Chemistry

PostPosted: Sun Jun 24, 2018 11:30 pm
by oranges
no, and stop necroing old threads

Re: New Chemistry

PostPosted: Sun Jun 24, 2018 11:36 pm
by iamgoofball
bring back numbers