int main() { //그래프 생성 Graph* G = CreateGraph(); // 정점 생성 Vertex* V1 = CreateVertex('1'); Vertex* V2 = CreateVertex('2'); Vertex* V3 = CreateVertex('3'); Vertex* V4 = CreateVertex('4'); Vertex* V5 = CreateVertex('5'); // 그래프에 정점을 추가 AddVertex(G, V1); AddVertex(G, V2); AddVertex(G, V3); AddVertex(G, V4); AddVertex(G, V5); // 정점과 정점을 간선으로 잇기 AddEdge(V1, CreateEdge(V1, V2, 0)); AddEdge(V1, CreateEdge(V1, V3, 0)); AddEdge(V1, CreateEdge(V1, V4, 0)); AddEdge(V1, CreateEdge(V1, V5, 0)); AddEdge(V2, CreateEdge(V2, V1, 0)); AddEdge(V2, CreateEdge(V2, V2, 0)); AddEdge(V2, CreateEdge(V2, V5, 0)); AddEdge(V3, CreateEdge(V3, V1, 0)); AddEdge(V3, CreateEdge(V3, V2, 0)); AddEdge(V4, CreateEdge(V4, V1, 0)); AddEdge(V4, CreateEdge(V4, V5, 0)); AddEdge(V5, CreateEdge(V5, V1, 0)); AddEdge(V5, CreateEdge(V5, V2, 0)); AddEdge(V5, CreateEdge(V5, V4, 0)); PrintGraph(G); // 그래프 소멸 DestroyGraph(G); return 0; }
void CD3DGUIWndRect::SetColor(DWORD Color) { if(m_VertexColor!=Color) { m_VertexColor=Color; CreateVertex(); } }
int main( void ) { /* 그래프 생성 */ Graph* G = CreateGraph(); /* 정점 생성 */ Vertex* V1 = CreateVertex( '1' ); Vertex* V2 = CreateVertex( '2' ); Vertex* V3 = CreateVertex( '3' ); Vertex* V4 = CreateVertex( '4' ); Vertex* V5 = CreateVertex( '5' ); /* 그래프에 정점을 추가 */ AddVertex( G, V1 ); AddVertex( G, V2 ); AddVertex( G, V3 ); AddVertex( G, V4 ); AddVertex( G, V5 ); /* 정점과 정점을 간선으로 잇기 */ AddEdge( V1, CreateEdge(V1, V2, 0) ); AddEdge( V1, CreateEdge(V1, V3, 0) ); AddEdge( V1, CreateEdge(V1, V4, 0) ); AddEdge( V1, CreateEdge(V1, V5, 0) ); AddEdge( V2, CreateEdge(V2, V1, 0) ); AddEdge( V2, CreateEdge(V2, V3, 0) ); AddEdge( V2, CreateEdge(V2, V5, 0) ); AddEdge( V3, CreateEdge(V3, V1, 0) ); AddEdge( V3, CreateEdge(V3, V2, 0) ); AddEdge( V4, CreateEdge(V4, V1, 0) ); AddEdge( V4, CreateEdge(V4, V5, 0) ); AddEdge( V5, CreateEdge(V5, V1, 0) ); AddEdge( V5, CreateEdge(V5, V2, 0) ); AddEdge( V5, CreateEdge(V5, V4, 0) ); PrintGraph( G ); /* 그래프 소멸 */ DestroyGraph( G ); return 0; }
void CD3DGUIWndRect::SetSize(FLOAT Width,FLOAT Height) { if(m_Rect.Width()!=Width||m_Rect.Height()!=Height) { m_Rect.SetSize(Width,Height); CreateVertex(); } }
void CD3DGUIWndRect::SetUV(FLOAT_RECT * pUVRect) { if(m_TextureUV!=*pUVRect) { m_TextureUV=*pUVRect; CreateVertex(); } }
void CD3DGUIWndRect::SetRect(FLOAT_RECT * pRect) { if(m_Rect!=*pRect) { m_Rect=*pRect; CreateVertex(); } }
void CD3DGUIWndRect::SetPos(FLOAT X,FLOAT Y) { if(m_Rect.left!=X||m_Rect.top!=Y) { m_Rect.SetPos(X,Y); CreateVertex(); } }
bool tdnMesh::LoadTDNM(FILE* file, const char* fileName) { unsigned int vertexSize( sizeof( MESHVERTEX2 ) ); // 頂点読み込み numVertexes = 0; fread_s( &numVertexes, sizeof( numVertexes ), sizeof( numVertexes ), 1, file ); delete[] vertexArray; vertexArray = new MESHVERTEX2[numVertexes]; fread_s( vertexArray, vertexSize * numVertexes, vertexSize * numVertexes, 1, file ); if ( !CreateVertex( numVertexes, sizeof( MESHVERTEX2 ), vertexArray ) ) return false; // インデックス設定 DWORD* indexArray = new DWORD[numVertexes]; for ( unsigned int i = 0; i < numVertexes; i++ ) { indexArray[i] = i; } CreateIndexes( numVertexes, indexArray ); delete[]indexArray; // 面数 numFaces = numVertexes / 3; // 頂点情報 D3DVERTEXELEMENT9 declAry[] = { { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, // 位置 { 0, sizeof( float ) * 3, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, // 法線 { 0, sizeof( float ) * 6, D3DDECLTYPE_UBYTE4N, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 }, // 頂点色 { 0, sizeof( float ) * 6 + sizeof( COLOR ), D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, // UV座標 D3DDECL_END() }; CreateDeclaration( sizeof( MESHVERTEX2 ), declAry ); // テクスチャ読み込み std::string workFileName = fileName; unsigned int filePathLength = workFileName.find_last_of('/'); if (filePathLength == std::string::npos) filePathLength = workFileName.find_last_of('\\'); workFileName = workFileName.substr(0, filePathLength + 1); size_t textureNameLen( 0 ); fread_s( &textureNameLen, sizeof( size_t ), sizeof( size_t ), 1, file ); delete[] textureName; textureName = new char[textureNameLen + 1]; fread_s( textureName, textureNameLen + 1, textureNameLen, 1, file ); textureName[textureNameLen] = '\0'; workFileName += textureName; texture = tdnTexture::Load(workFileName.c_str()); return true; }
int R3Mesh:: ReadImage(const char *filename) { // Create a mesh by reading an image file, // constructing vertices at (x,y,luminance), // and connecting adjacent pixels into faces. // That is, the image is interpretted as a height field, // where the luminance of each pixel provides its z-coordinate. // Read image R2Image *image = new R2Image(); if (!image->Read(filename)) return 0; // Create vertices and store in arrays R3MeshVertex ***vertices = new R3MeshVertex **[image->Width() ]; for (int i = 0; i < image->Width(); i++) { vertices[i] = new R3MeshVertex *[image->Height() ]; for (int j = 0; j < image->Height(); j++) { double luminance = image->Pixel(i, j).Luminance(); double z = luminance * image->Width(); R3Point position((double) i, (double) j, z); R2Point texcoords((double) i, (double) j); vertices[i][j] = CreateVertex(position, R3zero_vector, texcoords); } } // Create faces vector<R3MeshVertex *> face_vertices; for (int i = 1; i < image->Width(); i++) { for (int j = 1; j < image->Height(); j++) { face_vertices.clear(); face_vertices.push_back(vertices[i-1][j-1]); face_vertices.push_back(vertices[i][j-1]); face_vertices.push_back(vertices[i][j]); CreateFace(face_vertices); face_vertices.clear(); face_vertices.push_back(vertices[i-1][j-1]); face_vertices.push_back(vertices[i][j]); face_vertices.push_back(vertices[i-1][j]); CreateFace(face_vertices); } } // Delete vertex arrays for (int i = 0; i < image->Width(); i++) delete [] vertices[i]; delete [] vertices; // Delete image delete image; // Return success return 1; }
int main() { Graph g; g = Initialize(VERTEXNUM); CreateVertex(g, 1); CreateVertex(g, 2); CreateVertex(g, 3); CreateVertex(g, 4); CreateEdge(g, 1, 2); CreateEdge(g, 2, 3); CreateEdge(g, 3, 2); CreateEdge(g, 3, 1); CreateEdge(g, 3, 4); Unweighted(g, 1, VERTEXNUM); DestoryGraph(g, VERTEXNUM); return 0; }
bool tdnMesh::Create( const CreateData &data ) { if ( CreateVertex( data.numVertexes, data.vertexSize, data.vertexArray ) == false ) return false; if ( data.numIndexes != 0 && data.indexArray != nullptr ) if ( CreateIndexes( data.numIndexes, data.indexArray ) == false ) return false; if ( data.streamSize != 0 && data.streamArray != nullptr && data.numStream != 0 ) if ( CreateStream( data.numStream, data.streamSize, data.streamArray ) == false ) return false; if ( CreateDeclaration( data.vertexSize, data.decl ) == false ) return false; numFaces = data.numIndexes / 3; return true; }
bool EpaPolyhedron::Expand( const btPoint3& wSupportPoint, const btPoint3& wSupportPointOnA, const btPoint3& wSupportPointOnB, EpaFace* pFace, std::list< EpaFace* >& newFaces ) { EPA_DEBUG_ASSERT( !pFace->m_deleted ,"Face is already deleted!" ); EPA_DEBUG_ASSERT( newFaces.empty() ,"NewFaces list must be empty!" ); EPA_DEBUG_ASSERT( !pFace->m_deleted ,"Cannot expand deleted face!" ); // wSupportPoint must be front of face's plane used to do the expansion #ifdef EPA_POLYHEDRON_USE_PLANES btScalar dist = pFace->m_planeNormal.dot( wSupportPoint ) + pFace->m_planeDistance; if ( dist <= PLANE_THICKNESS ) { return false; } #endif std::list< EpaHalfEdge* > coneBaseEdges; DeleteVisibleFaces( wSupportPoint, pFace, coneBaseEdges ); EPA_DEBUG_ASSERT( ( coneBaseEdges.size() >= 3 ) ,"Cone base must have at least 3 edges!" ); EpaVertex* pConeAppex = CreateVertex( wSupportPoint, wSupportPointOnA, wSupportPointOnB ); EPA_DEBUG_ASSERT( pConeAppex ,"Failed to create vertex!" ); CreateCone( pConeAppex, coneBaseEdges, newFaces ); // Initialize new faces std::list< EpaFace* >::iterator newFacesItr( newFaces.begin() ); while ( newFacesItr != newFaces.end() ) { EpaFace* pNewFace = *newFacesItr; if ( !pNewFace->Initialize() ) { return false; } ++newFacesItr; } return true; }
WOGPipe* OGLevelConfig::CreatePipe(const QDomElement &element) { WOGPipe* pipe = new WOGPipe; pipe->id = element.attribute("id"); pipe->depth = element.attribute("depth").toFloat(); pipe->type = element.attribute("type"); pipe->vertex = new QList<QPointF>; QDomNode node = element.firstChild(); while (!node.isNull()) { pipe->vertex->append(CreateVertex(node.toElement())); node = node.nextSibling(); } return pipe; }
CD3DGUIWndRect::CD3DGUIWndRect(): CD3DObject(), m_TextureUV(0.0f,0.0f,100.0f,100.0f) { m_SubMesh.GetVertexFormat().FVF=D3DFVF_RECTVERTEX; m_SubMesh.GetVertexFormat().VertexSize=sizeof(RECTVERTEX); m_SubMesh.GetVertexFormat().IndexSize=sizeof(WORD); m_SubMesh.SetVertexCount(4); m_SubMesh.SetPrimitiveType(D3DPT_TRIANGLESTRIP); m_SubMesh.SetPrimitiveCount(2); m_SubMesh.SetVertices((BYTE *)m_Vertexs); m_SubMesh.AllocVertexBufferR(); m_SubMesh.SetRenderBufferUsed(CD3DSubMesh::BUFFER_USE_CUSTOM); m_VertexColor=D3DCOLOR_XRGB(255, 255, 255); Restore(); CreateVertex(); }
BOOL CVideoRect::Create(LPCTSTR FileName,bool ForceLoadDirectVobSub) { if(m_pRender==NULL) return FALSE; Destory(); m_SubMesh.GetMaterial().ClearAllTexture(); m_pVideoTexture=new CD3DVideoTexture(); m_pVideoTexture->SetManager(m_pRender->GetDevice()->GetTextureManager()); m_pVideoTexture->EnableForceLoadVobSub(ForceLoadDirectVobSub); m_SubMesh.GetMaterial().AddTexture(m_pVideoTexture,0,"",""); m_pVideoTexture->AddUseRef(); CD3DFX * pFX=m_pRender->GetDevice()->GetFXManager()-> LoadFXFromMemory("DefaultVideoFX",DEFAULT_VIDEO_FX,(int)strlen(DEFAULT_VIDEO_FX)); if(pFX) { m_SubMesh.GetMaterial().SetFX(pFX); } if(!m_pVideoTexture->Create(FileName)) { m_pVideoTexture->Destory(); return FALSE; } m_pRender->GetDevice()->GetTextureManager()->AddTexture(m_pVideoTexture,m_pVideoTexture->GetName()); //int Width,Height; //m_pVideoTexture->GetVideoSize(Width,Height); //m_Rect.left=0; //m_Rect.top=0; //m_Rect.right=Width; //m_Rect.bottom=Height; CreateVertex(); SetVisible(true); return TRUE; }
HRESULT InitD3D( HWND hWnd ) { // Create the D3D object, which is needed to create the D3DDevice. if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) ) { MessageBoxA(NULL, "Create D3D9 object failed!", "Error", 0) ; return E_FAIL; } D3DPRESENT_PARAMETERS d3dpp; ZeroMemory( &d3dpp, sizeof(d3dpp) ); d3dpp.Windowed = TRUE; // use window mode, not full screen d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; // Create device if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &g_pd3dDevice ) ) ) { MessageBoxA(NULL, "Create D3D9 device failed!", "Error", 0) ; return E_FAIL; } // Disable lighting, since we didn't specify color for vertex g_pd3dDevice->SetRenderState( D3DRS_LIGHTING , FALSE ); // Create teapot D3DXCreateTeapot(g_pd3dDevice, &g_pTeapotMesh, NULL) ; // Create texture HRESULT hr = D3DXCreateTextureFromFile(g_pd3dDevice, "../Common/Media/tiny.jpg", &g_pTexture) ; if (FAILED(hr)) { return E_FAIL ; } CreateVertex() ; return S_OK; }
R3Mesh:: R3Mesh(const R3Mesh& mesh) : bbox(R3null_box) { // Create vertices for (int i = 0; i < mesh.NVertices(); i++) { R3MeshVertex *v = mesh.Vertex(i); CreateVertex(v->position, v->normal, v->texcoords); } // Create faces for (int i = 0; i < mesh.NFaces(); i++) { R3MeshFace *f = mesh.Face(i); vector<R3MeshVertex *> face_vertices; for (unsigned int j = 0; j < f->vertices.size(); j++) { R3MeshVertex *ov = f->vertices[j]; R3MeshVertex *nv = Vertex(ov->id); face_vertices.push_back(nv); } CreateFace(face_vertices); } }
HRESULT CDirect3D::RestoreDeviceObjects(void) { unsigned int vertexbuffersize = sizeof(TLVERTEX) * 4; preProcess = false; #if C_D3DSHADERS if(psActive) { // Set up pixel shaders LoadPixelShader(); if(psEffect && psEffect->hasPreprocess()) { #if LOG_D3D LOG_MSG("D3D:Pixel shader preprocess active"); #endif preProcess = true; vertexbuffersize = sizeof(TLVERTEX) * 8; } } #endif // Initialize vertex pD3DDevice9->SetFVF(D3DFVF_TLVERTEX); // Create vertex buffer if(FAILED(pD3DDevice9->CreateVertexBuffer(vertexbuffersize, D3DUSAGE_WRITEONLY, D3DFVF_TLVERTEX, D3DPOOL_MANAGED, &vertexBuffer, NULL))) { LOG_MSG("D3D:Failed to create Vertex Buffer"); return E_FAIL; } // Lock vertex buffer and set vertices CreateVertex(); pD3DDevice9->SetStreamSource(0, vertexBuffer, 0, sizeof(TLVERTEX)); // Turn off culling pD3DDevice9->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); // Turn off D3D lighting pD3DDevice9->SetRenderState(D3DRS_LIGHTING, false); // Turn off the zbuffer pD3DDevice9->SetRenderState(D3DRS_ZENABLE, false); CreateDisplayTexture(); SetupSceneScaled(); if(!psActive) { pD3DDevice9->SetTexture(0, lpTexture); // Disable Shaders pD3DDevice9->SetVertexShader(0); pD3DDevice9->SetPixelShader(0); pD3DDevice9->SetTransform(D3DTS_PROJECTION, &m_matProj); pD3DDevice9->SetTransform(D3DTS_VIEW, &m_matView); pD3DDevice9->SetTransform(D3DTS_WORLD, &m_matWorld); } #if C_D3DSHADERS else if(psEffect) { if(preProcess) { // Projection is (0,0,0) -> (1,1,1) D3DXMatrixOrthoOffCenterLH(&m_matPreProj, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f); // Align texels with pixels D3DXMatrixTranslation(&m_matPreView, -0.5f/dwTexWidth, 0.5f/dwTexHeight, 0.0f); // Identity for world D3DXMatrixIdentity(&m_matPreWorld); } else if(FAILED(psEffect->SetMatrices(m_matProj, m_matView, m_matWorld))) { LOG_MSG("D3D:Set matrices failed."); InvalidateDeviceObjects(); return E_FAIL; } } #endif return S_OK; }
int main( int argc, char** argv ) { InitTests(argc, argv); Describe("MeshBuffer") .use(dummySignalSandbox) .it("can be created, modified and freed.", [](){ MeshBuffer* buffer = CreateMeshBuffer(); AddVertexToMeshBuffer(buffer, CreateVertex(0,0,0)); AddIndexToMeshBuffer(buffer, 0); FreeMeshBuffer(buffer); }) .it("can be transformed.", [](){ MeshBuffer* buffer = CreateMeshBuffer(); AddVertexToMeshBuffer(buffer, CreateVertex(0,0,0)); AddIndexToMeshBuffer(buffer, 0); AddVertexToMeshBuffer(buffer, CreateVertex(0,1,0)); AddIndexToMeshBuffer(buffer, 1); const Vec3 v = {{1,0,0}}; const Mat4 m = TranslateMat4(Mat4Identity, v); TransformMeshBuffer(buffer, m); const Vertex* vertices = GetMeshBufferVertices(buffer); const Vec3 v1 = {{1,0,0}}; const Vec3 v2 = {{1,1,0}}; Require(vertices[0].position == v1); Require(vertices[1].position == v2); // TODO: Test if normal and tangent are transformed correctly. FreeMeshBuffer(buffer); }) .it("can be appended to another buffer.", [](){ MeshBuffer* a = CreateMeshBuffer(); AddVertexToMeshBuffer(a, CreateVertex(0,0,0)); AddIndexToMeshBuffer(a, 0); AddVertexToMeshBuffer(a, CreateVertex(0,1,0)); AddIndexToMeshBuffer(a, 1); MeshBuffer* b = CreateMeshBuffer(); AddVertexToMeshBuffer(b, CreateVertex(2,3,4)); AddIndexToMeshBuffer(b, 0); AddVertexToMeshBuffer(b, CreateVertex(5,6,7)); AddIndexToMeshBuffer(b, 1); AppendMeshBuffer(a, b, NULL); const Vertex* vertices = GetMeshBufferVertices(a); const VertexIndex* indices = GetMeshBufferIndices(a); Require(GetMeshBufferVertexCount(a) == 4); const Vec3 v2 = {{2,3,4}}; const Vec3 v3 = {{5,6,7}}; Require(vertices[2].position == v2); Require(vertices[3].position == v3); Require(GetMeshBufferIndexCount(a) == 4); Require(indices[2] == 2); Require(indices[3] == 3); FreeMeshBuffer(a); FreeMeshBuffer(b); }) .it("can be appended to another buffer while transforming it.", [](){ MeshBuffer* a = CreateMeshBuffer(); AddVertexToMeshBuffer(a, CreateVertex(0,0,0)); AddIndexToMeshBuffer(a, 0); AddVertexToMeshBuffer(a, CreateVertex(0,1,0)); AddIndexToMeshBuffer(a, 1); MeshBuffer* b = CreateMeshBuffer(); AddVertexToMeshBuffer(b, CreateVertex(2,3,4)); AddIndexToMeshBuffer(b, 0); AddVertexToMeshBuffer(b, CreateVertex(5,6,7)); AddIndexToMeshBuffer(b, 1); const Vec3 v = {{1,0,0}}; const Mat4 m = TranslateMat4(Mat4Identity, v); AppendMeshBuffer(a, b, &m); const Vertex* vertices = GetMeshBufferVertices(a); const VertexIndex* indices = GetMeshBufferIndices(a); Require(GetMeshBufferVertexCount(a) == 4); const Vec3 v2 = {{3,3,4}}; const Vec3 v3 = {{6,6,7}}; Require(vertices[2].position == v2); Require(vertices[3].position == v3); Require(GetMeshBufferIndexCount(a) == 4); Require(indices[2] == 2); Require(indices[3] == 3); // TODO: Test if normal and tangent are transformed correctly. FreeMeshBuffer(a); FreeMeshBuffer(b); }); return RunTests(); }
void Dijkstra(Graph* G, Vertex* StartVertex, Graph* ShortestPath ) { int i = 0; PQNode StartNode = { 0, StartVertex }; PriorityQueue* PQ = PQ_Create(10); Vertex* CurrentVertex = NULL; Edge* CurrentEdge = NULL; int* Weights = (int*) malloc( sizeof(int) * G->VertexCount ); Vertex** ShortestPathVertices = (Vertex**) malloc( sizeof(Vertex*) * G->VertexCount ); Vertex** Fringes = (Vertex**) malloc( sizeof(Vertex*) * G->VertexCount ); Vertex** Precedences = (Vertex**) malloc( sizeof(Vertex*) * G->VertexCount ); CurrentVertex = G->Vertices; while ( CurrentVertex != NULL ) { Vertex* NewVertex = CreateVertex( CurrentVertex->Data ); AddVertex( ShortestPath, NewVertex); Fringes[i] = NULL; Precedences[i] = NULL; ShortestPathVertices[i] = NewVertex; Weights[i] = MAX_WEIGHT; CurrentVertex = CurrentVertex->Next; i++; } PQ_Enqueue ( PQ, StartNode ); Weights[StartVertex->Index] = 0; while( ! PQ_IsEmpty( PQ ) ) { PQNode Popped; PQ_Dequeue(PQ, &Popped); CurrentVertex = (Vertex*)Popped.Data; Fringes[CurrentVertex->Index] = CurrentVertex; CurrentEdge = CurrentVertex->AdjacencyList; while ( CurrentEdge != NULL ) { Vertex* TargetVertex = CurrentEdge->Target; if ( Fringes[TargetVertex->Index] == NULL && Weights[CurrentVertex->Index] + CurrentEdge->Weight < Weights[TargetVertex->Index] ) { PQNode NewNode = { CurrentEdge->Weight, TargetVertex }; PQ_Enqueue ( PQ, NewNode ); Precedences[TargetVertex->Index] = CurrentEdge->From; Weights[TargetVertex->Index] = Weights[CurrentVertex->Index] + CurrentEdge->Weight; } CurrentEdge = CurrentEdge->Next; } } for ( i=0; i<G->VertexCount; i++ ) { int FromIndex, ToIndex; if ( Precedences[i] == NULL ) continue; FromIndex = Precedences[i]->Index; ToIndex = i; AddEdge( ShortestPathVertices[FromIndex], CreateEdge( ShortestPathVertices[FromIndex], ShortestPathVertices[ToIndex], Weights[i] ) ); } free( Fringes ); free( Precedences ); free( ShortestPathVertices ); free( Weights ); PQ_Destroy( PQ ); }
void draw_frame(Device *device) { SR_CHECK_ERROR("Begin RenderFrame"); RenderState &render_state = device->render_state(); vec4ub color(77, 77, 77, 255); render_state.ClearBuffer(true, true, false, color); //3d device->render_state().Set3D(); depth_fbo.Bind(); //fbo로 그리기. deferred같은거 구현하기 위해서 임시로 시도함 device->render_state().Set3D(); render_state.ClearBuffer(true, true, false, color); VertexList vert_list; vert_list.push_back(CreateVertex(vec3(-0.5, -0.5, 0), vec2(0, 0))); vert_list.push_back(CreateVertex(vec3(0.5, -0.5, 0), vec2(1, 0))); vert_list.push_back(CreateVertex(vec3(0, 0.5, 0), vec2(0.5, 1))); //vbo, ibo 적절히 만들기 if(vbo.Loaded() == false) { vbo.Init(vert_list); } if(wire_ibo.Loaded() == false) { IndexList index_list; index_list.push_back(0); index_list.push_back(1); index_list.push_back(1); index_list.push_back(2); index_list.push_back(2); index_list.push_back(0); wire_ibo.Init(index_list); } { //shader사용 선언이 가장 먼저 device->render_state().UseShader(color_shader); SR_CHECK_ERROR("UseShader"); mat4 mvp(1.0f); ShaderVariable mvp_var = color_shader.uniform_var(kMVPHandleName); SetUniformMatrix(mvp_var, mvp); vec4 color(1.0f); ShaderVariable const_color_var = color_shader.uniform_var(kConstColorHandleName); SetUniformVector(const_color_var, color); SR_CHECK_ERROR("SetVector"); color_shader.SetVertexList(vert_list); color_shader.DrawArrays(kDrawTriangles, vert_list.size()); color_shader.DrawArrays(kDrawTriangles, vbo); color_shader.DrawElements(kDrawLines, vbo, wire_ibo); } { //shader사용 선언이 가장 먼저 device->render_state().UseShader(simple_shader); TexturePtr tex = device->tex_mgr()->Get("sora"); device->render_state().UseTexture(*tex, 0); SR_CHECK_ERROR("UseShader"); mat4 mvp(1.0f); mvp = glm::rotate(mvp, 10.0f, vec3(0, 0, 1)); ShaderVariable mvp_var = simple_shader.uniform_var(kMVPHandleName); SetUniformMatrix(mvp_var, mvp); SR_CHECK_ERROR("SetMatrix"); simple_shader.SetVertexList(vert_list); simple_shader.DrawArrays(kDrawTriangles, vert_list.size()); } //일반 3d객체 그리기+카메라 회전 장착 { //set camera + projection float win_width = (float)device->render_state().win_width(); float win_height = (float)device->render_state().win_height(); glm::mat4 projection = glm::perspective(45.0f, win_width / win_height, 0.1f, 100.0f); float radius = 4; float cam_x = radius * cos(SR_DEG_2_RAD(aptitude)) * sin(SR_DEG_2_RAD(latitude)); float cam_y = radius * sin(SR_DEG_2_RAD(aptitude)); float cam_z = radius * cos(SR_DEG_2_RAD(aptitude)) * cos(SR_DEG_2_RAD(latitude)); vec3 eye(cam_x, cam_y, cam_z); vec3 center(0); vec3 up(0, 1, 0); glm::mat4 view = glm::lookAt(eye, center, up); glm::mat4 mvp(1.0f); mvp = projection * view; ShaderVariable mvp_var = simple_shader.uniform_var(kMVPHandleName); SetUniformMatrix(mvp_var, mvp); SR_CHECK_ERROR("SetMatrix"); GeometricObject<Vertex> mesh; //mesh.PointTeapot(0.05f); //mesh.WireTeapot(0.05f); //mesh.SolidTeapot(0.05f); //mesh.WireShpere(1, 16, 16); //mesh.PointShpere(1, 16, 16); //mesh.SolidSphere(1, 16, 16); //mesh.SolidCube(1, 1, 1); //mesh.WireCube(1, 1, 1); mesh.PointCube(1, 1, 1); //mesh.PointCylinder(1, 1, 2, 8, 8); //mesh.WireCylinder(1, 1, 2, 8, 8); mesh.SolidCylinder(1, 1, 2, 8, 8); //mesh.WireAxis(5); //mesh.SolidPlane(3); //mesh.WirePlane(3, 0.1f); //mesh.SolidTorus(1, 0.1); //mesh.SolidCone(2, 2); auto it = mesh.Begin(); auto endit = mesh.End(); for( ; it != endit ; ++it) { const DrawCmdData<Vertex> &cmd = *it; //앞면 뒷면 그리기를 허용/불가능 정보까지 내장해야 //뚜껑없는 원통 그리기가 편하다 if(cmd.disable_cull_face == true) { glDisable(GL_CULL_FACE); } simple_shader.SetVertexList(cmd.vertex_list); if(cmd.index_list.empty()) { simple_shader.DrawArrays(cmd.draw_mode, cmd.vertex_list.size()); } else { simple_shader.DrawElements(cmd.draw_mode, cmd.index_list); } if(cmd.disable_cull_face == true) { glEnable(GL_CULL_FACE); } } } depth_fbo.Unbind(); /* //fbo에 있는 내용을 적절히 그리기 { device->render_state().Set2D(); device->render_state().UseShader(simple_shader); ShaderVariable mvp_var = simple_shader.uniform_var(kMVPHandleName); mat4 world_mat(1.0f); SetUniformMatrix(mvp_var, world_mat); //device->render_state().UseTexture(depth_fbo.color_tex()); device->render_state().UseTexture(depth_fbo.depth_tex()); Vertex2DList vert_list; vert_list.push_back(CreateVertex2D(-1, -1, 0, 0)); vert_list.push_back(CreateVertex2D(1, -1, 1, 0)); vert_list.push_back(CreateVertex2D(1, 1, 1, 1)); vert_list.push_back(CreateVertex2D(-1, 1, 0, 1)); simple_shader.SetVertexList(vert_list); simple_shader.DrawArrays(kDrawTriangleFan, vert_list.size()); } */ null_post_effect.DrawScissor(depth_fbo.color_tex(), 0, 0, 320, 480); grayscale_post_effect.DrawScissor(depth_fbo.color_tex(), 320, 0, 320, 480); grayscale_post_effect.Draw(depth_fbo.color_tex(), 100, 100, 100, 100); SR_CHECK_ERROR("End RenderFrame"); }
bool EpaPolyhedron::Create( btPoint3* pInitialPoints, btPoint3* pSupportPointsOnA, btPoint3* pSupportPointsOnB, const int nbInitialPoints ) { #ifndef EPA_POLYHEDRON_USE_PLANES EPA_DEBUG_ASSERT( ( nbInitialPoints <= 4 ) ,"nbInitialPoints greater than 4!" ); #endif if ( nbInitialPoints < 4 ) { // Insufficient nb of points return false; } //////////////////////////////////////////////////////////////////////////////// #ifdef EPA_POLYHEDRON_USE_PLANES int nbDiffCoords[ 3 ] = { 0, 0, 0 }; bool* pDiffCoords = new bool[ 3 * nbInitialPoints ]; int i; for (i=0;i<nbInitialPoints*3;i++) { pDiffCoords[i] = false; } //::memset( pDiffCoords, 0, sizeof( bool ) * 3 * nbInitialPoints ); int axis; for ( axis = 0; axis < 3; ++axis ) { for ( int i = 0; i < nbInitialPoints; ++i ) { bool isDifferent = true; for ( int j = 0; j < i; ++j ) { if ( pInitialPoints[ i ][ axis ] == pInitialPoints[ j ][ axis ] ) { isDifferent = false; break; } } if ( isDifferent ) { ++nbDiffCoords[ axis ]; pDiffCoords[ axis * nbInitialPoints + i ] = true; } } if ( nbDiffCoords[ axis ] <= 1 ) { // The input is degenerate return false; } } int finalPointsIndices[ 4 ] = { -1, -1, -1, -1 }; int axisOrderIndices[ 3 ] = { 0, 1, 2 }; for ( i = 0; i < 2/*round( nbAxis / 2 )*/; ++i ) { if ( nbDiffCoords[ i ] > nbDiffCoords[ i + 1 ] ) { int tmp = nbDiffCoords[ i ]; nbDiffCoords[ i ] = nbDiffCoords[ i + 1 ]; nbDiffCoords[ i + 1 ] = tmp; tmp = axisOrderIndices[ i ]; axisOrderIndices[ i ] = axisOrderIndices[ i + 1 ]; axisOrderIndices[ i + 1 ] = tmp; } } int nbSuccessfullAxis = 0; // The axes with less different coordinates choose first int minsIndices[ 3 ] = { -1, -1, -1 }; int maxsIndices[ 3 ] = { -1, -1, -1 }; int finalPointsIndex = 0; for ( axis = 0; ( axis < 3 ) && ( nbSuccessfullAxis < 2 ); ++axis ) { int axisIndex = axisOrderIndices[ axis ]; btScalar axisMin = SIMD_INFINITY; btScalar axisMax = -SIMD_INFINITY; for ( int i = 0; i < 4; ++i ) { // Among the diff coords pick the min and max coords if ( pDiffCoords[ axisIndex * nbInitialPoints + i ] ) { if ( pInitialPoints[ i ][ axisIndex ] < axisMin ) { axisMin = pInitialPoints[ i ][ axisIndex ]; minsIndices[ axisIndex ] = i; } if ( pInitialPoints[ i ][ axisIndex ] > axisMax ) { axisMax = pInitialPoints[ i ][ axisIndex ]; maxsIndices[ axisIndex ] = i; } } } //assert( ( minsIndices[ axisIndex ] != maxsIndices[ axisIndex ] ) && // "min and max have the same index!" ); if ( ( minsIndices[ axisIndex ] != -1 ) && ( maxsIndices[ axisIndex ] != -1 ) && ( minsIndices[ axisIndex ] != maxsIndices[ axisIndex ] ) ) { ++nbSuccessfullAxis; finalPointsIndices[ finalPointsIndex++ ] = minsIndices[ axisIndex ]; finalPointsIndices[ finalPointsIndex++ ] = maxsIndices[ axisIndex ]; // Make the choosen points to be impossible for other axes to choose //assert( ( minsIndices[ axisIndex ] != -1 ) && "Invalid index!" ); //assert( ( maxsIndices[ axisIndex ] != -1 ) && "Invalid index!" ); for ( int i = 0; i < 3; ++i ) { pDiffCoords[ i * nbInitialPoints + minsIndices[ axisIndex ] ] = false; pDiffCoords[ i * nbInitialPoints + maxsIndices[ axisIndex ] ] = false; } } } if ( nbSuccessfullAxis <= 1 ) { // Degenerate input ? EPA_DEBUG_ASSERT( false ,"nbSuccessfullAxis must be greater than 1!" ); return false; } delete[] pDiffCoords; #endif ////////////////////////////////////////////////////////////////////////// #ifdef EPA_POLYHEDRON_USE_PLANES btVector3 v0 = pInitialPoints[ finalPointsIndices[ 1 ] ] - pInitialPoints[ finalPointsIndices[ 0 ] ]; btVector3 v1 = pInitialPoints[ finalPointsIndices[ 2 ] ] - pInitialPoints[ finalPointsIndices[ 0 ] ]; #else btVector3 v0 = pInitialPoints[ 1 ] - pInitialPoints[ 0 ]; btVector3 v1 = pInitialPoints[ 2 ] - pInitialPoints[ 0 ]; #endif btVector3 planeNormal = v1.cross( v0 ); planeNormal.normalize(); #ifdef EPA_POLYHEDRON_USE_PLANES btScalar planeDistance = pInitialPoints[ finalPointsIndices[ 0 ] ].dot( -planeNormal ); #else btScalar planeDistance = pInitialPoints[ 0 ].dot( -planeNormal ); #endif #ifdef EPA_POLYHEDRON_USE_PLANES bool pointOnPlane0 = btEqual( pInitialPoints[ finalPointsIndices[ 0 ] ].dot( planeNormal ) + planeDistance, PLANE_THICKNESS ); if (!pointOnPlane0) { EPA_DEBUG_ASSERT(0,"Point0 should be on plane!"); return false; } bool pointOnPlane1 = btEqual( pInitialPoints[ finalPointsIndices[ 1 ] ].dot( planeNormal ) + planeDistance, PLANE_THICKNESS ); if (!pointOnPlane1) { EPA_DEBUG_ASSERT(0,"Point1 should be on plane!"); return false; } bool pointOnPlane2 = btEqual( pInitialPoints[ finalPointsIndices[ 2 ] ].dot( planeNormal ) + planeDistance, PLANE_THICKNESS ); if (!pointOnPlane2) { EPA_DEBUG_ASSERT(0,"Point2 should be on plane!"); return false; } #endif #ifndef EPA_POLYHEDRON_USE_PLANES { if ( planeDistance > 0 ) { btVector3 tmp = pInitialPoints[ 1 ]; pInitialPoints[ 1 ] = pInitialPoints[ 2 ]; pInitialPoints[ 2 ] = tmp; tmp = pSupportPointsOnA[ 1 ]; pSupportPointsOnA[ 1 ] = pSupportPointsOnA[ 2 ]; pSupportPointsOnA[ 2 ] = tmp; tmp = pSupportPointsOnB[ 1 ]; pSupportPointsOnB[ 1 ] = pSupportPointsOnB[ 2 ]; pSupportPointsOnB[ 2 ] = tmp; } } EpaVertex* pVertexA = CreateVertex( pInitialPoints[ 0 ], pSupportPointsOnA[ 0 ], pSupportPointsOnB[ 0 ] ); EpaVertex* pVertexB = CreateVertex( pInitialPoints[ 1 ], pSupportPointsOnA[ 1 ], pSupportPointsOnB[ 1 ] ); EpaVertex* pVertexC = CreateVertex( pInitialPoints[ 2 ], pSupportPointsOnA[ 2 ], pSupportPointsOnB[ 2 ] ); EpaVertex* pVertexD = CreateVertex( pInitialPoints[ 3 ], pSupportPointsOnA[ 3 ], pSupportPointsOnB[ 3 ] ); #else finalPointsIndices[ 3 ] = -1; btScalar absMaxDist = -SIMD_INFINITY; btScalar maxDist; for ( int pointIndex = 0; pointIndex < nbInitialPoints; ++pointIndex ) { btScalar dist = planeNormal.dot( pInitialPoints[ pointIndex ] ) + planeDistance; btScalar absDist = abs( dist ); if ( ( absDist > absMaxDist ) && !btEqual( dist, PLANE_THICKNESS ) ) { absMaxDist = absDist; maxDist = dist; finalPointsIndices[ 3 ] = pointIndex; } } if ( finalPointsIndices[ 3 ] == -1 ) { Destroy(); return false; } if ( maxDist > PLANE_THICKNESS ) { // Can swap indices only btPoint3 tmp = pInitialPoints[ finalPointsIndices[ 1 ] ]; pInitialPoints[ finalPointsIndices[ 1 ] ] = pInitialPoints[ finalPointsIndices[ 2 ] ]; pInitialPoints[ finalPointsIndices[ 2 ] ] = tmp; tmp = pSupportPointsOnA[ finalPointsIndices[ 1 ] ]; pSupportPointsOnA[ finalPointsIndices[ 1 ] ] = pSupportPointsOnA[ finalPointsIndices[ 2 ] ]; pSupportPointsOnA[ finalPointsIndices[ 2 ] ] = tmp; tmp = pSupportPointsOnB[ finalPointsIndices[ 1 ] ]; pSupportPointsOnB[ finalPointsIndices[ 1 ] ] = pSupportPointsOnB[ finalPointsIndices[ 2 ] ]; pSupportPointsOnB[ finalPointsIndices[ 2 ] ] = tmp; } EpaVertex* pVertexA = CreateVertex( pInitialPoints[ finalPointsIndices[ 0 ] ], pSupportPointsOnA[ finalPointsIndices[ 0 ] ], pSupportPointsOnB[ finalPointsIndices[ 0 ] ] ); EpaVertex* pVertexB = CreateVertex( pInitialPoints[ finalPointsIndices[ 1 ] ], pSupportPointsOnA[ finalPointsIndices[ 1 ] ], pSupportPointsOnB[ finalPointsIndices[ 1 ] ] ); EpaVertex* pVertexC = CreateVertex( pInitialPoints[ finalPointsIndices[ 2 ] ], pSupportPointsOnA[ finalPointsIndices[ 2 ] ], pSupportPointsOnB[ finalPointsIndices[ 2 ] ] ); EpaVertex* pVertexD = CreateVertex( pInitialPoints[ finalPointsIndices[ 3 ] ], pSupportPointsOnA[ finalPointsIndices[ 3 ] ], pSupportPointsOnB[ finalPointsIndices[ 3 ] ] ); #endif EpaFace* pFaceA = CreateFace(); EpaFace* pFaceB = CreateFace(); EpaFace* pFaceC = CreateFace(); EpaFace* pFaceD = CreateFace(); EpaHalfEdge* pFaceAHalfEdges[ 3 ]; EpaHalfEdge* pFaceCHalfEdges[ 3 ]; EpaHalfEdge* pFaceBHalfEdges[ 3 ]; EpaHalfEdge* pFaceDHalfEdges[ 3 ]; pFaceAHalfEdges[ 0 ] = CreateHalfEdge(); pFaceAHalfEdges[ 1 ] = CreateHalfEdge(); pFaceAHalfEdges[ 2 ] = CreateHalfEdge(); pFaceBHalfEdges[ 0 ] = CreateHalfEdge(); pFaceBHalfEdges[ 1 ] = CreateHalfEdge(); pFaceBHalfEdges[ 2 ] = CreateHalfEdge(); pFaceCHalfEdges[ 0 ] = CreateHalfEdge(); pFaceCHalfEdges[ 1 ] = CreateHalfEdge(); pFaceCHalfEdges[ 2 ] = CreateHalfEdge(); pFaceDHalfEdges[ 0 ] = CreateHalfEdge(); pFaceDHalfEdges[ 1 ] = CreateHalfEdge(); pFaceDHalfEdges[ 2 ] = CreateHalfEdge(); pFaceA->m_pHalfEdge = pFaceAHalfEdges[ 0 ]; pFaceB->m_pHalfEdge = pFaceBHalfEdges[ 0 ]; pFaceC->m_pHalfEdge = pFaceCHalfEdges[ 0 ]; pFaceD->m_pHalfEdge = pFaceDHalfEdges[ 0 ]; pFaceAHalfEdges[ 0 ]->m_pNextCCW = pFaceAHalfEdges[ 1 ]; pFaceAHalfEdges[ 1 ]->m_pNextCCW = pFaceAHalfEdges[ 2 ]; pFaceAHalfEdges[ 2 ]->m_pNextCCW = pFaceAHalfEdges[ 0 ]; pFaceBHalfEdges[ 0 ]->m_pNextCCW = pFaceBHalfEdges[ 1 ]; pFaceBHalfEdges[ 1 ]->m_pNextCCW = pFaceBHalfEdges[ 2 ]; pFaceBHalfEdges[ 2 ]->m_pNextCCW = pFaceBHalfEdges[ 0 ]; pFaceCHalfEdges[ 0 ]->m_pNextCCW = pFaceCHalfEdges[ 1 ]; pFaceCHalfEdges[ 1 ]->m_pNextCCW = pFaceCHalfEdges[ 2 ]; pFaceCHalfEdges[ 2 ]->m_pNextCCW = pFaceCHalfEdges[ 0 ]; pFaceDHalfEdges[ 0 ]->m_pNextCCW = pFaceDHalfEdges[ 1 ]; pFaceDHalfEdges[ 1 ]->m_pNextCCW = pFaceDHalfEdges[ 2 ]; pFaceDHalfEdges[ 2 ]->m_pNextCCW = pFaceDHalfEdges[ 0 ]; pFaceAHalfEdges[ 0 ]->m_pFace = pFaceA; pFaceAHalfEdges[ 1 ]->m_pFace = pFaceA; pFaceAHalfEdges[ 2 ]->m_pFace = pFaceA; pFaceBHalfEdges[ 0 ]->m_pFace = pFaceB; pFaceBHalfEdges[ 1 ]->m_pFace = pFaceB; pFaceBHalfEdges[ 2 ]->m_pFace = pFaceB; pFaceCHalfEdges[ 0 ]->m_pFace = pFaceC; pFaceCHalfEdges[ 1 ]->m_pFace = pFaceC; pFaceCHalfEdges[ 2 ]->m_pFace = pFaceC; pFaceDHalfEdges[ 0 ]->m_pFace = pFaceD; pFaceDHalfEdges[ 1 ]->m_pFace = pFaceD; pFaceDHalfEdges[ 2 ]->m_pFace = pFaceD; pFaceAHalfEdges[ 0 ]->m_pVertex = pVertexA; pFaceAHalfEdges[ 1 ]->m_pVertex = pVertexB; pFaceAHalfEdges[ 2 ]->m_pVertex = pVertexC; pFaceBHalfEdges[ 0 ]->m_pVertex = pVertexB; pFaceBHalfEdges[ 1 ]->m_pVertex = pVertexD; pFaceBHalfEdges[ 2 ]->m_pVertex = pVertexC; pFaceCHalfEdges[ 0 ]->m_pVertex = pVertexD; pFaceCHalfEdges[ 1 ]->m_pVertex = pVertexA; pFaceCHalfEdges[ 2 ]->m_pVertex = pVertexC; pFaceDHalfEdges[ 0 ]->m_pVertex = pVertexB; pFaceDHalfEdges[ 1 ]->m_pVertex = pVertexA; pFaceDHalfEdges[ 2 ]->m_pVertex = pVertexD; //pVertexA->m_pHalfEdge = pFaceAHalfEdges[ 0 ]; //pVertexB->m_pHalfEdge = pFaceAHalfEdges[ 1 ]; //pVertexC->m_pHalfEdge = pFaceAHalfEdges[ 2 ]; //pVertexD->m_pHalfEdge = pFaceBHalfEdges[ 1 ]; pFaceAHalfEdges[ 0 ]->m_pTwin = pFaceDHalfEdges[ 0 ]; pFaceAHalfEdges[ 1 ]->m_pTwin = pFaceBHalfEdges[ 2 ]; pFaceAHalfEdges[ 2 ]->m_pTwin = pFaceCHalfEdges[ 1 ]; pFaceBHalfEdges[ 0 ]->m_pTwin = pFaceDHalfEdges[ 2 ]; pFaceBHalfEdges[ 1 ]->m_pTwin = pFaceCHalfEdges[ 2 ]; pFaceBHalfEdges[ 2 ]->m_pTwin = pFaceAHalfEdges[ 1 ]; pFaceCHalfEdges[ 0 ]->m_pTwin = pFaceDHalfEdges[ 1 ]; pFaceCHalfEdges[ 1 ]->m_pTwin = pFaceAHalfEdges[ 2 ]; pFaceCHalfEdges[ 2 ]->m_pTwin = pFaceBHalfEdges[ 1 ]; pFaceDHalfEdges[ 0 ]->m_pTwin = pFaceAHalfEdges[ 0 ]; pFaceDHalfEdges[ 1 ]->m_pTwin = pFaceCHalfEdges[ 0 ]; pFaceDHalfEdges[ 2 ]->m_pTwin = pFaceBHalfEdges[ 0 ]; if ( !pFaceA->Initialize() || !pFaceB->Initialize() || !pFaceC->Initialize() || !pFaceD->Initialize() ) { EPA_DEBUG_ASSERT( false, "One initial face failed to initialize!" ); return false; } #ifdef EPA_POLYHEDRON_USE_PLANES if ( nbInitialPoints > 4 ) { for ( int i = 0; i < nbInitialPoints; ++i ) { if ( ( i != finalPointsIndices[ 0 ] ) && ( i != finalPointsIndices[ 1 ] ) && ( i != finalPointsIndices[ 2 ] ) && ( i != finalPointsIndices[ 3 ] ) ) { std::list< EpaFace* >::iterator facesItr( m_faces.begin() ); while ( facesItr != m_faces.end() ) { EpaFace* pFace = *facesItr; btScalar dist = pFace->m_planeNormal.dot( pInitialPoints[ i ] ) + pFace->m_planeDistance; if ( dist > PLANE_THICKNESS ) { std::list< EpaFace* > newFaces; bool expandOk = Expand( pInitialPoints[ i ], pSupportPointsOnA[ i ], pSupportPointsOnB[ i ], pFace, newFaces ); if ( !expandOk ) { // One or more new faces are affinely dependent return false; } EPA_DEBUG_ASSERT( !newFaces.empty() ,"Polyhedron should have expanded!" ); break; } ++facesItr; } } } } #endif return true; }
int R3Mesh:: ReadOff(const char *filename) { // Open file FILE *fp; if (!(fp = fopen(filename, "r"))) { fprintf(stderr, "Unable to open file %s\n", filename); return 0; } // Read file int nverts = 0; int nfaces = 0; int nedges = 0; int line_count = 0; int vertex_count = 0; int face_count = 0; char buffer[1024]; char header[64]; while (fgets(buffer, 1023, fp)) { // Increment line counter line_count++; // Skip white space char *bufferp = buffer; while (isspace(*bufferp)) bufferp++; // Skip blank lines and comments if (*bufferp == '#') continue; if (*bufferp == '\0') continue; // Check section if (nverts == 0) { // Read header keyword if (strstr(bufferp, "OFF")) { // Check if counts are on first line int tmp; if (sscanf(bufferp, "%s%d%d%d", header, &tmp, &nfaces, &nedges) == 4) { nverts = tmp; } } else { // Read counts from second line if ((sscanf(bufferp, "%d%d%d", &nverts, &nfaces, &nedges) != 3) || (nverts == 0)) { fprintf(stderr, "Syntax error reading header on line %d in file %s\n", line_count, filename); fclose(fp); return 0; } } } else if (vertex_count < nverts) { // Read vertex coordinates double x, y, z; if (sscanf(bufferp, "%lf%lf%lf", &x, &y, &z) != 3) { fprintf(stderr, "Syntax error with vertex coordinates on line %d in file %s\n", line_count, filename); fclose(fp); return 0; } // Create vertex CreateVertex(R3Point(x, y, z), R3zero_vector, R2zero_point); // Increment counter vertex_count++; } else if (face_count < nfaces) { // Read number of vertices in face int face_nverts = 0; bufferp = strtok(bufferp, " \t"); if (bufferp) face_nverts = atoi(bufferp); else { fprintf(stderr, "Syntax error with face on line %d in file %s\n", line_count, filename); fclose(fp); return 0; } // Read vertex indices for face vector<R3MeshVertex *> face_vertices; for (int i = 0; i < face_nverts; i++) { R3MeshVertex *v = NULL; bufferp = strtok(NULL, " \t"); if (bufferp) v = Vertex(atoi(bufferp)); else { fprintf(stderr, "Syntax error with face on line %d in file %s\n", line_count, filename); fclose(fp); return 0; } // Add vertex to vector face_vertices.push_back(v); } // Create face CreateFace(face_vertices); // Increment counter face_count++; } else { // Should never get here fprintf(stderr, "Found extra text starting at line %d in file %s\n", line_count, filename); break; } } // Check whether read all vertices if ((vertex_count != nverts) || (NVertices() < nverts)) { fprintf(stderr, "Expected %d vertices, but read %d vertex lines and created %d vertices in file %s\n", nverts, vertex_count, NVertices(), filename); } // Check whether read all faces if ((face_count != nfaces) || (NFaces() < nfaces)) { fprintf(stderr, "Expected %d faces, but read %d face lines and created %d faces in file %s\n", nfaces, face_count, NFaces(), filename); } // Close file fclose(fp); // Return number of faces read return NFaces(); }
void triebWerk::COBJParser::AddVertex(const char* a_pText) { CMesh::SVertex vertex; const char* ptr = a_pText; if (!m_ContainsNormals && !m_ContainsUVs) { std::string a_Text = a_pText; int v = std::stoi(a_Text); vertex.position = m_VertexPoint[v - 1]; vertex.normal = DirectX::XMFLOAT3(0, 0, 0); vertex.uv = DirectX::XMFLOAT2(0, 0); std::cout << "Nothing" << std::endl; } if (m_ContainsNormals && !m_ContainsUVs) { std::string a_Text = a_pText; size_t backslashPos = a_Text.find_first_of("//", 0); int v = std::stoi(a_Text.substr(0, backslashPos)); int vn = std::stoi(a_Text.substr(backslashPos + 2, backslashPos - a_Text.size())); vertex.position = m_VertexPoint[v - 1]; vertex.normal = m_Normal[vn-1]; vertex.uv = DirectX::XMFLOAT2(0, 0); std::cout << "No UV but Normal" << std::endl; } if (m_ContainsUVs && !m_ContainsNormals) { std::string a_Text = a_pText; size_t backslashPos = a_Text.find_first_of("/", 0); int v = std::stoi(a_Text.substr(0, backslashPos)); int vt = std::stoi(a_Text.substr(backslashPos + 1, backslashPos - a_Text.size())); vertex.position = m_VertexPoint[v - 1]; vertex.normal = DirectX::XMFLOAT3(0, 0, 0); vertex.uv = m_UV[vt - 1]; std::cout << "UV but no Normals" << std::endl; } if (m_ContainsUVs && m_ContainsNormals) { int val = 0; int elementCount = 0; int elements[3] = { 0 }; do { if (*ptr == '/') { elements[elementCount] = val; elementCount++; val = 0; } else { if (*ptr >= '0' && *ptr <= '9') { val *= 10; val += *ptr - '0'; } } ptr++; } while (*ptr); //last element elements[elementCount] = val; //size_t backslashPosFirst = a_Text.find_first_of("/", 0); //size_t backslashPosSecond = a_Text.find("/", backslashPosFirst+1); //int v = std::stoi(a_Text.substr(0, backslashPosFirst)); //int vt = std::stoi(a_Text.substr(backslashPosFirst + 1, backslashPosSecond - backslashPosFirst)); //int vn = std::stoi(a_Text.substr(backslashPosSecond + 1, a_Text.size() - backslashPosSecond)); vertex.position = m_VertexPoint[elements[0] - 1]; vertex.uv = m_UV[elements[1] - 1]; vertex.normal = m_Normal[elements[2] - 1]; } CreateVertex(vertex); }
int R3Mesh:: ReadRay(const char *filename) { // Open file FILE *fp; if (!(fp = fopen(filename, "r"))) { fprintf(stderr, "Unable to open file %s", filename); return 0; } // Read body char cmd[128]; int polygon_count = 0; int command_number = 1; while (fscanf(fp, "%s", cmd) == 1) { if (!strcmp(cmd, "#vertex")) { // Read data double px, py, pz; double nx, ny, nz; double ts, tt; if (fscanf(fp, "%lf%lf%lf%lf%lf%lf%lf%lf", &px, &py, &pz, &nx, &ny, &nz, &ts, &tt) != 8) { fprintf(stderr, "Unable to read vertex at command %d in file %s", command_number, filename); return 0; } // Create vertex R3Point point(px, py, pz); R3Vector normal(nx, ny, nz); R2Point texcoords(ts, tt); CreateVertex(point, normal, texcoords); } else if (!strcmp(cmd, "#shape_polygon")) { // Read data int m, nverts; if (fscanf(fp, "%d%d", &m, &nverts) != 2) { fprintf(stderr, "Unable to read polygon at command %d in file %s", command_number, filename); return 0; } // Get vertices vector<R3MeshVertex *> face_vertices; for (int i = 0; i < nverts; i++) { // Read vertex id int vertex_id; if (fscanf(fp, "%d", &vertex_id) != 1) { fprintf(stderr, "Unable to read polygon at command %d in file %s", command_number, filename); return 0; } // Get vertex R3MeshVertex *v = Vertex(vertex_id); face_vertices.push_back(v); } // Create face CreateFace(face_vertices); // Increment polygon counter polygon_count++; } // Increment command number command_number++; } // Close file fclose(fp); // Return number of faces created return polygon_count; }