dev.gamez.lv Forum Index dev.gamez.lv
Latvian Game Developers Community
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups 

3ds faili
Goto page 1, 2  Next
 
dev.gamez.lv Forum Index -> Grafikas programmēšana un teorija
View previous topic :: View next topic  
Author Message
coderpp



Joined: 20 Aug 2005
Posts: 167
Location: Rīga, Koknese, Gajiena

PostPosted: Wed Jan 04, 2006 2:23 pm    Post subject: 3ds faili

Vai 3ds faili sevii ietver arii tekstuuras??
Back to top
View user's profile Send e-mail
bubu
Indago Uzvarētājs
Indago Uzvarētājs


Joined: 23 Mar 2004
Posts: 3223
Location: Riga

PostPosted: Wed Jan 04, 2006 2:54 pm    Post subject:

Iisti nezinu, bet ierakstot guuglee "3ds file format textures" man liekas, ka neietver gan.
Back to top
View user's profile Send e-mail
elvman
Indago Uzvarētājs
Indago Uzvarētājs


Joined: 09 Apr 2003
Posts: 1278
Location: Kuldiga

PostPosted: Wed Jan 04, 2006 3:15 pm    Post subject:

Bet tu vari pats savu chunk uztaisiit ar tekstuuras informaaciju (arii atteelu) un tev buus .3ds fails ar tekstuuru iekshaa (tas gan aiznjems daudz vairaak vietas).
_________________
long time; /* know C */
Back to top
View user's profile Visit poster's website
EDDY



Joined: 07 Oct 2005
Posts: 1610
Location: Dzimtā zeme, Latvija

PostPosted: Sat Jan 07, 2006 3:26 pm    Post subject: Re: 3ds faili

Alberts wrote:
Vai 3ds faili sevii ietver arii tekstuuras??

Tu laikam gribeeji prasiit: "Vai *.3ds failaa glabaajas teksturas nosaukums vai tas jaapiesaista kodaa"?
Bet ideja ievilkt failaa vienlaikus gan tekstuuras kodu, gan objekta formaata kodu liekas interesanta.
Bet vieglaak tas buutu realizeejams uz Delphi.
_________________
Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday
Back to top
View user's profile
bubu
Indago Uzvarētājs
Indago Uzvarētājs


Joined: 23 Mar 2004
Posts: 3223
Location: Riga

PostPosted: Sat Jan 07, 2006 4:01 pm    Post subject: Re: 3ds faili

EDDY wrote:
Bet vieglaak tas buutu realizeejams uz Delphi.

Kāpēc?
Back to top
View user's profile Send e-mail
EDDY



Joined: 07 Oct 2005
Posts: 1610
Location: Dzimtā zeme, Latvija

PostPosted: Sat Jan 07, 2006 4:17 pm    Post subject:

Tapeec, ka bitmapu var Delphos realizeet kaa 2d masiivu no heksadecimaalajiem simboliem.
Turklaat Delphi speej *.exe failaa ietvert ari bitmapu kodu, ko realizeet uz C++ buutu grutaak.
Pagaidam tikai uz C# un Delphi es maaku ietveert bitmap kodu ieksh *.exe, jo taas ir liidziigas valodas.
Bet C++ ... taa ir tumsa shai zinjaa... Cool man.
_________________
Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday
Back to top
View user's profile
bubu
Indago Uzvarētājs
Indago Uzvarētājs


Joined: 23 Mar 2004
Posts: 3223
Location: Riga

PostPosted: Sat Jan 07, 2006 7:12 pm    Post subject:

Nu redzi, tas kas tev ir "vieglāk realizējams" nenozīmē, ka tas vispār un visur ir "vieglāk realizējams".

Iekš C++ to var šādi:
Code:
const unsigned char masivs[2][5] = {
  { 0x01, 0x02, 0x03, 0x04, 0x05 },
  { 0xA1, 0xB2, 0xC3, 0xC4, 0xC5 }
};

Kautkā negribās teikt, ka tas ir "grūtāk" nekā Delphos :) (ja godīgi, es Delphus esmu jau aizmirsis, tāpēc man grūtāk būtu Delphos to izdarīt, jo C++ veidu es varu no galvas uzrakstīt, toties Delphi masīva inicializācija man jāmeklē piemērā būtu. Ja nu vienīgi tā nav x: array of integer = {1,2,..,3}; )

Un vispār nesaprotu kam tur 2d masīvus. Pietiek ar 1D masīviem. Bildes dati pēc būtības ir baitu virkne.
Back to top
View user's profile Send e-mail
elvman
Indago Uzvarētājs
Indago Uzvarētājs


Joined: 09 Apr 2003
Posts: 1278
Location: Kuldiga

PostPosted: Sat Jan 07, 2006 7:18 pm    Post subject:

Nee! EDDY ar savu postu bija domaajis,ka Delphi ir integreeta funkcija,kas .BMP failu paarveido par 2D masiivu automatiski (bez stundu ilgas klaviaturas spaidishanas).
_________________
long time; /* know C */
Back to top
View user's profile Visit poster's website
eXeM



Joined: 22 Mar 2005
Posts: 155
Location: Ape

PostPosted: Sat Jan 07, 2006 7:21 pm    Post subject:

Delfos aatri paarveido un tad copy paste uz c++
Smile
Back to top
View user's profile
elvman
Indago Uzvarētājs
Indago Uzvarētājs


Joined: 09 Apr 2003
Posts: 1278
Location: Kuldiga

PostPosted: Sat Jan 07, 2006 8:31 pm    Post subject:

Vai vienkaarshi panjem 5 sekundees uztaisi utiliitu,kas automaatiski .BMP failu paarveido uz C++ n dimensiju masiivu f fromaataa,kur n vari izveeleeties (1 vai 2) un f ir kuakaads formaats piem-pa baitiem vai RGB veertiibas (vai GBR) ar cipariem utt.
_________________
long time; /* know C */
Back to top
View user's profile Visit poster's website
bubu
Indago Uzvarētājs
Indago Uzvarētājs


Joined: 23 Mar 2004
Posts: 3223
Location: Riga

PostPosted: Sat Jan 07, 2006 8:38 pm    Post subject:

Kas tā par utilītu? Kautkā agrāk tādu nebiju manījis. Lai gan varu saderēt internetā pilns ar jau gatavām tādām utilītām arī priekš C valodas ir :)
Back to top
View user's profile Send e-mail
elvman
Indago Uzvarētājs
Indago Uzvarētājs


Joined: 09 Apr 2003
Posts: 1278
Location: Kuldiga

PostPosted: Sat Jan 07, 2006 8:47 pm    Post subject:

Delphos taa nav utiliita,bet cik atceros (ar Delphiem straadaaju kaadus 3 gadus atpakalj) tad bija kaukaads options/convert graphics file to massive (es NOTEIKTI kljuudos ar nosaukumiem,bet kaukas liidziigs bija).
_________________
long time; /* know C */
Back to top
View user's profile Visit poster's website
EDDY



Joined: 07 Oct 2005
Posts: 1610
Location: Dzimtā zeme, Latvija

PostPosted: Tue Jan 10, 2006 3:09 pm    Post subject:

elvman wrote:
Nee! EDDY ar savu postu bija domaajis,ka Delphi ir integreeta funkcija,kas .BMP failu paarveido par 2D masiivu automatiski (bez stundu ilgas klaviaturas spaidishanas).

Japp, beidzot viens saprata.
Tachu, ja paskatamies reaali, tad 1D masiivs nezin vienu lietu:
Cik reiz cik pixels.
Tu, Bubu, saki, ka tas ir 1D massiivs, bet tad tev janjem priekshaa jaaraksta *.bmp faila formaata specifikaacija.
Tur *.bmp failam saakuma pusee ir defineets: cik reiz cik pixels, cik kraasu biti u.t.t. ....
Bet, manispeec, tu vari taisiit uz C++ ... es taa nedariitu, jo nav jeegas.
_________________
Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday
Back to top
View user's profile
bubu
Indago Uzvarētājs
Indago Uzvarētājs


Joined: 23 Mar 2004
Posts: 3223
Location: Riga

PostPosted: Tue Jan 10, 2006 6:33 pm    Post subject:

Nu un, ka nezin? Tam taču var papildus divos mainīgos (vai vienā, ja ļoti vēlies) saglabāt tā izmēru. Nu jā Delphi jau ir tāda fiška, ka tas saglabā to masīvu izmērus tāpatās (automātiski), tāpēc arī 2D masīvam tev tas pats vien sanāks - tb izmēru glabāšana atsevišķi.
Back to top
View user's profile Send e-mail
coderpp



Joined: 20 Aug 2005
Posts: 167
Location: Rīga, Koknese, Gajiena

PostPosted: Sat Feb 18, 2006 10:24 am    Post subject:

Chunks.h
Code:
#ifndef _3DS_CHUNKS_H_
#define _3DS_CHUNKS_H_

#define PRIMARY_ID   0x4D4D
#define EDIT3DS   0x3D3D
#define KEYF3DS   0xB000

#define VERSION   0x0002
#define MESH_VERSION 0x3D3E
#define KFVERSION 0x0005
#define COLOR_F   0x0010
#define COLOR_24  0x0011
#define LIN_COLOR_24 0x0012
#define LIN_COLOR_F  0x0013
#define INT_PERCENTAGE  0x0030
#define FLOAT_PERC   0x0031
#define MASTER_SCALE 0x0100
#define IMAGE_FILE   0x1100
#define AMBIENT_LIGHT   0X2100

#define NAMED_OBJECT 0x4000
#define OBJ_MESH  0x4100
#define MESH_VERTICES   0x4110
#define VERTEX_FLAGS 0x4111
#define MESH_FACES   0x4120
#define MESH_MATER   0x4130
#define MESH_TEX_VERT   0x4140
#define MESH_XFMATRIX   0x4160
#define MESH_COLOR_IND  0x4165
#define MESH_TEX_INFO   0x4170
#define HEIRARCHY 0x4F00

#define MATERIAL  0xAFFF
#define MAT_NAME  0xA000
#define MAT_AMBIENT  0xA010
#define MAT_DIFFUSE  0xA020
#define MAT_SPECULAR 0xA030
#define MAT_SHININESS   0xA040
#define MAT_FALLOFF  0xA052
#define MAT_EMISSIVE 0xA080
#define MAT_SHADER   0xA100
#define MAT_TEXMAP   0xA200
#define MAT_TEXFLNM  0xA300

#define OBJ_LIGHT 0x4600
#define OBJ_CAMERA   0x4700

#define ANIM_HEADER  0xB00A
#define ANIM_OBJ  0xB002
#define ANIM_NAME 0xB010
#define ANIM_POS  0xB020
#define ANIM_ROT  0xB021
#define ANIM_SCALE   0xB022

#endif
C3DSObject.h
Code:
#ifndef _C3DS_OBJECT_H_
#define _C3DS_OBJECT_H_

#include<stdio.h>
#include<vector>

// File chunk header.
struct stChunk
{
   stChunk() : id(0), length(0), bytesRead(0) {}
   short id;
   unsigned int length;
   unsigned int bytesRead;
};

// Vertex position.
struct stVertex
{
   stVertex() : x(0), y(0), z(0) {}
   float x, y, z;
};

// Triangle.
struct stFace
{
   stFace() : matId(0) { indices[0] = indices[1] = indices[2] = 0; }
   unsigned int indices[3];
   stVertex normal;
   int matId;
};

// Triangle as it is in the file.
struct stFileFace
{
   stFileFace() : vis(0) { indices[0] = indices[1] = indices[2] = 0; }
   unsigned short indices[3], vis;
};

// RGB color value.
struct stColor
{
   stColor() : r(0), g(0), b(0) {}
   unsigned char r, g, b;
};

// Texture coordinate for a vertex pos.
struct stTexCoord
{
   stTexCoord() : tu(0), tv(0) {}
   float tu, tv;
};

// Material of a face.
struct stMaterial
{
   stMaterial() { name[0] = '/0'; textureName[0] = '/0'; }
   char name[256];
   stColor color;
   char textureName[256];
};

// Mesh object.  A file can have more than 1.
struct stMesh
{
   stMesh() : pFaces(0), pVertices(0), pTexCoords(0),
              totalFaces(0), totalVertices(0), totalTexCoords(0) {}

   char name[256];

   stFace *pFaces;
   stVertex *pVertices;
   stTexCoord *pTexCoords;

   unsigned int totalFaces;
   unsigned int totalVertices;
   unsigned int totalTexCoords;
};

// 3DS Loader.
class C3DSObject
{
   public:
      C3DSObject() : totalMeshes(0), totalMaterials(0) {}
      ~C3DSObject() { Shutdown(); }

      // Load the entire file.
      bool LoadModel(char *fileName);

      // Deals with reading chunk headers.
      void ReadSubChunk(FILE *fp, stChunk *pChunk);
      void MoveToNextChunk(FILE *fp, stChunk *pChunk);
      int GetNextString(FILE *fp, char *str);
      void ReadChunk(FILE *fp, stChunk *pChunk);

      // Read different sections out of the file like vertex
      // positions, tex coords, faces, etc.
      void ReadMaterials(FILE *fp, stChunk *pChunk);
      void ReadDiffuse(FILE *fp, stChunk *pChunk);
      void ReadMeshMaterials(FILE *fp, stChunk *pChunk);
      void ReadFaces(FILE *fp, stChunk *pChunk);
      void ReadVertices(FILE *fp, stChunk *pChunk);
      void ReadTexCoords(FILE *fp, stChunk *pChunk);

      void Shutdown();

      // List of mesh objects if there are more than 1,
      // list of materials, and counters for each.
      std::vector<stMesh> meshList;
      std::vector<stMaterial> materialList;
      int totalMeshes;
      int totalMaterials;
};
#endif
C3DSObject.cpp
Code:
#include<stdio.h>
#include<math.h>
#include<string.h>
#include"C3DSObject.h"
#include"chunks.h"

bool C3DSObject::LoadModel(char *fileName)
{
   FILE *fp = NULL;
   stChunk primaryChunk;

   if(!fileName) return false;

   fp = fopen(fileName, "rb");
   if(!fp) return false;

   // The first chunk in the file is called the primary chunk.
   ReadChunk(fp, &primaryChunk);

   // This test will tell us if this is a 3DS file.
   if(primaryChunk.id != PRIMARY_ID) return false;

   // Recursively read the model file.
   ReadSubChunk(fp, &primaryChunk);
   fclose(fp);

   stVertex v1, v2;
   stVertex n;

   // This is used to create triangle normals.  If you want your
   // 3DS loader to support bump mapping, adding s and t tangents
   // below will do that for you.
   for(int i = 0; i < totalMeshes; i++)
      {
         for(unsigned int f = 0; f < meshList[i].totalFaces; f++)
            {
               stMesh *pMesh = &meshList[i];
               stFace *pFace = pMesh->pFaces;

               if(!pMesh || !pFace) continue;

               v1.x = pMesh->pVertices[pFace[f].indices[0]].x - pMesh->pVertices[pFace[f].indices[1]].x;
               v1.y = pMesh->pVertices[pFace[f].indices[0]].y - pMesh->pVertices[pFace[f].indices[1]].y;
               v1.z = pMesh->pVertices[pFace[f].indices[0]].z - pMesh->pVertices[pFace[f].indices[1]].z;

               v2.x = pMesh->pVertices[pFace[f].indices[1]].x - pMesh->pVertices[pFace[f].indices[2]].x;
               v2.y = pMesh->pVertices[pFace[f].indices[1]].y - pMesh->pVertices[pFace[f].indices[2]].y;
               v2.z = pMesh->pVertices[pFace[f].indices[1]].z - pMesh->pVertices[pFace[f].indices[2]].z;

               n.x = ((v1.y * v2.z) - (v1.z * v2.y));
               n.y = ((v1.z * v2.x) - (v1.x * v2.z));
               n.z = ((v1.x * v2.y) - (v1.y * v2.x));
               
               float len = 1 / (float)sqrt((n.x * n.x + n.y * n.y + n.z * n.z));
               n.x *= len; n.y *= len; n.z *= len;
           
               pFace[f].normal.x = n.x;
               pFace[f].normal.y = n.y;
               pFace[f].normal.z = n.z;
            }
      }

   return true;
}


void C3DSObject::ReadSubChunk(FILE *fp, stChunk *pChunk)
{
   stMesh mesh;
   stMesh *pMesh = NULL;
   stMaterial *pMat = NULL;
   stMaterial mat;
   char name[256];

   // Keep reading until we have finished reading this chunk.
   while(pChunk->bytesRead < pChunk->length)
      {
         // Read the next chunk.
         stChunk chunk;
         ReadChunk(fp, &chunk);

         // Depending on the chunk will depend on what
         // is being loaded.
         switch(chunk.id)
            {
               case EDIT3DS:
                  // Read the next chunk to get the actual data.
                  ReadSubChunk(fp, &chunk);
                  break;

               case NAMED_OBJECT:
                  // Add a new mesh object to the list.
                  meshList.push_back(mesh);
                  totalMeshes++;

                  // Load mesh data.
                  chunk.bytesRead += GetNextString(fp, name);
                  pMesh = &(meshList[totalMeshes - 1]);
                  strcpy(pMesh->name, name);

                  ReadSubChunk(fp, &chunk);
                  break;

               case OBJ_MESH:
                  // Read the next chunk to get the actual data.
                  ReadSubChunk(fp, &chunk);
                  break;

               case MATERIAL:
                  // Add a new material to the list then read it.
                  materialList.push_back(mat);
                  totalMaterials++;

                  ReadSubChunk(fp, &chunk);
                  break;

               case MAT_NAME:
                  // Read materials name and save it.
                  chunk.bytesRead += GetNextString(fp, name);
                  pMat = &(materialList[totalMaterials - 1]);
                  strcpy(pMat->name, name);
                  break;

               case MAT_TEXFLNM:
                  // Read texture filename and save it.
                  chunk.bytesRead += GetNextString(fp, name);
                  pMat = &(materialList[totalMaterials - 1]);
                  strcpy(pMat->textureName, name);
                  break;

               case MAT_DIFFUSE:
                  // Read diffuse colors.
                  ReadDiffuse(fp, &chunk);
                  break;

               case MAT_TEXMAP:
                  // Read the next chunk to get the actual data.
                  ReadSubChunk(fp, &chunk);
                  break;

               case MESH_FACES:
                  // Read triangles.
                  ReadFaces(fp, &chunk);
                  break;

               case MESH_VERTICES:
                  // Read vertex points.
                  ReadVertices(fp, &chunk);
                  break;
               
               case MESH_TEX_VERT:
                  // Read texture coords.
                  ReadTexCoords(fp, &chunk);
                  break;
               
               case MESH_MATER:
                  // Read material indices.
                  ReadMeshMaterials(fp, &chunk);
                  break;

               default:
                  // Skip chunk cuz we don't support
                  // whatever is here.
                  MoveToNextChunk(fp, &chunk);
                  break;
            }

         // Add to the total bytes loaded.
         pChunk->bytesRead += chunk.length;
      }
}


void C3DSObject::MoveToNextChunk(FILE *fp, stChunk *pChunk)
{
   int buff[50000];
   // Skip a chunks data.
   fread(buff, 1, pChunk->length - pChunk->bytesRead, fp);
}


int C3DSObject::GetNextString(FILE *fp, char *str)
{
   char buff[100] = { 0 };
   int index = 0;

   // Read an entire string.
   fread(buff, 1, 1, fp);
   while(*(buff + index) != 0)
      {
         index++;
         fread(buff + index, 1, 1, fp);
      }

   // Save the string and return the size of the string.
   strcpy(str, buff);
   return strlen(buff) + 1;
}


void C3DSObject::ReadChunk(FILE *fp, stChunk *pChunk)
{
   if(!pChunk) return;

   // Read chunk header.
   pChunk->bytesRead = fread(&pChunk->id, 1, 2, fp);
   pChunk->bytesRead += fread(&pChunk->length, 1, 4, fp);
}


void C3DSObject::ReadDiffuse(FILE *fp, stChunk *pChunk)
{
   stColor color;
   char header[6];

   // Read a color value.
   pChunk->bytesRead += fread(header, 1, 6, fp);
   pChunk->bytesRead += fread(&color, 1, 3, fp);

   // Save this color.
   stMaterial *mat = &(materialList[totalMaterials - 1]);
   mat->color.r = color.r;
   mat->color.g = color.g;
   mat->color.b = color.b;

   // Skip the rest of the chunk.
   MoveToNextChunk(fp, pChunk);
}


void C3DSObject::ReadMeshMaterials(FILE *fp, stChunk *pChunk)
{
   char name[256];
   int matId = 0;
   unsigned short totalMatIndices = 0;
   unsigned short *pMatIndices = NULL;

   // Read material name and total.
   pChunk->bytesRead += GetNextString(fp, name);
   pChunk->bytesRead += fread(&totalMatIndices, 1, 2, fp);

   // Allocate the material indices.
   pMatIndices = new unsigned short[totalMatIndices];

   // Read indices.
   pChunk->bytesRead += fread(pMatIndices, 1, totalMatIndices *
                              sizeof(unsigned short), fp);

   // Look if this material already exist in the list.
   for(int i = 0; i < totalMaterials; i++)
      {
         if(strcmp(name, materialList[i].name) == 0)
            matId = i;
      }

   // Get the current mesh.
   stMesh *pMesh = &(meshList[totalMeshes - 1]);

   // Add the material id to all faces that uses it.
   for(int i = 0; i < totalMatIndices; i++)
      pMesh->pFaces[pMatIndices[i]].matId = matId;
}


void C3DSObject::ReadFaces(FILE *fp, stChunk *pChunk)
{
   unsigned int totalFaces;
   stFileFace *pFaces;

   // Read number of faces.
   pChunk->bytesRead += fread(&totalFaces, 1, 2, fp);

   // Read faces.
   pFaces = new stFileFace[totalFaces];
   pChunk->bytesRead += fread(pFaces, 1, totalFaces *
                              sizeof(stFileFace), fp);

   // Get current mesh and a pointer to its faces.
   stMesh *pMesh = &(meshList[totalMeshes - 1]);
   pMesh->pFaces = new stFace[totalFaces];
   pMesh->totalFaces = totalFaces;

   // Loop through and copy the face data.
   for(unsigned int i = 0; i < totalFaces; i++)
      {
         pMesh->pFaces[i].indices[0] = pFaces[i].indices[0];
         pMesh->pFaces[i].indices[1] = pFaces[i].indices[1];
         pMesh->pFaces[i].indices[2] = pFaces[i].indices[2];
      }

   // Delete temp memory.
   delete[] pFaces;

   // Read the next chunk.
   ReadSubChunk(fp, pChunk);
}

void C3DSObject::ReadVertices(FILE *fp, stChunk *pChunk)
{
   unsigned int totalVertices;
   stVertex *pVertices;

   // Read number of vertices.
   pChunk->bytesRead += fread(&totalVertices, 1, 2, fp);

   // Load vertex points.
   pVertices = new stVertex[totalVertices];
   pChunk->bytesRead += fread(pVertices, 1, totalVertices *
                              sizeof(stVertex), fp);

   // Get the current mesh and save the data to it.
   stMesh *pMesh = &(meshList[totalMeshes - 1]);
   pMesh->pVertices = pVertices;
   pMesh->totalVertices = totalVertices;

   // Skip any data left in this chunk.
   MoveToNextChunk(fp, pChunk);
}

void C3DSObject::ReadTexCoords(FILE *fp, stChunk *pChunk)
{
   unsigned int totalTexCoords;
   stTexCoord *pTexCoords;

   // Read total.
   pChunk->bytesRead += fread(&totalTexCoords, 1, 2, fp);

   // Read all the tex coords.
   pTexCoords = new stTexCoord[totalTexCoords];
   pChunk->bytesRead += fread(pTexCoords, 1, totalTexCoords *
                              sizeof(stTexCoord), fp);

   // Get the current mesh and save the data to it.
   stMesh *pMesh = &(meshList[totalMeshes - 1]);
   pMesh->pTexCoords = pTexCoords;

   // Skip anything that is left.
   MoveToNextChunk(fp, pChunk);
}


void C3DSObject::Shutdown()
{
   // Loop through and make sure all data is released.
   for(int i = 0; i < totalMeshes; i++)
      {
         if(meshList[i].pFaces)
            {
               delete[] meshList[i].pFaces;
               meshList[i].pFaces = NULL;
            }

         if(meshList[i].pVertices)
            {
               delete[] meshList[i].pVertices;
               meshList[i].pVertices = NULL;
            }

         if(meshList[i].pTexCoords)
            {
               delete[] meshList[i].pTexCoords;
               meshList[i].pTexCoords = NULL;
            }

         meshList[i].totalFaces = 0;
         meshList[i].totalVertices = 0;
         meshList[i].totalTexCoords = 0;
      }

   // Free the list.
   for(std::vector<stMesh>::iterator itMesh = meshList.begin(); itMesh != meshList.end();)
      {
         meshList.erase(itMesh);
      }

   for(std::vector<stMaterial>::iterator itMat = materialList.begin(); itMat != materialList.end();)
      {
         materialList.erase(itMat);
      }

   totalMeshes = 0;
   totalMaterials = 0;
}
3DSLoader.cpp
Code:
#define WIN32_LEAN_AND_MEAN// Trims down the libraries.
#define VC_LEANMEAN        // Trims even further.

#include<windows.h>
#include<gl/gl.h>
#include<gl/glu.h>
#include"C3DSObject.h"

// Function prototypes...
bool InitializeGL();
void RenderScene();
void Shutdown();

// Global HDC used in the RenderScene() to swap buffers.
HDC g_HDC;

float xRotation = 0;
float yRotation = 0;

// Light properties for the diffuse light, specular light, and light position.
float diffuseLight[] = {0.8f, 0.8f, 0.8f, 1.0f};
float specularLight[] = {1.0f, 1.0f, 1.0f, 1.0f};

// 3DS model we'll be loading.
C3DSObject Model;
C3DSObject hold;

void SetupPixelFormat(HDC hDC)
{
   int nPixelFormat;

   static PIXELFORMATDESCRIPTOR pfd = {
         sizeof(PIXELFORMATDESCRIPTOR),   // size of structure.
         1,                               // always 1.
         PFD_DRAW_TO_WINDOW |             // support window
         PFD_SUPPORT_OPENGL |             // support OpenGl
         PFD_DOUBLEBUFFER,                // support double buffering
         PFD_TYPE_RGBA,                   // support RGBA
         16,                              // bit color mode
         0, 0, 0, 0, 0, 0,                // ignore color bits
         0,                               // no alpha buffer
         0,                               // ignore shift bit
         0,                               // no accumulation buffer
         0, 0, 0, 0,                      // ignore accumulation bits.
         16,                              // number of depth buffer bits.
         0,                               // number of stencil buffer bits.
         0,                               // 0 means no auxiliary buffer
         PFD_MAIN_PLANE,                  // The main drawing plane
         0,                               // this is reserved
         0, 0, 0 };                       // layer masks ignored.

   // this chooses the best pixel format and returns index.
   nPixelFormat = ChoosePixelFormat(hDC, &pfd);

   // This set pixel format to device context.
   SetPixelFormat(hDC, nPixelFormat, &pfd);
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
   static HGLRC hRC;             // Rendering context.
   static HDC hDC;               // Device context.
   int width, height;            // The window width and height.
   static POINT oldMousePos;     // Last mouse position.
   static POINT currentMousePos; // Current mouse position.
   static bool isMouseActive;    // Is the left mouse button down.

   switch(message)
      {
         case WM_CREATE:                     // Windows creation.
            hDC = GetDC(hwnd);               // This gets the device context for our window.
            g_HDC = hDC;                     // Assigns the global device context to this one.
            SetupPixelFormat(hDC);           // Call the pixel format function.

            hRC = wglCreateContext(hDC);     // Creates the rendering context.
            wglMakeCurrent(hDC, hRC);        // Makes the rendering context.
            return 0;
            break;

         case WM_CLOSE:                      // Close message.
         case WM_DESTROY:
            wglMakeCurrent(hDC, NULL);
            wglDeleteContext(hRC);           // Deletes the rendering context.

            PostQuitMessage(0);              // Says close the program.
            return 0;
            break;

         case WM_SIZE:                       // re-size message.
            height = HIWORD(lParam);         // This gets the height of the window.
            width = LOWORD(lParam);          // This gets the width of the window.

            if(height==0)                    // we don't want it to be possible for a
               {                             // height of 0.  If it is 0 me make it 1.
                  height = 1;
               }

            glViewport(0, 0, width, height); // resets the viewport to new dimensions.
            glMatrixMode(GL_PROJECTION);     // Sets the projection matrix.
            glLoadIdentity();                // Reset the modelview matrix.

            // calculate the aspect ratio of the window.
            gluPerspective(45.0f, (GLfloat)width/(GLfloat)height, 0.1f, 1000.0f);

            glMatrixMode(GL_MODELVIEW);      // Sets the projection matrix.
            glLoadIdentity();                // Reset the modelview matrix.

            return 0;
            break;

         case WM_KEYDOWN:
            switch(wParam)
               {
                  // Close the app if the user presses escape.
                  case VK_ESCAPE:
                     PostQuitMessage(0);
                     break;

                  default:
                     break;
               }
            break;

         case WM_LBUTTONDOWN:
            oldMousePos.x = currentMousePos.x = LOWORD (lParam);
            oldMousePos.y = currentMousePos.y = HIWORD (lParam);
            isMouseActive = true;
            break;

         case WM_LBUTTONUP:
            isMouseActive = false;
            break;

         case WM_MOUSEMOVE:
            currentMousePos.x = LOWORD (lParam);
            currentMousePos.y = HIWORD (lParam);

            if(isMouseActive)
               {
                  xRotation -= (currentMousePos.x - oldMousePos.x);
                  yRotation -= (currentMousePos.y - oldMousePos.y);
               }

            oldMousePos.x = currentMousePos.x;
            oldMousePos.y = currentMousePos.y;
            break;

         default: // Always have a default just in case.
            break;
      }

   // What this does is pass all of the unhandled messages to DefWindowProc.
   return (DefWindowProc(hwnd, message, wParam, lParam));
}


int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
   MSG msg;                // A message variable.
   WNDCLASSEX windowClass; // Your Window class.
   HWND hwnd;              // The Window handle.
   bool isFinished;        // True then exit.

   // This is the Window class.
   windowClass.cbSize = sizeof(WNDCLASSEX);        // size of the WNDCLASSEX structure.
   windowClass.style = CS_HREDRAW | CS_VREDRAW;    // style of the window.
   windowClass.lpfnWndProc = WndProc;              // Address to the windows procedure.
   windowClass.cbClsExtra = 0;                     // Extra class information.
   windowClass.cbWndExtra = 0;                     // Extra window information.
   windowClass.hInstance = hInstance;              // Handle of application Instance.
   // Handle of application Icon.
   windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
   windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);// mouse cursor
   windowClass.hbrBackground = NULL;               // background color.
   windowClass.lpszMenuName = NULL;                // name of the main menu.
   windowClass.lpszClassName = "UltimateGameProgrammingClass";// window class name.
   // icon when minimized.
   windowClass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);

   // You must register you class with Windows.
   if(!RegisterClassEx(&windowClass)) return 0;

   // Create window...
   hwnd = CreateWindowEx(NULL,// The extended window style.
                        "UltimateGameProgrammingClass",// window Class name.
                        "3DS Loader Demo - By the Programming Ace.",// window name.
                        WS_OVERLAPPEDWINDOW | WS_VISIBLE |// The window style.
                        WS_SYSMENU | WS_CLIPCHILDREN,// window style.
                        100, 100,// window x, y coordinate.
                        640, 480,// window width and height.
                        NULL,// handle to parent window.
                        NULL,// menu.
                        hInstance,// handle to app instance.
                        NULL);   // pointer to window creation data.
   
   // If there was an error with creating the window, then close the program.
   if(!hwnd) return 0;

   ShowWindow(hwnd, nShowCmd); // This shows the window.
   UpdateWindow(hwnd);        // This forces a paint message.

   isFinished = false;        // False = running, True = not running.

   // If initialize fail (return false), then we don't want the program to run.
   if(!InitializeGL()) isFinished = true;

   // This is the messsage loop.
   while(!isFinished)
      {
         if(PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
            {
               // If a quit message is received then stop rendering and quit the app.
               if(msg.message == WM_QUIT)
                  {
                     isFinished = true;
                  }

               TranslateMessage(&msg);
               DispatchMessage(&msg);
            }
         else
            {
               RenderScene();
            }
      }

   Shutdown();

   return (int)msg.wParam;
}


bool InitializeGL()
{
   glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
   glEnable(GL_DEPTH_TEST);
   glShadeModel(GL_SMOOTH);
   glEnable(GL_LIGHTING);
   glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);

   // Set up the information for the first light and set it in GL_LIGHT0.
   glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight);
   glLightfv(GL_LIGHT0, GL_SPECULAR, specularLight);

   // Enable the first light.
   glEnable(GL_LIGHT0);

   // Set up the material information for our objects.
   glEnable(GL_COLOR_MATERIAL);
   glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
   glMaterialfv(GL_FRONT, GL_SPECULAR, specularLight);
   glMateriali(GL_FRONT, GL_SHININESS, 128);

   // Load the light wave model file into our class.
   if(!Model.LoadModel("ball.3ds")) return false;

   return true;
}

void RenderScene()
{
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
   glLoadIdentity();

   glTranslatef(0.0f, 0.0f, -4.0f);
   glRotatef(-yRotation, 1.0f, 0.0f, 0.0f);
   glRotatef(-xRotation, 0.0f, 1.0f, 0.0f);

   // Loop through all meshes that are apart of the file
   // and render them.
   for(int i = 0; i < Model.totalMeshes; i++)
      {
         glBegin(GL_TRIANGLES);

         // Draw each triangle of this mesh.
         for(unsigned int f = 0; f < Model.meshList[i].totalFaces; f++)
            {
               // Get pointers to make the below code cleaner.
               stMesh *pMesh = &Model.meshList[i];
               stFace *pFace = pMesh->pFaces;
               stTexCoord *pTexCoord = pMesh->pTexCoords;

               // If one or both or NULL, we got a problem.
               if(!pMesh || !pFace) continue;

               // Draw the triangle.
               glNormal3f(pFace[f].normal.x, pFace[f].normal.y,
                          pFace[f].normal.z);

               if(pTexCoord) glTexCoord2f(pTexCoord[pFace[f].indices[0]].tu, pTexCoord[pFace[f].indices[0]].tv);
               glVertex3f(pMesh->pVertices[pFace[f].indices[0]].x,
                          pMesh->pVertices[pFace[f].indices[0]].y,
                          pMesh->pVertices[pFace[f].indices[0]].z);

               if(pTexCoord) glTexCoord2f(pTexCoord[pFace[f].indices[1]].tu, pTexCoord[pFace[f].indices[1]].tv);
               glVertex3f(pMesh->pVertices[pFace[f].indices[1]].x,
                          pMesh->pVertices[pFace[f].indices[1]].y,
                          pMesh->pVertices[pFace[f].indices[1]].z);

               if(pTexCoord) glTexCoord2f(pTexCoord[pFace[f].indices[2]].tu, pTexCoord[pFace[f].indices[2]].tv);
               glVertex3f(pMesh->pVertices[pFace[f].indices[2]].x,
                          pMesh->pVertices[pFace[f].indices[2]].y,
                          pMesh->pVertices[pFace[f].indices[2]].z);
            }
         glEnd();
      }

   SwapBuffers(g_HDC);
}

void Shutdown()
{
   // Release all resources.
   Model.Shutdown();
}

Kaapec vinjsh uzmet shaadu logu kad meginu palaist programmu:

Vinjs uzmet logu Microsoft Visual C++ Runtime Library.
Runtime error!
Back to top
View user's profile Send e-mail
Display posts from previous:   
dev.gamez.lv Forum Index -> Grafikas programmēšana un teorija All times are GMT + 2 Hours
Goto page 1, 2  Next
Page 1 of 2

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group