//==================================================================================== bool IniFile::readValue(const AnsiStr& section, const AnsiStr& variable, AnsiStr& strValue) { AnsiStr strLine = ""; if(readLine(section, variable, strLine)) { int len = strLine.length(); for(int i=0; i < len; i++) { if(strLine[i] == L'=') { strValue = strLine.substr(i+1); return true; } } } else { AnsiStr strFileTitle = ExtractFileName(m_strFileName); vlogerror("SettingsScript tried to read [file: %s; section: %s; variable: %s] which is not found.", strFileTitle.cptr(), section.cptr(), variable.cptr()); } return false; }
int ShaderManager::addFromFolder(const char* chrShadersPath) { int count = 0; vector<AnsiStr> vFiles; ListFilesInDir(vFiles, chrShadersPath, "vsh", true); for(int i=0; i<(int)vFiles.size(); i++) { AnsiStr strVShaderFP = vFiles[i]; AnsiStr strFShaderFP = ChangeFileExt(strVShaderFP, AnsiStr(".fsh")); AnsiStr strGShaderFP = ChangeFileExt(strVShaderFP, AnsiStr(".gsh")); AnsiStr strTitle = ExtractFileTitleOnly(strVShaderFP); if(FileExists(strGShaderFP)) { if(addFromFile(strTitle.cptr(), strVShaderFP, strFShaderFP, strGShaderFP)) { count++; } } else { if(addFromFile(strTitle.cptr(), strVShaderFP, strFShaderFP)) { count++; } } } return count; }
void resetMesh() { //remove it from scenegraph if(g_lpTissue) { TheSceneGraph::Instance().world()->removeRawRigidBody(g_lpTissue->getB3RigidBody()); TheSceneGraph::Instance().remove(g_lpTissue); SAFE_DELETE(g_lpTissue); } VolMesh* temp = NULL; if(FileExists(g_strFilePath)) { temp = new PS::MESH::VolMesh(); LogInfoArg1("Begin to read vega file from: %s", g_strFilePath.cptr()); bool res = PS::MESH::VolMeshIO::readVega(temp, g_strFilePath); if(!res) LogErrorArg1("Unable to load mesh from: %s", g_strFilePath.cptr()); } else { AnsiStr strExample = g_parser.value<AnsiStr>("example"); int pos = -1; if(strExample == "one") temp = PS::MESH::VolMeshSamples::CreateOneTetra(); else if(strExample == "two") temp = PS::MESH::VolMeshSamples::CreateTwoTetra(); else if(strExample.lfindstr(AnsiStr("cube"), pos)) { U32 nx, ny, nz = 0; sscanf(strExample.cptr(), "cube_%u_%u_%u", &nx, &ny, &nz); temp = PS::MESH::VolMeshSamples::CreateTruthCube(nx, ny, nz, 0.2); } else if(strExample.lfindstr(AnsiStr("eggshell"), pos)) { U32 nx, ny; //float radius, thickness; sscanf(strExample.cptr(), "eggshell_%u_%u", &nx, &ny); temp = PS::MESH::VolMeshSamples::CreateEggShell(nx, ny); } else temp = PS::MESH::VolMeshSamples::CreateOneTetra(); } LogInfo("Loaded mesh to temp"); g_lpTissue = new SGBulletRigidBodyCuttableMesh(*temp, temp->countNodes()); g_lpTissue->setFlagDrawSweepSurf(false); g_lpTissue->setDrawNodes(false); g_lpTissue->setDrawWireFrame(false); g_lpTissue->setFlagSplitMeshAfterCut(false); g_lpTissue->setFlagDrawAABB(false); TheSceneGraph::Instance().world()->addRawRigidBody(g_lpTissue->getB3RigidBody()); TheSceneGraph::Instance().add(g_lpTissue); g_lpTissue->setAnimate(false); SAFE_DELETE(temp); g_lpAvatar->setTissue(g_lpTissue); LogInfo("Mesh loaded"); }
int SGHeaders::addHeaderLine(const AnsiStr& title, const AnsiStr& strInfo) { if(m_hashHeaders.has(strInfo.cptr())) { LogInfoArg1("Header: %s is already present.", title.cptr()); return -1; } m_vHeaders.push_back(strInfo); int id = (int)m_vHeaders.size() - 1; m_hashHeaders.add(id, title.cptr()); return id; }
bool ShaderManager::addFromFile(const char* name, const AnsiStr& strVShaderFP, const AnsiStr& strFShaderFP, const AnsiStr& strGShaderFP) { AnsiStr strTitle = (name != NULL) ? AnsiStr(name) : ExtractFileTitleOnly(strVShaderFP); GLShader* aShader = new GLShader(); if(aShader->compileFromFile(strVShaderFP, strFShaderFP, strGShaderFP)) { if(ShaderManagerParent::add(aShader, strTitle.cptr())) { AnsiStr strArg = TheEventLogger::Instance().shortenPathBasedOnRoot(strVShaderFP); vloginfo("Added Vertex-Geometry-Fragment Shader from file: %s, Name: %s.", strArg.cptr(), name); return true; } else { SAFE_DELETE(aShader); vlogerror("Unable to add Vertex-Geometry-Fragment Shader from file. Name: %s", name); return false; } } else { SAFE_DELETE(aShader); return false; } }
bool VolMeshIO::writeObj(const VolMesh* vm, const AnsiStr& strPath) { if(vm == NULL) return false; Mesh objMesh; MeshNode* aNode = new MeshNode(); //output nodes for (U32 i = 0; i < vm->countNodes(); i++) { vec3d v = vm->const_nodeAt(i).pos; aNode->addVertex(vec3f(v.x, v.y, v.z)); } //output cell faces for (U32 i = 0; i < vm->countCells(); i++) { const CELL& cell = vm->const_cellAt(i); U32 nodes[3]; for(U32 j=0; j < COUNT_CELL_FACES; j++) { vm->getFaceNodes(cell.faces[j], nodes); aNode->addTriangle(nodes); } } // objMesh.addNode(aNode); return objMesh.store(strPath.cptr()); }
//==================================================================================== bool IniFile::writeFile() { ofstream ofs(m_strFileName.ptr(), ios::out | ios::trunc); if(!ofs.is_open()) return false; AnsiStr strLine; U32 ctSections = 0; for(int i=0; i < (int)m_content.size(); i++) { strLine = m_content[i]; //add an empty line if a new section if(strLine[0] == '[') { if(ctSections > 0) ofs << '\n'; ctSections++; } if(strLine.length() > 0) { ofs << strLine.cptr() << '\n'; } } ofs.close(); return true; }
bool Geometry::readObj(const AnsiStr& strFilePath) { Mesh mesh(strFilePath.cptr()); MeshNode* node = mesh.getNode(0); if(node == NULL) return false; int unitFace = node->getUnitFace(); if(unitFace != 3 && unitFace != 4) return false; GLFaceType ftype = ftTriangles; if(node->getUnitFace() == 4) ftype = ftQuads; //read mesh info init(node->getUnitVertex(), node->getUnitColor(), node->getUnitTexCoord(), ftype); addVertexAttribs(node->vertices(), node->getUnitVertex(), gbtPosition); addVertexAttribs(node->normals(), 3, gbtNormal); addVertexAttribs(node->colors(), node->getUnitColor(), gbtColor); addVertexAttribs(node->texcoords(), node->getUnitTexCoord(), gbtTexCoord); addFaceIndices(node->faceElements(), ftype); return true; }
bool VolMeshIO::writeVega(const VolMesh* vm, const AnsiStr& strPath) { if(vm == NULL) return false; if (vm->countNodes() == 0 || vm->countCells() == 0) return false; //Output veg file AnsiStr strVegFP = ChangeFileExt(strPath, ".veg"); ofstream fpOut(strVegFP.cptr()); //Include Node File fpOut << "# Vega Mesh File, Generated by FemBrain.\n"; fpOut << "# " << vm->countNodes() << " vertices, " << vm->countCells() << " elements\n"; fpOut << "\n"; fpOut << "*VERTICES\n"; fpOut << vm->countNodes() << " 3 0 0\n"; for (U32 i = 0; i < vm->countNodes(); i++) { vec3d v = vm->const_nodeAt(i).pos; //VEGA expects one based index for everything fpOut << i + 1 << " " << v.x << " " << v.y << " " << v.z << "\n"; } //Line Separator fpOut << "\n"; fpOut << "*ELEMENTS\n"; fpOut << "TET\n"; fpOut << vm->countCells() << " 4 0\n"; for (U32 i = 0; i < vm->countCells(); i++) { const CELL& cell = vm->const_cellAt(i); vec4u32 n = vec4u32(&cell.nodes[0]); //VEGA expects one based index for everything fpOut << i + 1 << " " << n.x + 1 << " " << n.y + 1 << " " << n.z + 1 << " " << n.w + 1 << "\n"; } //Add Default Material fpOut << "\n"; fpOut << "*MATERIAL BODY\n"; fpOut << "ENU, 1000, 10000000, 0.45\n"; fpOut << "\n"; fpOut << "*REGION\n"; fpOut << "allElements, BODY\n"; //Include Element File fpOut.close(); return true; }
bool SceneGraph::readConfig(const AnsiStr& strFP) { if(!FileExists(strFP)) { LogErrorArg1("File %s not found to read scene config.", strFP.cptr()); return false; } SettingsScript* script = new SettingsScript(strFP, SettingsScript::fmRead); m_camera.setRoll(script->readFloat("camera", "roll")); m_camera.setTilt(script->readFloat("camera", "tilt")); m_camera.setZoom(script->readFloat("camera", "zoom")); m_camera.setPan(script->readVec2f("camera", "pan")); SAFE_DELETE(script); return true; }
bool Geometry::writeObj(const AnsiStr& strFilePath) const { MeshNode* pnode = new MeshNode(); pnode->setVertexAttrib(m_vertices, gbtPosition, m_stepVertex); pnode->setVertexAttrib(m_normals, gbtNormal, 3); pnode->setVertexAttrib(m_colors, gbtColor, m_stepColor); pnode->setVertexAttrib(m_texCoords, gbtTexCoord, m_stepTexCoord); pnode->setFaceIndices(m_indices, m_stepFace); //store mesh Mesh* pmesh = new Mesh(); pmesh->addNode(pnode); bool bres = pmesh->store(strFilePath.cptr()); SAFE_DELETE(pmesh); return bres; }
bool SGEngine::readConfig(const AnsiStr& strFP) { if(!FileExists(strFP)) { vlogerror("File %s not found to read scene config.", strFP.cptr()); return false; } IniFile* script = new IniFile(strFP, IniFile::fmRead); m_camera.setRoll(script->readFloat("camera", "roll")); m_camera.setTilt(script->readFloat("camera", "tilt")); m_camera.setZoomLevel(script->readFloat("camera", "zoom")); m_camera.setPan(script->readVec2f("camera", "pan")); m_strRootFP = script->readString("system", "data"); SAFE_DELETE(script); return true; }
int main(int argc, char* argv[]) { cout << "Cutting tets" << endl; // prints !!!Hello World!!! //Initialize app glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL); glutInitWindowSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); glutCreateWindow("OpenGL Framework"); glutDisplayFunc(draw); glutReshapeFunc(def_resize); glutMouseFunc(MousePress); glutPassiveMotionFunc(MousePassiveMove); glutMotionFunc(MouseMove); glutMouseWheelFunc(MouseWheel); glutKeyboardFunc(NormalKey); glutSpecialFunc(SpecialKey); glutCloseFunc(closeApp); glutIdleFunc(timestep); //Setup Shading Environment static const GLfloat lightColor[4] = { 1.0f, 1.0f, 1.0f, 1.0f }; static const GLfloat lightPos[4] = { 0.0f, 9.0f, 0.0f, 1.0f }; //Setup Light0 Position and Color glLightfv(GL_LIGHT0, GL_AMBIENT, lightColor); glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor); glLightfv(GL_LIGHT0, GL_SPECULAR, lightColor); glLightfv(GL_LIGHT0, GL_POSITION, lightPos); //Turn on Light 0 glEnable(GL_LIGHT0); //Enable Lighting glEnable(GL_LIGHTING); //Enable features we want to use from OpenGL glShadeModel(GL_SMOOTH); glEnable(GL_POLYGON_SMOOTH); glEnable(GL_LINE_SMOOTH); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glEnable(GL_STENCIL_TEST); glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); //glClearColor(0.45f, 0.45f, 0.45f, 1.0f); glClearColor(1.0, 1.0, 1.0, 1.0); //Compiling shaders GLenum err = glewInit(); if (err != GLEW_OK) { //Problem: glewInit failed, something is seriously wrong. fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); exit(1); } //Build Shaders for drawing the mesh AnsiStr strRoot = ExtractOneLevelUp(ExtractFilePath(GetExePath())); AnsiStr strShaderRoot = strRoot + "data/shaders/"; //Load Shaders TheShaderManager::Instance().addFromFolder(strShaderRoot.cptr()); //Ground and Room TheSceneGraph::Instance().addFloor(32, 32, 0.5f); TheSceneGraph::Instance().addSceneBox(AABB(vec3f(-10, -10, -16), vec3f(10, 10, 16))); glutMainLoop(); return 0; }
int Run_SphereDistKernel() { AnsiStr strFP = ExtractOneLevelUp(ExtractFilePath(GetExePath())); strFP += AnsiStr("/PS_OpenCLKernels/SphereDist.cl"); ComputeDevice* lpGPU = new ComputeDevice(ComputeDevice::dtGPU); lpGPU->printInfo(); int prgID = lpGPU->addProgramFromFile(strFP.cptr()); assert(prgID >= 0); ComputeKernel* lpKernel = lpGPU->addKernel(prgID, "distSphere"); //Input Pos float* arrPosX = new float[DATA_SIZE]; float* arrPosY = new float[DATA_SIZE]; float* arrPosZ = new float[DATA_SIZE]; //Output Dist float* arrDist = new float[DATA_SIZE]; //Number of correct results returned unsigned int correct; cl_mem inMemPosX; cl_mem inMemPosY; cl_mem inMemPosZ; cl_mem outMemDist; // Fill the vector with random float values U32 count = DATA_SIZE; for (U32 i = 0; i < count; i++) { arrPosX[i] = rand() / (float) RAND_MAX; arrPosY[i] = rand() / (float) RAND_MAX; arrPosZ[i] = rand() / (float) RAND_MAX; } // Create the device memory vectors inMemPosX = lpGPU->createMemBuffer(sizeof(float) * count, PS::CL::memReadOnly); inMemPosY = lpGPU->createMemBuffer(sizeof(float) * count, PS::CL::memReadOnly); inMemPosZ = lpGPU->createMemBuffer(sizeof(float) * count, PS::CL::memReadOnly); outMemDist = lpGPU->createMemBuffer(sizeof(float) * count, PS::CL::memWriteOnly); // Transfer the input vector into device memory. //PosX if (!lpGPU->enqueueWriteBuffer(inMemPosX, sizeof(float) * count, arrPosX)) return -1; //PosY if (!lpGPU->enqueueWriteBuffer(inMemPosY, sizeof(float) * count, arrPosY)) return -1; //PosZ if (!lpGPU->enqueueWriteBuffer(inMemPosZ, sizeof(float) * count, arrPosZ)) return -1; // Set the arguments to the compute kernel lpKernel->setArg(0, sizeof(cl_mem), &inMemPosX); lpKernel->setArg(1, sizeof(cl_mem), &inMemPosY); lpKernel->setArg(2, sizeof(cl_mem), &inMemPosZ); lpKernel->setArg(3, sizeof(cl_mem), &outMemDist); lpKernel->setArg(4, sizeof(U32), &count); size_t local; size_t global; // Get the maximum work group size for executing the kernel on the device cl_int err = clGetKernelWorkGroupInfo(lpKernel->getKernel(), lpGPU->getDevice(), CL_KERNEL_WORK_GROUP_SIZE, sizeof(local), &local, NULL); if (err != CL_SUCCESS) { cerr << "Error: Failed to retrieve kernel work group info! " << err << endl; exit(1); } // Execute the kernel over the vector using the // maximum number of work group items for this device global = count; err = clEnqueueNDRangeKernel(lpGPU->getCommandQ(), lpKernel->getKernel(), 1, NULL, &global, &local, 0, NULL, NULL); if (err) { cerr << "Error: Failed to execute kernel!" << endl; return EXIT_FAILURE; } // Wait for all commands to complete lpGPU->finishAllCommands(); // Read back the results from the device to verify the output if (!lpGPU->enqueueReadBuffer(outMemDist, sizeof(float) * count, arrDist)) { return -1; } // Validate our results // correct = 0; float current; float v; for (U32 i = 0; i < count; i++) { current = arrDist[i]; v = arrPosX[i] * arrPosX[i] + arrPosY[i] * arrPosY[i] + arrPosZ[i] * arrPosZ[i]; if (FLOAT_EQ(current, v)) correct++; } // Print a brief summary detailing the results cout << "Computed " << correct << "/" << count << " correct values" << endl; cout << "Computed " << 100.f * (float) correct / (float) count << "% correct values" << endl; // Shutdown and cleanup SAFE_DELETE_ARRAY(arrPosX); SAFE_DELETE_ARRAY(arrPosY); SAFE_DELETE_ARRAY(arrPosZ); SAFE_DELETE_ARRAY(arrDist); clReleaseMemObject(inMemPosX); clReleaseMemObject(inMemPosY); clReleaseMemObject(inMemPosZ); clReleaseMemObject(outMemDist); SAFE_DELETE(lpGPU); return 1; }
int main(int argc, char* argv[]) { cout << "Cutting tets" << endl; g_parser.add_option("input", "[filepath] set input file in vega format", Value(AnsiStr("internal"))); g_parser.add_toggle("ringscalpel", "If the switch presents then the ring scalpel will be used"); g_parser.add_option("example", "[one, two, cube, eggshell] set an internal example", Value(AnsiStr("two"))); g_parser.add_option("gizmo", "loads a file to set gizmo location and orientation", Value(AnsiStr("gizmo.ini"))); if (g_parser.parse(argc, argv) < 0) exit(0); //file path g_strFilePath = ExtractFilePath(GetExePath()) + g_parser.value<AnsiStr>("input"); if (FileExists(g_strFilePath)) LogInfoArg1("input file: %s.", g_strFilePath.cptr()); else g_strFilePath = ""; //Initialize app glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL); glutInitWindowSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); glutCreateWindow("SoftRigidDynamics - Pourya Shirazian"); glutDisplayFunc(draw); glutReshapeFunc(def_resize); glutMouseFunc(MousePress); glutPassiveMotionFunc(MousePassiveMove); glutMotionFunc(MouseMove); glutMouseWheelFunc(MouseWheel); glutKeyboardFunc(NormalKey); glutSpecialFunc(SpecialKey); glutCloseFunc(closeApp); glutIdleFunc(timestep); def_initgl(); //Build Shaders for drawing the mesh AnsiStr strRoot = ExtractOneLevelUp(ExtractFilePath(GetExePath())); AnsiStr strShaderRoot = strRoot + "data/shaders/"; AnsiStr strMeshRoot = strRoot + "data/meshes/"; AnsiStr strTextureRoot = strRoot + "data/textures/"; AnsiStr strLeftPial = strMeshRoot + "brain/pial_Full_obj/lh.pial.obj"; AnsiStr strRightPial = strMeshRoot + "brain/pial_Full_obj/rh.pial.obj"; //Load Shaders TheShaderManager::Instance().addFromFolder(strShaderRoot.cptr()); //Load Textures TheTexManager::Instance().add(strTextureRoot + "wood.png"); TheTexManager::Instance().add(strTextureRoot + "rendermask.png"); TheTexManager::Instance().add(strTextureRoot + "maskalpha.png"); TheTexManager::Instance().add(strTextureRoot + "maskalphafilled.png"); TheTexManager::Instance().add(strTextureRoot + "spin.png"); //Ground and Room //TheSceneGraph::Instance().addFloor(32, 32, 0.5f); TheSceneGraph::Instance().addSceneBox(AABB(vec3f(-10, -10, -16), vec3f(10, 10, 16))); //floor Geometry g; g.addCube(vec3f(-8, -2.0, -8), vec3f(8, -1.8, 8)); g.addPerVertexColor(vec4f(0.5, 0.5, 0.5, 1)); SGBulletRigidMesh* floor = new SGBulletRigidMesh(); floor->setup(g, 0.0); floor->setName("floor"); TheSceneGraph::Instance().addRigidBody(floor); //create rigid bodies /* Geometry g1; g1.addCube(vec3f(0.0, 0.0, 0.0), 1.0); g1.addPerVertexColor(vec4f(0, 0, 1, 1)); for(int i=0; i < 8; i ++) { for(int j=0; j < 8; j++) { g1.colors().clear(); float r = RandRangeT<float>(0.0, 1.0); float g = RandRangeT<float>(0.0, 1.0); float b = RandRangeT<float>(0.0, 1.0); g1.addPerVertexColor(vec4f(r, g, b, 1.0f)); SGBulletRigidMesh* acube = new SGBulletRigidMesh(); acube->transform()->setTranslate(vec3f(i-3, 10.0, j-3)); acube->setup(g1, 1.0); TheSceneGraph::Instance().addRigidBody(acube); } } */ //Scalpel g_lpScalpel = new AvatarScalpel(); g_lpRing = new AvatarRing(TheTexManager::Instance().get("spin")); TheSceneGraph::Instance().add(g_lpScalpel); TheSceneGraph::Instance().add(g_lpRing); if(g_parser.value<int>("ringscalpel")) { g_lpAvatar = g_lpRing; g_lpScalpel->setVisible(false); } else { g_lpAvatar = g_lpScalpel; g_lpRing->setVisible(false); } g_lpAvatar->setTissue(g_lpTissue); g_lpAvatar->setOnCutFinishedEventHandler(finishedcut); TheGizmoManager::Instance().setFocusedNode(g_lpAvatar); //load gizmo manager file AnsiStr strGizmoFP = g_parser.value<AnsiStr>("gizmo"); TheGizmoManager::Instance().readConfig(strGizmoFP); resetMesh(); //render mask // SGRenderMask* renderMask = new SGRenderMask(TheTexManager::Instance().get("maskalpha")); // renderMask->setName("rendermask"); // TheSceneGraph::Instance().add(renderMask); glutMainLoop(); return 0; }
bool SGHeaders::updateHeaderLine(const AnsiStr& title, const AnsiStr& strInfo) { return updateHeaderLine(getHeaderId(title.cptr()), strInfo); }
void normal_key(unsigned char key, int x, int y) { key = tolower(key); switch(key) { case('/'): { g_lpTissue->setFlagDrawSweepSurf(!g_lpTissue->getFlagDrawSweepSurf()); vloginfo("Draw sweep surf set to: %d", g_lpTissue->getFlagDrawSweepSurf()); } break; case('a'): { if(!g_lpTissue) return; U32 i = g_lpTissue->getElemToShow(); if(g_lpTissue->isCellIndex(i)) g_lpTissue->setElemToShow(--i); else g_lpTissue->setElemToShow(0); if(g_lpTissue->isCellIndex(i)) { const CELL& cell = g_lpTissue->const_cellAt(i); AnsiStr strInfo = printToAStr("cell [%u], nodes [%u, %u, %u, %u]", i, cell.nodes[0], cell.nodes[1], cell.nodes[2], cell.nodes[3]); TheEngine::Instance().headers()->updateHeaderLine("cell", strInfo); } } break; case('d'): { if(!g_lpTissue) return; U32 i = g_lpTissue->getElemToShow(); if(g_lpTissue->isCellIndex(i)) g_lpTissue->setElemToShow(++i); else g_lpTissue->setElemToShow(0); if(g_lpTissue->isCellIndex(i)) { const CELL& cell = g_lpTissue->const_cellAt(i); AnsiStr strInfo = printToAStr("cell [%u], nodes [%u, %u, %u, %u]", i, cell.nodes[0], cell.nodes[1], cell.nodes[2], cell.nodes[3]); TheEngine::Instance().headers()->updateHeaderLine("cell", strInfo); } } break; case('e'): { if(!g_lpTissue) return; U32 ctElems = g_lpTissue->countCells(); U32 idxElem = -1; printf("Insert element index to show: [0:%u]\n", ctElems-1); scanf("%u", &idxElem); if(g_lpTissue->isCellIndex(idxElem)) g_lpTissue->setElemToShow(idxElem); else g_lpTissue->setElemToShow(); } break; case('g'):{ TheGizmoManager::Instance().setType(gtTranslate); } break; case('h'):{ bool flag = !TheEngine::Instance().get("headers")->isVisible(); TheEngine::Instance().get("headers")->setVisible(flag); vloginfo("Set headers draw to %s", flag ? "show" : "hide"); break; } case('s'):{ TheGizmoManager::Instance().setType(gtScale); break; } case('r'):{ TheGizmoManager::Instance().setType(gtRotate); break; } case ('t'): { if (g_lpAvatar == g_lpScalpel) { g_lpAvatar = g_lpRing; g_lpScalpel->setVisible(false); } else { g_lpAvatar = g_lpScalpel; g_lpRing->setVisible(false); } g_lpAvatar->setVisible(true); g_lpAvatar->setTissue(g_lpTissue); g_lpAvatar->setOnCutFinishedEventHandler(cutFinished); TheGizmoManager::Instance().setFocusedNode(g_lpAvatar); break; } case('.'):{ if(g_lpTissue) g_lpTissue->setFlagDrawWireFrame(!g_lpTissue->getFlagDrawWireFrame()); vloginfo("Wireframe mode is %d", g_lpTissue->getFlagDrawWireFrame()); break; } case('x'):{ TheGizmoManager::Instance().setAxis(axisX); } break; case('y'):{ TheGizmoManager::Instance().setAxis(axisY); } break; case('z'):{ TheGizmoManager::Instance().setAxis(axisZ); } break; case('m'): { bool flag = !TheEngine::Instance().get("rendermask")->isVisible(); TheEngine::Instance().get("rendermask")->setVisible(flag); vloginfo("Set rendermask to %s", flag ? "show" : "hide"); break; } break; case('p'): { TheEngine::Instance().print(); } break; case('['):{ TheEngine::Instance().camera().incrZoomLevel(0.5f); } break; case(']'):{ TheEngine::Instance().camera().incrZoomLevel(-0.5f); } break; case('w'):{ AnsiStr strRoot = ExtractOneLevelUp(ExtractFilePath(GetExePath())); AnsiStr strOutput = strRoot + "data/output/"; AnsiStr strVegOutput = strOutput + printToAStr("%s_cuts%d.veg", g_lpTissue->name().c_str(), g_lpTissue->countCompletedCuts()); AnsiStr strObjOutput = strOutput + printToAStr("%s_cuts%d.obj", g_lpTissue->name().c_str(), g_lpTissue->countCompletedCuts()); vloginfo("Attempt to store at %s. Make sure all the required directories are present!", strVegOutput.cptr()); if(VolMeshIO::writeVega(g_lpTissue, strVegOutput)) vloginfo("Stored the mesh at: %s", strVegOutput.cptr()); vloginfo("Attempt to store at %s. Make sure all the required directories are present!", strObjOutput.cptr()); if(VolMeshIO::writeObj(g_lpTissue, strObjOutput)) vloginfo("Stored the mesh at: %s", strObjOutput.cptr()); } break; } //Update Screen // glutPostRedisplay(); }
//================================================================== int ListFilesInDir(std::vector<AnsiStr>& lstFiles, const char* pDir, const char* pExtensions, bool storeWithPath) { AnsiStr strDir; AnsiStr strResolvedDir; lstFiles.resize(0); if(pDir == NULL) strResolvedDir = ps::dir::ExtractFilePath(ps::dir::GetExePath()); else strResolvedDir = AnsiStr(pDir); if(pExtensions != NULL) strDir = printToAStr("%s/*.%s", strResolvedDir.ptr(), pExtensions); else strDir = printToAStr("%s/*.*", strResolvedDir.ptr()); #ifdef PS_OS_WINDOWS WIN32_FIND_DATA ffd; HANDLE hFind = INVALID_HANDLE_VALUE; DWideStr wstrDir = toWideString(strDir); hFind = FindFirstFile(wstrDir.ptr(), &ffd); if(hFind == INVALID_HANDLE_VALUE) return 0; AnsiStr temp; do { if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { if (storeWithPath) { temp = strResolvedDir + "\\"; temp += AnsiStr(ffd.cFileName); lstFiles.push_back(temp); } else { temp = AnsiStr(ffd.cFileName); lstFiles.push_back(temp); } } }while (FindNextFile(hFind, &ffd) != 0); FindClose(hFind); #else DIR* dirFile = opendir( strResolvedDir.cptr() ); if ( dirFile ) { struct dirent* hFile; string strExt = "." + string(pExtensions); while (( hFile = readdir( dirFile )) != NULL ) { if ( !strcmp( hFile->d_name, "." )) continue; if ( !strcmp( hFile->d_name, ".." )) continue; // in linux hidden files all start with '.' if (hFile->d_name[0] == '.' ) continue; // dirFile.name is the name of the file. Do whatever string comparison // you want here. Something like: if ( strstr( hFile->d_name, strExt.c_str())) { if(storeWithPath) lstFiles.push_back(strResolvedDir + "//" + AnsiStr(hFile->d_name)); else lstFiles.push_back(AnsiStr(hFile->d_name)); printf("Found file %s", hFile->d_name); } } closedir( dirFile ); } #endif return (int)lstFiles.size(); }
int main(int argc, char* argv[]) { int ctThreads = tbb::task_scheduler_init::default_num_threads(); tbb::task_scheduler_init init(ctThreads); cout << "started tbb with " << ctThreads << " threads." << endl; //parser g_parser.addSwitch("--disjoint", "-d", "converts splitted part to disjoint meshes", "0"); g_parser.addSwitch("--ringscalpel", "-r", "If the switch presents then the ring scalpel will be used"); g_parser.addSwitch("--verbose", "-v", "prints detailed description."); g_parser.addSwitch("--input", "-i", "[filepath] set input file in vega format", "internal"); //g_parser.addSwitch("--example", "-e", "[one, two, cube, eggshell] set an internal example", "two"); //g_parser.addSwitch("--gizmo", "-g", "loads a file to set gizmo location and orientation", "gizmo.ini"); if(g_parser.parse(argc, argv) < 0) exit(0); //file path g_strIniFilePath = AnsiStr(g_parser.value("input").c_str()); if(FileExists(g_strIniFilePath)) vloginfo("input file: %s.", g_strIniFilePath.cptr()); else { vlogerror("Unable to find input filepath: [%s]", g_strIniFilePath.cptr()); exit(1); } //GLFW LIB g_lpWindow = NULL; glfwSetErrorCallback(error_callback); if (!glfwInit()) { vlogerror("Failed to init glfw"); exit(EXIT_FAILURE); } /* glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); */ g_lpWindow = glfwCreateWindow(DEFAULT_WIDTH, DEFAULT_HEIGHT, "tetcutter - Pourya Shirazian", NULL, NULL); if (!g_lpWindow) { glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(g_lpWindow); glfwSwapInterval(1); glfwSetKeyCallback(g_lpWindow, key_callback); glfwSetCursorPosCallback(g_lpWindow, mouse_motion_callback); glfwSetMouseButtonCallback(g_lpWindow, mouse_button_callback); glfwSetScrollCallback(g_lpWindow, scroll_callback); //init gl def_initgl(); //Build Shaders for drawing the mesh IniFile ini(g_strIniFilePath, IniFile::fmRead); AnsiStr strRoot = ini.readString("system", "data"); AnsiStr strShaderRoot = strRoot + "shaders/"; AnsiStr strTextureRoot = strRoot + "textures/"; AnsiStr strFontsRoot = strRoot + "fonts/"; //convert mesh // AnsiStr strNodesFP = strRoot + AnsiStr("data/meshes/matlab/nodes.txt"); // AnsiStr strFacesFP = strRoot + AnsiStr("data/meshes/matlab/faces.txt"); // AnsiStr strCellsFP = strRoot + AnsiStr("data/meshes/matlab/cells.txt"); // VolMeshIO::convertMatlabTextToVega(strNodesFP, strFacesFP, strCellsFP); //Load Shaders TheShaderManager::Instance().addFromFolder(strShaderRoot.cptr()); //Load Textures TheTexManager::Instance().add(strTextureRoot + "wood.png"); TheTexManager::Instance().add(strTextureRoot + "spin.png"); TheTexManager::Instance().add(strTextureRoot + "icefloor.png"); // TheTexManager::Instance().add(strTextureRoot + "rendermask.png"); // TheTexManager::Instance().add(strTextureRoot + "maskalpha.png"); // TheTexManager::Instance().add(strTextureRoot + "maskalphafilled.png"); vloginfo("Floor show is set to: [%d]", ini.readBool("visible", "floor")); //Ground and Room SGQuad* floor = new SGQuad(16.0f, 16.0f, TheTexManager::Instance().get("icefloor")); floor->setName("floor"); floor->transform()->translate(vec3f(0, -0.1f, 0)); floor->transform()->rotate(vec3f(1.0f, 0.0f, 0.0f), 90.0f); floor->setVisible(ini.readBool("visible", "floor")); TheEngine::Instance().add(floor); //Create Scalpel g_lpScalpel = new AvatarScalpel(); g_lpScalpel->setVisible(false); g_lpRing = new AvatarRing(TheTexManager::Instance().get("spin")); g_lpRing->setVisible(false); TheEngine::Instance().add(g_lpScalpel); TheEngine::Instance().add(g_lpRing); if(g_parser.value_to_int("ringscalpel") == 1) { g_lpAvatar = g_lpRing; g_lpRing->setVisible(true); } else { g_lpAvatar = g_lpScalpel; g_lpScalpel->setVisible(true); } g_lpAvatar->setTissue(g_lpTissue); g_lpAvatar->setOnCutFinishedEventHandler(cutFinished); TheGizmoManager::Instance().setFocusedNode(g_lpAvatar); TheGizmoManager::Instance().readConfig(g_strIniFilePath); //setup engine TheEngine::Instance().readConfig(g_strIniFilePath); TheEngine::Instance().headers()->addHeaderLine("cell", "info"); TheEngine::Instance().print(); //reset cuttable mesh resetMesh(); //mainloop while (!glfwWindowShouldClose(g_lpWindow)) { //setup projection matrix int width = DEFAULT_WIDTH; int height = DEFAULT_HEIGHT; glfwGetFramebufferSize(g_lpWindow, &width, &height); def_resize(width, height); //draw frame draw(); timestep(); glfwSwapBuffers(g_lpWindow); glfwPollEvents(); } //destroy window glfwDestroyWindow(g_lpWindow); glfwTerminate(); exit(EXIT_SUCCESS); return 0; }
VolMesh* VolMeshSamples::CreateTruthCube(int nx, int ny, int nz, double cellsize) { if(nx < 2 || ny < 2 || nz < 2) { LogError("Invalid input param to create a truth cube"); return NULL; } vector< vec3d > vertices; vector< vec4u32 > elements; vec3d start = vec3d(- (double)(nx)/2.0, 0, - (double)(nz)/2.0) * (cellsize); //add all nodes for(int i=0; i < nx; i++) { for(int j=0; j < ny; j++) { for(int k=0; k < nz; k++) { vec3d v = start + vec3d(i, j, k) * cellsize; vertices.push_back(v); } } } //corner defs enum CellCorners {LBN = 0, LBF = 1, LTN = 2, LTF = 3, RBN = 4, RBF = 5, RTN = 6, RTF = 7}; U32 cn[8]; //add all elements for(int i=0; i < nx-1; i++) { for(int j=0; j < ny-1; j++) { for(int k=0; k < nz-1; k++) { //collect cell nodes cn[LBN] = i * ny * nz + j * nz + k; cn[LBF] = i * ny * nz + j * nz + k + 1; cn[LTN] = i * ny * nz + (j+1) * nz + k; cn[LTF] = i * ny * nz + (j+1) * nz + k + 1; cn[RBN] = (i+1) * ny * nz + j * nz + k; cn[RBF] = (i+1) * ny * nz + j * nz + k + 1; cn[RTN] = (i+1) * ny * nz + (j+1) * nz + k; cn[RTF] = (i+1) * ny * nz + (j+1) * nz + k + 1; //add elements elements.push_back(vec4u32(cn[LBN], cn[LTN], cn[RBN], cn[LBF])); elements.push_back(vec4u32(cn[RTN], cn[LTN], cn[LBF], cn[RBN])); elements.push_back(vec4u32(cn[RTN], cn[LTN], cn[LTF], cn[LBF])); elements.push_back(vec4u32(cn[RTN], cn[RBN], cn[LBF], cn[RBF])); elements.push_back(vec4u32(cn[RTN], cn[LBF], cn[LTF], cn[RBF])); elements.push_back(vec4u32(cn[RTN], cn[LTF], cn[RTF], cn[RBF])); } } } //build the final mesh vector<double> vFlatVertices; vector<U32> vFlatElements; FlattenVec3<double>(vertices, vFlatVertices); FlattenVec4<U32>(elements, vFlatElements); AnsiStr strName = printToAStr("truthcube_%dx%dx%d", nx, ny, nz); VolMesh* cube = new VolMesh(vFlatVertices, vFlatElements); cube->setName(strName.cptr()); return cube; }
VolMesh* VolMeshSamples::CreateEggShell(int hseg, int vseg, double radius, double shelltickness) { if(hseg <= 0 || vseg <= 0) { LogErrorArg2("Invalid eggshell segments param: %u, %u", hseg, vseg); return NULL; } if(shelltickness >= radius) { LogErrorArg2("Invalid eggshell radius and thickness params: %.3f, %.3f", radius, shelltickness); return NULL; } vector< vec3d > vertices; vector< vec4u32 > elements; float vSegInv = 1.0f / (float)vseg; float hSegInv = 1.0f / (float)hseg; //Loop Over for(int v=0; v<vseg+1; v++) { double p = DEGTORAD(v * vSegInv * 180.0); for(int h=0; h<hseg; h++) { double o = DEGTORAD(h * hSegInv * 360.0); //vertex vec3d v1; v1.x = radius * sin(p) * sin(o); v1.z = radius * sin(p) * cos(o); v1.y = radius * cos(p); //Add Vertex vertices.push_back(v1); } } //layer 2 U32 layeroffset = vertices.size(); radius -= shelltickness; for(int v=0; v<vseg+1; v++) { double p = DEGTORAD(v * vSegInv * 180.0); for(int h=0; h<hseg; h++) { double o = DEGTORAD(h * hSegInv * 360.0); //vertex vec3d v1; v1.x = radius * sin(p) * sin(o); v1.z = radius * sin(p) * cos(o); v1.y = radius * cos(p); //Add Vertex vertices.push_back(v1); } } //Indices enum CellCorners {LBN = 0, LBF = 1, LTN = 2, LTF = 3, RBN = 4, RBF = 5, RTN = 6, RTF = 7}; U32 cn[8]; //Add all elements for(int v=0; v<vseg; v++) { for(int h=0; h<hseg; h++) { //top cn[LTN] = h + v*hseg; cn[LTF] = cn[LTN] + 1; cn[RTN] = h + (v+1)*hseg; cn[RTF] = cn[RTN] + 1; if(h == hseg-1) { cn[LTF] = v*hseg; cn[RTF] = (v+1)*hseg; } //bottom cn[LBN] = layeroffset + h + v*hseg; cn[LBF] = layeroffset + cn[LTN] + 1; cn[RBN] = layeroffset + h + (v+1)*hseg; cn[RBF] = layeroffset + cn[RTN] + 1; if(h == hseg-1) { cn[LBF] = layeroffset + v*hseg; cn[RBF] = layeroffset + (v+1)*hseg; } //add elements elements.push_back(vec4u32(cn[LBN], cn[LTN], cn[RBN], cn[LBF])); elements.push_back(vec4u32(cn[RTN], cn[LTN], cn[LBF], cn[RBN])); elements.push_back(vec4u32(cn[RTN], cn[LTN], cn[LTF], cn[LBF])); elements.push_back(vec4u32(cn[RTN], cn[RBN], cn[LBF], cn[RBF])); elements.push_back(vec4u32(cn[RTN], cn[LBF], cn[LTF], cn[RBF])); elements.push_back(vec4u32(cn[RTN], cn[LTF], cn[RTF], cn[RBF])); } } //remove slivers U32 i = 0; while(i < elements.size()) { //fetch vertices vec4u32 e = elements[i]; vec3d v[4]; for(U32 j=0; j < COUNT_CELL_NODES; j++) v[j] = vertices[e[j]]; if(VolMesh::ComputeCellVolume(v) < 0.0001) elements.erase(elements.begin() + i); else i++; } //build the final mesh vector<double> vFlatVertices; vector<U32> vFlatElements; FlattenVec3<double>(vertices, vFlatVertices); FlattenVec4<U32>(elements, vFlatElements); AnsiStr strName = printToAStr("eggshell_h%d_v%d", hseg, vseg); VolMesh* eggshell = new VolMesh(vFlatVertices, vFlatElements); eggshell->setName(strName.cptr()); return eggshell; }
bool VolMeshIO::readVega(VolMesh* vm, const AnsiStr& strPath) { if ((vm == NULL) || !FileExists(strPath)) return false; char chrLine[1024]; ifstream fpIn(strPath.cptr()); if (!fpIn.is_open()) return false; vector<double> vertices; vector<U32> elements; U32 ctLine = 0; U32 idxVertex = 0; U32 ctVertices = 0; U32 ctVertexStep = 0; U32 idxElement = 0; U32 ctElements = 0; U32 ctElementStep = 0; enum READMODE { modeReadHeader, modeReadVertex, modeReadElements, modeReadMaterial, modeReadRegion }; READMODE mode = modeReadHeader; READMODE prevMode = mode; while (!fpIn.eof()) { fpIn.getline(chrLine, 1024); AnsiStr strLine(chrLine); strLine.trim(); strLine.removeStartEndSpaces(); if (strLine.length() == 0) continue; if (strLine.firstChar() == '#') continue; if (strLine.firstChar() == '*') { vector<AnsiStr> tokens; strLine.decompose(' ', tokens); if (tokens[0] == "*VERTICES") mode = modeReadVertex; else if (tokens[0] == "*ELEMENTS") mode = modeReadElements; else if (tokens[0] == "*MATERIAL") mode = modeReadMaterial; else if (tokens[0] == "*REGION") mode = modeReadRegion; continue; } else if(strLine == "TETS") continue; //count tokens { vector<AnsiStr> tokens; int ctTokens = strLine.decompose(' ', tokens); if(ctTokens < 2) continue; } if (prevMode != mode) { if (mode == modeReadVertex && idxVertex == 0) { sscanf(strLine.cptr(), "%u %u", &ctVertices, &ctVertexStep); if (ctVertices <= 0 || ctVertexStep != 3) { fpIn.close(); return false; } vertices.reserve(ctVertices * ctVertexStep); prevMode = mode; continue; } else if (mode == modeReadElements && idxElement == 0) { sscanf(strLine.cptr(), "%u %u", &ctElements, &ctElementStep); if (ctElements <= 0 || ctElementStep != 4) { fpIn.close(); return false; } elements.reserve(ctElements * ctElementStep); prevMode = mode; continue; } } if (mode == modeReadVertex) { vec3d v; vector<AnsiStr> arrWords; int ctWords = strLine.decompose(' ', arrWords); if (ctWords >= 4) { U32 row = atoi(arrWords[0].cptr()) - 1; assert(row == idxVertex); v.x = atof(arrWords[1].cptr()); v.y = atof(arrWords[2].cptr()); v.z = atof(arrWords[3].cptr()); } //add vertex to the array vertices.push_back(v.x); vertices.push_back(v.y); vertices.push_back(v.z); idxVertex++; } else if (mode == modeReadElements) { vec4u32 e; vector<AnsiStr> arrWords; int ctWords = strLine.decompose(' ', arrWords); if (ctWords >= 5) { U32 row = atoi(arrWords[0].cptr()) - 1; assert(row == idxElement); e.x = atoi(arrWords[1].cptr()) - 1; e.y = atoi(arrWords[2].cptr()) - 1; e.z = atoi(arrWords[3].cptr()) - 1; e.w = atoi(arrWords[4].cptr()) - 1; } //add element to the array elements.push_back(e.x); elements.push_back(e.y); elements.push_back(e.z); elements.push_back(e.w); idxElement++; } prevMode = mode; ctLine++; } fpIn.close(); //check read amount if((vertices.size() / ctVertexStep) != ctVertices) return false; if((elements.size() / ctElementStep) != ctElements) return false; //setup mesh vm->cleanup(); vm->setName(ExtractFileTitleOnly(strPath).cptr()); return vm->setup(vertices, elements); }
bool VolMeshIO::convertMatlabTextToVega(const AnsiStr& strNodesFP, const AnsiStr& strFacesFP, const AnsiStr& strCellsFP) { // node: node coordinates (in mm) // face: surface triangles; the last column is the surface ID, // 1-scalp, 2-CSF, 3-gray matter, 4-white matter // elem: tetrahedral elements; the last column is the region ID, // 1-scalp and skull layer, 2-CSF, 3-gray matter, 4-white matter if(!FileExists(strNodesFP) || !FileExists(strCellsFP)) { LogError("Invalid input file!"); return false; } vector<vec3d> nodes; ifstream fpNodes(strNodesFP.cptr()); if (!fpNodes.is_open()) return false; //read nodes U32 ctLine = 0; char chrLine[1024]; while (!fpNodes.eof()) { fpNodes.getline(chrLine, 1024); AnsiStr strLine(chrLine); strLine.trim(); strLine.removeStartEndSpaces(); if (strLine.length() == 0) continue; if (strLine.firstChar() == '#') continue; //count tokens { vector<AnsiStr> tokens; int ctTokens = strLine.decompose(',', tokens); if(ctTokens < 2) continue; vec3d v; v.x = atof(tokens[0].cptr()); v.y = atof(tokens[1].cptr()); v.z = atof(tokens[2].cptr()); nodes.push_back(v); } ctLine++; } fpNodes.close(); vector< vector<U32> > vBrainSegmentCells; vBrainSegmentCells.resize(4); //read cells ifstream fpCells(strCellsFP.cptr()); if (!fpCells.is_open()) return false; U32 ctExpectedTokens = 5; vector<U32> vConvTokens; vConvTokens.resize(ctExpectedTokens); while (!fpCells.eof()) { fpCells.getline(chrLine, 1024); AnsiStr strLine(chrLine); strLine.trim(); strLine.removeStartEndSpaces(); if (strLine.length() == 0) continue; if (strLine.firstChar() == '#') continue; //count tokens { vector<AnsiStr> tokens; int ctTokens = strLine.decompose(',', tokens); if(ctTokens < 2) continue; for(U32 i=0; i < ctExpectedTokens; i++) vConvTokens[i] = atoi(tokens[i].cptr()); U32 idxSegment = vConvTokens.back() - 1; for(U32 i=0; i < ctExpectedTokens - 1; i++) vBrainSegmentCells[idxSegment].push_back(vConvTokens[i] - 1); } } fpCells.close(); //export brain segments enum BrainSegment {bsSkull = 1, bsCSF = 2, bsGrayMatter = 3, bsWhiteMatter = 4}; string arrSegmentTitles[4] = {"skull", "csf", "graymatter", "whitematter"}; AnsiStr strRoot = ExtractFilePath(strNodesFP); //export segments for(U32 i=0; i < 4; i++) { vector<U32> vFlatCells(vBrainSegmentCells[i].begin(), vBrainSegmentCells[i].end()); vector<vec3d> vFinalNodes; vFinalNodes.reserve(nodes.size()); map<U32, U32> mapSegmentNodes; //Make a unique set of nodes for(U32 j=0; j < vFlatCells.size(); j++) { //if not found in cache the add it if(mapSegmentNodes.find(vFlatCells[j]) == mapSegmentNodes.end()) { vFinalNodes.push_back(nodes[vFlatCells[j] ]); U32 idxNewNode = vFinalNodes.size() - 1; mapSegmentNodes[ vFlatCells[j] ] = idxNewNode; } //convert to the new node index vFlatCells[j] = mapSegmentNodes[ vFlatCells[j] ]; } //clear the map mapSegmentNodes.clear(); vector<double> vFlatNodes; FlattenVec3<double>(vFinalNodes, vFlatNodes); VolMesh* pvm = new VolMesh(vFlatNodes, vFlatCells); pvm->setVerbose(true); // quatd q; // q.fromAxisAngle(vec3d(0, 0, 1), 90.0); // rotatemesh(pvm, q); //aabb // AABB box1(vec3f(0.0f, 0.0f, 0.0f), vec3f(4.0f, 4.0f, 4.0f)); // fitmesh(pvm, box1); //aabb AABB box2(vec3f(-2.0f, 0.0f, -2.0f), vec3f(2.0f, 4.0f, 2.0f)); fitmesh(pvm, box2); AnsiStr strFP = strRoot + AnsiStr(arrSegmentTitles[i].c_str()) + AnsiStr(".veg"); if(writeVega(pvm, strFP)) { LogInfoArg2("Saved segment %s to %s", arrSegmentTitles[i].c_str(), strFP.cptr()); } SAFE_DELETE(pvm); } return true; }
//Read Program from file and then compile it int ComputeDevice::addProgramFromFile(const AnsiStr& strFP, bool tryLoadBinary) { if(!m_bReady) return -1; if(!PS::FILESTRINGUTILS::FileExists(strFP)) { LogErrorArg1("File does not exist! Path: %s", strFP.cptr()); return -1; } std::ifstream fp; fp.open(strFP.cptr(), std::ios::binary); if(!fp.is_open()) return -1; //Compute Source File Checksum for bin compatibility and future storage LogInfoArg1("Computing source file MD5 checksum for %s", strFP.cptr()); string checkSumOrg = ComputeCheckSum(strFP.cptr()); LogInfoArg1("Computed checksum is %s", checkSumOrg.c_str()); if(tryLoadBinary) { string checkSumLoaded; ComputeProgram* lpProgram = NULL; if(LoadSourceCheckSum(strFP.cptr(), checkSumLoaded)) { if(checkSumOrg == checkSumLoaded) { LogInfo("Checksums matched. Attempting to load ptx binfile."); string strBinFile = string(strFP.cptr()) + ".ptx"; std::ifstream binFile; binFile.open(strBinFile.c_str(), std::ios::binary); if(binFile.is_open()) { size_t size; binFile.seekg(0, std::ios::end); size = binFile.tellg(); binFile.seekg(0, std::ios::beg); U8* buf = new U8[size]; binFile.read((char*)buf, size); binFile.close(); lpProgram = loadPtxBinary(buf, size); if(lpProgram) LogInfoArg1("Kernels loaded from binfile at: %s", strBinFile.c_str()); else LogErrorArg1("An error occured while trying to load ptx binfile from: %s", strBinFile.c_str()); SAFE_DELETE(buf); } } } if(lpProgram) { //Add loaded to list m_lstPrograms.push_back(lpProgram); return ((int)m_lstPrograms.size() - 1); } } //From Source Code LogInfo("Compiling and storing bin file along with the computed md5 checksum for future loads."); size_t size; fp.seekg(0, std::ios::end); size = fp.tellg(); fp.seekg(0, std::ios::beg); char * buf = new char[size+1]; //Read file content fp.read(buf, size); buf[size] = '\0'; string strCode = string(buf); SAFE_DELETE(buf); fp.close(); //Save Binary int id = addProgram(strCode.c_str()); if(isProgramIndex(id)) { string strBinFile = string(strFP.cptr()) + ".ptx"; storePtxBinary(m_lstPrograms[id], strBinFile.c_str()); SaveSourceCheckSum(strFP.cptr(), checkSumOrg); } return id; }