static void tst_isolate_roots() { enable_trace("isolate_roots"); unsynch_mpq_manager qm; polynomial::manager pm(qm); algebraic_numbers::manager am(qm); polynomial_ref x0(pm); polynomial_ref x1(pm); polynomial_ref x2(pm); polynomial_ref x3(pm); x0 = pm.mk_polynomial(pm.mk_var()); x1 = pm.mk_polynomial(pm.mk_var()); x2 = pm.mk_polynomial(pm.mk_var()); x3 = pm.mk_polynomial(pm.mk_var()); polynomial_ref p(pm); p = x3*x1 + 1; scoped_anum v0(am), v1(am), v2(am); tst_isolate_roots(p, am, 0, v0, 1, v1, 2, v2); am.set(v1, 1); tst_isolate_roots(p, am, 0, v0, 1, v1, 2, v2); am.set(v1, 2); am.root(v1, 2, v1); tst_isolate_roots(p, am, 0, v0, 1, v1, 2, v2); p = (x1 + x2)*x3 + 1; am.set(v2, v1); tst_isolate_roots(p, am, 0, v0, 1, v1, 2, v2); p = (x1 + x2)*x3 + x1*x2 + 2; tst_isolate_roots(p, am, 0, v0, 1, v1, 2, v2); p = (x1 + x2)*(x3^3) + x1*x2 + 2; tst_isolate_roots(p, am, 0, v0, 1, v1, 2, v2); p = (x1 + x2)*(x3^2) - x1*x2 - 2; tst_isolate_roots(p, am, 0, v0, 1, v1, 2, v2); p = x0*(x1 + x2)*(x3^2) - x0*x1*x2 - 2; tst_isolate_roots(p, am, 0, v0, 1, v1, 2, v2); p = (x1 - x2)*x3 + x1*x2 - 2; tst_isolate_roots(p, am, 0, v0, 1, v1, 2, v2); p = (x1 - x2)*(x3^3) + x1*x2 - 2; tst_isolate_roots(p, am, 0, v0, 1, v1, 2, v2); p = (x3 - x0)*(x3 - x0 - x1); am.set(v0, 2); am.root(v0, 2, v0); // x2 -> sqrt(2) am.set(v1, 3); am.root(v1, 2, v1); // x1 -> sqrt(3) am.reset(v2); tst_isolate_roots(p, am, 0, v0, 1, v1, 2, v2); p = (x3 - x0)*((x3 - x0 - x1)^2); tst_isolate_roots(p, am, 0, v0, 1, v1, 2, v2); p = (x3 - x0)*(x3 - 2)*((x3 - 1)^2)*(x3 - x1); tst_isolate_roots(p, am, 0, v0, 1, v1, 2, v2); }
TriMesh * Resource::loadMeshFromObj(std::string _objSrc){ std::istringstream stream(FileUtils::voxReadFile(_objSrc)); std::vector<glm::vec3> verts; std::vector<glm::vec3> normals; std::vector<glm::vec2> uvs; std::smatch match; std::regex faceRegex("(\\d{1})[/]?(\\d?)[/]?(\\d?)[\\s]{1}"); bool faceFormatChecked = false; bool hasUvs = false; bool hasNorms = false; ObjFaceFormat faceStructure = VERTS; TriMesh* mesh = new TriMesh(GL_TRIANGLES, GL_STATIC_DRAW); int maxchars = 8192; std::vector<char> buf(maxchars); while(stream.peek() != -1) { stream.getline(&buf[0], maxchars); std::string line(&buf[0]); if (line.size() > 0) { if (line[line.size()-1] == '\n') line.erase(line.size()-1); } if (line.size() > 0) { if (line[line.size()-1] == '\r') line.erase(line.size()-1); } char p1 = -1; char p2 = -1; if(line.size() >= 1){ p1 = line[0]; } if(line.size() >= 1){ p2 = line[1]; } if(p1 == -1 || p2 == -1){ continue; } if(p1 == '\0' || p1 == '#'){ continue; } if(p1 == 'v' && p2 == ' '){ glm::vec3 tempVert(1); sscanf(line.c_str(), "%*s %f %f %f", &tempVert.x, &tempVert.y, &tempVert.z); verts.push_back(tempVert); }else if(p1 == 'v' && p2 == 'n'){ glm::vec3 tempNorm(1); sscanf(line.c_str(), "%*s %f %f %f", &tempNorm.x, &tempNorm.y, &tempNorm.z); normals.push_back(tempNorm); }else if(p1 == 'v' && p2 == 't'){ glm::vec2 tempUv(1); sscanf(line.c_str(), "%*s %f %f", &tempUv.x, &tempUv.y); uvs.push_back(tempUv); }else if(p1 == 'f' && p2 == ' '){ if(!faceFormatChecked){ std::smatch matches; std::regex_search(line, matches, faceRegex); if(matches[2].str().size() > 0 && matches[3].str().size() > 0){ faceStructure = VERTS_UVS_NORMALS; hasUvs = true; hasNorms = true; }else if(matches[2].str().size() > 0 && matches[3].str().size() <= 0){ faceStructure = VERTS_UVS; hasUvs = true; }else if(matches[2].str().size() <= 0 && matches[3].str().size() > 0){ faceStructure = VERTS_NORMALS; hasNorms = true; } faceFormatChecked = true; } Face face; std::string faceVert; std::string faceVerts; switch(faceStructure){ case VERTS : faceVert = " %d"; faceVerts = "%*s" + faceVert + faceVert + faceVert; sscanf(line.c_str(), faceVerts.c_str(), &face.f1Vert, &face.f2Vert, &face.f3Vert); break; case VERTS_UVS : faceVert = " %d/%d"; faceVerts = "%*s" + faceVert + faceVert + faceVert; sscanf(line.c_str(), faceVerts.c_str(), &face.f1Vert, &face.f1Uv, &face.f2Vert, &face.f2Uv, &face.f3Vert, &face.f3Uv); break; case VERTS_NORMALS : faceVert = " %d//%d"; faceVerts = "%*s" + faceVert + faceVert + faceVert; sscanf(line.c_str(), faceVerts.c_str(), &face.f1Vert, &face.f1Norm, &face.f2Vert, &face.f2Norm, &face.f3Vert, &face.f3Norm); break; case VERTS_UVS_NORMALS : faceVert = " %d/%d/%d"; faceVerts = "%*s" + faceVert + faceVert + faceVert; sscanf(line.c_str(), faceVerts.c_str(), &face.f1Vert, &face.f1Uv, &face.f1Norm, &face.f2Vert, &face.f2Uv, &face.f2Norm, &face.f3Vert, &face.f3Uv, &face.f3Norm); break; } Vertex v1(verts.at(face.f1Vert - 1)); Vertex v2(verts.at(face.f2Vert - 1)); Vertex v3(verts.at(face.f3Vert - 1)); if(hasUvs){ glm::vec2 uv = uvs.at(face.f1Uv - 1); v1.u = uv.x; v1.v = uv.y; uv = uvs.at(face.f2Uv - 1); v2.u = uv.x; v2.v = uv.y; uv = uvs.at(face.f3Uv - 1); v3.u = uv.x; v3.v = uv.y; } if(hasNorms){ glm::vec3 norm = normals.at(face.f1Norm - 1); v1.nx = norm.x; v1.ny = norm.y; v1.nz = norm.z; norm = normals.at(face.f2Norm - 1); v2.nx = norm.x; v2.ny = norm.y; v2.nz = norm.z; norm = normals.at(face.f3Norm - 1); v3.nx = norm.x; v3.ny = norm.y; v3.nz = norm.z; } mesh->pushVert(v1); mesh->pushVert(v2); mesh->pushVert(v3); mesh->pushTri(mesh->vertices.size()-3, mesh->vertices.size()-2, mesh->vertices.size()-1); } } return mesh; }
void TestSymBandDiv(tmv::DivType dt, PosDefCode pdc) { const int N = 10; std::vector<tmv::SymBandMatrixView<T> > sb; std::vector<tmv::SymBandMatrixView<std::complex<T> > > csb; MakeSymBandList(sb,csb,pdc); tmv::Vector<T> v1(N); tmv::Vector<T> v2(N-1); for (int i=0; i<N; ++i) v1(i) = T(16-3*i); for (int i=0; i<N-1; ++i) v2(i) = T(-7+2*i); std::ostream* checkout = showdiv ? &std::cout : 0; for(size_t i=START;i<sb.size();i++) { if (i>START) break; tmv::SymBandMatrixView<T> si = sb[i]; tmv::SymBandMatrixView<std::complex<T> > csi = csb[i]; if (dt == tmv::CH && csi.issym()) continue; si.saveDiv(); csi.saveDiv(); if (showstartdone) std::cout<<"Start loop: i = "<<i<<", si = "<<tmv::TMV_Text(si)<< " "<<si<<std::endl; Assert(IsPosDef(si) == (pdc==PosDef),"IsPosDef"); if (csi.isherm()) { Assert(IsPosDef(csi) == (pdc==PosDef),"IsPosDef"); } tmv::Matrix<T> m(si); m.saveDiv(); if (dt == tmv::CH) m.divideUsing(tmv::LU); else m.divideUsing(dt); m.setDiv(); Assert(m.checkDecomp(checkout),"CheckDecomp m"); T eps = EPS; if (pdc == Sing) eps *= 1000; else eps *= Norm(m)*Norm(m.inverse()); si.divideUsing(dt); si.setDiv(); if (si.isherm()) { tmv::HermMatrix<T> six = si; six.divideUsing(dt); six.setDiv(); Assert(six.checkDecomp(checkout),"CheckDecomp six(herm)"); } else { tmv::SymBandMatrix<T> six = si; six.divideUsing(dt); six.setDiv(); Assert(six.checkDecomp(checkout),"CheckDecomp six(sym)"); } Assert(si.checkDecomp(checkout),"CheckDecomp si"); tmv::Vector<T> x1 = v1/si; tmv::Vector<T> x2 = v1/m; if (showacc) { std::cout<<"v1 = "<<v1<<std::endl; std::cout<<"v1/si = "<<x1<<std::endl; std::cout<<"v1/m = "<<x2<<std::endl; std::cout<<"si*x1 = "<<si*x1<<std::endl; std::cout<<"m*x2 = "<<m*x2<<std::endl; std::cout<<"v/b: Norm(x1-x2) = "<<Norm(x1-x2)<< " "<<eps*Norm(x1)<<std::endl; } Assert(Norm(x1-x2) < eps*Norm(x1),"SymBand v/b"); x1 = v1%si; x2 = v1%m; if (showacc) std::cout<<"v%b: Norm(x1-x2) = "<<Norm(x1-x2)<< " "<<eps*Norm(x1)<<std::endl; Assert(Norm(x1-x2) < eps*Norm(x1),"SymBand v%b"); tmv::Matrix<T,tmv::ColMajor> sinv = si.inverse(); tmv::Matrix<T,tmv::ColMajor> minv = m.inverse(); if (showacc) { std::cout<<"sinv = "<<sinv<<std::endl; std::cout<<"minv = "<<minv<<std::endl; std::cout<<"Norm(minv-sinv) = "<<Norm(minv-sinv)<< " "<<eps*Norm(sinv)<<std::endl; } Assert(Norm(sinv-minv) < eps*Norm(sinv),"SymBand Inverse"); if (showacc) { std::cout<<"Det(si) = "<<Det(si)<<", Det(m) = "<<Det(m)<<std::endl; std::cout<<"abs(sdet-mdet) = "<<std::abs(Det(si)-Det(m)); std::cout<<" EPS*abs(mdet) = "<<eps*std::abs(Det(m))<<std::endl; std::cout<<"abs(abs(sdet)-abs(mdet)) = "<< std::abs(std::abs(Det(si))-std::abs(Det(m))); std::cout<<" EPS*abs(mdet) = "<<eps*std::abs(Det(m))<<std::endl; } if (pdc != Sing) { Assert(std::abs(Det(m)-Det(si)) < eps*std::abs(Det(m)), "SymBand Det"); T msign,ssign; Assert(std::abs(m.logDet(&msign)-si.logDet(&ssign)) < 10*N*eps, "SymBand LogDet"); Assert(std::abs(msign-ssign) < 10*N*eps, "SymBand LogDet - sign"); } tmv::Matrix<std::complex<T> > cm(csi); cm.saveDiv(); if (dt == tmv::CH) cm.divideUsing(tmv::LU); else cm.divideUsing(dt); cm.setDiv(); Assert(cm.checkDecomp(checkout),"CheckDecomp cm"); csi.divideUsing(dt); csi.setDiv(); if (csi.isherm()) { tmv::HermMatrix<std::complex<T> > csix = csi; csix.divideUsing(dt); csix.setDiv(); Assert(csix.checkDecomp(checkout),"CheckDecomp csix(herm)"); } else { tmv::SymBandMatrix<std::complex<T> > csix = csi; csix.divideUsing(dt); csix.setDiv(); Assert(csix.checkDecomp(checkout),"CheckDecomp csix(sym)"); } Assert(csi.checkDecomp(checkout),"CheckDecomp csi"); T ceps = EPS; if (pdc == Sing) ceps *= 1000; else ceps *= Norm(cm)*Norm(cm.inverse()); if (showacc) { std::cout<<"Det(csi) = "<<Det(csi)<< ", Det(cm) = "<<Det(cm)<<std::endl; std::cout<<"abs(csidet-cmdet) = "<<std::abs(Det(csi)-Det(cm)); std::cout<<" csidet/cmdet = "<<Det(csi)/Det(cm); std::cout<<" EPS*abs(cmdet) = "<< ceps*std::abs(Det(cm))<<std::endl; std::cout<<"abs(abs(csdet)-abs(cmdet)) = "<< std::abs(std::abs(Det(csi))-std::abs(Det(cm))); std::cout<<" EPS*abs(cmdet) = "<< ceps*std::abs(Det(cm))<<std::endl; } if (pdc != Sing) { Assert(std::abs(Det(csi)-Det(cm)) < ceps*std::abs(Det(cm)), "SymBand CDet"); std::complex<T> cmsign,cssign; Assert(std::abs(cm.logDet(&cmsign)-csi.logDet(&cssign)) < 10*N*eps, "SymBand CLogDet"); Assert(std::abs(cmsign-cssign) < 10*N*eps, "SymBand CLogDet - sign"); } tmv::Vector<std::complex<T> > cv = v1 * std::complex<T>(1,1); cv(1) += std::complex<T>(-1,5); cv(2) -= std::complex<T>(-1,5); // test real / complex tmv::Vector<std::complex<T> > y1 = v1/csi; tmv::Vector<std::complex<T> > y2 = v1/cm; if (showacc) std::cout<<"v/cs: Norm(y1-y2) = "<<Norm(y1-y2)<<" "<< ceps*Norm(y1)<<std::endl; Assert(Norm(y1-y2) < ceps*Norm(y1),"SymBand v/cs"); // test complex / real y1 = cv/si; y2 = cv/m; if (showacc) std::cout<<"cv/b: Norm(y1-y2) = "<<Norm(y1-y2)<<" "<< eps*Norm(y1)<<std::endl; Assert(Norm(y1-y2) < eps*Norm(y1),"SymBand cv/b"); // test complex / complex y1 = cv/csi; y2 = cv/cm; if (showacc) std::cout<<"cv/cs: Norm(y1-y2) = "<<Norm(y1-y2)<<" "<< ceps*Norm(y1)<<std::endl; Assert(Norm(y1-y2) < ceps*Norm(y1),"SymBand cv/cs"); y1 = v1%csi; y2 = v1%cm; if (showacc) std::cout<<"v%cs: Norm(y1-y2) = "<<Norm(y1-y2)<<" "<< ceps*Norm(y1)<<std::endl; Assert(Norm(y1-y2) < ceps*Norm(y1),"SymBand v%cs"); y1 = cv%si; y2 = cv%m; if (showacc) std::cout<<"cv%b: Norm(y1-y2) = "<<Norm(y1-y2)<<" "<< eps*Norm(y1)<<std::endl; Assert(Norm(y1-y2) < eps*Norm(y1),"SymBand cv%b"); y1 = cv%csi; y2 = cv%cm; if (showacc) std::cout<<"cv%cs: Norm(y1-y2) = "<<Norm(y1-y2)<<" "<< ceps*Norm(y1)<<std::endl; Assert(Norm(y1-y2) < ceps*Norm(y1),"SymBand cv%cs"); } if (pdc != Sing) { TestSymBandDiv_A<T>(dt,pdc); TestSymBandDiv_B1<T>(dt,pdc); TestSymBandDiv_C1<T>(dt,pdc); TestSymBandDiv_D1<T>(dt,pdc); TestSymBandDiv_E1<T>(dt,pdc); TestSymBandDiv_F1<T>(dt,pdc); } if (pdc == PosDef) { if (dt != tmv::CH) TestSymBandDiv_B2<T>(dt,pdc); if (dt == tmv::LU) TestSymBandDiv_C2<T>(dt,pdc); if (dt == tmv::LU) TestSymBandDiv_D2<T>(dt,pdc); if (dt != tmv::CH) TestSymBandDiv_E2<T>(dt,pdc); TestSymBandDiv_F2<T>(dt,pdc); } std::cout<<PDLabel(pdc)<<" SymBandMatrix<"<<tmv::TMV_Text(T())<< "> Division using "; std::cout<<tmv::TMV_Text(dt)<<" passed all tests\n"; }
void World::transformPartB() { for (int i = 0; i < objects.size(); i++) { (*objects[i]).transform(persp_trans); (*objects[i]).transform(ortho_proj); (*objects[i]).transform(viewport_trans); } for (int i = 0; i < objects.size(); i++) { Material obj_color = (*objects[i]).surface_mat; for (int j = 0; j < (*objects[i]).num_triangles; j++) { Triangle cur_tri = (*objects[i]).triangles[j]; Vector3 center = cur_tri.centroid; Vector3 tri_normal = (cur_tri.unit_normal[0] + cur_tri.unit_normal[1] + cur_tri.unit_normal[2]) / 3.0; //Back face culling if (tri_normal * (center) > 0.0) continue; Vector4 v1 = cur_tri.vertices[0]; Vector4 v2 = cur_tri.vertices[1]; Vector4 v3 = cur_tri.vertices[2]; float xa = v1(0); float xb = v2(0); float xc = v3(0); float ya = v1(1); float yb = v2(1); float yc = v3(1); float x_min = floor(getMin(xa, xb, xc)); float y_min = floor(getMin(ya, yb, yc)); float x_max = ceil(getMax(xa, xb, xc)); float y_max = ceil(getMax(ya, yb, yc)); float n = x_max - x_min; for (int y = y_min; y <= y_max; y++) { for (int x = x_min; x <= x_max; x++) { float beta = ( (ya - yc) * x + (xc - xa) * y + xa * yc - xc * ya) / ( (ya - yc) * xb + (xc - xa) * yb + xa * yc - xc * ya); float gamma = ( (ya - yb) * x + (xb - xa) * y + xa * yb - xb * ya) / ( (ya - yb) * xc + (xb - xa) * yc + xa * yb - xb * ya); if (beta > 0.0 && gamma > 0.0 && (beta + gamma) < 1.0) { //Attribute interpolation ==================================================== float d1 = cur_tri.world_vertices[0].getMagnitude(); float d2 = cur_tri.world_vertices[1].getMagnitude(); float d3 = cur_tri.world_vertices[2].getMagnitude(); Vector3 fragment_location = center; Vector3 fragment_normal = fragment_location - Vector3(0, 0, -7); fragment_location = fragment_location / fragment_location.getMagnitude(); fragment_normal = fragment_normal / fragment_normal.getMagnitude(); float distance = (d1 + beta * (d2 - d1) + gamma * (d3 - d1)) / 3.0; //End of attribute interpolation ============================================== Vector3 light_vec = (Vector3(-4.0, 4.0, -3.0) / Vector3(-4.0, 4.0, -3.0).getMagnitude()) - (fragment_location / fragment_location.getMagnitude()); light_vec = light_vec / light_vec.getMagnitude(); Vector3 h_spec = light_vec - (fragment_location / fragment_location.getMagnitude()); h_spec = h_spec / h_spec.getMagnitude(); RGBColor tri_color = getMax(0.0, 0.0, (fragment_normal * light_vec)) * obj_color.diffuse; tri_color = tri_color + (obj_color.ambient * 0.2); tri_color = tri_color + obj_color.specular * pow(getMax(0, 0, fragment_normal * h_spec), obj_color.phong_exponent); tri_color = tri_color.power(1.0 / 2.2); Pixel tri_pix = Pixel(tri_color, distance); if (tri_pix.depth < (im_plane.getPixel(x, y).depth - 0.001) || im_plane.getPixel(x, y).depth < 0.0) im_plane.setPixel(x, y, tri_pix); } } } } } }
int main(int argc, char *argv[]) { struct db_i *dbip; struct directory *dp; struct rt_db_internal intern; struct rt_bot_internal *bot_ip = NULL; struct rt_wdb *wdbp; struct bu_vls name; struct bu_vls bname; struct Mesh_Info *prev_mesh = NULL; struct Mesh_Info *mesh = NULL; bu_vls_init(&name); if (argc != 3) { bu_exit(1, "Usage: %s file.g object", argv[0]); } dbip = db_open(argv[1], DB_OPEN_READWRITE); if (dbip == DBI_NULL) { bu_exit(1, "ERROR: Unable to read from geometry database file %s\n", argv[1]); } if (db_dirbuild(dbip) < 0) bu_exit(1, "ERROR: Unable to read from %s\n", argv[1]); dp = db_lookup(dbip, argv[2], LOOKUP_QUIET); if (dp == RT_DIR_NULL) { bu_exit(1, "ERROR: Unable to look up object %s\n", argv[2]); } RT_DB_INTERNAL_INIT(&intern) if (rt_db_get_internal(&intern, dp, dbip, NULL, &rt_uniresource) < 0) { bu_exit(1, "ERROR: Unable to get internal representation of %s\n", argv[2]); } if (intern.idb_minor_type != DB5_MINORTYPE_BRLCAD_BOT) { bu_exit(1, "ERROR: object %s does not appear to be of type BoT\n", argv[2]); } else { bot_ip = (struct rt_bot_internal *)intern.idb_ptr; } RT_BOT_CK_MAGIC(bot_ip); for (size_t i_cnt = 1; i_cnt < 3; i_cnt++) { mesh = iterate(bot_ip, prev_mesh); prev_mesh = mesh; // Plot results struct bu_vls fname; bu_vls_init(&fname); bu_vls_printf(&fname, "root3_%d.pl", i_cnt); FILE* plot_file = fopen(bu_vls_addr(&fname), "w"); std::map<size_t, std::vector<size_t> >::iterator f_it; std::vector<size_t>::iterator l_it; int r = int(256*drand48() + 1.0); int g = int(256*drand48() + 1.0); int b = int(256*drand48() + 1.0); for (f_it = mesh->face_pts.begin(); f_it != mesh->face_pts.end(); f_it++) { l_it = (*f_it).second.begin(); plot_face(&mesh->points_p0[(int)(*l_it)], &mesh->points_p0[(int)(*(l_it+1))], &mesh->points_p0[(int)(*(l_it+2))], r, g , b, plot_file); } fclose(plot_file); } // When constructing the final BoT, use the limit points for all // vertices ON_3dPointArray points_inf; for (size_t v = 0; v < (size_t)mesh->points_p0.Count(); v++) { points_inf.Append(*mesh->points_p0.At((int)v)); //point_inf(v, mesh, &points_inf); } // The subdivision process shrinks the bot relative to its original // vertex positions - to better approximate the original surface, // average the change in position of the original vertices to get a // scaling factor and apply it to all points in the final mesh. fastf_t scale = 0.0; for (size_t pcnt = 0; pcnt < bot_ip->num_vertices; pcnt++) { ON_3dVector v1(ON_3dPoint(&bot_ip->vertices[pcnt*3])); ON_3dVector v2(*points_inf.At((int)pcnt)); scale += 1 + (v1.Length() - v2.Length())/v1.Length(); } scale = scale / bot_ip->num_vertices; for (size_t pcnt = 0; pcnt < (size_t)points_inf.Count(); pcnt++) { ON_3dPoint p0(*points_inf.At((int)pcnt)); ON_3dPoint p1 = p0 * scale; *points_inf.At((int)pcnt) = p1; } wdbp = wdb_dbopen(dbip, RT_WDB_TYPE_DB_DISK); fastf_t *vertices = (fastf_t *)bu_malloc(sizeof(fastf_t) * points_inf.Count() * 3, "new verts"); int *faces = (int *)bu_malloc(sizeof(int) * mesh->face_pts.size() * 3, "new faces"); for (size_t v = 0; v < (size_t)points_inf.Count(); v++) { vertices[v*3] = points_inf[(int)v].x; vertices[v*3+1] = points_inf[(int)v].y; vertices[v*3+2] = points_inf[(int)v].z; } std::map<size_t, std::vector<size_t> >::iterator f_it; std::vector<size_t>::iterator l_it; for (f_it = mesh->face_pts.begin(); f_it != mesh->face_pts.end(); f_it++) { l_it = (*f_it).second.begin(); faces[(*f_it).first*3] = (*l_it); faces[(*f_it).first*3+1] = (*(l_it + 1)); faces[(*f_it).first*3+2] = (*(l_it + 2)); } bu_vls_init(&bname); bu_vls_sprintf(&bname, "%s_subd", argv[2]); mk_bot(wdbp, bu_vls_addr(&bname), RT_BOT_SOLID, RT_BOT_UNORIENTED, 0, points_inf.Count(), mesh->face_pts.size(), vertices, faces, (fastf_t *)NULL, (struct bu_bitv *)NULL); wdb_close(wdbp); bu_vls_free(&bname); bu_free(vertices, "free subdivision BoT vertices"); bu_free(faces, "free subdivision BoT faces"); return 0; }
template<typename MatrixType> void basicStuff(const MatrixType& m) { typedef typename MatrixType::Index Index; typedef typename MatrixType::Scalar Scalar; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType; Index rows = m.rows(); Index cols = m.cols(); // this test relies a lot on Random.h, and there's not much more that we can do // to test it, hence I consider that we will have tested Random.h MatrixType m1 = MatrixType::Random(rows, cols), m2 = MatrixType::Random(rows, cols), m3(rows, cols), mzero = MatrixType::Zero(rows, cols), identity = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> ::Identity(rows, rows), square = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>::Random(rows, rows); VectorType v1 = VectorType::Random(rows), v2 = VectorType::Random(rows), vzero = VectorType::Zero(rows); Scalar x = ei_random<Scalar>(); Index r = ei_random<Index>(0, rows-1), c = ei_random<Index>(0, cols-1); m1.coeffRef(r,c) = x; VERIFY_IS_APPROX(x, m1.coeff(r,c)); m1(r,c) = x; VERIFY_IS_APPROX(x, m1(r,c)); v1.coeffRef(r) = x; VERIFY_IS_APPROX(x, v1.coeff(r)); v1(r) = x; VERIFY_IS_APPROX(x, v1(r)); v1[r] = x; VERIFY_IS_APPROX(x, v1[r]); VERIFY_IS_APPROX( v1, v1); VERIFY_IS_NOT_APPROX( v1, 2*v1); VERIFY_IS_MUCH_SMALLER_THAN( vzero, v1); if(!NumTraits<Scalar>::IsInteger) VERIFY_IS_MUCH_SMALLER_THAN( vzero, v1.norm()); VERIFY_IS_NOT_MUCH_SMALLER_THAN(v1, v1); VERIFY_IS_APPROX( vzero, v1-v1); VERIFY_IS_APPROX( m1, m1); VERIFY_IS_NOT_APPROX( m1, 2*m1); VERIFY_IS_MUCH_SMALLER_THAN( mzero, m1); VERIFY_IS_NOT_MUCH_SMALLER_THAN(m1, m1); VERIFY_IS_APPROX( mzero, m1-m1); // always test operator() on each read-only expression class, // in order to check const-qualifiers. // indeed, if an expression class (here Zero) is meant to be read-only, // hence has no _write() method, the corresponding MatrixBase method (here zero()) // should return a const-qualified object so that it is the const-qualified // operator() that gets called, which in turn calls _read(). VERIFY_IS_MUCH_SMALLER_THAN(MatrixType::Zero(rows,cols)(r,c), static_cast<Scalar>(1)); // now test copying a row-vector into a (column-)vector and conversely. square.col(r) = square.row(r).eval(); Matrix<Scalar, 1, MatrixType::RowsAtCompileTime> rv(rows); Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> cv(rows); rv = square.row(r); cv = square.col(r); VERIFY_IS_APPROX(rv, cv.transpose()); if(cols!=1 && rows!=1 && MatrixType::SizeAtCompileTime!=Dynamic) { VERIFY_RAISES_ASSERT(m1 = (m2.block(0,0, rows-1, cols-1))); } if(cols!=1 && rows!=1) { VERIFY_RAISES_ASSERT(m1[0]); VERIFY_RAISES_ASSERT((m1+m1)[0]); } VERIFY_IS_APPROX(m3 = m1,m1); MatrixType m4; VERIFY_IS_APPROX(m4 = m1,m1); m3.real() = m1.real(); VERIFY_IS_APPROX(static_cast<const MatrixType&>(m3).real(), static_cast<const MatrixType&>(m1).real()); VERIFY_IS_APPROX(static_cast<const MatrixType&>(m3).real(), m1.real()); // check == / != operators VERIFY(m1==m1); VERIFY(m1!=m2); VERIFY(!(m1==m2)); VERIFY(!(m1!=m1)); m1 = m2; VERIFY(m1==m2); VERIFY(!(m1!=m2)); }
TEST(TVector, can_create_copied_vector) { TVector<int> v(10); ASSERT_NO_THROW(TVector<int> v1(v)); }
TEST(vector2, magnitude) { Vector2 v1(4, 5); float magnitude = 6.4031; EXPECT_NEAR(magnitude, v1.Magnitude(), .0001); }
// Vector3 Tests TEST(vector3, equality) { Vector3 v1(1,2,3); Vector3 v2(1,2,3); EXPECT_TRUE(v1 == v2); }
TEST(vector2, copying) { Vector2 v1(6, 5); Vector2 v2(v1); EXPECT_TRUE(v1 == v2); }
TEST(vector3, magnitude) { Vector3 v1(4, 5, 6); float magnitude = sqrt(77); EXPECT_NEAR(magnitude, v1.Magnitude(), .0001); }
TEST(vector3, copying) { Vector3 v1(6, 5, 7); Vector3 v2(v1); EXPECT_TRUE(v1 == v2); }
//majorAxis and minorAxis is the estimated particle size in px void ProgSortByStatistics::processInprocessInputPrepareSPTH(MetaData &SF, bool trained) { //#define DEBUG PCAMahalanobisAnalyzer tempPcaAnalyzer0; PCAMahalanobisAnalyzer tempPcaAnalyzer1; PCAMahalanobisAnalyzer tempPcaAnalyzer2; PCAMahalanobisAnalyzer tempPcaAnalyzer3; PCAMahalanobisAnalyzer tempPcaAnalyzer4; //Morphology tempPcaAnalyzer0.clear(); //Signal to noise ratio tempPcaAnalyzer1.clear(); tempPcaAnalyzer2.clear(); tempPcaAnalyzer3.clear(); //Histogram analysis, to detect black points and saturated parts tempPcaAnalyzer4.clear(); double sign = 1;//;-1; int numNorm = 3; int numDescriptors0=numNorm; int numDescriptors2=4; int numDescriptors3=11; int numDescriptors4 = 10; MultidimArray<float> v0(numDescriptors0); MultidimArray<float> v2(numDescriptors2); MultidimArray<float> v3(numDescriptors3); MultidimArray<float> v4(numDescriptors4); if (verbose>0) { std::cout << " Sorting particle set by new xmipp method..." << std::endl; } int nr_imgs = SF.size(); if (verbose>0) init_progress_bar(nr_imgs); int c = XMIPP_MAX(1, nr_imgs / 60); int imgno = 0, imgnoPCA=0; bool thereIsEnable=SF.containsLabel(MDL_ENABLED); bool first=true; // We assume that at least there is one particle size_t Xdim, Ydim, Zdim, Ndim; getImageSize(SF,Xdim,Ydim,Zdim,Ndim); //Initialization: MultidimArray<double> nI, modI, tempI, tempM, ROI; MultidimArray<bool> mask; nI.resizeNoCopy(Ydim,Xdim); modI.resizeNoCopy(Ydim,Xdim); tempI.resizeNoCopy(Ydim,Xdim); tempM.resizeNoCopy(Ydim,Xdim); mask.resizeNoCopy(Ydim,Xdim); mask.initConstant(true); MultidimArray<double> autoCorr(2*Ydim,2*Xdim); MultidimArray<double> smallAutoCorr; Histogram1D hist; Matrix2D<double> U,V,temp; Matrix1D<double> D; MultidimArray<int> radial_count; MultidimArray<double> radial_avg; Matrix1D<int> center(2); MultidimArray<int> distance; int dim; center.initZeros(); v0.initZeros(numDescriptors0); v2.initZeros(numDescriptors2); v3.initZeros(numDescriptors3); v4.initZeros(numDescriptors4); ROI.resizeNoCopy(Ydim,Xdim); ROI.setXmippOrigin(); FOR_ALL_ELEMENTS_IN_ARRAY2D(ROI) { double temp = std::sqrt(i*i+j*j); if ( temp < (Xdim/2)) A2D_ELEM(ROI,i,j)= 1; else A2D_ELEM(ROI,i,j)= 0; } Image<double> img; FourierTransformer transformer(FFTW_BACKWARD); FOR_ALL_OBJECTS_IN_METADATA(SF) { if (thereIsEnable) { int enabled; SF.getValue(MDL_ENABLED,enabled,__iter.objId); if ( (enabled==-1) ) { imgno++; continue; } } img.readApplyGeo(SF,__iter.objId); if (targetXdim!=-1 && targetXdim!=XSIZE(img())) selfScaleToSize(LINEAR,img(),targetXdim,targetXdim,1); MultidimArray<double> &mI=img(); mI.setXmippOrigin(); mI.statisticsAdjust(0,1); mask.setXmippOrigin(); //The size of v1 depends on the image size and must be declared here int numDescriptors1 = XSIZE(mI)/2; //=100; MultidimArray<float> v1(numDescriptors1); v1.initZeros(numDescriptors1); double var = 1; normalize(transformer,mI,tempI,modI,0,var,mask); modI.setXmippOrigin(); tempI.setXmippOrigin(); nI = sign*tempI*(modI*modI); tempM = (modI*modI); A1D_ELEM(v0,0) = (tempM*ROI).sum(); int index = 1; var+=2; while (index < numNorm) { normalize(transformer,mI,tempI,modI,0,var,mask); modI.setXmippOrigin(); tempI.setXmippOrigin(); nI += sign*tempI*(modI*modI); tempM += (modI*modI); A1D_ELEM(v0,index) = (tempM*ROI).sum(); index++; var+=2; } nI /= tempM; tempPcaAnalyzer0.addVector(v0); nI=(nI*ROI); auto_correlation_matrix(mI,autoCorr); if (first) { radialAveragePrecomputeDistance(autoCorr, center, distance, dim); first=false; } fastRadialAverage(autoCorr, distance, dim, radial_avg, radial_count); for (int n = 0; n < numDescriptors1; ++n) A1D_ELEM(v1,n)=(float)DIRECT_A1D_ELEM(radial_avg,n); tempPcaAnalyzer1.addVector(v1); #ifdef DEBUG //String name = "000005@Images/Extracted/run_002/extra/BPV_1386.stk"; String name = "000010@Images/Extracted/run_001/extra/KLH_Dataset_I_Training_0028.stk"; //String name = "001160@Images/Extracted/run_001/DefaultFamily5"; std::cout << img.name() << std::endl; if (img.name()==name2) { FileName fpName = "test_1.txt"; mI.write(fpName); fpName = "test_2.txt"; nI.write(fpName); fpName = "test_3.txt"; tempM.write(fpName); fpName = "test_4.txt"; ROI.write(fpName); //exit(1); } #endif nI.binarize(0); int im = labelImage2D(nI,nI,8); compute_hist(nI, hist, 0, im, im+1); size_t l; int k,i,j; hist.maxIndex(l,k,i,j); A1D_ELEM(hist,j)=0; hist.maxIndex(l,k,i,j); nI.binarizeRange(j-1,j+1); double x0=0,y0=0,majorAxis=0,minorAxis=0,ellipAng=0; size_t area=0; fitEllipse(nI,x0,y0,majorAxis,minorAxis,ellipAng,area); A1D_ELEM(v2,0)=majorAxis/((img().xdim) ); A1D_ELEM(v2,1)=minorAxis/((img().xdim) ); A1D_ELEM(v2,2)= (fabs((img().xdim)/2-x0)+fabs((img().ydim)/2-y0))/((img().xdim)/2); A1D_ELEM(v2,3)=area/( (double)((img().xdim)/2)*((img().ydim)/2) ); for (int n=0 ; n < numDescriptors2 ; n++) { if ( std::isnan(std::abs(A1D_ELEM(v2,n)))) A1D_ELEM(v2,n)=0; } tempPcaAnalyzer2.addVector(v2); //mI.setXmippOrigin(); //auto_correlation_matrix(mI*ROI,autoCorr); //auto_correlation_matrix(nI,autoCorr); autoCorr.window(smallAutoCorr,-5,-5, 5, 5); smallAutoCorr.copy(temp); svdcmp(temp,U,D,V); for (int n = 0; n < numDescriptors3; ++n) A1D_ELEM(v3,n)=(float)VEC_ELEM(D,n); //A1D_ELEM(v3,n)=(float)VEC_ELEM(D,n)/VEC_ELEM(D,0); tempPcaAnalyzer3.addVector(v3); double minVal=0.; double maxVal=0.; mI.computeDoubleMinMax(minVal,maxVal); compute_hist(mI, hist, minVal, maxVal, 100); for (int n=0 ; n <= numDescriptors4-1 ; n++) { A1D_ELEM(v4,n)= (hist.percentil((n+1)*10)); } tempPcaAnalyzer4.addVector(v4); #ifdef DEBUG if (img.name()==name1) { FileName fpName = "test.txt"; mI.write(fpName); fpName = "test3.txt"; nI.write(fpName); } #endif imgno++; imgnoPCA++; if (imgno % c == 0 && verbose>0) progress_bar(imgno); } tempPcaAnalyzer0.evaluateZScore(2,20,trained); tempPcaAnalyzer1.evaluateZScore(2,20,trained); tempPcaAnalyzer2.evaluateZScore(2,20,trained); tempPcaAnalyzer3.evaluateZScore(2,20,trained); tempPcaAnalyzer4.evaluateZScore(2,20,trained); pcaAnalyzer.push_back(tempPcaAnalyzer0); pcaAnalyzer.push_back(tempPcaAnalyzer1); pcaAnalyzer.push_back(tempPcaAnalyzer1); pcaAnalyzer.push_back(tempPcaAnalyzer3); pcaAnalyzer.push_back(tempPcaAnalyzer4); }
int main (int, char**) { UnitTest t (76); Variant v0 (true); Variant v1 (42); Variant v2 (3.14); Variant v3 ("foo"); Variant v4 (1234567890, Variant::type_date); Variant v5 (1200, Variant::type_duration); // Truth table. Variant vFalse (false); Variant vTrue (true); t.is (vFalse && vFalse, false, "false && false --> false"); t.is (vFalse && vTrue, false, "false && true --> false"); t.is (vTrue && vFalse, false, "true && false --> false"); t.is (vTrue && vTrue, true, "true && true --> true"); Variant v00 = v0 && v0; t.is (v00.type (), Variant::type_boolean, "true && true --> boolean"); t.is (v00.get_bool (), true, "true && true --> true"); Variant v01 = v0 && v1; t.is (v01.type (), Variant::type_boolean, "true && 42 --> boolean"); t.is (v01.get_bool (), true, "true && 42 --> true"); Variant v02 = v0 && v2; t.is (v02.type (), Variant::type_boolean, "true && 3.14 --> boolean"); t.is (v02.get_bool (), true, "true && 3.14 --> true"); Variant v03 = v0 && v3; t.is (v03.type (), Variant::type_boolean, "true && 'foo' --> boolean"); t.is (v03.get_bool (), true, "true && 'foo' --> true"); Variant v04 = v0 && v4; t.is (v04.type (), Variant::type_boolean, "true && 1234567890 --> boolean"); t.is (v04.get_bool (), true, "true && 1234567890 --> true"); Variant v05 = v0 && v5; t.is (v05.type (), Variant::type_boolean, "true && 1200 --> boolean"); t.is (v05.get_bool (), true, "true && 1200 --> true"); Variant v10 = v1 && v0; t.is (v10.type (), Variant::type_boolean, "42 && true --> boolean"); t.is (v10.get_bool (), true, "42 && true --> true"); Variant v11 = v1 && v1; t.is (v11.type (), Variant::type_boolean, "42 && 42 --> boolean"); t.is (v11.get_bool (), true, "42 && 42 --> true"); Variant v12 = v1 && v2; t.is (v12.type (), Variant::type_boolean, "42 && 3.14 --> boolean"); t.is (v12.get_bool (), true, "42 && 3.14 --> true"); Variant v13 = v1 && v3; t.is (v13.type (), Variant::type_boolean, "42 && 'foo' --> boolean"); t.is (v13.get_bool (), true, "42 && 'foo' --> true"); Variant v14 = v1 && v4; t.is (v04.type (), Variant::type_boolean, "42 && 1234567890 --> boolean"); t.is (v04.get_bool (), true, "42 && 1234567890 --> true"); Variant v15 = v1 && v5; t.is (v15.type (), Variant::type_boolean, "42 && 1200 --> boolean"); t.is (v15.get_bool (), true, "42 && 1200 --> true"); Variant v20 = v2 && v0; t.is (v20.type (), Variant::type_boolean, "3.14 && true --> boolean"); t.is (v20.get_bool (), true, "3.14 && true --> true"); Variant v21 = v2 && v1; t.is (v21.type (), Variant::type_boolean, "3.14 && 42 --> boolean"); t.is (v21.get_bool (), true, "3.14 && 42 --> true"); Variant v22 = v2 && v2; t.is (v22.type (), Variant::type_boolean, "3.14 && 3.14 --> boolean"); t.is (v22.get_bool (), true, "3.14 && 3.14 --> true"); Variant v23 = v2 && v3; t.is (v23.type (), Variant::type_boolean, "3.14 && 'foo' --> boolean"); t.is (v23.get_bool (), true, "3.14 && 'foo' --> true"); Variant v24 = v2 && v4; t.is (v24.type (), Variant::type_boolean, "3.14 && 1234567890 --> boolean"); t.is (v24.get_bool (), true, "3.14 && 1234567890 --> true"); Variant v25 = v2 && v5; t.is (v25.type (), Variant::type_boolean, "3.14 && 1200 --> boolean"); t.is (v25.get_bool (), true, "3.14 && 1200 --> true"); Variant v30 = v3 && v0; t.is (v30.type (), Variant::type_boolean, "'foo' && true --> boolean"); t.is (v30.get_bool (), true, "'foo' && true --> true"); Variant v31 = v3 && v1; t.is (v31.type (), Variant::type_boolean, "'foo' && 42 --> boolean"); t.is (v31.get_bool (), true, "'foo' && 42 --> true"); Variant v32 = v3 && v2; t.is (v32.type (), Variant::type_boolean, "'foo' && 3.14 --> boolean"); t.is (v32.get_bool (), true, "'foo' && 3.14 --> true"); Variant v33 = v3 && v3; t.is (v33.type (), Variant::type_boolean, "'foo' && 'foo' --> boolean"); t.is (v33.get_bool (), true, "'foo' && 'foo' --> true"); Variant v34 = v3 && v4; t.is (v34.type (), Variant::type_boolean, "'foo' && 1234567890 --> boolean"); t.is (v34.get_bool (), true, "'foo' && 1234567890 --> true"); Variant v35 = v3 && v5; t.is (v35.type (), Variant::type_boolean, "'foo' && 1200 --> boolean"); t.is (v35.get_bool (), true, "'foo' && 1200 --> true"); Variant v40 = v4 && v0; t.is (v40.type (), Variant::type_boolean, "1234567890 && true --> boolean"); t.is (v40.get_bool (), true, "1234567890 && true --> true"); Variant v41 = v4 && v1; t.is (v41.type (), Variant::type_boolean, "1234567890 && 42 --> boolean"); t.is (v41.get_bool (), true, "1234567890 && 42 --> true"); Variant v42 = v4 && v2; t.is (v42.type (), Variant::type_boolean, "1234567890 && 3.14 --> boolean"); t.is (v42.get_bool (), true, "1234567890 && 3.14 --> true"); Variant v43 = v4 && v3; t.is (v43.type (), Variant::type_boolean, "1234567890 && 'foo' --> boolean"); t.is (v43.get_bool (), true, "1234567890 && 'foo' --> true"); Variant v44 = v4 && v4; t.is (v44.type (), Variant::type_boolean, "1234567890 && 1234567890 --> boolean"); t.is (v44.get_bool (), true, "1234567890 && 1234567890 --> true"); Variant v45 = v4 && v5; t.is (v45.type (), Variant::type_boolean, "1234567890 && 1200 --> boolean"); t.is (v45.get_bool (), true, "1234567890 && 1200 --> true"); Variant v50 = v5 && v0; t.is (v50.type (), Variant::type_boolean, "1200 && true --> boolean"); t.is (v50.get_bool (), true, "1200 && true --> true"); Variant v51 = v5 && v1; t.is (v51.type (), Variant::type_boolean, "1200 && 42 --> boolean"); t.is (v51.get_bool (), true, "1200 && 42 --> true"); Variant v52 = v5 && v2; t.is (v52.type (), Variant::type_boolean, "1200 && 3.14 --> boolean"); t.is (v52.get_bool (), true, "1200 && 3.14 --> true"); Variant v53 = v5 && v3; t.is (v53.type (), Variant::type_boolean, "1200 && 'foo' --> boolean"); t.is (v53.get_bool (), true, "1200 && 'foo' --> true"); Variant v54 = v5 && v4; t.is (v04.type (), Variant::type_boolean, "1200 && 1234567890 --> boolean"); t.is (v04.get_bool (), true, "1200 && 1234567890 --> true"); Variant v55 = v5 && v5; t.is (v55.type (), Variant::type_boolean, "1200 && 1200 --> boolean"); t.is (v55.get_bool (), true, "1200 && 1200 --> true"); return 0; }
Primitive* CGALImport::importSTL(QFileInfo fileinfo) { CGALPrimitive* p=new CGALPrimitive(); QFile f(fileinfo.absoluteFilePath()); if(!f.open(QIODevice::ReadOnly)) { output << "WARNING: Can't open import file '" << fileinfo.absoluteFilePath() << "'\n"; return p; } QByteArray header=f.read(5); if(header.size()==5 && QString(header)=="solid") { QTextStream data(&f); QRegExp re=QRegExp("\\s*(vertex)?\\s+"); while(!data.atEnd()) { QString line=data.readLine(); if(line.contains("solid") || line.contains("facet") || line.contains("endloop")) continue; if(line.contains("outer loop")) { p->createPolygon(); continue; } if(line.contains("vertex")) { QStringList tokens=line.split(re); bool ok=false; if(tokens.size()==4) { double x,y,z; bool ox,oy,oz; x=tokens[1].toDouble(&ox); y=tokens[2].toDouble(&oy); z=tokens[3].toDouble(&oz); if((ok=ox&&oy&&oz)) { CGAL::Point3 pt(x,y,z); p->appendVertex(pt); } } if(!ok) { output << "WARNING: Can't parse vertex line '" << line << "'\n"; } } } } else { f.read(80-5+4); while(1) { struct { float i, j, k; float x1, y1, z1; float x2, y2, z2; float x3, y3, z3; unsigned short acount; } __attribute__((packed)) data; if(f.read((char*)&data, sizeof(data)) != sizeof(data)) break; p->createPolygon(); CGAL::Point3 v1(data.x1,data.y1,data.z1); p->appendVertex(v1); CGAL::Point3 v2(data.x2,data.y2,data.z2); p->appendVertex(v2); CGAL::Point3 v3(data.x3,data.y3,data.z3); p->appendVertex(v3); } } return p->buildPrimitive(); }
// Hotrod 2.8 with mediatype allows to store and retrieve entries in different data format // this can be done specifying the mediatype for the communication int main(int argc, char** argv) { ConfigurationBuilder builder; builder.protocolVersion(Configuration::PROTOCOL_VERSION_28); builder.addServer().host("127.0.0.1").port(11222); builder.balancingStrategyProducer(nullptr); RemoteCacheManager cacheManager(builder.build(), false); cacheManager.start(); std::cout << "Tests for CacheManager" << std::endl; Marshaller<std::string> *km = new JBasicMarshaller<std::string>(); Marshaller<std::string> *vm = new JBasicMarshaller<std::string>(); RemoteCache<std::string, std::string> cache = cacheManager.getCache<std::string, std::string>(km, &Marshaller<std::string>::destroy, vm, &Marshaller<std::string>::destroy, std::string("transcodingCache")); // Define a data format for json DataFormat<std::string, std::string> df; df.keyMediaType = MediaType(APPLICATION_UNKNOWN_TYPE); df.valueMediaType = MediaType(APPLICATION_JSON_TYPE); df.valueMarshaller.reset(new BasicMarshaller<std::string>()); RemoteCache<std::string, std::string> cacheJson = cache.withDataFormat(&df); // Define a data forma for jboss marshaller DataFormat<std::string, std::string> df1; df1.keyMediaType = MediaType(APPLICATION_JBOSS_MARSHALLING_TYPE); df1.valueMediaType = MediaType(APPLICATION_JBOSS_MARSHALLING_TYPE); RemoteCache<std::string, std::string> cacheJBoss = cache.withDataFormat(&df1); std::string k1("key13"); std::string k2("key14"); std::string v1("boron"); std::string v2("chlorine"); cache.clear(); // put cache.put(k1, v1); std::unique_ptr<std::string> rv(cache.get(k1)); assert_not_null("get returned null!", __LINE__, rv); if (rv->compare(v1)) { std::cerr << "get/put fail for " << k1 << " got " << *rv << " expected " << v1 << std::endl; return 1; } cache.put(k2, v2); std::unique_ptr<std::string> rv2(cache.get(k2)); assert_not_null("get returned null!", __LINE__, rv2); if (rv2->compare(v2)) { std::cerr << "get/put fail for " << k2 << " got " << *rv2 << " expected " << v2 << std::endl; return 1; } std::unique_ptr<std::string> rv2Json(cacheJson.get(k2)); assert_not_null("get returned null!", __LINE__, rv2Json); if (rv2Json->compare("\"chlorine\"")) { std::cerr << "get/put fail for " << k2 << " got " << *rv2 << " expected \"boron\"" << std::endl; return 1; } std::unique_ptr<std::string> rv2JBoss(cacheJBoss.get(k2)); assert_not_null("get returned null!", __LINE__, rv2JBoss); if (rv2JBoss->compare(v2)) { std::cerr << "get/put fail for " << k2 << " got " << *rv2JBoss << " expected " << v2 << std::endl; return 1; } }
int main(int argc, char *argv[]) { int ierr = 0, i, j, forierr = 0; #ifdef EPETRA_MPI // Initialize MPI MPI_Init(&argc,&argv); Epetra_MpiComm Comm( MPI_COMM_WORLD ); #else Epetra_SerialComm Comm; #endif bool verbose = false; // Check if we should print results to standard out if (argc>1) if (argv[1][0]=='-' && argv[1][1]=='v') verbose = true; //char tmp; //if (Comm.MyPID()==0) cout << "Press any key to continue..."<< endl; //if (Comm.MyPID()==0) cin >> tmp; //Comm.Barrier(); Comm.SetTracebackMode(0); // This should shut down any error traceback reporting int MyPID = Comm.MyPID(); int NumProc = Comm.NumProc(); if (verbose && MyPID==0) cout << Epetra_Version() << endl << endl; if (verbose) cout << "Processor "<<MyPID<<" of "<< NumProc << " is alive."<<endl; // Redefine verbose to only print on PE 0 if (verbose && Comm.MyPID()!=0) verbose = false; int NumMyEquations = 20; long long NumGlobalEquations = NumMyEquations*NumProc+EPETRA_MIN(NumProc,3); if (MyPID < 3) NumMyEquations++; // Construct a Source Map that puts approximately the same Number of equations on each processor in // uniform global ordering Epetra_Map SourceMap(NumGlobalEquations, NumMyEquations, 0LL, Comm); // Get update list and number of local equations from newly created Map int NumMyElements = SourceMap.NumMyElements(); long long * SourceMyGlobalElements = new long long[NumMyElements]; SourceMap.MyGlobalElements(SourceMyGlobalElements); // Construct a Target Map that will contain: // some unchanged elements (relative to the soure map), // some permuted elements // some off-processor elements Epetra_Vector RandVec(SourceMap); RandVec.Random(); // This creates a vector of random numbers between negative one and one. long long *TargetMyGlobalElements = new long long[NumMyElements]; long long MinGID = SourceMap.MinMyGID64(); for (i=0; i< NumMyEquations/2; i++) TargetMyGlobalElements[i] = i + MinGID; // Half will be the same... for (i=NumMyEquations/2; i<NumMyEquations; i++) { int index = abs((int)(((double) (NumGlobalEquations-1) ) * RandVec[i])); TargetMyGlobalElements[i] = EPETRA_MIN(NumGlobalEquations-1,(long long) EPETRA_MAX(0,index)); } int NumSameIDs = 0; int NumPermutedIDs = 0; int NumRemoteIDs = 0; bool StillContiguous = true; for (i=0; i < NumMyEquations; i++) { if (SourceMyGlobalElements[i]==TargetMyGlobalElements[i] && StillContiguous) NumSameIDs++; else if (SourceMap.MyGID(TargetMyGlobalElements[i])) { StillContiguous = false; NumPermutedIDs++; } else { StillContiguous = false; NumRemoteIDs++; } } EPETRA_TEST_ERR(!(NumMyEquations==NumSameIDs+NumPermutedIDs+NumRemoteIDs),ierr); Epetra_Map TargetMap((long long) -1, NumMyElements, TargetMyGlobalElements, 0LL, Comm); // Create a multivector whose elements are GlobalID * (column number +1) int NumVectors = 3; Epetra_MultiVector SourceMultiVector(SourceMap, NumVectors); for (j=0; j < NumVectors; j++) for (i=0; i < NumMyElements; i++) SourceMultiVector[j][i] = (double) SourceMyGlobalElements[i]*(j+1); // Create a target multivector that we will fill using an Import Epetra_MultiVector TargetMultiVector(TargetMap, NumVectors); Epetra_Import Importer(TargetMap, SourceMap); EPETRA_TEST_ERR(!(TargetMultiVector.Import(SourceMultiVector, Importer, Insert)==0),ierr); // Test Target against expected values forierr = 0; for (j=0; j < NumVectors; j++) for (i=0; i < NumMyElements; i++) { if (TargetMultiVector[j][i]!= (double) TargetMyGlobalElements[i]*(j+1)) cout << "TargetMultiVector["<<i<<"]["<<j<<"] = " << TargetMultiVector[j][i] << " TargetMyGlobalElements[i]*(j+1) = " << TargetMyGlobalElements[i]*(j+1) << endl; forierr += !(TargetMultiVector[j][i]== (double) TargetMyGlobalElements[i]*(j+1)); } EPETRA_TEST_ERR(forierr,ierr); if (verbose) cout << "MultiVector Import using Importer Check OK" << endl << endl; ////////////////////////////////////////////////////////////////////////////// // Now use Importer to do an export Epetra_Vector TargetVector(SourceMap); Epetra_Vector ExpectedTarget(SourceMap); Epetra_Vector SourceVector(TargetMap); NumSameIDs = Importer.NumSameIDs(); int NumPermuteIDs = Importer.NumPermuteIDs(); int NumExportIDs = Importer.NumExportIDs(); int *PermuteFromLIDs = Importer.PermuteFromLIDs(); int *ExportLIDs = Importer.ExportLIDs(); int *ExportPIDs = Importer.ExportPIDs(); for (i=0; i < NumSameIDs; i++) ExpectedTarget[i] = (double) (MyPID+1); for (i=0; i < NumPermuteIDs; i++) ExpectedTarget[PermuteFromLIDs[i]] = (double) (MyPID+1); for (i=0; i < NumExportIDs; i++) ExpectedTarget[ExportLIDs[i]] += (double) (ExportPIDs[i]+1); for (i=0; i < NumMyElements; i++) SourceVector[i] = (double) (MyPID+1); EPETRA_TEST_ERR(!(TargetVector.Export(SourceVector, Importer, Add)==0),ierr); forierr = 0; for (i=0; i < NumMyElements; i++) { if (TargetVector[i]!= ExpectedTarget[i]) cout << " TargetVector["<<i<<"] = " << TargetVector[i] << " ExpectedTarget["<<i<<"] = " << ExpectedTarget[i] << " on PE " << MyPID << endl; forierr += !(TargetVector[i]== ExpectedTarget[i]); } EPETRA_TEST_ERR(forierr,ierr); if (verbose) cout << "Vector Export using Importer Check OK" << endl << endl; ////////////////////////////////////////////////////////////////////////////// // Now use Importer to create a reverse exporter TargetVector.PutScalar(0.0); Epetra_Export ReversedImport(Importer); EPETRA_TEST_ERR(!(TargetVector.Export(SourceVector, ReversedImport, Add)==0),ierr); forierr = 0; for (i=0; i < NumMyElements; i++) { if (TargetVector[i]!= ExpectedTarget[i]) cout << " TargetVector["<<i<<"] = " << TargetVector[i] << " ExpectedTarget["<<i<<"] = " << ExpectedTarget[i] << " on PE " << MyPID << endl; forierr += !(TargetVector[i]== ExpectedTarget[i]); } EPETRA_TEST_ERR(forierr,ierr); if (verbose) cout << "Vector Export using Reversed Importer Check OK" << endl << endl; ////////////////////////////////////////////////////////////////////////////// // Now use Exporter to create a reverse importer TargetVector.PutScalar(0.0); Epetra_Import ReversedExport(ReversedImport); EPETRA_TEST_ERR(!(TargetVector.Export(SourceVector, ReversedExport, Add)==0),ierr); forierr = 0; for (i=0; i < NumMyElements; i++) { if (TargetVector[i]!= ExpectedTarget[i]) cout << " TargetVector["<<i<<"] = " << TargetVector[i] << " ExpectedTarget["<<i<<"] = " << ExpectedTarget[i] << " on PE " << MyPID << endl; forierr += !(TargetVector[i]== ExpectedTarget[i]); } EPETRA_TEST_ERR(forierr,ierr); if (verbose) cout << "Vector Export using Reversed Exporter Check OK" << endl << endl; ////////////////////////////////////////////////////////////////////////////////////////// // Build a tridiagonal system two ways: // 1) From "standard" matrix view where equations are uniquely owned. // 2) From 1D PDE view where nodes (equations) between processors are shared and partial contributions are done // in parallel, then merged together at the end of the construction process. // ////////////////////////////////////////////////////////////////////////////////////////// // Construct a Standard Map that puts approximately the same number of equations on each processor in // uniform global ordering Epetra_Map StandardMap(NumGlobalEquations, NumMyEquations, 0LL, Comm); // Get update list and number of local equations from newly created Map NumMyElements = StandardMap.NumMyElements(); long long * StandardMyGlobalElements = new long long[NumMyElements]; StandardMap.MyGlobalElements(StandardMyGlobalElements); // Create a standard Epetra_CrsGraph Epetra_CrsGraph StandardGraph(Copy, StandardMap, 3); EPETRA_TEST_ERR(StandardGraph.IndicesAreGlobal(),ierr); EPETRA_TEST_ERR(StandardGraph.IndicesAreLocal(),ierr); // Add rows one-at-a-time // Need some vectors to help // Off diagonal Values will always be -1 long long *Indices = new long long[2]; int NumEntries; forierr = 0; for (i=0; i<NumMyEquations; i++) { if (StandardMyGlobalElements[i]==0) { Indices[0] = 1; NumEntries = 1; } else if (StandardMyGlobalElements[i] == NumGlobalEquations-1) { Indices[0] = NumGlobalEquations-2; NumEntries = 1; } else { Indices[0] = StandardMyGlobalElements[i]-1; Indices[1] = StandardMyGlobalElements[i]+1; NumEntries = 2; } forierr += !(StandardGraph.InsertGlobalIndices(StandardMyGlobalElements[i], NumEntries, Indices)==0); forierr += !(StandardGraph.InsertGlobalIndices(StandardMyGlobalElements[i], 1, StandardMyGlobalElements+i)==0); // Put in the diagonal entry } EPETRA_TEST_ERR(forierr,ierr); // Finish up EPETRA_TEST_ERR(!(StandardGraph.IndicesAreGlobal()),ierr); EPETRA_TEST_ERR(!(StandardGraph.FillComplete()==0),ierr); EPETRA_TEST_ERR(!(StandardGraph.IndicesAreLocal()),ierr); EPETRA_TEST_ERR(StandardGraph.StorageOptimized(),ierr); StandardGraph.OptimizeStorage(); EPETRA_TEST_ERR(!(StandardGraph.StorageOptimized()),ierr); EPETRA_TEST_ERR(StandardGraph.UpperTriangular(),ierr); EPETRA_TEST_ERR(StandardGraph.LowerTriangular(),ierr); // Create Epetra_CrsMatrix using the just-built graph Epetra_CrsMatrix StandardMatrix(Copy, StandardGraph); EPETRA_TEST_ERR(StandardMatrix.IndicesAreGlobal(),ierr); EPETRA_TEST_ERR(!(StandardMatrix.IndicesAreLocal()),ierr); // Add rows one-at-a-time // Need some vectors to help // Off diagonal Values will always be -1 double *Values = new double[2]; Values[0] = -1.0; Values[1] = -1.0; double two = 2.0; forierr = 0; for (i=0; i<NumMyEquations; i++) { if (StandardMyGlobalElements[i]==0) { Indices[0] = 1; NumEntries = 1; } else if (StandardMyGlobalElements[i] == NumGlobalEquations-1) { Indices[0] = NumGlobalEquations-2; NumEntries = 1; } else { Indices[0] = StandardMyGlobalElements[i]-1; Indices[1] = StandardMyGlobalElements[i]+1; NumEntries = 2; } forierr += !(StandardMatrix.ReplaceGlobalValues(StandardMyGlobalElements[i], NumEntries, Values, Indices)==0); // Put in the diagonal entry forierr += !(StandardMatrix.ReplaceGlobalValues(StandardMyGlobalElements[i], 1, &two, StandardMyGlobalElements+i)==0); } EPETRA_TEST_ERR(forierr,ierr); // Finish up EPETRA_TEST_ERR(!(StandardMatrix.IndicesAreLocal()),ierr); EPETRA_TEST_ERR(!(StandardMatrix.FillComplete()==0),ierr); EPETRA_TEST_ERR(!(StandardMatrix.IndicesAreLocal()),ierr); // EPETRA_TEST_ERR((StandardMatrix.StorageOptimized()),ierr); EPETRA_TEST_ERR((StandardMatrix.OptimizeStorage()),ierr); EPETRA_TEST_ERR(!(StandardMatrix.StorageOptimized()),ierr); EPETRA_TEST_ERR(StandardMatrix.UpperTriangular(),ierr); EPETRA_TEST_ERR(StandardMatrix.LowerTriangular(),ierr); // Construct an Overlapped Map of StandardMap that include the endpoints from two neighboring processors. int OverlapNumMyElements; long long OverlapMinMyGID; OverlapNumMyElements = NumMyElements + 1; if (MyPID==0) OverlapNumMyElements--; if (MyPID==0) OverlapMinMyGID = StandardMap.MinMyGID64(); else OverlapMinMyGID = StandardMap.MinMyGID64()-1; long long * OverlapMyGlobalElements = new long long[OverlapNumMyElements]; for (i=0; i< OverlapNumMyElements; i++) OverlapMyGlobalElements[i] = OverlapMinMyGID + i; Epetra_Map OverlapMap((long long) -1, OverlapNumMyElements, OverlapMyGlobalElements, 0LL, Comm); // Create the Overlap Epetra_Matrix Epetra_CrsMatrix OverlapMatrix(Copy, OverlapMap, 4); EPETRA_TEST_ERR(OverlapMatrix.IndicesAreGlobal(),ierr); EPETRA_TEST_ERR(OverlapMatrix.IndicesAreLocal(),ierr); // Add matrix element one cell at a time. // Each cell does an incoming and outgoing flux calculation double pos_one = 1.0; double neg_one = -1.0; forierr = 0; for (i=0; i<OverlapNumMyElements; i++) { long long node_left = OverlapMyGlobalElements[i]-1; long long node_center = node_left + 1; long long node_right = node_left + 2; if (i>0) { if (node_left>-1) forierr += !(OverlapMatrix.InsertGlobalValues(node_center, 1, &neg_one, &node_left)==0); forierr += !(OverlapMatrix.InsertGlobalValues(node_center, 1, &pos_one, &node_center)==0); } if (i<OverlapNumMyElements-1) { forierr += !(OverlapMatrix.InsertGlobalValues(node_center, 1, &pos_one, &node_center)==0); if (node_right<NumGlobalEquations) forierr += !(OverlapMatrix.InsertGlobalValues(node_center, 1, &neg_one, &node_right)==0); } } EPETRA_TEST_ERR(forierr,ierr); // Handle endpoints if (MyPID==0) { long long node_center = 0; EPETRA_TEST_ERR(!(OverlapMatrix.InsertGlobalValues(node_center, 1, &pos_one, &node_center)==0),ierr); } if (MyPID==NumProc-1) { long long node_center = OverlapMyGlobalElements[OverlapNumMyElements-1]; EPETRA_TEST_ERR(!(OverlapMatrix.InsertGlobalValues(node_center, 1, &pos_one, &node_center)==0),ierr); } EPETRA_TEST_ERR(!(OverlapMatrix.FillComplete()==0),ierr); // Make a gathered matrix from OverlapMatrix. It should be identical to StandardMatrix Epetra_CrsMatrix GatheredMatrix(Copy, StandardGraph); Epetra_Export Exporter(OverlapMap, StandardMap); EPETRA_TEST_ERR(!(GatheredMatrix.Export(OverlapMatrix, Exporter, Add)==0),ierr); EPETRA_TEST_ERR(!(GatheredMatrix.FillComplete()==0),ierr); // Check if entries of StandardMatrix and GatheredMatrix are identical int StandardNumEntries, GatheredNumEntries; int * StandardIndices, * GatheredIndices; double * StandardValues, * GatheredValues; int StandardNumMyNonzeros = StandardMatrix.NumMyNonzeros(); int GatheredNumMyNonzeros = GatheredMatrix.NumMyNonzeros(); EPETRA_TEST_ERR(!(StandardNumMyNonzeros==GatheredNumMyNonzeros),ierr); int StandardNumMyRows = StandardMatrix.NumMyRows(); int GatheredNumMyRows = GatheredMatrix.NumMyRows(); EPETRA_TEST_ERR(!(StandardNumMyRows==GatheredNumMyRows),ierr); forierr = 0; for (i=0; i< StandardNumMyRows; i++) { forierr += !(StandardMatrix.ExtractMyRowView(i, StandardNumEntries, StandardValues, StandardIndices)==0); forierr += !(GatheredMatrix.ExtractMyRowView(i, GatheredNumEntries, GatheredValues, GatheredIndices)==0); forierr += !(StandardNumEntries==GatheredNumEntries); for (j=0; j < StandardNumEntries; j++) { //if (StandardIndices[j]!=GatheredIndices[j]) // cout << "MyPID = " << MyPID << " i = " << i << " StandardIndices[" << j << "] = " << StandardIndices[j] // << " GatheredIndices[" << j << "] = " << GatheredIndices[j] << endl; //if (StandardValues[j]!=GatheredValues[j]) //cout << "MyPID = " << MyPID << " i = " << i << " StandardValues[" << j << "] = " << StandardValues[j] // << " GatheredValues[" << j << "] = " << GatheredValues[j] << endl; forierr += !(StandardIndices[j]==GatheredIndices[j]); forierr += !(StandardValues[j]==GatheredValues[j]); } } EPETRA_TEST_ERR(forierr,ierr); if (verbose) cout << "Matrix Export Check OK" << endl << endl; //Do Again with use of Epetra_OffsetIndex object for speed Epetra_OffsetIndex OffsetIndex( OverlapMatrix.Graph(), GatheredMatrix.Graph(), Exporter ); EPETRA_TEST_ERR(!(GatheredMatrix.Export(OverlapMatrix, Exporter, Add)==0),ierr); if (verbose) cout << "Optimized Matrix Export Check OK" << endl << endl; bool passed; Epetra_LongLongVector v1(StandardMap); v1.PutValue(2); Epetra_LongLongVector v2(StandardMap); v2.PutValue(3); Epetra_Export identExporter(StandardMap,StandardMap); // Identity exporter EPETRA_TEST_ERR(!(v2.Export(v1, identExporter, Insert)==0),ierr); passed = (v2.MinValue()==2); EPETRA_TEST_ERR(!passed,ierr); v1.PutValue(1); Epetra_Import identImporter(StandardMap,StandardMap); // Identity importer EPETRA_TEST_ERR(!(v2.Import(v1, identExporter, Insert)==0),ierr); passed = passed && (v2.MaxValue()==1); EPETRA_TEST_ERR(!passed,ierr); if (verbose) { if (passed) cout << "Identity Import/Export Check OK" << endl << endl; else cout << "Identity Import/Export Check Failed" << endl << endl; } int NumSubMapElements = StandardMap.NumMyElements()/2; int SubStart = Comm.MyPID(); NumSubMapElements = EPETRA_MIN(NumSubMapElements,StandardMap.NumMyElements()-SubStart); Epetra_Map SubMap((long long) -1, NumSubMapElements, StandardMyGlobalElements+SubStart, 0LL, Comm); Epetra_LongLongVector v3(View, SubMap, SubMap.MyGlobalElements64()); // Fill v3 with GID values for variety Epetra_Export subExporter(SubMap, StandardMap); // Export to a subset of indices of standard map EPETRA_TEST_ERR(!(v2.Export(v3,subExporter,Insert)==0),ierr); forierr = 0; for (i=0; i<SubMap.NumMyElements(); i++) { int i1 = StandardMap.LID(SubMap.GID64(i)); forierr += !(v3[i]==v2[i1]); } EPETRA_TEST_ERR(forierr,ierr); Epetra_Import subImporter(StandardMap, SubMap); // Import to a subset of indices of standard map EPETRA_TEST_ERR(!(v1.Import(v3,subImporter,Insert)==0),ierr); for (i=0; i<SubMap.NumMyElements(); i++) { int i1 = StandardMap.LID(SubMap.GID64(i)); forierr += !(v3[i]==v1[i1]); } EPETRA_TEST_ERR(forierr,ierr); if (verbose) { if (forierr==0) cout << "SubMap Import/Export Check OK" << endl << endl; else cout << "SubMap Import/Export Check Failed" << endl << endl; } #ifdef DOESNT_WORK_IN_PARALLEL forierr = special_submap_import_test(Comm); EPETRA_TEST_ERR(forierr, ierr); if (verbose) { if (forierr==0) cout << "Special SubMap Import Check OK" << endl << endl; else cout << "Special SubMap Import Check Failed" << endl << endl; } #endif forierr = alternate_import_constructor_test(Comm); EPETRA_TEST_ERR(forierr, ierr); if (verbose) { if (forierr==0) cout << "Alternative Import Constructor Check OK" << endl << endl; else cout << "Alternative Import Constructor Check Failed" << endl << endl; } // Release all objects delete [] SourceMyGlobalElements; delete [] TargetMyGlobalElements; delete [] OverlapMyGlobalElements; delete [] StandardMyGlobalElements; delete [] Values; delete [] Indices; #ifdef EPETRA_MPI MPI_Finalize() ; #endif /* end main */ return ierr ; }
void ElPoly::DefineSkin(int NSample){ std::list<Weighted_point> l; FT shrinkfactor = 0.5; double *Plot = new double[pNType()*CUBE(NSample)]; double *Count = new double[CUBE(NSample)]; double Thre = 10.; double Radius = pEdge(0)/(double)NSample; for(int p=0;p<pNPart();p++){ int t = pType(p); int vx = (int)(pPos(p,0)/pEdge(0)*NSample); int vy = (int)(pPos(p,1)/pEdge(1)*NSample); int vz = (int)(pPos(p,2)/pEdge(2)*NSample); int vTot = (vz*NSample+vy)*NSample+vx; Plot[vTot*pNType()+t] += 1.; } double *Norm = (double *)calloc(pNType(),sizeof(double)); for(int t=0;t<pNType();t++){ for(int v=0;v<CUBE(NSample);v++){ if(Norm[t] < Plot[v*pNType()+t]) Norm[t] = Plot[v*pNType()+t]; } Norm[t] = Norm[t] <= 0. ? 1. : Norm[t]; } for(int vx=0;vx<NSample;vx++){ double x = vx*pEdge(0)/(double)NSample; for(int vy=0;vy<NSample;vy++){ double y = vy*pEdge(1)/(double)NSample; for(int vz=0;vz<NSample;vz++){ double z = vz*pEdge(2)/(double)NSample; int vTot = (vz*NSample+vy)*NSample+vx; if(Plot[vTot*pNType()] > Thre){ l.push_front(Weighted_point(Bare_point(x,y,z),Radius)); } } } } Polyhedron Polyhe; Skin_surface_3 skin_surface(l.begin(), l.end(), shrinkfactor); CGAL::mesh_skin_surface_3(skin_surface, Polyhe); // CGAL::subdivide_skin_surface_mesh_3(skin_surface, Polyhe); // std::ofstream out("mesh.off"); // out << Polyhe; glDeleteLists(Dr->Particles,1); Dr->Particles = glGenLists(1); glNewList(Dr->Particles,GL_COMPILE); // Polyhedron::Facet_iterator fcUp = Polyhe.facets_begin(); // for(;fcUp != Polyhe.facets_end(); ++fcUp){ // Polyhedron::Supports_facet_halfedge = fcUp.halfedge(); // //Halfedge_around_facet_circulator heUp = fcUp.halfedge(); // } // for (Vertex_iterator vit = Polyhe.vertices_begin();vit != Polyhe.vertices_end(); vit++){ // // Vector n = policy.normal(vit); // // n = n/sqrt(n*n); // cout << vit->point() << std::endl; // Halfedge_iterator heUp = Polyhe.halfedges_begin(); // for(;heUp != Polyhe.halfedges_end(); ++heUp){ // //Polyhedron::Halfedge_handle Half = *heUp; // Vertex_handle veUp = heUp->vertex(); // K::Point_3 pf1 = vit->point(); // } // } CGAL::Inverse_index<Vertex_handle> index(Polyhe.vertices_begin(), Polyhe.vertices_end()); for(Facet_iterator fi = Polyhe.facets_begin();fi != Polyhe.facets_end(); ++fi) { HFC hc = fi->facet_begin(); HFC hc_end = hc; Polyhedron::Vertex_handle vf1 = (*hc).vertex(); hc++; Polyhedron::Vertex_handle vf2 = (*hc).vertex(); hc++; Polyhedron::Vertex_handle vf3 = (*hc).vertex(); hc++; K::Point_3 pf1 = vf1->point(); K::Point_3 pf2 = vf2->point(); K::Point_3 pf3 = vf3->point(); Vettore v1(pf1.x(),pf1.y(),pf1.z()); Vettore v2(pf2.x(),pf2.y(),pf2.z()); Vettore v3(pf3.x(),pf3.y(),pf3.z()); Vettore vN(3); v1.Mult(InvScaleUn); v2.Mult(InvScaleUn); v3.Mult(InvScaleUn); vN = (v1-v2) ^ (v3-v2); //if(vN.Norm() > 2.*AreaMean) continue; double Sfumatura = .3*Mat->Casuale(); glColor4f(0.1,.4+Sfumatura,0.2,1.); //glColor4f(HueUp[p].r,HueUp[p].g,HueUp[p].b,HueUp[p].a); DrTria(&v1,&v2,&v3,&vN); glColor4f(1.,.0,0.,1.); DrTriaContour(&v1,&v2,&v3); // glPushMatrix();//Particle // glBegin(GL_LINES); // do { // Polyhedron::Vertex_handle vh = (*hc).vertex(); // K::Point_3 pf1 = vh->point(); // glVertex3d(pf1.x(),pf1.y(),pf1.z()); // } while (++hc != hc_end); // glEnd(); // glPopMatrix();//Particle } glEndList(); // Tr tr; // 3D-Delaunay triangulation // C2t3 c2t3 (tr); // 2D-complex in 3D-Delaunay triangulation // Surface_3 surface(sphere_function,Sphere_3(CGAL::ORIGIN, 2.)); // Surface_mesh_default_criteria_3<Tr> criteria(30., 0.1,0.1); // // meshing surface // make_surface_mesh(c2t3, surface, criteria, CGAL::Non_manifold_tag()); // std::cout << "Final number of points: " << tr.number_of_vertices() << "\n"; // DT dt; // for(int c=0;c<Gen->NChain;c++){ // if(CHAIN_IF_TYPE(Ch[c].Type,CHAIN_UP) )continue; // Point_3<K> ChPos(pPos(c,CLat1),pPos(c,CLat2),pPos(c,CNorm)); // dt.insert(ChPos); // } // Face_iterator fcTr = dt.finite_faces_begin(); // glDeleteLists(Dr->Particles,1); // Dr->Particles = glGenLists(1); // glNewList(Dr->Particles,GL_COMPILE); // for(;fcTr != dt.faces_end(); ++fcTr){ // Vertex_handle vf1 = fcTr->vertex(0), // vf2 = fcTr->vertex(1),vf3 = fcTr->vertex(2); // Point pf1 = vf1->point(); // Point pf2 = vf2->point(); // Point pf3 = vf3->point(); // Vettore v1(pf1.x() - pf2.x(),pf1.y() - pf2.y(),pf1.z()-pf2.z()); // Vettore v2(pf3.x() - pf2.x(),pf3.y() - pf2.y(),pf1.z()-pf2.z()); // Vettore vN(3); // vN = v1 ^ v2; // DrTira(v1,v2,v3,vN); // } // glEndList(); }
int main(int argc, char** argv) { // ============================================= // vector init/add/sub/scale/normalize/dot/cross // ============================================= std::cout << "===========" << std::endl; std::cout << "vector init" << std::endl; std::cout << "===========" << std::endl << std::endl; { std::cout << "default c-tor:\t\t"; print_vec(glm::vec3()); std::cout << std::endl; std::cout << "arg c-tor (explicit):\t"; print_vec(glm::vec3(1, 2, 3)); std::cout << std::endl; std::cout << "arg c-tor (1 float):\t"; print_vec(glm::vec3(2)); std::cout << std::endl; std::cout << "arg c-tor (array):\t"; float arr[] = {1, 2, 3}; print_vec(glm::make_vec3(arr)); std::cout << std::endl; } std::cout << std::endl; std::cout << "==========" << std::endl; std::cout << "vector add" << std::endl; std::cout << "==========" << std::endl << std::endl; { glm::vec3 v1(1, 2, 3); glm::vec3 v2(4, 5, 6); std::cout << "v1:\t\t"; print_vec(v1); std::cout << std::endl; std::cout << "v2:\t\t"; print_vec(v2); std::cout << std::endl; std::cout << "v1+v2:\t\t"; print_vec(v1+v2); std::cout << std::endl; std::cout << "v1 += v2:\t"; v1 += v2; print_vec(v1); std::cout << std::endl; } std::cout << std::endl; std::cout << "==========" << std::endl; std::cout << "vector sub" << std::endl; std::cout << "==========" << std::endl << std::endl; { glm::vec3 v1(1, 2, 3); glm::vec3 v2(4, 5, 6); std::cout << "v1:\t\t"; print_vec(v1); std::cout << std::endl; std::cout << "v2:\t\t"; print_vec(v2); std::cout << std::endl; std::cout << "v1-v2:\t\t"; print_vec(v1-v2); std::cout << std::endl; std::cout << "v1 -= v2:\t"; v1 -= v2; print_vec(v1); std::cout << std::endl; } std::cout << std::endl; std::cout << "============" << std::endl; std::cout << "vector scale" << std::endl; std::cout << "============" << std::endl << std::endl; { glm::vec3 v(1, 2, 3); float k = 2; std::cout << "v:\t\t"; print_vec(v); std::cout << std::endl; std::cout << "k:\t\t" << k << std::endl; std::cout << "v*k:\t\tn/a"; //print_vec(v*k); std::cout << std::endl; std::cout << "v *= k:\t\t"; v *= k; print_vec(v); std::cout << std::endl; } std::cout << std::endl; std::cout << "================" << std::endl; std::cout << "vector normalize" << std::endl; std::cout << "================" << std::endl << std::endl; { glm::vec3 v(1, 2, 3); std::cout << "v:\t\t"; print_vec(v); std::cout << std::endl; std::cout << "normalize(v):\t"; print_vec(glm::normalize(v)); std::cout << std::endl; } std::cout << std::endl; std::cout << "==================" << std::endl; std::cout << "vector dot product" << std::endl; std::cout << "==================" << std::endl << std::endl; { glm::vec3 v1(1, 2, 3); glm::vec3 v2(4, 5, 6); std::cout << "v1:\t\t"; print_vec(v1); std::cout << std::endl; std::cout << "v2:\t\t"; print_vec(v2); std::cout << std::endl; std::cout << "v1*v2:\t\t"; print_vec(v1*v2); std::cout << std::endl; std::cout << "v1 *= v2:\t"; v1 *= v2; print_vec(v1); std::cout << std::endl; } std::cout << std::endl; std::cout << "====================" << std::endl; std::cout << "vector cross product" << std::endl; std::cout << "====================" << std::endl << std::endl; { glm::vec3 v1(1, 0, 0); glm::vec3 v2(0, 1, 0); std::cout << "v1:\t\t"; print_vec(v1); std::cout << std::endl; std::cout << "v2:\t\t"; print_vec(v2); std::cout << std::endl; std::cout << "cross(v1, v2):\t"; print_vec(glm::cross(v1, v2)); std::cout << std::endl; } std::cout << std::endl; // ======================================== // matrix init/transpose/invert/determinant // ======================================== std::cout << "===========" << std::endl; std::cout << "matrix init" << std::endl; std::cout << "===========" << std::endl << std::endl; { std::cout << "default c-tor:" << std::endl; print_mat(glm::mat4()); std::cout << std::endl; std::cout << "arg c-tor (explicit):" << std::endl; print_mat(glm::mat4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)); std::cout << std::endl; std::cout << "arg c-tor (1 float):" << std::endl; print_mat(glm::mat4(2)); std::cout << std::endl; std::cout << "arg c-tor (array):" << std::endl; float arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; print_mat(glm::make_mat4(arr)); } std::cout << std::endl; std::cout << "================" << std::endl; std::cout << "matrix transpose" << std::endl; std::cout << "================" << std::endl << std::endl; { glm::mat4 m; int n = 0; for(int i = 0; i<4; i++) { for(int j = 0; j<4; j++) m[i][j] = n++; } std::cout << "m:" << std::endl; print_mat(m); std::cout << std::endl; std::cout << "transpose(m):" << std::endl; print_mat(glm::transpose(m)); } std::cout << std::endl; std::cout << "==============" << std::endl; std::cout << "matrix inverse" << std::endl; std::cout << "==============" << std::endl << std::endl; { glm::mat4 m = glm::translate( glm::mat4(1), glm::vec3(10, 20, 30)); std::cout << "m (translate by [10, 20, 30]):" << std::endl; print_mat(m); std::cout << std::endl; std::cout << "inverse(m):" << std::endl; print_mat(glm::inverse(m)); } std::cout << std::endl; std::cout << "==================" << std::endl; std::cout << "matrix determinant" << std::endl; std::cout << "==================" << std::endl << std::endl; { glm::mat4 m = glm::translate( glm::mat4(2), glm::vec3(10, 20, 30)); std::cout << "m (scale by 2, translate by [10, 20, 30]):" << std::endl; print_mat(m); std::cout << std::endl; std::cout << "determinant(m):\t" << glm::determinant(m) << std::endl; } std::cout << std::endl; // vector matrix mult std::cout << "==================" << std::endl; std::cout << "vector-matrix mult" << std::endl; std::cout << "==================" << std::endl << std::endl; { glm::vec3 v(1, 2, 3); glm::mat4 m = glm::translate( glm::mat4(1), glm::vec3(10, 20, 30)); std::cout << "v:\t"; print_vec(v); std::cout << std::endl << std::endl; std::cout << "m (translate by [10, 20, 30]):" << std::endl; print_mat(m); std::cout << std::endl; std::cout << "m*v:\t"; print_vec(glm::vec3(m*glm::vec4(v, 1))); std::cout << std::endl; } std::cout << std::endl; std::cout << "==================" << std::endl; std::cout << "matrix-matrix mult" << std::endl; std::cout << "==================" << std::endl << std::endl; { glm::vec3 v(1, 2, 3); glm::mat4 m1 = glm::translate( glm::mat4(1), glm::vec3(10, 20, 30)); glm::mat4 m2 = glm::scale( glm::mat4(1), glm::vec3(2, 2, 2)); std::cout << "v:\t"; print_vec(v); std::cout << std::endl << std::endl; std::cout << "m1 (translate by [10, 20, 30]):" << std::endl; print_mat(m1); std::cout << std::endl; std::cout << "m2 (scale by 2):" << std::endl; print_mat(m2); std::cout << std::endl; std::cout << "m1*m2:" << std::endl; print_mat(m1*m2); std::cout << std::endl; std::cout << "m1*m2*v4:\t"; print_vec(glm::vec3(m1*m2*glm::vec4(v, 1))); std::cout << std::endl; } std::cout << std::endl; std::cout << "=============" << std::endl; std::cout << "vector rotate" << std::endl; std::cout << "=============" << std::endl << std::endl; { glm::vec3 v1(1, 0, 0); glm::vec3 v2(0, 1, 0); glm::vec3 v3(0, 0, 1); glm::mat4 m1 = glm::rotate( glm::mat4(1), 90.0f, glm::vec3(0.0f, 1.0f, 0.0f)); glm::mat4 m2 = glm::rotate( glm::mat4(1), 90.0f, glm::vec3(0.0f, 0.0f, 1.0f)); glm::mat4 m3 = glm::rotate( glm::mat4(1), 90.0f, glm::vec3(1.0f, 0.0f, 0.0f)); std::cout << "v1:\t"; print_vec(v1); std::cout << std::endl; std::cout << "v2:\t"; print_vec(v2); std::cout << std::endl; std::cout << "v3:\t"; print_vec(v3); std::cout << std::endl << std::endl; std::cout << "m1 (rotate +90 deg around y axis):" << std::endl; print_mat(m1); std::cout << std::endl; std::cout << "m2 (rotate +90 deg around z axis):" << std::endl; print_mat(m2); std::cout << std::endl; std::cout << "m3 (rotate +90 deg around x axis):" << std::endl; print_mat(m3); std::cout << std::endl; std::cout << "m1*v1:\t"; print_vec(glm::vec3(m1*glm::vec4(v1, 1))); std::cout << std::endl; std::cout << "m2*v2:\t"; print_vec(glm::vec3(m2*glm::vec4(v2, 1))); std::cout << std::endl; std::cout << "m3*v3:\t"; print_vec(glm::vec3(m3*glm::vec4(v3, 1))); std::cout << std::endl; } std::cout << std::endl; std::cout << "============" << std::endl; std::cout << "vector angle" << std::endl; std::cout << "============" << std::endl << std::endl; { glm::vec3 v1(1, 0, 0); glm::vec3 v2(0, 1, 0); glm::vec3 v3(-1, 0, 0); std::cout << "v1:\t"; print_vec(v1); std::cout << std::endl; std::cout << "v2:\t"; print_vec(v2); std::cout << std::endl; std::cout << "v3:\t"; print_vec(v3); std::cout << std::endl << std::endl; std::cout << "angle(v1, v2):\t" << glm::angle(v1, v2) << std::endl; std::cout << "angle(v2, v3):\t" << glm::angle(v2, v3) << std::endl; std::cout << "angle(v3, v1):\t" << glm::angle(v3, v1) << std::endl; } }
bool simplify_exprt::simplify_floatbv_op(exprt &expr) { const typet &type=ns.follow(expr.type()); if(type.id()!=ID_floatbv) return true; assert(expr.operands().size()==3); exprt op0=expr.op0(); exprt op1=expr.op1(); exprt op2=expr.op2(); // rounding mode assert(ns.follow(op0.type())==type); assert(ns.follow(op1.type())==type); // Remember that floating-point addition is _NOT_ associative. // Thus, we don't re-sort the operands. // We only merge constants! if(op0.is_constant() && op1.is_constant() && op2.is_constant()) { ieee_floatt v0(to_constant_expr(op0)); ieee_floatt v1(to_constant_expr(op1)); mp_integer rounding_mode; if(!to_integer(op2, rounding_mode)) { v0.rounding_mode=(ieee_floatt::rounding_modet)integer2long(rounding_mode); v1.rounding_mode=v0.rounding_mode; ieee_floatt result=v0; if(expr.id()==ID_floatbv_plus) result+=v1; else if(expr.id()==ID_floatbv_minus) result-=v1; else if(expr.id()==ID_floatbv_mult) result*=v1; else if(expr.id()==ID_floatbv_div) result/=v1; else assert(false); expr=result.to_expr(); return false; } } // division by one? Exact for all rounding modes. if (expr.id()==ID_floatbv_div && op1.is_constant() && op1.is_one()) { exprt tmp; tmp.swap(op0); expr.swap(tmp); return false; } return true; }
void World::transformPartC() { for (int i = 0; i < objects.size(); i++) { (*objects[i]).transform(persp_trans); (*objects[i]).transform(ortho_proj); (*objects[i]).transform(viewport_trans); } for (int i = 0; i < objects.size(); i++) { Material obj_color = (*objects[i]).surface_mat; for (int j = 0; j < (*objects[i]).num_triangles; j++) { Triangle cur_tri = (*objects[i]).triangles[j]; Vector3 center = cur_tri.centroid; Vector3 tri_normal = (cur_tri.unit_normal[0] + cur_tri.unit_normal[1] + cur_tri.unit_normal[2]) / 3.0; //Back face culling if (tri_normal * (center) > 0.0) continue; Vector4 v1 = cur_tri.vertices[0]; Vector4 v2 = cur_tri.vertices[1]; Vector4 v3 = cur_tri.vertices[2]; float xa = v1(0); float xb = v2(0); float xc = v3(0); float ya = v1(1); float yb = v2(1); float yc = v3(1); float x_min = floor(getMin(xa, xb, xc)); float y_min = floor(getMin(ya, yb, yc)); float x_max = ceil(getMax(xa, xb, xc)); float y_max = ceil(getMax(ya, yb, yc)); float n = x_max - x_min; for (int y = y_min; y <= y_max; y++) { for (int x = x_min; x <= x_max; x++) { float beta = ( (ya - yc) * x + (xc - xa) * y + xa * yc - xc * ya) / ( (ya - yc) * xb + (xc - xa) * yb + xa * yc - xc * ya); float gamma = ( (ya - yb) * x + (xb - xa) * y + xa * yb - xb * ya) / ( (ya - yb) * xc + (xb - xa) * yc + xa * yb - xb * ya); if (beta > 0.0 && gamma > 0.0 && (beta + gamma) < 1.0) { //Attribute interpolation ==================================================== float d1 = cur_tri.world_vertices[0].getMagnitude(); float d2 = cur_tri.world_vertices[1].getMagnitude(); float d3 = cur_tri.world_vertices[2].getMagnitude(); Vector3 norm_vert[3]; norm_vert[0] = cur_tri.unit_normal[0]; norm_vert[1] = cur_tri.unit_normal[1]; norm_vert[2] = cur_tri.unit_normal[2]; Vector3 vert_loc[3]; vert_loc[0] = Vector3(cur_tri.world_vertices[0](0), cur_tri.world_vertices[0](1), cur_tri.world_vertices[0](2)); vert_loc[1] = Vector3(cur_tri.world_vertices[1](0), cur_tri.world_vertices[1](1), cur_tri.world_vertices[1](2)); vert_loc[2] = Vector3(cur_tri.world_vertices[2](0), cur_tri.world_vertices[2](1), cur_tri.world_vertices[2](2)); for (int m = 0; m < 3; m++) { vert_loc[m] = vert_loc[m] / vert_loc[m].getMagnitude(); norm_vert[m] = norm_vert[m] / norm_vert[m].getMagnitude(); } RGBColor to_return[3]; float distance = (d1 + beta * d2 + gamma * d3) / 3.0; //End of attribute interpolation ============================================== for (int k = 0; k < 3; k++) { Vector3 light_vec = (Vector3(-4.0, 4.0, -3.0) / Vector3(-4.0, 4.0, -3.0).getMagnitude()) - (vert_loc[k] / vert_loc[k].getMagnitude()); light_vec = light_vec / light_vec.getMagnitude(); //center = center / center.getMagnitude(); Vector3 h_spec = light_vec - vert_loc[k]; h_spec = h_spec / h_spec.getMagnitude(); RGBColor tri_color = getMax(0.0, 0.0, (norm_vert[k] * light_vec)) * obj_color.diffuse; tri_color = tri_color + (obj_color.ambient * 0.2); tri_color = tri_color + obj_color.specular * pow(getMax(0, 0, norm_vert[k] * h_spec), obj_color.phong_exponent); //tri_color = tri_color.power(1.0 / 2.2); to_return[k] = tri_color; } RGBColor final_color = to_return[0] + (to_return[1] - to_return[0]) * beta + (to_return[2] - to_return[0]) * gamma; final_color = final_color.power(1.0 / 2.2); Pixel tri_pix = Pixel(final_color, distance); if (tri_pix.depth < (im_plane.getPixel(x, y).depth - 0.001) || im_plane.getPixel(x, y).depth < 0.0) im_plane.setPixel(x, y, tri_pix); } } } } } }
void test_basic_template( ForwardIterator first,ForwardIterator last BOOST_APPEND_EXPLICIT_TEMPLATE_TYPE(Flyweight)) { typedef typename Flyweight::value_type value_type; ForwardIterator it; for(it=first;it!=last;++it){ /* construct/copy/destroy */ Flyweight f1(*it); Flyweight f2; Flyweight c1(f1); const Flyweight c2(static_cast<const Flyweight&>(f2)); value_type v1(*it); boost::value_initialized<value_type> v2; BOOST_TEST(f1.get_key()==*it); BOOST_TEST((f1==f2)==(f1.get()==v2.data())); BOOST_TEST(f1==c1); BOOST_TEST(f2==c2); #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) Flyweight cr1(std::move(c1)); Flyweight cr2(std::move(c2)); BOOST_TEST(f1==cr1); BOOST_TEST(f2==cr2); #endif #if !defined(BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX) /* testcase for https://svn.boost.org/trac/boost/ticket/10439 */ Flyweight f3={}; BOOST_TEST(f3==f2); #endif f1=f1; BOOST_TEST(f1==f1); c1=f2; BOOST_TEST(c1==f2); c1=f1; BOOST_TEST(c1==f1); /* convertibility to underlying type */ BOOST_TEST(f1.get()==v1); /* identity of reference */ BOOST_TEST(&f1.get()==&c1.get()); /* modifiers */ f1.swap(f1); BOOST_TEST(f1==c1); f1.swap(f2); BOOST_TEST(f1==c2); BOOST_TEST(f2==c1); boost::flyweights::swap(f1,f2); BOOST_TEST(f1==c1); BOOST_TEST(f2==c2); /* specialized algorithms */ std::ostringstream oss1; oss1<<f1; std::ostringstream oss2; oss2<<f1.get(); BOOST_TEST(oss1.str()==oss2.str()); #if !defined(BOOST_FLYWEIGHT_DISABLE_HASH_SUPPORT) /* hash support */ BOOST_TEST(boost::hash<Flyweight>()(f1)==boost::hash<Flyweight>()(c1)); BOOST_TEST(boost::hash<Flyweight>()(f1)== boost::hash<const value_type*>()(&f1.get())); #if !defined(BOOST_NO_CXX11_HDR_FUNCTIONAL) BOOST_TEST(std::hash<Flyweight>()(f1)==std::hash<Flyweight>()(c1)); BOOST_TEST(std::hash<Flyweight>()(f1)== std::hash<const value_type*>()(&f1.get())); #endif #endif } }
void TinyRenderer::renderObject(TinyRenderObjectData& renderData) { B3_PROFILE("renderObject"); int width = renderData.m_rgbColorBuffer.get_width(); int height = renderData.m_rgbColorBuffer.get_height(); Vec3f light_dir_local = Vec3f(renderData.m_lightDirWorld[0], renderData.m_lightDirWorld[1], renderData.m_lightDirWorld[2]); Vec3f light_color = Vec3f(renderData.m_lightColor[0], renderData.m_lightColor[1], renderData.m_lightColor[2]); float light_distance = renderData.m_lightDistance; Model* model = renderData.m_model; if (0 == model) return; //discard invisible objects (zero alpha) if (model->getColorRGBA()[3] == 0) return; renderData.m_viewportMatrix = viewport(0, 0, width, height); b3AlignedObjectArray<float>& zbuffer = renderData.m_depthBuffer; b3AlignedObjectArray<float>* shadowBufferPtr = renderData.m_shadowBuffer; int* segmentationMaskBufferPtr = (renderData.m_segmentationMaskBufferPtr && renderData.m_segmentationMaskBufferPtr->size()) ? &renderData.m_segmentationMaskBufferPtr->at(0) : 0; TGAImage& frame = renderData.m_rgbColorBuffer; { // light target is set to be the origin, and the up direction is set to be vertical up. Matrix lightViewMatrix = lookat(light_dir_local * light_distance, Vec3f(0.0, 0.0, 0.0), Vec3f(0.0, 0.0, 1.0)); Matrix lightModelViewMatrix = lightViewMatrix * renderData.m_modelMatrix; Matrix modelViewMatrix = renderData.m_viewMatrix * renderData.m_modelMatrix; Vec3f localScaling(renderData.m_localScaling[0], renderData.m_localScaling[1], renderData.m_localScaling[2]); Matrix viewMatrixInv = renderData.m_viewMatrix.invert(); btVector3 P(viewMatrixInv[0][3], viewMatrixInv[1][3], viewMatrixInv[2][3]); Shader shader(model, light_dir_local, light_color, modelViewMatrix, lightModelViewMatrix, renderData.m_projectionMatrix, renderData.m_modelMatrix, renderData.m_viewportMatrix, localScaling, model->getColorRGBA(), width, height, shadowBufferPtr, renderData.m_lightAmbientCoeff, renderData.m_lightDiffuseCoeff, renderData.m_lightSpecularCoeff); { B3_PROFILE("face"); for (int i = 0; i < model->nfaces(); i++) { for (int j = 0; j < 3; j++) { shader.vertex(i, j); } // backface culling btVector3 v0(shader.world_tri.col(0)[0], shader.world_tri.col(0)[1], shader.world_tri.col(0)[2]); btVector3 v1(shader.world_tri.col(1)[0], shader.world_tri.col(1)[1], shader.world_tri.col(1)[2]); btVector3 v2(shader.world_tri.col(2)[0], shader.world_tri.col(2)[1], shader.world_tri.col(2)[2]); btVector3 N = (v1 - v0).cross(v2 - v0); if ((v0 - P).dot(N) >= 0) continue; mat<4, 3, float> stackTris[3]; b3AlignedObjectArray<mat<4, 3, float> > clippedTriangles; clippedTriangles.initializeFromBuffer(stackTris, 0, 3); bool hasClipped = clipTriangleAgainstNearplane(shader.varying_tri, clippedTriangles); if (hasClipped) { for (int t = 0; t < clippedTriangles.size(); t++) { triangleClipped(clippedTriangles[t], shader.varying_tri, shader, frame, &zbuffer[0], segmentationMaskBufferPtr, renderData.m_viewportMatrix, renderData.m_objectIndex + ((renderData.m_linkIndex + 1) << 24)); } } else { triangle(shader.varying_tri, shader, frame, &zbuffer[0], segmentationMaskBufferPtr, renderData.m_viewportMatrix, renderData.m_objectIndex + ((renderData.m_linkIndex + 1) << 24)); } } } } }
int main (int, char**) { UnitTest t (72); Variant v0 (true); Variant v1 (42); Variant v2 (3.14); Variant v3 ("foo"); Variant v4 (1234567890, Variant::type_date); Variant v5 (1200, Variant::type_duration); Variant v00 = v0 != v0; t.is (v00.type (), Variant::type_boolean, "true != true --> boolean"); t.is (v00.get_bool (), false, "true != true --> false"); Variant v01 = v0 != v1; t.is (v01.type (), Variant::type_boolean, "true != 42 --> boolean"); t.is (v01.get_bool (), true, "true != 42 --> true"); Variant v02 = v0 != v2; t.is (v02.type (), Variant::type_boolean, "true != 3.14 --> boolean"); t.is (v02.get_bool (), true, "true != 3.14 --> true"); Variant v03 = v0 != v3; t.is (v03.type (), Variant::type_boolean, "true != 'foo' --> boolean"); t.is (v03.get_bool (), true, "true != 'foo' --> true"); Variant v04 = v0 != v4; t.is (v04.type (), Variant::type_boolean, "true != 1234567890 --> boolean"); t.is (v04.get_bool (), true, "true != 1234567890 --> true"); Variant v05 = v0 != v5; t.is (v05.type (), Variant::type_boolean, "true != 1200 --> boolean"); t.is (v05.get_bool (), true, "true != 1200 --> true"); Variant v10 = v1 != v0; t.is (v10.type (), Variant::type_boolean, "42 != true --> boolean"); t.is (v10.get_bool (), true, "42 != true --> true"); Variant v11 = v1 != v1; t.is (v11.type (), Variant::type_boolean, "42 != 42 --> boolean"); t.is (v11.get_bool (), false, "42 != 42 --> false"); Variant v12 = v1 != v2; t.is (v12.type (), Variant::type_boolean, "42 != 3.14 --> boolean"); t.is (v12.get_bool (), true, "42 != 3.14 --> true"); Variant v13 = v1 != v3; t.is (v13.type (), Variant::type_boolean, "42 != 'foo' --> boolean"); t.is (v13.get_bool (), true, "42 != 'foo' --> true"); Variant v14 = v1 != v4; t.is (v04.type (), Variant::type_boolean, "42 != 1234567890 --> boolean"); t.is (v04.get_bool (), true, "42 != 1234567890 --> true"); Variant v15 = v1 != v5; t.is (v15.type (), Variant::type_boolean, "42 != 1200 --> boolean"); t.is (v15.get_bool (), true, "42 != 1200 --> true"); Variant v20 = v2 != v0; t.is (v20.type (), Variant::type_boolean, "3.14 != true --> boolean"); t.is (v20.get_bool (), true, "3.14 != true --> true"); Variant v21 = v2 != v1; t.is (v21.type (), Variant::type_boolean, "3.14 != 42 --> boolean"); t.is (v21.get_bool (), true, "3.14 != 42 --> true"); Variant v22 = v2 != v2; t.is (v22.type (), Variant::type_boolean, "3.14 != 3.14 --> boolean"); t.is (v22.get_bool (), false, "3.14 != 3.14 --> false"); Variant v23 = v2 != v3; t.is (v23.type (), Variant::type_boolean, "3.14 != 'foo' --> boolean"); t.is (v23.get_bool (), true, "3.14 != 'foo' --> true"); Variant v24 = v2 != v4; t.is (v24.type (), Variant::type_boolean, "3.14 != 1234567890 --> boolean"); t.is (v24.get_bool (), true, "3.14 != 1234567890 --> true"); Variant v25 = v2 != v5; t.is (v25.type (), Variant::type_boolean, "3.14 != 1200 --> boolean"); t.is (v25.get_bool (), true, "3.14 != 1200 --> true"); Variant v30 = v3 != v0; t.is (v30.type (), Variant::type_boolean, "'foo' != true --> boolean"); t.is (v30.get_bool (), true, "'foo' != true --> true"); Variant v31 = v3 != v1; t.is (v31.type (), Variant::type_boolean, "'foo' != 42 --> boolean"); t.is (v31.get_bool (), true, "'foo' != 42 --> true"); Variant v32 = v3 != v2; t.is (v32.type (), Variant::type_boolean, "'foo' != 3.14 --> boolean"); t.is (v32.get_bool (), true, "'foo' != 3.14 --> true"); Variant v33 = v3 != v3; t.is (v33.type (), Variant::type_boolean, "'foo' != 'foo' --> boolean"); t.is (v33.get_bool (), false, "'foo' != 'foo' --> false"); Variant v34 = v3 != v4; t.is (v34.type (), Variant::type_boolean, "'foo' != 1234567890 --> boolean"); t.is (v34.get_bool (), true, "'foo' != 1234567890 --> true"); Variant v35 = v3 != v5; t.is (v35.type (), Variant::type_boolean, "'foo' != 1200 --> boolean"); t.is (v35.get_bool (), true, "'foo' != 1200 --> true"); Variant v40 = v4 != v0; t.is (v40.type (), Variant::type_boolean, "1234567890 != true --> boolean"); t.is (v40.get_bool (), true, "1234567890 != true --> true"); Variant v41 = v4 != v1; t.is (v41.type (), Variant::type_boolean, "1234567890 != 42 --> boolean"); t.is (v41.get_bool (), true, "1234567890 != 42 --> true"); Variant v42 = v4 != v2; t.is (v42.type (), Variant::type_boolean, "1234567890 != 3.14 --> boolean"); t.is (v42.get_bool (), true, "1234567890 != 3.14 --> true"); Variant v43 = v4 != v3; t.is (v43.type (), Variant::type_boolean, "1234567890 != 'foo' --> boolean"); t.is (v43.get_bool (), true, "1234567890 != 'foo' --> true"); Variant v44 = v4 != v4; t.is (v44.type (), Variant::type_boolean, "1234567890 != 1234567890 --> boolean"); t.is (v44.get_bool (), false, "1234567890 != 1234567890 --> false"); Variant v45 = v4 != v5; t.is (v45.type (), Variant::type_boolean, "1234567890 != 1200 --> boolean"); t.is (v45.get_bool (), true, "1234567890 != 1200 --> true"); Variant v50 = v5 != v0; t.is (v50.type (), Variant::type_boolean, "1200 != true --> boolean"); t.is (v50.get_bool (), true, "1200 != true --> true"); Variant v51 = v5 != v1; t.is (v51.type (), Variant::type_boolean, "1200 != 42 --> boolean"); t.is (v51.get_bool (), true, "1200 != 42 --> true"); Variant v52 = v5 != v2; t.is (v52.type (), Variant::type_boolean, "1200 != 3.14 --> boolean"); t.is (v52.get_bool (), true, "1200 != 3.14 --> true"); Variant v53 = v5 != v3; t.is (v53.type (), Variant::type_boolean, "1200 != 'foo' --> boolean"); t.is (v53.get_bool (), true, "1200 != 'foo' --> true"); Variant v54 = v5 != v4; t.is (v04.type (), Variant::type_boolean, "1200 != 1234567890 --> boolean"); t.is (v04.get_bool (), true, "1200 != 1234567890 --> true"); Variant v55 = v5 != v5; t.is (v55.type (), Variant::type_boolean, "1200 != 1200 --> boolean"); t.is (v55.get_bool (), false, "1200 != 1200 --> false"); return 0; }
template<typename MatrixType> void integer_type_tests(const MatrixType& m) { typedef typename MatrixType::Index Index; typedef typename MatrixType::Scalar Scalar; VERIFY(NumTraits<Scalar>::IsInteger); enum { is_signed = (Scalar(-1) > Scalar(0)) ? 0 : 1 }; VERIFY(int(NumTraits<Scalar>::IsSigned) == is_signed); typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType; Index rows = m.rows(); Index cols = m.cols(); // this test relies a lot on Random.h, and there's not much more that we can do // to test it, hence I consider that we will have tested Random.h MatrixType m1(rows, cols), m2 = MatrixType::Random(rows, cols), m3(rows, cols), mzero = MatrixType::Zero(rows, cols); typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> SquareMatrixType; SquareMatrixType identity = SquareMatrixType::Identity(rows, rows), square = SquareMatrixType::Random(rows, rows); VectorType v1(rows), v2 = VectorType::Random(rows), vzero = VectorType::Zero(rows); do { m1 = MatrixType::Random(rows, cols); } while(m1 == mzero || m1 == m2); do { v1 = VectorType::Random(rows); } while(v1 == vzero || v1 == v2); VERIFY_IS_APPROX( v1, v1); VERIFY_IS_NOT_APPROX( v1, 2*v1); VERIFY_IS_APPROX( vzero, v1-v1); VERIFY_IS_APPROX( m1, m1); VERIFY_IS_NOT_APPROX( m1, 2*m1); VERIFY_IS_APPROX( mzero, m1-m1); VERIFY_IS_APPROX(m3 = m1,m1); MatrixType m4; VERIFY_IS_APPROX(m4 = m1,m1); m3.real() = m1.real(); VERIFY_IS_APPROX(static_cast<const MatrixType&>(m3).real(), static_cast<const MatrixType&>(m1).real()); VERIFY_IS_APPROX(static_cast<const MatrixType&>(m3).real(), m1.real()); // check == / != operators VERIFY(m1==m1); VERIFY(m1!=m2); VERIFY(!(m1==m2)); VERIFY(!(m1!=m1)); m1 = m2; VERIFY(m1==m2); VERIFY(!(m1!=m2)); // check linear structure Scalar s1; do { s1 = internal::random<Scalar>(); } while(s1 == 0); VERIFY_IS_EQUAL(m1+m1, 2*m1); VERIFY_IS_EQUAL(m1+m2-m1, m2); VERIFY_IS_EQUAL(m1*s1, s1*m1); VERIFY_IS_EQUAL((m1+m2)*s1, s1*m1+s1*m2); m3 = m2; m3 += m1; VERIFY_IS_EQUAL(m3, m1+m2); m3 = m2; m3 -= m1; VERIFY_IS_EQUAL(m3, m2-m1); m3 = m2; m3 *= s1; VERIFY_IS_EQUAL(m3, s1*m2); // check matrix product. VERIFY_IS_APPROX(identity * m1, m1); VERIFY_IS_APPROX(square * (m1 + m2), square * m1 + square * m2); VERIFY_IS_APPROX((m1 + m2).transpose() * square, m1.transpose() * square + m2.transpose() * square); VERIFY_IS_APPROX((m1 * m2.transpose()) * m1, m1 * (m2.transpose() * m1)); }
//! Creates a normal map from a height map texture. //! \param amplitude: Constant value by which the height information is multiplied. void CNullDriver::makeNormalMapTexture(ITexture* texture, f32 amplitude) const { if (!texture) return; if (texture->getColorFormat() != ECF_A1R5G5B5 && texture->getColorFormat() != ECF_A8R8G8B8 ) { Printer::log("Error: Unsupported texture color format for making normal map.", ELL_ERROR); return; } dimension2d<u32> dim = texture->getSize(); amplitude = amplitude / 255.0f; f32 vh = dim.Height / (f32)dim.Width; f32 hh = dim.Width / (f32)dim.Height; if (texture->getColorFormat() == ECF_A8R8G8B8) { // ECF_A8R8G8B8 version s32 *p = (s32*)texture->lock(); if (!p) { Printer::log("Could not lock texture for making normal map.", ELL_ERROR); return; } // copy texture u32 pitch = texture->getPitch() / 4; s32* in = new s32[dim.Height * pitch]; memcpy(in, p, dim.Height * pitch * 4); for (s32 x=0; x < s32(pitch); ++x) for (s32 y=0; y < s32(dim.Height); ++y) { // TODO: this could be optimized really a lot vector3df h1((x-1)*hh, nml32(x-1, y, pitch, dim.Height, in)*amplitude, y*vh); vector3df h2((x+1)*hh, nml32(x+1, y, pitch, dim.Height, in)*amplitude, y*vh); //vector3df v1(x*hh, nml32(x, y-1, pitch, dim.Height, in)*amplitude, (y-1)*vh); //vector3df v2(x*hh, nml32(x, y+1, pitch, dim.Height, in)*amplitude, (y+1)*vh); vector3df v1(x*hh, nml32(x, y+1, pitch, dim.Height, in)*amplitude, (y-1)*vh); vector3df v2(x*hh, nml32(x, y-1, pitch, dim.Height, in)*amplitude, (y+1)*vh); vector3df v = v1-v2; vector3df h = h1-h2; vector3df n = v.crossProduct(h); n.normalize(); n *= 0.5f; n += vector3df(0.5f,0.5f,0.5f); // now between 0 and 1 n *= 255.0f; s32 height = (s32)nml32(x, y, pitch, dim.Height, in); p[y*pitch + x] = SColor( height, // store height in alpha (s32)n.X, (s32)n.Z, (s32)n.Y).color; } delete [] in; texture->unlock(); } else { // ECF_A1R5G5B5 version s16 *p = (s16*)texture->lock(); if (!p) { Printer::log("Could not lock texture for making normal map.", ELL_ERROR); return; } u32 pitch = texture->getPitch() / 2; // copy texture s16* in = new s16[dim.Height * pitch]; memcpy(in, p, dim.Height * pitch * 2); for (s32 x=0; x < s32(pitch); ++x) for (s32 y=0; y < s32(dim.Height); ++y) { // TODO: this could be optimized really a lot vector3df h1((x-1)*hh, nml16(x-1, y, pitch, dim.Height, in)*amplitude, y*vh); vector3df h2((x+1)*hh, nml16(x+1, y, pitch, dim.Height, in)*amplitude, y*vh); vector3df v1(x*hh, nml16(x, y-1, pitch, dim.Height, in)*amplitude, (y-1)*vh); vector3df v2(x*hh, nml16(x, y+1, pitch, dim.Height, in)*amplitude, (y+1)*vh); vector3df v = v1-v2; vector3df h = h1-h2; vector3df n = v.crossProduct(h); n.normalize(); n *= 0.5f; n += vector3df(0.5f,0.5f,0.5f); // now between 0 and 1 n *= 255.0f; p[y*pitch + x] = RGBA16((u32)n.X, (u32)n.Z, (u32)n.Y); } delete [] in; texture->unlock(); } texture->regenerateMipMapLevels(); }
int main() { { miyabi::type_traits::dump< Foo >( std::cout ); std::cout << std::endl; miyabi::type_traits::dump< miyabi::ContainerFacade< Foo > >( std::cout ); std::cout << std::endl; miyabi::type_traits::dump< boost::array< float, 4 > >( std::cout ); } { miyabi::math::Vector< std::vector< float > > a( 3 ); a[ 0 ] = 3; a[ 1 ] = 4; a[ 2 ] = 5; miyabi::math::Vector< std::vector< float > > b( 4 ); b[ 0 ] = 0; b[ 1 ] = 3; b[ 2 ] = 6; b[ 3 ] = 9; miyabi::math::Vector< std::map< int, float > > c; c[ 0 ] = 1; c[ 3 ] = 2; c[ 7 ] = 3; c[ 9 ] = 4; miyabi::math::Vector< std::map< int, float > > d; d[ 0 ] = 1; d[ 2 ] = 4; d[ 3 ] = 8; d[ 5 ] = 12; miyabi::math::Vector< std::map< int, float > > result3 = c + d; std::cout << result3 << std::endl; c += d; std::cout << c[ 0 ] << " " << c[ 1 ] << " " << c[ 2 ] << " " << c[ 3 ] << " "; std::cout << c[ 4 ] << " " << c[ 5 ] << " " << c[ 6 ] << " " << c[ 7 ] << " "; std::cout << c[ 8 ] << " " << c[ 9 ] << " " << c[ 10 ] << " " << c[ 11 ] << std::endl; c += a; std::cout << c[ 0 ] << " " << c[ 1 ] << " " << c[ 2 ] << " " << c[ 3 ] << " "; std::cout << c[ 4 ] << " " << c[ 5 ] << " " << c[ 6 ] << " " << c[ 7 ] << " "; std::cout << c[ 8 ] << " " << c[ 9 ] << " " << c[ 10 ] << " " << c[ 11 ] << std::endl; miyabi::math::Vector< std::map< int, float > > da; da[ 0 ] = 1; miyabi::math::Vector< std::map< int, float > > db; db[ 2 ] = 1; std::cout << dot( da, da ) << std::endl; std::cout << dot( da, db ) << std::endl; miyabi::math::Vector< std::vector< float > > result = a + b; std::cout << &result.getBase() << std::endl; std::cout << result.size() << " " << result[ 1 ] << " " << result[ 2 ] << " " << result[ 3 ] << std::endl; miyabi::math::Vector< std::vector< float > > result2 = b - a; std::cout << result2[ 0 ] << " " << result2[ 1 ] << " " << result2[ 2 ] << " " << result2[ 3 ] << std::endl; miyabi::math::Vector< std::map< int, miyabi::math::Vector< std::map< int, float > > > > matrix; matrix[ 5 ][ 2 ] = 1; std::cout << matrix << std::endl; miyabi::math::outer_return_vector< miyabi::math::Vector< std::vector< float > >, miyabi::math::Vector< std::vector< float > > >::type ext_result = a * b; std::cout << ext_result << std::endl; miyabi::math::Vector< std::map< int, float > > foo; foo[ 90 ] = 1; foo[ 2048 ] = 1; std::cout << length( foo ) << std::endl; } { miyabi::math::Vector< std::map< int, float > > v1;v1[ 1 ]=1; miyabi::math::Vector< std::map< int, float > > v2;v2[ 0 ]=1; miyabi::math::Vector< std::map< int, float > > v3; std::cout << triangleArea( v1, v2, v3 ) << std::endl; miyabi::math::Vector< std::map< int, miyabi::math::Vector< std::map< int, float > > > > matrix2; for( int row = 0; row != 10; ++row ) for( int col = 0; col != 10; ++col ) matrix2.getValue( rand() % 16 ).getValue( rand() % 16 ) = rand() % 256; miyabi::math::Vector< std::vector< float > > log; for( int row = 0; row != 16; ++row ) log.getValue( row ) = row; std::cout << log << std::endl; std::cout << matrix2 << std::endl; lu( matrix2, log ); std::cout << matrix2 << std::endl; std::cout << log << std::endl; } { miyabi::math::Vector< std::map< int, miyabi::math::Vector< std::map< int, float > > > > mx; mx[0][0]=1;mx[0][1]=4;mx[0][2]=3;mx[0][3]=8; mx[1][1]=2;mx[1][2]=5;mx[1][3]=1; mx[2][0]=9;mx[2][1]=3; mx[3][0]=5; mx[3][2]=1;mx[3][3]=1; std::cout << inverse( mx ) << std::endl; std::cout << mx << std::endl; } { miyabi::math::Vector< std::vector< float > > v1( 3 ); v1[ 0 ] = 1.0f; v1[ 1 ] = 0.0f; v1[ 2 ] = 0.0f; miyabi::math::Vector< std::vector< float > > v2( 3 ); v2[ 0 ] = 0.0f; v2[ 1 ] = 1.0f; v2[ 2 ] = 0.0f; miyabi::math::Vector< std::vector< float > > v3 = cross( v1, v2 ); std::cout << v3 << std::endl; } { miyabi::math::Vector< std::vector< miyabi::math::Vector< std::vector< float > > > > polygon( 3 ); polygon.getValue( 0 ).getValue( 0 ) = 1.0f; polygon.getValue( 0 ).getValue( 1 ) = 0.0f; polygon.getValue( 0 ).getValue( 2 ) = 0.0f; polygon.getValue( 1 ).getValue( 0 ) = 0.0f; polygon.getValue( 1 ).getValue( 1 ) = 0.0f; polygon.getValue( 1 ).getValue( 2 ) = 1.0f; polygon.getValue( 2 ).getValue( 0 ) = 0.0f; polygon.getValue( 2 ).getValue( 1 ) = 1.0f; polygon.getValue( 2 ).getValue( 2 ) = 0.0f; typename miyabi::radiosity::triangle_matrix_return_vector< miyabi::math::Vector< std::vector< miyabi::math::Vector< std::vector< float > > > > >::type result = miyabi::radiosity::getTriangleMatrix( polygon ); polygon.getValue( 0 ).getValue( 3 ) = 1.0f; polygon.getValue( 1 ).getValue( 3 ) = 1.0f; polygon.getValue( 2 ).getValue( 3 ) = 1.0f; std::cout << result << std::endl; std::cout << result * polygon[ 0 ] << std::endl; std::cout << result * polygon[ 1 ] << std::endl; std::cout << result * polygon[ 2 ] << std::endl; // std::cout << triangleArea( v1, v2, v3 ) << " " << triangleArea( result * v1, result * v2, result * v3 ) << std::endl; } { miyabi::math::Vector< std::vector< miyabi::math::Vector< std::vector< float > > > > m; m.getValue( 0 ).getValue( 0 ) = -1; m.getValue( 0 ).getValue( 1 ) = 0; m.getValue( 0 ).getValue( 2 ) = 1; m.getValue( 1 ).getValue( 0 ) = 0; m.getValue( 1 ).getValue( 1 ) = -0.5f; m.getValue( 1 ).getValue( 2 ) = 1; m.getValue( 2 ).getValue( 0 ) = 0.0f; m.getValue( 2 ).getValue( 1 ) = 0.0f; m.getValue( 2 ).getValue( 2 ) = 1; inverse( m ); miyabi::math::Vector< std::vector< float > > v; v.getValue( 0 ) = 0; v.getValue( 1 ) = 0; v.getValue( 2 ) = 5; miyabi::math::Vector< std::vector< float > > r = m * v; std::cout << r << std::endl; r[ 0 ]; std::cout << -r[ 0 ] + r[ 2 ] << std::endl; std::cout << -0.5 * r[ 1 ] + r[ 2 ] << std::endl; std::cout << 0.2 * r[ 0 ] + 0.5 * r[ 1 ] + r[ 2 ] << std::endl; } { miyabi::math::Vector< std::vector< float > > p1; p1.getValue( 0 ) = 0; p1.getValue( 1 ) = 0; p1.getValue( 2 ) = 0; miyabi::math::Vector< std::vector< float > > p2; p2.getValue( 0 ) = 1; p2.getValue( 1 ) = 1; p2.getValue( 2 ) = 1; miyabi::math::Vector< std::vector< miyabi::math::Vector< std::vector< float > > > > m; m.getValue( 0 ).getValue( 0 ) = 10; m.getValue( 0 ).getValue( 1 ) = 0; m.getValue( 0 ).getValue( 2 ) = 0; m.getValue( 1 ).getValue( 0 ) = 0; m.getValue( 1 ).getValue( 1 ) = 10; m.getValue( 1 ).getValue( 2 ) = 0; m.getValue( 2 ).getValue( 0 ) = 0; m.getValue( 2 ).getValue( 1 ) = 0; m.getValue( 2 ).getValue( 2 ) = 10; std::cout << "i1 " << miyabi::radiosity::intersect( p1, p2, m ) << std::endl; std::cout << "i2 " << miyabi::radiosity::intersect2( p1, p2, m ) << std::endl; } { miyabi::math::Vector< std::vector< miyabi::math::Vector< std::vector< float > > > > p; p.getValue( 0 ).getValue( 0 ) = 5; p.getValue( 0 ).getValue( 1 ) = 1; p.getValue( 0 ).getValue( 2 ) = -10; p.getValue( 1 ).getValue( 0 ) = 5; p.getValue( 1 ).getValue( 1 ) = 2; p.getValue( 1 ).getValue( 2 ) = -3; p.getValue( 2 ).getValue( 0 ) = 5; p.getValue( 2 ).getValue( 1 ) = 3; p.getValue( 2 ).getValue( 2 ) = 8; miyabi::math::Vector< std::vector< miyabi::math::Vector< std::vector< float > > > > m; m.getValue( 0 ).getValue( 0 ) = 10; m.getValue( 0 ).getValue( 1 ) = 0; m.getValue( 0 ).getValue( 2 ) = 0; m.getValue( 1 ).getValue( 0 ) = 0; m.getValue( 1 ).getValue( 1 ) = 10; m.getValue( 1 ).getValue( 2 ) = 0; m.getValue( 2 ).getValue( 0 ) = 0; m.getValue( 2 ).getValue( 1 ) = 0; m.getValue( 2 ).getValue( 2 ) = 10; std::cout << miyabi::radiosity::cut( p, m ) << std::endl; } { miyabi::math::Vector< std::vector< miyabi::math::Vector< std::vector< float > > > > p; p.getValue( 0 ).getValue( 0 ) = 0; p.getValue( 0 ).getValue( 1 ) = 0; p.getValue( 0 ).getValue( 2 ) = 0; p.getValue( 1 ).getValue( 0 ) = 1; p.getValue( 1 ).getValue( 1 ) = 0; p.getValue( 1 ).getValue( 2 ) = 0; p.getValue( 2 ).getValue( 0 ) = 1; p.getValue( 2 ).getValue( 1 ) = 1; p.getValue( 2 ).getValue( 2 ) = 0; p.getValue( 3 ).getValue( 0 ) = 0; p.getValue( 3 ).getValue( 1 ) = 1; p.getValue( 3 ).getValue( 2 ) = 0; std::cout << area( p ) << std::endl; } }
void CIcosahedron::init( float s ){ this->clearMesh(); float p = ((1.0 + sqrt(5.0))/2.0)*s; TVector3 v0(s,0.0,p); this->iVertices.push_back(v0); TVector3 v1(-s,0.0,p); this->iVertices.push_back(v1); TVector3 v2(s,0.0,-p); this->iVertices.push_back(v2); TVector3 v3(-s,0.0,-p); this->iVertices.push_back(v3); TVector3 v4(0.0,p,s); this->iVertices.push_back(v4); TVector3 v5(0,-p,s); this->iVertices.push_back(v5); TVector3 v6(0,p,-s); this->iVertices.push_back(v6); TVector3 v7(0.0,-p,-s); this->iVertices.push_back(v7); TVector3 v8(p,s,0.0); this->iVertices.push_back(v8); TVector3 v9(-p,s,0.0); this->iVertices.push_back(v9); TVector3 v10(p,-s,0.0); this->iVertices.push_back(v10); TVector3 v11(-p,-s,0.0); this->iVertices.push_back(v11); TTriangle t0(0,4,1); this->iTriangles.push_back(t0); TTriangle t1(0,1,5); this->iTriangles.push_back(t1); TTriangle t2(0,5,10); this->iTriangles.push_back(t2); TTriangle t3(0,10,8); this->iTriangles.push_back(t3); TTriangle t4(0,8,4); this->iTriangles.push_back(t4); TTriangle t5(4,8,6); this->iTriangles.push_back(t5); TTriangle t6(4,6,9); this->iTriangles.push_back(t6); TTriangle t7(4,9,1); this->iTriangles.push_back(t7); TTriangle t8(1,9,11); this->iTriangles.push_back(t8); TTriangle t9(1,11,5); this->iTriangles.push_back(t9); TTriangle t10(2,7,3); this->iTriangles.push_back(t10); TTriangle t11(2,3,6); this->iTriangles.push_back(t11); TTriangle t12(2,6,8); this->iTriangles.push_back(t12); TTriangle t13(2,8,10); this->iTriangles.push_back(t13); TTriangle t14(2,10,7); this->iTriangles.push_back(t14); TTriangle t15(7,10,5); this->iTriangles.push_back(t15); TTriangle t16(7,5,11); this->iTriangles.push_back(t16); TTriangle t17(7,11,3); this->iTriangles.push_back(t17); TTriangle t18(3,11,9); this->iTriangles.push_back(t18); TTriangle t19(3,9,6); this->iTriangles.push_back(t19); }
void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) override { const PLSAATriangleEffect& te = args.fGP.cast<PLSAATriangleEffect>(); GrGLSLVertexBuilder* vsBuilder = args.fVertBuilder; GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler; GrGLSLUniformHandler* uniformHandler = args.fUniformHandler; varyingHandler->emitAttributes(te); this->setupPosition(vsBuilder, gpArgs, te.inPosition()->fName); GrGLSLVertToFrag v1(kVec2f_GrSLType); varyingHandler->addVarying("Vertex1", &v1, kHigh_GrSLPrecision); vsBuilder->codeAppendf("%s = vec2(%s.x, %s.y);", v1.vsOut(), te.inVertex1()->fName, te.inVertex1()->fName); GrGLSLVertToFrag v2(kVec2f_GrSLType); varyingHandler->addVarying("Vertex2", &v2, kHigh_GrSLPrecision); vsBuilder->codeAppendf("%s = vec2(%s.x, %s.y);", v2.vsOut(), te.inVertex2()->fName, te.inVertex2()->fName); GrGLSLVertToFrag v3(kVec2f_GrSLType); varyingHandler->addVarying("Vertex3", &v3, kHigh_GrSLPrecision); vsBuilder->codeAppendf("%s = vec2(%s.x, %s.y);", v3.vsOut(), te.inVertex3()->fName, te.inVertex3()->fName); GrGLSLVertToFrag delta1(kVec2f_GrSLType); varyingHandler->addVarying("delta1", &delta1, kHigh_GrSLPrecision); vsBuilder->codeAppendf("%s = vec2(%s.x - %s.x, %s.y - %s.y) * 0.5;", delta1.vsOut(), v1.vsOut(), v2.vsOut(), v2.vsOut(), v1.vsOut()); GrGLSLVertToFrag delta2(kVec2f_GrSLType); varyingHandler->addVarying("delta2", &delta2, kHigh_GrSLPrecision); vsBuilder->codeAppendf("%s = vec2(%s.x - %s.x, %s.y - %s.y) * 0.5;", delta2.vsOut(), v2.vsOut(), v3.vsOut(), v3.vsOut(), v2.vsOut()); GrGLSLVertToFrag delta3(kVec2f_GrSLType); varyingHandler->addVarying("delta3", &delta3, kHigh_GrSLPrecision); vsBuilder->codeAppendf("%s = vec2(%s.x - %s.x, %s.y - %s.y) * 0.5;", delta3.vsOut(), v3.vsOut(), v1.vsOut(), v1.vsOut(), v3.vsOut()); GrGLSLVertToFrag windings(kInt_GrSLType); varyingHandler->addFlatVarying("windings", &windings, kLow_GrSLPrecision); vsBuilder->codeAppendf("%s = %s;", windings.vsOut(), te.inWindings()->fName); // emit transforms this->emitTransforms(vsBuilder, varyingHandler, uniformHandler, gpArgs->fPositionVar, te.inPosition()->fName, te.localMatrix(), args.fTransformsIn, args.fTransformsOut); GrGLSLPPFragmentBuilder* fsBuilder = args.fFragBuilder; SkAssertResult(fsBuilder->enableFeature( GrGLSLFragmentShaderBuilder::kPixelLocalStorage_GLSLFeature)); SkAssertResult(fsBuilder->enableFeature( GrGLSLFragmentShaderBuilder::kStandardDerivatives_GLSLFeature)); fsBuilder->declAppendf(GR_GL_PLS_PATH_DATA_DECL); // Compute four subsamples, each shifted a quarter pixel along x and y from // gl_FragCoord. The oriented box positioning of the subsamples is of course not // optimal, but it greatly simplifies the math and this simplification is necessary for // performance reasons. fsBuilder->codeAppendf("highp vec2 firstSample = %s.xy - vec2(0.25);", fsBuilder->fragmentPosition()); fsBuilder->codeAppendf("highp vec2 delta1 = %s;", delta1.fsIn()); fsBuilder->codeAppendf("highp vec2 delta2 = %s;", delta2.fsIn()); fsBuilder->codeAppendf("highp vec2 delta3 = %s;", delta3.fsIn()); // Check whether first sample is inside the triangle by computing three dot products. If // all are < 0, we're inside. The first vector in each case is half of what it is // "supposed" to be, because we re-use them later as adjustment factors for which half // is the correct value, so we multiply the dots by two to compensate. fsBuilder->codeAppendf("highp float d1 = dot(delta1, (firstSample - %s).yx) * 2.0;", v1.fsIn()); fsBuilder->codeAppendf("highp float d2 = dot(delta2, (firstSample - %s).yx) * 2.0;", v2.fsIn()); fsBuilder->codeAppendf("highp float d3 = dot(delta3, (firstSample - %s).yx) * 2.0;", v3.fsIn()); fsBuilder->codeAppend("highp float dmax = max(d1, max(d2, d3));"); fsBuilder->codeAppendf("pls.windings[0] += (dmax <= 0.0) ? %s : 0;", windings.fsIn()); // for subsequent samples, we don't recalculate the entire dot product -- just adjust it // to the value it would have if we did recompute it. fsBuilder->codeAppend("d1 += delta1.x;"); fsBuilder->codeAppend("d2 += delta2.x;"); fsBuilder->codeAppend("d3 += delta3.x;"); fsBuilder->codeAppend("dmax = max(d1, max(d2, d3));"); fsBuilder->codeAppendf("pls.windings[1] += (dmax <= 0.0) ? %s : 0;", windings.fsIn()); fsBuilder->codeAppend("d1 += delta1.y;"); fsBuilder->codeAppend("d2 += delta2.y;"); fsBuilder->codeAppend("d3 += delta3.y;"); fsBuilder->codeAppend("dmax = max(d1, max(d2, d3));"); fsBuilder->codeAppendf("pls.windings[2] += (dmax <= 0.0) ? %s : 0;", windings.fsIn()); fsBuilder->codeAppend("d1 -= delta1.x;"); fsBuilder->codeAppend("d2 -= delta2.x;"); fsBuilder->codeAppend("d3 -= delta3.x;"); fsBuilder->codeAppend("dmax = max(d1, max(d2, d3));"); fsBuilder->codeAppendf("pls.windings[3] += (dmax <= 0.0) ? %s : 0;", windings.fsIn()); }
Color4 color_interpolation(Color4 const& color0, Color4 const& color1, float t) { Vector3 v0(color0[0]/255.0f, color0[1]/255.0f, color0[2]/255.0f); Vector3 v1(color1[0]/255.0f, color1[1]/255.0f, color1[2]/255.0f); Vector3 r = linear_interpolation(v0, v1, t); return Color4(r[0]*255.0f, r[1]*255.0f, r[2]*255.0f, 255); }