Exemplo n.º 1
0
int main()
{
    freopen("numar4.in","r",stdin);
    freopen("numar4.out","w",stdout);
    scanf("%d %d",&ni,&nz);
    int i;
    a[0]=ni+nz;
    for(i=ni+nz; i>0; --i) scanf("%d",&a[i]);
    b[0]=nz+1; b[nz+1]=1;
    for(i=nz;i!=0 && a[1]%2==0;) {
        imp(a,2);
        imp(b,2);
        --i;
    }
    for(i=nz;i!=0 && a[1]%5==0;) {
        imp(a,5);
        imp(b,5);
        --i;
    }
    printf("%d\n",a[0]);
    afis(a);
    printf("\n%d\n",b[0]);
    afis(b);
    return 0;
}
Exemplo n.º 2
0
JSValue* JSSVGLength::getValueProperty(ExecState* exec, int token) const
{
    switch (token) {
    case UnitTypeAttrNum: {
        SVGLength imp(*impl());

        return jsNumber(imp.unitType());
    }
    case ValueAttrNum: {
        SVGLength imp(*impl());

        return jsNumber(imp.value());
    }
    case ValueInSpecifiedUnitsAttrNum: {
        SVGLength imp(*impl());

        return jsNumber(imp.valueInSpecifiedUnits());
    }
    case ValueAsStringAttrNum: {
        SVGLength imp(*impl());

        return jsString(imp.valueAsString());
    }
    case ConstructorAttrNum:
        return getConstructor(exec);
    }
    return 0;
}
Exemplo n.º 3
0
void JSSVGLength::putValueProperty(ExecState* exec, int token, JSValue* value, int /*attr*/)
{
    switch (token) {
    case ValueAttrNum: {
        SVGLength imp(*impl());

        imp.setValue(value->toFloat(exec));
        m_impl->commitChange(exec, imp);
        break;
    }
    case ValueInSpecifiedUnitsAttrNum: {
        SVGLength imp(*impl());

        imp.setValueInSpecifiedUnits(value->toFloat(exec));
        m_impl->commitChange(exec, imp);
        break;
    }
    case ValueAsStringAttrNum: {
        SVGLength imp(*impl());

        imp.setValueAsString(valueToStringWithNullCheck(exec, value));
        m_impl->commitChange(exec, imp);
        break;
    }
    }
    if (context())
        context()->notifyAttributeChange();
}
Exemplo n.º 4
0
int main(int argc, char** argv) {
 
   // lowpass response
   // cf = sr/10
   // trans bw = sr/10
   float max = 1.f;
   float min = 0.f;
   float cf = 0.1f;
   float tbw = 0.1f;
   
   // magnitude response curve
   float points[3]= {max,min,min};
   float lens[3]= {cf,tbw,1-(cf+tbw)};
   
   // using Hamming window
   // filter order = 3.33*sr/tbw
   int order = 333;
   HammingTable window(order, 0.54f);
   ImpulseTable imp(order,3, 1.f, points, lens, 0.f,&window); 
   
   // test signal wavetable
   HarmTable t1(1024, 50, SAW);
   SndWave  output("test.wav", OVERWRITE); /* output */
   Oscili oscil(&t1, 100.f, 32767.f);  /* test signal */
   Convol fil(&imp, &oscil, 16.f);  /* filter */

  int dur = 5;
  for(int i=0; i<dur*(DEF_SR/DEF_VECSIZE); i++) {
	oscil.DoProcess();
	fil.DoProcess();
	fil >> output;
  }
  return 0;
}
Exemplo n.º 5
0
JSValue* JSSVGMatrix::rotate(ExecState* exec, const ArgList& args)
{
    AffineTransform imp(*impl());

    float angle = args[0]->toFloat(exec);
    return toJS(exec, JSSVGPODTypeWrapperCreatorReadOnly<AffineTransform>::create(imp.rotate(angle)).get(), m_context.get());
}
Exemplo n.º 6
0
JSValue* JSSVGMatrix::multiply(ExecState* exec, const ArgList& args)
{
    AffineTransform imp(*impl());

    AffineTransform secondMatrix = toSVGMatrix(args[0]);    
    return toJS(exec, JSSVGPODTypeWrapperCreatorReadOnly<AffineTransform>::create(imp.multiply(secondMatrix)).get(), m_context.get());
}
Exemplo n.º 7
0
void MainWindow::writeGraphviz()
{
	QFileDialog dialog(this);
	dialog.setFileMode(QFileDialog::AnyFile);
	dialog.setNameFilter(tr("Graphviz file (*.gv)"));
	if(dialog.exec()) {
		QFile f(dialog.selectedFiles()[0]);
		f.open(QIODevice::WriteOnly | QIODevice::Text);
		QTextStream out(&f);
		GameBoard b(*gbw->gameBoard());

		QString fdir = QFileInfo(dialog.selectedFiles()[0]).dir().path();

		GraphGen::setPrepareImageCallback([&](const GameBoard& b, const std::string& fname) {
			QFile imfile(fdir + "/" + QString::fromStdString(fname) + ".png");
			if(!imfile.exists()) {
				QImage image(100, 100, QImage::Format_RGB888);
				QPainter imp(&image);

				GameBoardWidget::paintBoard(&b, imp);

				image.save(imfile.fileName());

				std::cout << "Wrote image " << imfile.fileName().toStdString() << std::endl;
			}
		});

		out << QString::fromStdString(GraphGen::graph(b, 3*2, 4));
	}
}
Exemplo n.º 8
0
QString Record::dump() const
{
	Table * t = table();
	QStringList keys, values;
	keys << (t ? t->tableName() : QString("Invalid Record")) + " @ 0x" + QString::number((quint64)mImp,16);
	values << stateString();
	if( t ) {
		QStringList fieldNames = t->schema()->fieldNames();
		fieldNames.sort();
		foreach( QString fieldName, fieldNames ) {
			Field * f = t->schema()->field(fieldName);
			QVariant v = imp()->isColumnSelected(f->pos()) ? getValue(f->pos()) : "NOT SELECTED";
			keys << f->name();
			if( f->type() == Field::Interval )
				values << v.value<Interval>().toString();
			else if( v.userType() == qMetaTypeId<Record>() && f->flag( Field::ForeignKey ) ) {
				Record r = v.value<Record>();
				if( r.isRecord() )
					values << QString::number(r.key());
				else
					values << "<Uncommitted " + r.table()->schema()->className() + " @ 0x" + QString::number((quint64)r.mImp,16) + ">";
			} else
				values << v.toString();
		}
	}
void LogoutMessageBox::paintEvent(QPaintEvent *event)
{
    QImage imp(":/images/exitBox");
    QPainter painter(this);
    painter.drawImage(0, 0, imp.scaled(this->size()));
    QMessageBox::paintEvent(event);
}
Exemplo n.º 10
0
JSValue* JSSVGLengthPrototypeFunction::callAsFunction(ExecState* exec, JSObject* thisObj, const List& args)
{
    if (!thisObj->inherits(&JSSVGLength::info))
      return throwError(exec, TypeError);

    JSSVGLength* castedThisObj = static_cast<JSSVGLength*>(thisObj);
    JSSVGPODTypeWrapper<SVGLength>* wrapper = castedThisObj->impl();
    SVGLength imp(*wrapper);

    switch (id) {
    case JSSVGLength::NewValueSpecifiedUnitsFuncNum: {
        unsigned short unitType = args[0]->toInt32(exec);
        float valueInSpecifiedUnits = args[1]->toFloat(exec);

        imp.newValueSpecifiedUnits(unitType, valueInSpecifiedUnits);
        wrapper->commitChange(exec, imp);

        if (castedThisObj->context())
            castedThisObj->context()->notifyAttributeChange();
        return jsUndefined();
    }
    case JSSVGLength::ConvertToSpecifiedUnitsFuncNum: {
        unsigned short unitType = args[0]->toInt32(exec);

        imp.convertToSpecifiedUnits(unitType);
        wrapper->commitChange(exec, imp);

        if (castedThisObj->context())
            castedThisObj->context()->notifyAttributeChange();
        return jsUndefined();
    }
    }
    return 0;
}
Exemplo n.º 11
0
JSValue* JSSVGMatrix::scaleNonUniform(ExecState* exec, const ArgList& args)
{
    AffineTransform imp(*impl());

    float scaleFactorX = args[0]->toFloat(exec);
    float scaleFactorY = args[1]->toFloat(exec);

    return toJS(exec, JSSVGPODTypeWrapperCreatorReadOnly<AffineTransform>::create(imp.scaleNonUniform(scaleFactorX, scaleFactorY)).get(), m_context.get());
}
    Impedance operator *(Impedance _imp) {
        //TODO: DRY this up
        std::complex<double> complex_impedance = \
                (std::complex<double>)1/(_imp.inverse() + this->inverse());

        Impedance imp(complex_impedance);

        return imp;
    }
Exemplo n.º 13
0
void plantilla::mover(char _char){
	gotox(x,y);cout<<" ";
	x--;
	if(x<2){
		y=rand()%30+4;
		x=99;
	}
	imp(_char);
}
Exemplo n.º 14
0
JSValue* JSSVGMatrix::inverse(ExecState* exec, const ArgList&)
{
    AffineTransform imp(*impl());
    KJS::JSValue* result = toJS(exec, JSSVGPODTypeWrapperCreatorReadOnly<AffineTransform>::create(imp.inverse()).get(), m_context.get());

    if (!imp.isInvertible())
        setDOMException(exec, SVGException::SVG_MATRIX_NOT_INVERTABLE);

    return result;
}
Exemplo n.º 15
0
JSValue* JSSVGLength::convertToSpecifiedUnits(ExecState* exec, const ArgList& args)
{
    JSSVGPODTypeWrapper<SVGLength>* wrapper = impl();

    SVGLength imp(*wrapper);
    imp.convertToSpecifiedUnits(args.at(exec, 0)->toInt32(exec), context());

    wrapper->commitChange(imp, context());
    return jsUndefined();
}
Exemplo n.º 16
0
void Environment::disableWallpaper(LogWriter *log)
{
  log->info(_T("Try to disable wallpaper"));
  Impersonator imp(log);
  AutoImpersonator ai(&imp, log);

  if (SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, _T(""), 0) == 0) {
    throw SystemException(_T("Cannot disable desktop wallpaper"));
  }
}
Exemplo n.º 17
0
void Environment::restoreWallpaper(LogWriter *log)
{
  // FIXME: Remove log from here. Log only from caller.
  log->info(_T("Try to restore wallpaper"));
  Impersonator imp(log);
  AutoImpersonator ai(&imp, log);

  if (SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, 0, 0) == 0) {
      throw SystemException(_T("Cannot restore desktop wallpaper"));
  }
}
Exemplo n.º 18
0
int main(void){
    celula *lista;
    celula cabeca;
    celula *invertida;

    lista = &cabeca;
    cabeca.pc = NULL;

    ins(1, lista);
    ins(2, lista);
    ins(3, lista);
    ins(4, lista);

    imp(lista);

    libera(lista);

    imp(lista);

}
Exemplo n.º 19
0
JSValue JSSVGMatrix::inverse(ExecState* exec)
{
    AffineTransform imp(*impl());

    SVGElement* context = JSSVGContextCache::svgContextForDOMObject(this);
    JSValue result = toJS(exec, globalObject(), JSSVGStaticPODTypeWrapper<AffineTransform>::create(imp.inverse()).get(), context);

    if (!imp.isInvertible())
        setDOMException(exec, SVGException::SVG_MATRIX_NOT_INVERTABLE);

    return result;
}
Exemplo n.º 20
0
void MainWindow::writeStateImage()
{
	QFileDialog dialog(this);
	dialog.setFileMode(QFileDialog::AnyFile);
	dialog.setNameFilter(tr("PNG image (*.png)"));
	if(dialog.exec()) {
		QImage image(512, 512, QImage::Format_RGB888);
		QPainter imp(&image);
		GameBoardWidget::paintBoard(gbw->gameBoard(), imp);
		image.save(dialog.selectedFiles()[0]);
	}
}
Exemplo n.º 21
0
void KVFAZIA::Build(Int_t)
{
   // Build the combined INDRA & FAZIA arrays
   GetGeometryParameters();
   GenerateCorrespondanceFile();

   if (!gGeoManager) {
      new TGeoManager("FAZIA", Form("FAZIA geometry for dataset %s", gDataSet->GetName()));

      TGeoMaterial* matVacuum = gGeoManager->GetMaterial("Vacuum");
      if (!matVacuum) {
         matVacuum = new TGeoMaterial("Vacuum", 0, 0, 0);
         matVacuum->SetTitle("Vacuum");
      }
      TGeoMedium* Vacuum = gGeoManager->GetMedium("Vacuum");
      if (!Vacuum) Vacuum = new TGeoMedium("Vacuum", 1, matVacuum);
      TGeoVolume* top = gGeoManager->MakeBox("WORLD", Vacuum,  500, 500, 500);
      gGeoManager->SetTopVolume(top);
   }

   BuildFAZIA();
   if (fBuildTarget)
      BuildTarget();

   KVGeoImport imp(gGeoManager, KVMaterial::GetRangeTable(), this, kTRUE);
   imp.SetDetectorPlugin(ClassName());
   imp.SetNameCorrespondanceList(fCorrespondanceFile.Data());
   // any additional structure name formatting definitions
   DefineStructureFormats(imp);

   // the following parameters are optimized for a 12-block compact
   // geometry placed at 80cm with rings 1-5 of INDRA removed.
   // make sure that the expected number of detectors get imported!
   imp.ImportGeometry(fImport_dTheta, fImport_dPhi, fImport_ThetaMin, fImport_PhiMin, fImport_ThetaMax, fImport_PhiMax);

   /*
   KVFAZIADetector* det=0;
   TIter next_d(GetDetectors());
   while ( det = (KVFAZIADetector* )next_d() ){
      printf("%s %s %d %d %d\n",det->GetName(),det->GetFAZIAType(),det->GetBlockNumber(),det->GetQuartetNumber(),det->GetTelescopeNumber());
   }
   */
   SetIdentifications();
   SortIDTelescopes();
   KVDetector* det = GetDetector("SI2-T1-Q1-B001");
   det->GetIDTelescopes()->ls();



   SetDetectorThicknesses();
   SetBit(kIsBuilt);
}
Exemplo n.º 22
0
JSValue* JSSVGMatrix::rotateFromVector(ExecState* exec, const ArgList& args)
{
    AffineTransform imp(*impl());
 
    float x = args[0]->toFloat(exec);
    float y = args[1]->toFloat(exec);

    KJS::JSValue* result = toJS(exec, JSSVGPODTypeWrapperCreatorReadOnly<AffineTransform>::create(imp.rotateFromVector(x, y)).get(), m_context.get());

    if (x == 0.0 || y == 0.0)
        setDOMException(exec, SVGException::SVG_INVALID_VALUE_ERR);

    return result;
}
Exemplo n.º 23
0
JSValue JSSVGMatrix::rotateFromVector(ExecState* exec)
{
    AffineTransform imp(*impl());

    float x = exec->argument(0).toFloat(exec);
    float y = exec->argument(1).toFloat(exec);

    SVGElement* context = JSSVGContextCache::svgContextForDOMObject(this);
    JSValue result = toJS(exec, globalObject(), JSSVGStaticPODTypeWrapper<AffineTransform>::create(imp.rotateFromVector(x, y)).get(), context);

    if (x == 0.0 || y == 0.0)
        setDOMException(exec, SVGException::SVG_INVALID_VALUE_ERR);

    return result;
}
Exemplo n.º 24
0
 void volume_polygonize(const XForm& xform, const Geometry::RGrid<float>& grid,
                        HMesh::Manifold& mani, float tau, bool make_triangles)
 {
     mani.clear();
     vector<Vec3d> quad_vertices;
     polygonize(xform, grid, quad_vertices, tau);
     vector<int> indices;
     vector<int> faces(quad_vertices.size()/4,4);
     for(int i=0;i<quad_vertices.size();++i)
         indices.push_back(i);
     build(mani, quad_vertices.size(),
                quad_vertices[0].get(),
                faces.size(),
                &faces[0],
                &indices[0]);
     
     stitch_more(mani, 1e-5);
     
     if(make_triangles)
         triangulate(mani);
     
     float avg_edge_len=0;
     for(HalfEdgeIDIterator h = mani.halfedges_begin(); h != mani.halfedges_end();++h)
         avg_edge_len += length(mani, *h);
     avg_edge_len /= mani.no_halfedges();
     VolumetricImplicit imp(xform, grid);
     for(int iter=0;iter<4;++iter)
     {
         TAL_smoothing(mani, .25, 1);
         
         for(auto v: mani.vertices())
             if(mani.in_use(v)) {
                 Vec3d p = mani.pos(v);
                 if(!std::isnan(p[0]))
                     imp.push_to_surface(p,0,avg_edge_len*0.5);
                 if(std::isnan(p[0]))
                     mani.remove_vertex(v);
                 else
                     mani.pos(v) = p;
         }
     }
     mani.cleanup();
     cout << "Produced " << mani.no_faces() << " faces " << endl;
 }
Exemplo n.º 25
0
bool EventList::SearchInContact(MCONTACT hContact, TCHAR *strFind, ComparatorInterface* compFun)
{
	InitFilters();

	if (useImportedMessages) {
		std::vector<IImport::ExternalMessage> messages;
		{
			mir_cslock lck(csEventList);
			std::map<MCONTACT, EventList::ImportDiscData>::iterator it = contactFileMap.find(hContact);
			if (it != contactFileMap.end()) {
				ExportManager imp(hWnd, hContact, 1);
				imp.SetAutoImport(it->second.file);
				if (!imp.Import(it->second.type, messages, NULL))
					messages.clear();
			}
		}

		for (int i = 0; i < (int)importedMessages.size(); ++i)
			if (compFun->Compare((importedMessages[i].flags & DBEF_SENT) != 0, importedMessages[i].message, strFind))
				return true;
	}

	std::list<EventTempIndex> tempList;
	GetTempList(tempList, false, true, hContact);

	EventIndex ei;
	EventData ed;
	TCHAR str[MAXSELECTSTR + 8]; // for safety reason
	for (std::list<EventTempIndex>::iterator itL = tempList.begin(); itL != tempList.end(); ++itL) {
		ei.isExternal = itL->isExternal;
		ei.hEvent = itL->hEvent;
		if (GetEventData(ei, ed)) {
			GetEventMessage(ei, str);
			if (compFun->Compare(ed.isMe, str, strFind))
				return true;
		}
	}

	return false;
}
Exemplo n.º 26
0
std::vector<FlowRecord>
TaintReachable::process(const ContextID ctxt, const ImmutableCallSite cs) const {
  DEBUG(errs() << "Using taint reachable signature for: " << *cs.getInstruction() << "\n");

  FlowRecord exp(false,ctxt,ctxt);
  FlowRecord imp(true,ctxt,ctxt);

  // implicit from the pc of the call site and the function pointer
  imp.addSourceValue(*cs->getParent());
  imp.addSourceValue(*cs.getCalledValue());

  // Sources and sinks of the args
  for (ImmutableCallSite::arg_iterator arg = cs.arg_begin(), end = cs.arg_end();
       arg != end; ++arg) {
      // every argument's value is a source
      exp.addSourceValue(**arg);
      // if the argument is a pointer, everything it reaches is a source
      // and everything it reaches is a sink
      if ((*arg)->getType()->isPointerTy()) {
	exp.addSourceReachablePtr(**arg);
	imp.addSourceValue(**arg);

	exp.addSinkReachablePtr(**arg);
	imp.addSinkReachablePtr(**arg);
      }
  }

  // if the function has a return value it is a sink
  if (!cs->getType()->isVoidTy()) {
    imp.addSinkValue(*cs.getInstruction());
    exp.addSinkValue(*cs.getInstruction());
  }

  std::vector<FlowRecord> flows;
  flows.push_back(imp);
  flows.push_back(exp);
  return flows;
}
Exemplo n.º 27
0
std::vector<FlowRecord>
OverflowChecks::process(const ContextID ctxt, const ImmutableCallSite cs) const {
  DEBUG(errs() << "Using OverflowChecks signature...\n");

  FlowRecord exp(false,ctxt,ctxt);
  FlowRecord imp(true,ctxt,ctxt);

  imp.addSourceValue(*cs->getParent());

  // Add all argument values as sources
  for (ImmutableCallSite::arg_iterator arg = cs.arg_begin(), end = cs.arg_end();
       arg != end; ++arg)
    exp.addSourceValue(**arg);
  assert(!cs->getType()->isVoidTy() && "Found 'void' overflow check?");

  // And the return value as a sink
  exp.addSinkValue(*cs.getInstruction());
  imp.addSinkValue(*cs.getInstruction());

  std::vector<FlowRecord> flows;
  flows.push_back(imp);
  flows.push_back(exp);
  return flows;
}
Exemplo n.º 28
0
smt_astt 
smt_convt::overflow_arith(const expr2tc &expr)
{
  // If in integer mode, this is completely pointless. Return false.
  if (int_encoding)
    return mk_smt_bool(false);

  const overflow2t &overflow = to_overflow2t(expr);
  const arith_2ops &opers = static_cast<const arith_2ops &>(*overflow.operand);
  assert(opers.side_1->type == opers.side_2->type);
  constant_int2tc zero(opers.side_1->type, BigInt(0));
  lessthan2tc op1neg(opers.side_1, zero);
  lessthan2tc op2neg(opers.side_2, zero);

  equality2tc op1iszero(opers.side_1, zero);
  equality2tc op2iszero(opers.side_2, zero);
  or2tc containszero(op1iszero, op2iszero);

  // Guess whether we're performing a signed or unsigned comparison.
  bool is_signed = (is_signedbv_type(opers.side_1) ||
                    is_signedbv_type(opers.side_2));

  if (is_add2t(overflow.operand)) {
    if (is_signed) {
      // Two cases: pos/pos, and neg/neg, which can over and underflow resp.
      // In pos/neg cases, no overflow or underflow is possible, for any value.
      constant_int2tc zero(opers.side_1->type, BigInt(0));

      lessthan2tc op1pos(zero, opers.side_1);
      lessthan2tc op2pos(zero, opers.side_2);
      and2tc both_pos(op1pos, op2pos);

      not2tc negop1(op1pos);
      not2tc negop2(op2pos);
      and2tc both_neg(negop1, negop2);

      implies2tc nooverflow(both_pos,
                            greaterthanequal2tc(overflow.operand, zero));
      implies2tc nounderflow(both_neg,
                            lessthanequal2tc(overflow.operand, zero));
      return convert_ast(not2tc(and2tc(nooverflow, nounderflow)));
    } else {
      // Just ensure the result is >= both operands.
      greaterthanequal2tc ge1(overflow.operand, opers.side_1);
      greaterthanequal2tc ge2(overflow.operand, opers.side_2);
      and2tc res(ge1, ge2);
      not2tc inv(res);
      return convert_ast(inv);
    }
  } else if (is_sub2t(overflow.operand)) {
    if (is_signed) {
      // Convert to be an addition
      neg2tc negop2(opers.side_2->type, opers.side_2);
      add2tc anadd(opers.side_1->type, opers.side_1, negop2);
      expr2tc add_overflows(new overflow2t(anadd));

      // Corner case: subtracting MIN_INT from many things overflows. The result
      // should always be positive.
      constant_int2tc zero(opers.side_1->type, BigInt(0));
      uint64_t topbit = 1ULL << (opers.side_1->type->get_width() - 1);
      constant_int2tc min_int(opers.side_1->type, BigInt(topbit));
      equality2tc is_min_int(min_int, opers.side_2);
      implies2tc imp(is_min_int, greaterthan2tc(overflow.operand, zero));
      return convert_ast(or2tc(add_overflows, is_min_int));
    } else {
      // Just ensure the result is >= the operands.
      lessthanequal2tc le1(overflow.operand, opers.side_1);
      lessthanequal2tc le2(overflow.operand, opers.side_2);
      and2tc res(le1, le2);
      not2tc inv(res);
      return convert_ast(inv);
    }
  } else {
    assert(is_mul2t(overflow.operand) && "unexpected overflow_arith operand");

    // Zero extend; multiply; Make a decision based on the top half.
    unsigned int sz = zero->type->get_width();
    smt_sortt boolsort = boolean_sort;
    smt_sortt normalsort = mk_sort(SMT_SORT_BV, sz, false);
    smt_sortt bigsort = mk_sort(SMT_SORT_BV, sz * 2, false);

    // All one bit vector is tricky, might be 64 bits wide for all we know.
    constant_int2tc allonesexpr(zero->type, BigInt((sz == 64)
                                                 ? 0xFFFFFFFFFFFFFFFFULL
                                                 : ((1ULL << sz) - 1)));
    smt_astt allonesvector = convert_ast(allonesexpr);

    smt_astt arg1_ext, arg2_ext;
    if (is_signed) {
      // sign extend top bits.
      arg1_ext = convert_ast(opers.side_1);
      arg1_ext = convert_sign_ext(arg1_ext, bigsort, sz - 1, sz);
      arg2_ext = convert_ast(opers.side_2);
      arg2_ext = convert_sign_ext(arg2_ext, bigsort, sz - 1, sz);
    } else {
      // Zero extend the top parts
      arg1_ext = convert_ast(opers.side_1);
      arg1_ext = convert_zero_ext(arg1_ext, bigsort, sz);
      arg2_ext = convert_ast(opers.side_2);
      arg2_ext = convert_zero_ext(arg2_ext, bigsort, sz);
    }

    smt_astt result = mk_func_app(bigsort, SMT_FUNC_BVMUL, arg1_ext, arg2_ext);

    // Extract top half.
    smt_astt toppart = mk_extract(result, (sz * 2) - 1, sz, normalsort);

    if (is_signed) {
      // It should either be zero or all one's; which depends on what
      // configuration of signs it had. If both pos / both neg, then the top
      // should all be zeros, otherwise all ones. Implement with xor.
      smt_astt op1neg_ast = convert_ast(op1neg);
      smt_astt op2neg_ast = convert_ast(op2neg);
      smt_astt allonescond =
        mk_func_app(boolsort, SMT_FUNC_XOR, op1neg_ast, op2neg_ast);
      smt_astt zerovector = convert_ast(zero);

      smt_astt initial_switch =
        mk_func_app(normalsort, SMT_FUNC_ITE, allonescond,
                    allonesvector, zerovector);

      // either value being zero means the top must be zero.
      smt_astt contains_zero_ast = convert_ast(containszero);
      smt_astt second_switch = mk_func_app(normalsort, SMT_FUNC_ITE,
                                           contains_zero_ast,
                                           zerovector,
                                           initial_switch);

      smt_astt is_eq =
        mk_func_app(boolsort, SMT_FUNC_EQ, second_switch, toppart);
      return mk_func_app(boolsort, SMT_FUNC_NOT, &is_eq, 1);
    } else {
      // It should be zero; if not, overflow
      smt_astt iseq =
        mk_func_app(boolsort, SMT_FUNC_EQ, toppart, convert_ast(zero));
      return mk_func_app(boolsort, SMT_FUNC_NOT, &iseq, 1);
    }
  }

  return NULL;
}
Exemplo n.º 29
0
/** Updates skidding status.
 *  \param dt Time step size.
 *  \param is_on_ground True if the kart is on ground.
 *  \param steering Raw steering of the kart [-1,1], i.e. not adjusted by
 *               the kart's max steering angle.
 *  \param skidding  True if the skid button is pressed.
 */
void Skidding::update(float dt, bool is_on_ground, 
                      float steering, KartControl::SkidControl skidding)
{
    // If a kart animation is shown, stop all skidding bonuses.
    if(m_kart->getKartAnimation())
    {
        reset();
        return;
    }
    m_skid_bonus_ready = false;
    if (is_on_ground)
    {
        if((fabs(steering) > 0.001f) && 
            m_kart->getSpeed()>m_min_skid_speed &&
            (skidding==KartControl::SC_LEFT||skidding==KartControl::SC_RIGHT))
        {
            m_skid_factor +=  m_skid_increase *dt/m_time_till_max_skid;
        }
        else if(m_skid_factor>1.0f)
        {
            m_skid_factor *= m_skid_decrease;
        }
    }
    else
    {
        m_skid_factor = 1.0f; // Lose any skid factor as soon as we fly
    }

    if(m_skid_factor>m_skid_max)
        m_skid_factor = m_skid_max;
    else 
        if(m_skid_factor<1.0f) m_skid_factor = 1.0f;

    // FIXME hiker: remove once the new skidding code is finished.
    if(m_skid_state == SKID_OLD)
    {
        updateSteering(steering, dt);
        return;
    }

    // If skidding was started and a graphical jump should still
    // be displayed, update the data
    if(m_remaining_jump_time>0)
    {
        m_jump_speed -= World::getWorld()->getTrack()->getGravity()*dt;
        m_gfx_jump_offset += m_jump_speed * dt;
        m_remaining_jump_time -= dt;
        if(m_remaining_jump_time<0)
        {
            m_remaining_jump_time = 0.0f;
            m_gfx_jump_offset     = 0.0f;
        }
    }

    // This is only reached if the new skidding is enabled
    // ---------------------------------------------------

    // There are four distinct states related to skidding, controlled
    // by m_skid_state:
    // SKID_NONE: no skidding is happening. From here SKID_ACCUMULATE
    //    is reached when the skid key is pressed.
    // SKID_ACCUMULATE_{LEFT,RIGHT}:
    //    The kart is still skidding. The skidding time will be
    //    accumulated in m_skid_time, and once the minimum time for a 
    //    bonus is reached, the "bonus gfx now available" gfx is shown.
    //    If the skid button is not pressed anymore, this will trigger
    //    a potential bonus. Also the rotation of the physical body to 
    //    be in synch with the graphical kart is started (which is 
    //    independently handled in the kart physics). 
    // SKID_SHOW_GFX_{LEFT<RIGHT}
    //    Shows the skidding gfx while the bonus is available.
    // FIXME: what should we do if skid key is pressed while still in 
    //   SKID_SHOW_GFX??? Adjusting the body rotation is difficult.
    //   For now skidding will only start again once SKID_SHOW_GFX
    //   is changed to SKID_NONE.
    switch(m_skid_state)
    {
    case SKID_NONE: 
        {
            if(skidding!=KartControl::SC_LEFT &&
                skidding!=KartControl::SC_RIGHT)
                break;
            // Don't allow skidding while the kart is (apparently)
            // still in the air, or when the kart is too slow
            if(m_remaining_jump_time>0 ||
                m_kart->getSpeed() <m_min_skid_speed) break;

            m_skid_state = skidding==KartControl::SC_RIGHT 
                         ? SKID_ACCUMULATE_RIGHT
                         : SKID_ACCUMULATE_LEFT;
            // Add a little jump to the kart. Determine the vertical speed 
            // necessary for the kart to go 0.5*jump_time up (then it needs
            // the same time to come down again), based on v = gravity * t.
            // Then use this speed to determine the impulse necessary to 
            // reach this speed.
            float v = World::getWorld()->getTrack()->getGravity() 
                    * 0.5f*m_physical_jump_time;
            btVector3 imp(0, v / m_kart->getBody()->getInvMass(),0);
            m_kart->getVehicle()->getRigidBody()->applyCentralImpulse(imp);

            // Some karts might use a graphical-only jump. Set it up:
            m_jump_speed = World::getWorld()->getTrack()->getGravity() 
                         * 0.5f*m_graphical_jump_time;
            m_remaining_jump_time = m_graphical_jump_time;
             
#ifdef SKID_DEBUG
#define SPEED 20.0f
            updateSteering(steering, dt);
            m_actual_curve->clear();
            m_actual_curve->setVisible(true);
            m_predicted_curve->clear();
            m_predicted_curve->setVisible(true);
            m_predicted_curve->setPosition(m_kart->getXYZ());
            m_predicted_curve->setHeading(m_kart->getHeading());
            float angle = m_kart->getKartProperties()
                                ->getMaxSteerAngle(m_kart->getSpeed())
                        * fabsf(getSteeringFraction());
            angle = m_kart->getKartProperties()
                                ->getMaxSteerAngle(SPEED)
                        * fabsf(getSteeringFraction());
            float r = m_kart->getKartProperties()->getWheelBase()
                   / asin(angle)*1.0f;

            const int num_steps = 50;

            float dx = 2*r / num_steps;

            for(float x = 0; x <=2*r; x+=dx)
            {
                float real_x = m_skid_state==SKID_ACCUMULATE_LEFT ? -x : x;
                Vec3 xyz(real_x, 0.2f, sqrt(r*r-(r-x)*(r-x))*(1.0f+SPEED/150.0f)
                          *(1+(angle/m_kart->getKartProperties()->getMaxSteerAngle(SPEED)-0.6f)*0.1f));
                Vec3 xyz1=m_kart->getTrans()(xyz);
                printf("predict %f %f %f speed %f angle %f\n", 
                    xyz1.getX(), xyz1.getY(), xyz1.getZ(),
                    m_kart->getSpeed(), angle);
                m_predicted_curve->addPoint(xyz);
            }

#endif
            m_skid_time  = 0;   // fallthrough
        }
    case SKID_ACCUMULATE_LEFT:
    case SKID_ACCUMULATE_RIGHT:
        {
#ifdef SKID_DEBUG
            Vec3 v=m_kart->getVelocity();
            if(v.length()>5)
            {
                float r = SPEED/sqrt(v.getX()*v.getX() + v.getZ()*v.getZ());
                v.setX(v.getX()*r);
                v.setZ(v.getZ()*r);
                m_kart->getBody()->setLinearVelocity(v);

            }

            m_actual_curve->addPoint(m_kart->getXYZ());
            printf("actual %f %f %f turn %f speed %f angle %f\n",
                m_kart->getXYZ().getX(),m_kart->getXYZ().getY(),m_kart->getXYZ().getZ(),
                m_real_steering, m_kart->getSpeed(), 
                m_kart->getKartProperties()->getMaxSteerAngle(m_kart->getSpeed()));
#endif
            m_skid_time += dt;
            float bonus_time, bonus_speed, bonus_force;
            unsigned int level = getSkidBonus(&bonus_time, &bonus_speed,
                                              &bonus_force);
            // If at least level 1 bonus is reached, show appropriate gfx
            if(level>0) 
            {
                m_skid_bonus_ready = true;
                m_kart->getKartGFX()->setSkidLevel(level);
            }
            // If player stops skidding, trigger bonus, and change state to
            // SKID_SHOW_GFX_*
            if(skidding == KartControl::SC_NONE)
            {
                m_skid_state = m_skid_state == SKID_ACCUMULATE_LEFT 
                             ? SKID_SHOW_GFX_LEFT
                             : SKID_SHOW_GFX_RIGHT;
                float t = std::min(m_skid_time, m_skid_visual_time);
                t       = std::min(t,           m_skid_revert_visual_time);

                float vso = getVisualSkidRotation();
                btVector3 rot(0, vso*m_post_skid_rotate_factor, 0);
                m_kart->getVehicle()->setTimedRotation(t, rot);
                // skid_time is used to count backwards for the GFX
                m_skid_time = t;
                if(bonus_time>0)
                {
                    m_kart->getKartGFX()
                          ->setCreationRateRelative(KartGFX::KGFX_SKID, 1.0f);
                    m_kart->m_max_speed->
                        instantSpeedIncrease(MaxSpeed::MS_INCREASE_SKIDDING,
                                             bonus_speed, bonus_speed,
                                             bonus_force, bonus_time, 
                                             /*fade-out-time*/ 1.0f);
                }
                else
                    m_kart->getKartGFX()
                          ->setCreationRateAbsolute(KartGFX::KGFX_SKID, 0);
            }
            break;
        }   // case
    case SKID_SHOW_GFX_LEFT:
    case SKID_SHOW_GFX_RIGHT:
        m_skid_time -= dt;
        if(m_skid_time<=0)
        {
            m_skid_time = 0;
            m_kart->getKartGFX()
                  ->setCreationRateAbsolute(KartGFX::KGFX_SKID, 0);
            m_skid_state = SKID_NONE;
        }
    }   // switch
    updateSteering(steering, dt);
}   // update
Exemplo n.º 30
0
pss_select::pss_select(const expr_list &list) : expr(list) {
	imp().ptr()->setOp(ExprImp::GraphSelect);
}