Roy Triesscheijn’s Weblog

My programming world

Just a quicky

Posted by Roy Triesscheijn on December 8th, 2011

I always feel kind of obliged to make at least a post a month here, unfortunately I wasn’t able to post anything useful since the end of September (shame on me). Actually I haven’t been doing much programming at all lately. My main focus now is finishing up my Bsc in Computing Science, just one more course to go and of course the dreaded thesis. To everyone’s surprise, including mine, I will be doing a thesis about a topic picked by one of my professors who specializes in “intuitionistic propositional logic”. Hell I don’t even know what that means. Luckily for me I’ll be only dealing with a small sub-problem related to calculating the number of ‘upwards closed subsets’ (I’m not sure if this direct translation from Dutch to English makes any sense academically). Anyway it will mean I can visualize and think a lot of lattices.

So back to that tutorials thing that should be going on here. Don’t worry I’m not stopping or even formally postponing anything. I even have a few code files and some word documents laying around about adding ways to tint models programmatically so that you can give models more diverse looks without much more work. However I can’t promise when I get around to publishing it, hell I’ve got a new computer and it hasn’t even got XNA on it yet! Although I’m seriously considering switching to something else.

I would also like to add a tutorial or two on graph layout algorithms, both from my internships and the lattices that I’m going to visualize for my thesis.

Meanwhile while you wait, why not pick up the new Trine 2 which is a really good Indie game, man it looks absolutely perfect and the first 30 minutes already promise a lot more fun than Trine 1. *Not an advertisement, I’m just hyper excited about it :P *.

Sincerely,

Roy Triesscheijn

Posted in Blog | No Comments »

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

Posted by Roy Triesscheijn on September 24th, 2011

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/

Tags: , , , , , ,
Posted in Blog, General Coding, General Gamedesign, Tips, XNA | 4 Comments »

Nixxes internship post-mortem

Posted by Roy Triesscheijn on September 5th, 2011

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.

Tags: , , , , , , , ,
Posted in Blog, General Coding, General Gamedesign, Personal | No Comments »

Internship at Nixxes (cooperating with Ubisoft Montreal)

Posted by Roy Triesscheijn on July 3rd, 2011

 

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 ;-) ).

Lare Croft and the Guardian of Light

Tags: , , , , ,
Posted in Blog | 2 Comments »

Science LinX Herschel Exhibit

Posted by Roy Triesscheijn on June 19th, 2011

For Science LinX I’ve working on an exhibit regarding the ESA Herschel satellite for the last 6 months, and I’m happy to inform you that it’s almost complete.

Features

-Camera is moved by using multi-touch signals sent by monitor,
-Accurate simulation of our solar system, planets support properties like eccentricity, inclination, orbital radius, equatorial diameter,  rotations per earth-year, orbits per earth-year.
-Herschel satellite stationary in lagrange point L2.
-Fully 3D
-Multiple lighting effects
- Particle effects (not currently used)
-Beautiful skybox generated using Space Scape
-Expandable information boxes slowly center arc-ball camera on P.O.I.
-Twitter integration (following the @ESAHERSCHEL channel)
-Clickable planets, satellites and points of interests
-Multiple Zoom levels smoothly change information windows, ‘tunnel vision’.

Screenshots

Anyway, this all sounds exciting (or not) but it’s always better  to see it for yourself:

The Team
-Bart v/d Laar (Project Manager Science LinX)
-Ingeborg Veldman (Project Manager Science LinX Virtual)
-Hilbert Dijkstra (Project Designer, Text Writer)
-Roy Triesscheijn (Programmer)
-Hugo Engwerda (Artist)
-Gerwin Kramer (Modeler)
-Peter Barthel (Astronomer/Technical Consultant)

Tags: , , ,
Posted in Blog, General Coding, XNA | No Comments »

Codesnippet: A simple custom hexagon shape for WPF/Silverlight

Posted by Roy Triesscheijn on May 24th, 2011

Recently I’ve been trying to learn more about WPF, since WinForms is getting really old now. As a small exercise I was trying to create a custom Shape, so I created a new class, derived it from Shape and started following this tutorial untill I found out that you can’t override the DefiningGeometry method in Silverlight.

After some searching I found this MSDN Blog article, where in Silverlight a custom shape is created by extending from Path (well I wouldn’t have thought of that).

After a bit of tweaking I adapted the class to display a Hexagon instead of a Triangle:

namespace MyProject.Shapes
{
    public class Hexagon : Path
    {
        public Hexagon()
        {
            CreateDataPath(0, 0);
        }

        private void CreateDataPath(double width, double height)
        {
            height -= this.StrokeThickness;
            width -= this.StrokeThickness;

            //Prevent layout loop
            if(lastWidth == width && lastHeight == height)
                return;

            lastWidth = width;
            lastHeight = height;

            PathGeometry geometry = new PathGeometry();
            figure = new PathFigure();

            //See for figure info http://etc.usf.edu/clipart/50200/50219/50219_area_hexagon_lg.gif
            figure.StartPoint = new Point(0.25 * width, 0);
            AddPoint(0.75 * width, 0);
            AddPoint(width, 0.5 * height);
            AddPoint(0.75 * width, height);
            AddPoint(0.25 * width, height);
            AddPoint(0, 0.5 * height);
            figure.IsClosed = true;
            geometry.Figures.Add(figure);
            this.Data = geometry;
        }

        private void AddPoint(double x, double y)
        {
            LineSegment segment = new LineSegment();
            segment.Point = new Point(x + 0.5 * StrokeThickness,
                y + 0.5 * StrokeThickness);
            figure.Segments.Add(segment);
        }

        protected override Size MeasureOverride(Size availableSize)
        {
            return availableSize;
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            CreateDataPath(finalSize.Width, finalSize.Height);
            return finalSize;
        }

        #region FieldsAndProperties
        private double lastWidth = 0;
        private double lastHeight = 0;
        private PathFigure figure;
        #endregion
    }

You can use a ‘shape’ like this in XAML:

<UserControl x:Class="FantasyCartographer.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:Shapes="clr-namespace:MyNameSpace.Shapes"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <Canvas Height="161" HorizontalAlignment="Left" Margin="27,32,0,0" Name="canvas1" VerticalAlignment="Top" Width="254">
            <Shapes:Hexagon Canvas.Left="0" Canvas.Top="0" Height="154" x:Name="hexagon1" Stroke="Black" StrokeThickness="3" Width="188" Fill="Red"  />
        </Canvas>
    </Grid>
</UserControl>

Tip: don’t forget to define an xmlns namespace mapping to your own .NET namespaces so that you can use a shape even if you defined it in another namespace, I’ve done this in the above XAML code as an example.

Tags: , , , , ,
Posted in Blog, General Coding, Silverlight, Webdesign | No Comments »

XNA stereoscopic 3D using anyglyphs and red/cyan 3D-glasses

Posted by Roy Triesscheijn on May 8th, 2011

Anaglyphs are images designed to give a 3D effect when viewed with special glasses, usually with red and blue (sometimes red and cyan) filters over the left and right eyes, respectively.[1]


Using anaglyphs we can make our game look real 3D through those cheap red/cyan 3D-glasses. Adding an anaglyph effect to your XNA game is fairly easy.

Basically we need to undertake the following steps:
-Draw our scene twice to separate render targets, with a slightly offset camera
-Use a shader and draw a full screen quad to blend the images and color coding the images for each eye

Easy right!

Lets start by assuming you have the following draw code:

protected override void Draw(GameTime gameTime)
{
    //a lot of draw calls
    base.Draw(gameTime);
}

We need to extract all your drawing code (except base.Draw(..)) to a new method that as argument accepts a view matrix. Update your code so that the passed viewMatrix is used instead of your normal camera’s viewMatrix. Doing this will allow us to easily draw the scene twice with a slightly offset camera. You should now have something like this:

private void DrawForEye(Matrix viewMatrix)
{
    //...
}

Now let’s first write the shader that is going to blend the images, create a new effect in your content project and paste in the following code:

texture left;
sampler sLeft = sampler_state
{
	texture = ;
	magfilter = POINT;
	minfilter = POINT;
	mipfilter = POINT;
	AddressU  = CLAMP;
	AddressV  = CLAMP;
};

texture right;
sampler sRight = sampler_state
{
	texture = ;
	magfilter = POINT;
	minfilter = POINT;
	mipfilter = POINT;
	AddressU  = CLAMP;
	AddressV  = CLAMP;
};

struct VS_INPUT
{
	float3 Pos : POSITION;
	float2 Tex : TEXCOORD0;
};

struct VS_OUTPUT
{
	float4 Pos : POSITION;
	float2 Tex : TEXCOORD0;
};

void VtAnaglyph(VS_INPUT In, out VS_OUTPUT Out)
{
	Out.Pos = float4(In.Pos,1);
	Out.Tex = In.Tex;
}

float4 PxAnaglyph(VS_OUTPUT In) : COLOR0
{
    float4 colorLeft = tex2D(sLeft, In.Tex.xy);
	float4 colorRight = tex2D(sRight, In.Tex.xy);
    return float4(colorRight.r, colorLeft.g, colorLeft.b, max(colorLeft.a, colorRight.a));
}

technique Anaglyphs
{
    pass p0
    {
        VertexShader = compile vs_2_0 VtAnaglyph();
        PixelShader = compile ps_2_0 PxAnaglyph();
    }

}

This is a pretty standard HLSL shader, but I will quickly go over it.

The texture’s left and right will be the textures resulting from drawing the scene twice, slightly offset from each other. We use a sampler with POINT filters because the left and right textures are going to be exactly the same size as our final rendering.

The vertex shader is passed as input nothing more than the position and texture coordinate of the vertex, it doesn’t transform anything but it just directly passes to the pixel shader.

The pixel shader samples the textures for the left and right eye. The red channel is used to ‘encode’ the image for the right eye (the red is unfiltered by the cyan colored lens). The green and blue channel are taken from the image for the left eye (they are unfiltered by the red colored lens). You can look at this wikipedia entry for other color combinations in case you have different 3D-glasses.

Now that we have our effect we need to add 2 render targets, the effect and a quad renderer to our game class. (The Quad class is posted as a code snippet here and used as to render the final image).

Added these lines to the top of your game class.

RenderTarget2D leftEye;
RenderTarget2D rightEye;
Effect anaglyphEffect;
QuadRenderer quad;

//you can change this later to test different distances between the left and right eye viewpoint,
//the offset depends on the scale of your game, but small values seem to work best.
//I used 0.05 for a scene about 5x5x5 size.
float ammount = 0.05f;

And add these lines in your LoadContent method:

leftEye = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
rightEye = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
anaglyphEffect = Content.Load("Anaglyphs");
quad = new QuadRenderer(GraphicsDevice);

Now we need to calculate two slightly offset view-matrices, draw the scene two times using these view-matrices and then combine them using our effect. To accomplish this write the following Draw method:

protected override void Draw(GameTime gameTime)
{
    Matrix viewMatrix = camera.ViewMatrix; //use your own camere class here

    //The vector pointing to the right (1,0,0) as seen from the view matrix is stored
    //in the view matrix as (M11, M21, M31)
    Vector3 right = new Vector3(viewMatrix.M11, viewMatrix.M21, viewMatrix.M31) * amount; //ofset from the center for each eye
    Matrix viewMatrixLeft = Matrix.CreateLookAt(camera.Position - right, camera.LookAt, Vector3.Up);
    Matrix viewMatrixRight = Matrix.CreateLookAt(camera.Position + right, camera.LookAt, Vector3.Up);

    GraphicsDevice.SetRenderTarget(leftEye);
    DrawForEye(viewMatrixLeft, camera.ProjectionMatrix);

    GraphicsDevice.SetRenderTarget(rightEye);
    DrawForEye(viewMatrixRight, camera.ProjectionMatrix);

    GraphicsDevice.SetRenderTarget(null);

    anaglyphEffect.Techniques["Anaglyphs"].Passes[0].Apply();
    anaglyphEffect.Parameters["left"].SetValue(leftEye);
    anaglyphEffect.Parameters["right"].SetValue(rightEye);
    quad.DrawFullScreenQuad();

    base.Draw(gameTime);
}

And hooray! We now have anaglyphs in our game! This will result in some pretty picture (the following picture of course only make sense when you use red/cyan 3D-glasses)

Anaglyph Example, view with red/cyan glasses

When you have created some cool anaglyph images in XNA, be sure to send them in, I’ll make a small gallery here!

Tags: , , , , ,
Posted in Blog, General Coding, XNA | 5 Comments »

CodeSnippet: Quad renderer

Posted by Roy Triesscheijn on May 7th, 2011

This quad renderer was already part of my conversion of Catalin Zima’s Deferred Rendering for XNA tutorial, but because I plan to use it in a tutorial I’m going to write later today here is a handy snippet for drawing a quad with texture coordinates in XNA. (You could use the SpriteBatch class for this, but as you all know the SB class tends to mess up your render state if you do not define all states correctly).

Anyway here’s the class:

    public class QuadRenderer
    {
        public QuadRenderer(GraphicsDevice device)
        {
            this.device = device;
            vertices = new VertexPositionTexture[]
            {
                new VertexPositionTexture(new Vector3(0,0,0),new Vector2(1,1)),
                new VertexPositionTexture(new Vector3(0,0,0),new Vector2(0,1)),
                new VertexPositionTexture(new Vector3(0,0,0),new Vector2(0,0)),
                new VertexPositionTexture(new Vector3(0,0,0),new Vector2(1,0))
            };

            indexBuffer = new short[] { 0, 1, 2, 2, 3, 0 };
        }

        public void Draw(Vector2 v1, Vector2 v2)
        {
            vertices[0].Position.X = v2.X;
            vertices[0].Position.Y = v1.Y;

            vertices[1].Position.X = v1.X;
            vertices[1].Position.Y = v1.Y;

            vertices[2].Position.X = v1.X;
            vertices[2].Position.Y = v2.Y;

            vertices[3].Position.X = v2.X;
            vertices[3].Position.Y = v2.Y;

            device.DrawUserIndexedPrimitives&lt;VertexPositionTexture&gt;(PrimitiveType.TriangleList, vertices, 0, 4, indexBuffer, 0, 2);
        }

        public void DrawFullScreenQuad()
        {
            Draw(Vector2.One * -1, Vector2.One);
        }

        #region FieldsAndProperties
        private VertexPositionTexture[] vertices = null;
        private short[] indexBuffer = null;
        private GraphicsDevice device;
        #endregion
    }

Tags: , ,
Posted in Blog, XNA | 1 Comment »

Codesnippet: VertexPositionColorNormal

Posted by Roy Triesscheijn on April 13th, 2011

For some prototyping I needed a struct like VertexPositionColor, but I also needed a normal, after a minute of Googling I found out that nobody wrote a small (XNA4) compatible snippet) for this. So here I give you my own snippet. (Which also is a handy reference to see how the ‘new’ IVertexType interface in XNA4 works (yes I still think of XNA4 as new).

Anyway the source code:

    public struct VertexPositionColorNormal : IVertexType
    {
        public Vector3 Position;
        public Color Color;
        public Vector3 Normal;

        public VertexPositionColorNormal(Vector3 position, Color color, Vector3 normal)
        {
            this.Position = position;
            this.Color = color;
            this.Normal = normal;
        }

        public static readonly VertexElement[] VertexElements =
        {
            new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
            new VertexElement(sizeof(float)*3, VertexElementFormat.Color, VertexElementUsage.Color, 0),
            new VertexElement(sizeof(float)*4, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0)
        };
        public static readonly VertexDeclaration vertexDeclaration = new VertexDeclaration(VertexElements);

        public VertexDeclaration VertexDeclaration
        {
           get { return vertexDeclaration; }
        }
    }

Tags: , , ,
Posted in Blog, XNA | No Comments »

OpenGL Slides #2, Gooch Illumination and edge detection

Posted by Roy Triesscheijn on April 9th, 2011

As I’ve mentioned in a previous post I’ve been working a lot with OpenGL lately for a CG class. Every week we gave a presentation about some features and implementation details, to bad a lot of it is too much out of context if you haven’t followed the class. However I’ve found a few slides about cool-to-warm shading (a technique by Amy Gooch) and edge detection that are separate enough to post here, I hope it’s useful!

Tags: , , ,
Posted in Blog | No Comments »