Should entities have the capability to draw themselves? [closed] - c#

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
A bit of a simple question but it's one I'm never too sure of. This is mostly in context of game development. Let's say you had an entity, like a ship or a character. Should (and I know this is a matter of opinion) this object contain a Draw method? (perhaps implement an IDrawable interface)
When looking at source code in some game projects I see this done in very many ways. Sometimes there is a separate class that may take in an Entity base object and draw it, given its properties (texture, location, et cetera). Other times the entity is given its own draw method and they are able to render themselves.
I hope this question is not too subjective.. Sometimes I hear people say things like drawing should be completely separate from objects and they should not know how to draw themselves or have the capability to. Some are more pragmatic and feel this kind of design where objects have this capability are fine.
I'm not too sure myself. I didn't find any similar questions to this because it may be a bit subjective or either method is fine but I'd like to hear what SO has to say about it because these kinds of design decisions plague my development daily. These small decisions like whether object A should have the capability to perform function B or whether or not that would violate certain design principles.
I'm sure some will say to just go with my gut and refactor later if necessary but that's what I have been doing and now I'd like to hear the actual theory behind deciding when certain objects should maintain certain capabilities.
I suppose what I am looking for are some heuristics for determining how much authority a given object should have.

You should go with whatever makes your implementation the easiest. Even if it turns out you made the wrong choice, you first hand experience on why one method is better than the other and can apply that knowledge in the future. This is valuable knowledge that will help you make decisions later. I find that one of the best ways I learn the merits of something is to do it a wrong a few times (not on purpose mind you) so you can get a good understanding of the pitfalls of an approach.
The way I handle it is this: An entity has all the information on it that is required for it to be drawn. e.g. The sprites that make it up, where they are located relative to the center of the entity. The entity itself does very little, if anything at all. It's actually just a place to store information that other systems operate on.
The world rendering code handles drawing the world as well as all the entities in it. It looks at a given entity and draws each of its sprites in the right spot, applying any necessary camera transformations or effects or what-have-you.
This is how most of my game works. The entity has no idea about physics either, or anything. All it is is a collection of data, which other systems operate on. It doesn't know about physics, but it does have some Box2D structures that hang off of it which Box2D operates on during the physics updating phase. Same with AI or Input and everything else.

Each method has it's pros and cons.
Advantage of letting objects draw themselves:
It is more comfortable for both parties. the person writing the engine just has to call a function, and the person using it, writing these IDrawable classes has low level access to everything they need. If you wanted to make a system where each object has to define what it looks like which shaders and textures it will use, and how to apply any special effects. You will either have a pretty complicated system, or a very limited one.
Advantage of having a renderer manage and draw objects
All modern 3D game engines do it this way, and for a very good reason. If the renderer has full control over which textures are bound, which models to use, and which shaders are active, it can optimize. Say you had a lot of items rendering with the same shader. The renderer can set the shader once and render them all in one batch! You can't do this if each object draws itself.
Conclusion
For small projects, its fine to have each object draw itself. It's more comfortable in fact.
If you really want performance and want to squeeze everything out of your graphics card, you need a renderer that has strict control over what is rendered and how, so that it can optimize.

It depends what you mean by 'draw itself'. If you mean should it contain low-level routines involving pixels or triangles, then probably not.
My suggestion:
One class to represent the behavior of the object (movement, AI, whatever)
One class to represent the appearance of the object
One class to define an object as combination of an appearance and a behavior
If the 'appearance' involves some custom drawing routine, that could be in that class. On the whole though drawing would be abstracted from underlying API perhaps and either using the strategy, visitor or some IoC pattern the object would be drawn by some rendering manager. This is especially true in game design where things like swapping textures in/out of video memory and drawing things in the correct order is important; something needs to be able to optimize things above the object level.
To try to be more specific, one part of your object's graph (object itself or appearance subdivision) implements IRenderable, has a method Draw(IRenderEngine), and that IRenderEngine gives the IRenderable access to methods like DrawSprite, CreateParticleEffect or whatever. Optimising or measuring your engine and algorithms will be far easier this way, and if you need to swap out engines or re-write in an unmanaged, high-performance way (or port to another platform), just create a new implementation of IRenderEngine.
Hint: if you do this, you can have many things that look the same/similar but act differently by swapping out the behavior, or lots of things that look different but act the same. You can also have the behavior stuff happen on a server, and the appearance stuff happen on a client.
I've done something very similar to this before. Each class of object had a base class that contained properties used on the client, but on the server it was a derived instance of that class that was instantiated, and it included the behavior (movement, simulation, etc). The class also had a factory method for providing its associated IRenderable (appearance) interface. Actually had a pretty effective multiplayer game engine in the end with that approach.

I suppose what I am looking for are some heuristics for determining how
much authority a given object should have.
I'd replace authority with responsibility and then the answer is ONE. Responsibility both for the behaviour and drawing of a ship seems too much to me.

Related

Are there best practices for "Singletons" (persistent GameObjects) in Unity?

I'm rather new to Unity, and C# too as a matter of fact!
What I am doing right now is:
I have a "Singleton" (it's not really a Singleton but that's not the point) GameObject called GameManager, to which is attached my GameManager.cs script containing most of the game info (which tutorial text has been already displayed, functions to load localized text, last scene loaded...)
As children of this GameManager object, I have different kinds of GameObjects I do not want to destroy on load either, such as PostProcessing Profiles, Global Lights, Audio Manager, UI Canvasses (canvi?) and other things...
There are plenty of great tutorials on Unity, and it's an awesome community, but I could not really find any info on Unity's "best practice" regarding GameObjects management.
Is this a correct way to proceed? Will I have issues in the future with this method? Should I make a generic class that implements Unity's DontDestroyOnLoad() and have the Object I want to keep inherit from that class? Is there a better way?
It works fine for now, but I want to be sure I am not doing this the wrong way and potentially messing up with my game's performance or stability.
Many thanks in advance.
There are two best-practices here.
Build lots of singletons, and replace Unity's built-in initialization system
Build very few singletons, and work within Unity's initialization system, and make heavy use of the new Multi-Scene Editing system.
Option 1 is very popular with game-studios and professional gamedevs, who are skilled at doign this and have done it many times before. The main problem is that once you start down this route you are comitting to maintaining your own parallel init system. The main advantage is that your system is probably better, definitely more powerful, and usually faster (!) than Unity's internal one.
Option 2 is more popular with people new to game programming, who want to lean on as much of Unity's built-in features as possible.
That said, there are some strange things in your question.
For instance ... Canvas? Why on earth would you be trying to make Canvas into a singleton? This suggests you're misusing Canvas in a big way (and probably some of the other classes).
The standard approach (and the only one that Unity supports) is for every Scene to have its own unique Canvas. To do something different ... is very odd.
I suspect you've misunderstood what "DontDestoryOnLoad" does. It does not prevent things being destroyed on load!
Instead, it prevents being destroyed when a NEW scene is being loaded, and they only lived in the OLD scene. A much better name would have been: "DontDestroyWhenLoadingANewScene"
There are a lot of bugs (going back many years) in Unity with DontDestroyOnLoad, so in general its best to avoid it as much as possible. For simple cases it works fine, but if you use it too much you run into complex edge cases and interactions with Unity's own internal classes.
Obligatory utopic programmer answer: Try to avoid using singletons as much as possible.
That being said, feel free to use my singleton implementation, been using it for years in production and it works fine.
https://gist.github.com/ronrejwan/7a4f0037effec3c9e8943542cf9cfbc9

Hook DirectX to make objects in scene transpanent

I am good at C# programming and I want to know if is possible to make objects from another DirectX program about fifty persents tranpanent, so I can see behind them? I will be happy if you provide some working example or link to some tutorial to take me to the right direction.
I don´t care about DirectX version but it will be great if it work on version 9 and up.
I don´t know anything about patching DLLs, so it will be great if it only use some C# hooks without dll editing.
If it isn´t possible with C# it is possible with C++?
It is possible with both C# and C++ Although I prefer c++ for such things, I can recommend C# hook solutions like EasyHooks: https://easyhook.github.io/. With DX9 you might need to hook BeginScene function and apply transparency state, but iut might be too early. You have to do a lot of test. You might also need to modify the object's vertex declarations prior to Present (dx10/11) or EndScene (dx9). IT depends on how the objects are drawn in each application.
You can also check Direct3DHook on GitHub: https://github.com/spazzarama/Direct3DHook
You can look at #VuVirt answer for the hooking portion, but the challenge reside in the translucency portion, here a little list of the things you may have to consider depending on the application you want to hook to:
Depth testing : If objects are not render back to front, you have to disable depth testing to see them.
Depth Prepass : If an engine do a pre-pass to fill the depth, you won't be able again to see thought unless you disable that pass fully.
Translucency need a back to front order to look correct.
Deferred rendering : Opaque are rendered in multiple render-target and lit in screen space, tweaking the translucency here would be meaningless and pure wrong.
Occlusion culling : If an application do occlusion culling, the object you wanna see may not even be sent to DirectX.
Various post process may need to be opaque to copy surface around.
Way many other obstacles in the way.

Patterns: Render engine allowing editor integration?

I am trying to determine that if (before I start) on a new project I can pick some suitable patterns which will help with development as the project gets more complicated.
The Scenario
To have an application that draws 'simple' lines on the screen. Ideally encompassed into a 'Render Engine' which I can package into Silverlight, WPF demo applications etc.
I also require editor application that uses the render engine to do the bulk of the displaying, however provides additional functionality like control points for moving the lines about the screen & Dialogs for changing the colours of the lines etc.
The Goal
To keep the render engine specalised and efficient. The editor should be able to 'inject' the additional functionality (i.e. display of control points) into the objects used by the rendering engine, or into the render engine itself. I don't want to code any editor specific code into the render engine.
My thoughts so far
I'm thinking of using an encapsulation/template pattern for the objects that will be used by the rendering engine, somehow allowing the editor application to supply a class to the object which 'tacks on' the functionality for the control points (and for example the event handling for moving of the control points).
My reason behind liking this idea is that the rendering engine never need know about the environment in which it is working. The editor can be changed extensively without ever having to change the rendering engine (hopefully).
But....
I may be wrong, if anyone can see any pitfalls, or has experience of better ways to tackling this problem I would love to hear them!
I agree with Charlie that you should start with a simple design prototype and extend it as needed (that's how I started with my map rendering engine). I can give you a few suggestions though:
Separate the drawing engine from the rest of the code (here's an example how). By the drawing engine I mean the code that actually draws something on the screen/bitmap. It should consume drawing primitives, not some higher-level entities. This way you'll be able to switch the drawing engine easily (example: SVG, PDF, GDI, WPF...)
If you want to have an editor, one of the patterns that are useful is the State pattern
Well shoot, that's an impressive amount of forethought.
My philosophy has always been, use a design pattern when you need to use one. Otherwise you may become an architecture astronaut, designing grand schemes all for naught. It's good that you're thinking about design before development, but really, how much can you possibly know about the project before any code has been written? Just about nothing. And if you force yourself into a pattern before any code has been written, you may end up jamming a square peg into a round hole for the entire lifecycle of the application.
My advice to you: write a prototype first. Quick and dirty. No real design; just make a skeleton that walks. Learn from it. If you thought of a better way, scrap the original and redesign a new one. Use design patterns that make sense as you add functionality, not for the sake of adding functionality.

When do you define a class?

Say you want to write a Tetris clone, and you just started planning.
How do you decide what should be a class? Do you make individual blocks a class or just the different block-types?
I'm asking this because I often find myself writing either too many classes, or writing too few classes.
Take a step back.
I suspect that you're putting the cart before the horse here. OOP isn't a Good Thing in its own right, it's a technique for effectively solving problems. Problems like: "I have a large multiple-team organization of programmers with diverse skill sets and expertise. We are building large-scale complex software where many subsystems interact with each other. We have a limited budget."
OOP is good for this problem space because it emphasizes abstraction, encapsulation, polymorphism and inheritance. Each of those works well in the many-teams-writing-large-software space. Abstraction allows one team to use the work of another without having to understand the implementation details, thereby lowering the communication cost. Encapsulation allows one team to know that they can make changes to their internal structures to make them better without worrying about the costs of impacting another team. Polymorphism lowers the cost of using many different implementations of a given abstraction, depending on the current need. Inheritance allows one team to build upon the work of another, cleanly re-using existing code rather than spending time and money re-inventing it.
All of these things are good not in of themselves, but because they lower costs in large-team-complex-software scenarios.
Do they lower costs in one-guy-trivial-software scenarios? I don't think they do; I think they raise costs. The point of inheritance is to save time through code re-use; if you spend more time messing around with getting the perfect inheritance hierarchy than the time you save through code re-use, it's not a net win, it's a net loss. Similarly with all the others: if you don't have many different implementations of the same thing then spending time on polymorphism is a loss. If you don't have anyone who is going to consume your abstraction, or anyone from whom you need to protect your internal state, then abstraction and encapsulation are costs with no associated benefits.
If what you want to do is write Tetris in an OO style for practice writing in that style, by all means go right ahead and don't let me stop you. I'm just saying: don't feel that you have a moral requirement to use OOP to solve a problem that OOP is not well-suited to solve; OOP is not the be-all-and-end-all of software development styles.
You might want to check out How do you design object oriented projects?. The accepted solution is a good start. I would also pick up a design patterns book as well.
For a Tetris clone you're going to be better off I'd say creating a block class and using an enum or similar to record what shape piece it is. The reason is that all blocks act in the same way - they fall, they react to user input by rotating or falling faster, and they use collision detection to determine when to stop falling and trigger the next piece.
If you have a class per block-type then there'd be so little difference between each class that it would be a waste of time.
In another situation where you have a lot of similar concepts (like many different types of animals etc.) it might make mroe sense to have a class per sub-type, all inheriting from a parent class if the sub-types were more different from each other
Depends on your development methodology.
Assuming you do agile, then you can start with writing the classes you think you'll need. And then as you start filling in the implementation, you'll discover that some classes are obsolete or others need to be split out.
Assuming a more design-first-then-build approach (dsdm/rup/waterfall...), then you'd want to go for a design based on the "user story", see SwDevMan81's link for an example.
I would make a base-class Piece, because they each have similar functionality like move right, move left, move down, rotate CW, rotate CCW, color, position, and the list goes on. Then each piece should be a sub class like ZPiece, LPiece, SquarePiece, IPiece, BackwardsLPiece, etc... You probably do have many classes, but there are many different types of pieces.
The point of OOP you are asking about is inheritence. You don't want to reinvent the wheel when it comes to some functions like move left/right/down, nor do you want to repeat exact code in multiple locations. Those functions shouldn't change depending on the piece so put it in the base class. Each piece rotates differently, but it is in the base class because each class should implement it's own version of it.
Basically, anything all pieces have in common should be in a base class. Then everything that makes a piece unique should be in the class itself. Yes, I think making a block class and each piece has 4 of them is a bit much, but there are those that would disagree with me.

What Should Be in a 2D Game Engine? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Ok, so I ended up writing my own game engine based on top of XNA, and I am just wondering what else I need to make a complete engine.
This is what's in the engine:
Physics (Farseer Physics)
Particle Engine (Mercury Project)
2D Cameras
Input Handling
Screen Management (Menus, Pause Screen, etc.)
Sprite ( Animation, Sprite Sheets)
And XNA stuff like Sound.
Am I missing anything that might be crucial to a game engine?
You're approaching it in an upside-down manner.
What should be in your engine is the following:
All the code that turned out to be common between your first and your second game.
First, write a game. Don't write an engine, because, as you have found out, you don't know what it should contain, or how it should be designed. Write a game instead.
Once you have that game, write another game. Then, when you have done that, examine the second game's code. How much of it was reused from the first game?
Anything that was reused should then be refactored out into a separate project. That project is now your game engine.
This doesn't mean that you shouldn't plan, or shouldn't try to write nice code. But make sure you're working towards something concrete, something where you can tell a good implementation from a bad one. A good implementation of a game, is one that works, is fun, and doesn't crash. Write your code to achieve those things first.
A good implementation of an engine? That's trickier. What's a good implementation of a renderer? Of an AI framework? Of a particle system? Ultimately, the only way to determine whether you have a good engine is by seeing how well it works in an actual game. So if you don't have a game, you have no way to evaluate your engine. And if you have no way to evaluate your engine, you have no way of judging whether any of the code you're writing is actually useful.
A theme or market for your engine. If you're doing anything beyond basic your basic graphics engine, you'll want to concentrate on a market for your engine, like RPG, strategy, puzzle, platformer, action, or FPS (ok, not FPS).
This will help you point yourself in the direction you need to go in order to make further enhancements to the engine without asking us. An engine like say, the Unreal Engine, can do multiple things, but what it tends to do best is what it's made for, FPS games. Likewise, you should tailor your engine so that it suits a particular field of interest, and therefore is picked up for that type of gameplay.
You can make it general to a point, but realize the more generalized your engine is, the harder it is to program, both time wise and skill wise. Other programmers are also less likely to pick up a general engine (unless that's all there is) if a more specific platform is available. Or to just write their own since modifying a generalized engine is about as hard as creating your own.
A few more things:
Path finding - very useful for AI
AI - possibly - depends on how generic you want the engine to be.
High scores
Replays - makes high scores much more interesting, as you can actually watch them.
A couple ideas:
Artificial intelligence (perhaps just simple AI utilities, like pathfinding algorithms)
Saving all or part of the game state (for suspending and restarting at a later time or saving high scores).
I think that you covered the general requirements of a 2D engine. The only thing I would miss in that list would be:
GUI Library
Also to make development processes easier:
Script Engine (LUA, C#Script, ...)
Dynamically Refreshed Assets (see Nick Gravelyn's Blog Entry)
You might also add another layer on top of XNA's existing stuff:
A quite bareboned Network/Lobby implementation
More abstract handling of multiple controllers (DropIn/DropOut during gaming sessions, like see Resident Evil 5 Coop) - maybe event-based
Finally you might add some "ready2use" shaders. Maybe get some inspiration from the discontinued FaceWound (from the "Garry's Mod" developer).
It depends on the game, but another thing often needed is a good networking framework.
Many modern games, including 2D games, seem to have some form of networking in place.
Animation framework so that you can say: take this sprite, move it in this direction, folowing this path using this speed, acceleration and such
Basic GUI system. Don't implement a whole Windows, but basic things like a pointer and a button, and such - keep it basic
Debugging component for displaying FPS, numbers of sprites and such
Also a good thing is to make some games, and then you will quicky see what things you repeat doing for each game, and then look into how to can get that into the engine.
2d lighting system is a good advanced feature. You can use Krypton for that.
Map editor. Or even better support any tile-map format, compatible with "Tiled Map Editor". So you can just use Tiled.
Scheduler/Timer for game actions.
Screen wipe effects such as page turn, fade out, etc. to make nice transitions between screens.
Game layers with build in parallax would be usefull too.
In game console to process commands or scripts without restart.
Easy load for texture atlas as sprites or animation.
Nice Work,
We (me and some of my friends) are working on a game engine too actually,
We've already got all what you mentioned but moreover we've got the following.
audio manager : a simple class to handle background music and sounds
effects in XNA.
video manager : it's not complicated, a simple class to handle video
playing in XNA.
effects manager : is responsible for stuff like bloom, blur,
black/white colors .. etc.
Good Luck :)
3d Acceleration should be in a 2D engine.
Using the 3d hardware that most people have these days is the best way to get amazing performance for your 2D games...
Good collision detection is very helpful. If you implement it efficiently, it really reduces the time required for every frame. Besides that, in my engine (for Pygame) I have a method of separating the main screen into a number of subscreens, which I find useful.
Depending on the target game type, include Navigation Graph(s) with node and edge annotations. (Good for many games, but not so much for the token side scrollers that are made with 2D graphics engines)
A component to generate them (via a flood fill algorithm).
Be sure to include all of the major path finding/planning algorithms (A*/Dijkstra/etc.) to traverse those graphs.
The pitfall of this is that you will have to define what a 'map' is for the engine, which might limit users of the engine.
Related things:
Location based triggers (player enters an invisible circle and something happens - queue cutscene, start ambush, etc.). I would say provide a base class for the trigger and implement some basic ones to show how it's done (ie. weapon pickups etc.)
Some game engines implement networking (though this is kind of part of the 'xna stuff')
The most useful thing to include above all else would be tools to easily use your engine. Maybe use your engine to create the tools. I'm sure you would find a lot of flaws that way.
Simple pixelperfect collision detection. NOT Farseer Physics. Simple drawing routines like drawline, drawcircle etc.
A tile repeat tool. Something that allows the user to add/create a tile, and manipulate the edges for a smooth repeath pattern.
Um. This list is an "internals" list. To make great engine is to make great "external" list.
Look at UE3 for example -- it is here because of great tools. You need tools for world creation, to create optimal packages of resources (it should be in internal list too ;-)), for collision object specification etc.
Plus, to add to Organiccat answer you should decide on tech level. You can go for simple sprites or you can want fancy effects (so shaders are needed, and with this you need infrastructure)

Categories

Resources