Texture splatting vs height based texturing

Started by
1 comment, last by football94 10 years, 9 months ago

Hi guys

Ive been using a heightmap with height based multitexturing as a learning base for several projects

what I would like to do now is use that terrain to experiment with texture coordinate collision for example

to have a car model react(ex. if on dirt texture emit dust partcles, grass texture grass particles etc...) to certain textures as it moves across the terrain Ive tried different approaches(code below) but havent been able to implement it. what I would like to know is there a way to get the texture coordinates of height based textured terrain or is texutre splatting the best approach to go with.

Thankyou

this is the first method Ive been experimenting with

Triangle intersection by moeller and trumbore

public bool fine()
{

Ray ray = CalculateRay(mouseLocation, camera.viewMatrix, camera.projectionMatrix, viewport);





for (int y = 0; y < terrain.Tlength - 1; y++)
{
for (int x = 0; x < terrain.Twidth - 1; x++)
{


RayTriangleIntersect(nearPoint, direction, terrain.TerrainVertices[x + ((y + 1) * terrain.terrainWidth)].Normal, terrain.TerrainVertices[(x + 1) + (y * terrain.terrainWidth)].Normal, terrain.TerrainVertices[(x + 1) + (y * terrain.terrainWidth)].Normal, out distance, out u, out v);

if (u == v)
{
fine2(out pointa, out pointb, out pointc);
return true;
}
else
{
fine3(out pointa, out pointb, out pointc);
}











}
}
return false;
}

these are the second a third methods which returns highlighted(one red, one blue) collision triangles:

public void fine2(out Vector3 pointa, out Vector3 pointb, out Vector3 pointc)
{
// Store vertex positions so we can display the picked triangle.

Ray ray = CalculateRay(mouseLocation, camera.viewMatrix, camera.projectionMatrix, viewport);


int X, Z;

X = (int)Math.Floor(nearPoint.X);
Z = (int)Math.Floor(nearPoint.Z);

X = (int)Math.Ceiling(nearPoint.X);
Z = (int)Math.Ceiling(nearPoint.Z);

pointa = new Vector3(X, terrain.heightData[X, -Z], Z); // First Point of the Triangle
X = (int)Math.Floor(nearPoint.X);
Z = (int)Math.Ceiling(nearPoint.Z);
pointb = new Vector3(X, terrain.heightData[X, -Z], Z); // Second
X = (int)Math.Ceiling(nearPoint.X);
Z = (int)Math.Floor(nearPoint.Z);
pointc = new Vector3(X, terrain.heightData[X, -Z], Z); // And third



pickedTriangle[0].Position = pointa;
pickedTriangle[0].Color = Color.Blue;
pickedTriangle[1].Position = pointb;
pickedTriangle[1].Color = Color.Blue;
pickedTriangle[2].Position = pointc;
pickedTriangle[2].Color = Color.Blue;












return;
}

public void fine3(out Vector3 pointa, out Vector3 pointb, out Vector3 pointc)
{
// Store vertex positions so we can display the picked triangle.

Ray ray = CalculateRay(mouseLocation, camera.viewMatrix, camera.projectionMatrix, viewport);


int X, Z;

X = (int)Math.Floor(nearPoint.X);
Z = (int)Math.Floor(nearPoint.Z);

X = (int)Math.Ceiling(nearPoint.X);
Z = (int)Math.Ceiling(nearPoint.Z);

pointa = new Vector3(X, terrain.heightData[X, -Z], Z); // First Point of the Triangle
X = (int)Math.Floor(nearPoint.X);
Z = (int)Math.Ceiling(nearPoint.Z);
pointb = new Vector3(X, terrain.heightData[X, -Z], Z); // Second
X = (int)Math.Ceiling(nearPoint.X);
Z = (int)Math.Floor(nearPoint.Z);
pointc = new Vector3(X, terrain.heightData[X, -Z], Z); // And third



pickedTriangle[0].Position = pointa;
pickedTriangle[0].Color = Color.Red;
pickedTriangle[1].Position = pointb;
pickedTriangle[1].Color = Color.Red;
pickedTriangle[2].Position = pointc;
pickedTriangle[2].Color = Color.Red;












return;
}

and lastly the terrain code:

using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace TRIANGLE
{
public class Terrain
{
/*
* Struct to hold vertex information with pos,normal,texcoord and texweight
*/
public struct VertexMultitextured
{
public Vector3 Position;
public Vector3 Normal;
public Vector4 TextureCoordinate;
public Vector4 TexWeights;

public static int SizeInBytes = (3 + 3 + 4 + 4) * sizeof(float); // vec3 + vec3 + vec4 +vec4
public static VertexElement[] VertexElements = new VertexElement[]
{
// stream, offset, type, method, usage and usage index
new VertexElement( 0, 0, VertexElementFormat.Vector3, VertexElementMethod.Default, VertexElementUsage.Position, 0 ),
new VertexElement( 0, sizeof(float) * 3, VertexElementFormat.Vector3, VertexElementMethod.Default, VertexElementUsage.Normal, 0 ),
new VertexElement( 0, sizeof(float) * 6, VertexElementFormat.Vector4, VertexElementMethod.Default, VertexElementUsage.TextureCoordinate, 0 ),
new VertexElement( 0, sizeof(float) * 10, VertexElementFormat.Vector4, VertexElementMethod.Default, VertexElementUsage.TextureCoordinate, 1 ),
};
}

Game1 GameClass;
GraphicsDevice device;

public int terrainWidth;
public int terrainLength;
public float[,] heightData;
Vector3 diffuseColor;
VertexBuffer terrainVertexBuffer;
IndexBuffer terrainIndexBuffer;
VertexDeclaration terrainVertexDeclaration;
VertexMultitextured[] terrainVertices;
int[] terrainIndices;

public Texture2D grassTexture;
public Texture2D sandTexture;
public Texture2D rockTexture;
public Texture2D snowTexture;


public float grassv;
public float grassu;
public float sandv;
public float sandu;



public VertexMultitextured[] TerrainVertices
{
get
{
return terrainVertices;
}

}
public int Twidth
{
get
{
return terrainWidth;
}

}
public int Tlength
{
get
{
return terrainLength;
}

}
public float GRASSW
{
get
{
return (float)grassTexture.Width;
}

}
public float GRASSH
{
get
{
return (float)grassTexture.Height;
}

}
public Terrain(Game1 reference,GraphicsDevice device)
{
this.GameClass = reference;
this.device = device;

LoadVertices();
LoadTextures();
}

private void LoadTextures()
{
grassTexture = GameClass.Content.Load<Texture2D>("grass");
sandTexture = GameClass.Content.Load<Texture2D>("sand");
rockTexture = GameClass.Content.Load<Texture2D>("rock");
snowTexture = GameClass.Content.Load<Texture2D>("snow");



}

public void LoadVertices()
{

Texture2D heightMap = GameClass.Content.Load<Texture2D>("heightmap");
LoadHeightData(heightMap);

VertexMultitextured[] terrainVertices = SetUpTerrainVertices();
int[] terrainIndices = SetUpTerrainIndices();
terrainVertices = CalculateNormals(terrainVertices, terrainIndices);
CopyToTerrainBuffers(terrainVertices, terrainIndices);
terrainVertexDeclaration = new VertexDeclaration(device, VertexMultitextured.VertexElements);



}



public int[] TerrainIndices
{
get
{
return terrainIndices;
}

}



public void LoadHeightData(Texture2D heightMap)
{
float minimumHeight = float.MaxValue;
float maximumHeight = float.MinValue;

terrainWidth = heightMap.Width;
terrainLength = heightMap.Height;

// get rgb values for each pixel of hightmap
Color[] heightMapColors = new Color[terrainWidth * terrainLength];
heightMap.GetData(heightMapColors);

heightData = new float[terrainWidth, terrainLength];
for (int x = 0; x < terrainWidth; x++)
for (int y = 0; y < terrainLength; y++)
{
heightData[x, y] = heightMapColors[x + (y * terrainWidth)].R; // read r value
// determine minimum and maximum height value in terrain
if (heightData[x, y] < minimumHeight) minimumHeight = heightData[x, y];
if (heightData[x, y] > maximumHeight) maximumHeight = heightData[x, y];
}

// get height values in a range between 0 and 30
for (int x = 0; x < terrainWidth; x++)
for (int y = 0; y < terrainLength; y++)
heightData[x, y] = (heightData[x, y] - minimumHeight) / (maximumHeight - minimumHeight) * 30.0f;

}

/*
* Define Vertices
*/
private VertexMultitextured[] SetUpTerrainVertices()
{
terrainVertices = new VertexMultitextured[terrainWidth * terrainLength];

for (int x = 0; x < terrainWidth; x++)
{
for (int y = 0; y < terrainLength; y++)
{
// generate a vertex for each pixel of the heightmap
// a terrain is generated in x,-y direction
terrainVertices[x + (y * terrainWidth)].Position = new Vector3(x, heightData[x, y], -y);
terrainVertices[x + (y * terrainWidth)].TextureCoordinate.X = (float)x / 30.0f; // /30 to stretch texture so it looks realistic
terrainVertices[x + (y * terrainWidth)].TextureCoordinate.Y = (float)y / 30.0f;

/*
* A vertex with height 12 should have texweight 1.
* The weight should become 0 for heights 6 and 18, which are 12-6 and 12+6. In other words: all heights that
* are within 6 meters from 12 meter high should have a weight factor for the grass texture. This explains the
* ‘abs(height-12)/6’: it will be 0 for height = 12, and become 1 as height approaches 6 or 18. But we need
* the opposite: at height 12 we need weight=1, and at heights 6 and 12 we need weight 0. So we subtract our
* line above from 1 and get ‘1- abs(height-12)/6’. This will become smaller than 0 for height lower than 6
* and larger than 18, so we clamp this value between 0 and 1.
* Although this is a step in the good direction, it isn’t perfect yet. For example: as their snow and
* rock weights are 0.2, the pixels corresponding to height 25 will get 20% of their color from the snow
* texture, and 20% from the rock texture. The remaining 60% will remain black, so they will look very dark.
* To solve this, we must make sure that for every vertex, the sum of all weights is exactly 1.
* To do this, for each vertex we’ll make the sum of all weights, and divide all weights by this sum. In case
* of the previous example, the sum would be 0.2 + 0.2 = 0.4. Next, 0.2 divided by 0.4 gives 0.5 for both the
* new snow and rock weights. And of course, 0.5 + 0.5 equals 1. This is what is shown in the right part
* of the image above. You’ll notice that for each height, the summed weight value is 1.
*/

// X = Sand, Y = Grass, Z = Stone and W = Snow
terrainVertices[x + (y * terrainWidth)].TexWeights.X = MathHelper.Clamp(1.0f - Math.Abs(heightData[x, y] - 0) / 8.0f, 0, 1);
terrainVertices[x + (y * terrainWidth)].TexWeights.Y = MathHelper.Clamp(1.0f - Math.Abs(heightData[x, y] - 12) / 6.0f, 0, 1);
terrainVertices[x + (y * terrainWidth)].TexWeights.Z = MathHelper.Clamp(1.0f - Math.Abs(heightData[x, y] - 20) / 6.0f, 0, 1);
terrainVertices[x + (y * terrainWidth)].TexWeights.W = MathHelper.Clamp(1.0f - Math.Abs(heightData[x, y] - 30) / 6.0f, 0, 1);

float total = terrainVertices[x + y * terrainWidth].TexWeights.X;
total += terrainVertices[x + y * terrainWidth].TexWeights.Y;
total += terrainVertices[x + y * terrainWidth].TexWeights.Z;
total += terrainVertices[x + y * terrainWidth].TexWeights.W;

terrainVertices[x + y * terrainWidth].TexWeights.X /= total;
terrainVertices[x + y * terrainWidth].TexWeights.Y /= total;
terrainVertices[x + y * terrainWidth].TexWeights.Z /= total;
terrainVertices[x + y * terrainWidth].TexWeights.W /= total;
}
}

return terrainVertices;
}

/*
* Set indices clockwise to build faces
*/
private int[] SetUpTerrainIndices()
{
/*
* new int[(terrainWidth - 1) * (terrainLength - 1) * 6]
* Example, plane consisting of 4x3 points: first row is build out of 3 quads, second one also.
* row col 3 points are needed for each triangle, 6 for one quad
* so for a 4x3 points plane one can say (4-1)*(3-1) * 6
*/
int[] indices = new int[(terrainWidth - 1) * (terrainLength - 1) * 6];
int counter = 0;
for (int y = 0; y < terrainLength - 1; y++)
{
for (int x = 0; x < terrainWidth - 1; x++)
{
int lowerLeft = x + y * terrainWidth;
int lowerRight = (x + 1) + y * terrainWidth;
int topLeft = x + (y + 1) * terrainWidth;
int topRight = (x + 1) + (y + 1) * terrainWidth;

// order clockwise
indices[counter++] = topLeft;
indices[counter++] = lowerRight;
indices[counter++] = lowerLeft;

indices[counter++] = topLeft;
indices[counter++] = topRight;
indices[counter++] = lowerRight;
}
}

return indices;
}

/*
* Calculate Normals on Terrain for realistic shadows
*/
private VertexMultitextured[] CalculateNormals(VertexMultitextured[] vertices, int[] indices)
{
// initialise normals with 0 0 0
for (int i = 0; i < vertices.Length; i++)
vertices.Normal = new Vector3(0, 0, 0);

for (int i = 0; i < indices.Length / 3; i++)
{
// Calculate Triangle
int index1 = indices[i * 3];
int index2 = indices[i * 3 + 1];
int index3 = indices[i * 3 + 2];

// Calculate normal on triangle
Vector3 side1 = vertices[index1].Position - vertices[index3].Position;
Vector3 side2 = vertices[index1].Position - vertices[index2].Position;
Vector3 normal = Vector3.Cross(side1, side2);

// apply normal on all three vertices of triangle
vertices[index1].Normal += normal;
vertices[index2].Normal += normal;
vertices[index3].Normal += normal;
}

// normalize all normals
for (int i = 0; i < vertices.Length; i++)
vertices.Normal.Normalize();

return vertices;
}

/*
* Copy vertices and indices onto grafikcard buffer to save performance (so this data has to be transferred ONLY ONCE)
*/
private void CopyToTerrainBuffers(VertexMultitextured[] vertices, int[] indices)
{
terrainVertexBuffer = new VertexBuffer(device, vertices.Length * VertexMultitextured.SizeInBytes, BufferUsage.WriteOnly);
terrainVertexBuffer.SetData(vertices);

terrainIndexBuffer = new IndexBuffer(device, typeof(int), indices.Length, BufferUsage.WriteOnly);
terrainIndexBuffer.SetData(indices);
}

/*
* This draws the terrain
*/
public void DrawTerrain(Effect effect)
{
effect.CurrentTechnique = effect.Techniques["MultiTextured"];
effect.Parameters["xTexture0"].SetValue(sandTexture);
effect.Parameters["xTexture1"].SetValue(grassTexture);
effect.Parameters["xTexture2"].SetValue(rockTexture);
effect.Parameters["xTexture3"].SetValue(snowTexture);



Matrix worldMatrix = Matrix.Identity;
effect.Parameters["xWorld"].SetValue(worldMatrix);
effect.Parameters["xEnableLighting"].SetValue(true);
effect.Parameters["xAmbient"].SetValue(0.4f);
effect.Parameters["xLightDirection"].SetValue(new Vector3(-0.5f, -1, -0.5f));

effect.Begin();
foreach (EffectPass pass in effect.CurrentTechnique.Passes)
{
pass.Begin();

device.Vertices[0].SetSource(terrainVertexBuffer, 0, VertexMultitextured.SizeInBytes); // tell it that this data is in graka buffer
device.Indices = terrainIndexBuffer;
device.VertexDeclaration = terrainVertexDeclaration;

int noVertices = terrainVertexBuffer.SizeInBytes / VertexMultitextured.SizeInBytes;
int noTriangles = terrainIndexBuffer.SizeInBytes / sizeof(int) / 3;
device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, noVertices, 0, noTriangles);

pass.End();
}
effect.End();
}
public float GetHeight(float x, float z)
{
int xmin = (int)Math.Floor(x);
int xmax = xmin + 1;
int zmin = (int)Math.Floor(z);
int zmax = zmin + 1;

if (
(xmin < 0) || (zmin < 0) ||
(xmax > heightData.GetUpperBound(0)) ||
(zmax > heightData.GetUpperBound(1)))
{
return 0;
}

Vector3 p1 = new Vector3(xmin, heightData[xmin, zmax], zmax);
Vector3 p2 = new Vector3(xmax, heightData[xmax, zmin], zmin);
Vector3 p3;

if ((x - xmin) + (z - zmin) <= 1)
{
p3 = new Vector3(xmin, heightData[xmin, zmin], zmin);
}
else
{
p3 = new Vector3(xmax, heightData[xmax, zmax], zmax);
}

Plane plane = new Plane(p1, p2, p3);

Ray ray = new Ray(new Vector3(x, 0, z), Vector3.Up);

float? height = ray.Intersects(plane);

return height.HasValue ? height.Value : 0f;
}

}
}

Advertisement

I'm not quite following your OP but here's a stab in the dark at some of the questions I think you might be asking:

1) Texture splatting and height based texturing are not mutually exclusive. A common technique is to use the height and slope to determine splat weightings for your terrain materials.

2) If you need to get the texture coordinates of a given point on the height map you can transform your world space position into your terrain's object space and from here deduce the uv coordinates at that point. If you need more info on this, ask away.

Hello GeneralQuery

The info you gave me was huge it pointed me in the right direction and showed me what to look for

Ive been researching transforming a ray into object space and took a look at an xna triangle picking sample

to find out how it was done. I tried modify the code to work with the heightmap terrain(2D texture) but it was really slow and the triangle highlight collision indicator never appeared I think my problem is that I wasnt able to further modify the

picking sample to work with the terrain and this is where I am stuck at right now. I provided the piece of code(below) that I think needs to be modified to fit the terrain but I havent come across a sample done with xna that does it

float? RayIntersectsModel(Ray ray, Matrix modelTransform,
out Vector3 vertex1, out Vector3 vertex2,
out Vector3 vertex3)
{

vertex1 = vertex2 = vertex3 = Vector3.Zero;

Matrix inverseTransform = Matrix.Invert(modelTransform);

ray.Position = Vector3.Transform(ray.Position, inverseTransform);
ray.Direction = Vector3.TransformNormal(ray.Direction, inverseTransform);

}

This topic is closed to new replies.

Advertisement