# OpenGL bit of a conversion problem

This topic is 4297 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

i have recntly bought a few tutorials from www.gametutorials.com i am currently trying to convert the c++ direct3d water tutorial to vb.net , i have been trying for ages and can seem to find the problem , i have converted the code over word for word and still dosent work, so below i have posted the c++ and vb.net and i would be very gratefull if somebody could have a look at them and maybe point out some mistakes that i have made. c++ version water.h
#include "d3d_obj.h"
#include "d3d_texture.h"

/////////////
// Macros //
///////////

#define DEG2RAD(x) (x * (D3DX_PI / 180.0f)) // Converts degrees to radians
#define RAD2DEG(x) (x * (180.0f / D3DX_PI)) // Converts radians to degrees

#define F2I(x) ( (int)((x) + 0.5f) ) // Converts a float to int with proper rounding

////////////////
// Constants //
//////////////

const int kWaterTesselation = 32; // Number of rows X cols of tessellated quads in water
const int kWaveTableSize = 36; // Number of entries in the wave table

const float kWaterForce = 1.0f / 25.0f; // Controls the "choppiness" of the water (Range is 0.0f - 1.0f)
// 0.0f == Water is still
// 1.0f == Water is VERY choppy (so choppy it looks very bad)
const float kWaterWid = 30.0f; // Width of water (along X-axis)
const float kWaterHgt = 30.0f; // Height of water (along Z-axis)

class CWater
{
public:

CWater(); // Constructor

bool init(); // Initialize the water object
void process(); // Process the water object (apply sin() wave to Y value of verts)
void render(); // Render the water

~CWater(); // Deconstructor

private:

bool createGeometery(float width, float height, int tesselation);

CD3DTexture mTexture;
SVertex *mVerts;
WORD *mIndices;

int mVertCount;
int mIndexCount;
int mTesselation;

float mWaveTable[kWaveTableSize];
};

#endif


water.cpp

#include "water.h"

const CPos kWaterCen(0.0f, 0.0f, 0.0f); // Water is always centered at (0,0,0)

// Helper function for determining if a float is less than or equal to
// another float
inline bool ToleranceLE(float a, float b, float tolerance = 0.001f)
{
return ((a - tolerance) <= b);
}

// Constructor
CWater::CWater()
{
memset(mWaveTable, 0, sizeof(mWaveTable));

mVerts = NULL;
mIndices = NULL;

mVertCount = 0;
mIndexCount = 0;
mTesselation = 0;

// "texture" gets initialized by it's constructor
}

// Init the water object, returns true on success, false otherwise
bool CWater::init()
{
// Fill the wave table
float angInc = 360.0f / (float)kWaveTableSize;
float angle = 0.0f;

// Fill in the table with values of the sine function
for(int i = 0; i < kWaveTableSize; ++i)
{
angle += angInc;
}

if(!createGeometery(kWaterWid, kWaterHgt, kWaterTesselation))
return false;

}

// Process the water every frame
void CWater::process()
{
static int startIndex = 0;

int waveIndex = startIndex;
int vertIndex = 0;

// Loop through all rows of triangles
for(int i = 0; i <= mTesselation; ++i)
{
// Loop through all the columns of triangles
for(int j = 0; j <= mTesselation; ++j, ++vertIndex)
{
// Perturb each vertex
mVerts[vertIndex].y += mWaveTable[waveIndex] * kWaterForce;

if(++waveIndex == kWaveTableSize)
waveIndex = 0;
}

}

// Keep cycling thorough the mWaveTable
if(++startIndex == kWaveTableSize)
startIndex = 0;
}

// Render the water object as a triangle strip
void CWater::render()
{
bool b = g3D->setAlphaBlendMode(true); // Turn on alpha blending

mTexture.select(); // Select the water texture
g3D->render(mVerts, mVertCount, mIndices, mIndexCount); // Render the tessellated quad

g3D->setAlphaBlendMode(false); // Turn off alpha blending
}

// Creates a tesselated quad of (width x height) dimensions
// Number of triangles in quad is (tessAmt * tessAmt * 2)
bool CWater::createGeometery(float width, float height, int tessAmt)
{
if(width < 0.0f || height < 0.0f || tessAmt <= 0)
return false;

// Set tesselation amount
mTesselation = tessAmt;

// Calculate vertex count.  We know that we have (tesselation * tesselation * 2) triangles
// with 3 vertices per triangle.  So each row of vertices will contain "number of rows + 1"
// vertices and each column of vertices well contain "number of columns + 1" vertices.  This
// makes the total number of vertices equal the following equation
mVertCount = (mTesselation + 1) * (mTesselation + 1);

// Calculate index count.  We know that we'll have (tesselation * tesselation * 2) triangles
// and we have 3 vertices per triangle, thus the below equation
mIndexCount = mTesselation * mTesselation * 6;

// Allocate space for vertices and indices
mVerts = new SVertex[mVertCount];
mIndices = new WORD[mIndexCount];

if(mVerts == NULL || mIndices == NULL)
return false;

// Get the sub divided width and height of each triangle
float subDivideWid = width * (1.0f / (float)mTesselation);
float subDivideHgt = height * (1.0f / (float)mTesselation);

// Calculate the starting (x,y) and ending (x,y) of the quad
float startX = kWaterCen.x - (width / 2.0f);
float startY = kWaterCen.z - (height / 2.0f);
float endX = kWaterCen.x + (width / 2.0f);
float endY = kWaterCen.z + (height / 2.0f);

float uCoord = 0.0f; // Holds the current trinagle's U coordinate
float vCoord = 1.0f; // Holds the current triangle's V coordinate
float uvInc = 1.0f / (float)mTesselation; // Calculate the amount to add to each UV coordinate

int i = 0; // Index for all of for...loops

// Create all the vertices
for(float y = startY; ToleranceLE(y, endY); y += subDivideHgt)
{
for(float x = startX; ToleranceLE(x, endX); x += subDivideWid, ++i)
{
// Set the value for the current vert
mVerts.x = x;
mVerts.y = kWaterCen.y;
mVerts.z = y;
mVerts.u = uCoord;
mVerts.v = vCoord;
mVerts.color = D3DCOLOR_ARGB(128, 255, 255, 255);

uCoord += uvInc;
}

// Set UV for next row of vertices
uCoord = 0.0f;
vCoord -= uvInc;
}

// Make sure we calculatd the vertex count correctly
assert(mVertCount == i);

int indexValue = 0;
int nextRow = 0;

// Look at this sample 2 x 2 quad to understand the pattern used to fill in the indices
/*
6----7----8		Index count =  24
|\ 	 |\   |		Tesselation = 2
| \  | \  |
|  \ |  \ |		Pattern is:	0, 3, 1
|   \|   \|					1, 3, 4
3----4----5					1, 4, 2
|\ 	 |\   |					2, 4, 5
| \  | \  | 				3, 6, 4
|  \ |  \ |					4, 6, 7
|   \|   \|					4, 7, 5,
0----1----2					5, 7, 8
*/

// Create all the indices
for(i = 0; i < mIndexCount; i += 6)
{
mIndices = indexValue;
mIndices[i + 1] = indexValue + (mTesselation + 1);
mIndices[i + 2] = mIndices + 1;

indexValue++;

mIndices[i + 3] = indexValue;
mIndices[i + 4] = indexValue + mTesselation;
mIndices[i + 5] = mIndices[i + 4] + 1;

if(++nextRow == mTesselation)
{
indexValue++;
nextRow = 0;
}
}

return true;
}

// Free the memory
CWater::~CWater()
{
if(mVerts)
{
delete[] mVerts;
mVerts = NULL;
}

if(mIndices)
{
delete[] mIndices;
mIndices = NULL;
}
}


and here is my vb.net conversion

Public Class RealisticWater

Public Function Deg2Rad(ByVal X As Single) As Single
Return X * (PI / 180.0F) 'convert degrees to radian
End Function

Public Function Rad2Deg(ByVal x As Single) As Single
Return x * (180.0F / PI) 'converts radians to degrees
End Function

Public Function F2I(ByVal x As Single) As Integer
Return CType(x + 0.5F, Integer) 'converts  float to int with proper rounding
End Function

Private Const kWaterTesselation As Single = 32 ' number of row columns of teselation in water
Private Const kWaveTableSize As Single = 36 ' number of entries in the wav table
Private Const kWaterForce As Single = 0.1F / 25.0F ' // Controls the "choppiness" of the water (Range is 0.0f - 1.0f)
'// 0.0f == Water is still
'// 1.0f == Water is VERY choppy (so choppy it looks very bad)
Private Const kWaterWid As Single = 30.0F 'width of water along x axis
Private Const kWaterHgt As Single = 30.0F ' height of water along z axis

#Region "Water Vertex Structure"
Public Structure WVertex
Public x, y, z As Single
Public Color As Integer
Public u, v As Single
Public Const Format As VertexFormats = VertexFormats.Position Or VertexFormats.Diffuse Or (1 << VertexFormats.TextureCountShift)
'Public Const Format As VertexFormats = VertexFormats.Diffuse Or VertexFormats.Position Or (1 << VertexFormats.TextureCountShift)
End Structure
#End Region

Private mTexture As Direct3D.Texture
Private mVerts() As WVertex
Private mIndices() As Integer
Private mVertCount As Integer
Private mIndexCount As Integer
Private mTesselation As Single
Private mWaveTable(kWaveTableSize) As Single
Private kWaterCen As Vector3 = New Vector3(0, 0, 0) 'water is always cenetred at 0.0f
Private Dev As Direct3D.Device

Public Function ToleranceLE(ByVal a As Single, ByVal b As Single, Optional ByVal tolerance As Single = 0.001F) As Boolean
Return ((a - tolerance) <= b)
End Function

'// Constructor
Public Sub New(ByVal Device As Direct3D.Device, ByVal TexturePath As String)
Dev = Device
mVerts = Nothing
mIndices = Nothing
mVertCount = 0
mIndexCount = 0
mTesselation = 0
Init(TexturePath)
End Sub

'// Init the water object, returns true on success, false otherwise
Private Sub Init(ByVal TexturePath As String)
'// Fill the wave table
Dim anginc As Single = 360.0F / CType(kWaveTableSize, Single)
Dim angle As Single = 0.0F
Dim I As Integer

'// Fill in the table with values of the sine function
For I = 0 To kWaveTableSize - 1
angle += anginc
Next

CreateGeometery(kWaterWid, kWaterHgt, kWaterTesselation)

End Sub

'// Process the water every frame
Public Sub Process()
Static startIndex As Integer = 0
Dim waveIndex As Integer = startIndex
Dim vertIndex As Integer = 0
Dim i As Integer
Dim j As Integer

'// Loop through all rows of triangles
For i = 0 To mTesselation '- 1
'// Loop through all the columns of triangles
For j = 0 To mTesselation
'// Perturb each vertex
mVerts(vertIndex).y += mWaveTable(waveIndex) * kWaterForce
waveIndex = 0
End If
Next
Next

'// Keep cycling thorough the mWaveTable
startIndex = 0
End If
End Sub

Public Sub Process2()
Static startindex As Integer
Dim waveindex As Integer = startindex
Dim vertindex As Integer
Dim i As Integer
Dim j As Integer
'// Loop through all rows of triangles
For i = 0 To mTesselation
'// Loop through all the columns of triangles
For j = 0 To mTesselation
'// Perturb each vertex
mVerts(vertindex).y += mWaveTable(waveIndex) * kWaterForce
vertindex += 1
waveindex += 1
If waveindex = kWaveTableSize Then
waveindex = 0
End If
Next
Next
'// Keep cycling thorough the mWaveTable
startindex += 1
If startindex = kWaveTableSize Then
startindex = 0
End If
End Sub

'// Render the water object as a triangle strip
Public Sub Render()
Dev.RenderState.AlphaBlendEnable = True
Dev.RenderState.Lighting = False
Dev.VertexFormat = WVertex.Format
Dev.SetTexture(0, mTexture)
Dev.RenderState.CullMode = Cull.None
Dev.DrawIndexedUserPrimitives(PrimitiveType.TriangleStrip, 0, mIndexCount, mIndexCount / 3, mIndices, False, mVerts)
Dev.RenderState.Lighting = True
Dev.RenderState.AlphaBlendEnable = False
End Sub

'// Creates a tesselated quad of (width x height) dimensions
'// Number of triangles in quad is (tessAmt * tessAmt * 2)
Public Function createGeometery(ByVal width As Single, ByVal height As Single, ByVal tessAmt As Single) As Boolean

If width < 0.0F Or height < 0.0F Or tessAmt <= 0 Then Return False

'Set tesselation amount
mTesselation = tessAmt

' Calculate vertex count.  We know that we have (tesselation * tesselation * 2) triangles
' with 3 vertices per triangle.  So each row of vertices will contain "number of rows + 1"
' vertices and each column of vertices well contain "number of columns + 1" vertices.  This
' makes the total number of vertices equal the following equation
mVertCount = (mTesselation + 1) * (mTesselation + 1)

' Calculate index count.  We know that we'll have (tesselation * tesselation * 2) triangles
' and we have 3 vertices per triangle, thus the below equation
mIndexCount = mTesselation * mTesselation * 6

' Allocate space for vertices and indices
ReDim mVerts(mVertCount)
ReDim mIndices(mIndexCount)

'not sure how this could ever be true given the two lines above
'if mVerts = NULL or  mIndices == NULL Then Return False

' Get the sub divided width and height of each triangle
Dim subDivideWid As Single = width * (1 / mTesselation)
Dim subDivideHgt As Single = height * (1 / mTesselation)

Dim startx As Single
Dim starty As Single
Dim endx As Single
Dim endy As Single
Dim ucoord As Single
Dim vcoord As Single
Dim uvinc As Single

' Calculate the starting (x,y) and ending (x,y) of the quad
startx = kWaterCen.X - (width / 2.0F)
starty = kWaterCen.Z - (height / 2.0F)
endx = kWaterCen.X + (width / 2.0F)
endy = kWaterCen.Z + (height / 2.0F)

ucoord = 0.0F ' Holds the current trinagle's U coordinate
vcoord = 1.0F ' Holds the current triangle's V coordinate

uvinc = 1.0F / mTesselation ' Calculate the amount to add to each UV coordinate

Dim i As Integer = 0 ' Index for all of for...loops
Dim y As Single
Dim x As Single

' Create all the vertices
For y = starty To ToleranceLE(y, endy) Step subDivideHgt
For x = startx To ToleranceLE(x, endx) Step subDivideWid

' Set the value for the current vert
mVerts(i).x = x
mVerts(i).y = kWaterCen.Y
mVerts(i).z = y
mVerts(i).u = ucoord
mVerts(i).v = vcoord
mVerts(i).Color = Color.FromArgb(128, 255, 255, 255).ToArgb

ucoord += uvinc

i += 1

Next x

' Set UV for next row of vertices
ucoord = 0.0F
vcoord -= uvinc

Next y

' Make sure we calculatd the vertex count correctly
'If mVertCount <> i Then Throw New Exception("Vertex count does not equal " & i.ToString)

Dim indexValue As Integer = 0
Dim nextRow As Integer = 0

' Look at this sample 2 x 2 quad to understand the pattern used to fill in the indices
'6----7----8      Index count =  24
'|\     |\   |      Tesselation = 2
'| \  | \  |
'|  \ |  \ |      Pattern is:   0, 3, 1
'|   \|   \|               1, 3, 4
'3----4----5               1, 4, 2
'|\     |\   |               2, 4, 5
'| \  | \  |             3, 6, 4
'|  \ |  \ |               4, 6, 7
'|   \|   \|               4, 7, 5,
'0----1----2               5, 7, 8

' Create all the indices
For i = 0 To mIndexCount - 1 Step 6

mIndices(i) = indexValue
mIndices(i + 1) = indexValue + mTesselation + 1
mIndices(i + 2) = mIndices(i) + 1

indexValue += 1

mIndices(i + 3) = indexValue
mIndices(i + 4) = indexValue + mTesselation
mIndices(i + 5) = mIndices(i + 4) + 1

nextRow += 1

If nextRow = mTesselation Then
indexValue += 1
nextRow = 0
End If

Next i

Return True
End Function

Public Sub Dispose()
Erase mVerts
Erase mIndices
End Sub

End Class


plase any help will be very helpfull ive been trying for ages to get this working and i cant seem to see anything wrong. sorry i though i used the code tags already, i know im really sorry about all the code but the prob is i have gone trough it loadz of times and icant find the prob. the prob is it dosent render properly, but from what i can see its the vertice generation that causes the prob, i just for the life of me figure it out. and im not convberting opengl to MDX, its c++ MDX to vb.net MDX, which i have done loadz of times and should be almost identical, but i cant seem to find the problem. [Edited by - tuvd on May 17, 2006 6:25:36 AM]

##### Share on other sites

Also, alot of people that answer questions on these forums don't really have time to go through a whole bunch of code like that. A simple question with regards to conversion might be something like how do I convert ID3DXSprite to MDX or what is the MDX equavalent.

Stay cool.

• 10
• 12
• 10
• 10
• 11
• ### Similar Content

• Good Evening,
I want to make a 2D game which involves displaying some debug information. Especially for collision, enemy sights and so on ...
First of I was thinking about all those shapes which I need will need for debugging purposes: circles, rectangles, lines, polygons.
I am really stucked right now because of the fundamental question:
Where do I store my vertices positions for each line (object)? Currently I am not using a model matrix because I am using orthographic projection and set the final position within the VBO. That means that if I add a new line I would have to expand the "points" array and re-upload (recall glBufferData) it every time. The other method would be to use a model matrix and a fixed vbo for a line but it would be also messy to exactly create a line from (0,0) to (100,20) calculating the rotation and scale to make it fit.
If I proceed with option 1 "updating the array each frame" I was thinking of having 4 draw calls every frame for the lines vao, polygons vao and so on.
In addition to that I am planning to use some sort of ECS based architecture. So the other question would be:
Should I treat those debug objects as entities/components?
For me it would make sense to treat them as entities but that's creates a new issue with the previous array approach because it would have for example a transform and render component. A special render component for debug objects (no texture etc) ... For me the transform component is also just a matrix but how would I then define a line?
Treating them as components would'nt be a good idea in my eyes because then I would always need an entity. Well entity is just an id !? So maybe its a component?
Regards,
LifeArtist
• By QQemka
Hello. I am coding a small thingy in my spare time. All i want to achieve is to load a heightmap (as the lowest possible walking terrain), some static meshes (elements of the environment) and a dynamic character (meaning i can move, collide with heightmap/static meshes and hold a varying item in a hand ). Got a bunch of questions, or rather problems i can't find solution to myself. Nearly all are deal with graphics/gpu, not the coding part. My c++ is on high enough level.
Let's go:
Heightmap - i obviously want it to be textured, size is hardcoded to 256x256 squares. I can't have one huge texture stretched over entire terrain cause every pixel would be enormous. Thats why i decided to use 2 specified textures. First will be a tileset consisting of 16 square tiles (u v range from 0 to 0.25 for first tile and so on) and second a 256x256 buffer with 0-15 value representing index of the tile from tileset for every heigtmap square. Problem is, how do i blend the edges nicely and make some computationally cheap changes so its not obvious there are only 16 tiles? Is it possible to generate such terrain with some existing program?
Collisions - i want to use bounding sphere and aabb. But should i store them for a model or entity instance? Meaning i have 20 same trees spawned using the same tree model, but every entity got its own transformation (position, scale etc). Storing collision component per instance grats faster access + is precalculated and transformed (takes additional memory, but who cares?), so i stick with this, right? What should i do if object is dynamically rotated? The aabb is no longer aligned and calculating per vertex min/max everytime object rotates/scales is pretty expensive, right?
Drawing aabb - problem similar to above (storing aabb data per instance or model). This time in my opinion per model is enough since every instance also does not have own vertex buffer but uses the shared one (so 20 trees share reference to one tree model). So rendering aabb is about taking the model's aabb, transforming with instance matrix and voila. What about aabb vertex buffer (this is more of a cosmetic question, just curious, bumped onto it in time of writing this). Is it better to make it as 8 points and index buffer (12 lines), or only 2 vertices with min/max x/y/z and having the shaders dynamically generate 6 other vertices and draw the box? Or maybe there should be just ONE 1x1x1 cube box template moved/scaled per entity?
What if one model got a diffuse texture and a normal map, and other has only diffuse? Should i pass some bool flag to shader with that info, or just assume that my game supports only diffuse maps without fancy stuff?
There were several more but i forgot/solved them at time of writing
• By RenanRR
Hi All,
I'm reading the tutorials from learnOpengl site (nice site) and I'm having a question on the camera (https://learnopengl.com/Getting-started/Camera).
I always saw the camera being manipulated with the lookat, but in tutorial I saw the camera being changed through the MVP arrays, which do not seem to be camera, but rather the scene that changes:
#version 330 core layout (location = 0) in vec3 aPos; layout (location = 1) in vec2 aTexCoord; out vec2 TexCoord; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { gl_Position = projection * view * model * vec4(aPos, 1.0f); TexCoord = vec2(aTexCoord.x, aTexCoord.y); } then, the matrix manipulated:
..... glm::mat4 projection = glm::perspective(glm::radians(fov), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); ourShader.setMat4("projection", projection); .... glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); ourShader.setMat4("view", view); .... model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); ourShader.setMat4("model", model);
So, some doubts:
- Why use it like that?
- Is it okay to manipulate the camera that way?
-in this way, are not the vertex's positions that changes instead of the camera?
- I need to pass MVP to all shaders of object in my scenes ?

What it seems, is that the camera stands still and the scenery that changes...
it's right?

Thank you

• Sampling a floating point texture where the alpha channel holds 4-bytes of packed data into the float. I don't know how to cast the raw memory to treat it as an integer so I can perform bit-shifting operations.

int rgbValue = int(textureSample.w);//4 bytes of data packed as color
// algorithm might not be correct and endianness might need switching.
vec3 extractedData = vec3(  rgbValue & 0xFF000000,  (rgbValue << 8) & 0xFF000000, (rgbValue << 16) & 0xFF000000);
extractedData /= 255.0f;

• While writing a simple renderer using OpenGL, I faced an issue with the glGetUniformLocation function. For some reason, the location is coming to be -1.
Anyone has any idea .. what should I do?