Getting ObjImporter to parse quads

The App Hub’s Custom Model Importer sample loads 3D models of the ubiquitous .obj format, and is a straightforward way to get started with the XNA Content Processor. Not surprisingly, this sample just deals with handling the basics- it parses groups, converts triangles to vertices and loads diffuse textures, and not much else. It is not prepared to handle quad polygons, so I came up with a solution for it.

3D modeling with quads is very common and helpful for an artist, since they are better than triangles for reading the topology of the model, but they are not too friendly for real-time game rendering. Graphics hardware prefers triangles, and any quads from models imported into programs need to be handled appropriately. Either they may get totally ignored or crash your program when something goes wrong in your file importer. Using simpler file formats makes it a whole lot easier to understand how to solve such problems, and use the XNA content pipeline for your own needs.

The ObjImporter class of the custom model importer can be updated to handle quads in a certain winding order. I have modified it so that it can either read triangles or quads with vertices winding clockwise. To load models with quads, simply open ObjImporter.cs and look for the “f” case found in the ParseObjLine method (found around line 200) and replace it with the following code I wrote here:

// Faces (triangles and quads are supported)
case "f":

    // For triangles
    int[] polyIndices = {
        0, 1, 2
    };

    // Change the indices if a quad is needed
    if (lineTokens.Length > 4)
    {
        Array.Resize(ref polyIndices, 6);
        polyIndices[2] = 3;
        polyIndices[3] = 1;
        polyIndices[4] = 2;
        polyIndices[5] = 3;
    }

    // If the builder is null, this face is outside of a group
    // Start a new, unnamed group
    if (meshBuilder == null)
        StartMesh(null);

    // For each triangle vertex
    for (int vertexIndex = 0; vertexIndex < polyIndices.Length; vertexIndex++)
    {
        // Each vertex is a set of three indices:
        // position, texture coordinate, and normal
        // The indices are 1-based, separated by slashes
        // and only position is required.
        string[] indices = lineTokens[polyIndices[vertexIndex] + 1].Split('/');

        // Required: Position
        int positionIndex = int.Parse(indices[0],
            CultureInfo.InvariantCulture) - 1;

        if (indices.Length > 1)
        {
            // Optional: Texture coordinate
            int texCoordIndex;
            Vector2 texCoord;
            if (int.TryParse(indices[1], out texCoordIndex))
                texCoord = texCoords[texCoordIndex - 1];
            else
            texCoord = Vector2.Zero;

            // Set channel data for texture coordinate for the following
            // vertex. This must be done before calling AddTriangleVertex
            meshBuilder.SetVertexChannelData(textureCoordinateDataIndex,
                texCoord);
        }

        if (indices.Length > 2)
        {
            // Optional: Normal
            int normalIndex;
            Vector3 normal;
            if (int.TryParse(indices[2], out normalIndex))
                normal = normals[normalIndex - 1];
            else
                normal = Vector3.Zero;

            // Set channel data for normal for the following vertex.
            // This must be done before calling AddTriangleVertex
            meshBuilder.SetVertexChannelData(normalDataIndex, normal);
        }

        // Add the vertex with the vertex data that was just set
        meshBuilder.AddTriangleVertex(positionMap[positionIndex]);
    }
    break;

The notable differences here is the setup of polygon indices for both triangle and quad cases, and the vertexIndex loop parses index data from the order given directly by the index array and not straight as it is read from the line. I suppose there should still be a warning and a break to skip the addition of vertices if a n-gon has more than 4 sides, but these are rare.

Hope this helps people wanting to import mixed-polygon models into their programs!

Advertisements

Some XNA graphics engines to look out for

As I’ve been moving forward with my rendering framework, I have been researching and trying out some XNA rendering engines to draw inspiration from. Not all of them are free or even available to the public, but they have helped me along the way somehow. Here are the engines that have gotten my attention the most, how they influenced me, and some other comments about them.

  • SunBurn – For XNA, this one’s the big money. Literally, because you have to pay a decent sum even just for the indie license. I can’t bother to spend that much on an engine, but their demos are impressive. One thing that sets this apart from other engines is that 3D lighting effects can also be applied to 2D graphics. SunBurn is talked about as the best choice to go for bringing AAA-level graphics to your games, but its pricing structure makes it less accessible than other engines on this list.
  • Ploobs Game Engine – Unlike SunBurn, it handles a bit more than just graphics (plus it’s free), but I’m listing it anyways because its graphical features are still extensive. The documentation is more detailed than most free offerings, and has a UML diagram on how the renderer is structured, so that’s pretty nice too 🙂
  • Nelxon – Not really sure if this will also be the name of the engine but it’s his blog and recent work has centered around adding some nice graphical features to it. I used his resources for reference in my own work. Doesn’t seem to hint at offering the source code for his work, but I do hope he updates soon.
  • Final Engine – Another purely graphics-only engine, it has a host of great features comparable to Ploobs. Especially to note are its ability to render many nice materials, and MLAA (morphological anti-aliasing), something that I must have for a deferred renderer. Runs pretty well, and easy to set up and use. Additionally, it provides integration for NeoForce Controls, a separate GUI system for your games.
  • Hilva – This is the only other paid graphics engine other than SunBurn, but it’s free to use for distribution on PC. That said, it’s still closed source. I’m not as familiar with this engine as well as the others, but it does provide a lot. One feature I found interesting is that it replaces the model processing pipeline for XNA to facilitate the use of animated and multi-textured models.
  • Tomato – This one’s not as mature as the rest, but it has some good ideas. I tried this one on my PC and performance was slow. I still have a very good video card so I’m less hopeful for the Xbox 360. The built-in configurator is nice, though. I keep this one around because its rendering scheme is similar to what I plan to implement, and improve on it. The creator also recently started a new blog for it, so it’s still in production.

November update:  Nelxon, after a long hiatus, redesigned his site and wiped all the old content from his blog, except for his most visited resources. But he says that he’s still planning to finish his projects. The Tomato Engine blog has mysteriously disappeared, leaving only the CodePlex project site for information and downloads. This site hasn’t been updated since April.

XNA 4.0 parallax occlusion mapping

The XNACommunity Codeplex site, run by a group of hobbyist Spanish game developers, has a huge collection of programs and code examples that you can use freely for your own projects. However, most of them have not been updated for XNA 4.0. I was mostly interested in the Parallax Occulsion Mapping sample, and decided to see if I could update the code.

Parallax Mapping is a more complex way to make textures pop out, and it differs from normal and bump mapping that it actually projects the texture’s details in three dimensions, as opposed to just changing the lighting from the normals.

The original sample included a particle generator, which added a bit of flair to the scene. I could not get this working because the PointSprite object has been deprecated in XNA 4.0 and there’s no easy equivalent for it. The best I could to is make the generator produce black lines :-/ Its particle system was a bit complex to just simply change from point sprites to billboarded quads, so I just decided to omit this altogether since it’s not relevant to the real purpose of the sample.

Aside from trying to get the particles working, porting the program was a breeze. Just a few tweaks were needed in the effect files, and removing unneeded rendering functions and replacing others. Pressing the space bar lets you switch between no mapping, normal mapping, and parallax mapping. Use WASD/arrow keys to move around.

You can download the updated sample here, or check out the source at GitHub. It is ready to work with your XNA 4.0 projects. Please drop a line if you found it helpful!

Engine features and lighting comparison

Although the rendering engine is far from complete, I will briefly describe the features that my rendering engine currently has. Here’s a general list of them:

  • Supports both deferred rendering and Light Pre-Pass rendering (deferred lighting)
  • Post-process effects such as blur, depth of field and shadows (in progress)
  • Discrete components for render passes and post-process effects
  • Maintains relatively fast performance even with many point lights
  • FXAA (Fast Approximate Anti-Aliasing) to remove those unsightly jaggies
  • Lightweight and unobstrusive code

Continue reading

Past and present of the rendering engine

As I mentioned before, I have been working on a rendering engine for XNA called the Meteor Rendering Engine. I’ve only been working on it for a little over a month but already it’s come a long way. Even though it started out as simply a tutorial project from Catalin Zima-Zegreanu, I made enough modifications to it to call it my own.

Continue reading

New blog, and my programming projects

Hello, this is my first post on this blog, but not the first blog I have done. I’m a web developer by trade but program in C++ and C# in my spare time, usually on video games, which will be the focus of my blog.

As far as my background goes, I have been programming as a hobby for over 4 years, on and off, but now I have gotten more into it than ever before. I started just with C++ console programming in 2006, moved quickly into SDL, which was a bit of a show-stopper since I haven’t fully understood pointers and OOP. After taking a few steps back, I went back into programming in 2008 and haven’t looked back. If you want to be bored with more details take a look at the About page which will soon be updated.

The topics covered here will be mostly XNA and general game programming. I will be covering XNA a lot, as I have taken a big liking to it recently since picking it up a few months ago. Although I’m relatively fresh to XNA I’m not totally new to DirectX and 3D graphics programming, so I was movin’ matrices and setting vertex buffers in no time. Currently I have two personal projects on my hands- a rendering engine and a marble game (which has been put on hold a few times). Follow my next post where I will go into detail about it…