How to simulate Electricity in Tile-based game

Hello dear JGO-community :slight_smile:

I’ve been lurking around threads for quite time, but finally i need some personal advice, and i hope i chose the right place to post and/or do not violate any rules I may have overlooked.

I’ ll try to keep it short and simple, so for my question:

First: I want to implement an ‘electricity layer’ in a tile based 2D game.(As model think of Terraria). In fact, the electric layer has a limited number of tile types , basically sorts of connections for instance: ‘vertical’ | ‘horizontal’ | ‘+’ which is just a way of mapping the current from one tile to another. Kind of like its done in dwarf fortress.

Second: Then i have an object layer (i.e Entities with different Components) which both ‘affect’ the electric layer AND ‘are affected’ by the electric layer.
Eventually thers will be 1) Power sources (Batteries etc.) 2)Controllers (Buttons, Latches, etc.) 3)electric consumers(lights, etc).

I have tried some different things, which i dont think is worth explaining here.
So the issue i have is: However i do it, i need a way to update from:
1) the power sources -> towards -> 2) the switches etc -> towards -> 3) the elec. consumers

The stage where i am at now is that I thought of a ‘Node based system’, where an entity would be composed of in/ outputs and the create a node object for EVERY connection made. The way i visualize it, is the way ‘Blender 3D’ does it when connecting nodes in the nodes editor. I guess you know what i mean if you know blender.
I actually made some images explaining the case, but since i dont have a place to upload the images without making one more account on some site, i won’t for now.

At last: I thought of having an ‘impulse base system’ , where i iterate all the power sources and send impulses from there to everything connected (over Nodes), but still, i cant think of a simple, linearly/update friendly way of doing it.

I think writing more would make my question only more complicated, so i’ll leave it at that for now :smiley:

I hope/guess there is somebody who has some more experience in this sort of stuff ^^
Thank you very much in advance.

Greetings and all the best, JJ

(And off course i use LWJGL btw :P)

Oh I like this kind of stuff :smiley:

I know it’s kind of a different approach - not so simple, admittedly, but maybe you could try to use a cellular automata, for example Wireworld. It’s not so much usable for energy than for information transmittion, but still, would kind of add an interesting twist to your game, similar to redstone in minecraft, maybe try that out :slight_smile:

Love wireworld.

You could start with something like that because it’s simple, and if you decide you like the aesthetic, keep it, otherwise go farther.

Wow, I didnt think anybody would answer this quickly :stuck_out_tongue:

@matheus23
Thank you very much for the idea, allthough i looked at cellular automata as a whole, i always found it odd to use one.
Maybe it is just me but, if i look at a big tile map, and the cellular automata has to be fed with where the ‘current comes from’, what kind of tile it is and where the power should flow to, this technique seems like an obvious choice, but, other like in ‘conways game of life’ i couldnt just:
1)iterate over from am array start to finish and FLAG the changes accordingly and
2)iterate over again and actually APPLY the changes.
Because if i did that, there would be alot of unnessecary iteration to get the circuit to represent the right state , let alone the components :-.

Thank you very much again for pointing out wireworld :stuck_out_tongue: i have to look into it to see if it is applicable in my case, from what i’ve read there are some things i didnt consider. but i guess if it is do-able in Minecraft, it should be manageable in 2D aswell :stuck_out_tongue:

@BurntPizza
As i looked over a cellular automata, i thought it to be pretty simple, like: whats left?whats right? -> Do this. Seems easy :stuck_out_tongue:
Actually the only reason i want to do it ‘per tile’ so to say, is because i want the connections to be breakable and mess up the circuits, and i love that stuff.
Sometimes in a simple tile-game, what i enjoy doing most is just placing and removing blocks, and looking at it ^^

Thank you both very much for the replies :slight_smile:

Two arrays: One for reading all the tile values, one for writing. Then swap them (double-buffering) :slight_smile:
You only iterate once that way :slight_smile: (swapping is almost costless :wink: )

(shameless double-post)

Just found this, seems interesting: :wink:
http://cell-auto.com/optimisation/#naive

Your double buffer tip is one of the most simple and useful things i’ve come across in the last few months, i’ve never thougt of that :stuck_out_tongue:
And believe me, i pounded my head against a lot off stuff lately, from java to crazy patterns to OpenGl, i feel like a hungry man starving in front of a huge menu list.

I guess it’s all about choosing your own poison ^^

And thank you also for the link, i’ll definitely look into that. (and also i’ll spread the double buffering tip around, as if it was my own, too simple but so damn effective => genius) ;D

Thank you so much again ^^, ridiculous how hard it can be at times to get around the most simple things.

Btw, nice looking RPG you have there :stuck_out_tongue: (kinda feel like an account stalker)

Do you mean simulating it a bit like in the minecraft mod industrial craft 2? The key to something like that is to have a NET for the power , this is where you store all connections to the wire in a single grouping , meaning you can spread the power.

Hi :slight_smile:

I just looked at what industrial craft 2 is, since i never heard of that mod before :stuck_out_tongue:
But by what i read in 5 minutes, to post an answer quickly (sorry for the late answer), this seems to go in the direction I wanted,
since i am not at all a fan of cellular automata.

I will actually dig in if I can find anything explained on the industrial craft 2 site, but as it seems, you know about it allready :stuck_out_tongue:
If you could, please point me in the right direction ? :stuck_out_tongue:

I am making a fairly complex tile game, with many different layers, that use some kind of connectivity (water, electricity, pressure etc…) which should basically
be possible to be made with the same technique, but i havent figured it out yet.

What makes it worse, is that the different grids will have to affect each other, so doing it the cellular automata way yould be a painfull way (at least for me).

What do you mean by ‘NET’, i suppose you mean something different than a tile map as a ‘net’?
I will also need some kind of ‘power measure’, like voltage, etc, you get the idea.
If you could explain the data structure behind it, that would be awesome.

It this something that is handled through sending ‘packets’ from entity to entity, and letting each type of entity handle the packet on its own?
And also, i was so concerned to find a way to iterate and actualize every state of the circuit components in one frame, but from what i’ve seen, games generally do that more ‘randomly’, every 50 ms or so.

I am really looking forward for your answer, since im heavily in the development, and smashed my head against it the last few days ^^

Thank you in advance! :slight_smile:

You could try and find the source code for Indutrial Craft 2 or Thermal Expansion 4 (?), both mods for minecraft but with different power systems. Of course you won’t be able to implement their methods directly but it would definitely help.

I’ve been thinking about a similar system for the power systems on my prototype ship design / shooter game. The general idea would be that energy flows from generators (optionally via buffers) to consumers.

The approach I’m now thinking of requires a simple algorithm to be run after a block/tile is placed or removed:

  1. Start from one of the generators (does not matter which one). This will form an energy network, lets call it network “A”.
  2. Do a “fill” from the generator outwards along all tiles that conduct energy, and for each tile:
    • if a conduit (only function of which is conducting flow of energy) do nothing and continue the fill
    • if generator, buffer or consumer, assign it to this network (say set attribute network=“A”)
  3. Repeat from 1 for each generator that is not in a network yet untill all generators are assigned (creating network “B”, “C” etc)

In addition, my plan is to construct a graph of connected nodes for each network while the above algorithm is running. The graph’s “roots” would be generators, the leaves would be consumers, and in between could be buffers in any configuration (i guess there also could be switches etc).
A simple network could be:

          Producer   Producer
			    |          |
           Buffer       |
				/  \       /
     Consumer   Consumer

Energy flows from the top to the bottom. One consumer would then receive energy from both producers, with one source buffered (if consumption is lower than production), and the other consumer would only receive buffered energy from a single producer.

Constructing such a energy network graph would be somewhat expensive, but would only be needed during construction (or destruction, heh) time, whenever the network could be altered. Simulating the network operation would be much faster, as it would be a matter of following the graph from producers to consumers.

Anyway, I have no idea if you are thinking along these lines, but maybe it is of some us to you.

Hi Grunnt :stuck_out_tongue:

I see similarities in our line of thinking, and also your ship design/shooter , does have some components of what i am trying to achieve (customizable ships, ship steering and collision , torque etc).

I tried to make a circuit work like :
Iterate each power source -> output to the wires around it (by a method) and use and open/closed list -> then let every wire/component handle the maping aka. forwarding of the impulse itsel -> do it again.
But the problem was that i would have to ‘tag’ the connections between the wires and components, input/output/reserved etc.(too nasty for me)

But for the last 2 hours i tried to figure out a way, to implement a ‘shoot and forget’ method, so that components just emit ‘events’ and receive callbacks (i hate the word event for this but you get the idea), and the iterate every 50 ms, then set the states.(which i refer to as ‘impulse’ based)

Could you please explain me how, you would ‘save’ trees and connections like that, i mean design-whise AND java-whise, to be able to iterate it in a previously calculated manner? I would prefer, designing a pain in the *** node system, that i could then update properly, but i didnt get my head around it :stuck_out_tongue:
I love the idea to work with nodes though, it gives me something visual, and actually, a graph would be a great feature to expand upon this.

Thank you very very much for your time, I’m looking forward for your tips :stuck_out_tongue:

Btw, i might have to investigate your technique for thrusting and torque calculation on tile based space ships later on :stuck_out_tongue:

I haven’t 100% worked it out yet, so it may be a little time until I got a system working. The idea of creating a seperate model for the energy (/ electricity) network is that you can make it much simpler by removing all non-functional blocks in between producers and consumers and directly link those. Then I’ll go from consumer to producer, moving energy one step (node) at a time.

Unfortunately, I haven’t figured it out in enough detail yet to give you really helpful examples.

The idea is somewhat inspired by how Creeper World 3 transmits energy “pulses”. A cool game, by the way.

[quote=“JJengineering,post:12,topic:51560”]
For the thrust and torque I just use Box2D (in LibGDX) with a little custom code for generating the Box2D shapes based on the ship tiles and for applying force on the location of the tiles that contain thrusters. The shape generation code is pretty simple, but works well (I go through the grid line by line and create square shapes basically, then add each square shape to the ship body).

Havent read everything and maybe it’s just me but I wouldn’t use an array.
If you have only some little parts of your map powered by elec. you would have huge arrays for nothing and you would need to iterate over them. In addition, if you dont want the whole map to be loaded as it’s to big, you would run into problems like minecraft has.
For small elec. I would go for some tree-map-structured object :slight_smile:

You are definitely right about removing the non-functional blocks, should be hard to get there, but once it works, i think i’ll be the easiest, especially performance-whise.
I’ll work on it anyway, and maybe update you on what i got, since i pretty much need it to work yesterday ^^

I looked a little close into the ‘industrial craf7t 2’ mod for minecraft, actually seems to be something complex… But i havent found information about how it works yet.
If one of you, knows where the mod is explained (for programmers, not just how the blocks work,), please let me know :stuck_out_tongue:

Thank you again for the quick answer, i’m always slower in answering :slight_smile:

Concerning the thruster and torque, I actually wanted to do it the hard way, with SAT collision detection, but somehow i feel, i should really be using Box2D :slight_smile:

If not many components are used, that is off course true, i would still need to buffer every used object instead of iterating everything blindly, thats why some kind of ‘node map’ would be great.
If you know any documentation (link to it) on mapping stuff like that, i.e. generating and using them, that would be reaaally helpfull :slight_smile:
Somehow, i have a few pages on paper full of topics, techniques, programming, OpenGl, links … there is no end.
Programming a game,if you want to do it yourself, seems to be the biggest hole i ever fell in :P.
This is a topic, i can add to my list ^^

I remember the day i was able to get a sprite on screen, and i thought, ‘YES, now i can finally programm a damn game’ (i actually thought, i was at the end of the tunnel^^)

And also thank you for the answer :slight_smile:

There’s topics that are easy and topics that are hard. I think physics is generally a pretty difficult topic to do yourself, and I guess making somewhat realistic simulations of electrical networks is also pretty hard stuff.

I have now settled on an even simpler system: each seperate network of generators, consumers, buffers and conduits is collectively an “EnergyNetwork”. For simulation I do not take the structure of the network into account, I just simply calculate total production, consumption and buffering of the entire network. If there is enough energy generated or buffered then all consumers work at 100% effectiveness, if it is less, then effectiveness goes down. Effectiveness is a variable that I then use when calculating things like generated thrust or torque.

Updating the network is then quite simple:

  1. add generated energy to buffer
  2. calculate total energy needed by all consumers in the network (buffer capacity and production output is stable as long as the network does not change)
  3. if energy-need <= buffered-energy then effectiveness = 1
    else effectiveness = buffererd-energy / energy-need (if energy-need > 0)
  4. subtract consumed energy from buffered energy (check if buffer is not < 0 or > max capacity)

And that’s basically it. It’s not useable for things like switches etc, though.

Creating the network is done using a “flood fill”, starting from each generator in the grid. Every grid tile has a “visited” boolean that I use in the flood fill. So:

  1. Clear “visited” flag of all cells
  2. Go through entire grid, add all generators to a stack (or LibGDX Array)
  3. while stack is not empty
    • pop topmost generator from stack
    • if generator is not yet visited, buildnetwork(generator)

The buildnetwork(generator) function then does the following:

  1. Create a stack of cells to visit (visitStack)
  2. Add the generator to the visitStack
  3. While visitStack is not empty
    • pop topmost cell from visitStack
    • is the current cell not visited yet and an energy cell? (i.e. conduit to energy, producer, consumer or buffer?)
    • if true
      • add all surrounding cells (not outside grid ofcourse) to visitStack
      • add energy production, buffer size to totals in EnergyNetwork
      • add consumer cells to a list of consumers to quickly calculate energy consumption (which is dynamic since thrusters, etc may be on or off)
    • mark cell as visited

You can find more about this if you look into “flood fill” as a search term. This may not be what you are looking for, but I thought I’d share what approach I’m taking now.

Hey Grunnt :stuck_out_tongue:

Nice idea, (I like the way you approach the problem in a ‘generalized’ manner), and, if you dont need/want certain functionality, one does not need to work hard on something, that will probably never be needed :stuck_out_tongue:
And thank you very much for sharing your techniques! Interesting stuff :stuck_out_tongue:

I was grinding the internet the whole day, and i think i’ve come up with a very performant, simple technique, that will work for pretty much everything(power sources, switches etc).
It is basically a node tree, and when using recursion(allthough i still have to find out why recursion is told, to be such a ‘bad’ thing to do ? Oo ), the thing is updated very easily.
And then i think it is pretty simple to add functionality, so that only necessary updates are performed.

Actually, you put me on the node/tree thing, since i never considered it to be an option before :), so credits to you.

I’ll be working on it tomorrow, and i’ll let you know when i have some results, and since it is tile based, i have to come up with an ‘extendable way’, to code new components, and simply add them as such, and also map them to each other so that i get the full advantage of a node tree.

I worked with LibGDX for a while, but never used anything besides the sprite batcher, LibGDX seems to become quite fancy and really powerfull!?

Greetings and all the best, i’ll try to post some results tomorrow :slight_smile:

[quote=“JJengineering,post:18,topic:51560”]
There is nothing wrong with recursion in itself, it can be a quite elegant solution to many problems. However, the issue with recursion is that for each recursive call, some things get stored on the stack (a piece of memory where local variables are stored). So if you do many recursive calls (e.g. because you are parsing a large tiled grid using this approach) you may run out of stack memory and get exceptions.

So if you want to use recursion, you should be aware of this and ensure that there is an acceptable maximum “depth” of recursion. This means that the size of electricity networks must be limited somehow.

I followed this thread since its beginning cause i am interested in this system to.
I have seen your node tree solution and i found a possible problem (maybe i only missunderstood the solution…):
What if the Network looks something like this:

        Generator(1)
             |     Generator(2)
            / \        |       
           /   \____/\
Consumer(1)        \
                      Consumer(2)

Will the Generator(2) affect the Consumer(1)? For example if the Consumer(1) does consume more, then the Generator(1) produces, will it take some power of the Generator(2)?
Will the Generator(1) affect the Consumer(2)? For example if the Consumer(2) does consume more, then the Generator(2) produces, will it take some power of the Generator(1)?

If both questions are true, the Connection between Generator(1) and Generator(2) will be bi-directional, is that possible with the Node-Tree-Solution?