cocos2d-objc icon indicating copy to clipboard operation
cocos2d-objc copied to clipboard

Improved Renderer

Open vlidholt opened this issue 12 years ago • 7 comments

Create a new improved renderer. This will break custom OpenGL drawing from earlier versions, but otherwise be backwards compatible. Key features: Automatic batching & automatic culling. If it improves performance, add multithreading. We can possibly base this update on the new cocos2d-x renderer.

vlidholt avatar Jan 15 '14 21:01 vlidholt

See also #359

vlidholt avatar Jan 15 '14 22:01 vlidholt

A case for multi-threading:

The renderer for my Chipmunk Showcase app batched all of it's drawing into a single VBO that was submitted for rendering on a secondary thread (GCD queue actually). The original reason for this was to avoid iOS's extreme input latency issues when too much work or blocking calls are done on the main thread, disrupting the event loop. Instead of delivering input every few milliseconds as it comes in, the OS will buffer the input events and send them in clumps every few hundred milliseconds. Oddly this tends to be an all-or-nothing effect. Below a certain threshold there doesn't seem to be any buffering, then it jumps sharply to a couple hundred milliseconds with only a little change in CPU usage.

Originally I had intended to double buffer the vertex data as well, but apparently that never happened. So the multi-threading only avoided input latency issues and didn't improve performance. It actually even hurt it slightly. Yesterday I implemented proper double buffering and got some interesting numbers.

All testing is done on an iPad 2 since that is the bottom of the line dual core iOS device available. I modified some of the existing demos to use as performance tests. The performance to sprite rendering isn't directly translatable since I draw a lot of triangles per object, and the fragment shader cost is high. Additionally, generating the polygon data is done on the CPU and is fairly expensive. It should be possible to render several times as many sprites.

Scene 1:

Scene 1 Lots of boxes, no motion (gravity is disabled), low CPU usage for non-rendering. The scene draws anti-aliased boxes consisting of 10 triangles each.

The first test I did was to see how many boxes it could handle while maintaining a steady 60 fps rate.

Threaded: 2080 boxes Unthreaded: 1710 boxes Improvement: 22%

However due to using so much CPU time, both versions exhibited fairly severe input lag of several hundred milliseconds. This is where the threading becomes more useful. In the second test, I tried to find out how many boxes I could draw before the input lag issues began.

Threaded: 1890 boxes Unthreaded: 990 boxes Improvement: 91%

This is a huge improvement. By avoiding the expensive IO syncing off of the main thread, it's no longer forced to wait on the GPU and the event loop can run smoothly without having to decrease the number of drawn objects very much.

Scene 2:

Scene 2 Lots of hexagons moving and bouncing around. Medium CPU usage for the physics. The scene draws anti-aliased hexagons consisting of 16 triangles each. The scene also draws ~500 anti-aliased line segments consisting of 6 triangles each.

Testing again for how many objects can be rendered at without dropping frames, I got pretty similar ratios.

Threaded: 930 hexagons Unthreaded: 780 hexagons Improvement: 20%

Testing again for how many objects can be rendered before the input begins to lag.

Threaded: 870 hexagons Unthreaded: 480 hexagons Improvement: 81%

If this is an indication of the sort of performance we can expect from a threaded Cocos renderer, I'd say that's pretty good. 20% isn't amazing, but it's certainly nice if it comes for free. The nearly doubling of the limit while avoiding input lag is a huge benefit. I've seen several people struggle with this issue and have personally ran into it on many projects myself.

Implementation:

At a basic level, the showcase renderer is implemented similarly to what I've proposed for the Cocos renderer (and how the Cocos2D-x renderer is structured). To implement the threading, I have a serial GCD queue were all GL calls are done. The benefit of using GCD for this is you get an easy way to synchronize the rendering thread with the main thread and pass data back and forth. Geometry is handled by keeping a ring buffer of VBOs. The VBOs are mapped on the render thread and then passed back to the main thread to be filled. When the main thread is done with a VBO, it passes it back to the render thread where it's unmapped, drawn and then re-mapped. For custom rendering blocks that are not thread safe, the threaded renderer could easily be disabled on a frame-by-frame basis.

The Cocos2D-x renderer helps to validate some of the ideas I had.

  • Caching unique rendering states with an identifier. This means slower state changes to an object, but faster state checks when rendering.
  • Draw sorting options beyond just a node's z-value.
  • Frustum culling.
  • Custom drawing GL rendering code is wrapped in blocks.

Things that we can still improve on:

  • It doesn't seem to double buffer the VBOs at all. Probably very little performance improvement for threading.
  • The main rendering command only renders a single quad. Rendering a triangle list would be much more flexible.
  • GL rendering state information is rather limited.
  • Shader usage seems mostly the same. Still lots of room for improvement.

I'm probably forgetting some points, but need to log off for the night.

edit: Yep, forgot to leave a link to the threaded renderer branch of my showcase demo in case people want to fiddle with it. https://github.com/slembcke/ChipmunkShowcase/tree/mapbuffer

slembcke avatar Jan 16 '14 04:01 slembcke

Hi all

The -x guys have not implemented threading yet, and no-one knows if it will be worth it. The main areas they have been looking into, are

  • threaded audio
  • threaded physics
  • threaded render engine

My general feelings towards threading, can be read here http://thebackfiregames.wordpress.com/2014/01/10/to-thread-or-not-to-thread-that-is-the-question/

I think, that audio will be easy to thread, and could benefit quite a bit. Physics could probably benefit (I think that is mainly what Scotts examples proves), but will probably be very difficult to implement in the case where physics had to be separated. Threaded render engine will be medium difficult, but will not benefit.

Scotts examples clearly benefits, but I will have to say, that these are border cases, with an unusual amount of physics, and thus an unusual high CPU load. For the vast majority of apps, not including these kinds of physics, the performance would probably be worse. It wouldn’t matter of course, as the CPU load on many apps are quite low, so unless you had a bad case of AI, it would make no difference.

What we have to remember, is, that we will not gain one single frame from multithreading, unless the CPU is overloaded. We will probably lose performance for any app being fill rate limited, which will be 95+% of all apps struggling with framerate. Another huge disadvantage of threading the render engine, is the severe limitation in using openGL directly.

All in all, I do not like the idea. For more information on previous attempts on writing a threaded render engine, this might be of interest. http://www.slideshare.net/psteinb/threading-game-engines-quake-4-enemy-territory-quake-wars http://mrelusive.com/publications/presentations/2008_gdc/GDC%2008%20Threading%20QUAKE%204%20and%20ETQW%20Final.pdf

I agree however, that we should add a centralised render engine, and that the most important step in that direction, is to add a command layer to create an abstraction layer between cocos2d and OpenGL. The centralised approach can greatly increase render performance on pretty much all unoptimzed apps. It can also provide added functionality like global z scope, and other features that will make life much easier for the casual user. It will also continue to allow for unbroken openGL access.

/Birkemose

On 16 Jan 2014, at 05:38, slembcke [email protected] wrote:

A case for multi-threading:

The renderer for my Chipmunk Showcase app batched all of it's drawing into a single VBO that was submitted for rendering on a secondary thread (GCD queue actually). The original reason for this was to avoid iOS's extreme input latency issues when too much work or blocking calls are done on the main thread, disrupting the event loop. Instead of delivering input every few milliseconds as it comes in, the OS will buffer the input events and send them in clumps every few hundred milliseconds. Oddly this tends to be an all-or-nothing effect. Below a certain threshold there doesn't seem to be any buffering, then it jumps sharply to a couple hundred milliseconds with only a little change in CPU usage.

Originally I had intended to double buffer the vertex data as well, but apparently that never happened. So the multi-threading only avoided input latency issues and didn't improve performance. It actually even hurt it slightly. Yesterday I implemented proper double buffering and got some interesting numbers.

All testing is done on an iPad 2 since that is the bottom of the line dual core iOS device available. I modified some of the existing demos to use as performance tests. The performance to sprite rendering isn't directly translatable since I draw a lot of triangles per object, and the fragment shader cost is high. Additionally, generating the polygon data is done on the CPU and is fairly expensive. It should be possible to render several times as many sprites.

Scene 1:

Lots of boxes, no motion (gravity is disabled), low CPU usage for non-rendering. The scene draws anti-aliased boxes consisting of 10 triangles each.

The first test I did was to see how many boxes it could handle while maintaining a steady 60 fps rate.

Threaded: 2080 boxes Unthreaded: 1710 boxes Improvement: 22%

However due to using so much CPU time, both versions exhibited fairly severe input lag of several hundred milliseconds. This is where the threading becomes more useful. In the second test, I tried to find out how many boxes I could draw before the input lag issues began.

Threaded: 1890 boxes Unthreaded: 990 boxes Improvement: 91%

This is a huge improvement. By avoiding the expensive IO syncing off of the main thread, it's no longer forced to wait on the GPU and the event loop can run smoothly without having to decrease the number of drawn objects very much.

Scene 2:

Lots of hexagons moving and bouncing around. Medium CPU usage for the physics. The scene draws anti-aliased hexagons consisting of 16 triangles each. The scene also draws ~500 anti-aliased line segments consisting of 6 triangles each.

Testing again for how many objects can be rendered at without dropping frames, I got pretty similar ratios.

Threaded: 930 hexagons Unthreaded: 780 hexagons Improvement: 20%

Testing again for how many objects can be rendered before the input begins to lag.

Threaded: 870 hexagons Unthreaded: 480 hexagons Improvement: 81%

If this is an indication of the sort of performance we can expect from a threaded Cocos renderer, I'd say that's pretty good. 20% isn't amazing, but it's certainly nice if it comes for free. The nearly doubling of the limit while avoiding input lag is a huge benefit. I've seen several people struggle with this issue and have personally ran into it on many projects myself.

Implementation:

At a basic level, the showcase renderer is implemented similarly to what I've proposed for the Cocos renderer (and how the Cocos2D-x renderer is structured). To implement the threading, I have a serial GCD queue were all GL calls are done. The benefit of using GCD for this is you get an easy way to synchronize the rendering thread with the main thread and pass data back and forth. Geometry is handled by keeping a ring buffer of VBOs. The VBOs are mapped on the render thread and then passed back to the main thread to be filled. When the main thread is done with a VBO, it passes it back to the render thread where it's unmapped, drawn and then re-mapped. For custom rendering blocks that are not thread safe, the threaded renderer could easily be disabled on a frame-by-frame basis.

The Cocos2D-x renderer helps to validate some of the ideas I had.

Caching unique rendering states with an identifier. This means slower state changes to an object, but faster state checks when rendering. Draw sorting options beyond just a node's z-value. Frustum culling. Custom drawing GL rendering code is wrapped in blocks. Things that we can still improve on:

It doesn't seem to double buffer the VBOs at all. Probably very little performance improvement for threading. The main rendering command only renders a single quad. Rendering a triangle list would be much more flexible. GL rendering state information is rather limited. Shader usage seems mostly the same. Still lots of room for improvement. I'm probably forgetting some points, but need to log off for the night.

— Reply to this email directly or view it on GitHub.

Birkemose avatar Jan 16 '14 12:01 Birkemose

It's probably time, now that there's is time in the 3.x update cycles, to think about the points of difference that cocos2D-iPhone can offer that make it a superior choice to the available options from other vendors of game engines.

Because if you don't, there'll be no reason to use cocos2D-iPhone and everyone will choose one of the alternatives and there'll no longer be any point in developing cocos2D-iPhone. End of Line, so to speak.

Some of the real and potential advantages that could be assets to cocos2D-iPHone are...

  • Future proofing for the future of more cores, doing more for the game designers/developers than rivals, so faster, more dynamic, responsive and "heavy" games can be made on cocos2D than on others.
  • taking advantage of the underlying hardware to maximise input responsiveness, one of the most important aspects of the platforms points of difference.
  • Better physics performance with better physics than the rivals. Chipmunk is better, allowing rendering to be off on another thread allows for physics to be handled better/more by the main thread, further increasing this advantage.
  • Better and more interesting rendering and customisation of rendering (shaders etc) than rivals and easier simpler use cases. (e.g. plug-in and/or scripted style use of custom made shaders)
  • Easier "scripting" of modular additions (think the shaders example above applied to new kinds of more complex Actions and other features)
  • A complete and true Entity Framework that absolutely takes advantage the DOD inherent to such an approach and creates even more performance advantages when combined with the above threading distributions.

Generally I think Birkmouse has failed to understand the importance of performance in games, or that the OpenGL and Objective-C origins of cocos2D mean that those seriously considering it are looking to make the most of iOS hardware for performance... or natively inclined to program with Objective-C.

Somebody in the design process of making 3.x must consider the all important question:

"Why would someone choose cocos2D-iPhone 3.x?"

And start honestly assessing the answers to this question in the context of what else is available and what might be on the cards in terms of production values of importance to those considering the engine that aren't necessarily available elsewhere.

-- by way of quick examples:

As it stands, the biggest flaw in Sprite Kit is the physics.

The biggest problem with Unity is rendering and input efficiency and handling.

etc... go through each engine and find its strengths and weaknesses and figure out a way to make cocos2D-iPhone genuinely appealing to those most likely to make successful games that they can't make with the other engines.

Because if there's another choice, right about now it's going to be a better choice than the open source and unsupported and disorganised approach to cocos2D-iPhone that seems to be going on.

All other engines (that can be considered rivals) have a major supporter and/or are heavily commercialised.

Chipmunk's inclusion to cocos2D-iPhone is the single most compelling reason to use 3.0. Integrating the advice of its maker, shaper and creator to go down whatever paths he chooses might be the best way to add even more compelling reasons to use cocos2D-iPhone because he seems to know what he's doing, and, much more importantly, why he's striving to do those things.

cocos2D-iPhone is at a severe disadvantage. In the space of an engine generation it's gone from top dog to underdog.

Facing this, and the opportunity it represents, is the only way to come up with the design choices that give the engine a chance of surviving another engine generation.

Scott is your greatest asset. You risk upsetting him by not understanding his motivations and talents.

Try to understand the significance of the performance increases Scott's demonstrating, and the nature of Scott's tests and what they demonstrate beyond the literal.

Put them into the context of the market, and what you can ultimately bring to market. If you can't see your way to making cocos2D-iPhone a compelling choice, then there is no future market for it.

On Thu, Jan 16, 2014 at 4:15 AM, Birkemose [email protected] wrote:

Hi all

The -x guys have not implemented threading yet, and no-one knows if it will be worth it. The main areas they have been looking into, are

  • threaded audio
  • threaded physics
  • threaded render engine

My general feelings towards threading, can be read here

http://thebackfiregames.wordpress.com/2014/01/10/to-thread-or-not-to-thread-that-is-the-question/

I think, that audio will be easy to thread, and could benefit quite a bit. Physics could probably benefit (I think that is mainly what Scotts examples proves), but will probably be very difficult to implement in the case where physics had to be separated. Threaded render engine will be medium difficult, but will not benefit.

Scotts examples clearly benefits, but I will have to say, that these are border cases, with an unusual amount of physics, and thus an unusual high CPU load. For the vast majority of apps, not including these kinds of physics, the performance would probably be worse. It wouldn’t matter of course, as the CPU load on many apps are quite low, so unless you had a bad case of AI, it would make no difference.

What we have to remember, is, that we will not gain one single frame from multithreading, unless the CPU is overloaded. We will probably lose performance for any app being fill rate limited, which will be 95+% of all apps struggling with framerate. Another huge disadvantage of threading the render engine, is the severe limitation in using openGL directly.

All in all, I do not like the idea. For more information on previous attempts on writing a threaded render engine, this might be of interest.

http://www.slideshare.net/psteinb/threading-game-engines-quake-4-enemy-territory-quake-wars

http://mrelusive.com/publications/presentations/2008_gdc/GDC%2008%20Threading%20QUAKE%204%20and%20ETQW%20Final.pdf

I agree however, that we should add a centralised render engine, and that the most important step in that direction, is to add a command layer to create an abstraction layer between cocos2d and OpenGL. The centralised approach can greatly increase render performance on pretty much all unoptimzed apps. It can also provide added functionality like global z scope, and other features that will make life much easier for the casual user. It will also continue to allow for unbroken openGL access.

/Birkemose

On 16 Jan 2014, at 05:38, slembcke [email protected] wrote:

A case for multi-threading:

The renderer for my Chipmunk Showcase app batched all of it's drawing into a single VBO that was submitted for rendering on a secondary thread (GCD queue actually). The original reason for this was to avoid iOS's extreme input latency issues when too much work or blocking calls are done on the main thread, disrupting the event loop. Instead of delivering input every few milliseconds as it comes in, the OS will buffer the input events and send them in clumps every few hundred milliseconds. Oddly this tends to be an all-or-nothing effect. Below a certain threshold there doesn't seem to be any buffering, then it jumps sharply to a couple hundred milliseconds with only a little change in CPU usage.

Originally I had intended to double buffer the vertex data as well, but apparently that never happened. So the multi-threading only avoided input latency issues and didn't improve performance. It actually even hurt it slightly. Yesterday I implemented proper double buffering and got some interesting numbers.

All testing is done on an iPad 2 since that is the bottom of the line dual core iOS device available. I modified some of the existing demos to use as performance tests. The performance to sprite rendering isn't directly translatable since I draw a lot of triangles per object, and the fragment shader cost is high. Additionally, generating the polygon data is done on the CPU and is fairly expensive. It should be possible to render several times as many sprites.

Scene 1:

Lots of boxes, no motion (gravity is disabled), low CPU usage for non-rendering. The scene draws anti-aliased boxes consisting of 10 triangles each.

The first test I did was to see how many boxes it could handle while maintaining a steady 60 fps rate.

Threaded: 2080 boxes Unthreaded: 1710 boxes Improvement: 22%

However due to using so much CPU time, both versions exhibited fairly severe input lag of several hundred milliseconds. This is where the threading becomes more useful. In the second test, I tried to find out how many boxes I could draw before the input lag issues began.

Threaded: 1890 boxes Unthreaded: 990 boxes Improvement: 91%

This is a huge improvement. By avoiding the expensive IO syncing off of the main thread, it's no longer forced to wait on the GPU and the event loop can run smoothly without having to decrease the number of drawn objects very much.

Scene 2:

Lots of hexagons moving and bouncing around. Medium CPU usage for the physics. The scene draws anti-aliased hexagons consisting of 16 triangles each. The scene also draws ~500 anti-aliased line segments consisting of 6 triangles each.

Testing again for how many objects can be rendered at without dropping frames, I got pretty similar ratios.

Threaded: 930 hexagons Unthreaded: 780 hexagons Improvement: 20%

Testing again for how many objects can be rendered before the input begins to lag.

Threaded: 870 hexagons Unthreaded: 480 hexagons Improvement: 81%

If this is an indication of the sort of performance we can expect from a threaded Cocos renderer, I'd say that's pretty good. 20% isn't amazing, but it's certainly nice if it comes for free. The nearly doubling of the limit while avoiding input lag is a huge benefit. I've seen several people struggle with this issue and have personally ran into it on many projects myself.

Implementation:

At a basic level, the showcase renderer is implemented similarly to what I've proposed for the Cocos renderer (and how the Cocos2D-x renderer is structured). To implement the threading, I have a serial GCD queue were all GL calls are done. The benefit of using GCD for this is you get an easy way to synchronize the rendering thread with the main thread and pass data back and forth. Geometry is handled by keeping a ring buffer of VBOs. The VBOs are mapped on the render thread and then passed back to the main thread to be filled. When the main thread is done with a VBO, it passes it back to the render thread where it's unmapped, drawn and then re-mapped. For custom rendering blocks that are not thread safe, the threaded renderer could easily be disabled on a frame-by-frame basis.

The Cocos2D-x renderer helps to validate some of the ideas I had.

Caching unique rendering states with an identifier. This means slower state changes to an object, but faster state checks when rendering. Draw sorting options beyond just a node's z-value. Frustum culling. Custom drawing GL rendering code is wrapped in blocks. Things that we can still improve on:

It doesn't seem to double buffer the VBOs at all. Probably very little performance improvement for threading. The main rendering command only renders a single quad. Rendering a triangle list would be much more flexible. GL rendering state information is rather limited. Shader usage seems mostly the same. Still lots of room for improvement. I'm probably forgetting some points, but need to log off for the night.

— Reply to this email directly or view it on GitHub.

— Reply to this email directly or view it on GitHubhttps://github.com/cocos2d/cocos2d-iphone/issues/507#issuecomment-32463893 .

dissidently avatar Jan 16 '14 13:01 dissidently

I absolutely agree, that the main issue to work on with cocos2d, is, to make sure we have a solid and future proof 2D engine, with enough appeal to attract developers. We should definitely spend time, looking into where we can profile cocos2d the most.

I personally would like to see

  • One size fits all asset handling
  • Automatic sprite sheet generation
  • Geometry breakdown, to exchange fill rate for geometry
  • Centralised render engine
  • Automatic batching
  • Advanced "effects-like" shader support
  • Threading of what can be threaded (I think audio, ai and physics suits)
  • And a lot of other things

Things I do not believe so much in

  • Threaded render engine
  • Geometry culling
  • Some other things

Let us all hope, I did not upset Scott too much, by writing this ...

Birkemose avatar Jan 16 '14 14:01 Birkemose

Threaded audio is more or less done for us. OpenAL does almost all of it's work on a separate thread. Most of the work done on the main thread is just asynchronous queuing commands for the audio render thread to execute. I'd be surprised if there was anything to improve on that front.

The reason to thread the rendering is the same as for the audio. Since nothing ever reads the output of the audio (well... very rarely), you only have to synchronize it's input. Likewise with the rendering, it's the very last step in every frame and it's output is rarely if ever read back. I also have read up quite a bit on multi-threaded rendering too. Cocos2D's needs are relatively simple, and that's why I believe we can make it work well. ;)

Before threading is even an option, we need a render queue. I could (quite happily) discuss that for hours or days. At this point I think I should spend a few days on a prototype though. Get enough functionality working to run the ui-tests. I'm relatively certain that I can make something that will make everyone happy. Basic users that just want their existing code to run faster, users that want custom rendering to be easier, and people like Bill that want to write completely custom GL code.

My experience with the showcase renderer is that threading a such a render queue won't be so bad. Since there isn't a lot of shared state between the main thread and the render thread (much less than in a 3D game with mesh objects and other large resources) you don't need to worry about synchronization very much. I can prove that once I get that far though. ;)

Threaded physics:

Threaded physics isn't so easy, though I do understand why everybody wants it. The approach taken by Chipmunk Pro is to thread the solver. When calling cpSpaceStep() it runs it on two threads and waits for both to finish before returning from the function. From the calling thread, the API is unchanged. Its still synchronous, and collision callbacks still happen on the primary thread. Data level parallelism like this is relatively easy.

The only other option I can think of would be to make the physics task asynchronous. The scheduler would run the fixedUpdate methods, then start the async physics update, then call the update methods. The problem with that is you would need to put locks on all accesses to any physics access, and that includes the positions of all physics enabled CCNodes. That is a lot of extra synchronization. In the worst case, an update function will immediately try to read back from the physics and stall the main thread until the physics thread finishes. In the best case, you are going to pay small but measurable synchronization cost on every access to physics data. I'm not even sure what you would do with collision callbacks. Calling them synchronously on the main thread would be incredibly slow. Calling them asynchronously would reduce their usefulness. Calling them on the physics thread would make them hard to use and dangerous. The "surface area" of a physics library is just too big to make it both thread safe and efficient. For what it's worth, Erin Catto feels similarly: https://twitter.com/erin_catto/status/331535017211740160 Task level parallelism like that is totally possible, but it takes a lot of discipline by the game developer to make it efficient and can't effectively be hidden within an engine.

slembcke avatar Jan 16 '14 16:01 slembcke

To round off the threaded discussion.

I was able to gain a 15% increase in performance, using the demo app above. The app uses a dual VAO/VBO scheme, to make sure that some time consuming openGL operations, can be excuted in a second thread. What this in my opinion does, is producing an end result a little bit like a triple buffer scheme, as it gains CPU time, by pushing render output by one frame. The implications of this are a bit academic. Mainly I am not really keen on the idea of all openGl commands having to wrapped on blocks.

Another issue is, that when removing VAB/VBO in the example, and using an “old school” 256KB client side buffer, with full DMA transfer each frame, I got performance only 6-7% slower than the threaded solution, which is a little bit puzzling. With smaller DMA transfers, I would expect the difference to narrow even more. Seems like VBO's don't work well when the entire buffer is updated.

It also seems, that the sudden input lag, when running high CPU loads, is gone in iOS7.

As “Improved Renderer” is quite a big topic, I will add a few sub-topics, but still in the “Improved Renderer” department.

Birkemose avatar Jan 24 '14 17:01 Birkemose