/*! * \brief destructs the dynamic gui generated by a station and its sensor functions. */ void StationInfoDialog::destructDynamicGUI() { //sensor config labels, lineedits, comboboxes. Here they all get deleted and removed from GUI QMapIterator<QString, QLabel*> m(doubleParameterLabel); while(m.hasNext()){ m.next(); ui->tab_sensorConfig->layout()->removeWidget(m.value()); delete m.value(); } doubleParameterLabel.clear(); QMapIterator<QString, QLineEdit*> n(doubleParameter); while(n.hasNext()){ n.next(); ui->tab_sensorConfig->layout()->removeWidget(n.value()); delete n.value(); } doubleParameter.clear(); QMapIterator<QString, QLabel*> o(integerParameterLabel); while(o.hasNext()){ o.next(); ui->tab_sensorConfig->layout()->removeWidget(o.value()); delete o.value(); } integerParameterLabel.clear(); QMapIterator<QString, QLineEdit*> p(integerParameter); while(p.hasNext()){ p.next(); ui->tab_sensorConfig->layout()->removeWidget(p.value()); delete p.value(); } integerParameter.clear(); QMapIterator<QString, QLabel*> q(stringParameterLabel); while(q.hasNext()){ q.next(); ui->tab_sensorConfig->layout()->removeWidget(q.value()); delete q.value(); } stringParameterLabel.clear(); QMapIterator<QString, QComboBox*> r(stringParameter); while(r.hasNext()){ r.next(); ui->tab_sensorConfig->layout()->removeWidget(r.value()); delete r.value(); } stringParameter.clear(); QMapIterator<QString, QLayout*> s(sensorConfigLayouts); while(s.hasNext()){ s.next(); ui->tab_sensorConfig->layout()->removeItem(s.value()); delete s.value(); } sensorConfigLayouts.clear(); //undefined accuracy labels, lineedits and layouts. Here they all get deleted and removed from GUI ui->toolBox_accuracy->setItemText(4,"others"); QMapIterator<QString, QLabel*> k(undefinedSigmaLabel); while(k.hasNext()){ k.next(); ui->page_sigmaUndefined->layout()->removeWidget(k.value()); delete k.value(); } undefinedSigmaLabel.clear(); QMapIterator<QString, QLineEdit*> l(undefinedSigma); while(l.hasNext()){ l.next(); ui->page_sigmaUndefined->layout()->removeWidget(l.value()); delete l.value(); } undefinedSigma.clear(); QMapIterator<QString,QLayout*> j(accuracyLayouts); while(j.hasNext()){ j.next(); ui->page_sigmaUndefined->layout()->removeItem(j.value()); delete j.value(); } accuracyLayouts.clear(); }
std::string StyleParam::toString() const { std::string k(keyName(key)); k += " : "; // TODO: cap, join and color toString() if (value.is<none_type>()) { return k + "none"; } switch (key) { case StyleParamKey::extrude: { if (!value.is<glm::vec2>()) break; auto p = value.get<glm::vec2>(); return k + "(" + std::to_string(p[0]) + ", " + std::to_string(p[1]) + ")"; } case StyleParamKey::size: case StyleParamKey::offset: { if (!value.is<glm::vec2>()) break; auto p = value.get<glm::vec2>(); return k + "(" + std::to_string(p.x) + "px, " + std::to_string(p.y) + "px)"; } case StyleParamKey::transition_hide_time: case StyleParamKey::transition_show_time: case StyleParamKey::transition_selected_time: case StyleParamKey::font_family: case StyleParamKey::font_weight: case StyleParamKey::font_style: case StyleParamKey::text_source: case StyleParamKey::transform: case StyleParamKey::text_wrap: case StyleParamKey::sprite: case StyleParamKey::sprite_default: case StyleParamKey::style: case StyleParamKey::align: case StyleParamKey::anchor: if (!value.is<std::string>()) break; return k + value.get<std::string>(); case StyleParamKey::interactive: case StyleParamKey::visible: case StyleParamKey::centroid: case StyleParamKey::collide: if (!value.is<bool>()) break; return k + std::to_string(value.get<bool>()); case StyleParamKey::width: case StyleParamKey::outline_width: case StyleParamKey::font_stroke_width: case StyleParamKey::font_size: if (!value.is<Width>()) break; return k + std::to_string(value.get<Width>().value); case StyleParamKey::order: case StyleParamKey::outline_order: case StyleParamKey::priority: case StyleParamKey::color: case StyleParamKey::outline_color: case StyleParamKey::font_fill: case StyleParamKey::font_stroke_color: case StyleParamKey::cap: case StyleParamKey::outline_cap: case StyleParamKey::join: case StyleParamKey::outline_join: if (!value.is<uint32_t>()) break; return k + std::to_string(value.get<uint32_t>()); case StyleParamKey::none: break; } if (value.is<std::string>()) { return k + "wrong type: " + value.get<std::string>(); } return k + "undefined " + std::to_string(static_cast<uint8_t>(key)); }
bool Transporter::GenerateWaypoints() { TransportPath path; FillPathVector(GetInfo()->SpellFocus, path); if(path.Size() == 0) return false; vector<keyFrame> keyFrames; int mapChange = 0; for (int i = 1; i < (int)path.Size() - 1; i++) { if (mapChange == 0) { if ((path[i].mapid == path[i+1].mapid)) { keyFrame k(path[i].x, path[i].y, path[i].z, path[i].mapid, path[i].actionFlag, path[i].delay); keyFrames.push_back(k); } else { mapChange = 1; } } else { mapChange--; } } int lastStop = -1; int firstStop = -1; // first cell is arrived at by teleportation :S keyFrames[0].distFromPrev = 0; if (keyFrames[0].actionflag == 2) { lastStop = 0; } // find the rest of the distances between key points for (size_t i = 1; i < keyFrames.size(); i++) { if ((keyFrames[i-1].actionflag == 1) || (keyFrames[i].mapid != keyFrames[i-1].mapid)) { keyFrames[i].distFromPrev = 0; } else { keyFrames[i].distFromPrev = sqrt(pow(keyFrames[i].x - keyFrames[i - 1].x, 2) + pow(keyFrames[i].y - keyFrames[i - 1].y, 2) + pow(keyFrames[i].z - keyFrames[i - 1].z, 2)); } if (keyFrames[i].actionflag == 2) { if(firstStop<0) firstStop=(int)i; lastStop = (int)i; } } float tmpDist = 0; for (int i = 0; i < (int)keyFrames.size(); i++) { int j = (i + lastStop) % (int)keyFrames.size(); if (keyFrames[j].actionflag == 2) tmpDist = 0; else tmpDist += keyFrames[j].distFromPrev; keyFrames[j].distSinceStop = tmpDist; } for (int i = int(keyFrames.size()) - 1; i >= 0; i--) { int j = (i + (firstStop+1)) % (int)keyFrames.size(); tmpDist += keyFrames[(j + 1) % keyFrames.size()].distFromPrev; keyFrames[j].distUntilStop = tmpDist; if (keyFrames[j].actionflag == 2) tmpDist = 0; } for (size_t i = 0; i < keyFrames.size(); i++) { if (keyFrames[i].distSinceStop < (30 * 30 * 0.5)) keyFrames[i].tFrom = sqrt(2 * keyFrames[i].distSinceStop); else keyFrames[i].tFrom = ((keyFrames[i].distSinceStop - (30 * 30 * 0.5f)) / 30) + 30; if (keyFrames[i].distUntilStop < (30 * 30 * 0.5)) keyFrames[i].tTo = sqrt(2 * keyFrames[i].distUntilStop); else keyFrames[i].tTo = ((keyFrames[i].distUntilStop - (30 * 30 * 0.5f)) / 30) + 30; keyFrames[i].tFrom *= 1000; keyFrames[i].tTo *= 1000; } // for (int i = 0; i < keyFrames.size(); i++) { // sLog.outString("%f, %f, %f, %f, %f, %f, %f", keyFrames[i].x, keyFrames[i].y, keyFrames[i].distUntilStop, keyFrames[i].distSinceStop, keyFrames[i].distFromPrev, keyFrames[i].tFrom, keyFrames[i].tTo); // } // Now we're completely set up; we can move along the length of each waypoint at 100 ms intervals // speed = max(30, t) (remember x = 0.5s^2, and when accelerating, a = 1 unit/s^2 int t = 0; bool teleport = false; if (keyFrames[keyFrames.size() - 1].mapid != keyFrames[0].mapid) teleport = true; TWayPoint pos(keyFrames[0].mapid, keyFrames[0].x, keyFrames[0].y, keyFrames[0].z, teleport); uint32 last_t = 0; m_WayPoints[0] = pos; t += keyFrames[0].delay * 1000; int cM = keyFrames[0].mapid; for (size_t i = 0; i < keyFrames.size() - 1; i++) // { float d = 0; float tFrom = keyFrames[i].tFrom; float tTo = keyFrames[i].tTo; // keep the generation of all these points; we use only a few now, but may need the others later if (((d < keyFrames[i + 1].distFromPrev) && (tTo > 0))) { while ((d < keyFrames[i + 1].distFromPrev) && (tTo > 0)) { tFrom += 100; tTo -= 100; if (d > 0) { float newX, newY, newZ; newX = keyFrames[i].x + (keyFrames[i + 1].x - keyFrames[i].x) * d / keyFrames[i + 1].distFromPrev; newY = keyFrames[i].y + (keyFrames[i + 1].y - keyFrames[i].y) * d / keyFrames[i + 1].distFromPrev; newZ = keyFrames[i].z + (keyFrames[i + 1].z - keyFrames[i].z) * d / keyFrames[i + 1].distFromPrev; bool teleport = false; if ((int)keyFrames[i].mapid != cM) { teleport = true; cM = keyFrames[i].mapid; } // sLog.outString("T: %d, D: %f, x: %f, y: %f, z: %f", t, d, newX, newY, newZ); TWayPoint pos(keyFrames[i].mapid, newX, newY, newZ, teleport); if (teleport || ((t - last_t) >= 1000)) { m_WayPoints[t] = pos; last_t = t; } } if (tFrom < tTo) // caught in tFrom dock's "gravitational pull" { if (tFrom <= 30000) { d = 0.5f * (tFrom / 1000) * (tFrom / 1000); } else { d = 0.5f * 30 * 30 + 30 * ((tFrom - 30000) / 1000); } d = d - keyFrames[i].distSinceStop; } else { if (tTo <= 30000) { d = 0.5f * (tTo / 1000) * (tTo / 1000); } else { d = 0.5f * 30 * 30 + 30 * ((tTo - 30000) / 1000); } d = keyFrames[i].distUntilStop - d; } t += 100; } t -= 100; } if (keyFrames[i + 1].tFrom > keyFrames[i + 1].tTo) t += 100 - ((long)keyFrames[i + 1].tTo % 100); else t += (long)keyFrames[i + 1].tTo % 100; bool teleport = false; if ((keyFrames[i + 1].actionflag == 1) || (keyFrames[i + 1].mapid != keyFrames[i].mapid)) { teleport = true; cM = keyFrames[i + 1].mapid; } TWayPoint pos(keyFrames[i + 1].mapid, keyFrames[i + 1].x, keyFrames[i + 1].y, keyFrames[i + 1].z, teleport); // sLog.outString("T: %d, x: %f, y: %f, z: %f, t:%d", t, pos.x, pos.y, pos.z, teleport); //if (teleport) //m_WayPoints[t] = pos; if(keyFrames[i+1].delay > 5) pos.delayed = true; m_WayPoints.insert(WaypointMap::value_type(t, pos)); last_t = t; t += keyFrames[i + 1].delay * 1000; // sLog.outString("------"); } uint32 timer = t; mCurrentWaypoint = m_WayPoints.begin(); //mCurrentWaypoint = GetNextWaypoint(); mNextWaypoint = GetNextWaypoint(); m_pathTime = timer; return true; }
const Vector & SSPquadUP::getResistingForce(void) // this function computes the resisting force vector for the element { Vector f1(8); Vector f2(4); Vector mStress(3); // get stress from the material mStress = theMaterial->getStress(); // get trial displacement const Vector &mDisp_1 = theNodes[0]->getTrialDisp(); const Vector &mDisp_2 = theNodes[1]->getTrialDisp(); const Vector &mDisp_3 = theNodes[2]->getTrialDisp(); const Vector &mDisp_4 = theNodes[3]->getTrialDisp(); Vector d(8); d(0) = mDisp_1(0); d(1) = mDisp_1(1); d(2) = mDisp_2(0); d(3) = mDisp_2(1); d(4) = mDisp_3(0); d(5) = mDisp_3(1); d(6) = mDisp_4(0); d(7) = mDisp_4(1); // add stabilization force to internal force vector f1 = Kstab*d; // add internal force from the stress f1.addMatrixTransposeVector(1.0, Mmem, mStress, 4.0*mThickness*J0); // get mass density from the material double density = theMaterial->getRho(); // subtract body forces from internal force vector double xi[4]; double eta[4]; xi[0] = -1.0; xi[1] = 1.0; xi[2] = 1.0; xi[3] = -1.0; eta[0] = -1.0; eta[1] = -1.0; eta[2] = 1.0; eta[3] = 1.0; if (applyLoad == 0) { for (int i = 0; i < 4; i++) { f1(2*i) -= density*b[0]*mThickness*(J0 + J1*xi[i] + J2*eta[i]); f1(2*i+1) -= density*b[1]*mThickness*(J0 + J1*xi[i] + J2*eta[i]); } } else { for (int i = 0; i < 4; i++) { f1(2*i) -= density*appliedB[0]*mThickness*(J0 + J1*xi[i] + J2*eta[i]); f1(2*i+1) -= density*appliedB[1]*mThickness*(J0 + J1*xi[i] + J2*eta[i]); } } // account for fluid body forces Matrix k(2,2); Vector body(2); // permeability tensor k(0,0) = perm[0]; k(1,1) = perm[1]; // body force vector if (applyLoad == 0) { body(0) = b[0]; body(1) = b[1]; } else { body(0) = appliedB[0]; body(1) = appliedB[1]; } f2 = 4.0*J0*mThickness*fDens*dN*k*body; // assemble full internal force vector for the element mInternalForces(0) = f1(0); mInternalForces(1) = f1(1); mInternalForces(2) = f2(0); mInternalForces(3) = f1(2); mInternalForces(4) = f1(3); mInternalForces(5) = f2(1); mInternalForces(6) = f1(4); mInternalForces(7) = f1(5); mInternalForces(8) = f2(2); mInternalForces(9) = f1(6); mInternalForces(10) = f1(7); mInternalForces(11) = f2(3); // inertial unbalance load mInternalForces.addVector(1.0, Q, -1.0); return mInternalForces; }
/** * The predicted sharp edge gradient ∇I^s is used as a spatial prior to guide * the recovery of a coarse version of the latent image. * Objective function: E(I) = ||I ⊗ k - B||² + λ||∇I - ∇I^s||² * * @param blurred blurred grayvalue image (B) * @param kernel energy presserving kernel (k) * @param selectionGrads gradients of selected edges (x and y direction) (∇I^s) * @param latent resulting image (I) * @param weight λ, default is 2.0e-3 (weight from paper) */ void coarseImageEstimation(Mat blurred, const Mat& kernel, const array<Mat,2>& selectionGrads, Mat& latent, const float weight = 2.0e-3) { assert(kernel.type() == CV_32F && "works with energy preserving float kernel"); assert(blurred.type() == CV_8U && "works with gray valued blurred image"); // convert grayvalue image to float and normalize it to [0,1] blurred.convertTo(blurred, CV_32F); blurred /= 255.0; // fill kernel with zeros to get to the blurred image size // it's important to use BORDER_ISOLATED flag if the kernel is an ROI of a greater image! Mat pkernel; copyMakeBorder(kernel, pkernel, 0, blurred.rows - kernel.rows, 0, blurred.cols - kernel.cols, BORDER_CONSTANT, Scalar::all(0)); // using sobel filter as gradients dx and dy Mat sobelx = Mat::zeros(blurred.size(), CV_32F); sobelx.at<float>(0,0) = -1; sobelx.at<float>(0,1) = 1; Mat sobely = Mat::zeros(blurred.size(), CV_32F); sobely.at<float>(0,0) = -1; sobely.at<float>(1,0) = 1; // ____ ______ ______ // ( F(k) * F(B) + λ * (F(∂_x) * F(∂_x I^s) + F(∂_y) * F(∂_y I^s)) ) // I = F^-1 * ( --------------------------------------------------------------- ) // ( ____ ______ ______ ) // ( F(k) * F(k) + λ * (F(∂_x) * F(∂_x) + F(∂_y) * F(∂_y)) ) // where * is pointwise multiplication // // here: F(k) = k // F(∂_x I^s) = xS // F(∂_y I^s) = yS // F(∂_x) = dx // F(∂_y) = dy // F(B) = B // compute DFT (withoud padding) // the result are stored as 2 channel matrices: Re(FFT(I)), Im(FFT(I)) Mat K, xS, yS, B, Dx, Dy; deblur::dft(pkernel, K); deblur::dft(selectionGrads[0], xS); deblur::dft(selectionGrads[1], yS); deblur::dft(blurred, B); deblur::dft(sobelx, Dx); deblur::dft(sobely, Dy); // weight from paper complex<float> we(weight, 0.0); // latent image in fourier domain Mat I = Mat::zeros(xS.size(), xS.type()); // pointwise computation of I for (int x = 0; x < xS.cols; x++) { for (int y = 0; y < xS.rows; y++) { // complex entries at the current position complex<float> b(B.at<Vec2f>(y, x)[0], B.at<Vec2f>(y, x)[1]); complex<float> k(K.at<Vec2f>(y, x)[0], K.at<Vec2f>(y, x)[1]); complex<float> xs(xS.at<Vec2f>(y, x)[0], xS.at<Vec2f>(y, x)[1]); complex<float> ys(yS.at<Vec2f>(y, x)[0], yS.at<Vec2f>(y, x)[1]); complex<float> dx(Dx.at<Vec2f>(y, x)[0], Dx.at<Vec2f>(y, x)[1]); complex<float> dy(Dy.at<Vec2f>(y, x)[0], Dy.at<Vec2f>(y, x)[1]); // compute current point of latent image in fourier domain complex<float> i = (conj(k) * b + we * (conj(dx) * xs + conj(dy) * ys)) / (conj(k) * k + we * (conj(dx) * dx + conj(dy) * dy)); I.at<Vec2f>(y, x) = { real(i), imag(i) }; } } // compute inverse DFT of the latent image dft(I, latent, DFT_INVERSE | DFT_REAL_OUTPUT); // threshold the result because it has large negative and positive values // which would result in a very grayish image threshold(latent, latent, 0.0, -1, THRESH_TOZERO); // swap slices of the result // because the image is shifted to the upper-left corner (why??) int x = latent.cols; int y = latent.rows; int hs1 = (kernel.cols - 1) / 2; int hs2 = (kernel.rows - 1) / 2; // create rects per image slice // __________ // | | | // | 0 | 1 | // | | | // |------|---| // | 2 | 3 | // |______|___| // // rect gets the coordinates of the top-left corner, width and height Mat q0(latent, Rect(0, 0, x - hs1, y - hs2)); // Top-Left Mat q1(latent, Rect(x - hs1, 0, hs1, y - hs2)); // Top-Right Mat q2(latent, Rect(0, y - hs2, x - hs1, hs2)); // Bottom-Left Mat q3(latent, Rect(x - hs1, y - hs2, hs1, hs2)); // Bottom-Right Mat latentSwap; cv::hconcat(q3, q2, latentSwap); Mat tmp; cv::hconcat(q1, q0, tmp); cv::vconcat(latentSwap, tmp, latentSwap); // convert result to uchar image convertFloatToUchar(latentSwap, latent); assert(blurred.size() == latent.size() && "Something went wrong - latent and blurred size has to be equal"); }
void test() { {// from mutable int int i = 0; // direct-initialization { klass k(i); BOOST_CHECK(&i == &k.m_i); klass const ck(i); BOOST_CHECK(&i == &ck.m_i); } { klass_c k(i); BOOST_CHECK(&i == &k.m_i); klass_c const ck(i); BOOST_CHECK(&i == &ck.m_i); } { klass_cc k(i); BOOST_CHECK(&i == &k.m_i); klass_cc const ck(i); BOOST_CHECK(&i == &ck.m_i); } // copy-initialization { klass k = i; BOOST_CHECK(&i == &k.m_i); klass const ck = i; BOOST_CHECK(&i == &ck.m_i); } { klass_c k = i; BOOST_CHECK(&i == &k.m_i); klass_c const ck = i; BOOST_CHECK(&i == &ck.m_i); } { klass_cc k = i; BOOST_CHECK(&i == &k.m_i); klass_cc const ck = i; BOOST_CHECK(&i == &ck.m_i); } } {// from const int int const ci = 0; // direct-initialization { klass_cc k(ci); BOOST_CHECK(&ci == &k.m_i); klass_cc const ck(ci); BOOST_CHECK(&ci == &ck.m_i); } // copy-initialization { klass_cc k = ci; BOOST_CHECK(&ci == &k.m_i); // fails. klass_cc const ck = ci; BOOST_CHECK(&ci == &ck.m_i); // fails. } } }
int main(int argc, char *argv[]) { LOGOG_INITIALIZE(); TCLAP::CmdLine cmd("Simple matrix vector multiplication test", ' ', "0.1"); // Define a value argument and add it to the command line. // A value arg defines a flag and a type of value that it expects, // such as "-m matrix". TCLAP::ValueArg<std::string> matrix_arg("m", "matrix", "input matrix file", true, "", "string"); // Add the argument mesh_arg to the CmdLine object. The CmdLine object // uses this Arg to parse the command line. cmd.add( matrix_arg ); TCLAP::ValueArg<unsigned> n_cores_arg("p", "number-cores", "number of cores to use", false, 1, "number"); cmd.add( n_cores_arg ); TCLAP::ValueArg<unsigned> n_mults_arg("n", "number-of-multiplications", "number of multiplications to perform", true, 10, "number"); cmd.add( n_mults_arg ); TCLAP::ValueArg<std::string> output_arg("o", "output", "output file", false, "", "string"); cmd.add( output_arg ); TCLAP::ValueArg<unsigned> verbosity_arg("v", "verbose", "level of verbosity [0 very low information, 1 much information]", false, 0, "string"); cmd.add( verbosity_arg ); cmd.parse( argc, argv ); // read the number of multiplication to execute unsigned n_mults (n_mults_arg.getValue()); std::string fname_mat (matrix_arg.getValue()); FormatterCustom *custom_format (new FormatterCustom); logog::Cout *logogCout(new logog::Cout); logogCout->SetFormatter(*custom_format); logog::LogFile *logog_file(NULL); if (! output_arg.getValue().empty()) { logog_file = new logog::LogFile(output_arg.getValue().c_str()); logog_file->SetFormatter( *custom_format ); } // read number of threads unsigned n_threads (n_cores_arg.getValue()); INFO("%s was build with compiler %s", argv[0], BaseLib::BuildInfo::cmake_cxx_compiler.c_str()); #ifdef NDEBUG INFO("CXX_FLAGS: %s %s", BaseLib::BuildInfo::cmake_cxx_flags.c_str(), BaseLib::BuildInfo::cmake_cxx_flags_release.c_str()); #else INFO("CXX_FLAGS: %s %s", BaseLib::BuildInfo::cmake_cxx_flags.c_str(), BaseLib::BuildInfo::cmake_cxx_flags_debug.c_str()); #endif #ifdef UNIX const int max_host_name_len (255); char *hostname(new char[max_host_name_len]); if (gethostname(hostname, max_host_name_len) == 0) INFO("hostname: %s", hostname); delete [] host_name_len; #endif // *** reading matrix in crs format from file std::ifstream in(fname_mat.c_str(), std::ios::in | std::ios::binary); double *A(NULL); unsigned *iA(NULL), *jA(NULL), n; if (in) { INFO("reading matrix from %s ...", fname_mat.c_str()); BaseLib::RunTime timer; timer.start(); CS_read(in, n, iA, jA, A); INFO("\t- took %e s", timer.elapsed()); } else { ERR("error reading matrix from %s", fname_mat.c_str()); return -1; } unsigned nnz(iA[n]); INFO("\tParameters read: n=%d, nnz=%d", n, nnz); #ifdef _OPENMP omp_set_num_threads(n_threads); unsigned *mat_entries_per_core(new unsigned[n_threads]); for (unsigned k(0); k<n_threads; k++) { mat_entries_per_core[k] = 0; } OPENMP_LOOP_TYPE i; { #pragma omp parallel for for (i = 0; i < n; i++) { mat_entries_per_core[omp_get_thread_num()] += iA[i + 1] - iA[i]; } } INFO("*** work per core ***"); for (unsigned k(0); k<n_threads; k++) { INFO("\t%d\t%d", k, mat_entries_per_core[k]); } #endif #ifdef _OPENMP omp_set_num_threads(n_threads); MathLib::CRSMatrixOpenMP<double, unsigned> mat (n, iA, jA, A); #else MathLib::CRSMatrix<double, unsigned> mat (n, iA, jA, A); #endif double *x(new double[n]); double *y(new double[n]); for (unsigned k(0); k<n; ++k) x[k] = 1.0; INFO("*** %d matrix vector multiplications (MVM) with Toms amuxCRS (%d threads) ...", n_mults, n_threads); BaseLib::RunTime run_timer; BaseLib::CPUTime cpu_timer; run_timer.start(); cpu_timer.start(); for (std::size_t k(0); k<n_mults; k++) { mat.amux (1.0, x, y); } INFO("\t[MVM] - took %e sec cpu time, %e sec run time", cpu_timer.elapsed(), run_timer.elapsed()); delete [] x; delete [] y; delete custom_format; delete logogCout; delete logog_file; LOGOG_SHUTDOWN(); return 0; }
SpeedTestReport SpeedTest(const unsigned int nbAtom, const int nbAtomType,const string spacegroup, const RadiationType radiation, const unsigned long nbReflections, const unsigned int dataType,const REAL time) { Crystal cryst(9,11,15,1.2,1.3,1.7,spacegroup); for(int i=0;i<nbAtomType;++i) { cryst.AddScatteringPower(new ScatteringPowerAtom("O","O",1.5)); } for(int i=0;i<nbAtom;++i) { cryst.AddScatterer(new Atom(.0,.0,.0,"O", &(cryst.GetScatteringPowerRegistry().GetObj(i%nbAtomType)), 1.)); } cryst.SetUseDynPopCorr(false); RefinableObj *pData; switch(dataType) { case 0: { DiffractionDataSingleCrystal *pDataTmp=new DiffractionDataSingleCrystal; pDataTmp->SetWavelength(0.25); pDataTmp->SetRadiationType(radiation); pDataTmp->SetMaxSinThetaOvLambda(100.); pDataTmp->SetCrystal(cryst); float maxtheta=0.1; for(;;) { pDataTmp->GenHKLFullSpace(maxtheta, true); if(pDataTmp->GetNbRefl()>(long)nbReflections) break; maxtheta*=1.5; if(maxtheta>=M_PI/2.) break; } CrystVector_REAL hh; hh=pDataTmp->GetH();hh.resizeAndPreserve(nbReflections);hh+=0.0001; CrystVector_REAL kk; kk=pDataTmp->GetK();kk.resizeAndPreserve(nbReflections);kk+=0.0001; CrystVector_REAL ll; ll=pDataTmp->GetL();ll.resizeAndPreserve(nbReflections);ll+=0.0001; CrystVector_long h(nbReflections); h=hh; CrystVector_long k(nbReflections); k=kk; CrystVector_long l(nbReflections); l=ll; CrystVector_REAL iobs(nbReflections); for(unsigned int i=0;i<nbReflections;++i) iobs(i)=(REAL)rand(); CrystVector_REAL sigma(nbReflections);sigma=1; pDataTmp->SetHklIobs (h, k, l, iobs, sigma); pDataTmp->SetWeightToInvSigma2(); pData=pDataTmp; break; } case 1: { PowderPattern *pDataTmp=new PowderPattern; pDataTmp->SetWavelength(0.25); pDataTmp->SetRadiationType(radiation); pDataTmp->SetPowderPatternPar(0.001,.001,3140); CrystVector_REAL iobs(3140); for(unsigned int i=0;i<3140;++i) iobs(i)=(REAL)rand()+1.; pDataTmp->SetPowderPatternObs(iobs); pDataTmp->SetMaxSinThetaOvLambda(100.); PowderPatternBackground *backgdData= new PowderPatternBackground; backgdData->SetName("PbSo4-background"); { CrystVector_REAL tth(2),backgd(2); tth(0)=0.;tth(1)=3.14; backgd(0)=1.;backgd(1)=9.; backgdData->SetInterpPoints(tth,backgd); } pDataTmp->AddPowderPatternComponent(*backgdData); PowderPatternDiffraction * diffData=new PowderPatternDiffraction; diffData->SetCrystal(cryst); pDataTmp->AddPowderPatternComponent(*diffData); diffData->SetName("Crystal phase"); diffData->SetReflectionProfilePar(PROFILE_PSEUDO_VOIGT, .03*DEG2RAD*DEG2RAD,0.,0.,0.3,0); { float maxtheta=0.1; for(;;) { diffData->ScatteringData::GenHKLFullSpace(maxtheta, true); if(diffData->GetNbRefl()>(long)nbReflections) break; maxtheta*=1.5; if(maxtheta>=M_PI/2.) break; } CrystVector_REAL hh; hh=diffData->GetH();hh.resizeAndPreserve(nbReflections); CrystVector_REAL kk; kk=diffData->GetK();kk.resizeAndPreserve(nbReflections); CrystVector_REAL ll; ll=diffData->GetL();ll.resizeAndPreserve(nbReflections); diffData->SetHKL (hh, kk, ll); } pData=pDataTmp; break; } } //Create the global optimization object MonteCarloObj *pGlobalOptObj=new MonteCarloObj; pGlobalOptObj->AddRefinableObj(*pData); pGlobalOptObj->AddRefinableObj(cryst); //Refine only positionnal parameters pGlobalOptObj->FixAllPar(); pGlobalOptObj->SetParIsFixed(gpRefParTypeScattTransl,false); pGlobalOptObj->SetParIsFixed(gpRefParTypeScattOrient,false); //Don't cheat ;-) pGlobalOptObj->RandomizeStartingConfig(); //Annealing parameters (schedule, Tmax, Tmin, displacement schedule, pGlobalOptObj->SetAlgorithmParallTempering(ANNEALING_SMART,1e8,1e-8, ANNEALING_EXPONENTIAL,8,.125); //Global Optimization //The real job-first test long nbTrial=50000000; pGlobalOptObj->Optimize(nbTrial,true,0,time); SpeedTestReport report; report.mNbAtom=nbAtom; report.mNbAtomType=nbAtomType; report.mSpacegroup=spacegroup; report.mRadiation=radiation; report.mNbReflections=nbReflections; report.mDataType=dataType; report.mBogoMRAPS=(REAL)nbAtom*cryst.GetSpaceGroup().GetNbSymmetrics()*(REAL)nbReflections *(50000000-nbTrial)/pGlobalOptObj->GetLastOptimElapsedTime()/1e6; report.mBogoMRAPS_reduced=(REAL)nbAtom*cryst.GetSpaceGroup().GetNbSymmetrics(true,true) *(REAL)nbReflections *(50000000-nbTrial)/pGlobalOptObj->GetLastOptimElapsedTime()/1e6; report.mBogoSPS=(50000000-nbTrial)/pGlobalOptObj->GetLastOptimElapsedTime(); delete pGlobalOptObj; delete pData; return report; }
vector<int> NList::expandNumberList(vector<int> & nlist) { // Convert vector<int> n; ////////////////// // Check ranges for (int i=0; i<nlist.size(); i++) { if ( nlist[i] == -1 ) { if ( nlist[i-1] > nlist[i+1] ) { int tmp = nlist[i+1]; nlist[i+1] = nlist[i-1]; nlist[i-1] = tmp; } } } ////////////////// // Expand ranges for (int i=0; i<nlist.size(); i++) { if ( nlist[i]>0 ) { // Only add valid codes if ( nlist[i] <= maxcat ) n.push_back(nlist[i]); } else { int start = nlist[i-1]+1; int end = nlist[i+1]-1; if ( end > maxcat ) end = maxcat; for (int j=start; j<=end; j++) n.push_back(j); } } // Sort and uniquify stable_sort(n.begin(),n.end()); vector<int>::iterator ne = unique(n.begin(),n.end()); n.erase(ne, n.end()); // Shift to 0..N-1 coding for (int i=0; i<n.size(); i++) --n[i]; // Or is it a negative complement? if ( negmode ) { vector<bool> k(maxcat,false); for (int i=0; i<n.size(); i++) k[ n[i] ] = true; vector<int> n2 = n; n.clear(); for (int i=0; i<maxcat; i++) { if ( ! k[i] ) { n.push_back(i); } } } return n; }
tmp<volSymmTensorField> Smagorinsky2::B() const { volSymmTensorField D = dev(symm(fvc::grad(U()))); return (((2.0/3.0)*I)*k() - 2.0*nuSgs_*D - (2.0*cD2_)*delta()*(D&D)); }
int k() /* { dg-warning "possible candidate" } */ { if (++z > 10) _exit(0); k(); } /* { dg-warning "control reaches" } */
/** * returns the logarithmic derivative of the k speherical Bessel function \param l order of function (orbital angular momentum) \param rho independent variable */ double sphericalB::LogDer_k(int l ,double rho) { if (l > 0 && rho == 0.) return -1.e32; double out = k(l,rho); return derivative/out; }
XSECXPathNodeList * TXFMXPathFilter::evaluateSingleExpr(DSIGXPathFilterExpr *expr) { // Have a single expression that we wish to find the resultant nodeset // for XSECXPathNodeList addedNodes; setXPathNS(document, expr->mp_NSMap, addedNodes, mp_formatter, mp_nse); XPathProcessorImpl xppi; // The processor XercesParserLiaison xpl; #if XALAN_VERSION_MAJOR == 1 && XALAN_VERSION_MINOR > 10 XercesDOMSupport xds(xpl); #else XercesDOMSupport xds; #endif XPathEvaluator xpe; XPathFactoryDefault xpf; XPathConstructionContextDefault xpcc; XalanDocument * xd; XalanNode * contextNode; // Xalan can throw exceptions in all functions, so do one broad catch point. try { // Map to Xalan xd = xpl.createDocument(document); // For performing mapping XercesDocumentWrapper *xdw = xpl.mapDocumentToWrapper(xd); XercesWrapperNavigator xwn(xdw); // Map the "here" node XalanNode * hereNode = NULL; hereNode = xwn.mapNode(expr->mp_xpathFilterNode); if (hereNode == NULL) { hereNode = findHereNodeFromXalan(&xwn, xd, expr->mp_exprTextNode); if (hereNode == NULL) { throw XSECException(XSECException::XPathFilterError, "Unable to find here node in Xalan Wrapper map"); } } // Now work out what we have to set up in the new processing XalanDOMString cd; // For XPath Filter, the root is always the context node cd = XalanDOMString("/"); // Root node // The context node is the "root" node contextNode = xpe.selectSingleNode( xds, xd, cd.c_str(), xd->getDocumentElement()); XPathEnvSupportDefault xpesd; XObjectFactoryDefault xof; XPathExecutionContextDefault xpec(xpesd, xds, xof); ElementPrefixResolverProxy pr(xd->getDocumentElement(), xpesd, xds); // Work around the fact that the XPath implementation is designed for XSLT, so does // not allow here() as a NCName. // THIS IS A KLUDGE AND SHOULD BE DONE BETTER int offset = 0; safeBuffer k(KLUDGE_PREFIX); k.sbStrcatIn(":"); // Map the expression into a local code page string (silly - should be XMLCh) safeBuffer exprSB; exprSB << (*mp_formatter << expr->m_expr.rawXMLChBuffer()); offset = exprSB.sbStrstr("here()"); while (offset >= 0) { if (offset == 0 || offset == 1 || (!(exprSB[offset - 1] == ':' && exprSB[offset - 2] != ':') && separator(exprSB[offset - 1]))) { exprSB.sbStrinsIn(k.rawCharBuffer(), offset); } offset = exprSB.sbOffsetStrstr("here()", offset + 11); } // Install the External function in the Environment handler if (hereNode != NULL) { xpesd.installExternalFunctionLocal(XalanDOMString(URI_ID_DSIG), XalanDOMString("here"), DSIGXPathHere(hereNode)); } XPath * xp = xpf.create(); XalanDOMString Xexpr((char *) exprSB.rawBuffer()); xppi.initXPath(*xp, xpcc, Xexpr, pr); // Now resolve XObjectPtr xObj = xp->execute(contextNode, pr, xpec); // Now map to a list that others can use (naieve list at this time) const NodeRefListBase& lst = xObj->nodeset(); int size = (int) lst.getLength(); const DOMNode *item; XSECXPathNodeList * ret; XSECnew(ret, XSECXPathNodeList); Janitor<XSECXPathNodeList> j_ret(ret); for (int i = 0; i < size; ++ i) { if (lst.item(i) == xd) ret->addNode(document); else { item = xwn.mapNode(lst.item(i)); ret->addNode(item); } } xpesd.uninstallExternalFunctionGlobal(XalanDOMString(URI_ID_DSIG), XalanDOMString("here")); clearXPathNS(document, addedNodes, mp_formatter, mp_nse); j_ret.release(); return ret; } catch (XSLException &e) { safeBuffer msg; // Whatever happens - fix any changes to the original document clearXPathNS(document, addedNodes, mp_formatter, mp_nse); // Collate the exception message into an XSEC message. msg.sbTranscodeIn("Xalan Exception : "); #if defined (XSEC_XSLEXCEPTION_RETURNS_DOMSTRING) msg.sbXMLChCat(e.getType().c_str()); #else msg.sbXMLChCat(e.getType()); #endif msg.sbXMLChCat(" caught. Message : "); msg.sbXMLChCat(e.getMessage().c_str()); throw XSECException(XSECException::XPathFilterError, msg.rawXMLChBuffer()); } catch (...) { clearXPathNS(document, addedNodes, mp_formatter, mp_nse); throw; } return NULL; }
extern "C" void detect_community( #endif Thread& parent, wstring& status, Message const& message, vector<vector<Node*> >& community, bool& is_canceled, shared_ptr<Graph const> g, vector<double> const& edge_weight) { is_canceled = false; size_t const threshold = 4; // Extract 3 clique communities. pair<bool, vector<vector<Node*> > > cc3 = sociarium_project_graph_utility::clique_communities_3( &parent, &status, &message, g); if (cc3.first==false) { is_canceled = true; return; } vector<vector<Node*> > const& c3 = cc3.second; unordered_set<Node*> extracted_nodes_s; for (size_t i=0; i<c3.size(); ++i) if (c3[i].size()>threshold) extracted_nodes_s.insert(c3[i].begin(), c3[i].end()); if (extracted_nodes_s.empty()) return; vector<Node*> extracted_nodes(extracted_nodes_s.begin(), extracted_nodes_s.end()); // Rebuild a graph using extracted nodes. shared_ptr<Graph> g_tmp = g->copy_induced_subgraph(extracted_nodes.begin(), extracted_nodes.end()); // Extract the largest cliques. pair<bool, vector<vector<Node*> > > cc_tmp = sociarium_project_graph_utility::largest_cliques( &parent, &status, &message, g_tmp); if (cc_tmp.first==false) { is_canceled = true; return; } vector<vector<Node*> > c_tmp = cc_tmp.second; size_t const csz_tmp = c_tmp.size(); vector<int> flag(csz_tmp, 0); community.clear(); // Merge the largest cliques. for (size_t i=0; i<csz_tmp; ++i) { vector<Node*>& ci = c_tmp[i]; if (flag[i]!=0 || ci.size()<=threshold) continue; for (size_t j=i+1; j<csz_tmp; ++j) { vector<Node*>& cj = c_tmp[j]; if (flag[j]!=0 || cj.size()<=threshold) continue; if (is_percolatable(ci, cj, threshold)) { // Merge two cliques and eliminate duplicated nodes. unordered_set<Node*> k(ci.begin(), ci.end()); k.insert(cj.begin(), cj.end()); ci.clear(); cj.clear(); ci.insert(ci.end(), k.begin(), k.end()); flag[j] = 1; } } size_t const csz = ci.size(); vector<Node*> c(csz); for (size_t j=0; j<csz; ++j) c[j] = extracted_nodes[ci[j]->index()]; community.push_back(c); } }
TEST_F(fisheyeTest, jacobians) { int n = 10; cv::Mat X(1, n, CV_64FC3); cv::Mat om(3, 1, CV_64F), T(3, 1, CV_64F); cv::Mat f(2, 1, CV_64F), c(2, 1, CV_64F); cv::Mat k(4, 1, CV_64F); double alpha; cv::RNG r; r.fill(X, cv::RNG::NORMAL, 2, 1); X = cv::abs(X) * 10; r.fill(om, cv::RNG::NORMAL, 0, 1); om = cv::abs(om); r.fill(T, cv::RNG::NORMAL, 0, 1); T = cv::abs(T); T.at<double>(2) = 4; T *= 10; r.fill(f, cv::RNG::NORMAL, 0, 1); f = cv::abs(f) * 1000; r.fill(c, cv::RNG::NORMAL, 0, 1); c = cv::abs(c) * 1000; r.fill(k, cv::RNG::NORMAL, 0, 1); k*= 0.5; alpha = 0.01*r.gaussian(1); cv::Mat x1, x2, xpred; cv::Matx33d K(f.at<double>(0), alpha * f.at<double>(0), c.at<double>(0), 0, f.at<double>(1), c.at<double>(1), 0, 0, 1); cv::Mat jacobians; cv::fisheye::projectPoints(X, x1, om, T, K, k, alpha, jacobians); //test on T: cv::Mat dT(3, 1, CV_64FC1); r.fill(dT, cv::RNG::NORMAL, 0, 1); dT *= 1e-9*cv::norm(T); cv::Mat T2 = T + dT; cv::fisheye::projectPoints(X, x2, om, T2, K, k, alpha, cv::noArray()); xpred = x1 + cv::Mat(jacobians.colRange(11,14) * dT).reshape(2, 1); CV_Assert (cv::norm(x2 - xpred) < 1e-10); //test on om: cv::Mat dom(3, 1, CV_64FC1); r.fill(dom, cv::RNG::NORMAL, 0, 1); dom *= 1e-9*cv::norm(om); cv::Mat om2 = om + dom; cv::fisheye::projectPoints(X, x2, om2, T, K, k, alpha, cv::noArray()); xpred = x1 + cv::Mat(jacobians.colRange(8,11) * dom).reshape(2, 1); CV_Assert (cv::norm(x2 - xpred) < 1e-10); //test on f: cv::Mat df(2, 1, CV_64FC1); r.fill(df, cv::RNG::NORMAL, 0, 1); df *= 1e-9*cv::norm(f); cv::Matx33d K2 = K + cv::Matx33d(df.at<double>(0), df.at<double>(0) * alpha, 0, 0, df.at<double>(1), 0, 0, 0, 0); cv::fisheye::projectPoints(X, x2, om, T, K2, k, alpha, cv::noArray()); xpred = x1 + cv::Mat(jacobians.colRange(0,2) * df).reshape(2, 1); CV_Assert (cv::norm(x2 - xpred) < 1e-10); //test on c: cv::Mat dc(2, 1, CV_64FC1); r.fill(dc, cv::RNG::NORMAL, 0, 1); dc *= 1e-9*cv::norm(c); K2 = K + cv::Matx33d(0, 0, dc.at<double>(0), 0, 0, dc.at<double>(1), 0, 0, 0); cv::fisheye::projectPoints(X, x2, om, T, K2, k, alpha, cv::noArray()); xpred = x1 + cv::Mat(jacobians.colRange(2,4) * dc).reshape(2, 1); CV_Assert (cv::norm(x2 - xpred) < 1e-10); //test on k: cv::Mat dk(4, 1, CV_64FC1); r.fill(dk, cv::RNG::NORMAL, 0, 1); dk *= 1e-9*cv::norm(k); cv::Mat k2 = k + dk; cv::fisheye::projectPoints(X, x2, om, T, K, k2, alpha, cv::noArray()); xpred = x1 + cv::Mat(jacobians.colRange(4,8) * dk).reshape(2, 1); CV_Assert (cv::norm(x2 - xpred) < 1e-10); //test on alpha: cv::Mat dalpha(1, 1, CV_64FC1); r.fill(dalpha, cv::RNG::NORMAL, 0, 1); dalpha *= 1e-9*cv::norm(f); double alpha2 = alpha + dalpha.at<double>(0); K2 = K + cv::Matx33d(0, f.at<double>(0) * dalpha.at<double>(0), 0, 0, 0, 0, 0, 0, 0); cv::fisheye::projectPoints(X, x2, om, T, K, k, alpha2, cv::noArray()); xpred = x1 + cv::Mat(jacobians.col(14) * dalpha).reshape(2, 1); CV_Assert (cv::norm(x2 - xpred) < 1e-10); }
//-------------------------------------------------------------------------- void VePNGImage::From(VeBinaryIStream& kIn) { png_structp pkPngPtr; png_infop pkInfoPtr; pkPngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING,(void *)NULL,NULL,NULL); VE_ASSERT(pkPngPtr); pkInfoPtr = png_create_info_struct(pkPngPtr); VE_ASSERT(pkInfoPtr); VE_ASSERT_EQ(setjmp(png_jmpbuf(pkPngPtr)), VE_S_OK); png_set_read_fn(pkPngPtr, &kIn, VePngRead); png_read_png(pkPngPtr, pkInfoPtr, PNG_TRANSFORM_EXPAND, 0); m_u16Width = png_get_image_width(pkPngPtr, pkInfoPtr); m_u16Height = png_get_image_height(pkPngPtr, pkInfoPtr); VeByte byType = png_get_color_type(pkPngPtr, pkInfoPtr); VeByte byDepth = png_get_bit_depth(pkPngPtr, pkInfoPtr); VeByte byUnitSize(0), byPixelSize(0); VeRenderer::Format eFormat = VeRenderer::FMT_UNKNOWN; switch(byType) { case PNG_COLOR_TYPE_GRAY: case PNG_COLOR_TYPE_PALETTE: if(byDepth == 8) { eFormat = VeRenderer::FMT_R8_UNORM; } else if(byDepth == 16) { eFormat = VeRenderer::FMT_R16_UNORM; } byUnitSize = byDepth; byPixelSize = byDepth; break; case PNG_COLOR_TYPE_RGB: if(byDepth == 8) { eFormat = VeRenderer::FMT_R8G8B8A8_UNORM; } else if(byDepth == 16) { eFormat = VeRenderer::FMT_R16G16B16A16_UNORM; } byUnitSize = byDepth * 3; byPixelSize = byDepth * 4; break; case PNG_COLOR_TYPE_RGB_ALPHA: if(byDepth == 8) { eFormat = VeRenderer::FMT_R8G8B8A8_UNORM; } else if(byDepth == 16) { eFormat = VeRenderer::FMT_R16G16B16A16_UNORM; } byUnitSize = byDepth * 4; byPixelSize = byDepth * 4; break; case PNG_COLOR_TYPE_GRAY_ALPHA: if(byDepth == 8) { eFormat = VeRenderer::FMT_R8G8_UNORM; } else if(byDepth == 16) { eFormat = VeRenderer::FMT_R16G16_UNORM; } byUnitSize = byDepth * 2; byPixelSize = byDepth * 2; break; } VE_ASSERT(eFormat != VeRenderer::FMT_UNKNOWN); byPixelSize >>= 3; byUnitSize >>= 3; png_bytep* row_pointers = png_get_rows(pkPngPtr, pkInfoPtr); m_kStream.Reset(); m_kStream << m_u16Width; m_kStream << m_u16Height; m_kStream << VeUInt16(1); m_kStream << VeUInt16(1); m_kStream << VeUInt8(eFormat); m_kStream << VeUInt8(1); m_kStream << VeUInt8(0); m_kStream << VeUInt8(VeRenderer::USAGE_DEFAULT); m_kStream << VeUInt8(VeRenderer::BIND_SHADER_RESOURCE); m_kStream << VeUInt8(0); m_kStream << VeUInt16(0); m_kStream << VeUInt16(1); m_kStream << VeUInt16(1); VeUInt32 u32PixelPitch = byPixelSize * m_u16Width; VeUInt32 u32PixelByteWidth = u32PixelPitch * m_u16Height; m_kStream << u32PixelPitch; m_kStream << u32PixelByteWidth; m_kStream << u32PixelByteWidth; if(byUnitSize == byPixelSize) { for(VeUInt32 i(0); i < m_u16Height; ++i) { m_kStream.Write(row_pointers[i], u32PixelPitch); } } else { for(VeUInt32 i(0); i < m_u16Height; ++i) { for(VeUInt32 j(0); j < m_u16Width; ++j) { m_kStream.Write(row_pointers[i] + (j * byUnitSize), byUnitSize); for(VeInt32 k(0); k < (byPixelSize - byUnitSize); ++k) { m_kStream << VeUInt8(0xff); } } } } png_destroy_read_struct(&pkPngPtr, &pkInfoPtr, NULL); }
void Reflowster::init() { status = new Adafruit_NeoPixel(1, pinConfiguration_statusLed, NEO_GRB + NEO_KHZ800); // knob = new Encoder(pinConfiguration_encoderA, pinConfiguration_encoderB); probe = new Adafruit_MAX31855(pinConfiguration_thermocoupleCS); //display = new ReflowDisplay(); status->begin(); status->show(); pinMode(pinConfiguration_thermocoupleCS, OUTPUT); pinMode(pinConfiguration_relay, OUTPUT); pinMode(pinConfiguration_backButton, INPUT_PULLUP); pinMode(pinConfiguration_encoderButton, INPUT_PULLUP); pinMode(pinConfiguration_encoderA, INPUT_PULLUP); pinMode(pinConfiguration_encoderB, INPUT_PULLUP); pinMode(pinConfiguration_displayDS, OUTPUT); pinMode(pinConfiguration_displaySTCP, OUTPUT); pinMode(pinConfiguration_displaySHCP, OUTPUT); pinMode(pinConfiguration_beep, OUTPUT); pinMode(6,OUTPUT); digitalWrite(6,HIGH); pinMode(9,OUTPUT); digitalWrite(9,HIGH); pinMode(10,OUTPUT); digitalWrite(10,HIGH); pinMode(8,OUTPUT); //separator digitalWrite(8,HIGH); //Serial.begin(9600); // while(!getBackButton()) { // delay(1000); // Serial.println("not back.."); // } // delay(100); // while(getBackButton()) { // delay(1000); // Serial.println("back.."); // } // Serial.println("button"); // delay(100); tone(pinConfiguration_beep,200); delay(150); tone(pinConfiguration_beep,230); delay(150); noTone(pinConfiguration_beep); status->setPixelColor(0,status->Color(100,0,0)); delay(200); status->setPixelColor(0,status->Color(0,100,0)); delay(200); status->setPixelColor(0,status->Color(0,0,100)); delay(200); status->setPixelColor(0,status->Color(0,0,0)); // digitalWrite(pinConfiguration_displaySTCP,LOW); // digitalWrite(pinConfiguration_displayDS,HIGH); // digitalWrite(pinConfiguration_displaySHCP,LOW); // while(1);x while(1) { for (byte c=0; c<8; c++) { unsigned char b = 1 << c; // unsigned char b = 0xff; Serial.println((unsigned char)b); digitalWrite(pinConfiguration_displaySTCP, LOW); for (char i=0; i<8; i++) { digitalWrite(pinConfiguration_displaySHCP,LOW); delay(10); digitalWrite(pinConfiguration_displayDS,b&1); delay(10); Serial.print(" "); Serial.println(b&1); digitalWrite(pinConfiguration_displaySHCP,HIGH); delay(10); b = b >> 1; } digitalWrite(pinConfiguration_displaySTCP, HIGH); delay(500); } delay(100); } //setKnobPosition(50); Encoder k(2,0); while(1) { status->setPixelColor(0,status->Color(0,getKnobPosition(),0)); Serial.println(digitalRead(pinConfiguration_encoderA)); Serial.println(digitalRead(pinConfiguration_encoderB)); Serial.println(); status->show(); delay(200); } }
int AIShapeImport::DoImport(const TCHAR *filename,ImpInterface *i,Interface *gi, BOOL suppressPrompts) { // Get a scale factor from points (the file storage) to our units double mScale = GetMasterScale(UNITS_INCHES); float scaleFactor = float((1.0 / mScale) / 72.0); // Set a global prompt display switch showPrompts = suppressPrompts ? FALSE : TRUE; WorkFile theFile(filename,_T("rb")); if(suppressPrompts) { } else { if (!DialogBox(hInstance, MAKEINTRESOURCE(IDD_MERGEORREPL), gi->GetMAXHWnd(), ImportDlgProc)) return IMPEXP_CANCEL; } dStream = i->DumpFile(); if(!(stream = theFile.Stream())) { if(showPrompts) MessageBox(IDS_TH_ERR_OPENING_FILE, IDS_TH_3DSIMP); return 0; // Didn't open! } // Got the file -- Now put up the options dialog! if(showPrompts) { int result = DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_SHAPEIMPORTOPTIONS), gi->GetMAXHWnd(), ShapeImportOptionsDlgProc, (LPARAM)this); if(result <= 0) return IMPEXP_CANCEL; } else { // Set default parameters here importType = MULTIPLE_SHAPES; } if (replaceScene) { if (!i->NewScene()) return IMPEXP_CANCEL; } theShapeImport = this; int line,count,status,phase,buflen, reason; float x1,y1,x2,y2,x3,y3; char buffer[256]; phase=0; count=0; line=0; gotStuff = FALSE; GetDecSymbolFromRegistry(); loop: line++; if((status=getaline(stream,buffer,255,0))<0) { reason = IDS_TH_LINE_TOO_LONG; corrupted: if(showPrompts) MessageBox(reason, IDS_TH_3DSIMP); FinishWorkingShape(TRUE, i); return gotStuff; } if(status==0) { FinishWorkingShape(TRUE, i); return gotStuff; // EOF } /* Look for appropriate section of file */ buflen=static_cast<int>(strlen(buffer)); // SR DCAST64: Downcast to 2G limit. switch(phase) { case 0: /* Looking for the path */ buffer[10]=0; if(stricmp(buffer,"%%endsetup")==0) phase=1; break; case 1: /* Loading the path data -- looking for initial 'm' */ if(buflen<2) break; if(buffer[buflen-2]==' ' && buffer[buflen-1]=='m') { phase=2; goto phase2; } break; case 2: phase2: if(buflen<2) break; if(buffer[buflen-2]!=' ') break; switch(buffer[buflen-1]) { case 'm': { /* Moveto */ FixDecimalSymbol(buffer); if(sscanf(buffer,"%f %f",&x1,&y1)!=2) { #ifdef DBG1 DebugPrint("Moveto buffer:%s\n",buffer); #endif bad_file: reason = IDS_TH_INVALIDFILE; goto corrupted; } // If had one working, wrap it up FinishWorkingShape(FALSE, i); // Start this new spline if(!StartWorkingShape()) { reason = IDS_TH_NO_RAM; goto corrupted; } Point3 p(x1 * scaleFactor, y1 * scaleFactor, 0.0f); SplineKnot k(KTYPE_BEZIER, LTYPE_CURVE, p, p, p); spline->AddKnot(k); } break; case 'l': /* Lineto */ case 'L': { /* Lineto corner */ FixDecimalSymbol(buffer); if(sscanf(buffer,"%f %f",&x1,&y1)!=2) { #ifdef DBG1 DebugPrint("Lineto buffer:%s\n",buffer); #endif goto bad_file; } Point3 p(x1 * scaleFactor, y1 * scaleFactor, 0.0f); SplineKnot k(KTYPE_BEZIER, LTYPE_CURVE, p, p, p); spline->AddKnot(k); } break; case 'c': /* Curveto */ case 'C': { /* Curveto corner */ FixDecimalSymbol(buffer); if(sscanf(buffer,"%f %f %f %f %f %f",&x1,&y1,&x2,&y2,&x3,&y3)!=6) { #ifdef DBG1 DebugPrint("Curveto buffer:%s\n",buffer); #endif goto bad_file; } int lastKnot = spline->KnotCount() - 1; spline->SetOutVec(lastKnot, Point3(x1 * scaleFactor, y1 * scaleFactor, 0.0f)); Point3 p(x3 * scaleFactor, y3 * scaleFactor, 0.0f); Point3 in(x2 * scaleFactor, y2 * scaleFactor, 0.0f); SplineKnot k(KTYPE_BEZIER, LTYPE_CURVE, p, in, p); spline->AddKnot(k); } break; case 'v': /* Current/vec */ case 'V': { /* Current/vec corner */ FixDecimalSymbol(buffer); if(sscanf(buffer,"%f %f %f %f",&x2,&y2,&x3,&y3)!=4) { #ifdef DBG1 DebugPrint("Current/vec buffer:%s\n",buffer); #endif goto bad_file; } Point3 p(x3 * scaleFactor, y3 * scaleFactor, 0.0f); Point3 in(x2 * scaleFactor, y2 * scaleFactor, 0.0f); SplineKnot k(KTYPE_BEZIER, LTYPE_CURVE, p, in, p); spline->AddKnot(k); } break; case 'y': /* Vec/next */ case 'Y': { /* Vec/next corner */ FixDecimalSymbol(buffer); if(sscanf(buffer,"%f %f %f %f",&x1,&y1,&x3,&y3)!=4) { #ifdef DBG1 DebugPrint("vec/next buffer:%s\n",buffer); #endif goto bad_file; } int lastKnot = spline->KnotCount() - 1; spline->SetOutVec(lastKnot, Point3(x1 * scaleFactor, y1 * scaleFactor, 0.0f)); Point3 p(x3 * scaleFactor, y3 * scaleFactor, 0.0f); SplineKnot k(KTYPE_BEZIER, LTYPE_CURVE, p, p, p); spline->AddKnot(k); } break; } break; } count++; goto loop; }
void TransportMgr::GeneratePath(GameObjectTemplate const* goInfo, TransportTemplate* transport) { uint32 pathId = goInfo->moTransport.taxiPathID; TaxiPathNodeList const& path = sTaxiPathNodesByPath[pathId]; std::vector<KeyFrame>& keyFrames = transport->keyFrames; Movement::PointsArray splinePath, allPoints; bool mapChange = false; for (size_t i = 0; i < path.size(); ++i) allPoints.push_back(G3D::Vector3(path[i]->Loc.X, path[i]->Loc.Y, path[i]->Loc.Z)); // Add extra points to allow derivative calculations for all path nodes allPoints.insert(allPoints.begin(), allPoints.front().lerp(allPoints[1], -0.2f)); allPoints.push_back(allPoints.back().lerp(allPoints[allPoints.size() - 2], -0.2f)); allPoints.push_back(allPoints.back().lerp(allPoints[allPoints.size() - 2], -1.0f)); SplineRawInitializer initer(allPoints); TransportSpline orientationSpline; orientationSpline.init_spline_custom(initer); orientationSpline.initLengths(); for (size_t i = 0; i < path.size(); ++i) { if (!mapChange) { TaxiPathNodeEntry const* node_i = path[i]; if (i != path.size() - 1 && (node_i->Flags & TAXI_PATH_NODE_FLAG_TELEPORT || node_i->MapID != path[i + 1]->MapID)) { keyFrames.back().Teleport = true; mapChange = true; } else { KeyFrame k(node_i); G3D::Vector3 h; orientationSpline.evaluate_derivative(i + 1, 0.0f, h); k.InitialOrientation = Position::NormalizeOrientation(std::atan2(h.y, h.x) + float(M_PI)); keyFrames.push_back(k); splinePath.push_back(G3D::Vector3(node_i->Loc.X, node_i->Loc.Y, node_i->Loc.Z)); transport->mapsUsed.insert(k.Node->MapID); } } else mapChange = false; } if (splinePath.size() >= 2) { // Remove special catmull-rom spline points if (!keyFrames.front().IsStopFrame() && !keyFrames.front().Node->ArrivalEventID && !keyFrames.front().Node->DepartureEventID) { splinePath.erase(splinePath.begin()); keyFrames.erase(keyFrames.begin()); } if (!keyFrames.back().IsStopFrame() && !keyFrames.back().Node->ArrivalEventID && !keyFrames.back().Node->DepartureEventID) { splinePath.pop_back(); keyFrames.pop_back(); } } ASSERT(!keyFrames.empty()); if (transport->mapsUsed.size() > 1) { for (std::set<uint32>::const_iterator itr = transport->mapsUsed.begin(); itr != transport->mapsUsed.end(); ++itr) ASSERT(!sMapStore.LookupEntry(*itr)->Instanceable()); transport->inInstance = false; } else transport->inInstance = sMapStore.LookupEntry(*transport->mapsUsed.begin())->Instanceable(); // last to first is always "teleport", even for closed paths keyFrames.back().Teleport = true; const float speed = float(goInfo->moTransport.moveSpeed); const float accel = float(goInfo->moTransport.accelRate); const float accel_dist = 0.5f * speed * speed / accel; transport->accelTime = speed / accel; transport->accelDist = accel_dist; int32 firstStop = -1; int32 lastStop = -1; // first cell is arrived at by teleportation :S keyFrames[0].DistFromPrev = 0; keyFrames[0].Index = 1; if (keyFrames[0].IsStopFrame()) { firstStop = 0; lastStop = 0; } // find the rest of the distances between key points // Every path segment has its own spline size_t start = 0; for (size_t i = 1; i < keyFrames.size(); ++i) { if (keyFrames[i - 1].Teleport || i + 1 == keyFrames.size()) { size_t extra = !keyFrames[i - 1].Teleport ? 1 : 0; TransportSpline* spline = new TransportSpline(); spline->init_spline(&splinePath[start], i - start + extra, Movement::SplineBase::ModeCatmullrom); spline->initLengths(); for (size_t j = start; j < i + extra; ++j) { keyFrames[j].Index = j - start + 1; keyFrames[j].DistFromPrev = float(spline->length(j - start, j + 1 - start)); if (j > 0) keyFrames[j - 1].NextDistFromPrev = keyFrames[j].DistFromPrev; keyFrames[j].Spline = spline; } if (keyFrames[i - 1].Teleport) { keyFrames[i].Index = i - start + 1; keyFrames[i].DistFromPrev = 0.0f; keyFrames[i - 1].NextDistFromPrev = 0.0f; keyFrames[i].Spline = spline; } start = i; } if (keyFrames[i].IsStopFrame()) { // remember first stop frame if (firstStop == -1) firstStop = i; lastStop = i; } } keyFrames.back().NextDistFromPrev = keyFrames.front().DistFromPrev; if (firstStop == -1 || lastStop == -1) firstStop = lastStop = 0; // at stopping keyframes, we define distSinceStop == 0, // and distUntilStop is to the next stopping keyframe. // this is required to properly handle cases of two stopping frames in a row (yes they do exist) float tmpDist = 0.0f; for (size_t i = 0; i < keyFrames.size(); ++i) { int32 j = (i + lastStop) % keyFrames.size(); if (keyFrames[j].IsStopFrame() || j == lastStop) tmpDist = 0.0f; else tmpDist += keyFrames[j].DistFromPrev; keyFrames[j].DistSinceStop = tmpDist; } tmpDist = 0.0f; for (int32 i = int32(keyFrames.size()) - 1; i >= 0; i--) { int32 j = (i + firstStop) % keyFrames.size(); tmpDist += keyFrames[(j + 1) % keyFrames.size()].DistFromPrev; keyFrames[j].DistUntilStop = tmpDist; if (keyFrames[j].IsStopFrame() || j == firstStop) tmpDist = 0.0f; } for (size_t i = 0; i < keyFrames.size(); ++i) { float total_dist = keyFrames[i].DistSinceStop + keyFrames[i].DistUntilStop; if (total_dist < 2 * accel_dist) // won't reach full speed { if (keyFrames[i].DistSinceStop < keyFrames[i].DistUntilStop) // is still accelerating { // calculate accel+brake time for this short segment float segment_time = 2.0f * std::sqrt((keyFrames[i].DistUntilStop + keyFrames[i].DistSinceStop) / accel); // substract acceleration time keyFrames[i].TimeTo = segment_time - std::sqrt(2 * keyFrames[i].DistSinceStop / accel); } else // slowing down keyFrames[i].TimeTo = std::sqrt(2 * keyFrames[i].DistUntilStop / accel); } else if (keyFrames[i].DistSinceStop < accel_dist) // still accelerating (but will reach full speed) { // calculate accel + cruise + brake time for this long segment float segment_time = (keyFrames[i].DistUntilStop + keyFrames[i].DistSinceStop) / speed + (speed / accel); // substract acceleration time keyFrames[i].TimeTo = segment_time - std::sqrt(2 * keyFrames[i].DistSinceStop / accel); } else if (keyFrames[i].DistUntilStop < accel_dist) // already slowing down (but reached full speed) keyFrames[i].TimeTo = std::sqrt(2 * keyFrames[i].DistUntilStop / accel); else // at full speed keyFrames[i].TimeTo = (keyFrames[i].DistUntilStop / speed) + (0.5f * speed / accel); } // calculate tFrom times from tTo times float segmentTime = 0.0f; for (size_t i = 0; i < keyFrames.size(); ++i) { int32 j = (i + lastStop) % keyFrames.size(); if (keyFrames[j].IsStopFrame() || j == lastStop) segmentTime = keyFrames[j].TimeTo; keyFrames[j].TimeFrom = segmentTime - keyFrames[j].TimeTo; } // calculate path times keyFrames[0].ArriveTime = 0; float curPathTime = 0.0f; if (keyFrames[0].IsStopFrame()) { curPathTime = float(keyFrames[0].Node->Delay); keyFrames[0].DepartureTime = uint32(curPathTime * IN_MILLISECONDS); } for (size_t i = 1; i < keyFrames.size(); ++i) { curPathTime += keyFrames[i - 1].TimeTo; if (keyFrames[i].IsStopFrame()) { keyFrames[i].ArriveTime = uint32(curPathTime * IN_MILLISECONDS); keyFrames[i - 1].NextArriveTime = keyFrames[i].ArriveTime; curPathTime += float(keyFrames[i].Node->Delay); keyFrames[i].DepartureTime = uint32(curPathTime * IN_MILLISECONDS); } else { curPathTime -= keyFrames[i].TimeTo; keyFrames[i].ArriveTime = uint32(curPathTime * IN_MILLISECONDS); keyFrames[i - 1].NextArriveTime = keyFrames[i].ArriveTime; keyFrames[i].DepartureTime = keyFrames[i].ArriveTime; } } keyFrames.back().NextArriveTime = keyFrames.back().DepartureTime; transport->pathTime = keyFrames.back().DepartureTime; }
void IniFile::setStringValue(const char * section, const char * key, const char * value) { int sec_start, sec_end, key_start, key_end, value_start, value_end; std::string sec(section); std::string k(key); std::string val(value); loadIniFile(); sec_start = 0; int leftbrace, rightbrace, lastnewline, nextnewline; do { sec_start = _FileContainer.find(section, sec_start + 1); while (isInComment(sec_start)) { sec_start = _FileContainer.find(section, sec_start + 1); } if (sec_start == std::string::npos) break; leftbrace = _FileContainer.rfind('[', sec_start); rightbrace = _FileContainer.find(']', sec_start); lastnewline = _FileContainer.rfind('\n', sec_start); nextnewline = _FileContainer.find('\n', sec_start); if (rightbrace == std::string::npos) { sec_start = std::string::npos; break; } if (nextnewline == std::string::npos) nextnewline = _FileContainer.size(); } while (leftbrace < lastnewline || rightbrace > nextnewline); /* not find the section */ if (sec_start == std::string::npos) { _FileContainer += "\n[" + sec + "]\n" + k + "=" + val + "\n"; _FileMap.insert(std::map<std::string, std::string>::value_type(sec + "|" + k, val)); } else{ sec_end = sec_start + strlen(section); int bound = _FileContainer.find('[', sec_start); key_start = _FileContainer.find(key, sec_end); while (isInComment(key_start)) { key_start = _FileContainer.find(key, key_start + 1); } /* not find the key */ if (key_start == std::string::npos || (bound > std::string::npos && key_start > bound)) { int pos = _FileContainer.find('\n', sec_end) + 1; _FileContainer.insert(pos, key); pos += strlen(key); _FileContainer.insert(pos, "="); pos++; _FileContainer.insert(pos, value); pos += strlen(value); _FileContainer.insert(pos, "\n"); _FileMap.insert(std::map<std::string, std::string>::value_type(sec + "|" + k, val)); } else { key_end = key_start + strlen(key); value_start = _FileContainer.find('=', key_end) + 1; while (_FileContainer[value_start] == ' ') value_start++; value_end = _FileContainer.find('\n', value_start) - 1; if (value_end == std::string::npos) value_end = _FileContainer.size() - 1; while (_FileContainer[value_end] == ' ') value_end--; _FileContainer.replace(value_start, value_end - value_start + 1, value); auto iter = _FileMap.find(sec + "|" + k); iter->second = val; } } std::fstream file(_FileName.c_str(), std::ios::out); file << _FileContainer; }
bool Transport::GenerateWaypoints(uint32 pathid, std::set<uint32> &mapids) { TransportPath path; objmgr.GetTransportPathNodes(pathid, path); if (path.Empty()) return false; std::vector<keyFrame> keyFrames; int mapChange = 0; mapids.clear(); for (size_t i = 1; i < path.Size() - 1; i++) { if (mapChange == 0) { if ((path[i].mapid == path[i+1].mapid)) { keyFrame k(path[i].x, path[i].y, path[i].z, path[i].mapid, path[i].actionFlag, path[i].delay); keyFrames.push_back(k); mapids.insert(k.mapid); } else { mapChange = 1; } } else { --mapChange; } } int lastStop = -1; int firstStop = -1; // first cell is arrived at by teleportation :S keyFrames[0].distFromPrev = 0; if (keyFrames[0].actionflag == 2) { lastStop = 0; } // find the rest of the distances between key points for (size_t i = 1; i < keyFrames.size(); i++) { if ((keyFrames[i].actionflag == 1) || (keyFrames[i].mapid != keyFrames[i-1].mapid)) { keyFrames[i].distFromPrev = 0; } else { keyFrames[i].distFromPrev = sqrt(pow(keyFrames[i].x - keyFrames[i - 1].x, 2) + pow(keyFrames[i].y - keyFrames[i - 1].y, 2) + pow(keyFrames[i].z - keyFrames[i - 1].z, 2)); } if (keyFrames[i].actionflag == 2) { // remember first stop frame if(firstStop == -1) firstStop = i; lastStop = i; } } float tmpDist = 0; for (size_t i = 0; i < keyFrames.size(); i++) { int j = (i + lastStop) % keyFrames.size(); if (keyFrames[j].actionflag == 2) tmpDist = 0; else tmpDist += keyFrames[j].distFromPrev; keyFrames[j].distSinceStop = tmpDist; } for (int i = int(keyFrames.size()) - 1; i >= 0; i--) { int j = (i + (firstStop+1)) % keyFrames.size(); tmpDist += keyFrames[(j + 1) % keyFrames.size()].distFromPrev; keyFrames[j].distUntilStop = tmpDist; if (keyFrames[j].actionflag == 2) tmpDist = 0; } for (size_t i = 0; i < keyFrames.size(); i++) { if (keyFrames[i].distSinceStop < (30 * 30 * 0.5f)) keyFrames[i].tFrom = sqrt(2 * keyFrames[i].distSinceStop); else keyFrames[i].tFrom = ((keyFrames[i].distSinceStop - (30 * 30 * 0.5f)) / 30) + 30; if (keyFrames[i].distUntilStop < (30 * 30 * 0.5f)) keyFrames[i].tTo = sqrt(2 * keyFrames[i].distUntilStop); else keyFrames[i].tTo = ((keyFrames[i].distUntilStop - (30 * 30 * 0.5f)) / 30) + 30; keyFrames[i].tFrom *= 1000; keyFrames[i].tTo *= 1000; } // for (int i = 0; i < keyFrames.size(); i++) { // sLog.outString("%f, %f, %f, %f, %f, %f, %f", keyFrames[i].x, keyFrames[i].y, keyFrames[i].distUntilStop, keyFrames[i].distSinceStop, keyFrames[i].distFromPrev, keyFrames[i].tFrom, keyFrames[i].tTo); // } // Now we're completely set up; we can move along the length of each waypoint at 100 ms intervals // speed = max(30, t) (remember x = 0.5s^2, and when accelerating, a = 1 unit/s^2 int t = 0; bool teleport = false; if (keyFrames[keyFrames.size() - 1].mapid != keyFrames[0].mapid) teleport = true; WayPoint pos(keyFrames[0].mapid, keyFrames[0].x, keyFrames[0].y, keyFrames[0].z, teleport); m_WayPoints[0] = pos; t += keyFrames[0].delay * 1000; uint32 cM = keyFrames[0].mapid; for (size_t i = 0; i < keyFrames.size() - 1; i++) { float d = 0; float tFrom = keyFrames[i].tFrom; float tTo = keyFrames[i].tTo; // keep the generation of all these points; we use only a few now, but may need the others later if (((d < keyFrames[i + 1].distFromPrev) && (tTo > 0))) { while ((d < keyFrames[i + 1].distFromPrev) && (tTo > 0)) { tFrom += 100; tTo -= 100; if (d > 0) { float newX, newY, newZ; newX = keyFrames[i].x + (keyFrames[i + 1].x - keyFrames[i].x) * d / keyFrames[i + 1].distFromPrev; newY = keyFrames[i].y + (keyFrames[i + 1].y - keyFrames[i].y) * d / keyFrames[i + 1].distFromPrev; newZ = keyFrames[i].z + (keyFrames[i + 1].z - keyFrames[i].z) * d / keyFrames[i + 1].distFromPrev; bool teleport = false; if (keyFrames[i].mapid != cM) { teleport = true; cM = keyFrames[i].mapid; } // sLog.outString("T: %d, D: %f, x: %f, y: %f, z: %f", t, d, newX, newY, newZ); WayPoint pos(keyFrames[i].mapid, newX, newY, newZ, teleport); if (teleport) m_WayPoints[t] = pos; } if (tFrom < tTo) // caught in tFrom dock's "gravitational pull" { if (tFrom <= 30000) { d = 0.5f * (tFrom / 1000) * (tFrom / 1000); } else { d = 0.5f * 30 * 30 + 30 * ((tFrom - 30000) / 1000); } d = d - keyFrames[i].distSinceStop; } else { if (tTo <= 30000) { d = 0.5f * (tTo / 1000) * (tTo / 1000); } else { d = 0.5f * 30 * 30 + 30 * ((tTo - 30000) / 1000); } d = keyFrames[i].distUntilStop - d; } t += 100; } t -= 100; } if (keyFrames[i + 1].tFrom > keyFrames[i + 1].tTo) t += 100 - ((long)keyFrames[i + 1].tTo % 100); else t += (long)keyFrames[i + 1].tTo % 100; bool teleport = false; if ((keyFrames[i + 1].actionflag == 1) || (keyFrames[i + 1].mapid != keyFrames[i].mapid)) { teleport = true; cM = keyFrames[i + 1].mapid; } WayPoint pos(keyFrames[i + 1].mapid, keyFrames[i + 1].x, keyFrames[i + 1].y, keyFrames[i + 1].z, teleport); // sLog.outString("T: %d, x: %f, y: %f, z: %f, t:%d", t, pos.x, pos.y, pos.z, teleport); //if (teleport) m_WayPoints[t] = pos; t += keyFrames[i + 1].delay * 1000; // sLog.outString("------"); } uint32 timer = t; // sLog.outDetail(" Generated %d waypoints, total time %u.", m_WayPoints.size(), timer); m_curr = m_WayPoints.begin(); m_curr = GetNextWayPoint(); m_next = GetNextWayPoint(); m_pathTime = timer; m_nextNodeTime = m_curr->first; return true; }
~PolygonTest() { delete _polygon; for (std::size_t k(0); k<_pnts.size(); k++) delete _pnts[k]; }
void EarClippingTriangulation::initVertexList () { size_t n_pnts (_pnts.size()); for (size_t k(0); k<n_pnts; k++) _vertex_list.push_back (k); }
TEST_F(PolygonTest, isPntInPolygonCheckCorners) { for (std::size_t k(0); k<_pnts.size(); k++) EXPECT_TRUE(_polygon->isPntInPolygon(*_pnts[k])); }
void InteractionIntegralSM::computeAuxFields(RankTwoTensor & aux_stress, RankTwoTensor & grad_disp) { RealVectorValue k(0.0); if (_sif_mode == SifMethod::KI) k(0) = 1.0; else if (_sif_mode == SifMethod::KII) k(1) = 1.0; else if (_sif_mode == SifMethod::KIII) k(2) = 1.0; Real t = _theta; Real t2 = _theta / 2.0; Real tt2 = 3.0 * _theta / 2.0; Real st = std::sin(t); Real ct = std::cos(t); Real st2 = std::sin(t2); Real ct2 = std::cos(t2); Real stt2 = std::sin(tt2); Real ctt2 = std::cos(tt2); Real ct2sq = Utility::pow<2>(ct2); Real ct2cu = Utility::pow<3>(ct2); Real sqrt2PiR = std::sqrt(2.0 * libMesh::pi * _r); // Calculate auxiliary stress tensor aux_stress.zero(); aux_stress(0, 0) = 1.0 / sqrt2PiR * (k(0) * ct2 * (1.0 - st2 * stt2) - k(1) * st2 * (2.0 + ct2 * ctt2)); aux_stress(1, 1) = 1.0 / sqrt2PiR * (k(0) * ct2 * (1.0 + st2 * stt2) + k(1) * st2 * ct2 * ctt2); aux_stress(0, 1) = 1.0 / sqrt2PiR * (k(0) * ct2 * st2 * ctt2 + k(1) * ct2 * (1.0 - st2 * stt2)); aux_stress(0, 2) = -1.0 / sqrt2PiR * k(2) * st2; aux_stress(1, 2) = 1.0 / sqrt2PiR * k(2) * ct2; // plane stress // Real s33 = 0; // plane strain aux_stress(2, 2) = _poissons_ratio * (aux_stress(0, 0) + aux_stress(1, 1)); aux_stress(1, 0) = aux_stress(0, 1); aux_stress(2, 0) = aux_stress(0, 2); aux_stress(2, 1) = aux_stress(1, 2); // Calculate x1 derivative of auxiliary displacements grad_disp.zero(); grad_disp(0, 0) = k(0) / (4.0 * _shear_modulus * sqrt2PiR) * (ct * ct2 * _kappa + ct * ct2 - 2.0 * ct * ct2cu + st * st2 * _kappa + st * st2 - 6.0 * st * st2 * ct2sq) + k(1) / (4.0 * _shear_modulus * sqrt2PiR) * (ct * st2 * _kappa + ct * st2 + 2.0 * ct * st2 * ct2sq - st * ct2 * _kappa + 3.0 * st * ct2 - 6.0 * st * ct2cu); grad_disp(0, 1) = k(0) / (4.0 * _shear_modulus * sqrt2PiR) * (ct * st2 * _kappa + ct * st2 - 2.0 * ct * st2 * ct2sq - st * ct2 * _kappa - 5.0 * st * ct2 + 6.0 * st * ct2cu) + k(1) / (4.0 * _shear_modulus * sqrt2PiR) * (-ct * ct2 * _kappa + 3.0 * ct * ct2 - 2.0 * ct * ct2cu - st * st2 * _kappa + 3.0 * st * st2 - 6.0 * st * st2 * ct2sq); grad_disp(0, 2) = k(2) / (_shear_modulus * sqrt2PiR) * (st2 * ct - ct2 * st); }
void TransportMgr::GeneratePath(GameObjectTemplate const* goInfo, TransportTemplate* transport) { uint32 pathId = goInfo->moTransport.taxiPathId; TaxiPathNodeList const& path = sTaxiPathNodesByPath[pathId]; std::vector<KeyFrame>& keyFrames = transport->keyFrames; bool mapChange = false; for (size_t i = 1; i < path.size() - 1; ++i) { if (!mapChange) { TaxiPathNodeEntry const& node_i = path[i]; if (node_i.actionFlag == 1 || node_i.mapid != path[i+1].mapid) { keyFrames.back().teleport = true; mapChange = true; } else { KeyFrame k(node_i); keyFrames.push_back(k); transport->mapsUsed.insert(k.node->mapid); } } else mapChange = false; } // last to first is always "teleport", even for closed paths keyFrames.back().teleport = true; const float speed = float(goInfo->moTransport.moveSpeed); const float accel = float(goInfo->moTransport.accelRate); const float accel_dist = 0.5f * speed * speed / accel; transport->accelTime = speed / accel; transport->accelDist = accel_dist; int32 firstStop = -1; int32 lastStop = -1; // first cell is arrived at by teleportation :S keyFrames[0].distFromPrev = 0; if (keyFrames[0].IsStopFrame()) { firstStop = 0; lastStop = 0; } bool closed = (keyFrames[0].node->mapid == keyFrames.back().node->mapid) && (keyFrames[0].node->actionFlag != 1); // find the rest of the distances between key points for (size_t i = 1; i < keyFrames.size(); ++i) { if (keyFrames[i-1].teleport) keyFrames[i].distFromPrev = 0; else keyFrames[i].distFromPrev = sqrt(pow(keyFrames[i].node->x - keyFrames[i - 1].node->x, 2) + pow(keyFrames[i].node->y - keyFrames[i - 1].node->y, 2) + pow(keyFrames[i].node->z - keyFrames[i - 1].node->z, 2)); if (keyFrames[i].IsStopFrame()) { // remember first stop frame if (firstStop == -1) firstStop = i; lastStop = i; } else if (keyFrames[i].node->actionFlag == 1) closed = false; } if (closed) keyFrames[0].distFromPrev = sqrt(pow(keyFrames[0].node->x - keyFrames.back().node->x, 2) + pow(keyFrames[0].node->y - keyFrames.back().node->y, 2) + pow(keyFrames[0].node->z - keyFrames.back().node->z, 2)); // at stopping keyframes, we define distSinceStop == 0, // and distUntilStop is to the next stopping keyframe. // this is required to properly handle cases of two stopping frames in a row (yes they do exist) float tmpDist = 0.0f; for (size_t i = 0; i < keyFrames.size(); ++i) { int32 j = (i + lastStop) % keyFrames.size(); if (keyFrames[j].IsStopFrame()) tmpDist = 0.0f; else tmpDist += keyFrames[j].distFromPrev; keyFrames[j].distSinceStop = tmpDist; } tmpDist = 0.0f; for (int32 i = int32(keyFrames.size()) - 1; i >= 0; i--) { int32 j = (i + firstStop) % keyFrames.size(); tmpDist += keyFrames[(j + 1) % keyFrames.size()].distFromPrev; keyFrames[j].distUntilStop = tmpDist; if (keyFrames[j].IsStopFrame()) tmpDist = 0.0f; } for (size_t i = 0; i < keyFrames.size(); ++i) { /*if (keyFrames[i].distSinceStop < accel_dist) keyFrames[i].timeFrom = sqrt(2 * keyFrames[i].distSinceStop / accel); else //keyFrames[i].timeFrom = ((keyFrames[i].distSinceStop - (30 * 30 * 0.5f)) / 30) + 30; // t = (constant speed time) + (0.5 * time until full speed) keyFrames[i].timeFrom = (keyFrames[i].distSinceStop / speed) + (0.5f * speed / accel); */ float total_dist = keyFrames[i].distSinceStop + keyFrames[i].distUntilStop; if (total_dist < 2 * accel_dist) // won't reach full speed { if (keyFrames[i].distSinceStop < keyFrames[i].distUntilStop) // is still accelerating { // calculate accel+brake time for this short segment float segment_time = 2.0f * sqrt((keyFrames[i].distUntilStop + keyFrames[i].distSinceStop) / accel); // substract acceleration time keyFrames[i].timeTo = segment_time - sqrt(2 * keyFrames[i].distSinceStop / accel); } else // slowing down keyFrames[i].timeTo = sqrt(2 * keyFrames[i].distUntilStop / accel); } else if (keyFrames[i].distSinceStop < accel_dist) // still accelerating (but will reach full speed) { // calculate accel + cruise + brake time for this long segment float segment_time = (keyFrames[i].distUntilStop + keyFrames[i].distSinceStop) / speed + (speed / accel); // substract acceleration time keyFrames[i].timeTo = segment_time - sqrt(2 * keyFrames[i].distSinceStop / accel); } else if (keyFrames[i].distUntilStop < accel_dist) // already slowing down (but reached full speed) keyFrames[i].timeTo = sqrt(2 * keyFrames[i].distUntilStop / accel); else // at full speed keyFrames[i].timeTo = (keyFrames[i].distUntilStop / speed) + (0.5f * speed / accel); } // calculate tFrom times from tTo times float segmentTime = 0.0f; for (size_t i = 0; i < keyFrames.size(); ++i) { int32 j = (i + lastStop) % keyFrames.size(); if (keyFrames[j].IsStopFrame()) segmentTime = keyFrames[j].timeTo; keyFrames[j].timeFrom = segmentTime - keyFrames[j].timeTo; } // calculate path times keyFrames[0].pathTime = 0; float curPathTime = 0.0f; if (keyFrames[0].IsStopFrame()) { curPathTime = float(keyFrames[0].node->delay); keyFrames[0].departureTime = uint32(curPathTime * IN_MILLISECONDS); } for (size_t i = 1; i < keyFrames.size(); ++i) { curPathTime += keyFrames[i-1].timeTo; if (keyFrames[i].IsStopFrame()) { keyFrames[i].pathTime = uint32(curPathTime * IN_MILLISECONDS); curPathTime += (float)keyFrames[i].node->delay; keyFrames[i].departureTime = uint32(curPathTime * IN_MILLISECONDS); } else { curPathTime -= keyFrames[i].timeTo; keyFrames[i].pathTime = uint32(curPathTime * IN_MILLISECONDS); keyFrames[i].departureTime = keyFrames[i].pathTime; } } //sLog->outString("sinceStop | untilStop | fromPrev | tFrom | tTo | stop | pathTime"); //for (int i = 0; i < keyFrames.size(); ++i) //{ // sLog->outString("%9.3f | %9.3f | %9.3f | %7.3f | %7.3f | %u | %u", // keyFrames[i].distSinceStop, keyFrames[i].distUntilStop, keyFrames[i].distFromPrev, keyFrames[i].timeFrom, keyFrames[i].timeTo, // keyFrames[i].IsStopFrame(), keyFrames[i].pathTime); //} transport->pathTime = keyFrames.back().departureTime; //if (keyFrames.back().IsStopFrame()) // transport->pathTime += keyFrames.back().node->delay * IN_MILLISECONDS; }
bool InitializeStructure::FiniteStateMachineAnalysis(char *buffer,size_t size,int separator,int codepage) { char *p=buffer; char *end=buffer+size; char *secStart=nullptr; char *keyStart=nullptr; char *valueStart=nullptr; auto anonymous=new IniSection(); auto currentSec=anonymous; enum _FSMState{ STAT_NONE=0, STAT_SECTION, STAT_KEY, STAT_VALUE, STAT_COMMENT }state=STAT_NONE; for(;p<end;p++) { switch(state) { case STAT_NONE: { if(*p==L'[') { state=STAT_SECTION; secStart=p+1; }else if(*p=='#'||*p==';') { state=STAT_COMMENT; }else if(!isspace(*p)){ state=STAT_KEY; keyStart=p; } break; } case STAT_SECTION: { if(*p==']') { *p='\0'; std::string ke=keyStart; std::string va=valueStart; wcharget k(ke.c_str()); wcharget v(va.c_str()); Parameters pam(std::wstring(k.Get()),std::wstring(v.Get()),std::wstring(),0); currentSec->items.push_back(pam); state=STAT_NONE; } break; } case STAT_COMMENT: { if(*p=='\n') { state=STAT_NONE; break; } break; } case STAT_KEY: { if(*p==separator||*p=='\t') { *p='\0'; state=STAT_VALUE; valueStart=p+1; } break; } case STAT_VALUE: { if(*p=='\n'||*p=='\r') { *p='\0'; std::string ke=keyStart; std::string va=valueStart; wcharget k(ke.c_str()); wcharget v(va.c_str()); Parameters pam(std::wstring(k.Get()),std::wstring(v.Get()),std::wstring(),0); state=STAT_NONE; } break; } default: break; } } if(state==STAT_VALUE) { //// std::string ke=keyStart; std::string va=valueStart; wcharget k(ke.c_str()); wcharget v(va.c_str()); Parameters pam(std::wstring(k.Get()),std::wstring(v.Get()),std::wstring(),0); } return true; }
void then(T f) { caller_adaptor<T> x(f); caller *p = x.clone(); caller_keeper k(p); thenx(k); }
void setCellInt(numType x, numType y, long long int num) { key k(x,y); value val(std::to_string(num), dattype::INT); insertToCell(k ,val); }
/*! * \brief displays specified sensor parameters in the gui. * The sepecial gui elements are constructed dynamically. */ void StationInfoDialog::getSensorParameters() { if(OiFeatureState::getActiveFeature()->getStation()->sensorPad->instrument != NULL && OiFeatureState::getActiveFeature()->getStation()->sensorPad->instrument->getDoubleParameter() != NULL){ QMap<QString, double> doubleparam = *OiFeatureState::getActiveFeature()->getStation()->sensorPad->instrument->getDoubleParameter(); QMapIterator<QString, double> j(doubleparam); while(j.hasNext()){ j.next(); QLabel *l = new QLabel(); l->setText(j.key()); QLineEdit *le = new QLineEdit(); //le->setText(QString::number(j.value())); le->setText(QString::number(OiFeatureState::getActiveFeature()->getStation()->getInstrumentConfig()->doubleParameter.value(j.key()))); QHBoxLayout *layout = new QHBoxLayout(); layout->addWidget(l); layout->addWidget(le); layout->setStretch(0,1); layout->setStretch(1,1); masterSensorConfigLayout->addLayout(layout); doubleParameter.insert(j.key(),le); doubleParameterLabel.insert(j.key(),l); sensorConfigLayouts.insert(j.key(),layout); } } if(OiFeatureState::getActiveFeature()->getStation()->sensorPad->instrument != NULL && OiFeatureState::getActiveFeature()->getStation()->sensorPad->instrument->getIntegerParameter() != NULL){ QMap<QString, int> intParameter = *OiFeatureState::getActiveFeature()->getStation()->sensorPad->instrument->getIntegerParameter(); QMapIterator<QString, int> k(intParameter); while(k.hasNext()){ k.next(); QLabel *l = new QLabel(); l->setText(k.key()); QLineEdit *le = new QLineEdit(); //le->setText(QString::number(k.value())); le->setText(QString::number(OiFeatureState::getActiveFeature()->getStation()->getInstrumentConfig()->integerParameter.value(k.key()))); QHBoxLayout *layout = new QHBoxLayout(); layout->addWidget(l); layout->addWidget(le); layout->setStretch(0,1); layout->setStretch(1,1); masterSensorConfigLayout->addLayout(layout); integerParameter.insert(k.key(),le); integerParameterLabel.insert(k.key(),l); sensorConfigLayouts.insert(k.key(),layout); } } if(OiFeatureState::getActiveFeature()->getStation()->sensorPad->instrument != NULL && OiFeatureState::getActiveFeature()->getStation()->sensorPad->instrument->getStringParameter() != NULL){ QMap<QString,QStringList> strParameter = *OiFeatureState::getActiveFeature()->getStation()->sensorPad->instrument->getStringParameter(); QMapIterator<QString,QStringList> m(strParameter); while(m.hasNext()){ m.next(); QLabel *l = new QLabel(); l->setText(m.key()); QComboBox *cb = new QComboBox(); for(int a=0;a< m.value().size();a++){ cb->addItem(m.value().at(a)); } cb->setCurrentIndex(cb->findText(OiFeatureState::getActiveFeature()->getStation()->getInstrumentConfig()->stringParameter.value(m.key()))); QHBoxLayout *layout = new QHBoxLayout(); layout->addWidget(l); layout->addWidget(cb); layout->setStretch(0,1); layout->setStretch(1,1); masterSensorConfigLayout->addLayout(layout); stringParameter.insert(m.key(),cb); stringParameterLabel.insert(m.key(),l); sensorConfigLayouts.insert(m.key(),layout); } } ui->tab_sensorConfig->setLayout(masterSensorConfigLayout); }