Wednesday, April 2, 2014

Smashing tech

Our latest game Smash Hit has gone far beyond all expectations, being the #1 free game in over 100 countries during launch week and approaching 35 million downloads! I will write several blog posts about the technology here, starting with a tech summary of what is being used and then go deeper into each subject in future posts.



Physics
This is by far our most physics intense game to date. It's almost like a physics playground with a game glued on top. The physics engine is tailor made for this game specifically, but builds on top of the low level physics library I was working on a few years ago. The game is actually a great show case for the low level physics library since it is very non-generic. It's a streaming, highly dynamic world where more or less everything is moving all the time and objects get inserted and removed constantly. Therefore there is no deactivation (sleeping) or islands generation. There are also two types of objects simulated differently. The full rigid body, plus debris which are more light weight.

Destruction
Destruction is the core game mechanic and had to be fully procedural, very robust and with predictable performance. The engine supports compounds of convex shapes, like most physics engines. These shapes are then split with planes and glued back together when shattered. Though most objects in the game are flat, the breakage actually support full 3D objects with no limitations. The breaking mechanic is built into the core solver, so that objects can break in multiple steps during the same iteration. This is essential for good breakage of this magnitude.

Graphics
Due to the highly dynamic environment where there can be hundreds of moving objects at the same time, one draw call per object was not an option. Instead, all objects are gathered into dynamic vertex buffers. So there are basically only one draw call per material. Vertex transformation is done on the CPU to offload the GPU and allow culling before vertices and triangles are even sent to the GPU. CPU transformation also opens up for a few other tricks not available with conventional rendering. The camera is facing the same direction all the time, which allows the use of billboards to approximate geometry. You can see this in a few instances for round shapes in particular throughout the game.



Shadows
The static soft shadows are precomputed vertex lighting based on ambient occlusion. Lighting is quadratically interpolated in the fragment shader for a natural falloff. The dynamic soft-shadows are gaussian blobs rendered with one quad per rigid body. The size and orientation of the shadow need to be determined in run-time since an object can break arbitrarily. I'm using the inertia tensor of the rigid body to figure this out, and the shadow is then projected down on a plane using a downward raycast. This is of course an enormous simplification, but it looks great in 99% of all cases!

Music and sound
I wrote my own software mixing layer for this game, which enables custom sound effects processing for environmental acoustics. I use a reverb, echoes and low-pass filters with different settings for each environment in the game. The music is made out of about 30 different patterns, each with an intro and an outro, which are sample-correct mixed together during the transitions. The camera motion is synchronized to the music progression, so the music always switches to the next pattern exactly when entering a new room. This was pretty hard to get right, since this had to be done independent of the main time stepping in order to support slower devices. Hence, camera motion and physics simulation had to be completely decoupled in order to have both predictable simulation and music synchronization on all devices.



Scripting
Scripting has been a very useful tool during the development of this game. Each obstacle in the game is built and animated using a separate lua script. Since each obstacle is procedurally generated, it allows us to make many different varations of the same obstacle. For instance configuring width, height and color, or number blades in a fan, etc. Each obstacle runs within its very own lua context, so it is a completely safe sandbox environment. I've configured lua to minimize memory consumption, and implemented an efficient custom memory allocator, so each context only requires a single memory block of about 40 kb, and there are a few dozed of them active at the same time at most. Garbage collection is amortized to only run for one context each frame, so performance impact is minimal.

Performance
The game is designed for multicore devices and uses a fork-and-merge approach for both physics and graphics. I was considering putting the rendering on a separate background thread, but this would incur an extra frame of latency, which is really bad for an action game. The audio mixing and sounds decoding is done on separate threads.

If there is any area you find particularly interesting, let me know!

48 comments:

  1. I really enjoy this game, thank you.

    ReplyDelete
  2. kudos for making a wonderful game

    ReplyDelete
  3. Lightweight, not a mem hog. Graphically astounding, and quite addictive! You have a financial winner with this game.

    ReplyDelete
  4. Hej Dennis! Hur sjutton får man tag på dig/er!!!!
    Jag är väldigt intresserade av att ni kommer till Jakarta, Indonesien för ett stor Sverigesatsning där gaming kommer vara en komponent. Tror att medicore skulle vara superbra att ha där!

    ReplyDelete
    Replies
    1. Hej, vi har inga planer på Jakarta. Lycka till!

      Delete
  5. So much cool tech! I would love to hear more about the efficient rendering of so many small dynamic objects. The dynamic vertex buffers, CPU vertex transformation tricks etc. Also, of course more info on the breakage/destruction algorithm would be extremely interesting.

    ReplyDelete
  6. loved this on my HTC One X. loving it more on my ONE M8 due to the stereo speakers and better performance. love the game, so addictive. excellent soundtrack, audio, physics and graphics

    ReplyDelete
  7. Have you used any game engine for this game? BDW great game :)

    ReplyDelete
    Replies
    1. Hi Hassan, no it is a custom engine made specifically for this game. I doubt it would be possible to reach the required level of performance with an off-the-shelf engine.

      Delete
  8. I have been loving your game. I loved smashing windows in Counter Strike years ago. This lets me scratch that itch as the main game dynamic. Oddly satisfying like popping bubble wrap!

    Love how the physics are not eye candy but great part of the core game play. Well executed Guys!

    ReplyDelete
  9. Hi. All the stuff's interesting (approximating shadow from the inertia tensor is neat!), but I'd like to know how is your main loop structured? I assume you use fixed time steps for the physics, independent the from refresh rate. Do you take any special steps to ensure smooth framerate? Interpolation? Time delta smoothing? Any system specific tricks? I'm asking this especially because on mobile devices performance is quite unpredictable, plus there's a lot of quirks with Android (I don't know about iDevices), like the one described here: http://stackoverflow.com/questions/21172585/android-thread-performance-priority-on-galaxy-note-2-when-screen-is-touched-rele

    ReplyDelete
    Replies
    1. Hi there, the physics step is sort of coupled with the main update loop, but it takes one or two physics steps, depending on the frame rate. The physics uses a fixed time step, so it accumulates the physics time with wall time and tries to catch up if necessary by taking two steps. If the time difference is more than two steps, it is just capped and the simulation runs in slow motion. The neat part though, is that the camera motion is NOT coupled with physics, so the slow-motion effect is very hard to perceive.

      Delete
    2. I have not noticed any performance difference related to touch. Maybe it's because I do everything in native mode?

      Delete
  10. I love this game. I am stuck in level five at the moment. Wondering if you will make it avaialble for the PC, and if you would consider making the game playable as Easy, Medium, and Hard?

    ReplyDelete
    Replies
    1. There is no PC version planned, but I like the idea with different difficulty levels!

      Delete
  11. Very nice! I'd already checked into Endless Mode!! ^_^

    ReplyDelete
  12. Hi Dennis, thanks for the interesting article!
    Do you mind going deeper as to why Lua is useful? Why don't you guys just change C++ code and recompile or make tweaking available via (temporary) "settings" screen?
    I'd imagine recompile is very quick these days and if you just change Lua you still need to redeploy to device, right?
    May be you can give some examples when you found Lua scripting useful.
    Thanks!!

    ReplyDelete
    Replies
    1. I was going to ask the same question. I think even with procedural generation the obstacle code is not so big.

      Delete
    2. I see several benefits of using Lua for obstacles. Rapid iteration is obviously the biggest benefit, not having to restart the game to see changes, but having an isolated sanbox per obstacle is also very helpful, since I don't have to do any clean-up per obstacle. When the obstacle is removed, the entire Lua context is wiped, so there won't be any memory leaks, regardless of how the obstacle code is written. Finally, if there is a bug in the Lua code, it can stop the one obstacle from working, but it will never crash the game.

      Delete
  13. Best game ever! Currently i'm on endless mode... but I'd be happy to get more stages!!
    Thanks for a really great game!

    ReplyDelete
  14. Just out of the world game !!!
    Everything from graphics to gui is amazing....
    Can you plz make basic tutorial of making of game or how your game engine works???
    Hatsoff to you fan if mediocre games
    I think that someday i will also make such amazing game :)

    ReplyDelete
  15. I was at score 6201, then I went farther than ever and got a score of 5676 and this erased my 6201 as my high score. why?

    ReplyDelete
  16. Best tablet game, ever. Thank you so much for this, I hope you plan on introducing new levels on a regular basis, because I want to keep playing. Amazing, hypnotic music, too.

    ReplyDelete
  17. From developer to developer congratulations, you really do have a smash hit on your hands here! I'm trying to get into game programming (on the Android platform) and any wisdom that you may be able to share with us is so much appreciated. I am also not a gamer myself, but this game has me hooked! Keep up the great work!

    ReplyDelete
  18. I love this game! Huge fan.. Would you be interested to give live to some game ideas I have? I'm in New York, great potential!!

    ReplyDelete
  19. Hi,
    Smash Hit is certainly the best game I have played... Yet!
    I look forward to future levels being added, but I have found 4 potential and funny bugs that should be resolved. Does anyone know where to report these? All make the game easier, and have increased my ball count to many hundreds.

    ReplyDelete
    Replies
    1. Interesting, please send them to support@mediocre.se. Thanks!

      Delete
  20. Hi,
    Can I modify and share modified lua scripts from smash hit? I'm asking because I want to make mod for this game :)
    Sorry for my english

    ReplyDelete
    Replies
    1. Hi there, we don't officially support modding, but if you want to try and replace lua scripts and make your own obstacles, that's cool with me!

      Delete
  21. This comment has been removed by the author.

    ReplyDelete
  22. Is the refraction is physical or not. i don't see that quality even in computer games. How you managed that in real time.

    ReplyDelete
  23. One more question Dennis, when i play again some set of assets are removed or have changed order( like in the room with oscillating hammers) so have you created different sets of it manually or is there a random placement system. How many times your physics is calculated per sec. because i never saw a piece getting unstable.
    Really never seen a mobile game this much technologically advanced.

    ReplyDelete
  24. I was wondering why you stated that putting rendering on a seperate thread would introduce an extra frame of latency. Couldn't you queue render commands for the render thread and send them off. Then while the render thread is processing you build the next frame of your game loop.

    I figure this technique would keep the CPU and GPU fully utilized and "decrease" latency. I'd really appreciate why this method introduces latency.

    GREAT game by the way..... You have hooked my brothers with the gameplay!

    ReplyDelete
    Replies
    1. Putting rendering on a separate thread will introduce an extra frame of latency, because the rendering need the output of the physics engine to know the position and orientation of objects (which would be from the frame before in a task-parallel design). This however assumes that the game runs at full frame rate in both cases. Otherwise you are correct that fully utilizing the enitre CPU might reduce lag by increasing frame rate.

      Delete
  25. Thanks for the FANTASTIC post! This information is really good and thanks a ton for sharing it :-) I m looking forward desperately for the next post of yours..
    newest technology

    ReplyDelete
  26. Great game loved it...but i need to know wer the lua scripts are stored so that i could create my own obstacles...thx fo the game....

    ReplyDelete
  27. FANTASTIC GORGEOUS & addictive game. Work of art. Best casual game I ever played (been gaming in many genres since '92). Wish you guys would make another game with this modern, colorful artistic 3D-depth aesthetic style. Sophisticated programming & creative work compared to others within this game subgenre. Art, physics, leveling (constantly challenging without being frustrating!), great soundtrack & sounds, and game modes are all designed & implemented with high quality. Would have paid more than 2$ once I played free version. Thanks for blogging a bit about technically creating it. (I love IT, but am not hands-on developer -- just like reading generally how great developers technically & creatively make gorgeous efficient product; it's amazing & interesting). Just love the 3D gorgeous glassy varied objects, procedurally generated clean modern colorful art style environments, the meticulously detailed physics... Am constantly bettering my score because never tire of playing it. This app is amazing. Not like others, it's a stand-out. I see it now has 3 copycats on google, ha ha. I realize its a lot of work to do this but hope you make another game with glorious 3D colorful visuals & fun like this one... Driving & granny physics games nice but not so gorgeous & wonderful & visually LUSCIOUS as THIS app!! Thanks to all 3 of you guys!

    ReplyDelete
  28. PS suggest to please post a basic tutorial - there is no ingame legend or help page for what the little special little targets (gold, green, purple round symbols) are, which give slowdown period, extra balls, and something else (fire?)... List what they each do and especially if there is an expiration time or level limit on them? Not totally self-obvious, many would find it helpful. Also, no release/version shown in game menu?... I dont automatically update apps unless good reason to and I read what it is first. Thanks again for glorious beautiful immersive game.

    ReplyDelete
  29. This comment has been removed by the author.

    ReplyDelete