Esempio n. 1
0
int main()
{
    Liste l1=Exemple1();
    Liste l2=Exemple2();
    printf("Liste1 de 7 elements :\n");
    afficherliste(l1);
    printf("Liste2 de 6 elements :\n");
    afficherliste(l2);


    Arbin a1=la(l1);
    Arbin a2=la(l2);
    printf("Affichage de l'arbre1\n");
    afficherArbre(a1);
    printf("Affichage de l'arbre2\n");
    afficherArbre(a2);
    printf("\n");

    Liste l3=al(a1);
    printf("al sur arbre1 :\n");
    afficherliste(l3);

    Arbin u0=union0(a1,a2);
    Arbin u1=union1(a1,a2);

    printf("Affichage de union0 :\n");
    afficherArbre(u0);

    printf("Affichage de union1 :\n");
    afficherArbre(u1);

    printf("Oter le minimum de l'arbre1\n");
    Arbin o=om(a1);
    afficherArbre(o);

    Arbin i=ins(a1,42);
    printf("Insertion de 42 dans l'arbre1\n");
    afficherArbre(i);

    freeListe(l1);
    freeListe(l2);
    freeListe(l3);

    freeArbre(a1);
    freeArbre(a2);
    freeArbre(u0);
    freeArbre(u1);
    freeArbre(o);
    freeArbre(i);


    return 0;
}
Esempio n. 2
0
void
MainWindow::open(QString fileName)
{
    std::ifstream ifs(qPrintable(fileName));
    char c;
    double x,y;
    Segment_2 s;
    
    while(ifs >> c){
      if(c == 's'){
	ifs >> x >> y;
	Point_2 p(x,y);
	ifs >> x >> y;
	Point_2 q(x,y);
	
	Line_arc_2 la(Segment_2(p,q));
	for(std::vector<CGAL::Object>::iterator it = arcs.begin(); it != arcs.end(); ++it){
	  Circular_arc_2 vca;
	  Line_arc_2 vla;
	  if(assign(vca, *it)){
	    CGAL::intersection(la, vca, std::back_inserter(intersections));
	  } else if(assign(vla, *it)){
	    CGAL::intersection(la, vla, std::back_inserter(intersections));
	  }
	}
	arcs.push_back(make_object(la));
      } else if(c == 'c'){
Esempio n. 3
0
int* alltmera(int kryddnejlika, std::string* krympning) {
  if (kryddnejlika > 3 || *krympning == "kugg")
    return new int (29408);
  int krypta = kryddnejlika + 1;
  std::string* kula = new std::string("kulmen");
  int* kullerbytta = ann(krypta, kula);
  std::string* kulspruta = new std::string("kundmottagning");
  int* kunde = allmoge(krypta, kulspruta);
  std::string* kung = new std::string("kunnat");
  int* kunna = anskaffning(krypta, kung);
  std::string kunskapsutveckling("kupering");
  int kupa = annanstans(&krypta, kunskapsutveckling);
  std::string kurva("kvar");
  std::string* kvadd = alltihop(&krypta, kurva);
  std::string* kvarleva = new std::string("kvarvarande");
  int* kvarn = anskaffning(krypta, kvarleva);
  std::string* kvinna = new std::string("kyrka");
  int* kyckling = adressering(krypta, kvinna);
  std::string kyrkoherde("l");
  int kyss = anslutningspropp(0, kyrkoherde);
  std::string la("lada");
  int labb = annanstans(&krypta, la);
  int* laddning = new int(14289);
  return laddning;
} // alltmera
Esempio n. 4
0
int main() {
	string code = getText();
	list<Token> tokens;
	LexicalAnalyzer la(code);

	// Lines 18-28: tokenize the entire text, store in tokens list
	while (!la.analyzed()) {
		tokens.push_back(la.lexer());
	}
	la.initKnownTokenTypes(tokens);

	Fsm typeSetter;
	for (auto it = tokens.begin(); it != tokens.end(); ++it) {
		typeSetter.identify(*it);
	}
	if (tokens.back().lexeme() == "") { tokens.back().type("eof"); }
	else { tokens.push_back(Token("", "eof")); }
	
	SyntaxAnalyzer sa(tokens);
	sa.analyze();

	//display(tokens);

	system("pause");
	return 0;
}
Esempio n. 5
0
rc_t fullPipelineTest(ss_m* ssm, test_volume_t* test_vol)
{
    unsigned howManyToInsert = 1000;
    W_DO(populateBtree(ssm, test_vol, howManyToInsert));

    LogArchiver::LogConsumer cons(lsn_t(1,0), BLOCK_SIZE);
    LogArchiver::ArchiverHeap heap(BLOCK_SIZE);
    LogArchiver::ArchiveDirectory dir(test_env->archive_dir, BLOCK_SIZE);
    LogArchiver::BlockAssembly assemb(&dir);

    LogArchiver la(&dir, &cons, &heap, &assemb);
    la.fork();
    la.activate(lsn_t::null, true /* wait */);

    // nextLSN of consumer tells us that all logrecs up (and excluding) that
    // LSN were added to the heap. When shutdown is invoked, heap is then emptied
    // using the selection method, thus also gauaranteeing that the archive is persistent
    // up to nextLSN
    while (cons.getNextLSN() < ssm->log->durable_lsn()) {
        usleep(1000); // 1ms
    }

    la.shutdown();
    la.join();

    // TODO use archive scanner to verify:
    // 1) integrity of archive
    // 2) if no logrecs are missing (scan log with same ignores as log archiver
    // and check if each logrec is in archiver -- random access, NL join)

    return RCOK;
}
Esempio n. 6
0
void
ResolvedMethod::makeParameterList(TR::ResolvedMethodSymbol *methodSym)
   {
   ListAppender<TR::ParameterSymbol> la(&methodSym->getParameterList());
   TR::ParameterSymbol *parmSymbol;
   int32_t slot = 0;
   int32_t ordinal = 0;

   uint32_t parmSlots = numberOfParameterSlots();
   for (int32_t parmIndex = 0; parmIndex < parmSlots; ++parmIndex)
      {
      TR::IlType *type = _parmTypes[parmIndex];
      TR::DataType dt = type->getPrimitiveType();
      int32_t size = methodSym->convertTypeToSize(dt);

      parmSymbol = methodSym->comp()->getSymRefTab()->createParameterSymbol(methodSym, slot, type->getPrimitiveType(), false);
      parmSymbol->setOrdinal(ordinal++);

      char *s = type->getSignatureName();
      uint32_t len = strlen(s);
      parmSymbol->setTypeSignature(s, len);

      la.add(parmSymbol);

      ++slot;
      }

   int32_t lastInterpreterSlot = slot + numberOfTemps();
   methodSym->setTempIndex(lastInterpreterSlot, methodSym->comp()->fe());
   methodSym->setFirstJitTempIndex(methodSym->getTempIndex());
   }
Esempio n. 7
0
Arbin union0(Arbin a1,Arbin a2)
{
    Liste l1=al(a1);
    Liste l2=al(a2);
    Liste l=concat(l1,l2);
    Arbin a=la(l);
    freeListe(l);
    freeListe(l1);
    freeListe(l2);
    return a;
}
Esempio n. 8
0
void glpk_wrapper::set_objective(Enode * const e) {
    assert(is_expr_linear(e));
    LAExpression la(e);
    for (auto it = la.begin(); it != la.end(); ++it) {
        auto v = it->first;
        auto c = it->second;
        if (v != nullptr) {
            glp_set_obj_coef(lp, get_index(v) + 1, c);
        }
    }
}
Esempio n. 9
0
int main(int argc, char *argv[])
{
    SockStream  addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(uport);

    LoggingAcceptor la(addr);
    for(;;)
        InitiationDispatcher::Instance()->HandleEvents();
    return 0;
}
Esempio n. 10
0
static void do_import(SExpressionHashPackage *pkg,
                      const SReference &a,
                      const SReference &d)
{
    SReference la(a);
    if(!pkg->Import(la)) {
        throw IntelibX_package_conflict(a);
    }
    if(d.IsEmptyList()) return;
    SExpressionCons *dp = d.DynamicCastGetPtr<SExpressionCons>();
    INTELIB_ASSERT(dp, IntelibX_not_a_list(d));
    do_import(pkg, dp->Car(), dp->Cdr());
}
Point intersection(Segment a,Segment b)
{
	line la(a) ,lb(b);
	Point res = la.intersect(lb);
	if (res == Point::NaP)
		return res;
	if (res == Point::INFP)
		if ((a.x.x >= min(b.x.x,b.y.x))&&(a.x.x <= max(b.x.x,b.y.x)))
			return a.x;
		else
			return a.y;
	if (res.x <= min(max(a.x.x,a.y.x),max(b.x.x,b.y.x)) &&  res.x >= max(min(a.x.x,a.y.x),min(b.x.x,b.y.x)) 
	&&  res.y <= min(max(a.x.y,a.y.y),max(b.x.y,b.y.y)) &&  res.y >= max(min(a.x.y,a.y.y),min(b.x.y,b.y.y)))
		return res;
	return Point::NaP;
};
Esempio n. 12
0
void Agent::vmTick() {
	// Tick the VM associated with this agent.
	
	assert(vm); // There must *be* a VM to tick.
	LifeAssert la(this); // sanity check

	// If we're out of timeslice, give ourselves some more (depending on the game type).
	if (!vm->timeslice) {
		vm->timeslice = (engine.version < 3) ? 1 : 5;
	}

	// Keep trying to run VMs while we don't run out of timeslice, end up with a blocked VM, or a VM stops.
	while (vm && vm->timeslice && !vm->isBlocking() && !vm->stopped()) {
		assert(vm->timeslice > 0);

		// Tell the VM to tick (using all available timeslice), catching exceptions as necessary.
		try {
			vm->tick();
		} catch (invalidAgentException &e) {
			// try letting the exception script handle it
			if (!queueScript(255))
				unhandledException(e.prettyPrint(), true);
			else
				stopScript(); // we still want current script to die
		} catch (creaturesException &e) {
			unhandledException(e.prettyPrint(), true);
		} catch (std::exception &e) {
			unhandledException(e.what(), true);
		}
		
		// If the VM stopped, it's done.
		if (vm && vm->stopped()) {
			world.freeVM(vm);
			vm = NULL;
		}
	}

	// Zot any remaining timeslice, since we're done now.
	if (vm) vm->timeslice = 0;
	
	// If there's no current VM but there's one on the call stack, a previous VM must have finished,
	// pop one from the call stack to run next time.
	if (!vm && !vmstack.empty()) {
		vm = vmstack.front();
		vmstack.pop_front();
	}
}
Esempio n. 13
0
void Menu::display(float /*t*/, float /*dt*/)
{
	// 3D: Background.
	video.clearScreen();

	video.set3D();

	glDisable(GL_FOG);

	glColor4f(1.0f, 1.0f, 1.0f, 1.0f);

	Vec4D la(0.1f, 0.1f, 0.1f, 1.0f);
	glLightModelfv(GL_LIGHT_MODEL_AMBIENT, la);

	glEnable(GL_COLOR_MATERIAL);
	glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
	glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
	for (OpenGL::Light light = GL_LIGHT0; light < GL_LIGHT0 + 8; ++light)
	{
		glLightf(light, GL_CONSTANT_ATTENUATION, 0.0f);
		glLightf(light, GL_LINEAR_ATTENUATION, 0.7f);
		glLightf(light, GL_QUADRATIC_ATTENUATION, 0.03f);
		glDisable(light);
	}

	glEnable(GL_CULL_FACE);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);
	glEnable(GL_LIGHTING);
	glEnable(GL_TEXTURE_2D);

	mBackgroundModel.get()->cam.setup(globalTime);
	mBackgroundModel.get()->draw();

	glDisable(GL_TEXTURE_2D);
	glDisable(GL_LIGHTING);
	glDisable(GL_DEPTH_TEST);
	glDisable(GL_CULL_FACE);

	// 2D: UI.

	video.set2D();
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	mGUIFrame->render();
}
Esempio n. 14
0
void glpk_wrapper::set_constraint(int index, Enode * const e) {
    DREAL_LOG_INFO << "glpk_wrapper::set_constraint  " << e << " with " << e->getPolarity();
    assert(is_linear(e));
    changed = true;
    LAExpression la(e);
    auto vars = e->get_vars();
    auto s = vars.size();
    auto indices = new int[s + 1];
    auto values = new double[s + 1];
    int i = 1;
    for (auto it = la.begin(); it != la.end(); ++it) {
        auto v = it->first;
        double c = it->second;
        if (v != nullptr && c != 0.0) {
            DREAL_LOG_INFO << "glpk_wrapper::set_constraint " << c << " * " << v;
            indices[i] = get_index(v) + 1;
            values[i] = c;
            i += 1;
        } else {
            if (e->isEq()) {
                assert(!e->hasPolarity() || e->getPolarity() != l_False);
                DREAL_LOG_INFO << "glpk_wrapper::set_constraint == " << c;
                glp_set_row_bnds(lp, index, GLP_FX, -c, -c);
            } else {
                if (!e->hasPolarity() || e->getPolarity() != l_False) {
                    DREAL_LOG_INFO << "glpk_wrapper::set_constraint <= " << (-c);
                    glp_set_row_bnds(lp, index, GLP_UP, 0, -c);
                } else {
                    DREAL_LOG_INFO << "glpk_wrapper::set_constraint >= " << (-c);
                    glp_set_row_bnds(lp, index, GLP_LO, -c, 0);
                }
            }
        }
    }
    glp_set_mat_row(lp, index, i-1, indices, values);
    delete[] indices;
    delete[] values;
    // name the constraints (helps debugging)
    if (DREAL_LOG_INFO_IS_ON) {
        std::ostringstream stream;
        if (e->getPolarity() == l_False) {
            stream << "¬";
        }
        stream << e;
        glp_set_row_name(lp, index, stream.str().c_str());
    }
}
Esempio n. 15
0
Point
interiorMiterIntersection(Point p1, Point p2, Point p3,
                          double strokeWidth)
{
    Point va(p2-p1);
    Point vb(p3-p2);
    Point shiftA = 0.5 * strokeWidth * va.rotatedPI2().normalise();
    Point shiftB = 0.5 * strokeWidth * vb.rotatedPI2().normalise();
    if ( va.rotatedPI2() * vb >= 0.0 ) {
        // Left turn
        shiftA = -shiftA;
        shiftB = -shiftB;
    }
    EuclideanLine la(p1-shiftA,p2-shiftA);
    EuclideanLine lb(p2-shiftB,p3-shiftB);
    return intersection(la,lb);
}
Esempio n. 16
0
void DiagramLoader::load()
{
  LexicalAnalyzer la(url);
  la.scan();

  Parser parser (la.getTokens());
  parser.parse();
  string l =parser.getLabel();
  
  vector<Contour> c = parser.getContours();
  vector<Zone> z = parser.getZones();
  vector<Zone> sz = parser.getShadedZones();

  DiagramCreator dc (l, c,z,sz);
  
  diagram = dc.createDiagram();
}
Esempio n. 17
0
void glpk_wrapper::set_objective(Enode * const e) {
    changed = true;
    for (unsigned int i = 1; i <= domain.size(); i++) {
        glp_set_obj_coef(lp, i, 0);
    }
    if (e != nullptr) {
        assert(is_expr_linear(e));
        LAExpression la(e);
        for (auto it = la.begin(); it != la.end(); ++it) {
            auto v = it->first;
            auto c = it->second;
            if (v != nullptr) {
                glp_set_obj_coef(lp, get_index(v) + 1, c);
            }
        }
    }
}
Esempio n. 18
0
Point exteriorMiterIntersection(Point p1, Point p2, Point p3,
                                double strokeWidth)
{
    Point va(p2-p1);
    Point vb(p3-p2);
    Point shiftA = 0.5 * strokeWidth * va.rotatedPI2().normalise();
    Point shiftB = 0.5 * strokeWidth * vb.rotatedPI2().normalise();
    if ( va.rotatedPI2() * vb >= 0.0 ) {
        // Left turn
        shiftA = -shiftA;
        shiftB = -shiftB;
    }
    EuclideanLine la(p1+shiftA,p2+shiftA);
    EuclideanLine lb(p2+shiftB,p3+shiftB);
    Point result = intersection(la,lb);
    if (result.isInf()) {
        return p2;
    }
    return result;
}
Esempio n. 19
0
QString libkstartperf()
{
    QString lib;
    QString la_file = KStandardDirs::locate("module", "kstartperf.la");

    if (la_file.isEmpty())
    {
        // if no '.la' file could be found, fallback to a search for the .so file
        // in the standard KDE directories
        lib = KStandardDirs::locate("module","kstartperf.so");
	return lib;
    }

    // Find the name of the .so file by reading the .la file
    QFile la(la_file);
    if (la.open(QIODevice::ReadOnly))
    {
	QTextStream is(&la);
	QString line;

	while (!is.atEnd())
        {
	    line = is.readLine();
            if (line.left(15) == "library_names='")
            {
		lib = line.mid(15);
                int pos = lib.indexOf(' ');
                if (pos > 0)
		    lib = lib.left(pos);
	    }
	}

        la.close();
    }

    // Look up the actual .so file.
    lib = KStandardDirs::locate("module", lib);
    return lib;
}
Esempio n. 20
0
 UpdateFC(LibASS *ass) :
     ass(ass)
 {
     start();
     if (!wait(500))
     {
         QDialog d(QMPlay2GUI.mainW);
         d.setWindowTitle(QCoreApplication::applicationName());
         QLabel l(QObject::tr("Font cache is updating, please wait"));
         QProgressBar p;
         p.setRange(0, 0);
         QVBoxLayout la(&d);
         la.addWidget(&l);
         la.addWidget(&p);
         d.open();
         d.setMinimumSize(d.size());
         d.setMaximumSize(d.size());
         do
             el.processEvents(QEventLoop::ExcludeUserInputEvents | QEventLoop::WaitForMoreEvents);
         while (isRunning());
     }
 }
Esempio n. 21
0
rc_t runMergerFullTest(ss_m* ssm, test_volume_t* test_vol)
{
    unsigned howManyToInsert = 2000;
    W_DO(populateBtree(ssm, test_vol, howManyToInsert));

    LogArchiver::LogConsumer cons(lsn_t(1,0), BLOCK_SIZE);
    LogArchiver::ArchiverHeap heap(BLOCK_SIZE);
    LogArchiver::ArchiveDirectory dir(test_env->archive_dir, BLOCK_SIZE, false);
    LogArchiver::BlockAssembly assemb(&dir);

    LogArchiver la(&dir, &cons, &heap, &assemb);
    la.fork();
    la.activate(lsn_t::null, true /* wait */);
    // wait for logarchiver to consume up to durable LSN,
    while (cons.getNextLSN() < ssm->log->durable_lsn()) {
        usleep(1000); // 1ms
    }

    LogArchiver::ArchiveScanner::RunMerger* merger =
        buildRunMergerFromDirectory(dir);

    PageID prevPID = 0;
    lsn_t prevLSN = lsn_t::null;
    logrec_t* lr;
    while (merger->next(lr)) {
        EXPECT_TRUE(lr->valid_header(lr->lsn_ck()));
        EXPECT_TRUE(lr->pid() >= prevPID);
        EXPECT_TRUE(lr->lsn_ck() != prevLSN);
        prevPID = lr->pid();
        prevLSN = lr->lsn_ck();
    }

    la.shutdown();
    la.join();

    return RCOK;
}
/*
 * Receive callback for the /camera/depth_registered/points subscription
 */
std::vector<suturo_perception_msgs::PerceivedObject> SuturoPerceptionKnowledgeROSNode::receive_image_and_cloud(const sensor_msgs::ImageConstPtr& inputImage, const sensor_msgs::PointCloud2ConstPtr& inputCloud)
{
  // process only one cloud
  pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_in (new pcl::PointCloud<pcl::PointXYZRGB>());
  pcl::fromROSMsg(*inputCloud,*cloud_in);
  logger.logInfo((boost::format("Received a new point cloud: size = %s") % cloud_in->points.size()).str());

  // Gazebo sends us unorganized pointclouds!
  // Reorganize them to be able to compute the ROI of the objects
  // This workaround is only tested for gazebo 1.9!
  if(!cloud_in->isOrganized ())
  {
    logger.logInfo((boost::format("Received an unorganized PointCloud: %d x %d .Convert it to a organized one ...") % cloud_in->width % cloud_in->height ).str());

    pcl::PointCloud<pcl::PointXYZRGB>::Ptr org_cloud (new pcl::PointCloud<pcl::PointXYZRGB>());
    org_cloud->width = 640;
    org_cloud->height = 480;
    org_cloud->is_dense = false;
    org_cloud->points.resize(640 * 480);

    for (int i = 0; i < cloud_in->points.size(); i++) {
        pcl::PointXYZRGB result;
        result.x = 0;
        result.y = 0;
        result.z = 0;
        org_cloud->points[i]=cloud_in->points[i];
    }

    cloud_in = org_cloud;
  }
  
  cv_bridge::CvImagePtr cv_ptr;
  cv_ptr = cv_bridge::toCvCopy(inputImage, enc::BGR8);

  // Make a deep copy of the passed cv::Mat and set a new
  // boost pointer to it.
  boost::shared_ptr<cv::Mat> img(new cv::Mat(cv_ptr->image.clone()));
  sp.setOriginalRGBImage(img);
  
  logger.logInfo("processing...");
  sp.setOriginalCloud(cloud_in);
  sp.processCloudWithProjections(cloud_in);
  logger.logInfo("Cloud processed. Lock buffer and return the results");      

  mutex.lock();
  perceivedObjects = sp.getPerceivedObjects();

  if(sp.getOriginalRGBImage()->cols != sp.getOriginalCloud()->width
      && sp.getOriginalRGBImage()->rows != sp.getOriginalCloud()->height)
  {
    // Adjust the ROI if the image is at 1280x1024 and the pointcloud is at 640x480
    if(sp.getOriginalRGBImage()->cols == 1280 && sp.getOriginalRGBImage()->rows == 1024)
    {
      for (int i = 0; i < perceivedObjects.size(); i++) {
          ROI roi = perceivedObjects.at(i).get_c_roi();
          roi.origin.x*=2;
          roi.origin.y*=2;
          roi.width*=2;
          roi.height*=2;
          perceivedObjects.at(i).set_c_roi(roi);
      }
    }
    else
    {
      logger.logError("UNSUPPORTED MIXTURE OF IMAGE AND POINTCLOUD DIMENSIONS");
    }
  }
    
  // Execution pipeline
  // Each capability provides an enrichment for the
  // returned PerceivedObject
  
  // initialize threadpool
  boost::asio::io_service ioService;
  boost::thread_group threadpool;
  std::auto_ptr<boost::asio::io_service::work> work(new boost::asio::io_service::work(ioService));
  
  // Add worker threads to threadpool
  for(int i = 0; i < numThreads; ++i)
  {
    threadpool.create_thread(
      boost::bind(&boost::asio::io_service::run, &ioService)
      );
  }

  for (int i = 0; i < perceivedObjects.size(); i++) 
  {
    // Initialize Capabilities
    ColorAnalysis ca(perceivedObjects[i]);
    ca.setLowerSThreshold(color_analysis_lower_s);
    ca.setUpperSThreshold(color_analysis_upper_s);
    ca.setLowerVThreshold(color_analysis_lower_v);
    ca.setUpperVThreshold(color_analysis_upper_v);
    suturo_perception_shape_detection::RandomSampleConsensus sd(perceivedObjects[i]);
    //suturo_perception_vfh_estimation::VFHEstimation vfhe(perceivedObjects[i]);
    // suturo_perception_3d_capabilities::CuboidMatcherAnnotator cma(perceivedObjects[i]);
    // Init the cuboid matcher with the table coefficients
    suturo_perception_3d_capabilities::CuboidMatcherAnnotator cma(perceivedObjects[i], sp.getTableCoefficients() );

    // post work to threadpool
    ioService.post(boost::bind(&ColorAnalysis::execute, ca));
    ioService.post(boost::bind(&suturo_perception_shape_detection::RandomSampleConsensus::execute, sd));
    //ioService.post(boost::bind(&suturo_perception_vfh_estimation::VFHEstimation::execute, vfhe));
    ioService.post(boost::bind(&suturo_perception_3d_capabilities::CuboidMatcherAnnotator::execute, cma));

    // Is 2d recognition enabled?
    if(!recognitionDir.empty())
    {
      // perceivedObjects[i].c_recognition_label_2d="";
      suturo_perception_2d_capabilities::LabelAnnotator2D la(perceivedObjects[i], sp.getOriginalRGBImage(), object_matcher_);
      la.execute();
    }
    else
    {
      // Set an empty label
      perceivedObjects[i].set_c_recognition_label_2d("");
    }
  }
  //boost::this_thread::sleep(boost::posix_time::microseconds(1000));
  // wait for thread completion.
  // destroy the work object to wait for all queued tasks to finish
  work.reset();
  ioService.run();
  threadpool.join_all();

  std::vector<suturo_perception_msgs::PerceivedObject> perceivedObjs = *convertPerceivedObjects(&perceivedObjects); // TODO handle images in this method

  mutex.unlock();

  return perceivedObjs;
}
address InterpreterGenerator::generate_native_entry(bool synchronized)
{
  const Register handler  = r14;
  const Register function = r15;

  assert_different_registers(Rmethod, Rlocals, Rthread, Rstate, Rmonitor,
			     handler, function);

  // We use the same code for synchronized and not
  if (native_entry)
    return native_entry;

  address start = __ pc();

  // Allocate and initialize our stack frame.
  __ load (Rstate, 0);
  generate_compute_interpreter_state(true);

  // Make sure method is native and not abstract
#ifdef ASSERT
  {
    Label ok;
    __ lwz (r0, Address(Rmethod, methodOopDesc::access_flags_offset()));
    __ andi_ (r0, r0, JVM_ACC_NATIVE | JVM_ACC_ABSTRACT);
    __ compare (r0, JVM_ACC_NATIVE);
    __ beq (ok);
    __ should_not_reach_here (__FILE__, __LINE__);
    __ bind (ok);
  }
#endif

  // Lock if necessary
  Label not_synchronized_1;
  
  __ bne (CRsync, not_synchronized_1);
  __ lock_object (Rmonitor);
  __ bind (not_synchronized_1);
  
  // Get signature handler
  const Address signature_handler_addr(
    Rmethod, methodOopDesc::signature_handler_offset());

  Label return_to_caller, got_signature_handler;

  __ load (handler, signature_handler_addr);
  __ compare (handler, 0);
  __ bne (got_signature_handler);
  __ call_VM (noreg,
              CAST_FROM_FN_PTR(address,
                               InterpreterRuntime::prepare_native_call),
              Rmethod,
              CALL_VM_NO_EXCEPTION_CHECKS);
  __ load (r0, Address(Rthread, Thread::pending_exception_offset()));
  __ compare (r0, 0);
  __ bne (return_to_caller);
  __ load (handler, signature_handler_addr);
  __ bind (got_signature_handler); 

  // Get the native function entry point
  const Address native_function_addr(
    Rmethod, methodOopDesc::native_function_offset());

  Label got_function;

  __ load (function, native_function_addr);
#ifdef ASSERT
  {
    // InterpreterRuntime::prepare_native_call() sets the mirror
    // handle and native function address first and the signature
    // handler last, so function should always be set here.
    Label ok;
    __ compare (function, 0);
    __ bne (ok);
    __ should_not_reach_here (__FILE__, __LINE__);
    __ bind (ok);
  }
#endif

  // Call signature handler
  __ mtctr (handler);
  __ bctrl ();
  __ mr (handler, r0);

  // Pass JNIEnv
  __ la (r3, Address(Rthread, JavaThread::jni_environment_offset()));

  // Pass mirror handle if static
  const Address oop_temp_addr = STATE(_oop_temp);

  Label not_static;

  __ bne (CRstatic, not_static);
  __ get_mirror_handle (r4);
  __ store (r4, oop_temp_addr);
  __ la (r4, oop_temp_addr);
  __ bind (not_static);

  // Set up the Java frame anchor
  __ set_last_Java_frame ();

  // Change the thread state to native
  const Address thread_state_addr(Rthread, JavaThread::thread_state_offset());
#ifdef ASSERT
  {
    Label ok;
    __ lwz (r0, thread_state_addr);
    __ compare (r0, _thread_in_Java);
    __ beq (ok);
    __ should_not_reach_here (__FILE__, __LINE__);
    __ bind (ok);
  }
#endif
  __ load (r0, _thread_in_native);
  __ stw (r0, thread_state_addr);

  // Make the call
  __ call (function);
  __ fixup_after_potential_safepoint ();

  // The result will be in r3 (and maybe r4 on 32-bit) or f1.
  // Wherever it is, we need to store it before calling anything
  const Register r3_save      = r16;
#ifdef PPC32
  const Register r4_save      = r17;
#endif
  const FloatRegister f1_save = f14;

  __ mr (r3_save, r3);
#ifdef PPC32
  __ mr (r4_save, r4);
#endif
  __ fmr (f1_save, f1);

  // Switch thread to "native transition" state before reading the
  // synchronization state.  This additional state is necessary
  // because reading and testing the synchronization state is not
  // atomic with respect to garbage collection.
  __ load (r0, _thread_in_native_trans);
  __ stw (r0, thread_state_addr);

  // Ensure the new state is visible to the VM thread.
  if(os::is_MP()) {
    if (UseMembar)
      __ sync ();
    else
      __ serialize_memory (r3, r4);
  }

  // Check for safepoint operation in progress and/or pending
  // suspend requests.  We use a leaf call in order to leave
  // the last_Java_frame setup undisturbed.
  Label block, no_block;

  __ load (r3, (intptr_t) SafepointSynchronize::address_of_state());
  __ lwz (r0, Address(r3, 0));
  __ compare (r0, SafepointSynchronize::_not_synchronized);
  __ bne (block);
  __ lwz (r0, Address(Rthread, JavaThread::suspend_flags_offset()));
  __ compare (r0, 0);
  __ beq (no_block);
  __ bind (block);
  __ call_VM_leaf (
       CAST_FROM_FN_PTR(address, 
                        JavaThread::check_special_condition_for_native_trans));
  __ fixup_after_potential_safepoint ();
  __ bind (no_block);

  // Change the thread state
  __ load (r0, _thread_in_Java);
  __ stw (r0, thread_state_addr);

  // Reset the frame anchor  
  __ reset_last_Java_frame ();

  // If the result was an OOP then unbox it and store it in the frame
  // (where it will be safe from garbage collection) before we release
  // the handle it might be protected by
  Label non_oop, store_oop;
  
  __ load (r0, (intptr_t) AbstractInterpreter::result_handler(T_OBJECT));
  __ compare (r0, handler);
  __ bne (non_oop);
  __ compare (r3_save, 0);
  __ beq (store_oop);
  __ load (r3_save, Address(r3_save, 0));
  __ bind (store_oop);
  __ store (r3_save, STATE(_oop_temp));
  __ bind (non_oop);

  // Reset handle block
  __ load (r3, Address(Rthread, JavaThread::active_handles_offset()));
  __ load (r0, 0);
  __ stw (r0, Address(r3, JNIHandleBlock::top_offset_in_bytes()));

  // If there is an exception we skip the result handler and return.
  // Note that this also skips unlocking which seems totally wrong,
  // but apparently this is what the asm interpreter does so we do
  // too.
  __ load (r0, Address(Rthread, Thread::pending_exception_offset()));
  __ compare (r0, 0);
  __ bne (return_to_caller);
  
  // Unlock if necessary
  Label not_synchronized_2;
  
  __ bne (CRsync, not_synchronized_2);
  __ unlock_object (Rmonitor);
  __ bind (not_synchronized_2);

  // Restore saved result and call the result handler
  __ mr (r3, r3_save);
#ifdef PPC32
  __ mr (r4, r4_save);
#endif
  __ fmr (f1, f1_save);
  __ mtctr (handler);
  __ bctrl ();
  
  // Unwind the current activation and return
  __ bind (return_to_caller);

  generate_unwind_interpreter_state();
  __ blr ();

  native_entry = start;
  return start;
}
address InterpreterGenerator::generate_accessor_entry()
{
  if (!UseFastAccessorMethods)
    return NULL;

  Label& slow_path = fast_accessor_slow_entry_path;
  
  address start = __ pc();

  // Drop into the slow path if we need a safepoint check.
  __ load (r3, (intptr_t) SafepointSynchronize::address_of_state());
  __ load (r0, Address(r3, 0));
  __ compare (r0, SafepointSynchronize::_not_synchronized);
  __ bne (slow_path);
  
  // Load the object pointer and drop into the slow path
  // if we have a NullPointerException.
  const Register object = r4;

  __ load (object, Address(Rlocals, 0));
  __ compare (object, 0);
  __ beq (slow_path);

  // Read the field index from the bytecode, which looks like this:
  //  0:  0x2a:    aload_0
  //  1:  0xb4:    getfield
  //  2:             index (high byte)
  //  3:             index (low byte)
  //  4:  0xac/b0: ireturn/areturn
  const Register index = r5;
  
  __ load (index, Address(Rmethod, methodOopDesc::const_offset()));
  __ lwz (index, Address(index, constMethodOopDesc::codes_offset()));
#ifdef ASSERT
  {
    Label ok;
    __ shift_right (r0, index, 16);
    __ compare (r0, (Bytecodes::_aload_0 << 8) | Bytecodes::_getfield);
    __ beq (ok);
    __ should_not_reach_here (__FILE__, __LINE__);
    __ bind (ok);
  }
#endif
  __ andi_ (index, index, 0xffff);

  // Locate the entry in the constant pool cache
  const Register entry = r6;
  
  __ load (entry, Address(Rmethod, methodOopDesc::constants_offset()));
  __ load (entry, Address(entry,constantPoolOopDesc::cache_offset_in_bytes()));
  __ la (entry, Address(entry, constantPoolCacheOopDesc::base_offset()));
  __ shift_left(r0, index,
       exact_log2(in_words(ConstantPoolCacheEntry::size())) + LogBytesPerWord);
  __ add (entry, entry, r0);

  // Check the validity of the cache entry by testing whether the
  // _indices field contains Bytecode::_getfield in b1 byte.
  __ load (r0, Address(entry, ConstantPoolCacheEntry::indices_offset()));
  __ shift_right (r0, r0, 16);
  __ andi_ (r0, r0, 0xff);
  __ compare (r0, Bytecodes::_getfield);
  __ bne (slow_path);

  // Calculate the type and offset of the field
  const Register offset = r7;
  const Register type   = r8;

  __ load (offset, Address(entry, ConstantPoolCacheEntry::f2_offset()));
  __ load (type, Address(entry, ConstantPoolCacheEntry::flags_offset()));
  ConstantPoolCacheEntry::verify_tosBits();
  __ shift_right (type, type, ConstantPoolCacheEntry::tosBits);

  // Load the value
  Label is_object, is_int, is_byte, is_short, is_char;

  __ compare (type, atos);
  __ beq (is_object);
  __ compare (type, itos);
  __ beq (is_int);
  __ compare (type, btos);
  __ beq (is_byte);
  __ compare (type, stos);
  __ beq (is_short);
  __ compare (type, ctos);
  __ beq (is_char);

  __ load (r3, (intptr_t) "error: unknown type: %d\n");
  __ mr (r4, type);
  __ call (CAST_FROM_FN_PTR(address, printf));
  __ should_not_reach_here (__FILE__, __LINE__);

  __ bind (is_object);
  __ load_indexed (r3, object, offset);
  __ blr ();

  __ bind (is_int);
  __ lwax (r3, object, offset);
  __ blr ();

  __ bind (is_byte);
  __ lbax (r3, object, offset);
  __ blr ();

  __ bind (is_short);
  __ lhax (r3, object, offset);
  __ blr ();

  __ bind (is_char);
  __ lhzx (r3, object, offset);
  __ blr ();

  return start;  
}
static void teststdproblem(const ap::real_2d_array& a,
     int n,
     double& materr,
     double& orterr)
{
    int i;
    int j;
    ap::real_2d_array ua;
    ap::real_2d_array la;
    ap::real_2d_array t;
    ap::real_2d_array q;
    ap::real_2d_array t2;
    ap::real_2d_array t3;
    ap::real_1d_array tau;
    ap::real_1d_array d;
    ap::real_1d_array e;
    double v;

    ua.setbounds(0, n-1, 0, n-1);
    la.setbounds(0, n-1, 0, n-1);
    t.setbounds(0, n-1, 0, n-1);
    q.setbounds(0, n-1, 0, n-1);
    t2.setbounds(0, n-1, 0, n-1);
    t3.setbounds(0, n-1, 0, n-1);
    
    //
    // fill
    //
    for(i = 0; i <= n-1; i++)
    {
        for(j = 0; j <= n-1; j++)
        {
            ua(i,j) = 0;
        }
    }
    for(i = 0; i <= n-1; i++)
    {
        for(j = i; j <= n-1; j++)
        {
            ua(i,j) = a(i,j);
        }
    }
    for(i = 0; i <= n-1; i++)
    {
        for(j = 0; j <= n-1; j++)
        {
            la(i,j) = 0;
        }
    }
    for(i = 0; i <= n-1; i++)
    {
        for(j = 0; j <= i; j++)
        {
            la(i,j) = a(i,j);
        }
    }
    
    //
    // Test 2tridiagonal: upper
    //
    smatrixtd(ua, n, true, tau, d, e);
    smatrixtdunpackq(ua, n, true, tau, q);
    for(i = 0; i <= n-1; i++)
    {
        for(j = 0; j <= n-1; j++)
        {
            t(i,j) = 0;
        }
    }
    for(i = 0; i <= n-1; i++)
    {
        t(i,i) = d(i);
    }
    for(i = 0; i <= n-2; i++)
    {
        t(i,i+1) = e(i);
        t(i+1,i) = e(i);
    }
    for(i = 0; i <= n-1; i++)
    {
        for(j = 0; j <= n-1; j++)
        {
            v = ap::vdotproduct(q.getcolumn(i, 0, n-1), a.getcolumn(j, 0, n-1));
            t2(i,j) = v;
        }
    }
    for(i = 0; i <= n-1; i++)
    {
        for(j = 0; j <= n-1; j++)
        {
            v = ap::vdotproduct(t2.getrow(i, 0, n-1), q.getcolumn(j, 0, n-1));
            t3(i,j) = v;
        }
    }
    for(i = 0; i <= n-1; i++)
    {
        for(j = 0; j <= n-1; j++)
        {
            materr = ap::maxreal(materr, ap::abscomplex(t3(i,j)-t(i,j)));
        }
    }
    for(i = 0; i <= n-1; i++)
    {
        for(j = 0; j <= n-1; j++)
        {
            v = ap::vdotproduct(&q(i, 0), &q(j, 0), ap::vlen(0,n-1));
            if( i==j )
            {
                orterr = ap::maxreal(orterr, ap::abscomplex(v-1));
            }
            else
            {
                orterr = ap::maxreal(orterr, ap::abscomplex(v));
            }
        }
    }
    
    //
    // Test 2tridiagonal: lower
    //
    smatrixtd(la, n, false, tau, d, e);
    smatrixtdunpackq(la, n, false, tau, q);
    for(i = 0; i <= n-1; i++)
    {
        for(j = 0; j <= n-1; j++)
        {
            t(i,j) = 0;
        }
    }
    for(i = 0; i <= n-1; i++)
    {
        t(i,i) = d(i);
    }
    for(i = 0; i <= n-2; i++)
    {
        t(i,i+1) = e(i);
        t(i+1,i) = e(i);
    }
    for(i = 0; i <= n-1; i++)
    {
        for(j = 0; j <= n-1; j++)
        {
            v = ap::vdotproduct(q.getcolumn(i, 0, n-1), a.getcolumn(j, 0, n-1));
            t2(i,j) = v;
        }
    }
    for(i = 0; i <= n-1; i++)
    {
        for(j = 0; j <= n-1; j++)
        {
            v = ap::vdotproduct(t2.getrow(i, 0, n-1), q.getcolumn(j, 0, n-1));
            t3(i,j) = v;
        }
    }
    for(i = 0; i <= n-1; i++)
    {
        for(j = 0; j <= n-1; j++)
        {
            materr = ap::maxreal(materr, ap::abscomplex(t3(i,j)-t(i,j)));
        }
    }
    for(i = 0; i <= n-1; i++)
    {
        for(j = 0; j <= n-1; j++)
        {
            v = ap::vdotproduct(&q(i, 0), &q(j, 0), ap::vlen(0,n-1));
            if( i==j )
            {
                orterr = ap::maxreal(orterr, ap::abscomplex(v-1));
            }
            else
            {
                orterr = ap::maxreal(orterr, ap::abscomplex(v));
            }
        }
    }
}
Esempio n. 26
0
void Matrix::invertInplace(){
    determinant = la(size, elements);
    determinant = 1/determinant;
}
Esempio n. 27
0
int
main(int argc, char** argv)
{
    if (argc > 1)
	printf("Usage: %s\n", argv[0]);

#ifdef __x86_vector__
    printf("using x86 vectorization\n");
#elif defined(__fpu_vector__)
    printf("using fpu vectorization\n");
#endif

    {
	// test correctness
	double _a[8] VEC_ALIGN = {0, 1, 2, 3, 4, 5, 6, 7};
	double _b[8] VEC_ALIGN = {2, 4, 6, 8, 10, 12, 14, 16};
	dvec<8> a(_a);
	dvec<8> b(_b);

	dvec<8> c = a + b;
	double _c[8] VEC_ALIGN = {2, 5, 8, 11, 14, 17, 20, 23};
	assert(c == dvec<8>(_c));

	dvec<8> d = a - b;
	double _d[8] VEC_ALIGN = {-2, -3, -4, -5, -6, -7, -8, -9};
	assert(d == dvec<8>(_d));

	dvec<8> e = a * b;
	double _e[8] VEC_ALIGN = {0, 4, 12, 24, 40, 60, 84, 112};
	assert(e == dvec<8>(_e));

	dvec<8> f = a / b;
	double _f[8] VEC_ALIGN = {0, 0.25, 0.333333333333, 0.375, 0.40, 0.4166666666, 0.42857142, 0.4375};
	assert(f == dvec<8>(_f));

	dvec<8> g = a.madd(c, b);
	double _g[8] VEC_ALIGN = {2, 9, 22, 41, 66, 97, 134, 177};
	assert(g == dvec<8>(_g));

	dvec<8> h = a.madd(2.0, b);
	double _h[8] VEC_ALIGN = {2, 6, 10, 14, 18, 22, 26, 30};
	assert(h == dvec<8>(_h));

	srand(time(NULL));
	double total = 0.0;
	double rval[] = {
	    rand()/10000.0,
	    rand()/10000.0,
	    rand()/10000.0,
	    rand()/10000.0,
	    rand()/10000.0,
	    rand()/10000.0,
	    rand()/10000.0,
	    rand()/10000.0,
	    rand()/10000.0,
	    rand()/10000.0,
	    rand()/10000.0,
	    rand()/10000.0,
	    rand()/10000.0,
	    rand()/10000.0,
	    rand()/10000.0,
	    rand()/10000.0,
	    rand()/10000.0 };

	clock_t start = clock();
	for (int i = 0; i < COUNT; i++) {
	    double l_a[8] VEC_ALIGN = {rval[i%8], rval[i%8+1], rval[i%8+2], rval[i%8+3],
				       rval[i%8+4], rval[i%8+5], rval[i%8+6], rval[i%8+7]};
	    double l_b[8] VEC_ALIGN = {rval[i%8+1], rval[i%8+2], rval[i%8+3], rval[i%8+4],
				       rval[i%8+5], rval[i%8+6], rval[i%8+7], rval[i%8+8]};

	    dvec<8> la(l_a);
	    dvec<8> lb(l_b);

	    dvec<8> lc = la + lb;
	    dvec<8> ld = lc - la;
	    dvec<8> le = ld * lc;
	    dvec<8> lf = le / la;
	    dvec<8> lg = la.madd(rval[i%16], lf);
	    dvec<8> lh = lg.madd(lf, la+lb*lc-ld/le*lf);
	    total += lh[7];
	}
	printf("dvec<8> time: %3.4g\n", (double)(clock()-start)/(double)CLOCKS_PER_SEC);
    }

/* test correctness */
    vec2d a(100.0, -100.0);
    vec2d b(200.0, -200.0);

    vec2d c = a + b;
    assert(vequals(c, vec2d(300.0, -300.0)));

    vec2d d = a - b;
    assert(vequals(d, vec2d(-100.0, 100.0)));

    vec2d e = a * b;
    assert(vequals(e, vec2d(20000.0, 20000.0)));

    vec2d f = b / a;
    assert(vequals(f, vec2d(2.0, 2.0)));

    vec2d g = a.madd(20.0, b);
    assert(vequals(g, vec2d(2200.0, -2200.0)));

    vec2d h = a.madd(d, b);
    assert(vequals(h, vec2d(-9800.0, -10200.0)));

/* simple performance test */

    srand(time(NULL));
    double total = 0.0;
    double rval[] = {
	rand()/10000.0,
	rand()/10000.0,
	rand()/10000.0,
	rand()/10000.0,
	rand()/10000.0,
	rand()/10000.0,
	rand()/10000.0,
	rand()/10000.0,
	rand()/10000.0,
	rand()/10000.0,
	rand()/10000.0,
	rand()/10000.0,
	rand()/10000.0,
	rand()/10000.0,
	rand()/10000.0,
	rand()/10000.0 };

    clock_t start = clock();
    for (int i = 0; i < COUNT; i++) {
	vec2d la(rval[i%12], rval[i%12+2]);
	vec2d lb(rval[i%12+1], rval[i%12+3]);

	vec2d lc = la + lb;
	vec2d ld = lc - la;
	vec2d le = ld * lc;
	vec2d lf = le / la;
	vec2d lg = la.madd(rval[i%12], lf);
	vec2d lh = lg.madd(lg, la + lb - lc + ld - le + lf);
	total += lh.x() + lh.y();
    }
    printf("vec2d time: %3.4g\n", (double)(clock()-start)/(double)CLOCKS_PER_SEC);

    /* return 'fail' if no time elapsed */
    return (total > 0) ? 0 : 1;
}
Esempio n. 28
0
void Agent::tick() {
	// sanity checks to stop ticks on dead agents
	LifeAssert la(this);
	if (dying) return;
	
	if (sound) {
		// if the sound is no longer playing...
		if (sound->getState() != SS_PLAY) {
			// ...release our reference to it
			sound.reset();
		} else {
			// otherwise, reposition audio
			updateAudio(sound);
		}
	}

	// don't tick paused agents
	if (paused) return;

	// CA updates
	if (emitca_index != -1 && emitca_amount != 0.0f) {
		assert(0 <= emitca_index && emitca_index <= 19);
		shared_ptr<Room> r = world.map.roomAt(x, y);
		if (r) {
			r->catemp[emitca_index] += emitca_amount;
			/*if (r->catemp[emitca_index] <= 0.0f) r->catemp[emitca_index] = 0.0f;
			else if (r->catemp[emitca_index] >= 1.0f) r->catemp[emitca_index] = 1.0f;*/
		}
	}

	// TODO: this might be in the wrong place - note that parts are ticked *before* Agent::tick is called
	if (rotatable() && spritesperrotation != 0 && numberrotations > 1) {
		SpritePart *p = dynamic_cast<SpritePart *>(part(0));
		if (p) {
			// change base according to our SPIN and the ROTN settings
			unsigned int rotation = 0;
			rotation = (spin - (0.5f / numberrotations)) * numberrotations; // TODO: verify correctness
			p->setBase(spritesperrotation * rotation);
		}
	}

	// tick the physics engine
	physicsTick();
	if (dying) return; // in case we were autokilled

	// update the timer if needed, and then queue a timer event if necessary
	if (timerrate) {
		tickssincelasttimer++;
		if (tickssincelasttimer == timerrate) {
			queueScript(9); // TODO: include this?
			tickssincelasttimer = 0;
		}
		assert(timerrate > tickssincelasttimer);
	}

	// tick the agent VM
	if (vm) vmTick();

	// some silly hack to handle delayed voices
	tickVoices();
}
Esempio n. 29
0
int main( int argc , char * argv[] )  {
    std::cout << "算术" << std::endl;
    int a = 10 , b = 20;
    int ret;

    std::plus<int>add;
    ret = add(a,b);
    std::cout << ret << std::endl;

    std::minus<int> min;
    ret = min(b,a);
    std::cout << ret << std::endl;

    std::multiplies<int> mp;
    ret = mp(a,b);
    std::cout << ret << std::endl;

    std::divides<int> divi;
    ret = divi(a,b);
    std::cout << ret << std::endl;

    std::modulus<int> mod;
    ret = mod(a,b);
    std::cout << ret << std::endl;

    std::negate<int> neg;
    ret = neg(a);
    std::cout << ret << std::endl;


    std::cout << "关系" <<std::endl;
    int a2 = 10 , b2 = 20;
    int ret2;
    std::equal_to<int> et;
    ret2 = et(a,b);
    std::cout << ret2 <<std::endl;

    std::not_equal_to<int> net;
    ret2 = net(a,b);
    std::cout << ret2 << std::endl;

    std::greater<int>gt;
    ret2 = gt(b,a);
    std::cout << ret2 << std::endl;

    std::greater_equal<int> gte;
    ret2 = gte(a,b);
    std::cout << ret2 <<std::endl;

    std::less<int> ls;
    ret2 = ls(a,b);
    std::cout << ret2 << std::endl;

    std::less_equal<int> lel;
    ret2 = lel(a,b);
    std::cout << ret2 << std::endl;

    std::cout << "逻辑" << std::endl;
    int ret3;
    std::logical_and<int> la;
    ret3 = la(a,b);
    std::cout << ret3 <<std::endl;

    std::logical_or<int> lo;
    ret3 = lo(a,b);
    std::cout << ret3 << std::endl;

    std::logical_not<int>ln;
    ret3 = ln(b);
    std::cout << ret3 <<std::endl;

    return EXIT_SUCCESS;
}
Esempio n. 30
0
int Hull::AddContactsHullHull(Separation& sep, const Point3* pVertsA, const Point3* pVertsB,
                              const Transform& trA, const Transform& trB,const Hull& hullA,const Hull& hullB,
                              HullContactCollector* hullContactCollector)
{
    const int maxContacts = hullContactCollector->GetMaxNumContacts();

    Vector3 normalWorld = sep.m_axis;

    // edge->edge contact is always a single point
    if (sep.m_separator == Separation::kFeatureBoth)
    {
        const Hull::Edge& edgeA = hullA.GetEdge(sep.m_featureA);
        const Hull::Edge& edgeB = hullB.GetEdge(sep.m_featureB);

        float ta, tb;
        Line la(pVertsA[edgeA.m_verts[0]], pVertsA[edgeA.m_verts[1]]);
        Line lb(pVertsB[edgeB.m_verts[0]], pVertsB[edgeB.m_verts[1]]);

        Intersect(la, lb, ta, tb);

#ifdef VALIDATE_CONTACT_POINTS
        AssertPointInsideHull(contact.m_points[0].m_pos, trA, hullA);
        AssertPointInsideHull(contact.m_points[0].m_pos, trB, hullB);
#endif


        Point3 posWorld = Lerp(la.m_start, la.m_end, ta);
        float depth = -sep.m_dist;
        Vector3 tangent = Normalize(pVertsA[edgeA.m_verts[1]] - pVertsA[edgeA.m_verts[0]]);

        sep.m_contact = hullContactCollector->BatchAddContactGroup(sep,1,normalWorld,tangent,&posWorld,&depth);

    }
    // face->face contact is polygon
    else
    {
        short faceA = sep.m_featureA;
        short faceB = sep.m_featureB;

        Vector3 tangent;

        // find face of hull A that is most opposite contact axis
        // TODO: avoid having to transform planes here
        if (sep.m_separator == Separation::kFeatureB)
        {
            const Hull::Edge& edgeB = hullB.GetEdge(hullB.GetFaceFirstEdge(faceB));
            tangent = Normalize(pVertsB[edgeB.m_verts[1]] - pVertsB[edgeB.m_verts[0]]);

            Scalar dmin = Scalar::Consts::MaxValue;
            for (short face = 0; face < hullA.m_numFaces; face++)
            {
                Vector3 normal = hullA.GetPlane(face).GetNormal() * trA;
                Scalar d = Dot(normal, sep.m_axis);
                if (d < dmin)
                {
                    dmin = d;
                    faceA = face;
                }
            }
        }
        else
        {
            const Hull::Edge& edgeA = hullA.GetEdge(hullA.GetFaceFirstEdge(faceA));
            tangent = Normalize(pVertsA[edgeA.m_verts[1]] - pVertsA[edgeA.m_verts[0]]);

            Scalar dmin = Scalar::Consts::MaxValue;
            for (short face = 0; face < hullB.m_numFaces; face++)
            {
                Vector3 normal = hullB.GetPlane(face).GetNormal() * trB;
                Scalar d = Dot(normal, -sep.m_axis);
                if (d < dmin)
                {
                    dmin = d;
                    faceB = face;
                }
            }
        }

        Point3 workspace[2][Hull::kMaxVerts];

        // setup initial clip face (minimizing face from hull B)
        int numContacts = 0;
        for (short edge = hullB.GetFaceFirstEdge(faceB); edge != -1; edge = hullB.GetFaceNextEdge(faceB, edge))
            workspace[0][numContacts++] = pVertsB[ hullB.GetEdgeVertex0(faceB, edge) ];

        // clip polygon to back of planes of all faces of hull A that are adjacent to witness face
        Point3* pVtxIn = workspace[0];
        Point3* pVtxOut = workspace[1];

#if 0
        for (short edge = hullA.GetFaceFirstEdge(faceA); edge != -1; edge = hullA.GetFaceNextEdge(faceA, edge))
        {
            Plane planeA = hullA.GetPlane( hullA.GetEdgeOtherFace(edge, faceA) ) * trA;
            numContacts = ClipFace(numContacts, &pVtxIn, &pVtxOut, planeA);
        }
#else
        for (short f = 0; f < hullA.GetNumFaces(); f++)
        {
            Plane planeA = hullA.GetPlane(f) * trA;
            numContacts = ClipFace(numContacts, &pVtxIn, &pVtxOut, planeA);
        }
#endif

        // only keep points that are behind the witness face
        Plane planeA = hullA.GetPlane(faceA) * trA;

        float depths[Hull::kMaxVerts];
        int numPoints = 0;
        for (int i = 0; i < numContacts; i++)
        {
            Scalar d = Dot(planeA, pVtxIn[i]);
            if (IsNegative(d))
            {
                depths[numPoints] = (float)-d;
                pVtxIn[numPoints] = pVtxIn[i];

#ifdef VALIDATE_CONTACT_POINTS
                AssertPointInsideHull(pVtxIn[numPoints], trA, hullA);
                AssertPointInsideHull(pVtxIn[numPoints], trB, hullB);
#endif
                numPoints++;
            }
        }

        //we can also use a persistentManifold/reducer class
        // keep maxContacts points at most
        if (numPoints > 0)
        {
            if (numPoints > maxContacts)
            {
                int step = (numPoints << 8) / maxContacts;

                numPoints = maxContacts;
                for (int i = 0; i < numPoints; i++)
                {
                    int nth = (step * i) >> 8;

                    depths[i] = depths[nth];
                    pVtxIn[i] = pVtxIn[nth];


#ifdef VALIDATE_CONTACT_POINTS
                    AssertPointInsideHull(contact.m_points[i].m_pos, trA, hullA);
                    AssertPointInsideHull(contact.m_points[i].m_pos, trB, hullB);
#endif
                }
            }

            sep.m_contact = hullContactCollector->BatchAddContactGroup(sep,numPoints,normalWorld,tangent,pVtxIn,depths);

        }
        return numPoints;
    }