• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
mancubit

Unity
API agnostic systems without massive dynamic casts - possible?

13 posts in this topic

I am currently trying to build up an api agnostic rendering engine. I do this simply for fun and I hope to learn a lot from it, so its nothing really professional or anything, but should serve as a basis for rendering tryouts or maybe a game someday.

The thing i have problems with is, how i should handle the borders between multiplattform and api specific code. I cant really find a way to avoid massive dynamic casts here. I know this may sound like premature optimization (which to a certain extend, this possible is) but as I said I want to gain experience and I dont think I have found the best possible solution yet - so I decided to ask the community [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]


So lets take for example the shader system:

I have a abstract base class called "Shader" which represents a single shader (vertex shader, pixel shader etc. ) and I have an abstract "Renderer" class which can set a specific shader by passing it an object of base class "Shader" like this:
[source lang="cpp"]virtual void Renderer::SetVertexShader(Shader* shader) = 0;[/source]

So lets imagine i have an api-specific shader (derived from Shader) called "ShaderDX11" and a corresponding renderer (derived from "Renderer") called "RendererDX11". RendererDX11 now implements the SetVertexShader method and performs the api-specific stuff to activate the shader.

Now I cant figure out how i could prevent a dynamic cast here to access the object "ShaderDX11" because I only have a pointer to a "Shader" object. Basically I know that this can only be an object of type "ShaderDX11", yet I dont know how i could prevent an dynamic cast everytime I set a single shader.

The thing that bothers me, is that I have to perform a dynamic cast for every single resource that interacts with api-specific code (buffers, textures, shaders, render states, etc.). Is it common practice to make massive use of dynamic casts here? Or do I just miss somthing here?

Thanks for your help [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]
0

Share this post


Link to post
Share on other sites
You've only really got one graphics API per platform (except Windows, where you have to worry about D3D9/D3D11), so you switch renderer implementation at compile time. No dynamic casts. Something like:

Renderer.h
[code]
#if defined ZZZ_PLATFORM_WINDOWS
#include "RendererD3D9.h"
#elif defined ZZZ_PLATFORM_OSX
#include "RendererGL.h"
#elif
...
#endif
[/code]

RendererD3D9.h
[code]
class Renderer
{
...
};
[/code]

RendererGL.h
[code]
class Renderer
{
...
};
[/code]

Create separate D3D9/D3D11 builds for Windows and select most appropriate in game's launcher.
2

Share this post


Link to post
Share on other sites
Rather than passing an actual API-specific shader or other object your API-agnostic code will define it's own API-agnostic handles. An unsigned int might be good for this as it maps nicely to a GL texture or other object name and can be used as a table lookup for D3D. Otherwise you might prefer to store them in an std::vector, return the index into the vector when you create an object, then pass the index into the vector as your param when setting/binding. If you're feeling adventurous you could even use the memory location of an object as your handle (I [i]really[/i] don't recommend that... it would work fine though, it's just a mite hairy), whatever, just use something that's not API-specific but that be used to retrieve the actual API-specific object in your API-specific code. Edited by mhagain
0

Share this post


Link to post
Share on other sites
With C#, if you have something like this:
[code]
IAPIObject FactoryCreate( SomethingEnum e )
{
switch( e )
{
case SomethingEnum.DirectX : return new DirectXAPI( ) ;
case SomethingEnum.OpenGL : return new OpenGLAPI( ) ;
case SomethingEnum.CellPhoneSomething : return new CellPhoneAPI( ) ;
}
}
[/code]
My understanding (which may be wrong) is that, due to being dynamically-compiled, it thereafter can make optimizations based on the knowledge that the IAPI object returned is a specific, identifiable object.

I could be wrong, though.

(Note: I posted about C# as you didn't put a language limitation in your post)
1

Share this post


Link to post
Share on other sites
I don't understand why you are calling it a dynamic cast tho. You have a IRenderer interface implemented by RendererDX11 with a SetShader(Shader* shader) function. Once you are in the function you _KNOW_ that shader is a ShaderDX11 so you can static cast it or brutally C cast it. Another possibility is to have the ShaderDX11 have a pointer to the RendererDX11 passed in at creation time and a "Apply" virtual method. Something like this:

class IRenderer
{
void SetShader(IShader* shader) { shader->Apply();}
}

class RendererDX11 : IRenderer
{
void SetShader(ShaderDX11* shader) { // do your things }
}

class IShader
{
virtual void Apply()=0;
}

class ShaderDX11 : IShader
{
RendererDX11* renderer;
void Apply() { renderer->SetShader(this);}
}

Of course the problem here would be that you have 2 ways to do the same thing: IRenderer::SetShader and IShader::Apply perform the same operation. It's a shame in C++ you cannot "hide" the IShader::Apply() method to your users, in C# that would be "internal" so the only way to set the shader would be to call IRenderer::SetShader()
1

Share this post


Link to post
Share on other sites
I was basically going to say the same thing as above.

The last game I played that supported OpenGL and DirectX within the same executable was Unreal Tournament 2003, and that was almost 10 years ago.

And it basically makes sense.[list=1]
[*]Dynamic cast is something you never need to use within your entire career. I still to this day have never actually used that type of cast in code.
[*]Dynamic casts are not an optimization anyway. There is a lot of overhead associated with this type of cast, and it is generally regarded as a “never use” situation.
[*]Even if any specific user wanted to the option to run OpenGL or DirectX within the same executable, that user is only going to make that choice once. It is not like a users is going to suddenly decide in the middle of a game that he or she wants to switch from OpenGL to DirectX. That basically means all those virtual functions have no meaning. 10 months later you just called the same virtual functions over and over and basically just wasted time. Virtual functions make sense when the type of object might change during run-time, but, in a game, the change from DirectX to OpenGL or vice-versa is only going to happen at most once a year. Meanwhile, every frame of every day of every month of every year you are taking the hit from [i]the same virtual function[/i]. It doesn’t make sense. Just compile a second executable as all games these days do.
[/list]
And if you do decide to compile a second .EXE for each API as you should, you may find [url="http://lspiroengine.com/?p=49"]this article[/url] helpful. Trust me when I say you definitely do need a strategy to avoid spaghetti when you start compiling multiple versions of the same executable.


L. Spiro
2

Share this post


Link to post
Share on other sites
What Hodgman described above is known as the Pimpl idiom - http://en.wikipedia.org/wiki/Opaque_pointer

It's a nice alternative to inheriting from an abstract class.
0

Share this post


Link to post
Share on other sites
@all: thanks - everything you say makes perfect sense. I guess i will go with preprocessor solution then (it makes even the code easier)
@L. Spiro: the link to your post is interesting, thanks for that too.
@kunos: yes you are right, dynamic casts aren't necessary, static_casts would be sufficient (anyway i want to minimize casting at all)
0

Share this post


Link to post
Share on other sites
[quote name='L. Spiro' timestamp='1341498173' post='4955985']
I was basically going to say the same thing as above.

The last game I played that supported OpenGL and DirectX within the same executable was Unreal Tournament 2003, and that was almost 10 years ago.

And it basically makes sense.[list=1]
[*]Dynamic cast is something you never need to use within your entire career. I still to this day have never actually used that type of cast in code.
[*]Dynamic casts are not an optimization anyway. There is a lot of overhead associated with this type of cast, and it is generally regarded as a “never use” situation.
[*]Even if any specific user wanted to the option to run OpenGL or DirectX within the same executable, that user is only going to make that choice once. It is not like a users is going to suddenly decide in the middle of a game that he or she wants to switch from OpenGL to DirectX. That basically means all those virtual functions have no meaning. 10 months later you just called the same virtual functions over and over and basically just wasted time. Virtual functions make sense when the type of object might change during run-time, but, in a game, the change from DirectX to OpenGL or vice-versa is only going to happen at most once a year. Meanwhile, every frame of every day of every month of every year you are taking the hit from [i]the same virtual function[/i]. It doesn’t make sense. Just compile a second executable as all games these days do.
[/list]
And if you do decide to compile a second .EXE for each API as you should, you may find [url="http://lspiroengine.com/?p=49"]this article[/url] helpful. Trust me when I say you definitely do need a strategy to avoid spaghetti when you start compiling multiple versions of the same executable.


L. Spiro
[/quote]
How do you handle the user switching between APIs? The simplest method which would also allow end-user API switching would seem to be to just have the launcher swap around API.dlls - Copy the relevant API.dll from the DirectX/OpenGL/Whatever folder into the dlls folder when the user clicks "Ok".
0

Share this post


Link to post
Share on other sites
Did this a couple of years back (no shaders back then, so the code below is just an example).

What I did was create an API-Factory object that had a generic interface, but generated and operated on API specific objects.

something like this:

[source ]class API_Factory{
virtual void AbstractShader createShader(...)=0;
}

class AbstractShader{
virtual void Apply()=0;
}


class DX11_Factory:API_Factory{
AbstractShader createShader(...){return new DX11_Shader(this.DX11Context);}
}

class DX11_Shader:AbstractShader{
void Apply(){DX11Context.ActivateShader(this.blabla);};
}[/source]
0

Share this post


Link to post
Share on other sites
[quote name='Narf the Mouse' timestamp='1341521763' post='4956099']
[quote name='L. Spiro' timestamp='1341498173' post='4955985']
I was basically going to say the same thing as above.

The last game I played that supported OpenGL and DirectX within the same executable was Unreal Tournament 2003, and that was almost 10 years ago.

And it basically makes sense.[list=1]
[*]Dynamic cast is something you never need to use within your entire career. I still to this day have never actually used that type of cast in code.
[*]Dynamic casts are not an optimization anyway. There is a lot of overhead associated with this type of cast, and it is generally regarded as a “never use” situation.
[*]Even if any specific user wanted to the option to run OpenGL or DirectX within the same executable, that user is only going to make that choice once. It is not like a users is going to suddenly decide in the middle of a game that he or she wants to switch from OpenGL to DirectX. That basically means all those virtual functions have no meaning. 10 months later you just called the same virtual functions over and over and basically just wasted time. Virtual functions make sense when the type of object might change during run-time, but, in a game, the change from DirectX to OpenGL or vice-versa is only going to happen at most once a year. Meanwhile, every frame of every day of every month of every year you are taking the hit from [i]the same virtual function[/i]. It doesn’t make sense. Just compile a second executable as all games these days do.
[/list]
And if you do decide to compile a second .EXE for each API as you should, you may find [url="http://lspiroengine.com/?p=49"]this article[/url] helpful. Trust me when I say you definitely do need a strategy to avoid spaghetti when you start compiling multiple versions of the same executable.


L. Spiro
[/quote]
How do you handle the user switching between APIs? The simplest method which would also allow end-user API switching would seem to be to just have the launcher swap around API.dlls - Copy the relevant API.dll from the DirectX/OpenGL/Whatever folder into the dlls folder when the user clicks "Ok".
[/quote]
The appropriate DLL’s would be copied to the install directory at install time.
You then have a launcher which allows the user to select one version or another and executes it.

Or the user can select only one version at install time and only that is installed (with some ability to change that later).

Or the launcher remembers the last choice and automatically launches it (with some way to change that in the future).

There are many ways to go about it.


L. Spiro Edited by L. Spiro
0

Share this post


Link to post
Share on other sites
[quote name='L. Spiro' timestamp='1341532068' post='4956152']
[quote name='Narf the Mouse' timestamp='1341521763' post='4956099']
[quote name='L. Spiro' timestamp='1341498173' post='4955985']
I was basically going to say the same thing as above.

The last game I played that supported OpenGL and DirectX within the same executable was Unreal Tournament 2003, and that was almost 10 years ago.

And it basically makes sense.[list=1]
[*]Dynamic cast is something you never need to use within your entire career. I still to this day have never actually used that type of cast in code.
[*]Dynamic casts are not an optimization anyway. There is a lot of overhead associated with this type of cast, and it is generally regarded as a “never use” situation.
[*]Even if any specific user wanted to the option to run OpenGL or DirectX within the same executable, that user is only going to make that choice once. It is not like a users is going to suddenly decide in the middle of a game that he or she wants to switch from OpenGL to DirectX. That basically means all those virtual functions have no meaning. 10 months later you just called the same virtual functions over and over and basically just wasted time. Virtual functions make sense when the type of object might change during run-time, but, in a game, the change from DirectX to OpenGL or vice-versa is only going to happen at most once a year. Meanwhile, every frame of every day of every month of every year you are taking the hit from [i]the same virtual function[/i]. It doesn’t make sense. Just compile a second executable as all games these days do.
[/list]
And if you do decide to compile a second .EXE for each API as you should, you may find [url="http://lspiroengine.com/?p=49"]this article[/url] helpful. Trust me when I say you definitely do need a strategy to avoid spaghetti when you start compiling multiple versions of the same executable.


L. Spiro
[/quote]
How do you handle the user switching between APIs? The simplest method which would also allow end-user API switching would seem to be to just have the launcher swap around API.dlls - Copy the relevant API.dll from the DirectX/OpenGL/Whatever folder into the dlls folder when the user clicks "Ok".
[/quote]
The appropriate DLL’s would be copied to the install directory at install time.
You then have a launcher which allows the user to select one version or another and executes it.

Or the user can select only one version at install time and only that is installed (with some ability to change that later).

Or the launcher remembers the last choice and automatically launches it (with some way to change that in the future).

There are many ways to go about it.


L. Spiro
[/quote]
Thanks, sounds about what I was thinking.

*Makes a refactoring note*
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0

  • Similar Content

    • By ilovegames
      Are you ready to become the best truck driver?
      If the answer is yes then this game is for you!
      Various loads of cargo need to be delivered safely. Be careful or things might get broken.
      Your driving skills and accuracy will be tested in practice.
      Get in your truck and go!
      TruckDriverSteepRoadSetup.exe
    • By ilovegames
      OffRoad4x4: Max Speed

      If you passionately adore speed and cars, and most of all dream about tearing around in a large and powerful jeep, this game was made for you. First locate the finish line on the map to complete the level. Map or no map, you have to navigate the terrain like a pro. But you aren’t limited to performing tasks in the game as you are free to explore the area just enjoying the machine and the beautiful scenery.

       
       
      OffRoad4x4MaxSpeedSetup.exe
    • By TeoMakao
      Hello there!
      I am Theo and I am looking for an evil minion/partner in crime to help me with making games. Currently I am working on my first "official" game, which is point&click 2D adventure in Unity with Fungus extension, and I will need some help with that. More about the project and future goals in private.
      I need somebody who:
      - First and foremost is interested in making games, but since you are on this forum... yeah.
      - Is a 2D artist(amateur will do, but must be willing to improve)
      - Has at least some grasp around Unity(or is willing to learn)
      - Has at least some grasp around Fungus extension for Unity(or is willing to learn)
      - Is interested in talking about various concepts of imaginary worlds/characters(I need somebody to help me developing my universe and talking to myself proves inefficient)
      And optionally:
      - Is interested in fantasy worlds
      - Is interested in mythology
      - Is interested in sci-fi worlds
      - Is interested in talking about interesting ideas, even if they are completly abstract
      I am offering up to 50% of any profit made, depending on how engaged you'll be.
      This is the first time I am looking for someone to work with me by forums, so if I chose wrong place to announce I am sorry.
      If you are interested in working with me - feel free to PM.
      I do not expect you to sacrifice all the time for the project. For now it's pretty lightweighted.
    • By RobbyT15
      I'm a front end web developer trying to get into game development and I was hoping that someone has a project they would like some assistance on.  I've mostly done tutorials in Unity and made a couple games, roll-a-ball, space shooter, but would like to get more experience.  If anyone is willing to give me a chance, please reply to this message or shoot me an email at robbyt15@bmail.com.
    • By dhanrajsinh24
      I've recently made Fidget Spinner Unity Template which is available in most online stores. Buy and learn 2D game development with it or make your own reskin of the game.
      https://www.gamegorillaz.com/index.php/catalog/product/view/id/2779/s/fidget-spinner-unity-template/
      https://www.codester.com/items/4439/fidget-spinner-unity-template
  • Popular Now