C# Asynchronous sockets revisited

Three years ago I wrote a quick code snippet explaining asynchronous sockets. Recently someone found a rather large bug in that code so I decided to rewrite the tutorial (it’s one of my more popular articles and people have long been asking for the source code, which I lost a few years ago. So this way I kill a bug and give people the source code all at once).

I would like to thank stackoverflow user Polity for notifying me of the problems.

The client

Let’s first start with the client. For this example I created a small console application. It reads lines from the console until it sees an empty line. The text is then converted to a byte[] using the UTF8-Encoding schema.  Meanwhile I create a socket and call the BeginConnect method to start the process of creating an asynchronous connection. Asynchronous in this regards means that the entire program can keep crushing while a separate thread setups up the connection and sends the data. To guide the setup and the sending of the data while the program is running several callbacks are used. One to finish the connection setup and one to send the actual data. Before the actual message is sent I first send 4 bytes to tell how long the message is going to be. (Not doing this caused a subtle bug in the previous version which assumed a message was done once the receive buffer of the server was not entirely filled).

The server

The server is also simple. There is one socket continuously accepting new connections. So in contrary to the previous version this version accepts multiple concurrent connections. Once a connection has been made a separate thread is spawned, implicitly, by using the asynchronous BeginAccept method. In a callback the connecting is accepted using a new socket so the server can keep listing for more connections on the old socket. For each connection a small state object is kept to do the bookkeeping. It stores the active socket, the buffer, and fields  with information about the amount of data we expect to receive and how much data we have indeed received. In the read callback the first 4 bytes are extracted so that we know how much data to accept. After that we keep using BeginReceive until all data has made it’s way to the server. Only then we reconstruct the message.

Note that I use the TCP protocol for the sockets so I know that the data will be complete and in-order.

The source code

I’ve created a Visual Studio 2012 solution with the above two projects in them. Everything is compiled using the .NET 4.5 framework. The example will probably also compile in .NET3.5 but I noticed some methods that I previously used were deprecated  in .NET4.5, so I’ve used alternatives that might no be available in .NET3.5 (should be trivial to fix).

You can find the source code here

09
Sep 2012
CATEGORY

Blog, Programming

COMMENTS 5 Comments

Farseer physics 3.3.1 and XNA: Joints

In the previous tutorial, which you can find here, we created static and dynamic bodies. In this second tutorial we are going to take a look at joints. Simply said a joint is used to make a connection between two bodies or a body and the background.  The place where a joint is attached is called the anchor. Usually a joint has two anchors. One placed on the first body and one placed on a second body or on the world itself. Farseer uses the following naming convention for this. If a joint is ‘fixed’ it provides a joint between a body and the background/world. If a joint is not fixed it is used to connect two separate bodies to each other. So a RevoluteJoint connects two bodies and a FixedRevoluteJoint connects a body and the background/world.

Overview of joints

There are quite a few types of joints in Farseer:

Standard joints

Angle joints

Keeps a body at a fixed angle from another body or the world.

Distance joints

Keeps a body at a fixed distance from another body or from an anchor in the world.

Friction joints

Applies translational and angular friction to a body.

Line joints

A line joint can best be seen as a spring. It linearly connects to bodies (or a body and the background) together and tries to keep them at a fixed distance. It does not limit relative rotations but it does limit translation over one axis. They can be a bit tricky to place since the mass of the bodies themselves already affects the distance between the two bodies so setting the ‘at rest’ state is a bit of trial and error. Note that Line Joints are a new addition to Farseer and are not available in Box2D.

Prismatic joints

Enforces that two bodies can only slide in a linear motion (one degree of freedom) with respect to each other. See http://en.wikipedia.org/wiki/Prismatic_joint

Revolute joints

The most standard joints. Allows a body to rotate around an implicit axis coming from the screen (Z-Axis). Can be used to connect a body to the background or to another body.  Can be motorized.

Slider joints

A sort of prismatic joint that doesn’t limit the bodies to just linear motion. Best described as a combination of a revolute joint and a prismatic joint. Note that Slider Joints are also not available in Box2D.

Weld joints

Connects two bodies together disallowing any form of relative rotation/translation.

More complex joints

Gear joints

Connects two revolute joints or a revolute joint and a prismatic joint. Simulates that they are connected by gears so if the body on the first revolute joint rotates the body on the second revolute joint will rotate in the opposite direction.

Pulley joints

Used to create a pulley system. (Two bodies both connected to a rope that runs over a pulley). Can be used to create sophisticated elevators.

If you would like to know more about the joints Farseer offers you can check the Box2D documentation here (Farseer is a C# implementation of Box2D, and although it’s growing slowly to become more than that the best place for documentation is still the Box2D website).

Refactoring last week’s example

After doing some coding I found that I need access to the world-to-screen and screen-to-world conversion methods for the joints and they are currently members of the DrawablePhysicsObject class. So before we start creating or own joints we must first refactor last week’s example.

Create this new helper class:

    public static class CoordinateHelper
    {
        // Because Farseer uses 1 unit = 1 meter we need to convert
        // between pixel coordinates and physics coordinates.
        // I've chosen to use the rule that 100 pixels is one meter.
        // We have to take care to convert between these two
        // coordinate-sets wherever we mix them!

        public const float unitToPixel = 100.0f;
        public const float pixelToUnit = 1 / unitToPixel;

        public static Vector2 ToScreen(Vector2 worldCoordinates)
        {
            return worldCoordinates * unitToPixel;
        }

        public static Vector2 ToWorld(Vector2 screenCoordinates)
        {
            return screenCoordinates * pixelToUnit;
        }
    }

And then update the DrawablePhysicsObject class to use the helper class.

Some setup

Last week we added a list to store all the boxes that we randomly spawn. This week we’re going to create ‘paddles’ connected by joints. To store the paddles we’re going to need another list. So open Game1.cs and add the following field:

List paddles;

Then add the following three lines to draw the paddles:

foreach (DrawablePhysicsObject paddle in paddles)
{
    paddle.Draw(spriteBatch);
}

I’ve also added another image to the content project called ‘Paddle.png’.

Adding some bodies and joints

Now to demonstrate how to use joints I’m going to create three paddles. The first paddle will just be a simple body connected with revolute joint to the background. This means that it can spin freely. The second paddle is almost the same, but it will be motorized, adding some interaction to the scene. Finally we combine two line joints to create a trampoline. After this you should have a basic understanding on how joints work in Farseer.

A simple revolute joint

Add the end of the LoadContent method initialize the list we use to store the paddles. Then after that add the following code to create the first paddle:

// Create a simple paddle which center is anchored
// in the background. It can rotate freely
DrawablePhysicsObject simplePaddle = new DrawablePhysicsObject
(
    world,
    Content.Load("Paddle"),
    new Vector2(128, 16),
    10
);

JointFactory.CreateFixedRevoluteJoint
(
    world,
    simplePaddle.body,
    CoordinateHelper.ToWorld(new Vector2(0, 0)),
    CoordinateHelper.ToWorld(new Vector2(GraphicsDevice.Viewport.Width / 2.0f - 150,
                                         GraphicsDevice.Viewport.Height - 300))
);

paddles.Add(simplePaddle);

As you can see we first create a simple body, just as in the previous tutorial. The body is 128 pixels wide and 16 pixels high (note that the constructor of the DrawablePhysicsObject converts these units to world coordinates). It has a mass of 10KG. Note that we don’t have to set the position of the body. This is implicitly done by the joint, which fixes the body on the background at the anchor positions.

Next we create the joint. The first argument is our physics simulation and is used to register our joint to the simulation. We then pass the body this joint should be applied to. Since this is a Fixed joint we don’t need to pass a second body. The joint will connect the first body to the world. We then have to give some coordinates. We pass the center of the body (0,0) and somewhere in our world. Note that we use the conversion methods to go from pixel to world coordinates. Also don’t forget the last line, where we add the paddle to our list of paddles, else it won’t show up for drawing.

You can now run the simulation. Again press space to drop crate, you will see that we’ve create a small paddle that rotates freely when hit by a crate.

A motorized joint

The motorized joint is very similar:

// Creates a motorized paddle which left side is anchored in the background
// it will rotate slowly but the motor is not set soo strong that
// it can push everything away.
DrawablePhysicsObject motorPaddle = new DrawablePhysicsObject
(
    world,
    Content.Load("Paddle"),
    new Vector2(128, 16),
    10
);

var j = JointFactory.CreateFixedRevoluteJoint
(
    world,
    motorPaddle.body,
    CoordinateHelper.ToWorld(new Vector2(-48, 0)),
    CoordinateHelper.ToWorld(new Vector2(GraphicsDevice.Viewport.Width / 2.0f,
                                         GraphicsDevice.Viewport.Height - 280))
);

// rotate 1/4 of a circle per second
j.MotorSpeed = MathHelper.PiOver2;
// have little torque (power) so it can push away a few blocks
j.MotorTorque = 3;
j.MotorEnabled = true;
j.MaxMotorTorque = 10;

paddles.Add(motorPaddle);

Again we create a body and a Fixed Revolute Joint. But this time we store the joint created by the joint factory in the variable j so that we can access the properties of the joint. The revolute joint exposes a few interesting properties. The most interesting one is to motorize it. We’ve set a motor speed of pi/2. This means that the every second the joint will rotate the connected body by pi/2 radians, or a 1/4 of a circle. We also have to set the torque to give the motor enough power to rotate the body and to keep rotating even when a few crates are blocking the paddle. We also set the max motor torque and enable the motor. Again in the last line we add the paddle to our list of paddles so that it will be drawn.

A trampoline

To create a trampoline we will use two Line Joints (a sort of springs) to connect a paddle to the ground. This way we create some sort of trampoline. Add the following code:

// Use two line joints (a sort of springs) to create a trampoline
DrawablePhysicsObject trampolinePaddle = new DrawablePhysicsObject
(
    world,
    Content.Load("Paddle"),
    new Vector2(128, 16),
    10
);

trampolinePaddle.Position = new Vector2(600, floor.Position.Y - 175);

var l = JointFactory.CreateLineJoint
(
    floor.body,
    trampolinePaddle.body,
    CoordinateHelper.ToWorld(trampolinePaddle.Position - new Vector2(64, 0)),
    Vector2.UnitY
);

l.CollideConnected = true;
l.Frequency = 2.0f;
l.DampingRatio = 0.05f;

var r = JointFactory.CreateLineJoint
(
    floor.body,
    trampolinePaddle.body,
    CoordinateHelper.ToWorld(trampolinePaddle.Position + new Vector2(64, 0)),
    Vector2.UnitY
);

r.CollideConnected = true;
r.Frequency = 2.0f;
r.DampingRatio = 0.05f;

world.AddJoint(l);
world.AddJoint(r);

paddles.Add(trampolinePaddle);

Now the creation of the body should look really familiar now. Note that this time we do have to set the position of the body. The line joint will try to keep the paddle and the ground at roughly the same position as the starting position from each other so it needs some initial position.

We create two joints, they are exactly the same, except for where they connect to the paddle. One is anchored on the left side of the paddle and one on the right side. So I will only explain the first line joint.

We start by passing the body of the first body the line joint should connect to, the floor. We then pass the body of the paddle. We tell the line joint to connect to the paddle at the given relative coordinates.  We then give the axis of freedom the line joint should offer. In our case the Y-Axis.

We also set some properties, CollideConnected  means that the paddle and the floor can collide with each other. Handy now but for a wheel inside a car you might want to keep this at the default, turned off, state. We also set a nice frequency and damping ratio. Finally we add the joints to the world. Don’t forget this step! Only Fixed joints are automatically added to the world. We also add the paddle to our list of paddles to draw.

You can now run the simulation again. Try to drop a few crates on the trampoline, you will see that it behaves quite nicely.

Conclusion

Joints in Farseer are fairly easy to use and can add a dynamicity lot to your scene. Try playing around with all different joints to get a feel from them. All joints in Farseer are created using a way similar as shown in this tutorial. In the next tutorial we will add a controllable character and create a small platformer.

06
Sep 2012
COMMENTS 11 Comments
TAGS

, , ,

Using JavaScript as a script engine in XNA/C#

A scripting engine is a useful component in any game-engine. It allows you to execute modified code (aka scripts) in real time while your game is running. This gives you immediate feedback, allows for easy debugging of scripts and gives you true rapid prototyping abilities.

Scripting engines are also easier to work with than a full blown programming language, an error in a script is easy to recover from and because the scripts aren’t compiled it’s easy for the script interpreter to give helpful debug information. Even better: you don’t have to compile the script and the game keeps running so immediately after you fix the bug in your script you can see the result.

Script engines gives opportunities for ‘other’-programmers (gameplay, leveldesign, animator, etc..), they might not wish to delve into the intricacies of the programming language and frameworks you’re using for the game engine but they will be more than willing to write some script to modify the behavior of that new enemy.

So, why write a scripting engine for XNA? Well after reading the article ‘Embracing Dynamism’  by Niklas Frykholm on #AltDevBlogADay I got interested again in scripting engines. Shortly after that I heard that someone wrote a full JavaScript interpreter for C# called JINT  , well 1 + 1 = 2 so I started working on integrating JINT into XNA and see if I could set up an external IDE in WPF that, while the game is running, could load, modify and execute script code. After a few tries I finally succeeded and I’m pretty proud of the result.

All the wrapping and magic happens in the JintXNA project. The code, as it is now, works fine on Windows but Windows Phone and Xbox 360 support isn’t there yet out of the box since JINT is targeted at the full .NET 4.0 framework. However there is a port of JINT which targets the .NET Compact Framework  which should run on WP7 and the 360, I haven’t tried this yet though.

You can download the full source code of JintXNA here this package includes the JintXNA project, the IDE and a sample project and script as seen in the video.

05
Jun 2012
COMMENTS No Comments

Another faster version of A* (2D+3D) in C#

As you might know I once wrote an A* sample for C# more than 2 years ago. The first version worked but was very slow because of a bug. The second version was faster, and a third version (made by one of the readers of this blog) was even faster.

Btw did you know that the excellent game Dysomnia shipped with (a modified) version of my C#/A* code? Ok it’s just a few lines to get people started but it’s really cool to see how people use this little start for their cool projects!

Anyway, back on topic: during my internship at Nixxes an interested co-worker (thanks Marcel!) tweaked the heuristic, removed some unnecessary checks, and added a faster way to check if a tile was processed yet.

There is not much else to say, it’s still A*, it supports 2D and 3D, it uses a MinHeap and is faster than ever! (Note: this is a pure C# solution, so it doesn’t require XNA, but it will work nicely with XNA even on WP7 and the Xbox360).

Download the latest version here

Older relevant blog posts about A*  (from older to newer)
http://roy-t.nl/index.php/2009/02/24/implementing-a-path-finding-in-c-and-xna-source-code-can-we-cut-the-corner/
http://roy-t.nl/index.php/2009/07/07/new-version-a-pathfinding-in-3d/
http://roy-t.nl/index.php/2010/06/27/more-a-improvements/

Nixxes internship post-mortem

I tried to do a weekly update during my internship at Nixxes, but I never got around to finish a single post. However since Post-Mortems are hip these days I decided to write a simple post-mortem about my internship.

Let’s start with the beginning. In the first week my mentor at Nixxes was still on vacation so a co-worker set me up with a new computer (a shiny i7) and helped me set-up the development environment. I was handed a few drafts from another co-worker who a few years back wrote a proposal for the tool I was to build. So I tried to arm myself with knowledge and put my education to the task by writing things like inception documents and prototype proposals. Although this was a bit formal for the team (they only do a light scrum + two person commits) it helped me get a good overview of what I had to do. I also played a lot with their technology (trying to give good old Lara Croft green hair in a test-level of TR:Legend).

The tool I was to build had a simple enough goal and had to do with their automatic shader generation. I had to make a tool that gave artists insight in how different settings on materials would create different shader configurations. It was not to give technical insight inside the shaders (you wouldn’t want to bore artists with that) . But to let them reduce the number of actual shaders by simplifying material.

In the next few weeks I started searching for existing tech, testing and prototyping. I needed tools to show large complex graphs with a lot of cross-nodes. So I started searching for layout algorithms (In the end I combined two layout techniques and wrote code myself, but it’s always good to check if you’re not reinventing the wheel, and it gave me some great insights).

I also had to familiarize myself with WPF, which I really enjoyed (the learning curve for WPF is much shorter than for WinForms and the performance and ‘nice-ity’  of WPF greatly outclasses WinForms).

After a few prototypes we decided on a work-flow for the program and refined the core questions the program had to solve.  It’s really helpful to write those down because a goal might be too abstract/far away so these core questions help you refine your way to do the goal and give you some work flow hints. (It’s also good to have these in your help file).

Because of the limited time there was only one week of feedback from real artists but of course I was surrounded by techies  to help fill this void.

In the end we refined the work flow once more and tied in the program with existing tools. (Up until now I was just parsing raw data). I hooked into a content-service using C++/CLI. This C++/CLI program also hosted my C#/WPF frontend, and to my surprise this worked really well and was easy to do!

In the end I left behind a well document and finished product and because we had a week to spare there was even quite some polish (the last week was used to add in some background workers and  nicer progress bar, I also added cancellation support to the layout algorithm).

During my internship I also experienced the release of Deus Ex: Human Revolution, of which the tech and pc-port was done by Nixxes, so it was really great to see the game get an 8,9 on meta-critic!

The end-talk with my mentor was relaxed and pleasant. I knew I had done pretty well but I was quite surprised when he gave me a final grade of 9 out of 10! Yay!

All in all I had a great time, and I’ve learned a lot of new techniques (C++/CLI, WPF, Graph Layout Algorithms, Data Binding). I also finally got to experience a real hands-on approach where everything gets prioritized because resources are finite. On the university  it’s really a rare thing to experience this, so this was really an eye opener. I feel like I learned more valuable skills in these two months than I would have doing 3 more courses (Thanks to a helpful dean I could replace 3 courses with this intern shop)

I would like to thank everyone at Nixxes for a great time!

PS.

One of my co-workers again sped up my A* code after peeking at my blog. I have his code and am trying to add a nice visualizer to it this time before posting it, so expect it up soon.

Internship at Nixxes (cooperating with Ubisoft Montreal)

This summer I’ll be doing an internship at Nixxes Software in Utrecht, the Netherlands.  They are a group of highly experienced game technology programmers who are independent but work mostly for Ubisoft Montreal. Their latest projects includes work on “Lara Croft and the guardian of light”, “Deus Ex: Human Revolution”, and “Kane & Lynch 2″. They mostly develop on the engine used for these games, and tooling. It’s not yet sure what I’ll be doing but it will probably be a tool that too measure where performance can be increased, it will probably written in C# with interop-ed with C++/CLI.

I’m not yet sure if I’ll be working under an NDA (probably) and how much info I can release on what I’ve been doing, but I’d like to write a sort of development diary here. I’ll probably not be writing tutorials for the coming 2 months because I won’t have much free time.

Anyway I’ll be back after 2 months, so stay tuned and enjoy your summer vacation (I hope it will be more of an actual vacation for most people ;-) ).

Lara Croft and the Guardian of Light

03
Jul 2011
CATEGORY

Blog

COMMENTS 2 Comments

Traversal algorithms using yield

So two days ago I wrote a an article on traversal algorithms using delegates. One of the commenters (I’m looking at you Mart) mentioned a different approach using the yield keyword, which generates a state machine underneath.

I had heard of the yield keyword before, but I’ve never used it so far. I was thrilled to work out his comment, to find out how it works, et voila ,this blog-post was written.

I first wrote this generic Node class which allowed me to build a tree like structure.

    public class Node<T>
    {
        public Node(T self, List<Node<T>> children)
        {
            this.self = self;
            this.children = children;
        }
        public T self;
        public List<Node<T>> children;
    }

Depth first traversal of this tree is easily done using yield.

        public static IEnumerable<T> Traverse<T>(Node<T> root)
        {
            Stack<Node<T>> stack = new Stack<Node<T>>();
            stack.Push(root);
            while (stack.Count > 0)
            {
                Node<T> n = stack.Pop();
                yield return n.self;
                foreach (Node<T> child in n.children)
                {
                    stack.Push(child);
                }
            }
        }

When compiled, this piece of code generates a thread-safe state machine (very nifty) but thanks to the abstraction that yield gives us we don’t have to worry about. We can just interact with this method as if the result is an IEnumerable (as indicated/expected), so we can use this method like this:

                foreach (int i in DepthFirstTraversal.Traverse<int>(rootNode))
                {
                     //DoSomethingWith(i);
                }

But what are the performance implications of this hidden state machine? To test this I’ve adapted the previous post’s traversal algorithm to be as similar as possible:

        public static void Traverse<T>(Node<T> root, Action<T> action) 
        {
            Stack<Node<T>> stack = new Stack<Node<T>>();            
            stack.Push(root);

            while (stack.Count > 0)
            {
                Node<T> n = stack.Pop();
                action(n.self);
                foreach (Node<T> child in n.children)
                {
                    stack.Push(child);
                }
            }
        }

Performing a given action for each item in our tree (depth first) is done like this:

DepthFirstTraversal.Traverse<int>(rootNode, (i) => DoSomethingWith(i));

Using a recursive algorithm I constructed a tree (of ints) with a depth of 10, where each node has 2 child nodes. I then benchmarked how long it took to add each item in the tree to a list like this:

List<int> results = new List<int>(41);
//Yield approach
                foreach (int i in DepthFirstTraversal.Traverse<int>(rootNode))
                {
                    results.Add(i);
                }
//Action approach
                DepthFirstTraversal.Traverse<int>(rootNode, (i) => results.Add(i));

After 100.000 iterations the result was the following:

Average milliseconds for yield approach:            0.01265
Average milliseconds for delegate/Action<> approach 0.00578

So the yield approach is more then two times as slow as the delegate approach to a depth first traversal, which isn’t surprising since we’re talking state machine vs method+virtual lookup. Still it was interesting to see how yield works. For more in depth info about yield see this article by Jon Skeet.

See the code for this benchmark here

12
Feb 2011
COMMENTS 2 Comments
TAGS

, , ,

Traversal algorithms using generics, generic constraints (where), and Action delegates

As many of you I enjoy solving a very complex problem, however sometimes it’s finding new ways todo simple things that really excites me! This happened again today, I was working on a simple Depth-First-Search traversal algorithm when it suddenly doomed to me that I was duplicating a lot of code because I had to do DFS multiple times, with the only difference the action to take at each node.

Pondering about this for a few minutes and I thought about using a delegate as a sort of method pointer to tell the DFS algorithm what action to take for each node. I wrote a quick delegate and named it Action, but then I remembered that C# has the built in Action delegate.

With these techniques in mind I quickly wrote the following code:

public void DFS<T>(T node, Action<T> action) where T : IHasChildren<T>
{
    Stack<T> stack = new Stack<T>();
    action(node);
    stack.PushMany<T>(node.Children);
    while (stack.Count > 0)
    {
        T n = stack.Pop();
        action(n);
        stack.PushMany<T>(n.Children);
    }
}

public interface IHasChildren<T>
{
    List<T> Children;
}

This way you can use DFS on any type of node as long as it implements IHasChildren, and you can use any Action too, saves a lot of duplicate code !

Edit:

Stack.PushMany is my own extension method that allows a list to be put on a stack (just a simple for each).

10
Feb 2011
CATEGORY

Blog, Programming

COMMENTS 7 Comments

Wrapping effect files into proper classes

In XNA shaders are processed into Effect objects by the content pipeline. These effect objects are not really ‘first class citizens’ because, contrarily to most C# classes, these classes have a lot of loosely-typed features. To remedy this I’m going to show you how I wrap these effect objects into their own wrapper, when we see the differences I’ll explain the pros and cons of my approach.

For this tutorial we’re going to use a part of a shader I use for deferred rendering:

float4x4 World : WORLD;
float specularIntensity = 0.8f;
texture Texture : TEXTURE;

As said, the content processor wraps this nicely into an Effect object. Now if we’d like to draw something with this effect it would probably be done something like this:

Effect effect = Content.Load<Effect>("myEffect");
//Draw:
effect.Parameters.GetParameterBySemantic("World") = Matrix.Identity;
effect.Parameters["specularIntensity"] = 0.5f;
effect.Parameters["texture"] = 56;
effect.Techniques["technique1"].Passes[0].Apply();

Given the rest of the code is correct this will compile nicely, however during runtime we will receive an exception. Because we set the effect parameter “texture” to 56, which is not a proper texture value. Due to the loose typing this error could not be detected by the compiler, so it could sneak up on us. Also it’s a bit hard to remember all the parameters an effect has, because we cant see that without opening the .fx file, I’d argue that the effect class is not a proper class as we know other classes to be in C#. And it can’t be, because it has to be compatible with so many different shaders. Therefor I push forward my approach.

For the above shader I would write the following class:

    public class MyEffect
    {
        public MyEffect(Effect effect)
        {
            worldMatrix = effect.Parameters.GetParameterBySemantic("World");                        
            texture = effect.Parameters.GetParameterBySemantic("Texture");  
            specularIntensity = effect.Parameters["specularIntensity"];
            
            technique1 = effect.Techniques["Technique1"];            
        }

        public void Apply()
        {
            technique1.passes[0].Apply();
        }

        #region FieldsAndProperties        
        private EffectTechnique technique1;        

        private EffectParameter worldMatrix;
        public Matrix WorldMatrix { set { worldMatrix.SetValue(value); } }
        
        private EffectParameter texture;
        public Texture2D Texture { set { texture.SetValue(value); } }
        
        private EffectParameter specularIntensity;
        public Texture2D SpecularIntensity { set { specularIntensity.SetValue(value); } }
        #endregion
        
    }

Using this code drawing an object would look like this:

MyEffect effect = new MyEffect(Content.Load<Effect>("myEffect"));
//Draw:
effect.World = Matrix.Identity;
effect.SpecularIntensity = 0.5f;
effect.Texture = 56;
effect.Apply();

In my opinion this is a lot more readable and we now get an error while compiling that 56 does not match the type “Texture” also the new wrapper is more of an interface for the effect file. If we change one of the variable names in the effect file, we now only have to make a change at one place in our code base, even if we change the type of a parameter using some logic in the property we might still not have to change all the code. And if we really have to we will get a lot of helpful compiler warnings. We can now also find all references to a specific parameter. However the big downside is that Effect works for all effects (well you still have to remember the parameters and techniques which differ per shader), and this approach requires you to write a class per shader.

Anyway this is my approach, I’d love to know how other people handle this problem, and if you have any comments.

Update 7-2-2011:
After discussing alternative approaches (thanks Flashed!) I would like to give everybody a tip to try an extend this system. How about have a content pipeline project that automatically matches an effect file with an effect wrapper? You can use metadata in the .fx files todo this!

06
Feb 2011
CATEGORY

Blog, Programming, XNA

COMMENTS 3 Comments

An example of the ref keyword in C# (for structs and classes)

There is a lot of confusion about the ref keyword in C#. Many claim that it shouldn’t be used for classes, only for the very different structs. But the reference keyword can actually be very handy for both classes and structs!

The reference keyword signals .NET to pass the address of the reference to the correct memory instead of the reference itself. Now that is a bit vague, so let’s take a look at the following diagram:

I’ll first explain the scenario without using the ref keyword:

Object obj = new Object();
Change(obj);

public void Change(Object o)
{
    o = new Object();
}

First we create a new object. In our diagram this first creates the data “Reference1″ in a fresh piece of memory. This reference is like an address book and points toward a location in memory (for C people, points as in pointer). In the fresh piece of memory where “Reference1″ points we place the data for our new object. Now we pass our object to the method change. On a low level this means that a fresh piece of memory is found, the data in “Reference1″ is copied there (For the well computer versed, when a method is called, all the arguments for that method are copied and put on the stack). Let’s call this new pointer “Reference2″. This “Reference2″ at first still points at “MemoryLocation1″. However in the Change method we now create a new Object using the new keyword. This creates a new object in a fresh location in our memory. Let’s call this “MemoryLocation2″. To reflect these changes the address where “Reference2″ is pointing at is also changed, this way we keep referencing the correct object. As you can see the address in “Reference1″ is not changed, so “Reference1″ still points at “MemoryLocation1″ and “Reference2″ points at “MemoryLocation2″.

Now let’s consider what happens when we do use the reference keyword.

Object obj = new Object();
Change(ref obj);

public void Change(ref Object o)
{
    o = new Object();
}

At first we again have “Reference1″ pointing at “MemoryLocation1″. But when we pass our new object to the Change method something different happens. Instead of copying “Reference1″ the memory location of “Reference1″ is copied and put on the stack, in our diagram this is “ReferenceAddress”. When new object is created it’s again put in a fresh memory location (say “MemoryLocation3″). However since we are working with the address of “Reference1″, instead of a new reference, “Reference1″ is updated to point to “MemoryLocation3″. So the instance o inside the method change and the instance obj are now the same.

If this is still a bit fuzzy to you, here is a piece of code that should make it totally clear :). Note that structs and classes act in the same fashion this way:


public class MyClass //public struct MyStruct looks exactly the same, but is a struct
{
    public int MyData;
    public MyClass(int data)
    {
        this.MyData = data;
    }
}
class Program
    {
        static void Main(string[] args)
        {
            MyStruct struct1 = new MyStruct(1);
            Modify(struct1);

            MyStruct struct2 = new MyStruct(2);
            ModifyRef(ref struct2);
            Console.Out.WriteLine(String.Format("struct1: {0}, struct2: {1}", struct1.MyData, struct2.MyData));
//outputs "struct1: 1, struct2: 21"

            MyClass class1 = new MyClass(1);
            Modify(class1);

            MyClass class2 = new MyClass(2);
            ModifyRef(ref class2);

            Console.Out.WriteLine(String.Format("class1: {0}, class2: {1}", class1.MyData, class2.MyData));
//outputs "class1: 1, class2: 21"
            Console.ReadLine();
        }

        static void Modify(MyStruct s)
        {
            s = new MyStruct(11);
        }
        static void Modify(MyClass c)
        {
            c = new MyClass(11);
        }
        static void ModifyRef(ref MyStruct s)
        {
            s = new MyStruct(21);
        }
        static void ModifyRef(ref MyClass c)
        {
            c = new MyClass(21);
        }
    }
22
Jan 2011
CATEGORY

Blog, Programming

COMMENTS 2 Comments