Sign in to follow this  
tuvd

OpenGL bit of a conversion problem

Recommended Posts

tuvd    122
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)
	{
		mWaveTable[i] = sin(DEG2RAD(angle));
		angle += angInc;
	}

	// Create the tessellated quad
	if(!createGeometery(kWaterWid, kWaterHgt, kWaterTesselation))
		return false;
	
	// Load the water texture
	return mTexture.load("water.jpg"); 
}

// 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[i].x = x;
			mVerts[i].y = kWaterCen.y;
			mVerts[i].z = y;
			mVerts[i].u = uCoord;
			mVerts[i].v = vCoord;
			mVerts[i].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[i] = indexValue;
		mIndices[i + 1] = indexValue + (mTesselation + 1);
		mIndices[i + 2] = mIndices[i] + 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
                mWaveTable(I) = Sin(Deg2Rad(angle))
                angle += anginc
            Next

            '// Create the tessellated quad
            CreateGeometery(kWaterWid, kWaterHgt, kWaterTesselation)

            '// Load the water texture
            mTexture = TextureLoader.FromFile(Dev, TexturePath)
        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
                    If System.Threading.Interlocked.Increment(waveIndex) = kWaveTableSize Then
                        waveIndex = 0
                    End If
                Next
            Next

            '// Keep cycling thorough the mWaveTable
            If System.Threading.Interlocked.Increment(startIndex) = kWaveTableSize Then
                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 this post


Link to post
Share on other sites
Armadon    1091
Please place your code in the source tags. It's a bit difficult to read.

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.

It's just a few tips to better help your answering and you might find that you will get a much faster reply ;)

Stay cool.

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  

  • Similar Content

    • By pseudomarvin
      I assumed that if a shader is computationally expensive then the execution is just slower. But running the following GLSL FS instead just crashes
      void main() { float x = 0; float y = 0; int sum = 0; for (float x = 0; x < 10; x += 0.00005) { for (float y = 0; y < 10; y += 0.00005) { sum++; } } fragColor = vec4(1, 1, 1 , 1.0); } with unhandled exception in nvoglv32.dll. Are there any hard limits on the number of steps/time that a shader can take before it is shut down? I was thinking about implementing some time intensive computation in shaders where it would take on the order of seconds to compute a frame, is that possible? Thanks.
    • By Arulbabu Donbosco
      There are studios selling applications which is just copying any 3Dgraphic content and regenerating into another new window. especially for CAVE Virtual reality experience. so that the user opens REvite or CAD or any other 3D applications and opens a model. then when the user selects the rendered window the VR application copies the 3D model information from the OpenGL window. 
      I got the clue that the VR application replaces the windows opengl32.dll file. how this is possible ... how can we copy the 3d content from the current OpenGL window.
      anyone, please help me .. how to go further... to create an application like VR CAVE. 
       
      Thanks
    • By cebugdev
      hi all,

      i am trying to build an OpenGL 2D GUI system, (yeah yeah, i know i should not be re inventing the wheel, but this is for educational and some other purpose only),
      i have built GUI system before using 2D systems such as that of HTML/JS canvas, but in 2D system, i can directly match a mouse coordinates to the actual graphic coordinates with additional computation for screen size/ratio/scale ofcourse.
      now i want to port it to OpenGL, i know that to render a 2D object in OpenGL we specify coordiantes in Clip space or use the orthographic projection, now heres what i need help about.
      1. what is the right way of rendering the GUI? is it thru drawing in clip space or switching to ortho projection?
      2. from screen coordinates (top left is 0,0 nd bottom right is width height), how can i map the mouse coordinates to OpenGL 2D so that mouse events such as button click works? In consideration ofcourse to the current screen/size dimension.
      3. when let say if the screen size/dimension is different, how to handle this? in my previous javascript 2D engine using canvas, i just have my working coordinates and then just perform the bitblk or copying my working canvas to screen canvas and scale the mouse coordinates from there, in OpenGL how to work on a multiple screen sizes (more like an OpenGL ES question).
      lastly, if you guys know any books, resources, links or tutorials that handle or discuss this, i found one with marekknows opengl game engine website but its not free,
      Just let me know. Did not have any luck finding resource in google for writing our own OpenGL GUI framework.
      IF there are no any available online, just let me know, what things do i need to look into for OpenGL and i will study them one by one to make it work.
      thank you, and looking forward to positive replies.
    • By fllwr0491
      I have a few beginner questions about tesselation that I really have no clue.
      The opengl wiki doesn't seem to talk anything about the details.
       
      What is the relationship between TCS layout out and TES layout in?
      How does the tesselator know how control points are organized?
          e.g. If TES input requests triangles, but TCS can output N vertices.
             What happens in this case?
      In this article,
      http://www.informit.com/articles/article.aspx?p=2120983
      the isoline example TCS out=4, but TES in=isoline.
      And gl_TessCoord is only a single one.
      So which ones are the control points?
      How are tesselator building primitives?
    • By Orella
      I've been developing a 2D Engine using SFML + ImGui.
      Here you can see an image
      The editor is rendered using ImGui and the scene window is a sf::RenderTexture where I draw the GameObjects and then is converted to ImGui::Image to render it in the editor.
      Now I need to create a 3D Engine during this year in my Bachelor Degree but using SDL2 + ImGui and I want to recreate what I did with the 2D Engine. 
      I've managed to render the editor like I did in the 2D Engine using this example that comes with ImGui. 
      3D Editor preview
      But I don't know how to create an equivalent of sf::RenderTexture in SDL2, so I can draw the 3D scene there and convert it to ImGui::Image to show it in the editor.
      If you can provide code will be better. And if you want me to provide any specific code tell me.
      Thanks!
  • Popular Now