• 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
MatsK

Screen to world coordinates

3 posts in this topic

Hi!
I'm rendering 3D on top of 2D, and it seems to be working, but I need to be able to render a specific mesh at, say - 10, 10 in screen coordinates.
How?

My current approach involves using Viewport.Unproject(), but it doesn't seem to be working;

[source lang="csharp"] Vector3 NearScreenPoint = new Vector3(0, 0, 0);
Vector3 FarScreenPoint = new Vector3(0, 0, 1);
Vector3 NearWorldPoint = m_Scene.SceneMgr.Device.Viewport.Unproject(NearScreenPoint,
m_Scene.SceneMgr.ProjectionMatrix, m_Scene.SceneMgr.ViewMatrix, m_Scene.SceneMgr.WorldMatrix);
Vector3 FarWorldPoint = m_Scene.SceneMgr.Device.Viewport.Unproject(FarScreenPoint,
m_Scene.SceneMgr.ProjectionMatrix, m_Scene.SceneMgr.ViewMatrix, m_Scene.SceneMgr.WorldMatrix);
Vector3 Direction = FarWorldPoint - NearWorldPoint;
Direction.Normalize();

if (m_CurrentHeadMeshes.Count > 0)
{
for (int i = 0; i < m_CurrentHeadMeshes[0].VertexTexNormalPositions.Length; i++)
{
/*Vector4 Position = new Vector4(m_CurrentHeadMeshes[0].VertexTexNormalPositions[i].Position, 1);
Matrix WorldMat = Matrix.CreateWorld(new Vector3(0, 0, 0), Vector3.Forward, new Vector3(0, 1, 0));
Vector4.Transform(ref Position, ref WorldMat, out Position);

Position /= Position.W;
m_CurrentHeadMeshes[0].VertexTexNormalPositions[i].Position.X = Position.X;
m_CurrentHeadMeshes[0].VertexTexNormalPositions[i].Position.Y = Position.Y;
m_CurrentHeadMeshes[0].VertexTexNormalPositions[i].Position.Z = Position.Z;*/

m_CurrentHeadMeshes[0].VertexTexNormalPositions[i].Position *= Direction;
}
}[/source]

I also want to rotate the mesh around it's X-axis, but I commented out the code for doing that since it complicated things. Anyway, here is my entire code:

[source lang="csharp"]
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using SimsLib.ThreeD;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using LogThis;

namespace TSOClient.ThreeD
{
/// <summary>
/// Represents a surface for rendering 3D elements (sims) on top of UI elements.
/// </summary>
public class UI3DView : ThreeDElement
{
private List<BasicEffect> m_Effects;

private float m_Rotation;

private List<Mesh> m_CurrentHeadMeshes;
private List<Texture2D> m_HeadTextures;

private int m_Width, m_Height;
private bool m_SingleRenderer = true;

private SpriteBatch m_SBatch;

private Camera2D Cam = new Camera2D();

/// <summary>
/// Constructs a new UI3DView instance.
/// </summary>
/// <param name="Width">The width of this UI3DView surface.</param>
/// <param name="Height">The height of this UI3DView surface.</param>
/// <param name="SingleRenderer">Will this surface be used to render a single, or multiple sims?</param>
/// <param name="Screen">The ThreeDScene instance with which to create this UI3DView instance.</param>
/// <param name="StrID">The string ID for this UI3DView instance.</param>
public UI3DView(int Width, int Height, bool SingleRenderer, ThreeDScene Screen, string StrID)
: base(Screen)
{
m_Effects = new List<BasicEffect>();
m_Width = Width;
m_Height = Height;
m_SingleRenderer = SingleRenderer;

m_CurrentHeadMeshes = new List<Mesh>();
m_HeadTextures = new List<Texture2D>();

m_SBatch = new SpriteBatch(m_Scene.SceneMgr.Device);
m_Scene.SceneMgr.Device.DeviceReset += new EventHandler(GraphicsDevice_DeviceReset);
}

/// <summary>
/// Occurs when the graphicsdevice was reset, meaning all 3D resources
/// have to be recreated.
/// </summary>
private void GraphicsDevice_DeviceReset(object sender, EventArgs e)
{
for (int i = 0; i < m_Effects.Count; i++)
m_Effects[i] = new BasicEffect(m_Scene.SceneMgr.Device, null);

m_Scene.SceneMgr.Device.VertexDeclaration = new VertexDeclaration(m_Scene.SceneMgr.Device,
VertexPositionNormalTexture.VertexElements);
m_Scene.SceneMgr.Device.RenderState.CullMode = CullMode.None;

// Create camera and projection matrix
m_Scene.SceneMgr.WorldMatrix = Matrix.Identity;
m_Scene.SceneMgr.ViewMatrix = Matrix.CreateLookAt(Vector3.Right * 5, Vector3.Zero, Vector3.Down);
m_Scene.SceneMgr.ProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.Pi / 4.0f,
(float)m_Scene.SceneMgr.Device.PresentationParameters.BackBufferWidth /
(float)m_Scene.SceneMgr.Device.PresentationParameters.BackBufferHeight, 1.0f, 100.0f);
}

/// <summary>
/// Loads a head mesh.
/// </summary>
/// <param name="MeshID">The ID of the mesh to load.</param>
/// <param name="TexID">The ID of the texture to load.</param>
public void LoadHeadMesh(Outfit Outf, int SkinColor)
{
Appearance Apr;

switch (SkinColor)
{
case 0:
Apr = new Appearance(ContentManager.GetResourceFromLongID(Outf.LightAppearanceID));
break;
case 1:
Apr = new Appearance(ContentManager.GetResourceFromLongID(Outf.MediumAppearanceID));
break;
case 2:
Apr = new Appearance(ContentManager.GetResourceFromLongID(Outf.DarkAppearanceID));
break;
default:
Apr = new Appearance(ContentManager.GetResourceFromLongID(Outf.LightAppearanceID));
break;
}

Binding Bnd = new Binding(ContentManager.GetResourceFromLongID(Apr.BindingIDs[0]));

if (m_CurrentHeadMeshes.Count > 0)
{
if (!m_SingleRenderer)
{
m_Effects.Add(new BasicEffect(m_Scene.SceneMgr.Device, null));
m_CurrentHeadMeshes.Add(new Mesh(ContentManager.GetResourceFromLongID(Bnd.MeshAssetID), false));
m_CurrentHeadMeshes[m_CurrentHeadMeshes.Count - 1].ProcessMesh();

m_HeadTextures.Add(Texture2D.FromFile(m_Scene.SceneMgr.Device,
new MemoryStream(ContentManager.GetResourceFromLongID(Bnd.TextureAssetID))));
}
else
{
m_Effects[0] = new BasicEffect(m_Scene.SceneMgr.Device, null);
m_CurrentHeadMeshes[0] = new Mesh(ContentManager.GetResourceFromLongID(Bnd.MeshAssetID), false);
m_CurrentHeadMeshes[m_CurrentHeadMeshes.Count - 1].ProcessMesh();

m_HeadTextures[0] = Texture2D.FromFile(m_Scene.SceneMgr.Device,
new MemoryStream(ContentManager.GetResourceFromLongID(Bnd.TextureAssetID)));

Vector3 NearScreenPoint = new Vector3(0, 0, 0);
Vector3 FarScreenPoint = new Vector3(0, 0, 1);
Vector3 NearWorldPoint = m_Scene.SceneMgr.Device.Viewport.Unproject(NearScreenPoint,
m_Scene.SceneMgr.ProjectionMatrix, m_Scene.SceneMgr.ViewMatrix, m_Scene.SceneMgr.WorldMatrix);
Vector3 FarWorldPoint = m_Scene.SceneMgr.Device.Viewport.Unproject(FarScreenPoint,
m_Scene.SceneMgr.ProjectionMatrix, m_Scene.SceneMgr.ViewMatrix, m_Scene.SceneMgr.WorldMatrix);
Vector3 Direction = FarWorldPoint - NearWorldPoint;
Direction.Normalize();

if (m_CurrentHeadMeshes.Count > 0)
{
for (int i = 0; i < m_CurrentHeadMeshes[0].VertexTexNormalPositions.Length; i++)
{
/*Vector4 Position = new Vector4(m_CurrentHeadMeshes[0].VertexTexNormalPositions[i].Position, 1);
Matrix WorldMat = Matrix.CreateWorld(new Vector3(0, 0, 0), Vector3.Forward, new Vector3(0, 1, 0));
Vector4.Transform(ref Position, ref WorldMat, out Position);

Position /= Position.W;
m_CurrentHeadMeshes[0].VertexTexNormalPositions[i].Position.X = Position.X;
m_CurrentHeadMeshes[0].VertexTexNormalPositions[i].Position.Y = Position.Y;
m_CurrentHeadMeshes[0].VertexTexNormalPositions[i].Position.Z = Position.Z;*/

m_CurrentHeadMeshes[0].VertexTexNormalPositions[i].Position *= Direction;
}
}
}
}
else
{
m_Effects.Add(new BasicEffect(m_Scene.SceneMgr.Device, null));
m_CurrentHeadMeshes.Add(new Mesh(ContentManager.GetResourceFromLongID(Bnd.MeshAssetID), false));
m_CurrentHeadMeshes[m_CurrentHeadMeshes.Count - 1].ProcessMesh();

m_HeadTextures.Add(Texture2D.FromFile(m_Scene.SceneMgr.Device,
new MemoryStream(ContentManager.GetResourceFromLongID(Bnd.TextureAssetID))));
}
}

public override void Update(GameTime GTime)
{
/*m_Rotation += 0.01f;
m_Scene.SceneMgr.WorldMatrix = Matrix.CreateRotationX(m_Rotation);*/

base.Update(GTime);
}

public override void Draw()
{
base.Draw();

for (int i = 0; i < m_Effects.Count; i++)
{
for (int j = 0; j < m_HeadTextures.Count; j++)
{
if (m_HeadTextures[j] != null)
{
m_Effects[i].World = m_Scene.SceneMgr.WorldMatrix;
m_Effects[i].View = m_Scene.SceneMgr.ViewMatrix;
m_Effects[i].Projection = m_Scene.SceneMgr.ProjectionMatrix;

m_Effects[i].Texture = m_HeadTextures[j];
m_Effects[i].TextureEnabled = true;

m_Effects[i].EnableDefaultLighting();

m_Effects[i].CommitChanges();

// Draw
m_Effects[i].Begin();

for (int k = 0; k < m_Effects[i].Techniques.Count; k++)
{
foreach (EffectPass Pass in m_Effects[i].Techniques[k].Passes)
{
Pass.Begin();

foreach (Mesh Msh in m_CurrentHeadMeshes)
{
foreach (Face Fce in Msh.Faces)
{
if (Msh.VertexTexNormalPositions != null)
{
VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3];
Vertex[0] = Msh.VertexTexNormalPositions[Fce.AVertexIndex];
Vertex[1] = Msh.VertexTexNormalPositions[Fce.BVertexIndex];
Vertex[2] = Msh.VertexTexNormalPositions[Fce.CVertexIndex];

Vertex[0].TextureCoordinate = Msh.VertexTexNormalPositions[Fce.AVertexIndex].TextureCoordinate;
Vertex[1].TextureCoordinate = Msh.VertexTexNormalPositions[Fce.BVertexIndex].TextureCoordinate;
Vertex[2].TextureCoordinate = Msh.VertexTexNormalPositions[Fce.CVertexIndex].TextureCoordinate;

m_Scene.SceneMgr.Device.DrawUserPrimitives<VertexPositionNormalTexture>(
PrimitiveType.TriangleList, Vertex, 0, 1);
}
}
}

Pass.End();
m_Effects[i].End();
}
}
}
}
}
}
}[/source]
Also, here's my View, World and Projection:

[source lang="csharp"] m_WorldMatrix = Matrix.Identity;
m_ViewMatrix = Matrix.CreateLookAt(Vector3.Backward * 5, Vector3.Zero, Vector3.Right);
m_ProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.Pi / 4.0f,
(float)Device.PresentationParameters.BackBufferWidth /
(float)Device.PresentationParameters.BackBufferHeight,
1.0f, 100.0f);[/source]

I've been Googling around for answers to this issue for some time now, but everything seems to revolve around picking, which isn't helping me.
0

Share this post


Link to post
Share on other sites
If I understood correctly you want to draw 3d elements on the graphics user interface of your game.
You are right, you can use Unproject() but the parameters you feed are incorrect.

Near and far points must contain:
[code]
Vector3 NearScreenPoint = new Vector3(cx, cy, 0);
Vector3 FarScreenPoint = new Vector3(cx, cy, 1);
[/code]
where[b] cx and cy are the position in pixels [/b]referred to the[b] current viewport [/b](so take care of what is the current active viewport).

Now you can calculate Direction using:
[code]
Direction = Vector3.Lerp(NearScreenPoint, FarScreenPoint, dist);
[/code]
where [b]dist is a number in range [0..1][/b] to choice the distance of your 3D object from the camera. If you use 0 or 1 [b]you can't see the object[/b], it's clipped away.

Now, to render the object I think is better to use a translation matrix or, more simpler, to send the Direction vector to a shader that do the per-vertex transform on the GPU[b] adding Direction[/b] to the mesh vertex position. If you do this on CPU you waste time.

If i'm not clear please post. Edited by Koder4Fun
0

Share this post


Link to post
Share on other sites
Thanks for your answer!
Yes, I found out it was easier to just apply a translation matrix to the world matrix, as such:

[source lang="csharp"] m_Effects[i].World = m_Scene.SceneMgr.WorldMatrix *
Matrix.CreateTranslation(new Vector3(m_CurrentSims[j].HeadXPos, m_CurrentSims[j].HeadYPos, 0.0f));[/source]
As is evident from that snippet, I changed the class to function more as a renderingcontext, which was more in line with what I had originally intended. I also realized pretty quickly that I needed to scale, and I had to do that using the viewmatrix. Somehow, that affected the coordinatesystem, so I had to update my coordinates for where I wanted to render the mesh as I moved the viewmatrix further away. I'm still not 100% sure how to handle scaling because of this very issue. For now, I've just hardcoded it:
[source lang="csharp"]m_Effects[i].View = Matrix.CreateLookAt(Vector3.Backward * 17, Vector3.Zero, Vector3.Right);[/source]
0

Share this post


Link to post
Share on other sites
You can [b]chain [/b]all needed matrix transforms, you only need to be care with the order of multiplication:

[code]
ComboMatrix = TranslationMatrix * ScaleMatrix * RotationMatrix;
[/code]

To keep in mind the correct order [b]read the transformations in a right to left direction[/b], and you can see how the vertices of a mesh are transformed from the stored local-space coordinates to world-space coordinates.

This way you can calculate the matrix one time and apply it to all objects you want.
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