Array size and variables

Started by
9 comments, last by Pero83 12 years, 5 months ago
Well, i get to this problem a lot, and while dynamic arrays sometimes solves the problem, it doesn't in this case.

I'm making app, that should read obj and render it, so to speak.

So, i have function "readVertexCount", which reads file (say, obj), and return number of vertices. Now, in my other function, where i create vertex buffer, i create array, and need to tell the size. So, i call this "readVertexCount" function, and it gives me number of vertices (int). I'm trying to use this as array size:

int vSize = getVertexCount("cube.txt");
CustomVertex vertices[vSize];


but, as you probably guessed, i get error, saying, that array cannot have variable size.

Ok so i understand why this happens, but i don't know how to "fix" it.

So, why i basicly want to do, is have a function that returns number of vertices, and then use this in creating an array for vertex buffer. And i don't want to use dynamic arrays

Any ideas?
Advertisement
a. Use something like vector (ultimately allocates memory dynamically - can you not use an array created with 'new'?)

b. Create a fixed size array which is 'big enough', impose a limit on vertex count and waste some space
Tnx!




Well, i did try to use 'new', but problem was, that although it doesn't give me any error, it simply refuses to display mesh (like it didn't store values in array correctly).

I idid a like this:

CustomVertex* vertices;

vertices = new CustomVertex[fSize*3];



Maybe i did something wrong there....

b. sounds like solution that should work, but not sure if it's really ok, since it may not be the most optimized way.


Tnx!
I don't know if this was a typo but you wrote:



CustomVertex* vertices;

indices = new CustomVertex[fSize*3]; // instead of vertices = new CustomVertex[fSize*3];



oh yeah, sorry, it was a typo when i copied here. XD
Aha - when you said 'without using dynamic arrays' I thought you were excluding 'new', as an array created with new is often referred to as a dynamic array.

Using either new or a std::vector is almost certainly the way to go. Check out http://fredosaurus.com/notes-cpp/newdelete/50dynamalloc.html . There may be a problem in how you are populating the array with data from the file - we would need to see more code.
Tnx!

Hm, your link isn't working.

Hm, more code. Ok, lets say for index array, i'll give example of code that gave me problem.

If i do this:

short indices[36];

for (int i=0; i<(fSize*3); i++)
{
indices = i;
}


, it works fine.




But now, if i do this:

short* indices;
indices = new short[36];

for (int i=0; i<(fSize*3); i++)
{
indices = i;
}


It does work, but instead of whole cube (like in first example), i only see one triangle (face).

Shouldn't these provide identical results?


Not if you are using sizeof() to determine how many triangles to draw (or otherwise basing the number of triangles to render on the variable itself).
You should post the code for rendering the triangles.
Debug values for fSize and from where that number comes would not hurt.


L. Spiro

I restore Nintendo 64 video-game OST’s into HD! https://www.youtube.com/channel/UCCtX_wedtZ5BoyQBXEhnVZw/playlists?view=1&sort=lad&flow=grid

Yea show the rendering code. And dont use "36". Use a:

#define NUM_INDICES 36

= new short[NUM_INDICES];

NBA2K, Madden, Maneater, Killing Floor, Sims http://www.pawlowskipinball.com/pinballeternal

Hm, ok tnx guys. I'm posting here entire code, and do note, i'm a noob, so i'm probably doing many thigns wrong. :P




Also, just for info, i'm getting vSize and fSize from the txt file, where i "converter" obj file. I also tried to check the values with message box, and they are correct. So, for the moment, i put 36 as the fSize and vSize.(because if i use regular, static arrays with the size 36, it works)




//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// DX 6 - working with meshes
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Defines
#define CUSTOMFVF D3DFVF_XYZ

// Includes
#include <fstream>
#include <string>
#include <sstream>
#include <iostream>
#include <Windows.h>
#include <d3d9.h>
#include <d3dx9.h>

// Pragmas
#pragma comment (lib, "d3d9.lib")
#pragma comment (lib, "d3dx9.lib")

// Defines
#define SCREEN_WIDTH 1680
#define SCREEN_HEIGHT 1050

const int c = 120;
using namespace std;

// Structs
struct CustomVertex
{
float x,y,z;
//float nx, ny, nz;
//float u,v;
};

// Functions
bool init_window(HINSTANCE hInstance);
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
void init_d3d(HWND hWnd);
void setup_VMIB(void);
void render_frame(void);
void clean_d3d(void);
void setMesh(string filename, CustomVertex* vertex);
int getVertexCount(string filename);
int getFaceCount(string filename);

// Variables
HINSTANCE hInstance;
HWND hWnd;

// D3D variables
LPDIRECT3D9 d3d;
LPDIRECT3DDEVICE9 d3ddev;
LPD3DXMESH mesh;

D3DXMATRIX matProj, matView;



//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Win Main
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, INT nCmdShow)
{
if(!init_window(hInstance))
return 0;

MSG msg;
ZeroMemory(&msg, sizeof(msg));

init_d3d(hWnd);
setup_VMIB();

while(true)
{
while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if (msg.message == WM_QUIT)
break;
render_frame();
}
clean_d3d();
return msg.wParam;
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Init Window
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool init_window(HINSTANCE hInstance)
{
WNDCLASSEX wc;
ZeroMemory(&wc, sizeof(wc));

wc.cbSize = sizeof(wc);
wc.hInstance = hInstance;
wc.lpszClassName = "OBJ import Class";
wc.lpfnWndProc = WindowProc;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.style = CS_HREDRAW|CS_VREDRAW;

RegisterClassEx(&wc);

hWnd = CreateWindowEx(NULL, "OBJ import Class", "OBJ import Window", WS_EX_TOPMOST|WS_POPUP, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, NULL, NULL, hInstance, NULL);
if (!hWnd)
return false;

ShowWindow(hWnd, SW_SHOW);
return true;
}



//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Window Proc
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_DESTROY|WM_KEYDOWN:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}



//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// init D3D
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void init_d3d(HWND hWnd)
{

d3d = Direct3DCreate9(D3D_SDK_VERSION);
D3DPRESENT_PARAMETERS d3dpp;

ZeroMemory(&d3dpp, sizeof(d3dpp));
d3dpp.Windowed = true;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.hDeviceWindow = hWnd;
d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
d3dpp.BackBufferWidth = SCREEN_WIDTH;
d3dpp.BackBufferHeight = SCREEN_HEIGHT;
d3dpp.EnableAutoDepthStencil = true;
d3dpp.AutoDepthStencilFormat = D3DFMT_D16;

d3d->CreateDevice (D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &d3ddev);

d3ddev->SetRenderState(D3DRS_ZENABLE, TRUE);
d3ddev->SetRenderState(D3DRS_LIGHTING, FALSE);
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//setup Vertex Buffer / Index Buffer
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void setup_VMIB(void)
{

int vSize = getVertexCount("cube.txt");
//const int a = 36;
int fSize = getFaceCount("cube.txt");
//CustomVertex vertices[a];

/*ostringstream os;
os<<vSize;
string Content = os.str();
MessageBoxA(NULL, Content.c_str(), "43", MB_OK);*/

CustomVertex* vertices;
short* indices;
vertices = new CustomVertex[36];
indices = new short[36];

D3DXCreateMeshFVF(fSize, vSize, D3DXMESH_DYNAMIC| D3DXMESH_WRITEONLY, CUSTOMFVF, d3ddev, &mesh);
setMesh("cube.txt", vertices);

//set index array
for (int i=0; i<(vSize); i++)
{
indices = i;
}



// prepare to copy the vertices into the vertex buffer
VOID* pVertices;
// lock the vertex buffer
mesh->LockVertexBuffer(D3DLOCK_DISCARD, &pVertices);

// copy the vertices into the buffer
memcpy( pVertices, vertices, sizeof(vertices) );

// unlock the vertex buffer
mesh->UnlockVertexBuffer();

// prepare to copy the indexes into the index buffer
VOID* IndexPtr;
// Lock the index buffer
mesh->LockIndexBuffer( 0, &IndexPtr );

// Copy the indexes into the buffer
memcpy( IndexPtr, indices, sizeof(indices)*sizeof(WORD) );

// unlock the buffer
mesh->UnlockIndexBuffer();

delete [] vertices;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// render_frame
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void render_frame(void)
{
d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 55, 155), 1.0f, 0);
d3ddev->Clear(0, NULL, D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 55, 155), 1.0f, 0);

d3ddev->BeginScene();
d3ddev->SetFVF(CUSTOMFVF);

static float indexY = 0.0f; //ever increasing float value for Y axes
indexY +=0.15f;
D3DXMATRIX matRotY;

D3DXMatrixRotationY(&matRotY, indexY);
d3ddev->SetTransform(D3DTS_WORLD, &matRotY);

D3DXMatrixPerspectiveFovLH(&matProj, D3DXToRadian(45), (float)SCREEN_WIDTH/(float)SCREEN_HEIGHT, 1.0f, 1000.0f);
d3ddev->SetTransform(D3DTS_PROJECTION, &matProj);

D3DXMatrixLookAtLH(&matView, &D3DXVECTOR3(10.0f, 10.0f, 10.0f), &D3DXVECTOR3(0, 0, 0), &D3DXVECTOR3(0, 1.0f, 0));
d3ddev->SetTransform(D3DTS_VIEW, &matView);

mesh->DrawSubset(0);

d3ddev->EndScene();

d3ddev->Present(NULL,NULL, NULL, NULL);
}



//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// clean_D3D
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void clean_d3d(void)
{
mesh->Release();
d3ddev->Release();
d3d->Release();
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Set Mesh
/* Reads txt file, extract info about mesh and stores it into array */
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void setMesh(string filename, CustomVertex* vertex)
{
int i = 0;
ifstream fin;
char input;
string s;

fin.open("cube.txt");
//fin.get(input);

while(!fin.eof())
{
fin.get(input);
if(input == 'v')
{
//fin>>(float)vertex.x >>(float)vertex.y >>(float)vertex.z >>(float)vertex.u >>(float)vertex.v >>(float)vertex.nx >>(float)vertex.ny >>(float)vertex.nz;
fin>>(float)vertex.x >>(float)vertex.y >>(float)vertex.z;

/*ostringstream os;
os<<vertex.x;
string Content = os.str();
MessageBoxA(NULL, Content.c_str(), "43", MB_OK);*/
i++;
}

while(input != '\n')
{
fin.get(input);
}
}
fin.close();
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Get Number of Vertices
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int getVertexCount(string filename)
{
ifstream fin;
char input;
int vCount;
string s;
fin.open("cube.txt");
fin.get(input);


while(!fin.eof())
{
if(input == 'a')
{
fin>>s;
if(s == "Vertex_Count")
{
fin>>(int)vCount;
}
}
}
fin.close();
return vCount;
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Get Number of Vertices
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int getFaceCount(string filename)
{
ifstream fin;
char input;
int vCount;
string s;
fin.open("cube.txt");
fin.get(input);


while(!fin.eof())
{
if(input == 'a')
{
fin>>s;
if(s == "Face_Count")
{
fin>>(int)vCount;
}
}
}
fin.close();
return vCount;
}

This topic is closed to new replies.

Advertisement