M1 & sr2k (M1 &m1, const T1 &t1, const T2 &t2, const M2 &m2, const M3 &m3) { return m1 = t1 * m1 + t2 * (prod (m2, trans (m3)) + prod (m3, trans (m2))); }
// Try LocalXyzPointer types with NULL pointers. void LocalPointerTest::TestLocalXyzPointerNull() { { IcuTestErrorCode errorCode(*this, "TestLocalXyzPointerNull/LocalUConverterSelectorPointer"); static const char *const encoding="ISO-8859-1"; LocalUConverterSelectorPointer null; LocalUConverterSelectorPointer sel( ucnvsel_open(&encoding, 1, NULL, UCNV_ROUNDTRIP_SET, errorCode)); sel.adoptInstead(NULL); } #if !UCONFIG_NO_FORMATTING { IcuTestErrorCode errorCode(*this, "TestLocalXyzPointerNull/LocalUCalendarPointer"); LocalUCalendarPointer null; LocalUCalendarPointer cal(ucal_open(NULL, 0, "root", UCAL_GREGORIAN, errorCode)); if(!errorCode.logDataIfFailureAndReset("ucal_open()")) { cal.adoptInstead(NULL); } } { IcuTestErrorCode errorCode(*this, "TestLocalXyzPointerNull/LocalUDateTimePatternGeneratorPointer"); LocalUDateTimePatternGeneratorPointer null; LocalUDateTimePatternGeneratorPointer patgen(udatpg_open("root", errorCode)); patgen.adoptInstead(NULL); } { IcuTestErrorCode errorCode(*this, "TestLocalXyzPointerNull/LocalUMessageFormatPointer"); UnicodeString hello=UNICODE_STRING_SIMPLE("Hello {0}!"); LocalUMessageFormatPointer null; LocalUMessageFormatPointer msg( umsg_open(hello.getBuffer(), hello.length(), "root", NULL, errorCode)); msg.adoptInstead(NULL); } #endif /* !UCONFIG_NO_FORMATTING */ #if !UCONFIG_NO_REGULAR_EXPRESSIONS { IcuTestErrorCode errorCode(*this, "TestLocalXyzPointerNull/LocalURegularExpressionPointer"); UnicodeString pattern=UNICODE_STRING_SIMPLE("abc|xy+z"); LocalURegularExpressionPointer null; LocalURegularExpressionPointer regex( uregex_open(pattern.getBuffer(), pattern.length(), 0, NULL, errorCode)); if(!errorCode.logDataIfFailureAndReset("urege_open()")) { regex.adoptInstead(NULL); } } #endif /* !UCONFIG_NO_REGULAR_EXPRESSIONS */ #if !UCONFIG_NO_TRANSLITERATION { IcuTestErrorCode errorCode(*this, "TestLocalXyzPointerNull/LocalUTransliteratorPointer"); UnicodeString id=UNICODE_STRING_SIMPLE("Grek-Latn"); LocalUTransliteratorPointer null; LocalUTransliteratorPointer trans( utrans_openU(id.getBuffer(), id.length(), UTRANS_FORWARD, NULL, 0, NULL, errorCode)); if(!errorCode.logDataIfFailureAndReset("utrans_openU()")) { trans.adoptInstead(NULL); } } #endif /* !UCONFIG_NO_TRANSLITERATION */ }
void QgsGrassNewMapset::setSelectedRegion() { // mRegionsPoints are in EPSG 4326 = LL WGS84 int index = 2 * mRegionsComboBox->currentIndex(); std::vector<QgsPoint> points; // corners ll lr ur ul points.push_back( QgsPoint( mRegionsPoints[index] ) ); points.push_back( QgsPoint( mRegionsPoints[index+1].x(), mRegionsPoints[index].y() ) ); points.push_back( QgsPoint( mRegionsPoints[index+1] ) ); points.push_back( QgsPoint( mRegionsPoints[index].x(), mRegionsPoints[index+1].y() ) ); // Convert to currently selected coordinate system // Warning: seems that crashes if source == dest if ( mProjectionSelector->selectedCrsId() != GEOCRS_ID ) { // Warning: QgsCoordinateReferenceSystem::EpsgCrsId is broken (using epsg_id) //QgsCoordinateReferenceSystem source ( 4326, QgsCoordinateReferenceSystem::EpsgCrsId ); QgsCoordinateReferenceSystem source = QgsCoordinateReferenceSystem::fromSrsId( GEOCRS_ID ); if ( !source.isValid() ) { QgsGrass::warning( tr( "Cannot create QgsCoordinateReferenceSystem" ) ); return; } QgsCoordinateReferenceSystem dest = QgsCoordinateReferenceSystem::fromSrsId( mProjectionSelector->selectedCrsId() ); if ( !dest.isValid() ) { QgsGrass::warning( tr( "Cannot create QgsCoordinateReferenceSystem" ) ); return; } QgsCoordinateTransform trans( source, dest ); bool ok = true; for ( int i = 0; i < 4; i++ ) { QgsDebugMsg( QString( "%1,%2->" ).arg( points[i].x() ).arg( points[i].y() ) ); try { points[i] = trans.transform( points[i] ); QgsDebugMsg( QString( "%1,%2" ).arg( points[i].x() ).arg( points[i].y() ) ); } catch ( QgsCsException &cse ) { Q_UNUSED( cse ); QgsDebugMsg( "Cannot transform point" ); ok = false; break; } } if ( !ok ) { QgsGrass::warning( tr( "Cannot reproject selected region." ) ); return; } } double n = -90.0, s = 90.0, e = -180.0, w = 180.0; if ( mCellHead.proj == PROJECTION_LL ) { n = points[2].y(); s = points[0].y(); e = points[1].x(); w = points[0].x(); if ( n > 90 ) n = 90; if ( s < -90 ) s = -90; #if 0 if ( e > 180 ) e = 180; if ( w < -180 ) w = 180; #endif } else { for ( int i = 0; i < 4; i++ ) { if ( i == 0 || points[i].y() > n ) n = points[i].y(); if ( i == 0 || points[i].y() < s ) s = points[i].y(); if ( i == 0 || points[i].x() > e ) e = points[i].x(); if ( i == 0 || points[i].x() < w ) w = points[i].x(); } } mNorthLineEdit->setText( QString::number( n ) ); mSouthLineEdit->setText( QString::number( s ) ); mEastLineEdit->setText( QString::number( e ) ); mWestLineEdit->setText( QString::number( w ) ); mRegionModified = true; checkRegion(); drawRegion(); }
CSparseCholeskyInternal::CSparseCholeskyInternal(const CRSSparsity& sparsity, int nrhs) : LinearSolverInternal(sparsity,nrhs){ L_ = 0; S_ = 0; casadi_assert_message(sparsity==trans(sparsity),"CSparseCholeskyInternal: supplied sparsity must be symmetric, got " << sparsity.dimString() << "."); }
//********************************************************************** void IsotropicPlaneStressWrinkling::CalculateCauchyStresses( Vector& Cauchy_StressVector, const Matrix& F, const Vector& PK2_StressVector, const Vector& GreenLagrangeStrainVector) { //compute effective thickness variation Vector EffectiveStrain = GreenLagrangeStrainVector; Matrix Feff(2,2); if (MathUtils<double>::Norm3(mEw) != 0) { EffectiveStrain += mEw; //double emin=0.00; double emax=0.00; Vector vmin; Vector vmax; Matrix Finv(2,2); double Fdet; MathUtils<double>::InvertMatrix2(F,Finv,Fdet); Matrix wwt(2,2); Matrix Ewrink(2,2); Ewrink(0,0) = mEw[0]; Ewrink(0,1) = mEw[2]*0.5; Ewrink(1,0) = mEw[2]*0.5; Ewrink(1,1) = mEw[1]; noalias(wwt) = prod( Ewrink, trans(Finv) ); wwt = prod(Finv, wwt); std::cout << "oribbbbbbbbbile" << std::endl; // noalias(wwt) = prod( Finv, prod( Ewrink, trans(Finv) ) ); std::cout << "efficiency" << std::endl; // noalias(wwt) = prod( Finv, prod<Matrix>(Ewrink,trans(Finv)) ); // Matrix::MatMulAndAdd_B_D_Btrans(wwt,Finv,Ewrink); double alpha = fabs(wwt(0,0) + wwt(1,1)); wwt /= alpha; double beta = -1.00 + sqrt(2*alpha+1.00); noalias(Feff) = prod(wwt,F); //Matrix::MatMul(Feff,wwt,F); Feff *= beta; Feff += F; } else { Feff = F; } double epsz = ((mNU)/(1-mNU))*(EffectiveStrain[0] + EffectiveStrain[1]); double h_h0_ratio = sqrt(1-2.00*epsz); double DetF = MathUtils<double>::Det2(Feff); Matrix S(2,2); S(0,0) = PK2_StressVector[0]; S(0,1) = PK2_StressVector[2]; S(1,0) = PK2_StressVector[2]; S(1,1) = PK2_StressVector[1]; Matrix s(2,2); noalias(s) = prod(Feff, Matrix(prod(S, trans(Feff)) ) ); std::cout << "efficienza!!" << std::endl; // noalias(s) = prod(Feff, prod<Matrix>(S, trans(Feff) ) ); // Matrix::MatMulAndAdd_B_D_Btrans(s,Feff,S); //s = F*S*Ftrans Cauchy_StressVector[0] = s(0,0); Cauchy_StressVector[1] = s(1,1); Cauchy_StressVector[2] = s(0,1); Cauchy_StressVector /= DetF * h_h0_ratio; }
// Accumulate from L_AB_t auto sboxi = source_tree.box_begin(L_max - L); for (auto&& L_AB : local[tbox]) { source_box_type sbox = *sboxi; ++sboxi; const point_type& s_center = sbox.center(); target_box_type pbox = sbox.parent(); const point_type& p_center = pbox.center(); int p_idx = pbox.index() - source_tree.box_begin(pbox.level())->index(); // Multiply lhs_j += LgM_ij L_AB_i lhs.fill(0); prod(trans(LgM), L_AB, lhs); // Precompute phase * L_AB TODO: can reuse L_AB? auto li = std::begin(lhs); auto ci = std::begin(c_cheb); for (auto&& L_AcBp_i : local[cbox][p_idx]) { L_AcBp_i += *li * unit_polar(_M_ * (K.phase(*ci, s_center) - K.phase(*ci, p_center))); ++li; ++ci; } } } };
double diff(const vec& x, const mat& A, const vec& b) { return diff(trans(A), x, b); }
void Animate() { //Show FPS //showFpsCounter(); if(bAnim == true) { static OSG::Real64 t0 = OSG::getSystemTime(); OSG::Real64 t = OSG::getSystemTime() - t0; OSG::Real32 rot0 = t * 0.25; if(rot0 > 360.0) rot0 -= 360.0; OSG::Real32 rota = t * 0.5; if(rota > 360.0) rota -= 360.0; OSG::Real32 rotb = t * 1.0; if(rotb > 360.0) rotb -= 360.0; OSG::Real32 rotc = t * 1.5; if(rotc > 360.0) rotc -= 360.0; OSG::Real32 rotd = t * 2.0; if(rotd > 360.0) rotd -= 360.0; // _light2_trans->editMatrix().setTranslate(-100.0*sin(rota),-100.0*cos(rota), 250.0); //animate Trees OSG::Quaternion q; q.setValueAsAxisRad(1, 1, 1, 0.5 * sin(rota)); _tree1_trans->editMatrix().setRotate(q); _tree1_trans->editMatrix().setScale(OSG::Vec3f(12.0, 12.0, 10.0)); q.setIdentity(); q.setValueAsAxisRad(1, 1, 1, 0.5 * sin(rotc)); _tree2_trans->editMatrix().setRotate(q); _tree2_trans->editMatrix().setScale(OSG::Vec3f(12.0, 12.0, 10.0)); q.setIdentity(); q.setValueAsAxisRad(1, 1, 1, 0.5 * sin(rotb)); _tree3_trans->editMatrix().setRotate(q); _tree3_trans->editMatrix().setScale(OSG::Vec3f(12.0, 12.0, 10.0)); q.setIdentity(); q.setValueAsAxisRad(1, 1, 1, 0.5 * sin(rotb)); _tree4_trans->editMatrix().setRotate(q); _tree4_trans->editMatrix().setScale(OSG::Vec3f(12.0, 12.0, 10.0)); q.setIdentity(); q.setValueAsAxisRad(1, 1, 1, 0.5 * sin(rotc)); _tree5_trans->editMatrix().setRotate(q); _tree5_trans->editMatrix().setScale(OSG::Vec3f(12.0, 12.0, 10.0)); q.setIdentity(); q.setValueAsAxisRad(1, 1, 1, 0.5 * sin(rotb)); _tree6_trans->editMatrix().setRotate(q); _tree6_trans->editMatrix().setScale(OSG::Vec3f(12.0, 12.0, 10.0)); q.setIdentity(); q.setValueAsAxisRad(1, 1, 1, 0.5 * sin(rotd)); _tree7_trans->editMatrix().setRotate(q); _tree7_trans->editMatrix().setScale(OSG::Vec3f(12.0, 12.0, 10.0)); q.setIdentity(); q.setValueAsAxisRad(1, 1, 1, 0.5 * sin(rotb)); _tree8_trans->editMatrix().setRotate(q); _tree8_trans->editMatrix().setScale(OSG::Vec3f(12.0, 12.0, 10.0)); q.setIdentity(); q.setValueAsAxisRad(1, 1, 1, 0.5 * sin(rotc)); _tree9_trans->editMatrix().setRotate(q); _tree9_trans->editMatrix().setScale(OSG::Vec3f(12.0, 12.0, 10.0)); q.setIdentity(); { OSG::Matrix m; m.setIdentity(); OSG::Vec3f scale(0.15f,0.15f,0.15f); OSG::Vec3f trans(-40.0 * sin(rotb),-40.0 * cos(rotb), 50.0 + 25.0 * sin(rotd)); q.setValueAsAxisRad(0, 0, 1, -rotb); m.setTransform(trans, q, scale); _obj1_trans->setMatrix(m); } // { // _light2_trans->editMatrix().setTranslate(-40.0 * sin(rotb), -40.0 * // cos(rotb), // 50.0 + 25.0 * sin(rotd)); // } //animate Dinos { OSG::Matrix m; m.setIdentity(); OSG::Vec3f scale(5.0,5.0,5.0); OSG::Real32 ztrans1 = sin(2.0 * rotd); if(ztrans1 < 0) ztrans1 *= -1.0; OSG::Vec3f trans(-96.0 * cos(rot0),-96.0 * sin(rot0), 10.0 + 8.0 * ztrans1); m.setScale(OSG::Vec3f(5.0, 5.0, 5.0)); q.setValueAsAxisRad(0, 0, 1, rot0 - 170); m.setTransform(trans, q, scale); _dino1_trans->setMatrix(m); } { OSG::Matrix m; m.setIdentity(); OSG::Vec3f scale(3.0,3.0,3.0); OSG::Real32 ztrans1 = sin(2.5 * rotd); if(ztrans1 < 0) ztrans1 *= -1.0; OSG::Vec3f trans(-96.0 * cos((rot0 - 0.5)),-96.0 * sin((rot0 - 0.5)), 6.0 + 8.0 * ztrans1); m.setScale(OSG::Vec3f(5.0, 5.0, 5.0)); q.setValueAsAxisRad(0, 0, 1, rot0 - 169.9); m.setTransform(trans, q, scale); _dino2_trans->setMatrix(m); } { OSG::Matrix m; m.setIdentity(); OSG::Vec3f scale(3.0,3.0,3.0); OSG::Real32 ztrans1 = sin(3.0 * rotd); if(ztrans1 < 0) ztrans1 *= -1.0; OSG::Vec3f trans(-96.0 * cos((rot0 - 0.8)),-96.0 * sin((rot0 - 0.8)), 6.0 + 8.0 * ztrans1); m.setScale(OSG::Vec3f(5.0, 5.0, 5.0)); q.setValueAsAxisRad(0, 0, 1, rot0 - 170.1); m.setTransform(trans, q, scale); _dino3_trans->setMatrix(m); } { OSG::Matrix m; m.setIdentity(); OSG::Vec3f scale(3.0,3.0,3.0); OSG::Real32 ztrans1 = sin(2.75 * rotd); if(ztrans1 < 0) ztrans1 *= -1.0; OSG::Vec3f trans(-96.0 * cos((rot0 - 1.2)),-96.0 * sin((rot0 - 1.2)), 6.0 + 8.0 * ztrans1); m.setScale(OSG::Vec3f(5.0, 5.0, 5.0)); q.setValueAsAxisRad(0, 0, 1, rot0 - 170.1); m.setTransform(trans, q, scale); _dino4_trans->setMatrix(m); } } _navigator.idle(_mousebuttons, _lastx, _lasty); mgr->redraw(); }
bool BaseSurfaceOSystem::finishLoad() { BaseImage *image = new BaseImage(); if (!image->loadFile(_filename)) { delete image; return false; } _width = image->getSurface()->w; _height = image->getSurface()->h; bool isSaveGameGrayscale = scumm_strnicmp(_filename.c_str(), "savegame:", 9) == 0 && (_filename.c_str()[_filename.size() - 1] == 'g' || _filename.c_str()[_filename.size() - 1] == 'G'); if (isSaveGameGrayscale) { warning("grayscaleConversion not yet implemented"); // FIBITMAP *newImg = FreeImage_ConvertToGreyscale(img); TODO } // no alpha, set color key /* if (surface->format.bytesPerPixel != 4) SDL_SetColorKey(surf, SDL_TRUE, SDL_MapRGB(surf->format, ck_red, ck_green, ck_blue));*/ // convert 32-bit BMPs to 24-bit or they appear totally transparent (does any app actually write alpha in BMP properly?) // Well, actually, we don't convert via 24-bit as the color-key application overwrites the Alpha-channel anyhow. _surface->free(); delete _surface; bool needsColorKey = false; bool replaceAlpha = true; if (_filename.hasSuffix(".bmp") && image->getSurface()->format.bytesPerPixel == 4) { _surface = image->getSurface()->convertTo(g_system->getScreenFormat(), image->getPalette()); needsColorKey = true; replaceAlpha = false; } else if (image->getSurface()->format.bytesPerPixel == 1 && image->getPalette()) { _surface = image->getSurface()->convertTo(g_system->getScreenFormat(), image->getPalette()); needsColorKey = true; } else if (image->getSurface()->format.bytesPerPixel >= 3 && image->getSurface()->format != g_system->getScreenFormat()) { _surface = image->getSurface()->convertTo(g_system->getScreenFormat()); if (image->getSurface()->format.bytesPerPixel == 3) { needsColorKey = true; } } else { _surface = new Graphics::Surface(); _surface->copyFrom(*image->getSurface()); if (_surface->format.aBits() == 0) { needsColorKey = true; } } if (needsColorKey) { TransparentSurface trans(*_surface); trans.applyColorKey(_ckRed, _ckGreen, _ckBlue, replaceAlpha); } _hasAlpha = hasTransparency(_surface); _valid = true; _gameRef->addMem(_width * _height * 4); delete image; _loaded = true; return true; }
GMCube::GMCube(std::string aName) : mP0 (0,0), mSz (20000,20000), aFp ( aName.c_str(),ELISE_fp::READ), mX0 ( aFp.read_REAL8()), mY0 ( aFp.read_REAL8()), mZ0 ( aFp.read_REAL8()), mStepXY ( aFp.read_REAL8()), mStepZ ( aFp.read_REAL8()), mTx ( aFp.read_INT4()), mTy ( aFp.read_INT4()), mTz ( aFp.read_INT4()), mIZmin ( mTx, mTy), mIZmax ( mTx, mTy), mZoom (1.0), mW (Video_Win::WStd(Pt2di(mTx,mTy),mZoom)), mW2 (Video_Win::WStd(Pt2di(mTx,mTy),mZoom)), mW3 (Video_Win::WStd(Pt2di(200,100),mZoom)), mW4 (Video_Win::WStd(Pt2di(mTx,mTy),mZoom)), mDisp (mW2.disp()) { mSz = Inf(mSz,Pt2di(mTx,mTy)); INT aNbZ =0; long aDeb = aFp.tell(); INT aMaxZ =0; INT aVMax = -1000000; INT aVMin = 100000; for(INT y=0;y<mTy;++y) { for(INT x=0;x<mTx;++x) { INT2 zM = aFp.read_INT2(); INT2 aN = aFp.read_INT2(); mIZmin.data()[y][x] = zM; mIZmax.data()[y][x] = zM+aN; ElSetMax(aMaxZ ,(INT) aN); for (INT z=0 ; z<aN ; z++) { INT2 aVal = aFp.read_INT2(); ElSetMin(aVMin,aVal); ElSetMax(aVMax,aVal); } aNbZ += aN; } } cout << "NbZ = " << aNbZ << " " << mStepZ << "\n"; pSCA = cInterfaceCoxAlgo::StdNewOne ( mSz, trans(mIZmin.in(),mP0), trans(mIZmax.in(),mP0), 2, true ); cout << "AAAAAAAAAAAAa\n"; aFp.seek_begin(aDeb); Im2D_INT2 zCor(mTx,mTy); Im2D_U_INT1 CorMax(mTx,mTy); for(INT y=0;y<mTy;++y) { for(INT x=0;x<mTx;++x) { INT2 z1 = aFp.read_INT2(); INT2 z2 = z1+aFp.read_INT2(); INT cMax = -100000; INT zMax = z1; bool OkP2 = (x>=mP0.x) && (x<mP0.x+mSz.x) && (y>=mP0.y) && (y<mP0.y+mSz.y); for (INT z=z1 ; z<z2 ; z++) { INT2 aVal = aFp.read_INT2(); if (aVal > cMax) { cMax = aVal; zMax = z; } aVal = round_ni((aVMax-aVal)/(aVMax/100.0)); if (OkP2) pSCA->SetCost(Pt3di(x-mP0.x,y-mP0.y,z),aVal); } zCor.data()[y][x] = zMax; CorMax.data()[y][x] = (INT)(255 * (1.0-cMax/900.0)); } } cout << "VALS = [" << aVMin << " , " << aVMax << "]\n"; ELISE_COPY(zCor.all_pts(),CorMax.in(),mW.ogray()); ELISE_COPY(zCor.all_pts(),zCor.in(),mW2.ogray()); }
hObj hb(const rowvec &eta, const rowvec &data, const mat &iS, const rowvec &mu0, const rowvec &mu1, const rowvec &mu2, const rowvec &lambda0, const rowvec &lambda1, const rowvec &lambda2, const rowvec &beta0, const rowvec &beta1, const rowvec &beta2, const rowvec &gamma, const rowvec &gamma2, int fast=0) { unsigned ny=mu0.n_elem+mu1.n_elem+mu2.n_elem; int k=3+ny; colvec h(k); unsigned pos=2; unsigned dpos = 0; // cerr << "mu0" << endl; for (unsigned i=0; i<mu0.n_elem; i++) { pos++; // cerr << data(dpos) << "; "; h(pos) = data(dpos)-mu0(i)-lambda0(i)*eta(0); dpos++; } // cerr << "mu1" << endl; for (unsigned i=0; i<mu1.n_elem; i++) { pos++; // cerr << data(dpos) << "; "; h(pos) = data(dpos)-mu1(i)-lambda1(i)*eta(1); dpos++; } // cerr << "mu2" << endl; for (unsigned i=0; i<mu2.n_elem; i++) { pos++; // cerr << data(dpos) << "; "; h(pos) = data(dpos)-mu2(i)-lambda2(i)*eta(2); dpos++; } double zeta2 = eta(2)-gamma(0)*eta(0)-gamma(1)*eta(0)*eta(0); double zeta1 = eta(1)-gamma2(0)*eta(0)-gamma2(1)*eta(0)*eta(0); double zeta0 = eta(0); // cerr << "dpos=" << dpos << endl; // cerr << "mu0=" << mu0 << endl; // cerr << "mu1=" << mu1 << endl; // cerr << "mu2=" << mu2 << endl; // cerr << "beta" << endl; for (unsigned i=0; i<beta0.n_elem; i++) { // cerr << data(dpos) << "; "; zeta0 -= beta0(i)*data(dpos); dpos++; } for (unsigned i=0; i<beta1.n_elem; i++) { zeta1 -= beta1(i)*data(dpos); dpos++; } for (unsigned i=0; i<beta2.n_elem; i++) { zeta2 -= beta2(i)*data(dpos); dpos++; } h(0) = zeta0; h(1) = zeta1; h(2) = zeta2; mat iSh = iS*h; hObj res; res.h = h; res.hSh = -0.5*as_scalar(trans(h)*iSh); if (fast==1) return(res); mat D = zeros(k,3); D(0,0) = 1; D(1,0) = -gamma2(0)-2*gamma2(1)*eta(0); D(2,0) = -gamma(0)-2*gamma(1)*eta(0); D(1,1) = 1; D(2,2) = 1; // D[1,1] = 1; D[2,2] = 1; pos = 3; for (unsigned i=0; i<mu0.n_elem; i++) { D(pos,0) = -lambda0(i); pos++; } for (unsigned i=0; i<mu1.n_elem; i++) { D(pos,1) = -lambda1(i); pos++; } for (unsigned i=0; i<mu2.n_elem; i++) { D(pos,2) = -lambda2(i); pos++; } // cerr << "D=\n" << D << endl; mat dS = -trans(D)*iS; res.grad = dS*h; res.hess = dS*D; //mat dummy = trans(iSh)*d2eta0; //res.hess(0,0) -= dummy[0]; res.hess(0,0) -= -2*gamma(1)*iSh(2) - 2*gamma2(1)*iSh(1); return(res); }
void RecordedCamera::moveCamera_mouse(int x, int y) { Quat newQuat; const unsigned int widthViewport = p_widthViewport.getValue(); const unsigned int heightViewport = p_heightViewport.getValue(); if (isMoving) { if (currentMode == TRACKBALL_MODE) { float x1 = (2.0f * widthViewport / 2.0f - widthViewport) / widthViewport; float y1 = (heightViewport- 2.0f *heightViewport / 2.0f) /heightViewport; float x2 = (2.0f * (x + (-lastMousePosX + widthViewport / 2.0f)) - widthViewport) / widthViewport; float y2 = (heightViewport- 2.0f * (y + (-lastMousePosY +heightViewport / 2.0f))) /heightViewport; currentTrackball.ComputeQuaternion(x1, y1, x2, y2); //fetch rotation newQuat = currentTrackball.GetQuaternion(); Vec3 pivot; switch (p_pivot.getValue()) { case WORLD_CENTER_PIVOT: pivot = Vec3(0.0, 0.0, 0.0); break; case SCENE_CENTER_PIVOT : default: pivot = sceneCenter; break; } BaseCamera::rotateWorldAroundPoint(newQuat, pivot, this->getOrientation()); } else if (currentMode == ZOOM_MODE) { Vec3 trans(0.0, 0.0, -p_zoomSpeed.getValue() * (y - lastMousePosY) / heightViewport); trans = cameraToWorldTransform(trans); translate(trans); translateLookAt(trans); } else if (currentMode == PAN_MODE) { Vec3 trans(lastMousePosX - x, y-lastMousePosY, 0.0); trans = cameraToWorldTransform(trans)*p_panSpeed.getValue(); translate(trans); translateLookAt(trans); } //must call update afterwards lastMousePosX = x; lastMousePosY = y; } else if (currentMode == WHEEL_ZOOM_MODE) { Vec3 trans(0.0, 0.0, -p_zoomSpeed.getValue() * (y*0.5) / heightViewport); trans = cameraToWorldTransform(trans); translate((trans)); translateLookAt(trans); currentMode = NONE_MODE; } computeZ(); }
bool collisionBoundingBox(Ball &ball, bool debugVisual, Peg &peg) { GLfloat collisionDist = INFINITY; GLfloat cornerDist; int cornerIndex = -1; Point2f *vertices = new Point2f[5]; vertices[0].setXY(peg.radius + peg.position._x, peg.radius + peg.position._y); vertices[1].setXY(peg.radius + peg.position._x, -peg.radius + peg.position._y); vertices[2].setXY(-peg.radius + peg.position._x, -peg.radius + peg.position._y); vertices[3].setXY(-peg.radius + peg.position._x, peg.radius + peg.position._y); vertices[4].setXY(peg.radius + peg.position._x, peg.radius + peg.position._y); Point2f * orthogVecs = new Point2f[4]; orthogVecs[0].setXY(1.0, 0.0); orthogVecs[0].setXY(0.0, -1.0); orthogVecs[0].setXY(-1.0, 0.0); orthogVecs[0].setXY(0.0, 1.0); //Vector parallel to hit box edge remainder; Point2f hitRemaidner; //Component orthogonal to hit box edge GLfloat orthogDist; //Component paraell to hit box edge GLfloat hitRemainderDist; //Caluclate the ball's position in transformed co-ordinates Point2f orig(ball.position._x - peg.position._x, ball.position._y - peg.position._y); Point2f trans(cosf(peg.rotation) * orig._x + sinf(peg.rotation) * orig._y, -sin(peg.rotation) * orig._x + cosf(peg.rotation) * orig._y); for(int i = 0; i < 4; i++) { orthogDist = dotProduct(orthogVecs[i], trans); hitRemaidner._x = trans._x - orthogDist * orthogVecs[i]._x; hitRemaidner._y = trans._y - orthogDist * orthogVecs[i]._y; hitRemainderDist = hitRemaidner.magnitude(); //std::cout << "hitRemainderDist : "<< hitRemainderDist << std::endl; //std::cout << "peg.Radius : "<< peg.radius << std::endl; if(orthogDist >= 0.0 && hitRemainderDist <= peg.radius) { glColor3f(1.0f, 0.0f, 0.0f); collisionDist = orthogDist - (peg.radius + ball.radius); } else { glColor3f(1.0f, 1.0f, 1.0f); } if(debugVisual) { glBegin(GL_LINES); glVertex2f(vertices[i]._x, vertices[i]._y); glVertex2f(vertices[i+1]._x, vertices[i+1]._y); glEnd(); } } /*check Corners */ if(collisionDist == INFINITY) { for(int i = 0; i < 4; i++) { cornerDist = sqrt((trans._x - vertices[i]._x) * (trans._x - vertices[i]._x) + (trans._y - vertices[i]._y) * (trans._y - vertices[i]._y)) - ball.radius; if(cornerDist < collisionDist) { cornerIndex = i; collisionDist = cornerDist; } } if(debugVisual) { glColor3f(1.0f, 0.0f, 0.0f); glPointSize(3); glBegin(GL_POINTS); glVertex2f(vertices[cornerIndex]._x, vertices[cornerIndex]._y); glEnd(); } } // std::cout << "collisionDist : "<< collisionDist << std::endl; if(collisionDist > 0.0) return false; else return true; }
double H1_error(const space_ptrtype & Xh, const element_type & T, const double & values) const { // replace params by specified values ex solution = getSolution(values); auto gradg = expr<1,Dim,2>(grad(solution,vars), vars ); auto mesh = Xh->mesh(); double L2error = L2_error(Xh, T, values); double H1seminorm = math::sqrt( integrate( elements(mesh), Px()*(gradv(T) - gradg)*trans(gradv(T) - gradg) ).evaluate()(0,0) ); return math::sqrt( L2error*L2error + H1seminorm*H1seminorm); }
DEM read_dem () { int c; DEM f, a, b, d, x; int i; char buf[200]; DEM s; DEM d1; int flags1; DEM used1; extern DEM used; loop: do c = readchar (); while (c==' ' || c=='\t' || c=='\n' || c==0); switch (c) { case 'I': return I; case 'K': return K; case 'S': return S; case 'E': return E; case 'F': return If; case 'O': return Ord; case '-': f = read_dem (); a = read_dem (); return ap (f, a); case '/': a = read_dem (); b = read_dem (); return transym (a, b); case 'T': a = read_dem (); b = read_dem (); return trans (a, b); case 'X': a = read_dem (); return sym (a); case '#': a = read_dem (); b = read_dem (); return Axm (a, b); case 'i': a = read_dem (); return defI (a); case 'k': a = read_dem (); b = read_dem (); return defK (a, b); case 's': a = read_dem (); b = read_dem (); d = read_dem (); return defS (a, b, d); case ')': a = read_dem (); b = read_dem (); return IfNode (a, b); case '1': return Ext1; case '2': return Ext2; case '3': return Ext3; case '4': return Ext4; case '5': return Ext5; case '6': return Ext6; case 'e': return AE; case 'f': return EA0; /* a = read_dem (); return EA (a); */ case 'm': return MP; case 'a': return AI; case 'b': return AK; case 'c': return AS; case 'r': return RPA; case '0': return ZeroIsOrd; case '+': return SucIsOrd; case 'w': return LimIsOrd; case 'p': return PredIsOrd; case 'n': return StepIsOrd; case 'W': return TfI; case '<': a = read_dem (); return left (a); case '>': a = read_dem (); return right (a); case '\'': a = read_dem (); return rep(a); case '%': /*printf ("*1*");*/ a = read_dem (); /*printf ("*2*");*/ trace_dem ("read", a); /*printf ("*3*");*/ b = red (a); /*printf ("*4*");*/ trace_dem ("red", b); return b; /* return red (a); */ case 'R': a = read_dem (); return red1 (a, 0); case '@': a = read_dem (); return reduc (a, 1); case '~': a = read_dem (); return reduc (a, 0); case '$': a = read_dem (); return redu (a); case 'x': a = read_dem (); b = read_dem (); return ext (a, b); case '\\': a = read_dem (); b = read_dem (); trace_dem ("^(0)", a); trace_dem ("^(1)", b); d = exten (a, b); trace_dem ("^(r)", d); return d; case ']': a = read_dem (); b = read_dem (); d = dbextens (a, b); return d; case 'l': a = read_dem (); b = read_dem (); return Ext (a, b); /* return Lambda (a, b); */ case 'L': a = read_dem (); b = read_dem (); return Lambda (a, b); case '.': a = read_dem (); return DBLambda (a); case '!': a = read_dem (); b = read_dem (); return DB_lambda (a, b); /* return DBLambda (DBname (0, a, b)); */ case '?': a = read_dem (); b = read_dem (); return DB_Subst (a, b); case '_': a = read_dem (); b = read_dem (); d = read_dem (); return Subst (a, b, d); case ':': a = read_dem (); b = read_dem (); d = read_dem (); return ap (exten(a,d) ,b); case 'V': x = read_dem (); d = read_dem (); a = mk_dem (node(d), 0, NULL, DB_lambda (x, subdem(0,d)), DB_lambda (x, subdem(1,d)), subdem(2,d) == NULL ? NULL : DB_lambda (x, subdem(2,d)), NULL, NULL, NULL); return a; case 'A': x = read_dem (); d = read_dem (); a = mk_dem (node(d), 0, NULL, ap (x, subdem(0,d)), ap (x, subdem(1,d)), subdem(2,d) == NULL ? NULL : ap (x, subdem(2,d)), NULL, NULL, NULL); return a; case '"': a = read_dem (); /* return NoRed (a); */ no_red[nnr++] = a; return a; case '|': a = read_dem (); no_red[nnr++] = a; b = read_dem (); return b; case 'u': used1 = used; used = read_dem (); a = read_dem (); used = used1; return a; case '(': flags1 = flags; i = 0; for (;;) { c = readchar (); if (c == ')') break; buf[i++] = c; } buf[i] = 0; sscanf (buf, "%x", &flags); a = read_dem (); if ((flags & FLAG_PERM) == 0) flags = flags1; return a; case ',': a = read_dem (); return step (a); case '*': a = read_dem (); return rstep (a); case '`': a = read_dem (); return list_ap (a, nil); case '&': c = readchar (); switch (c) { case '/': return itransym; case 'i': return idefI; case 'k': return idefK; case 's': return idefS; case '<': return ileft; case '>': return iright; case '=': return ieq; case '#': return inode; case '0': return isubdem0; case '1': return isubdem1; case '2': return isubdem2; case '%': return ired; case '$': return iredu; case '\\': return iext; case ',': return istep; case '*': return irstep; default: fprintf (stderr, "Undefined &%c.\n", c); return I; } break; case '[': /* trace_dem ("read symbol", I); */ for (i=0; i<sizeof(buf); i++) { c = readchar(); if (c == ']') { buf[i] = 0; #ifdef TRACE1 printf ("buf=<%s>\n", buf); #endif if (buf[0] >= '0' && buf[0] <= '9') { #ifdef TRACE printf ("\nDBVar <%s>", buf); #endif d1 = DBVar (atoi(buf)); trace_dem ("", d); return d1; } s = Sym(buf); #ifdef TRACE1 trace_dem ("read symbol", s); #endif if (subdem(0,s) == NULL) { #ifdef TRACE1 trace_dem ("return symbol", s); #endif return s; } else { #ifdef TRACE trace_dem ("return value of", s); #endif return subdem(0,s); } } buf[i] = c; } fprintf (stderr, "Symbol too long\n"); return Sym(buf); default: return defined_dems[(unsigned char)c]; /* printf ("Illegal character 0x%02X\n", c); goto loop; */ } }
/////////////// // FUNCTIONS // /////////////// void interpret(CREATURE *crit, char *buf) { CREATURE *xcrit=0; OBJECT *obj=0; SOCIAL *social=0; EXIT *exit=0; ROOM *room=0; char command[MAX_BUFFER]; char temp[MAX_BUFFER]; char *pbuf = command; char **arguments; char **editargs; long i = 0, x = 0; long string = 0; bool found = 0; bool command_ok = 0; bool social_ok = 0; strcpy(temp,buf); while( isspace(*buf) ) buf++; // check for one character commands without spaces to // seperate arguments. - i.e. chat yo = .yo | pip if(ispunct(*buf)) *pbuf++ = *buf++; else { while( !isspace(*buf) && *buf != '\0' ) *pbuf++ = *buf++; } *pbuf = '\0'; while( isspace(*buf) ) buf++; // moved exits before other commands - pip. // insert full exit name for abbreviated one. for( i = 0; directions[i].abbr; i++) { if (directions[i].abbr[0] != '\0' && !strcasecmp(command,directions[i].abbr)) { sprintf(command,"%s",directions[i].name); break; } } if(!IsDisabled(crit)) { for(exit = crit->in_room->exits; exit; exit = exit->next ) { if( !strindex(exit->name, command) ) { if((room = hashfind_room(exit->to_vnum)) == 0) { sendcrit(crit,"That exit enters into a domain far too powerful for you to handle."); mudlog("exit(%s) in room(%s:%d) has bad to_vnum(%d)!", exit->name, crit->in_room->name, crit->in_room->vnum, exit->to_vnum); continue; } if (exit->door >= DOOR_CLOSED && !IsImmortal(crit)) { sendcritf(crit,"The %s door is closed.",exit->name); return; } if (crit->rider) { sendcritf(crit,"You can't move on your own until %s dismounts you.",crit->rider->name); return; } // adding mounts! if (crit->mount) message("$n ride$x $p on $N.",crit,crit->mount,exit->name); else message("$n leave$x $p.",crit,0,exit->name); trans(crit,room); if (crit->mount) { trans(crit->mount,crit); message("$n arrive$x riding $N.",crit,crit->mount,crit->in_room); } message("$n $v arrived.",crit,crit->in_room,0); interpret(crit,"look"); return; } } } // check if they in editor and get a successful return (edited something) // otherwise let them use normal commands if(IsEditing(crit)) { if(crit->socket->string) { if(!(string = string_editor(crit,temp))) return; str_dup(&(*crit->socket->variable), crit->socket->string); DeleteObject(crit->socket->string) return; } else temp[0] = '\0'; if(!ValidString(command)) strcat(temp,""); else sprintf(temp,"%s %s",command,buf); editargs = make_arguments(temp); if(editor(crit,editargs)) { free_arguments(editargs); return; } free_arguments(editargs); }
const std::string ForumTemplateViewThreadPage::GenerateContent(const std::string &method, const std::map<std::string,QueryVar> &queryvars) { int postcount=0; std::string fproxyprotocol(""); std::string fproxyhost(""); std::string fproxyport(""); std::string maincontent(""); std::string result(""); std::map<std::string,std::string> vars; std::vector<std::pair<std::string,std::string> > breadcrumblinks; std::string threadidstr(""); std::string boardidstr(""); std::string pagestr(""); std::string boardname(""); std::string firstunreadidstr(""); std::string threadpostrowodd(""); std::string threadpostroweven(""); std::string postrows(""); std::string threadpostattachment(""); std::string postattachments(""); std::string trusttable(""); bool showsignatures=false; bool showavatars=false; SQLite3DB::Transaction trans(m_db); Option opt(m_db); std::vector<std::string> skipspace; SQLite3DB::Statement fileattachmentst=m_db->Prepare("SELECT Key, Size FROM tblMessageFileAttachment WHERE MessageID=?;"); SQLite3DB::Statement truststpeeronly=m_db->Prepare("SELECT PeerMessageTrust, PeerTrustListTrust FROM tblIdentity WHERE IdentityID=?;"); SQLite3DB::Statement truststboth=m_db->Prepare("SELECT tblIdentityTrust.LocalMessageTrust, tblIdentity.PeerMessageTrust, tblIdentityTrust.LocalTrustListTrust, tblIdentity.PeerTrustListTrust FROM tblIdentity LEFT JOIN tblIdentityTrust ON tblIdentity.IdentityID=tblIdentityTrust.IdentityID WHERE tblIdentity.IdentityID=? AND tblIdentityTrust.LocalIdentityID=?;"); opt.GetBool("ForumShowSignatures",showsignatures); opt.GetBool("ForumShowAvatars",showavatars); opt.Get("FProxyProtocol",fproxyprotocol); opt.Get("FProxyHost",fproxyhost); opt.Get("FProxyPort",fproxyport); skipspace.push_back(" "); if(queryvars.find("messageuuid")!=queryvars.end()) { SQLite3DB::Statement st=m_db->Prepare("SELECT tblMessage.MessageID, tblThreadPost.ThreadID, tblThread.BoardID FROM tblMessage LEFT JOIN tblThreadPost ON tblMessage.MessageID=tblThreadPost.MessageID LEFT JOIN tblThread ON tblThreadPost.ThreadID=tblThread.ThreadID WHERE MessageUUID=?;"); st.Bind(0,(*queryvars.find("messageuuid")).second.GetData()); st.Step(); if(st.RowReturned()) { int messageid=0; int threadid=0; int boardid=0; st.ResultInt(2,boardid); m_viewstate.SetBoardID(boardid); if(st.ResultNull(1)==false) { st.ResultInt(1,threadid); m_viewstate.SetThreadID(threadid); } else { m_viewstate.SetThreadID(0); } } st.Finalize(); } if(queryvars.find("threadid")!=queryvars.end()) { int temp=0; threadidstr=(*queryvars.find("threadid")).second.GetData(); StringFunctions::Convert(threadidstr,temp); m_viewstate.SetThreadID(temp); } else { int temp=0; temp=m_viewstate.GetThreadID(); StringFunctions::Convert(temp,threadidstr); } if(queryvars.find("page")!=queryvars.end()) { pagestr=(*queryvars.find("page")).second.GetData(); int temp=0; if(StringFunctions::Convert(pagestr,temp)==true) { m_viewstate.SetPage(temp); } } else { int temp=0; temp=m_viewstate.GetPage(); StringFunctions::Convert(temp,pagestr); } if(queryvars.find("boardid")!=queryvars.end()) { boardidstr=(*queryvars.find("boardid")).second.GetData(); int temp=0; if(StringFunctions::Convert(boardidstr,temp)==true) { m_viewstate.SetBoardID(temp); } } else { int temp=0; temp=m_viewstate.GetBoardID(); StringFunctions::Convert(temp,boardidstr); } // first unread select must come before marking read messages SQLite3DB::Statement firstunreadst=m_db->Prepare("SELECT tblMessage.MessageID FROM tblThreadPost INNER JOIN tblMessage ON tblThreadPost.MessageID=tblMessage.MessageID WHERE ThreadID=? AND tblMessage.Read=0;"); firstunreadst.Bind(0,threadidstr); firstunreadst.Step(); if(firstunreadst.RowReturned()) { firstunreadst.ResultText(0,firstunreadidstr); } firstunreadst.Finalize(); trans.Begin(SQLite3DB::Transaction::TRANS_IMMEDIATE); if(queryvars.find("formaction")!=queryvars.end() && (*queryvars.find("formaction")).second=="markunread") { SQLite3DB::Statement updateread=m_db->Prepare("UPDATE tblMessage SET Read=0 WHERE tblMessage.MessageID IN (SELECT MessageID FROM tblThreadPost WHERE ThreadID=?);"); updateread.Bind(0,threadidstr); trans.Step(updateread); } else { SQLite3DB::Statement updateread=m_db->Prepare("UPDATE tblMessage SET Read=1 WHERE tblMessage.MessageID IN (SELECT MessageID FROM tblThreadPost WHERE ThreadID=?);"); updateread.Bind(0,threadidstr); trans.Step(updateread); } trans.Commit(); if(trans.IsSuccessful()==false) { m_log->error("ForumTemplateViewThreadPage::GenerateContent transaction failed SQL="+trans.GetErrorSQL()+" Error="+trans.GetLastErrorStr()); } // add/remove trust if(queryvars.find("formaction")!=queryvars.end() && (*queryvars.find("formaction")).second.GetData().find("trust")!=std::string::npos && queryvars.find("identityid")!=queryvars.end() && ValidateFormPassword(queryvars)) { trans.Begin(SQLite3DB::Transaction::TRANS_IMMEDIATE); SQLite3DB::Statement currenttrustst=m_db->Prepare("SELECT IFNULL(LocalMessageTrust,-1), IFNULL(LocalTrustListTrust,-1) FROM tblIdentityTrust WHERE IdentityID=? AND LocalIdentityID=?;"); SQLite3DB::Statement updatetrustst=m_db->Prepare("UPDATE tblIdentityTrust SET LocalMessageTrust=?, LocalTrustListTrust=? WHERE IdentityID=? AND LocalIdentityID=?;"); currenttrustst.Bind(0,(*queryvars.find("identityid")).second.GetData()); currenttrustst.Bind(1,m_viewstate.GetLocalIdentityID()); trans.Step(currenttrustst); if(currenttrustst.RowReturned()) { int localmessagetrust=-1; int localtrustlisttrust=-1; currenttrustst.ResultInt(0,localmessagetrust); currenttrustst.ResultInt(1,localtrustlisttrust); if((*queryvars.find("formaction")).second=="addmessagetrust") { if(localmessagetrust==-1) { localmessagetrust=50; } localmessagetrust=(std::min)(localmessagetrust+10,100); } else if((*queryvars.find("formaction")).second=="removemessagetrust") { if(localmessagetrust==-1) { localmessagetrust=50; } localmessagetrust=(std::max)(localmessagetrust-10,0); } else if((*queryvars.find("formaction")).second=="addtrustlisttrust") { if(localtrustlisttrust==-1) { localtrustlisttrust=50; } localtrustlisttrust=(std::min)(localtrustlisttrust+10,100); } else if((*queryvars.find("formaction")).second=="removetrustlisttrust") { if(localtrustlisttrust==-1) { localtrustlisttrust=50; } localtrustlisttrust=(std::max)(localtrustlisttrust-10,0); } if(localmessagetrust!=-1) { updatetrustst.Bind(0,localmessagetrust); } else { updatetrustst.Bind(0); } if(localtrustlisttrust!=-1) { updatetrustst.Bind(1,localtrustlisttrust); } else { updatetrustst.Bind(1); } updatetrustst.Bind(2,(*queryvars.find("identityid")).second.GetData()); updatetrustst.Bind(3,m_viewstate.GetLocalIdentityID()); trans.Step(updatetrustst); } trans.Finalize(currenttrustst); trans.Finalize(updatetrustst); trans.Commit(); if(trans.IsSuccessful()==false) { m_log->error("ForumTemplateViewThreadPage::GenerateContent transaction failed SQL="+trans.GetErrorSQL()+" Error="+trans.GetLastErrorStr()); } } SQLite3DB::Statement boardnamest=m_db->Prepare("SELECT tblBoard.BoardName FROM tblBoard INNER JOIN tblThread ON tblBoard.BoardID=tblThread.BoardID WHERE tblThread.ThreadID=?;"); boardnamest.Bind(0,threadidstr); boardnamest.Step(); if(boardnamest.RowReturned()) { boardnamest.ResultText(0,boardname); } boardnamest.Finalize(); breadcrumblinks.push_back(std::pair<std::string,std::string>("forummain.htm?viewstate="+m_viewstate.GetViewStateID(),SanitizeOutput(m_trans->Get("web.navlink.browseforums")))); breadcrumblinks.push_back(std::pair<std::string,std::string>("forumthreads.htm?viewstate="+m_viewstate.GetViewStateID()+"&boardid="+boardidstr+"&page="+pagestr,SanitizeOutput(boardname))); if(firstunreadidstr!="") { vars["FIRSTUNREADPOSTLINK"]="<a href=\"#"+firstunreadidstr+"\"><img src=\"images/mail_get.png\" border=\"0\" style=\"vertical-align:bottom;\">"+m_trans->Get("web.page.forumviewthread.firstunread")+"</a>"; } else { vars["FIRSTUNREADPOSTLINK"]=""; } m_templatehandler.GetSection("THREADPOSTATTACHMENT",threadpostattachment); m_templatehandler.GetSection("TRUSTTABLE",trusttable); vars["MARKUNREADLINK"]="<a href=\""+m_pagename+"?viewstate="+m_viewstate.GetViewStateID()+"&formaction=markunread&threadid="+threadidstr+"&boardid="+boardidstr+"&page="+pagestr+"\"><img src=\"images/mail_generic.png\" border=\"0\" style=\"vertical-align:bottom;\">"+m_trans->Get("web.page.forumviewthread.markunread")+"</a>"; // thread posts std::vector<std::string> ignoredsig; ignoredsig.push_back("THREADPOSTSIGNATUREDIV"); // don't replace this div when we get the section, we'll replace it later m_templatehandler.GetSection("THREADPOSTROWODD",threadpostrowodd,ignoredsig); m_templatehandler.GetSection("THREADPOSTROWEVEN",threadpostroweven,ignoredsig); trans.ClearError(); // only selects, deferred OK trans.Begin(); SQLite3DB::Statement st=m_db->Prepare("SELECT tblMessage.MessageID, tblMessage.IdentityID, tblMessage.FromName, tblMessage.Subject, tblMessage.MessageDate || ' ' || tblMessage.MessageTime, tblMessage.Body, tblIdentity.PublicKey || (SELECT OptionValue FROM tblOption WHERE Option='MessageBase') || '|' || tblMessage.InsertDate || '|Message-' || tblMessage.MessageIndex, tblMessage.MessageUUID, tblIdentity.Signature, tblIdentity.ShowSignature, tblIdentity.ShowAvatar, tblIdentity.FMSAvatar, tblIdentity.SoneAvatar FROM tblMessage INNER JOIN tblThreadPost ON tblMessage.MessageID=tblThreadPost.MessageID LEFT JOIN tblIdentity ON tblMessage.IdentityID=tblIdentity.IdentityID WHERE tblThreadPost.ThreadID=? ORDER BY tblThreadPost.PostOrder;"); st.Bind(0,threadidstr); trans.Step(st); while(st.RowReturned()) { std::map<std::string,std::string> postvars; std::string postrow(""); int messageid(0); std::string messageidstr=""; std::string identityidstr=""; std::string fromname=""; std::string subject=""; std::string datetime=""; std::string body=""; std::string postlink=""; std::string messageuuid=""; std::string signature=""; std::string showidsignature="0"; bool allowreply=true; bool showidavatar=false; std::string fmsavatar(""); std::string soneavatar(""); st.ResultInt(0,messageid); st.ResultText(0,messageidstr); st.ResultText(1,identityidstr); st.ResultText(2,fromname); st.ResultText(3,subject); st.ResultText(4,datetime); st.ResultText(5,body); st.ResultText(6,postlink); st.ResultText(7,messageuuid); st.ResultText(8,signature); st.ResultText(9,showidsignature); st.ResultBool(10,showidavatar); st.ResultText(11,fmsavatar); st.ResultText(12,soneavatar); if(postcount==0) { if(subject!="") { m_pagetitle+=" - "+SanitizeOutput(boardname,skipspace)+" - "+SanitizeOutput(subject,skipspace); } breadcrumblinks.push_back(std::pair<std::string,std::string>(m_pagename+"?viewstate="+m_viewstate.GetViewStateID()+"&threadid="+threadidstr+"&boardid="+boardidstr+"&page="+pagestr,SanitizeOutput(subject,skipspace))); } postvars["THREADPOSTANCHOR"]="<a name=\""+messageidstr+"\"></a><a name=\""+FixUUIDAnchor(messageuuid)+"\"></a>"; if(identityidstr=="") { postvars["CONDITIONALTRUSTTABLE"]=""; } else { int lmt=0; int pmt=0; std::string localmessagetrust(""); std::string localtrustlisttrust(""); std::string peermessagetrust(""); std::string peertrustlisttrust(""); if(m_viewstate.GetLocalIdentityID()==0) { truststpeeronly.Bind(0,identityidstr); truststpeeronly.Step(); if(truststpeeronly.RowReturned()) { truststpeeronly.ResultText(0,peermessagetrust); truststpeeronly.ResultText(1,peertrustlisttrust); truststpeeronly.ResultInt(0,pmt); if(peermessagetrust!="" && pmt<m_minpeermessagetrust) { allowreply=false; } } truststpeeronly.Reset(); } else { truststboth.Bind(0,identityidstr); truststboth.Bind(1,m_viewstate.GetLocalIdentityID()); truststboth.Step(); if(truststboth.RowReturned()) { truststboth.ResultText(0,localmessagetrust); truststboth.ResultText(1,peermessagetrust); truststboth.ResultText(2,localtrustlisttrust); truststboth.ResultText(3,peertrustlisttrust); truststboth.ResultInt(0,lmt); truststboth.ResultInt(1,pmt); if(localmessagetrust=="") { lmt=100; } if(peermessagetrust=="") { pmt=100; } if(((m_localtrustoverrides==false || localmessagetrust=="") && (pmt<m_minpeermessagetrust || lmt<m_minlocalmessagetrust)) || (m_localtrustoverrides==true && (lmt<m_minlocalmessagetrust))) { allowreply=false; } } truststboth.Reset(); } postvars["CONDITIONALTRUSTTABLE"]=trusttable; postvars["LOCALMESSAGETRUST"]=localmessagetrust; postvars["PEERMESSAGETRUST"]=peermessagetrust; postvars["LOCALTRUSTLISTTRUST"]=localtrustlisttrust; postvars["PEERTRUSTLISTTRUST"]=peertrustlisttrust; if(m_viewstate.GetLocalIdentityID()!=0) { postvars["LOCALMESSAGETRUST"]+="<a href=\""+m_pagename+"?viewstate="+m_viewstate.GetViewStateID()+"&"+CreateLinkFormPassword()+"&threadid="+threadidstr+"&boardid="+boardidstr+"&page="+pagestr+"&formaction=addmessagetrust&identityid="+identityidstr+"#"+messageidstr+"\"><img src=\"images/circleplus.png\" border=\"0\" style=\"vertical-align:bottom;\"></a>"; postvars["LOCALMESSAGETRUST"]+="<a href=\""+m_pagename+"?viewstate="+m_viewstate.GetViewStateID()+"&"+CreateLinkFormPassword()+"&threadid="+threadidstr+"&boardid="+boardidstr+"&page="+pagestr+"&formaction=removemessagetrust&identityid="+identityidstr+"#"+messageidstr+"\"><img src=\"images/circleminus.png\" border=\"0\" style=\"vertical-align:bottom;\"></a>"; postvars["LOCALTRUSTLISTTRUST"]+="<a href=\""+m_pagename+"?viewstate="+m_viewstate.GetViewStateID()+"&"+CreateLinkFormPassword()+"&threadid="+threadidstr+"&boardid="+boardidstr+"&page="+pagestr+"&formaction=addtrustlisttrust&identityid="+identityidstr+"#"+messageidstr+"\"><img src=\"images/circleplus.png\" border=\"0\" style=\"vertical-align:bottom;\"></a>"; postvars["LOCALTRUSTLISTTRUST"]+="<a href=\""+m_pagename+"?viewstate="+m_viewstate.GetViewStateID()+"&"+CreateLinkFormPassword()+"&threadid="+threadidstr+"&boardid="+boardidstr+"&page="+pagestr+"&formaction=removetrustlisttrust&identityid="+identityidstr+"#"+messageidstr+"\"><img src=\"images/circleminus.png\" border=\"0\" style=\"vertical-align:bottom;\"></a>"; } } postvars["THREADPOSTBODY"]=FixBody(body); postattachments=""; fileattachmentst.Bind(0,messageid); fileattachmentst.Step(); while(fileattachmentst.RowReturned()) { std::string thisattachment(""); std::map<std::string,std::string> attachmentvars; std::string key(""); int size=0; std::string sizestr(""); std::string keyname(""); std::string::size_type slashpos=std::string::npos; fileattachmentst.ResultText(0,key); fileattachmentst.ResultInt(0,size); fileattachmentst.ResultText(1,sizestr); if(size<0) { sizestr="?"; } keyname=key; slashpos=keyname.find('/'); if(slashpos!=std::string::npos && slashpos<keyname.size()) { keyname=keyname.substr(slashpos+1); } attachmentvars["THREADPOSTATTACHMENTLINK"]="<a href=\"[FPROXYPROTOCOL]://[FPROXYHOST]:[FPROXYPORT]/"+StringFunctions::UriEncode(key)+"\"><img src=\"images/attach.png\" border=\"0\" style=\"vertical-align:baseline;\"> "+SanitizeOutput(keyname)+"</a>"; attachmentvars["THREADPOSTATTACHMENTSIZE"]=sizestr+" bytes"; m_templatehandler.PerformReplacements(threadpostattachment,attachmentvars,thisattachment); postattachments+=thisattachment; fileattachmentst.Step(); } fileattachmentst.Reset(); if(postattachments!="") { postattachments="<div class=\"postattachments\">"+postattachments+"</div>"; } postvars["THREADPOSTATTACHMENTS"]=postattachments; if(identityidstr!="") { postvars["THREADPOSTAUTHORNAME"]="<a href=\"peerdetails.htm?identityid="+identityidstr+"\">"+FixAuthorName(fromname)+"</a>"; if(showsignatures==true && showidsignature=="1" && signature!="") { std::vector<std::string> skipspace(1," "); std::string lf(1,10); postvars["THREADPOSTSIGNATURE"]=StringFunctions::Replace(m_htmlrenderer.Render(signature),lf,"<br />"); } else { postvars["THREADPOSTSIGNATUREDIV"]=""; } if(showavatars==true && showidavatar==true) { /* std::vector<std::string> parts; StringFunctions::SplitMultiple(postlink,"@,",parts); if(parts.size()>1) { postvars["THREADPOSTAUTHORAVATAR"]="<img src=\"showavatar.htm?idpart="+StringFunctions::UriEncode(parts[1])+"\">"; } else { postvars["THREADPOSTAUTHORAVATAR"]=""; } */ if(fmsavatar!="") { postvars["THREADPOSTAUTHORAVATAR"]="<img src=\""+fproxyprotocol+"://"+fproxyhost+":"+fproxyport+"/"+StringFunctions::UriEncode(fmsavatar)+"\" style=\"max-width:150px;max-height:150px;\">"; } else if(soneavatar!="") { postvars["THREADPOSTAUTHORAVATAR"]="<img src=\""+fproxyprotocol+"://"+fproxyhost+":"+fproxyport+"/"+StringFunctions::UriEncode(soneavatar)+"\" style=\"max-width:150px;max-height:150px;\">"; } else { postvars["THREADPOSTAUTHORAVATAR"]=""; } } else { postvars["THREADPOSTAUTHORAVATAR"]=""; } } else { postvars["THREADPOSTAUTHORNAME"]=FixAuthorName(fromname); postvars["THREADPOSTSIGNATUREDIV"]=""; postvars["THREADPOSTAUTHORAVATAR"]=""; } postvars["THREADPOSTTITLE"]=SanitizeOutput(subject,skipspace); if(identityidstr!="" && postlink!="") { postvars["THREADPOSTLINK"]="<a href=\"[FPROXYPROTOCOL]://[FPROXYHOST]:[FPROXYPORT]/"+StringFunctions::UriEncode(postlink)+"?type=text/plain\"><img src=\"images/link.png\" border=\"0\" title=\""+m_trans->Get("web.page.forumviewthread.permalink")+"\"></a>"; } else { postvars["THREADPOSTLINK"]=""; } postvars["THREADPOSTLINK"]+=" <a href=\""+m_pagename+"?messageuuid="+FixUUIDAnchor(messageuuid)+"#"+FixUUIDAnchor(messageuuid)+"\"><img src=\"images/link.png\" border=\"0\" title=\""+m_trans->Get("web.page.forumviewthread.shareablelink")+"\"></a>"; postvars["THREADPOSTDATE"]=datetime; if(allowreply==true) { postvars["THREADPOSTREPLYLINK"]="<a href=\"forumcreatepost.htm?viewstate="+m_viewstate.GetViewStateID()+"&replytomessageid="+messageidstr+"&threadid="+threadidstr+"&boardid="+boardidstr+"&page="+pagestr+"\"><img src=\"images/mail_reply.png\" border=\"0\" style=\"vertical-align:bottom;\">"+m_trans->Get("web.page.forumviewthread.reply")+"</a>"; } else { postvars["THREADPOSTREPLYLINK"]=""; } postcount++; if(postcount%2==1) { m_templatehandler.PerformReplacements(threadpostrowodd,postvars,postrow); } else { m_templatehandler.PerformReplacements(threadpostroweven,postvars,postrow); } postrows+=postrow; trans.Step(st); } trans.Finalize(st); trans.Commit(); vars["THREADPOSTROWS"]=postrows; CreateBreadcrumbLinks(breadcrumblinks,result); vars["LOCATIONBREADCRUMBS"]=result; m_templatehandler.GetSection("FORUMVIEWTHREADCONTENT",maincontent); m_templatehandler.PerformReplacements(maincontent,vars,result); return result; }
int YS_Evolution2D::evolveSurface(YieldSurface_BC *ys, double lamda, Vector &G, Vector &F_Surface, int flag) { // first and fore-most: tmpYSPtr = ys; // int loc = ys->ele_Location; // opserr << " evolve surface [" << opserr << loc << "]\n"; // opserr << *ys; //freezeEvolution = false; -> have set this in commitState -> don't change // first save the vlues on stack // static vectors could get reallocated elsewhere Vector f_sur(2); f_sur(0) = F_Surface(0); f_sur(1) = F_Surface(1); Vector gl(2); gl(0) = G(0); gl(1) = G(1); setTrialPlasticStrains(lamda, f_sur, gl); if(freezeEvolution) return 0; //deformable = true; double kinX = gl(0)*getKinPlasticStiffness(0)/ys->getCap(0); double kinY = gl(1)*getKinPlasticStiffness(1)/ys->getCap(1); double isoX = gl(0)*getIsoPlasticStiffness(0)/ys->getCap(0); double isoY = gl(1)*getIsoPlasticStiffness(1)/ys->getCap(1); // opserr << "isoX = " << isoX << ", isoY = " << isoY << endln; // kinematic hardening double lamda_kin = kinematicRatio*lamda; double dfx_kin = lamda_kin*kinX; double dfy_kin = lamda_kin*kinY; // isotropic hardening double lamda_iso = isotropicRatio*lamda; double dfx_iso = lamda_iso*isoX; double dfy_iso = lamda_iso*isoY; double dfx_total = dfx_kin + dfx_iso; double dfy_total = dfy_kin + dfy_iso; double fx_new = f_sur(0) + dfx_total; double fy_new = f_sur(1) + dfy_total; double fx_iso_new = f_sur(0) + dfx_iso; double fy_iso_new = f_sur(1) + dfy_iso; // check 1: for cross-over -> same as: |F_sur + df| > |F_sur| && Kp < 0 // sign change //cout << "f_sur = " << f_sur(0) << ", f new = " << fx_new << endln; bool ys_harden = true; toOriginalCoord(fx_new, fy_new); if(ys->getDrift(fx_new, fy_new) < 0) ys_harden = false; bool iso_harden = true; toOriginalCoord(fx_iso_new, fy_iso_new); if(ys->getDrift(fx_iso_new, fy_iso_new) < 0) iso_harden = false; if(!ys_harden && (sign(f_sur(0)) != sign(fx_new))) // risky to use for fy -> P { // need to fix this dfx_iso = 0.0; dfx_kin = 0.0; opserr << "Condition happened..\n"; opserr << *ys; freezeEvolution = true; //cerr << "F_Surface(0) = " << f_sur(0) << ", F_New = " << fx_new << endln; //cin.get(); // if(!deformable) //nothing to do // return anyway for now { return 0; // dfy_iso = 0.0; // dfy_kin = 0.0; } } if(!ys_harden && (kinematicRatio != kinematicRatio_shrink) && (isotropicRatio != isotropicRatio_shrink) ) { double kinRatio = kinematicRatio_shrink; double isoRatio = isotropicRatio_shrink; // here it might be a good idea to redo the above step // will not make difference for peak-oriented but for // others may cause convergence problems (Kp_iso != Kp_kin) // what if its not softening anymore? lamda_iso = isoRatio*lamda; dfx_iso = lamda_iso*isoX; dfy_iso = lamda_iso*isoY; lamda_kin = kinRatio*lamda; dfx_kin = lamda_kin*kinX; dfy_kin = lamda_kin*kinY; dfx_total = dfx_kin + dfx_iso; dfy_total = dfy_kin + dfy_iso; fx_new = f_sur(0) + dfx_total; fy_new = f_sur(1) + dfy_total; toOriginalCoord(fx_new, fy_new); if(ys->getDrift(fx_new, fy_new) > 0) { opserr << "oops: YS_Evolution2D::evolveSurface() - softens->hardens\n"; ys_harden = true; } } // Update the isotropicFactor vector /* // This way does not work! int x_grow = 1; if(fabs(f_sur(0) + dfx_iso) < fabs(f_sur(0))) { // opserr << "Softening!\n"; x_grow = -1; } int y_grow = 1; if(fabs(f_sur(1) + dfy_iso) < fabs(f_sur(1))) y_grow = -1; */ int x_grow = 1, y_grow = 1; if(getIsoPlasticStiffness(0) < 0) x_grow = -1; if(getIsoPlasticStiffness(1) < 0) y_grow = -1; if(evolDebug) { opserr << "F_Surface Vector: " << f_sur; opserr << "Fx_new = " << fx_new << ", Fy_new = " << fy_new << endln; opserr << "Gradient: " << gl; opserr << "KpxIso = " << getIsoPlasticStiffness(0) << ", KpyIso = " << getIsoPlasticStiffness(1) << endln; opserr << "F_surf(1) = " << f_sur(1) << ", dfy_iso = " << dfy_iso << endln; opserr << "x_grow = " << x_grow << ", y_grow = " << y_grow << endln; opserr << "---------------------------------------------------------" << endln; } Vector mgnf(2); mgnf = isotropicFactor_hist; if(flag==1) mgnf = isotropicFactor; Vector delMag(2); if(deformable) { delMag(0) = x_grow*fabs(dfx_iso); delMag(1) = y_grow*fabs(dfy_iso); } else { double dR = sqrt(dfx_iso*dfx_iso + dfy_iso*dfy_iso); if(!iso_harden) dR = -1*dR; delMag(0) = dR; delMag(1) = dR; } Vector isoFact = mgnf + delMag; //check 2: For min isotropic factor if( (isotropicFactor(0) + delMag(0)) <= minIsoFactor) { delMag(0) = 0.0; dfx_kin = 0.0; freezeEvolution = true; if(!deformable)// nothing to do return 0; } if( (isotropicFactor(1) + delMag(1)) <= minIsoFactor) { delMag(1) = 0.0; dfy_kin = 0.0; freezeEvolution = true; if(!deformable) return 0; } // update the translation vector double fx_aim = f_sur(0) + dfx_kin; double fy_aim = f_sur(1) + dfy_kin; //cout << "YS_Evolution2D - F_Surface = " << F_Surface; toOriginalCoord(fx_aim, fy_aim); Vector f_aim(2); f_aim(0) = fx_aim; f_aim(1) = fy_aim; v2 = getEvolDirection(f_aim); Vector df_kin = ys->translationTo(f_aim, v2); // correct for isotropic factor Vector trans(2); trans = translate_hist; if(flag==1) trans = translate; // Update the quantities translate(0) = trans(0) + df_kin(0)*isotropicFactor(0); translate(1) = trans(1) + df_kin(1)*isotropicFactor(1); isotropicFactor = mgnf + delMag; return 0; }
void QSplitter::recalc( bool update ) { int fi = 2*frameWidth(); int maxl = fi; int minl = fi; int maxt = QWIDGETSIZE_MAX; int mint = fi; int n = data->list.count(); bool first = TRUE; /* The splitter before a hidden widget is always hidden. The splitter before the first visible widget is hidden. The splitter before any other visible widget is visible. */ for ( int i = 0; i< n; i++ ) { QSplitterLayoutStruct *s = data->list.at(i); if ( !s->isSplitter ) { QSplitterLayoutStruct *p = (i > 0) ? data->list.at( i-1 ) : 0; if ( p && p->isSplitter ) if ( first || s->wid->isHidden() ) p->wid->hide(); //may trigger new recalc else p->wid->show(); //may trigger new recalc if ( !s->wid->isHidden() ) first = FALSE; } } bool empty=TRUE; for ( int j = 0; j< n; j++ ) { QSplitterLayoutStruct *s = data->list.at(j); if ( !s->wid->isHidden() ) { empty = FALSE; if ( s->isSplitter ) { minl += s->sizer; maxl += s->sizer; } else { QSize minS = minSize(s->wid); minl += pick( minS ); maxl += pick( s->wid->maximumSize() ); mint = QMAX( mint, trans( minS )); int tm = trans( s->wid->maximumSize() ); if ( tm > 0 ) maxt = QMIN( maxt, tm ); } } } if ( empty ) maxl = maxt = 0; else maxl = QMIN( maxl, QWIDGETSIZE_MAX ); if ( maxt < mint ) maxt = mint; if ( orient == Horizontal ) { setMaximumSize( maxl, maxt ); setMinimumSize( minl, mint ); } else { setMaximumSize( maxt, maxl ); setMinimumSize( mint, minl ); } if ( update ) doResize(); }
void Beam<nDim,nOrder>::run() { this->changeRepository( boost::format( "doc/manual/solid/%1%/%2%/P%3%/h_%4%/" ) % this->about().appName() % entity_type::name() % nOrder % meshSize ); /* * First we create the mesh */ mesh_ptrtype mesh = createGMSHMesh( _mesh=new mesh_type, _update=MESH_UPDATE_EDGES|MESH_UPDATE_FACES|MESH_CHECK, _desc=domain( _name=( boost::format( "beam-%1%" ) % nDim ).str() , _shape="hypercube", _xmin=0., _xmax=0.351, _ymin=0., _ymax=0.02, _zmin=0., _zmax=0.02, _h=meshSize ) ); // add marker clamped to the mesh mesh->addMarkerName( "clamped",( nDim==2 )?1:19, (nDim==2)?1:2); mesh->addMarkerName( "tip",( nDim==2)?3:27, (nDim==2)?1:2); /* * The function space and some associate elements are then defined */ timers["init"].first.restart(); space_ptrtype Xh = space_type::New( mesh ); Xh->printInfo(); element_type u( Xh, "u" ); element_type v( Xh, "v" ); timers["init"].second = timers["init"].first.elapsed(); /* * Data associated with the simulation */ auto E = doption(_name="E")*pascal; const double nu = doption(_name="nu"); auto mu = E/( 2*( 1+nu ) ); auto lambda = E*nu/( ( 1+nu )*( 1-2*nu ) ); auto density = 1e3; auto gravity = -2*newton/pow<Dim>(meter);//-density*0.05; LOG(INFO) << "lambda = " << lambda << "\n" << "mu = " << mu << "\n" << "gravity= " << gravity << "\n"; /* * Construction of the right hand side * * \f$ f = \int_\Omega g * v \f$ where \f$ g \f$ is a vector * directed in the \f$ y \f$ direction. */ auto F = backend()->newVector( Xh ); F->zero(); timers["assembly"].first.restart(); if ( Dim == 3 ) form1( _test=Xh, _vector=F ) = integrate( elements( mesh ), trans( gravity.value()*oneZ() )*id( v ) ); else form1( _test=Xh, _vector=F ) = integrate( elements( mesh ), trans( gravity.value()*oneY() )*id( v ) ); timers["assembly"].second = timers["assembly"].first.elapsed(); /* * Construction of the left hand side */ auto D = backend()->newMatrix( Xh, Xh ); timers["assembly"].first.restart(); auto deft = sym(gradt(u)); auto def = sym(grad(u)); auto a = form2( _test=Xh, _trial=Xh, _matrix=D ); a = integrate( elements( mesh ), lambda.value()*divt( u )*div( v ) + 2.*mu.value()*trace( trans( deft )*def ) ); if ( M_bctype == 1 ) // weak Dirichlet bc { auto Id = eye<nDim>(); a += integrate( markedfaces( mesh, "clamped" ), - trans( ( 2.*mu.value()*deft+lambda.value()*trace( deft )*Id )*N() )*id( v ) - trans( ( 2.*mu.value()*def+lambda.value()*trace( def )*Id )*N() )*idt( u ) + bcCoeff*std::max(2.*mu.value(),lambda.value())*trans( idt( u ) )*id( v )/hFace() ); } if ( M_bctype == 0 ) a += on( markedfaces( mesh, "clamped" ), u, F, zero<nDim,1>() ); timers["assembly"].second += timers["assembly"].first.elapsed(); backend(_rebuild=true)->solve( _matrix=D, _solution=u, _rhs=F ); v = vf::project( Xh, elements( Xh->mesh() ), P() ); this->exportResults( 0, u, v ); auto i1 = mean( _range=markedfaces( mesh, "tip" ), _expr=idv( u ) ); LOG(INFO) << "deflection: " << i1 << "\n"; } // Beam::run
unsigned render() { pixfmt_type pf(rbuf_window()); agg::renderer_base<pixfmt_type> rb(pf); agg::renderer_scanline_aa_solid<agg::renderer_base<pixfmt_type> > ren(rb); switch(m_polygons.cur_item()) { case 0: { //------------------------------------ // Two simple paths // agg::path_storage ps1; agg::path_storage ps2; double x = m_x - initial_width()/2 + 100; double y = m_y - initial_height()/2 + 100; ps1.move_to(x+140, y+145); ps1.line_to(x+225, y+44); ps1.line_to(x+296, y+219); ps1.close_polygon(); ps1.line_to(x+226, y+289); ps1.line_to(x+82, y+292); ps1.move_to(x+220, y+222); ps1.line_to(x+363, y+249); ps1.line_to(x+265, y+331); ps1.move_to(x+242, y+243); ps1.line_to(x+268, y+309); ps1.line_to(x+325, y+261); ps1.move_to(x+259, y+259); ps1.line_to(x+273, y+288); ps1.line_to(x+298, y+266); ps2.move_to(100+32, 100+77); ps2.line_to(100+473, 100+263); ps2.line_to(100+351, 100+290); ps2.line_to(100+354, 100+374); m_ras.reset(); m_ras.add_path(ps1); ren.color(agg::rgba(0, 0, 0, 0.1)); agg::render_scanlines(m_ras, m_sl, ren); m_ras.reset(); m_ras.add_path(ps2); ren.color(agg::rgba(0, 0.6, 0, 0.1)); agg::render_scanlines(m_ras, m_sl, ren); generate_alpha_mask(ps1); perform_rendering(ps2); } break; case 1: { //------------------------------------ // Closed stroke // agg::path_storage ps1; agg::path_storage ps2; agg::conv_stroke<agg::path_storage> stroke(ps2); stroke.width(10.0); double x = m_x - initial_width()/2 + 100; double y = m_y - initial_height()/2 + 100; ps1.move_to(x+140, y+145); ps1.line_to(x+225, y+44); ps1.line_to(x+296, y+219); ps1.close_polygon(); ps1.line_to(x+226, y+289); ps1.line_to(x+82, y+292); ps1.move_to(x+220-50, y+222); ps1.line_to(x+265-50, y+331); ps1.line_to(x+363-50, y+249); ps1.close_polygon(agg::path_flags_ccw); ps2.move_to(100+32, 100+77); ps2.line_to(100+473, 100+263); ps2.line_to(100+351, 100+290); ps2.line_to(100+354, 100+374); ps2.close_polygon(); m_ras.reset(); m_ras.add_path(ps1); ren.color(agg::rgba(0, 0, 0, 0.1)); agg::render_scanlines(m_ras, m_sl, ren); m_ras.reset(); m_ras.add_path(stroke); ren.color(agg::rgba(0, 0.6, 0, 0.1)); agg::render_scanlines(m_ras, m_sl, ren); generate_alpha_mask(ps1); perform_rendering(stroke); } break; case 2: { //------------------------------------ // Great Britain and Arrows // agg::path_storage gb_poly; agg::path_storage arrows; make_gb_poly(gb_poly); make_arrows(arrows); agg::trans_affine mtx1; agg::trans_affine mtx2; mtx1 *= agg::trans_affine_translation(-1150, -1150); mtx1 *= agg::trans_affine_scaling(2.0); mtx2 = mtx1; mtx2 *= agg::trans_affine_translation(m_x - initial_width()/2, m_y - initial_height()/2); agg::conv_transform<agg::path_storage> trans_gb_poly(gb_poly, mtx1); agg::conv_transform<agg::path_storage> trans_arrows(arrows, mtx2); m_ras.add_path(trans_gb_poly); ren.color(agg::rgba(0.5, 0.5, 0, 0.1)); agg::render_scanlines(m_ras, m_sl, ren); agg::conv_stroke<agg::conv_transform<agg::path_storage> > stroke_gb_poly(trans_gb_poly); stroke_gb_poly.width(0.1); m_ras.add_path(stroke_gb_poly); ren.color(agg::rgba(0, 0, 0)); agg::render_scanlines(m_ras, m_sl, ren); m_ras.add_path(trans_arrows); ren.color(agg::rgba(0.0, 0.5, 0.5, 0.1)); agg::render_scanlines(m_ras, m_sl, ren); generate_alpha_mask(trans_gb_poly); perform_rendering(trans_arrows); } break; case 3: { //------------------------------------ // Great Britain and a Spiral // spiral sp(m_x, m_y, 10, 150, 30, 0.0); agg::conv_stroke<spiral> stroke(sp); stroke.width(15.0); agg::path_storage gb_poly; make_gb_poly(gb_poly); agg::trans_affine mtx; mtx *= agg::trans_affine_translation(-1150, -1150); mtx *= agg::trans_affine_scaling(2.0); agg::conv_transform<agg::path_storage> trans_gb_poly(gb_poly, mtx); m_ras.add_path(trans_gb_poly); ren.color(agg::rgba(0.5, 0.5, 0, 0.1)); agg::render_scanlines(m_ras, m_sl, ren); agg::conv_stroke<agg::conv_transform<agg::path_storage> > stroke_gb_poly(trans_gb_poly); stroke_gb_poly.width(0.1); m_ras.add_path(stroke_gb_poly); ren.color(agg::rgba(0, 0, 0)); agg::render_scanlines(m_ras, m_sl, ren); m_ras.add_path(stroke); ren.color(agg::rgba(0.0, 0.5, 0.5, 0.1)); agg::render_scanlines(m_ras, m_sl, ren); generate_alpha_mask(trans_gb_poly); perform_rendering(stroke); } break; case 4: { //------------------------------------ // Spiral and glyph // spiral sp(m_x, m_y, 10, 150, 30, 0.0); agg::conv_stroke<spiral> stroke(sp); stroke.width(15.0); agg::path_storage glyph; glyph.move_to(28.47, 6.45); glyph.curve3(21.58, 1.12, 19.82, 0.29); glyph.curve3(17.19, -0.93, 14.21, -0.93); glyph.curve3(9.57, -0.93, 6.57, 2.25); glyph.curve3(3.56, 5.42, 3.56, 10.60); glyph.curve3(3.56, 13.87, 5.03, 16.26); glyph.curve3(7.03, 19.58, 11.99, 22.51); glyph.curve3(16.94, 25.44, 28.47, 29.64); glyph.line_to(28.47, 31.40); glyph.curve3(28.47, 38.09, 26.34, 40.58); glyph.curve3(24.22, 43.07, 20.17, 43.07); glyph.curve3(17.09, 43.07, 15.28, 41.41); glyph.curve3(13.43, 39.75, 13.43, 37.60); glyph.line_to(13.53, 34.77); glyph.curve3(13.53, 32.52, 12.38, 31.30); glyph.curve3(11.23, 30.08, 9.38, 30.08); glyph.curve3(7.57, 30.08, 6.42, 31.35); glyph.curve3(5.27, 32.62, 5.27, 34.81); glyph.curve3(5.27, 39.01, 9.57, 42.53); glyph.curve3(13.87, 46.04, 21.63, 46.04); glyph.curve3(27.59, 46.04, 31.40, 44.04); glyph.curve3(34.28, 42.53, 35.64, 39.31); glyph.curve3(36.52, 37.21, 36.52, 30.71); glyph.line_to(36.52, 15.53); glyph.curve3(36.52, 9.13, 36.77, 7.69); glyph.curve3(37.01, 6.25, 37.57, 5.76); glyph.curve3(38.13, 5.27, 38.87, 5.27); glyph.curve3(39.65, 5.27, 40.23, 5.62); glyph.curve3(41.26, 6.25, 44.19, 9.18); glyph.line_to(44.19, 6.45); glyph.curve3(38.72, -0.88, 33.74, -0.88); glyph.curve3(31.35, -0.88, 29.93, 0.78); glyph.curve3(28.52, 2.44, 28.47, 6.45); glyph.close_polygon(); glyph.move_to(28.47, 9.62); glyph.line_to(28.47, 26.66); glyph.curve3(21.09, 23.73, 18.95, 22.51); glyph.curve3(15.09, 20.36, 13.43, 18.02); glyph.curve3(11.77, 15.67, 11.77, 12.89); glyph.curve3(11.77, 9.38, 13.87, 7.06); glyph.curve3(15.97, 4.74, 18.70, 4.74); glyph.curve3(22.41, 4.74, 28.47, 9.62); glyph.close_polygon(); agg::trans_affine mtx; mtx *= agg::trans_affine_scaling(4.0); mtx *= agg::trans_affine_translation(220, 200); agg::conv_transform<agg::path_storage> trans(glyph, mtx); agg::conv_curve<agg::conv_transform<agg::path_storage> > curve(trans); m_ras.reset(); m_ras.add_path(stroke); ren.color(agg::rgba(0, 0, 0, 0.1)); agg::render_scanlines(m_ras, m_sl, ren); m_ras.reset(); m_ras.add_path(curve); ren.color(agg::rgba(0, 0.6, 0, 0.1)); agg::render_scanlines(m_ras, m_sl, ren); generate_alpha_mask(stroke); perform_rendering(curve); } break; } return 0; }
/* * This function handles the user application commands for register access. * * It retrieves command ID carried with IWL_TM_ATTR_COMMAND and calls to the * handlers respectively. * * If it's an unknown commdn ID, -ENOSYS is returned; or -ENOMSG if the * mandatory fields(IWL_TM_ATTR_REG_OFFSET,IWL_TM_ATTR_REG_VALUE32, * IWL_TM_ATTR_REG_VALUE8) are missing; Otherwise 0 is replied indicating * the success of the command execution. * * If IWL_TM_ATTR_COMMAND is IWL_TM_CMD_APP2DEV_REG_READ32, the register read * value is returned with IWL_TM_ATTR_REG_VALUE32. * * @hw: ieee80211_hw object that represents the device * @tb: gnl message fields from the user space */ static int iwl_testmode_reg(struct ieee80211_hw *hw, struct nlattr **tb) { struct iwl_priv *priv = hw->priv; u32 ofs, val32, cmd; u8 val8; struct sk_buff *skb; int status = 0; if (!tb[IWL_TM_ATTR_REG_OFFSET]) { IWL_DEBUG_INFO(priv, "Error finding register offset\n"); return -ENOMSG; } ofs = nla_get_u32(tb[IWL_TM_ATTR_REG_OFFSET]); IWL_INFO(priv, "testmode register access command offset 0x%x\n", ofs); /* Allow access only to FH/CSR/HBUS in direct mode. Since we don't have the upper bounds for the CSR and HBUS segments, we will use only the upper bound of FH for sanity check. */ cmd = nla_get_u32(tb[IWL_TM_ATTR_COMMAND]); if ((cmd == IWL_TM_CMD_APP2DEV_DIRECT_REG_READ32 || cmd == IWL_TM_CMD_APP2DEV_DIRECT_REG_WRITE32 || cmd == IWL_TM_CMD_APP2DEV_DIRECT_REG_WRITE8) && (ofs >= FH_MEM_UPPER_BOUND)) { IWL_DEBUG_INFO(priv, "offset out of segment (0x0 - 0x%x)\n", FH_MEM_UPPER_BOUND); return -EINVAL; } switch (cmd) { case IWL_TM_CMD_APP2DEV_DIRECT_REG_READ32: val32 = iwl_read_direct32(trans(priv), ofs); IWL_INFO(priv, "32bit value to read 0x%x\n", val32); skb = cfg80211_testmode_alloc_reply_skb(hw->wiphy, 20); if (!skb) { IWL_DEBUG_INFO(priv, "Error allocating memory\n"); return -ENOMEM; } NLA_PUT_U32(skb, IWL_TM_ATTR_REG_VALUE32, val32); status = cfg80211_testmode_reply(skb); if (status < 0) IWL_DEBUG_INFO(priv, "Error sending msg : %d\n", status); break; case IWL_TM_CMD_APP2DEV_DIRECT_REG_WRITE32: if (!tb[IWL_TM_ATTR_REG_VALUE32]) { IWL_DEBUG_INFO(priv, "Error finding value to write\n"); return -ENOMSG; } else { val32 = nla_get_u32(tb[IWL_TM_ATTR_REG_VALUE32]); IWL_INFO(priv, "32bit value to write 0x%x\n", val32); iwl_write_direct32(trans(priv), ofs, val32); } break; case IWL_TM_CMD_APP2DEV_DIRECT_REG_WRITE8: if (!tb[IWL_TM_ATTR_REG_VALUE8]) { IWL_DEBUG_INFO(priv, "Error finding value to write\n"); return -ENOMSG; } else { val8 = nla_get_u8(tb[IWL_TM_ATTR_REG_VALUE8]); IWL_INFO(priv, "8bit value to write 0x%x\n", val8); iwl_write8(trans(priv), ofs, val8); } break; case IWL_TM_CMD_APP2DEV_INDIRECT_REG_READ32: val32 = iwl_read_prph(trans(priv), ofs); IWL_INFO(priv, "32bit value to read 0x%x\n", val32); skb = cfg80211_testmode_alloc_reply_skb(hw->wiphy, 20); if (!skb) { IWL_DEBUG_INFO(priv, "Error allocating memory\n"); return -ENOMEM; } NLA_PUT_U32(skb, IWL_TM_ATTR_REG_VALUE32, val32); status = cfg80211_testmode_reply(skb); if (status < 0) IWL_DEBUG_INFO(priv, "Error sending msg : %d\n", status); break; case IWL_TM_CMD_APP2DEV_INDIRECT_REG_WRITE32: if (!tb[IWL_TM_ATTR_REG_VALUE32]) { IWL_DEBUG_INFO(priv, "Error finding value to write\n"); return -ENOMSG; } else { val32 = nla_get_u32(tb[IWL_TM_ATTR_REG_VALUE32]); IWL_INFO(priv, "32bit value to write 0x%x\n", val32); iwl_write_prph(trans(priv), ofs, val32); } break; default: IWL_DEBUG_INFO(priv, "Unknown testmode register command ID\n"); return -ENOSYS; } return status; nla_put_failure: kfree_skb(skb); return -EMSGSIZE; }
int test(NumericT epsilon) { std::size_t N = 142; // should be larger than 128 in order to avoid false negatives due to blocking viennacl::tools::uniform_random_numbers<NumericT> randomNumber; // // Vector setup and test: // std::vector<NumericT> std_x(N); std::vector<NumericT> std_y(N); std::vector<NumericT> std_z(N); for (std::size_t i=0; i<std_x.size(); ++i) std_x[i] = NumericT(i + 1); for (std::size_t i=0; i<std_y.size(); ++i) std_y[i] = NumericT(i*i + 1); for (std::size_t i=0; i<std_z.size(); ++i) std_z[i] = NumericT(2 * i + 1); viennacl::vector<NumericT> vcl_x; viennacl::vector<NumericT> vcl_y; viennacl::vector<NumericT> vcl_z; viennacl::copy(std_x, vcl_x); viennacl::copy(std_y, vcl_y); viennacl::copy(std_z, vcl_z); // This shouldn't do anything bad: vcl_x = vcl_x; check(std_x, vcl_x, "x = x", epsilon); // This should work, even though we are dealing with the same buffer: std_x[0] = std_x[2]; std_x[1] = std_x[3]; viennacl::project(vcl_x, viennacl::range(0, 2)) = viennacl::project(vcl_x, viennacl::range(2, 4)); check(std_x, vcl_x, "x = x (range)", epsilon); // // Matrix-Vector // std::vector<std::vector<NumericT> > std_A(N, std::vector<NumericT>(N, NumericT(1))); std::vector<std::vector<NumericT> > std_B(N, std::vector<NumericT>(N, NumericT(2))); std::vector<std::vector<NumericT> > std_C(N, std::vector<NumericT>(N, NumericT(3))); viennacl::matrix<NumericT> vcl_A; viennacl::matrix<NumericT> vcl_B; viennacl::matrix<NumericT> vcl_C; viennacl::copy(std_A, vcl_A); viennacl::copy(std_B, vcl_B); viennacl::copy(std_C, vcl_C); // This shouldn't do anything bad: vcl_A = vcl_A; check(std_A, vcl_A, "A = A", epsilon); // This should work, even though we are dealing with the same buffer: std_A[0][0] = std_A[0][2]; std_A[0][1] = std_A[0][3]; viennacl::project(vcl_A, viennacl::range(0, 1), viennacl::range(0, 2)) = viennacl::project(vcl_A, viennacl::range(0, 1), viennacl::range(2, 4)); check(std_A, vcl_A, "A = A (range)", epsilon); // check x <- A * x; for (std::size_t i = 0; i<std_y.size(); ++i) { NumericT val = 0; for (std::size_t j = 0; j<std_x.size(); ++j) val += std_A[i][j] * std_x[j]; std_y[i] = val; } vcl_x = viennacl::linalg::prod(vcl_A, vcl_x); check(std_y, vcl_x, "x = A*x", epsilon); typedef unsigned int KeyType; std::vector< std::map<KeyType, NumericT> > std_Asparse(N); for (std::size_t i=0; i<std_Asparse.size(); ++i) { if (i > 0) std_Asparse[i][KeyType(i-1)] = randomNumber(); std_Asparse[i][KeyType(i)] = NumericT(1) + randomNumber(); if (i < std_Asparse.size() - 1) std_Asparse[i][KeyType(i+1)] = randomNumber(); } // Sparse viennacl::compressed_matrix<NumericT> vcl_A_csr; viennacl::coordinate_matrix<NumericT> vcl_A_coo; viennacl::ell_matrix<NumericT> vcl_A_ell; viennacl::sliced_ell_matrix<NumericT> vcl_A_sell; viennacl::hyb_matrix<NumericT> vcl_A_hyb; viennacl::copy(std_Asparse, vcl_A_csr); viennacl::copy(std_Asparse, vcl_A_coo); viennacl::copy(std_Asparse, vcl_A_ell); viennacl::copy(std_Asparse, vcl_A_sell); viennacl::copy(std_Asparse, vcl_A_hyb); for (std::size_t i=0; i<std_Asparse.size(); ++i) { NumericT val = 0; for (typename std::map<unsigned int, NumericT>::const_iterator it = std_Asparse[i].begin(); it != std_Asparse[i].end(); ++it) val += it->second * std_x[it->first]; std_y[i] = val; } viennacl::copy(std_x, vcl_x); vcl_x = viennacl::linalg::prod(vcl_A_csr, vcl_x); check(std_y, vcl_x, "x = A*x (sparse, csr)", epsilon); viennacl::copy(std_x, vcl_x); vcl_x = viennacl::linalg::prod(vcl_A_coo, vcl_x); check(std_y, vcl_x, "x = A*x (sparse, coo)", epsilon); viennacl::copy(std_x, vcl_x); vcl_x = viennacl::linalg::prod(vcl_A_ell, vcl_x); check(std_y, vcl_x, "x = A*x (sparse, ell)", epsilon); viennacl::copy(std_x, vcl_x); vcl_x = viennacl::linalg::prod(vcl_A_sell, vcl_x); check(std_y, vcl_x, "x = A*x (sparse, sell)", epsilon); viennacl::copy(std_x, vcl_x); vcl_x = viennacl::linalg::prod(vcl_A_hyb, vcl_x); check(std_y, vcl_x, "x = A*x (sparse, hyb)", epsilon); std::cout << std::endl; // // Matrix-Matrix (dense times dense): // test_gemm<op_assign>(epsilon, std_A, std_B, std_C, vcl_A, "A", vcl_B, "B", vcl_A, true); test_gemm<op_assign>(epsilon, std_B, std_A, std_C, vcl_B, "B", vcl_A, "A", vcl_A, false); test_gemm<op_assign>(epsilon, std_A, std_A, std_C, vcl_A, "A", vcl_A, "A", vcl_A, true); std::cout << std::endl; test_gemm<op_plus_assign>(epsilon, std_A, std_B, std_C, vcl_A, "A", vcl_B, "B", vcl_A, true); test_gemm<op_plus_assign>(epsilon, std_B, std_A, std_C, vcl_B, "B", vcl_A, "A", vcl_A, false); test_gemm<op_plus_assign>(epsilon, std_A, std_A, std_C, vcl_A, "A", vcl_A, "A", vcl_A, true); std::cout << std::endl; test_gemm<op_minus_assign>(epsilon, std_A, std_B, std_C, vcl_A, "A", vcl_B, "B", vcl_A, true); test_gemm<op_minus_assign>(epsilon, std_B, std_A, std_C, vcl_B, "B", vcl_A, "A", vcl_A, false); test_gemm<op_minus_assign>(epsilon, std_A, std_A, std_C, vcl_A, "A", vcl_A, "A", vcl_A, true); std::cout << std::endl; // // Matrix-Matrix (sparse times dense) // // A = sparse * A viennacl::copy(std_A, vcl_A); for (std::size_t i = 0; i<std_A.size(); ++i) for (std::size_t j = 0; j<std_A[i].size(); ++j) { NumericT tmp = 0; for (std::size_t k = 0; k<std_A[i].size(); ++k) tmp += std_Asparse[i][KeyType(k)] * std_A[k][j]; std_C[i][j] = tmp; } viennacl::copy(std_A, vcl_A); vcl_A = viennacl::linalg::prod(vcl_A_csr, vcl_A); check(std_C, vcl_A, "A = csr*A", epsilon); viennacl::copy(std_A, vcl_A); vcl_A = viennacl::linalg::prod(vcl_A_coo, vcl_A); check(std_C, vcl_A, "A = coo*A", epsilon); viennacl::copy(std_A, vcl_A); vcl_A = viennacl::linalg::prod(vcl_A_ell, vcl_A); check(std_C, vcl_A, "A = ell*A", epsilon); viennacl::copy(std_A, vcl_A); //vcl_A = viennacl::linalg::prod(vcl_A_sell, vcl_A); //check(std_C, vcl_A, "A = sell*A", epsilon); viennacl::copy(std_A, vcl_A); vcl_A = viennacl::linalg::prod(vcl_A_hyb, vcl_A); check(std_C, vcl_A, "A = hyb*A", epsilon); // A = sparse * A^T viennacl::copy(std_A, vcl_A); for (std::size_t i = 0; i<std_A.size(); ++i) for (std::size_t j = 0; j<std_A[i].size(); ++j) { NumericT tmp = 0; for (std::size_t k = 0; k<std_A[i].size(); ++k) tmp += std_Asparse[i][KeyType(k)] * std_A[j][k]; std_C[i][j] = tmp; } viennacl::copy(std_A, vcl_A); vcl_A = viennacl::linalg::prod(vcl_A_csr, trans(vcl_A)); check(std_C, vcl_A, "A = csr*A^T", epsilon); viennacl::copy(std_A, vcl_A); vcl_A = viennacl::linalg::prod(vcl_A_coo, trans(vcl_A)); check(std_C, vcl_A, "A = coo*A^T", epsilon); viennacl::copy(std_A, vcl_A); vcl_A = viennacl::linalg::prod(vcl_A_ell, trans(vcl_A)); check(std_C, vcl_A, "A = ell*A^T", epsilon); viennacl::copy(std_A, vcl_A); //vcl_A = viennacl::linalg::prod(vcl_A_sell, trans(vcl_A)); //check(std_C, vcl_A, "A = sell*A^T", epsilon); viennacl::copy(std_A, vcl_A); vcl_A = viennacl::linalg::prod(vcl_A_hyb, trans(vcl_A)); check(std_C, vcl_A, "A = hyb*A^T", epsilon); return EXIT_SUCCESS; }
/* * This function handles the user application commands for driver. * * It retrieves command ID carried with IWL_TM_ATTR_COMMAND and calls to the * handlers respectively. * * If it's an unknown commdn ID, -ENOSYS is replied; otherwise, the returned * value of the actual command execution is replied to the user application. * * If there's any message responding to the user space, IWL_TM_ATTR_SYNC_RSP * is used for carry the message while IWL_TM_ATTR_COMMAND must set to * IWL_TM_CMD_DEV2APP_SYNC_RSP. * * @hw: ieee80211_hw object that represents the device * @tb: gnl message fields from the user space */ static int iwl_testmode_driver(struct ieee80211_hw *hw, struct nlattr **tb) { struct iwl_priv *priv = hw->priv; struct iwl_trans *trans = trans(priv); struct sk_buff *skb; unsigned char *rsp_data_ptr = NULL; int status = 0, rsp_data_len = 0; u32 devid, inst_size = 0, data_size = 0; switch (nla_get_u32(tb[IWL_TM_ATTR_COMMAND])) { case IWL_TM_CMD_APP2DEV_GET_DEVICENAME: rsp_data_ptr = (unsigned char *)cfg(priv)->name; rsp_data_len = strlen(cfg(priv)->name); skb = cfg80211_testmode_alloc_reply_skb(hw->wiphy, rsp_data_len + 20); if (!skb) { IWL_DEBUG_INFO(priv, "Error allocating memory\n"); return -ENOMEM; } NLA_PUT_U32(skb, IWL_TM_ATTR_COMMAND, IWL_TM_CMD_DEV2APP_SYNC_RSP); NLA_PUT(skb, IWL_TM_ATTR_SYNC_RSP, rsp_data_len, rsp_data_ptr); status = cfg80211_testmode_reply(skb); if (status < 0) IWL_DEBUG_INFO(priv, "Error sending msg : %d\n", status); break; case IWL_TM_CMD_APP2DEV_LOAD_INIT_FW: status = iwl_load_ucode_wait_alive(trans, IWL_UCODE_INIT); if (status) IWL_DEBUG_INFO(priv, "Error loading init ucode: %d\n", status); break; case IWL_TM_CMD_APP2DEV_CFG_INIT_CALIB: iwl_testmode_cfg_init_calib(priv); iwl_trans_stop_device(trans); break; case IWL_TM_CMD_APP2DEV_LOAD_RUNTIME_FW: status = iwl_load_ucode_wait_alive(trans, IWL_UCODE_REGULAR); if (status) { IWL_DEBUG_INFO(priv, "Error loading runtime ucode: %d\n", status); break; } status = iwl_alive_start(priv); if (status) IWL_DEBUG_INFO(priv, "Error starting the device: %d\n", status); break; case IWL_TM_CMD_APP2DEV_LOAD_WOWLAN_FW: iwl_scan_cancel_timeout(priv, 200); iwl_trans_stop_device(trans); status = iwl_load_ucode_wait_alive(trans, IWL_UCODE_WOWLAN); if (status) { IWL_DEBUG_INFO(priv, "Error loading WOWLAN ucode: %d\n", status); break; } status = iwl_alive_start(priv); if (status) IWL_DEBUG_INFO(priv, "Error starting the device: %d\n", status); break; case IWL_TM_CMD_APP2DEV_GET_EEPROM: if (priv->shrd->eeprom) { skb = cfg80211_testmode_alloc_reply_skb(hw->wiphy, cfg(priv)->base_params->eeprom_size + 20); if (!skb) { IWL_DEBUG_INFO(priv, "Error allocating memory\n"); return -ENOMEM; } NLA_PUT_U32(skb, IWL_TM_ATTR_COMMAND, IWL_TM_CMD_DEV2APP_EEPROM_RSP); NLA_PUT(skb, IWL_TM_ATTR_EEPROM, cfg(priv)->base_params->eeprom_size, priv->shrd->eeprom); status = cfg80211_testmode_reply(skb); if (status < 0) IWL_DEBUG_INFO(priv, "Error sending msg : %d\n", status); } else return -EFAULT; break; case IWL_TM_CMD_APP2DEV_FIXRATE_REQ: if (!tb[IWL_TM_ATTR_FIXRATE]) { IWL_DEBUG_INFO(priv, "Error finding fixrate setting\n"); return -ENOMSG; } priv->tm_fixed_rate = nla_get_u32(tb[IWL_TM_ATTR_FIXRATE]); break; case IWL_TM_CMD_APP2DEV_GET_FW_VERSION: IWL_INFO(priv, "uCode version raw: 0x%x\n", priv->ucode_ver); skb = cfg80211_testmode_alloc_reply_skb(hw->wiphy, 20); if (!skb) { IWL_DEBUG_INFO(priv, "Error allocating memory\n"); return -ENOMEM; } NLA_PUT_U32(skb, IWL_TM_ATTR_FW_VERSION, priv->ucode_ver); status = cfg80211_testmode_reply(skb); if (status < 0) IWL_DEBUG_INFO(priv, "Error sending msg : %d\n", status); break; case IWL_TM_CMD_APP2DEV_GET_DEVICE_ID: devid = trans(priv)->hw_id; IWL_INFO(priv, "hw version: 0x%x\n", devid); skb = cfg80211_testmode_alloc_reply_skb(hw->wiphy, 20); if (!skb) { IWL_DEBUG_INFO(priv, "Error allocating memory\n"); return -ENOMEM; } NLA_PUT_U32(skb, IWL_TM_ATTR_DEVICE_ID, devid); status = cfg80211_testmode_reply(skb); if (status < 0) IWL_DEBUG_INFO(priv, "Error sending msg : %d\n", status); break; case IWL_TM_CMD_APP2DEV_GET_FW_INFO: skb = cfg80211_testmode_alloc_reply_skb(hw->wiphy, 20 + 8); if (!skb) { IWL_DEBUG_INFO(priv, "Error allocating memory\n"); return -ENOMEM; } switch (priv->shrd->ucode_type) { case IWL_UCODE_REGULAR: inst_size = trans(priv)->ucode_rt.code.len; data_size = trans(priv)->ucode_rt.data.len; break; case IWL_UCODE_INIT: inst_size = trans(priv)->ucode_init.code.len; data_size = trans(priv)->ucode_init.data.len; break; case IWL_UCODE_WOWLAN: inst_size = trans(priv)->ucode_wowlan.code.len; data_size = trans(priv)->ucode_wowlan.data.len; break; case IWL_UCODE_NONE: IWL_DEBUG_INFO(priv, "The uCode has not been loaded\n"); break; default: IWL_DEBUG_INFO(priv, "Unsupported uCode type\n"); break; } NLA_PUT_U32(skb, IWL_TM_ATTR_FW_TYPE, priv->shrd->ucode_type); NLA_PUT_U32(skb, IWL_TM_ATTR_FW_INST_SIZE, inst_size); NLA_PUT_U32(skb, IWL_TM_ATTR_FW_DATA_SIZE, data_size); status = cfg80211_testmode_reply(skb); if (status < 0) IWL_DEBUG_INFO(priv, "Error sending msg : %d\n", status); break; default: IWL_DEBUG_INFO(priv, "Unknown testmode driver command ID\n"); return -ENOSYS; } return status; nla_put_failure: kfree_skb(skb); return -EMSGSIZE; }
// Use LocalXyzPointer types that are not covered elsewhere in the intltest suite. void LocalPointerTest::TestLocalXyzPointer() { IcuTestErrorCode errorCode(*this, "TestLocalXyzPointer"); static const char *const encoding="ISO-8859-1"; LocalUConverterSelectorPointer sel( ucnvsel_open(&encoding, 1, NULL, UCNV_ROUNDTRIP_SET, errorCode)); if(errorCode.logIfFailureAndReset("ucnvsel_open()")) { return; } if(sel.isNull()) { errln("LocalUConverterSelectorPointer failure"); return; } #if !UCONFIG_NO_FORMATTING LocalUCalendarPointer cal(ucal_open(NULL, 0, "root", UCAL_GREGORIAN, errorCode)); if(errorCode.logDataIfFailureAndReset("ucal_open()")) { return; } if(cal.isNull()) { errln("LocalUCalendarPointer failure"); return; } LocalUDateTimePatternGeneratorPointer patgen(udatpg_open("root", errorCode)); if(errorCode.logDataIfFailureAndReset("udatpg_open()")) { return; } if(patgen.isNull()) { errln("LocalUDateTimePatternGeneratorPointer failure"); return; } LocalULocaleDisplayNamesPointer ldn(uldn_open("de-CH", ULDN_STANDARD_NAMES, errorCode)); if(errorCode.logIfFailureAndReset("uldn_open()")) { return; } if(ldn.isNull()) { errln("LocalULocaleDisplayNamesPointer failure"); return; } UnicodeString hello=UNICODE_STRING_SIMPLE("Hello {0}!"); LocalUMessageFormatPointer msg( umsg_open(hello.getBuffer(), hello.length(), "root", NULL, errorCode)); if(errorCode.logIfFailureAndReset("umsg_open()")) { return; } if(msg.isNull()) { errln("LocalUMessageFormatPointer failure"); return; } #endif /* UCONFIG_NO_FORMATTING */ #if !UCONFIG_NO_NORMALIZATION const UNormalizer2 *nfc=unorm2_getNFCInstance(errorCode); UnicodeSet emptySet; LocalUNormalizer2Pointer fn2(unorm2_openFiltered(nfc, emptySet.toUSet(), errorCode)); if(errorCode.logIfFailureAndReset("unorm2_openFiltered()")) { return; } if(fn2.isNull()) { errln("LocalUNormalizer2Pointer failure"); return; } #endif /* !UCONFIG_NO_NORMALIZATION */ #if !UCONFIG_NO_IDNA LocalUIDNAPointer idna(uidna_openUTS46(0, errorCode)); if(errorCode.logIfFailureAndReset("uidna_openUTS46()")) { return; } if(idna.isNull()) { errln("LocalUIDNAPointer failure"); return; } #endif /* !UCONFIG_NO_IDNA */ #if !UCONFIG_NO_REGULAR_EXPRESSIONS UnicodeString pattern=UNICODE_STRING_SIMPLE("abc|xy+z"); LocalURegularExpressionPointer regex( uregex_open(pattern.getBuffer(), pattern.length(), 0, NULL, errorCode)); if(errorCode.logIfFailureAndReset("uregex_open()")) { return; } if(regex.isNull()) { errln("LocalURegularExpressionPointer failure"); return; } #endif /* UCONFIG_NO_REGULAR_EXPRESSIONS */ #if !UCONFIG_NO_TRANSLITERATION UnicodeString id=UNICODE_STRING_SIMPLE("Grek-Latn"); LocalUTransliteratorPointer trans( utrans_openU(id.getBuffer(), id.length(), UTRANS_FORWARD, NULL, 0, NULL, errorCode)); if(errorCode.logIfFailureAndReset("utrans_open()")) { return; } if(trans.isNull()) { errln("LocalUTransliteratorPointer failure"); return; } #endif /* !UCONFIG_NO_TRANSLITERATION */ // destructors }
/* * This function handles the user application commands for uCode trace * * It retrieves command ID carried with IWL_TM_ATTR_COMMAND and calls to the * handlers respectively. * * If it's an unknown commdn ID, -ENOSYS is replied; otherwise, the returned * value of the actual command execution is replied to the user application. * * @hw: ieee80211_hw object that represents the device * @tb: gnl message fields from the user space */ static int iwl_testmode_trace(struct ieee80211_hw *hw, struct nlattr **tb) { struct iwl_priv *priv = hw->priv; struct sk_buff *skb; int status = 0; struct device *dev = trans(priv)->dev; switch (nla_get_u32(tb[IWL_TM_ATTR_COMMAND])) { case IWL_TM_CMD_APP2DEV_BEGIN_TRACE: if (priv->testmode_trace.trace_enabled) return -EBUSY; if (!tb[IWL_TM_ATTR_TRACE_SIZE]) priv->testmode_trace.buff_size = TRACE_BUFF_SIZE_DEF; else priv->testmode_trace.buff_size = nla_get_u32(tb[IWL_TM_ATTR_TRACE_SIZE]); if (!priv->testmode_trace.buff_size) return -EINVAL; if (priv->testmode_trace.buff_size < TRACE_BUFF_SIZE_MIN || priv->testmode_trace.buff_size > TRACE_BUFF_SIZE_MAX) return -EINVAL; priv->testmode_trace.total_size = priv->testmode_trace.buff_size + TRACE_BUFF_PADD; priv->testmode_trace.cpu_addr = dma_alloc_coherent(dev, priv->testmode_trace.total_size, &priv->testmode_trace.dma_addr, GFP_KERNEL); if (!priv->testmode_trace.cpu_addr) return -ENOMEM; priv->testmode_trace.trace_enabled = true; priv->testmode_trace.trace_addr = (u8 *)PTR_ALIGN( priv->testmode_trace.cpu_addr, 0x100); memset(priv->testmode_trace.trace_addr, 0x03B, priv->testmode_trace.buff_size); skb = cfg80211_testmode_alloc_reply_skb(hw->wiphy, sizeof(priv->testmode_trace.dma_addr) + 20); if (!skb) { IWL_DEBUG_INFO(priv, "Error allocating memory\n"); iwl_trace_cleanup(priv); return -ENOMEM; } NLA_PUT(skb, IWL_TM_ATTR_TRACE_ADDR, sizeof(priv->testmode_trace.dma_addr), (u64 *)&priv->testmode_trace.dma_addr); status = cfg80211_testmode_reply(skb); if (status < 0) { IWL_DEBUG_INFO(priv, "Error sending msg : %d\n", status); } priv->testmode_trace.num_chunks = DIV_ROUND_UP(priv->testmode_trace.buff_size, DUMP_CHUNK_SIZE); break; case IWL_TM_CMD_APP2DEV_END_TRACE: iwl_trace_cleanup(priv); break; default: IWL_DEBUG_INFO(priv, "Unknown testmode mem command ID\n"); return -ENOSYS; } return status; nla_put_failure: kfree_skb(skb); if (nla_get_u32(tb[IWL_TM_ATTR_COMMAND]) == IWL_TM_CMD_APP2DEV_BEGIN_TRACE) iwl_trace_cleanup(priv); return -EMSGSIZE; }
/**************************** REGION ********************************/ void QgsGrassNewMapset::setRegionPage() { // Set defaults if ( !mRegionModified ) { setGrassRegionDefaults(); } // Create new projection QgsCoordinateReferenceSystem newCrs; if ( mProjRadioButton->isChecked() ) { QgsDebugMsg( QString( "selectedCrsId() = %1" ).arg( mProjectionSelector->selectedCrsId() ) ); if ( mProjectionSelector->selectedCrsId() > 0 ) { newCrs.createFromSrsId( mProjectionSelector->selectedCrsId() ); if ( ! newCrs.isValid() ) { QgsGrass::warning( tr( "Cannot create projection." ) ); } } } // Reproject previous region if it was modified // and if previous and current projection is valid if ( mRegionModified && newCrs.isValid() && mCrs.isValid() && newCrs.srsid() != mCrs.srsid() ) { QgsCoordinateTransform trans( mCrs, newCrs ); double n = mNorthLineEdit->text().toDouble(); double s = mSouthLineEdit->text().toDouble(); double e = mEastLineEdit->text().toDouble(); double w = mWestLineEdit->text().toDouble(); std::vector<QgsPoint> points; // TODO: this is not perfect points.push_back( QgsPoint( w, s ) ); points.push_back( QgsPoint( e, n ) ); bool ok = true; for ( int i = 0; i < 2; i++ ) { try { points[i] = trans.transform( points[i] ); } catch ( QgsCsException &cse ) { Q_UNUSED( cse ); QgsDebugMsg( "Cannot transform point" ); ok = false; break; } } if ( ok ) { int precision = newCrs.mapUnits() == Qgis::Degrees ? 6 : 1; mNorthLineEdit->setText( qgsDoubleToString( points[1].y(), precision ) ); mSouthLineEdit->setText( qgsDoubleToString( points[0].y(), precision ) ); mEastLineEdit->setText( qgsDoubleToString( points[1].x(), precision ) ); mWestLineEdit->setText( qgsDoubleToString( points[0].x(), precision ) ); } else { QgsGrass::warning( tr( "Cannot reproject previously set region, default region set." ) ); setGrassRegionDefaults(); } } // Set current region projection mCrs = newCrs; // Enable / disable region selection widgets if ( mNoProjRadioButton->isChecked() ) { mRegionMap->hide(); mCurrentRegionButton->hide(); mRegionsComboBox->hide(); mRegionButton->hide(); mSetRegionFrame->hide(); } else { mRegionMap->show(); mCurrentRegionButton->show(); mRegionsComboBox->show(); mRegionButton->show(); mSetRegionFrame->show(); QgsRectangle ext = mIface->mapCanvas()->extent(); mCurrentRegionButton->setEnabled( !ext.isEmpty() ); } checkRegion(); if ( !mNoProjRadioButton->isChecked() ) { drawRegion(); } }
void avtResampleFilter::ResampleInput(void) { int i, j, k; avtDataset_p output = GetTypedOutput(); double bounds[6] = { 0, 0, 0, 0, 0, 0 }; bool is3D = GetBounds(bounds); debug4 << "Resampling over space: " << bounds[0] << ", " << bounds[1] << ": " << bounds[2] << ", " << bounds[3] << ": " << bounds[4] << ", " << bounds[5] << endl; // // Our resampling leaves some invalid values in the data range. The // easiest way to bypass this is to get the data range from the input and // pass it along (since resampling does not change it in theory). // double range[2]; if (GetInput()->GetInfo().GetAttributes().ValidActiveVariable()) { GetDataExtents(range); output->GetInfo().GetAttributes().GetDesiredDataExtents()->Set(range); } avtViewInfo view; double scale[3]; CreateViewFromBounds(view, bounds, scale); // // What we want the width, height, and depth to be depends on the // attributes. // int width, height, depth; GetDimensions(width, height, depth, bounds, is3D); // // If there are no variables, then just create the mesh and exit. // bool thereAreNoVariables = (GetInput()->GetInfo().GetAttributes().GetNumberOfVariables() <= 0); if (thereAreNoVariables) { if (PAR_Rank() == 0) { vtkRectilinearGrid *rg = CreateGrid(bounds, width, height, depth, 0, width, 0, height, cellCenteredOutput, is3D); avtDataTree_p tree = new avtDataTree(rg, 0); rg->Delete(); SetOutputDataTree(tree); } else { // // Putting in a NULL data tree can lead to seg faults, etc. // avtDataTree_p dummy = new avtDataTree(); SetOutputDataTree(dummy); } return; } // // World space is a right-handed coordinate system. Image space (as used // in the sample point extractor) is a left-handed coordinate system. // This is because large X is at the right and large Y is at the top. // The z-buffer has the closest points at z=0, so Z is going away from the // screen ===> left handed coordinate system. If we reflect across X, // then this will account for the difference between the coordinate // systems. // scale[0] *= -1.; // // We don't want an Update to go all the way up the pipeline, so make // a terminating source corresponding to our input. // avtDataset_p ds; avtDataObject_p dObj = GetInput(); CopyTo(ds, dObj); avtSourceFromAVTDataset termsrc(ds); // // The sample point extractor expects everything to be in image space. // avtWorldSpaceToImageSpaceTransform trans(view, scale); trans.SetInput(termsrc.GetOutput()); bool doKernel = (GetInput()->GetInfo().GetAttributes().GetTopologicalDimension() == 0); avtSamplePointExtractor extractor(width, height, depth); extractor.SendCellsMode(false); extractor.Set3DMode(is3D); extractor.SetInput(trans.GetOutput()); if (doKernel) extractor.SetKernelBasedSampling(true); avtSamplePoints_p samples = extractor.GetTypedOutput(); // // If the selection this filter exists to create has already been handled, // or if there are no pieces for this processor to process, then we can skip // execution. But, take care to emulate the same collective // calls other processors may make before returning. // if (GetInput()->GetInfo().GetAttributes().GetSelectionApplied(selID)) { debug1 << "Bypassing Resample operator because database plugin " "claims to have applied the selection already" << endl; SetOutputDataTree(GetInputDataTree()); // we can save a lot of time if we know everyone can bypass if (UnifyMaximumValue(0) == 0) return; // here is some dummied up code to match collective calls below int effectiveVars = samples->GetNumberOfRealVariables(); double *ptrtmp = new double[width*height*depth]; for (int jj = 0; jj < width*height*depth; jj++) ptrtmp[jj] = -FLT_MAX; for (i = 0 ; i < effectiveVars ; i++) Collect(ptrtmp, width*height*depth); delete [] ptrtmp; return; } else { UnifyMaximumValue(1); } // // // PROBLEM SIZED WORK OCCURS BEYOND THIS POINT // If you add (or remove) collective calls below this point, make sure to // put matching sequence into bypass code above // // avtSamplePointCommunicator communicator; avtImagePartition partition(width, height, PAR_Size(), PAR_Rank()); communicator.SetImagePartition(&partition); bool doDistributedResample = false; #ifdef PARALLEL doDistributedResample = atts.GetDistributedResample(); #endif if (doDistributedResample) { partition.SetShouldProduceOverlaps(true); avtDataObject_p dob; CopyTo(dob, samples); communicator.SetInput(dob); samples = communicator.GetTypedOutput(); } // Always set up an arbitrator, even if user selected random. bool arbLessThan = !atts.GetUseArbitrator() || atts.GetArbitratorLessThan(); std::string arbName = atts.GetArbitratorVarName(); if (arbName == "default") arbName = primaryVariable; extractor.SetUpArbitrator(arbName, arbLessThan); // // Since this is Execute, forcing an update is okay... // samples->Update(GetGeneralContract()); if (samples->GetInfo().GetValidity().HasErrorOccurred()) { GetOutput()->GetInfo().GetValidity().ErrorOccurred(); GetOutput()->GetInfo().GetValidity().SetErrorMessage( samples->GetInfo().GetValidity().GetErrorMessage()); } // // Create a rectilinear dataset that is stretched according to the // original bounds. // int width_start = 0; int width_end = width; int height_start = 0; int height_end = height; if (doDistributedResample) { partition.GetThisPartition(width_start, width_end, height_start, height_end); width_end += 1; height_end += 1; } // // If we have more processors than domains, we have to handle that // gracefully. Communicate how many variables there are so that those // that don't have data can play well. // int realVars = samples->GetNumberOfRealVariables(); int numArrays = realVars; if (doKernel) numArrays++; vtkDataArray **vars = new vtkDataArray*[numArrays]; for (i = 0 ; i < numArrays ; i++) { vars[i] = vtkDoubleArray::New(); if (doKernel && (i == numArrays-1)) vars[i]->SetNumberOfComponents(1); else { vars[i]->SetNumberOfComponents(samples->GetVariableSize(i)); vars[i]->SetName(samples->GetVariableName(i).c_str()); } } if (doKernel) samples->GetVolume()->SetUseKernel(true); avtImagePartition *ip = NULL; if (doDistributedResample) ip = &partition; // We want all uncovered regions to get the default value. That is // what the first argument of GetVariables is for. But if the // default value is large, then it will screw up the collect call below, // which uses MPI_MAX for an all reduce. So give uncovered regions very // small values now (-FLT_MAX) and then replace them later. double defaultPlaceholder = -FLT_MAX; samples->GetVolume()->GetVariables(defaultPlaceholder, vars, numArrays, ip); if (!doDistributedResample) { // // Collect will perform the parallel collection. Does nothing in // serial. This will only be valid on processor 0. // for (i = 0 ; i < numArrays ; i++) { double *ptr = (double *) vars[i]->GetVoidPointer(0); Collect(ptr, vars[i]->GetNumberOfComponents()*width*height*depth); } } // Now replace the -FLT_MAX's with the default value. (See comment above.) for (i = 0 ; i < numArrays ; i++) { int numTups = vars[i]->GetNumberOfComponents() * vars[i]->GetNumberOfTuples(); if (numTups > 0) { double *ptr = (double *) vars[i]->GetVoidPointer(0); for (j = 0 ; j < numTups ; j++) ptr[j] = (ptr[j] == defaultPlaceholder ? atts.GetDefaultVal() : ptr[j]); } } bool iHaveData = false; if (doDistributedResample) iHaveData = true; if (PAR_Rank() == 0) iHaveData = true; if (height_end > height) iHaveData = false; if (iHaveData) { vtkRectilinearGrid *rg = CreateGrid(bounds, width, height, depth, width_start, width_end, height_start, height_end, cellCenteredOutput, is3D); if (doKernel) { double min_weight = avtPointExtractor::GetMinimumWeightCutoff(); vtkDataArray *weights = vars[numArrays-1]; int numVals = weights->GetNumberOfTuples(); for (i = 0 ; i < realVars ; i++) { for (j = 0 ; j < vars[i]->GetNumberOfComponents() ; j++) { for (k = 0 ; k < numVals ; k++) { double weight = weights->GetTuple1(k); if (weight <= min_weight) vars[i]->SetComponent(k, j, atts.GetDefaultVal()); else vars[i]->SetComponent(k, j, vars[i]->GetComponent(k, j) / weight); } } } } // // Attach these variables to our rectilinear grid. // for (i = 0 ; i < realVars ; i++) { const char *varname = vars[i]->GetName(); if (strcmp(varname, primaryVariable) == 0) { if (vars[i]->GetNumberOfComponents() == 3) if (cellCenteredOutput) rg->GetCellData()->SetVectors(vars[i]); else rg->GetPointData()->SetVectors(vars[i]); else if (vars[i]->GetNumberOfComponents() == 1) { if (cellCenteredOutput) { rg->GetCellData()->AddArray(vars[i]); rg->GetCellData()->SetScalars(vars[i]); } else { rg->GetPointData()->AddArray(vars[i]); rg->GetPointData()->SetScalars(vars[i]); } } else { if (cellCenteredOutput) rg->GetCellData()->AddArray(vars[i]); else rg->GetPointData()->AddArray(vars[i]); } } else { if (cellCenteredOutput) rg->GetCellData()->AddArray(vars[i]); else rg->GetPointData()->AddArray(vars[i]); } } avtDataTree_p tree = new avtDataTree(rg, 0); rg->Delete(); SetOutputDataTree(tree); } else { // // Putting in a NULL data tree can lead to seg faults, etc. // avtDataTree_p dummy = new avtDataTree(); SetOutputDataTree(dummy); } for (i = 0 ; i < numArrays ; i++) { vars[i]->Delete(); } delete [] vars; }
void QgsGrassNewMapset::drawRegion() { QPixmap pm = mPixmap; mRegionMap->setPixmap( pm ); if ( mCellHead.proj == PROJECTION_XY ) return; QgsDebugMsg( QString( "pm.isNull() = %1" ).arg( pm.isNull() ) ); QPainter p( &pm ); p.setPen( QPen( QColor( 255, 0, 0 ), 3 ) ); double n = mNorthLineEdit->text().toDouble(); double s = mSouthLineEdit->text().toDouble(); double e = mEastLineEdit->text().toDouble(); double w = mWestLineEdit->text().toDouble(); // Shift if LL and W > E if ( mCellHead.proj == PROJECTION_LL && w > e ) { if (( 180 - w ) < ( e + 180 ) ) { w -= 360; } else { e += 360; } } QList<QgsPoint> tpoints; // ll lr ur ul ll tpoints << QgsPoint( w, s ); tpoints << QgsPoint( e, s ); tpoints << QgsPoint( e, n ); tpoints << QgsPoint( w, n ); tpoints << QgsPoint( w, s ); // Because of possible shift +/- 360 in LL we have to split // the lines at least in 3 parts QList<QgsPoint> points; // for ( int i = 0; i < 4; i++ ) { for ( int j = 0; j < 3; j++ ) { double x = tpoints[i].x(); double y = tpoints[i].y(); double dx = ( tpoints[i+1].x() - x ) / 3; double dy = ( tpoints[i+1].y() - y ) / 3; QgsDebugMsg( QString( "dx = %1 x = %2" ).arg( dx ).arg( x + j*dx ) ); points << QgsPoint( x + j*dx, y + j*dy ); } } points << points[0]; // close polygon // Warning: seems that crashes if source == dest if ( mProjectionSelector->selectedCrsId() != GEOCRS_ID ) { QgsCoordinateReferenceSystem source = QgsCoordinateReferenceSystem::fromSrsId( mProjectionSelector->selectedCrsId() ); if ( !source.isValid() ) { QgsGrass::warning( tr( "Cannot create QgsCoordinateReferenceSystem" ) ); return; } QgsCoordinateReferenceSystem dest = QgsCoordinateReferenceSystem::fromSrsId( GEOCRS_ID ); if ( !dest.isValid() ) { QgsGrass::warning( tr( "Cannot create QgsCoordinateReferenceSystem" ) ); return; } QgsCoordinateTransform trans( source, dest ); for ( int i = points.size() - 1; i >= 0; i-- ) { // Warning: I found that with some projections (e.g. Abidjan 1987) // if N = 90 or S = -90 the coordinate projected to // WGS84 is nonsense (156.983,89.9988 regardless x) -> // use 89.9 - for draw it is not so important if ( mCellHead.proj == PROJECTION_LL ) { if ( points[i].y() >= 89.9 ) points[i].setY( 89.9 ); if ( points[i].y() <= -89.9 ) points[i].setY( -89.9 ); } QgsDebugMsg( QString( "%1,%2" ).arg( points[i].x() ).arg( points[i].y() ) ); // exclude points if transformation failed try { points[i] = trans.transform( points[i] ); QgsDebugMsg( QString( " --> %1,%2" ).arg( points[i].x() ).arg( points[i].y() ) ); } catch ( QgsCsException &cse ) { Q_UNUSED( cse ); QgsDebugMsg( "Cannot transform point" ); points.removeAt( i ); } } if ( points.size() < 3 ) { QgsDebugMsg( "Cannot reproject region." ); return; } } for ( int shift = -360; shift <= 360; shift += 360 ) { for ( int i = 0; i < 12; i++ ) { double x1 = points[i].x(); double x2 = points[i+1].x(); if ( qAbs( x2 - x1 ) > 150 ) { if ( x2 < x1 ) { x2 += 360; } else { x2 -= 360; } } p.drawLine( 180 + shift + ( int )x1, 90 - ( int )points[i].y(), 180 + shift + ( int )x2, 90 - ( int )points[i+1].y() ); } } p.end(); mRegionMap->setPixmap( pm ); }
M1 & srk (M1 &m1, const T1 &t1, const T2 &t2, const M2 &m2) { return m1 = t1 * m1 + t2 * prod (m2, trans (m2)); }