• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Gage64

[SlimDX] Mesh utility functions (source included)

2 posts in this topic

I'm playing around with SlimDX to learn more about shaders, and in the process I wrote a few mesh utility functions. Currently I have functions to: * Compute a bounding sphere/box * Compute texture coordinates Here's the code:
public static BoundingSphere ComputeBoundingSphere(Mesh mesh)
{
    List<Vector3> verts = new List<Vector3>(mesh.VertexCount);
    DataStream ds = mesh.LockVertexBuffer(LockFlags.ReadOnly);

    while (ds.Position < ds.Length)
    {
        long oldPos = ds.Position;

        Vector3 pos = ds.Read<Vector3>();
        verts.Add(pos);

        ds.Position = oldPos + mesh.BytesPerVertex;
    }

    mesh.UnlockVertexBuffer();

    return BoundingSphere.FromPoints(verts.ToArray());
}

public static BoundingBox ComputeBoundingBox(Mesh mesh)
{
    List<Vector3> verts = new List<Vector3>(mesh.VertexCount);
    DataStream ds = mesh.LockVertexBuffer(LockFlags.ReadOnly);

    while (ds.Position < ds.Length)
    {
        long oldPos = ds.Position;

        Vector3 pos = ds.Read<Vector3>();
        verts.Add(pos);

        ds.Position = oldPos + mesh.BytesPerVertex;
    }

    mesh.UnlockVertexBuffer();

    return BoundingBox.FromPoints(verts.ToArray());
}

public static int FindElementIndex(VertexElement[] elems, DeclarationUsage usage)
{
    for (int i = 0; i < elems.Length; ++i)
    {
        if (elems[i].Usage == usage)
            return i;
    }

    return -1;
}

// This code uses the methods described in:
// www.mvps.org/directx/articles/spheremap.htm
public static void ComputeTexCoords(Device device, ref Mesh mesh, bool useNormals)
{
    if (useNormals)
    {
        if ((mesh.VertexFormat & VertexFormat.Normal) == 0)
        {
            mesh.ComputeNormals();
        }
    }

    // Make room for texture coordinates
    // The 'newMesh' variable is not needed anymore. The extra {} ensure that it is not used accidentally
    {
        Mesh newMesh = mesh.Clone(device, mesh.CreationOptions, mesh.VertexFormat | VertexFormat.Texture1);
        mesh.Dispose();
        mesh = newMesh;
    }

    VertexElement[] elems = mesh.GetDeclaration();
    int posElem       = FindElementIndex(elems, DeclarationUsage.Position);
    int normalElem    = FindElementIndex(elems, DeclarationUsage.Normal);
    int texCoordsElem = FindElementIndex(elems, DeclarationUsage.TextureCoordinate);

    // Needed for positional spherical mapping
    BoundingBox bbox = ComputeBoundingBox(mesh);

    DataStream ds = mesh.LockVertexBuffer(LockFlags.None);

    while (ds.Position < ds.Length)
    {
        long oldPos = ds.Position;

        Vector3 vec;
        if (useNormals)     // Spherical mapping with normals
        {
            ds.Position += elems[normalElem].Offset;
            vec = ds.Read<Vector3>();
            ds.Position = oldPos;
        }
        else                // Spherical mapping with positions
        {
            ds.Position += elems[posElem].Offset;
            Vector3 pos = ds.Read<Vector3>();
            ds.Position = oldPos;

            Vector3 center = (bbox.Minimum + bbox.Maximum) * 0.5f;
            vec = Vector3.Normalize(pos - center);
        }

        float u = (float)Math.Asin(vec.X) / (float)Math.PI + 0.5f;
        float v = (float)Math.Asin(vec.Y) / (float)Math.PI + 0.5f;

        ds.Position += elems[texCoordsElem].Offset;
        ds.Write<float>(u);
        ds.Write<float>(v);

        ds.Position = oldPos + mesh.BytesPerVertex;
    }

    mesh.UnlockVertexBuffer();
}

The functions seem to work, but I have not tested them thoroughly, so I can't say that with full certainty. If you see any errors, please let me know. I'm also not too happy with the implementation, mostly because there's a lot of duplicate code. If you know of a better way to do this sort of thing, I would love to hear about it. I hope this will be useful to someone.
0

Share this post


Link to post
Share on other sites
You can cut down on a lot of that code by using a little LINQ and a few helper methods that exist in SlimDX already. This is how I'd write the function. It should be the same thing, although I wrote it on the fly so it might have a few typos:


public static Mesh ComputeTextureCoords(Device device, Mesh mesh, bool useNormals)
{
if (useNormals && (mesh.VertexFormat & VertexFormat.Normal) == 0)
mesh.ComputeNormals();

mesh = mesh.Clone(device, mesh.CreationOptions, mesh.VertexFormat | VertexFormat.Texture1);

var elements = mesh.GetDeclaration();
var dataStream = mesh.LockVertexBuffer(LockFlags.None);
var box = BoundingBox.FromPoints(D3DX.GetVectors(dataStream, mesh.VertexCount, mesh.BytesPerVertex));
var center = (box.Minimum + box.Maximum) * 0.5f;

dataStream.Position = elements.FirstOrDefault(e => useNormals ? e.Usage == DeclarationUsage.Normal : e.Usage == DeclarationUsage.Position).Offset;
var vectors = D3DX.GetVectors(dataStream, mesh.VertexCount, mesh.BytesPerVertex).Select(v => useNormals ? v : Vector3.Normalize(v - center));
dataStream.Position = elements.FirstOrDefault(e => e.Usage == DeclarationUsage.TextureCoordinate).Offset;

foreach (var vector in vectors)
{
dataStream.Write((float)(Math.Asin(vector.X) / Math.PI + 0.5));
dataStream.Write((float)(Math.Asin(vector.Y) / Math.PI + 0.5));
dataStream.Position += mesh.BytesPerVertex - (sizeof(float) * 2);
}

mesh.UnlockVertexBuffer();
return mesh;
}

0

Share this post


Link to post
Share on other sites
Thanks. I'm still not familiar with the C# 3.0 features but that does look pretty nice.

Also, I somehow managed to miss the D3DX class...
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0