Putting the 'role' back in role-playing games since 2002.
Donate to Codex
Good Old Games
  • Welcome to rpgcodex.net, a site dedicated to discussing computer based role-playing games in a free and open fashion. We're less strict than other forums, but please refer to the rules.

    "This message is awaiting moderator approval": All new users must pass through our moderation queue before they will be able to post normally. Until your account has "passed" your posts will only be visible to yourself (and moderators) until they are approved. Give us a week to get around to approving / deleting / ignoring your mundane opinion on crap before hassling us about it. Once you have passed the moderation period (think of it as a test), you will be able to post normally, just like all the other retards.

XNA C# Development - Simple Q&A Thread

J1M

Arcane
Joined
May 14, 2008
Messages
14,628
The Qt Tutorial thread did better than I expected in terms of interest and post quality but I don't like Qt, so I thought we should have a similar thread for discussing an environment that I do enjoy working in: XNA.

Thread 'Rules': :obviously:
-This thread is for discussing game development with XNA and C#. It is not about Microsoft or how much better/worse C++/Java is.
-I don't intend to write any tutorials myself, but I will link to them from this post if someone else does.
-If you are answering someone's question, please quote it - even if it is your own.


What is XNA?
-XNA stands for "XNA is Not an Acronym". It is a framework built on top of .NET that is intended to speed up game development for Windows, Xbox, and Windows Phone, especially for smaller developers. With the right setup, changing from a Windows to an Xbox version of a game can be as simple as hitting compile again. (100% shared code and art assets) Usually Windows Phone projects require a set of lower quality assets.

What is C#?
-C# is a language with similar principles to those of Java, but developed by Microsoft. Personally, I find the syntax and power of C# is much nicer. C# had a bit of a rocky reception years ago, but I find it has matured nicely. It is easier to use and learn than C/C++.

How do I get started?
-First, install Visual Studio 2010. If you don't attend a university that will give you a free copy, you can try Visual C# 2010 Express, which is free. (I use the full version, but this thread is the place to ask if you have problems)
http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-csharp-express
-Next, install Microsoft XNA Game Studio 4.0
http://www.microsoft.com/en-us/download/details.aspx?id=23714

Tutorials!
Microsoft's site for everything XNA
http://msdn.microsoft.com/en-us/centrum-xna.aspx
2D Game Tutorial:
http://create.msdn.com/en-US/education/tutorial/2dgame/getting_started


I am building a 2D tactics-style game with a friend and consider myself to have moderate knowledge of C# and XNA. I will answer what I can to get the ball rolling. I love Properties and Lambdas (anonymous functions). They have seen some extensive use in the work I've done lately on my own game project.


Discussion Ideas:
-Linq

-Annotations
(Two things I haven't touched yet.) If someone is an expert in those areas it would be nice if they could give a summary of what they are useful for with a simple example.

-Nuclex font rendering integration.
In XNA 4.0 the default quality of the font rendering was adjusted to reduce texture file size. The guy who does Nuclex wrote a pipeline extension that improves/fixes SpriteFont rendering quality. I plan to eventually integrate his solution into my own project, but I haven't got around to it yet. I would be interested to hear from anyone who has already done so. Relevant link: http://www.nuclex.org/blog/2-gamedev/113-xna-sprite-font-quality
 

lmbarns

Educated
Joined
May 16, 2012
Messages
83
Location
Seattle, WA
I don't use it anymore but I do use a program that was made with XNA so I have it installed, which is awesome http://www.envygames.com/content/index.php/archives/673 but they're moving it to T3d for another market (mac, iOS). But it's a cool use of creating useful tools with a game framework.

I have tons of 3d models and couldn't find squat for 2d sprites and that program generates nice sprite sheets from your animated models. There's a lot more "stock" 3d models available than 2d, I've found, unless you're an artist or hire flash artists cheap. Then you can tweak them in photoshop.

Back when I was testing it out they had a good 2d mobile shooter example that was pretty cool and covered a lot of mechanics you could apply to a lot of types of games.
 

20 Eyes

Liturgist
Joined
Nov 23, 2010
Messages
1,395
I quite like XNA.
I am building a 2D tactics-style game with a friend and consider myself to have moderate knowledge of C# and XNA.

What a coincidence, I'm planning on making one myself. I'm in the early/pre-planning stages, but I'm working on a tile engine for it. I just got tile selection working, which feels good because I would've had no idea how to do this a few months ago. I think I'm going to try something super-simple like Advance Wars or Fire Emblem. I still have a lot to learn about programming, but I think I might be able to pull off something like Advance Wars. Should be a good learning experience, in either case. I'm sure I'll have questions for you once/if I get further along.

litHX.png
 

Styg

Stygian Software
Developer
Joined
Aug 18, 2010
Messages
742
Location
Serbia
I love C#. I started programming in it 6-7 years ago and never looked back. It's a robust productive language with many useful features.

I stay the heck away from Linq though, it feels so out of place from the rest of the stuff, but I guess it's useful for someone who likes SQL (which I don't!).

I love Lamba expressions and use them extensively, but they do facilitate lazy programming practices and, in my experience, less experienced programmers often use them to the detriment of code's performance (mostly IEnumerable<T> extensions stuff).
 
Self-Ejected

Davaris

Self-Ejected
Developer
Joined
Mar 7, 2005
Messages
6,547
Location
Idiocracy
Blog claims osx's memory manager is fundamentally broken

http://www.terathon.com/forums/viewtopic.php?f=12&t=11810


by Eric Lengyel on 05 May 2012, 00:58
There are lots of problems with garbage collection, and many of them have to do with unpredictable delays and other performance issues. But I think the worst thing, by far, is the following statement from Microsoft's C# docs:

"The programmer has no control over when the destructor is called because this is determined by the garbage collector."​



Since you can never tell when an object's destructor is going to be called, garbage collection creates an extraordinarily-difficult-to-debug monumental mess in any large piece of software with negative effects far outweighing the problems that garbage collection was supposed to solve in the first place.​

Its not a C++ vs C# argument, but it is something people should know about C#. I used C# and Python for a while and I think they have really nice syntax.
 

Marsal

Arcane
Joined
Oct 2, 2006
Messages
1,304
Blog claims osx's memory manager is fundamentally broken

http://www.terathon.com/forums/viewtopic.php?f=12&t=11810


by Eric Lengyel on 05 May 2012, 00:58
There are lots of problems with garbage collection, and many of them have to do with unpredictable delays and other performance issues. But I think the worst thing, by far, is the following statement from Microsoft's C# docs:

"The programmer has no control over when the destructor is called because this is determined by the garbage collector."​



Since you can never tell when an object's destructor is going to be called, garbage collection creates an extraordinarily-difficult-to-debug monumental mess in any large piece of software with negative effects far outweighing the problems that garbage collection was supposed to solve in the first place.​

Its not a C++ vs C# argument, but it is something people should know about C#. I used C# and Python for a while and I think they have really nice syntax.
Not a problem if you make TB games :obviously: It's Microsoft's way of apologizing for FAGBOX and the decline it caused.
 

lmbarns

Educated
Joined
May 16, 2012
Messages
83
Location
Seattle, WA
So why does Crytek waste time adding C# support to CryEngine, if it can't perform in their obviously complex applications? http://docs.inkdev.net/display/CryMono/Home It actually looks really fucking promising. I'm impressed.

I'm on Davaris's ignore if anyone wants to ask him the same question. Why would his favorite engine destroy their reputation by supporting something that is so fundamentally flawed?

I like C#.

Full context of his link: http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx
The programmer has no control over when the destructor is called because this is determined by the garbage collector. The garbage collector checks for objects that are no longer being used by the application. If it considers an object eligible for destruction, it calls the destructor (if any) and reclaims the memory used to store the object. Destructors are also called when the program exits.

It is possible to force garbage collection by calling Collect, but most of the time, this should be avoided because it may create performance issues.

clear.gif
Using Destructors to Release Resources
In general, C# does not require as much memory management as is needed when you develop with a language that does not target a runtime with garbage collection. This is because the .NET Framework garbage collector implicitly manages the allocation and release of memory for your objects. However, when your application encapsulates unmanaged resources such as windows, files, and network connections, you should use destructors to free those resources. When the object is eligible for destruction, the garbage collector runs the Finalize method of the object.

Explicit Release of Resources
If your application is using an expensive external resource, we also recommend that you provide a way to explicitly release the resource before the garbage collector frees the object. You do this by implementing a Dispose method from the IDisposable interface that performs the necessary cleanup for the object. This can considerably improve the performance of the application. Even with this explicit control over resources, the destructor becomes a safeguard to clean up resources if the call to the Dispose method failed.
Clean it up manually if it's that resource intensive.
 

Marsal

Arcane
Joined
Oct 2, 2006
Messages
1,304
So why does Crytek waste time adding C# support to CryEngine, if it can't perform in their obviously complex applications? http://docs.inkdev.net/display/CryMono/Home It actually looks really fucking promising. I'm impressed.

I'm on Davaris's ignore if anyone wants to ask him the same question. Why would his favorite engine destroy their reputation by supporting something that is so fundamentally flawed?

I like C#.
He'll see it now. I like C#, too. I didn't really look into it, but my guess is that GC has negligible impact on performance if C# is used only for scripting. I don't think GC is that much of a problem, even in more demanding games. Magicka seems to run fine, without any major slowdowns (anecdotal evidence, of course).
 

DakaSha

Arcane
Joined
Dec 4, 2010
Messages
4,792
C# works fine on Pc. I used it for XBawx once though and it slowed to a crawl (due to GC). I'm pretty sure it can be remedied by more strict coding though.
Also just for the record C# can do things (performance wise) that a lot of people seem to not know about.

ALSO (and this is a big deal) when you are spending up to 1/4 the time writing code it leaves you that much more time for optimizing ;)

In any case I adore C# and wish I could use it for my current shit. It's a great language imo
 
Self-Ejected

Davaris

Self-Ejected
Developer
Joined
Mar 7, 2005
Messages
6,547
Location
Idiocracy
Troll from Unity
The link is there, so you are free to pit your your academic qualifications and real world experience, against those of Eric Lengyel, any time.

everyone else
Unreal is dropping Unreal Script, and is returning to C++ for Unreal 4... Dun, dun, dun!

I tried the UDK editor this week and it ran like a half dead slug, on my machine. The Unity editor was sluggish, when I tried it a couple of years back and I won't waste my time or bandwidth, downloading Crytek, because it is a mod kit, with heavy handed DRM. No internet, no Crytek. Even worse, if I want shadows (that do not move) from multiple sources in UDK, I discovered I need a render farm. lol

By comparison on my machine, the C4 editor runs like a slippery eel. :) So who do you ask about performance? The people that say you must upgrade, to run their sluggish software?
 

lmbarns

Educated
Joined
May 16, 2012
Messages
83
Location
Seattle, WA
Anyone interested in Mono game dev might be interested in this slide presentation from AltDevConf 2012 which discusses garbage collection where performance is concerned, among other things: http://tirania.org/slides/AltDevConf-2012-Mono.pdf

Yea some idiots trying to flex their epeen on here think if you're not making their favorite genre of game, particularly military combat from source, that their shit somehow doesn't stink and they're much better than everyone. Meanwhile there's a lot more to indie game dev than writing code, and as an individual the more tools, resources, documentation, active community, the more likely you're to finish.

Linking 1 liners and trying to use that as some strawman argument (ignoring any alternative workarounds) for why something is useless, is retarded. Meanwhile his engine is from 2005, and it's got 1 guy running around trying to progress it, but in 7 years they're still 3 years behind UDK, Unity, Torque3d, and yes, XNA, on every level. Their community in 7 years has a couple thousand posts, hahahaha, yea the creator will help you out but that's anemic growth at best. His demo games are worse than Unity Free, the only difference is he has dynamic shadows which costs money in Unity. But his graphics rendering is ugly in the examples provided by the engine creator, those same models would look better in Unity, UDK, etc, with some normal maps and a better shader.

Both C4 and unity are written in C++ and both use physX, unity uses mono for scripting and doesn't include source. You can use dll's when you have pro, it has extensive documentation and plugins, C4 has a guy that will work on your bugs, and source code, little else. 7 fucking years old, I didn't realize that until now and it's anemic at best. Maybe in a few years it'll be at the level the major engines are at right now.....Unity isn't recognizable from a year ago, let alone when it came out. UDK and T3d too. Fuck even game maker has progressed as a product more than C4 hahahaha.

And tbh it's funny as shit how much of an elitist prick davaris is, lol he should be supportive of whatever level of game development people are at, his game isn't any better.(he blocked me after I posted a screenshot here of his tank game, to show what an elitist prick he is, for no reason)

All I can say.....
http://en.wikipedia.org/wiki/Illusory_superiority
http://en.wikipedia.org/wiki/Dunning–Kruger_effect
 

Marsal

Arcane
Joined
Oct 2, 2006
Messages
1,304
Anyone interested in Mono game dev might be interested in this slide presentation from AltDevConf 2012 which discusses garbage collection where performance is concerned, among other things: http://tirania.org/slides/AltDevConf-2012-Mono.pdf
Thanks for the link. I remember seeing a presentation a couple years ago (from GDC, I think) where performance of managed code was discussed. I'll try to dig it up, but I remember the conclusion was that GC really doesn't matter much.
 

J1M

Arcane
Joined
May 14, 2008
Messages
14,628
I quite like XNA.
I am building a 2D tactics-style game with a friend and consider myself to have moderate knowledge of C# and XNA.

What a coincidence, I'm planning on making one myself. I'm in the early/pre-planning stages, but I'm working on a tile engine for it. I just got tile selection working, which feels good because I would've had no idea how to do this a few months ago. I think I'm going to try something super-simple like Advance Wars or Fire Emblem. I still have a lot to learn about programming, but I think I might be able to pull off something like Advance Wars. Should be a good learning experience, in either case. I'm sure I'll have questions for you once/if I get further along.

litHX.png
Looks good so far. I took a different approach and worked on things like UI first because I wasn't sure what I wanted to work on. Added localization support last week.
 

J1M

Arcane
Joined
May 14, 2008
Messages
14,628
I have a decision to make going forward with my project. The combat system needs to built, which will include numerous enumerations of skills/feats/attributes/classes/etc. I'm unsure of what the best way to represent these collections is. The simplest approach would be to use a basic C# enum and pipe that into some sort of structure that will look up the appropriate name, affect, etc. A better approach might be to create a base class, perhaps even a CustomEnum base class, and have the skills/feats enumerated through a values property that contains lots of 'yield return' statements. Or, there could be a better way to do enumerations that I haven't thought of.

The basic enum has the drawback of a variety of different combat system items resolving to the same enum value.
Code:
//access using something like this: Enum.GetNames(typeof(CreatureTypes));
enum CreatureTypes {
SPIRIT,
BEAST,
HUMANOID,
FLORA
}

The second option, which would roughly recreate the enum functionality of Java, is more code to set up and maintain.
Code:
class CreatureType : Jnum {
public static readonly CreatureType ANIMATE = new CreatureType("Spirit");
public static readonly CreatureType BEAST = new CreatureType("Beast");
public static readonly CreatureType HUMANOID = new CreatureType("Humanoid");
public static readonly CreatureType MAGICAL_BEAST = new CreatureType("Flora");
 
new public static IEnumerable<CreatureType> Values {
get {
yield return SPIRIT;
yield return BEAST;
yield return HUMANOID;
yield return FLORA;
}
}
 
CreatureType(string name)
: base(name) {
}
}
Any thoughts?
 

Marsal

Arcane
Joined
Oct 2, 2006
Messages
1,304
My advice is to go with the simplest method, that's to say, the one that makes the most (intuitive) sense to you and is most straightforward to use in the further development. Complicating things and doing things outside your comfort zone (unless there is a REALLY good reason) only introduces bugs and headaches later on, IMO.
 

Styg

Stygian Software
Developer
Joined
Aug 18, 2010
Messages
742
Location
Serbia
If you have a limited set of things, enum is a good way to go. You can then later you is as a key in a dictionary to store additional information for that particular entity.

Avoid using IEnumerable, use dictionary instead, it's optimized for search and that's what you'll need most of the times.
 

J1M

Arcane
Joined
May 14, 2008
Messages
14,628
I will certainly be using enums. The question is whether to use C# or Java-style enums.
 

Styg

Stygian Software
Developer
Joined
Aug 18, 2010
Messages
742
Location
Serbia
I will certainly be using enums. The question is whether to use C# or Java-style enums.
Why would you simulate enum functionality when you already have it as language feature?
 

DakaSha

Arcane
Joined
Dec 4, 2010
Messages
4,792
Enum != Enum

edit: I dont speak java but the difference between C# enums and HaXe enums for instance is huge. At least iirc (Always possible i was unaware of C# enum functionality back then)
 

J1M

Arcane
Joined
May 14, 2008
Messages
14,628
I will certainly be using enums. The question is whether to use C# or Java-style enums.
Why would you simulate enum functionality when you already have it as language feature?
C# enums are just a thin layer around a set of integer constants.

Java enums are essentially a special type of class that doesn't support inheritance and can contain variables, methods, etc. With a Java enum you can do something like:
Code:
if(MyEnum.POWER_ATTACK.checkPrereqs(myCharacter)){
    myLevelUpList.add(MyEnum.POWER_ATTACK.getLocalizedName(), MyEnum.POWER_ATTACK.getFeatIcon());
}
//Obviously you'd never write this exact code, but you get the idea
 

lmbarns

Educated
Joined
May 16, 2012
Messages
83
Location
Seattle, WA
Damn looks like I'm getting a following. The butthurt on this forum is staggering.

I was specifically mentioning Drocon and Davaris as having prerequisites (not everybody) to criticize because in other posts they spew a bunch of bullshit and criticism without having any credibility themselves.

I love how every thread I post in someone follows me and brings the conversation back to Unity. Notice I posted in this discussion related to XNA because I was interested in it and Davaris had to troll (which I bit) with some statement his "idol" said as a strawman for why C# is a worthless language.

:bravo:
 

J1M

Arcane
Joined
May 14, 2008
Messages
14,628
I have a decision to make going forward with my project. The combat system needs to built, which will include numerous enumerations of skills/feats/attributes/classes/etc. I'm unsure of what the best way to represent these collections is. The simplest approach would be to use a basic C# enum and pipe that into some sort of structure that will look up the appropriate name, affect, etc. A better approach might be to create a base class, perhaps even a CustomEnum base class, and have the skills/feats enumerated through a values property that contains lots of 'yield return' statements. Or, there could be a better way to do enumerations that I haven't thought of.

Decided to code up functionality similar to a JavaEnum. The idea of constantly calling Enum.GetValues(typeof(enumType)) was not appealing to me. Also made them better than Java, because now you can use inheritance or composition with them. With this I can call an enumType.Values property. Sharing it here because it is fairly nifty and a highly requested C# feature. If anyone really cares I can share the EnumSet code too.

Code:
//Review the sample enum in the comments below for a template on how to implement a JavaEnum
    public abstract class JavaEnum : IComparable {
        public static IEnumerable<JavaEnum> Values {
            get {
                throw new NotImplementedException("Enumeration missing");
            }
        }
 
        public readonly string Name;
 
        public JavaEnum(string name) {
            this.Name = name;
        }
 
        public override string ToString() {
            return base.ToString() + "." + Name.ToUpper();
        }
 
        public int CompareTo(object obj) {
            if(obj is JavaEnum) {
                return string.Compare(this.Name, ((JavaEnum)obj).Name);
            } else {
                throw new ArgumentException();
            }
        }
 
 
        //Dictionary values are of type SortedSet<T>
        private static Dictionary<Type, object> enumDictionary;
        public static SortedSet<T> RetrieveEnumValues<T>() where T : JavaEnum {
            if(enumDictionary == null) {
                enumDictionary = new Dictionary<Type, object>();
            }
            object enums;
            if(!enumDictionary.TryGetValue(typeof(T), out enums)) {
                enums = new SortedSet<T>();
                FieldInfo[] myFieldInfo = typeof(T).GetFields(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public);
                foreach(FieldInfo f in myFieldInfo) {
                    if(f.FieldType == typeof(T)) {
                        ((SortedSet<T>)enums).Add((T)f.GetValue(null));
                    }
                }
                enumDictionary.Add(typeof(T), enums);
            }
            return (SortedSet<T>)enums;
        }
    }
 
    //*
    //Sample JavaEnum
    public class SampleEnum : JavaEnum {
        //Enum values
        public static readonly SampleEnum A = new SampleEnum("A", 1);
        public static readonly SampleEnum B = new SampleEnum("B", 2);
        public static readonly SampleEnum C = new SampleEnum("C", 3);
 
        //Variables or Properties common to all enums of this type
        public int int1;
        public static int int2 = 4;
        public static readonly int int3 = 9;
 
        //The Values property must be replaced with a call to JavaEnum.generateEnumValues<MyEnumType>() to generate an IEnumerable set.
        public static new IEnumerable<SampleEnum> Values {
            get {
                foreach(var e in JavaEnum.RetrieveEnumValues<SampleEnum>()) {
                    yield return e;
                }
                //If this enum should compose several enums, add them here
                //foreach(var e in ChildSampleEnum.Values) {
                //    yield return e;
                //}
            }
        }
 
        public SampleEnum(string name, int int1)
            : base(name) {
            this.int1 = int1;
        }
    }
    */
 

SCO

Arcane
In My Safe Space
Joined
Feb 3, 2009
Messages
16,320
Shadorwun: Hong Kong
Eh, the actual 'advantage' of java enums is that they forbid dynamic state: they're fixed values and their inner state doesn't change (yes in java this can cause problems if you're binding static things into enums, because of deserialization or construction before the static value is initialized, so you got to go lazy).

Subtyping goes against this, which is why the designers forbid it /well that and it was easier to do enums using the already defined single inheritance.
It's the same issue as why you shouldn't call overridable methods on constructors, but on steroids, since enums are supposed to offer even more guarantees.

BTW:
When a class extends a concrete Comparable class and adds a significant field, a correct implementation of compareTo cannot be constructed. The only alternative is to use composition instead of inheritance. (A similar situation holds true for equals. See Effective Java for more information.)
One consequence of these three provisions is that the equality test imposed by a compareTo method must obey the same restrictions imposed by the equals contract: reflexivity, symmetry, and transitivity. Therefore the same caveat applies:
there is no way to extend an instantiable class with a new value component while preserving the compareTo contract, unless you are willing to forgo the benefits of object-oriented abstraction (Item 8). The same workaround applies, too. If you want to add a value component to a class that implements Comparable, don’t extend it; write an unrelated class containing an instance of the first class. Then provide a “view” method that returns this instance. This frees you to implement whatever compareTo method you like on the second class, while allowing its client to view an instance of the second class as an instance of the first class when needed.

http://stackoverflow.com/questions/4983646/how-to-compare-classes-and-inherited-classes-in-java

failures of O.O. ;)

edit2: i just noticed your implementation: might want to make that method final (or the equivalent) so that it only can compare by name.
 

J1M

Arcane
Joined
May 14, 2008
Messages
14,628
A decent idea SCO, but not needed. C#'s version of final is called sealed and it is the implicit default on all methods. You only need to use it if you have first established a method as virtual and at some point in the inheritance chain you want to prevent it from being overridden further.

I did decide to modify the CompareTo method to use the ToString method's full type+name string. This led to caching that string via constructor to improve performance.
 

SCO

Arcane
In My Safe Space
Joined
Feb 3, 2009
Messages
16,320
Shadorwun: Hong Kong
Yeah :lol: don't know C# as well as i should. Anyway, just a bit of a warning; i've used enum before because of their explicitness and shininess and compact serialized form, and i'm pretty sure i fucked up.

My enum was like this:
public enum Blah implements Binding {
Fullscreen(DAction.createAction("Set/Reset fullscreen", "Toggles full screen", Application.instance, "fullScreen"), "alt ENTER"),
...
The interface was a keybiding, since they represent global shortcuts in the application. Anyway as you can see the enum takes as argument a Action and default keystroke - all apparently fixed values that don't really change - the problem was in the use of the Application.instance singleton. Since de-serialization of a enum actually is the same as accessing them (and anyway i used them in the constructor/readObject), the 'singleton' had to be not null at the time.

No big deal right? Just init the static field in the constructor and readObject of the Application class.

However i had a surprise when i did that: the singleton didn't blow up due to NPE; but the actions weren't operating on the right object if the deserialization failed - because if it did, the application got reset, and the instance that was shown on screen was different from the instance passed to the actions.

Moral of the story for me: if you're going to add arguments to your enums, make sure they are really final/sealed of if they can't - lazy.

So i got a lazy 'singleton' :lol:
 

As an Amazon Associate, rpgcodex.net earns from qualifying purchases.
Back
Top Bottom